repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
yangdd1205/spring-boot | spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConversionServiceDeducerTests.java | 3700 | /*
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.context.properties;
import java.io.InputStream;
import java.io.OutputStream;
import org.junit.jupiter.api.Test;
import org.springframework.boot.convert.ApplicationConversionService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ConversionServiceDeducer}.
*
* @author Phillip Webb
*/
class ConversionServiceDeducerTests {
@Test
void getConversionServiceWhenHasConversionServiceBeanReturnsBean() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(
CustomConverterServiceConfiguration.class);
ConversionServiceDeducer deducer = new ConversionServiceDeducer(applicationContext);
assertThat(deducer.getConversionService()).isInstanceOf(TestApplicationConversionService.class);
}
@Test
void getConversionServiceWhenHasNoConversionServiceBeanAndNoQualifiedBeansReturnsSharedInstance() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(EmptyConfiguration.class);
ConversionServiceDeducer deducer = new ConversionServiceDeducer(applicationContext);
assertThat(deducer.getConversionService()).isSameAs(ApplicationConversionService.getSharedInstance());
}
@Test
void getConversionServiceWhenHasQualifiedConverterBeansReturnsNewInstance() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(
CustomConverterConfiguration.class);
ConversionServiceDeducer deducer = new ConversionServiceDeducer(applicationContext);
ConversionService conversionService = deducer.getConversionService();
assertThat(conversionService).isNotSameAs(ApplicationConversionService.getSharedInstance());
assertThat(conversionService.canConvert(InputStream.class, OutputStream.class)).isTrue();
}
@Configuration(proxyBeanMethods = false)
static class CustomConverterServiceConfiguration {
@Bean(ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME)
TestApplicationConversionService conversionService() {
return new TestApplicationConversionService();
}
}
@Configuration(proxyBeanMethods = false)
static class EmptyConfiguration {
}
@Configuration(proxyBeanMethods = false)
static class CustomConverterConfiguration {
@Bean
@ConfigurationPropertiesBinding
TestConverter testConverter() {
return new TestConverter();
}
}
private static class TestApplicationConversionService extends ApplicationConversionService {
}
private static class TestConverter implements Converter<InputStream, OutputStream> {
@Override
public OutputStream convert(InputStream source) {
throw new UnsupportedOperationException();
}
}
}
| mit |
janhenke/corefx | src/System.Reflection.TypeExtensions/tests/MethodBase/MethodBaseContainsGenericParameters.cs | 9127 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Reflection.Tests
{
// ContainsGenericParameters
public class MethodBaseContainsGenericParameters
{
public class TestClass
{
public TestClass()
{
}
public TestClass(int val)
{
}
public void TestGenericMethod<T>(T p1)
{
}
public void TestMethod(int val)
{
}
public void TestMethod2(int val)
{
}
public void TestMethod2(int val1, float val2, string val3)
{
}
public void TestPartialGenericMethod<T>(int val, T p1)
{
}
public T TestGenericReturnTypeMethod<T>()
{
T ret = default(T);
return ret;
}
}
public class TestGenericClass<T>
{
public TestGenericClass()
{
}
public TestGenericClass(T val)
{
}
public TestGenericClass(T p, int val)
{
}
public void TestMethod(T p1)
{
}
public void TestMultipleGenericMethod<U>(U p2)
{
}
public void TestVoidMethod()
{
}
}
// Positive Test 1: ContainsGenericParameters should return true for open generic method
[Fact]
public void PosTest1()
{
Type type = typeof(TestClass);
MethodBase methodInfo = type.GetMethod("TestGenericMethod");
Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for open generic method" + methodInfo);
}
// Positive Test 2: ContainsGenericParameters should return false for a closed generic method
[Fact]
public void PosTest2()
{
Type type = typeof(TestClass);
MethodInfo methodInfo = type.GetMethod("TestGenericMethod");
MethodBase genericMethodInfo = methodInfo.MakeGenericMethod(typeof(int));
Assert.False(genericMethodInfo.ContainsGenericParameters, "ContainsGenericParameters returns true for closed generic method");
}
// Positive Test 3: ContainsGenericParameters should return false for a non generic method
[Fact]
public void PosTest3()
{
Type type = typeof(TestClass);
MethodBase methodInfo = type.GetMethod("TestMethod");
Assert.False(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns true for non generic method");
}
// Positive Test 4: ContainsGenericParameters should return true for a generic method contains non generic parameter
[Fact]
public void PosTest4()
{
Type type = typeof(TestClass);
MethodBase methodInfo = type.GetMethod("TestPartialGenericMethod");
Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for a generic method contains non generic parameter" + methodInfo);
}
// Positive Test 5: ContainsGenericParameters should return true for a generic method only contains generic return type
[Fact]
public void PosTest5()
{
Type type = typeof(TestClass);
MethodBase methodInfo = type.GetMethod("TestPartialGenericMethod");
Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for a generic method only contains generic return type" + methodInfo);
}
// Positive Test 6: ContainsGenericParameters should return false for a generic method in a closed generic type
[Fact]
public void PosTest6()
{
Type type = typeof(TestGenericClass<int>);
MethodBase methodInfo = type.GetMethod("TestMethod");
Assert.False(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns true for a generic method in a closed generic type");
}
// Positive Test 7: ContainsGenericParameters should return true for a method in a opened generic type
[Fact]
public void PosTest7()
{
Type type = typeof(TestGenericClass<>);
MethodBase methodInfo = type.GetMethod("TestMethod");
Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for a method in a opened generic type" + methodInfo);
}
// Positive Test 8: ContainsGenericParameters should return true for a generic method in a opened generic type
[Fact]
public void PosTest8()
{
Type type = typeof(TestGenericClass<>);
MethodBase methodInfo = type.GetMethod("TestMultipleGenericMethod");
Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for a generic method in a opened generic type" + methodInfo);
}
// Positive Test 9: ContainsGenericParameters should return true for a generic method in a closed generic type
[Fact]
public void PosTest9()
{
Type type = typeof(TestGenericClass<int>);
MethodBase methodInfo = type.GetMethod("TestMultipleGenericMethod");
Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for a generic method in a closed generic type" + methodInfo);
}
// Positive Test 10: ContainsGenericParameters should return true for a method in a generic type
[Fact]
public void PosTest10()
{
Type type = typeof(TestGenericClass<>);
MethodBase methodInfo = type.GetMethod("TestVoidMethod");
Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for a generic method in a generic type" + methodInfo);
}
// Positive Test 11: ContainsGenericParameters should return false for a method in a closed generic type
[Fact]
public void PosTest11()
{
Type type = typeof(TestGenericClass<int>);
MethodBase methodInfo = type.GetMethod("TestVoidMethod");
Assert.False(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns truefor a generic method in a closed generic type");
}
// Positive Test 12: ContainsGenericParameters should return false for a constructor in a non generic type
[Fact]
public void PosTest12()
{
Type type = typeof(TestClass);
MethodBase methodInfo = type.GetConstructor(new Type[] { });
Assert.False(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns true for a constructor in a non generic type");
methodInfo = type.GetConstructor(new Type[] { typeof(int) });
Assert.False(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns true for a constructor in a non generic type");
}
// Positive Test 13: ContainsGenericParameters should return false for a constructor in a open generic type
[Fact]
public void PosTest13()
{
Type type = typeof(TestGenericClass<>);
MethodBase[] ctors = type.GetConstructors();
for (int i = 0; i < ctors.Length; ++i)
{
// ContainsGenericParameters should behave same for both methods and constructors.
// If method/ctor or the declaring type contains uninstantiated open generic parameter,
// ContainsGenericParameters should return true. (Which also means we can't invoke that type)
Assert.True(ctors[i].ContainsGenericParameters, "ContainsGenericParameters returns false for a constructor" + ctors[i] + " in a open generic type ");
}
}
// Positive Test 14: ContainsGenericParameters should return false for a constructor in a closed generic type
[Fact]
public void PosTest14()
{
Type type = typeof(TestGenericClass<int>);
MethodBase[] ctors = type.GetConstructors();
for (int i = 0; i < ctors.Length; ++i)
{
Assert.False(ctors[i].ContainsGenericParameters, "ContainsGenericParameters returns true for a constructor" + ctors[i] + " in a closed generic type");
}
}
// Positive Test 15: Exercise GetMethod(name, Type [])
[Fact]
public void PosTest15()
{
Type type = typeof(TestClass);
MethodInfo specificMethod = type.GetMethod("TestMethod2", new Type[] { typeof(int), typeof(float), typeof(string) });
Assert.NotNull(specificMethod);
}
}
}
| mit |
jonathansty/Game-Engine-Research | Engine/Thirdparty/Windows/VulkanSDK/spirv-tools/test/link/global_values_amount_test.cpp | 5424 | // Copyright (c) 2017 Pierre Moreau
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "gmock/gmock.h"
#include "linker_fixture.h"
namespace {
using ::testing::HasSubstr;
class EntryPoints : public spvtest::LinkerTest {
public:
EntryPoints() { binaries.reserve(0xFFFF); }
virtual void SetUp() override {
binaries.push_back({SpvMagicNumber,
SpvVersion,
SPV_GENERATOR_CODEPLAY,
10u, // NOTE: Bound
0u, // NOTE: Schema; reserved
3u << SpvWordCountShift | SpvOpTypeFloat,
1u, // NOTE: Result ID
32u, // NOTE: Width
4u << SpvWordCountShift | SpvOpTypePointer,
2u, // NOTE: Result ID
SpvStorageClassInput,
1u, // NOTE: Type ID
2u << SpvWordCountShift | SpvOpTypeVoid,
3u, // NOTE: Result ID
3u << SpvWordCountShift | SpvOpTypeFunction,
4u, // NOTE: Result ID
3u, // NOTE: Return type
5u << SpvWordCountShift | SpvOpFunction,
3u, // NOTE: Result type
5u, // NOTE: Result ID
SpvFunctionControlMaskNone,
4u, // NOTE: Function type
2u << SpvWordCountShift | SpvOpLabel,
6u, // NOTE: Result ID
4u << SpvWordCountShift | SpvOpVariable,
2u, // NOTE: Type ID
7u, // NOTE: Result ID
SpvStorageClassFunction,
4u << SpvWordCountShift | SpvOpVariable,
2u, // NOTE: Type ID
8u, // NOTE: Result ID
SpvStorageClassFunction,
4u << SpvWordCountShift | SpvOpVariable,
2u, // NOTE: Type ID
9u, // NOTE: Result ID
SpvStorageClassFunction,
1u << SpvWordCountShift | SpvOpReturn,
1u << SpvWordCountShift | SpvOpFunctionEnd});
for (size_t i = 0u; i < 2u; ++i) {
spvtest::Binary binary = {
SpvMagicNumber,
SpvVersion,
SPV_GENERATOR_CODEPLAY,
103u, // NOTE: Bound
0u, // NOTE: Schema; reserved
3u << SpvWordCountShift | SpvOpTypeFloat,
1u, // NOTE: Result ID
32u, // NOTE: Width
4u << SpvWordCountShift | SpvOpTypePointer,
2u, // NOTE: Result ID
SpvStorageClassInput,
1u // NOTE: Type ID
};
for (uint32_t j = 0u; j < 0xFFFFu / 2u; ++j) {
binary.push_back(4u << SpvWordCountShift | SpvOpVariable);
binary.push_back(2u); // NOTE: Type ID
binary.push_back(j + 3u); // NOTE: Result ID
binary.push_back(SpvStorageClassInput);
}
binaries.push_back(binary);
}
}
virtual void TearDown() override { binaries.clear(); }
spvtest::Binaries binaries;
};
// TODO(dneto): Fix performance issue for debug builds on Windows
#if !(defined(SPIRV_WINDOWS) && defined(_DEBUG))
TEST_F(EntryPoints, UnderLimit) {
spvtest::Binary linked_binary;
ASSERT_EQ(SPV_SUCCESS, Link(binaries, &linked_binary));
EXPECT_THAT(GetErrorMessage(), std::string());
}
TEST_F(EntryPoints, OverLimit) {
binaries.push_back({SpvMagicNumber,
SpvVersion,
SPV_GENERATOR_CODEPLAY,
5u, // NOTE: Bound
0u, // NOTE: Schema; reserved
3u << SpvWordCountShift | SpvOpTypeFloat,
1u, // NOTE: Result ID
32u, // NOTE: Width
4u << SpvWordCountShift | SpvOpTypePointer,
2u, // NOTE: Result ID
SpvStorageClassInput,
1u, // NOTE: Type ID
4u << SpvWordCountShift | SpvOpVariable,
2u, // NOTE: Type ID
3u, // NOTE: Result ID
SpvStorageClassInput,
4u << SpvWordCountShift | SpvOpVariable,
2u, // NOTE: Type ID
4u, // NOTE: Result ID
SpvStorageClassInput});
spvtest::Binary linked_binary;
ASSERT_EQ(SPV_ERROR_INTERNAL, Link(binaries, &linked_binary));
EXPECT_THAT(GetErrorMessage(),
HasSubstr("The limit of global values, 65535, was exceeded; "
"65536 global values were found."));
}
#endif // !(defined(SPIRV_WINDOWS) && defined(_DEBUG))
} // anonymous namespace
| mit |
JHKennedy4/nqr-client | jspm_packages/npm/core-js@1.2.5/library/fn/symbol/index.js | 148 | /* */
require("../../modules/es6.symbol");
require("../../modules/es6.object.to-string");
module.exports = require("../../modules/$.core").Symbol;
| mit |
Eddman/material2 | src/material-examples/datepicker-formats/datepicker-formats-example.ts | 1652 | import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {MomentDateAdapter} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
// Depending on whether rollup is used, moment needs to be imported differently.
// Since Moment.js doesn't have a default export, we normally need to import using the `* as`
// syntax. However, rollup creates a synthetic default module and we thus need to import it using
// the `default as` syntax.
import * as _moment from 'moment';
import {default as _rollupMoment} from 'moment';
const moment = _rollupMoment || _moment;
// See the Moment.js docs for the meaning of these formats:
// https://momentjs.com/docs/#/displaying/format/
export const MY_FORMATS = {
parse: {
dateInput: 'LL',
},
display: {
dateInput: 'LL',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
/** @title Datepicker with custom formats */
@Component({
selector: 'datepicker-formats-example',
templateUrl: 'datepicker-formats-example.html',
styleUrls: ['datepicker-formats-example.css'],
providers: [
// `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your
// application's root module. We provide it at the component level here, due to limitations of
// our example generation script.
{provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
{provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
],
})
export class DatepickerFormatsExample {
date = new FormControl(moment());
}
| mit |
yogeshsaroya/new-cdnjs | ajax/libs/mathjax/2.1/fonts/HTML-CSS/TeX/png/Fraktur/Regular/BasicLatin.js | 130 | version https://git-lfs.github.com/spec/v1
oid sha256:a665d9d8a6100222ac5094344efe5310c5f6d8caf70f134ae30850a92b39e6cb
size 11746
| mit |
klebercode/prestashop | classes/Hook.php | 24065 | <?php
/*
* 2007-2015 PrestaShop
*
* 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@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2015 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class HookCore extends ObjectModel
{
/**
* @var string Hook name identifier
*/
public $name;
/**
* @var string Hook title (displayed in BO)
*/
public $title;
/**
* @var string Hook description
*/
public $description;
/**
* @var bool
*/
public $position = false;
/**
* @var bool Is this hook usable with live edit ?
*/
public $live_edit = false;
/**
* @var array List of executed hooks on this page
*/
public static $executed_hooks = array();
public static $native_module;
/**
* @see ObjectModel::$definition
*/
public static $definition = array(
'table' => 'hook',
'primary' => 'id_hook',
'fields' => array(
'name' => array('type' => self::TYPE_STRING, 'validate' => 'isHookName', 'required' => true, 'size' => 64),
'title' => array('type' => self::TYPE_STRING, 'validate' => 'isGenericName'),
'description' => array('type' => self::TYPE_HTML, 'validate' => 'isCleanHtml'),
'position' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'live_edit' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
),
);
/**
* @deprecated 1.5.0
*/
protected static $_hook_modules_cache = null;
/**
* @deprecated 1.5.0
*/
protected static $_hook_modules_cache_exec = null;
public function add($autodate = true, $null_values = false)
{
Cache::clean('hook_idsbyname');
return parent::add($autodate, $null_values);
}
/**
* Return Hooks List
*
* @param bool $position
* @return array Hooks List
*/
public static function getHooks($position = false)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT * FROM `'._DB_PREFIX_.'hook` h
'.($position ? 'WHERE h.`position` = 1' : '').'
ORDER BY `name`'
);
}
/**
* Return hook ID from name
*
* @param string $hook_name Hook name
* @return int Hook ID
*/
public static function getIdByName($hook_name)
{
$hook_name = strtolower($hook_name);
if (!Validate::isHookName($hook_name))
return false;
$cache_id = 'hook_idsbyname';
if (!Cache::isStored($cache_id))
{
// Get all hook ID by name and alias
$hook_ids = array();
$db = Db::getInstance();
$result = $db->ExecuteS('
SELECT `id_hook`, `name`
FROM `'._DB_PREFIX_.'hook`
UNION
SELECT `id_hook`, ha.`alias` as name
FROM `'._DB_PREFIX_.'hook_alias` ha
INNER JOIN `'._DB_PREFIX_.'hook` h ON ha.name = h.name', false);
while ($row = $db->nextRow($result))
$hook_ids[strtolower($row['name'])] = $row['id_hook'];
Cache::store($cache_id, $hook_ids);
}
else
$hook_ids = Cache::retrieve($cache_id);
return (isset($hook_ids[$hook_name]) ? $hook_ids[$hook_name] : false);
}
/**
* Return hook ID from name
*/
public static function getNameById($hook_id)
{
$cache_id = 'hook_namebyid_'.$hook_id;
if (!Cache::isStored($cache_id))
Cache::store($cache_id, Db::getInstance()->getValue('
SELECT `name`
FROM `'._DB_PREFIX_.'hook`
WHERE `id_hook` = '.(int)$hook_id)
);
return Cache::retrieve($cache_id);
}
/**
* Return hook live edit bool from ID
*/
public static function getLiveEditById($hook_id)
{
$cache_id = 'hook_live_editbyid_'.$hook_id;
if (!Cache::isStored($cache_id))
Cache::store($cache_id, Db::getInstance()->getValue('
SELECT `live_edit`
FROM `'._DB_PREFIX_.'hook`
WHERE `id_hook` = '.(int)$hook_id)
);
return Cache::retrieve($cache_id);
}
/**
* Get list of hook alias
*
* @since 1.5.0
* @return array
*/
public static function getHookAliasList()
{
$cache_id = 'hook_alias';
if (!Cache::isStored($cache_id))
{
$hook_alias_list = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'hook_alias`');
$hook_alias = array();
if ($hook_alias_list)
foreach ($hook_alias_list as $ha)
$hook_alias[strtolower($ha['alias'])] = $ha['name'];
Cache::store($cache_id, $hook_alias);
}
return Cache::retrieve($cache_id);
}
/**
* Return retrocompatible hook name
*
* @since 1.5.0
* @param string $hook_name Hook name
* @return int Hook ID
*/
public static function getRetroHookName($hook_name)
{
$alias_list = Hook::getHookAliasList();
if (isset($alias_list[strtolower($hook_name)]))
return $alias_list[strtolower($hook_name)];
$retro_hook_name = array_search($hook_name, $alias_list);
if ($retro_hook_name === false)
return '';
return $retro_hook_name;
}
/**
* Get list of all registered hooks with modules
*
* @since 1.5.0
* @return array
*/
public static function getHookModuleList()
{
$cache_id = 'hook_module_list';
if (!Cache::isStored($cache_id))
{
$results = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT h.id_hook, h.name as h_name, title, description, h.position, live_edit, hm.position as hm_position, m.id_module, m.name, active
FROM `'._DB_PREFIX_.'hook` h
INNER JOIN `'._DB_PREFIX_.'hook_module` hm ON (h.id_hook = hm.id_hook AND hm.id_shop = '.(int)Context::getContext()->shop->id.')
INNER JOIN `'._DB_PREFIX_.'module` as m ON (m.id_module = hm.id_module)
ORDER BY hm.position');
$list = array();
foreach ($results as $result)
{
if (!isset($list[$result['id_hook']]))
$list[$result['id_hook']] = array();
$list[$result['id_hook']][$result['id_module']] = array(
'id_hook' => $result['id_hook'],
'title' => $result['title'],
'description' => $result['description'],
'hm.position' => $result['position'],
'live_edit' => $result['live_edit'],
'm.position' => $result['hm_position'],
'id_module' => $result['id_module'],
'name' => $result['name'],
'active' => $result['active'],
);
}
Cache::store($cache_id, $list);
// @todo remove this in 1.6, we keep it in 1.5 for retrocompatibility
Hook::$_hook_modules_cache = $list;
}
return Cache::retrieve($cache_id);
}
/**
* Return Hooks List
*
* @since 1.5.0
* @param int $id_hook
* @param int $id_module
* @return array Modules List
*/
public static function getModulesFromHook($id_hook, $id_module = null)
{
$hm_list = Hook::getHookModuleList();
$module_list = (isset($hm_list[$id_hook])) ? $hm_list[$id_hook] : array();
if ($id_module)
return (isset($module_list[$id_module])) ? array($module_list[$id_module]) : array();
return $module_list;
}
/**
* Get list of modules we can execute per hook
*
* @since 1.5.0
* @param string $hook_name Get list of modules for this hook if given
* @return array
*/
public static function getHookModuleExecList($hook_name = null)
{
$context = Context::getContext();
$cache_id = 'hook_module_exec_list_'.(isset($context->shop->id) ? '_'.$context->shop->id : '' ).((isset($context->customer)) ? '_'.$context->customer->id : '');
if (!Cache::isStored($cache_id) || $hook_name == 'displayPayment' || $hook_name == 'displayBackOfficeHeader')
{
$frontend = true;
$groups = array();
$use_groups = Group::isFeatureActive();
if (isset($context->employee))
$frontend = false;
else
{
// Get groups list
if ($use_groups)
{
if (isset($context->customer) && $context->customer->isLogged())
$groups = $context->customer->getGroups();
elseif (isset($context->customer) && $context->customer->isLogged(true))
$groups = array((int)Configuration::get('PS_GUEST_GROUP'));
else
$groups = array((int)Configuration::get('PS_UNIDENTIFIED_GROUP'));
}
}
// SQL Request
$sql = new DbQuery();
$sql->select('h.`name` as hook, m.`id_module`, h.`id_hook`, m.`name` as module, h.`live_edit`');
$sql->from('module', 'm');
if ($hook_name != 'displayBackOfficeHeader')
{
$sql->join(Shop::addSqlAssociation('module', 'm', true, 'module_shop.enable_device & '.(int)Context::getContext()->getDevice()));
$sql->innerJoin('module_shop', 'ms', 'ms.`id_module` = m.`id_module`');
}
$sql->innerJoin('hook_module', 'hm', 'hm.`id_module` = m.`id_module`');
$sql->innerJoin('hook', 'h', 'hm.`id_hook` = h.`id_hook`');
if ($hook_name != 'displayPayment')
$sql->where('h.name != "displayPayment"');
// For payment modules, we check that they are available in the contextual country
elseif ($frontend)
{
if (Validate::isLoadedObject($context->country))
$sql->where('(h.name = "displayPayment" AND (SELECT id_country FROM '._DB_PREFIX_.'module_country mc WHERE mc.id_module = m.id_module AND id_country = '.(int)$context->country->id.' AND id_shop = '.(int)$context->shop->id.' LIMIT 1) = '.(int)$context->country->id.')');
if (Validate::isLoadedObject($context->currency))
$sql->where('(h.name = "displayPayment" AND (SELECT id_currency FROM '._DB_PREFIX_.'module_currency mcr WHERE mcr.id_module = m.id_module AND id_currency IN ('.(int)$context->currency->id.', -1, -2) LIMIT 1) IN ('.(int)$context->currency->id.', -1, -2))');
}
if (Validate::isLoadedObject($context->shop))
$sql->where('hm.id_shop = '.(int)$context->shop->id);
if ($frontend)
{
if ($use_groups)
{
$sql->leftJoin('module_group', 'mg', 'mg.`id_module` = m.`id_module`');
if (Validate::isLoadedObject($context->shop))
$sql->where('mg.id_shop = '.((int)$context->shop->id).(count($groups) ? ' AND mg.`id_group` IN ('.implode(', ', $groups).')' : ''));
elseif (count($groups))
$sql->where('mg.`id_group` IN ('.implode(', ', $groups).')');
}
}
$sql->groupBy('hm.id_hook, hm.id_module');
$sql->orderBy('hm.`position`');
$list = array();
if ($result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql))
foreach ($result as $row)
{
$row['hook'] = strtolower($row['hook']);
if (!isset($list[$row['hook']]))
$list[$row['hook']] = array();
$list[$row['hook']][] = array(
'id_hook' => $row['id_hook'],
'module' => $row['module'],
'id_module' => $row['id_module'],
'live_edit' => $row['live_edit'],
);
}
if ($hook_name != 'displayPayment' && $hook_name != 'displayBackOfficeHeader')
{
Cache::store($cache_id, $list);
// @todo remove this in 1.6, we keep it in 1.5 for retrocompatibility
self::$_hook_modules_cache_exec = $list;
}
}
else
$list = Cache::retrieve($cache_id);
// If hook_name is given, just get list of modules for this hook
if ($hook_name)
{
$retro_hook_name = strtolower(Hook::getRetroHookName($hook_name));
$hook_name = strtolower($hook_name);
$return = array();
$inserted_modules = array();
if (isset($list[$hook_name]))
$return = $list[$hook_name];
foreach ($return as $module)
$inserted_modules[] = $module['id_module'];
if (isset($list[$retro_hook_name]))
foreach ($list[$retro_hook_name] as $retro_module_call)
if (!in_array($retro_module_call['id_module'], $inserted_modules))
$return[] = $retro_module_call;
return (count($return) > 0 ? $return : false);
}
else
return $list;
}
/**
* Execute modules for specified hook
*
* @param string $hook_name Hook Name
* @param array $hook_args Parameters for the functions
* @param int $id_module Execute hook for this module only
* @return string modules output
*/
public static function exec($hook_name, $hook_args = array(), $id_module = null, $array_return = false, $check_exceptions = true, $use_push = false, $id_shop = null)
{
if (defined('PS_INSTALLATION_IN_PROGRESS'))
return;
static $disable_non_native_modules = null;
if ($disable_non_native_modules === null)
$disable_non_native_modules = (bool)Configuration::get('PS_DISABLE_NON_NATIVE_MODULE');
// Check arguments validity
if (($id_module && !is_numeric($id_module)) || !Validate::isHookName($hook_name))
throw new PrestaShopException('Invalid id_module or hook_name');
// If no modules associated to hook_name or recompatible hook name, we stop the function
if (!$module_list = Hook::getHookModuleExecList($hook_name))
return '';
// Check if hook exists
if (!$id_hook = Hook::getIdByName($hook_name))
return false;
// Store list of executed hooks on this page
Hook::$executed_hooks[$id_hook] = $hook_name;
$live_edit = false;
$context = Context::getContext();
if (!isset($hook_args['cookie']) || !$hook_args['cookie'])
$hook_args['cookie'] = $context->cookie;
if (!isset($hook_args['cart']) || !$hook_args['cart'])
$hook_args['cart'] = $context->cart;
$retro_hook_name = Hook::getRetroHookName($hook_name);
// Look on modules list
$altern = 0;
$output = '';
if ($disable_non_native_modules && !isset(Hook::$native_module))
Hook::$native_module = Module::getNativeModuleList();
$different_shop = false;
if ($id_shop !== null && Validate::isUnsignedId($id_shop) && $id_shop != $context->shop->getContextShopID())
{
$old_context_shop_id = $context->shop->getContextShopID();
$old_context = $context->shop->getContext();
$old_shop = clone $context->shop;
$shop = new Shop((int)$id_shop);
if (Validate::isLoadedObject($shop))
{
$context->shop = $shop;
$context->shop->setContext(Shop::CONTEXT_SHOP, $shop->id);
$different_shop = true;
}
}
foreach ($module_list as $array)
{
// Check errors
if ($id_module && $id_module != $array['id_module'])
continue;
if ((bool)$disable_non_native_modules && Hook::$native_module && count(Hook::$native_module) && !in_array($array['module'], self::$native_module))
continue;
// Check permissions
if ($check_exceptions)
{
$exceptions = Module::getExceptionsStatic($array['id_module'], $array['id_hook']);
$controller = Dispatcher::getInstance()->getController();
$controller_obj = Context::getContext()->controller;
//check if current controller is a module controller
if (isset($controller_obj->module) && Validate::isLoadedObject($controller_obj->module))
$controller = 'module-'.$controller_obj->module->name.'-'.$controller;
if (in_array($controller, $exceptions))
continue;
//retro compat of controller names
$matching_name = array(
'authentication' => 'auth',
'productscomparison' => 'compare'
);
if (isset($matching_name[$controller]) && in_array($matching_name[$controller], $exceptions))
continue;
if (Validate::isLoadedObject($context->employee) && !Module::getPermissionStatic($array['id_module'], 'view', $context->employee))
continue;
}
if (!($moduleInstance = Module::getInstanceByName($array['module'])))
continue;
if ($use_push && !$moduleInstance->allow_push)
continue;
// Check which / if method is callable
$hook_callable = is_callable(array($moduleInstance, 'hook'.$hook_name));
$hook_retro_callable = is_callable(array($moduleInstance, 'hook'.$retro_hook_name));
if (($hook_callable || $hook_retro_callable) && Module::preCall($moduleInstance->name))
{
$hook_args['altern'] = ++$altern;
if ($use_push && isset($moduleInstance->push_filename) && file_exists($moduleInstance->push_filename))
Tools::waitUntilFileIsModified($moduleInstance->push_filename, $moduleInstance->push_time_limit);
// Call hook method
if ($hook_callable)
$display = $moduleInstance->{'hook'.$hook_name}($hook_args);
elseif ($hook_retro_callable)
$display = $moduleInstance->{'hook'.$retro_hook_name}($hook_args);
// Live edit
if (!$array_return && $array['live_edit'] && Tools::isSubmit('live_edit') && Tools::getValue('ad') && Tools::getValue('liveToken') == Tools::getAdminToken('AdminModulesPositions'.(int)Tab::getIdFromClassName('AdminModulesPositions').(int)Tools::getValue('id_employee')))
{
$live_edit = true;
$output .= self::wrapLiveEdit($display, $moduleInstance, $array['id_hook']);
}
elseif ($array_return)
$output[$moduleInstance->name] = $display;
else
$output .= $display;
}
}
if ($different_shop)
{
$context->shop = $old_shop;
$context->shop->setContext($old_context, $shop->id);
}
if ($array_return)
return $output;
else
return ($live_edit ? '<script type="text/javascript">hooks_list.push(\''.$hook_name.'\');</script>
<div id="'.$hook_name.'" class="dndHook" style="min-height:50px">' : '').$output.($live_edit ? '</div>' : '');// Return html string
}
public static function wrapLiveEdit($display, $moduleInstance, $id_hook)
{
return '<script type="text/javascript"> modules_list.push(\''.Tools::safeOutput($moduleInstance->name).'\');</script>
<div id="hook_'.(int)$id_hook.'_module_'.(int)$moduleInstance->id.'_moduleName_'.str_replace('_', '-', Tools::safeOutput($moduleInstance->name)).'"
class="dndModule" style="border: 1px dotted red;'.(!strlen($display) ? 'height:50px;' : '').'">
<span style="font-family: Georgia;font-size:13px;font-style:italic;">
<img style="padding-right:5px;" src="'._MODULE_DIR_.Tools::safeOutput($moduleInstance->name).'/logo.gif">'
.Tools::safeOutput($moduleInstance->displayName).'<span style="float:right">
<a href="#" id="'.(int)$id_hook.'_'.(int)$moduleInstance->id.'" class="moveModule">
<img src="'._PS_ADMIN_IMG_.'arrow_out.png"></a>
<a href="#" id="'.(int)$id_hook.'_'.(int)$moduleInstance->id.'" class="unregisterHook">
<img src="'._PS_ADMIN_IMG_.'delete.gif"></a></span>
</span>'.$display.'</div>';
}
/**
* @deprecated 1.5.0
*/
public static function updateOrderStatus($newOrderStatusId, $id_order)
{
Tools::displayAsDeprecated();
$order = new Order((int)($id_order));
$newOS = new OrderState((int)($newOrderStatusId), $order->id_lang);
$return = ((int)($newOS->id) == Configuration::get('PS_OS_PAYMENT')) ? Hook::exec('paymentConfirm', array('id_order' => (int)($order->id))) : true;
$return = Hook::exec('updateOrderStatus', array('newOrderStatus' => $newOS, 'id_order' => (int)($order->id))) && $return;
return $return;
}
/**
* @deprecated 1.5.0
*/
public static function postUpdateOrderStatus($newOrderStatusId, $id_order)
{
Tools::displayAsDeprecated();
$order = new Order((int)($id_order));
$newOS = new OrderState((int)($newOrderStatusId), $order->id_lang);
$return = Hook::exec('postUpdateOrderStatus', array('newOrderStatus' => $newOS, 'id_order' => (int)($order->id)));
return $return;
}
/**
* @deprecated 1.5.0
*/
public static function orderConfirmation($id_order)
{
Tools::displayAsDeprecated();
if (Validate::isUnsignedId($id_order))
{
$params = array();
$order = new Order((int)$id_order);
$currency = new Currency((int)$order->id_currency);
if (Validate::isLoadedObject($order))
{
$cart = new Cart((int)$order->id_cart);
$params['total_to_pay'] = $cart->getOrderTotal();
$params['currency'] = $currency->sign;
$params['objOrder'] = $order;
$params['currencyObj'] = $currency;
return Hook::exec('orderConfirmation', $params);
}
}
return false;
}
/**
* @deprecated 1.5.0
*/
public static function paymentReturn($id_order, $id_module)
{
Tools::displayAsDeprecated();
if (Validate::isUnsignedId($id_order) && Validate::isUnsignedId($id_module))
{
$params = array();
$order = new Order((int)($id_order));
$currency = new Currency((int)($order->id_currency));
if (Validate::isLoadedObject($order))
{
$cart = new Cart((int)$order->id_cart);
$params['total_to_pay'] = $cart->getOrderTotal();
$params['currency'] = $currency->sign;
$params['objOrder'] = $order;
$params['currencyObj'] = $currency;
return Hook::exec('paymentReturn', $params, (int)($id_module));
}
}
return false;
}
/**
* @deprecated 1.5.0
*/
public static function PDFInvoice($pdf, $id_order)
{
Tools::displayAsDeprecated();
if (!is_object($pdf) || !Validate::isUnsignedId($id_order))
return false;
return Hook::exec('PDFInvoice', array('pdf' => $pdf, 'id_order' => $id_order));
}
/**
* @deprecated 1.5.0
*/
public static function backBeforePayment($module)
{
Tools::displayAsDeprecated();
if ($module)
return Hook::exec('backBeforePayment', array('module' => strval($module)));
}
/**
* @deprecated 1.5.0
*/
public static function updateCarrier($id_carrier, $carrier)
{
Tools::displayAsDeprecated();
if (!Validate::isUnsignedId($id_carrier) || !is_object($carrier))
return false;
return Hook::exec('updateCarrier', array('id_carrier' => $id_carrier, 'carrier' => $carrier));
}
/**
* Preload hook modules cache
*
* @deprecated 1.5.0 use Hook::getHookModuleList() instead
* @return boolean preload_needed
*/
public static function preloadHookModulesCache()
{
Tools::displayAsDeprecated();
if (!is_null(self::$_hook_modules_cache))
return false;
self::$_hook_modules_cache = Hook::getHookModuleList();
return true;
}
/**
* Return hook ID from name
*
* @param string $hookName Hook name
* @return integer Hook ID
*
* @deprecated since 1.5.0 use Hook::getIdByName() instead
*/
public static function get($hookName)
{
Tools::displayAsDeprecated();
if (!Validate::isHookName($hookName))
die(Tools::displayError());
$result = Db::getInstance()->getRow('
SELECT `id_hook`, `name`
FROM `'._DB_PREFIX_.'hook`
WHERE `name` = \''.pSQL($hookName).'\'');
return ($result ? $result['id_hook'] : false);
}
/**
* Called when quantity of a product is updated.
*
* @param Product
* @param Order
*/
public static function newOrder($cart, $order, $customer, $currency, $orderStatus)
{
Tools::displayAsDeprecated();
return Hook::exec('newOrder', array(
'cart' => $cart,
'order' => $order,
'customer' => $customer,
'currency' => $currency,
'orderStatus' => $orderStatus));
}
/**
* @deprecated 1.5.0
*/
public static function updateQuantity($product, $order = null)
{
Tools::displayAsDeprecated();
return Hook::exec('updateQuantity', array('product' => $product, 'order' => $order));
}
/**
* @deprecated 1.5.0
*/
public static function productFooter($product, $category)
{
Tools::displayAsDeprecated();
return Hook::exec('productFooter', array('product' => $product, 'category' => $category));
}
/**
* @deprecated 1.5.0
*/
public static function productOutOfStock($product)
{
Tools::displayAsDeprecated();
return Hook::exec('productOutOfStock', array('product' => $product));
}
/**
* @deprecated 1.5.0
*/
public static function addProduct($product)
{
Tools::displayAsDeprecated();
return Hook::exec('addProduct', array('product' => $product));
}
/**
* @deprecated 1.5.0
*/
public static function updateProduct($product)
{
Tools::displayAsDeprecated();
return Hook::exec('updateProduct', array('product' => $product));
}
/**
* @deprecated 1.5.0
*/
public static function deleteProduct($product)
{
Tools::displayAsDeprecated();
return Hook::exec('deleteProduct', array('product' => $product));
}
/**
* @deprecated 1.5.0
*/
public static function updateProductAttribute($id_product_attribute)
{
Tools::displayAsDeprecated();
return Hook::exec('updateProductAttribute', array('id_product_attribute' => $id_product_attribute));
}
}
| mit |
npmcomponent/sebpiq-WAAClock | dist/WAAClock-0.1.1.js | 66372 | ;(function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s<n.length;s++)i(n[s]);return i})({1:[function(require,module,exports){
var WAAClock = require('./lib/WAAClock')
window.WAAClock = WAAClock
},{"./lib/WAAClock":2}],3:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
if (canPost) {
var queue = [];
window.addEventListener('message', function (ev) {
if (ev.source === window && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage('process-tick', '*');
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.binding = function (name) {
throw new Error('process.binding is not supported');
}
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
},{}],4:[function(require,module,exports){
(function(process){if (!process.EventEmitter) process.EventEmitter = function () {};
var EventEmitter = exports.EventEmitter = process.EventEmitter;
var isArray = typeof Array.isArray === 'function'
? Array.isArray
: function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]'
}
;
function indexOf (xs, x) {
if (xs.indexOf) return xs.indexOf(x);
for (var i = 0; i < xs.length; i++) {
if (x === xs[i]) return i;
}
return -1;
}
// By default EventEmitters will print a warning if more than
// 10 listeners are added to it. This is a useful default which
// helps finding memory leaks.
//
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
var defaultMaxListeners = 10;
EventEmitter.prototype.setMaxListeners = function(n) {
if (!this._events) this._events = {};
this._events.maxListeners = n;
};
EventEmitter.prototype.emit = function(type) {
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events || !this._events.error ||
(isArray(this._events.error) && !this._events.error.length))
{
if (arguments[1] instanceof Error) {
throw arguments[1]; // Unhandled 'error' event
} else {
throw new Error("Uncaught, unspecified 'error' event.");
}
return false;
}
}
if (!this._events) return false;
var handler = this._events[type];
if (!handler) return false;
if (typeof handler == 'function') {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
var args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
return true;
} else if (isArray(handler)) {
var args = Array.prototype.slice.call(arguments, 1);
var listeners = handler.slice();
for (var i = 0, l = listeners.length; i < l; i++) {
listeners[i].apply(this, args);
}
return true;
} else {
return false;
}
};
// EventEmitter is defined in src/node_events.cc
// EventEmitter.prototype.emit() is also defined there.
EventEmitter.prototype.addListener = function(type, listener) {
if ('function' !== typeof listener) {
throw new Error('addListener only takes instances of Function');
}
if (!this._events) this._events = {};
// To avoid recursion in the case that type == "newListeners"! Before
// adding it to the listeners, first emit "newListeners".
this.emit('newListener', type, listener);
if (!this._events[type]) {
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
} else if (isArray(this._events[type])) {
// Check for listener leak
if (!this._events[type].warned) {
var m;
if (this._events.maxListeners !== undefined) {
m = this._events.maxListeners;
} else {
m = defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
console.trace();
}
}
// If we've already got an array, just append.
this._events[type].push(listener);
} else {
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
var self = this;
self.on(type, function g() {
self.removeListener(type, g);
listener.apply(this, arguments);
});
return this;
};
EventEmitter.prototype.removeListener = function(type, listener) {
if ('function' !== typeof listener) {
throw new Error('removeListener only takes instances of Function');
}
// does not use listeners(), so no side effect of creating _events[type]
if (!this._events || !this._events[type]) return this;
var list = this._events[type];
if (isArray(list)) {
var i = indexOf(list, listener);
if (i < 0) return this;
list.splice(i, 1);
if (list.length == 0)
delete this._events[type];
} else if (this._events[type] === listener) {
delete this._events[type];
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
if (arguments.length === 0) {
this._events = {};
return this;
}
// does not use listeners(), so no side effect of creating _events[type]
if (type && this._events && this._events[type]) this._events[type] = null;
return this;
};
EventEmitter.prototype.listeners = function(type) {
if (!this._events) this._events = {};
if (!this._events[type]) this._events[type] = [];
if (!isArray(this._events[type])) {
this._events[type] = [this._events[type]];
}
return this._events[type];
};
})(require("__browserify_process"))
},{"__browserify_process":3}],5:[function(require,module,exports){
var events = require('events');
exports.isArray = isArray;
exports.isDate = function(obj){return Object.prototype.toString.call(obj) === '[object Date]'};
exports.isRegExp = function(obj){return Object.prototype.toString.call(obj) === '[object RegExp]'};
exports.print = function () {};
exports.puts = function () {};
exports.debug = function() {};
exports.inspect = function(obj, showHidden, depth, colors) {
var seen = [];
var stylize = function(str, styleType) {
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
var styles =
{ 'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39] };
var style =
{ 'special': 'cyan',
'number': 'blue',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red' }[styleType];
if (style) {
return '\033[' + styles[style][0] + 'm' + str +
'\033[' + styles[style][1] + 'm';
} else {
return str;
}
};
if (! colors) {
stylize = function(str, styleType) { return str; };
}
function format(value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (value && typeof value.inspect === 'function' &&
// Filter out the util module, it's inspect function is special
value !== exports &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
return value.inspect(recurseTimes);
}
// Primitive types cannot have properties
switch (typeof value) {
case 'undefined':
return stylize('undefined', 'undefined');
case 'string':
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return stylize(simple, 'string');
case 'number':
return stylize('' + value, 'number');
case 'boolean':
return stylize('' + value, 'boolean');
}
// For some reason typeof null is "object", so special case here.
if (value === null) {
return stylize('null', 'null');
}
// Look up the keys of the object.
var visible_keys = Object_keys(value);
var keys = showHidden ? Object_getOwnPropertyNames(value) : visible_keys;
// Functions without properties can be shortcutted.
if (typeof value === 'function' && keys.length === 0) {
if (isRegExp(value)) {
return stylize('' + value, 'regexp');
} else {
var name = value.name ? ': ' + value.name : '';
return stylize('[Function' + name + ']', 'special');
}
}
// Dates without properties can be shortcutted
if (isDate(value) && keys.length === 0) {
return stylize(value.toUTCString(), 'date');
}
var base, type, braces;
// Determine the object type
if (isArray(value)) {
type = 'Array';
braces = ['[', ']'];
} else {
type = 'Object';
braces = ['{', '}'];
}
// Make functions say that they are functions
if (typeof value === 'function') {
var n = value.name ? ': ' + value.name : '';
base = (isRegExp(value)) ? ' ' + value : ' [Function' + n + ']';
} else {
base = '';
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + value.toUTCString();
}
if (keys.length === 0) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return stylize('' + value, 'regexp');
} else {
return stylize('[Object]', 'special');
}
}
seen.push(value);
var output = keys.map(function(key) {
var name, str;
if (value.__lookupGetter__) {
if (value.__lookupGetter__(key)) {
if (value.__lookupSetter__(key)) {
str = stylize('[Getter/Setter]', 'special');
} else {
str = stylize('[Getter]', 'special');
}
} else {
if (value.__lookupSetter__(key)) {
str = stylize('[Setter]', 'special');
}
}
}
if (visible_keys.indexOf(key) < 0) {
name = '[' + key + ']';
}
if (!str) {
if (seen.indexOf(value[key]) < 0) {
if (recurseTimes === null) {
str = format(value[key]);
} else {
str = format(value[key], recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (isArray(value)) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = stylize('[Circular]', 'special');
}
}
if (typeof name === 'undefined') {
if (type === 'Array' && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = stylize(name, 'string');
}
}
return name + ': ' + str;
});
seen.pop();
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.length + 1;
}, 0);
if (length > 50) {
output = braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
} else {
output = braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
return output;
}
return format(obj, (typeof depth === 'undefined' ? 2 : depth));
};
function isArray(ar) {
return ar instanceof Array ||
Array.isArray(ar) ||
(ar && ar !== Object.prototype && isArray(ar.__proto__));
}
function isRegExp(re) {
return re instanceof RegExp ||
(typeof re === 'object' && Object.prototype.toString.call(re) === '[object RegExp]');
}
function isDate(d) {
if (d instanceof Date) return true;
if (typeof d !== 'object') return false;
var properties = Date.prototype && Object_getOwnPropertyNames(Date.prototype);
var proto = d.__proto__ && Object_getOwnPropertyNames(d.__proto__);
return JSON.stringify(proto) === JSON.stringify(properties);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
exports.log = function (msg) {};
exports.pump = null;
var Object_keys = Object.keys || function (obj) {
var res = [];
for (var key in obj) res.push(key);
return res;
};
var Object_getOwnPropertyNames = Object.getOwnPropertyNames || function (obj) {
var res = [];
for (var key in obj) {
if (Object.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
var Object_create = Object.create || function (prototype, properties) {
// from es5-shim
var object;
if (prototype === null) {
object = { '__proto__' : null };
}
else {
if (typeof prototype !== 'object') {
throw new TypeError(
'typeof prototype[' + (typeof prototype) + '] != \'object\''
);
}
var Type = function () {};
Type.prototype = prototype;
object = new Type();
object.__proto__ = prototype;
}
if (typeof properties !== 'undefined' && Object.defineProperties) {
Object.defineProperties(object, properties);
}
return object;
};
exports.inherits = function(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object_create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (typeof f !== 'string') {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(exports.inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j': return JSON.stringify(args[i++]);
default:
return x;
}
});
for(var x = args[i]; i < len; x = args[++i]){
if (x === null || typeof x !== 'object') {
str += ' ' + x;
} else {
str += ' ' + exports.inspect(x);
}
}
return str;
};
},{"events":4}],2:[function(require,module,exports){
var _ = require('underscore')
, EventEmitter = require('events').EventEmitter
, inherits = require('util').inherits
if (typeof AudioContext === 'undefined') {
if (typeof webkitAudioContext !== 'undefined')
var AudioContext = webkitAudioContext
else
console.error('This browser doesn\'t seem to support web audio API')
}
// ==================== Event ==================== //
var Event = function(clock, time, func) {
this.clock = clock
this.time = time
this.func = func
this.repeatTime = null
this.toleranceTime = 0.010
}
inherits(Event, EventEmitter)
_.extend(Event.prototype, {
// Unschedules the event
clear: function() {
this.clock._clear(this)
return this
},
// Sets the event to repeat every `time` seconds.
repeat: function(time) {
this.clock._setRepeat(this, time)
return this
},
// Sets the tolerance of the event. If the event is executed more than
// `time` seconds behind the expected date, it will be dropped.
tolerance: function(time) {
this.toleranceTime = time
return this
},
// Returns true if the event is repeated, false otherwise
isRepeated: function() { return this.repeatTime !== null }
})
// ==================== WAAClock ==================== //
var CLOCK_DEFAULTS = {
tickTime: 0.010,
lookAheadTime: 0.020
}
var WAAClock = module.exports = function(context, opts) {
var self = this
opts = _.defaults(opts || {}, CLOCK_DEFAULTS)
_.extend(this, _.pick(opts, Object.keys(CLOCK_DEFAULTS)))
this.context = context
initAudioContext(context, this)
this._events = []
this._start()
}
_.extend(WAAClock.prototype, {
// ---------- Public API ---------- //
// Schedule `func` to run after `delay` seconds.
// This method tries to schedule the event as accurately as possible,
// but it will never be exact as `AudioNode.start` or `AudioParam.scheduleSetValue`.
setTimeout: function(func, delay) {
var self = this
, event = this._createEvent(function() {
setTimeout(func, self._relTime(event.time))
}, this._absTime(delay))
return event
},
// Stretch time and repeat time of all scheduled `events` by `ratio`, keeping
// their relative distance. In fact this is equivalent to changing the tempo.
timeStretch: function(events, ratio) {
var self = this
, eventRef = _.min(events, function(e) { return e.time })
, tRef1 = eventRef.time
, tRef2 = this._absTime(ratio * this._relTime(eventRef.time))
events.forEach(function(event) {
self._setTime(event, tRef2 + ratio * (event.time - tRef1))
if(event.isRepeated()) self._setRepeat(event, event.repeatTime * ratio)
})
return events
},
// ---------- Private ---------- //
// Unschedule `event`
_clear: function(event) {
this._removeEvent(event)
},
// Sets the interval at which `event` repeats. `time` is in seconds.
_setRepeat: function(event, time) {
if (time === 0)
throw new Error('delay cannot be 0')
event.repeatTime = time
},
// Sets the occurence time of `event`. `time` is in absolute time.
_setTime: function(event, time) {
if (time < this.context.currentTime)
throw new Error('cannot schedule an event in the past')
this._removeEvent(event)
event.time = time
this._insertEvent(event)
},
// This starts the periodical execution of `_tick`
_start: function() {
if (this._tickIntervalId === undefined) {
var self = this
this._tickIntervalId = setInterval(function() {
self._tick()
}, this.tickTime * 1000)
self._tick()
}
// Force the context's clock to start
this.context.createBufferSource()
},
// This function is ran periodically, and at each tick it executes
// events for that are scheduled to happen in a time <= `lookAheadTime`.
_tick: function() {
var timeLookedAhead = this._absTime(this.lookAheadTime)
, event = this._events.shift()
// Execute the events
while(event && event.time <= timeLookedAhead) {
if (event.time > this._absTime(-event.toleranceTime)) {
event.func()
event.emit('executed')
} else {
event.emit('expired')
console.warn('event expired')
}
if (event.isRepeated())
this._setTime(event, event.time + event.repeatTime)
event = this._events.shift()
}
// Put back the last event
if(event) this._events.unshift(event)
},
// Creates an event and insert it to the list
_createEvent: function(func, time) {
var event = new Event(this, time, func)
this._insertEvent(event)
return event
},
// Inserts an event to the list
_insertEvent: function(event) {
this._events.splice(this._indexByTime(event.time), 0, event)
},
// Removes an event from the list
_removeEvent: function(event) {
var ind = this._events.indexOf(event)
if (ind !== -1) this._events.splice(ind, 1)
},
// Returns the index of the first event whose time is >= to `time`
_indexByTime: function(time) {
return _.sortedIndex(this._events, {time: time}, function(e) { return e.time })
},
// Converts from relative time to absolute time
_absTime: function(relTime) {
return relTime + this.context.currentTime
},
// Converts from absolute time to relative time
_relTime: function(absTime) {
return absTime - this.context.currentTime
}
})
// ==================== Web Audio API patches ==================== //
var AudioParamMixin = {
setValueAtTime2: function(value, time) {
var self = this
, event = this._waac._createEvent(function() {
self.setValueAtTime(value, event.time)
}, time)
return event
},
_waac: null
}
var initAudioContext = function(context, clock) {
// Replacing the AudioNode creation methods to attach custom methods
// upon creation of each AudioNode
['createOscillator', 'createBufferSource', 'createMediaElementSource',
'createMediaStreamSource', 'createMediaStreamDestination', 'createScriptProcessor',
'createAnalyser', 'createGain', 'createDelay', 'createBiquadFilter',
'createWaveShaper', 'createPanner', 'createConvolver', 'createChannelSplitter',
'createChannelMerger', 'createDynamicsCompressor'].forEach(function(methName) {
context[methName] = function() {
var node = AudioContext.prototype[methName].apply(this, arguments)
return initAudioNode(node, clock)
}
})
return _.extend(context, AudioContextMixin, {_waac: clock})
}
var AudioContextMixin = {
_waac: null
}
var initAudioNode = function(node, clock) {
// Mixing-in AudioParams
var audioParams = _.filter(_.values(node), function(val) {
return _.isObject(val) && _.isFunction(val.setValueAtTime)
})
audioParams.forEach(function(audioParam) {
_.extend(audioParam, AudioParamMixin, {_waac: clock})
})
// Adding start2/stop2 to nodes that have start/stop methods
;['start', 'stop'].forEach(function(methName) {
if (node[methName]) node[methName+'2'] = AudioNodeMixin[methName+'2']
})
return _.extend(node, {_waac: clock})
}
var AudioNodeMixin = {
start2: function(time) {
var self = this
, args = _.toArray(arguments).slice(1)
, event = this._waac._createEvent(function() {
self.start.apply(self, [event.time].concat(args))
}, time)
return event
},
stop2: function(time) {
var args = _.toArray(arguments).slice(1)
, event = this._waac._createEvent(function() {
self.stop.apply(self, [event.time].concat(args))
}, time)
return event
},
_waac: null
}
},{"events":4,"util":5,"underscore":6}],6:[function(require,module,exports){
(function(){// Underscore.js 1.4.4
// http://underscorejs.org
// (c) 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore may be freely distributed under the MIT license.
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `global` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Establish the object that gets returned to break out of a loop iteration.
var breaker = {};
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var push = ArrayProto.push,
slice = ArrayProto.slice,
concat = ArrayProto.concat,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeForEach = ArrayProto.forEach,
nativeMap = ArrayProto.map,
nativeReduce = ArrayProto.reduce,
nativeReduceRight = ArrayProto.reduceRight,
nativeFilter = ArrayProto.filter,
nativeEvery = ArrayProto.every,
nativeSome = ArrayProto.some,
nativeIndexOf = ArrayProto.indexOf,
nativeLastIndexOf = ArrayProto.lastIndexOf,
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object via a string identifier,
// for Closure Compiler "advanced" mode.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.4.4';
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (_.has(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
// Return the results of applying the iterator to each element.
// Delegates to **ECMAScript 5**'s native `map` if available.
_.map = _.collect = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
each(obj, function(value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
return results;
};
var reduceError = 'Reduce of empty array with no initial value';
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
_.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduce && obj.reduce === nativeReduce) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
}
each(obj, function(value, index, list) {
if (!initial) {
memo = value;
initial = true;
} else {
memo = iterator.call(context, memo, value, index, list);
}
});
if (!initial) throw new TypeError(reduceError);
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
// Delegates to **ECMAScript 5**'s native `reduceRight` if available.
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
}
var length = obj.length;
if (length !== +length) {
var keys = _.keys(obj);
length = keys.length;
}
each(obj, function(value, index, list) {
index = keys ? keys[--length] : --length;
if (!initial) {
memo = obj[index];
initial = true;
} else {
memo = iterator.call(context, memo, obj[index], index, list);
}
});
if (!initial) throw new TypeError(reduceError);
return memo;
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, iterator, context) {
var result;
any(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Delegates to **ECMAScript 5**'s native `filter` if available.
// Aliased as `select`.
_.filter = _.select = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
each(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, iterator, context) {
return _.filter(obj, function(value, index, list) {
return !iterator.call(context, value, index, list);
}, context);
};
// Determine whether all of the elements match a truth test.
// Delegates to **ECMAScript 5**'s native `every` if available.
// Aliased as `all`.
_.every = _.all = function(obj, iterator, context) {
iterator || (iterator = _.identity);
var result = true;
if (obj == null) return result;
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
each(obj, function(value, index, list) {
if (!(result = result && iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if at least one element in the object matches a truth test.
// Delegates to **ECMAScript 5**'s native `some` if available.
// Aliased as `any`.
var any = _.some = _.any = function(obj, iterator, context) {
iterator || (iterator = _.identity);
var result = false;
if (obj == null) return result;
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
each(obj, function(value, index, list) {
if (result || (result = iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if the array or object contains a given value (using `===`).
// Aliased as `include`.
_.contains = _.include = function(obj, target) {
if (obj == null) return false;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
return any(obj, function(value) {
return value === target;
});
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
return (isFunc ? method : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, function(value){ return value[key]; });
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs, first) {
if (_.isEmpty(attrs)) return first ? null : [];
return _[first ? 'find' : 'filter'](obj, function(value) {
for (var key in attrs) {
if (attrs[key] !== value[key]) return false;
}
return true;
});
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.where(obj, attrs, true);
};
// Return the maximum element or (element-based computation).
// Can't optimize arrays of integers longer than 65,535 elements.
// See: https://bugs.webkit.org/show_bug.cgi?id=80797
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
return Math.max.apply(Math, obj);
}
if (!iterator && _.isEmpty(obj)) return -Infinity;
var result = {computed : -Infinity, value: -Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed >= result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
return Math.min.apply(Math, obj);
}
if (!iterator && _.isEmpty(obj)) return Infinity;
var result = {computed : Infinity, value: Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed < result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Shuffle an array.
_.shuffle = function(obj) {
var rand;
var index = 0;
var shuffled = [];
each(obj, function(value) {
rand = _.random(index++);
shuffled[index - 1] = shuffled[rand];
shuffled[rand] = value;
});
return shuffled;
};
// An internal function to generate lookup iterators.
var lookupIterator = function(value) {
return _.isFunction(value) ? value : function(obj){ return obj[value]; };
};
// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, value, context) {
var iterator = lookupIterator(value);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value : value,
index : index,
criteria : iterator.call(context, value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index < right.index ? -1 : 1;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(obj, value, context, behavior) {
var result = {};
var iterator = lookupIterator(value || _.identity);
each(obj, function(value, index) {
var key = iterator.call(context, value, index, obj);
behavior(result, key, value);
});
return result;
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = function(obj, value, context) {
return group(obj, value, context, function(result, key, value) {
(_.has(result, key) ? result[key] : (result[key] = [])).push(value);
});
};
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = function(obj, value, context) {
return group(obj, value, context, function(result, key) {
if (!_.has(result, key)) result[key] = 0;
result[key]++;
});
};
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iterator, context) {
iterator = iterator == null ? _.identity : lookupIterator(iterator);
var value = iterator.call(context, obj);
var low = 0, high = array.length;
while (low < high) {
var mid = (low + high) >>> 1;
iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
}
return low;
};
// Safely convert anything iterable into a real, live array.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (obj.length === +obj.length) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N. The **guard** check allows it to work with
// `_.map`.
_.initial = function(array, n, guard) {
return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if ((n != null) && !guard) {
return slice.call(array, Math.max(array.length - n, 0));
} else {
return array[array.length - 1];
}
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, (n == null) || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, output) {
each(input, function(value) {
if (_.isArray(value)) {
shallow ? push.apply(output, value) : flatten(value, shallow, output);
} else {
output.push(value);
}
});
return output;
};
// Return a completely flattened version of an array.
_.flatten = function(array, shallow) {
return flatten(array, shallow, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iterator, context) {
if (_.isFunction(isSorted)) {
context = iterator;
iterator = isSorted;
isSorted = false;
}
var initial = iterator ? _.map(array, iterator, context) : array;
var results = [];
var seen = [];
each(initial, function(value, index) {
if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
seen.push(value);
results.push(array[index]);
}
});
return results;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(concat.apply(ArrayProto, arguments));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.indexOf(other, item) >= 0;
});
});
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
return _.filter(array, function(value){ return !_.contains(rest, value); });
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
var args = slice.call(arguments);
var length = _.max(_.pluck(args, 'length'));
var results = new Array(length);
for (var i = 0; i < length; i++) {
results[i] = _.pluck(args, "" + i);
}
return results;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
if (list == null) return {};
var result = {};
for (var i = 0, l = list.length; i < l; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
// we need this function. Return the position of the first occurrence of an
// item in an array, or -1 if the item is not included in the array.
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, l = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
for (; i < l; i++) if (array[i] === item) return i;
return -1;
};
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
_.lastIndexOf = function(array, item, from) {
if (array == null) return -1;
var hasIndex = from != null;
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
}
var i = (hasIndex ? from : array.length);
while (i--) if (array[i] === item) return i;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = arguments[2] || 1;
var len = Math.max(Math.ceil((stop - start) / step), 0);
var idx = 0;
var range = new Array(len);
while(idx < len) {
range[idx++] = start;
start += step;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
_.bind = function(func, context) {
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
var args = slice.call(arguments, 2);
return function() {
return func.apply(context, args.concat(slice.call(arguments)));
};
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context.
_.partial = function(func) {
var args = slice.call(arguments, 1);
return function() {
return func.apply(this, args.concat(slice.call(arguments)));
};
};
// Bind all of an object's methods to that object. Useful for ensuring that
// all callbacks defined on an object belong to it.
_.bindAll = function(obj) {
var funcs = slice.call(arguments, 1);
if (funcs.length === 0) funcs = _.functions(obj);
each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memo = {};
hasher || (hasher = _.identity);
return function() {
var key = hasher.apply(this, arguments);
return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
};
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){ return func.apply(null, args); }, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time.
_.throttle = function(func, wait) {
var context, args, timeout, result;
var previous = 0;
var later = function() {
previous = new Date;
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = new Date;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout, result;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) result = func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) result = func.apply(context, args);
return result;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
memo = func.apply(this, arguments);
func = null;
return memo;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return function() {
var args = [func];
push.apply(args, arguments);
return wrapper.apply(this, args);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var funcs = arguments;
return function() {
var args = arguments;
for (var i = funcs.length - 1; i >= 0; i--) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
if (times <= 0) return func();
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = nativeKeys || function(obj) {
if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
var values = [];
for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
return values;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
var pairs = [];
for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
return result;
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
}
});
return obj;
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
each(keys, function(key) {
if (key in obj) copy[key] = obj[key];
});
return copy;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
for (var key in obj) {
if (!_.contains(keys, key)) copy[key] = obj[key];
}
return copy;
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
each(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
if (obj[prop] == null) obj[prop] = source[prop];
}
}
});
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
if (a === b) return a !== 0 || 1 / a == 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className != toString.call(b)) return false;
switch (className) {
// Strings, numbers, dates, and booleans are compared by value.
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return a == String(b);
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
// other numeric values.
return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a == +b;
// RegExps are compared by their source patterns and flags.
case '[object RegExp]':
return a.source == b.source &&
a.global == b.global &&
a.multiline == b.multiline &&
a.ignoreCase == b.ignoreCase;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] == a) return bStack[length] == b;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
var size = 0, result = true;
// Recursively compare objects and arrays.
if (className == '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size == b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
if (!(result = eq(a[size], b[size], aStack, bStack))) break;
}
}
} else {
// Objects with different constructors are not equivalent, but `Object`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
_.isFunction(bCtor) && (bCtor instanceof bCtor))) {
return false;
}
// Deep compare objects.
for (var key in a) {
if (_.has(a, key)) {
// Count the expected number of properties.
size++;
// Deep compare each member.
if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
}
}
// Ensure that both objects contain the same number of properties.
if (result) {
for (key in b) {
if (_.has(b, key) && !(size--)) break;
}
result = !size;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return result;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b, [], []);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (_.has(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) == '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
return obj === Object(obj);
};
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) == '[object ' + name + ']';
};
});
// Define a fallback version of the method in browsers (ahem, IE), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return !!(obj && _.has(obj, 'callee'));
};
}
// Optimize `isFunction` if appropriate.
if (typeof (/./) !== 'function') {
_.isFunction = function(obj) {
return typeof obj === 'function';
};
}
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj != +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iterators.
_.identity = function(value) {
return value;
};
// Run a function **n** times.
_.times = function(n, iterator, context) {
var accum = Array(n);
for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
return accum;
};
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
// List of HTML entities for escaping.
var entityMap = {
escape: {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
}
};
entityMap.unescape = _.invert(entityMap.escape);
// Regexes containing the keys and values listed immediately above.
var entityRegexes = {
escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
};
// Functions for escaping and unescaping strings to/from HTML interpolation.
_.each(['escape', 'unescape'], function(method) {
_[method] = function(string) {
if (string == null) return '';
return ('' + string).replace(entityRegexes[method], function(match) {
return entityMap[method][match];
});
};
});
// If the value of the named property is a function then invoke it;
// otherwise, return it.
_.result = function(object, property) {
if (object == null) return null;
var value = object[property];
return _.isFunction(value) ? value.call(object) : value;
};
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
each(_.functions(obj), function(name){
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return result.call(this, func.apply(_, args));
};
});
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(text, data, settings) {
var render;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = new RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset)
.replace(escaper, function(match) { return '\\' + escapes[match]; });
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
}
if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
}
if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
index = offset + match.length;
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + "return __p;\n";
try {
render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
if (data) return render(data, _);
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled function source as a convenience for precompilation.
template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
return template;
};
// Add a "chain" function, which will delegate to the wrapper.
_.chain = function(obj) {
return _(obj).chain();
};
// OOP
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
// Helper function to continue chaining intermediate results.
var result = function(obj) {
return this._chain ? _(obj).chain() : obj;
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
var obj = this._wrapped;
method.apply(obj, arguments);
if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
return result.call(this, obj);
};
});
// Add all accessor Array functions to the wrapper.
each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
return result.call(this, method.apply(this._wrapped, arguments));
};
});
_.extend(_.prototype, {
// Start chaining a wrapped Underscore object.
chain: function() {
this._chain = true;
return this;
},
// Extracts the result from a wrapped and chained object.
value: function() {
return this._wrapped;
}
});
}).call(this);
})()
},{}]},{},[1])
; | mit |
cdnjs/cdnjs | ajax/libs/simple-icons/4.16.0/zendframework.js | 655 | module.exports={title:"Zend Framework",slug:"zendframework",svg:'<svg role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>Zend Framework icon</title><path d="M.932 6.242v2.535h5.652L0 17.757h10.219v-2.534h-5.18l6.553-8.98H.932zm13.537.162c-3.178 0-3.178 3.178-3.178 3.178h9.531C24 9.582 24 6.404 24 6.404h-9.531zm-.006 4.067c-3.173 0-3.172 3.172-3.172 3.172l4.762.005c3.178 0 3.177-3.177 3.177-3.177h-4.767zm0 4.049c-3.173 0-3.172 3.183-3.172 3.183l1.584-.006c3.178 0 3.178-3.177 3.178-3.177h-1.59Z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://framework.zend.com/",hex:"68B604",license:void 0}; | mit |
RallySoftware/eclipselink.runtime | foundation/eclipselink.extension.oracle.test/src/org/eclipse/persistence/testing/tests/nchar/CharNcharTableCreator.java | 4915 | /*******************************************************************************
* 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.tests.nchar;
import org.eclipse.persistence.tools.schemaframework.*;
/**
* This class was generated by the TopLink table creator generator.
* It stores the meta-data (tables) that define the database schema.
* @see org.eclipse.persistence.sessions.factories.TableCreatorClassGenerator
*/
public class CharNcharTableCreator extends TableCreator {
public CharNcharTableCreator() {
setName("CharNchar");
addTableDefinition(buildCHARNCHARTable());
}
public TableDefinition buildCHARNCHARTable() {
TableDefinition table = new TableDefinition();
table.setName("CHARNCHAR");
FieldDefinition fieldID = new FieldDefinition();
fieldID.setName("ID");
fieldID.setTypeName("NUMBER");
fieldID.setSize(20);
fieldID.setSubSize(0);
fieldID.setIsPrimaryKey(true);
fieldID.setIsIdentity(false);
fieldID.setUnique(false);
fieldID.setShouldAllowNull(false);
table.addField(fieldID);
FieldDefinition fieldCH = new FieldDefinition();
fieldCH.setName("CH");
fieldCH.setTypeName("CHAR");
fieldCH.setSize(1);
fieldCH.setSubSize(0);
fieldCH.setIsPrimaryKey(false);
fieldCH.setIsIdentity(false);
fieldCH.setUnique(false);
fieldCH.setShouldAllowNull(true);
table.addField(fieldCH);
FieldDefinition fieldNCH = new FieldDefinition();
fieldNCH.setName("NCH");
fieldNCH.setTypeName("NCHAR");
fieldNCH.setSize(1);
fieldNCH.setSubSize(0);
fieldNCH.setIsPrimaryKey(false);
fieldNCH.setIsIdentity(false);
fieldNCH.setUnique(false);
fieldNCH.setShouldAllowNull(true);
table.addField(fieldNCH);
FieldDefinition fieldSTR = new FieldDefinition();
fieldSTR.setName("STR");
fieldSTR.setTypeName("VARCHAR2");
fieldSTR.setSize(20);
fieldSTR.setSubSize(0);
fieldSTR.setIsPrimaryKey(false);
fieldSTR.setIsIdentity(false);
fieldSTR.setUnique(false);
fieldSTR.setShouldAllowNull(true);
table.addField(fieldSTR);
FieldDefinition fieldNSTR = new FieldDefinition();
fieldNSTR.setName("NSTR");
fieldNSTR.setTypeName("NVARCHAR2");
fieldNSTR.setSize(20);
fieldNSTR.setSubSize(0);
fieldNSTR.setIsPrimaryKey(false);
fieldNSTR.setIsIdentity(false);
fieldNSTR.setUnique(false);
fieldNSTR.setShouldAllowNull(true);
table.addField(fieldNSTR);
FieldDefinition fieldCLB = new FieldDefinition();
fieldCLB.setName("CLB");
fieldCLB.setTypeName("CLOB");
fieldCLB.setSize(0);
fieldCLB.setSubSize(0);
fieldCLB.setIsPrimaryKey(false);
fieldCLB.setIsIdentity(false);
fieldCLB.setUnique(false);
fieldCLB.setShouldAllowNull(true);
table.addField(fieldCLB);
FieldDefinition fieldNCLB = new FieldDefinition();
fieldNCLB.setName("NCLB");
fieldNCLB.setTypeName("NCLOB");
fieldNCLB.setSize(0);
fieldNCLB.setSubSize(0);
fieldNCLB.setIsPrimaryKey(false);
fieldNCLB.setIsIdentity(false);
fieldNCLB.setUnique(false);
fieldNCLB.setShouldAllowNull(true);
table.addField(fieldNCLB);
FieldDefinition fieldCLB2 = new FieldDefinition();
fieldCLB2.setName("CLB2");
fieldCLB2.setTypeName("CLOB");
fieldCLB2.setSize(0);
fieldCLB2.setSubSize(0);
fieldCLB2.setIsPrimaryKey(false);
fieldCLB2.setIsIdentity(false);
fieldCLB2.setUnique(false);
fieldCLB2.setShouldAllowNull(true);
table.addField(fieldCLB2);
FieldDefinition fieldNCLB2 = new FieldDefinition();
fieldNCLB2.setName("NCLB2");
fieldNCLB2.setTypeName("NCLOB");
fieldNCLB2.setSize(0);
fieldNCLB2.setSubSize(0);
fieldNCLB2.setIsPrimaryKey(false);
fieldNCLB2.setIsIdentity(false);
fieldNCLB2.setUnique(false);
fieldNCLB2.setShouldAllowNull(true);
table.addField(fieldNCLB2);
return table;
}
}
| epl-1.0 |
rarguello/ironjacamar | core/src/main/java/org/ironjacamar/core/workmanager/transport/remote/jgroups/SecurityActions.java | 3081 | /*
* IronJacamar, a Java EE Connector Architecture implementation
* Copyright 2014, 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 Eclipse Public License 1.0 as
* published by the Free Software Foundation.
*
* 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 Eclipse
* Public License for more details.
*
* You should have received a copy of the Eclipse 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.ironjacamar.core.workmanager.transport.remote.jgroups;
import org.ironjacamar.core.workmanager.ClassBundle;
import org.ironjacamar.core.workmanager.WorkClassLoader;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
/**
* Privileged Blocks
* @author <a href="mailto:jesper.pedersen@ironjacamar.org">Jesper Pedersen</a>
*/
class SecurityActions
{
/**
* Constructor
*/
private SecurityActions()
{
}
/**
* Get a system property
* @param name The property name
* @return The property value
*/
static String getSystemProperty(final String name)
{
return AccessController.doPrivileged(new PrivilegedAction<String>()
{
public String run()
{
return System.getProperty(name);
}
});
}
/**
* Create a WorkClassLoader
* @param cb The class bundle
* @return The class loader
*/
static WorkClassLoader createWorkClassLoader(final ClassBundle cb)
{
return AccessController.doPrivileged(new PrivilegedAction<WorkClassLoader>()
{
public WorkClassLoader run()
{
return new WorkClassLoader(cb);
}
});
}
/**
* Get the method
* @param c The class
* @param name The name
* @param params The parameters
* @return The method
* @exception NoSuchMethodException If a matching method is not found.
*/
static Method getMethod(final Class<?> c, final String name, final Class<?>... params)
throws NoSuchMethodException
{
if (System.getSecurityManager() == null)
return c.getMethod(name, params);
Method result = AccessController.doPrivileged(new PrivilegedAction<Method>()
{
public Method run()
{
try
{
return c.getMethod(name, params);
}
catch (NoSuchMethodException e)
{
return null;
}
}
});
if (result != null)
return result;
throw new NoSuchMethodException();
}
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/performance/jdbc/RowFetchTest.java | 3576 | /*******************************************************************************
* 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.tests.performance.jdbc;
import java.util.*;
import java.sql.*;
import org.eclipse.persistence.internal.sessions.AbstractSession;
import org.eclipse.persistence.testing.framework.*;
/**
* This test compares the performance between using a set rowfetch or the default.
*/
public class RowFetchTest extends PerformanceComparisonTestCase {
protected Connection connection;
protected Number id;
protected String sql;
public RowFetchTest() {
setName("Default row fetch vs set row fetch (2, 1 object) PerformanceComparisonTest");
setDescription("Compares the performance between using default and set row fetch, query 1 row, row fetch set to 2.");
addSetRowFetch();
}
public void setup() throws Exception {
connection = (Connection)((AbstractSession)getSession()).getAccessor().getDatasourceConnection();
PreparedStatement statement = connection.prepareStatement("SELECT EMP_ID FROM EMPLOYEE");
ResultSet result = statement.executeQuery();
int size = result.getMetaData().getColumnCount();
result.next();
id = (Number)result.getObject(1);
result.close();
statement.close();
sql = "SELECT * FROM EMPLOYEE where emp_id = " + id;
}
/**
* Default row fetch (10).
*/
public void test() throws Exception {
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet result = statement.executeQuery();
int size = result.getMetaData().getColumnCount();
Vector rows = new Vector();
while (result.next()) {
Vector row = new Vector(size);
for (int column = 1; column <= size; column++) {
row.add(result.getObject(column));
}
rows.add(row);
}
result.close();
statement.close();
}
/**
* Static.
*/
public void addSetRowFetch() {
PerformanceComparisonTestCase test = new PerformanceComparisonTestCase() {
public void test() throws Exception {
PreparedStatement statement = connection.prepareStatement(sql);
statement.setFetchSize(2);
ResultSet result = statement.executeQuery();
int size = result.getMetaData().getColumnCount();
Vector rows = new Vector();
while (result.next()) {
Vector row = new Vector(size);
for (int column = 1; column <= size; column++) {
row.add(result.getObject(column));
}
rows.add(row);
}
result.close();
statement.close();
}
};
test.setName("SetRowFetchTest");
addTest(test);
}
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/sessions/coordination/RemoteConnection.java | 2615 | /*******************************************************************************
* 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.sessions.coordination;
import org.eclipse.persistence.exceptions.CommunicationException;
import org.eclipse.persistence.sessions.coordination.ServiceId;
import org.eclipse.persistence.sessions.coordination.Command;
/**
* <p>
* <b>Purpose</b>: Define an abstract class for the remote object that can execute
* a remote command using different transport protocols.
* <p>
* <b>Description</b>: This abstract class represents the remote object that is
* used by the remote command manager to send remote commands. The underlying
* transport mechanism is transparently implemented by the transport subclass
* implementations.
*
* @since OracleAS TopLink 10<i>g</i> (9.0.4)
*/
public abstract class RemoteConnection implements java.io.Serializable {
/** The service on the receiving end of this connection */
protected ServiceId serviceId;
/**
* INTERNAL:
* Execute the remote command. The result of execution is returned.
*/
public abstract Object executeCommand(Command command) throws CommunicationException;
/**
* INTERNAL:
* Execute the remote command. The result of execution is returned.
*/
public abstract Object executeCommand(byte[] command) throws CommunicationException;
/**
* INTERNAL:
* Return the service info of the receiving service
*/
public ServiceId getServiceId() {
return serviceId;
}
/**
* INTERNAL:
* Set the service info of the receiving service
*/
public void setServiceId(ServiceId newServiceId) {
serviceId = newServiceId;
}
public String toString() {
return "RemoteConnection[" + serviceId + "]";
}
/**
* INTERNAL:
* cleanup whatever is necessary. Invoked when the TransportManager discard connections.
*/
public void close() {
}
;
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | jpa/org.eclipse.persistence.jpa/src/org/eclipse/persistence/internal/jpa/metadata/accessors/classes/EntityAccessor.java | 66596 | /*******************************************************************************
* 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:
* Guy Pelletier - initial API and implementation from Oracle TopLink
* 05/16/2008-1.0M8 Guy Pelletier
* - 218084: Implement metadata merging functionality between mapping files
* 05/23/2008-1.0M8 Guy Pelletier
* - 211330: Add attributes-complete support to the EclipseLink-ORM.XML Schema
* 05/30/2008-1.0M8 Guy Pelletier
* - 230213: ValidationException when mapping to attribute in MappedSuperClass
* 06/20/2008-1.0M9 Guy Pelletier
* - 232975: Failure when attribute type is generic
* 07/15/2008-1.0.1 Guy Pelletier
* - 240679: MappedSuperclass Id not picked when on get() method accessor
* 09/23/2008-1.1 Guy Pelletier
* - 241651: JPA 2.0 Access Type support
* 10/01/2008-1.1 Guy Pelletier
* - 249329: To remain JPA 1.0 compliant, any new JPA 2.0 annotations should be referenced by name
* 12/12/2008-1.1 Guy Pelletier
* - 249860: Implement table per class inheritance support.
* 01/28/2009-2.0 Guy Pelletier
* - 248293: JPA 2.0 Element Collections (part 1)
* 02/06/2009-2.0 Guy Pelletier
* - 248293: JPA 2.0 Element Collections (part 2)
* 03/27/2009-2.0 Guy Pelletier
* - 241413: JPA 2.0 Add EclipseLink support for Map type attributes
* 04/03/2009-2.0 Guy Pelletier
* - 241413: JPA 2.0 Add EclipseLink support for Map type attributes
* 04/24/2009-2.0 Guy Pelletier
* - 270011: JPA 2.0 MappedById support
* 04/30/2009-2.0 Michael O'Brien
* - 266912: JPA 2.0 Metamodel API (part of Criteria API)
* 06/16/2009-2.0 Guy Pelletier
* - 277039: JPA 2.0 Cache Usage Settings
* 06/25/2009-2.0 Michael O'Brien
* - 266912: change MappedSuperclass handling in stage2 to pre process accessors
* in support of the custom descriptors holding mappings required by the Metamodel.
* processAccessType() is now public and is overridden in the superclass
* 09/29/2009-2.0 Guy Pelletier
* - 282553: JPA 2.0 JoinTable support for OneToOne and ManyToOne
* 10/21/2009-2.0 Guy Pelletier
* - 290567: mappedbyid support incomplete
* 12/2/2009-2.1 Guy Pelletier
* - 296289: Add current annotation metadata support on mapped superclasses to EclipseLink-ORM.XML Schema
* 12/18/2009-2.1 Guy Pelletier
* - 211323: Add class extractor support to the EclipseLink-ORM.XML Schema
* 04/09/2010-2.1 Guy Pelletier
* - 307050: Add defaults for access methods of a VIRTUAL access type
* 05/04/2010-2.1 Guy Pelletier
* - 309373: Add parent class attribute to EclipseLink-ORM
* 05/14/2010-2.1 Guy Pelletier
* - 253083: Add support for dynamic persistence using ORM.xml/eclipselink-orm.xml
* 06/01/2010-2.1 Guy Pelletier
* - 315195: Add new property to avoid reading XML during the canonical model generation
* 06/09/2010-2.0.3 Guy Pelletier
* - 313401: shared-cache-mode defaults to NONE when the element value is unrecognized
* 06/14/2010-2.2 Guy Pelletier
* - 264417: Table generation is incorrect for JoinTables in AssociationOverrides
* 06/18/2010-2.2 Guy Pelletier
* - 300458: EclispeLink should throw a more specific exception than NPE
* 06/22/2010-2.2 Guy Pelletier
* - 308729: Persistent Unit deployment exception when mappedsuperclass has no annotations but has lifecycle callbacks
* 07/05/2010-2.1.1 Guy Pelletier
* - 317708: Exception thrown when using LAZY fetch on VIRTUAL mapping
* 08/11/2010-2.2 Guy Pelletier
* - 312123: JPA: Validation error during Id processing on parameterized generic OneToOne Entity relationship from MappedSuperclass
* 09/03/2010-2.2 Guy Pelletier
* - 317286: DB column lenght not in sync between @Column and @JoinColumn
* 09/16/2010-2.2 Guy Pelletier
* - 283028: Add support for letting an @Embeddable extend a @MappedSuperclass
* 12/01/2010-2.2 Guy Pelletier
* - 331234: xml-mapping-metadata-complete overriden by metadata-complete specification
* 01/04/2011-2.3 Guy Pelletier
* - 330628: @PrimaryKeyJoinColumn(...) is not working equivalently to @JoinColumn(..., insertable = false, updatable = false)
* 03/24/2011-2.3 Guy Pelletier
* - 337323: Multi-tenant with shared schema support (part 1)
* 04/05/2011-2.3 Guy Pelletier
* - 337323: Multi-tenant with shared schema support (part 3)
* 03/24/2011-2.3 Guy Pelletier
* - 337323: Multi-tenant with shared schema support (part 8)
* 07/03/2011-2.3.1 Guy Pelletier
* - 348756: m_cascadeOnDelete boolean should be changed to Boolean
* 10/09/2012-2.5 Guy Pelletier
* - 374688: JPA 2.1 Converter support
* 10/25/2012-2.5 Guy Pelletier
* - 3746888: JPA 2.1 Converter support
* 11/19/2012-2.5 Guy Pelletier
* - 389090: JPA 2.1 DDL Generation Support (foreign key metadata support)
* 11/28/2012-2.5 Guy Pelletier
* - 374688: JPA 2.1 Converter support
* 11/29/2012-2.5 Guy Pelletier
* - 395406: Fix nightly static weave test errors
* 12/07/2012-2.5 Guy Pelletier
* - 389090: JPA 2.1 DDL Generation Support (foreign key metadata support)
* 09 Jan 2013-2.5 Gordon Yorke
* - 397772: JPA 2.1 Entity Graph Support
* 02/13/2013-2.5 Guy Pelletier
* - 397772: JPA 2.1 Entity Graph Support (XML support)
* 02/20/2013-2.5 Guy Pelletier
* - 389090: JPA 2.1 DDL Generation Support (foreign key metadata support)
* 05/19/2014-2.6 Tomas Kraus
* - 437578: @Cacheable annotation value is passed to CachePolicy for ENABLE_SELECTIVE and DISABLE_SELECTIVE shared cache mode
******************************************************************************/
package org.eclipse.persistence.internal.jpa.metadata.accessors.classes;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.eclipse.persistence.annotations.CascadeOnDelete;
import org.eclipse.persistence.annotations.ClassExtractor;
import org.eclipse.persistence.annotations.Index;
import org.eclipse.persistence.annotations.Indexes;
import org.eclipse.persistence.annotations.VirtualAccessMethods;
import org.eclipse.persistence.exceptions.ValidationException;
import org.eclipse.persistence.internal.helper.DatabaseTable;
import org.eclipse.persistence.internal.helper.DatabaseField;
import org.eclipse.persistence.internal.helper.Helper;
import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataAccessibleObject;
import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataAnnotation;
import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataClass;
import org.eclipse.persistence.internal.jpa.metadata.columns.DiscriminatorColumnMetadata;
import org.eclipse.persistence.internal.jpa.metadata.columns.PrimaryKeyForeignKeyMetadata;
import org.eclipse.persistence.internal.jpa.metadata.columns.PrimaryKeyJoinColumnMetadata;
import org.eclipse.persistence.internal.jpa.metadata.converters.ConvertMetadata;
import org.eclipse.persistence.internal.jpa.metadata.graphs.NamedEntityGraphMetadata;
import org.eclipse.persistence.internal.jpa.metadata.inheritance.InheritanceMetadata;
import org.eclipse.persistence.internal.jpa.metadata.listeners.EntityClassListenerMetadata;
import org.eclipse.persistence.internal.jpa.metadata.listeners.EntityListenerMetadata;
import org.eclipse.persistence.internal.jpa.metadata.mappings.AccessMethodsMetadata;
import org.eclipse.persistence.internal.jpa.metadata.MetadataDescriptor;
import org.eclipse.persistence.internal.jpa.metadata.MetadataLogger;
import org.eclipse.persistence.internal.jpa.metadata.MetadataProject;
import org.eclipse.persistence.internal.jpa.metadata.ORMetadata;
import org.eclipse.persistence.internal.jpa.metadata.tables.IndexMetadata;
import org.eclipse.persistence.internal.jpa.metadata.tables.SecondaryTableMetadata;
import org.eclipse.persistence.internal.jpa.metadata.tables.TableMetadata;
import org.eclipse.persistence.internal.jpa.metadata.xml.XMLEntityMappings;
import static org.eclipse.persistence.internal.jpa.metadata.MetadataConstants.JPA_ACCESS_FIELD;
import static org.eclipse.persistence.internal.jpa.metadata.MetadataConstants.JPA_ACCESS_PROPERTY;
import static org.eclipse.persistence.internal.jpa.metadata.MetadataConstants.JPA_CONVERT;
import static org.eclipse.persistence.internal.jpa.metadata.MetadataConstants.JPA_CONVERTS;
import static org.eclipse.persistence.internal.jpa.metadata.MetadataConstants.JPA_ENTITY;
import static org.eclipse.persistence.internal.jpa.metadata.MetadataConstants.JPA_DISCRIMINATOR_COLUMN;
import static org.eclipse.persistence.internal.jpa.metadata.MetadataConstants.JPA_DISCRIMINATOR_VALUE;
import static org.eclipse.persistence.internal.jpa.metadata.MetadataConstants.JPA_INHERITANCE;
import static org.eclipse.persistence.internal.jpa.metadata.MetadataConstants.JPA_PRIMARY_KEY_JOIN_COLUMN;
import static org.eclipse.persistence.internal.jpa.metadata.MetadataConstants.JPA_PRIMARY_KEY_JOIN_COLUMNS;
import static org.eclipse.persistence.internal.jpa.metadata.MetadataConstants.JPA_SECONDARY_TABLE;
import static org.eclipse.persistence.internal.jpa.metadata.MetadataConstants.JPA_SECONDARY_TABLES;
import static org.eclipse.persistence.internal.jpa.metadata.MetadataConstants.JPA_TABLE;
import static org.eclipse.persistence.internal.jpa.metadata.MetadataConstants.JPA_ENTITY_GRAPH;
import static org.eclipse.persistence.internal.jpa.metadata.MetadataConstants.JPA_ENTITY_GRAPHS;
/**
* An entity accessor.
*
* Key notes:
* - any metadata mapped from XML to this class must be compared in the
* equals method.
* - any metadata mapped from XML to this class must be handled in the merge
* method. (merging is done at the accessor/mapping level)
* - any metadata mapped from XML to this class must be initialized in the
* initXMLObject method.
* - methods should be preserved in alphabetical order.
*
* @author Guy Pelletier
* @since EclipseLink 1.0
*/
public class EntityAccessor extends MappedSuperclassAccessor {
private Boolean m_cascadeOnDelete;
private InheritanceMetadata m_inheritance;
private DiscriminatorColumnMetadata m_discriminatorColumn;
private PrimaryKeyForeignKeyMetadata m_primaryKeyForeignKey;
private List<ConvertMetadata> m_converts = new ArrayList<ConvertMetadata>();
private List<PrimaryKeyJoinColumnMetadata> m_primaryKeyJoinColumns = new ArrayList<PrimaryKeyJoinColumnMetadata>();
private List<SecondaryTableMetadata> m_secondaryTables = new ArrayList<SecondaryTableMetadata>();
private List<IndexMetadata> m_indexes = new ArrayList<IndexMetadata>();
private List<NamedEntityGraphMetadata> m_namedEntityGraphs = new ArrayList<NamedEntityGraphMetadata>();
private MetadataClass m_classExtractor;
private String m_classExtractorName;
private String m_discriminatorValue;
private String m_entityName;
private TableMetadata m_table;
/**
* INTERNAL:
*/
public EntityAccessor() {
super("<entity>");
}
/**
* INTERNAL:
*/
public EntityAccessor(MetadataAnnotation annotation, MetadataClass cls, MetadataProject project) {
super(annotation, cls, project);
}
/**
* INTERNAL:
* Add multiple fields to the descriptor. Called from either Inheritance
* or SecondaryTable context.
*/
protected void addMultipleTableKeyFields(List<PrimaryKeyJoinColumnMetadata> primaryKeyJoinColumns, DatabaseTable targetTable, String PK_CTX, String FK_CTX) {
// ProcessPrimaryKeyJoinColumns will validate the primary key join
// columns passed in and will return a list of PrimaryKeyJoinColumnMetadata.
for (PrimaryKeyJoinColumnMetadata primaryKeyJoinColumn : processPrimaryKeyJoinColumns(primaryKeyJoinColumns)) {
// Look up the primary key field from the referenced column name.
DatabaseField pkField = getReferencedField(primaryKeyJoinColumn.getReferencedColumnName(), getDescriptor(), PK_CTX);
DatabaseField fkField = primaryKeyJoinColumn.getForeignKeyField(pkField);
setFieldName(fkField, pkField.getName(), FK_CTX);
fkField.setTable(targetTable);
// Add the foreign key field to the descriptor.
getDescriptor().addForeignKeyFieldForMultipleTable(fkField, pkField);
}
}
/**
* INTERNAL:
* Build a list of classes that are decorated with a MappedSuperclass
* annotation or that are tagged as a mapped-superclass in an XML document.
*
* This method will also do a couple other things as well since we are
* traversing the parent classes:
* - Build a map of generic types specified and will be used to resolve
* actual class types for mappings.
* - Will discover and set the inheritance parent and root descriptors
* if this entity is part of an inheritance hierarchy.
* - save mapped-superclass descriptors on the project for later use
* by the Metamodel API
*
* Note: The list is rebuilt every time this method is called since
* it is called both during pre-deploy and deploy where the class loader
* dependencies change.
*/
protected void discoverMappedSuperclassesAndInheritanceParents(boolean addMappedSuperclassAccessors) {
// Clear any previous discovery.
clearMappedSuperclassesAndInheritanceParents();
EntityAccessor currentEntityAccessor = this;
MetadataClass parentClass = getJavaClass().getSuperclass();
List<String> genericTypes = getJavaClass().getGenericType();
// We keep a list of potential subclass accessors to ensure they
// have their root parent descriptor set correctly.
List<EntityAccessor> subclassEntityAccessors = new ArrayList<EntityAccessor>();
subclassEntityAccessors.add(currentEntityAccessor);
if (! parentClass.isObject()) {
while (parentClass != null && ! parentClass.isObject()) {
if (getProject().hasEntity(parentClass)) {
// Our parent is an entity.
EntityAccessor parentEntityAccessor = getProject().getEntityAccessor(parentClass);
// Set the current entity's inheritance parent descriptor.
currentEntityAccessor.getDescriptor().setInheritanceParentDescriptor(parentEntityAccessor.getDescriptor());
// Update the current entity accessor.
currentEntityAccessor = parentEntityAccessor;
// Clear out any previous mapped superclasses and inheritance
// parents that were discovered. We're going to re-discover
// them now.
currentEntityAccessor.clearMappedSuperclassesAndInheritanceParents();
// If we found an entity with inheritance metadata, set the
// root descriptor on its subclasses.
if (currentEntityAccessor.hasInheritance()) {
for (EntityAccessor subclassEntityAccessor : subclassEntityAccessors) {
subclassEntityAccessor.getDescriptor().setInheritanceRootDescriptor(currentEntityAccessor.getDescriptor());
}
// Clear the subclass list, we'll keep looking but the
// inheritance strategy may have changed so we need to
// build a new list of subclasses.
subclassEntityAccessors.clear();
}
// Add the descriptor to the subclass list
subclassEntityAccessors.add(currentEntityAccessor);
} else {
// Our parent might be a mapped superclass, check and add
// as needed.
currentEntityAccessor.addPotentialMappedSuperclass(parentClass, addMappedSuperclassAccessors);
}
// Resolve any generic types from the generic parent onto the
// current entity accessor.
currentEntityAccessor.resolveGenericTypes(genericTypes, parentClass);
// Grab the generic types from the parent class.
genericTypes = parentClass.getGenericType();
// Finally, get the next parent and keep processing ...
parentClass = parentClass.getSuperclass();
}
} else {
// Resolve any generic types we have (we may be an inheritance root).
currentEntityAccessor.resolveGenericTypes(genericTypes, parentClass);
}
// Set our root descriptor of the inheritance hierarchy on all the
// subclass descriptors. The root may not have explicit inheritance
// metadata therefore, make the current descriptor of the entity
// hierarchy the root.
if (! subclassEntityAccessors.isEmpty()) {
for (EntityAccessor subclassEntityAccessor : subclassEntityAccessors) {
if (subclassEntityAccessor != currentEntityAccessor) {
subclassEntityAccessor.getDescriptor().setInheritanceRootDescriptor(currentEntityAccessor.getDescriptor());
}
}
}
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public Boolean getCascadeOnDelete() {
return m_cascadeOnDelete;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public String getClassExtractorName() {
return m_classExtractorName;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public List<ConvertMetadata> getConverts() {
return m_converts;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public DiscriminatorColumnMetadata getDiscriminatorColumn() {
return m_discriminatorColumn;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public String getDiscriminatorValue() {
return m_discriminatorValue;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public String getEntityName() {
return m_entityName;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public List<IndexMetadata> getIndexes() {
return m_indexes;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public InheritanceMetadata getInheritance() {
return m_inheritance;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public List<NamedEntityGraphMetadata> getNamedEntityGraphs() {
return m_namedEntityGraphs;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public PrimaryKeyForeignKeyMetadata getPrimaryKeyForeignKey() {
return m_primaryKeyForeignKey;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public List<PrimaryKeyJoinColumnMetadata> getPrimaryKeyJoinColumns() {
return m_primaryKeyJoinColumns;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public List<SecondaryTableMetadata> getSecondaryTables() {
return m_secondaryTables;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public TableMetadata getTable() {
return m_table;
}
/**
* INTERNAL:
* This method is a little involved since a class extractor is mutually
* exclusive with a discriminator column.
*
* Within one xml file it is impossible to have both specified since they
* are within a choice tag. However, if one is specified in the orm.xml
* and the other in the eclipselink-orm.xml, after the merge both will be
* set on this accessor, so we need to check which came from the
* eclipselink-orm.xml because it is the one we need to use.
*/
public boolean hasClassExtractor() {
if (m_classExtractorName != null && m_discriminatorColumn != null) {
// If we have both a classExtractorName and a discriminatorColumn
// then the only way this is possible is if the user has both an
// orm.xml and an eclipselink-orm.xml and one specifies the
// discriminator column and the other specifies the class extractor.
// We must use the one from the eclipselink-orm.xml.
return ! m_discriminatorColumn.loadedFromEclipseLinkXML();
} else if (m_classExtractorName != null) {
// We have a class extractor name and we don't care where it came
// from. It must be used and override any annotations.
return true;
} else if (m_discriminatorColumn != null) {
// We have a discriminator column and we don't care where it came
// from. It must be used and override any annotations.
return false;
} else {
// Nothing was specified in XML. Must look at the annotations now.
if (isAnnotationPresent(ClassExtractor.class) && (isAnnotationPresent(JPA_DISCRIMINATOR_COLUMN) || isAnnotationPresent(JPA_DISCRIMINATOR_VALUE))) {
throw ValidationException.classExtractorCanNotBeSpecifiedWithDiscriminatorMetadata(getJavaClassName());
}
return isAnnotationPresent(ClassExtractor.class);
}
}
/**
* INTERNAL:
* Return true if this class has an inheritance specifications.
*/
public boolean hasInheritance() {
if (m_inheritance == null) {
return isAnnotationPresent(JPA_INHERITANCE);
} else {
return true;
}
}
/**
* INTERNAL:
*/
@Override
public void initXMLObject(MetadataAccessibleObject accessibleObject, XMLEntityMappings entityMappings) {
super.initXMLObject(accessibleObject, entityMappings);
// Initialize simple class objects.
m_classExtractor = initXMLClassName(m_classExtractorName);
// Initialize single objects.
initXMLObject(m_inheritance, accessibleObject);
initXMLObject(m_discriminatorColumn, accessibleObject);
initXMLObject(m_table, accessibleObject);
initXMLObject(m_primaryKeyForeignKey, accessibleObject);
// Initialize lists of ORMetadata objects.
initXMLObjects(m_secondaryTables, accessibleObject);
initXMLObjects(m_primaryKeyJoinColumns, accessibleObject);
initXMLObjects(m_indexes, accessibleObject);
initXMLObjects(m_converts, accessibleObject);
initXMLObjects(m_namedEntityGraphs, accessibleObject);
}
/**
* INTERNAL:
*/
public boolean isCascadeOnDelete() {
return (m_cascadeOnDelete == null) ? isAnnotationPresent(CascadeOnDelete.class) : m_cascadeOnDelete.booleanValue();
}
/**
* INTERNAL:
* Return true if this accessor represents an entity class.
*/
@Override
public boolean isEntityAccessor() {
return true;
}
/**
* INTERNAL:
*/
@Override
public boolean isMappedSuperclass() {
return false;
}
/**
* INTERNAL:
* Entity level merging details.
*/
@Override
public void merge(ORMetadata metadata) {
super.merge(metadata);
EntityAccessor accessor = (EntityAccessor) metadata;
// Simple object merging.
m_cascadeOnDelete = (Boolean) mergeSimpleObjects(m_cascadeOnDelete, accessor.getCascadeOnDelete(), accessor, "<cascade-on-delete>");
m_entityName = (String) mergeSimpleObjects(m_entityName, accessor.getEntityName(), accessor, "@name");
m_discriminatorValue = (String) mergeSimpleObjects(m_discriminatorValue, accessor.getDiscriminatorValue(), accessor, "<discriminator-value>");
m_classExtractorName = (String) mergeSimpleObjects(m_classExtractorName, accessor.getClassExtractorName(), accessor, "<class-extractor>");
// ORMetadata object merging.
m_discriminatorColumn = (DiscriminatorColumnMetadata) mergeORObjects(m_discriminatorColumn, accessor.getDiscriminatorColumn());
m_inheritance = (InheritanceMetadata) mergeORObjects(m_inheritance, accessor.getInheritance());
m_table = (TableMetadata) mergeORObjects(m_table, accessor.getTable());
m_primaryKeyForeignKey = (PrimaryKeyForeignKeyMetadata) mergeORObjects(m_primaryKeyForeignKey, accessor.getPrimaryKeyForeignKey());
// ORMetadata list merging.
m_secondaryTables = mergeORObjectLists(m_secondaryTables, accessor.getSecondaryTables());
m_primaryKeyJoinColumns = mergeORObjectLists(m_primaryKeyJoinColumns, accessor.getPrimaryKeyJoinColumns());
m_indexes = mergeORObjectLists(m_indexes, accessor.getIndexes());
m_converts = mergeORObjectLists(m_converts, accessor.getConverts());
m_namedEntityGraphs = mergeORObjectLists(m_namedEntityGraphs, accessor.getNamedEntityGraphs());
}
/**
* INTERNAL:
* The pre-process method is called during regular deployment and metadata
* processing and will pre-process the items of interest on an entity class.
*
* The order of processing is important, care must be taken if changes must
* be made.
*/
@Override
public void preProcess() {
// If we are not already an inheritance subclass (meaning we were not
// discovered through a subclass entity discovery) then perform the
// discovery process before processing any further. We traverse the
// chain upwards and we can not guarantee which entity will be processed
// first in an inheritance hierarchy.
if (! getDescriptor().isInheritanceSubclass()) {
discoverMappedSuperclassesAndInheritanceParents(true);
}
// If we are an inheritance subclass process out root first.
if (getDescriptor().isInheritanceSubclass()) {
// Ensure our parent accessors are processed first. Top->down.
// An inheritance subclass can no longer blindly inherit a default
// access type from the root of the inheritance hierarchy since
// that root may explicitly set an access type which applies only
// to itself. The first entity in the hierarchy (going down) that
// does not specify an explicit type will be used to determine
// the default access type.
EntityAccessor parentAccessor = (EntityAccessor) getDescriptor().getInheritanceParentDescriptor().getClassAccessor();
if (! parentAccessor.isPreProcessed()) {
parentAccessor.preProcess();
}
}
// Process the correct access type before any other processing.
processAccessType();
// Process a virtual class specification after determining access type.
processVirtualClass();
// Process the default access methods after determining access type.
processAccessMethods();
// Process a @Struct and @EIS annotation to create the correct type of descriptor.
processStruct();
processNoSql();
// Process our parents metadata after processing our own.
super.preProcess();
}
/**
* INTERNAL:
* The pre-process for canonical model method is called (and only called)
* during the canonical model generation. The use of this pre-process allows
* us to remove some items from the regular pre-process that do not apply
* to the canonical model generation.
*
* The order of processing is important, care must be taken if changes must
* be made.
*/
@Override
public void preProcessForCanonicalModel() {
setIsPreProcessed();
// If we are not already an inheritance subclass (meaning we were not
// discovered through a subclass entity discovery) then perform
// the discovery process before processing any further. We traverse
// the chain upwards and we can not guarantee which entity will be
// processed first in an inheritance hierarchy.
if (! getDescriptor().isInheritanceSubclass()) {
discoverMappedSuperclassesAndInheritanceParents(false);
}
// If we are an inheritance subclass process out root first.
if (getDescriptor().isInheritanceSubclass()) {
// Ensure our parent accessors are processed first. Top->down.
// An inheritance subclass can no longer blindly inherit a default
// access type from the root of the inheritance hierarchy since
// that root may explicitly set an access type which applies only
// to itself. The first entity in the hierarchy (going down) that
// does not specify an explicit type will be used to determine
// the default access type.
EntityAccessor parentAccessor = (EntityAccessor) getDescriptor().getInheritanceParentDescriptor().getClassAccessor();
if (! parentAccessor.isPreProcessed()) {
parentAccessor.preProcessForCanonicalModel();
}
}
// Process our parents metadata after processing our own.
super.preProcessForCanonicalModel();
}
/**
* INTERNAL:
* Process the items of interest on an entity class. The order of processing
* is important, care must be taken if changes must be made.
*/
@Override
public void process() {
// Process the entity annotation.
processEntity();
// If we are an inheritance subclass process our root first.
if (getDescriptor().isInheritanceSubclass()) {
ClassAccessor parentAccessor = getDescriptor().getInheritanceParentDescriptor().getClassAccessor();
if (! parentAccessor.isProcessed()) {
parentAccessor.process();
}
}
// Process the Table and Inheritance metadata.
processTableAndInheritance();
// Process the indices metadata.
processIndexes();
// Process the cascade on delete metadata.
processCascadeOnDelete();
// Process the JPA converts metadata.
processConverts();
// Process our parents metadata after processing our own.
super.process();
// Finally, process the mapping accessors on this entity (and all those
// from super classes that apply to us).
processMappingAccessors();
// Process the entity graph metadata.
processEntityGraphs();
}
/**
* INTERNAL:
* For VIRTUAL access we need to look for default access methods that we
* need to use with our mapping attributes.
*/
public void processAccessMethods() {
// If we use virtual access and do not have any access methods
// specified then go look for access methods on a mapped superclass
// or inheritance parent.
if (hasAccessMethods()) {
getDescriptor().setDefaultAccessMethods(getAccessMethods());
} else {
MetadataAnnotation virtualAccessMethods = getAnnotation(VirtualAccessMethods.class);
if (virtualAccessMethods != null){
getDescriptor().setDefaultAccessMethods(new AccessMethodsMetadata(virtualAccessMethods, this));
return;
}
// Go through the mapped superclasses.
for (MappedSuperclassAccessor mappedSuperclass : getMappedSuperclasses()) {
if (mappedSuperclass.hasAccessMethods()) {
getDescriptor().setDefaultAccessMethods(mappedSuperclass.getAccessMethods());
return;
}
virtualAccessMethods = mappedSuperclass.getAnnotation(VirtualAccessMethods.class);
if (virtualAccessMethods != null){
getDescriptor().setDefaultAccessMethods(new AccessMethodsMetadata(virtualAccessMethods, this));
return;
}
}
// Go through the inheritance parents.
if (getDescriptor().isInheritanceSubclass()) {
MetadataDescriptor parentDescriptor = getDescriptor().getInheritanceParentDescriptor();
while (parentDescriptor.isInheritanceSubclass()) {
if (parentDescriptor.getClassAccessor().hasAccessMethods()) {
getDescriptor().setDefaultAccessMethods(parentDescriptor.getClassAccessor().getAccessMethods());
return;
}
virtualAccessMethods = parentDescriptor.getClassAccessor().getAnnotation(VirtualAccessMethods.class);
if (virtualAccessMethods != null){
getDescriptor().setDefaultAccessMethods(new AccessMethodsMetadata(virtualAccessMethods, this));
return;
}
parentDescriptor = parentDescriptor.getInheritanceParentDescriptor();
}
}
}
}
/**
* INTERNAL:
* Figure out the access type for this entity. It works as follows:
* 1 - check for an explicit access type specification
* 2 - check our inheritance parents (ignoring explicit specifications)
* 3 - check our mapped superclasses (ignoring explicit specifications) for
* the location of annotations
* 4 - check the entity itself for the location of annotations
* 5 - check for an xml default from a persistence-unit-metadata-defaults or
* entity-mappings setting.
* 6 - we have exhausted our search, default to FIELD.
*/
@Override
public void processAccessType() {
// This function has been overridden in the MappedSuperclassAccessor
// parent. Do not call this superclass method.
// Step 1 - Check for an explicit setting.
String explicitAccessType = getAccess();
// Step 2, regardless if there is an explicit access type we still
// want to determine the default access type for this entity since
// any embeddable, mapped superclass or id class that depends on it
// will have it available.
String defaultAccessType = null;
// 1 - Check the access types from our parents if we are an inheritance
// sub-class. Inheritance hierarchies are processed top->down so our
// first parent that does not define an explicit access type will have
// the type we would want to default to.
if (getDescriptor().isInheritanceSubclass()) {
MetadataDescriptor parent = getDescriptor().getInheritanceParentDescriptor();
while (parent != null) {
if (! parent.getClassAccessor().hasAccess()) {
defaultAccessType = parent.getDefaultAccess();
break;
}
parent = parent.getInheritanceParentDescriptor();
}
}
// 2 - If there is no inheritance or no inheritance parent that does not
// explicitly define an access type. Let's check this entities mapped
// superclasses now.
if (defaultAccessType == null) {
for (MappedSuperclassAccessor mappedSuperclass : getMappedSuperclasses()) {
if (! mappedSuperclass.hasAccess()) {
if (mappedSuperclass.hasObjectRelationalFieldMappingAnnotationsDefined()) {
defaultAccessType = JPA_ACCESS_FIELD;
} else if (mappedSuperclass.hasObjectRelationalMethodMappingAnnotationsDefined()) {
defaultAccessType = JPA_ACCESS_PROPERTY;
}
break;
}
}
// 3 - If there are no mapped superclasses or no mapped superclasses
// without an explicit access type. Check where the annotations are
// defined on this entity class.
if (defaultAccessType == null) {
if (hasObjectRelationalFieldMappingAnnotationsDefined()) {
defaultAccessType = JPA_ACCESS_FIELD;
} else if (hasObjectRelationalMethodMappingAnnotationsDefined()) {
defaultAccessType = JPA_ACCESS_PROPERTY;
} else {
// 4 - If there are no annotations defined on either the
// fields or properties, check for an xml default from
// persistence-unit-metadata-defaults or entity-mappings.
if (getDescriptor().getDefaultAccess() != null) {
defaultAccessType = getDescriptor().getDefaultAccess();
} else {
// 5 - We've exhausted our search, set the access type
// to FIELD.
defaultAccessType = JPA_ACCESS_FIELD;
}
}
}
}
// Finally set the default access type on the descriptor and log a
// message to the user if we are defaulting the access type for this
// entity to use that default.
getDescriptor().setDefaultAccess(defaultAccessType);
if (explicitAccessType == null) {
getLogger().logConfigMessage(MetadataLogger.ACCESS_TYPE, defaultAccessType, getJavaClass());
}
// This access type setting on the class descriptor will be used to
// weave the class properly.
getDescriptor().setAccessTypeOnClassDescriptor(getAccessType());
}
/**
* INTERNAL:
* Process a caching metadata for this entity accessor logging ignore
* warnings where necessary.
*/
@Override
protected void processCaching() {
if (getProject().isSharedCacheModeAll()) {
if (getDescriptor().isCacheableFalse()) {
// The persistence unit has an ALL caching type and the user
// specified Cacheable(false). Log a warning message that it is
// being ignored. If Cacheable(true) was specified then it is
// redundant and we just carry on.
getLogger().logConfigMessage(MetadataLogger.IGNORE_CACHEABLE_FALSE, getJavaClass());
}
// Process the cache metadata.
processCachingMetadata();
} else if (getProject().isSharedCacheModeNone()) {
if (getDescriptor().isCacheableTrue()) {
// The persistence unit has a NONE caching type and the the user
// specified Cacheable(true). Log a warning message that it is being
// ignored. If Cacheable(false) was specified then it is redundant
// and we just carry on.
getLogger().logConfigMessage(MetadataLogger.IGNORE_CACHEABLE_TRUE, getJavaClass());
}
// Turn off the cache.
getDescriptor().useNoCache();
} else if (getProject().isSharedCacheModeEnableSelective()) {
if (!getDescriptor().isCacheableTrue()) {
// ENABLE_SELECTIVE and Cacheable(false) or no setting, turn off the cache.
getDescriptor().useNoCache();
}
// Cacheable annotation in current class can override default or inherited settings.
getDescriptor().setCacheableInDescriptor();
// ENABLE_SELECTIVE and Cacheable(true), process the cache metadata.
processCachingMetadata();
} else if (getProject().isSharedCacheModeDisableSelective() || getProject().isSharedCacheModeUnspecified()) {
if (getDescriptor().isCacheableFalse()) {
// DISABLE_SELECTIVE and Cacheable(false), turn off cache.
getDescriptor().useNoCache();
}
// Cacheable annotation in current class can override default or inherited settings.
getDescriptor().setCacheableInDescriptor();
// DISABLE_SELECTIVE and Cacheable(true) or no setting, process the cache metadata.
processCachingMetadata();
}
}
/**
* INTERNAL:
* Check if CascadeOnDelete was set on the Entity.
*/
protected void processCascadeOnDelete() {
getDescriptor().getClassDescriptor().setIsCascadeOnDeleteSetOnDatabaseOnSecondaryTables(isCascadeOnDelete());
}
/**
* INTERNAL:
* Return the user defined class extractor class for this entity. Assumes
* hasClassExtractor has been called beforehand (meaning we either have
* an annotation or XML definition.
*/
public String processClassExtractor() {
MetadataAnnotation classExtractor = getAnnotation(ClassExtractor.class);
if (m_classExtractor == null) {
m_classExtractor = getMetadataClass(classExtractor.getAttributeString("value"));
} else {
getLogger().logConfigMessage(MetadataLogger.OVERRIDE_ANNOTATION_WITH_XML, classExtractor, getJavaClassName(), getLocation());
}
return m_classExtractor.getName();
}
/**
* INTERNAL:
* Add a convert metadata to the descriptor convert map.
*/
public void processConvert(ConvertMetadata convert) {
if (convert.hasAttributeName()) {
if (convert.getAttributeName().indexOf(".") > -1) {
// We have a dot notation name.
String dotNotationName = convert.getAttributeName();
int dotIndex = dotNotationName.indexOf(".");
String attributeName = dotNotationName.substring(0, dotIndex);
String remainder = dotNotationName.substring(dotIndex + 1);
// Update the convert attribute name for correct convert processing.
convert.setAttributeName(remainder);
getDescriptor().addConvert(attributeName, convert);
} else {
// Simple single name.
String attributeName = convert.getAttributeName();
convert.setAttributeName("");
getDescriptor().addConvert(attributeName, convert);
}
} else {
throw ValidationException.missingConvertAttributeName(getJavaClassName());
}
}
/**
* INTERNAL:
* Process the convert metadata for this entity accessor logging ignore
* warnings where necessary.
*/
public void processConverts() {
if (m_converts.isEmpty()) {
// Look for a Converts annotation.
if (isAnnotationPresent(JPA_CONVERTS)) {
for (Object convert : (Object[]) getAnnotation(JPA_CONVERTS).getAttributeArray("value")) {
processConvert(new ConvertMetadata((MetadataAnnotation) convert, this));
}
} else {
// Look for a Convert annotation
if (isAnnotationPresent(JPA_CONVERT)) {
processConvert(new ConvertMetadata(getAnnotation(JPA_CONVERT), this));
}
}
} else {
if (isAnnotationPresent(JPA_CONVERT)) {
getLogger().logConfigMessage(MetadataLogger.OVERRIDE_ANNOTATION_WITH_XML, getAnnotation(JPA_CONVERT), getJavaClassName(), getLocation());
}
if (isAnnotationPresent(JPA_CONVERTS)) {
getLogger().logConfigMessage(MetadataLogger.OVERRIDE_ANNOTATION_WITH_XML, getAnnotation(JPA_CONVERTS), getJavaClassName(), getLocation());
}
for (ConvertMetadata convert : m_converts) {
processConvert(convert);
}
}
}
/**
* INTERNAL:
* Allows for processing DerivedIds. All referenced accessors are processed
* first to ensure the necessary fields are set before this derivedId is processed
*/
@Override
public void processDerivedId(HashSet<ClassAccessor> processing, HashSet<ClassAccessor> processed) {
if (! processed.contains(this)) {
super.processDerivedId(processing, processed);
// Validate we found a primary key.
validatePrimaryKey();
// Primary key has been validated, let's process those items that
// depend on it now.
// Process the SecondaryTable(s) metadata.
processSecondaryTables();
}
}
/**
* INTERNAL:
* Process the discriminator column metadata (defaulting if necessary),
* and return the EclipseLink database field.
*/
public DatabaseField processDiscriminatorColumn() {
MetadataAnnotation discriminatorColumn = getAnnotation(JPA_DISCRIMINATOR_COLUMN);
if (m_discriminatorColumn == null) {
m_discriminatorColumn = new DiscriminatorColumnMetadata(discriminatorColumn, this);
} else {
if (isAnnotationPresent(JPA_DISCRIMINATOR_COLUMN)) {
getLogger().logConfigMessage(MetadataLogger.OVERRIDE_ANNOTATION_WITH_XML, discriminatorColumn, getJavaClassName(), getLocation());
}
}
return m_discriminatorColumn.process(getDescriptor(), MetadataLogger.INHERITANCE_DISCRIMINATOR_COLUMN);
}
/**
* INTERNAL:
* Process a discriminator value to set the class indicator on the root
* descriptor of the inheritance hierarchy.
*
* If there is no discriminator value, the class indicator defaults to
* the class name.
*/
public String processDiscriminatorValue() {
if (! Modifier.isAbstract(getJavaClass().getModifiers())) {
// Add the indicator to the inheritance root class' descriptor. The
// default is the short class name.
if (m_discriminatorValue == null) {
MetadataAnnotation discriminatorValue = getAnnotation(JPA_DISCRIMINATOR_VALUE);
if (discriminatorValue == null) {
// By default return the alias (i.e. entity name if provided
// otherwise the short java class name)
return getDescriptor().getAlias();
} else {
return discriminatorValue.getAttributeString("value");
}
} else {
return m_discriminatorValue;
}
}
return null;
}
/**
* INTERNAL:
* Process the entity metadata.
*/
protected void processEntity() {
// Process the entity name (alias) and default if necessary.
if (m_entityName == null) {
m_entityName = (getAnnotation(JPA_ENTITY) == null) ? "" : getAnnotation(JPA_ENTITY).getAttributeString("name");
}
if (m_entityName == null || m_entityName.equals("")) {
m_entityName = Helper.getShortClassName(getJavaClassName());
getLogger().logConfigMessage(MetadataLogger.ALIAS, getDescriptor(), m_entityName);
}
getProject().addAlias(m_entityName, getDescriptor());
}
/**
* INTERNAL:
* Process the entity graph metadata on this entity accessor.
*/
protected void processEntityGraphs() {
if (m_namedEntityGraphs.isEmpty()) {
// Look for an NamedEntityGraphs annotation.
if (isAnnotationPresent(JPA_ENTITY_GRAPHS)) {
for (Object entityGraph : (Object[]) getAnnotation(JPA_ENTITY_GRAPHS).getAttributeArray("value")) {
new NamedEntityGraphMetadata((MetadataAnnotation) entityGraph, this).process(this);
}
} else {
// Look for a NamedEntityGraph annotation
if (isAnnotationPresent(JPA_ENTITY_GRAPH)) {
new NamedEntityGraphMetadata(getAnnotation(JPA_ENTITY_GRAPH), this).process(this);
}
}
} else {
// Process the named entity graphs from XML.
if (isAnnotationPresent(JPA_ENTITY_GRAPH)) {
getLogger().logConfigMessage(MetadataLogger.OVERRIDE_ANNOTATION_WITH_XML, getAnnotation(JPA_ENTITY_GRAPH), getJavaClassName(), getLocation());
}
if (isAnnotationPresent(JPA_ENTITY_GRAPHS)) {
getLogger().logConfigMessage(MetadataLogger.OVERRIDE_ANNOTATION_WITH_XML, getAnnotation(JPA_ENTITY_GRAPHS), getJavaClassName(), getLocation());
}
for (NamedEntityGraphMetadata entityGraph : m_namedEntityGraphs) {
entityGraph.process(this);
}
}
}
/**
* INTERNAL:
* Process index information for the given metadata descriptor.
*/
protected void processIndexes() {
// TODO: This method is adding annotation metadata to XML metadata. This
// is wrong and does not follow the spec ideology. XML metadata should
// override not merge with annotations.
if (isAnnotationPresent(Index.class)) {
m_indexes.add(new IndexMetadata(getAnnotation(Index.class), this));
}
if (isAnnotationPresent(Indexes.class)) {
for (Object index : getAnnotation(Indexes.class).getAttributeArray("value")) {
m_indexes.add(new IndexMetadata((MetadataAnnotation) index, this));
}
}
for (IndexMetadata indexMetadata : m_indexes) {
indexMetadata.process(getDescriptor(), null);
}
}
/**
* INTERNAL:
* Process the Inheritance metadata for a root of an inheritance
* hierarchy. One may or may not be specified for the entity class that is
* the root of the entity class hierarchy, so we need to default in this
* case. This method should only be called on the root of the inheritance
* hierarchy.
*/
protected void processInheritance() {
// Process the inheritance metadata first. Create one if one does not
// exist.
if (m_inheritance == null) {
m_inheritance = new InheritanceMetadata(getAnnotation(JPA_INHERITANCE), this);
}
m_inheritance.process(getDescriptor());
}
/**
* INTERNAL:
* Process the inheritance metadata for an inheritance subclass. The
* parent descriptor must be provided.
*/
public void processInheritancePrimaryKeyJoinColumns() {
// If there are no primary key join columns specified in XML, look for
// some defined through annotations.
if (m_primaryKeyJoinColumns.isEmpty()) {
// Process all the primary key join columns first.
if (isAnnotationPresent(JPA_PRIMARY_KEY_JOIN_COLUMNS)) {
MetadataAnnotation primaryKeyJoinColumns = getAnnotation(JPA_PRIMARY_KEY_JOIN_COLUMNS);
for (Object primaryKeyJoinColumn : primaryKeyJoinColumns.getAttributeArray("value")) {
m_primaryKeyJoinColumns.add(new PrimaryKeyJoinColumnMetadata((MetadataAnnotation) primaryKeyJoinColumn, this));
}
// Set the primary key foreign key metadata if one is specified.
if (primaryKeyJoinColumns.hasAttribute("foreignKey")) {
setPrimaryKeyForeignKey(new PrimaryKeyForeignKeyMetadata(primaryKeyJoinColumns.getAttributeAnnotation("foreignKey"), this));
}
}
// Process the single primary key join column second.
if (isAnnotationPresent(JPA_PRIMARY_KEY_JOIN_COLUMN)) {
PrimaryKeyJoinColumnMetadata primaryKeyJoinColumn = new PrimaryKeyJoinColumnMetadata(getAnnotation(JPA_PRIMARY_KEY_JOIN_COLUMN), this);
m_primaryKeyJoinColumns.add(primaryKeyJoinColumn);
// Set the primary key foreign key metadata if specified.
if (primaryKeyJoinColumn.hasForeignKey()) {
setPrimaryKeyForeignKey(new PrimaryKeyForeignKeyMetadata(primaryKeyJoinColumn.getForeignKey()));
}
}
}
// Process the primary key join columns into multiple table key fields.
addMultipleTableKeyFields(m_primaryKeyJoinColumns, getDescriptor().getPrimaryTable(), MetadataLogger.INHERITANCE_PK_COLUMN, MetadataLogger.INHERITANCE_FK_COLUMN);
// Process the primary key foreign key.
if (m_primaryKeyForeignKey != null) {
m_primaryKeyForeignKey.process(getDescriptor().getPrimaryTable());
}
}
/**
* INTERNAL:
* Process the listeners for this entity.
*/
public void processListeners(ClassLoader loader) {
// Step 1 - process the default listeners that were defined in XML.
// Default listeners process the class for additional lifecycle
// callback methods that are decorated with annotations.
// NOTE: We add the default listeners regardless if the exclude default
// listeners flag is set. This allows the user to change the exclude
// flag at runtime and have the default listeners available to them.
for (EntityListenerMetadata defaultListener : getProject().getDefaultListeners()) {
// We need to clone the default listeners. Can't re-use the
// same one for all the entities in the persistence unit.
((EntityListenerMetadata) defaultListener.clone()).process(this, loader, true);
}
// Step 2 - process the entity listeners that are defined on the entity
// class and mapped superclasses (taking metadata-complete into
// consideration). Go through the mapped superclasses first, top->down
// only if the exclude superclass listeners flag is not set.
discoverMappedSuperclassesAndInheritanceParents(true);
if (! getDescriptor().excludeSuperclassListeners()) {
int mappedSuperclassesSize = getMappedSuperclasses().size();
for (int i = mappedSuperclassesSize - 1; i >= 0; i--) {
getMappedSuperclasses().get(i).processEntityListeners(loader);
}
}
processEntityListeners(loader);
// Step 3 - process the entity class for lifecycle callback methods. Go
// through the mapped superclasses as well.
new EntityClassListenerMetadata(this).process(getMappedSuperclasses(), loader);
}
/**
* INTERNAL:
* Process the accessors for the given class.
* If we are within a TABLE_PER_CLASS inheritance hierarchy, our parent
* accessors will already have been added at this point.
* @see InheritanceMetadata process()
*/
@Override
public void processMappingAccessors() {
// Process our mapping accessors, and then perform the necessary
// validation checks for this entity.
super.processMappingAccessors();
// Validate the optimistic locking setting.
validateOptimisticLocking();
// Check that we have a simple pk. If it is a derived id, this will be
// run in a second pass
if (! hasDerivedId()){
// Validate we found a primary key.
validatePrimaryKey();
// Primary key has been validated, let's process those items that
// depend on it now.
// Process the SecondaryTable(s) metadata.
processSecondaryTables();
}
}
/**
* INTERNAL:
* Process a MetadataSecondaryTable. Do all the table name defaulting and
* set the correct, fully qualified name on the TopLink DatabaseTable.
*/
protected void processSecondaryTable(SecondaryTableMetadata secondaryTable) {
// Process any table defaults and log warning messages.
processTable(secondaryTable, secondaryTable.getName());
// Add the table to the descriptor.
getDescriptor().addTable(secondaryTable.getDatabaseTable());
// Get the primary key join column(s) and add the multiple table key fields.
addMultipleTableKeyFields(secondaryTable.getPrimaryKeyJoinColumns(), secondaryTable.getDatabaseTable(), MetadataLogger.SECONDARY_TABLE_PK_COLUMN, MetadataLogger.SECONDARY_TABLE_FK_COLUMN);
}
/**
* INTERNAL:
* Process secondary-table(s) for a given entity.
*/
protected void processSecondaryTables() {
// Ignore secondary tables when the descriptor is an EIS descriptor.
if (! getDescriptor().getClassDescriptor().isEISDescriptor()) {
MetadataAnnotation secondaryTable = getAnnotation(JPA_SECONDARY_TABLE);
MetadataAnnotation secondaryTables = getAnnotation(JPA_SECONDARY_TABLES);
if (m_secondaryTables.isEmpty()) {
// Look for a SecondaryTables annotation.
if (secondaryTables != null) {
for (Object table : secondaryTables.getAttributeArray("value")) {
processSecondaryTable(new SecondaryTableMetadata((MetadataAnnotation)table, this));
}
} else {
// Look for a SecondaryTable annotation
if (secondaryTable != null) {
processSecondaryTable(new SecondaryTableMetadata(secondaryTable, this));
}
}
} else {
if (secondaryTable != null) {
getLogger().logConfigMessage(MetadataLogger.OVERRIDE_ANNOTATION_WITH_XML, secondaryTable, getJavaClassName(), getLocation());
}
if (secondaryTables != null) {
getLogger().logConfigMessage(MetadataLogger.OVERRIDE_ANNOTATION_WITH_XML, secondaryTables, getJavaClassName(), getLocation());
}
for (SecondaryTableMetadata table : m_secondaryTables) {
processSecondaryTable(table);
}
}
}
}
/**
* INTERNAL:
* Process table information for the given metadata descriptor.
*/
protected void processTable() {
MetadataAnnotation table = getAnnotation(JPA_TABLE);
if (m_table == null) {
// Check for a table annotation. If no annotation is defined, the
// table will default.
processTable(new TableMetadata(table, this));
} else {
if (table != null) {
getLogger().logConfigMessage(MetadataLogger.OVERRIDE_ANNOTATION_WITH_XML, table, getJavaClassName(), getLocation());
}
processTable(m_table);
}
}
/**
* INTERNAL:
* Process a MetadataTable. Do all the table name defaulting and set the
* correct, fully qualified name on the TopLink DatabaseTable.
*/
protected void processTable(TableMetadata table) {
// Ignore secondary tables when the descriptor is an EIS descriptor.
if (! getDescriptor().getClassDescriptor().isEISDescriptor()) {
// Process any table defaults and log warning messages.
processTable(table, getDescriptor().getDefaultTableName());
// Set the table on the descriptor.
getDescriptor().setPrimaryTable(table.getDatabaseTable());
}
}
/**
* INTERNAL:
* Process any inheritance specifics. NOTE: Inheritance hierarchies are
* always processed from the top down so it is safe to assume that all
* our parents have already been processed fully. The only exception being
* when a root accessor doesn't know they are a root (defaulting case). In
* this case we'll tell the root accessor to process the inheritance
* metadata before continuing with our own processing.
*/
protected void processTableAndInheritance() {
// If we are an inheritance subclass, ensure our root is processed
// first since it has information its subclasses depend on.
if (getDescriptor().isInheritanceSubclass()) {
MetadataDescriptor rootDescriptor = getDescriptor().getInheritanceRootDescriptor();
EntityAccessor rootAccessor = (EntityAccessor) rootDescriptor.getClassAccessor();
// An entity who didn't know they were the root of an inheritance
// hierarchy (that is, does not define inheritance metadata) must
// process and default the inheritance metadata.
if (! rootAccessor.hasInheritance()) {
rootAccessor.processInheritance();
}
// Process the table metadata for this descriptor if either there
// is an inheritance specification (we're a new root) or if we are
// part of a joined or table per class inheritance strategy.
if (hasInheritance() || ! rootDescriptor.usesSingleTableInheritanceStrategy()) {
processTable();
}
// If this entity has inheritance metadata as well, then the
// inheritance strategy is mixed and we need to process the
// inheritance metadata to ensure this entity's subclasses process
// correctly.
if (hasInheritance()) {
// Process the inheritance metadata.
processInheritance();
} else {
// Process the inheritance details using the inheritance
// metadata from our parent. This will put the right
// inheritance policy on our descriptor.
rootAccessor.getInheritance().process(getDescriptor());
}
} else {
// Process the table metadata if there is some, otherwise default.
processTable();
// If we have inheritance metadata, then process it now. If we are
// an inheritance root class that doesn't know it, a subclass will
// force this processing to occur.
if (hasInheritance()) {
processInheritance();
}
}
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public void setCascadeOnDelete(Boolean cascadeOnDelete) {
m_cascadeOnDelete = cascadeOnDelete;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public void setClassExtractorName(String classExtractorName) {
m_classExtractorName = classExtractorName;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public void setConverts(List<ConvertMetadata> converts) {
m_converts = converts;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public void setDiscriminatorColumn(DiscriminatorColumnMetadata discriminatorColumn) {
m_discriminatorColumn = discriminatorColumn;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public void setDiscriminatorValue(String discriminatorValue) {
m_discriminatorValue = discriminatorValue;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public void setEntityName(String entityName) {
m_entityName = entityName;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public void setIndexes(List<IndexMetadata> indexes) {
m_indexes = indexes;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public void setInheritance(InheritanceMetadata inheritance) {
m_inheritance = inheritance;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public void setNamedEntityGraphs(List<NamedEntityGraphMetadata> namedEntityGraphs) {
m_namedEntityGraphs = namedEntityGraphs;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public void setPrimaryKeyForeignKey(PrimaryKeyForeignKeyMetadata primaryKeyForeignKey) {
m_primaryKeyForeignKey = primaryKeyForeignKey;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public void setPrimaryKeyJoinColumns(List<PrimaryKeyJoinColumnMetadata> primaryKeyJoinColumns) {
m_primaryKeyJoinColumns = primaryKeyJoinColumns;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public void setSecondaryTables(List<SecondaryTableMetadata> secondaryTables) {
m_secondaryTables = secondaryTables;
}
/**
* INTERNAL:
* Used for OX mapping.
*/
public void setTable(TableMetadata table) {
m_table = table;
}
/**
* INTERNAL:
* Validate a OptimisticLocking(type=VERSION_COLUMN) setting. That is,
* validate that we found a version field. If not, throw an exception.
*/
protected void validateOptimisticLocking() {
if (getDescriptor().usesVersionColumnOptimisticLocking() && ! getDescriptor().usesOptimisticLocking()) {
throw ValidationException.optimisticLockingVersionElementNotSpecified(getJavaClass());
}
}
/**
* INTERNAL:
* Call this method after a primary key should have been found.
*/
protected void validatePrimaryKey() {
// If this descriptor has a composite primary key, check that all
// our composite primary key attributes were validated.
if (getDescriptor().hasCompositePrimaryKey()) {
if (getDescriptor().pkClassWasNotValidated()) {
throw ValidationException.invalidCompositePKSpecification(getJavaClass(), getDescriptor().getPKClassName());
}
// Log a warning to the user that they have specified multiple id
// fields without an id class specification. If they are using a
// @PrimaryKey specification don't issue the warning.
if (! getDescriptor().hasPKClass() && ! getDescriptor().hasPrimaryKey()) {
getLogger().logWarningMessage(MetadataLogger.MULTIPLE_ID_FIELDS_WITHOUT_ID_CLASS, getJavaClassName());
}
} else {
// Descriptor has a single primary key. Validate an id attribute was
// found, unless we are an inheritance subclass or an aggregate descriptor.
if (! getDescriptor().hasPrimaryKeyFields() && ! getDescriptor().isInheritanceSubclass()) {
throw ValidationException.noPrimaryKeyAnnotationsFound(getJavaClass());
}
}
}
}
| epl-1.0 |
trylimits/Eclipse-Postfix-Code-Completion | luna/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/IProposableFix.java | 1652 | /*******************************************************************************
* Copyright (c) 2007, 2008 IBM Corporation 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
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.corext.fix;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jdt.ui.cleanup.ICleanUpFix;
/**
* A <code>ICleanUpFix</code> which can be used in a
* correction proposal environment. A proposal
* will be shown to the user and if chosen the
* fix is executed.
*
* @since 3.4
*/
public interface IProposableFix extends ICleanUpFix {
/**
* Returns the string to be displayed in the list of completion proposals.
*
* @return the string to be displayed
*/
public String getDisplayString();
/**
* Returns optional additional information about the proposal. The additional information will
* be presented to assist the user in deciding if the selected proposal is the desired choice.
* <p>
* Returns <b>null</b> if the default proposal info should be used.
* </p>
*
* @return the additional information or <code>null</code>
*/
public String getAdditionalProposalInfo();
/**
* A status informing about issues with this fix
* or <b>null</b> if no issues.
*
* @return status to inform the user
*/
public IStatus getStatus();
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | utils/eclipselink.utils.workbench/mappingsplugin/source/org/eclipse/persistence/tools/workbench/mappingsplugin/ui/mapping/relational/RelationalFieldTransformerAssociationsPanel.java | 4230 | /*******************************************************************************
* 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.mappingsplugin.ui.mapping.relational;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import org.eclipse.persistence.tools.workbench.framework.context.WorkbenchContext;
import org.eclipse.persistence.tools.workbench.framework.context.WorkbenchContextHolder;
import org.eclipse.persistence.tools.workbench.mappingsmodel.mapping.relational.MWRelationalFieldTransformerAssociation;
import org.eclipse.persistence.tools.workbench.mappingsmodel.mapping.relational.MWRelationalTransformationMapping;
import org.eclipse.persistence.tools.workbench.mappingsplugin.ui.mapping.FieldTransformerAssociationsPanel;
import org.eclipse.persistence.tools.workbench.mappingsplugin.ui.mapping.TransformerEditingDialog;
import org.eclipse.persistence.tools.workbench.uitools.app.ValueModel;
final class RelationalFieldTransformerAssociationsPanel
extends FieldTransformerAssociationsPanel
{
// **************** Constructors ******************************************
/** Expects a MWRelationalTransformationMapping object */
public RelationalFieldTransformerAssociationsPanel(ValueModel transformationMappingHolder, WorkbenchContextHolder contextHolder) {
super(transformationMappingHolder, contextHolder);
}
// **************** Initialization ****************************************
protected ActionListener buildAddFieldTransformerAssociationAction() {
return new AbstractAction() {
public void actionPerformed(ActionEvent e) {
MWRelationalTransformationMapping transformationMapping =
(MWRelationalTransformationMapping) RelationalFieldTransformerAssociationsPanel.this.getSubjectHolder().getValue();
WorkbenchContext context = RelationalFieldTransformerAssociationsPanel.this.getWorkbenchContext();
if (transformationMapping.parentDescriptorIsAggregate()) {
TransformerEditingDialog.promptToAddFieldTransformerAssociationForAggregate(transformationMapping, context);
}
else {
RelationalFieldTransformerAssociationEditingDialog.promptToAddFieldTransformerAssociation(transformationMapping, context);
}
}
};
}
protected ActionListener buildEditFieldTransformerAssociationAction() {
return new AbstractAction() {
public void actionPerformed(ActionEvent e) {
MWRelationalTransformationMapping transformationMapping =
(MWRelationalTransformationMapping) RelationalFieldTransformerAssociationsPanel.this.getSubjectHolder().getValue();
MWRelationalFieldTransformerAssociation association =
(MWRelationalFieldTransformerAssociation) RelationalFieldTransformerAssociationsPanel.this.selectedFieldTransformerAssociation();
WorkbenchContext context =
RelationalFieldTransformerAssociationsPanel.this.getWorkbenchContext();
if (transformationMapping.parentDescriptorIsAggregate()) {
TransformerEditingDialog.promptToEditFieldTransformerAssociationForAggregate(association, context);
}
else {
RelationalFieldTransformerAssociationEditingDialog.promptToEditFieldTransformerAssociation(association, context);
}
}
};
}
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | foundation/eclipselink.extension.oracle.test/src/org/eclipse/persistence/testing/tests/ucp/UCPCallbackUnitOfWorkTests.java | 3329 | /*******************************************************************************
* Copyright (c) 2010, 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:
* James Sutherland - initial API and implementation
******************************************************************************/
package org.eclipse.persistence.testing.tests.ucp;
import java.sql.SQLException;
import oracle.ucp.jdbc.PoolDataSource;
import oracle.ucp.jdbc.PoolDataSourceFactory;
import org.eclipse.persistence.descriptors.partitioning.RoundRobinPartitioningPolicy;
import org.eclipse.persistence.platform.database.oracle.ucp.UCPDataPartitioningCallback;
import org.eclipse.persistence.sessions.JNDIConnector;
import org.eclipse.persistence.sessions.Project;
import org.eclipse.persistence.sessions.server.Server;
import org.eclipse.persistence.testing.framework.TestErrorException;
import org.eclipse.persistence.testing.tests.unitofwork.UnitOfWorkClientSessionTestModel;
/**
* This model is used to test Oracle UCP.
* To test a RAC, URL should be a composite like:
* "@(DESCRIPTION=(LOAD_BALANCE=on) (ADDRESS=(PROTOCOL=TCP)(HOST=host1) (PORT=1521)) (ADDRESS=(PROTOCOL=TCP)(HOST=host2) (PORT=1521)) (CONNECT_DATA=(SERVICE_NAME=service)))"
*
*/
public class UCPCallbackUnitOfWorkTests extends UnitOfWorkClientSessionTestModel {
@Override
public Server buildServerSession() {
try {
PoolDataSourceFactory factory = new oracle.ucp.jdbc.PoolDataSourceFactory();
PoolDataSource dataSource = factory.getPoolDataSource();
//dataSource.setONSConfiguration("nodes=adcdbc01-r.us.oracle.com:6200");
dataSource.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource");
dataSource.setURL(getSession().getLogin().getConnectionString());
dataSource.setUser(getSession().getLogin().getUserName());
dataSource.setPassword(getSession().getLogin().getPassword());
dataSource.setInitialPoolSize(5);
dataSource.setMinPoolSize(5);
dataSource.setMaxPoolSize(10);
dataSource.setFastConnectionFailoverEnabled(true);
Project project = getSession().getProject().clone();
project.setLogin(project.getLogin().clone());
project.getLogin().setConnector(new JNDIConnector(dataSource));
project.getLogin().setUsesExternalConnectionPooling(true);
project.getLogin().setPartitioningCallback(new UCPDataPartitioningCallback());
Server server = project.createServerSession();
server.setPartitioningPolicy(new RoundRobinPartitioningPolicy("node1", "node2"));
server.setSessionLog(getSession().getSessionLog());
server.login();
return server;
} catch (SQLException error) {
throw new TestErrorException("UCP failed to initialize.", error);
}
}
}
| epl-1.0 |
slemeur/che | plugins/plugin-orion/che-plugin-orion-editor/src/main/java/org/eclipse/che/ide/requirejs/config/ConfigItem.java | 819 | /*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.requirejs.config;
import com.google.gwt.core.client.JavaScriptObject;
public class ConfigItem extends AssocitativeJsObject<JavaScriptObject> {
protected ConfigItem() {
}
public static final native ConfigItem create() /*-{
return {};
}-*/;
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/models/jpa/advanced/additionalcriteria/Sandwich.java | 1998 | /*******************************************************************************
* Copyright (c) 2011, 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:
* 15/08/2011-2.3.1 Guy Pelletier
* - 298494: JPQL exists subquery generates unnecessary table join
******************************************************************************/
package org.eclipse.persistence.testing.models.jpa.advanced.additionalcriteria;
import static org.eclipse.persistence.config.CacheIsolationType.PROTECTED;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.AdditionalCriteria;
import org.eclipse.persistence.annotations.Cache;
@Entity
@Table(name="JPA_AC_SANDWICH")
@DiscriminatorValue("S")
@AdditionalCriteria("this.description like :SANDWICH_DESCRIPTION")
@PrimaryKeyJoinColumn(name="S_ID", referencedColumnName="F_ID")
public class Sandwich extends Food {
@Column(name="S_NAME")
public String name;
@Column(name="S_DESCRIPTION")
public String description;
public String getDescription() {
return description;
}
public String getName() {
return name;
}
public void setDescription(String description) {
this.description = description;
}
public void setName(String name) {
this.name = name;
}
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | utils/eclipselink.utils.workbench/mappingsplugin/source/org/eclipse/persistence/tools/workbench/mappingsplugin/ui/mapping/MappingSelectionActionsPolicy.java | 6506 | /*******************************************************************************
* 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.mappingsplugin.ui.mapping;
import javax.swing.Icon;
import javax.swing.JOptionPane;
import org.eclipse.persistence.tools.workbench.framework.action.AbstractEnablableFrameworkAction;
import org.eclipse.persistence.tools.workbench.framework.action.FrameworkAction;
import org.eclipse.persistence.tools.workbench.framework.action.ToggleFrameworkAction;
import org.eclipse.persistence.tools.workbench.framework.app.ApplicationNode;
import org.eclipse.persistence.tools.workbench.framework.app.GroupContainerDescription;
import org.eclipse.persistence.tools.workbench.framework.app.MenuDescription;
import org.eclipse.persistence.tools.workbench.framework.app.MenuGroupDescription;
import org.eclipse.persistence.tools.workbench.framework.app.RootMenuDescription;
import org.eclipse.persistence.tools.workbench.framework.app.SelectionActionsPolicy;
import org.eclipse.persistence.tools.workbench.framework.app.ToggleMenuItemDescription;
import org.eclipse.persistence.tools.workbench.framework.app.ToggleToolBarButtonDescription;
import org.eclipse.persistence.tools.workbench.framework.context.WorkbenchContext;
import org.eclipse.persistence.tools.workbench.mappingsplugin.MappingsPlugin;
import org.eclipse.persistence.tools.workbench.uitools.LabelArea;
import org.eclipse.persistence.tools.workbench.uitools.swing.EmptyIcon;
import org.eclipse.persistence.tools.workbench.utility.string.StringTools;
public abstract class MappingSelectionActionsPolicy
implements SelectionActionsPolicy
{
protected static final Icon EMPTY_ICON = new EmptyIcon(16);
// **************** Variables *********************************************
private MappingsPlugin mwPlugin;
// **************** Constructors ******************************************
public MappingSelectionActionsPolicy(MappingsPlugin plugin) {
super();
this.mwPlugin = plugin;
}
// **************** Plugin ************************************************
protected MappingsPlugin getMappingsPlugin() {
return this.mwPlugin;
}
// **************** SelectionActionsPolicy contract ***********************
public GroupContainerDescription buildMenuDescription(WorkbenchContext context) {
RootMenuDescription menuDesc = new RootMenuDescription();
MenuGroupDescription classActionGroup = new MenuGroupDescription();
classActionGroup.add(this.mwPlugin.getRefreshClassesAction(context));
classActionGroup.add(this.mwPlugin.getAddOrRefreshClassesAction(context));
classActionGroup.add(this.mwPlugin.getCreateNewClassAction(context));
menuDesc.add(classActionGroup);
MenuGroupDescription removeGroup = new MenuGroupDescription();
removeGroup.add(getRemoveAction(context));
menuDesc.add(removeGroup);
MenuGroupDescription mapAsGroup = new MenuGroupDescription();
mapAsGroup.add(buildMapAsMenuDescription(context));
menuDesc.add(mapAsGroup);
return menuDesc;
}
public final MenuDescription buildMapAsMenuDescription(WorkbenchContext context)
{
MenuDescription desc = new MenuDescription(context.getApplicationContext().getResourceRepository().getString("CHANGE_MAPPING_TYPE_MENU"),
context.getApplicationContext().getResourceRepository().getString("CHANGE_MAPPING_TYPE_MENU"),
context.getApplicationContext().getResourceRepository().getMnemonic("CHANGE_MAPPING_TYPE_MENU"),
EMPTY_ICON
);
addToMapAsMenuDescription(desc, context);
return desc;
}
protected abstract void addToMapAsMenuDescription(MenuDescription menu, WorkbenchContext context);
protected ToggleFrameworkAction getMapAsUnmappedAction(WorkbenchContext context) {
return new MapAsUnmappedAction(context);
}
protected final ToggleMenuItemDescription buildUnmappedMenuItem(WorkbenchContext context) {
return new ToggleMenuItemDescription(getMapAsUnmappedAction(context));
}
protected final ToggleToolBarButtonDescription buildUnmappedToolBarButton(WorkbenchContext context) {
return new ToggleToolBarButtonDescription(getMapAsUnmappedAction(context));
}
private FrameworkAction getRemoveAction(WorkbenchContext context) {
return new RemoveAction(context);
}
// ********** inner class **********
private static class RemoveAction extends AbstractEnablableFrameworkAction {
RemoveAction(WorkbenchContext context) {
super(context);
}
protected void initialize() {
super.initialize();
this.initializeIcon("remove");
this.initializeTextAndMnemonic("REMOVE_ACTION");
this.initializeToolTipText("REMOVE_ACTION.toolTipText");
}
protected void execute() {
if ( ! this.confirmRemoval()) {
return;
}
ApplicationNode[] selectedNodes = this.selectedNodes();
for (int i = 0; i < selectedNodes.length; i++) {
((MappingNode) selectedNodes[i]).remove();
}
}
private boolean confirmRemoval() {
return JOptionPane.YES_OPTION ==
JOptionPane.showConfirmDialog(
this.getWorkbenchContext().getCurrentWindow(),
new LabelArea(this.resourceRepository().getString("REMOVE_MAPPING_ACTION_DIALOG.message", StringTools.CR)),
this.resourceRepository().getString("REMOVE_MAPPING_ACTION_DIALOG.title"),
JOptionPane.YES_NO_OPTION
);
}
protected boolean shouldBeEnabled(ApplicationNode selectedNode) {
return true;
}
}
}
| epl-1.0 |
creative2020/mu2 | wp-content/plugins/wpmudev-updates/includes/templates/dashboard-signup.php | 6623 | <?php
global $current_user;
$default_name = empty($current_user->first_name) ? $current_user->display_name : $current_user->first_name;
if ($default_name == 'admin')
$default_name == '';
?>
<section id="profile" class="api-key-form step1">
<form action="<?php echo $this->server_url; ?>?action=get_apikey" method="post" id="api-login" class="clearfix">
<fieldset>
<legend>
<?php _e('Login to WPMU DEV', 'wpmudev') ?><br />
<small><?php _e('to enable the power of the Dashboard', 'wpmudev') ?></small>
</legend>
<?php if (isset($_GET['api_error'])) {
?><div class="registered_error"><p><i class="wdvicon-warning-sign wdvicon-large"></i> <?php _e('Invalid Username or Password. Please try again.', 'wpmudev'); ?><br /><a href="http://premium.wpmudev.org/wp-login.php?action=lostpassword" target="_blank"><?php _e('Forgot your password?', 'wpmudev'); ?></a></p></div><?php
} ?>
<?php if (isset($connection_error) && $connection_error) { ?>
<div class="registered_error"><p><i class="wdvicon-warning-sign wdvicon-large"></i> <?php printf(__('Your server had a problem connecting to WPMU DEV: "%s" Please try again.', 'wpmudev'), $this->api_error); ?><br><?php _e('If this problem continues, please contact your host with this error message and ask:', 'wpmudev'); ?><br><em><?php printf( __('"Is php on my server properly configured to be able to contact %s with a GET HTTP request via fsockopen or CURL?"', 'wpmudev'), $this->server_url ); ?></em></p></div>
<?php } else if (isset($key_valid) && !$key_valid) { ?>
<div class="registered_error"><p><i class="wdvicon-warning-sign wdvicon-large"></i> <?php _e('Your API Key was invalid. Please try again.', 'wpmudev'); ?></p></div>
<?php } ?>
<ol>
<li>
<div><label for="user_name1"><?php _e('Email/Username', 'wpmudev') ?></label></div>
<input type="text" name="username" id="user_name1" autocomplete="off" />
<!-- output line below if validation passed -->
<section class="validation"><span class="wdvicon-ok"></span></section>
</li>
<li>
<div><label for="password1"><?php _e('Your password', 'wpmudev') ?></label></div>
<input type="password" name="password" id="password1" autocomplete="off" />
<input type="hidden" name="dashboard_url" value="<?php echo $this->dashboard_url; ?>" />
<!-- output line below if validation passed -->
<section class="validation"><span class="wdvicon-ok"></span></section>
</li>
<li class="submit-data">
<div class="cta-wrap">
<button type="submit" class="wpmu-button full-width"><?php _e('Login »', 'wpmudev') ?></button>
<p><?php _e('Not a member yet?', 'wpmudev') ?> <a href="#" id="not-member"><?php _e('Create a free account', 'wpmudev') ?></a>.</p>
</div>
</li>
</ol>
</fieldset>
</form>
<form id="api-signup" class="clearfix" action="<?php echo $this->server_url; ?>?action=register-new" method="post" style="display:none;">
<fieldset>
<legend>
<?php _e('Get your <b>free</b> API key', 'wpmudev') ?><br />
<small><?php _e('to experience the power of WPMU DEV', 'wpmudev') ?></small>
</legend>
<?php if (isset($_GET['register_error'])) {
//build error message
$err_message = array();
foreach($_GET['register_error'] as $error) {
if ($error == 'firstname') $err_message[] = __('Please enter your First name or Nickname.', 'wpmudev'); // Deprecated
if ($error == 'email') $err_message[] = __('This email is invalid or in use already. Please enter a valid email.', 'wpmudev');
if ($error == 'password') $err_message[] = __('Please enter a valid password with a minimum of 5 characters.', 'wpmudev');
if ($error == 'fail') $err_message[] = __('There was an unknown error. Couldn’t register you... Sorry!', 'wpmudev');
}
?><div class="registered_error"><p><i class="wdvicon-warning-sign wdvicon-large"></i> <?php echo implode('<br>', $err_message); ?></p></div><?php
} ?>
<ol>
<li>
<div><label for="first_name"><?php _e('First name', 'wpmudev') ?></label></div>
<input type="text" name="first_name" id="first_name" value="<?php echo $default_name; ?>" data-default_error="<?php esc_attr_e(__('Please enter your First name or a Nickname.', 'wpmudev')); ?>" />
<!-- output line below if error validating -->
<section class="validation error"><span class="wdvicon-remove-sign"></span><?php _e('Please enter your First name or a Nickname.', 'wpmudev') ?></section>
</li>
<li>
<div><label for="email_addr"><?php _e('Your email', 'wpmudev') ?></label></div>
<input type="email" name="email" id="email_addr" value="<?php echo $current_user->user_email; ?>" />
<!-- output line below if validation passed -->
<section class="validation"><span class="wdvicon-ok"></span></section>
</li>
<li>
<div><label for="password"><?php _e('Choose your password', 'wpmudev') ?></label></div>
<input type="password" name="password" id="password" />
<input type="hidden" name="dashboard_url" value="<?php echo $this->dashboard_url; ?>" />
<input type="hidden" name="referrer" value="<?php echo apply_filters('wpmudev_registration_referrer', ''); ?>" />
<!-- output line below if validation passed -->
<section class="validation"><span class="wdvicon-ok"></span></section>
</li>
<li class="submit-data">
<div class="cta-wrap">
<button type="submit" class="wpmu-button full-width"><?php _e('Get your API key »', 'wpmudev') ?></button>
<p><?php _e('Already a member?', 'wpmudev') ?> <a href="#" id="already-member"><?php _e('Click here', 'wpmudev') ?></a>.</p>
</div>
</li>
</ol>
</fieldset>
</form>
</section>
<section class="promotional">
<h3><span class="wpmudev-logo-small"></span> <?php _e('members get:', 'wpmudev') ?></h3>
<ul>
<li class="promo-plugins"><span class="promo-icn"></span><?php _e('Hundreds of amazing WordPress plugins to choose from', 'wpmudev') ?></li>
<li class="promo-themes"><span class="promo-icn"></span><?php _e('Quality WordPress, Multisite & BuddyPress themes and theme packs', 'wpmudev') ?></li>
<li class="promo-support"><span class="promo-icn"></span><?php _e('Spectacular WordPress support, fast response times, white label videos & more', 'wpmudev') ?></li>
<li class="promo-community"><span class="promo-icn"></span><?php _e('An amazing community of WordPress professionals to interact with', 'wpmudev') ?></li>
</ul>
</section> | gpl-2.0 |
remixod/netServer | Utilities/WCell.Util/DynamicProperties/SampleApp.cs | 12453 | //
// Author: James Nies
// Date: 3/22/2005
// Description: Sample application that tests the PropertyAccessor class.
//
// *** This code was written by James Nies and has been provided to you, ***
// *** free of charge, for your use. I assume no responsibility for any ***
// *** undesired events resulting from the use of this code or the ***
// *** information that has been provided with it . ***
//
using System;
using System.Reflection;
using System.Collections;
using System.Diagnostics;
using System.Threading;
using WCell.Util.DynamicProperties;
namespace WCell.Util.DynamicProperties
{
/// <summary>
/// Sample application for the fast dynamic property
/// accesssor.
/// </summary>
class SampleApp
{
#region Test Constants
private static readonly int TEST_INTEGER = 319;
private static readonly string TEST_STRING = "Test string.";
private static readonly sbyte TEST_SBYTE = 12;
private static readonly byte TEST_BYTE = 234;
private static readonly char TEST_CHAR = 'a';
private static readonly short TEST_SHORT = -673;
private static readonly ushort TEST_USHORT = 511;
private static readonly long TEST_LONG = 8798798798;
private static readonly ulong TEST_ULONG = 918297981798;
private static readonly bool TEST_BOOL = false;
private static readonly double TEST_DOUBLE = 789.12;
private static readonly float TEST_FLOAT = 123.12F;
private static readonly DateTime TEST_DATETIME = new DateTime(2005, 3, 6);
private static readonly decimal TEST_DECIMAL = new decimal(98798798.1221);
private static readonly int[] TEST_ARRAY = new int[] { 1, 2, 3 };
const int TEST_ITERATIONS = 100000000;
#endregion Test Constants
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// Test getting an integer property.
//
Thread.Sleep(500);
TestGetIntegerPerformance();
Thread.Sleep(500);
//
// Test setting an integer property.
//
TestSetIntegerPerformance();
Thread.Sleep(500);
//
// Test getting a string property.
//
TestGetStringPerformance();
Thread.Sleep(500);
//
// Test setting an integer property.
//
TestSetStringPerformance();
Console.Read();
}
/// <summary>
/// Test the performance of getting an integer property.
/// </summary>
public static void TestGetIntegerPerformance()
{
PropertyAccessorTestObject testObject
= CreateTestObject();
int test = 0;
//
// Generic Property accessor
//
Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Reset(); watch.Start();
GenericPropertyAccessor<PropertyAccessorTestObject, int> propertyAccessor =
new GenericPropertyAccessor<PropertyAccessorTestObject, int>("Int");
for (int i = 0; i < TEST_ITERATIONS; i++)
{
test = propertyAccessor.Get(testObject);
}
watch.Stop();
double genericPropertyAccessorMs = watch.ElapsedMilliseconds;
//
// Direct access
//
watch.Reset(); watch.Start();
for (int i = 0; i < TEST_ITERATIONS; i++)
{
test = testObject.Int;
}
watch.Stop();
double directAccessMs = watch.ElapsedMilliseconds;
//
// Property accessor
//
Type type = testObject.GetType();
watch.Reset(); watch.Start();
PropertyAccessor propertyAccessor2 = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Int");
for (int i = 0; i < TEST_ITERATIONS; i++)
{
test = (int)propertyAccessor2.Get(testObject);
}
watch.Stop();
double propertyAccessorMs = watch.ElapsedMilliseconds;
//
// Print results
//
Console.WriteLine(
TEST_ITERATIONS.ToString() + " property gets on integer..."
+ "\nDirect access ms: \t\t\t\t" + directAccessMs.ToString()
+ "\nGenericPropertyAccessor (Reflection.Emit) ms: \t" + genericPropertyAccessorMs.ToString()
+ "\nPropertyAccessor (Reflection.Emit) ms: \t\t" + propertyAccessorMs.ToString() + "\n\n");
}
/// <summary>
/// Test the performance of setting an integer property.
/// </summary>
public static void TestSetIntegerPerformance()
{
const int TEST_VALUE = 123;
PropertyAccessorTestObject testObject
= CreateTestObject();
//
// Generic Property accessor
//
Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Reset(); watch.Start();
GenericPropertyAccessor<PropertyAccessorTestObject, int> propertyAccessor =
new GenericPropertyAccessor<PropertyAccessorTestObject, int>("Int");
for (int i = 0; i < TEST_ITERATIONS; i++)
{
propertyAccessor.Set(testObject, TEST_VALUE);
}
watch.Stop();
double genericPropertyAccessorMs = watch.ElapsedMilliseconds;
//
// Direct access
//
watch.Reset(); watch.Start();
for (int i = 0; i < TEST_ITERATIONS; i++)
{
testObject.Int = TEST_VALUE;
}
watch.Stop();
double directAccessMs = watch.ElapsedMilliseconds;
//
// Property accessor
//
Type type = testObject.GetType();
watch.Reset(); watch.Start();
PropertyAccessor propertyAccessor2 = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Int");
for (int i = 0; i < TEST_ITERATIONS; i++)
{
propertyAccessor2.Set(testObject, TEST_VALUE);
}
watch.Stop();
double propertyAccessorMs = watch.ElapsedMilliseconds;
//
// Print results
//
Console.WriteLine(
TEST_ITERATIONS.ToString() + " property sets on integer..."
+ "\nDirect access ms: \t\t\t\t" + directAccessMs.ToString()
+ "\nGenericPropertyAccessor (Reflection.Emit) ms: \t" + genericPropertyAccessorMs.ToString()
+ "\nPropertyAccessor (Reflection.Emit) ms: \t\t" + propertyAccessorMs.ToString() + "\n\n");
}
/// <summary>
/// Test the performance of getting a string property.
/// </summary>
public static void TestGetStringPerformance()
{
PropertyAccessorTestObject testObject
= CreateTestObject();
string test = "Unset";
//
// Generic Property accessor
//
Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Reset(); watch.Start();
GenericPropertyAccessor<PropertyAccessorTestObject, string> propertyAccessor =
new GenericPropertyAccessor<PropertyAccessorTestObject, string>("String");
for (int i = 0; i < TEST_ITERATIONS; i++)
{
test = propertyAccessor.Get(testObject);
}
watch.Stop();
double genericPropertyAccessorMs = watch.ElapsedMilliseconds;
//
// Direct access
//
watch.Reset(); watch.Start();
for (int i = 0; i < TEST_ITERATIONS; i++)
{
test = testObject.String;
}
watch.Stop();
double directAccessMs = watch.ElapsedMilliseconds;
//
// Property accessor
//
Type type = testObject.GetType();
watch.Reset(); watch.Start();
PropertyAccessor propertyAccessor2 = new PropertyAccessor(typeof(PropertyAccessorTestObject), "String");
for (int i = 0; i < TEST_ITERATIONS; i++)
{
test = (string)propertyAccessor2.Get(testObject);
}
watch.Stop();
double propertyAccessorMs = watch.ElapsedMilliseconds;
//
// Print results
//
Console.WriteLine(
TEST_ITERATIONS.ToString() + " property gets on string..."
+ "\nDirect access ms: \t\t\t\t" + directAccessMs.ToString()
+ "\nGenericPropertyAccessor (Reflection.Emit) ms: \t" + genericPropertyAccessorMs.ToString()
+ "\nPropertyAccessor (Reflection.Emit) ms: \t\t" + propertyAccessorMs.ToString() + "\n\n");
}
/// <summary>
/// Test the performance of setting a string property.
/// </summary>
public static void TestSetStringPerformance()
{
const string TEST_VALUE = "Test";
PropertyAccessorTestObject testObject
= CreateTestObject();
//
// Generic Property accessor
//
Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Reset(); watch.Start();
GenericPropertyAccessor<PropertyAccessorTestObject, string> propertyAccessor =
new GenericPropertyAccessor<PropertyAccessorTestObject, string>("String");
for (int i = 0; i < TEST_ITERATIONS; i++)
{
propertyAccessor.Set(testObject, TEST_VALUE);
}
watch.Stop();
double genericPropertyAccessorMs = watch.ElapsedMilliseconds;
//
// Direct access
//
watch.Reset(); watch.Start();
for (int i = 0; i < TEST_ITERATIONS; i++)
{
testObject.String = TEST_VALUE;
}
watch.Stop();
double directAccessMs = watch.ElapsedMilliseconds;
//
// Property accessor
//
Type type = testObject.GetType();
watch.Reset(); watch.Start();
PropertyAccessor propertyAccessor2 = new PropertyAccessor(typeof(PropertyAccessorTestObject), "String");
for (int i = 0; i < TEST_ITERATIONS; i++)
{
propertyAccessor2.Set(testObject, TEST_VALUE);
}
watch.Stop();
double propertyAccessorMs = watch.ElapsedMilliseconds;
//
// Print results
//
Console.WriteLine(
TEST_ITERATIONS.ToString() + " property sets on string..."
+ "\nDirect access ms: \t\t\t\t" + directAccessMs.ToString()
+ "\nGenericPropertyAccessor (Reflection.Emit) ms: \t" + genericPropertyAccessorMs.ToString()
+ "\nPropertyAccessor (Reflection.Emit) ms: \t\t" + propertyAccessorMs.ToString() + "\n\n");
}
/// <summary>
/// Creates an object for testing the PropertyAccessor class.
/// </summary>
/// <returns></returns>
public static PropertyAccessorTestObject CreateTestObject()
{
PropertyAccessorTestObject testObject = new PropertyAccessorTestObject();
testObject.Int = TEST_INTEGER;
testObject.String = TEST_STRING;
testObject.Bool = TEST_BOOL;
testObject.Byte = TEST_BYTE;
testObject.Char = TEST_CHAR;
testObject.DateTime = TEST_DATETIME;
testObject.Decimal = TEST_DECIMAL;
testObject.Double = TEST_DOUBLE;
testObject.Float = TEST_FLOAT;
testObject.Long = TEST_LONG;
testObject.Sbyte = TEST_SBYTE;
testObject.Short = TEST_SHORT;
testObject.ULong = TEST_ULONG;
testObject.UShort = TEST_USHORT;
testObject.List = new ArrayList(TEST_ARRAY);
return testObject;
}
}
} | gpl-2.0 |
filemon/freemind | freemind/modes/mindmapmode/attributeactors/ReplaceAttributeValueActor.java | 2676 | /*FreeMind - A Program for creating and viewing Mindmaps
*Copyright (C) 2000-2006 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitri Polivaev and others.
*
*See COPYING for Details
*
*This program is free software; you can redistribute it and/or
*modify it under the terms of the GNU General Public License
*as published by the Free Software Foundation; either version 2
*of the License, or (at your option) any later version.
*
*This program is distributed in the hope that it will be useful,
*but WITHOUT ANY WARRANTY; without even the implied warranty of
*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*GNU General Public License for more details.
*
*You should have received a copy of the GNU General Public License
*along with this program; if not, write to the Free Software
*Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/*
* Created on 29.01.2006
* Created by Dimitri Polivaev
*/
package freemind.modes.mindmapmode.attributeactors;
import freemind.controller.actions.generated.instance.ReplaceAttributeValueElementaryAction;
import freemind.controller.actions.generated.instance.XmlAction;
import freemind.modes.mindmapmode.MindMapController;
import freemind.modes.mindmapmode.actions.xml.AbstractActorXml;
import freemind.modes.mindmapmode.actions.xml.ActionPair;
public class ReplaceAttributeValueActor extends AbstractActorXml {
public ReplaceAttributeValueActor(MindMapController mindMapModeController) {
super(mindMapModeController);
}
public XmlAction createAction(String name, String oldValue, String newValue) {
ReplaceAttributeValueElementaryAction action = new ReplaceAttributeValueElementaryAction();
action.setName(name);
action.setOldValue(oldValue);
action.setNewValue(newValue);
return action;
}
public ActionPair createActionPair(String name, String oldValue,
String newValue) {
ActionPair actionPair = new ActionPair(createAction(name, oldValue,
newValue), createAction(name, newValue, oldValue));
return actionPair;
}
public void act(XmlAction action) {
if (action instanceof ReplaceAttributeValueElementaryAction) {
ReplaceAttributeValueElementaryAction replaceAttributeValueAction = (ReplaceAttributeValueElementaryAction) action;
act(replaceAttributeValueAction.getName(),
replaceAttributeValueAction.getOldValue(),
replaceAttributeValueAction.getNewValue());
}
}
private void act(String name, String oldValue, String newValue) {
getAttributeRegistry().getElement(name)
.replaceValue(oldValue, newValue);
}
public Class getDoActionClass() {
return ReplaceAttributeValueElementaryAction.class;
}
}
| gpl-2.0 |
Dreyerized/bananascrum | vendor/gems/icalendar-1.1.0/lib/icalendar/tzinfo.rb | 4170 | =begin
Copyright (C) 2008 Sean Dague
This library is free software; you can redistribute it and/or modify it
under the same terms as the ruby language itself, see the file COPYING for
details.
=end
# The following adds a bunch of mixins to the tzinfo class, with the
# intent on making it very easy to load in tzinfo data for generating
# ical events. With this you can do the following:
#
# require "icalendar/tzinfo"
#
# estart = DateTime.new(2008, 12, 29, 8, 0, 0)
# eend = DateTime.new(2008, 12, 29, 11, 0, 0)
# tstring = "America/Chicago"
#
# tz = TZInfo::Timezone.get(tstring)
# cal = Calendar.new
# # the mixins now generate all the timezone info for the date in question
# timezone = tz.ical_timezone(estart)
# cal.add(timezone)
#
# cal.event do
# dtstart estart
# dtend eend
# summary "Meeting with the man."
# description "Have a long lunch meeting and decide nothing..."
# klass "PRIVATE"
# end
#
# puts cal.to_ical
#
# The recurance rule calculations are hacky, and only start at the
# beginning of the current dst transition. I doubt this works for non
# dst areas yet. However, for a standard dst flipping zone, this
# seems to work fine (tested in Mozilla Thunderbird + Lightning).
# Future goal would be making this better.
# require "rubygems"
# require "tzinfo"
module TZInfo
class Timezone
def ical_timezone(date)
period = period_for_local(date)
timezone = Icalendar::Timezone.new
timezone.timezone_id = identifier
timezone.add(period.daylight)
timezone.add(period.standard)
return timezone
end
end
class TimezoneTransitionInfo
def offset_from
a = previous_offset.utc_total_offset
sprintf("%2.2d%2.2d", (a / 3600).to_i, ((a / 60) % 60).to_i)
end
def offset_to
a = offset.utc_total_offset
sprintf("%2.2d%2.2d", (a / 3600).to_i, ((a / 60) % 60).to_i)
end
def rrule
start = local_start.to_datetime
# this is somewhat of a hack, but seems to work ok
[sprintf(
"FREQ=YEARLY;BYMONTH=%d;BYDAY=%d%s",
start.month,
((start.day - 1)/ 7).to_i + 1,
start.strftime("%a").upcase[0,2]
)]
end
def dtstart
local_start.to_datetime.strftime("%Y%m%dT%H%M%S")
end
end
class TimezonePeriod
def daylight
day = Icalendar::Daylight.new
if dst?
day.timezone_name = abbreviation.to_s
day.timezone_offset_from = start_transition.offset_from
day.timezone_offset_to = start_transition.offset_to
day.dtstart = start_transition.dtstart
day.recurrence_rules = start_transition.rrule
else
day.timezone_name = abbreviation.to_s.sub("ST","DT")
day.timezone_offset_from = end_transition.offset_from
day.timezone_offset_to = end_transition.offset_to
day.dtstart = end_transition.dtstart
day.recurrence_rules = end_transition.rrule
end
return day
end
def standard
std = Icalendar::Standard.new
if dst?
std.timezone_name = abbreviation.to_s.sub("DT","ST")
std.timezone_offset_from = end_transition.offset_from
std.timezone_offset_to = end_transition.offset_to
std.dtstart = end_transition.dtstart
std.recurrence_rules = end_transition.rrule
else
std.timezone_name = abbreviation.to_s
std.timezone_offset_from = start_transition.offset_from
std.timezone_offset_to = start_transition.offset_to
std.dtstart = start_transition.dtstart
std.recurrence_rules = start_transition.rrule
end
return std
end
end
end
| gpl-2.0 |
sohilgupta/datamelons | wp_bkp/html/wp-content/themes/Adament/comments.php | 3014 | <?php
/**
* The template for displaying Comments.
*
* The area of the page that contains both current comments
* and the comment form. The actual display of comments is
* handled by a callback to fabframe_comment() which is
* located in the inc/template-tags.php file.
*
* @package fabframe
*/
/*
* If the current post is protected by a password and
* the visitor has not yet entered the password we will
* return early without loading the comments.
*/
if ( post_password_required() ) {
return;
}
?>
<div id="comments" class="comments-area">
<?php // You can start editing here -- including this comment! ?>
<?php if ( have_comments() ) : ?>
<h2 class="comments-title">
<?php
printf( _nx( 'One thought on “%2$s”', '%1$s thoughts on “%2$s”', get_comments_number(), 'comments title', 'fabframe' ),
number_format_i18n( get_comments_number() ), '<span>' . get_the_title() . '</span>' );
?>
</h2>
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
<nav id="comment-nav-above" class="comment-navigation" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Comment navigation', 'fabframe' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __( '← Older Comments', 'fabframe' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments →', 'fabframe' ) ); ?></div>
</nav><!-- #comment-nav-above -->
<?php endif; // check for comment navigation ?>
<ol class="comment-list">
<?php
/* Loop through and list the comments. Tell wp_list_comments()
* to use fabframe_comment() to format the comments.
* If you want to override this in a child theme, then you can
* define fabframe_comment() and that will be used instead.
* See fabframe_comment() in inc/template-tags.php for more.
*/
wp_list_comments( array( 'callback' => 'fabframe_comment' ) );
?>
</ol><!-- .comment-list -->
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
<nav id="comment-nav-below" class="comment-navigation" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Comment navigation', 'fabframe' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __( '← Older Comments', 'fabframe' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments →', 'fabframe' ) ); ?></div>
</nav><!-- #comment-nav-below -->
<?php endif; // check for comment navigation ?>
<?php endif; // have_comments() ?>
<?php
// If comments are closed and there are comments, let's leave a little note, shall we?
if ( ! comments_open() && '0' != get_comments_number() && post_type_supports( get_post_type(), 'comments' ) ) :
?>
<p class="no-comments"><?php _e( 'Comments are closed.', 'fabframe' ); ?></p>
<?php endif; ?>
<?php comment_form(); ?>
</div><!-- #comments -->
| gpl-2.0 |
hyphaltip/cndtools | include/boost/asio/detail/strand_service.hpp | 13163 | //
// strand_service.hpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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)
//
#ifndef BOOST_ASIO_DETAIL_STRAND_SERVICE_HPP
#define BOOST_ASIO_DETAIL_STRAND_SERVICE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/push_options.hpp>
#include <boost/asio/detail/push_options.hpp>
#include <boost/aligned_storage.hpp>
#include <boost/assert.hpp>
#include <boost/functional/hash.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/asio/detail/pop_options.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/detail/bind_handler.hpp>
#include <boost/asio/detail/call_stack.hpp>
#include <boost/asio/detail/handler_alloc_helpers.hpp>
#include <boost/asio/detail/handler_invoke_helpers.hpp>
#include <boost/asio/detail/mutex.hpp>
#include <boost/asio/detail/noncopyable.hpp>
#include <boost/asio/detail/service_base.hpp>
namespace boost {
namespace asio {
namespace detail {
// Default service implementation for a strand.
class strand_service
: public boost::asio::detail::service_base<strand_service>
{
public:
class handler_base;
class invoke_current_handler;
class post_next_waiter_on_exit;
// The underlying implementation of a strand.
class strand_impl
{
public:
strand_impl()
: current_handler_(0),
first_waiter_(0),
last_waiter_(0)
{
}
private:
// Only this service will have access to the internal values.
friend class strand_service;
friend class post_next_waiter_on_exit;
friend class invoke_current_handler;
// Mutex to protect access to internal data.
boost::asio::detail::mutex mutex_;
// The handler that is ready to execute. If this pointer is non-null then it
// indicates that a handler holds the lock.
handler_base* current_handler_;
// The start of the list of waiting handlers for the strand.
handler_base* first_waiter_;
// The end of the list of waiting handlers for the strand.
handler_base* last_waiter_;
// Storage for posted handlers.
typedef boost::aligned_storage<128> handler_storage_type;
#if defined(__BORLANDC__)
boost::aligned_storage<128> handler_storage_;
#else
handler_storage_type handler_storage_;
#endif
};
friend class strand_impl;
typedef strand_impl* implementation_type;
// Base class for all handler types.
class handler_base
{
public:
typedef void (*invoke_func_type)(handler_base*,
strand_service&, implementation_type&);
typedef void (*destroy_func_type)(handler_base*);
handler_base(invoke_func_type invoke_func, destroy_func_type destroy_func)
: next_(0),
invoke_func_(invoke_func),
destroy_func_(destroy_func)
{
}
void invoke(strand_service& service_impl, implementation_type& impl)
{
invoke_func_(this, service_impl, impl);
}
void destroy()
{
destroy_func_(this);
}
protected:
~handler_base()
{
}
private:
friend class strand_service;
friend class strand_impl;
friend class post_next_waiter_on_exit;
handler_base* next_;
invoke_func_type invoke_func_;
destroy_func_type destroy_func_;
};
// Helper class to allow handlers to be dispatched.
class invoke_current_handler
{
public:
invoke_current_handler(strand_service& service_impl,
const implementation_type& impl)
: service_impl_(service_impl),
impl_(impl)
{
}
void operator()()
{
impl_->current_handler_->invoke(service_impl_, impl_);
}
friend void* asio_handler_allocate(std::size_t size,
invoke_current_handler* this_handler)
{
return this_handler->do_handler_allocate(size);
}
friend void asio_handler_deallocate(void*, std::size_t,
invoke_current_handler*)
{
}
void* do_handler_allocate(std::size_t size)
{
#if defined(__BORLANDC__)
BOOST_ASSERT(size <= boost::aligned_storage<128>::size);
#else
BOOST_ASSERT(size <= strand_impl::handler_storage_type::size);
#endif
(void)size;
return impl_->handler_storage_.address();
}
// The asio_handler_invoke hook is not defined here since the default one
// provides the correct behaviour, and including it here breaks MSVC 7.1
// in some situations.
private:
strand_service& service_impl_;
implementation_type impl_;
};
// Helper class to automatically enqueue next waiter on block exit.
class post_next_waiter_on_exit
{
public:
post_next_waiter_on_exit(strand_service& service_impl,
implementation_type& impl)
: service_impl_(service_impl),
impl_(impl),
cancelled_(false)
{
}
~post_next_waiter_on_exit()
{
if (!cancelled_)
{
boost::asio::detail::mutex::scoped_lock lock(impl_->mutex_);
impl_->current_handler_ = impl_->first_waiter_;
if (impl_->current_handler_)
{
impl_->first_waiter_ = impl_->first_waiter_->next_;
if (impl_->first_waiter_ == 0)
impl_->last_waiter_ = 0;
lock.unlock();
service_impl_.get_io_service().post(
invoke_current_handler(service_impl_, impl_));
}
}
}
void cancel()
{
cancelled_ = true;
}
private:
strand_service& service_impl_;
implementation_type& impl_;
bool cancelled_;
};
// Class template for a waiter.
template <typename Handler>
class handler_wrapper
: public handler_base
{
public:
handler_wrapper(Handler handler)
: handler_base(&handler_wrapper<Handler>::do_invoke,
&handler_wrapper<Handler>::do_destroy),
handler_(handler)
{
}
static void do_invoke(handler_base* base,
strand_service& service_impl, implementation_type& impl)
{
// Take ownership of the handler object.
typedef handler_wrapper<Handler> this_type;
this_type* h(static_cast<this_type*>(base));
typedef handler_alloc_traits<Handler, this_type> alloc_traits;
handler_ptr<alloc_traits> ptr(h->handler_, h);
post_next_waiter_on_exit p1(service_impl, impl);
// Make a copy of the handler so that the memory can be deallocated before
// the upcall is made.
Handler handler(h->handler_);
// A handler object must still be valid when the next waiter is posted
// since destroying the last handler might cause the strand object to be
// destroyed. Therefore we create a second post_next_waiter_on_exit object
// that will be destroyed before the handler object.
p1.cancel();
post_next_waiter_on_exit p2(service_impl, impl);
// Free the memory associated with the handler.
ptr.reset();
// Indicate that this strand is executing on the current thread.
call_stack<strand_impl>::context ctx(impl);
// Make the upcall.
boost_asio_handler_invoke_helpers::invoke(handler, handler);
}
static void do_destroy(handler_base* base)
{
// Take ownership of the handler object.
typedef handler_wrapper<Handler> this_type;
this_type* h(static_cast<this_type*>(base));
typedef handler_alloc_traits<Handler, this_type> alloc_traits;
handler_ptr<alloc_traits> ptr(h->handler_, h);
// A sub-object of the handler may be the true owner of the memory
// associated with the handler. Consequently, a local copy of the handler
// is required to ensure that any owning sub-object remains valid until
// after we have deallocated the memory here.
Handler handler(h->handler_);
(void)handler;
// Free the memory associated with the handler.
ptr.reset();
}
private:
Handler handler_;
};
// Construct a new strand service for the specified io_service.
explicit strand_service(boost::asio::io_service& io_service)
: boost::asio::detail::service_base<strand_service>(io_service),
mutex_(),
salt_(0)
{
}
// Destroy all user-defined handler objects owned by the service.
void shutdown_service()
{
// Construct a list of all handlers to be destroyed.
boost::asio::detail::mutex::scoped_lock lock(mutex_);
handler_base* first_handler = 0;
for (std::size_t i = 0; i < num_implementations; ++i)
{
if (strand_impl* impl = implementations_[i].get())
{
if (impl->current_handler_)
{
impl->current_handler_->next_ = first_handler;
first_handler = impl->current_handler_;
impl->current_handler_ = 0;
}
if (impl->first_waiter_)
{
impl->last_waiter_->next_ = first_handler;
first_handler = impl->first_waiter_;
impl->first_waiter_ = 0;
impl->last_waiter_ = 0;
}
}
}
// Destroy all handlers without holding the lock.
lock.unlock();
while (first_handler)
{
handler_base* next = first_handler->next_;
first_handler->destroy();
first_handler = next;
}
}
// Construct a new strand implementation.
void construct(implementation_type& impl)
{
std::size_t index = boost::hash_value(&impl);
boost::hash_combine(index, salt_++);
index = index % num_implementations;
boost::asio::detail::mutex::scoped_lock lock(mutex_);
if (!implementations_[index])
implementations_[index].reset(new strand_impl);
impl = implementations_[index].get();
}
// Destroy a strand implementation.
void destroy(implementation_type& impl)
{
impl = 0;
}
// Request the io_service to invoke the given handler.
template <typename Handler>
void dispatch(implementation_type& impl, Handler handler)
{
if (call_stack<strand_impl>::contains(impl))
{
boost_asio_handler_invoke_helpers::invoke(handler, handler);
}
else
{
// Allocate and construct an object to wrap the handler.
typedef handler_wrapper<Handler> value_type;
typedef handler_alloc_traits<Handler, value_type> alloc_traits;
raw_handler_ptr<alloc_traits> raw_ptr(handler);
handler_ptr<alloc_traits> ptr(raw_ptr, handler);
boost::asio::detail::mutex::scoped_lock lock(impl->mutex_);
if (impl->current_handler_ == 0)
{
// This handler now has the lock, so can be dispatched immediately.
impl->current_handler_ = ptr.release();
lock.unlock();
this->get_io_service().dispatch(invoke_current_handler(*this, impl));
}
else
{
// Another handler already holds the lock, so this handler must join
// the list of waiters. The handler will be posted automatically when
// its turn comes.
if (impl->last_waiter_)
{
impl->last_waiter_->next_ = ptr.get();
impl->last_waiter_ = impl->last_waiter_->next_;
}
else
{
impl->first_waiter_ = ptr.get();
impl->last_waiter_ = ptr.get();
}
ptr.release();
}
}
}
// Request the io_service to invoke the given handler and return immediately.
template <typename Handler>
void post(implementation_type& impl, Handler handler)
{
// Allocate and construct an object to wrap the handler.
typedef handler_wrapper<Handler> value_type;
typedef handler_alloc_traits<Handler, value_type> alloc_traits;
raw_handler_ptr<alloc_traits> raw_ptr(handler);
handler_ptr<alloc_traits> ptr(raw_ptr, handler);
boost::asio::detail::mutex::scoped_lock lock(impl->mutex_);
if (impl->current_handler_ == 0)
{
// This handler now has the lock, so can be dispatched immediately.
impl->current_handler_ = ptr.release();
lock.unlock();
this->get_io_service().post(invoke_current_handler(*this, impl));
}
else
{
// Another handler already holds the lock, so this handler must join the
// list of waiters. The handler will be posted automatically when its turn
// comes.
if (impl->last_waiter_)
{
impl->last_waiter_->next_ = ptr.get();
impl->last_waiter_ = impl->last_waiter_->next_;
}
else
{
impl->first_waiter_ = ptr.get();
impl->last_waiter_ = ptr.get();
}
ptr.release();
}
}
private:
// Mutex to protect access to the array of implementations.
boost::asio::detail::mutex mutex_;
// Number of implementations shared between all strand objects.
enum { num_implementations = 193 };
// The head of a linked list of all implementations.
boost::scoped_ptr<strand_impl> implementations_[num_implementations];
// Extra value used when hashing to prevent recycled memory locations from
// getting the same strand implementation.
std::size_t salt_;
};
} // namespace detail
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // BOOST_ASIO_DETAIL_STRAND_SERVICE_HPP
| gpl-2.0 |
HighTower1991/HotswapAgent | plugin/hotswap-agent-proxy-plugin/src/main/java/org/hotswap/agent/plugin/proxy/java/ProxyGenerator.java | 64478 | /*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.hotswap.agent.plugin.proxy.java;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.UUID;
import sun.security.action.GetBooleanAction;
/**
* ProxyGenerator contains the code to generate a dynamic proxy class for the java.lang.reflect.Proxy API.
*
* The external interfaces to ProxyGenerator is the static "generateProxyClass" method.
*
* @author Peter Jones
* @since 1.3
*/
/**
* Added static field init-code to proxy methods
*
* @author Erki Ehtla
*
*/
public class ProxyGenerator {
/*
* In the comments below, "JVMS" refers to The Java Virtual Machine Specification Second Edition and "JLS" refers to
* the original version of The Java Language Specification, unless otherwise specified.
*/
/* generate 1.5-era class file version */
private static final int CLASSFILE_MAJOR_VERSION = 49;
private static final int CLASSFILE_MINOR_VERSION = 0;
/*
* beginning of constants copied from sun.tools.java.RuntimeConstants (which no longer exists):
*/
/* constant pool tags */
private static final int CONSTANT_UTF8 = 1;
private static final int CONSTANT_UNICODE = 2;
private static final int CONSTANT_INTEGER = 3;
private static final int CONSTANT_FLOAT = 4;
private static final int CONSTANT_LONG = 5;
private static final int CONSTANT_DOUBLE = 6;
private static final int CONSTANT_CLASS = 7;
private static final int CONSTANT_STRING = 8;
private static final int CONSTANT_FIELD = 9;
private static final int CONSTANT_METHOD = 10;
private static final int CONSTANT_INTERFACEMETHOD = 11;
private static final int CONSTANT_NAMEANDTYPE = 12;
/* access and modifier flags */
private static final int ACC_PUBLIC = 0x00000001;
private static final int ACC_PRIVATE = 0x00000002;
// private static final int ACC_PROTECTED = 0x00000004;
private static final int ACC_STATIC = 0x00000008;
private static final int ACC_FINAL = 0x00000010;
// private static final int ACC_SYNCHRONIZED = 0x00000020;
// private static final int ACC_VOLATILE = 0x00000040;
// private static final int ACC_TRANSIENT = 0x00000080;
// private static final int ACC_NATIVE = 0x00000100;
// private static final int ACC_INTERFACE = 0x00000200;
// private static final int ACC_ABSTRACT = 0x00000400;
private static final int ACC_SUPER = 0x00000020;
// private static final int ACC_STRICT = 0x00000800;
/* opcodes */
// private static final int opc_nop = 0;
private static final int opc_aconst_null = 1;
// private static final int opc_iconst_m1 = 2;
private static final int opc_iconst_0 = 3;
private static final int opc_iconst_1 = 4;
// private static final int opc_iconst_2 = 5;
// private static final int opc_iconst_3 = 6;
// private static final int opc_iconst_4 = 7;
// private static final int opc_iconst_5 = 8;
// private static final int opc_lconst_0 = 9;
// private static final int opc_lconst_1 = 10;
// private static final int opc_fconst_0 = 11;
// private static final int opc_fconst_1 = 12;
// private static final int opc_fconst_2 = 13;
// private static final int opc_dconst_0 = 14;
// private static final int opc_dconst_1 = 15;
private static final int opc_bipush = 16;
private static final int opc_sipush = 17;
private static final int opc_ldc = 18;
private static final int opc_ldc_w = 19;
// private static final int opc_ldc2_w = 20;
private static final int opc_iload = 21;
private static final int opc_lload = 22;
private static final int opc_fload = 23;
private static final int opc_dload = 24;
private static final int opc_aload = 25;
private static final int opc_iload_0 = 26;
// private static final int opc_iload_1 = 27;
// private static final int opc_iload_2 = 28;
// private static final int opc_iload_3 = 29;
private static final int opc_lload_0 = 30;
// private static final int opc_lload_1 = 31;
// private static final int opc_lload_2 = 32;
// private static final int opc_lload_3 = 33;
private static final int opc_fload_0 = 34;
// private static final int opc_fload_1 = 35;
// private static final int opc_fload_2 = 36;
// private static final int opc_fload_3 = 37;
private static final int opc_dload_0 = 38;
// private static final int opc_dload_1 = 39;
// private static final int opc_dload_2 = 40;
// private static final int opc_dload_3 = 41;
private static final int opc_aload_0 = 42;
// private static final int opc_aload_1 = 43;
// private static final int opc_aload_2 = 44;
// private static final int opc_aload_3 = 45;
// private static final int opc_iaload = 46;
// private static final int opc_laload = 47;
// private static final int opc_faload = 48;
// private static final int opc_daload = 49;
// private static final int opc_aaload = 50;
// private static final int opc_baload = 51;
// private static final int opc_caload = 52;
// private static final int opc_saload = 53;
// private static final int opc_istore = 54;
// private static final int opc_lstore = 55;
// private static final int opc_fstore = 56;
// private static final int opc_dstore = 57;
private static final int opc_astore = 58;
// private static final int opc_istore_0 = 59;
// private static final int opc_istore_1 = 60;
// private static final int opc_istore_2 = 61;
// private static final int opc_istore_3 = 62;
// private static final int opc_lstore_0 = 63;
// private static final int opc_lstore_1 = 64;
// private static final int opc_lstore_2 = 65;
// private static final int opc_lstore_3 = 66;
// private static final int opc_fstore_0 = 67;
// private static final int opc_fstore_1 = 68;
// private static final int opc_fstore_2 = 69;
// private static final int opc_fstore_3 = 70;
// private static final int opc_dstore_0 = 71;
// private static final int opc_dstore_1 = 72;
// private static final int opc_dstore_2 = 73;
// private static final int opc_dstore_3 = 74;
private static final int opc_astore_0 = 75;
// private static final int opc_astore_1 = 76;
// private static final int opc_astore_2 = 77;
// private static final int opc_astore_3 = 78;
// private static final int opc_iastore = 79;
// private static final int opc_lastore = 80;
// private static final int opc_fastore = 81;
// private static final int opc_dastore = 82;
private static final int opc_aastore = 83;
// private static final int opc_bastore = 84;
// private static final int opc_castore = 85;
// private static final int opc_sastore = 86;
private static final int opc_pop = 87;
// private static final int opc_pop2 = 88;
private static final int opc_dup = 89;
// private static final int opc_dup_x1 = 90;
// private static final int opc_dup_x2 = 91;
// private static final int opc_dup2 = 92;
// private static final int opc_dup2_x1 = 93;
// private static final int opc_dup2_x2 = 94;
// private static final int opc_swap = 95;
// private static final int opc_iadd = 96;
// private static final int opc_ladd = 97;
// private static final int opc_fadd = 98;
// private static final int opc_dadd = 99;
// private static final int opc_isub = 100;
// private static final int opc_lsub = 101;
// private static final int opc_fsub = 102;
// private static final int opc_dsub = 103;
// private static final int opc_imul = 104;
// private static final int opc_lmul = 105;
// private static final int opc_fmul = 106;
// private static final int opc_dmul = 107;
// private static final int opc_idiv = 108;
// private static final int opc_ldiv = 109;
// private static final int opc_fdiv = 110;
// private static final int opc_ddiv = 111;
// private static final int opc_irem = 112;
// private static final int opc_lrem = 113;
// private static final int opc_frem = 114;
// private static final int opc_drem = 115;
// private static final int opc_ineg = 116;
// private static final int opc_lneg = 117;
// private static final int opc_fneg = 118;
// private static final int opc_dneg = 119;
// private static final int opc_ishl = 120;
// private static final int opc_lshl = 121;
// private static final int opc_ishr = 122;
// private static final int opc_lshr = 123;
// private static final int opc_iushr = 124;
// private static final int opc_lushr = 125;
// private static final int opc_iand = 126;
// private static final int opc_land = 127;
// private static final int opc_ior = 128;
// private static final int opc_lor = 129;
// private static final int opc_ixor = 130;
// private static final int opc_lxor = 131;
// private static final int opc_iinc = 132;
// private static final int opc_i2l = 133;
// private static final int opc_i2f = 134;
// private static final int opc_i2d = 135;
// private static final int opc_l2i = 136;
// private static final int opc_l2f = 137;
// private static final int opc_l2d = 138;
// private static final int opc_f2i = 139;
// private static final int opc_f2l = 140;
// private static final int opc_f2d = 141;
// private static final int opc_d2i = 142;
// private static final int opc_d2l = 143;
// private static final int opc_d2f = 144;
// private static final int opc_i2b = 145;
// private static final int opc_i2c = 146;
// private static final int opc_i2s = 147;
// private static final int opc_lcmp = 148;
// private static final int opc_fcmpl = 149;
// private static final int opc_fcmpg = 150;
// private static final int opc_dcmpl = 151;
// private static final int opc_dcmpg = 152;
// private static final int opc_ifeq = 153;
private static final int opc_ifne = 154;
// private static final int opc_iflt = 155;
// private static final int opc_ifge = 156;
// private static final int opc_ifgt = 157;
// private static final int opc_ifle = 158;
// private static final int opc_if_icmpeq = 159;
// private static final int opc_if_icmpne = 160;
// private static final int opc_if_icmplt = 161;
// private static final int opc_if_icmpge = 162;
// private static final int opc_if_icmpgt = 163;
// private static final int opc_if_icmple = 164;
// private static final int opc_if_acmpeq = 165;
// private static final int opc_if_acmpne = 166;
// private static final int opc_goto = 167;
// private static final int opc_jsr = 168;
// private static final int opc_ret = 169;
// private static final int opc_tableswitch = 170;
// private static final int opc_lookupswitch = 171;
private static final int opc_ireturn = 172;
private static final int opc_lreturn = 173;
private static final int opc_freturn = 174;
private static final int opc_dreturn = 175;
private static final int opc_areturn = 176;
private static final int opc_return = 177;
private static final int opc_getstatic = 178;
private static final int opc_putstatic = 179;
private static final int opc_getfield = 180;
// private static final int opc_putfield = 181;
private static final int opc_invokevirtual = 182;
private static final int opc_invokespecial = 183;
private static final int opc_invokestatic = 184;
private static final int opc_invokeinterface = 185;
private static final int opc_new = 187;
// private static final int opc_newarray = 188;
private static final int opc_anewarray = 189;
// private static final int opc_arraylength = 190;
private static final int opc_athrow = 191;
private static final int opc_checkcast = 192;
// private static final int opc_instanceof = 193;
// private static final int opc_monitorenter = 194;
// private static final int opc_monitorexit = 195;
private static final int opc_wide = 196;
// private static final int opc_multianewarray = 197;
// private static final int opc_ifnull = 198;
// private static final int opc_ifnonnull = 199;
// private static final int opc_goto_w = 200;
// private static final int opc_jsr_w = 201;
// end of constants copied from sun.tools.java.RuntimeConstants
/** name of the superclass of proxy classes */
private final static String superclassName = "java/lang/reflect/Proxy";
/** name of field for storing a proxy instance's invocation handler */
private final static String handlerFieldName = "h";
/** debugging flag for saving generated class files */
private final static boolean saveGeneratedFiles = java.security.AccessController.doPrivileged(
new GetBooleanAction("sun.misc.ProxyGenerator.saveGeneratedFiles")).booleanValue();
/**
* Generate a public proxy class given a name and a list of proxy interfaces.
*/
public static byte[] generateProxyClass(final String name, Class<?>[] interfaces) {
return generateProxyClass(name, interfaces, (ACC_PUBLIC | ACC_FINAL | ACC_SUPER));
}
/**
* Generate a proxy class given a name and a list of proxy interfaces.
*
* @param name
* the class name of the proxy class
* @param interfaces
* proxy interfaces
* @param accessFlags
* access flags of the proxy class
*/
public static byte[] generateProxyClass(final String name, Class<?>[] interfaces, int accessFlags) {
ProxyGenerator gen = new ProxyGenerator(name, interfaces, accessFlags);
final byte[] classFile = gen.generateClassFile();
if (saveGeneratedFiles) {
java.security.AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
public Void run() {
try {
int i = name.lastIndexOf('.');
Path path;
if (i > 0) {
Path dir = Paths.get(name.substring(0, i).replace('.', File.separatorChar));
Files.createDirectories(dir);
path = dir.resolve(name.substring(i + 1, name.length()) + ".class");
} else {
path = Paths.get(name + ".class");
}
Files.write(path, classFile);
return null;
} catch (IOException e) {
throw new InternalError("I/O exception saving generated file: " + e);
}
}
});
}
return classFile;
}
/* preloaded Method objects for methods in java.lang.Object */
private static Method hashCodeMethod;
private static Method equalsMethod;
private static Method toStringMethod;
static {
try {
hashCodeMethod = Object.class.getMethod("hashCode");
equalsMethod = Object.class.getMethod("equals", new Class<?>[] { Object.class });
toStringMethod = Object.class.getMethod("toString");
} catch (NoSuchMethodException e) {
throw new NoSuchMethodError(e.getMessage());
}
}
/** name of proxy class */
private String className;
private String random = UUID.randomUUID().toString().replace("-", "");
private String initFieldName = "clinitCalled" + random;
private String initMethodName = "clinitMethodByJavaAgentForHotSwap";
/** proxy interfaces */
private Class<?>[] interfaces;
/** proxy class access flags */
private int accessFlags;
/** constant pool of class being generated */
private ConstantPool cp = new ConstantPool();
/** FieldInfo struct for each field of generated class */
private List<FieldInfo> fields = new ArrayList<>();
/** MethodInfo struct for each method of generated class */
private List<MethodInfo> methods = new ArrayList<>();
/**
* maps method signature string to list of ProxyMethod objects for proxy methods with that signature
*/
private Map<String, List<ProxyMethod>> proxyMethods = new HashMap<>();
/** count of ProxyMethod objects added to proxyMethods */
private int proxyMethodCount = 0;
/**
* Construct a ProxyGenerator to generate a proxy class with the specified name and for the given interfaces.
*
* A ProxyGenerator object contains the state for the ongoing generation of a particular proxy class.
*/
private ProxyGenerator(String className, Class<?>[] interfaces, int accessFlags) {
this.className = className;
this.interfaces = interfaces;
this.accessFlags = accessFlags;
}
/**
* Generate a class file for the proxy class. This method drives the class file generation process.
*/
private byte[] generateClassFile() {
/*
* ============================================================ Step 1: Assemble ProxyMethod objects for all
* methods to generate proxy dispatching code for.
*/
/*
* Record that proxy methods are needed for the hashCode, equals, and toString methods of java.lang.Object. This
* is done before the methods from the proxy interfaces so that the methods from java.lang.Object take
* precedence over duplicate methods in the proxy interfaces.
*/
addProxyMethod(hashCodeMethod, Object.class);
addProxyMethod(equalsMethod, Object.class);
addProxyMethod(toStringMethod, Object.class);
/*
* Now record all of the methods from the proxy interfaces, giving earlier interfaces precedence over later ones
* with duplicate methods.
*/
for (Class<?> intf : interfaces) {
for (Method m : intf.getMethods()) {
addProxyMethod(m, intf);
}
}
/*
* For each set of proxy methods with the same signature, verify that the methods' return types are compatible.
*/
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
checkReturnTypes(sigmethods);
}
/*
* ============================================================ Step 2: Assemble FieldInfo and MethodInfo
* structs for all of fields and methods in the class we are generating.
*/
try {
methods.add(generateConstructor());
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
for (ProxyMethod pm : sigmethods) {
// add static field for method's Method object
fields.add(new FieldInfo(pm.methodFieldName, "Ljava/lang/reflect/Method;", ACC_PRIVATE | ACC_STATIC));
}
}
fields.add(new FieldInfo(initFieldName, "Z", ACC_PRIVATE | ACC_STATIC));
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
for (ProxyMethod pm : sigmethods) {
// generate code for proxy method and add it
methods.add(pm.generateMethod());
}
}
methods.add(generateStaticInitializer());
methods.add(generateStaticInitializerCaller());
} catch (IOException e) {
throw new InternalError("unexpected I/O Exception" + e);
}
if (methods.size() > 65535) {
throw new IllegalArgumentException("method limit exceeded");
}
if (fields.size() > 65535) {
throw new IllegalArgumentException("field limit exceeded");
}
/*
* ============================================================ Step 3: Write the final class file.
*/
/*
* Make sure that constant pool indexes are reserved for the following items before starting to write the final
* class file.
*/
cp.getClass(dotToSlash(className));
cp.getClass(superclassName);
for (Class<?> intf : interfaces) {
cp.getClass(dotToSlash(intf.getName()));
}
/*
* Disallow new constant pool additions beyond this point, since we are about to write the final constant pool
* table.
*/
cp.setReadOnly();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
try {
/*
* Write all the items of the "ClassFile" structure. See JVMS section 4.1.
*/
// u4 magic;
dout.writeInt(0xCAFEBABE);
// u2 minor_version;
dout.writeShort(CLASSFILE_MINOR_VERSION);
// u2 major_version;
dout.writeShort(CLASSFILE_MAJOR_VERSION);
cp.write(dout); // (write constant pool)
// u2 access_flags;
dout.writeShort(accessFlags);
// u2 this_class;
dout.writeShort(cp.getClass(dotToSlash(className)));
// u2 super_class;
dout.writeShort(cp.getClass(superclassName));
// u2 interfaces_count;
dout.writeShort(interfaces.length);
// u2 interfaces[interfaces_count];
for (Class<?> intf : interfaces) {
dout.writeShort(cp.getClass(dotToSlash(intf.getName())));
}
// u2 fields_count;
dout.writeShort(fields.size());
// field_info fields[fields_count];
for (FieldInfo f : fields) {
f.write(dout);
}
// u2 methods_count;
dout.writeShort(methods.size());
// method_info methods[methods_count];
for (MethodInfo m : methods) {
m.write(dout);
}
// u2 attributes_count;
dout.writeShort(0); // (no ClassFile attributes for proxy classes)
} catch (IOException e) {
throw new InternalError("unexpected I/O Exception" + e);
}
return bout.toByteArray();
}
/**
* Add another method to be proxied, either by creating a new ProxyMethod object or augmenting an old one for a
* duplicate method.
*
* "fromClass" indicates the proxy interface that the method was found through, which may be different from (a
* subinterface of) the method's "declaring class". Note that the first Method object passed for a given name and
* descriptor identifies the Method object (and thus the declaring class) that will be passed to the invocation
* handler's "invoke" method for a given set of duplicate methods.
*/
private void addProxyMethod(Method m, Class<?> fromClass) {
String name = m.getName();
Class<?>[] parameterTypes = m.getParameterTypes();
Class<?> returnType = m.getReturnType();
Class<?>[] exceptionTypes = m.getExceptionTypes();
String sig = name + getParameterDescriptors(parameterTypes);
List<ProxyMethod> sigmethods = proxyMethods.get(sig);
if (sigmethods != null) {
for (ProxyMethod pm : sigmethods) {
if (returnType == pm.returnType) {
/*
* Found a match: reduce exception types to the greatest set of exceptions that can thrown
* compatibly with the throws clauses of both overridden methods.
*/
List<Class<?>> legalExceptions = new ArrayList<>();
collectCompatibleTypes(exceptionTypes, pm.exceptionTypes, legalExceptions);
collectCompatibleTypes(pm.exceptionTypes, exceptionTypes, legalExceptions);
pm.exceptionTypes = new Class<?>[legalExceptions.size()];
pm.exceptionTypes = legalExceptions.toArray(pm.exceptionTypes);
return;
}
}
} else {
sigmethods = new ArrayList<>(3);
proxyMethods.put(sig, sigmethods);
}
sigmethods.add(new ProxyMethod(name, parameterTypes, returnType, exceptionTypes, fromClass));
}
/**
* For a given set of proxy methods with the same signature, check that their return types are compatible according
* to the Proxy specification.
*
* Specifically, if there is more than one such method, then all of the return types must be reference types, and
* there must be one return type that is assignable to each of the rest of them.
*/
private static void checkReturnTypes(List<ProxyMethod> methods) {
/*
* If there is only one method with a given signature, there cannot be a conflict. This is the only case in
* which a primitive (or void) return type is allowed.
*/
if (methods.size() < 2) {
return;
}
/*
* List of return types that are not yet known to be assignable from ("covered" by) any of the others.
*/
LinkedList<Class<?>> uncoveredReturnTypes = new LinkedList<>();
nextNewReturnType: for (ProxyMethod pm : methods) {
Class<?> newReturnType = pm.returnType;
if (newReturnType.isPrimitive()) {
throw new IllegalArgumentException("methods with same signature "
+ getFriendlyMethodSignature(pm.methodName, pm.parameterTypes)
+ " but incompatible return types: " + newReturnType.getName() + " and others");
}
boolean added = false;
/*
* Compare the new return type to the existing uncovered return types.
*/
ListIterator<Class<?>> liter = uncoveredReturnTypes.listIterator();
while (liter.hasNext()) {
Class<?> uncoveredReturnType = liter.next();
/*
* If an existing uncovered return type is assignable to this new one, then we can forget the new one.
*/
if (newReturnType.isAssignableFrom(uncoveredReturnType)) {
assert !added;
continue nextNewReturnType;
}
/*
* If the new return type is assignable to an existing uncovered one, then should replace the existing
* one with the new one (or just forget the existing one, if the new one has already be put in the
* list).
*/
if (uncoveredReturnType.isAssignableFrom(newReturnType)) {
// (we can assume that each return type is unique)
if (!added) {
liter.set(newReturnType);
added = true;
} else {
liter.remove();
}
}
}
/*
* If we got through the list of existing uncovered return types without an assignability relationship, then
* add the new return type to the list of uncovered ones.
*/
if (!added) {
uncoveredReturnTypes.add(newReturnType);
}
}
/*
* We shouldn't end up with more than one return type that is not assignable from any of the others.
*/
if (uncoveredReturnTypes.size() > 1) {
ProxyMethod pm = methods.get(0);
throw new IllegalArgumentException("methods with same signature "
+ getFriendlyMethodSignature(pm.methodName, pm.parameterTypes) + " but incompatible return types: "
+ uncoveredReturnTypes);
}
}
/**
* A FieldInfo object contains information about a particular field in the class being generated. The class mirrors
* the data items of the "field_info" structure of the class file format (see JVMS 4.5).
*/
private class FieldInfo {
public int accessFlags;
public String name;
public String descriptor;
public FieldInfo(String name, String descriptor, int accessFlags) {
this.name = name;
this.descriptor = descriptor;
this.accessFlags = accessFlags;
/*
* Make sure that constant pool indexes are reserved for the following items before starting to write the
* final class file.
*/
cp.getUtf8(name);
cp.getUtf8(descriptor);
}
public void write(DataOutputStream out) throws IOException {
/*
* Write all the items of the "field_info" structure. See JVMS section 4.5.
*/
// u2 access_flags;
out.writeShort(accessFlags);
// u2 name_index;
out.writeShort(cp.getUtf8(name));
// u2 descriptor_index;
out.writeShort(cp.getUtf8(descriptor));
// u2 attributes_count;
out.writeShort(0); // (no field_info attributes for proxy classes)
}
}
/**
* An ExceptionTableEntry object holds values for the data items of an entry in the "exception_table" item of the
* "Code" attribute of "method_info" structures (see JVMS 4.7.3).
*/
private static class ExceptionTableEntry {
public short startPc;
public short endPc;
public short handlerPc;
public short catchType;
public ExceptionTableEntry(short startPc, short endPc, short handlerPc, short catchType) {
this.startPc = startPc;
this.endPc = endPc;
this.handlerPc = handlerPc;
this.catchType = catchType;
}
};
/**
* A MethodInfo object contains information about a particular method in the class being generated. This class
* mirrors the data items of the "method_info" structure of the class file format (see JVMS 4.6).
*/
private class MethodInfo {
public int accessFlags;
public String name;
public String descriptor;
public short maxStack;
public short maxLocals;
public ByteArrayOutputStream code = new ByteArrayOutputStream();
public List<ExceptionTableEntry> exceptionTable = new ArrayList<ExceptionTableEntry>();
public short[] declaredExceptions;
public MethodInfo(String name, String descriptor, int accessFlags) {
this.name = name;
this.descriptor = descriptor;
this.accessFlags = accessFlags;
/*
* Make sure that constant pool indexes are reserved for the following items before starting to write the
* final class file.
*/
cp.getUtf8(name);
cp.getUtf8(descriptor);
cp.getUtf8("Code");
cp.getUtf8("Exceptions");
}
public void write(DataOutputStream out) throws IOException {
/*
* Write all the items of the "method_info" structure. See JVMS section 4.6.
*/
// u2 access_flags;
out.writeShort(accessFlags);
// u2 name_index;
out.writeShort(cp.getUtf8(name));
// u2 descriptor_index;
out.writeShort(cp.getUtf8(descriptor));
// u2 attributes_count;
out.writeShort(2); // (two method_info attributes:)
// Write "Code" attribute. See JVMS section 4.7.3.
// u2 attribute_name_index;
out.writeShort(cp.getUtf8("Code"));
// u4 attribute_length;
out.writeInt(12 + code.size() + 8 * exceptionTable.size());
// u2 max_stack;
out.writeShort(maxStack);
// u2 max_locals;
out.writeShort(maxLocals);
// u2 code_length;
out.writeInt(code.size());
// u1 code[code_length];
code.writeTo(out);
// u2 exception_table_length;
out.writeShort(exceptionTable.size());
for (ExceptionTableEntry e : exceptionTable) {
// u2 start_pc;
out.writeShort(e.startPc);
// u2 end_pc;
out.writeShort(e.endPc);
// u2 handler_pc;
out.writeShort(e.handlerPc);
// u2 catch_type;
out.writeShort(e.catchType);
}
// u2 attributes_count;
out.writeShort(0);
// write "Exceptions" attribute. See JVMS section 4.7.4.
// u2 attribute_name_index;
out.writeShort(cp.getUtf8("Exceptions"));
// u4 attributes_length;
out.writeInt(2 + 2 * declaredExceptions.length);
// u2 number_of_exceptions;
out.writeShort(declaredExceptions.length);
// u2 exception_index_table[number_of_exceptions];
for (short value : declaredExceptions) {
out.writeShort(value);
}
}
}
/**
* A ProxyMethod object represents a proxy method in the proxy class being generated: a method whose implementation
* will encode and dispatch invocations to the proxy instance's invocation handler.
*/
private class ProxyMethod {
public String methodName;
public Class<?>[] parameterTypes;
public Class<?> returnType;
public Class<?>[] exceptionTypes;
public Class<?> fromClass;
public String methodFieldName;
private ProxyMethod(String methodName, Class<?>[] parameterTypes, Class<?> returnType,
Class<?>[] exceptionTypes, Class<?> fromClass) {
this.methodName = methodName;
this.parameterTypes = parameterTypes;
this.returnType = returnType;
this.exceptionTypes = exceptionTypes;
this.fromClass = fromClass;
this.methodFieldName = "m" + proxyMethodCount++;
}
/**
* Return a MethodInfo object for this method, including generating the code and exception table entry.
*/
private MethodInfo generateMethod() throws IOException {
String desc = getMethodDescriptor(parameterTypes, returnType);
MethodInfo minfo = new MethodInfo(methodName, desc, ACC_PUBLIC | ACC_FINAL);
int[] parameterSlot = new int[parameterTypes.length];
int nextSlot = 1;
for (int i = 0; i < parameterSlot.length; i++) {
parameterSlot[i] = nextSlot;
nextSlot += getWordsPerType(parameterTypes[i]);
}
int localSlot0 = nextSlot;
short pc, tryBegin = 0, tryEnd;
DataOutputStream out = new DataOutputStream(minfo.code);
out.writeByte(opc_getstatic);
out.writeShort(cp.getFieldRef(dotToSlash(className), initFieldName, "Z"));
out.writeByte(opc_ifne);
out.writeShort(6);
out.writeByte(opc_invokestatic);
out.writeShort(cp.getMethodRef(dotToSlash(className), initMethodName, "()V"));
code_aload(0, out);
out.writeByte(opc_getfield);
out.writeShort(cp.getFieldRef(superclassName, handlerFieldName, "Ljava/lang/reflect/InvocationHandler;"));
code_aload(0, out);
out.writeByte(opc_getstatic);
out.writeShort(cp.getFieldRef(dotToSlash(className), methodFieldName, "Ljava/lang/reflect/Method;"));
if (parameterTypes.length > 0) {
code_ipush(parameterTypes.length, out);
out.writeByte(opc_anewarray);
out.writeShort(cp.getClass("java/lang/Object"));
for (int i = 0; i < parameterTypes.length; i++) {
out.writeByte(opc_dup);
code_ipush(i, out);
codeWrapArgument(parameterTypes[i], parameterSlot[i], out);
out.writeByte(opc_aastore);
}
} else {
out.writeByte(opc_aconst_null);
}
out.writeByte(opc_invokeinterface);
out.writeShort(cp.getInterfaceMethodRef("java/lang/reflect/InvocationHandler", "invoke",
"(Ljava/lang/Object;Ljava/lang/reflect/Method;" + "[Ljava/lang/Object;)Ljava/lang/Object;"));
out.writeByte(4);
out.writeByte(0);
if (returnType == void.class) {
out.writeByte(opc_pop);
out.writeByte(opc_return);
} else {
codeUnwrapReturnValue(returnType, out);
}
tryEnd = pc = (short) minfo.code.size();
List<Class<?>> catchList = computeUniqueCatchList(exceptionTypes);
if (catchList.size() > 0) {
for (Class<?> ex : catchList) {
minfo.exceptionTable.add(new ExceptionTableEntry(tryBegin, tryEnd, pc, cp.getClass(dotToSlash(ex
.getName()))));
}
out.writeByte(opc_athrow);
pc = (short) minfo.code.size();
minfo.exceptionTable.add(new ExceptionTableEntry(tryBegin, tryEnd, pc, cp
.getClass("java/lang/Throwable")));
code_astore(localSlot0, out);
out.writeByte(opc_new);
out.writeShort(cp.getClass("java/lang/reflect/UndeclaredThrowableException"));
out.writeByte(opc_dup);
code_aload(localSlot0, out);
out.writeByte(opc_invokespecial);
out.writeShort(cp.getMethodRef("java/lang/reflect/UndeclaredThrowableException", "<init>",
"(Ljava/lang/Throwable;)V"));
out.writeByte(opc_athrow);
}
if (minfo.code.size() > 65535) {
throw new IllegalArgumentException("code size limit exceeded");
}
minfo.maxStack = 10;
minfo.maxLocals = (short) (localSlot0 + 1);
minfo.declaredExceptions = new short[exceptionTypes.length];
for (int i = 0; i < exceptionTypes.length; i++) {
minfo.declaredExceptions[i] = cp.getClass(dotToSlash(exceptionTypes[i].getName()));
}
return minfo;
}
/**
* Generate code for wrapping an argument of the given type whose value can be found at the specified local
* variable index, in order for it to be passed (as an Object) to the invocation handler's "invoke" method. The
* code is written to the supplied stream.
*/
private void codeWrapArgument(Class<?> type, int slot, DataOutputStream out) throws IOException {
if (type.isPrimitive()) {
PrimitiveTypeInfo prim = PrimitiveTypeInfo.get(type);
if (type == int.class || type == boolean.class || type == byte.class || type == char.class
|| type == short.class) {
code_iload(slot, out);
} else if (type == long.class) {
code_lload(slot, out);
} else if (type == float.class) {
code_fload(slot, out);
} else if (type == double.class) {
code_dload(slot, out);
} else {
throw new AssertionError();
}
out.writeByte(opc_invokestatic);
out.writeShort(cp.getMethodRef(prim.wrapperClassName, "valueOf", prim.wrapperValueOfDesc));
} else {
code_aload(slot, out);
}
}
/**
* Generate code for unwrapping a return value of the given type from the invocation handler's "invoke" method
* (as type Object) to its correct type. The code is written to the supplied stream.
*/
private void codeUnwrapReturnValue(Class<?> type, DataOutputStream out) throws IOException {
if (type.isPrimitive()) {
PrimitiveTypeInfo prim = PrimitiveTypeInfo.get(type);
out.writeByte(opc_checkcast);
out.writeShort(cp.getClass(prim.wrapperClassName));
out.writeByte(opc_invokevirtual);
out.writeShort(cp.getMethodRef(prim.wrapperClassName, prim.unwrapMethodName, prim.unwrapMethodDesc));
if (type == int.class || type == boolean.class || type == byte.class || type == char.class
|| type == short.class) {
out.writeByte(opc_ireturn);
} else if (type == long.class) {
out.writeByte(opc_lreturn);
} else if (type == float.class) {
out.writeByte(opc_freturn);
} else if (type == double.class) {
out.writeByte(opc_dreturn);
} else {
throw new AssertionError();
}
} else {
out.writeByte(opc_checkcast);
out.writeShort(cp.getClass(dotToSlash(type.getName())));
out.writeByte(opc_areturn);
}
}
/**
* Generate code for initializing the static field that stores the Method object for this proxy method. The code
* is written to the supplied stream.
*/
private void codeFieldInitialization(DataOutputStream out) throws IOException {
codeClassForName(fromClass, out);
code_ldc(cp.getString(methodName), out);
code_ipush(parameterTypes.length, out);
out.writeByte(opc_anewarray);
out.writeShort(cp.getClass("java/lang/Class"));
for (int i = 0; i < parameterTypes.length; i++) {
out.writeByte(opc_dup);
code_ipush(i, out);
if (parameterTypes[i].isPrimitive()) {
PrimitiveTypeInfo prim = PrimitiveTypeInfo.get(parameterTypes[i]);
out.writeByte(opc_getstatic);
out.writeShort(cp.getFieldRef(prim.wrapperClassName, "TYPE", "Ljava/lang/Class;"));
} else {
codeClassForName(parameterTypes[i], out);
}
out.writeByte(opc_aastore);
}
out.writeByte(opc_invokevirtual);
out.writeShort(cp.getMethodRef("java/lang/Class", "getMethod", "(Ljava/lang/String;[Ljava/lang/Class;)"
+ "Ljava/lang/reflect/Method;"));
out.writeByte(opc_putstatic);
out.writeShort(cp.getFieldRef(dotToSlash(className), methodFieldName, "Ljava/lang/reflect/Method;"));
}
}
/**
* Generate the constructor method for the proxy class.
*/
private MethodInfo generateConstructor() throws IOException {
MethodInfo minfo = new MethodInfo("<init>", "(Ljava/lang/reflect/InvocationHandler;)V", ACC_PUBLIC);
DataOutputStream out = new DataOutputStream(minfo.code);
code_aload(0, out);
code_aload(1, out);
out.writeByte(opc_invokespecial);
out.writeShort(cp.getMethodRef(superclassName, "<init>", "(Ljava/lang/reflect/InvocationHandler;)V"));
out.writeByte(opc_return);
minfo.maxStack = 10;
minfo.maxLocals = 2;
minfo.declaredExceptions = new short[0];
return minfo;
}
private MethodInfo generateStaticInitializerCaller() throws IOException {
MethodInfo minfo = new MethodInfo("<clinit>", "()V", ACC_STATIC);
DataOutputStream out = new DataOutputStream(minfo.code);
out.writeByte(opc_invokestatic);
out.writeShort(cp.getMethodRef(dotToSlash(className), initMethodName, "()V"));
out.writeByte(opc_return);
minfo.declaredExceptions = new short[0];
return minfo;
}
/**
* Generate the static initializer method for the proxy class.
*/
private MethodInfo generateStaticInitializer() throws IOException {
MethodInfo minfo = new MethodInfo(initMethodName, "()V", ACC_STATIC);
int localSlot0 = 1;
short pc, tryBegin = 0, tryEnd;
DataOutputStream out = new DataOutputStream(minfo.code);
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
for (ProxyMethod pm : sigmethods) {
pm.codeFieldInitialization(out);
}
}
out.writeByte(opc_iconst_1);
out.writeByte(opc_putstatic);
out.writeShort(cp.getFieldRef(dotToSlash(className), initFieldName, "Z"));
out.writeByte(opc_return);
tryEnd = pc = (short) minfo.code.size();
minfo.exceptionTable.add(new ExceptionTableEntry(tryBegin, tryEnd, pc, cp
.getClass("java/lang/NoSuchMethodException")));
code_astore(localSlot0, out);
out.writeByte(opc_new);
out.writeShort(cp.getClass("java/lang/NoSuchMethodError"));
out.writeByte(opc_dup);
code_aload(localSlot0, out);
out.writeByte(opc_invokevirtual);
out.writeShort(cp.getMethodRef("java/lang/Throwable", "getMessage", "()Ljava/lang/String;"));
out.writeByte(opc_invokespecial);
out.writeShort(cp.getMethodRef("java/lang/NoSuchMethodError", "<init>", "(Ljava/lang/String;)V"));
out.writeByte(opc_athrow);
pc = (short) minfo.code.size();
minfo.exceptionTable.add(new ExceptionTableEntry(tryBegin, tryEnd, pc, cp
.getClass("java/lang/ClassNotFoundException")));
code_astore(localSlot0, out);
out.writeByte(opc_new);
out.writeShort(cp.getClass("java/lang/NoClassDefFoundError"));
out.writeByte(opc_dup);
code_aload(localSlot0, out);
out.writeByte(opc_invokevirtual);
out.writeShort(cp.getMethodRef("java/lang/Throwable", "getMessage", "()Ljava/lang/String;"));
out.writeByte(opc_invokespecial);
out.writeShort(cp.getMethodRef("java/lang/NoClassDefFoundError", "<init>", "(Ljava/lang/String;)V"));
out.writeByte(opc_athrow);
if (minfo.code.size() > 65535) {
throw new IllegalArgumentException("code size limit exceeded");
}
minfo.maxStack = 10;
minfo.maxLocals = (short) (localSlot0 + 1);
minfo.declaredExceptions = new short[0];
return minfo;
}
/*
* =============== Code Generation Utility Methods ===============
*/
/*
* The following methods generate code for the load or store operation indicated by their name for the given local
* variable. The code is written to the supplied stream.
*/
private void code_iload(int lvar, DataOutputStream out) throws IOException {
codeLocalLoadStore(lvar, opc_iload, opc_iload_0, out);
}
private void code_lload(int lvar, DataOutputStream out) throws IOException {
codeLocalLoadStore(lvar, opc_lload, opc_lload_0, out);
}
private void code_fload(int lvar, DataOutputStream out) throws IOException {
codeLocalLoadStore(lvar, opc_fload, opc_fload_0, out);
}
private void code_dload(int lvar, DataOutputStream out) throws IOException {
codeLocalLoadStore(lvar, opc_dload, opc_dload_0, out);
}
private void code_aload(int lvar, DataOutputStream out) throws IOException {
codeLocalLoadStore(lvar, opc_aload, opc_aload_0, out);
}
// private void code_istore(int lvar, DataOutputStream out)
// throws IOException
// {
// codeLocalLoadStore(lvar, opc_istore, opc_istore_0, out);
// }
// private void code_lstore(int lvar, DataOutputStream out)
// throws IOException
// {
// codeLocalLoadStore(lvar, opc_lstore, opc_lstore_0, out);
// }
// private void code_fstore(int lvar, DataOutputStream out)
// throws IOException
// {
// codeLocalLoadStore(lvar, opc_fstore, opc_fstore_0, out);
// }
// private void code_dstore(int lvar, DataOutputStream out)
// throws IOException
// {
// codeLocalLoadStore(lvar, opc_dstore, opc_dstore_0, out);
// }
private void code_astore(int lvar, DataOutputStream out) throws IOException {
codeLocalLoadStore(lvar, opc_astore, opc_astore_0, out);
}
/**
* Generate code for a load or store instruction for the given local variable. The code is written to the supplied
* stream.
*
* "opcode" indicates the opcode form of the desired load or store instruction that takes an explicit local variable
* index, and "opcode_0" indicates the corresponding form of the instruction with the implicit index 0.
*/
private void codeLocalLoadStore(int lvar, int opcode, int opcode_0, DataOutputStream out) throws IOException {
assert lvar >= 0 && lvar <= 0xFFFF;
if (lvar <= 3) {
out.writeByte(opcode_0 + lvar);
} else if (lvar <= 0xFF) {
out.writeByte(opcode);
out.writeByte(lvar & 0xFF);
} else {
/*
* Use the "wide" instruction modifier for local variable indexes that do not fit into an unsigned byte.
*/
out.writeByte(opc_wide);
out.writeByte(opcode);
out.writeShort(lvar & 0xFFFF);
}
}
/**
* Generate code for an "ldc" instruction for the given constant pool index (the "ldc_w" instruction is used if the
* index does not fit into an unsigned byte). The code is written to the supplied stream.
*/
private void code_ldc(int index, DataOutputStream out) throws IOException {
assert index >= 0 && index <= 0xFFFF;
if (index <= 0xFF) {
out.writeByte(opc_ldc);
out.writeByte(index & 0xFF);
} else {
out.writeByte(opc_ldc_w);
out.writeShort(index & 0xFFFF);
}
}
/**
* Generate code to push a constant integer value on to the operand stack, using the "iconst_<i>", "bipush", or
* "sipush" instructions depending on the size of the value. The code is written to the supplied stream.
*/
private void code_ipush(int value, DataOutputStream out) throws IOException {
if (value >= -1 && value <= 5) {
out.writeByte(opc_iconst_0 + value);
} else if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) {
out.writeByte(opc_bipush);
out.writeByte(value & 0xFF);
} else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) {
out.writeByte(opc_sipush);
out.writeShort(value & 0xFFFF);
} else {
throw new AssertionError();
}
}
/**
* Generate code to invoke the Class.forName with the name of the given class to get its Class object at runtime.
* The code is written to the supplied stream. Note that the code generated by this method may caused the checked
* ClassNotFoundException to be thrown.
*/
private void codeClassForName(Class<?> cl, DataOutputStream out) throws IOException {
code_ldc(cp.getString(cl.getName()), out);
out.writeByte(opc_invokestatic);
out.writeShort(cp.getMethodRef("java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;"));
}
/*
* ==================== General Utility Methods ====================
*/
/**
* Convert a fully qualified class name that uses '.' as the package separator, the external representation used by
* the Java language and APIs, to a fully qualified class name that uses '/' as the package separator, the
* representation used in the class file format (see JVMS section 4.2).
*/
private static String dotToSlash(String name) {
return name.replace('.', '/');
}
/**
* Return the "method descriptor" string for a method with the given parameter types and return type. See JVMS
* section 4.3.3.
*/
private static String getMethodDescriptor(Class<?>[] parameterTypes, Class<?> returnType) {
return getParameterDescriptors(parameterTypes) + ((returnType == void.class) ? "V" : getFieldType(returnType));
}
/**
* Return the list of "parameter descriptor" strings enclosed in parentheses corresponding to the given parameter
* types (in other words, a method descriptor without a return descriptor). This string is useful for constructing
* string keys for methods without regard to their return type.
*/
private static String getParameterDescriptors(Class<?>[] parameterTypes) {
StringBuilder desc = new StringBuilder("(");
for (int i = 0; i < parameterTypes.length; i++) {
desc.append(getFieldType(parameterTypes[i]));
}
desc.append(')');
return desc.toString();
}
/**
* Return the "field type" string for the given type, appropriate for a field descriptor, a parameter descriptor, or
* a return descriptor other than "void". See JVMS section 4.3.2.
*/
private static String getFieldType(Class<?> type) {
if (type.isPrimitive()) {
return PrimitiveTypeInfo.get(type).baseTypeString;
} else if (type.isArray()) {
/*
* According to JLS 20.3.2, the getName() method on Class does return the VM type descriptor format for
* array classes (only); using that should be quicker than the otherwise obvious code:
*
* return "[" + getTypeDescriptor(type.getComponentType());
*/
return type.getName().replace('.', '/');
} else {
return "L" + dotToSlash(type.getName()) + ";";
}
}
/**
* Returns a human-readable string representing the signature of a method with the given name and parameter types.
*/
private static String getFriendlyMethodSignature(String name, Class<?>[] parameterTypes) {
StringBuilder sig = new StringBuilder(name);
sig.append('(');
for (int i = 0; i < parameterTypes.length; i++) {
if (i > 0) {
sig.append(',');
}
Class<?> parameterType = parameterTypes[i];
int dimensions = 0;
while (parameterType.isArray()) {
parameterType = parameterType.getComponentType();
dimensions++;
}
sig.append(parameterType.getName());
while (dimensions-- > 0) {
sig.append("[]");
}
}
sig.append(')');
return sig.toString();
}
/**
* Return the number of abstract "words", or consecutive local variable indexes, required to contain a value of the
* given type. See JVMS section 3.6.1.
*
* Note that the original version of the JVMS contained a definition of this abstract notion of a "word" in section
* 3.4, but that definition was removed for the second edition.
*/
private static int getWordsPerType(Class<?> type) {
if (type == long.class || type == double.class) {
return 2;
} else {
return 1;
}
}
/**
* Add to the given list all of the types in the "from" array that are not already contained in the list and are
* assignable to at least one of the types in the "with" array.
*
* This method is useful for computing the greatest common set of declared exceptions from duplicate methods
* inherited from different interfaces.
*/
private static void collectCompatibleTypes(Class<?>[] from, Class<?>[] with, List<Class<?>> list) {
for (Class<?> fc : from) {
if (!list.contains(fc)) {
for (Class<?> wc : with) {
if (wc.isAssignableFrom(fc)) {
list.add(fc);
break;
}
}
}
}
}
/**
* Given the exceptions declared in the throws clause of a proxy method, compute the exceptions that need to be
* caught from the invocation handler's invoke method and rethrown intact in the method's implementation before
* catching other Throwables and wrapping them in UndeclaredThrowableExceptions.
*
* The exceptions to be caught are returned in a List object. Each exception in the returned list is guaranteed to
* not be a subclass of any of the other exceptions in the list, so the catch blocks for these exceptions may be
* generated in any order relative to each other.
*
* Error and RuntimeException are each always contained by the returned list (if none of their superclasses are
* contained), since those unchecked exceptions should always be rethrown intact, and thus their subclasses will
* never appear in the returned list.
*
* The returned List will be empty if java.lang.Throwable is in the given list of declared exceptions, indicating
* that no exceptions need to be caught.
*/
private static List<Class<?>> computeUniqueCatchList(Class<?>[] exceptions) {
List<Class<?>> uniqueList = new ArrayList<>();
// unique exceptions to catch
uniqueList.add(Error.class); // always catch/rethrow these
uniqueList.add(RuntimeException.class);
nextException: for (Class<?> ex : exceptions) {
if (ex.isAssignableFrom(Throwable.class)) {
/*
* If Throwable is declared to be thrown by the proxy method, then no catch blocks are necessary,
* because the invoke can, at most, throw Throwable anyway.
*/
uniqueList.clear();
break;
} else if (!Throwable.class.isAssignableFrom(ex)) {
/*
* Ignore types that cannot be thrown by the invoke method.
*/
continue;
}
/*
* Compare this exception against the current list of exceptions that need to be caught:
*/
for (int j = 0; j < uniqueList.size();) {
Class<?> ex2 = uniqueList.get(j);
if (ex2.isAssignableFrom(ex)) {
/*
* if a superclass of this exception is already on the list to catch, then ignore this one and
* continue;
*/
continue nextException;
} else if (ex.isAssignableFrom(ex2)) {
/*
* if a subclass of this exception is on the list to catch, then remove it;
*/
uniqueList.remove(j);
} else {
j++; // else continue comparing.
}
}
// This exception is unique (so far): add it to the list to catch.
uniqueList.add(ex);
}
return uniqueList;
}
/**
* A PrimitiveTypeInfo object contains assorted information about a primitive type in its public fields. The struct
* for a particular primitive type can be obtained using the static "get" method.
*/
private static class PrimitiveTypeInfo {
/** "base type" used in various descriptors (see JVMS section 4.3.2) */
public String baseTypeString;
/** name of corresponding wrapper class */
public String wrapperClassName;
/** method descriptor for wrapper class "valueOf" factory method */
public String wrapperValueOfDesc;
/** name of wrapper class method for retrieving primitive value */
public String unwrapMethodName;
/** descriptor of same method */
public String unwrapMethodDesc;
private static Map<Class<?>, PrimitiveTypeInfo> table = new HashMap<>();
static {
add(byte.class, Byte.class);
add(char.class, Character.class);
add(double.class, Double.class);
add(float.class, Float.class);
add(int.class, Integer.class);
add(long.class, Long.class);
add(short.class, Short.class);
add(boolean.class, Boolean.class);
}
private static void add(Class<?> primitiveClass, Class<?> wrapperClass) {
table.put(primitiveClass, new PrimitiveTypeInfo(primitiveClass, wrapperClass));
}
private PrimitiveTypeInfo(Class<?> primitiveClass, Class<?> wrapperClass) {
assert primitiveClass.isPrimitive();
baseTypeString = Array.newInstance(primitiveClass, 0).getClass().getName().substring(1);
wrapperClassName = dotToSlash(wrapperClass.getName());
wrapperValueOfDesc = "(" + baseTypeString + ")L" + wrapperClassName + ";";
unwrapMethodName = primitiveClass.getName() + "Value";
unwrapMethodDesc = "()" + baseTypeString;
}
public static PrimitiveTypeInfo get(Class<?> cl) {
return table.get(cl);
}
}
/**
* A ConstantPool object represents the constant pool of a class file being generated. This representation of a
* constant pool is designed specifically for use by ProxyGenerator; in particular, it assumes that constant pool
* entries will not need to be resorted (for example, by their type, as the Java compiler does), so that the final
* index value can be assigned and used when an entry is first created.
*
* Note that new entries cannot be created after the constant pool has been written to a class file. To prevent such
* logic errors, a ConstantPool instance can be marked "read only", so that further attempts to add new entries will
* fail with a runtime exception.
*
* See JVMS section 4.4 for more information about the constant pool of a class file.
*/
private static class ConstantPool {
/**
* list of constant pool entries, in constant pool index order.
*
* This list is used when writing the constant pool to a stream and for assigning the next index value. Note
* that element 0 of this list corresponds to constant pool index 1.
*/
private List<Entry> pool = new ArrayList<>(32);
/**
* maps constant pool data of all types to constant pool indexes.
*
* This map is used to look up the index of an existing entry for values of all types.
*/
private Map<Object, Short> map = new HashMap<>(16);
/** true if no new constant pool entries may be added */
private boolean readOnly = false;
/**
* Get or assign the index for a CONSTANT_Utf8 entry.
*/
public short getUtf8(String s) {
if (s == null) {
throw new NullPointerException();
}
return getValue(s);
}
/**
* Get or assign the index for a CONSTANT_Integer entry.
*/
public short getInteger(int i) {
return getValue(new Integer(i));
}
/**
* Get or assign the index for a CONSTANT_Float entry.
*/
public short getFloat(float f) {
return getValue(new Float(f));
}
/**
* Get or assign the index for a CONSTANT_Class entry.
*/
public short getClass(String name) {
short utf8Index = getUtf8(name);
return getIndirect(new IndirectEntry(CONSTANT_CLASS, utf8Index));
}
/**
* Get or assign the index for a CONSTANT_String entry.
*/
public short getString(String s) {
short utf8Index = getUtf8(s);
return getIndirect(new IndirectEntry(CONSTANT_STRING, utf8Index));
}
/**
* Get or assign the index for a CONSTANT_FieldRef entry.
*/
public short getFieldRef(String className, String name, String descriptor) {
short classIndex = getClass(className);
short nameAndTypeIndex = getNameAndType(name, descriptor);
return getIndirect(new IndirectEntry(CONSTANT_FIELD, classIndex, nameAndTypeIndex));
}
/**
* Get or assign the index for a CONSTANT_MethodRef entry.
*/
public short getMethodRef(String className, String name, String descriptor) {
short classIndex = getClass(className);
short nameAndTypeIndex = getNameAndType(name, descriptor);
return getIndirect(new IndirectEntry(CONSTANT_METHOD, classIndex, nameAndTypeIndex));
}
/**
* Get or assign the index for a CONSTANT_InterfaceMethodRef entry.
*/
public short getInterfaceMethodRef(String className, String name, String descriptor) {
short classIndex = getClass(className);
short nameAndTypeIndex = getNameAndType(name, descriptor);
return getIndirect(new IndirectEntry(CONSTANT_INTERFACEMETHOD, classIndex, nameAndTypeIndex));
}
/**
* Get or assign the index for a CONSTANT_NameAndType entry.
*/
public short getNameAndType(String name, String descriptor) {
short nameIndex = getUtf8(name);
short descriptorIndex = getUtf8(descriptor);
return getIndirect(new IndirectEntry(CONSTANT_NAMEANDTYPE, nameIndex, descriptorIndex));
}
/**
* Set this ConstantPool instance to be "read only".
*
* After this method has been called, further requests to get an index for a non-existent entry will cause an
* InternalError to be thrown instead of creating of the entry.
*/
public void setReadOnly() {
readOnly = true;
}
/**
* Write this constant pool to a stream as part of the class file format.
*
* This consists of writing the "constant_pool_count" and "constant_pool[]" items of the "ClassFile" structure,
* as described in JVMS section 4.1.
*/
public void write(OutputStream out) throws IOException {
DataOutputStream dataOut = new DataOutputStream(out);
// constant_pool_count: number of entries plus one
dataOut.writeShort(pool.size() + 1);
for (Entry e : pool) {
e.write(dataOut);
}
}
/**
* Add a new constant pool entry and return its index.
*/
private short addEntry(Entry entry) {
pool.add(entry);
/*
* Note that this way of determining the index of the added entry is wrong if this pool supports
* CONSTANT_Long or CONSTANT_Double entries.
*/
if (pool.size() >= 65535) {
throw new IllegalArgumentException("constant pool size limit exceeded");
}
return (short) pool.size();
}
/**
* Get or assign the index for an entry of a type that contains a direct value. The type of the given object
* determines the type of the desired entry as follows:
*
* java.lang.String CONSTANT_Utf8 java.lang.Integer CONSTANT_Integer java.lang.Float CONSTANT_Float
* java.lang.Long CONSTANT_Long java.lang.Double CONSTANT_DOUBLE
*/
private short getValue(Object key) {
Short index = map.get(key);
if (index != null) {
return index.shortValue();
} else {
if (readOnly) {
throw new InternalError("late constant pool addition: " + key);
}
short i = addEntry(new ValueEntry(key));
map.put(key, new Short(i));
return i;
}
}
/**
* Get or assign the index for an entry of a type that contains references to other constant pool entries.
*/
private short getIndirect(IndirectEntry e) {
Short index = map.get(e);
if (index != null) {
return index.shortValue();
} else {
if (readOnly) {
throw new InternalError("late constant pool addition");
}
short i = addEntry(e);
map.put(e, new Short(i));
return i;
}
}
/**
* Entry is the abstact superclass of all constant pool entry types that can be stored in the "pool" list; its
* purpose is to define a common method for writing constant pool entries to a class file.
*/
private static abstract class Entry {
public abstract void write(DataOutputStream out) throws IOException;
}
/**
* ValueEntry represents a constant pool entry of a type that contains a direct value (see the comments for the
* "getValue" method for a list of such types).
*
* ValueEntry objects are not used as keys for their entries in the Map "map", so no useful hashCode or equals
* methods are defined.
*/
private static class ValueEntry extends Entry {
private Object value;
public ValueEntry(Object value) {
this.value = value;
}
public void write(DataOutputStream out) throws IOException {
if (value instanceof String) {
out.writeByte(CONSTANT_UTF8);
out.writeUTF((String) value);
} else if (value instanceof Integer) {
out.writeByte(CONSTANT_INTEGER);
out.writeInt(((Integer) value).intValue());
} else if (value instanceof Float) {
out.writeByte(CONSTANT_FLOAT);
out.writeFloat(((Float) value).floatValue());
} else if (value instanceof Long) {
out.writeByte(CONSTANT_LONG);
out.writeLong(((Long) value).longValue());
} else if (value instanceof Double) {
out.writeDouble(CONSTANT_DOUBLE);
out.writeDouble(((Double) value).doubleValue());
} else {
throw new InternalError("bogus value entry: " + value);
}
}
}
/**
* IndirectEntry represents a constant pool entry of a type that references other constant pool entries, i.e.,
* the following types:
*
* CONSTANT_Class, CONSTANT_String, CONSTANT_Fieldref, CONSTANT_Methodref, CONSTANT_InterfaceMethodref, and
* CONSTANT_NameAndType.
*
* Each of these entry types contains either one or two indexes of other constant pool entries.
*
* IndirectEntry objects are used as the keys for their entries in the Map "map", so the hashCode and equals
* methods are overridden to allow matching.
*/
private static class IndirectEntry extends Entry {
private int tag;
private short index0;
private short index1;
/**
* Construct an IndirectEntry for a constant pool entry type that contains one index of another entry.
*/
public IndirectEntry(int tag, short index) {
this.tag = tag;
this.index0 = index;
this.index1 = 0;
}
/**
* Construct an IndirectEntry for a constant pool entry type that contains two indexes for other entries.
*/
public IndirectEntry(int tag, short index0, short index1) {
this.tag = tag;
this.index0 = index0;
this.index1 = index1;
}
public void write(DataOutputStream out) throws IOException {
out.writeByte(tag);
out.writeShort(index0);
/*
* If this entry type contains two indexes, write out the second, too.
*/
if (tag == CONSTANT_FIELD || tag == CONSTANT_METHOD || tag == CONSTANT_INTERFACEMETHOD
|| tag == CONSTANT_NAMEANDTYPE) {
out.writeShort(index1);
}
}
public int hashCode() {
return tag + index0 + index1;
}
public boolean equals(Object obj) {
if (obj instanceof IndirectEntry) {
IndirectEntry other = (IndirectEntry) obj;
if (tag == other.tag && index0 == other.index0 && index1 == other.index1) {
return true;
}
}
return false;
}
}
}
}
| gpl-2.0 |
tlist/asian-crush-backup | wp-content/plugins/user-role-editor/js/ure-js.js | 10971 | // get/post via jQuery
(function($) {
$.extend({
ure_getGo: function(url, params) {
document.location = url + '?' + $.param(params);
},
ure_postGo: function(url, params) {
var $form = $("<form>")
.attr("method", "post")
.attr("action", url);
$.each(params, function(name, value) {
$("<input type='hidden'>")
.attr("name", name)
.attr("value", value)
.appendTo($form);
});
$form.appendTo("body");
$form.submit();
}
});
})(jQuery);
jQuery(function() {
jQuery("#ure_select_all").button({
label: ure_data.select_all
}).click(function(event){
event.preventDefault();
ure_select_all(1);
});
if (typeof ure_current_role === 'undefined' || 'administrator' !== ure_current_role ) {
jQuery("#ure_unselect_all").button({
label: ure_data.unselect_all
}).click(function(event){
event.preventDefault();
ure_select_all(0);
});
jQuery("#ure_reverse_selection").button({
label: ure_data.reverse
}).click(function(event){
event.preventDefault();
ure_select_all(-1);
});
}
jQuery("#ure_update_role").button({
label: ure_data.update
}).click(function(){
if (!confirm(ure_data.confirm_submit)) {
return false;
}
jQuery('#ure_form').submit();
});
jQuery("#ure_add_role").button({
label: ure_data.add_role
}).click(function(event){
event.preventDefault();
jQuery(function($) {
$info = $('#ure_add_role_dialog');
$info.dialog({
dialogClass: 'wp-dialog',
modal: true,
autoOpen: true,
closeOnEscape: true,
width: 320,
height: 190,
resizable: false,
title: ure_data.add_new_role_title,
'buttons' : {
'Add Role': function () {
var role_id = $('#user_role_id').val();
if (role_id == '') {
alert( ure_data.role_name_required );
return false;
}
if (!(/^[\w-]*$/.test(role_id))) {
alert( ure_data.role_name_valid_chars );
return false;
}
var role_name = $('#user_role_name').val();
var role_copy_from = $('#user_role_copy_from').val();
$(this).dialog('close');
$.ure_postGo( ure_data.page_url,
{ action: 'add-new-role', user_role_id: role_id, user_role_name: role_name, user_role_copy_from: role_copy_from,
ure_nonce: ure_data.wp_nonce} );
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
$('.ui-dialog-buttonpane button:contains("Add Role")').attr("id", "dialog-add-role-button");
$('#dialog-add_role-button').html(ure_data.add_role);
$('.ui-dialog-buttonpane button:contains("Cancel")').attr("id", "dialog-cancel-button");
$('#dialog-cancel-button').html(ure_data.cancel);
});
});
jQuery("#ure_delete_role").button({
label: ure_data.delete_role
}).click(function(event){
event.preventDefault();
jQuery(function($) {
$('#ure_delete_role_dialog').dialog({
dialogClass: 'wp-dialog',
modal: true,
autoOpen: true,
closeOnEscape: true,
width: 320,
height: 190,
resizable: false,
title: ure_data.delete_role,
buttons: {
'Delete Role': function() {
var user_role_id = $('#del_user_role').val();
if (!confirm(ure_data.delete_role)) {
return false;
}
$(this).dialog('close');
$.ure_postGo(ure_data.page_url,
{action: 'delete-role', user_role_id: user_role_id, ure_nonce: ure_data.wp_nonce});
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
// translate buttons caption
$('.ui-dialog-buttonpane button:contains("Delete Role")').attr("id", "dialog-delete-button");
$('#dialog-delete-button').html(ure_data.delete);
$('.ui-dialog-buttonpane button:contains("Cancel")').attr("id", "dialog-cancel-button");
$('#dialog-cancel-button').html(ure_data.cancel);
});
});
jQuery("#ure_add_capability").button({
label: ure_data.add_capability
}).click(function(event){
event.preventDefault();
jQuery(function($) {
$info = $('#ure_add_capability_dialog');
$info.dialog({
dialogClass: 'wp-dialog',
modal: true,
autoOpen: true,
closeOnEscape: true,
width: 320,
height: 190,
resizable: false,
title: ure_data.add_capability,
'buttons' : {
'Add Capability': function () {
var capability_id = $('#capability_id').val();
if (capability_id == '') {
alert( ure_data.capability_name_required );
return false;
}
if (!(/^[\w-]*$/.test(capability_id))) {
alert( ure_data.capability_name_valid_chars );
return false;
}
$(this).dialog('close');
$.ure_postGo( ure_data.page_url,
{ action: 'add-new-capability', capability_id: capability_id, ure_nonce: ure_data.wp_nonce} );
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
$('.ui-dialog-buttonpane button:contains("Add Capability")').attr("id", "dialog-add-capability-button");
$('#dialog-add_capability-button').html(ure_data.add_capability);
$('.ui-dialog-buttonpane button:contains("Cancel")').attr("id", "dialog-cancel-button");
$('#dialog-cancel-button').html(ure_data.cancel);
});
});
jQuery("#ure_delete_capability").button({
label: ure_data.delete_capability
}).click(function(event){
event.preventDefault();
jQuery(function($) {
$('#ure_delete_capability_dialog').dialog({
dialogClass: 'wp-dialog',
modal: true,
autoOpen: true,
closeOnEscape: true,
width: 320,
height: 190,
resizable: false,
title: ure_data.delete_capability,
buttons: {
'Delete Capability': function() {
if (!confirm(ure_data.delete_capability +' - '+ ure_data.delete_capability_warning)) {
return;
}
$(this).dialog('close');
var user_capability_id = $('#remove_user_capability').val();
$.ure_postGo(ure_data.page_url,
{action: 'delete-user-capability', user_capability_id: user_capability_id, ure_nonce: ure_data.wp_nonce});
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
// translate buttons caption
$('.ui-dialog-buttonpane button:contains("Delete Capability")').attr("id", "dialog-delete-capability-button");
$('#dialog-delete-capability-button').html(ure_data.delete_capability);
$('.ui-dialog-buttonpane button:contains("Cancel")').attr("id", "dialog-cancel-button");
$('#dialog-cancel-button').html(ure_data.cancel);
});
});
jQuery("#ure_default_role").button({
label: ure_data.default_role
}).click(function(event){
event.preventDefault();
jQuery(function($) {
$('#ure_default_role_dialog').dialog({
dialogClass: 'wp-dialog',
modal: true,
autoOpen: true,
closeOnEscape: true,
width: 320,
height: 190,
resizable: false,
title: ure_data.default_role,
buttons: {
'Set New Default Role': function() {
$(this).dialog('close');
var user_role_id = $('#default_user_role').val();
$.ure_postGo(ure_data.page_url,
{action: 'change-default-role', user_role_id: user_role_id, ure_nonce: ure_data.wp_nonce});
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
// translate buttons caption
$('.ui-dialog-buttonpane button:contains("Set New Default Role")').attr("id", "dialog-default-role-button");
$('#dialog-default-role-button').html(ure_data.delete);
$('.ui-dialog-buttonpane button:contains("Cancel")').attr("id", "dialog-cancel-button");
$('#dialog-cancel-button').html(ure_data.cancel);
});
});
jQuery("#ure_reset_roles").button({
label: ure_data.reset
}).click(function(){
if (!confirm( ure_data.reset_warning )) {
return false;
}
jQuery.ure_postGo(ure_data.page_url, {action: 'reset', ure_nonce: ure_data.wp_nonce});
});
});
// change color of apply to all check box - for multi-site setup only
function ure_applyToAllOnClick(cb) {
el = document.getElementById('ure_apply_to_all_div');
if (cb.checked) {
el.style.color = '#FF0000';
} else {
el.style.color = '#000000';
}
}
// end of ure_applyToAllOnClick()
// turn on checkbox back if clicked to turn off
function turn_it_back(control) {
control.checked = true;
}
// end of turn_it_back()
/**
* Manipulate mass capability checkboxes selection
* @param {bool} selected
* @returns {none}
*/
function ure_select_all(selected) {
var form = document.getElementById('ure_form');
for (i = 0; i < form.elements.length; i++) {
el = form.elements[i];
if (el.type !== 'checkbox') {
continue;
}
if (el.name === 'ure_caps_readable' || el.name === 'ure_show_deprecated_caps' || el.disabled ||
el.name.substr(0, 8) === 'wp_role_') {
continue;
}
if (selected >= 0) {
form.elements[i].checked = selected;
} else {
form.elements[i].checked = !form.elements[i].checked;
}
}
}
// end of ure_select_all()
function ure_turn_caps_readable(user_id) {
if (user_id === 0) {
var ure_object = 'role';
} else {
var ure_object = 'user';
}
jQuery.ure_postGo(ure_data.page_url, {action: 'caps-readable', object: ure_object, user_id: user_id, ure_nonce: ure_data.wp_nonce});
}
// end of ure_turn_caps_readable()
function ure_turn_deprecated_caps(user_id) {
if (user_id === 0) {
var ure_object = 'role';
} else {
var ure_object = 'user';
}
jQuery.ure_postGo(ure_data.page_url, {action: 'show-deprecated-caps', object: ure_object, user_id: user_id, ure_nonce: ure_data.wp_nonce});
}
// ure_turn_deprecated_caps()
function ure_role_change(role_name) {
jQuery.ure_postGo(ure_data.page_url, {action: 'role-change', object: 'role', user_role: role_name, ure_nonce: ure_data.wp_nonce});
}
// end of ure_role_change() | gpl-2.0 |
NewRoute/glfusion | private/vendor/james-heinrich/getid3/getid3/module.graphic.gif.php | 8817 | <?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
// also https://github.com/JamesHeinrich/getID3 //
/////////////////////////////////////////////////////////////////
// See readme.txt for more details //
/////////////////////////////////////////////////////////////////
// //
// module.graphic.gif.php //
// module for analyzing GIF Image files //
// dependencies: NONE //
// ///
/////////////////////////////////////////////////////////////////
// https://www.w3.org/Graphics/GIF/spec-gif89a.txt
// http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp
class getid3_gif extends getid3_handler
{
public function Analyze() {
$info = &$this->getid3->info;
$info['fileformat'] = 'gif';
$info['video']['dataformat'] = 'gif';
$info['video']['lossless'] = true;
$info['video']['pixel_aspect_ratio'] = (float) 1;
$this->fseek($info['avdataoffset']);
$GIFheader = $this->fread(13);
$offset = 0;
$info['gif']['header']['raw']['identifier'] = substr($GIFheader, $offset, 3);
$offset += 3;
$magic = 'GIF';
if ($info['gif']['header']['raw']['identifier'] != $magic) {
$this->error('Expecting "'.getid3_lib::PrintHexBytes($magic).'" at offset '.$info['avdataoffset'].', found "'.getid3_lib::PrintHexBytes($info['gif']['header']['raw']['identifier']).'"');
unset($info['fileformat']);
unset($info['gif']);
return false;
}
$info['gif']['header']['raw']['version'] = substr($GIFheader, $offset, 3);
$offset += 3;
$info['gif']['header']['raw']['width'] = getid3_lib::LittleEndian2Int(substr($GIFheader, $offset, 2));
$offset += 2;
$info['gif']['header']['raw']['height'] = getid3_lib::LittleEndian2Int(substr($GIFheader, $offset, 2));
$offset += 2;
$info['gif']['header']['raw']['flags'] = getid3_lib::LittleEndian2Int(substr($GIFheader, $offset, 1));
$offset += 1;
$info['gif']['header']['raw']['bg_color_index'] = getid3_lib::LittleEndian2Int(substr($GIFheader, $offset, 1));
$offset += 1;
$info['gif']['header']['raw']['aspect_ratio'] = getid3_lib::LittleEndian2Int(substr($GIFheader, $offset, 1));
$offset += 1;
$info['video']['resolution_x'] = $info['gif']['header']['raw']['width'];
$info['video']['resolution_y'] = $info['gif']['header']['raw']['height'];
$info['gif']['version'] = $info['gif']['header']['raw']['version'];
$info['gif']['header']['flags']['global_color_table'] = (bool) ($info['gif']['header']['raw']['flags'] & 0x80);
if ($info['gif']['header']['raw']['flags'] & 0x80) {
// Number of bits per primary color available to the original image, minus 1
$info['gif']['header']['bits_per_pixel'] = 3 * ((($info['gif']['header']['raw']['flags'] & 0x70) >> 4) + 1);
} else {
$info['gif']['header']['bits_per_pixel'] = 0;
}
$info['gif']['header']['flags']['global_color_sorted'] = (bool) ($info['gif']['header']['raw']['flags'] & 0x40);
if ($info['gif']['header']['flags']['global_color_table']) {
// the number of bytes contained in the Global Color Table. To determine that
// actual size of the color table, raise 2 to [the value of the field + 1]
$info['gif']['header']['global_color_size'] = pow(2, ($info['gif']['header']['raw']['flags'] & 0x07) + 1);
$info['video']['bits_per_sample'] = ($info['gif']['header']['raw']['flags'] & 0x07) + 1;
} else {
$info['gif']['header']['global_color_size'] = 0;
}
if ($info['gif']['header']['raw']['aspect_ratio'] != 0) {
// Aspect Ratio = (Pixel Aspect Ratio + 15) / 64
$info['gif']['header']['aspect_ratio'] = ($info['gif']['header']['raw']['aspect_ratio'] + 15) / 64;
}
if ($info['gif']['header']['flags']['global_color_table']) {
$GIFcolorTable = $this->fread(3 * $info['gif']['header']['global_color_size']);
$offset = 0;
for ($i = 0; $i < $info['gif']['header']['global_color_size']; $i++) {
$red = getid3_lib::LittleEndian2Int(substr($GIFcolorTable, $offset++, 1));
$green = getid3_lib::LittleEndian2Int(substr($GIFcolorTable, $offset++, 1));
$blue = getid3_lib::LittleEndian2Int(substr($GIFcolorTable, $offset++, 1));
$info['gif']['global_color_table'][$i] = (($red << 16) | ($green << 8) | ($blue));
}
}
// Image Descriptor
while (!feof($this->getid3->fp)) {
$NextBlockTest = $this->fread(1);
switch ($NextBlockTest) {
/*
case ',': // ',' - Image separator character
$ImageDescriptorData = $NextBlockTest.$this->fread(9);
$ImageDescriptor = array();
$ImageDescriptor['image_left'] = getid3_lib::LittleEndian2Int(substr($ImageDescriptorData, 1, 2));
$ImageDescriptor['image_top'] = getid3_lib::LittleEndian2Int(substr($ImageDescriptorData, 3, 2));
$ImageDescriptor['image_width'] = getid3_lib::LittleEndian2Int(substr($ImageDescriptorData, 5, 2));
$ImageDescriptor['image_height'] = getid3_lib::LittleEndian2Int(substr($ImageDescriptorData, 7, 2));
$ImageDescriptor['flags_raw'] = getid3_lib::LittleEndian2Int(substr($ImageDescriptorData, 9, 1));
$ImageDescriptor['flags']['use_local_color_map'] = (bool) ($ImageDescriptor['flags_raw'] & 0x80);
$ImageDescriptor['flags']['image_interlaced'] = (bool) ($ImageDescriptor['flags_raw'] & 0x40);
$info['gif']['image_descriptor'][] = $ImageDescriptor;
if ($ImageDescriptor['flags']['use_local_color_map']) {
$this->warning('This version of getID3() cannot parse local color maps for GIFs');
return true;
}
$RasterData = array();
$RasterData['code_size'] = getid3_lib::LittleEndian2Int($this->fread(1));
$RasterData['block_byte_count'] = getid3_lib::LittleEndian2Int($this->fread(1));
$info['gif']['raster_data'][count($info['gif']['image_descriptor']) - 1] = $RasterData;
$CurrentCodeSize = $RasterData['code_size'] + 1;
for ($i = 0; $i < pow(2, $RasterData['code_size']); $i++) {
$DefaultDataLookupTable[$i] = chr($i);
}
$DefaultDataLookupTable[pow(2, $RasterData['code_size']) + 0] = ''; // Clear Code
$DefaultDataLookupTable[pow(2, $RasterData['code_size']) + 1] = ''; // End Of Image Code
$NextValue = $this->GetLSBits($CurrentCodeSize);
echo 'Clear Code: '.$NextValue.'<BR>';
$NextValue = $this->GetLSBits($CurrentCodeSize);
echo 'First Color: '.$NextValue.'<BR>';
$Prefix = $NextValue;
$i = 0;
while ($i++ < 20) {
$NextValue = $this->GetLSBits($CurrentCodeSize);
echo $NextValue.'<br>';
}
echo 'escaping<br>';
return true;
break;
*/
case '!':
// GIF Extension Block
$ExtensionBlockData = $NextBlockTest.$this->fread(2);
$ExtensionBlock = array();
$ExtensionBlock['function_code'] = getid3_lib::LittleEndian2Int(substr($ExtensionBlockData, 1, 1));
$ExtensionBlock['byte_length'] = getid3_lib::LittleEndian2Int(substr($ExtensionBlockData, 2, 1));
$ExtensionBlock['data'] = (($ExtensionBlock['byte_length'] > 0) ? $this->fread($ExtensionBlock['byte_length']) : null);
if (substr($ExtensionBlock['data'], 0, 11) == 'NETSCAPE2.0') { // Netscape Application Block (NAB)
$ExtensionBlock['data'] .= $this->fread(4);
if (substr($ExtensionBlock['data'], 11, 2) == "\x03\x01") {
$info['gif']['animation']['animated'] = true;
$info['gif']['animation']['loop_count'] = getid3_lib::LittleEndian2Int(substr($ExtensionBlock['data'], 13, 2));
} else {
$this->warning('Expecting 03 01 at offset '.($this->ftell() - 4).', found "'.getid3_lib::PrintHexBytes(substr($ExtensionBlock['data'], 11, 2)).'"');
}
}
$info['gif']['extension_blocks'][] = $ExtensionBlock;
break;
case ';':
$info['gif']['terminator_offset'] = $this->ftell() - 1;
// GIF Terminator
break;
default:
break;
}
}
return true;
}
public function GetLSBits($bits) {
static $bitbuffer = '';
while (strlen($bitbuffer) < $bits) {
$bitbuffer = str_pad(decbin(ord($this->fread(1))), 8, '0', STR_PAD_LEFT).$bitbuffer;
}
$value = bindec(substr($bitbuffer, 0 - $bits));
$bitbuffer = substr($bitbuffer, 0, 0 - $bits);
return $value;
}
}
| gpl-2.0 |
yeKcim/warmux | old/wormux-0.8.5.1/tools/servers/index_server/main.cpp | 4335 | /******************************************************************************
* Wormux is a convivial mass murder game.
* Copyright (C) 2001-2009 Wormux Team.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/resource.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <list>
#include <map>
#include <WSERVER_debug.h>
#include <WSERVER_env.h>
#include "config.h"
#include "client.h"
#include "clock.h"
#include "download.h"
#include "server.h"
#include "sync_slave.h"
#include "stat.h"
// map < version, client >
std::multimap<std::string, Client*> clients;
int main(int /*argc*/, char* /*argv*/[])
{
DPRINT(INFO, "Wormux index server version %i", VERSION);
DPRINT(INFO, "%s", wx_clock.DateStr());
Env::SetConfigClass(config);
Env::SetWorkingDir();
bool local, r;
r = config.Get("local", local);
if (!r)
TELL_ERROR;
if (!local)
DownloadServerList();
Env::SetChroot();
Env::MaskSigPipe();
// Set the maximum number of connection
Env::SetMaxConnection();
stats.Init();
int port = 0;
config.Get("port", port);
Server listen_sock(port);
// Set of socket where an activity have been detected
fd_set acting_sock_set;
if (!local)
sync_slave.Start();
while(1)
{
wx_clock.HandleJobs(local);
sync_slave.CheckGames();
struct timeval timeout;
memset(&timeout, 0, sizeof(timeout));
timeout.tv_sec = 1;
timeout.tv_usec = 0;
acting_sock_set = listen_sock.GetSockSet();
// Lock the process until activity is detected
if ( select(FD_SETSIZE, &acting_sock_set, NULL, NULL, &timeout) < 1 )
{
// Timeout to check for other games on other servers
if(timeout.tv_sec != 0 && timeout.tv_usec != 0)
TELL_ERROR;
}
// Find the socket where activity have been detected:
// First check for already established connections
for(std::multimap<std::string,Client*>::iterator client = clients.begin();
client != clients.end();
++client)
{
client->second->CheckState();
if( ! client->second->connected )
{
// Connection closed
DPRINT(CONN, "Closind FD %u from client %p\n", client->second->GetFD(), client->second);
listen_sock.CloseConnection( client->second->GetFD() );
delete client->second;
clients.erase(client);
DPRINT(CONN, "%i connections up!", (int)clients.size());
break;
}
if( FD_ISSET( client->second->GetFD(), &acting_sock_set) )
{
if( ! client->second->Receive() ) {
DPRINT(CONN, "Nothing received from client %p, disconnecting!", client->second);
client->second->connected = false;
}
// Exit as the clients list may have changed
break;
}
}
// Then check if there is any new incoming connection
if( FD_ISSET(listen_sock.GetFD(), &acting_sock_set) )
{
Client* client = listen_sock.NewConnection();
if(client != NULL)
clients.insert(std::make_pair("unknown", client ));
DPRINT(CONN, "%i connections up!", (int)clients.size());
// Exit as the 'clients' list may have changed
}
}
}
| gpl-2.0 |
ePubViet/epubweb | components/com_kunena/models/topics.php | 13912 | <?php
/**
* Kunena Component
* @package Kunena.Site
* @subpackage Models
*
* @copyright (C) 2008 - 2014 Kunena Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @link http://www.kunena.org
**/
defined ( '_JEXEC' ) or die ();
/**
* Topics Model for Kunena
*
* @since 2.0
*/
class KunenaModelTopics extends KunenaModel {
protected $topics = false;
protected $messages = false;
protected $total = 0;
protected $topicActions = false;
protected $actionMove = false;
protected function populateState() {
$params = $this->getParameters();
$this->setState ( 'params', $params );
$format = $this->getWord ( 'format', 'html' );
$this->setState ( 'format', $format );
$active = $this->app->getMenu ()->getActive ();
$active = $active ? (int) $active->id : 0;
$layout = $this->getWord ( 'layout', 'default' );
$this->setState ( 'layout', $layout );
$userid = $this->getInt ( 'userid', -1 );
if ($userid < 0) {
$userid = $this->me->userid;
} elseif($userid > 0) {
$userid = KunenaFactory::getUser($userid)->userid;
} else {
$userid = 0;
}
$this->setState ( 'user', $userid );
$mode = $this->getWord ( 'mode', 'default' );
$this->setState ( 'list.mode', $mode );
$modetype = $this->getWord ( 'modetype', '' );
$this->setState ( 'list.modetype', $modetype );
$catid = $this->getInt ( 'catid' );
if ($catid) {
$latestcategory = array($catid);
$latestcategory_in = true;
} else {
if (JFactory::getDocument()->getType() != 'feed') {
// Get configuration from menu item.
$latestcategory = $params->get('topics_categories', '');
$latestcategory_in = $params->get('topics_catselection', '');
// Make sure that category list is an array.
if (!is_array($latestcategory)) $latestcategory = explode ( ',', $latestcategory );
// Default to global configuration.
if (in_array('', $latestcategory, true)) $latestcategory = $this->config->latestcategory;
if ($latestcategory_in == '') $latestcategory_in = $this->config->latestcategory_in;
} else {
// Use RSS configuration.
if(!empty($this->config->rss_excluded_categories)) {
$latestcategory = $this->config->rss_excluded_categories;
$latestcategory_in = 0;
} else {
$latestcategory = $this->config->rss_included_categories;
$latestcategory_in = 1;
}
}
if (!is_array($latestcategory)) $latestcategory = explode ( ',', $latestcategory );
if (empty($latestcategory) || in_array(0, $latestcategory)) {
$latestcategory = false;
}
}
$this->setState ( 'list.categories', $latestcategory );
$this->setState ( 'list.categories.in', $latestcategory_in );
// Selection time.
if (JFactory::getDocument()->getType() != 'feed') {
// Selection time from user state / menu item / url parameter / configuration.
$value = $this->getUserStateFromRequest ( "com_kunena.topics_{$active}_{$layout}_{$mode}_{$userid}_{$catid}_list_time", 'sel', $params->get('topics_time', $this->config->show_list_time), 'int' );
$this->setState ( 'list.time', (int) $value );
} else {
// Selection time.
$value = $this->getInt ('sel', $this->config->rss_timelimit);
$this->setState ( 'list.time', $value );
}
// List state information
$value = $this->getUserStateFromRequest ( "com_kunena.topics_{$active}_{$layout}_{$mode}_{$userid}_{$catid}_list_limit", 'limit', 0, 'int' );
if ($value < 1 || $value > 100) $value = $this->config->threads_per_page;
$this->setState ( 'list.limit', $value );
//$value = $this->getUserStateFromRequest ( "com_kunena.topics_{$active}_{$layout}_{$mode}_list_ordering", 'filter_order', 'time', 'cmd' );
//$this->setState ( 'list.ordering', $value );
$value = $this->getUserStateFromRequest ( "com_kunena.topics_{$active}_{$layout}_{$mode}_{$userid}_{$catid}_list_start", 'limitstart', 0, 'int' );
//$value = $this->getInt ( 'limitstart', 0 );
$this->setState ( 'list.start', $value );
$value = $this->getUserStateFromRequest ( "com_kunena.topics_{$active}_{$layout}_{$mode}_{$userid}_{$catid}_list_direction", 'filter_order_Dir', 'desc', 'word' );
if ($value != 'asc')
$value = 'desc';
$this->setState ( 'list.direction', $value );
}
public function getTopics() {
if ($this->topics === false) {
$layout = $this->getState ( 'layout' );
$mode = $this->getState('list.mode');
if ($mode == 'plugin') {
$pluginmode = $this->getState('list.modetype');
if(!empty($pluginmode)) {
$total = 0;
$topics = false;
JPluginHelper::importPlugin('kunena');
$dispatcher = JDispatcher::getInstance();
$dispatcher->trigger('onKunenaGetTopics', array($layout, $pluginmode, &$topics, &$total, $this));
if(!empty($topics)) {
$this->topics = $topics;
$this->total = $total;
$this->_common ();
}
}
}
if ($this->topics === false) {
switch ($layout) {
case 'user':
$this->getUserTopics();
break;
default:
$this->getRecentTopics();
}
}
}
return $this->topics;
}
protected function getRecentTopics() {
$catid = $this->getState ( 'item.id' );
$limitstart = $this->getState ( 'list.start' );
$limit = $this->getState ( 'list.limit' );
$time = $this->getState ( 'list.time' );
if ($time < 0) {
$time = 0;
} elseif ($time == 0) {
$time = KunenaFactory::getSession ()->lasttime;
} else {
$time = JFactory::getDate ()->toUnix () - ($time * 3600);
}
$latestcategory = $this->getState ( 'list.categories' );
$latestcategory_in = $this->getState ( 'list.categories.in' );
$hold = 0;
$where = '';
$lastpost = true;
// Reset topics.
$this->total = 0;
$this->topics = array();
switch ($this->getState ( 'list.mode' )) {
case 'topics' :
$lastpost = false;
break;
case 'sticky' :
$where = 'AND tt.ordering>0';
break;
case 'locked' :
$where = 'AND tt.locked>0';
break;
case 'noreplies' :
$where = 'AND tt.posts=1';
break;
case 'unapproved' :
$allowed = KunenaForumCategoryHelper::getCategories(false, false, 'topic.approve');
if (empty($allowed)) {
return;
}
$allowed = implode(',', array_keys($allowed));
$hold = '1';
$where = "AND tt.category_id IN ({$allowed})";
break;
case 'deleted' :
$allowed = KunenaForumCategoryHelper::getCategories(false, false, 'topic.undelete');
if (empty($allowed)) {
return;
}
$allowed = implode(',', array_keys($allowed));
$hold = '2';
$where = "AND tt.category_id IN ({$allowed})";
break;
case 'replies' :
default :
break;
}
$params = array (
'reverse' => ! $latestcategory_in,
'orderby' => $lastpost ? 'tt.last_post_time DESC' : 'tt.first_post_time DESC',
'starttime' => $time,
'hold' => $hold,
'where' => $where );
list ( $this->total, $this->topics ) = KunenaForumTopicHelper::getLatestTopics ( $latestcategory, $limitstart, $limit, $params );
$this->_common ();
}
protected function getUserTopics() {
$catid = $this->getState ( 'item.id' );
$limitstart = $this->getState ( 'list.start' );
$limit = $this->getState ( 'list.limit' );
$latestcategory = $this->getState ( 'list.categories' );
$latestcategory_in = $this->getState ( 'list.categories.in' );
$started = false;
$posts = false;
$favorites = false;
$subscriptions = false;
// Set order by
$orderby = "tt.last_post_time DESC";
switch ($this->getState ( 'list.mode' )) {
case 'posted' :
$posts = true;
$orderby = "ut.last_post_id DESC";
break;
case 'started' :
$started = true;
break;
case 'favorites' :
$favorites = true;
break;
case 'subscriptions' :
$subscriptions = true;
break;
default :
$posts = true;
$favorites = true;
$subscriptions = true;
$orderby = "ut.favorite DESC, tt.last_post_time DESC";
break;
}
$params = array (
'reverse' => ! $latestcategory_in,
'orderby' => $orderby,
'hold' => 0,
'user' => $this->getState ( 'user' ),
'started' => $started,
'posted' => $posts,
'favorited' => $favorites,
'subscribed' => $subscriptions );
list ( $this->total, $this->topics ) = KunenaForumTopicHelper::getLatestTopics ( $latestcategory, $limitstart, $limit, $params );
$this->_common ();
}
protected function getPosts() {
$this->topics = array();
$start = $this->getState ( 'list.start' );
$limit = $this->getState ( 'list.limit' );
// Time will be calculated inside KunenaForumMessageHelper::getLatestMessages()
$time = $this->getState ( 'list.time' );
$params = array();
$params['mode'] = $this->getState ( 'list.mode' );
$params['reverse'] = ! $this->getState ( 'list.categories.in' );
$params['starttime'] = $time;
$params['user'] = $this->getState ( 'user' );
list ($this->total, $this->messages) = KunenaForumMessageHelper::getLatestMessages($this->getState ( 'list.categories' ), $start, $limit, $params);
$topicids = array();
foreach ( $this->messages as $message ) {
$topicids[$message->thread] = $message->thread;
}
$authorise = 'read';
switch ($params['mode']) {
case 'unapproved':
$authorise = 'approve';
break;
case 'deleted':
$authorise = 'undelete';
break;
}
$this->topics = KunenaForumTopicHelper::getTopics ( $topicids, $authorise );
$userlist = $postlist = array();
foreach ( $this->messages as $message ) {
$userlist[intval($message->userid)] = intval($message->userid);
$postlist[intval($message->id)] = intval($message->id);
}
$this->_common($userlist, $postlist);
}
protected function _common(array $userlist = array(), array $postlist = array()) {
if ($this->total > 0) {
// collect user ids for avatar prefetch when integrated
$lastpostlist = array();
foreach ( $this->topics as $topic ) {
$userlist[intval($topic->first_post_userid)] = intval($topic->first_post_userid);
$userlist[intval($topic->last_post_userid)] = intval($topic->last_post_userid);
$lastpostlist[intval($topic->last_post_id)] = intval($topic->last_post_id);
}
// Prefetch all users/avatars to avoid user by user queries during template iterations
if ( !empty($userlist) ) KunenaUserHelper::loadUsers($userlist);
KunenaForumTopicHelper::getUserTopics(array_keys($this->topics));
KunenaForumTopicHelper::getKeywords(array_keys($this->topics));
$lastpostlist += KunenaForumTopicHelper::fetchNewStatus($this->topics);
// Fetch last / new post positions when user can see unapproved or deleted posts
$me = KunenaUserHelper::get();
if ($postlist || ($lastpostlist && $me->userid && ($this->me->isAdmin() || KunenaAccess::getInstance()->getModeratorStatus()))) {
KunenaForumMessageHelper::loadLocation($postlist + $lastpostlist);
}
}
}
public function getMessages() {
if ($this->topics === false) {
$this->getPosts();
}
return $this->messages;
}
public function getTotal() {
if ($this->topics === false) {
$this->getTopics();
}
return $this->total;
}
public function getTopicActions() {
if ($this->topics === false) {
$this->getTopics();
}
$delete = $approve = $undelete = $move = $permdelete = false;
foreach ($this->topics as $topic) {
if (!$delete && $topic->authorise('delete')) $delete = true;
if (!$approve && $topic->authorise('approve')) $approve = true;
if (!$undelete && $topic->authorise('undelete')) $undelete = true;
if (!$move && $topic->authorise('move')) {
$move = $this->actionMove = true;
}
if (!$permdelete && $topic->authorise('permdelete')) $permdelete = true;
}
$actionDropdown[] = JHtml::_('select.option', 'none', JText::_('COM_KUNENA_BULK_CHOOSE_ACTION'));
if ($this->getState ('list.mode') == 'subscriptions')
$actionDropdown[] = JHtml::_('select.option', 'unsubscribe', JText::_('COM_KUNENA_UNSUBSCRIBE_SELECTED'));
if ($this->getState ('list.mode') == 'favorites')
$actionDropdown[] = JHtml::_('select.option', 'unfavorite', JText::_('COM_KUNENA_UNFAVORITE_SELECTED'));
if ($move) $actionDropdown[] = JHtml::_('select.option', 'move', JText::_('COM_KUNENA_MOVE_SELECTED'));
if ($approve) $actionDropdown[] = JHtml::_('select.option', 'approve', JText::_('COM_KUNENA_APPROVE_SELECTED'));
if ($delete) $actionDropdown[] = JHtml::_('select.option', 'delete', JText::_('COM_KUNENA_DELETE_SELECTED'));
if ($permdelete) $actionDropdown[] = JHtml::_('select.option', 'permdel', JText::_('COM_KUNENA_BUTTON_PERMDELETE_LONG'));
if ($undelete) $actionDropdown[] = JHtml::_('select.option', 'restore', JText::_('COM_KUNENA_BUTTON_UNDELETE_LONG'));
if (count($actionDropdown) == 1) return null;
return $actionDropdown;
}
public function getPostActions() {
if ($this->messages === false) {
$this->getPosts();
}
$delete = $approve = $undelete = $move = $permdelete = false;
foreach ($this->messages as $message) {
if (!$delete && $message->authorise('delete')) $delete = true;
if (!$approve && $message->authorise('approve')) $approve = true;
if (!$undelete && $message->authorise('undelete')) $undelete = true;
if (!$permdelete && $message->authorise('permdelete')) $permdelete = true;
}
$actionDropdown[] = JHtml::_('select.option', 'none', JText::_('COM_KUNENA_BULK_CHOOSE_ACTION'));
if ($approve) $actionDropdown[] = JHtml::_('select.option', 'approve_posts', JText::_('COM_KUNENA_APPROVE_SELECTED'));
if ($delete) $actionDropdown[] = JHtml::_('select.option', 'delete_posts', JText::_('COM_KUNENA_DELETE_SELECTED'));
if ($permdelete) $actionDropdown[] = JHtml::_('select.option', 'permdel_posts', JText::_('COM_KUNENA_BUTTON_PERMDELETE_LONG'));
if ($undelete) $actionDropdown[] = JHtml::_('select.option', 'restore_posts', JText::_('COM_KUNENA_BUTTON_UNDELETE_LONG'));
if (count($actionDropdown) == 1) return null;
return $actionDropdown;
}
public function getActionMove() {
return $this->actionMove;
}
}
| gpl-2.0 |
jonaslindert/susyhell | common/FeynHiggs-2.10.1/extse/OasatPdep.app/SecDec3/loop/T1234m0110/together/epstothe0/g3.cc | 9212 | #include "intfile.hh"
double Pr3(const double x[], double es[], double esx[], double em[], double lambda, double lrs[], double bi) {
double x0=x[0];
double x1=x[1];
double x2=x[2];
double y[32];
double FOUT;
y[1]=1./bi;
y[2]=em[0];
y[3]=esx[0];
y[4]=-x0;
y[5]=1.+y[4];
y[6]=y[1]*y[2];
y[7]=x1*y[1]*y[2];
y[8]=2.*x2*y[1]*y[2];
y[9]=x1*x2*y[1]*y[2];
y[10]=x2*x2;
y[11]=y[1]*y[2]*y[10];
y[12]=-(x1*y[1]*y[3]);
y[13]=-(x2*y[1]*y[3]);
y[14]=y[6]+y[7]+y[8]+y[9]+y[11]+y[12]+y[13];
y[15]=lrs[0];
y[16]=-x1;
y[17]=1.+y[16];
y[18]=x0*y[1]*y[2];
y[19]=x2*y[1]*y[2];
y[20]=x0*x2*y[1]*y[2];
y[21]=-(y[1]*y[3]);
y[22]=-(x0*y[1]*y[3]);
y[23]=y[6]+y[18]+y[19]+y[20]+y[21]+y[22];
y[24]=lrs[1];
y[25]=-x2;
y[26]=1.+y[25];
y[27]=2.*x0*y[1]*y[2];
y[28]=x0*x1*y[1]*y[2];
y[29]=2.*x0*x2*y[1]*y[2];
y[30]=y[6]+y[7]+y[22]+y[27]+y[28]+y[29];
y[31]=lrs[2];
FOUT=(x0*pow(y[26],2)*pow(y[30],2)*pow(y[31],2)*y[1]*y[2]*y[5]*y[10]*y[14]*y\
[15]+x0*x1*x2*y[1]*y[2]*y[5]*y[14]*y[15]*y[17]*y[23]*y[24]*y[26]*y[30]*y[31\
])/(-(x0*y[1]*y[2]*y[5]*y[14]*y[15])-x0*x1*y[1]*y[2]*y[5]*y[14]*y[15]-2.*x0\
*x2*y[1]*y[2]*y[5]*y[14]*y[15]-x0*x1*x2*y[1]*y[2]*y[5]*y[14]*y[15]+x0*x1*y[\
1]*y[3]*y[5]*y[14]*y[15]+x0*x2*y[1]*y[3]*y[5]*y[14]*y[15]-x0*y[1]*y[2]*y[5]\
*y[10]*y[14]*y[15]-x1*y[1]*y[2]*y[17]*y[23]*y[24]-x0*x1*y[1]*y[2]*y[17]*y[2\
3]*y[24]-x1*x2*y[1]*y[2]*y[17]*y[23]*y[24]-x0*x1*x2*y[1]*y[2]*y[17]*y[23]*y\
[24]+x1*y[1]*y[3]*y[17]*y[23]*y[24]+x0*x1*y[1]*y[3]*y[17]*y[23]*y[24]-x2*y[\
1]*y[2]*y[26]*y[30]*y[31]-2.*x0*x2*y[1]*y[2]*y[26]*y[30]*y[31]-x1*x2*y[1]*y\
[2]*y[26]*y[30]*y[31]-x0*x1*x2*y[1]*y[2]*y[26]*y[30]*y[31]+x0*x2*y[1]*y[3]*\
y[26]*y[30]*y[31]-2.*x0*y[1]*y[2]*y[10]*y[26]*y[30]*y[31]);
return (FOUT);
}
double Pm3(const double x[], double es[], double esx[], double em[], double lambda, double lrs[], double bi) {
double x0=x[0];
double x1=x[1];
double x2=x[2];
double y[35];
double FOUT;
y[1]=1./bi;
y[2]=em[0];
y[3]=esx[0];
y[4]=y[1]*y[2];
y[5]=x0*y[1]*y[2];
y[6]=x2*y[1]*y[2];
y[7]=x1*y[1]*y[2];
y[8]=x1*x2*y[1]*y[2];
y[9]=x2*x2;
y[10]=-(x1*y[1]*y[3]);
y[11]=-x0;
y[12]=1.+y[11];
y[13]=-x1;
y[14]=1.+y[13];
y[15]=x0*x2*y[1]*y[2];
y[16]=-(y[1]*y[3]);
y[17]=-(x0*y[1]*y[3]);
y[18]=y[4]+y[5]+y[6]+y[15]+y[16]+y[17];
y[19]=2.*x2*y[1]*y[2];
y[20]=y[1]*y[2]*y[9];
y[21]=-(x2*y[1]*y[3]);
y[22]=y[4]+y[7]+y[8]+y[10]+y[19]+y[20]+y[21];
y[23]=lrs[0];
y[24]=lrs[1];
y[25]=x0*x1*y[1]*y[2];
y[26]=2.*x0*x2*y[1]*y[2];
y[27]=-x2;
y[28]=1.+y[27];
y[29]=2.*x0*y[1]*y[2];
y[30]=y[4]+y[7]+y[17]+y[25]+y[26]+y[29];
y[31]=lrs[2];
y[32]=pow(y[28],2);
y[33]=pow(y[30],2);
y[34]=pow(y[31],2);
FOUT=pow(x0*x1*x2*y[1]*y[2]-x0*x1*y[1]*y[3]-x0*x2*y[1]*y[3]+y[4]+y[5]+y[6]+y\
[7]+y[8]+x0*y[1]*y[2]*y[9]+y[10]+y[25]+y[26]+lambda*lambda*(-(x0*x1*y[1]*y[\
2]*y[12]*y[14]*y[18]*y[22]*y[23]*y[24])-x0*x1*x2*y[1]*y[2]*y[12]*y[14]*y[18\
]*y[22]*y[23]*y[24]+x0*x1*y[1]*y[3]*y[12]*y[14]*y[18]*y[22]*y[23]*y[24]-2.*\
x0*x2*y[1]*y[2]*y[12]*y[22]*y[23]*y[28]*y[30]*y[31]-x0*x1*x2*y[1]*y[2]*y[12\
]*y[22]*y[23]*y[28]*y[30]*y[31]+x0*x2*y[1]*y[3]*y[12]*y[22]*y[23]*y[28]*y[3\
0]*y[31]-2.*x0*y[1]*y[2]*y[9]*y[12]*y[22]*y[23]*y[28]*y[30]*y[31]-x1*x2*y[1\
]*y[2]*y[14]*y[18]*y[24]*y[28]*y[30]*y[31]-x0*x1*x2*y[1]*y[2]*y[14]*y[18]*y\
[24]*y[28]*y[30]*y[31]-x0*y[1]*y[2]*y[9]*y[32]*y[33]*y[34]),2)+pow(lambda*(\
-(x0*y[1]*y[2]*y[12]*y[22]*y[23])-x0*x1*y[1]*y[2]*y[12]*y[22]*y[23]-2.*x0*x\
2*y[1]*y[2]*y[12]*y[22]*y[23]-x0*x1*x2*y[1]*y[2]*y[12]*y[22]*y[23]+x0*x1*y[\
1]*y[3]*y[12]*y[22]*y[23]+x0*x2*y[1]*y[3]*y[12]*y[22]*y[23]-x0*y[1]*y[2]*y[\
9]*y[12]*y[22]*y[23]-x1*y[1]*y[2]*y[14]*y[18]*y[24]-x0*x1*y[1]*y[2]*y[14]*y\
[18]*y[24]-x1*x2*y[1]*y[2]*y[14]*y[18]*y[24]-x0*x1*x2*y[1]*y[2]*y[14]*y[18]\
*y[24]+x1*y[1]*y[3]*y[14]*y[18]*y[24]+x0*x1*y[1]*y[3]*y[14]*y[18]*y[24]-x2*\
y[1]*y[2]*y[28]*y[30]*y[31]-2.*x0*x2*y[1]*y[2]*y[28]*y[30]*y[31]-x1*x2*y[1]\
*y[2]*y[28]*y[30]*y[31]-x0*x1*x2*y[1]*y[2]*y[28]*y[30]*y[31]+x0*x2*y[1]*y[3\
]*y[28]*y[30]*y[31]-2.*x0*y[1]*y[2]*y[9]*y[28]*y[30]*y[31])+pow(lambda,3)*(\
x0*x1*x2*y[1]*y[2]*y[12]*y[14]*y[18]*y[22]*y[23]*y[24]*y[28]*y[30]*y[31]+x0\
*y[1]*y[2]*y[9]*y[12]*y[22]*y[23]*y[32]*y[33]*y[34]),2);
return (FOUT);
}
double Ps3(const double x[], double es[], double esx[], double em[], double lambda, double lrs[], double bi) {
double x0=x[0];
double x1=x[1];
double x2=x[2];
double y[32];
double FOUT;
y[1]=1./bi;
y[2]=em[0];
y[3]=esx[0];
y[4]=-x0;
y[5]=1.+y[4];
y[6]=y[1]*y[2];
y[7]=x1*y[1]*y[2];
y[8]=2.*x2*y[1]*y[2];
y[9]=x1*x2*y[1]*y[2];
y[10]=x2*x2;
y[11]=y[1]*y[2]*y[10];
y[12]=-(x1*y[1]*y[3]);
y[13]=-(x2*y[1]*y[3]);
y[14]=y[6]+y[7]+y[8]+y[9]+y[11]+y[12]+y[13];
y[15]=lrs[0];
y[16]=-x1;
y[17]=1.+y[16];
y[18]=x0*y[1]*y[2];
y[19]=x2*y[1]*y[2];
y[20]=x0*x2*y[1]*y[2];
y[21]=-(y[1]*y[3]);
y[22]=-(x0*y[1]*y[3]);
y[23]=y[6]+y[18]+y[19]+y[20]+y[21]+y[22];
y[24]=lrs[1];
y[25]=-x2;
y[26]=1.+y[25];
y[27]=2.*x0*y[1]*y[2];
y[28]=x0*x1*y[1]*y[2];
y[29]=2.*x0*x2*y[1]*y[2];
y[30]=y[6]+y[7]+y[22]+y[27]+y[28]+y[29];
y[31]=lrs[2];
FOUT=lambda*(-(x0*y[1]*y[2]*y[5]*y[14]*y[15])-x0*x1*y[1]*y[2]*y[5]*y[14]*y[1\
5]-2.*x0*x2*y[1]*y[2]*y[5]*y[14]*y[15]-x0*x1*x2*y[1]*y[2]*y[5]*y[14]*y[15]+\
x0*x1*y[1]*y[3]*y[5]*y[14]*y[15]+x0*x2*y[1]*y[3]*y[5]*y[14]*y[15]-x0*y[1]*y\
[2]*y[5]*y[10]*y[14]*y[15]-x1*y[1]*y[2]*y[17]*y[23]*y[24]-x0*x1*y[1]*y[2]*y\
[17]*y[23]*y[24]-x1*x2*y[1]*y[2]*y[17]*y[23]*y[24]-x0*x1*x2*y[1]*y[2]*y[17]\
*y[23]*y[24]+x1*y[1]*y[3]*y[17]*y[23]*y[24]+x0*x1*y[1]*y[3]*y[17]*y[23]*y[2\
4]-x2*y[1]*y[2]*y[26]*y[30]*y[31]-2.*x0*x2*y[1]*y[2]*y[26]*y[30]*y[31]-x1*x\
2*y[1]*y[2]*y[26]*y[30]*y[31]-x0*x1*x2*y[1]*y[2]*y[26]*y[30]*y[31]+x0*x2*y[\
1]*y[3]*y[26]*y[30]*y[31]-2.*x0*y[1]*y[2]*y[10]*y[26]*y[30]*y[31])+pow(lamb\
da,3)*(x0*pow(y[26],2)*pow(y[30],2)*pow(y[31],2)*y[1]*y[2]*y[5]*y[10]*y[14]\
*y[15]+x0*x1*x2*y[1]*y[2]*y[5]*y[14]*y[15]*y[17]*y[23]*y[24]*y[26]*y[30]*y[\
31]);
return (FOUT);
}
double Pa3(const double x[], double es[], double esx[], double em[], double lambda, double lrs[], double bi) {
double x0=x[0];
double x1=x[1];
double x2=x[2];
double y[35];
double FOUT;
y[1]=1./bi;
y[2]=em[0];
y[3]=esx[0];
y[4]=y[1]*y[2];
y[5]=x0*y[1]*y[2];
y[6]=x2*y[1]*y[2];
y[7]=x1*y[1]*y[2];
y[8]=x1*x2*y[1]*y[2];
y[9]=x2*x2;
y[10]=-(x1*y[1]*y[3]);
y[11]=-x0;
y[12]=1.+y[11];
y[13]=-x1;
y[14]=1.+y[13];
y[15]=x0*x2*y[1]*y[2];
y[16]=-(y[1]*y[3]);
y[17]=-(x0*y[1]*y[3]);
y[18]=y[4]+y[5]+y[6]+y[15]+y[16]+y[17];
y[19]=2.*x2*y[1]*y[2];
y[20]=y[1]*y[2]*y[9];
y[21]=-(x2*y[1]*y[3]);
y[22]=y[4]+y[7]+y[8]+y[10]+y[19]+y[20]+y[21];
y[23]=lrs[0];
y[24]=lrs[1];
y[25]=x0*x1*y[1]*y[2];
y[26]=2.*x0*x2*y[1]*y[2];
y[27]=-x2;
y[28]=1.+y[27];
y[29]=2.*x0*y[1]*y[2];
y[30]=y[4]+y[7]+y[17]+y[25]+y[26]+y[29];
y[31]=lrs[2];
y[32]=pow(y[28],2);
y[33]=pow(y[30],2);
y[34]=pow(y[31],2);
FOUT=(lambda*(-(x0*y[1]*y[2]*y[12]*y[22]*y[23])-x0*x1*y[1]*y[2]*y[12]*y[22]*\
y[23]-2.*x0*x2*y[1]*y[2]*y[12]*y[22]*y[23]-x0*x1*x2*y[1]*y[2]*y[12]*y[22]*y\
[23]+x0*x1*y[1]*y[3]*y[12]*y[22]*y[23]+x0*x2*y[1]*y[3]*y[12]*y[22]*y[23]-x0\
*y[1]*y[2]*y[9]*y[12]*y[22]*y[23]-x1*y[1]*y[2]*y[14]*y[18]*y[24]-x0*x1*y[1]\
*y[2]*y[14]*y[18]*y[24]-x1*x2*y[1]*y[2]*y[14]*y[18]*y[24]-x0*x1*x2*y[1]*y[2\
]*y[14]*y[18]*y[24]+x1*y[1]*y[3]*y[14]*y[18]*y[24]+x0*x1*y[1]*y[3]*y[14]*y[\
18]*y[24]-x2*y[1]*y[2]*y[28]*y[30]*y[31]-2.*x0*x2*y[1]*y[2]*y[28]*y[30]*y[3\
1]-x1*x2*y[1]*y[2]*y[28]*y[30]*y[31]-x0*x1*x2*y[1]*y[2]*y[28]*y[30]*y[31]+x\
0*x2*y[1]*y[3]*y[28]*y[30]*y[31]-2.*x0*y[1]*y[2]*y[9]*y[28]*y[30]*y[31])+po\
w(lambda,3)*(x0*x1*x2*y[1]*y[2]*y[12]*y[14]*y[18]*y[22]*y[23]*y[24]*y[28]*y\
[30]*y[31]+x0*y[1]*y[2]*y[9]*y[12]*y[22]*y[23]*y[32]*y[33]*y[34]))/(lambda*\
(x0*x1*x2*y[1]*y[2]-x0*x1*y[1]*y[3]-x0*x2*y[1]*y[3]+y[4]+y[5]+y[6]+y[7]+y[8\
]+x0*y[1]*y[2]*y[9]+y[10]+y[25]+y[26]+lambda*lambda*(-(x0*x1*y[1]*y[2]*y[12\
]*y[14]*y[18]*y[22]*y[23]*y[24])-x0*x1*x2*y[1]*y[2]*y[12]*y[14]*y[18]*y[22]\
*y[23]*y[24]+x0*x1*y[1]*y[3]*y[12]*y[14]*y[18]*y[22]*y[23]*y[24]-2.*x0*x2*y\
[1]*y[2]*y[12]*y[22]*y[23]*y[28]*y[30]*y[31]-x0*x1*x2*y[1]*y[2]*y[12]*y[22]\
*y[23]*y[28]*y[30]*y[31]+x0*x2*y[1]*y[3]*y[12]*y[22]*y[23]*y[28]*y[30]*y[31\
]-2.*x0*y[1]*y[2]*y[9]*y[12]*y[22]*y[23]*y[28]*y[30]*y[31]-x1*x2*y[1]*y[2]*\
y[14]*y[18]*y[24]*y[28]*y[30]*y[31]-x0*x1*x2*y[1]*y[2]*y[14]*y[18]*y[24]*y[\
28]*y[30]*y[31]-x0*y[1]*y[2]*y[9]*y[32]*y[33]*y[34])));
return (FOUT);
}
double Pt3t1(const double x[], double es[], double esx[], double em[], double lambda, double lrs[], double bi) {
double x0=x[0];
double x1=x[1];
double x2=x[2];
double y[4];
double FOUT;
y[1]=1./bi;
y[2]=em[0];
y[3]=esx[0];
FOUT=(1.-x0)*x0*(y[1]*y[2]+x1*y[1]*y[2]+2.*x2*y[1]*y[2]+x1*x2*y[1]*y[2]+x2*x\
2*y[1]*y[2]-x1*y[1]*y[3]-x2*y[1]*y[3]);
return (FOUT);
}
double Pt3t2(const double x[], double es[], double esx[], double em[], double lambda, double lrs[], double bi) {
double x0=x[0];
double x1=x[1];
double x2=x[2];
double y[4];
double FOUT;
y[1]=1./bi;
y[2]=em[0];
y[3]=esx[0];
FOUT=(1.-x1)*x1*(y[1]*y[2]+x0*y[1]*y[2]+x2*y[1]*y[2]+x0*x2*y[1]*y[2]-y[1]*y[\
3]-x0*y[1]*y[3]);
return (FOUT);
}
double Pt3t3(const double x[], double es[], double esx[], double em[], double lambda, double lrs[], double bi) {
double x0=x[0];
double x1=x[1];
double x2=x[2];
double y[3];
double FOUT;
y[1]=1./bi;
y[2]=em[0];
FOUT=(1.-x2)*x2*(-(x0*esx[0]*y[1])+y[1]*y[2]+2.*x0*y[1]*y[2]+x1*y[1]*y[2]+x0\
*x1*y[1]*y[2]+2.*x0*x2*y[1]*y[2]);
return (FOUT);
}
| gpl-2.0 |
artefactual-labs/trac | sites/all/modules/print/print.tpl.php | 1482 | <?php
/**
* @file
* Default print module template
*
* @ingroup print
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="<?php print $print['language']; ?>" xml:lang="<?php print $print['language']; ?>">
<head>
<?php print $print['head']; ?>
<?php print $print['base_href']; ?>
<title><?php print $print['title']; ?></title>
<?php print $print['scripts']; ?>
<?php print $print['sendtoprinter']; ?>
<?php print $print['robots_meta']; ?>
<?php print $print['favicon']; ?>
<?php print $print['css']; ?>
</head>
<body>
<?php if (!empty($print['message'])) {
print '<div class="print-message">'. $print['message'] .'</div><p />';
} ?>
<div class="print-logo"><?php print $print['logo']; ?></div>
<div class="print-site_name"><?php print $print['site_name']; ?></div>
<p />
<div class="print-breadcrumb"><?php print $print['breadcrumb']; ?></div>
<hr class="print-hr" />
<div class="print-content"><?php print $print['content']; ?></div>
<div class="print-footer"><?php print $print['footer_message']; ?></div>
<hr class="print-hr" />
<div class="print-source_url"><?php print $print['source_url']; ?></div>
<div class="print-links"><?php print $print['pfp_links']; ?></div>
<?php print $print['footer_scripts']; ?>
</body>
</html>
| gpl-2.0 |
ArthurBaduyen/UCD | wp-content/plugins/team/includes/class-functions.php | 7147 | <?php
/*
* @Author ParaTheme
* Copyright: 2015 ParaTheme
*/
if ( ! defined('ABSPATH')) exit; // if direct access
class class_team_functions {
public function __construct()
{
//$this->settings_page = new Team_Settings();
//add_action( 'admin_menu', array( $this, 'admin_menu' ), 12 );
//add_action('admin_menu', array($this, 'create_menu'));
}
public function team_member_posttype($posttype = array('team_member'))
{
return apply_filters('team_member_posttype', $posttype);
}
public function team_member_taxonomy($taxonomy = 'team_group')
{
return apply_filters('team_member_taxonomy', $taxonomy); //string only
}
public function team_member_social_field()
{
/*
$social_field = array(
"mobile"=>"Mobile",
"website"=>"Website",
"email"=>"Email",
"skype"=>"Skype",
"facebook"=>"Facebook",
"twitter"=>"Twitter",
"googleplus"=>"Google plus",
"pinterest"=>"Pinterest",
"linkedin"=>"Linkedin",
"vimeo"=>"Vimeo",
);
*/
$social_field = array(
"mobile"=>array('meta_key'=>"mobile",'name'=>"Mobile",'icon'=>'','visibility'=>'1','can_remove'=>'no',),
"website"=>array('meta_key'=>"website",'name'=>"Website",'icon'=>'','visibility'=>'1','can_remove'=>'no',),
"email"=>array('meta_key'=>"email",'name'=>"Email",'icon'=>'','visibility'=>'1','can_remove'=>'no',),
"skype"=>array('meta_key'=>"skype",'name'=>"Skype",'icon'=>'','visibility'=>'1','can_remove'=>'no',),
"facebook"=>array('meta_key'=>"facebook",'name'=>"Facebook",'icon'=>'','visibility'=>'1','can_remove'=>'yes',),
"twitter"=>array('meta_key'=>"twitter",'name'=>"Twitter",'icon'=>'','visibility'=>'1','can_remove'=>'yes',),
"googleplus"=>array('meta_key'=>"googleplus",'name'=>"Google plus",'icon'=>'','visibility'=>'1','can_remove'=>'yes',),
"pinterest"=>array('meta_key'=>"pinterest",'name'=>"Pinterest",'icon'=>'','visibility'=>'1','can_remove'=>'yes',),
"linkedin"=>array('meta_key'=>"linkedin",'name'=>"Linkedin",'icon'=>'','visibility'=>'1','can_remove'=>'yes',),
"vimeo"=>array('meta_key'=>"vimeo",'name'=>"Vimeo",'icon'=>'','visibility'=>'1','can_remove'=>'yes',),
);
return apply_filters( 'team_member_social_field', $social_field );
}
public function team_grid_items()
{
$team_grid_items = array(
'thumbnail'=>__('Thumbnail','team'),
'title'=>__('Title','team'),
'position'=>__('Position / Role','team'),
'content'=>__('Content / Biography','team'),
'social'=>__('Social','team'),
);
$team_grid_items = apply_filters('team_grid_items',$team_grid_items);
return $team_grid_items;
}
public function team_themes($themes = array())
{
$themes = array(
'flat'=>'Flat',
'rounded'=>'Rounded',
'zoom-out'=>'Zoom Out',
);
foreach(apply_filters( 'team_themes', $themes ) as $theme_key=> $theme_name)
{
$theme_list[$theme_key] = $theme_name;
}
return $theme_list;
}
public function team_themes_dir($themes_dir = array())
{
$main_dir = team_plugin_dir.'themes/';
$themes_dir = array(
'flat'=>$main_dir.'flat',
'rounded'=>$main_dir.'rounded',
'zoom-out'=>$main_dir.'zoom-out',
);
foreach(apply_filters( 'team_themes_dir', $themes_dir ) as $theme_key=> $theme_dir)
{
$theme_list_dir[$theme_key] = $theme_dir;
}
return $theme_list_dir;
}
public function team_themes_url($themes_url = array())
{
$main_url = team_plugin_url.'themes/';
$themes_url = array(
'flat'=>$main_url.'flat',
'rounded'=>$main_url.'rounded',
'zoom-out'=>$main_url.'zoom-out',
);
foreach(apply_filters( 'team_themes_url', $themes_url ) as $theme_key=> $theme_url)
{
$theme_list_url[$theme_key] = $theme_url;
}
return $theme_list_url;
}
// Single Team Member
public function team_single_themes($themes = array())
{
$themes = array(
'flat'=>'Flat',
);
foreach(apply_filters( 'team_single_themes', $themes ) as $theme_key=> $theme_name)
{
$theme_list[$theme_key] = $theme_name;
}
return $theme_list;
}
public function team_single_themes_dir($themes_dir = array())
{
$main_dir = team_plugin_dir.'themes-single/';
$themes_dir = $this->team_themes();
foreach($themes_dir as $theme_key=> $theme_dir)
{
$theme_list_dir[$theme_key] = $main_dir.$theme_key;
}
return $theme_list_dir;
}
public function team_single_themes_url($themes_url = array())
{
$main_url = team_plugin_url.'themes-single/';
$themes_url = $this->team_themes();
foreach($themes_url as $theme_key=> $theme_url)
{
$theme_list_url[$theme_key] = $main_url.$theme_key;
}
return $theme_list_url;
}
public function team_share_plugin()
{
?>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.3&appId=652982311485932";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-href="http://paratheme.com/items/team-responsive-meet-the-team-grid-for-wordpress" data-layout="standard" data-action="like" data-show-faces="true" data-share="true"></div>
<br /><br />
<!-- Place this tag in your head or just before your close body tag. -->
<script src="https://apis.google.com/js/platform.js" async defer></script>
<!-- Place this tag where you want the +1 button to render. -->
<div class="g-plusone" data-size="medium" data-annotation="inline" data-width="300" data-href="<?php echo team_share_url; ?>"></div>
<br />
<br />
<a href="https://twitter.com/share" class="twitter-share-button" data-url="<?php echo team_share_url; ?>" data-text="<?php echo team_plugin_name; ?>" data-via="ParaTheme" data-hashtags="WordPress">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
<?php
}
}
new class_team_functions();
| gpl-2.0 |
BrendanAnnable/mt4j | extensions/org/mt4jx/input/inputProcessors/componentProcessors/Group3DProcessorNew/LassoGrouping/LassoGroupSelectionManager.java | 8992 | package org.mt4jx.input.inputProcessors.componentProcessors.Group3DProcessorNew.LassoGrouping;
import org.mt4j.components.MTCanvas;
import org.mt4j.components.MTComponent;
import org.mt4j.components.StateChange;
import org.mt4j.components.StateChangeEvent;
import org.mt4j.components.StateChangeListener;
import org.mt4j.components.visibleComponents.shapes.MTPolygon;
import org.mt4j.input.MTEvent;
import org.mt4j.input.inputData.AbstractCursorInputEvt;
import org.mt4j.input.inputData.InputCursor;
import org.mt4j.input.inputProcessors.IInputProcessor;
import org.mt4j.input.inputProcessors.MTGestureEvent;
import org.mt4j.input.inputProcessors.componentProcessors.AbstractComponentProcessor;
import org.mt4j.input.inputProcessors.componentProcessors.AbstractCursorProcessor;
import org.mt4j.input.inputProcessors.componentProcessors.lassoProcessor.IdragClusterable;
import org.mt4jx.input.inputProcessors.componentProcessors.Group3DProcessorNew.Cluster;
import org.mt4jx.input.inputProcessors.componentProcessors.Group3DProcessorNew.ClusterDataManager;
import org.mt4jx.input.inputProcessors.componentProcessors.Group3DProcessorNew.ISelection;
import org.mt4jx.input.inputProcessors.componentProcessors.Group3DProcessorNew.ISelectionListener;
import org.mt4jx.input.inputProcessors.componentProcessors.Group3DProcessorNew.ISelectionManager;
import org.mt4jx.input.inputProcessors.componentProcessors.Group3DProcessorNew.MTLassoSelectionEvent;
import org.mt4jx.input.inputProcessors.componentProcessors.Group3DProcessorNew.MTSelectionEvent;
import org.mt4jx.util.extension3D.MergeHelper;
import java.util.*;
public class LassoGroupSelectionManager extends AbstractCursorProcessor implements ISelectionManager {
private List<ISelectionListener> selectionListeners;
private HashMap<InputCursor,ISelection> cursorToSelection = new HashMap<InputCursor,ISelection>();
/** The canvas. */
private MTCanvas canvas;
/** The drag selectables. */
private List<MTComponent> dragSelectables = new ArrayList<MTComponent>();
private ClusterDataManager clusterManager;
/**
* the selection which is used for the cursors, for every cursor one selection is copied
*/
private LassoSelection selection;
public LassoGroupSelectionManager(MTCanvas canvas,ClusterDataManager clusterManager)
{
this.selectionListeners = new ArrayList<ISelectionListener>();
this.canvas = canvas;
this.clusterManager = clusterManager;
this.selection = new LassoSelection(canvas.getRenderer(),canvas.getAttachedCamera(),this);
}
public void addSelectionListener(ISelectionListener listener)
{
if(!(selectionListeners.contains(listener)))
{
this.selectionListeners.add(listener);
}
}
public void removeSelectionListener(ISelectionListener listener)
{
if(selectionListeners.contains(listener))
{
this.selectionListeners.remove(listener);
}
}
public void newInputCursor(InputCursor cursor)
{
if(!cursorToSelection.containsKey(cursor))
{
LassoSelection sel = (LassoSelection)selection.getCopy();
cursorToSelection.put(cursor, sel);
}
}
public ISelection getSelection(InputCursor inputCursor)
{
if(cursorToSelection.containsKey(inputCursor))
{
return cursorToSelection.get(inputCursor);
}
return null;
}
public void removeInputCursor(InputCursor inputCursor)
{
if(cursorToSelection.containsKey(inputCursor))
{
cursorToSelection.remove(inputCursor);
}
}
@Override
public void cursorEnded(InputCursor inputCursor,
AbstractCursorInputEvt currentEvent) {
logger.debug(this.getName() + " INPUT_ENDED RECIEVED - MOTION: " + inputCursor.getId());
LassoSelection sel = (LassoSelection)this.getSelection(inputCursor);
this.removeInputCursor(inputCursor);
ArrayList<MTComponent> components = new ArrayList<MTComponent>();
if(sel.getSelectedComponents().size()>1)
{
for(MTComponent elem : sel.getSelectedComponents())
{
MTComponent comp = (MTComponent)elem;
Cluster formerCluster = null;
if((formerCluster=clusterManager.getClusterForComponent(comp))!=null)
{
clusterManager.removeComponentFromCluster(comp, formerCluster);
//send the updated Selected Comps to the visualizer
ArrayList<MTComponent> newSelectedComps = new ArrayList<MTComponent>();
for(MTComponent formerComp : formerCluster.getChildren())
{
newSelectedComps.add(formerComp);
}
//this.fireSelectionEvent(new MTLassoSelectionEvent(this,MTLassoSelectionEvent.SELECTION_UPDATED,newSelectedComps,null,formerCluster));
}
components.add(comp);
}
Cluster cluster = clusterManager.createCluster(components,true);
this.canvas.removeChild(sel.getPolygon());
this.fireEvent(new MTLassoSelectionEvent(this,MTLassoSelectionEvent.SELECTION_ENDED,sel.getSelectedComponents(),sel.getPolygon(),cluster));
}else if(sel.getSelectedComponents().size()==1)
{
Cluster formerCluster = null;
if((formerCluster=clusterManager.getClusterForComponent((MTComponent)sel.getSelectedComponents().get(0)))!=null)
{
clusterManager.removeComponentFromCluster((MTComponent)sel.getSelectedComponents().get(0), formerCluster);
this.canvas.addChild(sel.getSelectedComponents().get(0));
}
this.canvas.removeChild(sel.getPolygon());
}else
{
this.canvas.removeChild(sel.getPolygon());
}
this.unLock(inputCursor);
}
@Override
public void cursorLocked(InputCursor cursor,
IInputProcessor lockingprocessor) {
if (lockingprocessor instanceof AbstractComponentProcessor){
logger.debug(this.getName() + " Recieved MOTION LOCKED by (" + ((AbstractComponentProcessor)lockingprocessor).getName() + ") - cursor ID: " + cursor.getId());
}else{
logger.debug(this.getName() + " Recieved MOTION LOCKED by higher priority signal - cursor ID: " + cursor.getId());
}
this.abortGesture(cursor);
}
@Override
public void cursorStarted(InputCursor inputCursor,
AbstractCursorInputEvt currentEvent) {
if (this.canLock(inputCursor)){
newInputCursor(inputCursor);
LassoSelection sel = (LassoSelection)getSelection(inputCursor);
sel.startSelection(inputCursor);
//sel.getPolygon().attachCamera(canvas.getAttachedCamera());
canvas.addChild(sel.getPolygon());
this.fireEvent(new MTSelectionEvent(this,MTSelectionEvent.SELECTION_STARTED,sel.getSelectedComponents()));
}
}
@Override
public void cursorUnlocked(InputCursor cursor) {
logger.debug(this.getName() + " Recieved UNLOCKED signal for cursor ID: " + cursor.getId());
//Do nothing here, we dont want this gesture to be resumable
}
@Override
public void cursorUpdated(InputCursor inputCursor,
AbstractCursorInputEvt currentEvent) {
LassoSelection sel = (LassoSelection)getSelection(inputCursor);
sel.updateCursorInput(inputCursor);
}
/**g
* Adds the clusterable.
*
* @param selectable the selectable
*/
public synchronized void addClusterable(MTComponent selectable){
getDragSelectables().add(selectable);
if (selectable instanceof MTComponent) {
MTComponent baseComp = (MTComponent) selectable;
baseComp.addStateChangeListener(StateChange.COMPONENT_DESTROYED, new StateChangeListener(){
public void stateChanged(StateChangeEvent evt) {
if (evt.getSource() instanceof MTComponent) {
MTComponent clusterAble = (MTComponent) evt.getSource();
removeClusterable(clusterAble);
//logger.debug("Removed comp from clustergesture analyzers tracking");
}
}
});
}
}
/**
* Removes the clusterable.
*
* @param selectable the selectable
*/
public synchronized void removeClusterable(MTComponent selectable){
getDragSelectables().remove(selectable);
}
/**
* Abort gesture.
*
* @param m the involved cursor
*/
public void abortGesture(InputCursor m){
//because of aborting we send an empty selectionarrray
ArrayList<MTComponent> selectedComps = new ArrayList<MTComponent>();
LassoSelection sel = (LassoSelection)getSelection(m);
this.fireEvent(new MTLassoSelectionEvent(this,MTSelectionEvent.SELECTION_ENDED,selectedComps,sel.getPolygon(),null));
removeInputCursor(m);
logger.debug(this.getName() + " cursor:" + m.getId() + " MOTION LOCKED. Was an active cursor in this gesture!");
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
public void fireEvent(MTEvent event) {
for(int i=0;i<selectionListeners.size();i++)
{
selectionListeners.get(i).processMTEvent(event);
}
}
public void setDragSelectables(List<MTComponent> dragSelectables) {
this.dragSelectables = dragSelectables;
}
public List<MTComponent> getDragSelectables() {
return dragSelectables;
}
}
| gpl-2.0 |
greg-hellings/sword | utilities/addcomment.cpp | 1609 | /******************************************************************************
*
* addcomment.cpp -
*
* $Id$
*
* Copyright 1998-2013 CrossWire Bible Society (http://www.crosswire.org)
* CrossWire Bible Society
* P. O. Box 2528
* Tempe, AZ 85280-2528
*
* 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 2.
*
* 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.
*
*/
#include <stdio.h>
#include <iostream>
#include <versekey.h>
#include <rawtext.h>
#include <zcom.h>
#include <rawcom.h>
#include <rawfiles.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int loop;
int max;
RawFiles personal("modules/comments/rawfiles/personal/", "MINE", "Personal Comments");
VerseKey mykey;
if (argc < 3) {
fprintf(stderr, "usage: %s <\"comment\"> <\"verse\"> [count] [disable AutoNormalization]\n", argv[0]);
exit(-1);
}
if (argc > 4)
mykey.AutoNormalize(0); // Turn off autonormalize if 3 args to allow for intros
// This is kludgy but at lease you can try it
// with something like: sword "Matthew 1:0" 1 1
mykey = argv[2];
mykey.Persist(1);
personal.setKey(mykey);
max = (argc < 4) ? 1 : atoi(argv[3]);
for (loop = 0; loop < max; loop++) {
personal << argv[1];
mykey++;
}
std::cout << "Added Comment" << std::endl;
return 0;
}
| gpl-2.0 |
raddick/sdssOrg | wp-content/plugins/password-protect-wordpress/lava/_classes/lavaAdvancedTablePage.php | 2157 |
<?php
class lavaAdvancedTablePage extends lavaPage
{
public $dataSource;
public $dataCache;
public $displayOrder = array();
function loadPage() {
$this->addAction( "toolbarButtons" );
$this->_pages()->addScript( $this->_slug( "lavaTableScripts" ), "lava/_static/table_scripts.js", array( "jquery" ) );
}
function setDataSource( $dataSource )
{
$this->dataSource = $dataSource;
return $this->_pages( false );
}
function setDisplayOrder( $displayString )
{
$this->displayOrder = explode( ";", $displayString );
$dataSourceSlug = $this->dataSource;
$hookTag = "_dataSourceAjax_row/dataSource:{$dataSourceSlug}";
$this->addFilter( $hookTag, "doDisplayOrder" );
return $this->_pages( false );
}
function setOrderBy( $order ) {
$this->_tables()->fetchTable( $this->dataSource )->setOrderBy( $order );
return $this->_pages( false );
}
function displayPage() {
if( is_null( $this->dataSource ) ) {
$this->dieWith( "No data source specified for this page" );
}
$this->doTablePage();
}
function doTablePage() {
//$this->setHiddenField( "" )
?>
<div class="lava-layout lava-layout-full-width bleed-left bleed-right">
<div class="lava-inset-module lava-filters">
</div>
</div>
<?php
}
function toolbarButtons()
{
?>
<div class="toolbar-block toolbar-overground">
<button class="lava-btn lava-btn-action lava-btn-inline lava-btn-action-white lava-table-loader-refresh-button" data-clicked-text="<?php _e( "Refreshing", $this->_framework() ) ?>"><?php _e( "Refresh", $this->_framework() ) ?></button>
<button class="lava-btn lava-btn-action lava-btn-inline lava-btn-action-white lava-btn-form-submit lava-btn-confirmation not-implemented" data-form="lava-table-reset" data-clicked-text="<?php _e( "Resetting", $this->_framework() ) ?>"><?php _e( "Reset Settings", $this->_framework() ) ?></button>
</div>
<?php
}
}
?> | gpl-2.0 |
Elv13/awesome-1 | tests/test-screen-changes.lua | 3217 | -- Tests for screen additions & removals
local runner = require("_runner")
local test_client = require("_client")
local naughty = require("naughty")
local max = require("awful.layout.suit.max")
local real_screen = screen[1]
local fake_screen = screen.fake_add(50, 50, 500, 500)
local test_client1, test_client2
local list_count = 0
screen.connect_signal("list", function()
list_count = list_count + 1
end)
local steps = {
-- Step 1: Set up some clients to experiment with and assign them as needed
function(count)
if count == 1 then -- Setup.
test_client()
test_client()
end
local cls = client.get()
if #cls == 2 then
test_client1, test_client2 = cls[1], cls[2]
test_client1.screen = real_screen
test_client2.screen = fake_screen
-- Use a tiled layout
fake_screen.selected_tag.layout = max
-- Display a notification on the screen-to-be-removed
naughty.notification { message = "test", screen = fake_screen }
return true
end
end,
-- Step 2: Move the screen
function(count)
if count == 1 then
fake_screen:fake_resize(100, 110, 600, 610)
return
end
-- Everything should be done by now
local geom = test_client2:geometry()
local bw = test_client2.border_width
local ug = test_client2:tags()[1].gap
assert(geom.x - 2*ug == 100, geom.x - 2*ug)
assert(geom.y - 2*ug == 110, geom.y - 2*ug)
assert(geom.width + 2*bw + 4*ug == 600, geom.width + 2*bw + 4*ug)
assert(geom.height + 2*bw + 4*ug == 610, geom.height + 2*bw + 4*ug)
local wb = fake_screen.mywibox
assert(wb.screen == fake_screen, tostring(wb.screen) .. " ~= " .. tostring(fake_screen))
assert(wb.x == 100, wb.x)
assert(wb.y == 110, wb.y)
assert(wb.width == 600, wb.width)
-- Test screen order changes
assert(list_count == 0)
assert(screen[1] == real_screen)
assert(screen[2] == fake_screen)
real_screen:swap(fake_screen)
assert(list_count == 1)
assert(screen[2] == real_screen)
assert(screen[1] == fake_screen)
return true
end,
-- Step 3: Say goodbye to the screen
function()
local wb = fake_screen.mywibox
fake_screen:fake_remove()
-- Now that the screen is invalid, the wibox shouldn't refer to it any
-- more
assert(wb.screen ~= fake_screen)
-- Wrap in a weak table to allow garbage collection
fake_screen = setmetatable({ fake_screen }, { __mode = "v" })
return true
end,
-- Step 4: Everything should now be on the main screen, the old screen
-- should be garbage collectable
function()
assert(test_client1.screen == real_screen, test_client1.screen)
assert(test_client2.screen == real_screen, test_client2.screen)
collectgarbage("collect")
if #fake_screen == 0 then
return true
end
end,
}
runner.run_steps(steps)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
arto70/NDL-VuFind2 | module/VuFind/src/VuFind/Controller/AjaxResponseTrait.php | 6174 | <?php
/**
* Trait to allow AJAX response generation.
*
* PHP version 7
*
* Copyright (C) Villanova University 2018.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Controller
* @author Chris Hallberg <challber@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:controllers Wiki
*/
namespace VuFind\Controller;
use VuFind\AjaxHandler\AjaxHandlerInterface as Ajax;
use VuFind\AjaxHandler\PluginManager;
/**
* Trait to allow AJAX response generation.
*
* Dependencies:
* - \VuFind\I18n\Translator\TranslatorAwareTrait
* - Injection of $this->ajaxManager (for some functionality)
*
* @category VuFind
* @package Controller
* @author Chris Hallberg <challber@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:controllers Wiki
*/
trait AjaxResponseTrait
{
/**
* Array of PHP errors captured during execution. Add this code to your
* constructor in order to populate the array:
* set_error_handler([static::class, 'storeError']);
*
* @var array
*/
protected static $php_errors = [];
/**
* AJAX Handler plugin manager
*
* @var PluginManager;
*/
protected $ajaxManager = null;
/**
* Format the content of the AJAX response based on the response type.
*
* @param string $type Content-type of output
* @param mixed $data The response data
* @param int $httpCode A custom HTTP Status Code
*
* @return string
* @throws \Exception
*/
protected function formatContent($type, $data, $httpCode)
{
switch ($type) {
case 'application/javascript':
$output = ['data' => $data];
if ('development' == APPLICATION_ENV && count(self::$php_errors) > 0) {
$output['php_errors'] = self::$php_errors;
}
return json_encode($output);
case 'text/plain':
return ((null !== $httpCode && $httpCode >= 400) ? 'ERROR ' : 'OK ')
. $data;
case 'text/html':
return $data ?: '';
default:
throw new \Exception("Unsupported content type: $type");
}
}
/**
* Send output data and exit.
*
* @param string $type Content type to output
* @param mixed $data The response data
* @param int $httpCode A custom HTTP Status Code
*
* @return \Zend\Http\Response
* @throws \Exception
*/
protected function getAjaxResponse($type, $data, $httpCode = null)
{
$response = $this->getResponse();
$headers = $response->getHeaders();
$headers->addHeaderLine('Content-type', $type);
$headers->addHeaderLine('Cache-Control', 'no-cache, must-revalidate');
$headers->addHeaderLine('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT');
if ($httpCode !== null) {
$response->setStatusCode($httpCode);
}
$response->setContent($this->formatContent($type, $data, $httpCode));
return $response;
}
/**
* Turn an exception into error response.
*
* @param string $type Content type to output
* @param \Exception $e Exception to output.
*
* @return \Zend\Http\Response
*/
protected function getExceptionResponse($type, \Exception $e)
{
$debugMsg = ('development' == APPLICATION_ENV)
? ': ' . $e->getMessage() : '';
return $this->getAjaxResponse(
$type,
$this->translate('An error has occurred') . $debugMsg,
Ajax::STATUS_HTTP_ERROR
);
}
/**
* Call an AJAX method and turn the result into a response.
*
* @param string $method AJAX method to call
* @param string $type Content type to output
*
* @return \Zend\Http\Response
*/
protected function callAjaxMethod($method, $type = 'application/javascript')
{
// Check the AJAX handler plugin manager for the method.
if (!$this->ajaxManager) {
throw new \Exception('AJAX Handler Plugin Manager missing.');
}
if ($this->ajaxManager->has($method)) {
try {
$handler = $this->ajaxManager->get($method);
return $this->getAjaxResponse(
$type, ...$handler->handleRequest($this->params())
);
} catch (\Exception $e) {
return $this->getExceptionResponse($type, $e);
}
}
// If we got this far, we can't handle the requested method:
return $this->getAjaxResponse(
$type,
$this->translate('Invalid Method'),
Ajax::STATUS_HTTP_BAD_REQUEST
);
}
/**
* Store the errors for later, to be added to the output
*
* @param string $errno Error code number
* @param string $errstr Error message
* @param string $errfile File where error occurred
* @param string $errline Line number of error
*
* @return bool Always true to cancel default error handling
*/
public static function storeError($errno, $errstr, $errfile, $errline)
{
self::$php_errors[] = "ERROR [$errno] - " . $errstr . "<br />\n"
. " Occurred in " . $errfile . " on line " . $errline . ".";
return true;
}
}
| gpl-2.0 |
pspanja/ezpublish-kernel | eZ/Publish/Core/MVC/Symfony/Matcher/Tests/Block/Id/BlockTest.php | 1974 | <?php
/**
* File containing the BlockTest 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.
*/
namespace eZ\Publish\Core\MVC\Symfony\Matcher\Tests\Block\Id;
use eZ\Publish\Core\MVC\Symfony\Matcher\Block\Id\Block as BlockIdMatcher;
use eZ\Publish\Core\FieldType\Page\Parts\Block;
use PHPUnit\Framework\TestCase;
class BlockTest extends TestCase
{
/**
* @var \eZ\Publish\Core\MVC\Symfony\Matcher\Block\MatcherInterface
*/
private $matcher;
protected function setUp()
{
parent::setUp();
$this->matcher = new BlockIdMatcher();
}
/**
* @dataProvider matchBlockProvider
*
* @param $matchingConfig
* @param \eZ\Publish\Core\FieldType\Page\Parts\Block $block
* @param $expectedResult
*/
public function testMatchBlock($matchingConfig, Block $block, $expectedResult)
{
$this->matcher->setMatchingConfig($matchingConfig);
$this->assertSame($expectedResult, $this->matcher->matchBlock($block));
}
public function matchBlockProvider()
{
return array(
array(
123,
$this->generateBlockForId(123),
true,
),
array(
123,
$this->generateBlockForId(456),
false,
),
array(
array(123, 789),
$this->generateBlockForId(456),
false,
),
array(
array(123, 789),
$this->generateBlockForId(789),
true,
),
);
}
/**
* @param $id
*
* @return \eZ\Publish\Core\FieldType\Page\Parts\Block
*/
private function generateBlockForId($id)
{
return new Block(
array('id' => $id)
);
}
}
| gpl-2.0 |
valstu/jarpa | wp-content/plugins/sportspress/includes/admin/post-types/meta-boxes/class-sp-meta-box-calendar-feeds.php | 1414 | <?php
/**
* Calendar Feeds
*
* Based on a tutorial by Steve Thomas.
*
* @author ThemeBoy
* @category Admin
* @package SportsPress/Admin/Meta_Boxes
* @version 1.5
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
/**
* SP_Meta_Box_Calendar_Feeds
*/
class SP_Meta_Box_Calendar_Feeds {
/**
* Output the metabox
*/
public static function output( $post ) {
$feeds = new SP_Feeds();
$calendar_feeds = $feeds->calendar;
?>
<div>
<?php foreach ( $calendar_feeds as $slug => $formats ) { ?>
<?php $link = add_query_arg( 'feed', 'sp-' . $slug, untrailingslashit( get_post_permalink( $post ) ) ); ?>
<?php foreach ( $formats as $format ) { ?>
<?php
$protocol = sp_array_value( $format, 'protocol' );
if ( $protocol ) {
$feed = str_replace( array( 'http:', 'https:' ), 'webcal:', $link );
} else {
$feed = $link;
}
$prefix = sp_array_value( $format, 'prefix' );
if ( $prefix ) {
$feed = $prefix . urlencode( $feed );
}
?>
<p>
<strong><?php echo sp_array_value( $format, 'name' ); ?></strong>
<a class="sp-link" href="<?php echo $feed; ?>" target="_blank" title="<?php _e( 'Link', 'sportspress' ); ?>"></a>
</p>
<p>
<input type="text" value="<?php echo $feed; ?>" readonly="readonly" class="code widefat">
</p>
<?php } ?>
<?php } ?>
</div>
<?php
}
} | gpl-2.0 |
spxtr/dolphin | Source/Core/Core/PowerPC/JitArm64/JitArm64_Integer.cpp | 31441 | // Copyright 2014 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include "Common/Arm64Emitter.h"
#include "Common/Assert.h"
#include "Common/BitUtils.h"
#include "Common/CommonTypes.h"
#include "Core/Core.h"
#include "Core/CoreTiming.h"
#include "Core/PowerPC/JitArm64/Jit.h"
#include "Core/PowerPC/JitArm64/JitArm64_RegCache.h"
#include "Core/PowerPC/PPCTables.h"
#include "Core/PowerPC/PowerPC.h"
using namespace Arm64Gen;
void JitArm64::ComputeRC0(ARM64Reg reg)
{
gpr.BindCRToRegister(0, false);
SXTW(gpr.CR(0), reg);
}
void JitArm64::ComputeRC0(u64 imm)
{
gpr.BindCRToRegister(0, false);
MOVI2R(gpr.CR(0), imm);
if (imm & 0x80000000)
SXTW(gpr.CR(0), DecodeReg(gpr.CR(0)));
}
void JitArm64::ComputeCarry(bool Carry)
{
js.carryFlagSet = false;
if (!js.op->wantsCA)
return;
if (Carry)
{
ARM64Reg WA = gpr.GetReg();
MOVI2R(WA, 1);
STRB(INDEX_UNSIGNED, WA, PPC_REG, PPCSTATE_OFF(xer_ca));
gpr.Unlock(WA);
return;
}
STRB(INDEX_UNSIGNED, WSP, PPC_REG, PPCSTATE_OFF(xer_ca));
}
void JitArm64::ComputeCarry()
{
js.carryFlagSet = false;
if (!js.op->wantsCA)
return;
js.carryFlagSet = true;
if (CanMergeNextInstructions(1) && js.op[1].opinfo->type == ::OpType::Integer)
{
return;
}
FlushCarry();
}
void JitArm64::FlushCarry()
{
if (!js.carryFlagSet)
return;
ARM64Reg WA = gpr.GetReg();
CSINC(WA, WSP, WSP, CC_CC);
STRB(INDEX_UNSIGNED, WA, PPC_REG, PPCSTATE_OFF(xer_ca));
gpr.Unlock(WA);
js.carryFlagSet = false;
}
void JitArm64::reg_imm(u32 d, u32 a, u32 value, u32 (*do_op)(u32, u32),
void (ARM64XEmitter::*op)(ARM64Reg, ARM64Reg, u64, ARM64Reg), bool Rc)
{
if (gpr.IsImm(a))
{
gpr.SetImmediate(d, do_op(gpr.GetImm(a), value));
if (Rc)
ComputeRC0(gpr.GetImm(d));
}
else
{
gpr.BindToRegister(d, d == a);
ARM64Reg WA = gpr.GetReg();
(this->*op)(gpr.R(d), gpr.R(a), value, WA);
gpr.Unlock(WA);
if (Rc)
ComputeRC0(gpr.R(d));
}
}
static constexpr u32 BitOR(u32 a, u32 b)
{
return a | b;
}
static constexpr u32 BitAND(u32 a, u32 b)
{
return a & b;
}
static constexpr u32 BitXOR(u32 a, u32 b)
{
return a ^ b;
}
void JitArm64::arith_imm(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
u32 a = inst.RA, s = inst.RS;
switch (inst.OPCD)
{
case 24: // ori
case 25: // oris
{
// check for nop
if (a == s && inst.UIMM == 0)
{
// NOP
return;
}
const u32 immediate = inst.OPCD == 24 ? inst.UIMM : inst.UIMM << 16;
reg_imm(a, s, immediate, BitOR, &ARM64XEmitter::ORRI2R);
break;
}
case 28: // andi
reg_imm(a, s, inst.UIMM, BitAND, &ARM64XEmitter::ANDI2R, true);
break;
case 29: // andis
reg_imm(a, s, inst.UIMM << 16, BitAND, &ARM64XEmitter::ANDI2R, true);
break;
case 26: // xori
case 27: // xoris
{
if (a == s && inst.UIMM == 0)
{
// NOP
return;
}
const u32 immediate = inst.OPCD == 26 ? inst.UIMM : inst.UIMM << 16;
reg_imm(a, s, immediate, BitXOR, &ARM64XEmitter::EORI2R);
break;
}
}
}
void JitArm64::addix(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
u32 d = inst.RD, a = inst.RA;
u32 imm = (u32)(s32)inst.SIMM_16;
if (inst.OPCD == 15)
{
imm <<= 16;
}
if (a)
{
if (gpr.IsImm(a))
{
gpr.SetImmediate(d, gpr.GetImm(a) + imm);
}
else
{
gpr.BindToRegister(d, d == a);
ARM64Reg WA = gpr.GetReg();
ADDI2R(gpr.R(d), gpr.R(a), imm, WA);
gpr.Unlock(WA);
}
}
else
{
// a == 0, implies zero register
gpr.SetImmediate(d, imm);
}
}
void JitArm64::boolX(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
int a = inst.RA, s = inst.RS, b = inst.RB;
if (gpr.IsImm(s) && gpr.IsImm(b))
{
if (inst.SUBOP10 == 28) // andx
gpr.SetImmediate(a, (u32)gpr.GetImm(s) & (u32)gpr.GetImm(b));
else if (inst.SUBOP10 == 476) // nandx
gpr.SetImmediate(a, ~((u32)gpr.GetImm(s) & (u32)gpr.GetImm(b)));
else if (inst.SUBOP10 == 60) // andcx
gpr.SetImmediate(a, (u32)gpr.GetImm(s) & (~(u32)gpr.GetImm(b)));
else if (inst.SUBOP10 == 444) // orx
gpr.SetImmediate(a, (u32)gpr.GetImm(s) | (u32)gpr.GetImm(b));
else if (inst.SUBOP10 == 124) // norx
gpr.SetImmediate(a, ~((u32)gpr.GetImm(s) | (u32)gpr.GetImm(b)));
else if (inst.SUBOP10 == 412) // orcx
gpr.SetImmediate(a, (u32)gpr.GetImm(s) | (~(u32)gpr.GetImm(b)));
else if (inst.SUBOP10 == 316) // xorx
gpr.SetImmediate(a, (u32)gpr.GetImm(s) ^ (u32)gpr.GetImm(b));
else if (inst.SUBOP10 == 284) // eqvx
gpr.SetImmediate(a, ~((u32)gpr.GetImm(s) ^ (u32)gpr.GetImm(b)));
if (inst.Rc)
ComputeRC0(gpr.GetImm(a));
}
else if (s == b)
{
if ((inst.SUBOP10 == 28 /* andx */) || (inst.SUBOP10 == 444 /* orx */))
{
if (a != s)
{
gpr.BindToRegister(a, false);
MOV(gpr.R(a), gpr.R(s));
}
if (inst.Rc)
ComputeRC0(gpr.R(a));
}
else if ((inst.SUBOP10 == 476 /* nandx */) || (inst.SUBOP10 == 124 /* norx */))
{
gpr.BindToRegister(a, a == s);
MVN(gpr.R(a), gpr.R(s));
if (inst.Rc)
ComputeRC0(gpr.R(a));
}
else if ((inst.SUBOP10 == 412 /* orcx */) || (inst.SUBOP10 == 284 /* eqvx */))
{
gpr.SetImmediate(a, 0xFFFFFFFF);
if (inst.Rc)
ComputeRC0(gpr.GetImm(a));
}
else if ((inst.SUBOP10 == 60 /* andcx */) || (inst.SUBOP10 == 316 /* xorx */))
{
gpr.SetImmediate(a, 0);
if (inst.Rc)
ComputeRC0(gpr.GetImm(a));
}
else
{
PanicAlert("WTF!");
}
}
else
{
gpr.BindToRegister(a, (a == s) || (a == b));
if (inst.SUBOP10 == 28) // andx
{
AND(gpr.R(a), gpr.R(s), gpr.R(b));
}
else if (inst.SUBOP10 == 476) // nandx
{
AND(gpr.R(a), gpr.R(s), gpr.R(b));
MVN(gpr.R(a), gpr.R(a));
}
else if (inst.SUBOP10 == 60) // andcx
{
BIC(gpr.R(a), gpr.R(s), gpr.R(b));
}
else if (inst.SUBOP10 == 444) // orx
{
ORR(gpr.R(a), gpr.R(s), gpr.R(b));
}
else if (inst.SUBOP10 == 124) // norx
{
ORR(gpr.R(a), gpr.R(s), gpr.R(b));
MVN(gpr.R(a), gpr.R(a));
}
else if (inst.SUBOP10 == 412) // orcx
{
ORN(gpr.R(a), gpr.R(s), gpr.R(b));
}
else if (inst.SUBOP10 == 316) // xorx
{
EOR(gpr.R(a), gpr.R(s), gpr.R(b));
}
else if (inst.SUBOP10 == 284) // eqvx
{
EON(gpr.R(a), gpr.R(b), gpr.R(s));
}
else
{
PanicAlert("WTF!");
}
if (inst.Rc)
ComputeRC0(gpr.R(a));
}
}
void JitArm64::addx(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
FALLBACK_IF(inst.OE);
int a = inst.RA, b = inst.RB, d = inst.RD;
if (gpr.IsImm(a) && gpr.IsImm(b))
{
s32 i = (s32)gpr.GetImm(a), j = (s32)gpr.GetImm(b);
gpr.SetImmediate(d, i + j);
if (inst.Rc)
ComputeRC0(gpr.GetImm(d));
}
else if (gpr.IsImm(a) || gpr.IsImm(b))
{
int imm_reg = gpr.IsImm(a) ? a : b;
int in_reg = gpr.IsImm(a) ? b : a;
gpr.BindToRegister(d, d == in_reg);
ARM64Reg WA = gpr.GetReg();
ADDI2R(gpr.R(d), gpr.R(in_reg), gpr.GetImm(imm_reg), WA);
gpr.Unlock(WA);
if (inst.Rc)
ComputeRC0(gpr.R(d));
}
else
{
gpr.BindToRegister(d, d == a || d == b);
ADD(gpr.R(d), gpr.R(a), gpr.R(b));
if (inst.Rc)
ComputeRC0(gpr.R(d));
}
}
void JitArm64::extsXx(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
int a = inst.RA, s = inst.RS;
int size = inst.SUBOP10 == 922 ? 16 : 8;
if (gpr.IsImm(s))
{
gpr.SetImmediate(a, (u32)(s32)(size == 16 ? (s16)gpr.GetImm(s) : (s8)gpr.GetImm(s)));
if (inst.Rc)
ComputeRC0(gpr.GetImm(a));
}
else
{
gpr.BindToRegister(a, a == s);
SBFM(gpr.R(a), gpr.R(s), 0, size - 1);
if (inst.Rc)
ComputeRC0(gpr.R(a));
}
}
void JitArm64::cntlzwx(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
int a = inst.RA;
int s = inst.RS;
if (gpr.IsImm(s))
{
gpr.SetImmediate(a, __builtin_clz(gpr.GetImm(s)));
if (inst.Rc)
ComputeRC0(gpr.GetImm(a));
}
else
{
gpr.BindToRegister(a, a == s);
CLZ(gpr.R(a), gpr.R(s));
if (inst.Rc)
ComputeRC0(gpr.R(a));
}
}
void JitArm64::negx(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
int a = inst.RA;
int d = inst.RD;
FALLBACK_IF(inst.OE);
if (gpr.IsImm(a))
{
gpr.SetImmediate(d, ~((u32)gpr.GetImm(a)) + 1);
if (inst.Rc)
ComputeRC0(gpr.GetImm(d));
}
else
{
gpr.BindToRegister(d, d == a);
SUB(gpr.R(d), WSP, gpr.R(a));
if (inst.Rc)
ComputeRC0(gpr.R(d));
}
}
void JitArm64::cmp(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
int crf = inst.CRFD;
u32 a = inst.RA, b = inst.RB;
gpr.BindCRToRegister(crf, false);
ARM64Reg CR = gpr.CR(crf);
if (gpr.IsImm(a) && gpr.IsImm(b))
{
s64 A = static_cast<s32>(gpr.GetImm(a));
s64 B = static_cast<s32>(gpr.GetImm(b));
MOVI2R(CR, A - B);
return;
}
if (gpr.IsImm(b) && !gpr.GetImm(b))
{
SXTW(CR, gpr.R(a));
return;
}
ARM64Reg WA = gpr.GetReg();
ARM64Reg XA = EncodeRegTo64(WA);
ARM64Reg RA = gpr.R(a);
ARM64Reg RB = gpr.R(b);
SXTW(XA, RA);
SXTW(CR, RB);
SUB(CR, XA, CR);
gpr.Unlock(WA);
}
void JitArm64::cmpl(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
int crf = inst.CRFD;
u32 a = inst.RA, b = inst.RB;
gpr.BindCRToRegister(crf, false);
ARM64Reg CR = gpr.CR(crf);
if (gpr.IsImm(a) && gpr.IsImm(b))
{
u64 A = gpr.GetImm(a);
u64 B = gpr.GetImm(b);
MOVI2R(CR, A - B);
return;
}
if (gpr.IsImm(b) && !gpr.GetImm(b))
{
MOV(DecodeReg(CR), gpr.R(a));
return;
}
SUB(gpr.CR(crf), EncodeRegTo64(gpr.R(a)), EncodeRegTo64(gpr.R(b)));
}
void JitArm64::cmpi(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
u32 a = inst.RA;
s64 B = inst.SIMM_16;
int crf = inst.CRFD;
gpr.BindCRToRegister(crf, false);
ARM64Reg CR = gpr.CR(crf);
if (gpr.IsImm(a))
{
s64 A = static_cast<s32>(gpr.GetImm(a));
MOVI2R(CR, A - B);
return;
}
SXTW(CR, gpr.R(a));
if (B != 0)
{
ARM64Reg WA = gpr.GetReg();
SUBI2R(CR, CR, B, EncodeRegTo64(WA));
gpr.Unlock(WA);
}
}
void JitArm64::cmpli(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
u32 a = inst.RA;
u64 B = inst.UIMM;
int crf = inst.CRFD;
gpr.BindCRToRegister(crf, false);
ARM64Reg CR = gpr.CR(crf);
if (gpr.IsImm(a))
{
u64 A = gpr.GetImm(a);
MOVI2R(CR, A - B);
return;
}
if (!B)
{
MOV(DecodeReg(CR), gpr.R(a));
return;
}
SUBI2R(CR, EncodeRegTo64(gpr.R(a)), B, CR);
}
void JitArm64::rlwinmx(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
u32 a = inst.RA, s = inst.RS;
u32 mask = Helper_Mask(inst.MB, inst.ME);
if (gpr.IsImm(inst.RS))
{
gpr.SetImmediate(a, Common::RotateLeft(gpr.GetImm(s), inst.SH) & mask);
if (inst.Rc)
ComputeRC0(gpr.GetImm(a));
return;
}
gpr.BindToRegister(a, a == s);
if (!inst.SH && mask == 0xFFFFFFFF)
{
if (a != s)
MOV(gpr.R(a), gpr.R(s));
}
else if (!inst.SH)
{
// Immediate mask
ANDI2R(gpr.R(a), gpr.R(s), mask);
}
else if (inst.ME == 31 && 31 < inst.SH + inst.MB)
{
// Bit select of the upper part
UBFX(gpr.R(a), gpr.R(s), 32 - inst.SH, 32 - inst.MB);
}
else if (inst.ME == 31 - inst.SH && 32 > inst.SH + inst.MB)
{
// Bit select of the lower part
UBFIZ(gpr.R(a), gpr.R(s), inst.SH, 32 - inst.SH - inst.MB);
}
else
{
ARM64Reg WA = gpr.GetReg();
MOVI2R(WA, mask);
AND(gpr.R(a), WA, gpr.R(s), ArithOption(gpr.R(s), ST_ROR, 32 - inst.SH));
gpr.Unlock(WA);
}
if (inst.Rc)
ComputeRC0(gpr.R(a));
}
void JitArm64::rlwnmx(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
u32 a = inst.RA, b = inst.RB, s = inst.RS;
u32 mask = Helper_Mask(inst.MB, inst.ME);
if (gpr.IsImm(b) && gpr.IsImm(s))
{
gpr.SetImmediate(a, Common::RotateLeft(gpr.GetImm(s), gpr.GetImm(b) & 0x1F) & mask);
if (inst.Rc)
ComputeRC0(gpr.GetImm(a));
}
else if (gpr.IsImm(b))
{
gpr.BindToRegister(a, a == s);
ARM64Reg WA = gpr.GetReg();
ArithOption Shift(gpr.R(s), ST_ROR, 32 - (gpr.GetImm(b) & 0x1f));
MOVI2R(WA, mask);
AND(gpr.R(a), WA, gpr.R(s), Shift);
gpr.Unlock(WA);
if (inst.Rc)
ComputeRC0(gpr.R(a));
}
else
{
gpr.BindToRegister(a, a == s || a == b);
ARM64Reg WA = gpr.GetReg();
NEG(WA, gpr.R(b));
RORV(gpr.R(a), gpr.R(s), WA);
ANDI2R(gpr.R(a), gpr.R(a), mask, WA);
gpr.Unlock(WA);
if (inst.Rc)
ComputeRC0(gpr.R(a));
}
}
void JitArm64::srawix(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
int a = inst.RA;
int s = inst.RS;
int amount = inst.SH;
bool inplace_carry = CanMergeNextInstructions(1) && js.op[1].wantsCAInFlags;
if (gpr.IsImm(s))
{
s32 imm = (s32)gpr.GetImm(s);
gpr.SetImmediate(a, imm >> amount);
if (amount != 0 && (imm < 0) && (imm << (32 - amount)))
ComputeCarry(true);
else
ComputeCarry(false);
}
else if (amount == 0)
{
gpr.BindToRegister(a, a == s);
ARM64Reg RA = gpr.R(a);
ARM64Reg RS = gpr.R(s);
MOV(RA, RS);
ComputeCarry(false);
}
else
{
gpr.BindToRegister(a, a == s);
ARM64Reg RA = gpr.R(a);
ARM64Reg RS = gpr.R(s);
if (js.op->wantsCA)
{
ARM64Reg WA = gpr.GetReg();
ARM64Reg dest = inplace_carry ? WA : WSP;
if (a != s)
{
ASR(RA, RS, amount);
ANDS(dest, RA, RS, ArithOption(RS, ST_LSL, 32 - amount));
}
else
{
LSL(WA, RS, 32 - amount);
ASR(RA, RS, amount);
ANDS(dest, WA, RA);
}
if (inplace_carry)
{
CMP(dest, 1);
ComputeCarry();
}
else
{
CSINC(WA, WSP, WSP, CC_EQ);
STRB(INDEX_UNSIGNED, WA, PPC_REG, PPCSTATE_OFF(xer_ca));
}
gpr.Unlock(WA);
}
else
{
ASR(RA, RS, amount);
}
if (inst.Rc)
ComputeRC0(RA);
}
}
void JitArm64::addic(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
int a = inst.RA, d = inst.RD;
bool rc = inst.OPCD == 13;
s32 simm = inst.SIMM_16;
u32 imm = (u32)simm;
if (gpr.IsImm(a))
{
u32 i = gpr.GetImm(a);
gpr.SetImmediate(d, i + imm);
bool has_carry = Interpreter::Helper_Carry(i, imm);
ComputeCarry(has_carry);
if (rc)
ComputeRC0(gpr.GetImm(d));
}
else
{
gpr.BindToRegister(d, d == a);
ARM64Reg WA = gpr.GetReg();
ADDSI2R(gpr.R(d), gpr.R(a), simm, WA);
gpr.Unlock(WA);
ComputeCarry();
if (rc)
ComputeRC0(gpr.R(d));
}
}
void JitArm64::mulli(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
int a = inst.RA, d = inst.RD;
if (gpr.IsImm(a))
{
s32 i = (s32)gpr.GetImm(a);
gpr.SetImmediate(d, i * inst.SIMM_16);
}
else
{
gpr.BindToRegister(d, d == a);
ARM64Reg WA = gpr.GetReg();
MOVI2R(WA, (u32)(s32)inst.SIMM_16);
MUL(gpr.R(d), gpr.R(a), WA);
gpr.Unlock(WA);
}
}
void JitArm64::mullwx(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
FALLBACK_IF(inst.OE);
int a = inst.RA, b = inst.RB, d = inst.RD;
if (gpr.IsImm(a) && gpr.IsImm(b))
{
s32 i = (s32)gpr.GetImm(a), j = (s32)gpr.GetImm(b);
gpr.SetImmediate(d, i * j);
if (inst.Rc)
ComputeRC0(gpr.GetImm(d));
}
else
{
gpr.BindToRegister(d, d == a || d == b);
MUL(gpr.R(d), gpr.R(a), gpr.R(b));
if (inst.Rc)
ComputeRC0(gpr.R(d));
}
}
void JitArm64::mulhwx(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
int a = inst.RA, b = inst.RB, d = inst.RD;
if (gpr.IsImm(a) && gpr.IsImm(b))
{
s32 i = (s32)gpr.GetImm(a), j = (s32)gpr.GetImm(b);
gpr.SetImmediate(d, (u32)((u64)(((s64)i * (s64)j)) >> 32));
if (inst.Rc)
ComputeRC0(gpr.GetImm(d));
}
else
{
gpr.BindToRegister(d, d == a || d == b);
SMULL(EncodeRegTo64(gpr.R(d)), gpr.R(a), gpr.R(b));
LSR(EncodeRegTo64(gpr.R(d)), EncodeRegTo64(gpr.R(d)), 32);
if (inst.Rc)
ComputeRC0(gpr.R(d));
}
}
void JitArm64::mulhwux(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
int a = inst.RA, b = inst.RB, d = inst.RD;
if (gpr.IsImm(a) && gpr.IsImm(b))
{
u32 i = gpr.GetImm(a), j = gpr.GetImm(b);
gpr.SetImmediate(d, (u32)(((u64)i * (u64)j) >> 32));
if (inst.Rc)
ComputeRC0(gpr.GetImm(d));
}
else
{
gpr.BindToRegister(d, d == a || d == b);
UMULL(EncodeRegTo64(gpr.R(d)), gpr.R(a), gpr.R(b));
LSR(EncodeRegTo64(gpr.R(d)), EncodeRegTo64(gpr.R(d)), 32);
if (inst.Rc)
ComputeRC0(gpr.R(d));
}
}
void JitArm64::addzex(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
FALLBACK_IF(inst.OE);
int a = inst.RA, d = inst.RD;
if (js.carryFlagSet)
{
gpr.BindToRegister(d, d == a);
ADCS(gpr.R(d), gpr.R(a), WZR);
}
else if (d == a)
{
gpr.BindToRegister(d, true);
ARM64Reg WA = gpr.GetReg();
LDRB(INDEX_UNSIGNED, WA, PPC_REG, PPCSTATE_OFF(xer_ca));
ADDS(gpr.R(d), gpr.R(a), WA);
gpr.Unlock(WA);
}
else
{
gpr.BindToRegister(d, false);
LDRB(INDEX_UNSIGNED, gpr.R(d), PPC_REG, PPCSTATE_OFF(xer_ca));
ADDS(gpr.R(d), gpr.R(a), gpr.R(d));
}
ComputeCarry();
if (inst.Rc)
ComputeRC0(gpr.R(d));
}
void JitArm64::subfx(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
FALLBACK_IF(inst.OE);
int a = inst.RA, b = inst.RB, d = inst.RD;
if (gpr.IsImm(a) && gpr.IsImm(b))
{
u32 i = gpr.GetImm(a), j = gpr.GetImm(b);
gpr.SetImmediate(d, j - i);
if (inst.Rc)
ComputeRC0(gpr.GetImm(d));
}
else
{
gpr.BindToRegister(d, d == a || d == b);
SUB(gpr.R(d), gpr.R(b), gpr.R(a));
if (inst.Rc)
ComputeRC0(gpr.R(d));
}
}
void JitArm64::subfex(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
FALLBACK_IF(inst.OE);
int a = inst.RA, b = inst.RB, d = inst.RD;
if (gpr.IsImm(a) && gpr.IsImm(b))
{
u32 i = gpr.GetImm(a), j = gpr.GetImm(b);
gpr.BindToRegister(d, false);
ARM64Reg WA = gpr.GetReg();
if (js.carryFlagSet)
{
MOVI2R(WA, ~i + j, gpr.R(d));
ADC(gpr.R(d), WA, WZR);
}
else
{
LDRB(INDEX_UNSIGNED, WA, PPC_REG, PPCSTATE_OFF(xer_ca));
ADDI2R(gpr.R(d), WA, ~i + j, gpr.R(d));
}
gpr.Unlock(WA);
bool must_have_carry = Interpreter::Helper_Carry(~i, j);
bool might_have_carry = (~i + j) == 0xFFFFFFFF;
if (must_have_carry)
{
ComputeCarry(true);
}
else if (might_have_carry)
{
// carry stay as it is
}
else
{
ComputeCarry(false);
}
}
else
{
ARM64Reg WA = gpr.GetReg();
gpr.BindToRegister(d, d == a || d == b);
// upload the carry state
if (!js.carryFlagSet)
{
LDRB(INDEX_UNSIGNED, WA, PPC_REG, PPCSTATE_OFF(xer_ca));
CMP(WA, 1);
}
// d = ~a + b + carry;
if (gpr.IsImm(a))
MOVI2R(WA, ~gpr.GetImm(a));
else
MVN(WA, gpr.R(a));
ADCS(gpr.R(d), WA, gpr.R(b));
gpr.Unlock(WA);
ComputeCarry();
}
if (inst.Rc)
ComputeRC0(gpr.R(d));
}
void JitArm64::subfcx(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
FALLBACK_IF(inst.OE);
int a = inst.RA, b = inst.RB, d = inst.RD;
if (gpr.IsImm(a) && gpr.IsImm(b))
{
u32 a_imm = gpr.GetImm(a), b_imm = gpr.GetImm(b);
gpr.SetImmediate(d, b_imm - a_imm);
ComputeCarry(a_imm == 0 || Interpreter::Helper_Carry(b_imm, 0u - a_imm));
if (inst.Rc)
ComputeRC0(gpr.GetImm(d));
}
else
{
gpr.BindToRegister(d, d == a || d == b);
// d = b - a
SUBS(gpr.R(d), gpr.R(b), gpr.R(a));
ComputeCarry();
if (inst.Rc)
ComputeRC0(gpr.R(d));
}
}
void JitArm64::subfzex(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
FALLBACK_IF(inst.OE);
int a = inst.RA, d = inst.RD;
gpr.BindToRegister(d, d == a);
if (js.carryFlagSet)
{
MVN(gpr.R(d), gpr.R(a));
ADCS(gpr.R(d), gpr.R(d), WZR);
}
else
{
ARM64Reg WA = gpr.GetReg();
LDRB(INDEX_UNSIGNED, WA, PPC_REG, PPCSTATE_OFF(xer_ca));
MVN(gpr.R(d), gpr.R(a));
ADDS(gpr.R(d), gpr.R(d), WA);
gpr.Unlock(WA);
}
ComputeCarry();
if (inst.Rc)
ComputeRC0(gpr.R(d));
}
void JitArm64::subfic(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
int a = inst.RA, d = inst.RD;
s32 imm = inst.SIMM_16;
if (gpr.IsImm(a))
{
u32 a_imm = gpr.GetImm(a);
gpr.SetImmediate(d, imm - a_imm);
ComputeCarry(a_imm == 0 || Interpreter::Helper_Carry(imm, 0u - a_imm));
}
else
{
gpr.BindToRegister(d, d == a);
// d = imm - a
ARM64Reg WA = gpr.GetReg();
MOVI2R(WA, imm);
SUBS(gpr.R(d), WA, gpr.R(a));
gpr.Unlock(WA);
ComputeCarry();
}
}
void JitArm64::addex(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
FALLBACK_IF(inst.OE);
int a = inst.RA, b = inst.RB, d = inst.RD;
if (gpr.IsImm(a) && gpr.IsImm(b))
{
u32 i = gpr.GetImm(a), j = gpr.GetImm(b);
gpr.BindToRegister(d, false);
ARM64Reg WA = gpr.GetReg();
if (js.carryFlagSet)
{
MOVI2R(WA, i + j);
ADC(gpr.R(d), WA, WZR);
}
else
{
LDRB(INDEX_UNSIGNED, WA, PPC_REG, PPCSTATE_OFF(xer_ca));
ADDI2R(gpr.R(d), WA, i + j, gpr.R(d));
}
gpr.Unlock(WA);
bool must_have_carry = Interpreter::Helper_Carry(i, j);
bool might_have_carry = (i + j) == 0xFFFFFFFF;
if (must_have_carry)
{
ComputeCarry(true);
}
else if (might_have_carry)
{
// carry stay as it is
}
else
{
ComputeCarry(false);
}
}
else
{
gpr.BindToRegister(d, d == a || d == b);
// upload the carry state
if (!js.carryFlagSet)
{
ARM64Reg WA = gpr.GetReg();
LDRB(INDEX_UNSIGNED, WA, PPC_REG, PPCSTATE_OFF(xer_ca));
CMP(WA, 1);
gpr.Unlock(WA);
}
// d = a + b + carry;
ADCS(gpr.R(d), gpr.R(a), gpr.R(b));
ComputeCarry();
}
if (inst.Rc)
ComputeRC0(gpr.R(d));
}
void JitArm64::addcx(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
FALLBACK_IF(inst.OE);
int a = inst.RA, b = inst.RB, d = inst.RD;
if (gpr.IsImm(a) && gpr.IsImm(b))
{
u32 i = gpr.GetImm(a), j = gpr.GetImm(b);
gpr.SetImmediate(d, i + j);
bool has_carry = Interpreter::Helper_Carry(i, j);
ComputeCarry(has_carry);
if (inst.Rc)
ComputeRC0(gpr.GetImm(d));
}
else
{
gpr.BindToRegister(d, d == a || d == b);
ADDS(gpr.R(d), gpr.R(a), gpr.R(b));
ComputeCarry();
if (inst.Rc)
ComputeRC0(gpr.R(d));
}
}
void JitArm64::divwux(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
FALLBACK_IF(inst.OE);
int a = inst.RA, b = inst.RB, d = inst.RD;
if (gpr.IsImm(a) && gpr.IsImm(b))
{
u32 i = gpr.GetImm(a), j = gpr.GetImm(b);
gpr.SetImmediate(d, j == 0 ? 0 : i / j);
if (inst.Rc)
ComputeRC0(gpr.GetImm(d));
}
else
{
gpr.BindToRegister(d, d == a || d == b);
// d = a / b
UDIV(gpr.R(d), gpr.R(a), gpr.R(b));
if (inst.Rc)
ComputeRC0(gpr.R(d));
}
}
void JitArm64::divwx(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
FALLBACK_IF(inst.OE);
int a = inst.RA, b = inst.RB, d = inst.RD;
if (gpr.IsImm(a) && gpr.IsImm(b))
{
s32 imm_a = gpr.GetImm(a);
s32 imm_b = gpr.GetImm(b);
s32 imm_d;
if (imm_b == 0 || ((u32)imm_a == 0x80000000 && imm_b == -1))
{
if (((u32)imm_a & 0x80000000) && imm_b == 0)
imm_d = -1;
else
imm_d = 0;
}
else
{
imm_d = (u32)(imm_a / imm_b);
}
gpr.SetImmediate(d, imm_d);
if (inst.Rc)
ComputeRC0(imm_d);
}
else if (gpr.IsImm(b) && gpr.GetImm(b) != 0 && gpr.GetImm(b) != -1u)
{
ARM64Reg WA = gpr.GetReg();
MOVI2R(WA, gpr.GetImm(b));
gpr.BindToRegister(d, d == a);
SDIV(gpr.R(d), gpr.R(a), WA);
gpr.Unlock(WA);
if (inst.Rc)
ComputeRC0(gpr.R(d));
}
else
{
FlushCarry();
gpr.BindToRegister(d, d == a || d == b);
ARM64Reg WA = gpr.GetReg();
ARM64Reg RA = gpr.R(a);
ARM64Reg RB = gpr.R(b);
ARM64Reg RD = gpr.R(d);
FixupBranch slow1 = CBZ(RB);
MOVI2R(WA, -0x80000000LL);
CMP(RA, WA);
CCMN(RB, 1, 0, CC_EQ);
FixupBranch slow2 = B(CC_EQ);
SDIV(RD, RA, RB);
FixupBranch done = B();
SetJumpTarget(slow1);
SetJumpTarget(slow2);
CMP(RB, 0);
CCMP(RA, 0, 0, CC_EQ);
CSETM(RD, CC_LT);
SetJumpTarget(done);
gpr.Unlock(WA);
if (inst.Rc)
ComputeRC0(RD);
}
}
void JitArm64::slwx(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
int a = inst.RA, b = inst.RB, s = inst.RS;
if (gpr.IsImm(b) && gpr.IsImm(s))
{
u32 i = gpr.GetImm(s), j = gpr.GetImm(b);
gpr.SetImmediate(a, (j & 0x20) ? 0 : i << (j & 0x1F));
if (inst.Rc)
ComputeRC0(gpr.GetImm(a));
}
else if (gpr.IsImm(b))
{
u32 i = gpr.GetImm(b);
if (i & 0x20)
{
gpr.SetImmediate(a, 0);
if (inst.Rc)
ComputeRC0(0);
}
else
{
gpr.BindToRegister(a, a == s);
LSL(gpr.R(a), gpr.R(s), i & 0x1F);
if (inst.Rc)
ComputeRC0(gpr.R(a));
}
}
else
{
gpr.BindToRegister(a, a == b || a == s);
// PowerPC any shift in the 32-63 register range results in zero
// Since it has 32bit registers
// AArch64 it will use a mask of the register size for determining what shift amount
// So if we use a 64bit so the bits will end up in the high 32bits, and
// Later instructions will just eat high 32bits since it'll run 32bit operations for everything.
LSLV(EncodeRegTo64(gpr.R(a)), EncodeRegTo64(gpr.R(s)), EncodeRegTo64(gpr.R(b)));
if (inst.Rc)
ComputeRC0(gpr.R(a));
}
}
void JitArm64::srwx(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
int a = inst.RA, b = inst.RB, s = inst.RS;
if (gpr.IsImm(b) && gpr.IsImm(s))
{
u32 i = gpr.GetImm(s), amount = gpr.GetImm(b);
gpr.SetImmediate(a, (amount & 0x20) ? 0 : i >> (amount & 0x1F));
if (inst.Rc)
ComputeRC0(gpr.GetImm(a));
}
else if (gpr.IsImm(b))
{
u32 amount = gpr.GetImm(b);
if (amount & 0x20)
{
gpr.SetImmediate(a, 0);
if (inst.Rc)
ComputeRC0(0);
}
else
{
gpr.BindToRegister(a, a == s);
LSR(gpr.R(a), gpr.R(s), amount & 0x1F);
if (inst.Rc)
ComputeRC0(gpr.R(a));
}
}
else
{
gpr.BindToRegister(a, a == b || a == s);
// wipe upper bits. TODO: get rid of it, but then no instruction is allowed to emit some higher
// bits.
MOV(gpr.R(s), gpr.R(s));
LSRV(EncodeRegTo64(gpr.R(a)), EncodeRegTo64(gpr.R(s)), EncodeRegTo64(gpr.R(b)));
if (inst.Rc)
ComputeRC0(gpr.R(a));
}
}
void JitArm64::srawx(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
int a = inst.RA, b = inst.RB, s = inst.RS;
bool inplace_carry = CanMergeNextInstructions(1) && js.op[1].wantsCAInFlags;
if (gpr.IsImm(b) && gpr.IsImm(s))
{
s32 i = gpr.GetImm(s), amount = gpr.GetImm(b);
if (amount & 0x20)
{
gpr.SetImmediate(a, i & 0x80000000 ? 0xFFFFFFFF : 0);
ComputeCarry(i & 0x80000000 ? true : false);
}
else
{
amount &= 0x1F;
gpr.SetImmediate(a, i >> amount);
ComputeCarry(amount != 0 && i < 0 && (i << (32 - amount)));
}
if (inst.Rc)
ComputeRC0(gpr.GetImm(a));
return;
}
if (gpr.IsImm(b) && !js.op->wantsCA)
{
int amount = gpr.GetImm(b);
if (amount & 0x20)
amount = 0x1F;
else
amount &= 0x1F;
gpr.BindToRegister(a, a == s);
ASR(gpr.R(a), gpr.R(s), amount);
}
else if (!js.op->wantsCA)
{
gpr.BindToRegister(a, a == b || a == s);
ARM64Reg WA = gpr.GetReg();
LSL(EncodeRegTo64(WA), EncodeRegTo64(gpr.R(s)), 32);
ASRV(EncodeRegTo64(WA), EncodeRegTo64(WA), EncodeRegTo64(gpr.R(b)));
LSR(EncodeRegTo64(gpr.R(a)), EncodeRegTo64(WA), 32);
gpr.Unlock(WA);
}
else
{
gpr.BindToRegister(a, a == b || a == s);
ARM64Reg WA = gpr.GetReg();
ARM64Reg WB = gpr.GetReg();
ARM64Reg WC = gpr.GetReg();
ARM64Reg RB = gpr.R(b);
ARM64Reg RS = gpr.R(s);
ANDI2R(WA, RB, 32);
FixupBranch bit_is_not_zero = TBNZ(RB, 5);
ANDSI2R(WC, RB, 31);
MOV(WB, RS);
FixupBranch is_zero = B(CC_EQ);
ASRV(WB, RS, WC);
FixupBranch bit_is_zero = TBZ(RS, 31);
MOVI2R(WA, 32);
SUB(WC, WA, WC);
LSL(WC, RS, WC);
CMP(WC, 0);
CSET(WA, CC_NEQ);
FixupBranch end = B();
SetJumpTarget(bit_is_not_zero);
CMP(RS, 0);
CSET(WA, CC_LT);
CSINV(WB, WZR, WZR, CC_GE);
SetJumpTarget(is_zero);
SetJumpTarget(bit_is_zero);
SetJumpTarget(end);
MOV(gpr.R(a), WB);
if (inplace_carry)
{
CMP(WA, 1);
ComputeCarry();
}
else
{
STRB(INDEX_UNSIGNED, WA, PPC_REG, PPCSTATE_OFF(xer_ca));
}
gpr.Unlock(WA, WB, WC);
}
if (inst.Rc)
ComputeRC0(gpr.R(a));
}
void JitArm64::rlwimix(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITIntegerOff);
int a = inst.RA, s = inst.RS;
u32 mask = Helper_Mask(inst.MB, inst.ME);
if (gpr.IsImm(a) && gpr.IsImm(s))
{
u32 res = (gpr.GetImm(a) & ~mask) | (Common::RotateLeft(gpr.GetImm(s), inst.SH) & mask);
gpr.SetImmediate(a, res);
if (inst.Rc)
ComputeRC0(res);
}
else
{
if (mask == 0 || (a == s && inst.SH == 0))
{
// Do Nothing
}
else if (mask == 0xFFFFFFFF)
{
if (inst.SH || a != s)
gpr.BindToRegister(a, a == s);
if (inst.SH)
ROR(gpr.R(a), gpr.R(s), 32 - inst.SH);
else if (a != s)
MOV(gpr.R(a), gpr.R(s));
}
else if (inst.SH == 0 && inst.MB <= inst.ME)
{
// No rotation
// No mask inversion
u32 lsb = 31 - inst.ME;
u32 width = inst.ME - inst.MB + 1;
gpr.BindToRegister(a, true);
ARM64Reg WA = gpr.GetReg();
UBFX(WA, gpr.R(s), lsb, width);
BFI(gpr.R(a), WA, lsb, width);
gpr.Unlock(WA);
}
else if (inst.SH && inst.MB <= inst.ME)
{
// No mask inversion
u32 lsb = 31 - inst.ME;
u32 width = inst.ME - inst.MB + 1;
gpr.BindToRegister(a, true);
ARM64Reg WA = gpr.GetReg();
ROR(WA, gpr.R(s), 32 - inst.SH);
UBFX(WA, WA, lsb, width);
BFI(gpr.R(a), WA, lsb, width);
gpr.Unlock(WA);
}
else
{
gpr.BindToRegister(a, true);
ARM64Reg WA = gpr.GetReg();
ARM64Reg WB = gpr.GetReg();
MOVI2R(WA, mask);
BIC(WB, gpr.R(a), WA);
AND(WA, WA, gpr.R(s), ArithOption(gpr.R(s), ST_ROR, 32 - inst.SH));
ORR(gpr.R(a), WB, WA);
gpr.Unlock(WA, WB);
}
if (inst.Rc)
ComputeRC0(gpr.R(a));
}
}
| gpl-2.0 |
lukephills/KollektivGallery | wp-content/plugins/bj-lazy-load/inc/compat/wp-print.php | 245 | <?php
function bjll_compat_wpprint() {
if ( 1 == intval( get_query_var( 'print' ) ) || 1 == intval( get_query_var( 'printpage' ) ) ) {
add_filter( 'bjll/enabled', '__return_false' );
}
}
add_action( 'bjll/compat', 'bjll_compat_wpprint' );
| gpl-2.0 |
psci2195/espresso-ffans | testsuite/scripts/samples/test_visualization_cellsystem.py | 1263 | # Copyright (C) 2019 The ESPResSo project
#
# This file is part of ESPResSo.
#
# ESPResSo 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.
#
# ESPResSo 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/>.
import unittest as ut
import importlib_wrapper
def disable_GUI(code):
# integrate without visualizer
breakpoint = "visualizer.run(1)"
assert breakpoint in code
code = code.replace(breakpoint, "steps=1\nsystem.integrator.run(steps)", 1)
return code
sample, skipIfMissingFeatures = importlib_wrapper.configure_and_import(
"@SAMPLES_DIR@/visualization_cellsystem.py",
substitutions=disable_GUI, steps=100)
@skipIfMissingFeatures
class Sample(ut.TestCase):
system = sample.system
if __name__ == "__main__":
ut.main()
| gpl-3.0 |
TerrahKitsune/NWNX | nwnx_lua/nwnx_memory.cpp | 1258 | #include "nwnx_memory.h"
#include <string.h>
CNWNXMemory::CNWNXMemory( void ){
SetFunctionPointers( );
}
CNWNXMemory::~CNWNXMemory( void ){
//Nothing here yet
return;
}
void CNWNXMemory::SetFunctionPointers( void ){
//Set our nwnx memory funcs
nwnx_malloc = (void *(__cdecl *)(unsigned int))0x0040D550;
//nwns free routine
nwnx_free = (void (__cdecl *)(void *))0x0040D560;
}
void * CNWNXMemory::nwnx_calloc( unsigned int num, unsigned int size ){
void * pArray = nwnx_malloc( num*size );
if( pArray == NULL )
return NULL;
memset( pArray, NULL, num*size );
return pArray;
}
void * CNWNXMemory::nwnx_realloc( void * ptr, unsigned int size ){
//If size is 0, just free and return null
if( size == 0 ){
nwnx_free( ptr );
return NULL;
}
//ptr is null, behave like malloc
else if( ptr == NULL ){
return nwnx_malloc( size );
}
//Create new memory and grab the old size
void * temp = nwnx_malloc( size );
unsigned long oldSize = sizeof( ptr );
//It succeeded, proceed to copy all or as much of the old memory as possible
//And free the old memory
if( temp != NULL ){
memcpy( temp, ptr, oldSize > size ? size : oldSize );
nwnx_free( ptr );
ptr=temp;
}
//Return the pointer holding the memory
return ptr;
} | gpl-3.0 |
anvilvapre/OpenRA | OpenRA.Mods.Common/Traits/World/ScriptLobbyDropdown.cs | 1921 | #region Copyright & License Information
/*
* Copyright 2007-2016 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;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Traits
{
[Desc("Controls the map difficulty, tech level, and short game lobby options.")]
public class ScriptLobbyDropdownInfo : ITraitInfo, ILobbyOptions
{
[FieldLoader.Require]
[Desc("Internal id for this option.")]
public readonly string ID = null;
[FieldLoader.Require]
[Desc("Display name for this option.")]
public readonly string Label = null;
[FieldLoader.Require]
[Desc("Default option key in the `Values` list.")]
public readonly string Default = null;
[FieldLoader.Require]
[Desc("Difficulty levels supported by the map.")]
public readonly Dictionary<string, string> Values = null;
[Desc("Prevent the option from being changed from its default value.")]
public readonly bool Locked = false;
IEnumerable<LobbyOption> ILobbyOptions.LobbyOptions(Ruleset rules)
{
yield return new LobbyOption(ID, Label,
new ReadOnlyDictionary<string, string>(Values),
Default, Locked);
}
public object Create(ActorInitializer init) { return new ScriptLobbyDropdown(this); }
}
public class ScriptLobbyDropdown : INotifyCreated
{
public readonly ScriptLobbyDropdownInfo Info;
public string Value { get; private set; }
public ScriptLobbyDropdown(ScriptLobbyDropdownInfo info)
{
Info = info;
}
void INotifyCreated.Created(Actor self)
{
Value = self.World.LobbyInfo.GlobalSettings.OptionOrDefault(Info.ID, Info.Default);
}
}
}
| gpl-3.0 |
fengzhe29888/gnuradio-old | gr-qtgui/lib/time_sink_f_impl.cc | 18428 | /* -*- c++ -*- */
/*
* Copyright 2011-2013 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio 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, or (at your option)
* any later version.
*
* GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "time_sink_f_impl.h"
#include <gnuradio/io_signature.h>
#include <gnuradio/block_detail.h>
#include <gnuradio/buffer.h>
#include <gnuradio/prefs.h>
#include <string.h>
#include <volk/volk.h>
#include <gnuradio/fft/fft.h>
#include <qwt_symbol.h>
namespace gr {
namespace qtgui {
time_sink_f::sptr
time_sink_f::make(int size, double samp_rate,
const std::string &name,
int nconnections,
QWidget *parent)
{
return gnuradio::get_initial_sptr
(new time_sink_f_impl(size, samp_rate, name, nconnections, parent));
}
time_sink_f_impl::time_sink_f_impl(int size, double samp_rate,
const std::string &name,
int nconnections,
QWidget *parent)
: sync_block("time_sink_f",
io_signature::make(nconnections, nconnections, sizeof(float)),
io_signature::make(0, 0, 0)),
d_size(size), d_buffer_size(2*size), d_samp_rate(samp_rate), d_name(name),
d_nconnections(nconnections), d_parent(parent)
{
// Required now for Qt; argc must be greater than 0 and argv
// must have at least one valid character. Must be valid through
// life of the qApplication:
// http://harmattan-dev.nokia.com/docs/library/html/qt4/qapplication.html
d_argc = 1;
d_argv = new char;
d_argv[0] = '\0';
d_main_gui = NULL;
for(int n = 0; n < d_nconnections; n++) {
d_buffers.push_back((double*)volk_malloc(d_buffer_size*sizeof(double),
volk_get_alignment()));
memset(d_buffers[n], 0, d_buffer_size*sizeof(double));
}
// Set alignment properties for VOLK
const int alignment_multiple =
volk_get_alignment() / sizeof(float);
set_alignment(std::max(1,alignment_multiple));
d_tags = std::vector< std::vector<gr::tag_t> >(d_nconnections);
initialize();
d_main_gui->setNPoints(d_size); // setup GUI box with size
set_trigger_mode(TRIG_MODE_FREE, TRIG_SLOPE_POS, 0, 0, 0);
set_history(2); // so we can look ahead for the trigger slope
declare_sample_delay(1); // delay the tags for a history of 2
}
time_sink_f_impl::~time_sink_f_impl()
{
if(!d_main_gui->isClosed())
d_main_gui->close();
// d_main_gui is a qwidget destroyed with its parent
for(int n = 0; n < d_nconnections; n++) {
volk_free(d_buffers[n]);
}
delete d_argv;
}
bool
time_sink_f_impl::check_topology(int ninputs, int noutputs)
{
return ninputs == d_nconnections;
}
void
time_sink_f_impl::initialize()
{
if(qApp != NULL) {
d_qApplication = qApp;
}
else {
#if QT_VERSION >= 0x040500
std::string style = prefs::singleton()->get_string("qtgui", "style", "raster");
QApplication::setGraphicsSystem(QString(style.c_str()));
#endif
d_qApplication = new QApplication(d_argc, &d_argv);
}
// If a style sheet is set in the prefs file, enable it here.
std::string qssfile = prefs::singleton()->get_string("qtgui","qss","");
if(qssfile.size() > 0) {
QString sstext = get_qt_style_sheet(QString(qssfile.c_str()));
d_qApplication->setStyleSheet(sstext);
}
d_main_gui = new TimeDisplayForm(d_nconnections, d_parent);
d_main_gui->setNPoints(d_size);
d_main_gui->setSampleRate(d_samp_rate);
if(d_name.size() > 0)
set_title(d_name);
// initialize update time to 10 times a second
set_update_time(0.1);
}
void
time_sink_f_impl::exec_()
{
d_qApplication->exec();
}
QWidget*
time_sink_f_impl::qwidget()
{
return d_main_gui;
}
#ifdef ENABLE_PYTHON
PyObject*
time_sink_f_impl::pyqwidget()
{
PyObject *w = PyLong_FromVoidPtr((void*)d_main_gui);
PyObject *retarg = Py_BuildValue("N", w);
return retarg;
}
#else
void *
time_sink_f_impl::pyqwidget()
{
return NULL;
}
#endif
void
time_sink_f_impl::set_y_axis(double min, double max)
{
d_main_gui->setYaxis(min, max);
}
void
time_sink_f_impl::set_y_label(const std::string &label,
const std::string &unit)
{
d_main_gui->setYLabel(label, unit);
}
void
time_sink_f_impl::set_update_time(double t)
{
//convert update time to ticks
gr::high_res_timer_type tps = gr::high_res_timer_tps();
d_update_time = t * tps;
d_main_gui->setUpdateTime(t);
d_last_time = 0;
}
void
time_sink_f_impl::set_title(const std::string &title)
{
d_main_gui->setTitle(title.c_str());
}
void
time_sink_f_impl::set_line_label(int which, const std::string &label)
{
d_main_gui->setLineLabel(which, label.c_str());
}
void
time_sink_f_impl::set_line_color(int which, const std::string &color)
{
d_main_gui->setLineColor(which, color.c_str());
}
void
time_sink_f_impl::set_line_width(int which, int width)
{
d_main_gui->setLineWidth(which, width);
}
void
time_sink_f_impl::set_line_style(int which, int style)
{
d_main_gui->setLineStyle(which, (Qt::PenStyle)style);
}
void
time_sink_f_impl::set_line_marker(int which, int marker)
{
d_main_gui->setLineMarker(which, (QwtSymbol::Style)marker);
}
void
time_sink_f_impl::set_line_alpha(int which, double alpha)
{
d_main_gui->setMarkerAlpha(which, (int)(255.0*alpha));
}
void
time_sink_f_impl::set_trigger_mode(trigger_mode mode,
trigger_slope slope,
float level,
float delay, int channel,
const std::string &tag_key)
{
gr::thread::scoped_lock lock(d_setlock);
d_trigger_mode = mode;
d_trigger_slope = slope;
d_trigger_level = level;
d_trigger_delay = static_cast<int>(delay*d_samp_rate);
d_trigger_channel = channel;
d_trigger_tag_key = pmt::intern(tag_key);
d_triggered = false;
d_trigger_count = 0;
if((d_trigger_delay < 0) || (d_trigger_delay >= d_size)) {
GR_LOG_WARN(d_logger, boost::format("Trigger delay (%1%) outside of display range (0:%2%).") \
% (d_trigger_delay/d_samp_rate) % ((d_size-1)/d_samp_rate));
d_trigger_delay = std::max(0, std::min(d_size-1, d_trigger_delay));
delay = d_trigger_delay/d_samp_rate;
}
d_main_gui->setTriggerMode(d_trigger_mode);
d_main_gui->setTriggerSlope(d_trigger_slope);
d_main_gui->setTriggerLevel(d_trigger_level);
d_main_gui->setTriggerDelay(delay);
d_main_gui->setTriggerChannel(d_trigger_channel);
d_main_gui->setTriggerTagKey(tag_key);
_reset();
}
void
time_sink_f_impl::set_size(int width, int height)
{
d_main_gui->resize(QSize(width, height));
}
std::string
time_sink_f_impl::title()
{
return d_main_gui->title().toStdString();
}
std::string
time_sink_f_impl::line_label(int which)
{
return d_main_gui->lineLabel(which).toStdString();
}
std::string
time_sink_f_impl::line_color(int which)
{
return d_main_gui->lineColor(which).toStdString();
}
int
time_sink_f_impl::line_width(int which)
{
return d_main_gui->lineWidth(which);
}
int
time_sink_f_impl::line_style(int which)
{
return d_main_gui->lineStyle(which);
}
int
time_sink_f_impl::line_marker(int which)
{
return d_main_gui->lineMarker(which);
}
double
time_sink_f_impl::line_alpha(int which)
{
return (double)(d_main_gui->markerAlpha(which))/255.0;
}
void
time_sink_f_impl::set_nsamps(const int newsize)
{
if(newsize != d_size) {
gr::thread::scoped_lock lock(d_setlock);
// Set new size and reset buffer index
// (throws away any currently held data, but who cares?)
d_size = newsize;
d_buffer_size = 2*d_size;
// Resize buffers and replace data
for(int n = 0; n < d_nconnections; n++) {
volk_free(d_buffers[n]);
d_buffers[n] = (double*)volk_malloc(d_buffer_size*sizeof(double),
volk_get_alignment());
memset(d_buffers[n], 0, d_buffer_size*sizeof(double));
}
// If delay was set beyond the new boundary, pull it back.
if(d_trigger_delay >= d_size) {
GR_LOG_WARN(d_logger, boost::format("Trigger delay (%1%) outside of display range (0:%2%). Moving to 50%% point.") \
% (d_trigger_delay/d_samp_rate) % ((d_size-1)/d_samp_rate));
d_trigger_delay = d_size-1;
d_main_gui->setTriggerDelay(d_trigger_delay/d_samp_rate);
}
d_main_gui->setNPoints(d_size);
_reset();
}
}
void
time_sink_f_impl::set_samp_rate(const double samp_rate)
{
gr::thread::scoped_lock lock(d_setlock);
d_samp_rate = samp_rate;
d_main_gui->setSampleRate(d_samp_rate);
}
int
time_sink_f_impl::nsamps() const
{
return d_size;
}
void
time_sink_f_impl::enable_stem_plot(bool en)
{
d_main_gui->setStem(en);
}
void
time_sink_f_impl::enable_menu(bool en)
{
d_main_gui->enableMenu(en);
}
void
time_sink_f_impl::enable_grid(bool en)
{
d_main_gui->setGrid(en);
}
void
time_sink_f_impl::enable_autoscale(bool en)
{
d_main_gui->autoScale(en);
}
void
time_sink_f_impl::enable_semilogx(bool en)
{
d_main_gui->setSemilogx(en);
}
void
time_sink_f_impl::enable_semilogy(bool en)
{
d_main_gui->setSemilogy(en);
}
void
time_sink_f_impl::enable_tags(int which, bool en)
{
if(which == -1) {
for(int n = 0; n < d_nconnections; n++) {
d_main_gui->setTagMenu(n, en);
}
}
else
d_main_gui->setTagMenu(which, en);
}
void
time_sink_f_impl::reset()
{
gr::thread::scoped_lock lock(d_setlock);
_reset();
}
void
time_sink_f_impl::_reset()
{
// Move the tail of the buffers to the front. This section
// represents data that might have to be plotted again if a
// trigger occurs and we have a trigger delay set. The tail
// section is between (d_end-d_trigger_delay) and d_end.
int n;
if(d_trigger_delay) {
for(n = 0; n < d_nconnections; n++) {
memmove(d_buffers[n], &d_buffers[n][d_size-d_trigger_delay], d_trigger_delay*sizeof(double));
}
// Also move the offsets of any tags that occur in the tail
// section so they would be plotted again, too.
for(n = 0; n < d_nconnections; n++) {
std::vector<gr::tag_t> tmp_tags;
for(size_t t = 0; t < d_tags[n].size(); t++) {
if(d_tags[n][t].offset > (uint64_t)(d_size - d_trigger_delay)) {
d_tags[n][t].offset = d_tags[n][t].offset - (d_size - d_trigger_delay);
tmp_tags.push_back(d_tags[n][t]);
}
}
d_tags[n] = tmp_tags;
}
}
// Otherwise, just clear the local list of tags.
else {
for(n = 0; n < d_nconnections; n++) {
d_tags[n].clear();
}
}
// Reset the start and end indices.
d_start = 0;
d_end = d_size;
// Reset the trigger. If in free running mode, ignore the
// trigger delay and always set trigger to true.
if(d_trigger_mode == TRIG_MODE_FREE) {
d_index = 0;
d_triggered = true;
}
else {
d_index = d_trigger_delay;
d_triggered = false;
}
}
void
time_sink_f_impl::_npoints_resize()
{
int newsize = d_main_gui->getNPoints();
set_nsamps(newsize);
}
void
time_sink_f_impl::_adjust_tags(int adj)
{
for(size_t n = 0; n < d_tags.size(); n++) {
for(size_t t = 0; t < d_tags[n].size(); t++) {
d_tags[n][t].offset += adj;
}
}
}
void
time_sink_f_impl::_gui_update_trigger()
{
d_trigger_mode = d_main_gui->getTriggerMode();
d_trigger_slope = d_main_gui->getTriggerSlope();
d_trigger_level = d_main_gui->getTriggerLevel();
d_trigger_channel = d_main_gui->getTriggerChannel();
d_trigger_count = 0;
float delayf = d_main_gui->getTriggerDelay();
int delay = static_cast<int>(delayf*d_samp_rate);
if(delay != d_trigger_delay) {
// We restrict the delay to be within the window of time being
// plotted.
if((delay < 0) || (delay >= d_size)) {
GR_LOG_WARN(d_logger, boost::format("Trigger delay (%1%) outside of display range (0:%2%).") \
% (delay/d_samp_rate) % ((d_size-1)/d_samp_rate));
delay = std::max(0, std::min(d_size-1, delay));
delayf = delay/d_samp_rate;
}
d_trigger_delay = delay;
d_main_gui->setTriggerDelay(delayf);
_reset();
}
std::string tagkey = d_main_gui->getTriggerTagKey();
d_trigger_tag_key = pmt::intern(tagkey);
}
void
time_sink_f_impl::_test_trigger_tags(int nitems)
{
int trigger_index;
uint64_t nr = nitems_read(d_trigger_channel);
std::vector<gr::tag_t> tags;
get_tags_in_range(tags, d_trigger_channel,
nr, nr + nitems,
d_trigger_tag_key);
if(tags.size() > 0) {
d_triggered = true;
trigger_index = tags[0].offset - nr;
d_start = d_index + trigger_index - d_trigger_delay - 1;
d_end = d_start + d_size;
d_trigger_count = 0;
_adjust_tags(-d_start);
}
}
void
time_sink_f_impl::_test_trigger_norm(int nitems, gr_vector_const_void_star inputs)
{
int trigger_index;
const float *in = (const float*)inputs[d_trigger_channel];
for(trigger_index = 0; trigger_index < nitems; trigger_index++) {
d_trigger_count++;
// Test if trigger has occurred based on the input stream,
// channel number, and slope direction
if(_test_trigger_slope(&in[trigger_index])) {
d_triggered = true;
d_start = d_index + trigger_index - d_trigger_delay;
d_end = d_start + d_size;
d_trigger_count = 0;
_adjust_tags(-d_start);
break;
}
}
// If using auto trigger mode, trigger periodically even
// without a trigger event.
if((d_trigger_mode == TRIG_MODE_AUTO) && (d_trigger_count > d_size)) {
d_triggered = true;
d_trigger_count = 0;
}
}
bool
time_sink_f_impl::_test_trigger_slope(const float *in) const
{
float x0, x1;
x0 = in[0];
x1 = in[1];
if(d_trigger_slope == TRIG_SLOPE_POS)
return ((x0 <= d_trigger_level) && (x1 > d_trigger_level));
else
return ((x0 >= d_trigger_level) && (x1 < d_trigger_level));
}
int
time_sink_f_impl::work(int noutput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items)
{
int n=0, idx=0;
const float *in;
_npoints_resize();
_gui_update_trigger();
gr::thread::scoped_lock lock(d_setlock);
int nfill = d_end - d_index; // how much room left in buffers
int nitems = std::min(noutput_items, nfill); // num items we can put in buffers
// If auto, normal, or tag trigger, look for the trigger
if((d_trigger_mode != TRIG_MODE_FREE) && !d_triggered) {
// trigger off a tag key (first one found)
if(d_trigger_mode == TRIG_MODE_TAG) {
_test_trigger_tags(nitems);
}
// Normal or Auto trigger
else {
_test_trigger_norm(nitems, input_items);
}
}
// Copy data into the buffers.
for(n = 0; n < d_nconnections; n++) {
in = (const float*)input_items[idx];
volk_32f_convert_64f(&d_buffers[n][d_index],
&in[1], nitems);
uint64_t nr = nitems_read(idx);
std::vector<gr::tag_t> tags;
get_tags_in_range(tags, idx, nr, nr + nitems);
for(size_t t = 0; t < tags.size(); t++) {
tags[t].offset = tags[t].offset - nr + (d_index-d_start-1);
}
d_tags[idx].insert(d_tags[idx].end(), tags.begin(), tags.end());
idx++;
}
d_index += nitems;
// If we've have a trigger and a full d_size of items in the buffers, plot.
if((d_triggered) && (d_index == d_end)) {
// Copy data to be plotted to start of buffers.
for(n = 0; n < d_nconnections; n++) {
memmove(d_buffers[n], &d_buffers[n][d_start], d_size*sizeof(double));
}
// Plot if we are able to update
if(gr::high_res_timer_now() - d_last_time > d_update_time) {
d_last_time = gr::high_res_timer_now();
d_qApplication->postEvent(d_main_gui,
new TimeUpdateEvent(d_buffers, d_size, d_tags));
}
// We've plotting, so reset the state
_reset();
}
// If we've filled up the buffers but haven't triggered, reset.
if(d_index == d_end) {
_reset();
}
return nitems;
}
} /* namespace qtgui */
} /* namespace gr */
| gpl-3.0 |
benhamidene/livingdoc-core | livingdoc-core/src/main/java/info/novatec/testit/livingdoc/converter/AbstractTypeConverter.java | 3395 | /* Copyright (c) 2006 Pyxis Technologies inc.
*
* This 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 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 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 St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF site:
* http://www.fsf.org. */
package info.novatec.testit.livingdoc.converter;
import org.apache.commons.lang3.StringUtils;
/**
* Abstract base class for <code>TypeConverter</code> implementations that takes
* care handling null or empty string values. Subclasses are guaranteed to
* receive a non-null and non-empty string in their <code>doConvert()</code>
* implementations.
*
* @version $Revision: $ $Date: $
*/
public abstract class AbstractTypeConverter implements TypeConverter {
/**
* Template implementation of the <code>convert()</code> method. Takes care
* of handling null and empty string values. Once these basic operations are
* handled, will delegate to the <code>doConvert()</code> method of
* subclasses.
*
* @param value The string value to convert
* @param type The type to convert to
* @return The converted value, or null
*/
@Override
public Object parse(String value, Class< ? > type) {
if (StringUtils.isBlank(value)) {
return null;
}
return doConvert(value.trim(), type);
}
/**
* Basic implementation of the <code>toString()</code> method. Takes care of
* handling null values otherwise call the doToString of the object.
*
* @param value The value to stringnified
* @return The string representation of the value
*/
@Override
public String toString(Object value) {
if (value == null) {
return "";
}
return doToString(value);
}
/**
* Subclass must implement this method to do the actual type conversion.
* Subclass implementations are garanteed to receive a non-null and
* non-empty string.
*
* @param value The string value to convert
* @return The converted value, or null
*/
protected abstract Object doConvert(String value);
/**
* Do the conversion of the given value into the given type.
*
* @param value The string value to convert
* @param type The type to convert to
* @return The converted value, or null
*/
protected Object doConvert(String value, Class< ? > type) {
return doConvert(value);
}
/**
* Subclass must implement this method to overide the default call to the
* toString method of the value. Subclass implementations are garanteed to
* receive a non-null object.
*
* @param value The string value to convert
* @return The converted value, or null
*/
protected String doToString(Object value) {
return String.valueOf(value);
}
}
| gpl-3.0 |
iohannez/gnuradio | gr-blocks/python/blocks/qa_wavfile.py | 2349 | #!/usr/bin/env python
#
# Copyright 2008,2010,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later version.
#
# GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, gr_unittest, blocks
import os
from os.path import getsize
g_in_file = os.path.join(os.getenv("srcdir"), "test_16bit_1chunk.wav")
g_extra_header_offset = 36
g_extra_header_len = 18
class test_wavefile(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_001_checkwavread(self):
wf = blocks.wavfile_source(g_in_file)
self.assertEqual(wf.sample_rate(), 8000)
def test_002_checkwavcopy(self):
infile = g_in_file
outfile = "test_out.wav"
wf_in = blocks.wavfile_source(infile)
wf_out = blocks.wavfile_sink(outfile,
wf_in.channels(),
wf_in.sample_rate(),
wf_in.bits_per_sample())
self.tb.connect(wf_in, wf_out)
self.tb.run()
wf_out.close()
# we're losing all extra header chunks
self.assertEqual(getsize(infile) - g_extra_header_len, getsize(outfile))
in_f = open(infile, 'rb')
out_f = open(outfile, 'rb')
in_data = in_f.read()
out_data = out_f.read()
out_f.close()
os.remove(outfile)
# cut extra header chunks input file
self.assertEqual(in_data[:g_extra_header_offset] + \
in_data[g_extra_header_offset + g_extra_header_len:], out_data)
if __name__ == '__main__':
gr_unittest.run(test_wavefile, "test_wavefile.xml")
| gpl-3.0 |
maddinpsy/FtpSyncer | etc/SharpSSH/jsch/RequestX11.cs | 2585 | using System;
namespace Tamir.SharpSsh.jsch
{
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2002,2003,2004 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
class RequestX11 : Request
{
public void setCookie(String cookie)
{
ChannelX11.cookie=Util.getBytes(cookie);
}
public void request(Session session, Channel channel)
{
Buffer buf=new Buffer();
Packet packet=new Packet(buf);
// byte SSH_MSG_CHANNEL_REQUEST(98)
// uint32 recipient channel
// string request type // "x11-req"
// boolean want reply // 0
// boolean single connection
// string x11 authentication protocol // "MIT-MAGIC-COOKIE-1".
// string x11 authentication cookie
// uint32 x11 screen number
packet.reset();
buf.putByte((byte) Session.SSH_MSG_CHANNEL_REQUEST);
buf.putInt(channel.getRecipient());
buf.putString(Util.getBytes("x11-req"));
buf.putByte((byte)(waitForReply() ? 1 : 0));
buf.putByte((byte)0);
buf.putString(Util.getBytes("MIT-MAGIC-COOKIE-1"));
buf.putString(ChannelX11.getFakedCookie(session));
buf.putInt(0);
session.write(packet);
}
public bool waitForReply(){ return false; }
}
}
| gpl-3.0 |
emonty/ansible-modules-core | packaging/os/yum.py | 40426 | #!/usr/bin/python -tt
# -*- coding: utf-8 -*-
# (c) 2012, Red Hat, Inc
# Written by Seth Vidal <skvidal at fedoraproject.org>
# (c) 2014, Epic Games, Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
#
import os
import yum
import rpm
import platform
import tempfile
import shutil
from distutils.version import LooseVersion
try:
from yum.misc import find_unfinished_transactions, find_ts_remaining
from rpmUtils.miscutils import splitFilename
transaction_helpers = True
except:
transaction_helpers = False
DOCUMENTATION = '''
---
module: yum
version_added: historical
short_description: Manages packages with the I(yum) package manager
description:
- Installs, upgrade, removes, and lists packages and groups with the I(yum) package manager.
options:
name:
description:
- "Package name, or package specifier with version, like C(name-1.0). When using state=latest, this can be '*' which means run: yum -y update. You can also pass a url or a local path to a rpm file (using state=present). To operate on several packages this can accept a comma separated list of packages or (as of 2.0) a list of packages."
required: true
default: null
aliases: [ 'pkg' ]
exclude:
description:
- "Package name(s) to exclude when state=present, or latest"
required: false
version_added: "2.0"
default: null
list:
description:
- Various (non-idempotent) commands for usage with C(/usr/bin/ansible) and I(not) playbooks. See examples.
required: false
default: null
state:
description:
- Whether to install (C(present) or C(installed), C(latest)), or remove (C(absent) or C(removed)) a package.
required: false
choices: [ "present", "installed", "latest", "absent", "removed" ]
default: "present"
enablerepo:
description:
- I(Repoid) of repositories to enable for the install/update operation.
These repos will not persist beyond the transaction.
When specifying multiple repos, separate them with a ",".
required: false
version_added: "0.9"
default: null
aliases: []
disablerepo:
description:
- I(Repoid) of repositories to disable for the install/update operation.
These repos will not persist beyond the transaction.
When specifying multiple repos, separate them with a ",".
required: false
version_added: "0.9"
default: null
aliases: []
conf_file:
description:
- The remote yum configuration file to use for the transaction.
required: false
version_added: "0.6"
default: null
aliases: []
disable_gpg_check:
description:
- Whether to disable the GPG checking of signatures of packages being
installed. Has an effect only if state is I(present) or I(latest).
required: false
version_added: "1.2"
default: "no"
choices: ["yes", "no"]
aliases: []
update_cache:
description:
- Force updating the cache. Has an effect only if state is I(present)
or I(latest).
required: false
version_added: "1.9"
default: "no"
choices: ["yes", "no"]
aliases: []
validate_certs:
description:
- This only applies if using a https url as the source of the rpm. e.g. for localinstall. If set to C(no), the SSL certificates will not be validated.
- This should only set to C(no) used on personally controlled sites using self-signed certificates as it avoids verifying the source site.
- Prior to 2.1 the code worked as if this was set to C(yes).
required: false
default: "yes"
choices: ["yes", "no"]
version_added: "2.1"
notes:
- When used with a loop of package names in a playbook, ansible optimizes
the call to the yum module. Instead of calling the module with a single
package each time through the loop, ansible calls the module once with all
of the package names from the loop.
- In versions prior to 1.9.2 this module installed and removed each package
given to the yum module separately. This caused problems when packages
specified by filename or url had to be installed or removed together. In
1.9.2 this was fixed so that packages are installed in one yum
transaction. However, if one of the packages adds a new yum repository
that the other packages come from (such as epel-release) then that package
needs to be installed in a separate task. This mimics yum's command line
behaviour.
- 'Yum itself has two types of groups. "Package groups" are specified in the
rpm itself while "environment groups" are specified in a separate file
(usually by the distribution). Unfortunately, this division becomes
apparent to ansible users because ansible needs to operate on the group
of packages in a single transaction and yum requires groups to be specified
in different ways when used in that way. Package groups are specified as
"@development-tools" and environment groups are "@^gnome-desktop-environment".
Use the "yum group list" command to see which category of group the group
you want to install falls into.'
# informational: requirements for nodes
requirements: [ yum ]
author:
- "Ansible Core Team"
- "Seth Vidal"
'''
EXAMPLES = '''
- name: install the latest version of Apache
yum:
name: httpd
state: latest
- name: remove the Apache package
yum:
name: httpd
state: absent
- name: install the latest version of Apache from the testing repo
yum:
name: httpd
enablerepo: testing
state: present
- name: install one specific version of Apache
yum:
name: httpd-2.2.29-1.4.amzn1
state: present
- name: upgrade all packages
yum:
name: '*'
state: latest
- name: install the nginx rpm from a remote repo
yum:
name: 'http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm'
state: present
- name: install nginx rpm from a local file
yum:
name: /usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm
state: present
- name: install the 'Development tools' package group
yum:
name: "@Development tools"
state: present
- name: install the 'Gnome desktop' environment group
yum:
name: "@^gnome-desktop-environment"
state: present
'''
# 64k. Number of bytes to read at a time when manually downloading pkgs via a url
BUFSIZE = 65536
def_qf = "%{name}-%{version}-%{release}.%{arch}"
rpmbin = None
def yum_base(conf_file=None):
my = yum.YumBase()
my.preconf.debuglevel=0
my.preconf.errorlevel=0
my.preconf.plugins = True
if conf_file and os.path.exists(conf_file):
my.preconf.fn = conf_file
if os.geteuid() != 0:
if hasattr(my, 'setCacheDir'):
my.setCacheDir()
else:
cachedir = yum.misc.getCacheDir()
my.repos.setCacheDir(cachedir)
my.conf.cache = 0
return my
def ensure_yum_utils(module):
repoquerybin = module.get_bin_path('repoquery', required=False)
if module.params['install_repoquery'] and not repoquerybin and not module.check_mode:
yum_path = module.get_bin_path('yum')
if yum_path:
rc, so, se = module.run_command('%s -y install yum-utils' % yum_path)
repoquerybin = module.get_bin_path('repoquery', required=False)
return repoquerybin
def fetch_rpm_from_url(spec, module=None):
# download package so that we can query it
tempdir = tempfile.mkdtemp()
package = os.path.join(tempdir, str(spec.rsplit('/', 1)[1]))
try:
rsp, info = fetch_url(module, spec)
if not rsp:
module.fail_json(msg="Failure downloading %s, %s" % (spec, info['msg']))
f = open(package, 'w')
data = rsp.read(BUFSIZE)
while data:
f.write(data)
data = rsp.read(BUFSIZE)
f.close()
except Exception:
e = get_exception()
shutil.rmtree(tempdir)
if module:
module.fail_json(msg="Failure downloading %s, %s" % (spec, e))
return package
def po_to_nevra(po):
if hasattr(po, 'ui_nevra'):
return po.ui_nevra
else:
return '%s-%s-%s.%s' % (po.name, po.version, po.release, po.arch)
def is_installed(module, repoq, pkgspec, conf_file, qf=def_qf, en_repos=None, dis_repos=None, is_pkg=False):
if en_repos is None:
en_repos = []
if dis_repos is None:
dis_repos = []
if not repoq:
pkgs = []
try:
my = yum_base(conf_file)
for rid in dis_repos:
my.repos.disableRepo(rid)
for rid in en_repos:
my.repos.enableRepo(rid)
e, m, u = my.rpmdb.matchPackageNames([pkgspec])
pkgs = e + m
if not pkgs and not is_pkg:
pkgs.extend(my.returnInstalledPackagesByDep(pkgspec))
except Exception:
e = get_exception()
module.fail_json(msg="Failure talking to yum: %s" % e)
return [ po_to_nevra(p) for p in pkgs ]
else:
global rpmbin
if not rpmbin:
rpmbin = module.get_bin_path('rpm', required=True)
cmd = [rpmbin, '-q', '--qf', qf, pkgspec]
# rpm localizes messages and we're screen scraping so make sure we use
# the C locale
lang_env = dict(LANG='C', LC_ALL='C', LC_MESSAGES='C')
rc, out, err = module.run_command(cmd, environ_update=lang_env)
if rc != 0 and 'is not installed' not in out:
module.fail_json(msg='Error from rpm: %s: %s' % (cmd, err))
if 'is not installed' in out:
out = ''
pkgs = [p for p in out.replace('(none)', '0').split('\n') if p.strip()]
if not pkgs and not is_pkg:
cmd = [rpmbin, '-q', '--qf', qf, '--whatprovides', pkgspec]
rc2, out2, err2 = module.run_command(cmd, environ_update=lang_env)
else:
rc2, out2, err2 = (0, '', '')
if rc2 != 0 and 'no package provides' not in out2:
module.fail_json(msg='Error from rpm: %s: %s' % (cmd, err + err2))
if 'no package provides' in out2:
out2 = ''
pkgs += [p for p in out2.replace('(none)', '0').split('\n') if p.strip()]
return pkgs
return []
def is_available(module, repoq, pkgspec, conf_file, qf=def_qf, en_repos=None, dis_repos=None):
if en_repos is None:
en_repos = []
if dis_repos is None:
dis_repos = []
if not repoq:
pkgs = []
try:
my = yum_base(conf_file)
for rid in dis_repos:
my.repos.disableRepo(rid)
for rid in en_repos:
my.repos.enableRepo(rid)
e,m,u = my.pkgSack.matchPackageNames([pkgspec])
pkgs = e + m
if not pkgs:
pkgs.extend(my.returnPackagesByDep(pkgspec))
except Exception:
e = get_exception()
module.fail_json(msg="Failure talking to yum: %s" % e)
return [ po_to_nevra(p) for p in pkgs ]
else:
myrepoq = list(repoq)
r_cmd = ['--disablerepo', ','.join(dis_repos)]
myrepoq.extend(r_cmd)
r_cmd = ['--enablerepo', ','.join(en_repos)]
myrepoq.extend(r_cmd)
cmd = myrepoq + ["--qf", qf, pkgspec]
rc,out,err = module.run_command(cmd)
if rc == 0:
return [ p for p in out.split('\n') if p.strip() ]
else:
module.fail_json(msg='Error from repoquery: %s: %s' % (cmd, err))
return []
def is_update(module, repoq, pkgspec, conf_file, qf=def_qf, en_repos=None, dis_repos=None):
if en_repos is None:
en_repos = []
if dis_repos is None:
dis_repos = []
if not repoq:
retpkgs = []
pkgs = []
updates = []
try:
my = yum_base(conf_file)
for rid in dis_repos:
my.repos.disableRepo(rid)
for rid in en_repos:
my.repos.enableRepo(rid)
pkgs = my.returnPackagesByDep(pkgspec) + my.returnInstalledPackagesByDep(pkgspec)
if not pkgs:
e,m,u = my.pkgSack.matchPackageNames([pkgspec])
pkgs = e + m
updates = my.doPackageLists(pkgnarrow='updates').updates
except Exception:
e = get_exception()
module.fail_json(msg="Failure talking to yum: %s" % e)
for pkg in pkgs:
if pkg in updates:
retpkgs.append(pkg)
return set([ po_to_nevra(p) for p in retpkgs ])
else:
myrepoq = list(repoq)
r_cmd = ['--disablerepo', ','.join(dis_repos)]
myrepoq.extend(r_cmd)
r_cmd = ['--enablerepo', ','.join(en_repos)]
myrepoq.extend(r_cmd)
cmd = myrepoq + ["--pkgnarrow=updates", "--qf", qf, pkgspec]
rc,out,err = module.run_command(cmd)
if rc == 0:
return set([ p for p in out.split('\n') if p.strip() ])
else:
module.fail_json(msg='Error from repoquery: %s: %s' % (cmd, err))
return set()
def what_provides(module, repoq, req_spec, conf_file, qf=def_qf, en_repos=None, dis_repos=None):
if en_repos is None:
en_repos = []
if dis_repos is None:
dis_repos = []
if req_spec.endswith('.rpm') and '://' not in req_spec:
return req_spec
elif '://' in req_spec:
local_path = fetch_rpm_from_url(req_spec, module=module)
return local_path
if not repoq:
pkgs = []
try:
my = yum_base(conf_file)
for rid in dis_repos:
my.repos.disableRepo(rid)
for rid in en_repos:
my.repos.enableRepo(rid)
pkgs = my.returnPackagesByDep(req_spec) + my.returnInstalledPackagesByDep(req_spec)
if not pkgs:
e,m,u = my.pkgSack.matchPackageNames([req_spec])
pkgs.extend(e)
pkgs.extend(m)
e,m,u = my.rpmdb.matchPackageNames([req_spec])
pkgs.extend(e)
pkgs.extend(m)
except Exception:
e = get_exception()
module.fail_json(msg="Failure talking to yum: %s" % e)
return set([ po_to_nevra(p) for p in pkgs ])
else:
myrepoq = list(repoq)
r_cmd = ['--disablerepo', ','.join(dis_repos)]
myrepoq.extend(r_cmd)
r_cmd = ['--enablerepo', ','.join(en_repos)]
myrepoq.extend(r_cmd)
cmd = myrepoq + ["--qf", qf, "--whatprovides", req_spec]
rc,out,err = module.run_command(cmd)
cmd = myrepoq + ["--qf", qf, req_spec]
rc2,out2,err2 = module.run_command(cmd)
if rc == 0 and rc2 == 0:
out += out2
pkgs = set([ p for p in out.split('\n') if p.strip() ])
if not pkgs:
pkgs = is_installed(module, repoq, req_spec, conf_file, qf=qf)
return pkgs
else:
module.fail_json(msg='Error from repoquery: %s: %s' % (cmd, err + err2))
return set()
def transaction_exists(pkglist):
"""
checks the package list to see if any packages are
involved in an incomplete transaction
"""
conflicts = []
if not transaction_helpers:
return conflicts
# first, we create a list of the package 'nvreas'
# so we can compare the pieces later more easily
pkglist_nvreas = []
for pkg in pkglist:
pkglist_nvreas.append(splitFilename(pkg))
# next, we build the list of packages that are
# contained within an unfinished transaction
unfinished_transactions = find_unfinished_transactions()
for trans in unfinished_transactions:
steps = find_ts_remaining(trans)
for step in steps:
# the action is install/erase/etc., but we only
# care about the package spec contained in the step
(action, step_spec) = step
(n,v,r,e,a) = splitFilename(step_spec)
# and see if that spec is in the list of packages
# requested for installation/updating
for pkg in pkglist_nvreas:
# if the name and arch match, we're going to assume
# this package is part of a pending transaction
# the label is just for display purposes
label = "%s-%s" % (n,a)
if n == pkg[0] and a == pkg[4]:
if label not in conflicts:
conflicts.append("%s-%s" % (n,a))
break
return conflicts
def local_nvra(module, path):
"""return nvra of a local rpm passed in"""
ts = rpm.TransactionSet()
ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES)
fd = os.open(path, os.O_RDONLY)
try:
header = ts.hdrFromFdno(fd)
finally:
os.close(fd)
return '%s-%s-%s.%s' % (header[rpm.RPMTAG_NAME],
header[rpm.RPMTAG_VERSION],
header[rpm.RPMTAG_RELEASE],
header[rpm.RPMTAG_ARCH])
def pkg_to_dict(pkgstr):
if pkgstr.strip():
n,e,v,r,a,repo = pkgstr.split('|')
else:
return {'error_parsing': pkgstr}
d = {
'name':n,
'arch':a,
'epoch':e,
'release':r,
'version':v,
'repo':repo,
'nevra': '%s:%s-%s-%s.%s' % (e,n,v,r,a)
}
if repo == 'installed':
d['yumstate'] = 'installed'
else:
d['yumstate'] = 'available'
return d
def repolist(module, repoq, qf="%{repoid}"):
cmd = repoq + ["--qf", qf, "-a"]
rc,out,err = module.run_command(cmd)
ret = []
if rc == 0:
ret = set([ p for p in out.split('\n') if p.strip() ])
return ret
def list_stuff(module, repoquerybin, conf_file, stuff):
qf = "%{name}|%{epoch}|%{version}|%{release}|%{arch}|%{repoid}"
# is_installed goes through rpm instead of repoquery so it needs a slightly different format
is_installed_qf = "%{name}|%{epoch}|%{version}|%{release}|%{arch}|installed\n"
repoq = [repoquerybin, '--show-duplicates', '--plugins', '--quiet']
if conf_file and os.path.exists(conf_file):
repoq += ['-c', conf_file]
if stuff == 'installed':
return [ pkg_to_dict(p) for p in sorted(is_installed(module, repoq, '-a', conf_file, qf=is_installed_qf)) if p.strip() ]
elif stuff == 'updates':
return [ pkg_to_dict(p) for p in sorted(is_update(module, repoq, '-a', conf_file, qf=qf)) if p.strip() ]
elif stuff == 'available':
return [ pkg_to_dict(p) for p in sorted(is_available(module, repoq, '-a', conf_file, qf=qf)) if p.strip() ]
elif stuff == 'repos':
return [ dict(repoid=name, state='enabled') for name in sorted(repolist(module, repoq)) if name.strip() ]
else:
return [ pkg_to_dict(p) for p in sorted(is_installed(module, repoq, stuff, conf_file, qf=is_installed_qf) + is_available(module, repoq, stuff, conf_file, qf=qf)) if p.strip() ]
def install(module, items, repoq, yum_basecmd, conf_file, en_repos, dis_repos):
pkgs = []
res = {}
res['results'] = []
res['msg'] = ''
res['rc'] = 0
res['changed'] = False
tempdir = tempfile.mkdtemp()
for spec in items:
pkg = None
# check if pkgspec is installed (if possible for idempotence)
# localpkg
if spec.endswith('.rpm') and '://' not in spec:
# get the pkg name-v-r.arch
if not os.path.exists(spec):
res['msg'] += "No RPM file matching '%s' found on system" % spec
res['results'].append("No RPM file matching '%s' found on system" % spec)
res['rc'] = 127 # Ensure the task fails in with-loop
module.fail_json(**res)
nvra = local_nvra(module, spec)
# look for them in the rpmdb
if is_installed(module, repoq, nvra, conf_file, en_repos=en_repos, dis_repos=dis_repos):
# if they are there, skip it
continue
pkg = spec
# URL
elif '://' in spec:
# download package so that we can check if it's already installed
package = fetch_rpm_from_url(spec, module=module)
nvra = local_nvra(module, package)
if is_installed(module, repoq, nvra, conf_file, en_repos=en_repos, dis_repos=dis_repos):
# if it's there, skip it
continue
pkg = package
#groups :(
elif spec.startswith('@'):
# complete wild ass guess b/c it's a group
pkg = spec
# range requires or file-requires or pkgname :(
else:
# most common case is the pkg is already installed and done
# short circuit all the bs - and search for it as a pkg in is_installed
# if you find it then we're done
if not set(['*','?']).intersection(set(spec)):
installed_pkgs = is_installed(module, repoq, spec, conf_file, en_repos=en_repos, dis_repos=dis_repos, is_pkg=True)
if installed_pkgs:
res['results'].append('%s providing %s is already installed' % (installed_pkgs[0], spec))
continue
# look up what pkgs provide this
pkglist = what_provides(module, repoq, spec, conf_file, en_repos=en_repos, dis_repos=dis_repos)
if not pkglist:
res['msg'] += "No package matching '%s' found available, installed or updated" % spec
res['results'].append("No package matching '%s' found available, installed or updated" % spec)
res['rc'] = 126 # Ensure the task fails in with-loop
module.fail_json(**res)
# if any of the packages are involved in a transaction, fail now
# so that we don't hang on the yum operation later
conflicts = transaction_exists(pkglist)
if len(conflicts) > 0:
res['msg'] += "The following packages have pending transactions: %s" % ", ".join(conflicts)
res['rc'] = 125 # Ensure the task fails in with-loop
module.fail_json(**res)
# if any of them are installed
# then nothing to do
found = False
for this in pkglist:
if is_installed(module, repoq, this, conf_file, en_repos=en_repos, dis_repos=dis_repos, is_pkg=True):
found = True
res['results'].append('%s providing %s is already installed' % (this, spec))
break
# if the version of the pkg you have installed is not in ANY repo, but there are
# other versions in the repos (both higher and lower) then the previous checks won't work.
# so we check one more time. This really only works for pkgname - not for file provides or virt provides
# but virt provides should be all caught in what_provides on its own.
# highly irritating
if not found:
if is_installed(module, repoq, spec, conf_file, en_repos=en_repos, dis_repos=dis_repos):
found = True
res['results'].append('package providing %s is already installed' % (spec))
if found:
continue
# if not - then pass in the spec as what to install
# we could get here if nothing provides it but that's not
# the error we're catching here
pkg = spec
pkgs.append(pkg)
if pkgs:
cmd = yum_basecmd + ['install'] + pkgs
if module.check_mode:
# Remove rpms downloaded for EL5 via url
try:
shutil.rmtree(tempdir)
except Exception:
e = get_exception()
module.fail_json(msg="Failure deleting temp directory %s, %s" % (tempdir, e))
module.exit_json(changed=True, results=res['results'], changes=dict(installed=pkgs))
changed = True
lang_env = dict(LANG='C', LC_ALL='C', LC_MESSAGES='C')
rc, out, err = module.run_command(cmd, environ_update=lang_env)
if (rc == 1):
for spec in items:
# Fail on invalid urls:
if ('://' in spec and ('No package %s available.' % spec in out or 'Cannot open: %s. Skipping.' % spec in err)):
module.fail_json(msg='Package at %s could not be installed' % spec, rc=1, changed=False)
if (rc != 0 and 'Nothing to do' in err) or 'Nothing to do' in out:
# avoid failing in the 'Nothing To Do' case
# this may happen with an URL spec.
# for an already installed group,
# we get rc = 0 and 'Nothing to do' in out, not in err.
rc = 0
err = ''
out = '%s: Nothing to do' % spec
changed = False
res['rc'] = rc
res['results'].append(out)
res['msg'] += err
# FIXME - if we did an install - go and check the rpmdb to see if it actually installed
# look for each pkg in rpmdb
# look for each pkg via obsoletes
# Record change
res['changed'] = changed
# Remove rpms downloaded for EL5 via url
try:
shutil.rmtree(tempdir)
except Exception:
e = get_exception()
module.fail_json(msg="Failure deleting temp directory %s, %s" % (tempdir, e))
return res
def remove(module, items, repoq, yum_basecmd, conf_file, en_repos, dis_repos):
pkgs = []
res = {}
res['results'] = []
res['msg'] = ''
res['changed'] = False
res['rc'] = 0
for pkg in items:
is_group = False
# group remove - this is doom on a stick
if pkg.startswith('@'):
is_group = True
else:
if not is_installed(module, repoq, pkg, conf_file, en_repos=en_repos, dis_repos=dis_repos):
res['results'].append('%s is not installed' % pkg)
continue
pkgs.append(pkg)
if pkgs:
# run an actual yum transaction
cmd = yum_basecmd + ["remove"] + pkgs
if module.check_mode:
module.exit_json(changed=True, results=res['results'], changes=dict(removed=pkgs))
rc, out, err = module.run_command(cmd)
res['rc'] = rc
res['results'].append(out)
res['msg'] = err
# compile the results into one batch. If anything is changed
# then mark changed
# at the end - if we've end up failed then fail out of the rest
# of the process
# at this point we should check to see if the pkg is no longer present
for pkg in pkgs:
if not pkg.startswith('@'): # we can't sensibly check for a group being uninstalled reliably
# look to see if the pkg shows up from is_installed. If it doesn't
if not is_installed(module, repoq, pkg, conf_file, en_repos=en_repos, dis_repos=dis_repos):
res['changed'] = True
else:
module.fail_json(**res)
if rc != 0:
module.fail_json(**res)
return res
def latest(module, items, repoq, yum_basecmd, conf_file, en_repos, dis_repos):
res = {}
res['results'] = []
res['msg'] = ''
res['changed'] = False
res['rc'] = 0
pkgs = {}
pkgs['update'] = []
pkgs['install'] = []
updates = {}
update_all = False
cmd = None
# determine if we're doing an update all
if '*' in items:
update_all = True
# run check-update to see if we have packages pending
rc, out, err = module.run_command(yum_basecmd + ['check-update'])
if rc == 0 and update_all:
res['results'].append('Nothing to do here, all packages are up to date')
return res
elif rc == 100:
# remove incorrect new lines in longer columns in output from yum check-update
out=re.sub('\n\W+', ' ', out)
available_updates = out.split('\n')
# build update dictionary
for line in available_updates:
line = line.split()
# ignore irrelevant lines
# FIXME... revisit for something less kludgy
if '*' in line or len(line) != 3 or '.' not in line[0]:
continue
else:
pkg, version, repo = line
name, dist = pkg.rsplit('.', 1)
updates.update({name: {'version': version, 'dist': dist, 'repo': repo}})
elif rc == 1:
res['msg'] = err
res['rc'] = rc
module.fail_json(**res)
if update_all:
cmd = yum_basecmd + ['update']
will_update = set(updates.keys())
will_update_from_other_package = dict()
else:
will_update = set()
will_update_from_other_package = dict()
for spec in items:
# some guess work involved with groups. update @<group> will install the group if missing
if spec.startswith('@'):
pkgs['update'].append(spec)
will_update.add(spec)
continue
# dep/pkgname - find it
else:
if is_installed(module, repoq, spec, conf_file, en_repos=en_repos, dis_repos=dis_repos):
pkgs['update'].append(spec)
else:
pkgs['install'].append(spec)
pkglist = what_provides(module, repoq, spec, conf_file, en_repos=en_repos, dis_repos=dis_repos)
# FIXME..? may not be desirable to throw an exception here if a single package is missing
if not pkglist:
res['msg'] += "No package matching '%s' found available, installed or updated" % spec
res['results'].append("No package matching '%s' found available, installed or updated" % spec)
res['rc'] = 126 # Ensure the task fails in with-loop
module.fail_json(**res)
nothing_to_do = True
for this in pkglist:
if spec in pkgs['install'] and is_available(module, repoq, this, conf_file, en_repos=en_repos, dis_repos=dis_repos):
nothing_to_do = False
break
# this contains the full NVR and spec could contain wildcards
# or virtual provides (like "python-*" or "smtp-daemon") while
# updates contains name only.
this_name_only = '-'.join(this.split('-')[:-2])
if spec in pkgs['update'] and this_name_only in updates:
nothing_to_do = False
will_update.add(spec)
# Massage the updates list
if spec != this_name_only:
# For reporting what packages would be updated more
# succinctly
will_update_from_other_package[spec] = this_name_only
break
if nothing_to_do:
res['results'].append("All packages providing %s are up to date" % spec)
continue
# if any of the packages are involved in a transaction, fail now
# so that we don't hang on the yum operation later
conflicts = transaction_exists(pkglist)
if len(conflicts) > 0:
res['msg'] += "The following packages have pending transactions: %s" % ", ".join(conflicts)
res['results'].append("The following packages have pending transactions: %s" % ", ".join(conflicts))
res['rc'] = 128 # Ensure the task fails in with-loop
module.fail_json(**res)
# check_mode output
if module.check_mode:
to_update = []
for w in will_update:
if w.startswith('@'):
to_update.append((w, None))
msg = '%s will be updated' % w
elif w not in updates:
other_pkg = will_update_from_other_package[w]
to_update.append((w, 'because of (at least) %s-%s.%s from %s' % (other_pkg, updates[other_pkg]['version'], updates[other_pkg]['dist'], updates[other_pkg]['repo'])))
else:
to_update.append((w, '%s.%s from %s' % (updates[w]['version'], updates[w]['dist'], updates[w]['repo'])))
res['changes'] = dict(installed=pkgs['install'], updated=to_update)
if len(will_update) > 0 or len(pkgs['install']) > 0:
res['changed'] = True
return res
# run commands
if cmd: # update all
rc, out, err = module.run_command(cmd)
res['changed'] = True
else:
if len(pkgs['install']) > 0: # install missing
cmd = yum_basecmd + ['install'] + pkgs['install']
rc, out, err = module.run_command(cmd)
if not out.strip().lower().endswith("no packages marked for update"):
res['changed'] = True
else:
rc, out, err = [0, '', '']
if len(will_update) > 0: # update present
cmd = yum_basecmd + ['update'] + pkgs['update']
rc2, out2, err2 = module.run_command(cmd)
if not out2.strip().lower().endswith("no packages marked for update"):
res['changed'] = True
else:
rc2, out2, err2 = [0, '', '']
if not update_all:
rc += rc2
out += out2
err += err2
res['rc'] += rc
res['msg'] += err
res['results'].append(out)
if rc:
res['failed'] = True
return res
def ensure(module, state, pkgs, conf_file, enablerepo, disablerepo,
disable_gpg_check, exclude, repoq):
# fedora will redirect yum to dnf, which has incompatibilities
# with how this module expects yum to operate. If yum-deprecated
# is available, use that instead to emulate the old behaviors.
if module.get_bin_path('yum-deprecated'):
yumbin = module.get_bin_path('yum-deprecated')
else:
yumbin = module.get_bin_path('yum')
# need debug level 2 to get 'Nothing to do' for groupinstall.
yum_basecmd = [yumbin, '-d', '2', '-y']
if conf_file and os.path.exists(conf_file):
yum_basecmd += ['-c', conf_file]
if repoq:
repoq += ['-c', conf_file]
dis_repos =[]
en_repos = []
if disablerepo:
dis_repos = disablerepo.split(',')
r_cmd = ['--disablerepo=%s' % disablerepo]
yum_basecmd.extend(r_cmd)
if enablerepo:
en_repos = enablerepo.split(',')
r_cmd = ['--enablerepo=%s' % enablerepo]
yum_basecmd.extend(r_cmd)
if exclude:
e_cmd = ['--exclude=%s' % exclude]
yum_basecmd.extend(e_cmd)
if state in ['installed', 'present', 'latest']:
if module.params.get('update_cache'):
module.run_command(yum_basecmd + ['makecache'])
my = yum_base(conf_file)
try:
if disablerepo:
my.repos.disableRepo(disablerepo)
current_repos = my.repos.repos.keys()
if enablerepo:
try:
my.repos.enableRepo(enablerepo)
new_repos = my.repos.repos.keys()
for i in new_repos:
if not i in current_repos:
rid = my.repos.getRepo(i)
a = rid.repoXML.repoid
current_repos = new_repos
except yum.Errors.YumBaseError:
e = get_exception()
module.fail_json(msg="Error setting/accessing repos: %s" % (e))
except yum.Errors.YumBaseError:
e = get_exception()
module.fail_json(msg="Error accessing repos: %s" % e)
if state in ['installed', 'present']:
if disable_gpg_check:
yum_basecmd.append('--nogpgcheck')
res = install(module, pkgs, repoq, yum_basecmd, conf_file, en_repos, dis_repos)
elif state in ['removed', 'absent']:
res = remove(module, pkgs, repoq, yum_basecmd, conf_file, en_repos, dis_repos)
elif state == 'latest':
if disable_gpg_check:
yum_basecmd.append('--nogpgcheck')
res = latest(module, pkgs, repoq, yum_basecmd, conf_file, en_repos, dis_repos)
else:
# should be caught by AnsibleModule argument_spec
module.fail_json(msg="we should never get here unless this all"
" failed", changed=False, results='', errors='unexpected state')
return res
def main():
# state=installed name=pkgspec
# state=removed name=pkgspec
# state=latest name=pkgspec
#
# informational commands:
# list=installed
# list=updates
# list=available
# list=repos
# list=pkgspec
module = AnsibleModule(
argument_spec = dict(
name=dict(aliases=['pkg'], type="list"),
exclude=dict(required=False, default=None),
# removed==absent, installed==present, these are accepted as aliases
state=dict(default='installed', choices=['absent','present','installed','removed','latest']),
enablerepo=dict(),
disablerepo=dict(),
list=dict(),
conf_file=dict(default=None),
disable_gpg_check=dict(required=False, default="no", type='bool'),
update_cache=dict(required=False, default="no", type='bool'),
validate_certs=dict(required=False, default="yes", type='bool'),
# this should not be needed, but exists as a failsafe
install_repoquery=dict(required=False, default="yes", type='bool'),
),
required_one_of = [['name','list']],
mutually_exclusive = [['name','list']],
supports_check_mode = True
)
params = module.params
if params['list']:
repoquerybin = ensure_yum_utils(module)
if not repoquerybin:
module.fail_json(msg="repoquery is required to use list= with this module. Please install the yum-utils package.")
results = dict(results=list_stuff(module, repoquerybin, params['conf_file'], params['list']))
else:
# If rhn-plugin is installed and no rhn-certificate is available on
# the system then users will see an error message using the yum API.
# Use repoquery in those cases.
my = yum_base(params['conf_file'])
# A sideeffect of accessing conf is that the configuration is
# loaded and plugins are discovered
my.conf
repoquery = None
try:
yum_plugins = my.plugins._plugins
except AttributeError:
pass
else:
if 'rhnplugin' in yum_plugins:
repoquerybin = ensure_yum_utils(module)
if repoquerybin:
repoquery = [repoquerybin, '--show-duplicates', '--plugins', '--quiet']
pkg = [ p.strip() for p in params['name']]
exclude = params['exclude']
state = params['state']
enablerepo = params.get('enablerepo', '')
disablerepo = params.get('disablerepo', '')
disable_gpg_check = params['disable_gpg_check']
results = ensure(module, state, pkg, params['conf_file'], enablerepo,
disablerepo, disable_gpg_check, exclude, repoquery)
if repoquery:
results['msg'] = '%s %s' % (results.get('msg',''),
'Warning: Due to potential bad behaviour with rhnplugin and certificates, used slower repoquery calls instead of Yum API.')
module.exit_json(**results)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.urls import *
if __name__ == '__main__':
main()
| gpl-3.0 |
MarmonDesigns/cloud.ky | wp-content/themes/milo/install/fresh-framework/adminScreens/bootstrapVariables/class.ffAdminScreenBootstrapVariables.php | 450 | <?php
class ffAdminScreenBootstrapVariables extends ffAdminScreen implements ffIAdminScreen {
public function getMenu() {
$menu = $this->_getMenuObject();
//add_menu_page($page_title, $menu_title, $capability, $menu_slug)
$menu->pageTitle = 'Bootstrap Variables';
$menu->menuTitle = 'Bootstrap Variables';
$menu->type = ffMenu::TYPE_SUB_LEVEL;
$menu->capability = 'manage_options';
$menu->parentSlug='themes.php';
return $menu;
}
} | gpl-3.0 |
madhumita-dfki/Excitement-Open-Platform | lexicalinferenceminer/src/main/java/eu/excitementproject/eop/lexicalminer/definition/classifier/syntacticpatterns/offlineClassifiers/syntacticpatternsCounts/SyntacticOfflinePosRelationCountClassifier.java | 646 | package eu.excitementproject.eop.lexicalminer.definition.classifier.syntacticpatterns.offlineClassifiers.syntacticpatternsCounts;
import eu.excitementproject.eop.lexicalminer.dataAccessLayer.RetrievalTool;
public class SyntacticOfflinePosRelationCountClassifier extends
SyntacticAbstractOfflineCountClassifier {
public SyntacticOfflinePosRelationCountClassifier(RetrievalTool retrivalTool, Double NPBonus) {
super(retrivalTool,NPBonus);
}
@Override
protected void setM_PatternNameColumn() {
m_PatternNameColumn = "POSrelationsPattern";
}
@Override
protected void setM_PatternKind() {
m_PatternKind = "pos_relations";
}
}
| gpl-3.0 |
65/ga-popular-posts | lib/google-api-php-client-2.2.0/vendor/google/apiclient-services/src/Google/Service/AndroidEnterprise/Resource/Enterprises.php | 14836 | <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "enterprises" collection of methods.
* Typical usage is:
* <code>
* $androidenterpriseService = new Google_Service_AndroidEnterprise(...);
* $enterprises = $androidenterpriseService->enterprises;
* </code>
*/
class Google_Service_AndroidEnterprise_Resource_Enterprises extends Google_Service_Resource
{
/**
* Acknowledges notifications that were received from
* Enterprises.PullNotificationSet to prevent subsequent calls from returning
* the same notifications. (enterprises.acknowledgeNotificationSet)
*
* @param array $optParams Optional parameters.
*
* @opt_param string notificationSetId The notification set ID as returned by
* Enterprises.PullNotificationSet. This must be provided.
*/
public function acknowledgeNotificationSet($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('acknowledgeNotificationSet', array($params));
}
/**
* Completes the signup flow, by specifying the Completion token and Enterprise
* token. This request must not be called multiple times for a given Enterprise
* Token. (enterprises.completeSignup)
*
* @param array $optParams Optional parameters.
*
* @opt_param string completionToken The Completion token initially returned by
* GenerateSignupUrl.
* @opt_param string enterpriseToken The Enterprise token appended to the
* Callback URL.
* @return Google_Service_AndroidEnterprise_Enterprise
*/
public function completeSignup($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('completeSignup', array($params), "Google_Service_AndroidEnterprise_Enterprise");
}
/**
* Returns a unique token to access an embeddable UI. To generate a web UI, pass
* the generated token into the managed Google Play javascript API. Each token
* may only be used to start one UI session. See the javascript API
* documentation for further information. (enterprises.createWebToken)
*
* @param string $enterpriseId The ID of the enterprise.
* @param Google_Service_AndroidEnterprise_AdministratorWebTokenSpec $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_AndroidEnterprise_AdministratorWebToken
*/
public function createWebToken($enterpriseId, Google_Service_AndroidEnterprise_AdministratorWebTokenSpec $postBody, $optParams = array())
{
$params = array('enterpriseId' => $enterpriseId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('createWebToken', array($params), "Google_Service_AndroidEnterprise_AdministratorWebToken");
}
/**
* Deletes the binding between the EMM and enterprise. This is now deprecated.
* Use this method only to unenroll customers that were previously enrolled with
* the insert call, then enroll them again with the enroll call.
* (enterprises.delete)
*
* @param string $enterpriseId The ID of the enterprise.
* @param array $optParams Optional parameters.
*/
public function delete($enterpriseId, $optParams = array())
{
$params = array('enterpriseId' => $enterpriseId);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params));
}
/**
* Enrolls an enterprise with the calling EMM. (enterprises.enroll)
*
* @param string $token The token provided by the enterprise to register the
* EMM.
* @param Google_Service_AndroidEnterprise_Enterprise $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_AndroidEnterprise_Enterprise
*/
public function enroll($token, Google_Service_AndroidEnterprise_Enterprise $postBody, $optParams = array())
{
$params = array('token' => $token, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('enroll', array($params), "Google_Service_AndroidEnterprise_Enterprise");
}
/**
* Generates a sign-up URL. (enterprises.generateSignupUrl)
*
* @param array $optParams Optional parameters.
*
* @opt_param string callbackUrl The callback URL to which the Admin will be
* redirected after successfully creating an enterprise. Before redirecting
* there the system will add a single query parameter to this URL named
* "enterpriseToken" which will contain an opaque token to be used for the
* CompleteSignup request. Beware that this means that the URL will be parsed,
* the parameter added and then a new URL formatted, i.e. there may be some
* minor formatting changes and, more importantly, the URL must be well-formed
* so that it can be parsed.
* @return Google_Service_AndroidEnterprise_SignupInfo
*/
public function generateSignupUrl($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('generateSignupUrl', array($params), "Google_Service_AndroidEnterprise_SignupInfo");
}
/**
* Retrieves the name and domain of an enterprise. (enterprises.get)
*
* @param string $enterpriseId The ID of the enterprise.
* @param array $optParams Optional parameters.
* @return Google_Service_AndroidEnterprise_Enterprise
*/
public function get($enterpriseId, $optParams = array())
{
$params = array('enterpriseId' => $enterpriseId);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_AndroidEnterprise_Enterprise");
}
/**
* Returns a service account and credentials. The service account can be bound
* to the enterprise by calling setAccount. The service account is unique to
* this enterprise and EMM, and will be deleted if the enterprise is unbound.
* The credentials contain private key data and are not stored server-side.
*
* This method can only be called after calling Enterprises.Enroll or
* Enterprises.CompleteSignup, and before Enterprises.SetAccount; at other times
* it will return an error.
*
* Subsequent calls after the first will generate a new, unique set of
* credentials, and invalidate the previously generated credentials.
*
* Once the service account is bound to the enterprise, it can be managed using
* the serviceAccountKeys resource. (enterprises.getServiceAccount)
*
* @param string $enterpriseId The ID of the enterprise.
* @param array $optParams Optional parameters.
*
* @opt_param string keyType The type of credential to return with the service
* account. Required.
* @return Google_Service_AndroidEnterprise_ServiceAccount
*/
public function getServiceAccount($enterpriseId, $optParams = array())
{
$params = array('enterpriseId' => $enterpriseId);
$params = array_merge($params, $optParams);
return $this->call('getServiceAccount', array($params), "Google_Service_AndroidEnterprise_ServiceAccount");
}
/**
* Returns the store layout for the enterprise. If the store layout has not been
* set, returns "basic" as the store layout type and no homepage.
* (enterprises.getStoreLayout)
*
* @param string $enterpriseId The ID of the enterprise.
* @param array $optParams Optional parameters.
* @return Google_Service_AndroidEnterprise_StoreLayout
*/
public function getStoreLayout($enterpriseId, $optParams = array())
{
$params = array('enterpriseId' => $enterpriseId);
$params = array_merge($params, $optParams);
return $this->call('getStoreLayout', array($params), "Google_Service_AndroidEnterprise_StoreLayout");
}
/**
* Establishes the binding between the EMM and an enterprise. This is now
* deprecated; use enroll instead. (enterprises.insert)
*
* @param string $token The token provided by the enterprise to register the
* EMM.
* @param Google_Service_AndroidEnterprise_Enterprise $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_AndroidEnterprise_Enterprise
*/
public function insert($token, Google_Service_AndroidEnterprise_Enterprise $postBody, $optParams = array())
{
$params = array('token' => $token, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_AndroidEnterprise_Enterprise");
}
/**
* Looks up an enterprise by domain name. This is only supported for enterprises
* created via the Google-initiated creation flow. Lookup of the id is not
* needed for enterprises created via the EMM-initiated flow since the EMM
* learns the enterprise ID in the callback specified in the
* Enterprises.generateSignupUrl call. (enterprises.listEnterprises)
*
* @param string $domain The exact primary domain name of the enterprise to look
* up.
* @param array $optParams Optional parameters.
* @return Google_Service_AndroidEnterprise_EnterprisesListResponse
*/
public function listEnterprises($domain, $optParams = array())
{
$params = array('domain' => $domain);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_AndroidEnterprise_EnterprisesListResponse");
}
/**
* Pulls and returns a notification set for the enterprises associated with the
* service account authenticated for the request. The notification set may be
* empty if no notification are pending. A notification set returned needs to be
* acknowledged within 20 seconds by calling
* Enterprises.AcknowledgeNotificationSet, unless the notification set is empty.
* Notifications that are not acknowledged within the 20 seconds will eventually
* be included again in the response to another PullNotificationSet request, and
* those that are never acknowledged will ultimately be deleted according to the
* Google Cloud Platform Pub/Sub system policy. Multiple requests might be
* performed concurrently to retrieve notifications, in which case the pending
* notifications (if any) will be split among each caller, if any are pending.
* If no notifications are present, an empty notification list is returned.
* Subsequent requests may return more notifications once they become available.
* (enterprises.pullNotificationSet)
*
* @param array $optParams Optional parameters.
*
* @opt_param string requestMode The request mode for pulling notifications.
* Specifying waitForNotifications will cause the request to block and wait
* until one or more notifications are present, or return an empty notification
* list if no notifications are present after some time. Speciying
* returnImmediately will cause the request to immediately return the pending
* notifications, or an empty list if no notifications are present. If omitted,
* defaults to waitForNotifications.
* @return Google_Service_AndroidEnterprise_NotificationSet
*/
public function pullNotificationSet($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('pullNotificationSet', array($params), "Google_Service_AndroidEnterprise_NotificationSet");
}
/**
* Sends a test push notification to validate the EMM integration with the
* Google Cloud Pub/Sub service for this enterprise.
* (enterprises.sendTestPushNotification)
*
* @param string $enterpriseId The ID of the enterprise.
* @param array $optParams Optional parameters.
* @return Google_Service_AndroidEnterprise_EnterprisesSendTestPushNotificationResponse
*/
public function sendTestPushNotification($enterpriseId, $optParams = array())
{
$params = array('enterpriseId' => $enterpriseId);
$params = array_merge($params, $optParams);
return $this->call('sendTestPushNotification', array($params), "Google_Service_AndroidEnterprise_EnterprisesSendTestPushNotificationResponse");
}
/**
* Sets the account that will be used to authenticate to the API as the
* enterprise. (enterprises.setAccount)
*
* @param string $enterpriseId The ID of the enterprise.
* @param Google_Service_AndroidEnterprise_EnterpriseAccount $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_AndroidEnterprise_EnterpriseAccount
*/
public function setAccount($enterpriseId, Google_Service_AndroidEnterprise_EnterpriseAccount $postBody, $optParams = array())
{
$params = array('enterpriseId' => $enterpriseId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('setAccount', array($params), "Google_Service_AndroidEnterprise_EnterpriseAccount");
}
/**
* Sets the store layout for the enterprise. By default, storeLayoutType is set
* to "basic" and the basic store layout is enabled. The basic layout only
* contains apps approved by the admin, and that have been added to the
* available product set for a user (using the setAvailableProductSet call).
* Apps on the page are sorted in order of their product ID value. If you create
* a custom store layout (by setting storeLayoutType = "custom" and setting a
* homepage), the basic store layout is disabled. (enterprises.setStoreLayout)
*
* @param string $enterpriseId The ID of the enterprise.
* @param Google_Service_AndroidEnterprise_StoreLayout $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_AndroidEnterprise_StoreLayout
*/
public function setStoreLayout($enterpriseId, Google_Service_AndroidEnterprise_StoreLayout $postBody, $optParams = array())
{
$params = array('enterpriseId' => $enterpriseId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('setStoreLayout', array($params), "Google_Service_AndroidEnterprise_StoreLayout");
}
/**
* Unenrolls an enterprise from the calling EMM. (enterprises.unenroll)
*
* @param string $enterpriseId The ID of the enterprise.
* @param array $optParams Optional parameters.
*/
public function unenroll($enterpriseId, $optParams = array())
{
$params = array('enterpriseId' => $enterpriseId);
$params = array_merge($params, $optParams);
return $this->call('unenroll', array($params));
}
}
| gpl-3.0 |
smartebikes/SmartEbikesMonitorSystem | android_app/IOIOLib/src/ioio/lib/api/PulseInput.java | 11680 | /*
* Copyright 2011 Ytai Ben-Tsvi. All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED "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 ARSHAN POURSOHI 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.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied.
*/
package ioio.lib.api;
import ioio.lib.api.exception.ConnectionLostException;
/**
* An interface for pulse width and frequency measurements of digital signals.
* <p>
* PulseInput (commonly known as "input capture") is a versatile module which
* enables extraction of various timing information from a digital signal. There
* are two main use cases: pulse duration measurement and frequency measurement.
* In pulse width measurement we measure the duration of a positive ("high") or
* negative ("low") pulse, i.e. the elapsed time between a rise and a fall or
* vice versa. This mode is useful, for example, for decoding a PWM signal or
* measuring the delay of a sonar return signal. In frequency measurement we
* measure the duration between a rising edge to the following rising edge. This
* gives us a momentary reading of a signal's frequency or period. This is
* commonly used, for example, in conjunction with an optical or magnetic sensor
* for measuring a turning shaft's speed.
* <p>
* {@link PulseInput} instances are obtained by calling
* {@link IOIO#openPulseInput(ioio.lib.api.DigitalInput.Spec, ioio.lib.api.PulseInput.ClockRate, ioio.lib.api.PulseInput.PulseMode, boolean)}
* . When created, some important configuration decisions have to be made: the
* precision (single or double), the clock rate and the mode of operation. Modes
* are straightforward: {@link PulseMode#POSITIVE} is used for measuring a
* positive pulse, {@link PulseMode#NEGATIVE} a negative pulse, and
* {@link PulseMode#FREQ} / {@link PulseMode#FREQ_SCALE_4} /
* {@link PulseMode#FREQ_SCALE_16} are used for measuring frequency. The
* difference between the three scaling modes is that without scaling, the
* frequency is determined by measurement of a single
* (rising-edge-to-rising-edge) period. In x4 scaling, 4 consecutive periods are
* measured and the time is divided by 4, providing some smoothing as well as
* better resolution. Similarly for x16 scaling. Note that scaling affects the
* range of signals to be measured, as discussed below.
* <p>
* The choice of single vs. double-precision is important to understand: IOIO
* internally uses either 16-bit counters or 32-bit counters for the timing. 16-
* counters force us to either limit the maximum duration (and the minimum
* frequency) or compromise accuracy as compared to 32-bit counters. However, if
* you need many concurrent pulse measurements in your application, you may have
* no choice but to use single-precision.
* <p>
* The clock rate selection is important (and even critical when working in
* single-precision) and requires the user to make some assumptions about the
* nature of the measured signal. The higher the clock rate, the more precise
* the measurement, but the longest pulse that can be measured decreases (or
* lowest frequency that can be measured increases). Using the scaling option
* when operating in frequency mode also affects these sizes. combinations. It
* is always recommended to choose the most precise mode, which exceeds the
* maximum expected pulse width (or inverse frequency). If a pulse is received
* whom duration exceeds the longest allowed pulse, it will be "folded" into the
* valid range and product garbage readings.
* <p>
* The following table (sorted by longest pulse) summarizes all possible clock /
* mode combinations. The table applies for <b>single-precision</b> operation.
* For double-precision, simply multiply the longest pulse by 65536 and divide
* the lowest frequency by the same amount. Interestingly, the number written in
* [ms] units in the longest pulse column, roughly corresponds to the same
* number in minutes when working with double precsion, since 1[min] =
* 60000[ms].
* <table border="1">
* <tr>
* <th>Clock</th>
* <th>Scaling</th>
* <th>Resolution</th>
* <th>Longest pulse</th>
* <th>Lowest frequency</th>
* </tr>
* <tr>
* <td>62.5KHz</td>
* <td>1</td>
* <td>16us</td>
* <td>1.048s</td>
* <td>0.95Hz</td>
* </tr>
* <tr>
* <td>250KHz</td>
* <td>1</td>
* <td>4us</td>
* <td>262.1ms</td>
* <td>3.81Hz</td>
* </tr>
* <tr>
* <td>62.5KHz</td>
* <td>4</td>
* <td>4us</td>
* <td>262.1ms</td>
* <td>3.81Hz</td>
* </tr>
* <tr>
* <td>250KHz</td>
* <td>4</td>
* <td>1us</td>
* <td>65.54ms</td>
* <td>15.26Hz</td>
* </tr>
* <tr>
* <td>62.5KHz</td>
* <td>16</td>
* <td>1us</td>
* <td>65.54ms</td>
* <td>15.26Hz</td>
* </tr>
* <tr>
* <td>2MHz</td>
* <td>1</td>
* <td>500ns</td>
* <td>32.77ms</td>
* <td>30.52Hz</td>
* </tr>
* <tr>
* <td>250KHz</td>
* <td>16</td>
* <td>250us</td>
* <td>16.38ms</td>
* <td>61.0Hz</td>
* </tr>
* <tr>
* <td>2MHz</td>
* <td>4</td>
* <td>125ns</td>
* <td>8.192ms</td>
* <td>122.1Hz</td>
* </tr>
* <tr>
* <td>16MHz</td>
* <td>1</td>
* <td>62.5ns</td>
* <td>4.096ms</td>
* <td>244.1Hz</td>
* </tr>
* <tr>
* <td>2MHz</td>
* <td>16</td>
* <td>31.25ns</td>
* <td>2.048ms</td>
* <td>488.3Hz</td>
* </tr>
* <tr>
* <td>16MHz</td>
* <td>4</td>
* <td>15.6ns</td>
* <td>1.024ms</td>
* <td>976.6Hz</td>
* </tr>
* <tr>
* <td>16MHz</td>
* <td>16</td>
* <td>3.9ns</td>
* <td>256us</td>
* <td>3.906KHz</td>
* </tr>
* </table>
*
* <p>
* In some applications it is desirable to measure every incoming pulse rather
* than repetitively query the result of the last measurement. For that purpose
* the {@link #waitPulseGetDuration()} method exists: every incoming pulse width
* is pushed into a small internal queue from which it can be read. The client
* waits for data to be available, then reads it and data that comes in in the
* meanwhile is stored. The queue has limited size, so it is important to read
* quickly if no pulses are to be lost. Note that once a pulse is detected, the
* next one must have its leading edge at least 5ms after the leading edge of
* the current one, or else it will be skipped. This throttling has been
* introduced on purpose, in order to prevent saturation the communication
* channel when the input signal is very high frequency. Effectively, this means
* that the maximum sample rate is 200Hz. This rate has been chosen as it
* enables measure R/C servo signals without missing pulses.
*
* <p>
* Typical usage (servo signal pulse width measurement):
*
* <pre>
* {@code
* // Open pulse input at 16MHz, double-precision
* PulseInput in = ioio.openPulseInput(3, PulseMode.POSITIVE);
* ...
* float widthSec = in.getDuration();
* OR:
* float widthSec = in.waitPulseGetDuration();
* ...
* in.close(); // pin 3 can now be used for something else.
* }
* </pre>
*
* <p>
* Typical usage (frequency measurement):
*
* <pre>
* {@code
* // Signal is known to be slightly over 150Hz. Single precision can be used.
* PulseInput in = ioio.openPulseInput(3,
* ClockRate.RATE_2MHz,
* PulseMode.FREQ_SCALE_4,
* false);
* ...
* float freqHz = in.getFrequency();
* ...
* in.close(); // pin 3 can now be used for something else.
* }
* </pre>
*/
public interface PulseInput extends Closeable {
/** An enumeration for describing the module's operating mode. */
public enum PulseMode {
/** Positive pulse measurement (rising-edge-to-falling-edge). */
POSITIVE(1),
/** Negative pulse measurement (falling-edge-to-rising-edge). */
NEGATIVE(1),
/** Frequency measurement (rising-edge-to-rising-edge). */
FREQ(1),
/** Frequency measurement (rising-edge-to-rising-edge) with 4x scaling. */
FREQ_SCALE_4(4),
/** Frequency measurement (rising-edge-to-rising-edge) with 16x scaling. */
FREQ_SCALE_16(16);
/** The scaling factor as an integer. */
public final int scaling;
private PulseMode(int s) {
scaling = s;
}
}
/** Suported clock rate enum. */
public enum ClockRate {
/** 16MHz */
RATE_16MHz(16000000),
/** 2MHz */
RATE_2MHz(2000000),
/** 250KHz */
RATE_250KHz(250000),
/** 62.5KHz */
RATE_62KHz(62500);
/** The value in Hertz units. */
public final int hertz;
private ClockRate(int h) {
hertz = h;
}
}
/**
* Gets the pulse duration in case of pulse measurement mode, or the period
* in case of frequency mode. When scaling is used, this is compensated for
* here, so the duration of a single cycle will be returned.
* <p>
* The first call to this method may block shortly until the first data
* update arrives. The client may interrupt the calling thread.
*
* @return The duration, in seconds.
* @throws InterruptedException
* The calling thread has been interrupted.
* @throws ConnectionLostException
* The connection with the IOIO has been lost.
*/
public float getDuration() throws InterruptedException,
ConnectionLostException;
/**
* Reads a single measurement from the queue. If the queue is empty, will
* block until more data arrives. The calling thread may be interrupted in
* order to abort the call. See interface documentation for further
* explanation regarding the read queue.
* <p>
* This method may not be used if the interface has was opened in frequency
* mode.
*
* @return The duration, in seconds.
* @throws InterruptedException
* The calling thread has been interrupted.
* @throws ConnectionLostException
* The connection with the IOIO has been lost.
*/
public float waitPulseGetDuration() throws InterruptedException,
ConnectionLostException;
/**
* Gets the momentary frequency of the measured signal. When scaling is
* used, this is compensated for here, so the true frequency of the signal
* will be returned.
* <p>
* The first call to this method may block shortly until the first data
* update arrives. The client may interrupt the calling thread.
*
* @return The frequency, in Hz.
* @throws InterruptedException
* The calling thread has been interrupted.
* @throws ConnectionLostException
* The connection with the IOIO has been lost.
*/
public float getFrequency() throws InterruptedException,
ConnectionLostException;
}
| gpl-3.0 |
Pengostores/magento1_training | app/code/core/Mage/Catalog/Model/Api2/Product/Category/Rest.php | 2898 | <?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_Catalog
* @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)
*/
/**
* Abstract API2 class for product categories
*
* @category Mage
* @package Mage_Catalog
* @author Magento Core Team <core@magentocommerce.com>
*/
abstract class Mage_Catalog_Model_Api2_Product_Category_Rest extends Mage_Catalog_Model_Api2_Product_Rest
{
/**
* Product category assign is not available
*
* @param array $data
*/
protected function _create(array $data)
{
$this->_critical(self::RESOURCE_METHOD_NOT_ALLOWED);
}
/**
* Product category update is not available
*
* @param array $data
*/
protected function _update(array $data)
{
$this->_critical(self::RESOURCE_METHOD_NOT_ALLOWED);
}
/**
* Retrieve product data
*
* @return array
*/
protected function _retrieveCollection()
{
$return = array();
foreach ($this->_getCategoryIds() as $categoryId) {
$return[] = array('category_id' => $categoryId);
}
return $return;
}
/**
* Only admin have permissions for product category unassign
*/
protected function _delete()
{
$this->_critical(self::RESOURCE_METHOD_NOT_ALLOWED);
}
/**
* Load category by id
*
* @param int $categoryId
* @return Mage_Catalog_Model_Category
*/
protected function _getCategoryById($categoryId)
{
/** @var $category Mage_Catalog_Model_Category */
$category = Mage::getModel('catalog/category')->setStoreId(0)->load($categoryId);
if (!$category->getId()) {
$this->_critical('Category not found', Mage_Api2_Model_Server::HTTP_NOT_FOUND);
}
return $category;
}
/**
* Get assigned categories ids
*
* @return array
*/
protected function _getCategoryIds()
{
return $this->_getProduct()->getCategoryCollection()->addIsActiveFilter()->getAllIds();
}
}
| gpl-3.0 |
madhumita-dfki/Excitement-Open-Platform | distsim/src/main/java/eu/excitementproject/eop/distsim/storage/LoadingStateException.java | 782 | /**
*
*/
package eu.excitementproject.eop.distsim.storage;
/**
* @author Meni Adler
* @since 01/07/2012
*
*/
public class LoadingStateException extends Exception {
private static final long serialVersionUID = 1L;
/**
*
*/
public LoadingStateException() {
// TODO Auto-generated constructor stub
}
/**
* @param message
*/
public LoadingStateException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
/**
* @param cause
*/
public LoadingStateException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
/**
* @param message
* @param cause
*/
public LoadingStateException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
}
| gpl-3.0 |
MatzFan/bitsharesblocks | config/spec-e2e.js | 334 | exports.config = {
chromeOnly: true,
chromeDriver: '../node_modules/protractor/selenium/chromedriver',
specs: [
'../spec-e2e/**/*spec.{js,coffee}'
],
capabilities: {
'browserName': 'chrome'
},
baseUrl: 'http://localhost:8000',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000
}
};
| gpl-3.0 |
HexHive/datashield | libcxx/libcxx/test/std/depr/depr.auto.ptr/auto.ptr/element_type.pass.cpp | 748 | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <memory>
// template <class X>
// class auto_ptr
// {
// public:
// typedef X element_type;
// ...
// };
#include <memory>
#include <type_traits>
template <class T>
void
test()
{
static_assert((std::is_same<typename std::auto_ptr<T>::element_type, T>::value), "");
std::auto_ptr<T> p;
((void)p);
}
int main()
{
test<int>();
test<double>();
test<void>();
}
| gpl-3.0 |
pquerna/cloud-init-debian-pkg-dead | cloudinit/config/cc_mounts.py | 8483 | # vi: ts=4 expandtab
#
# Copyright (C) 2009-2010 Canonical Ltd.
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
#
# Author: Scott Moser <scott.moser@canonical.com>
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3, as
# published by the Free Software Foundation.
#
# 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/>.
from string import whitespace # pylint: disable=W0402
import logging
import os.path
import re
from cloudinit import type_utils
from cloudinit import util
# Shortname matches 'sda', 'sda1', 'xvda', 'hda', 'sdb', xvdb, vda, vdd1, sr0
SHORTNAME_FILTER = r"^([x]{0,1}[shv]d[a-z][0-9]*|sr[0-9]+)$"
SHORTNAME = re.compile(SHORTNAME_FILTER)
WS = re.compile("[%s]+" % (whitespace))
FSTAB_PATH = "/etc/fstab"
LOG = logging.getLogger(__name__)
def is_mdname(name):
# return true if this is a metadata service name
if name in ["ami", "root", "swap"]:
return True
# names 'ephemeral0' or 'ephemeral1'
# 'ebs[0-9]' appears when '--block-device-mapping sdf=snap-d4d90bbc'
for enumname in ("ephemeral", "ebs"):
if name.startswith(enumname) and name.find(":") == -1:
return True
return False
def sanitize_devname(startname, transformer, log):
log.debug("Attempting to determine the real name of %s", startname)
# workaround, allow user to specify 'ephemeral'
# rather than more ec2 correct 'ephemeral0'
devname = startname
if devname == "ephemeral":
devname = "ephemeral0"
log.debug("Adjusted mount option from ephemeral to ephemeral0")
(blockdev, part) = util.expand_dotted_devname(devname)
if is_mdname(blockdev):
orig = blockdev
blockdev = transformer(blockdev)
if not blockdev:
return None
if not blockdev.startswith("/"):
blockdev = "/dev/%s" % blockdev
log.debug("Mapped metadata name %s to %s", orig, blockdev)
else:
if SHORTNAME.match(startname):
blockdev = "/dev/%s" % blockdev
return devnode_for_dev_part(blockdev, part)
def handle(_name, cfg, cloud, log, _args):
# fs_spec, fs_file, fs_vfstype, fs_mntops, fs-freq, fs_passno
defvals = [None, None, "auto", "defaults,nobootwait", "0", "2"]
defvals = cfg.get("mount_default_fields", defvals)
# these are our default set of mounts
defmnts = [["ephemeral0", "/mnt", "auto", defvals[3], "0", "2"],
["swap", "none", "swap", "sw", "0", "0"]]
cfgmnt = []
if "mounts" in cfg:
cfgmnt = cfg["mounts"]
for i in range(len(cfgmnt)):
# skip something that wasn't a list
if not isinstance(cfgmnt[i], list):
log.warn("Mount option %s not a list, got a %s instead",
(i + 1), type_utils.obj_name(cfgmnt[i]))
continue
start = str(cfgmnt[i][0])
sanitized = sanitize_devname(start, cloud.device_name_to_device, log)
if sanitized is None:
log.debug("Ignorming nonexistant named mount %s", start)
continue
if sanitized != start:
log.debug("changed %s => %s" % (start, sanitized))
cfgmnt[i][0] = sanitized
# in case the user did not quote a field (likely fs-freq, fs_passno)
# but do not convert None to 'None' (LP: #898365)
for j in range(len(cfgmnt[i])):
if cfgmnt[i][j] is None:
continue
else:
cfgmnt[i][j] = str(cfgmnt[i][j])
for i in range(len(cfgmnt)):
# fill in values with defaults from defvals above
for j in range(len(defvals)):
if len(cfgmnt[i]) <= j:
cfgmnt[i].append(defvals[j])
elif cfgmnt[i][j] is None:
cfgmnt[i][j] = defvals[j]
# if the second entry in the list is 'None' this
# clears all previous entries of that same 'fs_spec'
# (fs_spec is the first field in /etc/fstab, ie, that device)
if cfgmnt[i][1] is None:
for j in range(i):
if cfgmnt[j][0] == cfgmnt[i][0]:
cfgmnt[j][1] = None
# for each of the "default" mounts, add them only if no other
# entry has the same device name
for defmnt in defmnts:
start = defmnt[0]
sanitized = sanitize_devname(start, cloud.device_name_to_device, log)
if sanitized is None:
log.debug("Ignoring nonexistant default named mount %s", start)
continue
if sanitized != start:
log.debug("changed default device %s => %s" % (start, sanitized))
defmnt[0] = sanitized
cfgmnt_has = False
for cfgm in cfgmnt:
if cfgm[0] == defmnt[0]:
cfgmnt_has = True
break
if cfgmnt_has:
log.debug(("Not including %s, already"
" previously included"), start)
continue
cfgmnt.append(defmnt)
# now, each entry in the cfgmnt list has all fstab values
# if the second field is None (not the string, the value) we skip it
actlist = []
for x in cfgmnt:
if x[1] is None:
log.debug("Skipping non-existent device named %s", x[0])
else:
actlist.append(x)
if len(actlist) == 0:
log.debug("No modifications to fstab needed.")
return
comment = "comment=cloudconfig"
cc_lines = []
needswap = False
dirs = []
for line in actlist:
# write 'comment' in the fs_mntops, entry, claiming this
line[3] = "%s,%s" % (line[3], comment)
if line[2] == "swap":
needswap = True
if line[1].startswith("/"):
dirs.append(line[1])
cc_lines.append('\t'.join(line))
fstab_lines = []
for line in util.load_file(FSTAB_PATH).splitlines():
try:
toks = WS.split(line)
if toks[3].find(comment) != -1:
continue
except:
pass
fstab_lines.append(line)
fstab_lines.extend(cc_lines)
contents = "%s\n" % ('\n'.join(fstab_lines))
util.write_file(FSTAB_PATH, contents)
if needswap:
try:
util.subp(("swapon", "-a"))
except:
util.logexc(log, "Activating swap via 'swapon -a' failed")
for d in dirs:
try:
util.ensure_dir(d)
except:
util.logexc(log, "Failed to make '%s' config-mount", d)
try:
util.subp(("mount", "-a"))
except:
util.logexc(log, "Activating mounts via 'mount -a' failed")
def devnode_for_dev_part(device, partition):
"""
Find the name of the partition. While this might seem rather
straight forward, its not since some devices are '<device><partition>'
while others are '<device>p<partition>'. For example, /dev/xvda3 on EC2
will present as /dev/xvda3p1 for the first partition since /dev/xvda3 is
a block device.
"""
if not os.path.exists(device):
return None
short_name = os.path.basename(device)
sys_path = "/sys/block/%s" % short_name
if not os.path.exists(sys_path):
LOG.debug("did not find entry for %s in /sys/block", short_name)
return None
sys_long_path = sys_path + "/" + short_name
if partition is not None:
partition = str(partition)
if partition is None:
valid_mappings = [sys_long_path + "1", sys_long_path + "p1"]
elif partition != "0":
valid_mappings = [sys_long_path + "%s" % partition,
sys_long_path + "p%s" % partition]
else:
valid_mappings = []
for cdisk in valid_mappings:
if not os.path.exists(cdisk):
continue
dev_path = "/dev/%s" % os.path.basename(cdisk)
if os.path.exists(dev_path):
return dev_path
if partition is None or partition == "0":
return device
LOG.debug("Did not fine partition %s for device %s", partition, device)
return None
| gpl-3.0 |
kabariyamilind/openMRSDEV | api/src/main/java/org/openmrs/ConceptMap.java | 3377 | /**
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs;
import org.hibernate.search.annotations.ContainedIn;
import org.hibernate.search.annotations.DocumentId;
import org.hibernate.search.annotations.IndexedEmbedded;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
/**
* The concept map object represents a mapping of Concept to ConceptSource. A concept can have 0 to
* N mappings to any and all concept sources in the database.
*/
@Root
public class ConceptMap extends BaseConceptMap implements java.io.Serializable {
public static final long serialVersionUID = 754677L;
// Fields
@DocumentId
private Integer conceptMapId;
@ContainedIn
private Concept concept;
@IndexedEmbedded(includeEmbeddedObjectId = true)
private ConceptReferenceTerm conceptReferenceTerm;
// Constructors
/** default constructor */
public ConceptMap() {
}
/** constructor with concept map id */
public ConceptMap(Integer conceptMapId) {
this.conceptMapId = conceptMapId;
}
/**
* Convenience constructor that takes the term to be mapped to and the type of the map
*
* @param conceptReferenceTerm the concept reference term to map to
* @param conceptMapType the concept map type for this concept reference term map
*/
public ConceptMap(ConceptReferenceTerm conceptReferenceTerm, ConceptMapType conceptMapType) {
this.conceptReferenceTerm = conceptReferenceTerm;
setConceptMapType(conceptMapType);
}
/**
* @see org.openmrs.BaseOpenmrsObject#toString()
*/
@Override
public String toString() {
if (conceptMapId == null) {
return "";
}
return conceptMapId.toString();
}
/**
* @return the concept
*/
@Element
public Concept getConcept() {
return concept;
}
/**
* @param concept the concept to set
*/
@Element
public void setConcept(Concept concept) {
this.concept = concept;
}
/**
* @return Returns the conceptMapId.
*/
@Attribute
public Integer getConceptMapId() {
return conceptMapId;
}
/**
* @param conceptMapId The conceptMapId to set.
*/
@Attribute
public void setConceptMapId(Integer conceptMapId) {
this.conceptMapId = conceptMapId;
}
/**
* @return the conceptReferenceTerm
* @since 1.9
*/
public ConceptReferenceTerm getConceptReferenceTerm() {
if (conceptReferenceTerm == null) {
conceptReferenceTerm = new ConceptReferenceTerm();
}
return conceptReferenceTerm;
}
/**
* @param conceptReferenceTerm the conceptReferenceTerm to set
* @since 1.9
*/
public void setConceptReferenceTerm(ConceptReferenceTerm conceptReferenceTerm) {
this.conceptReferenceTerm = conceptReferenceTerm;
}
/**
* @since 1.5
* @see org.openmrs.OpenmrsObject#getId()
*/
public Integer getId() {
return getConceptMapId();
}
/**
* @since 1.5
* @see org.openmrs.OpenmrsObject#setId(java.lang.Integer)
*/
public void setId(Integer id) {
setConceptMapId(id);
}
}
| mpl-2.0 |
SlateScience/MozillaJS | js/src/jit-test/tests/debug/Frame-eval-07.js | 945 | // test frame.eval in non-top frames
var g = newGlobal('new-compartment');
var N = g.N = 12; // must be even
assertEq(N % 2, 0);
var dbg = new Debugger(g);
var hits = 0;
dbg.onDebuggerStatement = function (frame) {
var n = frame.eval("n").return;
if (n === 0) {
for (var i = 0; i <= N; i++) {
assertEq(frame.type, 'call');
assertEq(frame.callee.name, i % 2 === 0 ? 'even' : 'odd');
assertEq(frame.eval("n").return, i);
frame = frame.older;
}
assertEq(frame.type, 'call');
assertEq(frame.callee.name, undefined);
frame = frame.older;
assertEq(frame.type, 'eval');
hits++;
}
};
var result = g.eval("(" + function () {
function odd(n) { return n > 0 && !even(n - 1); }
function even(n) { debugger; return n == 0 || !odd(n - 1); }
return even(N);
} + ")();");
assertEq(result, true);
assertEq(hits, 1);
| mpl-2.0 |
GoodERPJeff/gooderp_addons | money/models/cash_flow_statement.py | 1781 | # -*- coding: utf-8 -*-
##############################################################################
import odoo.addons.decimal_precision as dp
from odoo import fields, models, api
LINE_TYPES = [('get', u'销售收款'),
('pay', u'采购付款'),
('category', u'其他收支'),
('begin', u'科目期初'),
('end', u'科目期末'),
('lines', u'表行计算')]
class CashFlowTemplate(models.Model):
_name = 'cash.flow.template'
_order = 'sequence'
sequence = fields.Integer(u'序号')
name = fields.Char(u'项目')
line_num = fields.Char(u'行次')
line_type = fields.Selection(LINE_TYPES, u'行类型')
# for type sum
category_ids = fields.Many2many(
'core.category', string=u'收支类别', domain="[('type','in',['other_get','other_pay'])]")
# for type begin
begin_ids = fields.Many2many('finance.account', string=u'会计科目期初')
# for type end
end_ids = fields.Many2many('finance.account', string=u'会计科目期末')
# for type lines
plus_ids = fields.Many2many(
'cash.flow.template', 'c_p', 'c_id', 'p_id', string=u'+表行')
nega_ids = fields.Many2many(
'cash.flow.template', 'c_n', 'c_id', 'n_id', string=u'-表行')
class CashFlowStatement(models.Model):
_name = 'cash.flow.statement'
name = fields.Char(u'项目')
line_num = fields.Char(u'行次')
amount = fields.Float(u'本月金额', digits=dp.get_precision('Amount'))
year_amount = fields.Float(u'本年累计金额', digits=dp.get_precision('Amount'))
class CoreCategory(models.Model):
_inherit = 'core.category'
cash_flow_template_ids = fields.Many2many(
'cash.flow.template', string=u'现金流量表行')
| agpl-3.0 |
wfxiang08/sql-layer-1 | fdb-sql-layer-core/src/main/java/com/foundationdb/server/types/mcompat/mfuncs/MChr.java | 1105 | /**
* Copyright (C) 2009-2013 FoundationDB, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.foundationdb.server.types.mcompat.mfuncs;
import com.foundationdb.server.types.TScalar;
import com.foundationdb.server.types.common.funcs.Chr;
import com.foundationdb.server.types.mcompat.mtypes.MNumeric;
import com.foundationdb.server.types.mcompat.mtypes.MString;
public class MChr {
public static final TScalar INSTANCE = new Chr(MString.CHAR, MNumeric.INT);
}
| agpl-3.0 |
murugamsm/webmail-lite | adminpanel/modules/common/js/db.js | 326 | $(function () {
$('#test_btn').click(function () {
$('#isTestConnection').val('1');
this.form.submit();
});
$('#update_btn').click(function () {
PopUpWindow(AP_INDEX + '?pop&type=db&action=update');
});
$('#create_btn').click(function () {
PopUpWindow(AP_INDEX + '?pop&type=db&action=create');
});
}); | agpl-3.0 |
jasolangi/jasolangi.github.io | modules/db/src/main/java/org.openlmis.db/repository/mapper/DbMapper.java | 1384 | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2013 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses. For additional information contact info@OpenLMIS.org.
*/
package org.openlmis.db.repository.mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.Date;
/**
* This class provides utility methods to interact with DB, like getting timestamp and record count for a table
*/
@Repository
public interface DbMapper {
@Select("SELECT CURRENT_TIMESTAMP")
public Date getCurrentTimeStamp();
@Select("SELECT COUNT(*) FROM ${table}")
int getCount(@Param("table") String table);
}
| agpl-3.0 |
EaglesoftZJ/actor-platform | actor-sdk/sdk-core/runtime/runtime-shared/src/main/java/im/actor/runtime/crypto/primitives/curve25519/ge_sub.java | 2733 | package im.actor.runtime.crypto.primitives.curve25519;
// Disabling Bounds checks for speeding up calculations
/*-[
#define J2OBJC_DISABLE_ARRAY_BOUND_CHECKS 1
]-*/
public class ge_sub {
//CONVERT #include "ge.h"
/*
r = p - q
*/
public static void ge_sub(ge_p1p1 r, ge_p3 p, ge_cached q) {
int[] t0 = new int[10];
//CONVERT #include "ge_sub.h"
/* qhasm: enter ge_sub */
/* qhasm: fe X1 */
/* qhasm: fe Y1 */
/* qhasm: fe Z1 */
/* qhasm: fe Z2 */
/* qhasm: fe T1 */
/* qhasm: fe ZZ */
/* qhasm: fe YpX2 */
/* qhasm: fe YmX2 */
/* qhasm: fe T2d2 */
/* qhasm: fe X3 */
/* qhasm: fe Y3 */
/* qhasm: fe Z3 */
/* qhasm: fe T3 */
/* qhasm: fe YpX1 */
/* qhasm: fe YmX1 */
/* qhasm: fe A */
/* qhasm: fe B */
/* qhasm: fe C */
/* qhasm: fe D */
/* qhasm: YpX1 = Y1+X1 */
/* asm 1: fe_add.fe_add(>YpX1=fe#1,<Y1=fe#12,<X1=fe#11); */
/* asm 2: fe_add.fe_add(>YpX1=r.X,<Y1=p.Y,<X1=p.X); */
fe_add.fe_add(r.X, p.Y, p.X);
/* qhasm: YmX1 = Y1-X1 */
/* asm 1: fe_sub.fe_sub(>YmX1=fe#2,<Y1=fe#12,<X1=fe#11); */
/* asm 2: fe_sub.fe_sub(>YmX1=r.Y,<Y1=p.Y,<X1=p.X); */
fe_sub.fe_sub(r.Y, p.Y, p.X);
/* qhasm: A = YpX1*YmX2 */
/* asm 1: fe_mul.fe_mul(>A=fe#3,<YpX1=fe#1,<YmX2=fe#16); */
/* asm 2: fe_mul.fe_mul(>A=r.Z,<YpX1=r.X,<YmX2=q.YminusX); */
fe_mul.fe_mul(r.Z, r.X, q.YminusX);
/* qhasm: B = YmX1*YpX2 */
/* asm 1: fe_mul.fe_mul(>B=fe#2,<YmX1=fe#2,<YpX2=fe#15); */
/* asm 2: fe_mul.fe_mul(>B=r.Y,<YmX1=r.Y,<YpX2=q.YplusX); */
fe_mul.fe_mul(r.Y, r.Y, q.YplusX);
/* qhasm: C = T2d2*T1 */
/* asm 1: fe_mul.fe_mul(>C=fe#4,<T2d2=fe#18,<T1=fe#14); */
/* asm 2: fe_mul.fe_mul(>C=r.T,<T2d2=q.T2d,<T1=p.T); */
fe_mul.fe_mul(r.T, q.T2d, p.T);
/* qhasm: ZZ = Z1*Z2 */
/* asm 1: fe_mul.fe_mul(>ZZ=fe#1,<Z1=fe#13,<Z2=fe#17); */
/* asm 2: fe_mul.fe_mul(>ZZ=r.X,<Z1=p.Z,<Z2=q.Z); */
fe_mul.fe_mul(r.X, p.Z, q.Z);
/* qhasm: D = 2*ZZ */
/* asm 1: fe_add.fe_add(>D=fe#5,<ZZ=fe#1,<ZZ=fe#1); */
/* asm 2: fe_add.fe_add(>D=t0,<ZZ=r.X,<ZZ=r.X); */
fe_add.fe_add(t0, r.X, r.X);
/* qhasm: X3 = A-B */
/* asm 1: fe_sub.fe_sub(>X3=fe#1,<A=fe#3,<B=fe#2); */
/* asm 2: fe_sub.fe_sub(>X3=r.X,<A=r.Z,<B=r.Y); */
fe_sub.fe_sub(r.X, r.Z, r.Y);
/* qhasm: Y3 = A+B */
/* asm 1: fe_add.fe_add(>Y3=fe#2,<A=fe#3,<B=fe#2); */
/* asm 2: fe_add.fe_add(>Y3=r.Y,<A=r.Z,<B=r.Y); */
fe_add.fe_add(r.Y, r.Z, r.Y);
/* qhasm: Z3 = D-C */
/* asm 1: fe_sub.fe_sub(>Z3=fe#3,<D=fe#5,<C=fe#4); */
/* asm 2: fe_sub.fe_sub(>Z3=r.Z,<D=t0,<C=r.T); */
fe_sub.fe_sub(r.Z, t0, r.T);
/* qhasm: T3 = D+C */
/* asm 1: fe_add.fe_add(>T3=fe#4,<D=fe#5,<C=fe#4); */
/* asm 2: fe_add.fe_add(>T3=r.T,<D=t0,<C=r.T); */
fe_add.fe_add(r.T, t0, r.T);
/* qhasm: return */
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace-archive/ValueObjects/src/ims/core/vo/domain/PatientProcedureWebServiceVoAssembler.java | 46593 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5007.25751)
* WARNING: DO NOT MODIFY the content of this file
* Generated on 16/04/2014, 12:32
*
*/
package ims.core.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Marius Mihalec
*/
public class PatientProcedureWebServiceVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.core.vo.PatientProcedureWebServiceVo copy(ims.core.vo.PatientProcedureWebServiceVo valueObjectDest, ims.core.vo.PatientProcedureWebServiceVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_PatientProcedure(valueObjectSrc.getID_PatientProcedure());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// SiteText
valueObjectDest.setSiteText(valueObjectSrc.getSiteText());
// ProcedureOutcome
valueObjectDest.setProcedureOutcome(valueObjectSrc.getProcedureOutcome());
// PeformedBy
valueObjectDest.setPeformedBy(valueObjectSrc.getPeformedBy());
// SurgeonsGrade
valueObjectDest.setSurgeonsGrade(valueObjectSrc.getSurgeonsGrade());
// Location
valueObjectDest.setLocation(valueObjectSrc.getLocation());
// Specialty
valueObjectDest.setSpecialty(valueObjectSrc.getSpecialty());
// InfoSource
valueObjectDest.setInfoSource(valueObjectSrc.getInfoSource());
// ConfirmedStatus
valueObjectDest.setConfirmedStatus(valueObjectSrc.getConfirmedStatus());
// ConfirmedBy
valueObjectDest.setConfirmedBy(valueObjectSrc.getConfirmedBy());
// ConfirmedDateTime
valueObjectDest.setConfirmedDateTime(valueObjectSrc.getConfirmedDateTime());
// AuthoringInformation
valueObjectDest.setAuthoringInformation(valueObjectSrc.getAuthoringInformation());
// ProcSite
valueObjectDest.setProcSite(valueObjectSrc.getProcSite());
// ProcLaterality
valueObjectDest.setProcLaterality(valueObjectSrc.getProcLaterality());
// ProcDate
valueObjectDest.setProcDate(valueObjectSrc.getProcDate());
// ProcTime
valueObjectDest.setProcTime(valueObjectSrc.getProcTime());
// CancelledDate
valueObjectDest.setCancelledDate(valueObjectSrc.getCancelledDate());
// CancelledReason
valueObjectDest.setCancelledReason(valueObjectSrc.getCancelledReason());
// Notes
valueObjectDest.setNotes(valueObjectSrc.getNotes());
// HCPPresent
valueObjectDest.setHCPPresent(valueObjectSrc.getHCPPresent());
// ProcEndDate
valueObjectDest.setProcEndDate(valueObjectSrc.getProcEndDate());
// ProcEndTime
valueObjectDest.setProcEndTime(valueObjectSrc.getProcEndTime());
// ProcedureIntent
valueObjectDest.setProcedureIntent(valueObjectSrc.getProcedureIntent());
// UniqueLineRefNo
valueObjectDest.setUniqueLineRefNo(valueObjectSrc.getUniqueLineRefNo());
// PlannedProc
valueObjectDest.setPlannedProc(valueObjectSrc.getPlannedProc());
// Procedure
valueObjectDest.setProcedure(valueObjectSrc.getProcedure());
// ProcedureDescription
valueObjectDest.setProcedureDescription(valueObjectSrc.getProcedureDescription());
// ProcedureStatus
valueObjectDest.setProcedureStatus(valueObjectSrc.getProcedureStatus());
// DatePlanned
valueObjectDest.setDatePlanned(valueObjectSrc.getDatePlanned());
// ProcedureUrgency
valueObjectDest.setProcedureUrgency(valueObjectSrc.getProcedureUrgency());
return valueObjectDest;
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* This is a convenience method only.
* It is intended to be used when one called to an Assembler is made.
* If more than one call to an Assembler is made then #createPatientProcedureWebServiceVoCollectionFromPatientProcedure(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.core.clinical.domain.objects.PatientProcedure objects.
*/
public static ims.core.vo.PatientProcedureWebServiceVoCollection createPatientProcedureWebServiceVoCollectionFromPatientProcedure(java.util.Set domainObjectSet)
{
return createPatientProcedureWebServiceVoCollectionFromPatientProcedure(new DomainObjectMap(), domainObjectSet);
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectSet - Set of ims.core.clinical.domain.objects.PatientProcedure objects.
*/
public static ims.core.vo.PatientProcedureWebServiceVoCollection createPatientProcedureWebServiceVoCollectionFromPatientProcedure(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.core.vo.PatientProcedureWebServiceVoCollection voList = new ims.core.vo.PatientProcedureWebServiceVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.core.clinical.domain.objects.PatientProcedure domainObject = (ims.core.clinical.domain.objects.PatientProcedure) iterator.next();
ims.core.vo.PatientProcedureWebServiceVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param domainObjectList - List of ims.core.clinical.domain.objects.PatientProcedure objects.
*/
public static ims.core.vo.PatientProcedureWebServiceVoCollection createPatientProcedureWebServiceVoCollectionFromPatientProcedure(java.util.List domainObjectList)
{
return createPatientProcedureWebServiceVoCollectionFromPatientProcedure(new DomainObjectMap(), domainObjectList);
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectList - List of ims.core.clinical.domain.objects.PatientProcedure objects.
*/
public static ims.core.vo.PatientProcedureWebServiceVoCollection createPatientProcedureWebServiceVoCollectionFromPatientProcedure(DomainObjectMap map, java.util.List domainObjectList)
{
ims.core.vo.PatientProcedureWebServiceVoCollection voList = new ims.core.vo.PatientProcedureWebServiceVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.core.clinical.domain.objects.PatientProcedure domainObject = (ims.core.clinical.domain.objects.PatientProcedure) domainObjectList.get(i);
ims.core.vo.PatientProcedureWebServiceVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ims.core.clinical.domain.objects.PatientProcedure set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.Set extractPatientProcedureSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PatientProcedureWebServiceVoCollection voCollection)
{
return extractPatientProcedureSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractPatientProcedureSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PatientProcedureWebServiceVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectSet == null)
{
domainObjectSet = new java.util.HashSet();
}
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
ims.core.vo.PatientProcedureWebServiceVo vo = voCollection.get(i);
ims.core.clinical.domain.objects.PatientProcedure domainObject = PatientProcedureWebServiceVoAssembler.extractPatientProcedure(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = domainObjectSet.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
domainObjectSet.remove(iter.next());
}
return domainObjectSet;
}
/**
* Create the ims.core.clinical.domain.objects.PatientProcedure list from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.List extractPatientProcedureList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PatientProcedureWebServiceVoCollection voCollection)
{
return extractPatientProcedureList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractPatientProcedureList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PatientProcedureWebServiceVoCollection voCollection, java.util.List domainObjectList, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectList == null)
{
domainObjectList = new java.util.ArrayList();
}
for(int i=0; i<size; i++)
{
ims.core.vo.PatientProcedureWebServiceVo vo = voCollection.get(i);
ims.core.clinical.domain.objects.PatientProcedure domainObject = PatientProcedureWebServiceVoAssembler.extractPatientProcedure(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
int domIdx = domainObjectList.indexOf(domainObject);
if (domIdx == -1)
{
domainObjectList.add(i, domainObject);
}
else if (i != domIdx && i < domainObjectList.size())
{
Object tmp = domainObjectList.get(i);
domainObjectList.set(i, domainObjectList.get(domIdx));
domainObjectList.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=domainObjectList.size();
while (i1 > size)
{
domainObjectList.remove(i1-1);
i1=domainObjectList.size();
}
return domainObjectList;
}
/**
* Create the ValueObject from the ims.core.clinical.domain.objects.PatientProcedure object.
* @param domainObject ims.core.clinical.domain.objects.PatientProcedure
*/
public static ims.core.vo.PatientProcedureWebServiceVo create(ims.core.clinical.domain.objects.PatientProcedure domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.core.clinical.domain.objects.PatientProcedure object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.core.vo.PatientProcedureWebServiceVo create(DomainObjectMap map, ims.core.clinical.domain.objects.PatientProcedure domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.core.vo.PatientProcedureWebServiceVo valueObject = (ims.core.vo.PatientProcedureWebServiceVo) map.getValueObject(domainObject, ims.core.vo.PatientProcedureWebServiceVo.class);
if ( null == valueObject )
{
valueObject = new ims.core.vo.PatientProcedureWebServiceVo(domainObject.getId(), domainObject.getVersion());
map.addValueObject(domainObject, valueObject);
valueObject = insert(map, valueObject, domainObject);
}
return valueObject;
}
/**
* Update the ValueObject with the Domain Object.
* @param valueObject to be updated
* @param domainObject ims.core.clinical.domain.objects.PatientProcedure
*/
public static ims.core.vo.PatientProcedureWebServiceVo insert(ims.core.vo.PatientProcedureWebServiceVo valueObject, ims.core.clinical.domain.objects.PatientProcedure domainObject)
{
if (null == domainObject)
{
return valueObject;
}
DomainObjectMap map = new DomainObjectMap();
return insert(map, valueObject, domainObject);
}
/**
* Update the ValueObject with the Domain Object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param valueObject to be updated
* @param domainObject ims.core.clinical.domain.objects.PatientProcedure
*/
public static ims.core.vo.PatientProcedureWebServiceVo insert(DomainObjectMap map, ims.core.vo.PatientProcedureWebServiceVo valueObject, ims.core.clinical.domain.objects.PatientProcedure domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_PatientProcedure(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// SiteText
valueObject.setSiteText(domainObject.getSiteText());
// ProcedureOutcome
ims.domain.lookups.LookupInstance instance2 = domainObject.getProcedureOutcome();
if ( null != instance2 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance2.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance2.getImage().getImageId(), instance2.getImage().getImagePath());
}
color = instance2.getColor();
if (color != null)
color.getValue();
ims.clinical.vo.lookups.PatientProcedureOutcome voLookup2 = new ims.clinical.vo.lookups.PatientProcedureOutcome(instance2.getId(),instance2.getText(), instance2.isActive(), null, img, color);
ims.clinical.vo.lookups.PatientProcedureOutcome parentVoLookup2 = voLookup2;
ims.domain.lookups.LookupInstance parent2 = instance2.getParent();
while (parent2 != null)
{
if (parent2.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent2.getImage().getImageId(), parent2.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent2.getColor();
if (color != null)
color.getValue();
parentVoLookup2.setParent(new ims.clinical.vo.lookups.PatientProcedureOutcome(parent2.getId(),parent2.getText(), parent2.isActive(), null, img, color));
parentVoLookup2 = parentVoLookup2.getParent();
parent2 = parent2.getParent();
}
valueObject.setProcedureOutcome(voLookup2);
}
// PeformedBy
valueObject.setPeformedBy(ims.core.vo.domain.HcpLiteVoAssembler.create(map, domainObject.getPeformedBy()) );
// SurgeonsGrade
ims.domain.lookups.LookupInstance instance4 = domainObject.getSurgeonsGrade();
if ( null != instance4 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance4.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance4.getImage().getImageId(), instance4.getImage().getImagePath());
}
color = instance4.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.MedicGrade voLookup4 = new ims.core.vo.lookups.MedicGrade(instance4.getId(),instance4.getText(), instance4.isActive(), null, img, color);
ims.core.vo.lookups.MedicGrade parentVoLookup4 = voLookup4;
ims.domain.lookups.LookupInstance parent4 = instance4.getParent();
while (parent4 != null)
{
if (parent4.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent4.getImage().getImageId(), parent4.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent4.getColor();
if (color != null)
color.getValue();
parentVoLookup4.setParent(new ims.core.vo.lookups.MedicGrade(parent4.getId(),parent4.getText(), parent4.isActive(), null, img, color));
parentVoLookup4 = parentVoLookup4.getParent();
parent4 = parent4.getParent();
}
valueObject.setSurgeonsGrade(voLookup4);
}
// Location
valueObject.setLocation(domainObject.getLocation());
// Specialty
ims.domain.lookups.LookupInstance instance6 = domainObject.getSpecialty();
if ( null != instance6 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance6.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance6.getImage().getImageId(), instance6.getImage().getImagePath());
}
color = instance6.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.Specialty voLookup6 = new ims.core.vo.lookups.Specialty(instance6.getId(),instance6.getText(), instance6.isActive(), null, img, color);
ims.core.vo.lookups.Specialty parentVoLookup6 = voLookup6;
ims.domain.lookups.LookupInstance parent6 = instance6.getParent();
while (parent6 != null)
{
if (parent6.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent6.getImage().getImageId(), parent6.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent6.getColor();
if (color != null)
color.getValue();
parentVoLookup6.setParent(new ims.core.vo.lookups.Specialty(parent6.getId(),parent6.getText(), parent6.isActive(), null, img, color));
parentVoLookup6 = parentVoLookup6.getParent();
parent6 = parent6.getParent();
}
valueObject.setSpecialty(voLookup6);
}
// InfoSource
ims.domain.lookups.LookupInstance instance7 = domainObject.getInfoSource();
if ( null != instance7 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance7.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance7.getImage().getImageId(), instance7.getImage().getImagePath());
}
color = instance7.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.SourceofInformation voLookup7 = new ims.core.vo.lookups.SourceofInformation(instance7.getId(),instance7.getText(), instance7.isActive(), null, img, color);
ims.core.vo.lookups.SourceofInformation parentVoLookup7 = voLookup7;
ims.domain.lookups.LookupInstance parent7 = instance7.getParent();
while (parent7 != null)
{
if (parent7.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent7.getImage().getImageId(), parent7.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent7.getColor();
if (color != null)
color.getValue();
parentVoLookup7.setParent(new ims.core.vo.lookups.SourceofInformation(parent7.getId(),parent7.getText(), parent7.isActive(), null, img, color));
parentVoLookup7 = parentVoLookup7.getParent();
parent7 = parent7.getParent();
}
valueObject.setInfoSource(voLookup7);
}
// ConfirmedStatus
ims.domain.lookups.LookupInstance instance8 = domainObject.getConfirmedStatus();
if ( null != instance8 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance8.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance8.getImage().getImageId(), instance8.getImage().getImagePath());
}
color = instance8.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.ConfirmedStatus voLookup8 = new ims.core.vo.lookups.ConfirmedStatus(instance8.getId(),instance8.getText(), instance8.isActive(), null, img, color);
ims.core.vo.lookups.ConfirmedStatus parentVoLookup8 = voLookup8;
ims.domain.lookups.LookupInstance parent8 = instance8.getParent();
while (parent8 != null)
{
if (parent8.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent8.getImage().getImageId(), parent8.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent8.getColor();
if (color != null)
color.getValue();
parentVoLookup8.setParent(new ims.core.vo.lookups.ConfirmedStatus(parent8.getId(),parent8.getText(), parent8.isActive(), null, img, color));
parentVoLookup8 = parentVoLookup8.getParent();
parent8 = parent8.getParent();
}
valueObject.setConfirmedStatus(voLookup8);
}
// ConfirmedBy
valueObject.setConfirmedBy(ims.core.vo.domain.HcpLiteVoAssembler.create(map, domainObject.getConfirmedBy()) );
// ConfirmedDateTime
java.util.Date ConfirmedDateTime = domainObject.getConfirmedDateTime();
if ( null != ConfirmedDateTime )
{
valueObject.setConfirmedDateTime(new ims.framework.utils.DateTime(ConfirmedDateTime) );
}
// AuthoringInformation
valueObject.setAuthoringInformation(ims.core.vo.domain.AuthoringInformationVoAssembler.create(map, domainObject.getAuthoringInformation()) );
// ProcSite
ims.domain.lookups.LookupInstance instance12 = domainObject.getProcSite();
if ( null != instance12 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance12.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance12.getImage().getImageId(), instance12.getImage().getImagePath());
}
color = instance12.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.MedicalHistoryProcedureSite voLookup12 = new ims.core.vo.lookups.MedicalHistoryProcedureSite(instance12.getId(),instance12.getText(), instance12.isActive(), null, img, color);
ims.core.vo.lookups.MedicalHistoryProcedureSite parentVoLookup12 = voLookup12;
ims.domain.lookups.LookupInstance parent12 = instance12.getParent();
while (parent12 != null)
{
if (parent12.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent12.getImage().getImageId(), parent12.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent12.getColor();
if (color != null)
color.getValue();
parentVoLookup12.setParent(new ims.core.vo.lookups.MedicalHistoryProcedureSite(parent12.getId(),parent12.getText(), parent12.isActive(), null, img, color));
parentVoLookup12 = parentVoLookup12.getParent();
parent12 = parent12.getParent();
}
valueObject.setProcSite(voLookup12);
}
// ProcLaterality
ims.domain.lookups.LookupInstance instance13 = domainObject.getProcLaterality();
if ( null != instance13 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance13.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance13.getImage().getImageId(), instance13.getImage().getImagePath());
}
color = instance13.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.LateralityLRB voLookup13 = new ims.core.vo.lookups.LateralityLRB(instance13.getId(),instance13.getText(), instance13.isActive(), null, img, color);
ims.core.vo.lookups.LateralityLRB parentVoLookup13 = voLookup13;
ims.domain.lookups.LookupInstance parent13 = instance13.getParent();
while (parent13 != null)
{
if (parent13.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent13.getImage().getImageId(), parent13.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent13.getColor();
if (color != null)
color.getValue();
parentVoLookup13.setParent(new ims.core.vo.lookups.LateralityLRB(parent13.getId(),parent13.getText(), parent13.isActive(), null, img, color));
parentVoLookup13 = parentVoLookup13.getParent();
parent13 = parent13.getParent();
}
valueObject.setProcLaterality(voLookup13);
}
// ProcDate
Integer ProcDate = domainObject.getProcDate();
if ( null != ProcDate )
{
valueObject.setProcDate(new ims.framework.utils.PartialDate(ProcDate) );
}
// ProcTime
String ProcTime = domainObject.getProcTime();
if ( null != ProcTime )
{
valueObject.setProcTime(new ims.framework.utils.Time(ProcTime) );
}
// CancelledDate
java.util.Date CancelledDate = domainObject.getCancelledDate();
if ( null != CancelledDate )
{
valueObject.setCancelledDate(new ims.framework.utils.Date(CancelledDate) );
}
// CancelledReason
valueObject.setCancelledReason(domainObject.getCancelledReason());
// Notes
valueObject.setNotes(domainObject.getNotes());
// HCPPresent
valueObject.setHCPPresent(ims.core.vo.domain.HcpLiteVoAssembler.createHcpLiteVoCollectionFromHcp(map, domainObject.getHCPPresent()) );
// ProcEndDate
Integer ProcEndDate = domainObject.getProcEndDate();
if ( null != ProcEndDate )
{
valueObject.setProcEndDate(new ims.framework.utils.PartialDate(ProcEndDate) );
}
// ProcEndTime
String ProcEndTime = domainObject.getProcEndTime();
if ( null != ProcEndTime )
{
valueObject.setProcEndTime(new ims.framework.utils.Time(ProcEndTime) );
}
// ProcedureIntent
ims.domain.lookups.LookupInstance instance22 = domainObject.getProcedureIntent();
if ( null != instance22 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance22.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance22.getImage().getImageId(), instance22.getImage().getImagePath());
}
color = instance22.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.ProcedureIntent voLookup22 = new ims.core.vo.lookups.ProcedureIntent(instance22.getId(),instance22.getText(), instance22.isActive(), null, img, color);
ims.core.vo.lookups.ProcedureIntent parentVoLookup22 = voLookup22;
ims.domain.lookups.LookupInstance parent22 = instance22.getParent();
while (parent22 != null)
{
if (parent22.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent22.getImage().getImageId(), parent22.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent22.getColor();
if (color != null)
color.getValue();
parentVoLookup22.setParent(new ims.core.vo.lookups.ProcedureIntent(parent22.getId(),parent22.getText(), parent22.isActive(), null, img, color));
parentVoLookup22 = parentVoLookup22.getParent();
parent22 = parent22.getParent();
}
valueObject.setProcedureIntent(voLookup22);
}
// UniqueLineRefNo
valueObject.setUniqueLineRefNo(domainObject.getUniqueLineRefNo());
// PlannedProc
if (domainObject.getPlannedProc() != null)
{
if(domainObject.getPlannedProc() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already.
{
HibernateProxy p = (HibernateProxy) domainObject.getPlannedProc();
int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString());
valueObject.setPlannedProc(new ims.core.clinical.vo.PatientProcedureRefVo(id, -1));
}
else
{
valueObject.setPlannedProc(new ims.core.clinical.vo.PatientProcedureRefVo(domainObject.getPlannedProc().getId(), domainObject.getPlannedProc().getVersion()));
}
}
// Procedure
valueObject.setProcedure(ims.core.vo.domain.ProcedureLiteVoAssembler.create(map, domainObject.getProcedure()) );
// ProcedureDescription
valueObject.setProcedureDescription(domainObject.getProcedureDescription());
// ProcedureStatus
ims.domain.lookups.LookupInstance instance27 = domainObject.getProcedureStatus();
if ( null != instance27 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance27.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance27.getImage().getImageId(), instance27.getImage().getImagePath());
}
color = instance27.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.PatientProcedureStatus voLookup27 = new ims.core.vo.lookups.PatientProcedureStatus(instance27.getId(),instance27.getText(), instance27.isActive(), null, img, color);
ims.core.vo.lookups.PatientProcedureStatus parentVoLookup27 = voLookup27;
ims.domain.lookups.LookupInstance parent27 = instance27.getParent();
while (parent27 != null)
{
if (parent27.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent27.getImage().getImageId(), parent27.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent27.getColor();
if (color != null)
color.getValue();
parentVoLookup27.setParent(new ims.core.vo.lookups.PatientProcedureStatus(parent27.getId(),parent27.getText(), parent27.isActive(), null, img, color));
parentVoLookup27 = parentVoLookup27.getParent();
parent27 = parent27.getParent();
}
valueObject.setProcedureStatus(voLookup27);
}
// DatePlanned
Integer DatePlanned = domainObject.getDatePlanned();
if ( null != DatePlanned )
{
valueObject.setDatePlanned(new ims.framework.utils.PartialDate(DatePlanned) );
}
// ProcedureUrgency
ims.domain.lookups.LookupInstance instance29 = domainObject.getProcedureUrgency();
if ( null != instance29 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance29.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance29.getImage().getImageId(), instance29.getImage().getImagePath());
}
color = instance29.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.ProcedureUrgency voLookup29 = new ims.core.vo.lookups.ProcedureUrgency(instance29.getId(),instance29.getText(), instance29.isActive(), null, img, color);
ims.core.vo.lookups.ProcedureUrgency parentVoLookup29 = voLookup29;
ims.domain.lookups.LookupInstance parent29 = instance29.getParent();
while (parent29 != null)
{
if (parent29.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent29.getImage().getImageId(), parent29.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent29.getColor();
if (color != null)
color.getValue();
parentVoLookup29.setParent(new ims.core.vo.lookups.ProcedureUrgency(parent29.getId(),parent29.getText(), parent29.isActive(), null, img, color));
parentVoLookup29 = parentVoLookup29.getParent();
parent29 = parent29.getParent();
}
valueObject.setProcedureUrgency(voLookup29);
}
return valueObject;
}
/**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/
public static ims.core.clinical.domain.objects.PatientProcedure extractPatientProcedure(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PatientProcedureWebServiceVo valueObject)
{
return extractPatientProcedure(domainFactory, valueObject, new HashMap());
}
public static ims.core.clinical.domain.objects.PatientProcedure extractPatientProcedure(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PatientProcedureWebServiceVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_PatientProcedure();
ims.core.clinical.domain.objects.PatientProcedure domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.core.clinical.domain.objects.PatientProcedure)domMap.get(valueObject);
}
// ims.core.vo.PatientProcedureWebServiceVo ID_PatientProcedure field is unknown
domainObject = new ims.core.clinical.domain.objects.PatientProcedure();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_PatientProcedure());
if (domMap.get(key) != null)
{
return (ims.core.clinical.domain.objects.PatientProcedure)domMap.get(key);
}
domainObject = (ims.core.clinical.domain.objects.PatientProcedure) domainFactory.getDomainObject(ims.core.clinical.domain.objects.PatientProcedure.class, id );
//TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up.
if (domainObject == null)
return null;
domMap.put(key, domainObject);
}
domainObject.setVersion(valueObject.getVersion_PatientProcedure());
//This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly
//Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least.
if (valueObject.getSiteText() != null && valueObject.getSiteText().equals(""))
{
valueObject.setSiteText(null);
}
domainObject.setSiteText(valueObject.getSiteText());
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value2 = null;
if ( null != valueObject.getProcedureOutcome() )
{
value2 =
domainFactory.getLookupInstance(valueObject.getProcedureOutcome().getID());
}
domainObject.setProcedureOutcome(value2);
domainObject.setPeformedBy(ims.core.vo.domain.HcpLiteVoAssembler.extractHcp(domainFactory, valueObject.getPeformedBy(), domMap));
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value4 = null;
if ( null != valueObject.getSurgeonsGrade() )
{
value4 =
domainFactory.getLookupInstance(valueObject.getSurgeonsGrade().getID());
}
domainObject.setSurgeonsGrade(value4);
//This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly
//Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least.
if (valueObject.getLocation() != null && valueObject.getLocation().equals(""))
{
valueObject.setLocation(null);
}
domainObject.setLocation(valueObject.getLocation());
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value6 = null;
if ( null != valueObject.getSpecialty() )
{
value6 =
domainFactory.getLookupInstance(valueObject.getSpecialty().getID());
}
domainObject.setSpecialty(value6);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value7 = null;
if ( null != valueObject.getInfoSource() )
{
value7 =
domainFactory.getLookupInstance(valueObject.getInfoSource().getID());
}
domainObject.setInfoSource(value7);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value8 = null;
if ( null != valueObject.getConfirmedStatus() )
{
value8 =
domainFactory.getLookupInstance(valueObject.getConfirmedStatus().getID());
}
domainObject.setConfirmedStatus(value8);
domainObject.setConfirmedBy(ims.core.vo.domain.HcpLiteVoAssembler.extractHcp(domainFactory, valueObject.getConfirmedBy(), domMap));
ims.framework.utils.DateTime dateTime10 = valueObject.getConfirmedDateTime();
java.util.Date value10 = null;
if ( dateTime10 != null )
{
value10 = dateTime10.getJavaDate();
}
domainObject.setConfirmedDateTime(value10);
domainObject.setAuthoringInformation(ims.core.vo.domain.AuthoringInformationVoAssembler.extractAuthoringInformation(domainFactory, valueObject.getAuthoringInformation(), domMap));
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value12 = null;
if ( null != valueObject.getProcSite() )
{
value12 =
domainFactory.getLookupInstance(valueObject.getProcSite().getID());
}
domainObject.setProcSite(value12);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value13 = null;
if ( null != valueObject.getProcLaterality() )
{
value13 =
domainFactory.getLookupInstance(valueObject.getProcLaterality().getID());
}
domainObject.setProcLaterality(value13);
ims.framework.utils.PartialDate ProcDate = valueObject.getProcDate();
Integer value14 = null;
if ( null != ProcDate )
{
value14 = ProcDate.toInteger();
}
domainObject.setProcDate(value14);
ims.framework.utils.Time time15 = valueObject.getProcTime();
String value15 = null;
if ( time15 != null )
{
value15 = time15.toString();
}
domainObject.setProcTime(value15);
java.util.Date value16 = null;
ims.framework.utils.Date date16 = valueObject.getCancelledDate();
if ( date16 != null )
{
value16 = date16.getDate();
}
domainObject.setCancelledDate(value16);
//This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly
//Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least.
if (valueObject.getCancelledReason() != null && valueObject.getCancelledReason().equals(""))
{
valueObject.setCancelledReason(null);
}
domainObject.setCancelledReason(valueObject.getCancelledReason());
//This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly
//Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least.
if (valueObject.getNotes() != null && valueObject.getNotes().equals(""))
{
valueObject.setNotes(null);
}
domainObject.setNotes(valueObject.getNotes());
// SaveAsRefVO treated as RefValueObject
ims.core.resource.people.vo.HcpRefVoCollection refCollection19 = new ims.core.resource.people.vo.HcpRefVoCollection();
if (valueObject.getHCPPresent() != null)
{
for (int i19=0; i19<valueObject.getHCPPresent().size(); i19++)
{
ims.core.resource.people.vo.HcpRefVo ref19 = (ims.core.resource.people.vo.HcpRefVo)valueObject.getHCPPresent().get(i19);
refCollection19.add(ref19);
}
}
int size19 = (null == refCollection19) ? 0 : refCollection19.size();
java.util.Set domainHCPPresent19 = domainObject.getHCPPresent();
if (domainHCPPresent19 == null)
{
domainHCPPresent19 = new java.util.HashSet();
}
java.util.Set newSet19 = new java.util.HashSet();
for(int i=0; i<size19; i++)
{
ims.core.resource.people.vo.HcpRefVo vo = refCollection19.get(i);
ims.core.resource.people.domain.objects.Hcp dom = null;
if ( null != vo )
{
if (vo.getBoId() == null)
{
if (domMap.get(vo) != null)
{
dom = (ims.core.resource.people.domain.objects.Hcp)domMap.get(vo);
}
}
else
{
dom = (ims.core.resource.people.domain.objects.Hcp)domainFactory.getDomainObject( ims.core.resource.people.domain.objects.Hcp.class, vo.getBoId());
}
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainHCPPresent19.contains(dom))
{
domainHCPPresent19.add(dom);
}
newSet19.add(dom);
}
java.util.Set removedSet19 = new java.util.HashSet();
java.util.Iterator iter19 = domainHCPPresent19.iterator();
//Find out which objects need to be removed
while (iter19.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter19.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet19.contains(o))
{
removedSet19.add(o);
}
}
iter19 = removedSet19.iterator();
//Remove the unwanted objects
while (iter19.hasNext())
{
domainHCPPresent19.remove(iter19.next());
}
domainObject.setHCPPresent(domainHCPPresent19);
ims.framework.utils.PartialDate ProcEndDate = valueObject.getProcEndDate();
Integer value20 = null;
if ( null != ProcEndDate )
{
value20 = ProcEndDate.toInteger();
}
domainObject.setProcEndDate(value20);
ims.framework.utils.Time time21 = valueObject.getProcEndTime();
String value21 = null;
if ( time21 != null )
{
value21 = time21.toString();
}
domainObject.setProcEndTime(value21);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value22 = null;
if ( null != valueObject.getProcedureIntent() )
{
value22 =
domainFactory.getLookupInstance(valueObject.getProcedureIntent().getID());
}
domainObject.setProcedureIntent(value22);
//This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly
//Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least.
if (valueObject.getUniqueLineRefNo() != null && valueObject.getUniqueLineRefNo().equals(""))
{
valueObject.setUniqueLineRefNo(null);
}
domainObject.setUniqueLineRefNo(valueObject.getUniqueLineRefNo());
ims.core.clinical.domain.objects.PatientProcedure value24 = null;
if ( null != valueObject.getPlannedProc() )
{
if (valueObject.getPlannedProc().getBoId() == null)
{
if (domMap.get(valueObject.getPlannedProc()) != null)
{
value24 = (ims.core.clinical.domain.objects.PatientProcedure)domMap.get(valueObject.getPlannedProc());
}
}
else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field
{
value24 = domainObject.getPlannedProc();
}
else
{
value24 = (ims.core.clinical.domain.objects.PatientProcedure)domainFactory.getDomainObject(ims.core.clinical.domain.objects.PatientProcedure.class, valueObject.getPlannedProc().getBoId());
}
}
domainObject.setPlannedProc(value24);
// SaveAsRefVO - treated as a refVo in extract methods
ims.core.clinical.domain.objects.Procedure value25 = null;
if ( null != valueObject.getProcedure() )
{
if (valueObject.getProcedure().getBoId() == null)
{
if (domMap.get(valueObject.getProcedure()) != null)
{
value25 = (ims.core.clinical.domain.objects.Procedure)domMap.get(valueObject.getProcedure());
}
}
else
{
value25 = (ims.core.clinical.domain.objects.Procedure)domainFactory.getDomainObject(ims.core.clinical.domain.objects.Procedure.class, valueObject.getProcedure().getBoId());
}
}
domainObject.setProcedure(value25);
//This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly
//Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least.
if (valueObject.getProcedureDescription() != null && valueObject.getProcedureDescription().equals(""))
{
valueObject.setProcedureDescription(null);
}
domainObject.setProcedureDescription(valueObject.getProcedureDescription());
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value27 = null;
if ( null != valueObject.getProcedureStatus() )
{
value27 =
domainFactory.getLookupInstance(valueObject.getProcedureStatus().getID());
}
domainObject.setProcedureStatus(value27);
ims.framework.utils.PartialDate DatePlanned = valueObject.getDatePlanned();
Integer value28 = null;
if ( null != DatePlanned )
{
value28 = DatePlanned.toInteger();
}
domainObject.setDatePlanned(value28);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value29 = null;
if ( null != valueObject.getProcedureUrgency() )
{
value29 =
domainFactory.getLookupInstance(valueObject.getProcedureUrgency().getID());
}
domainObject.setProcedureUrgency(value29);
return domainObject;
}
}
| agpl-3.0 |
artsmorgan/crmtecnosagot | app/protected/modules/zurmo/views/ActionBarAndZeroModelsYetView.php | 2639 | <?php
/*********************************************************************************
* Zurmo is a customer relationship management program developed by
* Zurmo, Inc. Copyright (C) 2015 Zurmo Inc.
*
* Zurmo is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* Zurmo is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive
* Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com.
*
* The interactive user interfaces in original and modified versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the Zurmo
* logo and Zurmo copyright notice. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display the words
* "Copyright Zurmo Inc. 2015. All rights reserved".
********************************************************************************/
/**
* Renders an action bar and a zero models yet view.
*/
class ActionBarAndZeroModelsYetView extends GridView
{
public function __construct(ActionBarForSearchAndListView $actionBarView, ZeroModelsYetView $zeroModelsYetView)
{
parent::__construct(2, 1);
$this->setView($actionBarView, 0, 0);
$this->setView($zeroModelsYetView, 1, 0);
}
public function isUniqueToAPage()
{
return true;
}
}
?> | agpl-3.0 |
geoiq/digitalgazette | db/migrate/20091105213521_add_require_user_full_info_to_sites.rb | 216 | class AddRequireUserFullInfoToSites < ActiveRecord::Migration
def self.up
add_column :sites, :require_user_full_info, :boolean
end
def self.down
remove_column :sites, :require_user_full_info
end
end
| agpl-3.0 |
rossjones/openMAXIMS | Source Library/openmaxims_workspace/SpinalInjuries/src/ims/spinalinjuries/forms/opdmedicalnotes/BaseLogic.java | 6808 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// 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.spinalinjuries.forms.opdmedicalnotes;
public abstract class BaseLogic extends Handlers
{
public final Class getDomainInterface() throws ClassNotFoundException
{
return ims.spinalinjuries.domain.OPDMedicalNotes.class;
}
public final void setContext(ims.framework.UIEngine engine, GenForm form, ims.spinalinjuries.domain.OPDMedicalNotes domain)
{
setContext(engine, form);
this.domain = domain;
}
protected final void oncmbNxtOpdUnitValueSet(Object value)
{
java.util.ArrayList listOfValues = this.form.cmbNxtOpdUnit().getValues();
if(value == null)
{
if(listOfValues != null && listOfValues.size() > 0)
{
for(int x = 0; x < listOfValues.size(); x++)
{
ims.core.vo.lookups.TimeWeeksMonthsYears existingInstance = (ims.core.vo.lookups.TimeWeeksMonthsYears)listOfValues.get(x);
if(!existingInstance.isActive())
{
bindcmbNxtOpdUnitLookup();
return;
}
}
}
}
else if(value instanceof ims.core.vo.lookups.TimeWeeksMonthsYears)
{
ims.core.vo.lookups.TimeWeeksMonthsYears instance = (ims.core.vo.lookups.TimeWeeksMonthsYears)value;
if(listOfValues != null)
{
if(listOfValues.size() == 0)
bindcmbNxtOpdUnitLookup();
for(int x = 0; x < listOfValues.size(); x++)
{
ims.core.vo.lookups.TimeWeeksMonthsYears existingInstance = (ims.core.vo.lookups.TimeWeeksMonthsYears)listOfValues.get(x);
if(existingInstance.equals(instance))
return;
}
}
this.form.cmbNxtOpdUnit().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor());
}
}
protected final void bindcmbNxtOpdUnitLookup()
{
this.form.cmbNxtOpdUnit().clear();
ims.core.vo.lookups.TimeWeeksMonthsYearsCollection lookupCollection = ims.core.vo.lookups.LookupHelper.getTimeWeeksMonthsYears(this.domain.getLookupService());
for(int x = 0; x < lookupCollection.size(); x++)
{
this.form.cmbNxtOpdUnit().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor());
}
}
protected final void setcmbNxtOpdUnitLookupValue(int id)
{
ims.core.vo.lookups.TimeWeeksMonthsYears instance = ims.core.vo.lookups.LookupHelper.getTimeWeeksMonthsYearsInstance(this.domain.getLookupService(), id);
if(instance != null)
this.form.cmbNxtOpdUnit().setValue(instance);
}
protected final void defaultcmbNxtOpdUnitLookupValue()
{
this.form.cmbNxtOpdUnit().setValue((ims.core.vo.lookups.TimeWeeksMonthsYears)domain.getLookupService().getDefaultInstance(ims.core.vo.lookups.TimeWeeksMonthsYears.class, engine.getFormName().getID(), ims.core.vo.lookups.TimeWeeksMonthsYears.TYPE_ID));
}
protected final void oncmbAutoDysreflexiaValueSet(Object value)
{
java.util.ArrayList listOfValues = this.form.cmbAutoDysreflexia().getValues();
if(value == null)
{
if(listOfValues != null && listOfValues.size() > 0)
{
for(int x = 0; x < listOfValues.size(); x++)
{
ims.core.vo.lookups.AutonomicDysreflexia existingInstance = (ims.core.vo.lookups.AutonomicDysreflexia)listOfValues.get(x);
if(!existingInstance.isActive())
{
bindcmbAutoDysreflexiaLookup();
return;
}
}
}
}
else if(value instanceof ims.core.vo.lookups.AutonomicDysreflexia)
{
ims.core.vo.lookups.AutonomicDysreflexia instance = (ims.core.vo.lookups.AutonomicDysreflexia)value;
if(listOfValues != null)
{
if(listOfValues.size() == 0)
bindcmbAutoDysreflexiaLookup();
for(int x = 0; x < listOfValues.size(); x++)
{
ims.core.vo.lookups.AutonomicDysreflexia existingInstance = (ims.core.vo.lookups.AutonomicDysreflexia)listOfValues.get(x);
if(existingInstance.equals(instance))
return;
}
}
this.form.cmbAutoDysreflexia().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor());
}
}
protected final void bindcmbAutoDysreflexiaLookup()
{
this.form.cmbAutoDysreflexia().clear();
ims.core.vo.lookups.AutonomicDysreflexiaCollection lookupCollection = ims.core.vo.lookups.LookupHelper.getAutonomicDysreflexia(this.domain.getLookupService());
for(int x = 0; x < lookupCollection.size(); x++)
{
this.form.cmbAutoDysreflexia().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor());
}
}
protected final void setcmbAutoDysreflexiaLookupValue(int id)
{
ims.core.vo.lookups.AutonomicDysreflexia instance = ims.core.vo.lookups.LookupHelper.getAutonomicDysreflexiaInstance(this.domain.getLookupService(), id);
if(instance != null)
this.form.cmbAutoDysreflexia().setValue(instance);
}
protected final void defaultcmbAutoDysreflexiaLookupValue()
{
this.form.cmbAutoDysreflexia().setValue((ims.core.vo.lookups.AutonomicDysreflexia)domain.getLookupService().getDefaultInstance(ims.core.vo.lookups.AutonomicDysreflexia.class, engine.getFormName().getID(), ims.core.vo.lookups.AutonomicDysreflexia.TYPE_ID));
}
public final void free()
{
super.free();
domain = null;
}
protected ims.spinalinjuries.domain.OPDMedicalNotes domain;
}
| agpl-3.0 |
admpub/nging | vendor/github.com/tklauser/go-sysconf/zsysconf_defs_dragonfly.go | 7458 | // Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs sysconf_defs_dragonfly.go
//go:build dragonfly
// +build dragonfly
package sysconf
const (
SC_AIO_LISTIO_MAX = 0x2a
SC_AIO_MAX = 0x2b
SC_AIO_PRIO_DELTA_MAX = 0x2c
SC_ARG_MAX = 0x1
SC_ATEXIT_MAX = 0x6b
SC_BC_BASE_MAX = 0x9
SC_BC_DIM_MAX = 0xa
SC_BC_SCALE_MAX = 0xb
SC_BC_STRING_MAX = 0xc
SC_CHILD_MAX = 0x2
SC_CLK_TCK = 0x3
SC_COLL_WEIGHTS_MAX = 0xd
SC_DELAYTIMER_MAX = 0x2d
SC_EXPR_NEST_MAX = 0xe
SC_GETGR_R_SIZE_MAX = 0x46
SC_GETPW_R_SIZE_MAX = 0x47
SC_HOST_NAME_MAX = 0x48
SC_IOV_MAX = 0x38
SC_LINE_MAX = 0xf
SC_LOGIN_NAME_MAX = 0x49
SC_MQ_OPEN_MAX = 0x2e
SC_MQ_PRIO_MAX = 0x4b
SC_NGROUPS_MAX = 0x4
SC_OPEN_MAX = 0x5
SC_PAGE_SIZE = 0x2f
SC_PAGESIZE = 0x2f
SC_RE_DUP_MAX = 0x10
SC_RTSIG_MAX = 0x30
SC_SEM_NSEMS_MAX = 0x31
SC_SEM_VALUE_MAX = 0x32
SC_SIGQUEUE_MAX = 0x33
SC_STREAM_MAX = 0x1a
SC_SYMLOOP_MAX = 0x78
SC_THREAD_DESTRUCTOR_ITERATIONS = 0x55
SC_THREAD_KEYS_MAX = 0x56
SC_THREAD_STACK_MIN = 0x5d
SC_THREAD_THREADS_MAX = 0x5e
SC_TIMER_MAX = 0x34
SC_TTY_NAME_MAX = 0x65
SC_TZNAME_MAX = 0x1b
SC_ADVISORY_INFO = 0x41
SC_ASYNCHRONOUS_IO = 0x1c
SC_BARRIERS = 0x42
SC_CLOCK_SELECTION = 0x43
SC_CPUTIME = 0x44
SC_FSYNC = 0x26
SC_IPV6 = 0x76
SC_JOB_CONTROL = 0x6
SC_MAPPED_FILES = 0x1d
SC_MEMLOCK = 0x1e
SC_MEMLOCK_RANGE = 0x1f
SC_MEMORY_PROTECTION = 0x20
SC_MESSAGE_PASSING = 0x21
SC_MONOTONIC_CLOCK = 0x4a
SC_PRIORITIZED_IO = 0x22
SC_PRIORITY_SCHEDULING = 0x23
SC_RAW_SOCKETS = 0x77
SC_READER_WRITER_LOCKS = 0x4c
SC_REALTIME_SIGNALS = 0x24
SC_REGEXP = 0x4d
SC_SAVED_IDS = 0x7
SC_SEMAPHORES = 0x25
SC_SHARED_MEMORY_OBJECTS = 0x27
SC_SHELL = 0x4e
SC_SPAWN = 0x4f
SC_SPIN_LOCKS = 0x50
SC_SPORADIC_SERVER = 0x51
SC_SYNCHRONIZED_IO = 0x28
SC_THREAD_ATTR_STACKADDR = 0x52
SC_THREAD_ATTR_STACKSIZE = 0x53
SC_THREAD_CPUTIME = 0x54
SC_THREAD_PRIO_INHERIT = 0x57
SC_THREAD_PRIO_PROTECT = 0x58
SC_THREAD_PRIORITY_SCHEDULING = 0x59
SC_THREAD_PROCESS_SHARED = 0x5a
SC_THREAD_SAFE_FUNCTIONS = 0x5b
SC_THREAD_SPORADIC_SERVER = 0x5c
SC_THREADS = 0x60
SC_TIMEOUTS = 0x5f
SC_TIMERS = 0x29
SC_TRACE = 0x61
SC_TRACE_EVENT_FILTER = 0x62
SC_TRACE_INHERIT = 0x63
SC_TRACE_LOG = 0x64
SC_TYPED_MEMORY_OBJECTS = 0x66
SC_VERSION = 0x8
SC_V6_ILP32_OFF32 = 0x67
SC_V6_ILP32_OFFBIG = 0x68
SC_V6_LP64_OFF64 = 0x69
SC_V6_LPBIG_OFFBIG = 0x6a
SC_2_C_BIND = 0x12
SC_2_C_DEV = 0x13
SC_2_CHAR_TERM = 0x14
SC_2_FORT_DEV = 0x15
SC_2_FORT_RUN = 0x16
SC_2_LOCALEDEF = 0x17
SC_2_PBS = 0x3b
SC_2_PBS_ACCOUNTING = 0x3c
SC_2_PBS_CHECKPOINT = 0x3d
SC_2_PBS_LOCATE = 0x3e
SC_2_PBS_MESSAGE = 0x3f
SC_2_PBS_TRACK = 0x40
SC_2_SW_DEV = 0x18
SC_2_UPE = 0x19
SC_2_VERSION = 0x11
SC_XOPEN_CRYPT = 0x6c
SC_XOPEN_ENH_I18N = 0x6d
SC_XOPEN_REALTIME = 0x6f
SC_XOPEN_REALTIME_THREADS = 0x70
SC_XOPEN_SHM = 0x71
SC_XOPEN_STREAMS = 0x72
SC_XOPEN_UNIX = 0x73
SC_XOPEN_VERSION = 0x74
SC_XOPEN_XCU_VERSION = 0x75
SC_PHYS_PAGES = 0x79
SC_NPROCESSORS_CONF = 0x39
SC_NPROCESSORS_ONLN = 0x3a
)
const (
_BC_BASE_MAX = 0x63
_BC_DIM_MAX = 0x800
_BC_SCALE_MAX = 0x63
_BC_STRING_MAX = 0x3e8
_COLL_WEIGHTS_MAX = 0xa
_EXPR_NEST_MAX = 0x20
_LINE_MAX = 0x800
_RE_DUP_MAX = 0xff
_CLK_TCK = 0x80
_MAXHOSTNAMELEN = 0x100
_MAXLOGNAME = 0x11
_MAXSYMLINKS = 0x20
_ATEXIT_SIZE = 0x20
_POSIX_ADVISORY_INFO = -0x1
_POSIX_ARG_MAX = 0x1000
_POSIX_ASYNCHRONOUS_IO = 0x0
_POSIX_BARRIERS = 0x30db0
_POSIX_CHILD_MAX = 0x19
_POSIX_CLOCK_SELECTION = -0x1
_POSIX_CPUTIME = 0x30db0
_POSIX_FSYNC = 0x30db0
_POSIX_IPV6 = 0x0
_POSIX_JOB_CONTROL = 0x1
_POSIX_MAPPED_FILES = 0x30db0
_POSIX_MEMLOCK = -0x1
_POSIX_MEMLOCK_RANGE = 0x30db0
_POSIX_MEMORY_PROTECTION = 0x30db0
_POSIX_MESSAGE_PASSING = 0x30db0
_POSIX_MONOTONIC_CLOCK = 0x30db0
_POSIX_PRIORITIZED_IO = -0x1
_POSIX_PRIORITY_SCHEDULING = 0x30db0
_POSIX_RAW_SOCKETS = 0x30db0
_POSIX_READER_WRITER_LOCKS = 0x30db0
_POSIX_REALTIME_SIGNALS = 0x30db0
_POSIX_REGEXP = 0x1
_POSIX_SEM_VALUE_MAX = 0x7fff
_POSIX_SEMAPHORES = 0x30db0
_POSIX_SHARED_MEMORY_OBJECTS = 0x30db0
_POSIX_SHELL = 0x1
_POSIX_SPAWN = 0x30db0
_POSIX_SPIN_LOCKS = 0x30db0
_POSIX_SPORADIC_SERVER = -0x1
_POSIX_SYNCHRONIZED_IO = -0x1
_POSIX_THREAD_ATTR_STACKADDR = 0x30db0
_POSIX_THREAD_ATTR_STACKSIZE = 0x30db0
_POSIX_THREAD_CPUTIME = 0x30db0
_POSIX_THREAD_PRIO_INHERIT = 0x30db0
_POSIX_THREAD_PRIO_PROTECT = 0x30db0
_POSIX_THREAD_PRIORITY_SCHEDULING = 0x30db0
_POSIX_THREAD_PROCESS_SHARED = -0x1
_POSIX_THREAD_SAFE_FUNCTIONS = -0x1
_POSIX_THREAD_SPORADIC_SERVER = -0x1
_POSIX_THREADS = 0x30db0
_POSIX_TIMEOUTS = 0x30db0
_POSIX_TIMERS = 0x30db0
_POSIX_TRACE = -0x1
_POSIX_TYPED_MEMORY_OBJECTS = -0x1
_POSIX_VERSION = 0x30db0
_V6_ILP32_OFF32 = -0x1
_V6_ILP32_OFFBIG = 0x0
_V6_LP64_OFF64 = 0x0
_V6_LPBIG_OFFBIG = -0x1
_POSIX2_C_BIND = 0x31069
_POSIX2_C_DEV = 0x31069
_POSIX2_CHAR_TERM = 0x1
_POSIX2_LOCALEDEF = 0x31069
_POSIX2_PBS = -0x1
_POSIX2_SW_DEV = 0x31069
_POSIX2_UPE = 0x31069
_POSIX2_VERSION = 0x30a2c
_XOPEN_CRYPT = -0x1
_XOPEN_ENH_I18N = -0x1
_XOPEN_REALTIME = -0x1
_XOPEN_REALTIME_THREADS = -0x1
_XOPEN_SHM = 0x1
_XOPEN_UNIX = -0x1
_PTHREAD_DESTRUCTOR_ITERATIONS = 0x4
_PTHREAD_KEYS_MAX = 0x100
_PTHREAD_STACK_MIN = 0x4000
)
const (
_PC_NAME_MAX = 0x4
_PATH_DEV = "/dev/"
_PATH_ZONEINFO = "/usr/share/zoneinfo"
)
| agpl-3.0 |
JC5/firefly-iii | resources/lang/nb_NO/email.php | 8254 | <?php
/**
* email.php
* Copyright (c) 2019 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
return [
// common items
'greeting' => 'Hi there,',
'closing' => 'Beep boop,',
'signature' => 'The Firefly III Mail Robot',
'footer_ps' => 'PS: This message was sent because a request from IP :ipAddress triggered it.',
// admin test
'admin_test_subject' => 'A test message from your Firefly III installation',
'admin_test_body' => 'This is a test message from your Firefly III instance. It was sent to :email.',
// new IP
'login_from_new_ip' => 'New login on Firefly III',
'new_ip_body' => 'Firefly III detected a new login on your account from an unknown IP address. If you never logged in from the IP address below, or it has been more than six months ago, Firefly III will warn you.',
'new_ip_warning' => 'If you recognize this IP address or the login, you can ignore this message. If you didn\'t login, of if you have no idea what this is about, verify your password security, change it, and log out all other sessions. To do this, go to your profile page. Of course you have 2FA enabled already, right? Stay safe!',
'ip_address' => 'IP address',
'host_name' => 'Host',
'date_time' => 'Date + time',
// access token created
'access_token_created_subject' => 'A new access token was created',
'access_token_created_body' => 'Somebody (hopefully you) just created a new Firefly III API Access Token for your user account.',
'access_token_created_explanation' => 'With this token, they can access <strong>all</strong> of your financial records through the Firefly III API.',
'access_token_created_revoke' => 'If this wasn\'t you, please revoke this token as soon as possible at :url.',
// registered
'registered_subject' => 'Welcome to Firefly III!',
'registered_welcome' => 'Welcome to <a style="color:#337ab7" href=":address">Firefly III</a>. Your registration has made it, and this email is here to confirm it. Yay!',
'registered_pw' => 'If you have forgotten your password already, please reset it using <a style="color:#337ab7" href=":address/password/reset">the password reset tool</a>.',
'registered_help' => 'There is a help-icon in the top right corner of each page. If you need help, click it!',
'registered_doc_html' => 'If you haven\'t already, please read the <a style="color:#337ab7" href="https://docs.firefly-iii.org/about-firefly-iii/personal-finances">grand theory</a>.',
'registered_doc_text' => 'If you haven\'t already, please read the first use guide and the full description.',
'registered_closing' => 'Enjoy!',
'registered_firefly_iii_link' => 'Firefly III:',
'registered_pw_reset_link' => 'Password reset:',
'registered_doc_link' => 'Documentation:',
// email change
'email_change_subject' => 'Your Firefly III email address has changed',
'email_change_body_to_new' => 'You or somebody with access to your Firefly III account has changed your email address. If you did not expect this message, please ignore and delete it.',
'email_change_body_to_old' => 'You or somebody with access to your Firefly III account has changed your email address. If you did not expect this to happen, you <strong>must</strong> follow the "undo"-link below to protect your account!',
'email_change_ignore' => 'If you initiated this change, you may safely ignore this message.',
'email_change_old' => 'The old email address was: :email',
'email_change_old_strong' => 'The old email address was: <strong>:email</strong>',
'email_change_new' => 'The new email address is: :email',
'email_change_new_strong' => 'The new email address is: <strong>:email</strong>',
'email_change_instructions' => 'You cannot use Firefly III until you confirm this change. Please follow the link below to do so.',
'email_change_undo_link' => 'To undo the change, follow this link:',
// OAuth token created
'oauth_created_subject' => 'A new OAuth client has been created',
'oauth_created_body' => 'Somebody (hopefully you) just created a new Firefly III API OAuth Client for your user account. It\'s labeled ":name" and has callback URL <span style="font-family: monospace;">:url</span>.',
'oauth_created_explanation' => 'With this client, they can access <strong>all</strong> of your financial records through the Firefly III API.',
'oauth_created_undo' => 'If this wasn\'t you, please revoke this client as soon as possible at :url.',
// reset password
'reset_pw_subject' => 'Your password reset request',
'reset_pw_instructions' => 'Somebody tried to reset your password. If it was you, please follow the link below to do so.',
'reset_pw_warning' => '<strong>PLEASE</strong> verify that the link actually goes to the Firefly III you expect it to go!',
// error
'error_subject' => 'Caught an error in Firefly III',
'error_intro' => 'Firefly III v:version ran into an error: <span style="font-family: monospace;">:errorMessage</span>.',
'error_type' => 'The error was of type ":class".',
'error_timestamp' => 'The error occurred on/at: :time.',
'error_location' => 'This error occurred in file "<span style="font-family: monospace;">:file</span>" on line :line with code :code.',
'error_user' => 'The error was encountered by user #:id, <a href="mailto::email">:email</a>.',
'error_no_user' => 'There was no user logged in for this error or no user was detected.',
'error_ip' => 'The IP address related to this error is: :ip',
'error_url' => 'URL is: :url',
'error_user_agent' => 'User agent: :userAgent',
'error_stacktrace' => 'The full stacktrace is below. If you think this is a bug in Firefly III, you can forward this message to <a href="mailto:james@firefly-iii.org?subject=BUG!">james@firefly-iii.org</a>. This can help fix the bug you just encountered.',
'error_github_html' => 'If you prefer, you can also open a new issue on <a href="https://github.com/firefly-iii/firefly-iii/issues">GitHub</a>.',
'error_github_text' => 'If you prefer, you can also open a new issue on https://github.com/firefly-iii/firefly-iii/issues.',
'error_stacktrace_below' => 'The full stacktrace is below:',
// report new journals
'new_journals_subject' => 'Firefly III has created a new transaction|Firefly III has created :count new transactions',
'new_journals_header' => 'Firefly III has created a transaction for you. You can find it in your Firefly III installation:|Firefly III has created :count transactions for you. You can find them in your Firefly III installation:',
];
| agpl-3.0 |
gcoop-libre/SuiteCRM | modules/Administration/RepairXSS.php | 4146 | <?php
if (!defined('sugarEntry') || !sugarEntry) {
die('Not A Valid Entry Point');
}
/**
*
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
*
* SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd.
* Copyright (C) 2011 - 2018 SalesAgility Ltd.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
*/
/*********************************************************************************
* Description:
* Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
* Reserved. Contributor(s): ______________________________________..
*********************************************************************************/
include("include/modules.php"); // provides $moduleList, $beanList, etc.
///////////////////////////////////////////////////////////////////////////////
//// UTILITIES
/**
* Cleans all SugarBean tables of XSS - no asynchronous calls. May take a LONG time to complete.
* Meant to be called from a Scheduler instance or other timed or other automation.
*/
function cleanAllBeans()
{
}
//// END UTILITIES
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//// PAGE OUTPUT
if (isset($runSilent) && $runSilent == true) {
// if called from Scheduler
cleanAllBeans();
} else {
$hide = array('Activities', 'Home', 'iFrames', 'Calendar', 'Dashboard');
sort($moduleList);
$options = array();
$options[] = $app_strings['LBL_NONE'];
$options['all'] = "--{$app_strings['LBL_TABGROUP_ALL']}--";
foreach ($moduleList as $module) {
if (!in_array($module, $hide)) {
$options[$module] = $module;
}
}
$options = get_select_options_with_id($options, '');
$beanDropDown = "<select onchange='SUGAR.Administration.RepairXSS.refreshEstimate(this);' id='repairXssDropdown'>{$options}</select>";
echo getClassicModuleTitle('Administration', array($mod_strings['LBL_REPAIRXSS_TITLE']), false);
echo "<script>var done = '{$mod_strings['LBL_DONE']}';</script>";
$smarty = new Sugar_Smarty();
$smarty->assign("mod", $mod_strings);
$smarty->assign("beanDropDown", $beanDropDown);
$smarty->display("modules/Administration/templates/RepairXSS.tpl");
} // end else
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace-archive/Therapies/src/ims/therapies/domain/PatientMotorChart.java | 3026 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// 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.therapies.domain;
// Generated from form domain impl
public interface PatientMotorChart extends ims.domain.DomainInterface
{
// Generated from form domain interface definition
/**
* List Motor Areas
*/
public ims.clinicaladmin.vo.MotorAreaVoCollection listMotorAreas();
// Generated from form domain interface definition
/**
* list HCPs
*/
public ims.core.vo.HcpCollection listHCPs(ims.core.vo.HcpFilter filter);
// Generated from form domain interface definition
/**
* List all previous MotorCharts for this ClinicalContact
*/
public ims.therapies.vo.PatientMotorChartShortVoCollection listPatientMotorChartShort(ims.core.admin.vo.CareContextRefVo careContextRefVo);
// Generated from form domain interface definition
/**
* Get a Motor Chart
*/
public ims.therapies.vo.PatientMotorChartVo getPatientMotorChart(ims.spinalinjuries.therapies.vo.PatientMotorChartRefVo chartVo);
// Generated from form domain interface definition
/**
* Save a patient Motor Chart
*/
public ims.therapies.vo.PatientMotorChartVo savePatientMotorChart(ims.therapies.vo.PatientMotorChartVo chartVo) throws ims.domain.exceptions.StaleObjectException;
// Generated from form domain interface definition
/**
* get Muscles
*/
public ims.clinicaladmin.vo.MuscleGroupsVo getMuscles(ims.clinicaladmin.vo.MuscleGroupsVo voMuscleGroup);
}
| agpl-3.0 |
LLNL/spack | var/spack/repos/builtin/packages/perl-time-piece/package.py | 538 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PerlTimePiece(PerlPackage):
"""Object Oriented time objects"""
homepage = "https://metacpan.org/pod/Time::Piece"
url = "http://search.cpan.org/CPAN/authors/id/E/ES/ESAYM/Time-Piece-1.3203.tar.gz"
version('1.3203', sha256='6971faf6476e4f715a5b5336f0a97317f36e7880fcca6c4db7c3e38e764a6f41')
| lgpl-2.1 |
dotnetprojects/DotNetSiemensPLCToolBoxLibrary | LibNoDaveConnectionLibrary/DataTypes/MultiLanguangeString.cs | 1218 | //using System;
//using System.Collections.Generic;
//using System.Globalization;
//using System.Linq;
//using System.Text;
//using System.Xml;
//using DotNetSiemensPLCToolBoxLibrary.Projectfiles;
//namespace DotNetSiemensPLCToolBoxLibrary.DataTypes
//{
// public class MultiLanguangeString
// {
// private XmlNode node;
// public MultiLanguangeString(XmlNode node)
// {
// this.node = node;
// }
// public string GetText(CultureInfo cultureInfo, Step7ProjectV11 tiaProject)
// {
// var xmlnode = node.SelectSingleNode("coreText/cultures/culture[@id='" + cultureInfo.LCID + "']");
// if (xmlnode != null)
// {
// var val = xmlnode.Attributes["value"];
// if (val != null)
// return val.Value;
// }
// var lidNode = node.SelectSingleNode("attribSet[@id='" + tiaProject.asId2Names.First(itm => itm.Value == "Siemens.Automation.ObjectFrame.ICoreTextExtendedData").Key + "']/attrib[@name='DefaultText']");
// return lidNode.InnerText;
// }
// }
//}
| lgpl-2.1 |
def-/commandergenius | project/jni/application/enigma/lib-src/enigma-core/ecl_alist.hh | 2191 | /*
* Copyright (C) 2002 Daniel Heck
*
* 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.
*/
#ifndef ECL_ALIST_HH
#define ECL_ALIST_HH
/*
* This file defines STL-like associative lists (similar to the ones
* found in Lisp dialects, but with a C++-ish look and feel. They can
* be used as a std::map replacement when linear searches aren't
* expensive.
*/
#include <string>
#include <list>
#include <utility>
namespace ecl
{
template <class KEY, class VAL>
class AssocList : public std::list<std::pair<KEY, VAL> > {
public:
typedef KEY key_type;
typedef std::pair<KEY,VAL> value_type;
typedef typename std::list<value_type>::iterator iterator;
typedef typename std::list<value_type>::const_iterator const_iterator;
//
// Lookup of keys
//
iterator find (const key_type &key) {
iterator i=this->begin(), e=this->end();
for (; i!=e; ++i)
if (i->first == key)
break;
return i;
}
const_iterator find (const key_type &key) const {
const_iterator i=this->begin(), e=this->end();
for (; i!=e; ++i)
if (i->first == key)
break;
return i;
}
VAL &operator[] (const key_type &key) {
iterator i=find(key);
if (i==this->end())
i=insert(this->end(), make_pair(key, VAL()));
return i->second;
}
};
}
#endif
| lgpl-2.1 |
openscenegraph/osg | src/osgPresentation/PropertyManager.cpp | 11475 | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2018 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osgPresentation/PropertyManager>
#include <osg/io_utils>
using namespace osgPresentation;
const osg::Object* osgPresentation::getUserObject(const osg::NodePath& nodepath, const std::string& name)
{
for(osg::NodePath::const_reverse_iterator itr = nodepath.rbegin();
itr != nodepath.rend();
++itr)
{
const osg::UserDataContainer* udc = (*itr)->getUserDataContainer();
const osg::Object* object = udc ? udc->getUserObject(name) : 0;
if (object) return object;
}
return 0;
}
bool osgPresentation::containsPropertyReference(const std::string& str)
{
return (str.find('$')!=std::string::npos);
}
void PropertyAnimation::reset()
{
_firstTime = DBL_MAX;
_pauseTime = DBL_MAX;
OSG_NOTICE<<"PropertyAnimation::reset()"<<std::endl;
}
void PropertyAnimation::setPause(bool pause)
{
OSG_NOTICE<<"PropertyAnimation::setPause("<<pause<<")"<<std::endl;
if (_pause==pause)
{
return;
}
_pause = pause;
if (_firstTime==DBL_MAX) return;
if (_pause)
{
_pauseTime = _latestTime;
}
else
{
_firstTime += (_latestTime-_pauseTime);
}
}
double PropertyAnimation::getAnimationTime() const
{
return _latestTime-_firstTime;
}
void PropertyAnimation::operator()(osg::Node* node, osg::NodeVisitor* nv)
{
if (nv->getVisitorType()==osg::NodeVisitor::UPDATE_VISITOR &&
nv->getFrameStamp())
{
double time = nv->getFrameStamp()->getSimulationTime();
_latestTime = time;
if (!_pause)
{
// Only update _firstTime the first time, when its value is still DBL_MAX
if (_firstTime==DBL_MAX) _firstTime = time;
update(*node);
}
}
traverse(node, nv);
}
class MySetValueVisitor : public osg::ValueObject::SetValueVisitor
{
public:
MySetValueVisitor(double in_r1, double in_r2, osg::ValueObject* in_object2):
_r1(in_r1), _r2(in_r2), _object2(in_object2)
{
}
template<typename T>
void combineRealUserValue(T& value) const
{
typedef osg::TemplateValueObject<T> UserValueObject;
const UserValueObject* uvo = _object2 ? dynamic_cast<const UserValueObject*>(_object2) : 0;
if (uvo)
{
value = value*_r1 + uvo->getValue()*_r2;
}
OSG_NOTICE<<"combineRealUserValue r1="<<_r1<<", r2="<<_r2<<", value="<<value<<std::endl;
}
template<typename T>
void combineIntegerUserValue(T& value) const
{
typedef osg::TemplateValueObject<T> UserValueObject;
const UserValueObject* uvo = _object2 ? dynamic_cast<const UserValueObject*>(_object2) : 0;
if (uvo)
{
value = static_cast<T>(static_cast<double>(value)*_r1 + static_cast<double>(uvo->getValue())*_r2);
}
OSG_NOTICE<<"combineIntegerUserValue "<<value<<std::endl;
}
template<typename T>
void combineDiscretUserValue(T& value) const
{
if (_r1<_r2) // choose value2 if possible
{
typedef osg::TemplateValueObject<T> UserValueObject;
const UserValueObject* uvo = _object2 ? dynamic_cast<const UserValueObject*>(_object2) : 0;
if (uvo)
{
value = uvo->getValue();
}
}
OSG_NOTICE<<"combineDiscretUserValue "<<value<<std::endl;
}
template<typename T>
void combineRotationUserValue(T& /*value*/) const
{
OSG_NOTICE<<"combineRotationUserValue TODO - do slerp"<<std::endl;
}
template<typename T>
void combinePlaneUserValue(T& /*value*/) const
{
OSG_NOTICE<<"combinePlaneUserValue TODO"<<std::endl;
}
template<typename T>
void combineMatrixUserValue(T& /*value*/) const
{
OSG_NOTICE<<"combineMatrixUserValue TODO - decomposs into translate, rotation and scale and then interpolate."<<std::endl;
}
virtual void apply(bool& value) { combineDiscretUserValue(value); }
virtual void apply(char& value) { combineDiscretUserValue(value); }
virtual void apply(unsigned char& value) { combineDiscretUserValue(value); }
virtual void apply(short& value) { combineIntegerUserValue(value); }
virtual void apply(unsigned short& value) { combineIntegerUserValue(value); }
virtual void apply(int& value) { combineIntegerUserValue(value); }
virtual void apply(unsigned int& value) { combineIntegerUserValue(value); }
virtual void apply(float& value) { combineRealUserValue(value); }
virtual void apply(double& value) { combineRealUserValue(value); }
virtual void apply(std::string& value) { combineDiscretUserValue(value); }
virtual void apply(osg::Vec2f& value) { combineRealUserValue(value); }
virtual void apply(osg::Vec3f& value) { combineRealUserValue(value); }
virtual void apply(osg::Vec4f& value) { combineRealUserValue(value); }
virtual void apply(osg::Vec2d& value) { combineRealUserValue(value); }
virtual void apply(osg::Vec3d& value) { combineRealUserValue(value); }
virtual void apply(osg::Vec4d& value) { combineRealUserValue(value); }
virtual void apply(osg::Quat& value) { combineRotationUserValue(value); }
virtual void apply(osg::Plane& value) { combinePlaneUserValue(value); }
virtual void apply(osg::Matrixf& value) { combineMatrixUserValue(value); }
virtual void apply(osg::Matrixd& value) { combineMatrixUserValue(value); }
virtual ~MySetValueVisitor() {}
double _r1, _r2;
osg::ValueObject* _object2;
};
void PropertyAnimation::update(osg::Node& node)
{
OSG_NOTICE<<"PropertyAnimation::update()"<<this<<std::endl;
double time = getAnimationTime();
if (_keyFrameMap.empty()) return;
KeyFrameMap::const_iterator itr = _keyFrameMap.lower_bound(time);
if (itr==_keyFrameMap.begin())
{
// need to copy first UserDataContainer
OSG_NOTICE<<"PropertyAnimation::update() : copy first UserDataContainer"<<std::endl;
assign(node.getOrCreateUserDataContainer(), itr->second.get());
}
else if (itr!=_keyFrameMap.end())
{
KeyFrameMap::const_iterator itr_1 = itr; --itr_1;
KeyFrameMap::const_iterator itr_2 = itr;
// delta_time = second.time - first.time
double delta_time = itr_2->first - itr_1->first;
double r1, r2;
if (delta_time==0.0)
{
r1 = 0.5;
r2 = 0.5;
}
else
{
r2 = (time - itr_1->first)/delta_time;
r1 = 1.0-r2;
}
osg::UserDataContainer* p1 = itr_1->second.get();
osg::UserDataContainer* p2 = itr_2->second.get();
// clone all the properties from p1;
osg::ref_ptr<osg::UserDataContainer> destination = node.getOrCreateUserDataContainer();
assign(destination.get(), p1);
for(unsigned int i2=0; i2<p2->getNumUserObjects(); ++i2)
{
osg::Object* obj_2 = p2->getUserObject(i2);
unsigned int i1 = p1->getUserObjectIndex(obj_2->getName());
if (i1<p1->getNumUserObjects())
{
osg::Object* obj_1 = p1->getUserObject(i1);
osg::ValueObject* valueobject_1 = dynamic_cast<osg::ValueObject*>(obj_1);
osg::ValueObject* valueobject_2 = dynamic_cast<osg::ValueObject*>(obj_2);
if (valueobject_1 && valueobject_2)
{
osg::ref_ptr<osg::ValueObject> vo = osg::clone(valueobject_1);
MySetValueVisitor mySetValue(r1, r2, valueobject_2);
vo->set(mySetValue);
assign(destination.get(), vo.get());
}
else if (obj_1)
{
assign(destination.get(), obj_1);
}
else if (obj_2)
{
assign(destination.get(), obj_2);
}
}
else
{
// need to insert property;
assign(destination.get(), obj_2);
}
}
}
else // (itr==_keyFrameMap.end())
{
OSG_NOTICE<<"PropertyAnimation::update() : copy last UserDataContainer"<<std::endl;
assign(node.getOrCreateUserDataContainer(), _keyFrameMap.rbegin()->second.get());
}
}
void PropertyAnimation::assign(osg::UserDataContainer* destination, osg::UserDataContainer* source)
{
if (!destination) return;
if (!source) return;
for(unsigned int i=0; i<source->getNumUserObjects(); ++i)
{
assign(destination, source->getUserObject(i));
}
}
void PropertyAnimation::assign(osg::UserDataContainer* udc, osg::Object* obj)
{
if (!obj) return;
unsigned int index = udc->getUserObjectIndex(obj);
if (index != udc->getNumUserObjects())
{
OSG_NOTICE<<"Object already assigned to UserDataContainer"<<std::endl;
return;
}
index = udc->getUserObjectIndex(obj->getName());
if (index != udc->getNumUserObjects())
{
OSG_NOTICE<<"Replacing object in UserDataContainer"<<std::endl;
udc->setUserObject(index, obj);
return;
}
OSG_NOTICE<<"Assigned object to UserDataContainer"<<std::endl;
udc->addUserObject(obj);
}
void ImageSequenceUpdateCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
{
float x;
if (_propertyManager->getProperty(_propertyName,x))
{
double xMin = -1.0;
double xMax = 1.0;
double position = ((double)x-xMin)/(xMax-xMin)*_imageSequence->getLength();
_imageSequence->seek(position);
}
else
{
OSG_INFO<<"ImageSequenceUpdateCallback::operator() Could not find property : "<<_propertyName<<std::endl;
}
// note, callback is responsible for scenegraph traversal so
// they must call traverse(node,nv) to ensure that the
// scene graph subtree (and associated callbacks) are traversed.
traverse(node,nv);
}
bool PropertyEventCallback::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
{
bool mouseEvent = (ea.getEventType()==osgGA::GUIEventAdapter::MOVE ||
ea.getEventType()==osgGA::GUIEventAdapter::DRAG ||
ea.getEventType()==osgGA::GUIEventAdapter::PUSH ||
ea.getEventType()==osgGA::GUIEventAdapter::RELEASE);
if(mouseEvent)
{
_propertyManager->setProperty("mouse.x",ea.getX());
_propertyManager->setProperty("mouse.x_normalized",ea.getXnormalized());
_propertyManager->setProperty("mouse.y",ea.getX());
_propertyManager->setProperty("mouse.y_normalized",ea.getYnormalized());
}
return false;
}
| lgpl-2.1 |
marclaporte/jitsi | test/net/java/sip/communicator/slick/protocol/jabber/TestOperationSetPresence.java | 43403 | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.slick.protocol.jabber;
import java.beans.*;
import java.util.*;
import junit.framework.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.service.protocol.jabberconstants.*;
import net.java.sip.communicator.util.*;
/**
* Tests Jabber implementations of a Presence Operation Set. Tests in this class
* verify functionality such as: Changing local (our own) status and
* corresponding event dispatching; Querying status of contacts, Subscribing
* for presence notifications upong status changes of specific contacts.
* <p>
* Using a custom suite() method, we make sure that apart from standard test
* methods (those with a <tt>test</tt> prefix) we also execute those that
* we want run in a specific order like for example - postTestSubscribe() and
* postTestUnsubscribe().
* <p>
* @author Damian Minkov
* @author Lubomir Marinov
*/
public class TestOperationSetPresence
extends TestCase
{
private static final Logger logger =
Logger.getLogger(TestOperationSetPresence.class);
private JabberSlickFixture fixture = new JabberSlickFixture();
private OperationSetPresence operationSetPresence1 = null;
private final Map<String, PresenceStatus> supportedStatusSet1
= new HashMap<String, PresenceStatus>();
private OperationSetPresence operationSetPresence2 = null;
private final Map<String, PresenceStatus> supportedStatusSet2
= new HashMap<String, PresenceStatus>();
private String statusMessageRoot = new String("Our status is now: ");
private static AuthEventCollector authEventCollector1
= new AuthEventCollector();
private static AuthEventCollector authEventCollector2
= new AuthEventCollector();
public TestOperationSetPresence(String name)
{
super(name);
}
@Override
protected void setUp() throws Exception
{
super.setUp();
fixture.setUp();
Map<String, OperationSet> supportedOperationSets1 =
fixture.provider1.getSupportedOperationSets();
if ( supportedOperationSets1 == null
|| supportedOperationSets1.size() < 1)
throw new NullPointerException(
"No OperationSet implementations are supported by "
+"this implementation. ");
//get the operation set presence here.
operationSetPresence1 =
(OperationSetPresence)supportedOperationSets1.get(
OperationSetPresence.class.getName());
//if the op set is null then the implementation doesn't offer a presence
//operation set which is unacceptable for jabber.
if (operationSetPresence1 == null)
{
throw new NullPointerException(
"An implementation of the Jabber service must provide an "
+ "implementation of at least the one of the Presence "
+ "Operation Sets");
}
// do it once again for the second provider
Map<String, OperationSet> supportedOperationSets2 =
fixture.provider2.getSupportedOperationSets();
if ( supportedOperationSets2 == null
|| supportedOperationSets2.size() < 1)
throw new NullPointerException(
"No OperationSet implementations are supported by "
+"this Jabber implementation. ");
//get the operation set presence here.
operationSetPresence2 =
(OperationSetPresence)supportedOperationSets2.get(
OperationSetPresence.class.getName());
//if the op set is null then the implementation doesn't offer a presence
//operation set which is unacceptable for jabber.
if (operationSetPresence2 == null)
{
throw new NullPointerException(
"An implementation of the Jabber service must provide an "
+ "implementation of at least the one of the Presence "
+ "Operation Sets");
}
/*
* Retrieve the supported PresenceStatus values because the instances
* are specific to the ProtocolProviderService implementations.
*/
// operationSetPresence1
for (Iterator<PresenceStatus> supportedStatusIt
= operationSetPresence1.getSupportedStatusSet();
supportedStatusIt.hasNext();)
{
PresenceStatus supportedStatus = supportedStatusIt.next();
supportedStatusSet1.put(supportedStatus.getStatusName(),
supportedStatus);
}
// operationSetPresence2
for (Iterator<PresenceStatus> supportedStatusIt
= operationSetPresence2.getSupportedStatusSet();
supportedStatusIt.hasNext();)
{
PresenceStatus supportedStatus = supportedStatusIt.next();
supportedStatusSet2.put(supportedStatus.getStatusName(),
supportedStatus);
}
}
@Override
protected void tearDown() throws Exception
{
super.tearDown();
fixture.tearDown();
}
/**
* Creates a test suite containing all tests of this class followed by
* test methods that we want executed in a specified order.
* @return Test
*/
public static Test suite()
{
//return an (almost) empty suite if we're running in offline mode.
if(JabberSlickFixture.onlineTestingDisabled)
{
TestSuite suite = new TestSuite();
//the only test around here that we could run without net
//connectivity
suite.addTest(
new TestOperationSetPresence(
"testSupportedStatusSetForCompleteness"));
return suite;
}
TestSuite suite = new TestSuite();
// clear the lists before subscribing users
suite.addTest(new TestOperationSetPresence("clearLists"));
// first postTestSubscribe. to be sure that contacts are in the
// list so we can further continue and test presences each other
suite.addTest(new TestOperationSetPresence("postTestSubscribe"));
// // add other tests
// suite.addTestSuite(TestOperationSetPresence.class);
//
// now test unsubscribe
suite.addTest(new TestOperationSetPresence("postTestUnsubscribe"));
return suite;
}
/**
* Verifies that all necessary Jabber test states are supported by the
* implementation.
*/
public void testSupportedStatusSetForCompleteness()
{
//first create a local list containing the presence status instances
//supported by the underlying implementation.
Iterator<PresenceStatus> supportedStatusSetIter =
operationSetPresence1.getSupportedStatusSet();
List<String> supportedStatusNames = new LinkedList<String>();
while (supportedStatusSetIter.hasNext())
{
supportedStatusNames.add(supportedStatusSetIter
.next().getStatusName());
}
//create a copy of the MUST status set and remove any matching status
//that is also present in the supported set.
List<String> requiredStatusNames =
Arrays.asList(JabberStatusEnum.getStatusNames());
requiredStatusNames.removeAll(supportedStatusNames);
//if we have anything left then the implementation is wrong.
int unsupported = requiredStatusNames.size();
assertTrue( "There are " + unsupported + " statuses as follows:"
+ requiredStatusNames, unsupported == 0);
}
/**
* Verify that changing state to AWAY works as supposed to and that it
* generates the corresponding event.
* @throws Exception in case a failure occurs while the operation set
* is switching to the new state.
*/
public void testChangingStateToAway() throws Exception
{
subtestStateTransition(JabberStatusEnum.AWAY);
}
/**
* Verify that changing state to DND works as supposed to and that it
* generates the corresponding event.
* @throws Exception in case a failure occurs while the operation set
* is switching to the new state.
*/
public void testChangingStateToDnd() throws Exception
{
subtestStateTransition(JabberStatusEnum.DO_NOT_DISTURB);
}
/**
* Verify that changing state to FREE_FOR_CHAT works as supposed to and
* that it generates the corresponding event.
* @throws Exception in case a failure occurs while the operation set
* is switching to the new state.
*/
public void testChangingStateToFreeForChat() throws Exception
{
subtestStateTransition(JabberStatusEnum.FREE_FOR_CHAT);
}
/**
* Verify that changing state to ONLINE works as supposed to and that it
* generates the corresponding event.
* @throws Exception in case a failure occurs while the operation set
* is switching to the new state.
*/
public void testChangingStateToOnline() throws Exception
{
subtestStateTransition(JabberStatusEnum.AVAILABLE);
}
/**
* Used by methods testing state transiotions
*
* @param newStatus the JabberStatusEnum field corresponding to the status
* that we'd like the opeation set to enter.
*
* @throws Exception in case changing the state causes an exception
*/
private void subtestStateTransition(String newStatusName) throws Exception
{
logger.trace(" --=== beginning state transition test ===--");
PresenceStatus newStatus = supportedStatusSet1.get(newStatusName);
PresenceStatus oldStatus = operationSetPresence1.getPresenceStatus();
String oldStatusMessage
= operationSetPresence1.getCurrentStatusMessage();
String newStatusMessage = statusMessageRoot + newStatus;
logger.debug( "old status is=" + oldStatus.getStatusName()
+ " new status=" + newStatus.getStatusName());
//First register a listener to make sure that all corresponding
//events have been generated.
PresenceStatusEventCollector statusEventCollector
= new PresenceStatusEventCollector();
operationSetPresence1.addProviderPresenceStatusListener(
statusEventCollector);
//change the status
operationSetPresence1
.publishPresenceStatus(newStatus, newStatusMessage);
pauseAfterStateChanges();
//test event notification.
statusEventCollector.waitForPresEvent(10000);
statusEventCollector.waitForStatMsgEvent(10000);
operationSetPresence1.removeProviderPresenceStatusListener(
statusEventCollector);
assertEquals("Events dispatched during an event transition.",
1, statusEventCollector.collectedPresEvents.size());
assertEquals("A status changed event contained wrong old status.",
oldStatus,
statusEventCollector
.collectedPresEvents.get(0).getOldStatus());
assertEquals("A status changed event contained wrong new status.",
newStatus,
statusEventCollector
.collectedPresEvents.get(0).getNewStatus());
// verify that the operation set itself is aware of the status change
assertEquals("opSet.getPresenceStatus() did not return properly.",
newStatus,
operationSetPresence1.getPresenceStatus());
PresenceStatus actualStatus =
operationSetPresence2.queryContactStatus(fixture.userID1);
assertEquals("The underlying implementation did not switch to the "
+"requested presence status.",
newStatus,
actualStatus);
//check whether the server returned the status message that we've set.
assertEquals("No status message events.",
1, statusEventCollector.collectedStatMsgEvents.size());
assertEquals("A status message event contained wrong old value.",
oldStatusMessage,
statusEventCollector.collectedStatMsgEvents.get(0)
.getOldValue());
assertEquals("A status message event contained wrong new value.",
newStatusMessage,
statusEventCollector.collectedStatMsgEvents.get(0)
.getNewValue());
// verify that the operation set itself is aware of the new status msg.
assertEquals("opSet.getCurrentStatusMessage() did not return properly.",
newStatusMessage,
operationSetPresence1.getCurrentStatusMessage());
logger.trace(" --=== finished test ===--");
}
/**
* Give time changes to take effect
*/
private void pauseAfterStateChanges()
{
try
{
Thread.sleep(1500);
}
catch (InterruptedException ex)
{
logger.debug("Pausing between state changes was interrupted", ex);
}
}
/**
* Verifies that querying status works fine. The tester agent would
* change status and the operation set would have to return the right status
* after every change.
*
* @throws java.lang.Exception if one of the transitions fails
*/
public void testQueryContactStatus()
throws Exception
{
// --- AWAY ---
logger.debug("Will Query an AWAY contact.");
subtestQueryContactStatus(JabberStatusEnum.AWAY,
JabberStatusEnum.AWAY);
// --- DND ---
logger.debug("Will Query a DND contact.");
subtestQueryContactStatus(JabberStatusEnum.DO_NOT_DISTURB,
JabberStatusEnum.DO_NOT_DISTURB);
// --- FFC ---
logger.debug("Will Query a Free For Chat contact.");
subtestQueryContactStatus(JabberStatusEnum.FREE_FOR_CHAT,
JabberStatusEnum.FREE_FOR_CHAT);
// --- Online ---
logger.debug("Will Query an Online contact.");
subtestQueryContactStatus(JabberStatusEnum.AVAILABLE,
JabberStatusEnum.AVAILABLE);
}
/**
* Used by functions testing the queryContactStatus method of the
* presence operation set.
* @param status the status as specified, that
* the tester agent should switch to.
* @param expectedReturn the PresenceStatus that the presence operation
* set should see the tester agent in once it has switched to taStatusLong.
*
* @throws java.lang.Exception if querying the status causes some exception.
*/
private void subtestQueryContactStatus(String status, String expectedReturn)
throws Exception
{
operationSetPresence2.publishPresenceStatus(
supportedStatusSet2.get(status), "status message");
pauseAfterStateChanges();
PresenceStatus actualReturn
= operationSetPresence1.queryContactStatus(fixture.userID2);
assertEquals("Querying a "
+ expectedReturn
+ " state did not return as expected"
, supportedStatusSet1.get(expectedReturn)
, actualReturn);
}
/**
* The method would add a subscription for a contact, wait for a
* subscription event confirming the subscription, then change the status
* of the newly added contact (which is actually the testerAgent) and
* make sure that the corresponding notification events have been generated.
*
* @throws java.lang.Exception if an exception occurs during testing.
*/
public void postTestSubscribe()
throws Exception
{
logger.debug("Testing Subscription and Subscription Event Dispatch.");
logger.trace("set Auth Handlers");
operationSetPresence1.setAuthorizationHandler(authEventCollector1);
operationSetPresence2.setAuthorizationHandler(authEventCollector2);
/**
* Testing Scenario
*
* user1 add user2
* - check user2 receive auth request
* - user2 deny
* - check user1 received deny
* user1 add user2
* - check user2 receive auth request
* - user2 accept
* - check user1 received accept
*/
// first we will reject
authEventCollector2.responseToRequest =
new AuthorizationResponse(AuthorizationResponse.REJECT, null);
operationSetPresence1.subscribe(fixture.userID2);
authEventCollector2.waitForAuthRequest(10000);
assertTrue("Error authorization request not received from " +
fixture.userID2,
authEventCollector2.isAuthorizationRequestReceived);
authEventCollector1.waitForAuthResponse(10000);
assertTrue("Error authorization reply not received from " +
fixture.userID1,
authEventCollector1.isAuthorizationResponseReceived);
assertEquals("Error received authorization reply not as expected",
authEventCollector2.responseToRequest.getResponseCode(),
authEventCollector1.response.getResponseCode());
pauseAfterStateChanges();
SubscriptionEventCollector subEvtCollector
= new SubscriptionEventCollector();
operationSetPresence1.addSubscriptionListener(subEvtCollector);
// second we will accept
authEventCollector2.responseToRequest =
new AuthorizationResponse(AuthorizationResponse.ACCEPT, null);
authEventCollector2.isAuthorizationRequestReceived = false;
authEventCollector1.isAuthorizationResponseReceived = false;
operationSetPresence1.subscribe(fixture.userID2);
authEventCollector2.waitForAuthRequest(10000);
assertTrue("Error authorization request not received from " +
fixture.userID2,
authEventCollector2.isAuthorizationRequestReceived);
authEventCollector1.waitForAuthResponse(10000);
assertTrue("Error authorization reply not received from " +
fixture.userID1,
authEventCollector1.isAuthorizationResponseReceived);
assertEquals("Error received authorization reply not as expected",
authEventCollector2.responseToRequest.getResponseCode(),
authEventCollector1.response.getResponseCode());
// fix . from no on accept all subscription request for the two
// tested accounts
authEventCollector1.responseToRequest =
new AuthorizationResponse(AuthorizationResponse.ACCEPT, null);
authEventCollector2.responseToRequest =
new AuthorizationResponse(AuthorizationResponse.ACCEPT, null);
operationSetPresence1.removeSubscriptionListener(subEvtCollector);
assertTrue("Subscription event dispatching failed."
, subEvtCollector.collectedSubscriptionEvents.size() > 0);
SubscriptionEvent subEvt = null;
synchronized(subEvtCollector)
{
Iterator<SubscriptionEvent> events
= subEvtCollector.collectedSubscriptionEvents.iterator();
while (events.hasNext())
{
SubscriptionEvent elem = events.next();
if(elem.getEventID() == SubscriptionEvent.SUBSCRIPTION_CREATED)
subEvt = elem;
}
}
// it happens that when adding contacts which require authorization
// sometimes the collected events are 3 - added, deleted, added
// so we get the last one if there is such
assertNotNull("Subscription event dispatching failed.", subEvt);
assertEquals("SubscriptionEvent Source:",
fixture.userID2,
((Contact)subEvt.getSource()).getAddress());
assertEquals("SubscriptionEvent Source Contact:",
fixture.userID2,
subEvt.getSourceContact().getAddress());
assertSame("SubscriptionEvent Source Provider:",
fixture.provider1,
subEvt.getSourceProvider());
subEvtCollector.collectedSubscriptionEvents.clear();
subEvtCollector.collectedSubscriptionMovedEvents.clear();
subEvtCollector.collectedContactPropertyChangeEvents.clear();
// make the user agent tester change its states and make sure we are
// notified
logger.debug("Testing presence notifications.");
PresenceStatus oldStatus
= operationSetPresence2.getPresenceStatus();
PresenceStatus newStatus
= supportedStatusSet2.get(JabberStatusEnum.FREE_FOR_CHAT);
//in case we are by any chance already in a FREE_FOR_CHAT status, we'll
//be changing to something else
if(oldStatus.equals(newStatus)){
newStatus
= supportedStatusSet2.get(JabberStatusEnum.DO_NOT_DISTURB);
}
//now do the actual status notification testing
ContactPresenceEventCollector contactPresEvtCollector
= new ContactPresenceEventCollector(
fixture.userID2, newStatus);
operationSetPresence1.addContactPresenceStatusListener(
contactPresEvtCollector);
synchronized (contactPresEvtCollector){
operationSetPresence2
.publishPresenceStatus(newStatus, "new status");
//we may already have the event, but it won't hurt to check.
contactPresEvtCollector.waitForEvent(10000);
operationSetPresence1
.removeContactPresenceStatusListener(contactPresEvtCollector);
}
assertEquals(
"Presence Notif. event dispatching failed.",
1,
contactPresEvtCollector.collectedEvents.size());
ContactPresenceStatusChangeEvent presEvt = contactPresEvtCollector.collectedEvents.get(0);
assertEquals("Presence Notif. event Source:",
fixture.userID2,
((Contact)presEvt.getSource()).getAddress());
assertEquals("Presence Notif. event Source Contact:",
fixture.userID2,
presEvt.getSourceContact().getAddress());
assertSame("Presence Notif. event Source Provider:",
fixture.provider1,
presEvt.getSourceProvider());
PresenceStatus reportedNewStatus = presEvt.getNewStatus();
PresenceStatus reportedOldStatus = presEvt.getOldStatus();
assertEquals( "Reported new PresenceStatus: ",
newStatus, reportedNewStatus );
//don't require equality between the reported old PresenceStatus and
//the actual presence status of the tester agent because a first
//notification is not supposed to have the old status as it really was.
assertNotNull( "Reported old PresenceStatus: ", reportedOldStatus );
}
/**
* We unsubscribe from presence notification deliveries concerning
* testerAgent's presence status and verify that we receive the
* subscription removed event. We then make the tester agent change status
* and make sure that no notifications are delivered.
*
* @throws java.lang.Exception in case unsubscribing fails.
*/
public void postTestUnsubscribe()
throws Exception
{
logger.debug("Testing Unsubscribe and unsubscription event dispatch.");
// First create a subscription and verify that it really gets created.
SubscriptionEventCollector subEvtCollector
= new SubscriptionEventCollector();
operationSetPresence1.addSubscriptionListener(subEvtCollector);
Contact jabberTesterAgentContact = operationSetPresence1
.findContactByID(fixture.userID2);
assertNotNull(
"Failed to find an existing subscription for the tester agent"
, jabberTesterAgentContact);
synchronized(subEvtCollector){
operationSetPresence1.unsubscribe(jabberTesterAgentContact);
subEvtCollector.waitForSubscriptionEvent(10000);
//don't want any more events
operationSetPresence1.removeSubscriptionListener(subEvtCollector);
}
assertEquals(
"Subscription event dispatching failed.",
1,
subEvtCollector.collectedSubscriptionEvents.size());
SubscriptionEvent subEvt =
subEvtCollector.collectedSubscriptionEvents.get(0);
assertEquals("SubscriptionEvent Source:",
jabberTesterAgentContact, subEvt.getSource());
assertEquals("SubscriptionEvent Source Contact:",
jabberTesterAgentContact, subEvt.getSourceContact());
assertSame("SubscriptionEvent Source Provider:",
fixture.provider1,
subEvt.getSourceProvider());
subEvtCollector.collectedSubscriptionEvents.clear();
subEvtCollector.collectedSubscriptionMovedEvents.clear();
subEvtCollector.collectedContactPropertyChangeEvents.clear();
// make the user agent tester change its states and make sure we don't
// get notifications as we're now unsubscribed.
logger.debug("Testing (lack of) presence notifications.");
PresenceStatus oldStatus
= operationSetPresence2.getPresenceStatus();
PresenceStatus newStatus
= supportedStatusSet2.get(JabberStatusEnum.FREE_FOR_CHAT);
//in case we are by any chance already in a FREE_FOR_CHAT status, we'll
//be changing to something else
if(oldStatus.equals(newStatus)){
newStatus
= supportedStatusSet2.get(JabberStatusEnum.DO_NOT_DISTURB);
}
//now do the actual status notification testing
ContactPresenceEventCollector contactPresEvtCollector
= new ContactPresenceEventCollector(fixture.userID2, null);
operationSetPresence1.addContactPresenceStatusListener(
contactPresEvtCollector);
synchronized (contactPresEvtCollector)
{
operationSetPresence2.publishPresenceStatus(
newStatus, "new status");
//we may already have the event, but it won't hurt to check.
contactPresEvtCollector.waitForEvent(10000);
operationSetPresence1
.removeContactPresenceStatusListener(contactPresEvtCollector);
}
assertEquals("Presence Notifications were received after unsubscibing."
, 0, contactPresEvtCollector.collectedEvents.size());
}
public void clearLists()
throws Exception
{
logger.debug("Clear the two lists before tests");
fixture.clearProvidersLists();
Object o = new Object();
synchronized(o)
{
o.wait(3000);
}
}
/**
* An event collector that would collect all events generated by a
* provider after a status change. The collector would also do a notidyAll
* every time it receives an event.
*/
private class PresenceStatusEventCollector
implements ProviderPresenceStatusListener
{
public ArrayList<ProviderPresenceStatusChangeEvent> collectedPresEvents
= new ArrayList<ProviderPresenceStatusChangeEvent>();
public ArrayList<PropertyChangeEvent> collectedStatMsgEvents
= new ArrayList<PropertyChangeEvent>();
public void providerStatusChanged(ProviderPresenceStatusChangeEvent evt)
{
synchronized(this)
{
logger.debug("Collected evt("+collectedPresEvents.size()
+")= "+evt);
collectedPresEvents.add(evt);
notifyAll();
}
}
public void providerStatusMessageChanged(PropertyChangeEvent evt)
{
synchronized(this)
{
logger.debug("Collected stat.msg. evt("
+collectedPresEvents.size()+")= "+evt);
collectedStatMsgEvents.add(evt);
notifyAll();
}
}
/**
* Blocks until at least one event is received or until waitFor
* miliseconds pass (whicever happens first).
*
* @param waitFor the number of miliseconds that we should be waiting
* for an event before simply bailing out.
*/
public void waitForPresEvent(long waitFor)
{
logger.trace("Waiting for a change in provider status.");
TestOperationSetPresence.waitForEvent(
this,
waitFor,
collectedPresEvents);
}
/**
* Blocks until at least one staus message event is received or until
* waitFor miliseconds pass (whichever happens first).
*
* @param waitFor the number of miliseconds that we should be waiting
* for a status message event before simply bailing out.
*/
public void waitForStatMsgEvent(long waitFor)
{
logger.trace("Waiting for a provider status message event.");
TestOperationSetPresence.waitForEvent(
this,
waitFor,
collectedStatMsgEvents);
}
}
/**
* The class would listen for and store received subscription modification
* events.
*/
private class SubscriptionEventCollector implements SubscriptionListener
{
/**
* Collects all SubscriptionEvent generated.
*/
public ArrayList<SubscriptionEvent> collectedSubscriptionEvents
= new ArrayList<SubscriptionEvent>();
/**
* Collects all SubscriptionMovedEvent generated.
*/
public ArrayList<SubscriptionMovedEvent>
collectedSubscriptionMovedEvents
= new ArrayList<SubscriptionMovedEvent>();
/**
* Collects all ContactPropertyChangeEvent generated.
*/
public ArrayList<ContactPropertyChangeEvent>
collectedContactPropertyChangeEvents
= new ArrayList<ContactPropertyChangeEvent>();
/**
* Blocks until at least one SubscriptionEvent is received or until
* waitFor miliseconds pass (whicever happens first).
*
* @param waitFor the number of miliseconds that we should be waiting
* for an SubscriptionEvent before simply bailing out.
*/
public void waitForSubscriptionEvent(long waitFor)
{
TestOperationSetPresence.waitForEvent(
this,
waitFor,
collectedSubscriptionEvents);
}
/**
* Blocks until at least one SubscriptionMovedEvent is received or until
* waitFor miliseconds pass (whicever happens first).
*
* @param waitFor the number of miliseconds that we should be waiting
* for an SubscriptionMovedEvent before simply bailing out.
*/
public void waitForSubscriptionMovedEvent(long waitFor)
{
TestOperationSetPresence.waitForEvent(
this,
waitFor,
collectedSubscriptionMovedEvents);
}
/**
* Blocks until at least one ContactPropertyChangeEvent is received or
* until waitFor miliseconds pass (whicever happens first).
*
* @param waitFor the number of miliseconds that we should be waiting
* for an ContactPropertyChangeEvent before simply bailing out.
*/
public void waitForContactPropertyChangeEvent(long waitFor)
{
TestOperationSetPresence.waitForEvent(
this,
waitFor,
collectedContactPropertyChangeEvents);
}
/**
* Stores the received subsctiption and notifies all waiting on this
* object
* @param evt the SubscriptionEvent containing the corresponding contact
*/
public void receivedSubscriptionEvent(SubscriptionEvent evt)
{
synchronized(this)
{
logger.debug(
"Collected SubscriptionEvnet("
+ collectedSubscriptionEvents.size()
+ ")= "
+ evt);
collectedSubscriptionEvents.add(evt);
notifyAll();
}
}
/**
* Stores the received subsctiption and notifies all waiting on this
* object
* @param evt the SubscriptionEvent containing the corresponding contact
*/
public void subscriptionCreated(SubscriptionEvent evt)
{
receivedSubscriptionEvent(evt);
}
/**
* Stores the received subsctiption and notifies all waiting on this
* object
* @param evt the SubscriptionEvent containing the corresponding contact
*/
public void subscriptionRemoved(SubscriptionEvent evt)
{
receivedSubscriptionEvent(evt);
}
/**
* Stores the received subsctiption and notifies all waiting on this
* object
* @param evt the SubscriptionEvent containing the corresponding contact
*/
public void contactModified(ContactPropertyChangeEvent evt)
{
synchronized(this)
{
logger.debug(
"Collected ContactPropertyChangeEvent("
+ collectedContactPropertyChangeEvents.size()
+ ")= "
+ evt);
collectedContactPropertyChangeEvents.add(evt);
notifyAll();
}
}
/**
* Stores the received subsctiption and notifies all waiting on this
* object
* @param evt the SubscriptionEvent containing the corresponding contact
*/
public void subscriptionMoved(SubscriptionMovedEvent evt)
{
synchronized(this)
{
logger.debug(
"Collected evt("
+ collectedSubscriptionMovedEvents.size()
+ ")= "
+ evt);
collectedSubscriptionMovedEvents.add(evt);
notifyAll();
}
}
/**
* Stores the received subsctiption and notifies all waiting on this
* object
* @param evt the SubscriptionEvent containing the corresponding contact
*/
public void subscriptionFailed(SubscriptionEvent evt)
{
receivedSubscriptionEvent(evt);
}
/**
* Stores the received subsctiption and notifies all waiting on this
* object
* @param evt the SubscriptionEvent containing the corresponding contact
*/
public void subscriptionResolved(SubscriptionEvent evt)
{
receivedSubscriptionEvent(evt);
}
}
/**
* The class would listen for and store received events caused by changes
* in contact presence states.
*/
private class ContactPresenceEventCollector
implements ContactPresenceStatusListener
{
public ArrayList<ContactPresenceStatusChangeEvent> collectedEvents
= new ArrayList<ContactPresenceStatusChangeEvent>();
private String trackedScreenName = null;
private PresenceStatus status = null;
ContactPresenceEventCollector(String screenname,
PresenceStatus wantedStatus)
{
this.trackedScreenName = screenname;
this.status = wantedStatus;
}
/**
* Blocks until at least one event is received or until waitFor
* miliseconds pass (whicever happens first).
*
* @param waitFor the number of miliseconds that we should be waiting
* for an event before simply bailing out.
*/
public void waitForEvent(long waitFor)
{
TestOperationSetPresence.waitForEvent(
this,
waitFor,
collectedEvents);
}
/**
* Stores the received status change event and notifies all waiting on
* this object
* @param evt the SubscriptionEvent containing the corresponding contact
*/
public void contactPresenceStatusChanged(
ContactPresenceStatusChangeEvent evt)
{
synchronized(this)
{
//if the user has specified event details and the received
//event does not match - then ignore it.
if( this.trackedScreenName != null
&& !evt.getSourceContact().getAddress()
.equals(trackedScreenName))
return;
if( status == null )
return;
if(status != evt.getNewStatus())
return;
logger.debug("Collected evt("+collectedEvents.size()+")= "+evt);
collectedEvents.add(evt);
notifyAll();
}
}
}
/**
* Blocks until at least one event is received or until waitFor
* miliseconds pass (whicever happens first).
* Must be called by with a synchronized collectedEvents Object.
*
* @param waitFor the number of miliseconds that we should be waiting
* for an event before simply bailing out.
* @param collectedEvents the array used to collect the events. Must be
* synchronized before calling this function.
*/
public static void waitForEvent(
Object eventCollector,
long waitFor,
List collectedEvents)
{
long startTime = System.currentTimeMillis();
long elapsedTime = 0;
synchronized(eventCollector)
{
try
{
while(collectedEvents.size() == 0
&& elapsedTime < waitFor)
{
// Wait may be awake by a notifyAll generated by Events
// different from those collected by collectedEvents.
eventCollector.wait(waitFor - elapsedTime);
// Recomputes the time elapsed since the start of this
// waitForEvent.
elapsedTime = System.currentTimeMillis() - startTime;
}
}
catch (InterruptedException ex)
{
logger.debug(
"Interrupted while waiting for a subscription evt", ex);
}
}
}
/**
* Authorization handler for the implementation tests
* <p>
* 1. when authorization request is received we answer with the already set
* Authorization response, but before that wait some time as a normal user
* </p>
* <p>
* 2. When authorization request is required for adding buddy
* the request is made with already set authorization reason
* </p>
* <p>
* 3. When authorization replay is received - we store that it is received
* and the reason that was received
* </p>
*/
private static class AuthEventCollector
implements AuthorizationHandler
{
boolean isAuthorizationRequestSent = false;
boolean isAuthorizationResponseReceived = false;
AuthorizationResponse response = null;
// receiving auth request
AuthorizationResponse responseToRequest = null;
boolean isAuthorizationRequestReceived = false;
public AuthorizationResponse processAuthorisationRequest(
AuthorizationRequest req, Contact sourceContact)
{
logger.debug("Processing in " + this);
synchronized(this)
{
logger.trace("processAuthorisationRequest " + req + " " +
sourceContact);
isAuthorizationRequestReceived = true;
notifyAll();
// will wait as a normal user
Object lock = new Object();
synchronized (lock)
{
try
{
lock.wait(2000);
}
catch (Exception ex)
{}
}
return responseToRequest;
}
}
public AuthorizationRequest createAuthorizationRequest(Contact contact)
{
logger.trace("createAuthorizationRequest " + contact);
AuthorizationRequest authReq = new AuthorizationRequest();
isAuthorizationRequestSent = true;
return authReq;
}
public void processAuthorizationResponse(AuthorizationResponse
response, Contact sourceContact)
{
synchronized(this)
{
isAuthorizationResponseReceived = true;
this.response = response;
logger.trace("processAuthorizationResponse '" +
response.getResponseCode().getCode() + " " +
sourceContact);
notifyAll();
}
}
public void waitForAuthResponse(long waitFor)
{
synchronized(this)
{
if(isAuthorizationResponseReceived)
{
logger.debug("authorization response already received");
return;
}
try{
wait(waitFor);
}
catch (InterruptedException ex)
{
logger.debug(
"Interrupted while waiting for a subscription evt", ex);
}
}
}
public void waitForAuthRequest(long waitFor)
{
synchronized(this)
{
if(isAuthorizationRequestReceived)
{
logger.debug("authorization request already received");
return;
}
try{
wait(waitFor);
}
catch (InterruptedException ex)
{
logger.debug(
"Interrupted while waiting for a subscription evt", ex);
}
}
}
}
}
| lgpl-2.1 |
shailendrairis/TikiWiki12.2 | lib/core/Tracker/Field/GeographicFeature.php | 2060 | <?php
// (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id: GeographicFeature.php 46458 2013-06-25 17:06:31Z lphuberdeau $
/**
* Handler class for geographic features (points, lines, polygons)
*
* Letter key: ~GF~
*
*/
class Tracker_Field_GeographicFeature extends Tracker_Field_Abstract implements Tracker_Field_Synchronizable, Tracker_Field_Indexable
{
public static function getTypes()
{
return array(
'GF' => array(
'name' => tr('Geographic Feature'),
'description' => tr('Stores a geographic feature on a map.'),
'help' => 'Location Tracker Field',
'prefs' => array('trackerfield_geographicfeature'),
'tags' => array('advanced'),
'default' => 'n',
'params' => array(
),
),
);
}
function getFieldData(array $requestData = array())
{
if (isset($requestData[$this->getInsertId()])) {
$value = $requestData[$this->getInsertId()];
} else {
$value = $this->getValue();
}
return array(
'value' => $value,
);
}
function renderInput($context = array())
{
return tr('Feature cannot be set or modified through this interface.');
}
function renderOutput($context = array())
{
return tr('Feature cannot be viewed.');
}
function importRemote($value)
{
return $value;
}
function exportRemote($value)
{
return $value;
}
function importRemoteField(array $info, array $syncInfo)
{
return $info;
}
function getDocumentPart(Search_Type_Factory_Interface $typeFactory)
{
return array(
'geo_located' => $typeFactory->identifier('y'),
'geo_feature' => $typeFactory->identifier($this->getValue()),
'geo_feature_field' => $typeFactory->identifier($this->getConfiguration('permName')),
);
}
function getProvidedFields()
{
return array('geo_located', 'geo_feature', 'geo_feature_field');
}
function getGlobalFields()
{
return array();
}
}
| lgpl-2.1 |
gunnarmorling/hibernate-ogm | core/src/main/java/org/hibernate/ogm/options/shared/spi/IndexOption.java | 954 | /*
* Hibernate OGM, Domain model persistence for NoSQL datastores
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.ogm.options.shared.spi;
/**
* Options specific to the datastore for a given index.
*
* @author Guillaume Smet
*/
public class IndexOption {
/**
* The target index name.
*/
private String targetIndexName;
/**
* The index options. Typically, might be a JSON object.
*/
private String options;
IndexOption() {
}
IndexOption(String targetIndexName) {
this.targetIndexName = targetIndexName;
}
IndexOption(org.hibernate.ogm.options.shared.IndexOption annotation) {
this( annotation.forIndex() );
this.options = annotation.options();
}
public String getTargetIndexName() {
return targetIndexName;
}
public String getOptions() {
return options;
}
}
| lgpl-2.1 |
LLNL/spack | var/spack/repos/builtin/packages/libgpuarray/package.py | 1533 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Libgpuarray(CMakePackage):
"""Make a common GPU ndarray(n dimensions array) that can be reused by all
projects that is as future proof as possible, while keeping it easy to use
for simple need/quick test."""
homepage = "https://github.com/Theano/libgpuarray"
url = "https://github.com/Theano/libgpuarray/archive/v0.6.1.tar.gz"
version('0.7.6', sha256='ad1c00dd47c3d36ee1708e5167377edbfcdb7226e837ef9c68b841afbb4a4f6a')
version('0.7.5', sha256='39c4d2e743848be43c8819c736e089ae51b11aa446cc6ee05af945c2dfd63420')
version('0.7.2', sha256='ef11ee6f8d62d53831277fd3dcab662aa770a5b5de2d30fe3018c4af959204da')
version('0.7.1', sha256='4d0f9dd63b0595a8c04d8cee91b2619847c033b011c71d776caa784322382ed6')
version('0.7.0', sha256='afe7907435dcbf78b3ea9b9f6c97e5a0d4a219a7170f5025ca0db1c289bb88df')
version('0.6.9', sha256='689716feecb4e495f4d383ec1518cf3ba70a2a642a903cc445b6b6ffc119bc25')
version('0.6.2', sha256='04756c6270c0ce3b91a9bf01be38c4fc743f5356acc18d9f807198021677bcc8')
version('0.6.1', sha256='b2466311e0e3bacdf7a586bba0263f6d232bf9f8d785e91ddb447653741e6ea5')
version('0.6.0', sha256='a58a0624e894475a4955aaea25e82261c69b4d22c8f15ec07041a4ba176d35af')
depends_on('cuda')
depends_on('cmake@3:', type='build')
depends_on('check')
| lgpl-2.1 |
evolvedmicrobe/beast-mcmc | src/dr/evomodel/treelikelihood/LikelihoodScalingProvider.java | 1226 | /*
* LikelihoodScalingProvider.java
*
* Copyright (c) 2002-2014 Alexei Drummond, Andrew Rambaut and Marc Suchard
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* BEAST 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 BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.evomodel.treelikelihood;
/**
* @author Marc A. Suchard
*/
public interface LikelihoodScalingProvider {
void getLogScalingFactors(int nodeNumber, double[] buffer);
boolean arePartialsRescaled();
}
| lgpl-2.1 |
LLNL/spack | var/spack/repos/builtin/packages/perl-devel-stacktrace/package.py | 563 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PerlDevelStacktrace(PerlPackage):
"""An object representing a stack trace."""
homepage = "https://metacpan.org/pod/Devel::StackTrace"
url = "http://search.cpan.org/CPAN/authors/id/D/DR/DROLSKY/Devel-StackTrace-2.02.tar.gz"
version('2.02', sha256='cbbd96db0ecf194ed140198090eaea0e327d9a378a4aa15f9a34b3138a91931f')
| lgpl-2.1 |
bonahona/ShellCms | ShellLib/Core/ModelProxy.php | 822 | <?php
// Class built to act as a proxy for models containing foreign keys to other objects.
// This is built to whenever a model with references is loaded it does not have to actually load all other objects from db
// but their info is stored so they can be loaded upon request
class ModelProxy
{
public $FieldName;
public $PrimaryKey;
public $Model;
public $Object;
function __construct($fieldName, $model)
{
$this->FieldName = $fieldName;
$this->PrimaryKey = null;
$this->Model = $model;
$this->Object = null;
}
public function Load()
{
if($this->PrimaryKey == null || $this->Model == null){
return;
}
if($this->Object == null){
$this->Object = $this->Model->Find($this->PrimaryKey);
}
}
} | lgpl-3.0 |
diamondo25/MultiShark | ScriptDotNet/CustomFunctions/AppendFunc.cs | 903 | using System;
using System.Collections.Generic;
using System.Text;
using Irony.Compiler;
using ScriptNET.Runtime;
using ScriptNET.Ast;
namespace ScriptNET.CustomFunctions
{
internal class AppendFunc : IInvokable
{
public static AppendFunc FunctionDefinition = new AppendFunc();
public static string FunctionName = "AppendAst";
private AppendFunc()
{
}
#region IInvokable Members
public bool CanInvoke()
{
return true;
}
public object Invoke(IScriptContext context, object[] args)
{
ScriptProg node = (ScriptProg)args[0];
//Get Prog
AstNode prog = node.Parent;
while (prog != null && !(prog is ScriptProg))
prog = prog.Parent;
foreach (ScriptAst scriptnode in node.Elements.ChildNodes)
{
prog.ChildNodes[0].ChildNodes.Add(scriptnode);
}
return node;
}
#endregion
}
}
| lgpl-3.0 |
vvelikodny/go-ethereum | vendor/github.com/elastic/gosigar/sigar_windows.go | 12282 | // Copyright (c) 2012 VMware, Inc.
package gosigar
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"syscall"
"time"
"github.com/StackExchange/wmi"
"github.com/elastic/gosigar/sys/windows"
"github.com/pkg/errors"
)
// Win32_Process represents a process on the Windows operating system. If
// additional fields are added here (that match the Windows struct) they will
// automatically be populated when calling getWin32Process.
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa394372(v=vs.85).aspx
type Win32_Process struct {
CommandLine string
}
// Win32_OperatingSystem WMI class represents a Windows-based operating system
// installed on a computer.
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa394239(v=vs.85).aspx
type Win32_OperatingSystem struct {
LastBootUpTime time.Time
}
var (
// version is Windows version of the host OS.
version = windows.GetWindowsVersion()
// processQueryLimitedInfoAccess is set to PROCESS_QUERY_INFORMATION for Windows
// 2003 and XP where PROCESS_QUERY_LIMITED_INFORMATION is unknown. For all newer
// OS versions it is set to PROCESS_QUERY_LIMITED_INFORMATION.
processQueryLimitedInfoAccess = windows.PROCESS_QUERY_LIMITED_INFORMATION
// bootTime is the time when the OS was last booted. This value may be nil
// on operating systems that do not support the WMI query used to obtain it.
bootTime *time.Time
bootTimeLock sync.Mutex
)
func init() {
if !version.IsWindowsVistaOrGreater() {
// PROCESS_QUERY_LIMITED_INFORMATION cannot be used on 2003 or XP.
processQueryLimitedInfoAccess = syscall.PROCESS_QUERY_INFORMATION
}
}
func (self *LoadAverage) Get() error {
return ErrNotImplemented{runtime.GOOS}
}
func (self *FDUsage) Get() error {
return ErrNotImplemented{runtime.GOOS}
}
func (self *ProcEnv) Get(pid int) error {
return ErrNotImplemented{runtime.GOOS}
}
func (self *ProcExe) Get(pid int) error {
return ErrNotImplemented{runtime.GOOS}
}
func (self *ProcFDUsage) Get(pid int) error {
return ErrNotImplemented{runtime.GOOS}
}
func (self *Uptime) Get() error {
// Minimum supported OS is Windows Vista.
if !version.IsWindowsVistaOrGreater() {
return ErrNotImplemented{runtime.GOOS}
}
bootTimeLock.Lock()
defer bootTimeLock.Unlock()
if bootTime == nil {
os, err := getWin32OperatingSystem()
if err != nil {
return errors.Wrap(err, "failed to get boot time using WMI")
}
bootTime = &os.LastBootUpTime
}
self.Length = time.Since(*bootTime).Seconds()
return nil
}
func (self *Mem) Get() error {
memoryStatusEx, err := windows.GlobalMemoryStatusEx()
if err != nil {
return errors.Wrap(err, "GlobalMemoryStatusEx failed")
}
self.Total = memoryStatusEx.TotalPhys
self.Free = memoryStatusEx.AvailPhys
self.Used = self.Total - self.Free
self.ActualFree = self.Free
self.ActualUsed = self.Used
return nil
}
func (self *Swap) Get() error {
memoryStatusEx, err := windows.GlobalMemoryStatusEx()
if err != nil {
return errors.Wrap(err, "GlobalMemoryStatusEx failed")
}
self.Total = memoryStatusEx.TotalPageFile
self.Free = memoryStatusEx.AvailPageFile
self.Used = self.Total - self.Free
return nil
}
func (self *Cpu) Get() error {
idle, kernel, user, err := windows.GetSystemTimes()
if err != nil {
return errors.Wrap(err, "GetSystemTimes failed")
}
// CPU times are reported in milliseconds by gosigar.
self.Idle = uint64(idle / time.Millisecond)
self.Sys = uint64(kernel / time.Millisecond)
self.User = uint64(user / time.Millisecond)
return nil
}
func (self *CpuList) Get() error {
cpus, err := windows.NtQuerySystemProcessorPerformanceInformation()
if err != nil {
return errors.Wrap(err, "NtQuerySystemProcessorPerformanceInformation failed")
}
self.List = make([]Cpu, 0, len(cpus))
for _, cpu := range cpus {
self.List = append(self.List, Cpu{
Idle: uint64(cpu.IdleTime / time.Millisecond),
Sys: uint64(cpu.KernelTime / time.Millisecond),
User: uint64(cpu.UserTime / time.Millisecond),
})
}
return nil
}
func (self *FileSystemList) Get() error {
drives, err := windows.GetLogicalDriveStrings()
if err != nil {
return errors.Wrap(err, "GetLogicalDriveStrings failed")
}
for _, drive := range drives {
dt, err := windows.GetDriveType(drive)
if err != nil {
return errors.Wrapf(err, "GetDriveType failed")
}
self.List = append(self.List, FileSystem{
DirName: drive,
DevName: drive,
TypeName: dt.String(),
})
}
return nil
}
// Get retrieves a list of all process identifiers (PIDs) in the system.
func (self *ProcList) Get() error {
pids, err := windows.EnumProcesses()
if err != nil {
return errors.Wrap(err, "EnumProcesses failed")
}
// Convert uint32 PIDs to int.
self.List = make([]int, 0, len(pids))
for _, pid := range pids {
self.List = append(self.List, int(pid))
}
return nil
}
func (self *ProcState) Get(pid int) error {
var errs []error
var err error
self.Name, err = getProcName(pid)
if err != nil {
errs = append(errs, errors.Wrap(err, "getProcName failed"))
}
self.State, err = getProcStatus(pid)
if err != nil {
errs = append(errs, errors.Wrap(err, "getProcStatus failed"))
}
self.Ppid, err = getParentPid(pid)
if err != nil {
errs = append(errs, errors.Wrap(err, "getParentPid failed"))
}
self.Username, err = getProcCredName(pid)
if err != nil {
errs = append(errs, errors.Wrap(err, "getProcCredName failed"))
}
if len(errs) > 0 {
errStrs := make([]string, 0, len(errs))
for _, e := range errs {
errStrs = append(errStrs, e.Error())
}
return errors.New(strings.Join(errStrs, "; "))
}
return nil
}
// getProcName returns the process name associated with the PID.
func getProcName(pid int) (string, error) {
handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess, false, uint32(pid))
if err != nil {
return "", errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
}
defer syscall.CloseHandle(handle)
filename, err := windows.GetProcessImageFileName(handle)
if err != nil {
return "", errors.Wrapf(err, "GetProcessImageFileName failed for pid=%v", pid)
}
return filepath.Base(filename), nil
}
// getProcStatus returns the status of a process.
func getProcStatus(pid int) (RunState, error) {
handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess, false, uint32(pid))
if err != nil {
return RunStateUnknown, errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
}
defer syscall.CloseHandle(handle)
var exitCode uint32
err = syscall.GetExitCodeProcess(handle, &exitCode)
if err != nil {
return RunStateUnknown, errors.Wrapf(err, "GetExitCodeProcess failed for pid=%v")
}
if exitCode == 259 { //still active
return RunStateRun, nil
}
return RunStateSleep, nil
}
// getParentPid returns the parent process ID of a process.
func getParentPid(pid int) (int, error) {
handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess, false, uint32(pid))
if err != nil {
return RunStateUnknown, errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
}
defer syscall.CloseHandle(handle)
procInfo, err := windows.NtQueryProcessBasicInformation(handle)
if err != nil {
return 0, errors.Wrapf(err, "NtQueryProcessBasicInformation failed for pid=%v", pid)
}
return int(procInfo.InheritedFromUniqueProcessID), nil
}
func getProcCredName(pid int) (string, error) {
handle, err := syscall.OpenProcess(syscall.PROCESS_QUERY_INFORMATION, false, uint32(pid))
if err != nil {
return "", errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
}
defer syscall.CloseHandle(handle)
// Find process token via win32.
var token syscall.Token
err = syscall.OpenProcessToken(handle, syscall.TOKEN_QUERY, &token)
if err != nil {
return "", errors.Wrapf(err, "OpenProcessToken failed for pid=%v", pid)
}
// Find the token user.
tokenUser, err := token.GetTokenUser()
if err != nil {
return "", errors.Wrapf(err, "GetTokenInformation failed for pid=%v", pid)
}
// Close token to prevent handle leaks.
err = token.Close()
if err != nil {
return "", errors.Wrapf(err, "failed while closing process token handle for pid=%v", pid)
}
// Look up domain account by SID.
account, domain, _, err := tokenUser.User.Sid.LookupAccount("")
if err != nil {
sid, sidErr := tokenUser.User.Sid.String()
if sidErr != nil {
return "", errors.Wrapf(err, "failed while looking up account name for pid=%v", pid)
}
return "", errors.Wrapf(err, "failed while looking up account name for SID=%v of pid=%v", sid, pid)
}
return fmt.Sprintf(`%s\%s`, domain, account), nil
}
func (self *ProcMem) Get(pid int) error {
handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess|windows.PROCESS_VM_READ, false, uint32(pid))
if err != nil {
return errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
}
defer syscall.CloseHandle(handle)
counters, err := windows.GetProcessMemoryInfo(handle)
if err != nil {
return errors.Wrapf(err, "GetProcessMemoryInfo failed for pid=%v", pid)
}
self.Resident = uint64(counters.WorkingSetSize)
self.Size = uint64(counters.PrivateUsage)
return nil
}
func (self *ProcTime) Get(pid int) error {
cpu, err := getProcTimes(pid)
if err != nil {
return err
}
// Windows epoch times are expressed as time elapsed since midnight on
// January 1, 1601 at Greenwich, England. This converts the Filetime to
// unix epoch in milliseconds.
self.StartTime = uint64(cpu.CreationTime.Nanoseconds() / 1e6)
// Convert to millis.
self.User = uint64(windows.FiletimeToDuration(&cpu.UserTime).Nanoseconds() / 1e6)
self.Sys = uint64(windows.FiletimeToDuration(&cpu.KernelTime).Nanoseconds() / 1e6)
self.Total = self.User + self.Sys
return nil
}
func getProcTimes(pid int) (*syscall.Rusage, error) {
handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess, false, uint32(pid))
if err != nil {
return nil, errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
}
defer syscall.CloseHandle(handle)
var cpu syscall.Rusage
if err := syscall.GetProcessTimes(handle, &cpu.CreationTime, &cpu.ExitTime, &cpu.KernelTime, &cpu.UserTime); err != nil {
return nil, errors.Wrapf(err, "GetProcessTimes failed for pid=%v", pid)
}
return &cpu, nil
}
func (self *ProcArgs) Get(pid int) error {
// The minimum supported client for Win32_Process is Windows Vista.
if !version.IsWindowsVistaOrGreater() {
return ErrNotImplemented{runtime.GOOS}
}
process, err := getWin32Process(int32(pid))
if err != nil {
return errors.Wrapf(err, "ProcArgs failed for pid=%v", pid)
}
self.List = []string{process.CommandLine}
return nil
}
func (self *FileSystemUsage) Get(path string) error {
freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes, err := windows.GetDiskFreeSpaceEx(path)
if err != nil {
return errors.Wrap(err, "GetDiskFreeSpaceEx failed")
}
self.Total = totalNumberOfBytes
self.Free = totalNumberOfFreeBytes
self.Used = self.Total - self.Free
self.Avail = freeBytesAvailable
return nil
}
// getWin32Process gets information about the process with the given process ID.
// It uses a WMI query to get the information from the local system.
func getWin32Process(pid int32) (Win32_Process, error) {
var dst []Win32_Process
query := fmt.Sprintf("WHERE ProcessId = %d", pid)
q := wmi.CreateQuery(&dst, query)
err := wmi.Query(q, &dst)
if err != nil {
return Win32_Process{}, fmt.Errorf("could not get Win32_Process %s: %v", query, err)
}
if len(dst) < 1 {
return Win32_Process{}, fmt.Errorf("could not get Win32_Process %s: Process not found", query)
}
return dst[0], nil
}
func getWin32OperatingSystem() (Win32_OperatingSystem, error) {
var dst []Win32_OperatingSystem
q := wmi.CreateQuery(&dst, "")
err := wmi.Query(q, &dst)
if err != nil {
return Win32_OperatingSystem{}, errors.Wrap(err, "wmi query for Win32_OperatingSystem failed")
}
if len(dst) != 1 {
return Win32_OperatingSystem{}, errors.New("wmi query for Win32_OperatingSystem failed")
}
return dst[0], nil
}
func (self *Rusage) Get(who int) error {
if who != 0 {
return ErrNotImplemented{runtime.GOOS}
}
pid := os.Getpid()
cpu, err := getProcTimes(pid)
if err != nil {
return err
}
self.Utime = windows.FiletimeToDuration(&cpu.UserTime)
self.Stime = windows.FiletimeToDuration(&cpu.KernelTime)
return nil
}
| lgpl-3.0 |
MrNuggelz/EnderIO | src/main/java/crazypants/enderio/machine/invpanel/server/AbstractInventory.java | 2342 | package crazypants.enderio.machine.invpanel.server;
import net.minecraft.item.ItemStack;
abstract class AbstractInventory {
static final SlotKey[] NO_SLOTS = new SlotKey[0];
SlotKey[] slotKeys = NO_SLOTS;
protected void setEmpty(InventoryDatabaseServer db) {
if (slotKeys.length != 0) {
reset(db, 0);
}
}
protected void reset(InventoryDatabaseServer db, int count) {
for (SlotKey slotKey : slotKeys) {
if(slotKey != null) {
slotKey.remove(db);
}
}
slotKeys = new SlotKey[count];
}
protected void updateSlot(InventoryDatabaseServer db, int slot, ItemStack stack) {
if (stack == null) {
emptySlot(db, slot);
} else {
updateSlot(db, slot, stack, stack.stackSize);
}
}
protected void updateSlot(InventoryDatabaseServer db, int slot, ItemStack stack, int count) {
SlotKey slotKey = slotKeys[slot];
ItemEntry current = slotKey != null ? slotKey.item : null;
ItemEntry key = db.lookupItem(stack, current, true);
if (key != current) {
updateSlotKey(db, slot, slotKey, key, count);
} else if (slotKey != null && slotKey.count != count) {
slotKey.count = count;
db.entryChanged(current);
}
}
protected void emptySlot(InventoryDatabaseServer db, int slot) {
SlotKey slotKey = slotKeys[slot];
if (slotKey != null) {
slotKey.remove(db);
slotKeys[slot] = null;
}
}
private void updateSlotKey(InventoryDatabaseServer db, int slot, SlotKey slotKey, ItemEntry key, int count) {
if (slotKey != null) {
slotKey.remove(db);
slotKey = null;
}
if (key != null) {
slotKey = new SlotKey(this, slot, key, count);
key.addSlot(slotKey);
db.entryChanged(key);
}
slotKeys[slot] = slotKey;
}
protected void updateCount(InventoryDatabaseServer db, int slot, ItemEntry entry, int count) {
SlotKey slotKey = slotKeys[slot];
if (slotKey != null && slotKey.count != count && slotKey.item == entry) {
if (count == 0) {
slotKey.remove(db);
slotKeys[slot] = null;
} else {
slotKey.count = count;
db.entryChanged(slotKey.item);
}
}
}
abstract int scanInventory(InventoryDatabaseServer db);
abstract int extractItem(InventoryDatabaseServer db, ItemEntry entry, int slot, int count);
}
| unlicense |
puramshetty/sakai | site-manage/site-manage-group-helper/tool/src/java/org/sakaiproject/site/tool/helper/managegroup/impl/SiteManageGroupHandler.java | 15327 | package org.sakaiproject.site.tool.helper.managegroup.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.authz.api.AuthzGroupService;
import org.sakaiproject.authz.api.Member;
import org.sakaiproject.authz.api.Role;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.event.cover.EventTrackingService;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.site.util.Participant;
import org.sakaiproject.site.util.SiteConstants;
import org.sakaiproject.site.util.SiteParticipantHelper;
import org.sakaiproject.site.util.GroupHelper;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.tool.api.ToolSession;
import uk.org.ponder.messageutil.TargettedMessage;
import uk.org.ponder.messageutil.TargettedMessageList;
/**
*
* @author
*
*/
public class SiteManageGroupHandler {
/** Our log (commons). */
private static final Log M_log = LogFactory.getLog(SiteManageGroupHandler.class);
private Collection<Member> groupMembers;
private final GroupComparator groupComparator = new GroupComparator();
public Site site = null;
public SiteService siteService = null;
public AuthzGroupService authzGroupService = null;
public ToolManager toolManager = null;
public SessionManager sessionManager = null;
public ServerConfigurationService serverConfigurationService;
private List<Group> groups = null;
public String memberList = "";
public boolean update = false;
public boolean done = false;
public String[] selectedGroupMembers = new String[]{};
public String[] selectedSiteMembers = new String[]{};
private final String HELPER_ID = "sakai.tool.helper.id";
private final String GROUP_DELETE = "group.delete";
private final String SITE_RESET = "group.reset";
// Tool session attribute name used to schedule a whole page refresh.
public static final String ATTR_TOP_REFRESH = "sakai.vppa.top.refresh";
public TargettedMessageList messages;
public void setMessages(TargettedMessageList messages) {
this.messages = messages;
}
/**
* reset the message list
*/
private void resetTargettedMessageList()
{
this.messages = new TargettedMessageList();
}
// the group title
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
// group title
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
// group description
private String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
// for those to be deleted groups
public String[] deleteGroupIds;
/**
* reset the variables
*/
public void resetParams()
{
// SAK-29645 - preserve user input
if( messages.size() == 0 )
{
id = "";
title = "";
description ="";
deleteGroupIds=new String[]{};
selectedGroupMembers = new String[]{};
selectedSiteMembers = new String[]{};
}
}
/**
* Gets the groups for the current site
* @return Map of groups (id, group)
*/
public List<Group> getGroups() {
if (site == null) {
init();
}
if (update) {
groups = new ArrayList<>();
if (site != null)
{
// only show groups created by WSetup tool itself
Collection allGroups = (Collection) site.getGroups();
for (Iterator gIterator = allGroups.iterator(); gIterator.hasNext();) {
Group gNext = (Group) gIterator.next();
String gProp = gNext.getProperties().getProperty(Group.GROUP_PROP_WSETUP_CREATED);
if (gProp != null && gProp.equals(Boolean.TRUE.toString())) {
groups.add(gNext);
}
}
}
}
Collections.sort( groups, groupComparator );
return groups;
}
/**
* Initialization method, just gets the current site in preperation for other calls
*
*/
public void init() {
if (site == null) {
String siteId = null;
try {
siteId = sessionManager.getCurrentToolSession()
.getAttribute(HELPER_ID + ".siteId").toString();
}
catch (java.lang.NullPointerException npe) {
// Site ID wasn't set in the helper call!!
}
if (siteId == null) {
siteId = toolManager.getCurrentPlacement().getContext();
}
try {
site = siteService.getSite(siteId);
update = siteService.allowUpdateSite(site.getId()) || siteService.allowUpdateGroupMembership(site.getId());
} catch (IdUnusedException e) {
// The siteId we were given was bogus
M_log.warn( e );
}
}
title = "";
if (groupMembers == null)
{
groupMembers = new ArrayList<>();
}
}
/**
* Wrapper around siteService to save a site
* @param site
* @throws IdUnusedException
* @throws PermissionException
*/
public void saveSite(Site site) throws IdUnusedException, PermissionException {
siteService.save(site);
}
public List<Participant> getSiteParticipant(Group group)
{
List<Participant> rv = new ArrayList<>();
if (site != null)
{
String siteId = site.getId();
String realmId = siteService.siteReference(siteId);
List<String> providerCourseList = SiteParticipantHelper.getProviderCourseList(siteId);
Collection<Participant> rvCopy = SiteParticipantHelper.prepareParticipants(siteId, providerCourseList);
// check with group attendents
if (group != null)
{
// need to remove those inside group already
for(Participant p:rvCopy)
{
if (p.getUniqname() != null && group.getMember(p.getUniqname()) == null)
{
rv.add(p);
}
}
}
else
{
// if the group is null, add all site members
rv.addAll(rvCopy);
}
}
return rv;
}
public Collection<Member> getGroupParticipant()
{
return groupMembers;
}
/**
* Allows the Cancel button to return control to the tool calling this helper
*
* @return status
*/
public String processCancel() {
// reset the warning messages
resetTargettedMessageList();
ToolSession session = sessionManager.getCurrentToolSession();
session.setAttribute(ATTR_TOP_REFRESH, Boolean.TRUE);
return "done";
}
/**
* Cancel out of the current action and go back to main view
*
* @return status
*/
public String processBack() {
// reset the warning messages
resetTargettedMessageList();
return "cancel";
}
public String reset() {
try {
siteService.save(site);
EventTrackingService.post(
EventTrackingService.newEvent(SITE_RESET, "/site/" + site.getId(), false));
}
catch (IdUnusedException | PermissionException e) {
M_log.warn( e );
}
return "";
}
/**
* Adds a new group to the current site, or edits an existing group
* @return "success" if group was added/edited, null if something went wrong
*/
public String processAddGroup () {
// reset the warning messages
resetTargettedMessageList();
Group group;
id = StringUtils.trimToNull(id);
title = StringUtils.trimToNull(title);
if (title == null)
{
//we need something in the title field SAK-21517
messages.addMessage(new TargettedMessage("editgroup.titlemissing",new Object[]{}, TargettedMessage.SEVERITY_ERROR));
return null;
}
else if (title.length() > SiteConstants.SITE_GROUP_TITLE_LIMIT)
{
messages.addMessage(new TargettedMessage("site_group_title_length_limit",new Object[] { String.valueOf(SiteConstants.SITE_GROUP_TITLE_LIMIT) }, TargettedMessage.SEVERITY_ERROR));
return null;
}
else
{
String sameTitleGroupId = GroupHelper.getSiteGroupByTitle(site, title);
// "id" will be null if adding a new group, otherwise it will be the id of the group being edited
if (!sameTitleGroupId.isEmpty() && (id == null || !sameTitleGroupId.equals(id)))
{
messages.addMessage(new TargettedMessage("group.title.same", null, TargettedMessage.SEVERITY_ERROR));
return null;
}
}
if (id != null)
{
// editing existing group
group = site.getGroup(id);
}
else
{
// adding a new group
group= site.addGroup();
group.getProperties().addProperty(Group.GROUP_PROP_WSETUP_CREATED, Boolean.TRUE.toString());
}
if (group != null)
{
group.setTitle(title);
group.setDescription(description);
boolean found;
// remove those no longer included in the group
Set members = group.getMembers();
String[] membersSelected = memberList.split("##");
for (Iterator iMembers = members.iterator(); iMembers
.hasNext();) {
found = false;
String mId = ((Member) iMembers.next()).getUserId();
for (int i = 0; !found && i < membersSelected.length; i++)
{
if (mId.equals(membersSelected[i])) {
found = true;
}
}
if (!found) {
group.removeMember(mId);
}
}
// add those seleted members
for( String memberId : membersSelected )
{
memberId = StringUtils.trimToNull(memberId);
if (memberId != null && group.getUserRole(memberId) == null) {
Role r = site.getUserRole(memberId);
Member m = site.getMember(memberId);
Role memberRole = m != null ? m.getRole() : null;
// for every member added through the "Manage
// Groups" interface, he should be defined as
// non-provided
// get role first from site definition.
// However, if the user is inactive, getUserRole would return null; then use member role instead
group.addMember(memberId, r != null ? r.getId()
: memberRole != null? memberRole.getId() : "", m != null ? m.isActive() : true,
false);
}
}
// save the changes
try
{
siteService.save(site);
// reset the form params
resetParams();
}
catch (IdUnusedException | PermissionException e) {
M_log.warn(this + ".processAddGroup: cannot find site " + site.getId(), e);
return null;
}
}
return "success";
}
public String processConfirmGroupDelete()
{
// reset the warning messages
resetTargettedMessageList();
if (deleteGroupIds == null || deleteGroupIds.length == 0)
{
// no group chosen to be deleted
M_log.debug(this + ".processConfirmGroupDelete: no group chosen to be deleted.");
messages.addMessage(new TargettedMessage("delete_group_nogroup","no group chosen"));
return null;
}
else
{
List<Group> groups = new ArrayList<>();
for( String groupId : deleteGroupIds )
{
//
Group g = site.getGroup(groupId);
groups.add(g);
}
return "confirm";
}
}
public String processDeleteGroups()
{
// reset the warning messages
resetTargettedMessageList();
if (site != null)
{
for( String groupId : deleteGroupIds )
{
Group g = site.getGroup(groupId);
if (g != null) {
site.removeGroup(g);
}
}
try {
siteService.save(site);
} catch (IdUnusedException e) {
messages.addMessage(new TargettedMessage("editgroup.site.notfound.alert","cannot find site"));
M_log.warn(this + ".processDeleteGroups: Problem of saving site after group removal: site id =" + site.getId(), e);
} catch (PermissionException e) {
messages.addMessage(new TargettedMessage("editgroup.site.permission.alert","not allowed to find site"));
M_log.warn(this + ".processDeleteGroups: Permission problem of saving site after group removal: site id=" + site.getId(), e);
}
}
return "success";
}
public String processCancelDelete()
{
// reset the warning messages
resetTargettedMessageList();
return "cancel";
}
/**
* Removes a group from the site
*
* @param groupId
* @return title of page removed
* @throws IdUnusedException
* @throws PermissionException
*/
public String removeGroup(String groupId)
throws IdUnusedException, PermissionException {
Group group = site.getGroup(groupId);
site.removeGroup(group);
saveSite(site);
EventTrackingService.post(
EventTrackingService.newEvent(GROUP_DELETE, "/site/" + site.getId() +
"/group/" + group.getId(), false));
return group.getTitle();
}
public String[] getDeleteGroupIds() {
return deleteGroupIds;
}
public List<Group> getSelectedGroups()
{
List<Group> rv = new ArrayList<>();
if (deleteGroupIds != null && deleteGroupIds.length > 0 && site != null)
{
for( String groupId : deleteGroupIds )
{
Group g = site.getGroup(groupId);
rv.add(g);
}
}
return rv;
}
public void setDeleteGroupIds(String[] deleteGroupIds) {
this.deleteGroupIds = deleteGroupIds;
}
/**
* Gets the current tool
* @return Tool
*/
public Tool getCurrentTool() {
return toolManager.getCurrentTool();
}
/**
** Comparator for sorting Group objects
**/
private class GroupComparator implements Comparator {
public int compare(Object o1, Object o2) {
return ((Group)o1).getTitle().compareToIgnoreCase( ((Group)o2).getTitle() );
}
}
}
| apache-2.0 |
mibo/olingo-odata2 | odata2-lib/odata-fit/src/test/java/org/apache/olingo/odata2/fit/mapping/MapProcessor.java | 5984 | /*******************************************************************************
* 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.olingo.odata2.fit.mapping;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.olingo.odata2.api.edm.EdmProperty;
import org.apache.olingo.odata2.api.ep.EntityProvider;
import org.apache.olingo.odata2.api.ep.EntityProviderWriteProperties;
import org.apache.olingo.odata2.api.exception.ODataException;
import org.apache.olingo.odata2.api.exception.ODataNotFoundException;
import org.apache.olingo.odata2.api.processor.ODataResponse;
import org.apache.olingo.odata2.api.processor.ODataSingleProcessor;
import org.apache.olingo.odata2.api.uri.info.GetEntitySetUriInfo;
import org.apache.olingo.odata2.api.uri.info.GetEntityUriInfo;
import org.apache.olingo.odata2.api.uri.info.GetSimplePropertyUriInfo;
public class MapProcessor extends ODataSingleProcessor {
public static final int RECORD_COUNT = 10;
private final ArrayList<HashMap<String, String>> records = new ArrayList<HashMap<String, String>>();
{
HashMap<String, String> record;
for (int i = 1; i <= RECORD_COUNT; i++) {
record = new HashMap<String, String>();
record.put("P01", "V01." + i);
record.put("P02", "V02." + i);
record.put("P03", "V03." + i);
records.add(record);
}
}
private int indexOf(final String key, final String value) {
for (int i = 0; i < RECORD_COUNT; i++) {
if (records.get(i).containsKey(key) && records.get(i).containsValue(value)) {
return i;
}
}
return -1;
}
@Override
public ODataResponse readEntitySet(final GetEntitySetUriInfo uriInfo, final String contentType)
throws ODataException {
final EntityProviderWriteProperties properties =
EntityProviderWriteProperties.serviceRoot(getContext().getPathInfo().getServiceRoot()).build();
final List<Map<String, Object>> values = new ArrayList<Map<String, Object>>();
for (final HashMap<String, String> record : records) {
final HashMap<String, Object> data = new HashMap<String, Object>();
for (final String pName : uriInfo.getTargetEntitySet().getEntityType().getPropertyNames()) {
final EdmProperty property = (EdmProperty) uriInfo.getTargetEntitySet().getEntityType().getProperty(pName);
final String mappedPropertyName = (String) property.getMapping().getObject();
data.put(pName, record.get(mappedPropertyName));
}
values.add(data);
}
final ODataResponse response =
EntityProvider.writeFeed(contentType, uriInfo.getTargetEntitySet(), values, properties);
return response;
}
@Override
public ODataResponse readEntity(final GetEntityUriInfo uriInfo, final String contentType) throws ODataException {
final EntityProviderWriteProperties properties =
EntityProviderWriteProperties.serviceRoot(getContext().getPathInfo().getServiceRoot()).build();
// query
final String mappedKeyName =
(String) uriInfo.getTargetEntitySet().getEntityType().getKeyProperties().get(0).getMapping().getObject();
final String keyValue = uriInfo.getKeyPredicates().get(0).getLiteral();
final int index = indexOf(mappedKeyName, keyValue);
if ((index < 0) || (index > records.size())) {
throw new ODataNotFoundException(ODataNotFoundException.ENTITY.addContent(keyValue));
}
final HashMap<String, String> record = records.get(index);
final HashMap<String, Object> data = new HashMap<String, Object>();
for (final String pName : uriInfo.getTargetEntitySet().getEntityType().getPropertyNames()) {
final EdmProperty property = (EdmProperty) uriInfo.getTargetEntitySet().getEntityType().getProperty(pName);
final String mappedPropertyName = (String) property.getMapping().getObject();
data.put(pName, record.get(mappedPropertyName));
}
final ODataResponse response =
EntityProvider.writeEntry(contentType, uriInfo.getTargetEntitySet(), data, properties);
return response;
}
@Override
public ODataResponse readEntitySimplePropertyValue(final GetSimplePropertyUriInfo uriInfo, final String contentType)
throws ODataException {
final List<EdmProperty> propertyPath = uriInfo.getPropertyPath();
final EdmProperty property = propertyPath.get(propertyPath.size() - 1);
final String mappedKeyName =
(String) uriInfo.getTargetEntitySet().getEntityType().getKeyProperties().get(0).getMapping().getObject();
final String keyValue = uriInfo.getKeyPredicates().get(0).getLiteral();
final int index = indexOf(mappedKeyName, keyValue);
if ((index < 0) || (index > records.size())) {
throw new ODataNotFoundException(ODataNotFoundException.ENTITY.addContent(keyValue));
}
final HashMap<String, String> record = records.get(index);
final String mappedPropertyName = (String) property.getMapping().getObject();
final Object value = record.get(mappedPropertyName);
final ODataResponse response = EntityProvider.writePropertyValue(property, value);
return response;
}
}
| apache-2.0 |
Intel-tensorflow/tensorflow | tensorflow/lite/testing/op_tests/tile.py | 3079 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Test configs for tile."""
import tensorflow.compat.v1 as tf
from tensorflow.lite.testing.zip_test_utils import create_tensor_data
from tensorflow.lite.testing.zip_test_utils import make_zip_of_tests
from tensorflow.lite.testing.zip_test_utils import register_make_test_function
@register_make_test_function()
def make_tile_tests(options):
"""Make a set of tests to do tile."""
test_parameters = [
{
"input_dtype": [tf.float32, tf.int32, tf.bool, tf.string],
"input_shape": [[3, 2, 1], [2, 2, 2]],
"multiplier_dtype": [tf.int32, tf.int64],
"multiplier_shape": [[3]]
},
{
"input_dtype": [tf.float32, tf.int32],
"input_shape": [[]],
"multiplier_dtype": [tf.int32, tf.int64],
"multiplier_shape": [[0]]
},
{
"input_dtype": [tf.float32],
"input_shape": [[3, 2, 1]],
"multiplier_dtype": [tf.int32, tf.int64],
"multiplier_shape": [[3]],
"fully_quantize": [True],
# The input range is used to create representative dataset for both
# input and multiplier so it needs to be positive.
"input_range": [(1, 10)],
}
]
def build_graph(parameters):
"""Build the tile op testing graph."""
input_value = tf.compat.v1.placeholder(
dtype=parameters["input_dtype"],
shape=parameters["input_shape"],
name="input")
multiplier_value = tf.compat.v1.placeholder(
dtype=parameters["multiplier_dtype"],
shape=parameters["multiplier_shape"],
name="multiplier")
out = tf.tile(input_value, multiplier_value)
return [input_value, multiplier_value], [out]
def build_inputs(parameters, sess, inputs, outputs):
min_value, max_value = parameters.get("input_range", (-10, 10))
input_value = create_tensor_data(
parameters["input_dtype"],
parameters["input_shape"],
min_value=min_value,
max_value=max_value)
multipliers_value = create_tensor_data(
parameters["multiplier_dtype"],
parameters["multiplier_shape"],
min_value=0)
return [input_value, multipliers_value], sess.run(
outputs,
feed_dict={
inputs[0]: input_value,
inputs[1]: multipliers_value
})
make_zip_of_tests(options, test_parameters, build_graph, build_inputs)
| apache-2.0 |
kuujo/onos | protocols/bgp/bgpio/src/test/java/org/onosproject/bgpio/types/IPv4AddressTest.java | 1392 | /*
* Copyright 2015-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 org.onosproject.bgpio.types;
import org.junit.Test;
import org.onlab.packet.Ip4Address;
import com.google.common.testing.EqualsTester;
/**
* Test for IPv4Address Tlv.
*/
public class IPv4AddressTest {
private final Ip4Address value1 = Ip4Address.valueOf("127.0.0.1");
private final Ip4Address value2 = Ip4Address.valueOf("127.0.0.1");
private final IPv4AddressTlv tlv1 = IPv4AddressTlv.of(value1, (short) 259);
private final IPv4AddressTlv sameAsTlv1 = IPv4AddressTlv.of(value1, (short) 259);
private final IPv4AddressTlv tlv2 = IPv4AddressTlv.of(value2, (short) 260);
@Test
public void basics() {
new EqualsTester()
.addEqualityGroup(tlv1, sameAsTlv1)
.addEqualityGroup(tlv2)
.testEquals();
}
}
| apache-2.0 |
msebire/intellij-community | platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/AppEditorFontOptions.java | 3601 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.editor.colors.impl;
import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.editor.colors.EditorFontCache;
import com.intellij.openapi.editor.colors.FontPreferences;
import com.intellij.openapi.editor.colors.ModifiableFontPreferences;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
@State(name = "DefaultFont", storages = @Storage("editor.xml"))
public class AppEditorFontOptions implements PersistentStateComponent<AppEditorFontOptions.PersistentFontPreferences> {
private final FontPreferencesImpl myFontPreferences = new FontPreferencesImpl();
public AppEditorFontOptions() {
myFontPreferences.register(
FontPreferences.DEFAULT_FONT_NAME,
UISettings.restoreFontSize(FontPreferences.DEFAULT_FONT_SIZE, 1.0f));
}
public static class PersistentFontPreferences {
public int FONT_SIZE = FontPreferences.DEFAULT_FONT_SIZE;
public @NotNull String FONT_FAMILY = FontPreferences.DEFAULT_FONT_NAME;
public float FONT_SCALE = 1.0f;
public float LINE_SPACING = FontPreferences.DEFAULT_LINE_SPACING;
public boolean USE_LIGATURES = false;
public @Nullable String SECONDARY_FONT_FAMILY;
/**
* Serialization constructor.
*/
private PersistentFontPreferences() {
}
public PersistentFontPreferences(FontPreferences fontPreferences) {
FONT_FAMILY = fontPreferences.getFontFamily();
FONT_SIZE = fontPreferences.getSize(FONT_FAMILY);
FONT_SCALE = UISettings.getDefFontScale();
LINE_SPACING = fontPreferences.getLineSpacing();
USE_LIGATURES = fontPreferences.useLigatures();
List<String> fontFamilies = fontPreferences.getEffectiveFontFamilies();
if (fontFamilies.size() > 1) {
SECONDARY_FONT_FAMILY = fontFamilies.get(1);
}
}
private static PersistentFontPreferences getDefaultState() {
return new PersistentFontPreferences();
}
}
public static AppEditorFontOptions getInstance() {
return ServiceManager.getService(AppEditorFontOptions.class);
}
@Nullable
@Override
public PersistentFontPreferences getState() {
return new PersistentFontPreferences(myFontPreferences);
}
@Override
public void loadState(@NotNull PersistentFontPreferences state) {
copyState(state, myFontPreferences);
myFontPreferences.setChangeListener(() -> EditorFontCache.getInstance().reset());
}
private static void copyState(PersistentFontPreferences state, @NotNull ModifiableFontPreferences fontPreferences) {
fontPreferences.clear();
int fontSize = UISettings.restoreFontSize(state.FONT_SIZE, state.FONT_SCALE);
fontPreferences.register(state.FONT_FAMILY, fontSize);
fontPreferences.setLineSpacing(state.LINE_SPACING);
fontPreferences.setUseLigatures(state.USE_LIGATURES);
if (state.SECONDARY_FONT_FAMILY != null) {
fontPreferences.register(state.SECONDARY_FONT_FAMILY, fontSize);
}
}
public static void initDefaults(@NotNull ModifiableFontPreferences fontPreferences) {
copyState(PersistentFontPreferences.getDefaultState(), fontPreferences);
}
@NotNull
public FontPreferences getFontPreferences() {
return myFontPreferences;
}
}
| apache-2.0 |
KaranToor/MA450 | google-cloud-sdk/.install/.backup/lib/third_party/pygments/lexers/functional.py | 109035 | # -*- coding: utf-8 -*-
"""
pygments.lexers.functional
~~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for functional languages.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import Lexer, RegexLexer, bygroups, include, do_insertions
from pygments.token import Text, Comment, Operator, Keyword, Name, \
String, Number, Punctuation, Literal, Generic, Error
__all__ = ['RacketLexer', 'SchemeLexer', 'CommonLispLexer', 'HaskellLexer',
'LiterateHaskellLexer', 'SMLLexer', 'OcamlLexer', 'ErlangLexer',
'ErlangShellLexer', 'OpaLexer', 'CoqLexer', 'NewLispLexer',
'ElixirLexer', 'ElixirConsoleLexer', 'KokaLexer']
class RacketLexer(RegexLexer):
"""
Lexer for `Racket <http://racket-lang.org/>`_ source code (formerly known as
PLT Scheme).
*New in Pygments 1.6.*
"""
name = 'Racket'
aliases = ['racket', 'rkt']
filenames = ['*.rkt', '*.rktl']
mimetypes = ['text/x-racket', 'application/x-racket']
# From namespace-mapped-symbols
keywords = [
'#%app', '#%datum', '#%expression', '#%module-begin',
'#%plain-app', '#%plain-lambda', '#%plain-module-begin',
'#%provide', '#%require', '#%stratified-body', '#%top',
'#%top-interaction', '#%variable-reference', '...', 'and', 'begin',
'begin-for-syntax', 'begin0', 'case', 'case-lambda', 'cond',
'datum->syntax-object', 'define', 'define-for-syntax',
'define-struct', 'define-syntax', 'define-syntax-rule',
'define-syntaxes', 'define-values', 'define-values-for-syntax',
'delay', 'do', 'expand-path', 'fluid-let', 'hash-table-copy',
'hash-table-count', 'hash-table-for-each', 'hash-table-get',
'hash-table-iterate-first', 'hash-table-iterate-key',
'hash-table-iterate-next', 'hash-table-iterate-value',
'hash-table-map', 'hash-table-put!', 'hash-table-remove!',
'hash-table?', 'if', 'lambda', 'let', 'let*', 'let*-values',
'let-struct', 'let-syntax', 'let-syntaxes', 'let-values', 'let/cc',
'let/ec', 'letrec', 'letrec-syntax', 'letrec-syntaxes',
'letrec-syntaxes+values', 'letrec-values', 'list-immutable',
'make-hash-table', 'make-immutable-hash-table', 'make-namespace',
'module', 'module-identifier=?', 'module-label-identifier=?',
'module-template-identifier=?', 'module-transformer-identifier=?',
'namespace-transformer-require', 'or', 'parameterize',
'parameterize*', 'parameterize-break', 'provide',
'provide-for-label', 'provide-for-syntax', 'quasiquote',
'quasisyntax', 'quasisyntax/loc', 'quote', 'quote-syntax',
'quote-syntax/prune', 'require', 'require-for-label',
'require-for-syntax', 'require-for-template', 'set!',
'set!-values', 'syntax', 'syntax-case', 'syntax-case*',
'syntax-id-rules', 'syntax-object->datum', 'syntax-rules',
'syntax/loc', 'time', 'transcript-off', 'transcript-on', 'unless',
'unquote', 'unquote-splicing', 'unsyntax', 'unsyntax-splicing',
'when', 'with-continuation-mark', 'with-handlers',
'with-handlers*', 'with-syntax', 'λ'
]
# From namespace-mapped-symbols
builtins = [
'*', '+', '-', '/', '<', '<=', '=', '>', '>=',
'abort-current-continuation', 'abs', 'absolute-path?', 'acos',
'add1', 'alarm-evt', 'always-evt', 'andmap', 'angle', 'append',
'apply', 'arithmetic-shift', 'arity-at-least',
'arity-at-least-value', 'arity-at-least?', 'asin', 'assoc', 'assq',
'assv', 'atan', 'banner', 'bitwise-and', 'bitwise-bit-field',
'bitwise-bit-set?', 'bitwise-ior', 'bitwise-not', 'bitwise-xor',
'boolean?', 'bound-identifier=?', 'box', 'box-immutable', 'box?',
'break-enabled', 'break-thread', 'build-path',
'build-path/convention-type', 'byte-pregexp', 'byte-pregexp?',
'byte-ready?', 'byte-regexp', 'byte-regexp?', 'byte?', 'bytes',
'bytes->immutable-bytes', 'bytes->list', 'bytes->path',
'bytes->path-element', 'bytes->string/latin-1',
'bytes->string/locale', 'bytes->string/utf-8', 'bytes-append',
'bytes-close-converter', 'bytes-convert', 'bytes-convert-end',
'bytes-converter?', 'bytes-copy', 'bytes-copy!', 'bytes-fill!',
'bytes-length', 'bytes-open-converter', 'bytes-ref', 'bytes-set!',
'bytes-utf-8-index', 'bytes-utf-8-length', 'bytes-utf-8-ref',
'bytes<?', 'bytes=?', 'bytes>?', 'bytes?', 'caaaar', 'caaadr',
'caaar', 'caadar', 'caaddr', 'caadr', 'caar', 'cadaar', 'cadadr',
'cadar', 'caddar', 'cadddr', 'caddr', 'cadr',
'call-in-nested-thread', 'call-with-break-parameterization',
'call-with-composable-continuation',
'call-with-continuation-barrier', 'call-with-continuation-prompt',
'call-with-current-continuation', 'call-with-escape-continuation',
'call-with-exception-handler',
'call-with-immediate-continuation-mark', 'call-with-input-file',
'call-with-output-file', 'call-with-parameterization',
'call-with-semaphore', 'call-with-semaphore/enable-break',
'call-with-values', 'call/cc', 'call/ec', 'car', 'cdaaar',
'cdaadr', 'cdaar', 'cdadar', 'cdaddr', 'cdadr', 'cdar', 'cddaar',
'cddadr', 'cddar', 'cdddar', 'cddddr', 'cdddr', 'cddr', 'cdr',
'ceiling', 'channel-get', 'channel-put', 'channel-put-evt',
'channel-try-get', 'channel?', 'chaperone-box', 'chaperone-evt',
'chaperone-hash', 'chaperone-of?', 'chaperone-procedure',
'chaperone-struct', 'chaperone-struct-type', 'chaperone-vector',
'chaperone?', 'char->integer', 'char-alphabetic?', 'char-blank?',
'char-ci<=?', 'char-ci<?', 'char-ci=?', 'char-ci>=?', 'char-ci>?',
'char-downcase', 'char-foldcase', 'char-general-category',
'char-graphic?', 'char-iso-control?', 'char-lower-case?',
'char-numeric?', 'char-punctuation?', 'char-ready?',
'char-symbolic?', 'char-title-case?', 'char-titlecase',
'char-upcase', 'char-upper-case?', 'char-utf-8-length',
'char-whitespace?', 'char<=?', 'char<?', 'char=?', 'char>=?',
'char>?', 'char?', 'check-duplicate-identifier',
'checked-procedure-check-and-extract', 'choice-evt',
'cleanse-path', 'close-input-port', 'close-output-port',
'collect-garbage', 'collection-file-path', 'collection-path',
'compile', 'compile-allow-set!-undefined',
'compile-context-preservation-enabled',
'compile-enforce-module-constants', 'compile-syntax',
'compiled-expression?', 'compiled-module-expression?',
'complete-path?', 'complex?', 'cons',
'continuation-mark-set->context', 'continuation-mark-set->list',
'continuation-mark-set->list*', 'continuation-mark-set-first',
'continuation-mark-set?', 'continuation-marks',
'continuation-prompt-available?', 'continuation-prompt-tag?',
'continuation?', 'copy-file', 'cos',
'current-break-parameterization', 'current-code-inspector',
'current-command-line-arguments', 'current-compile',
'current-continuation-marks', 'current-custodian',
'current-directory', 'current-drive', 'current-error-port',
'current-eval', 'current-evt-pseudo-random-generator',
'current-gc-milliseconds', 'current-get-interaction-input-port',
'current-inexact-milliseconds', 'current-input-port',
'current-inspector', 'current-library-collection-paths',
'current-load', 'current-load-extension',
'current-load-relative-directory', 'current-load/use-compiled',
'current-locale', 'current-memory-use', 'current-milliseconds',
'current-module-declare-name', 'current-module-declare-source',
'current-module-name-resolver', 'current-namespace',
'current-output-port', 'current-parameterization',
'current-preserved-thread-cell-values', 'current-print',
'current-process-milliseconds', 'current-prompt-read',
'current-pseudo-random-generator', 'current-read-interaction',
'current-reader-guard', 'current-readtable', 'current-seconds',
'current-security-guard', 'current-subprocess-custodian-mode',
'current-thread', 'current-thread-group',
'current-thread-initial-stack-size',
'current-write-relative-directory', 'custodian-box-value',
'custodian-box?', 'custodian-limit-memory',
'custodian-managed-list', 'custodian-memory-accounting-available?',
'custodian-require-memory', 'custodian-shutdown-all', 'custodian?',
'custom-print-quotable-accessor', 'custom-print-quotable?',
'custom-write-accessor', 'custom-write?', 'date', 'date*',
'date*-nanosecond', 'date*-time-zone-name', 'date*?', 'date-day',
'date-dst?', 'date-hour', 'date-minute', 'date-month',
'date-second', 'date-time-zone-offset', 'date-week-day',
'date-year', 'date-year-day', 'date?', 'datum-intern-literal',
'default-continuation-prompt-tag', 'delete-directory',
'delete-file', 'denominator', 'directory-exists?',
'directory-list', 'display', 'displayln', 'dump-memory-stats',
'dynamic-require', 'dynamic-require-for-syntax', 'dynamic-wind',
'eof', 'eof-object?', 'ephemeron-value', 'ephemeron?', 'eprintf',
'eq-hash-code', 'eq?', 'equal-hash-code',
'equal-secondary-hash-code', 'equal?', 'equal?/recur',
'eqv-hash-code', 'eqv?', 'error', 'error-display-handler',
'error-escape-handler', 'error-print-context-length',
'error-print-source-location', 'error-print-width',
'error-value->string-handler', 'eval', 'eval-jit-enabled',
'eval-syntax', 'even?', 'evt?', 'exact->inexact', 'exact-integer?',
'exact-nonnegative-integer?', 'exact-positive-integer?', 'exact?',
'executable-yield-handler', 'exit', 'exit-handler', 'exn',
'exn-continuation-marks', 'exn-message', 'exn:break',
'exn:break-continuation', 'exn:break?', 'exn:fail',
'exn:fail:contract', 'exn:fail:contract:arity',
'exn:fail:contract:arity?', 'exn:fail:contract:continuation',
'exn:fail:contract:continuation?',
'exn:fail:contract:divide-by-zero',
'exn:fail:contract:divide-by-zero?',
'exn:fail:contract:non-fixnum-result',
'exn:fail:contract:non-fixnum-result?',
'exn:fail:contract:variable', 'exn:fail:contract:variable-id',
'exn:fail:contract:variable?', 'exn:fail:contract?',
'exn:fail:filesystem', 'exn:fail:filesystem:exists',
'exn:fail:filesystem:exists?', 'exn:fail:filesystem:version',
'exn:fail:filesystem:version?', 'exn:fail:filesystem?',
'exn:fail:network', 'exn:fail:network?', 'exn:fail:out-of-memory',
'exn:fail:out-of-memory?', 'exn:fail:read',
'exn:fail:read-srclocs', 'exn:fail:read:eof', 'exn:fail:read:eof?',
'exn:fail:read:non-char', 'exn:fail:read:non-char?',
'exn:fail:read?', 'exn:fail:syntax', 'exn:fail:syntax-exprs',
'exn:fail:syntax:unbound', 'exn:fail:syntax:unbound?',
'exn:fail:syntax?', 'exn:fail:unsupported',
'exn:fail:unsupported?', 'exn:fail:user', 'exn:fail:user?',
'exn:fail?', 'exn:srclocs-accessor', 'exn:srclocs?', 'exn?', 'exp',
'expand', 'expand-once', 'expand-syntax', 'expand-syntax-once',
'expand-syntax-to-top-form', 'expand-to-top-form',
'expand-user-path', 'expt', 'file-exists?',
'file-or-directory-identity', 'file-or-directory-modify-seconds',
'file-or-directory-permissions', 'file-position', 'file-size',
'file-stream-buffer-mode', 'file-stream-port?',
'filesystem-root-list', 'find-executable-path',
'find-library-collection-paths', 'find-system-path', 'fixnum?',
'floating-point-bytes->real', 'flonum?', 'floor', 'flush-output',
'for-each', 'force', 'format', 'fprintf', 'free-identifier=?',
'gcd', 'generate-temporaries', 'gensym', 'get-output-bytes',
'get-output-string', 'getenv', 'global-port-print-handler',
'guard-evt', 'handle-evt', 'handle-evt?', 'hash', 'hash-equal?',
'hash-eqv?', 'hash-has-key?', 'hash-placeholder?', 'hash-ref!',
'hasheq', 'hasheqv', 'identifier-binding',
'identifier-label-binding', 'identifier-prune-lexical-context',
'identifier-prune-to-source-module',
'identifier-remove-from-definition-context',
'identifier-template-binding', 'identifier-transformer-binding',
'identifier?', 'imag-part', 'immutable?', 'impersonate-box',
'impersonate-hash', 'impersonate-procedure', 'impersonate-struct',
'impersonate-vector', 'impersonator-of?',
'impersonator-prop:application-mark',
'impersonator-property-accessor-procedure?',
'impersonator-property?', 'impersonator?', 'inexact->exact',
'inexact-real?', 'inexact?', 'input-port?', 'inspector?',
'integer->char', 'integer->integer-bytes',
'integer-bytes->integer', 'integer-length', 'integer-sqrt',
'integer-sqrt/remainder', 'integer?',
'internal-definition-context-seal', 'internal-definition-context?',
'keyword->string', 'keyword<?', 'keyword?', 'kill-thread', 'lcm',
'length', 'liberal-define-context?', 'link-exists?', 'list',
'list*', 'list->bytes', 'list->string', 'list->vector', 'list-ref',
'list-tail', 'list?', 'load', 'load-extension',
'load-on-demand-enabled', 'load-relative',
'load-relative-extension', 'load/cd', 'load/use-compiled',
'local-expand', 'local-expand/capture-lifts',
'local-transformer-expand',
'local-transformer-expand/capture-lifts', 'locale-string-encoding',
'log', 'magnitude', 'make-arity-at-least', 'make-bytes',
'make-channel', 'make-continuation-prompt-tag', 'make-custodian',
'make-custodian-box', 'make-date', 'make-date*',
'make-derived-parameter', 'make-directory', 'make-ephemeron',
'make-exn', 'make-exn:break', 'make-exn:fail',
'make-exn:fail:contract', 'make-exn:fail:contract:arity',
'make-exn:fail:contract:continuation',
'make-exn:fail:contract:divide-by-zero',
'make-exn:fail:contract:non-fixnum-result',
'make-exn:fail:contract:variable', 'make-exn:fail:filesystem',
'make-exn:fail:filesystem:exists',
'make-exn:fail:filesystem:version', 'make-exn:fail:network',
'make-exn:fail:out-of-memory', 'make-exn:fail:read',
'make-exn:fail:read:eof', 'make-exn:fail:read:non-char',
'make-exn:fail:syntax', 'make-exn:fail:syntax:unbound',
'make-exn:fail:unsupported', 'make-exn:fail:user',
'make-file-or-directory-link', 'make-hash-placeholder',
'make-hasheq-placeholder', 'make-hasheqv',
'make-hasheqv-placeholder', 'make-immutable-hasheqv',
'make-impersonator-property', 'make-input-port', 'make-inspector',
'make-known-char-range-list', 'make-output-port', 'make-parameter',
'make-pipe', 'make-placeholder', 'make-polar',
'make-prefab-struct', 'make-pseudo-random-generator',
'make-reader-graph', 'make-readtable', 'make-rectangular',
'make-rename-transformer', 'make-resolved-module-path',
'make-security-guard', 'make-semaphore', 'make-set!-transformer',
'make-shared-bytes', 'make-sibling-inspector',
'make-special-comment', 'make-srcloc', 'make-string',
'make-struct-field-accessor', 'make-struct-field-mutator',
'make-struct-type', 'make-struct-type-property',
'make-syntax-delta-introducer', 'make-syntax-introducer',
'make-thread-cell', 'make-thread-group', 'make-vector',
'make-weak-box', 'make-weak-hasheqv', 'make-will-executor', 'map',
'max', 'mcar', 'mcdr', 'mcons', 'member', 'memq', 'memv', 'min',
'module->exports', 'module->imports', 'module->language-info',
'module->namespace', 'module-compiled-exports',
'module-compiled-imports', 'module-compiled-language-info',
'module-compiled-name', 'module-path-index-join',
'module-path-index-resolve', 'module-path-index-split',
'module-path-index?', 'module-path?', 'module-predefined?',
'module-provide-protected?', 'modulo', 'mpair?', 'nack-guard-evt',
'namespace-attach-module', 'namespace-attach-module-declaration',
'namespace-base-phase', 'namespace-mapped-symbols',
'namespace-module-identifier', 'namespace-module-registry',
'namespace-require', 'namespace-require/constant',
'namespace-require/copy', 'namespace-require/expansion-time',
'namespace-set-variable-value!', 'namespace-symbol->identifier',
'namespace-syntax-introduce', 'namespace-undefine-variable!',
'namespace-unprotect-module', 'namespace-variable-value',
'namespace?', 'negative?', 'never-evt', 'newline',
'normal-case-path', 'not', 'null', 'null?', 'number->string',
'number?', 'numerator', 'object-name', 'odd?', 'open-input-bytes',
'open-input-file', 'open-input-output-file', 'open-input-string',
'open-output-bytes', 'open-output-file', 'open-output-string',
'ormap', 'output-port?', 'pair?', 'parameter-procedure=?',
'parameter?', 'parameterization?', 'path->bytes',
'path->complete-path', 'path->directory-path', 'path->string',
'path-add-suffix', 'path-convention-type', 'path-element->bytes',
'path-element->string', 'path-for-some-system?',
'path-list-string->path-list', 'path-replace-suffix',
'path-string?', 'path?', 'peek-byte', 'peek-byte-or-special',
'peek-bytes', 'peek-bytes!', 'peek-bytes-avail!',
'peek-bytes-avail!*', 'peek-bytes-avail!/enable-break',
'peek-char', 'peek-char-or-special', 'peek-string', 'peek-string!',
'pipe-content-length', 'placeholder-get', 'placeholder-set!',
'placeholder?', 'poll-guard-evt', 'port-closed-evt',
'port-closed?', 'port-commit-peeked', 'port-count-lines!',
'port-count-lines-enabled', 'port-display-handler',
'port-file-identity', 'port-file-unlock', 'port-next-location',
'port-print-handler', 'port-progress-evt',
'port-provides-progress-evts?', 'port-read-handler',
'port-try-file-lock?', 'port-write-handler', 'port-writes-atomic?',
'port-writes-special?', 'port?', 'positive?',
'prefab-key->struct-type', 'prefab-struct-key', 'pregexp',
'pregexp?', 'primitive-closure?', 'primitive-result-arity',
'primitive?', 'print', 'print-as-expression',
'print-boolean-long-form', 'print-box', 'print-graph',
'print-hash-table', 'print-mpair-curly-braces',
'print-pair-curly-braces', 'print-reader-abbreviations',
'print-struct', 'print-syntax-width', 'print-unreadable',
'print-vector-length', 'printf', 'procedure->method',
'procedure-arity', 'procedure-arity-includes?', 'procedure-arity?',
'procedure-closure-contents-eq?', 'procedure-extract-target',
'procedure-reduce-arity', 'procedure-rename',
'procedure-struct-type?', 'procedure?', 'promise?',
'prop:arity-string', 'prop:checked-procedure',
'prop:custom-print-quotable', 'prop:custom-write',
'prop:equal+hash', 'prop:evt', 'prop:exn:srclocs',
'prop:impersonator-of', 'prop:input-port',
'prop:liberal-define-context', 'prop:output-port',
'prop:procedure', 'prop:rename-transformer',
'prop:set!-transformer', 'pseudo-random-generator->vector',
'pseudo-random-generator-vector?', 'pseudo-random-generator?',
'putenv', 'quotient', 'quotient/remainder', 'raise',
'raise-arity-error', 'raise-mismatch-error', 'raise-syntax-error',
'raise-type-error', 'raise-user-error', 'random', 'random-seed',
'rational?', 'rationalize', 'read', 'read-accept-bar-quote',
'read-accept-box', 'read-accept-compiled', 'read-accept-dot',
'read-accept-graph', 'read-accept-infix-dot', 'read-accept-lang',
'read-accept-quasiquote', 'read-accept-reader', 'read-byte',
'read-byte-or-special', 'read-bytes', 'read-bytes!',
'read-bytes-avail!', 'read-bytes-avail!*',
'read-bytes-avail!/enable-break', 'read-bytes-line',
'read-case-sensitive', 'read-char', 'read-char-or-special',
'read-curly-brace-as-paren', 'read-decimal-as-inexact',
'read-eval-print-loop', 'read-language', 'read-line',
'read-on-demand-source', 'read-square-bracket-as-paren',
'read-string', 'read-string!', 'read-syntax',
'read-syntax/recursive', 'read/recursive', 'readtable-mapping',
'readtable?', 'real->double-flonum', 'real->floating-point-bytes',
'real->single-flonum', 'real-part', 'real?', 'regexp',
'regexp-match', 'regexp-match-peek', 'regexp-match-peek-immediate',
'regexp-match-peek-positions',
'regexp-match-peek-positions-immediate',
'regexp-match-peek-positions-immediate/end',
'regexp-match-peek-positions/end', 'regexp-match-positions',
'regexp-match-positions/end', 'regexp-match/end', 'regexp-match?',
'regexp-max-lookbehind', 'regexp-replace', 'regexp-replace*',
'regexp?', 'relative-path?', 'remainder',
'rename-file-or-directory', 'rename-transformer-target',
'rename-transformer?', 'resolve-path', 'resolved-module-path-name',
'resolved-module-path?', 'reverse', 'round', 'seconds->date',
'security-guard?', 'semaphore-peek-evt', 'semaphore-post',
'semaphore-try-wait?', 'semaphore-wait',
'semaphore-wait/enable-break', 'semaphore?',
'set!-transformer-procedure', 'set!-transformer?', 'set-box!',
'set-mcar!', 'set-mcdr!', 'set-port-next-location!',
'shared-bytes', 'shell-execute', 'simplify-path', 'sin',
'single-flonum?', 'sleep', 'special-comment-value',
'special-comment?', 'split-path', 'sqrt', 'srcloc',
'srcloc-column', 'srcloc-line', 'srcloc-position', 'srcloc-source',
'srcloc-span', 'srcloc?', 'string', 'string->bytes/latin-1',
'string->bytes/locale', 'string->bytes/utf-8',
'string->immutable-string', 'string->keyword', 'string->list',
'string->number', 'string->path', 'string->path-element',
'string->symbol', 'string->uninterned-symbol',
'string->unreadable-symbol', 'string-append', 'string-ci<=?',
'string-ci<?', 'string-ci=?', 'string-ci>=?', 'string-ci>?',
'string-copy', 'string-copy!', 'string-downcase', 'string-fill!',
'string-foldcase', 'string-length', 'string-locale-ci<?',
'string-locale-ci=?', 'string-locale-ci>?',
'string-locale-downcase', 'string-locale-upcase',
'string-locale<?', 'string-locale=?', 'string-locale>?',
'string-normalize-nfc', 'string-normalize-nfd',
'string-normalize-nfkc', 'string-normalize-nfkd', 'string-ref',
'string-set!', 'string-titlecase', 'string-upcase',
'string-utf-8-length', 'string<=?', 'string<?', 'string=?',
'string>=?', 'string>?', 'string?', 'struct->vector',
'struct-accessor-procedure?', 'struct-constructor-procedure?',
'struct-info', 'struct-mutator-procedure?',
'struct-predicate-procedure?', 'struct-type-info',
'struct-type-make-constructor', 'struct-type-make-predicate',
'struct-type-property-accessor-procedure?',
'struct-type-property?', 'struct-type?', 'struct:arity-at-least',
'struct:date', 'struct:date*', 'struct:exn', 'struct:exn:break',
'struct:exn:fail', 'struct:exn:fail:contract',
'struct:exn:fail:contract:arity',
'struct:exn:fail:contract:continuation',
'struct:exn:fail:contract:divide-by-zero',
'struct:exn:fail:contract:non-fixnum-result',
'struct:exn:fail:contract:variable', 'struct:exn:fail:filesystem',
'struct:exn:fail:filesystem:exists',
'struct:exn:fail:filesystem:version', 'struct:exn:fail:network',
'struct:exn:fail:out-of-memory', 'struct:exn:fail:read',
'struct:exn:fail:read:eof', 'struct:exn:fail:read:non-char',
'struct:exn:fail:syntax', 'struct:exn:fail:syntax:unbound',
'struct:exn:fail:unsupported', 'struct:exn:fail:user',
'struct:srcloc', 'struct?', 'sub1', 'subbytes', 'subprocess',
'subprocess-group-enabled', 'subprocess-kill', 'subprocess-pid',
'subprocess-status', 'subprocess-wait', 'subprocess?', 'substring',
'symbol->string', 'symbol-interned?', 'symbol-unreadable?',
'symbol?', 'sync', 'sync/enable-break', 'sync/timeout',
'sync/timeout/enable-break', 'syntax->list', 'syntax-arm',
'syntax-column', 'syntax-disarm', 'syntax-e', 'syntax-line',
'syntax-local-bind-syntaxes', 'syntax-local-certifier',
'syntax-local-context', 'syntax-local-expand-expression',
'syntax-local-get-shadower', 'syntax-local-introduce',
'syntax-local-lift-context', 'syntax-local-lift-expression',
'syntax-local-lift-module-end-declaration',
'syntax-local-lift-provide', 'syntax-local-lift-require',
'syntax-local-lift-values-expression',
'syntax-local-make-definition-context',
'syntax-local-make-delta-introducer',
'syntax-local-module-defined-identifiers',
'syntax-local-module-exports',
'syntax-local-module-required-identifiers', 'syntax-local-name',
'syntax-local-phase-level',
'syntax-local-transforming-module-provides?', 'syntax-local-value',
'syntax-local-value/immediate', 'syntax-original?',
'syntax-position', 'syntax-property',
'syntax-property-symbol-keys', 'syntax-protect', 'syntax-rearm',
'syntax-recertify', 'syntax-shift-phase-level', 'syntax-source',
'syntax-source-module', 'syntax-span', 'syntax-taint',
'syntax-tainted?', 'syntax-track-origin',
'syntax-transforming-module-expression?', 'syntax-transforming?',
'syntax?', 'system-big-endian?', 'system-idle-evt',
'system-language+country', 'system-library-subpath',
'system-path-convention-type', 'system-type', 'tan',
'tcp-abandon-port', 'tcp-accept', 'tcp-accept-evt',
'tcp-accept-ready?', 'tcp-accept/enable-break', 'tcp-addresses',
'tcp-close', 'tcp-connect', 'tcp-connect/enable-break',
'tcp-listen', 'tcp-listener?', 'tcp-port?', 'terminal-port?',
'thread', 'thread-cell-ref', 'thread-cell-set!', 'thread-cell?',
'thread-dead-evt', 'thread-dead?', 'thread-group?',
'thread-resume', 'thread-resume-evt', 'thread-rewind-receive',
'thread-running?', 'thread-suspend', 'thread-suspend-evt',
'thread-wait', 'thread/suspend-to-kill', 'thread?', 'time-apply',
'truncate', 'udp-addresses', 'udp-bind!', 'udp-bound?',
'udp-close', 'udp-connect!', 'udp-connected?', 'udp-open-socket',
'udp-receive!', 'udp-receive!*', 'udp-receive!-evt',
'udp-receive!/enable-break', 'udp-receive-ready-evt', 'udp-send',
'udp-send*', 'udp-send-evt', 'udp-send-ready-evt', 'udp-send-to',
'udp-send-to*', 'udp-send-to-evt', 'udp-send-to/enable-break',
'udp-send/enable-break', 'udp?', 'unbox',
'uncaught-exception-handler', 'use-collection-link-paths',
'use-compiled-file-paths', 'use-user-specific-search-paths',
'values', 'variable-reference->empty-namespace',
'variable-reference->module-base-phase',
'variable-reference->module-declaration-inspector',
'variable-reference->module-source',
'variable-reference->namespace', 'variable-reference->phase',
'variable-reference->resolved-module-path',
'variable-reference-constant?', 'variable-reference?', 'vector',
'vector->immutable-vector', 'vector->list',
'vector->pseudo-random-generator',
'vector->pseudo-random-generator!', 'vector->values',
'vector-fill!', 'vector-immutable', 'vector-length', 'vector-ref',
'vector-set!', 'vector-set-performance-stats!', 'vector?',
'version', 'void', 'void?', 'weak-box-value', 'weak-box?',
'will-execute', 'will-executor?', 'will-register',
'will-try-execute', 'with-input-from-file', 'with-output-to-file',
'wrap-evt', 'write', 'write-byte', 'write-bytes',
'write-bytes-avail', 'write-bytes-avail*', 'write-bytes-avail-evt',
'write-bytes-avail/enable-break', 'write-char', 'write-special',
'write-special-avail*', 'write-special-evt', 'write-string', 'zero?'
]
# From SchemeLexer
valid_name = r'[a-zA-Z0-9!$%&*+,/:<=>?@^_~|-]+'
tokens = {
'root' : [
(r';.*$', Comment.Single),
(r'#\|[^|]+\|#', Comment.Multiline),
# whitespaces - usually not relevant
(r'\s+', Text),
## numbers: Keep in mind Racket reader hash prefixes,
## which can denote the base or the type. These don't map
## neatly onto pygments token types; some judgment calls
## here. Note that none of these regexps attempt to
## exclude identifiers that start with a number, such as a
## variable named "100-Continue".
# #b
(r'#b[-+]?[01]+\.[01]+', Number.Float),
(r'#b[01]+e[-+]?[01]+', Number.Float),
(r'#b[-+]?[01]/[01]+', Number),
(r'#b[-+]?[01]+', Number.Integer),
(r'#b\S*', Error),
# #d OR no hash prefix
(r'(#d)?[-+]?\d+\.\d+', Number.Float),
(r'(#d)?\d+e[-+]?\d+', Number.Float),
(r'(#d)?[-+]?\d+/\d+', Number),
(r'(#d)?[-+]?\d+', Number.Integer),
(r'#d\S*', Error),
# #e
(r'#e[-+]?\d+\.\d+', Number.Float),
(r'#e\d+e[-+]?\d+', Number.Float),
(r'#e[-+]?\d+/\d+', Number),
(r'#e[-+]?\d+', Number),
(r'#e\S*', Error),
# #i is always inexact-real, i.e. float
(r'#i[-+]?\d+\.\d+', Number.Float),
(r'#i\d+e[-+]?\d+', Number.Float),
(r'#i[-+]?\d+/\d+', Number.Float),
(r'#i[-+]?\d+', Number.Float),
(r'#i\S*', Error),
# #o
(r'#o[-+]?[0-7]+\.[0-7]+', Number.Oct),
(r'#o[0-7]+e[-+]?[0-7]+', Number.Oct),
(r'#o[-+]?[0-7]+/[0-7]+', Number.Oct),
(r'#o[-+]?[0-7]+', Number.Oct),
(r'#o\S*', Error),
# #x
(r'#x[-+]?[0-9a-fA-F]+\.[0-9a-fA-F]+', Number.Hex),
# the exponent variation (e.g. #x1e1) is N/A
(r'#x[-+]?[0-9a-fA-F]+/[0-9a-fA-F]+', Number.Hex),
(r'#x[-+]?[0-9a-fA-F]+', Number.Hex),
(r'#x\S*', Error),
# strings, symbols and characters
(r'"(\\\\|\\"|[^"])*"', String),
(r"'" + valid_name, String.Symbol),
(r"#\\([()/'\"._!§$%& ?=+-]{1}|[a-zA-Z0-9]+)", String.Char),
(r'#rx".+"', String.Regex),
(r'#px".+"', String.Regex),
# constants
(r'(#t|#f)', Name.Constant),
# keyword argument names (e.g. #:keyword)
(r'#:\S+', Keyword.Declaration),
# #lang
(r'#lang \S+', Keyword.Namespace),
# special operators
(r"('|#|`|,@|,|\.)", Operator),
# highlight the keywords
('(%s)' % '|'.join([
re.escape(entry) + ' ' for entry in keywords]),
Keyword
),
# first variable in a quoted string like
# '(this is syntactic sugar)
(r"(?<='\()" + valid_name, Name.Variable),
(r"(?<=#\()" + valid_name, Name.Variable),
# highlight the builtins
("(?<=\()(%s)" % '|'.join([
re.escape(entry) + ' ' for entry in builtins]),
Name.Builtin
),
# the remaining functions; handle both ( and [
(r'(?<=(\(|\[|\{))' + valid_name, Name.Function),
# find the remaining variables
(valid_name, Name.Variable),
# the famous parentheses!
(r'(\(|\)|\[|\]|\{|\})', Punctuation),
],
}
class SchemeLexer(RegexLexer):
"""
A Scheme lexer, parsing a stream and outputting the tokens
needed to highlight scheme code.
This lexer could be most probably easily subclassed to parse
other LISP-Dialects like Common Lisp, Emacs Lisp or AutoLisp.
This parser is checked with pastes from the LISP pastebin
at http://paste.lisp.org/ to cover as much syntax as possible.
It supports the full Scheme syntax as defined in R5RS.
*New in Pygments 0.6.*
"""
name = 'Scheme'
aliases = ['scheme', 'scm']
filenames = ['*.scm', '*.ss']
mimetypes = ['text/x-scheme', 'application/x-scheme']
# list of known keywords and builtins taken form vim 6.4 scheme.vim
# syntax file.
keywords = [
'lambda', 'define', 'if', 'else', 'cond', 'and', 'or', 'case', 'let',
'let*', 'letrec', 'begin', 'do', 'delay', 'set!', '=>', 'quote',
'quasiquote', 'unquote', 'unquote-splicing', 'define-syntax',
'let-syntax', 'letrec-syntax', 'syntax-rules'
]
builtins = [
'*', '+', '-', '/', '<', '<=', '=', '>', '>=', 'abs', 'acos', 'angle',
'append', 'apply', 'asin', 'assoc', 'assq', 'assv', 'atan',
'boolean?', 'caaaar', 'caaadr', 'caaar', 'caadar', 'caaddr', 'caadr',
'caar', 'cadaar', 'cadadr', 'cadar', 'caddar', 'cadddr', 'caddr',
'cadr', 'call-with-current-continuation', 'call-with-input-file',
'call-with-output-file', 'call-with-values', 'call/cc', 'car',
'cdaaar', 'cdaadr', 'cdaar', 'cdadar', 'cdaddr', 'cdadr', 'cdar',
'cddaar', 'cddadr', 'cddar', 'cdddar', 'cddddr', 'cdddr', 'cddr',
'cdr', 'ceiling', 'char->integer', 'char-alphabetic?', 'char-ci<=?',
'char-ci<?', 'char-ci=?', 'char-ci>=?', 'char-ci>?', 'char-downcase',
'char-lower-case?', 'char-numeric?', 'char-ready?', 'char-upcase',
'char-upper-case?', 'char-whitespace?', 'char<=?', 'char<?', 'char=?',
'char>=?', 'char>?', 'char?', 'close-input-port', 'close-output-port',
'complex?', 'cons', 'cos', 'current-input-port', 'current-output-port',
'denominator', 'display', 'dynamic-wind', 'eof-object?', 'eq?',
'equal?', 'eqv?', 'eval', 'even?', 'exact->inexact', 'exact?', 'exp',
'expt', 'floor', 'for-each', 'force', 'gcd', 'imag-part',
'inexact->exact', 'inexact?', 'input-port?', 'integer->char',
'integer?', 'interaction-environment', 'lcm', 'length', 'list',
'list->string', 'list->vector', 'list-ref', 'list-tail', 'list?',
'load', 'log', 'magnitude', 'make-polar', 'make-rectangular',
'make-string', 'make-vector', 'map', 'max', 'member', 'memq', 'memv',
'min', 'modulo', 'negative?', 'newline', 'not', 'null-environment',
'null?', 'number->string', 'number?', 'numerator', 'odd?',
'open-input-file', 'open-output-file', 'output-port?', 'pair?',
'peek-char', 'port?', 'positive?', 'procedure?', 'quotient',
'rational?', 'rationalize', 'read', 'read-char', 'real-part', 'real?',
'remainder', 'reverse', 'round', 'scheme-report-environment',
'set-car!', 'set-cdr!', 'sin', 'sqrt', 'string', 'string->list',
'string->number', 'string->symbol', 'string-append', 'string-ci<=?',
'string-ci<?', 'string-ci=?', 'string-ci>=?', 'string-ci>?',
'string-copy', 'string-fill!', 'string-length', 'string-ref',
'string-set!', 'string<=?', 'string<?', 'string=?', 'string>=?',
'string>?', 'string?', 'substring', 'symbol->string', 'symbol?',
'tan', 'transcript-off', 'transcript-on', 'truncate', 'values',
'vector', 'vector->list', 'vector-fill!', 'vector-length',
'vector-ref', 'vector-set!', 'vector?', 'with-input-from-file',
'with-output-to-file', 'write', 'write-char', 'zero?'
]
# valid names for identifiers
# well, names can only not consist fully of numbers
# but this should be good enough for now
valid_name = r'[a-zA-Z0-9!$%&*+,/:<=>?@^_~|-]+'
tokens = {
'root' : [
# the comments - always starting with semicolon
# and going to the end of the line
(r';.*$', Comment.Single),
# whitespaces - usually not relevant
(r'\s+', Text),
# numbers
(r'-?\d+\.\d+', Number.Float),
(r'-?\d+', Number.Integer),
# support for uncommon kinds of numbers -
# have to figure out what the characters mean
#(r'(#e|#i|#b|#o|#d|#x)[\d.]+', Number),
# strings, symbols and characters
(r'"(\\\\|\\"|[^"])*"', String),
(r"'" + valid_name, String.Symbol),
(r"#\\([()/'\"._!§$%& ?=+-]{1}|[a-zA-Z0-9]+)", String.Char),
# constants
(r'(#t|#f)', Name.Constant),
# special operators
(r"('|#|`|,@|,|\.)", Operator),
# highlight the keywords
('(%s)' % '|'.join([
re.escape(entry) + ' ' for entry in keywords]),
Keyword
),
# first variable in a quoted string like
# '(this is syntactic sugar)
(r"(?<='\()" + valid_name, Name.Variable),
(r"(?<=#\()" + valid_name, Name.Variable),
# highlight the builtins
("(?<=\()(%s)" % '|'.join([
re.escape(entry) + ' ' for entry in builtins]),
Name.Builtin
),
# the remaining functions
(r'(?<=\()' + valid_name, Name.Function),
# find the remaining variables
(valid_name, Name.Variable),
# the famous parentheses!
(r'(\(|\))', Punctuation),
(r'(\[|\])', Punctuation),
],
}
class CommonLispLexer(RegexLexer):
"""
A Common Lisp lexer.
*New in Pygments 0.9.*
"""
name = 'Common Lisp'
aliases = ['common-lisp', 'cl']
filenames = ['*.cl', '*.lisp', '*.el'] # use for Elisp too
mimetypes = ['text/x-common-lisp']
flags = re.IGNORECASE | re.MULTILINE
### couple of useful regexes
# characters that are not macro-characters and can be used to begin a symbol
nonmacro = r'\\.|[a-zA-Z0-9!$%&*+-/<=>?@\[\]^_{}~]'
constituent = nonmacro + '|[#.:]'
terminated = r'(?=[ "()\'\n,;`])' # whitespace or terminating macro characters
### symbol token, reverse-engineered from hyperspec
# Take a deep breath...
symbol = r'(\|[^|]+\||(?:%s)(?:%s)*)' % (nonmacro, constituent)
def __init__(self, **options):
from pygments.lexers._clbuiltins import BUILTIN_FUNCTIONS, \
SPECIAL_FORMS, MACROS, LAMBDA_LIST_KEYWORDS, DECLARATIONS, \
BUILTIN_TYPES, BUILTIN_CLASSES
self.builtin_function = BUILTIN_FUNCTIONS
self.special_forms = SPECIAL_FORMS
self.macros = MACROS
self.lambda_list_keywords = LAMBDA_LIST_KEYWORDS
self.declarations = DECLARATIONS
self.builtin_types = BUILTIN_TYPES
self.builtin_classes = BUILTIN_CLASSES
RegexLexer.__init__(self, **options)
def get_tokens_unprocessed(self, text):
stack = ['root']
for index, token, value in RegexLexer.get_tokens_unprocessed(self, text, stack):
if token is Name.Variable:
if value in self.builtin_function:
yield index, Name.Builtin, value
continue
if value in self.special_forms:
yield index, Keyword, value
continue
if value in self.macros:
yield index, Name.Builtin, value
continue
if value in self.lambda_list_keywords:
yield index, Keyword, value
continue
if value in self.declarations:
yield index, Keyword, value
continue
if value in self.builtin_types:
yield index, Keyword.Type, value
continue
if value in self.builtin_classes:
yield index, Name.Class, value
continue
yield index, token, value
tokens = {
'root' : [
('', Text, 'body'),
],
'multiline-comment' : [
(r'#\|', Comment.Multiline, '#push'), # (cf. Hyperspec 2.4.8.19)
(r'\|#', Comment.Multiline, '#pop'),
(r'[^|#]+', Comment.Multiline),
(r'[|#]', Comment.Multiline),
],
'commented-form' : [
(r'\(', Comment.Preproc, '#push'),
(r'\)', Comment.Preproc, '#pop'),
(r'[^()]+', Comment.Preproc),
],
'body' : [
# whitespace
(r'\s+', Text),
# single-line comment
(r';.*$', Comment.Single),
# multi-line comment
(r'#\|', Comment.Multiline, 'multiline-comment'),
# encoding comment (?)
(r'#\d*Y.*$', Comment.Special),
# strings and characters
(r'"(\\.|\\\n|[^"\\])*"', String),
# quoting
(r":" + symbol, String.Symbol),
(r"'" + symbol, String.Symbol),
(r"'", Operator),
(r"`", Operator),
# decimal numbers
(r'[-+]?\d+\.?' + terminated, Number.Integer),
(r'[-+]?\d+/\d+' + terminated, Number),
(r'[-+]?(\d*\.\d+([defls][-+]?\d+)?|\d+(\.\d*)?[defls][-+]?\d+)' \
+ terminated, Number.Float),
# sharpsign strings and characters
(r"#\\." + terminated, String.Char),
(r"#\\" + symbol, String.Char),
# vector
(r'#\(', Operator, 'body'),
# bitstring
(r'#\d*\*[01]*', Literal.Other),
# uninterned symbol
(r'#:' + symbol, String.Symbol),
# read-time and load-time evaluation
(r'#[.,]', Operator),
# function shorthand
(r'#\'', Name.Function),
# binary rational
(r'#[bB][+-]?[01]+(/[01]+)?', Number),
# octal rational
(r'#[oO][+-]?[0-7]+(/[0-7]+)?', Number.Oct),
# hex rational
(r'#[xX][+-]?[0-9a-fA-F]+(/[0-9a-fA-F]+)?', Number.Hex),
# radix rational
(r'#\d+[rR][+-]?[0-9a-zA-Z]+(/[0-9a-zA-Z]+)?', Number),
# complex
(r'(#[cC])(\()', bygroups(Number, Punctuation), 'body'),
# array
(r'(#\d+[aA])(\()', bygroups(Literal.Other, Punctuation), 'body'),
# structure
(r'(#[sS])(\()', bygroups(Literal.Other, Punctuation), 'body'),
# path
(r'#[pP]?"(\\.|[^"])*"', Literal.Other),
# reference
(r'#\d+=', Operator),
(r'#\d+#', Operator),
# read-time comment
(r'#+nil' + terminated + '\s*\(', Comment.Preproc, 'commented-form'),
# read-time conditional
(r'#[+-]', Operator),
# special operators that should have been parsed already
(r'(,@|,|\.)', Operator),
# special constants
(r'(t|nil)' + terminated, Name.Constant),
# functions and variables
(r'\*' + symbol + '\*', Name.Variable.Global),
(symbol, Name.Variable),
# parentheses
(r'\(', Punctuation, 'body'),
(r'\)', Punctuation, '#pop'),
],
}
class HaskellLexer(RegexLexer):
"""
A Haskell lexer based on the lexemes defined in the Haskell 98 Report.
*New in Pygments 0.8.*
"""
name = 'Haskell'
aliases = ['haskell', 'hs']
filenames = ['*.hs']
mimetypes = ['text/x-haskell']
reserved = ['case','class','data','default','deriving','do','else',
'if','in','infix[lr]?','instance',
'let','newtype','of','then','type','where','_']
ascii = ['NUL','SOH','[SE]TX','EOT','ENQ','ACK',
'BEL','BS','HT','LF','VT','FF','CR','S[OI]','DLE',
'DC[1-4]','NAK','SYN','ETB','CAN',
'EM','SUB','ESC','[FGRU]S','SP','DEL']
tokens = {
'root': [
# Whitespace:
(r'\s+', Text),
#(r'--\s*|.*$', Comment.Doc),
(r'--(?![!#$%&*+./<=>?@\^|_~:\\]).*?$', Comment.Single),
(r'{-', Comment.Multiline, 'comment'),
# Lexemes:
# Identifiers
(r'\bimport\b', Keyword.Reserved, 'import'),
(r'\bmodule\b', Keyword.Reserved, 'module'),
(r'\berror\b', Name.Exception),
(r'\b(%s)(?!\')\b' % '|'.join(reserved), Keyword.Reserved),
(r'^[_a-z][\w\']*', Name.Function),
(r"'?[_a-z][\w']*", Name),
(r"('')?[A-Z][\w\']*", Keyword.Type),
# Operators
(r'\\(?![:!#$%&*+.\\/<=>?@^|~-]+)', Name.Function), # lambda operator
(r'(<-|::|->|=>|=)(?![:!#$%&*+.\\/<=>?@^|~-]+)', Operator.Word), # specials
(r':[:!#$%&*+.\\/<=>?@^|~-]*', Keyword.Type), # Constructor operators
(r'[:!#$%&*+.\\/<=>?@^|~-]+', Operator), # Other operators
# Numbers
(r'\d+[eE][+-]?\d+', Number.Float),
(r'\d+\.\d+([eE][+-]?\d+)?', Number.Float),
(r'0[oO][0-7]+', Number.Oct),
(r'0[xX][\da-fA-F]+', Number.Hex),
(r'\d+', Number.Integer),
# Character/String Literals
(r"'", String.Char, 'character'),
(r'"', String, 'string'),
# Special
(r'\[\]', Keyword.Type),
(r'\(\)', Name.Builtin),
(r'[][(),;`{}]', Punctuation),
],
'import': [
# Import statements
(r'\s+', Text),
(r'"', String, 'string'),
# after "funclist" state
(r'\)', Punctuation, '#pop'),
(r'qualified\b', Keyword),
# import X as Y
(r'([A-Z][a-zA-Z0-9_.]*)(\s+)(as)(\s+)([A-Z][a-zA-Z0-9_.]*)',
bygroups(Name.Namespace, Text, Keyword, Text, Name), '#pop'),
# import X hiding (functions)
(r'([A-Z][a-zA-Z0-9_.]*)(\s+)(hiding)(\s+)(\()',
bygroups(Name.Namespace, Text, Keyword, Text, Punctuation), 'funclist'),
# import X (functions)
(r'([A-Z][a-zA-Z0-9_.]*)(\s+)(\()',
bygroups(Name.Namespace, Text, Punctuation), 'funclist'),
# import X
(r'[a-zA-Z0-9_.]+', Name.Namespace, '#pop'),
],
'module': [
(r'\s+', Text),
(r'([A-Z][a-zA-Z0-9_.]*)(\s+)(\()',
bygroups(Name.Namespace, Text, Punctuation), 'funclist'),
(r'[A-Z][a-zA-Z0-9_.]*', Name.Namespace, '#pop'),
],
'funclist': [
(r'\s+', Text),
(r'[A-Z][a-zA-Z0-9_]*', Keyword.Type),
(r'(_[\w\']+|[a-z][\w\']*)', Name.Function),
(r'--.*$', Comment.Single),
(r'{-', Comment.Multiline, 'comment'),
(r',', Punctuation),
(r'[:!#$%&*+.\\/<=>?@^|~-]+', Operator),
# (HACK, but it makes sense to push two instances, believe me)
(r'\(', Punctuation, ('funclist', 'funclist')),
(r'\)', Punctuation, '#pop:2'),
],
'comment': [
# Multiline Comments
(r'[^-{}]+', Comment.Multiline),
(r'{-', Comment.Multiline, '#push'),
(r'-}', Comment.Multiline, '#pop'),
(r'[-{}]', Comment.Multiline),
],
'character': [
# Allows multi-chars, incorrectly.
(r"[^\\']", String.Char),
(r"\\", String.Escape, 'escape'),
("'", String.Char, '#pop'),
],
'string': [
(r'[^\\"]+', String),
(r"\\", String.Escape, 'escape'),
('"', String, '#pop'),
],
'escape': [
(r'[abfnrtv"\'&\\]', String.Escape, '#pop'),
(r'\^[][A-Z@\^_]', String.Escape, '#pop'),
('|'.join(ascii), String.Escape, '#pop'),
(r'o[0-7]+', String.Escape, '#pop'),
(r'x[\da-fA-F]+', String.Escape, '#pop'),
(r'\d+', String.Escape, '#pop'),
(r'\s+\\', String.Escape, '#pop'),
],
}
line_re = re.compile('.*?\n')
bird_re = re.compile(r'(>[ \t]*)(.*\n)')
class LiterateHaskellLexer(Lexer):
"""
For Literate Haskell (Bird-style or LaTeX) source.
Additional options accepted:
`litstyle`
If given, must be ``"bird"`` or ``"latex"``. If not given, the style
is autodetected: if the first non-whitespace character in the source
is a backslash or percent character, LaTeX is assumed, else Bird.
*New in Pygments 0.9.*
"""
name = 'Literate Haskell'
aliases = ['lhs', 'literate-haskell']
filenames = ['*.lhs']
mimetypes = ['text/x-literate-haskell']
def get_tokens_unprocessed(self, text):
hslexer = HaskellLexer(**self.options)
style = self.options.get('litstyle')
if style is None:
style = (text.lstrip()[0:1] in '%\\') and 'latex' or 'bird'
code = ''
insertions = []
if style == 'bird':
# bird-style
for match in line_re.finditer(text):
line = match.group()
m = bird_re.match(line)
if m:
insertions.append((len(code),
[(0, Comment.Special, m.group(1))]))
code += m.group(2)
else:
insertions.append((len(code), [(0, Text, line)]))
else:
# latex-style
from pygments.lexers.text import TexLexer
lxlexer = TexLexer(**self.options)
codelines = 0
latex = ''
for match in line_re.finditer(text):
line = match.group()
if codelines:
if line.lstrip().startswith('\\end{code}'):
codelines = 0
latex += line
else:
code += line
elif line.lstrip().startswith('\\begin{code}'):
codelines = 1
latex += line
insertions.append((len(code),
list(lxlexer.get_tokens_unprocessed(latex))))
latex = ''
else:
latex += line
insertions.append((len(code),
list(lxlexer.get_tokens_unprocessed(latex))))
for item in do_insertions(insertions, hslexer.get_tokens_unprocessed(code)):
yield item
class SMLLexer(RegexLexer):
"""
For the Standard ML language.
*New in Pygments 1.5.*
"""
name = 'Standard ML'
aliases = ['sml']
filenames = ['*.sml', '*.sig', '*.fun',]
mimetypes = ['text/x-standardml', 'application/x-standardml']
alphanumid_reserved = [
# Core
'abstype', 'and', 'andalso', 'as', 'case', 'datatype', 'do', 'else',
'end', 'exception', 'fn', 'fun', 'handle', 'if', 'in', 'infix',
'infixr', 'let', 'local', 'nonfix', 'of', 'op', 'open', 'orelse',
'raise', 'rec', 'then', 'type', 'val', 'with', 'withtype', 'while',
# Modules
'eqtype', 'functor', 'include', 'sharing', 'sig', 'signature',
'struct', 'structure', 'where',
]
symbolicid_reserved = [
# Core
':', '\|', '=', '=>', '->', '#',
# Modules
':>',
]
nonid_reserved = [ '(', ')', '[', ']', '{', '}', ',', ';', '...', '_' ]
alphanumid_re = r"[a-zA-Z][a-zA-Z0-9_']*"
symbolicid_re = r"[!%&$#+\-/:<=>?@\\~`^|*]+"
# A character constant is a sequence of the form #s, where s is a string
# constant denoting a string of size one character. This setup just parses
# the entire string as either a String.Double or a String.Char (depending
# on the argument), even if the String.Char is an erronous
# multiple-character string.
def stringy (whatkind):
return [
(r'[^"\\]', whatkind),
(r'\\[\\\"abtnvfr]', String.Escape),
# Control-character notation is used for codes < 32,
# where \^@ == \000
(r'\\\^[\x40-\x5e]', String.Escape),
# Docs say 'decimal digits'
(r'\\[0-9]{3}', String.Escape),
(r'\\u[0-9a-fA-F]{4}', String.Escape),
(r'\\\s+\\', String.Interpol),
(r'"', whatkind, '#pop'),
]
# Callbacks for distinguishing tokens and reserved words
def long_id_callback(self, match):
if match.group(1) in self.alphanumid_reserved: token = Error
else: token = Name.Namespace
yield match.start(1), token, match.group(1)
yield match.start(2), Punctuation, match.group(2)
def end_id_callback(self, match):
if match.group(1) in self.alphanumid_reserved: token = Error
elif match.group(1) in self.symbolicid_reserved: token = Error
else: token = Name
yield match.start(1), token, match.group(1)
def id_callback(self, match):
str = match.group(1)
if str in self.alphanumid_reserved: token = Keyword.Reserved
elif str in self.symbolicid_reserved: token = Punctuation
else: token = Name
yield match.start(1), token, str
tokens = {
# Whitespace and comments are (almost) everywhere
'whitespace': [
(r'\s+', Text),
(r'\(\*', Comment.Multiline, 'comment'),
],
'delimiters': [
# This lexer treats these delimiters specially:
# Delimiters define scopes, and the scope is how the meaning of
# the `|' is resolved - is it a case/handle expression, or function
# definition by cases? (This is not how the Definition works, but
# it's how MLton behaves, see http://mlton.org/SMLNJDeviations)
(r'\(|\[|{', Punctuation, 'main'),
(r'\)|\]|}', Punctuation, '#pop'),
(r'\b(let|if|local)\b(?!\')', Keyword.Reserved, ('main', 'main')),
(r'\b(struct|sig|while)\b(?!\')', Keyword.Reserved, 'main'),
(r'\b(do|else|end|in|then)\b(?!\')', Keyword.Reserved, '#pop'),
],
'core': [
# Punctuation that doesn't overlap symbolic identifiers
(r'(%s)' % '|'.join([re.escape(z) for z in nonid_reserved]),
Punctuation),
# Special constants: strings, floats, numbers in decimal and hex
(r'#"', String.Char, 'char'),
(r'"', String.Double, 'string'),
(r'~?0x[0-9a-fA-F]+', Number.Hex),
(r'0wx[0-9a-fA-F]+', Number.Hex),
(r'0w\d+', Number.Integer),
(r'~?\d+\.\d+[eE]~?\d+', Number.Float),
(r'~?\d+\.\d+', Number.Float),
(r'~?\d+[eE]~?\d+', Number.Float),
(r'~?\d+', Number.Integer),
# Labels
(r'#\s*[1-9][0-9]*', Name.Label),
(r'#\s*(%s)' % alphanumid_re, Name.Label),
(r'#\s+(%s)' % symbolicid_re, Name.Label),
# Some reserved words trigger a special, local lexer state change
(r'\b(datatype|abstype)\b(?!\')', Keyword.Reserved, 'dname'),
(r'(?=\b(exception)\b(?!\'))', Text, ('ename')),
(r'\b(functor|include|open|signature|structure)\b(?!\')',
Keyword.Reserved, 'sname'),
(r'\b(type|eqtype)\b(?!\')', Keyword.Reserved, 'tname'),
# Regular identifiers, long and otherwise
(r'\'[0-9a-zA-Z_\']*', Name.Decorator),
(r'(%s)(\.)' % alphanumid_re, long_id_callback, "dotted"),
(r'(%s)' % alphanumid_re, id_callback),
(r'(%s)' % symbolicid_re, id_callback),
],
'dotted': [
(r'(%s)(\.)' % alphanumid_re, long_id_callback),
(r'(%s)' % alphanumid_re, end_id_callback, "#pop"),
(r'(%s)' % symbolicid_re, end_id_callback, "#pop"),
(r'\s+', Error),
(r'\S+', Error),
],
# Main parser (prevents errors in files that have scoping errors)
'root': [ (r'', Text, 'main') ],
# In this scope, I expect '|' to not be followed by a function name,
# and I expect 'and' to be followed by a binding site
'main': [
include('whitespace'),
# Special behavior of val/and/fun
(r'\b(val|and)\b(?!\')', Keyword.Reserved, 'vname'),
(r'\b(fun)\b(?!\')', Keyword.Reserved,
('#pop', 'main-fun', 'fname')),
include('delimiters'),
include('core'),
(r'\S+', Error),
],
# In this scope, I expect '|' and 'and' to be followed by a function
'main-fun': [
include('whitespace'),
(r'\s', Text),
(r'\(\*', Comment.Multiline, 'comment'),
# Special behavior of val/and/fun
(r'\b(fun|and)\b(?!\')', Keyword.Reserved, 'fname'),
(r'\b(val)\b(?!\')', Keyword.Reserved,
('#pop', 'main', 'vname')),
# Special behavior of '|' and '|'-manipulating keywords
(r'\|', Punctuation, 'fname'),
(r'\b(case|handle)\b(?!\')', Keyword.Reserved,
('#pop', 'main')),
include('delimiters'),
include('core'),
(r'\S+', Error),
],
# Character and string parsers
'char': stringy(String.Char),
'string': stringy(String.Double),
'breakout': [
(r'(?=\b(%s)\b(?!\'))' % '|'.join(alphanumid_reserved), Text, '#pop'),
],
# Dealing with what comes after module system keywords
'sname': [
include('whitespace'),
include('breakout'),
(r'(%s)' % alphanumid_re, Name.Namespace),
(r'', Text, '#pop'),
],
# Dealing with what comes after the 'fun' (or 'and' or '|') keyword
'fname': [
include('whitespace'),
(r'\'[0-9a-zA-Z_\']*', Name.Decorator),
(r'\(', Punctuation, 'tyvarseq'),
(r'(%s)' % alphanumid_re, Name.Function, '#pop'),
(r'(%s)' % symbolicid_re, Name.Function, '#pop'),
# Ignore interesting function declarations like "fun (x + y) = ..."
(r'', Text, '#pop'),
],
# Dealing with what comes after the 'val' (or 'and') keyword
'vname': [
include('whitespace'),
(r'\'[0-9a-zA-Z_\']*', Name.Decorator),
(r'\(', Punctuation, 'tyvarseq'),
(r'(%s)(\s*)(=(?!%s))' % (alphanumid_re, symbolicid_re),
bygroups(Name.Variable, Text, Punctuation), '#pop'),
(r'(%s)(\s*)(=(?!%s))' % (symbolicid_re, symbolicid_re),
bygroups(Name.Variable, Text, Punctuation), '#pop'),
(r'(%s)' % alphanumid_re, Name.Variable, '#pop'),
(r'(%s)' % symbolicid_re, Name.Variable, '#pop'),
# Ignore interesting patterns like 'val (x, y)'
(r'', Text, '#pop'),
],
# Dealing with what comes after the 'type' (or 'and') keyword
'tname': [
include('whitespace'),
include('breakout'),
(r'\'[0-9a-zA-Z_\']*', Name.Decorator),
(r'\(', Punctuation, 'tyvarseq'),
(r'=(?!%s)' % symbolicid_re, Punctuation, ('#pop', 'typbind')),
(r'(%s)' % alphanumid_re, Keyword.Type),
(r'(%s)' % symbolicid_re, Keyword.Type),
(r'\S+', Error, '#pop'),
],
# A type binding includes most identifiers
'typbind': [
include('whitespace'),
(r'\b(and)\b(?!\')', Keyword.Reserved, ('#pop', 'tname')),
include('breakout'),
include('core'),
(r'\S+', Error, '#pop'),
],
# Dealing with what comes after the 'datatype' (or 'and') keyword
'dname': [
include('whitespace'),
include('breakout'),
(r'\'[0-9a-zA-Z_\']*', Name.Decorator),
(r'\(', Punctuation, 'tyvarseq'),
(r'(=)(\s*)(datatype)',
bygroups(Punctuation, Text, Keyword.Reserved), '#pop'),
(r'=(?!%s)' % symbolicid_re, Punctuation,
('#pop', 'datbind', 'datcon')),
(r'(%s)' % alphanumid_re, Keyword.Type),
(r'(%s)' % symbolicid_re, Keyword.Type),
(r'\S+', Error, '#pop'),
],
# common case - A | B | C of int
'datbind': [
include('whitespace'),
(r'\b(and)\b(?!\')', Keyword.Reserved, ('#pop', 'dname')),
(r'\b(withtype)\b(?!\')', Keyword.Reserved, ('#pop', 'tname')),
(r'\b(of)\b(?!\')', Keyword.Reserved),
(r'(\|)(\s*)(%s)' % alphanumid_re,
bygroups(Punctuation, Text, Name.Class)),
(r'(\|)(\s+)(%s)' % symbolicid_re,
bygroups(Punctuation, Text, Name.Class)),
include('breakout'),
include('core'),
(r'\S+', Error),
],
# Dealing with what comes after an exception
'ename': [
include('whitespace'),
(r'(exception|and)\b(\s+)(%s)' % alphanumid_re,
bygroups(Keyword.Reserved, Text, Name.Class)),
(r'(exception|and)\b(\s*)(%s)' % symbolicid_re,
bygroups(Keyword.Reserved, Text, Name.Class)),
(r'\b(of)\b(?!\')', Keyword.Reserved),
include('breakout'),
include('core'),
(r'\S+', Error),
],
'datcon': [
include('whitespace'),
(r'(%s)' % alphanumid_re, Name.Class, '#pop'),
(r'(%s)' % symbolicid_re, Name.Class, '#pop'),
(r'\S+', Error, '#pop'),
],
# Series of type variables
'tyvarseq': [
(r'\s', Text),
(r'\(\*', Comment.Multiline, 'comment'),
(r'\'[0-9a-zA-Z_\']*', Name.Decorator),
(alphanumid_re, Name),
(r',', Punctuation),
(r'\)', Punctuation, '#pop'),
(symbolicid_re, Name),
],
'comment': [
(r'[^(*)]', Comment.Multiline),
(r'\(\*', Comment.Multiline, '#push'),
(r'\*\)', Comment.Multiline, '#pop'),
(r'[(*)]', Comment.Multiline),
],
}
class OcamlLexer(RegexLexer):
"""
For the OCaml language.
*New in Pygments 0.7.*
"""
name = 'OCaml'
aliases = ['ocaml']
filenames = ['*.ml', '*.mli', '*.mll', '*.mly']
mimetypes = ['text/x-ocaml']
keywords = [
'as', 'assert', 'begin', 'class', 'constraint', 'do', 'done',
'downto', 'else', 'end', 'exception', 'external', 'false',
'for', 'fun', 'function', 'functor', 'if', 'in', 'include',
'inherit', 'initializer', 'lazy', 'let', 'match', 'method',
'module', 'mutable', 'new', 'object', 'of', 'open', 'private',
'raise', 'rec', 'sig', 'struct', 'then', 'to', 'true', 'try',
'type', 'value', 'val', 'virtual', 'when', 'while', 'with',
]
keyopts = [
'!=','#','&','&&','\(','\)','\*','\+',',','-',
'-\.','->','\.','\.\.',':','::',':=',':>',';',';;','<',
'<-','=','>','>]','>}','\?','\?\?','\[','\[<','\[>','\[\|',
']','_','`','{','{<','\|','\|]','}','~'
]
operators = r'[!$%&*+\./:<=>?@^|~-]'
word_operators = ['and', 'asr', 'land', 'lor', 'lsl', 'lxor', 'mod', 'or']
prefix_syms = r'[!?~]'
infix_syms = r'[=<>@^|&+\*/$%-]'
primitives = ['unit', 'int', 'float', 'bool', 'string', 'char', 'list', 'array']
tokens = {
'escape-sequence': [
(r'\\[\\\"\'ntbr]', String.Escape),
(r'\\[0-9]{3}', String.Escape),
(r'\\x[0-9a-fA-F]{2}', String.Escape),
],
'root': [
(r'\s+', Text),
(r'false|true|\(\)|\[\]', Name.Builtin.Pseudo),
(r'\b([A-Z][A-Za-z0-9_\']*)(?=\s*\.)',
Name.Namespace, 'dotted'),
(r'\b([A-Z][A-Za-z0-9_\']*)', Name.Class),
(r'\(\*(?![)])', Comment, 'comment'),
(r'\b(%s)\b' % '|'.join(keywords), Keyword),
(r'(%s)' % '|'.join(keyopts[::-1]), Operator),
(r'(%s|%s)?%s' % (infix_syms, prefix_syms, operators), Operator),
(r'\b(%s)\b' % '|'.join(word_operators), Operator.Word),
(r'\b(%s)\b' % '|'.join(primitives), Keyword.Type),
(r"[^\W\d][\w']*", Name),
(r'-?\d[\d_]*(.[\d_]*)?([eE][+\-]?\d[\d_]*)', Number.Float),
(r'0[xX][\da-fA-F][\da-fA-F_]*', Number.Hex),
(r'0[oO][0-7][0-7_]*', Number.Oct),
(r'0[bB][01][01_]*', Number.Binary),
(r'\d[\d_]*', Number.Integer),
(r"'(?:(\\[\\\"'ntbr ])|(\\[0-9]{3})|(\\x[0-9a-fA-F]{2}))'",
String.Char),
(r"'.'", String.Char),
(r"'", Keyword), # a stray quote is another syntax element
(r'"', String.Double, 'string'),
(r'[~?][a-z][\w\']*:', Name.Variable),
],
'comment': [
(r'[^(*)]+', Comment),
(r'\(\*', Comment, '#push'),
(r'\*\)', Comment, '#pop'),
(r'[(*)]', Comment),
],
'string': [
(r'[^\\"]+', String.Double),
include('escape-sequence'),
(r'\\\n', String.Double),
(r'"', String.Double, '#pop'),
],
'dotted': [
(r'\s+', Text),
(r'\.', Punctuation),
(r'[A-Z][A-Za-z0-9_\']*(?=\s*\.)', Name.Namespace),
(r'[A-Z][A-Za-z0-9_\']*', Name.Class, '#pop'),
(r'[a-z_][A-Za-z0-9_\']*', Name, '#pop'),
],
}
class ErlangLexer(RegexLexer):
"""
For the Erlang functional programming language.
Blame Jeremy Thurgood (http://jerith.za.net/).
*New in Pygments 0.9.*
"""
name = 'Erlang'
aliases = ['erlang']
filenames = ['*.erl', '*.hrl', '*.es', '*.escript']
mimetypes = ['text/x-erlang']
keywords = [
'after', 'begin', 'case', 'catch', 'cond', 'end', 'fun', 'if',
'let', 'of', 'query', 'receive', 'try', 'when',
]
builtins = [ # See erlang(3) man page
'abs', 'append_element', 'apply', 'atom_to_list', 'binary_to_list',
'bitstring_to_list', 'binary_to_term', 'bit_size', 'bump_reductions',
'byte_size', 'cancel_timer', 'check_process_code', 'delete_module',
'demonitor', 'disconnect_node', 'display', 'element', 'erase', 'exit',
'float', 'float_to_list', 'fun_info', 'fun_to_list',
'function_exported', 'garbage_collect', 'get', 'get_keys',
'group_leader', 'hash', 'hd', 'integer_to_list', 'iolist_to_binary',
'iolist_size', 'is_atom', 'is_binary', 'is_bitstring', 'is_boolean',
'is_builtin', 'is_float', 'is_function', 'is_integer', 'is_list',
'is_number', 'is_pid', 'is_port', 'is_process_alive', 'is_record',
'is_reference', 'is_tuple', 'length', 'link', 'list_to_atom',
'list_to_binary', 'list_to_bitstring', 'list_to_existing_atom',
'list_to_float', 'list_to_integer', 'list_to_pid', 'list_to_tuple',
'load_module', 'localtime_to_universaltime', 'make_tuple', 'md5',
'md5_final', 'md5_update', 'memory', 'module_loaded', 'monitor',
'monitor_node', 'node', 'nodes', 'open_port', 'phash', 'phash2',
'pid_to_list', 'port_close', 'port_command', 'port_connect',
'port_control', 'port_call', 'port_info', 'port_to_list',
'process_display', 'process_flag', 'process_info', 'purge_module',
'put', 'read_timer', 'ref_to_list', 'register', 'resume_process',
'round', 'send', 'send_after', 'send_nosuspend', 'set_cookie',
'setelement', 'size', 'spawn', 'spawn_link', 'spawn_monitor',
'spawn_opt', 'split_binary', 'start_timer', 'statistics',
'suspend_process', 'system_flag', 'system_info', 'system_monitor',
'system_profile', 'term_to_binary', 'tl', 'trace', 'trace_delivered',
'trace_info', 'trace_pattern', 'trunc', 'tuple_size', 'tuple_to_list',
'universaltime_to_localtime', 'unlink', 'unregister', 'whereis'
]
operators = r'(\+\+?|--?|\*|/|<|>|/=|=:=|=/=|=<|>=|==?|<-|!|\?)'
word_operators = [
'and', 'andalso', 'band', 'bnot', 'bor', 'bsl', 'bsr', 'bxor',
'div', 'not', 'or', 'orelse', 'rem', 'xor'
]
atom_re = r"(?:[a-z][a-zA-Z0-9_]*|'[^\n']*[^\\]')"
variable_re = r'(?:[A-Z_][a-zA-Z0-9_]*)'
escape_re = r'(?:\\(?:[bdefnrstv\'"\\/]|[0-7][0-7]?[0-7]?|\^[a-zA-Z]))'
macro_re = r'(?:'+variable_re+r'|'+atom_re+r')'
base_re = r'(?:[2-9]|[12][0-9]|3[0-6])'
tokens = {
'root': [
(r'\s+', Text),
(r'%.*\n', Comment),
('(' + '|'.join(keywords) + r')\b', Keyword),
('(' + '|'.join(builtins) + r')\b', Name.Builtin),
('(' + '|'.join(word_operators) + r')\b', Operator.Word),
(r'^-', Punctuation, 'directive'),
(operators, Operator),
(r'"', String, 'string'),
(r'<<', Name.Label),
(r'>>', Name.Label),
('(' + atom_re + ')(:)', bygroups(Name.Namespace, Punctuation)),
('(?:^|(?<=:))(' + atom_re + r')(\s*)(\()',
bygroups(Name.Function, Text, Punctuation)),
(r'[+-]?'+base_re+r'#[0-9a-zA-Z]+', Number.Integer),
(r'[+-]?\d+', Number.Integer),
(r'[+-]?\d+.\d+', Number.Float),
(r'[]\[:_@\".{}()|;,]', Punctuation),
(variable_re, Name.Variable),
(atom_re, Name),
(r'\?'+macro_re, Name.Constant),
(r'\$(?:'+escape_re+r'|\\[ %]|[^\\])', String.Char),
(r'#'+atom_re+r'(:?\.'+atom_re+r')?', Name.Label),
],
'string': [
(escape_re, String.Escape),
(r'"', String, '#pop'),
(r'~[0-9.*]*[~#+bBcdefginpPswWxX]', String.Interpol),
(r'[^"\\~]+', String),
(r'~', String),
],
'directive': [
(r'(define)(\s*)(\()('+macro_re+r')',
bygroups(Name.Entity, Text, Punctuation, Name.Constant), '#pop'),
(r'(record)(\s*)(\()('+macro_re+r')',
bygroups(Name.Entity, Text, Punctuation, Name.Label), '#pop'),
(atom_re, Name.Entity, '#pop'),
],
}
class ErlangShellLexer(Lexer):
"""
Shell sessions in erl (for Erlang code).
*New in Pygments 1.1.*
"""
name = 'Erlang erl session'
aliases = ['erl']
filenames = ['*.erl-sh']
mimetypes = ['text/x-erl-shellsession']
_prompt_re = re.compile(r'\d+>(?=\s|\Z)')
def get_tokens_unprocessed(self, text):
erlexer = ErlangLexer(**self.options)
curcode = ''
insertions = []
for match in line_re.finditer(text):
line = match.group()
m = self._prompt_re.match(line)
if m is not None:
end = m.end()
insertions.append((len(curcode),
[(0, Generic.Prompt, line[:end])]))
curcode += line[end:]
else:
if curcode:
for item in do_insertions(insertions,
erlexer.get_tokens_unprocessed(curcode)):
yield item
curcode = ''
insertions = []
if line.startswith('*'):
yield match.start(), Generic.Traceback, line
else:
yield match.start(), Generic.Output, line
if curcode:
for item in do_insertions(insertions,
erlexer.get_tokens_unprocessed(curcode)):
yield item
class OpaLexer(RegexLexer):
"""
Lexer for the Opa language (http://opalang.org).
*New in Pygments 1.5.*
"""
name = 'Opa'
aliases = ['opa']
filenames = ['*.opa']
mimetypes = ['text/x-opa']
# most of these aren't strictly keywords
# but if you color only real keywords, you might just
# as well not color anything
keywords = [
'and', 'as', 'begin', 'css', 'database', 'db', 'do', 'else', 'end',
'external', 'forall', 'if', 'import', 'match', 'package', 'parser',
'rec', 'server', 'then', 'type', 'val', 'with', 'xml_parser',
]
# matches both stuff and `stuff`
ident_re = r'(([a-zA-Z_]\w*)|(`[^`]*`))'
op_re = r'[.=\-<>,@~%/+?*&^!]'
punc_re = r'[()\[\],;|]' # '{' and '}' are treated elsewhere
# because they are also used for inserts
tokens = {
# copied from the caml lexer, should be adapted
'escape-sequence': [
(r'\\[\\\"\'ntr}]', String.Escape),
(r'\\[0-9]{3}', String.Escape),
(r'\\x[0-9a-fA-F]{2}', String.Escape),
],
# factorizing these rules, because they are inserted many times
'comments': [
(r'/\*', Comment, 'nested-comment'),
(r'//.*?$', Comment),
],
'comments-and-spaces': [
include('comments'),
(r'\s+', Text),
],
'root': [
include('comments-and-spaces'),
# keywords
(r'\b(%s)\b' % '|'.join(keywords), Keyword),
# directives
# we could parse the actual set of directives instead of anything
# starting with @, but this is troublesome
# because it needs to be adjusted all the time
# and assuming we parse only sources that compile, it is useless
(r'@'+ident_re+r'\b', Name.Builtin.Pseudo),
# number literals
(r'-?.[\d]+([eE][+\-]?\d+)', Number.Float),
(r'-?\d+.\d*([eE][+\-]?\d+)', Number.Float),
(r'-?\d+[eE][+\-]?\d+', Number.Float),
(r'0[xX][\da-fA-F]+', Number.Hex),
(r'0[oO][0-7]+', Number.Oct),
(r'0[bB][01]+', Number.Binary),
(r'\d+', Number.Integer),
# color literals
(r'#[\da-fA-F]{3,6}', Number.Integer),
# string literals
(r'"', String.Double, 'string'),
# char literal, should be checked because this is the regexp from
# the caml lexer
(r"'(?:(\\[\\\"'ntbr ])|(\\[0-9]{3})|(\\x[0-9a-fA-F]{2})|.)'",
String.Char),
# this is meant to deal with embedded exprs in strings
# every time we find a '}' we pop a state so that if we were
# inside a string, we are back in the string state
# as a consequence, we must also push a state every time we find a
# '{' or else we will have errors when parsing {} for instance
(r'{', Operator, '#push'),
(r'}', Operator, '#pop'),
# html literals
# this is a much more strict that the actual parser,
# since a<b would not be parsed as html
# but then again, the parser is way too lax, and we can't hope
# to have something as tolerant
(r'<(?=[a-zA-Z>])', String.Single, 'html-open-tag'),
# db path
# matching the '[_]' in '/a[_]' because it is a part
# of the syntax of the db path definition
# unfortunately, i don't know how to match the ']' in
# /a[1], so this is somewhat inconsistent
(r'[@?!]?(/\w+)+(\[_\])?', Name.Variable),
# putting the same color on <- as on db path, since
# it can be used only to mean Db.write
(r'<-(?!'+op_re+r')', Name.Variable),
# 'modules'
# although modules are not distinguished by their names as in caml
# the standard library seems to follow the convention that modules
# only area capitalized
(r'\b([A-Z]\w*)(?=\.)', Name.Namespace),
# operators
# = has a special role because this is the only
# way to syntactic distinguish binding constructions
# unfortunately, this colors the equal in {x=2} too
(r'=(?!'+op_re+r')', Keyword),
(r'(%s)+' % op_re, Operator),
(r'(%s)+' % punc_re, Operator),
# coercions
(r':', Operator, 'type'),
# type variables
# we need this rule because we don't parse specially type
# definitions so in "type t('a) = ...", "'a" is parsed by 'root'
("'"+ident_re, Keyword.Type),
# id literal, #something, or #{expr}
(r'#'+ident_re, String.Single),
(r'#(?={)', String.Single),
# identifiers
# this avoids to color '2' in 'a2' as an integer
(ident_re, Text),
# default, not sure if that is needed or not
# (r'.', Text),
],
# it is quite painful to have to parse types to know where they end
# this is the general rule for a type
# a type is either:
# * -> ty
# * type-with-slash
# * type-with-slash -> ty
# * type-with-slash (, type-with-slash)+ -> ty
#
# the code is pretty funky in here, but this code would roughly
# translate in caml to:
# let rec type stream =
# match stream with
# | [< "->"; stream >] -> type stream
# | [< ""; stream >] ->
# type_with_slash stream
# type_lhs_1 stream;
# and type_1 stream = ...
'type': [
include('comments-and-spaces'),
(r'->', Keyword.Type),
(r'', Keyword.Type, ('#pop', 'type-lhs-1', 'type-with-slash')),
],
# parses all the atomic or closed constructions in the syntax of type
# expressions: record types, tuple types, type constructors, basic type
# and type variables
'type-1': [
include('comments-and-spaces'),
(r'\(', Keyword.Type, ('#pop', 'type-tuple')),
(r'~?{', Keyword.Type, ('#pop', 'type-record')),
(ident_re+r'\(', Keyword.Type, ('#pop', 'type-tuple')),
(ident_re, Keyword.Type, '#pop'),
("'"+ident_re, Keyword.Type),
# this case is not in the syntax but sometimes
# we think we are parsing types when in fact we are parsing
# some css, so we just pop the states until we get back into
# the root state
(r'', Keyword.Type, '#pop'),
],
# type-with-slash is either:
# * type-1
# * type-1 (/ type-1)+
'type-with-slash': [
include('comments-and-spaces'),
(r'', Keyword.Type, ('#pop', 'slash-type-1', 'type-1')),
],
'slash-type-1': [
include('comments-and-spaces'),
('/', Keyword.Type, ('#pop', 'type-1')),
# same remark as above
(r'', Keyword.Type, '#pop'),
],
# we go in this state after having parsed a type-with-slash
# while trying to parse a type
# and at this point we must determine if we are parsing an arrow
# type (in which case we must continue parsing) or not (in which
# case we stop)
'type-lhs-1': [
include('comments-and-spaces'),
(r'->', Keyword.Type, ('#pop', 'type')),
(r'(?=,)', Keyword.Type, ('#pop', 'type-arrow')),
(r'', Keyword.Type, '#pop'),
],
'type-arrow': [
include('comments-and-spaces'),
# the look ahead here allows to parse f(x : int, y : float -> truc)
# correctly
(r',(?=[^:]*?->)', Keyword.Type, 'type-with-slash'),
(r'->', Keyword.Type, ('#pop', 'type')),
# same remark as above
(r'', Keyword.Type, '#pop'),
],
# no need to do precise parsing for tuples and records
# because they are closed constructions, so we can simply
# find the closing delimiter
# note that this function would be not work if the source
# contained identifiers like `{)` (although it could be patched
# to support it)
'type-tuple': [
include('comments-and-spaces'),
(r'[^\(\)/*]+', Keyword.Type),
(r'[/*]', Keyword.Type),
(r'\(', Keyword.Type, '#push'),
(r'\)', Keyword.Type, '#pop'),
],
'type-record': [
include('comments-and-spaces'),
(r'[^{}/*]+', Keyword.Type),
(r'[/*]', Keyword.Type),
(r'{', Keyword.Type, '#push'),
(r'}', Keyword.Type, '#pop'),
],
# 'type-tuple': [
# include('comments-and-spaces'),
# (r'\)', Keyword.Type, '#pop'),
# (r'', Keyword.Type, ('#pop', 'type-tuple-1', 'type-1')),
# ],
# 'type-tuple-1': [
# include('comments-and-spaces'),
# (r',?\s*\)', Keyword.Type, '#pop'), # ,) is a valid end of tuple, in (1,)
# (r',', Keyword.Type, 'type-1'),
# ],
# 'type-record':[
# include('comments-and-spaces'),
# (r'}', Keyword.Type, '#pop'),
# (r'~?(?:\w+|`[^`]*`)', Keyword.Type, 'type-record-field-expr'),
# ],
# 'type-record-field-expr': [
#
# ],
'nested-comment': [
(r'[^/*]+', Comment),
(r'/\*', Comment, '#push'),
(r'\*/', Comment, '#pop'),
(r'[/*]', Comment),
],
# the copy pasting between string and single-string
# is kinda sad. Is there a way to avoid that??
'string': [
(r'[^\\"{]+', String.Double),
(r'"', String.Double, '#pop'),
(r'{', Operator, 'root'),
include('escape-sequence'),
],
'single-string': [
(r'[^\\\'{]+', String.Double),
(r'\'', String.Double, '#pop'),
(r'{', Operator, 'root'),
include('escape-sequence'),
],
# all the html stuff
# can't really reuse some existing html parser
# because we must be able to parse embedded expressions
# we are in this state after someone parsed the '<' that
# started the html literal
'html-open-tag': [
(r'[\w\-:]+', String.Single, ('#pop', 'html-attr')),
(r'>', String.Single, ('#pop', 'html-content')),
],
# we are in this state after someone parsed the '</' that
# started the end of the closing tag
'html-end-tag': [
# this is a star, because </> is allowed
(r'[\w\-:]*>', String.Single, '#pop'),
],
# we are in this state after having parsed '<ident(:ident)?'
# we thus parse a possibly empty list of attributes
'html-attr': [
(r'\s+', Text),
(r'[\w\-:]+=', String.Single, 'html-attr-value'),
(r'/>', String.Single, '#pop'),
(r'>', String.Single, ('#pop', 'html-content')),
],
'html-attr-value': [
(r"'", String.Single, ('#pop', 'single-string')),
(r'"', String.Single, ('#pop', 'string')),
(r'#'+ident_re, String.Single, '#pop'),
(r'#(?={)', String.Single, ('#pop', 'root')),
(r'[^"\'{`=<>]+', String.Single, '#pop'),
(r'{', Operator, ('#pop', 'root')), # this is a tail call!
],
# we should probably deal with '\' escapes here
'html-content': [
(r'<!--', Comment, 'html-comment'),
(r'</', String.Single, ('#pop', 'html-end-tag')),
(r'<', String.Single, 'html-open-tag'),
(r'{', Operator, 'root'),
(r'[^<{]+', String.Single),
],
'html-comment': [
(r'-->', Comment, '#pop'),
(r'[^\-]+|-', Comment),
],
}
class CoqLexer(RegexLexer):
"""
For the `Coq <http://coq.inria.fr/>`_ theorem prover.
*New in Pygments 1.5.*
"""
name = 'Coq'
aliases = ['coq']
filenames = ['*.v']
mimetypes = ['text/x-coq']
keywords1 = [
# Vernacular commands
'Section', 'Module', 'End', 'Require', 'Import', 'Export', 'Variable',
'Variables', 'Parameter', 'Parameters', 'Axiom', 'Hypothesis',
'Hypotheses', 'Notation', 'Local', 'Tactic', 'Reserved', 'Scope',
'Open', 'Close', 'Bind', 'Delimit', 'Definition', 'Let', 'Ltac',
'Fixpoint', 'CoFixpoint', 'Morphism', 'Relation', 'Implicit',
'Arguments', 'Set', 'Unset', 'Contextual', 'Strict', 'Prenex',
'Implicits', 'Inductive', 'CoInductive', 'Record', 'Structure',
'Canonical', 'Coercion', 'Theorem', 'Lemma', 'Corollary',
'Proposition', 'Fact', 'Remark', 'Example', 'Proof', 'Goal', 'Save',
'Qed', 'Defined', 'Hint', 'Resolve', 'Rewrite', 'View', 'Search',
'Show', 'Print', 'Printing', 'All', 'Graph', 'Projections', 'inside',
'outside',
]
keywords2 = [
# Gallina
'forall', 'exists', 'exists2', 'fun', 'fix', 'cofix', 'struct',
'match', 'end', 'in', 'return', 'let', 'if', 'is', 'then', 'else',
'for', 'of', 'nosimpl', 'with', 'as',
]
keywords3 = [
# Sorts
'Type', 'Prop',
]
keywords4 = [
# Tactics
'pose', 'set', 'move', 'case', 'elim', 'apply', 'clear', 'hnf', 'intro',
'intros', 'generalize', 'rename', 'pattern', 'after', 'destruct',
'induction', 'using', 'refine', 'inversion', 'injection', 'rewrite',
'congr', 'unlock', 'compute', 'ring', 'field', 'replace', 'fold',
'unfold', 'change', 'cutrewrite', 'simpl', 'have', 'suff', 'wlog',
'suffices', 'without', 'loss', 'nat_norm', 'assert', 'cut', 'trivial',
'revert', 'bool_congr', 'nat_congr', 'symmetry', 'transitivity', 'auto',
'split', 'left', 'right', 'autorewrite',
]
keywords5 = [
# Terminators
'by', 'done', 'exact', 'reflexivity', 'tauto', 'romega', 'omega',
'assumption', 'solve', 'contradiction', 'discriminate',
]
keywords6 = [
# Control
'do', 'last', 'first', 'try', 'idtac', 'repeat',
]
# 'as', 'assert', 'begin', 'class', 'constraint', 'do', 'done',
# 'downto', 'else', 'end', 'exception', 'external', 'false',
# 'for', 'fun', 'function', 'functor', 'if', 'in', 'include',
# 'inherit', 'initializer', 'lazy', 'let', 'match', 'method',
# 'module', 'mutable', 'new', 'object', 'of', 'open', 'private',
# 'raise', 'rec', 'sig', 'struct', 'then', 'to', 'true', 'try',
# 'type', 'val', 'virtual', 'when', 'while', 'with'
keyopts = [
'!=', '#', '&', '&&', r'\(', r'\)', r'\*', r'\+', ',', '-',
r'-\.', '->', r'\.', r'\.\.', ':', '::', ':=', ':>', ';', ';;', '<',
'<-', '=', '>', '>]', '>}', r'\?', r'\?\?', r'\[', r'\[<', r'\[>',
r'\[\|', ']', '_', '`', '{', '{<', r'\|', r'\|]', '}', '~', '=>',
r'/\\', r'\\/',
u'Π', u'λ',
]
operators = r'[!$%&*+\./:<=>?@^|~-]'
word_operators = ['and', 'asr', 'land', 'lor', 'lsl', 'lxor', 'mod', 'or']
prefix_syms = r'[!?~]'
infix_syms = r'[=<>@^|&+\*/$%-]'
primitives = ['unit', 'int', 'float', 'bool', 'string', 'char', 'list',
'array']
tokens = {
'root': [
(r'\s+', Text),
(r'false|true|\(\)|\[\]', Name.Builtin.Pseudo),
(r'\(\*', Comment, 'comment'),
(r'\b(%s)\b' % '|'.join(keywords1), Keyword.Namespace),
(r'\b(%s)\b' % '|'.join(keywords2), Keyword),
(r'\b(%s)\b' % '|'.join(keywords3), Keyword.Type),
(r'\b(%s)\b' % '|'.join(keywords4), Keyword),
(r'\b(%s)\b' % '|'.join(keywords5), Keyword.Pseudo),
(r'\b(%s)\b' % '|'.join(keywords6), Keyword.Reserved),
(r'\b([A-Z][A-Za-z0-9_\']*)(?=\s*\.)',
Name.Namespace, 'dotted'),
(r'\b([A-Z][A-Za-z0-9_\']*)', Name.Class),
(r'(%s)' % '|'.join(keyopts[::-1]), Operator),
(r'(%s|%s)?%s' % (infix_syms, prefix_syms, operators), Operator),
(r'\b(%s)\b' % '|'.join(word_operators), Operator.Word),
(r'\b(%s)\b' % '|'.join(primitives), Keyword.Type),
(r"[^\W\d][\w']*", Name),
(r'\d[\d_]*', Number.Integer),
(r'0[xX][\da-fA-F][\da-fA-F_]*', Number.Hex),
(r'0[oO][0-7][0-7_]*', Number.Oct),
(r'0[bB][01][01_]*', Number.Binary),
(r'-?\d[\d_]*(.[\d_]*)?([eE][+\-]?\d[\d_]*)', Number.Float),
(r"'(?:(\\[\\\"'ntbr ])|(\\[0-9]{3})|(\\x[0-9a-fA-F]{2}))'",
String.Char),
(r"'.'", String.Char),
(r"'", Keyword), # a stray quote is another syntax element
(r'"', String.Double, 'string'),
(r'[~?][a-z][\w\']*:', Name.Variable),
],
'comment': [
(r'[^(*)]+', Comment),
(r'\(\*', Comment, '#push'),
(r'\*\)', Comment, '#pop'),
(r'[(*)]', Comment),
],
'string': [
(r'[^"]+', String.Double),
(r'""', String.Double),
(r'"', String.Double, '#pop'),
],
'dotted': [
(r'\s+', Text),
(r'\.', Punctuation),
(r'[A-Z][A-Za-z0-9_\']*(?=\s*\.)', Name.Namespace),
(r'[A-Z][A-Za-z0-9_\']*', Name.Class, '#pop'),
(r'[a-z][a-z0-9_\']*', Name, '#pop'),
(r'', Text, '#pop')
],
}
def analyse_text(text):
if text.startswith('(*'):
return True
class NewLispLexer(RegexLexer):
"""
For `newLISP. <www.newlisp.org>`_ source code (version 10.3.0).
*New in Pygments 1.5.*
"""
name = 'NewLisp'
aliases = ['newlisp']
filenames = ['*.lsp', '*.nl']
mimetypes = ['text/x-newlisp', 'application/x-newlisp']
flags = re.IGNORECASE | re.MULTILINE | re.UNICODE
# list of built-in functions for newLISP version 10.3
builtins = [
'^', '--', '-', ':', '!', '!=', '?', '@', '*', '/', '&', '%', '+', '++',
'<', '<<', '<=', '=', '>', '>=', '>>', '|', '~', '$', '$0', '$1', '$10',
'$11', '$12', '$13', '$14', '$15', '$2', '$3', '$4', '$5', '$6', '$7',
'$8', '$9', '$args', '$idx', '$it', '$main-args', 'abort', 'abs',
'acos', 'acosh', 'add', 'address', 'amb', 'and', 'and', 'append-file',
'append', 'apply', 'args', 'array-list', 'array?', 'array', 'asin',
'asinh', 'assoc', 'atan', 'atan2', 'atanh', 'atom?', 'base64-dec',
'base64-enc', 'bayes-query', 'bayes-train', 'begin', 'begin', 'begin',
'beta', 'betai', 'bind', 'binomial', 'bits', 'callback', 'case', 'case',
'case', 'catch', 'ceil', 'change-dir', 'char', 'chop', 'Class', 'clean',
'close', 'command-event', 'cond', 'cond', 'cond', 'cons', 'constant',
'context?', 'context', 'copy-file', 'copy', 'cos', 'cosh', 'count',
'cpymem', 'crc32', 'crit-chi2', 'crit-z', 'current-line', 'curry',
'date-list', 'date-parse', 'date-value', 'date', 'debug', 'dec',
'def-new', 'default', 'define-macro', 'define-macro', 'define',
'delete-file', 'delete-url', 'delete', 'destroy', 'det', 'device',
'difference', 'directory?', 'directory', 'div', 'do-until', 'do-while',
'doargs', 'dolist', 'dostring', 'dotimes', 'dotree', 'dump', 'dup',
'empty?', 'encrypt', 'ends-with', 'env', 'erf', 'error-event',
'eval-string', 'eval', 'exec', 'exists', 'exit', 'exp', 'expand',
'explode', 'extend', 'factor', 'fft', 'file-info', 'file?', 'filter',
'find-all', 'find', 'first', 'flat', 'float?', 'float', 'floor', 'flt',
'fn', 'for-all', 'for', 'fork', 'format', 'fv', 'gammai', 'gammaln',
'gcd', 'get-char', 'get-float', 'get-int', 'get-long', 'get-string',
'get-url', 'global?', 'global', 'if-not', 'if', 'ifft', 'import', 'inc',
'index', 'inf?', 'int', 'integer?', 'integer', 'intersect', 'invert',
'irr', 'join', 'lambda-macro', 'lambda?', 'lambda', 'last-error',
'last', 'legal?', 'length', 'let', 'let', 'let', 'letex', 'letn',
'letn', 'letn', 'list?', 'list', 'load', 'local', 'log', 'lookup',
'lower-case', 'macro?', 'main-args', 'MAIN', 'make-dir', 'map', 'mat',
'match', 'max', 'member', 'min', 'mod', 'module', 'mul', 'multiply',
'NaN?', 'net-accept', 'net-close', 'net-connect', 'net-error',
'net-eval', 'net-interface', 'net-ipv', 'net-listen', 'net-local',
'net-lookup', 'net-packet', 'net-peek', 'net-peer', 'net-ping',
'net-receive-from', 'net-receive-udp', 'net-receive', 'net-select',
'net-send-to', 'net-send-udp', 'net-send', 'net-service',
'net-sessions', 'new', 'nil?', 'nil', 'normal', 'not', 'now', 'nper',
'npv', 'nth', 'null?', 'number?', 'open', 'or', 'ostype', 'pack',
'parse-date', 'parse', 'peek', 'pipe', 'pmt', 'pop-assoc', 'pop',
'post-url', 'pow', 'prefix', 'pretty-print', 'primitive?', 'print',
'println', 'prob-chi2', 'prob-z', 'process', 'prompt-event',
'protected?', 'push', 'put-url', 'pv', 'quote?', 'quote', 'rand',
'random', 'randomize', 'read', 'read-char', 'read-expr', 'read-file',
'read-key', 'read-line', 'read-utf8', 'read', 'reader-event',
'real-path', 'receive', 'ref-all', 'ref', 'regex-comp', 'regex',
'remove-dir', 'rename-file', 'replace', 'reset', 'rest', 'reverse',
'rotate', 'round', 'save', 'search', 'seed', 'seek', 'select', 'self',
'semaphore', 'send', 'sequence', 'series', 'set-locale', 'set-ref-all',
'set-ref', 'set', 'setf', 'setq', 'sgn', 'share', 'signal', 'silent',
'sin', 'sinh', 'sleep', 'slice', 'sort', 'source', 'spawn', 'sqrt',
'starts-with', 'string?', 'string', 'sub', 'swap', 'sym', 'symbol?',
'symbols', 'sync', 'sys-error', 'sys-info', 'tan', 'tanh', 'term',
'throw-error', 'throw', 'time-of-day', 'time', 'timer', 'title-case',
'trace-highlight', 'trace', 'transpose', 'Tree', 'trim', 'true?',
'true', 'unicode', 'unify', 'unique', 'unless', 'unpack', 'until',
'upper-case', 'utf8', 'utf8len', 'uuid', 'wait-pid', 'when', 'while',
'write', 'write-char', 'write-file', 'write-line', 'write',
'xfer-event', 'xml-error', 'xml-parse', 'xml-type-tags', 'zero?',
]
# valid names
valid_name = r'([a-zA-Z0-9!$%&*+.,/<=>?@^_~|-])+|(\[.*?\])+'
tokens = {
'root': [
# shebang
(r'#!(.*?)$', Comment.Preproc),
# comments starting with semicolon
(r';.*$', Comment.Single),
# comments starting with #
(r'#.*$', Comment.Single),
# whitespace
(r'\s+', Text),
# strings, symbols and characters
(r'"(\\\\|\\"|[^"])*"', String),
# braces
(r"{", String, "bracestring"),
# [text] ... [/text] delimited strings
(r'\[text\]*', String, "tagstring"),
# 'special' operators...
(r"('|:)", Operator),
# highlight the builtins
('(%s)' % '|'.join(re.escape(entry) + '\\b' for entry in builtins),
Keyword),
# the remaining functions
(r'(?<=\()' + valid_name, Name.Variable),
# the remaining variables
(valid_name, String.Symbol),
# parentheses
(r'(\(|\))', Punctuation),
],
# braced strings...
'bracestring': [
("{", String, "#push"),
("}", String, "#pop"),
("[^{}]+", String),
],
# tagged [text]...[/text] delimited strings...
'tagstring': [
(r'(?s)(.*?)(\[/text\])', String, '#pop'),
],
}
class ElixirLexer(RegexLexer):
"""
For the `Elixir language <http://elixir-lang.org>`_.
*New in Pygments 1.5.*
"""
name = 'Elixir'
aliases = ['elixir', 'ex', 'exs']
filenames = ['*.ex', '*.exs']
mimetypes = ['text/x-elixir']
def gen_elixir_sigil_rules():
states = {}
states['strings'] = [
(r'(%[A-Ba-z])?"""(?:.|\n)*?"""', String.Doc),
(r"'''(?:.|\n)*?'''", String.Doc),
(r'"', String.Double, 'dqs'),
(r"'.*'", String.Single),
(r'(?<!\w)\?(\\(x\d{1,2}|\h{1,2}(?!\h)\b|0[0-7]{0,2}(?![0-7])\b|'
r'[^x0MC])|(\\[MC]-)+\w|[^\s\\])', String.Other)
]
for lbrace, rbrace, name, in ('\\{', '\\}', 'cb'), \
('\\[', '\\]', 'sb'), \
('\\(', '\\)', 'pa'), \
('\\<', '\\>', 'lt'):
states['strings'] += [
(r'%[a-z]' + lbrace, String.Double, name + 'intp'),
(r'%[A-Z]' + lbrace, String.Double, name + 'no-intp')
]
states[name +'intp'] = [
(r'' + rbrace + '[a-z]*', String.Double, "#pop"),
include('enddoublestr')
]
states[name +'no-intp'] = [
(r'.*' + rbrace + '[a-z]*', String.Double , "#pop")
]
return states
tokens = {
'root': [
(r'\s+', Text),
(r'#.*$', Comment.Single),
(r'\b(case|cond|end|bc|lc|if|unless|try|loop|receive|fn|defmodule|'
r'defp?|defprotocol|defimpl|defrecord|defmacrop?|defdelegate|'
r'defexception|exit|raise|throw|unless|after|rescue|catch|else)\b(?![?!])|'
r'(?<!\.)\b(do|\-\>)\b\s*', Keyword),
(r'\b(import|require|use|recur|quote|unquote|super|refer)\b(?![?!])',
Keyword.Namespace),
(r'(?<!\.)\b(and|not|or|when|xor|in)\b', Operator.Word),
(r'%=|\*=|\*\*=|\+=|\-=|\^=|\|\|=|'
r'<=>|<(?!<|=)|>(?!<|=|>)|<=|>=|===|==|=~|!=|!~|(?=[ \t])\?|'
r'(?<=[ \t])!+|&&|\|\||\^|\*|\+|\-|/|'
r'\||\+\+|\-\-|\*\*|\/\/|\<\-|\<\>|<<|>>|=|\.', Operator),
(r'(?<!:)(:)([a-zA-Z_]\w*([?!]|=(?![>=]))?|\<\>|===?|>=?|<=?|'
r'<=>|&&?|%\(\)|%\[\]|%\{\}|\+\+?|\-\-?|\|\|?|\!|//|[%&`/\|]|'
r'\*\*?|=?~|<\-)|([a-zA-Z_]\w*([?!])?)(:)(?!:)', String.Symbol),
(r':"', String.Symbol, 'interpoling_symbol'),
(r'\b(nil|true|false)\b(?![?!])|\b[A-Z]\w*\b', Name.Constant),
(r'\b(__(FILE|LINE|MODULE|MAIN|FUNCTION)__)\b(?![?!])', Name.Builtin.Pseudo),
(r'[a-zA-Z_!][\w_]*[!\?]?', Name),
(r'[(){};,/\|:\\\[\]]', Punctuation),
(r'@[a-zA-Z_]\w*|&\d', Name.Variable),
(r'\b(0[xX][0-9A-Fa-f]+|\d(_?\d)*(\.(?![^\d\s])'
r'(_?\d)*)?([eE][-+]?\d(_?\d)*)?|0[bB][01]+)\b', Number),
(r'%r\/.*\/', String.Regex),
include('strings'),
],
'dqs': [
(r'"', String.Double, "#pop"),
include('enddoublestr')
],
'interpoling': [
(r'#{', String.Interpol, 'interpoling_string'),
],
'interpoling_string' : [
(r'}', String.Interpol, "#pop"),
include('root')
],
'interpoling_symbol': [
(r'"', String.Symbol, "#pop"),
include('interpoling'),
(r'[^#"]+', String.Symbol),
],
'enddoublestr' : [
include('interpoling'),
(r'[^#"]+', String.Double),
]
}
tokens.update(gen_elixir_sigil_rules())
class ElixirConsoleLexer(Lexer):
"""
For Elixir interactive console (iex) output like:
.. sourcecode:: iex
iex> [head | tail] = [1,2,3]
[1,2,3]
iex> head
1
iex> tail
[2,3]
iex> [head | tail]
[1,2,3]
iex> length [head | tail]
3
*New in Pygments 1.5.*
"""
name = 'Elixir iex session'
aliases = ['iex']
mimetypes = ['text/x-elixir-shellsession']
_prompt_re = re.compile('(iex|\.{3})> ')
def get_tokens_unprocessed(self, text):
exlexer = ElixirLexer(**self.options)
curcode = ''
insertions = []
for match in line_re.finditer(text):
line = match.group()
if line.startswith(u'** '):
insertions.append((len(curcode),
[(0, Generic.Error, line[:-1])]))
curcode += line[-1:]
else:
m = self._prompt_re.match(line)
if m is not None:
end = m.end()
insertions.append((len(curcode),
[(0, Generic.Prompt, line[:end])]))
curcode += line[end:]
else:
if curcode:
for item in do_insertions(insertions,
exlexer.get_tokens_unprocessed(curcode)):
yield item
curcode = ''
insertions = []
yield match.start(), Generic.Output, line
if curcode:
for item in do_insertions(insertions,
exlexer.get_tokens_unprocessed(curcode)):
yield item
class KokaLexer(RegexLexer):
"""
Lexer for the `Koka <http://research.microsoft.com/en-us/projects/koka/>`_
language.
*New in Pygments 1.6.*
"""
name = 'Koka'
aliases = ['koka']
filenames = ['*.kk', '*.kki']
mimetypes = ['text/x-koka']
keywords = [
'infix', 'infixr', 'infixl', 'prefix', 'postfix',
'type', 'cotype', 'rectype', 'alias',
'struct', 'con',
'fun', 'function', 'val', 'var',
'external',
'if', 'then', 'else', 'elif', 'return', 'match',
'private', 'public', 'private',
'module', 'import', 'as',
'include', 'inline',
'rec',
'try', 'yield', 'enum',
'interface', 'instance',
]
# keywords that are followed by a type
typeStartKeywords = [
'type', 'cotype', 'rectype', 'alias', 'struct', 'enum',
]
# keywords valid in a type
typekeywords = [
'forall', 'exists', 'some', 'with',
]
# builtin names and special names
builtin = [
'for', 'while', 'repeat',
'foreach', 'foreach-indexed',
'error', 'catch', 'finally',
'cs', 'js', 'file', 'ref', 'assigned',
]
# symbols that can be in an operator
symbols = '[\$%&\*\+@!/\\\^~=\.:\-\?\|<>]+'
# symbol boundary: an operator keyword should not be followed by any of these
sboundary = '(?!'+symbols+')'
# name boundary: a keyword should not be followed by any of these
boundary = '(?![a-zA-Z0-9_\\-])'
# main lexer
tokens = {
'root': [
include('whitespace'),
# go into type mode
(r'::?' + sboundary, Keyword.Type, 'type'),
(r'alias' + boundary, Keyword, 'alias-type'),
(r'struct' + boundary, Keyword, 'struct-type'),
(r'(%s)' % '|'.join(typeStartKeywords) + boundary, Keyword, 'type'),
# special sequences of tokens (we use ?: for non-capturing group as
# required by 'bygroups')
(r'(module)(\s*)((?:interface)?)(\s*)'
r'((?:[a-z](?:[a-zA-Z0-9_]|\-[a-zA-Z])*\.)*'
r'[a-z](?:[a-zA-Z0-9_]|\-[a-zA-Z])*)',
bygroups(Keyword, Text, Keyword, Text, Name.Namespace)),
(r'(import)(\s+)((?:[a-z](?:[a-zA-Z0-9_]|\-[a-zA-Z])*\.)*[a-z]'
r'(?:[a-zA-Z0-9_]|\-[a-zA-Z])*)(\s*)((?:as)?)'
r'((?:[A-Z](?:[a-zA-Z0-9_]|\-[a-zA-Z])*)?)',
bygroups(Keyword, Text, Name.Namespace, Text, Keyword,
Name.Namespace)),
# keywords
(r'(%s)' % '|'.join(typekeywords) + boundary, Keyword.Type),
(r'(%s)' % '|'.join(keywords) + boundary, Keyword),
(r'(%s)' % '|'.join(builtin) + boundary, Keyword.Pseudo),
(r'::|:=|\->|[=\.:]' + sboundary, Keyword),
(r'\-' + sboundary, Generic.Strong),
# names
(r'[A-Z]([a-zA-Z0-9_]|\-[a-zA-Z])*(?=\.)', Name.Namespace),
(r'[A-Z]([a-zA-Z0-9_]|\-[a-zA-Z])*(?!\.)', Name.Class),
(r'[a-z]([a-zA-Z0-9_]|\-[a-zA-Z])*', Name),
(r'_([a-zA-Z0-9_]|\-[a-zA-Z])*', Name.Variable),
# literal string
(r'@"', String.Double, 'litstring'),
# operators
(symbols, Operator),
(r'`', Operator),
(r'[\{\}\(\)\[\];,]', Punctuation),
# literals. No check for literal characters with len > 1
(r'[0-9]+\.[0-9]+([eE][\-\+]?[0-9]+)?', Number.Float),
(r'0[xX][0-9a-fA-F]+', Number.Hex),
(r'[0-9]+', Number.Integer),
(r"'", String.Char, 'char'),
(r'"', String.Double, 'string'),
],
# type started by alias
'alias-type': [
(r'=',Keyword),
include('type')
],
# type started by struct
'struct-type': [
(r'(?=\((?!,*\)))',Punctuation, '#pop'),
include('type')
],
# type started by colon
'type': [
(r'[\(\[<]', Keyword.Type, 'type-nested'),
include('type-content')
],
# type nested in brackets: can contain parameters, comma etc.
'type-nested': [
(r'[\)\]>]', Keyword.Type, '#pop'),
(r'[\(\[<]', Keyword.Type, 'type-nested'),
(r',', Keyword.Type),
(r'([a-z](?:[a-zA-Z0-9_]|\-[a-zA-Z])*)(\s*)(:)(?!:)',
bygroups(Name.Variable,Text,Keyword.Type)), # parameter name
include('type-content')
],
# shared contents of a type
'type-content': [
include('whitespace'),
# keywords
(r'(%s)' % '|'.join(typekeywords) + boundary, Keyword.Type),
(r'(?=((%s)' % '|'.join(keywords) + boundary + '))',
Keyword, '#pop'), # need to match because names overlap...
# kinds
(r'[EPH]' + boundary, Keyword.Type),
(r'[*!]', Keyword.Type),
# type names
(r'[A-Z]([a-zA-Z0-9_]|\-[a-zA-Z])*(?=\.)', Name.Namespace),
(r'[A-Z]([a-zA-Z0-9_]|\-[a-zA-Z])*(?!\.)', Name.Class),
(r'[a-z][0-9]*(?![a-zA-Z_\-])', Keyword.Type), # Generic.Emph
(r'_([a-zA-Z0-9_]|\-[a-zA-Z])*', Keyword.Type), # Generic.Emph
(r'[a-z]([a-zA-Z0-9_]|\-[a-zA-Z])*', Keyword.Type),
# type keyword operators
(r'::|\->|[\.:|]', Keyword.Type),
#catchall
(r'', Text, '#pop')
],
# comments and literals
'whitespace': [
(r'\s+', Text),
(r'/\*', Comment.Multiline, 'comment'),
(r'//.*$', Comment.Single)
],
'comment': [
(r'[^/\*]+', Comment.Multiline),
(r'/\*', Comment.Multiline, '#push'),
(r'\*/', Comment.Multiline, '#pop'),
(r'[\*/]', Comment.Multiline),
],
'litstring': [
(r'[^"]+', String.Double),
(r'""', String.Escape),
(r'"', String.Double, '#pop'),
],
'string': [
(r'[^\\"\n]+', String.Double),
include('escape-sequence'),
(r'["\n]', String.Double, '#pop'),
],
'char': [
(r'[^\\\'\n]+', String.Char),
include('escape-sequence'),
(r'[\'\n]', String.Char, '#pop'),
],
'escape-sequence': [
(r'\\[abfnrtv0\\\"\'\?]', String.Escape),
(r'\\x[0-9a-fA-F]{2}', String.Escape),
(r'\\u[0-9a-fA-F]{4}', String.Escape),
# Yes, \U literals are 6 hex digits.
(r'\\U[0-9a-fA-F]{6}', String.Escape)
]
}
| apache-2.0 |
asankas/developer-studio | esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/edit/parts/CloneTargetContainerEditPart.java | 8799 | package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.PositionConstants;
import org.eclipse.draw2d.RoundedRectangle;
import org.eclipse.draw2d.Shape;
import org.eclipse.draw2d.StackLayout;
import org.eclipse.draw2d.ToolbarLayout;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.LayoutEditPolicy;
import org.eclipse.gef.editpolicies.NonResizableEditPolicy;
import org.eclipse.gef.requests.CreateRequest;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeNodeEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.CreationEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.DragDropEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles;
import org.eclipse.gmf.runtime.diagram.ui.figures.BorderItemLocator;
import org.eclipse.gmf.runtime.draw2d.ui.figures.ConstrainedToolbarLayout;
import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel;
import org.eclipse.gmf.runtime.gef.ui.figures.DefaultSizeNodeFigure;
import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.gmf.tooling.runtime.edit.policies.reparent.CreationEditPolicyWithCustomReparent;
import org.eclipse.swt.graphics.Color;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.CloneMediatorGraphicalShape;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.FixedBorderItemLocator;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.policies.CloneTargetContainerCanonicalEditPolicy;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.policies.CloneTargetContainerItemSemanticEditPolicy;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbVisualIDRegistry;
/**
* @generated
*/
public class CloneTargetContainerEditPart extends ShapeNodeEditPart {
/**
* @generated
*/
public static final int VISUAL_ID = 3604;
/**
* @generated
*/
protected IFigure contentPane;
/**
* @generated
*/
protected IFigure primaryShape;
/**
* @generated
*/
public CloneTargetContainerEditPart(View view) {
super(view);
}
/**
* @generated
*/
protected void createDefaultEditPolicies() {
installEditPolicy(EditPolicyRoles.CREATION_ROLE, new CreationEditPolicyWithCustomReparent(
EsbVisualIDRegistry.TYPED_INSTANCE));
super.createDefaultEditPolicies();
installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE,
new CloneTargetContainerItemSemanticEditPolicy());
installEditPolicy(EditPolicyRoles.DRAG_DROP_ROLE, new DragDropEditPolicy());
installEditPolicy(EditPolicyRoles.CANONICAL_ROLE,
new CloneTargetContainerCanonicalEditPolicy());
installEditPolicy(EditPolicy.LAYOUT_ROLE, createLayoutEditPolicy());
// XXX need an SCR to runtime to have another abstract superclass that would let children add reasonable editpolicies
// removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.CONNECTION_HANDLES_ROLE);
}
/**
* @generated
*/
protected LayoutEditPolicy createLayoutEditPolicy() {
org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy lep = new org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy() {
protected EditPolicy createChildEditPolicy(EditPart child) {
EditPolicy result = child.getEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE);
if (result == null) {
result = new NonResizableEditPolicy();
}
return result;
}
protected Command getMoveChildrenCommand(Request request) {
return null;
}
protected Command getCreateCommand(CreateRequest request) {
return null;
}
};
return lep;
}
/**
* @generated
*/
protected IFigure createNodeShape() {
return primaryShape = new CloneMediatorFigure();
}
/**
* @generated
*/
public CloneMediatorFigure getPrimaryShape() {
return (CloneMediatorFigure) primaryShape;
}
/**
* @generated
*/
protected NodeFigure createNodePlate() {
DefaultSizeNodeFigure result = new DefaultSizeNodeFigure(40, 40);
return result;
}
public void refreshOutputConnector(EditPart childEditPart) {
if (childEditPart instanceof CloneMediatorEditPart) {
CloneMediatorEditPart cloneMediatorEditPart = (CloneMediatorEditPart) childEditPart;
if (cloneMediatorEditPart.targetOutputConnectors.size() != 0) {
BorderItemLocator locator = new FixedBorderItemLocator(this.getFigure(),
cloneMediatorEditPart.targetOutputConnectors.get(0),
PositionConstants.WEST, 0.5);
if (cloneMediatorEditPart.targetOutputConnectors.get(0) != null) {
cloneMediatorEditPart.getBorderedFigure().getBorderItemContainer()
.add(cloneMediatorEditPart.targetOutputConnectors.get(0), locator);
}
}
} else {
//Should handle properly.
throw new ClassCastException();
}
}
protected void addChildVisual(EditPart childEditPart, int index) {
refreshOutputConnector(((CloneMediatorEditPart) childEditPart.getParent().getParent()
.getParent()));
super.addChildVisual(childEditPart, -1);
}
/**
* Creates figure for this edit part.
*
* Body of this method does not depend on settings in generation model
* so you may safely remove <i>generated</i> tag and modify it.
*
* @generated
*/
protected NodeFigure createNodeFigure() {
NodeFigure figure = createNodePlate();
figure.setLayoutManager(new StackLayout());
IFigure shape = createNodeShape();
figure.add(shape);
contentPane = setupContentPane(shape);
return figure;
}
/**
* Default implementation treats passed figure as content pane.
* Respects layout one may have set for generated figure.
* @param nodeShape instance of generated figure class
* @generated
*/
protected IFigure setupContentPane(IFigure nodeShape) {
if (nodeShape.getLayoutManager() == null) {
ConstrainedToolbarLayout layout = new ConstrainedToolbarLayout();
layout.setSpacing(5);
nodeShape.setLayoutManager(layout);
}
return nodeShape; // use nodeShape itself as contentPane
}
/**
* @generated
*/
public IFigure getContentPane() {
if (contentPane != null) {
return contentPane;
}
return super.getContentPane();
}
/**
* @generated
*/
protected void setForegroundColor(Color color) {
if (primaryShape != null) {
primaryShape.setForegroundColor(color);
}
}
/**
* @generated
*/
protected void setBackgroundColor(Color color) {
if (primaryShape != null) {
primaryShape.setBackgroundColor(color);
}
}
/**
* @generated
*/
protected void setLineWidth(int width) {
if (primaryShape instanceof Shape) {
((Shape) primaryShape).setLineWidth(width);
}
}
/**
* @generated
*/
protected void setLineType(int style) {
if (primaryShape instanceof Shape) {
((Shape) primaryShape).setLineStyle(style);
}
}
/**
* @generated NOT
*/
public class CloneMediatorFigure extends RoundedRectangle {
/**
* @generated
*/
private WrappingLabel fFigureCloneMediatorPropertyValue;
/**
* @generated NOT
*/
public CloneMediatorFigure() {
ToolbarLayout layoutThis = new ToolbarLayout();
layoutThis.setStretchMinorAxis(true);
layoutThis.setMinorAlignment(ToolbarLayout.ALIGN_CENTER);
layoutThis.setSpacing(0);
layoutThis.setVertical(true);
this.setLayoutManager(layoutThis);
this.setAlpha(0); //to make this transparent
this.setCornerDimensions(new Dimension(getMapMode().DPtoLP(0), getMapMode().DPtoLP(0)));
//Fixing TOOLS-1972.
this.setMinimumSize(new Dimension(getMapMode().DPtoLP(60), getMapMode().DPtoLP(100)));
this.setLineStyle(Graphics.LINE_DASH);
this.setBackgroundColor(THIS_BACK);
}
/**
* @generated
*/
private void createContents() {
fFigureCloneMediatorPropertyValue = new WrappingLabel();
fFigureCloneMediatorPropertyValue.setText("<...>");
this.add(fFigureCloneMediatorPropertyValue);
}
/**
* @generated
*/
public WrappingLabel getFigureCloneMediatorPropertyValue() {
return fFigureCloneMediatorPropertyValue;
}
/* *//**
* @generated
*/
/*
private void createContents() {
fFigureCloneMediatorPropertyValue = new WrappingLabel();
fFigureCloneMediatorPropertyValue.setText("<...>");
this.add(fFigureCloneMediatorPropertyValue);
}
*//**
* @generated
*/
/*
public WrappingLabel getFigureCloneMediatorPropertyValue() {
return fFigureCloneMediatorPropertyValue;
}*/
}
public boolean isSelectable() {
// TODO This or using ResizableEditpolicy?
return false;
}
/**
* @generated
*/
static final Color THIS_BACK = new Color(null, 230, 230, 230);
}
| apache-2.0 |
rgoldberg/guava | guava-gwt/test/com/google/common/collect/HashingTest_gwt.java | 975 | /*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
public class HashingTest_gwt extends com.google.gwt.junit.client.GWTTestCase {
@Override public String getModuleName() {
return "com.google.common.collect.testModule";
}
public void testSmear() throws Exception {
com.google.common.collect.HashingTest testCase = new com.google.common.collect.HashingTest();
testCase.testSmear();
}
}
| apache-2.0 |
romanoff/google-closure-library | closure/goog/ui/select.js | 12189 | // Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A class that supports single selection from a dropdown menu,
* with semantics similar to the native HTML <code><select></code>
* element.
*
* @see ../demos/select.html
*/
goog.provide('goog.ui.Select');
goog.require('goog.events.EventType');
goog.require('goog.ui.Component.EventType');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.MenuButton');
goog.require('goog.ui.SelectionModel');
goog.require('goog.ui.registry');
/**
* A selection control. Extends {@link goog.ui.MenuButton} by composing a
* menu with a selection model, and automatically updating the button's caption
* based on the current selection.
*
* @param {goog.ui.ControlContent} caption Default caption or existing DOM
* structure to display as the button's caption when nothing is selected.
* @param {goog.ui.Menu=} opt_menu Menu containing selection options.
* @param {goog.ui.ButtonRenderer=} opt_renderer Renderer used to render or
* decorate the control; defaults to {@link goog.ui.MenuButtonRenderer}.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for
* document interaction.
* @constructor
* @extends {goog.ui.MenuButton}
*/
goog.ui.Select = function(caption, opt_menu, opt_renderer, opt_domHelper) {
goog.ui.MenuButton.call(this, caption, opt_menu, opt_renderer, opt_domHelper);
this.setDefaultCaption(caption);
};
goog.inherits(goog.ui.Select, goog.ui.MenuButton);
/**
* The selection model controlling the items in the menu.
* @type {goog.ui.SelectionModel}
* @private
*/
goog.ui.Select.prototype.selectionModel_ = null;
/**
* Default caption to be shown when no option is selected.
* @type {goog.ui.ControlContent}
* @private
*/
goog.ui.Select.prototype.defaultCaption_ = null;
/**
* Configures the component after its DOM has been rendered, and sets up event
* handling. Overrides {@link goog.ui.MenuButton#enterDocument}.
*/
goog.ui.Select.prototype.enterDocument = function() {
goog.ui.Select.superClass_.enterDocument.call(this);
this.updateCaption_();
this.listenToSelectionModelEvents_();
};
/**
* Decorates the given element with this control. Overrides the superclass
* implementation by initializing the default caption on the select button.
* @param {Element} element Element to decorate.
*/
goog.ui.Select.prototype.decorateInternal = function(element) {
goog.ui.Select.superClass_.decorateInternal.call(this, element);
var caption = this.getCaption();
if (caption) {
// Initialize the default caption.
this.setDefaultCaption(caption);
} else {
// There is no default caption; select the first option.
this.setSelectedIndex(0);
}
};
/** @inheritDoc */
goog.ui.Select.prototype.disposeInternal = function() {
goog.ui.Select.superClass_.disposeInternal.call(this);
if (this.selectionModel_) {
this.selectionModel_.dispose();
this.selectionModel_ = null;
}
this.defaultCaption_ = null;
};
/**
* Handles {@link goog.ui.Component.EventType.ACTION} events dispatched by
* the menu item clicked by the user. Updates the selection model, calls
* the superclass implementation to hide the menu, stops the propagation of
* the event, and dispatches an ACTION event on behalf of the select control
* itself. Overrides {@link goog.ui.MenuButton#handleMenuAction}.
* @param {goog.events.Event} e Action event to handle.
*/
goog.ui.Select.prototype.handleMenuAction = function(e) {
this.setSelectedItem(/** @type {goog.ui.MenuItem} */ (e.target));
goog.ui.Select.superClass_.handleMenuAction.call(this, e);
e.stopPropagation();
this.dispatchEvent(goog.ui.Component.EventType.ACTION);
};
/**
* Handles {@link goog.events.EventType.SELECT} events raised by the
* selection model when the selection changes. Updates the contents of the
* select button.
* @param {goog.events.Event} e Selection event to handle.
*/
goog.ui.Select.prototype.handleSelectionChange = function(e) {
var item = this.getSelectedItem();
goog.ui.Select.superClass_.setValue.call(this, item && item.getValue());
this.updateCaption_();
};
/**
* Replaces the menu currently attached to the control (if any) with the given
* argument, and updates the selection model. Does nothing if the new menu is
* the same as the old one. Overrides {@link goog.ui.MenuButton#setMenu}.
* @param {goog.ui.Menu} menu New menu to be attached to the menu button.
* @return {goog.ui.Menu|undefined} Previous menu (undefined if none).
*/
goog.ui.Select.prototype.setMenu = function(menu) {
// Call superclass implementation to replace the menu.
var oldMenu = goog.ui.Select.superClass_.setMenu.call(this, menu);
// Do nothing unless the new menu is different from the current one.
if (menu != oldMenu) {
// Clear the old selection model (if any).
if (this.selectionModel_) {
this.selectionModel_.clear();
}
// Initialize new selection model (unless the new menu is null).
if (menu) {
if (this.selectionModel_) {
menu.forEachChild(function(child, index) {
this.selectionModel_.addItem(child);
}, this);
} else {
this.createSelectionModel_(menu);
}
}
}
return oldMenu;
};
/**
* Returns the default caption to be shown when no option is selected.
* @return {goog.ui.ControlContent} Default caption.
*/
goog.ui.Select.prototype.getDefaultCaption = function() {
return this.defaultCaption_;
};
/**
* Sets the default caption to the given string or DOM structure.
* @param {goog.ui.ControlContent} caption Default caption to be shown
* when no option is selected.
*/
goog.ui.Select.prototype.setDefaultCaption = function(caption) {
this.defaultCaption_ = caption;
this.updateCaption_();
};
/**
* Adds a new menu item at the end of the menu.
* @param {goog.ui.MenuItem|goog.ui.MenuSeparator} item Menu item to add to the
* menu.
*/
goog.ui.Select.prototype.addItem = function(item) {
goog.ui.Select.superClass_.addItem.call(this, item);
if (this.selectionModel_) {
this.selectionModel_.addItem(item);
} else {
this.createSelectionModel_(this.getMenu());
}
};
/**
* Adds a new menu item at a specific index in the menu.
* @param {goog.ui.MenuItem|goog.ui.MenuSeparator} item Menu item to add to the
* menu.
* @param {number} index Index at which to insert the menu item.
*/
goog.ui.Select.prototype.addItemAt = function(item, index) {
goog.ui.Select.superClass_.addItemAt.call(this, item, index);
if (this.selectionModel_) {
this.selectionModel_.addItemAt(item, index);
} else {
this.createSelectionModel_(this.getMenu());
}
};
/**
* Removes an item from the menu and disposes it.
* @param {goog.ui.MenuItem} item The menu item to remove.
*/
goog.ui.Select.prototype.removeItem = function(item) {
goog.ui.Select.superClass_.removeItem.call(this, item);
if (this.selectionModel_) {
this.selectionModel_.removeItem(item);
}
};
/**
* Removes a menu item at a given index in the menu and disposes it.
* @param {number} index Index of item.
*/
goog.ui.Select.prototype.removeItemAt = function(index) {
goog.ui.Select.superClass_.removeItemAt.call(this, index);
if (this.selectionModel_) {
this.selectionModel_.removeItemAt(index);
}
};
/**
* Selects the specified option (assumed to be in the select menu), and
* deselects the previously selected option, if any. A null argument clears
* the selection.
* @param {goog.ui.MenuItem} item Option to be selected (null to clear
* the selection).
*/
goog.ui.Select.prototype.setSelectedItem = function(item) {
if (this.selectionModel_) {
this.selectionModel_.setSelectedItem(item);
}
};
/**
* Selects the option at the specified index, or clears the selection if the
* index is out of bounds.
* @param {number} index Index of the option to be selected.
*/
goog.ui.Select.prototype.setSelectedIndex = function(index) {
if (this.selectionModel_) {
this.setSelectedItem(
/** @type {goog.ui.MenuItem} */ (this.selectionModel_.getItemAt(index)));
}
};
/**
* Selects the first option found with an associated value equal to the
* argument, or clears the selection if no such option is found. A null
* argument also clears the selection. Overrides {@link
* goog.ui.Button#setValue}.
* @param {*} value Value of the option to be selected (null to clear
* the selection).
*/
goog.ui.Select.prototype.setValue = function(value) {
if (goog.isDefAndNotNull(value) && this.selectionModel_) {
for (var i = 0, item; item = this.selectionModel_.getItemAt(i); i++) {
if (item && typeof item.getValue == 'function' &&
item.getValue() == value) {
this.setSelectedItem(/** @type {goog.ui.MenuItem} */ (item));
return;
}
}
}
this.setSelectedItem(null);
};
/**
* Returns the currently selected option.
* @return {goog.ui.MenuItem} The currently selected option (null if none).
*/
goog.ui.Select.prototype.getSelectedItem = function() {
return this.selectionModel_ ?
/** @type {goog.ui.MenuItem} */ (this.selectionModel_.getSelectedItem()) :
null;
};
/**
* Returns the index of the currently selected option.
* @return {number} 0-based index of the currently selected option (-1 if none).
*/
goog.ui.Select.prototype.getSelectedIndex = function() {
return this.selectionModel_ ? this.selectionModel_.getSelectedIndex() : -1;
};
/**
* @return {goog.ui.SelectionModel} The selection model.
* @protected
*/
goog.ui.Select.prototype.getSelectionModel = function() {
return this.selectionModel_;
};
/**
* Creates a new selection model and sets up an event listener to handle
* {@link goog.events.EventType.SELECT} events dispatched by it.
* @param {goog.ui.Component=} opt_component If provided, will add the
* component's children as items to the selection model.
* @private
*/
goog.ui.Select.prototype.createSelectionModel_ = function(opt_component) {
this.selectionModel_ = new goog.ui.SelectionModel();
if (opt_component) {
opt_component.forEachChild(function(child, index) {
this.selectionModel_.addItem(child);
}, this);
}
this.listenToSelectionModelEvents_();
};
/**
* Subscribes to events dispatched by the selection model.
* @private
*/
goog.ui.Select.prototype.listenToSelectionModelEvents_ = function() {
if (this.selectionModel_) {
this.getHandler().listen(this.selectionModel_, goog.events.EventType.SELECT,
this.handleSelectionChange);
}
};
/**
* Updates the caption to be shown in the select button. If no option is
* selected and a default caption is set, sets the caption to the default
* caption; otherwise to the empty string.
* @private
*/
goog.ui.Select.prototype.updateCaption_ = function() {
var item = this.getSelectedItem();
this.setContent(item ? item.getCaption() : this.defaultCaption_);
};
/**
* Opens or closes the menu. Overrides {@link goog.ui.MenuButton#setOpen} by
* highlighting the currently selected option on open.
* @param {boolean} open Whether to open or close the menu.
*/
goog.ui.Select.prototype.setOpen = function(open) {
goog.ui.Select.superClass_.setOpen.call(this, open);
if (this.isOpen()) {
this.getMenu().setHighlightedIndex(this.getSelectedIndex());
}
};
// Register a decorator factory function for goog.ui.Selects.
goog.ui.registry.setDecoratorByClassName(
goog.getCssName('goog-select'), function() {
// Select defaults to using MenuButtonRenderer, since it shares its L&F.
return new goog.ui.Select(null);
});
| apache-2.0 |
BRD-CD/superset | superset/assets/visualizations/word_cloud.js | 1629 | /* eslint-disable no-use-before-define */
import d3 from 'd3';
import cloudLayout from 'd3-cloud';
import { category21 } from '../javascripts/modules/colors';
function wordCloudChart(slice, payload) {
const chart = d3.select(slice.selector);
const data = payload.data;
const fd = slice.formData;
const range = [
fd.size_from,
fd.size_to,
];
const rotation = fd.rotation;
let fRotation;
if (rotation === 'square') {
fRotation = () => Math.floor((Math.random() * 2) * 90);
} else if (rotation === 'flat') {
fRotation = () => 0;
} else {
fRotation = () => Math.floor(((Math.random() * 6) - 3) * 30);
}
const size = [slice.width(), slice.height()];
const scale = d3.scale.linear()
.range(range)
.domain(d3.extent(data, function (d) {
return d.size;
}));
function draw(words) {
chart.selectAll('*').remove();
chart.append('svg')
.attr('width', layout.size()[0])
.attr('height', layout.size()[1])
.append('g')
.attr('transform', `translate(${layout.size()[0] / 2},${layout.size()[1] / 2})`)
.selectAll('text')
.data(words)
.enter()
.append('text')
.style('font-size', d => d.size + 'px')
.style('font-family', 'Impact')
.style('fill', d => category21(d.text))
.attr('text-anchor', 'middle')
.attr('transform', d => `translate(${d.x}, ${d.y}) rotate(${d.rotate})`)
.text(d => d.text);
}
const layout = cloudLayout()
.size(size)
.words(data)
.padding(5)
.rotate(fRotation)
.font('serif')
.fontSize(d => scale(d.size))
.on('end', draw);
layout.start();
}
module.exports = wordCloudChart;
| apache-2.0 |
jwren/intellij-community | java/java-tests/testData/codeInsight/completion/normal/CompletePatternVariableSwitchStmt.java | 296 |
class Main {
void f(Object o) {
switch(o) {
case Integer integer && inte<caret>, null
}
}
void g(Object o) {
switch(o) {
case null, Integer integer && inte<caret>
}
}
void h(Object o) {
switch(o) {
case Integer integer && inte<caret>
}
}
} | apache-2.0 |