code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
namespace Neos\Diff;
/**
* This file is part of the Neos.Diff package.
*
* (c) 2009 Chris Boulton <chris.boulton@interspire.com>
* Portions (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
/**
* Class Diff
*/
class Diff
{
/**
* @var array The "old" sequence to use as the basis for the comparison.
*/
private $a = null;
/**
* @var array The "new" sequence to generate the changes for.
*/
private $b = null;
/**
* @var array Array containing the generated opcodes for the differences between the two items.
*/
private $groupedCodes = null;
/**
* @var array Associative array of the default options available for the diff class and their default value.
*/
private $defaultOptions = [
'context' => 3,
'ignoreNewLines' => false,
'ignoreWhitespace' => false,
'ignoreCase' => false
];
/**
* @var array Array of the options that have been applied for generating the diff.
*/
private $options = [];
/**
* The constructor.
*
* @param array $a Array containing the lines of the first string to compare.
* @param array $b Array containing the lines for the second string to compare.
* @param array $options Options (see $defaultOptions in this class)
*/
public function __construct(array $a, array $b, array $options = [])
{
$this->a = $a;
$this->b = $b;
$this->options = array_merge($this->defaultOptions, $options);
}
/**
* Render a diff using the supplied rendering class and return it.
*
* @param Renderer\AbstractRenderer $renderer An instance of the rendering object to use for generating the diff.
* @return mixed The generated diff. Exact return value depends on the renderer used.
*/
public function render(Renderer\AbstractRenderer $renderer)
{
$renderer->diff = $this;
return $renderer->render();
}
/**
* Get a range of lines from $start to $end from the first comparison string
* and return them as an array. If no values are supplied, the entire string
* is returned. It's also possible to specify just one line to return only
* that line.
*
* @param int $start The starting number.
* @param int $end The ending number. If not supplied, only the item in $start will be returned.
* @return array Array of all of the lines between the specified range.
*/
public function getA($start = 0, $end = null)
{
if ($start == 0 && $end === null) {
return $this->a;
}
if ($end === null) {
$length = 1;
} else {
$length = $end - $start;
}
return array_slice($this->a, $start, $length);
}
/**
* Get a range of lines from $start to $end from the second comparison string
* and return them as an array. If no values are supplied, the entire string
* is returned. It's also possible to specify just one line to return only
* that line.
*
* @param int $start The starting number.
* @param int $end The ending number. If not supplied, only the item in $start will be returned.
* @return array Array of all of the lines between the specified range.
*/
public function getB($start = 0, $end = null)
{
if ($start == 0 && $end === null) {
return $this->b;
}
if ($end === null) {
$length = 1;
} else {
$length = $end - $start;
}
return array_slice($this->b, $start, $length);
}
/**
* Generate a list of the compiled and grouped opcodes for the differences between the
* two strings. Generally called by the renderer, this class instantiates the sequence
* matcher and performs the actual diff generation and return an array of the opcodes
* for it. Once generated, the results are cached in the diff class instance.
*
* @return array Array of the grouped opcodes for the generated diff.
*/
public function getGroupedOpcodes()
{
if (!is_null($this->groupedCodes)) {
return $this->groupedCodes;
}
$sequenceMatcher = new SequenceMatcher($this->a, $this->b, null, $this->options);
$this->groupedCodes = $sequenceMatcher->getGroupedOpcodes();
return $this->groupedCodes;
}
}
| dimaip/neos-development-collection | Neos.Diff/Classes/Diff.php | PHP | gpl-3.0 | 4,601 |
# -*- coding: utf-8 -*-
"""
Tests of extended hints
"""
import unittest
from ddt import ddt, data, unpack
# With the use of ddt, some of the data expected_string cases below are naturally long stretches
# of text text without whitespace. I think it's best to leave such lines intact
# in the test code. Therefore:
# pylint: disable=line-too-long
# For out many ddt data cases, prefer a compact form of { .. }
from capa.tests.helpers import new_loncapa_problem, load_fixture
class HintTest(unittest.TestCase):
"""Base class for tests of extended hinting functionality."""
def correctness(self, problem_id, choice):
"""Grades the problem and returns the 'correctness' string from cmap."""
student_answers = {problem_id: choice}
cmap = self.problem.grade_answers(answers=student_answers) # pylint: disable=no-member
return cmap[problem_id]['correctness']
def get_hint(self, problem_id, choice):
"""Grades the problem and returns its hint from cmap or the empty string."""
student_answers = {problem_id: choice}
cmap = self.problem.grade_answers(answers=student_answers) # pylint: disable=no-member
adict = cmap.cmap.get(problem_id)
if adict:
return adict['msg']
else:
return ''
# It is a little surprising how much more complicated TextInput is than all the other cases.
@ddt
class TextInputHintsTest(HintTest):
"""
Test Text Input Hints Test
"""
xml = load_fixture('extended_hints_text_input.xml')
problem = new_loncapa_problem(xml)
def test_tracking_log(self):
"""Test that the tracking log comes out right."""
self.problem.capa_module.reset_mock()
self.get_hint(u'1_3_1', u'Blue')
self.problem.capa_module.runtime.track_function.assert_called_with(
'edx.problem.hint.feedback_displayed',
{'module_id': 'i4x://Foo/bar/mock/abc',
'problem_part_id': '1_2',
'trigger_type': 'single',
'hint_label': u'Correct:',
'correctness': True,
'student_answer': [u'Blue'],
'question_type': 'stringresponse',
'hints': [{'text': 'The red light is scattered by water molecules leaving only blue light.'}]}
)
@data(
{'problem_id': u'1_2_1', u'choice': u'GermanyΩ',
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="hint-text">I do not think so.Ω</div></div>'},
{'problem_id': u'1_2_1', u'choice': u'franceΩ',
'expected_string': u'<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">Viva la France!Ω</div></div>'},
{'problem_id': u'1_2_1', u'choice': u'FranceΩ',
'expected_string': u'<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">Viva la France!Ω</div></div>'},
{'problem_id': u'1_2_1', u'choice': u'Mexico',
'expected_string': ''},
{'problem_id': u'1_2_1', u'choice': u'USAΩ',
'expected_string': u'<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">Less well known, but yes, there is a Paris, Texas.Ω</div></div>'},
{'problem_id': u'1_2_1', u'choice': u'usaΩ',
'expected_string': u'<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">Less well known, but yes, there is a Paris, Texas.Ω</div></div>'},
{'problem_id': u'1_2_1', u'choice': u'uSAxΩ',
'expected_string': u''},
{'problem_id': u'1_2_1', u'choice': u'NICKLANDΩ',
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="hint-text">The country name does not end in LANDΩ</div></div>'},
{'problem_id': u'1_3_1', u'choice': u'Blue',
'expected_string': u'<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">The red light is scattered by water molecules leaving only blue light.</div></div>'},
{'problem_id': u'1_3_1', u'choice': u'blue',
'expected_string': u''},
{'problem_id': u'1_3_1', u'choice': u'b',
'expected_string': u''},
)
@unpack
def test_text_input_hints(self, problem_id, choice, expected_string):
hint = self.get_hint(problem_id, choice)
self.assertEqual(hint, expected_string)
@ddt
class TextInputExtendedHintsCaseInsensitive(HintTest):
"""Test Text Input Extended hints Case Insensitive"""
xml = load_fixture('extended_hints_text_input.xml')
problem = new_loncapa_problem(xml)
@data(
{'problem_id': u'1_5_1', 'choice': 'abc', 'expected_string': ''}, # wrong answer yielding no hint
{'problem_id': u'1_5_1', 'choice': 'A', 'expected_string':
u'<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Woo Hoo </span><div class="hint-text">hint1</div></div>'},
{'problem_id': u'1_5_1', 'choice': 'a', 'expected_string':
u'<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Woo Hoo </span><div class="hint-text">hint1</div></div>'},
{'problem_id': u'1_5_1', 'choice': 'B', 'expected_string':
u'<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><div class="hint-text">hint2</div></div>'},
{'problem_id': u'1_5_1', 'choice': 'b', 'expected_string':
u'<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><div class="hint-text">hint2</div></div>'},
{'problem_id': u'1_5_1', 'choice': 'C', 'expected_string':
u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><div class="hint-text">hint4</div></div>'},
{'problem_id': u'1_5_1', 'choice': 'c', 'expected_string':
u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><div class="hint-text">hint4</div></div>'},
# regexp cases
{'problem_id': u'1_5_1', 'choice': 'FGGG', 'expected_string':
u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><div class="hint-text">hint6</div></div>'},
{'problem_id': u'1_5_1', 'choice': 'fgG', 'expected_string':
u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><div class="hint-text">hint6</div></div>'},
)
@unpack
def test_text_input_hints(self, problem_id, choice, expected_string):
hint = self.get_hint(problem_id, choice)
self.assertEqual(hint, expected_string)
@ddt
class TextInputExtendedHintsCaseSensitive(HintTest):
"""Sometimes the semantics can be encoded in the class name."""
xml = load_fixture('extended_hints_text_input.xml')
problem = new_loncapa_problem(xml)
@data(
{'problem_id': u'1_6_1', 'choice': 'abc', 'expected_string': ''},
{'problem_id': u'1_6_1', 'choice': 'A', 'expected_string':
u'<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">hint1</div></div>'},
{'problem_id': u'1_6_1', 'choice': 'a', 'expected_string': u''},
{'problem_id': u'1_6_1', 'choice': 'B', 'expected_string':
u'<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">hint2</div></div>'},
{'problem_id': u'1_6_1', 'choice': 'b', 'expected_string': u''},
{'problem_id': u'1_6_1', 'choice': 'C', 'expected_string':
u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="hint-text">hint4</div></div>'},
{'problem_id': u'1_6_1', 'choice': 'c', 'expected_string': u''},
# regexp cases
{'problem_id': u'1_6_1', 'choice': 'FGG', 'expected_string':
u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="hint-text">hint6</div></div>'},
{'problem_id': u'1_6_1', 'choice': 'fgG', 'expected_string': u''},
)
@unpack
def test_text_input_hints(self, problem_id, choice, expected_string):
message_text = self.get_hint(problem_id, choice)
self.assertEqual(message_text, expected_string)
@ddt
class TextInputExtendedHintsCompatible(HintTest):
"""
Compatibility test with mixed old and new style additional_answer tags.
"""
xml = load_fixture('extended_hints_text_input.xml')
problem = new_loncapa_problem(xml)
@data(
{'problem_id': u'1_7_1', 'choice': 'A', 'correct': 'correct',
'expected_string': '<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">hint1</div></div>'},
{'problem_id': u'1_7_1', 'choice': 'B', 'correct': 'correct', 'expected_string': ''},
{'problem_id': u'1_7_1', 'choice': 'C', 'correct': 'correct',
'expected_string': '<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">hint2</div></div>'},
{'problem_id': u'1_7_1', 'choice': 'D', 'correct': 'incorrect', 'expected_string': ''},
# check going through conversion with difficult chars
{'problem_id': u'1_7_1', 'choice': """<&"'>""", 'correct': 'correct', 'expected_string': ''},
)
@unpack
def test_text_input_hints(self, problem_id, choice, correct, expected_string):
message_text = self.get_hint(problem_id, choice)
self.assertEqual(message_text, expected_string)
self.assertEqual(self.correctness(problem_id, choice), correct)
@ddt
class TextInputExtendedHintsRegex(HintTest):
"""
Extended hints where the answer is regex mode.
"""
xml = load_fixture('extended_hints_text_input.xml')
problem = new_loncapa_problem(xml)
@data(
{'problem_id': u'1_8_1', 'choice': 'ABwrong', 'correct': 'incorrect', 'expected_string': ''},
{'problem_id': u'1_8_1', 'choice': 'ABC', 'correct': 'correct',
'expected_string': '<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">hint1</div></div>'},
{'problem_id': u'1_8_1', 'choice': 'ABBBBC', 'correct': 'correct',
'expected_string': '<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">hint1</div></div>'},
{'problem_id': u'1_8_1', 'choice': 'aBc', 'correct': 'correct',
'expected_string': '<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">hint1</div></div>'},
{'problem_id': u'1_8_1', 'choice': 'BBBB', 'correct': 'correct',
'expected_string': '<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">hint2</div></div>'},
{'problem_id': u'1_8_1', 'choice': 'bbb', 'correct': 'correct',
'expected_string': '<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">hint2</div></div>'},
{'problem_id': u'1_8_1', 'choice': 'C', 'correct': 'incorrect',
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="hint-text">hint4</div></div>'},
{'problem_id': u'1_8_1', 'choice': 'c', 'correct': 'incorrect',
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="hint-text">hint4</div></div>'},
{'problem_id': u'1_8_1', 'choice': 'D', 'correct': 'incorrect',
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="hint-text">hint6</div></div>'},
{'problem_id': u'1_8_1', 'choice': 'd', 'correct': 'incorrect',
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="hint-text">hint6</div></div>'},
)
@unpack
def test_text_input_hints(self, problem_id, choice, correct, expected_string):
message_text = self.get_hint(problem_id, choice)
self.assertEqual(message_text, expected_string)
self.assertEqual(self.correctness(problem_id, choice), correct)
@ddt
class NumericInputHintsTest(HintTest):
"""
This class consists of a suite of test cases to be run on the numeric input problem represented by the XML below.
"""
xml = load_fixture('extended_hints_numeric_input.xml')
problem = new_loncapa_problem(xml) # this problem is properly constructed
def test_tracking_log(self):
self.get_hint(u'1_2_1', u'1.141')
self.problem.capa_module.runtime.track_function.assert_called_with(
'edx.problem.hint.feedback_displayed',
{'module_id': 'i4x://Foo/bar/mock/abc', 'problem_part_id': '1_1', 'trigger_type': 'single',
'hint_label': u'Nice',
'correctness': True,
'student_answer': [u'1.141'],
'question_type': 'numericalresponse',
'hints': [{'text': 'The square root of two turns up in the strangest places.'}]}
)
@data(
{'problem_id': u'1_2_1', 'choice': '1.141',
'expected_string': u'<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Nice </span><div class="hint-text">The square root of two turns up in the strangest places.</div></div>'},
# additional answer
{'problem_id': u'1_2_1', 'choice': '10',
'expected_string': u'<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">This is an additional hint.</div></div>'},
{'problem_id': u'1_3_1', 'choice': '4',
'expected_string': u'<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">Pretty easy, uh?.</div></div>'},
# should get hint, when correct via numeric-tolerance
{'problem_id': u'1_2_1', 'choice': '1.15',
'expected_string': u'<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Nice </span><div class="hint-text">The square root of two turns up in the strangest places.</div></div>'},
# when they answer wrong, nothing
{'problem_id': u'1_2_1', 'choice': '2', 'expected_string': ''},
)
@unpack
def test_numeric_input_hints(self, problem_id, choice, expected_string):
hint = self.get_hint(problem_id, choice)
self.assertEqual(hint, expected_string)
@ddt
class CheckboxHintsTest(HintTest):
"""
This class consists of a suite of test cases to be run on the checkbox problem represented by the XML below.
"""
xml = load_fixture('extended_hints_checkbox.xml')
problem = new_loncapa_problem(xml) # this problem is properly constructed
@data(
{'problem_id': u'1_2_1', 'choice': [u'choice_0'],
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="feedback-hint-multi"><div class="hint-text">You are right that apple is a fruit.</div><div class="hint-text">You are right that mushrooms are not fruit</div><div class="hint-text">Remember that grape is also a fruit.</div><div class="hint-text">What is a camero anyway?</div></div></div>'},
{'problem_id': u'1_2_1', 'choice': [u'choice_1'],
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="feedback-hint-multi"><div class="hint-text">Remember that apple is also a fruit.</div><div class="hint-text">Mushroom is a fungus, not a fruit.</div><div class="hint-text">Remember that grape is also a fruit.</div><div class="hint-text">What is a camero anyway?</div></div></div>'},
{'problem_id': u'1_2_1', 'choice': [u'choice_2'],
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="feedback-hint-multi"><div class="hint-text">Remember that apple is also a fruit.</div><div class="hint-text">You are right that mushrooms are not fruit</div><div class="hint-text">You are right that grape is a fruit</div><div class="hint-text">What is a camero anyway?</div></div></div>'},
{'problem_id': u'1_2_1', 'choice': [u'choice_3'],
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="feedback-hint-multi"><div class="hint-text">Remember that apple is also a fruit.</div><div class="hint-text">You are right that mushrooms are not fruit</div><div class="hint-text">Remember that grape is also a fruit.</div><div class="hint-text">What is a camero anyway?</div></div></div>'},
{'problem_id': u'1_2_1', 'choice': [u'choice_4'],
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="feedback-hint-multi"><div class="hint-text">Remember that apple is also a fruit.</div><div class="hint-text">You are right that mushrooms are not fruit</div><div class="hint-text">Remember that grape is also a fruit.</div><div class="hint-text">I do not know what a Camero is but it is not a fruit.</div></div></div>'},
{'problem_id': u'1_2_1', 'choice': [u'choice_0', u'choice_1'], # compound
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Almost right </span><div class="hint-text">You are right that apple is a fruit, but there is one you are missing. Also, mushroom is not a fruit.</div></div>'},
{'problem_id': u'1_2_1', 'choice': [u'choice_1', u'choice_2'], # compound
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="hint-text">You are right that grape is a fruit, but there is one you are missing. Also, mushroom is not a fruit.</div></div>'},
{'problem_id': u'1_2_1', 'choice': [u'choice_0', u'choice_2'],
'expected_string': u'<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="feedback-hint-multi"><div class="hint-text">You are right that apple is a fruit.</div><div class="hint-text">You are right that mushrooms are not fruit</div><div class="hint-text">You are right that grape is a fruit</div><div class="hint-text">What is a camero anyway?</div></div></div>'},
{'problem_id': u'1_3_1', 'choice': [u'choice_0'],
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="feedback-hint-multi"><div class="hint-text">No, sorry, a banana is a fruit.</div><div class="hint-text">You are right that mushrooms are not vegatbles</div><div class="hint-text">Brussel sprout is the only vegetable in this list.</div></div></div>'},
{'problem_id': u'1_3_1', 'choice': [u'choice_1'],
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="feedback-hint-multi"><div class="hint-text">poor banana.</div><div class="hint-text">You are right that mushrooms are not vegatbles</div><div class="hint-text">Brussel sprout is the only vegetable in this list.</div></div></div>'},
{'problem_id': u'1_3_1', 'choice': [u'choice_2'],
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="feedback-hint-multi"><div class="hint-text">poor banana.</div><div class="hint-text">Mushroom is a fungus, not a vegetable.</div><div class="hint-text">Brussel sprout is the only vegetable in this list.</div></div></div>'},
{'problem_id': u'1_3_1', 'choice': [u'choice_3'],
'expected_string': u'<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="feedback-hint-multi"><div class="hint-text">poor banana.</div><div class="hint-text">You are right that mushrooms are not vegatbles</div><div class="hint-text">Brussel sprouts are vegetables.</div></div></div>'},
{'problem_id': u'1_3_1', 'choice': [u'choice_0', u'choice_1'], # compound
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Very funny </span><div class="hint-text">Making a banana split?</div></div>'},
{'problem_id': u'1_3_1', 'choice': [u'choice_1', u'choice_2'],
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="feedback-hint-multi"><div class="hint-text">poor banana.</div><div class="hint-text">Mushroom is a fungus, not a vegetable.</div><div class="hint-text">Brussel sprout is the only vegetable in this list.</div></div></div>'},
{'problem_id': u'1_3_1', 'choice': [u'choice_0', u'choice_2'],
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="feedback-hint-multi"><div class="hint-text">No, sorry, a banana is a fruit.</div><div class="hint-text">Mushroom is a fungus, not a vegetable.</div><div class="hint-text">Brussel sprout is the only vegetable in this list.</div></div></div>'},
# check for interaction between compoundhint and correct/incorrect
{'problem_id': u'1_4_1', 'choice': [u'choice_0', u'choice_1'], # compound
'expected_string': u'<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="hint-text">AB</div></div>'},
{'problem_id': u'1_4_1', 'choice': [u'choice_0', u'choice_2'], # compound
'expected_string': u'<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">AC</div></div>'},
# check for labeling where multiple child hints have labels
# These are some tricky cases
{'problem_id': '1_5_1', 'choice': ['choice_0', 'choice_1'],
'expected_string': '<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">AA </span><div class="feedback-hint-multi"><div class="hint-text">aa</div></div></div>'},
{'problem_id': '1_5_1', 'choice': ['choice_0'],
'expected_string': '<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="feedback-hint-multi"><div class="hint-text">aa</div><div class="hint-text">bb</div></div></div>'},
{'problem_id': '1_5_1', 'choice': ['choice_1'],
'expected_string': ''},
{'problem_id': '1_5_1', 'choice': [],
'expected_string': '<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">BB </span><div class="feedback-hint-multi"><div class="hint-text">bb</div></div></div>'},
{'problem_id': '1_6_1', 'choice': ['choice_0'],
'expected_string': '<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><div class="feedback-hint-multi"><div class="hint-text">aa</div></div></div>'},
{'problem_id': '1_6_1', 'choice': ['choice_0', 'choice_1'],
'expected_string': '<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><div class="hint-text">compoundo</div></div>'},
# The user selects *nothing*, but can still get "unselected" feedback
{'problem_id': '1_7_1', 'choice': [],
'expected_string': '<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="feedback-hint-multi"><div class="hint-text">bb</div></div></div>'},
# 100% not match of sel/unsel feedback
{'problem_id': '1_7_1', 'choice': ['choice_1'],
'expected_string': ''},
# Here we have the correct combination, and that makes feedback too
{'problem_id': '1_7_1', 'choice': ['choice_0'],
'expected_string': '<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="feedback-hint-multi"><div class="hint-text">aa</div><div class="hint-text">bb</div></div></div>'},
)
@unpack
def test_checkbox_hints(self, problem_id, choice, expected_string):
self.maxDiff = None # pylint: disable=invalid-name
hint = self.get_hint(problem_id, choice)
self.assertEqual(hint, expected_string)
class CheckboxHintsTestTracking(HintTest):
"""
Test the rather complicated tracking log output for checkbox cases.
"""
xml = """
<problem>
<p>question</p>
<choiceresponse>
<checkboxgroup>
<choice correct="true">Apple
<choicehint selected="true">A true</choicehint>
<choicehint selected="false">A false</choicehint>
</choice>
<choice correct="false">Banana
</choice>
<choice correct="true">Cronut
<choicehint selected="true">C true</choicehint>
</choice>
<compoundhint value="A C">A C Compound</compoundhint>
</checkboxgroup>
</choiceresponse>
</problem>
"""
problem = new_loncapa_problem(xml)
def test_tracking_log(self):
"""Test checkbox tracking log - by far the most complicated case"""
# A -> 1 hint
self.get_hint(u'1_2_1', [u'choice_0'])
self.problem.capa_module.runtime.track_function.assert_called_with(
'edx.problem.hint.feedback_displayed',
{'hint_label': u'Incorrect:',
'module_id': 'i4x://Foo/bar/mock/abc',
'problem_part_id': '1_1',
'choice_all': ['choice_0', 'choice_1', 'choice_2'],
'correctness': False,
'trigger_type': 'single',
'student_answer': [u'choice_0'],
'hints': [{'text': 'A true', 'trigger': [{'choice': 'choice_0', 'selected': True}]}],
'question_type': 'choiceresponse'}
)
# B C -> 2 hints
self.problem.capa_module.runtime.track_function.reset_mock()
self.get_hint(u'1_2_1', [u'choice_1', u'choice_2'])
self.problem.capa_module.runtime.track_function.assert_called_with(
'edx.problem.hint.feedback_displayed',
{'hint_label': u'Incorrect:',
'module_id': 'i4x://Foo/bar/mock/abc',
'problem_part_id': '1_1',
'choice_all': ['choice_0', 'choice_1', 'choice_2'],
'correctness': False,
'trigger_type': 'single',
'student_answer': [u'choice_1', u'choice_2'],
'hints': [
{'text': 'A false', 'trigger': [{'choice': 'choice_0', 'selected': False}]},
{'text': 'C true', 'trigger': [{'choice': 'choice_2', 'selected': True}]}
],
'question_type': 'choiceresponse'}
)
# A C -> 1 Compound hint
self.problem.capa_module.runtime.track_function.reset_mock()
self.get_hint(u'1_2_1', [u'choice_0', u'choice_2'])
self.problem.capa_module.runtime.track_function.assert_called_with(
'edx.problem.hint.feedback_displayed',
{'hint_label': u'Correct:',
'module_id': 'i4x://Foo/bar/mock/abc',
'problem_part_id': '1_1',
'choice_all': ['choice_0', 'choice_1', 'choice_2'],
'correctness': True,
'trigger_type': 'compound',
'student_answer': [u'choice_0', u'choice_2'],
'hints': [
{'text': 'A C Compound',
'trigger': [{'choice': 'choice_0', 'selected': True}, {'choice': 'choice_2', 'selected': True}]}
],
'question_type': 'choiceresponse'}
)
@ddt
class MultpleChoiceHintsTest(HintTest):
"""
This class consists of a suite of test cases to be run on the multiple choice problem represented by the XML below.
"""
xml = load_fixture('extended_hints_multiple_choice.xml')
problem = new_loncapa_problem(xml)
def test_tracking_log(self):
"""Test that the tracking log comes out right."""
self.problem.capa_module.reset_mock()
self.get_hint(u'1_3_1', u'choice_2')
self.problem.capa_module.runtime.track_function.assert_called_with(
'edx.problem.hint.feedback_displayed',
{'module_id': 'i4x://Foo/bar/mock/abc', 'problem_part_id': '1_2', 'trigger_type': 'single',
'student_answer': [u'choice_2'], 'correctness': False, 'question_type': 'multiplechoiceresponse',
'hint_label': 'OOPS', 'hints': [{'text': 'Apple is a fruit.'}]}
)
@data(
{'problem_id': u'1_2_1', 'choice': u'choice_0',
'expected_string': '<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><div class="hint-text">Mushroom is a fungus, not a fruit.</div></div>'},
{'problem_id': u'1_2_1', 'choice': u'choice_1',
'expected_string': ''},
{'problem_id': u'1_3_1', 'choice': u'choice_1',
'expected_string': '<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">Potato is a root vegetable.</div></div>'},
{'problem_id': u'1_2_1', 'choice': u'choice_2',
'expected_string': '<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">OUTSTANDING </span><div class="hint-text">Apple is indeed a fruit.</div></div>'},
{'problem_id': u'1_3_1', 'choice': u'choice_2',
'expected_string': '<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">OOPS </span><div class="hint-text">Apple is a fruit.</div></div>'},
{'problem_id': u'1_3_1', 'choice': u'choice_9',
'expected_string': ''},
)
@unpack
def test_multiplechoice_hints(self, problem_id, choice, expected_string):
hint = self.get_hint(problem_id, choice)
self.assertEqual(hint, expected_string)
@ddt
class MultpleChoiceHintsWithHtmlTest(HintTest):
"""
This class consists of a suite of test cases to be run on the multiple choice problem represented by the XML below.
"""
xml = load_fixture('extended_hints_multiple_choice_with_html.xml')
problem = new_loncapa_problem(xml)
def test_tracking_log(self):
"""Test that the tracking log comes out right."""
self.problem.capa_module.reset_mock()
self.get_hint(u'1_2_1', u'choice_0')
self.problem.capa_module.runtime.track_function.assert_called_with(
'edx.problem.hint.feedback_displayed',
{'module_id': 'i4x://Foo/bar/mock/abc', 'problem_part_id': '1_1', 'trigger_type': 'single',
'student_answer': [u'choice_0'], 'correctness': False, 'question_type': 'multiplechoiceresponse',
'hint_label': 'Incorrect:', 'hints': [{'text': 'Mushroom <img src="#" ale="#"/>is a fungus, not a fruit.'}]}
)
@data(
{'problem_id': u'1_2_1', 'choice': u'choice_0',
'expected_string': '<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="hint-text">Mushroom <img src="#" ale="#"/>is a fungus, not a fruit.</div></div>'},
{'problem_id': u'1_2_1', 'choice': u'choice_1',
'expected_string': '<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="hint-text">Potato is <img src="#" ale="#"/> not a fruit.</div></div>'},
{'problem_id': u'1_2_1', 'choice': u'choice_2',
'expected_string': '<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text"><a href="#">Apple</a> is a fruit.</div></div>'}
)
@unpack
def test_multiplechoice_hints(self, problem_id, choice, expected_string):
hint = self.get_hint(problem_id, choice)
self.assertEqual(hint, expected_string)
@ddt
class DropdownHintsTest(HintTest):
"""
This class consists of a suite of test cases to be run on the drop down problem represented by the XML below.
"""
xml = load_fixture('extended_hints_dropdown.xml')
problem = new_loncapa_problem(xml)
def test_tracking_log(self):
"""Test that the tracking log comes out right."""
self.problem.capa_module.reset_mock()
self.get_hint(u'1_3_1', u'FACES')
self.problem.capa_module.runtime.track_function.assert_called_with(
'edx.problem.hint.feedback_displayed',
{'module_id': 'i4x://Foo/bar/mock/abc', 'problem_part_id': '1_2', 'trigger_type': 'single',
'student_answer': [u'FACES'], 'correctness': True, 'question_type': 'optionresponse',
'hint_label': 'Correct:', 'hints': [{'text': 'With lots of makeup, doncha know?'}]}
)
@data(
{'problem_id': u'1_2_1', 'choice': 'Multiple Choice',
'expected_string': '<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Good Job </span><div class="hint-text">Yes, multiple choice is the right answer.</div></div>'},
{'problem_id': u'1_2_1', 'choice': 'Text Input',
'expected_string': '<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="hint-text">No, text input problems do not present options.</div></div>'},
{'problem_id': u'1_2_1', 'choice': 'Numerical Input',
'expected_string': '<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="hint-text">No, numerical input problems do not present options.</div></div>'},
{'problem_id': u'1_3_1', 'choice': 'FACES',
'expected_string': '<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">With lots of makeup, doncha know?</div></div>'},
{'problem_id': u'1_3_1', 'choice': 'dogs',
'expected_string': '<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">NOPE </span><div class="hint-text">Not dogs, not cats, not toads</div></div>'},
{'problem_id': u'1_3_1', 'choice': 'wrongo',
'expected_string': ''},
# Regression case where feedback includes answer substring
{'problem_id': u'1_4_1', 'choice': 'AAA',
'expected_string': '<div class="feedback-hint-incorrect"><div class="explanation-title">Answer</div><span class="hint-label">Incorrect: </span><div class="hint-text">AAABBB1</div></div>'},
{'problem_id': u'1_4_1', 'choice': 'BBB',
'expected_string': '<div class="feedback-hint-correct"><div class="explanation-title">Answer</div><span class="hint-label">Correct: </span><div class="hint-text">AAABBB2</div></div>'},
{'problem_id': u'1_4_1', 'choice': 'not going to match',
'expected_string': ''},
)
@unpack
def test_dropdown_hints(self, problem_id, choice, expected_string):
hint = self.get_hint(problem_id, choice)
self.assertEqual(hint, expected_string)
class ErrorConditionsTest(HintTest):
"""
Erroneous xml should raise exception.
"""
def test_error_conditions_illegal_element(self):
xml_with_errors = load_fixture('extended_hints_with_errors.xml')
with self.assertRaises(Exception):
new_loncapa_problem(xml_with_errors) # this problem is improperly constructed
| synergeticsedx/deployment-wipro | common/lib/capa/capa/tests/test_hint_functionality.py | Python | agpl-3.0 | 37,584 |
// Copyright John Maddock 2006.
// Use, modification and distribution are subject to 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)
// Test real concept.
// real_concept is an archetype for User defined Real types.
// This file defines the features, constructors, operators, functions...
// that are essential to use mathematical and statistical functions.
// The template typename "RealType" is used where this type
// (as well as the normal built-in types, float, double & long double)
// can be used.
// That this is the minimum set is confirmed by use as a type
// in tests of all functions & distributions, for example:
// test_spots(0.F); & test_spots(0.); for float and double, but also
// test_spots(boost::math::concepts::real_concept(0.));
// NTL quad_float type is an example of a type meeting the requirements,
// but note minor additions are needed - see ntl.diff and documentation
// "Using With NTL - a High-Precision Floating-Point Library".
#ifndef BOOST_MATH_REAL_CONCEPT_HPP
#define BOOST_MATH_REAL_CONCEPT_HPP
#include <boost/config.hpp>
#include <boost/limits.hpp>
#include <boost/math/special_functions/round.hpp>
#include <boost/math/special_functions/trunc.hpp>
#include <boost/math/special_functions/modf.hpp>
#include <boost/math/tools/precision.hpp>
#include <boost/math/policies/policy.hpp>
#if defined(__SGI_STL_PORT)
# include <boost/math/tools/real_cast.hpp>
#endif
#include <ostream>
#include <istream>
#include <boost/config/no_tr1/cmath.hpp>
#include <math.h> // fmodl
#if defined(__SGI_STL_PORT) || defined(_RWSTD_VER) || defined(__LIBCOMO__)
# include <cstdio>
#endif
namespace boost{ namespace math{
namespace concepts
{
#ifdef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
typedef double real_concept_base_type;
#else
typedef long double real_concept_base_type;
#endif
class real_concept
{
public:
// Constructors:
real_concept() : m_value(0){}
real_concept(char c) : m_value(c){}
#ifndef BOOST_NO_INTRINSIC_WCHAR_T
real_concept(wchar_t c) : m_value(c){}
#endif
real_concept(unsigned char c) : m_value(c){}
real_concept(signed char c) : m_value(c){}
real_concept(unsigned short c) : m_value(c){}
real_concept(short c) : m_value(c){}
real_concept(unsigned int c) : m_value(c){}
real_concept(int c) : m_value(c){}
real_concept(unsigned long c) : m_value(c){}
real_concept(long c) : m_value(c){}
#if defined(__DECCXX) || defined(__SUNPRO_CC)
real_concept(unsigned long long c) : m_value(static_cast<real_concept_base_type>(c)){}
real_concept(long long c) : m_value(static_cast<real_concept_base_type>(c)){}
#elif defined(BOOST_HAS_LONG_LONG)
real_concept(boost::ulong_long_type c) : m_value(static_cast<real_concept_base_type>(c)){}
real_concept(boost::long_long_type c) : m_value(static_cast<real_concept_base_type>(c)){}
#elif defined(BOOST_HAS_MS_INT64)
real_concept(unsigned __int64 c) : m_value(static_cast<real_concept_base_type>(c)){}
real_concept(__int64 c) : m_value(static_cast<real_concept_base_type>(c)){}
#endif
real_concept(float c) : m_value(c){}
real_concept(double c) : m_value(c){}
real_concept(long double c) : m_value(c){}
// Assignment:
real_concept& operator=(char c) { m_value = c; return *this; }
real_concept& operator=(unsigned char c) { m_value = c; return *this; }
real_concept& operator=(signed char c) { m_value = c; return *this; }
#ifndef BOOST_NO_INTRINSIC_WCHAR_T
real_concept& operator=(wchar_t c) { m_value = c; return *this; }
#endif
real_concept& operator=(short c) { m_value = c; return *this; }
real_concept& operator=(unsigned short c) { m_value = c; return *this; }
real_concept& operator=(int c) { m_value = c; return *this; }
real_concept& operator=(unsigned int c) { m_value = c; return *this; }
real_concept& operator=(long c) { m_value = c; return *this; }
real_concept& operator=(unsigned long c) { m_value = c; return *this; }
#ifdef BOOST_HAS_LONG_LONG
real_concept& operator=(boost::long_long_type c) { m_value = static_cast<real_concept_base_type>(c); return *this; }
real_concept& operator=(boost::ulong_long_type c) { m_value = static_cast<real_concept_base_type>(c); return *this; }
#endif
real_concept& operator=(float c) { m_value = c; return *this; }
real_concept& operator=(double c) { m_value = c; return *this; }
real_concept& operator=(long double c) { m_value = c; return *this; }
// Access:
real_concept_base_type value()const{ return m_value; }
// Member arithmetic:
real_concept& operator+=(const real_concept& other)
{ m_value += other.value(); return *this; }
real_concept& operator-=(const real_concept& other)
{ m_value -= other.value(); return *this; }
real_concept& operator*=(const real_concept& other)
{ m_value *= other.value(); return *this; }
real_concept& operator/=(const real_concept& other)
{ m_value /= other.value(); return *this; }
real_concept operator-()const
{ return -m_value; }
real_concept const& operator+()const
{ return *this; }
real_concept& operator++()
{ ++m_value; return *this; }
real_concept& operator--()
{ --m_value; return *this; }
private:
real_concept_base_type m_value;
};
// Non-member arithmetic:
inline real_concept operator+(const real_concept& a, const real_concept& b)
{
real_concept result(a);
result += b;
return result;
}
inline real_concept operator-(const real_concept& a, const real_concept& b)
{
real_concept result(a);
result -= b;
return result;
}
inline real_concept operator*(const real_concept& a, const real_concept& b)
{
real_concept result(a);
result *= b;
return result;
}
inline real_concept operator/(const real_concept& a, const real_concept& b)
{
real_concept result(a);
result /= b;
return result;
}
// Comparison:
inline bool operator == (const real_concept& a, const real_concept& b)
{ return a.value() == b.value(); }
inline bool operator != (const real_concept& a, const real_concept& b)
{ return a.value() != b.value();}
inline bool operator < (const real_concept& a, const real_concept& b)
{ return a.value() < b.value(); }
inline bool operator <= (const real_concept& a, const real_concept& b)
{ return a.value() <= b.value(); }
inline bool operator > (const real_concept& a, const real_concept& b)
{ return a.value() > b.value(); }
inline bool operator >= (const real_concept& a, const real_concept& b)
{ return a.value() >= b.value(); }
// Non-member functions:
inline real_concept acos(real_concept a)
{ return std::acos(a.value()); }
inline real_concept cos(real_concept a)
{ return std::cos(a.value()); }
inline real_concept asin(real_concept a)
{ return std::asin(a.value()); }
inline real_concept atan(real_concept a)
{ return std::atan(a.value()); }
inline real_concept atan2(real_concept a, real_concept b)
{ return std::atan2(a.value(), b.value()); }
inline real_concept ceil(real_concept a)
{ return std::ceil(a.value()); }
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
// I've seen std::fmod(long double) crash on some platforms
// so use fmodl instead:
#ifdef _WIN32_WCE
//
// Ugly workaround for macro fmodl:
//
inline long double call_fmodl(long double a, long double b)
{ return fmodl(a, b); }
inline real_concept fmod(real_concept a, real_concept b)
{ return call_fmodl(a.value(), b.value()); }
#else
inline real_concept fmod(real_concept a, real_concept b)
{ return fmodl(a.value(), b.value()); }
#endif
#endif
inline real_concept cosh(real_concept a)
{ return std::cosh(a.value()); }
inline real_concept exp(real_concept a)
{ return std::exp(a.value()); }
inline real_concept fabs(real_concept a)
{ return std::fabs(a.value()); }
inline real_concept abs(real_concept a)
{ return std::abs(a.value()); }
inline real_concept floor(real_concept a)
{ return std::floor(a.value()); }
inline real_concept modf(real_concept a, real_concept* ipart)
{
real_concept_base_type ip;
real_concept_base_type result = std::modf(a.value(), &ip);
*ipart = ip;
return result;
}
inline real_concept frexp(real_concept a, int* expon)
{ return std::frexp(a.value(), expon); }
inline real_concept ldexp(real_concept a, int expon)
{ return std::ldexp(a.value(), expon); }
inline real_concept log(real_concept a)
{ return std::log(a.value()); }
inline real_concept log10(real_concept a)
{ return std::log10(a.value()); }
inline real_concept tan(real_concept a)
{ return std::tan(a.value()); }
inline real_concept pow(real_concept a, real_concept b)
{ return std::pow(a.value(), b.value()); }
#if !defined(__SUNPRO_CC)
inline real_concept pow(real_concept a, int b)
{ return std::pow(a.value(), b); }
#else
inline real_concept pow(real_concept a, int b)
{ return std::pow(a.value(), static_cast<real_concept_base_type>(b)); }
#endif
inline real_concept sin(real_concept a)
{ return std::sin(a.value()); }
inline real_concept sinh(real_concept a)
{ return std::sinh(a.value()); }
inline real_concept sqrt(real_concept a)
{ return std::sqrt(a.value()); }
inline real_concept tanh(real_concept a)
{ return std::tanh(a.value()); }
//
// Conversion and truncation routines:
//
template <class Policy>
inline int iround(const concepts::real_concept& v, const Policy& pol)
{ return boost::math::iround(v.value(), pol); }
inline int iround(const concepts::real_concept& v)
{ return boost::math::iround(v.value(), policies::policy<>()); }
template <class Policy>
inline long lround(const concepts::real_concept& v, const Policy& pol)
{ return boost::math::lround(v.value(), pol); }
inline long lround(const concepts::real_concept& v)
{ return boost::math::lround(v.value(), policies::policy<>()); }
#ifdef BOOST_HAS_LONG_LONG
template <class Policy>
inline boost::long_long_type llround(const concepts::real_concept& v, const Policy& pol)
{ return boost::math::llround(v.value(), pol); }
inline boost::long_long_type llround(const concepts::real_concept& v)
{ return boost::math::llround(v.value(), policies::policy<>()); }
#endif
template <class Policy>
inline int itrunc(const concepts::real_concept& v, const Policy& pol)
{ return boost::math::itrunc(v.value(), pol); }
inline int itrunc(const concepts::real_concept& v)
{ return boost::math::itrunc(v.value(), policies::policy<>()); }
template <class Policy>
inline long ltrunc(const concepts::real_concept& v, const Policy& pol)
{ return boost::math::ltrunc(v.value(), pol); }
inline long ltrunc(const concepts::real_concept& v)
{ return boost::math::ltrunc(v.value(), policies::policy<>()); }
#ifdef BOOST_HAS_LONG_LONG
template <class Policy>
inline boost::long_long_type lltrunc(const concepts::real_concept& v, const Policy& pol)
{ return boost::math::lltrunc(v.value(), pol); }
inline boost::long_long_type lltrunc(const concepts::real_concept& v)
{ return boost::math::lltrunc(v.value(), policies::policy<>()); }
#endif
// Streaming:
template <class charT, class traits>
inline std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& os, const real_concept& a)
{
return os << a.value();
}
template <class charT, class traits>
inline std::basic_istream<charT, traits>& operator>>(std::basic_istream<charT, traits>& is, real_concept& a)
{
#if defined(BOOST_MSVC) && defined(__SGI_STL_PORT)
//
// STLPort 5.1.4 has a problem reading long doubles from strings,
// see http://sourceforge.net/tracker/index.php?func=detail&aid=1811043&group_id=146814&atid=766244
//
double v;
is >> v;
a = v;
return is;
#elif defined(__SGI_STL_PORT) || defined(_RWSTD_VER) || defined(__LIBCOMO__)
std::string s;
real_concept_base_type d;
is >> s;
std::sscanf(s.c_str(), "%Lf", &d);
a = d;
return is;
#else
real_concept_base_type v;
is >> v;
a = v;
return is;
#endif
}
} // namespace concepts
namespace tools
{
template <>
inline concepts::real_concept max_value<concepts::real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::real_concept))
{
return max_value<concepts::real_concept_base_type>();
}
template <>
inline concepts::real_concept min_value<concepts::real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::real_concept))
{
return min_value<concepts::real_concept_base_type>();
}
template <>
inline concepts::real_concept log_max_value<concepts::real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::real_concept))
{
return log_max_value<concepts::real_concept_base_type>();
}
template <>
inline concepts::real_concept log_min_value<concepts::real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::real_concept))
{
return log_min_value<concepts::real_concept_base_type>();
}
template <>
inline concepts::real_concept epsilon<concepts::real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::real_concept))
{
#ifdef __SUNPRO_CC
return std::numeric_limits<concepts::real_concept_base_type>::epsilon();
#else
return tools::epsilon<concepts::real_concept_base_type>();
#endif
}
template <>
inline int digits<concepts::real_concept>(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(concepts::real_concept))
{
// Assume number of significand bits is same as real_concept_base_type,
// unless std::numeric_limits<T>::is_specialized to provide digits.
return tools::digits<concepts::real_concept_base_type>();
// Note that if numeric_limits real concept is NOT specialized to provide digits10
// (or max_digits10) then the default precision of 6 decimal digits will be used
// by Boost test (giving misleading error messages like
// "difference between {9.79796} and {9.79796} exceeds 5.42101e-19%"
// and by Boost lexical cast and serialization causing loss of accuracy.
}
} // namespace tools
#if defined(__SGI_STL_PORT) || defined(BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS)
//
// We shouldn't really need these type casts any more, but there are some
// STLport iostream bugs we work around by using them....
//
namespace tools
{
// real_cast converts from T to integer and narrower floating-point types.
// Convert from T to integer types.
template <>
inline unsigned int real_cast<unsigned int, concepts::real_concept>(concepts::real_concept r)
{
return static_cast<unsigned int>(r.value());
}
template <>
inline int real_cast<int, concepts::real_concept>(concepts::real_concept r)
{
return static_cast<int>(r.value());
}
template <>
inline long real_cast<long, concepts::real_concept>(concepts::real_concept r)
{
return static_cast<long>(r.value());
}
// Converts from T to narrower floating-point types, float, double & long double.
template <>
inline float real_cast<float, concepts::real_concept>(concepts::real_concept r)
{
return static_cast<float>(r.value());
}
template <>
inline double real_cast<double, concepts::real_concept>(concepts::real_concept r)
{
return static_cast<double>(r.value());
}
template <>
inline long double real_cast<long double, concepts::real_concept>(concepts::real_concept r)
{
return r.value();
}
} // STLPort
#endif
#if BOOST_WORKAROUND(BOOST_MSVC, <= 1310)
//
// For some strange reason ADL sometimes fails to find the
// correct overloads, unless we bring these declarations into scope:
//
using concepts::itrunc;
using concepts::iround;
#endif
} // namespace math
} // namespace boost
#endif // BOOST_MATH_REAL_CONCEPT_HPP
| Stevenwork/Innov_code | v0.9/innovApp/libboost_1_49_0/include/boost/math/concepts/real_concept.hpp | C++ | lgpl-3.0 | 15,306 |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Model } from '../model';
import { GitExtension, Repository, API } from './git';
import { ApiRepository, ApiImpl } from './api1';
import { Event, EventEmitter } from 'vscode';
export function deprecated(_target: any, key: string, descriptor: any): void {
if (typeof descriptor.value !== 'function') {
throw new Error('not supported');
}
const fn = descriptor.value;
descriptor.value = function () {
console.warn(`Git extension API method '${key}' is deprecated.`);
return fn.apply(this, arguments);
};
}
export class GitExtensionImpl implements GitExtension {
enabled: boolean = false;
private _onDidChangeEnablement = new EventEmitter<boolean>();
readonly onDidChangeEnablement: Event<boolean> = this._onDidChangeEnablement.event;
private _model: Model | undefined = undefined;
set model(model: Model | undefined) {
this._model = model;
const enabled = !!model;
if (this.enabled === enabled) {
return;
}
this.enabled = enabled;
this._onDidChangeEnablement.fire(this.enabled);
}
get model(): Model | undefined {
return this._model;
}
constructor(model?: Model) {
if (model) {
this.enabled = true;
this._model = model;
}
}
@deprecated
async getGitPath(): Promise<string> {
if (!this._model) {
throw new Error('Git model not found');
}
return this._model.git.path;
}
@deprecated
async getRepositories(): Promise<Repository[]> {
if (!this._model) {
throw new Error('Git model not found');
}
return this._model.repositories.map(repository => new ApiRepository(repository));
}
getAPI(version: number): API {
if (!this._model) {
throw new Error('Git model not found');
}
if (version !== 1) {
throw new Error(`No API version ${version} found.`);
}
return new ApiImpl(this._model);
}
}
| jwren/intellij-community | plugins/textmate/lib/bundles/git/src/api/extension.ts | TypeScript | apache-2.0 | 2,148 |
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/grappler/costs/graph_memory.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/inputs/trivial_test_graph_input_yielder.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace grappler {
namespace {
class GraphMemoryTest : public ::testing::Test {
protected:
std::unordered_map<string, DeviceProperties> devices_;
public:
GraphMemoryTest() {
devices_["/CPU:0"].set_type("CPU");
devices_["/CPU:0"].set_num_cores(1);
devices_["/CPU:0"].set_frequency(1);
devices_["/CPU:0"].set_bandwidth(1);
devices_["/GPU:0"].set_type("GPU");
devices_["/GPU:0"].set_num_cores(1);
devices_["/GPU:0"].set_frequency(1);
devices_["/CPU:0"].set_bandwidth(1);
(*devices_["/GPU:0"].mutable_environment())["architecture"] = "3";
}
};
TEST_F(GraphMemoryTest, Basic) {
TrivialTestGraphInputYielder fake_input(4, 1, 10, false, {"/CPU:0"});
GrapplerItem item;
CHECK(fake_input.NextItem(&item));
item.feed.clear();
GraphMemory memory(item);
Status s = memory.InferStatically(devices_);
TF_CHECK_OK(s);
const GraphMemory::MemoryUsage& mem_usage =
memory.GetPeakMemoryUsage("/CPU:0");
EXPECT_EQ(120, mem_usage.used_memory);
std::set<string> tensors;
for (const auto& t : mem_usage.live_tensors) {
tensors.insert(strings::StrCat(t.node, ":", t.output_id));
}
// When the execution of the 'Sign' node completes, TF can start executing
// 'Sign_1' and release the memory used by 'x'. Since we can't be sure of
// the order in which this takes place, in the worst case the 3 tensors are in
// memory.
std::set<string> expected;
expected.insert("Sign:0");
expected.insert("Sign_1:0");
expected.insert("x:0");
EXPECT_EQ(expected, tensors);
}
TEST_F(GraphMemoryTest, UnknownBatchSize) {
TrivialTestGraphInputYielder fake_input(4, 1, -1, false, {"/CPU:0"});
GrapplerItem item;
CHECK(fake_input.NextItem(&item));
item.feed.clear();
GraphMemory memory(item);
Status s = memory.InferStatically(devices_);
TF_CHECK_OK(s);
// Same maths as before, except that batch size is unknown and therefore
// assumed to be one.
const GraphMemory::MemoryUsage& mem_usage =
memory.GetPeakMemoryUsage("/CPU:0");
EXPECT_EQ(16, mem_usage.used_memory);
std::set<string> tensors;
for (const auto& t : mem_usage.live_tensors) {
tensors.insert(strings::StrCat(t.node, ":", t.output_id));
}
std::set<string> expected;
expected.insert("Const/Const:0");
expected.insert("Sign:0");
expected.insert("x:0");
EXPECT_EQ(expected, tensors);
}
TEST_F(GraphMemoryTest, MultiDevice) {
TrivialTestGraphInputYielder fake_input(4, 2, 1024 * 1024, false,
{"/CPU:0", "/GPU:0"});
GrapplerItem item;
CHECK(fake_input.NextItem(&item));
item.feed.clear();
GraphMemory memory(item);
Status s = memory.InferStatically(devices_);
TF_CHECK_OK(s);
const GraphMemory::MemoryUsage& cpu_mem = memory.GetPeakMemoryUsage("/CPU:0");
EXPECT_EQ(16777216, cpu_mem.used_memory);
std::set<string> cpu_tensors;
for (const auto& t : cpu_mem.live_tensors) {
cpu_tensors.insert(strings::StrCat(t.node, ":", t.output_id));
}
std::set<string> cpu_expected;
cpu_expected.insert("Recv_Sign_1_0_on_/CPU_0:0");
cpu_expected.insert("Sign:0");
cpu_expected.insert("x:0");
cpu_expected.insert("AddN:0");
EXPECT_EQ(cpu_expected, cpu_tensors);
const GraphMemory::MemoryUsage& gpu_mem = memory.GetPeakMemoryUsage("/GPU:0");
EXPECT_EQ(16777216, gpu_mem.used_memory);
std::set<string> gpu_tensors;
for (const auto& t : gpu_mem.live_tensors) {
gpu_tensors.insert(strings::StrCat(t.node, ":", t.output_id));
}
std::set<string> gpu_expected;
gpu_expected.insert("Recv_AddN_0_on_/GPU_0:0");
gpu_expected.insert("Sign_1:0");
gpu_expected.insert("AddN_1:0");
gpu_expected.insert("AddN_3:0");
EXPECT_EQ(gpu_expected, gpu_tensors);
}
TEST_F(GraphMemoryTest, GpuSwapping) {
TrivialTestGraphInputYielder fake_input(4, 2, 1024 * 1024, false, {"/GPU:0"});
GrapplerItem item;
CHECK(fake_input.NextItem(&item));
item.feed.clear();
{
// Estimate the max memory usage for the graph.
GraphMemory memory(item);
Status s = memory.InferStatically(devices_);
TF_CHECK_OK(s);
const GraphMemory::MemoryUsage& gpu_mem =
memory.GetPeakMemoryUsage("/GPU:0");
EXPECT_EQ(20971520, gpu_mem.used_memory);
std::set<string> gpu_tensors;
for (const auto& t : gpu_mem.live_tensors) {
gpu_tensors.insert(strings::StrCat(t.node, ":", t.output_id));
}
std::set<string> gpu_expected;
gpu_expected.insert("Sign:0");
gpu_expected.insert("Sign_1:0");
gpu_expected.insert("AddN:0");
gpu_expected.insert("AddN_1:0");
gpu_expected.insert("AddN_2:0");
EXPECT_EQ(gpu_expected, gpu_tensors);
}
{
// Swap the first input to node AddN_1: its fanin (the square nodes) should
// not appear in the max cut anymore.
for (auto& node : *item.graph.mutable_node()) {
if (node.name() == "AddN_1") {
(*node.mutable_attr())["_swap_to_host"].mutable_list()->add_i(0);
}
}
GraphMemory memory(item);
Status s = memory.InferStatically(devices_);
TF_CHECK_OK(s);
const GraphMemory::MemoryUsage& new_gpu_mem =
memory.GetPeakMemoryUsage("/GPU:0");
EXPECT_EQ(20971520, new_gpu_mem.used_memory);
std::set<string> new_gpu_tensors;
for (const auto& t : new_gpu_mem.live_tensors) {
new_gpu_tensors.insert(strings::StrCat(t.node, ":", t.output_id));
}
std::set<string> new_gpu_expected;
new_gpu_expected.insert("AddN:0");
new_gpu_expected.insert("AddN_1:0");
new_gpu_expected.insert("AddN_2:0");
new_gpu_expected.insert("AddN_3:0");
new_gpu_expected.insert("AddN_4:0");
EXPECT_EQ(new_gpu_expected, new_gpu_tensors);
}
}
TEST_F(GraphMemoryTest, CtrlDependencies) {
// Build a simple graph with a control dependency.
Scope s = Scope::NewRootScope();
Output a = ops::Const(s.WithOpName("a").WithDevice("/CPU:0"), 10.0f, {3});
Output v =
ops::Variable(s.WithOpName("v").WithDevice("/CPU:0"), {3}, DT_FLOAT);
Output assign =
ops::Assign(s.WithOpName("assign").WithDevice("/CPU:0"), v, a);
ops::NoOp init(
s.WithOpName("init").WithDevice("/CPU:0").WithControlDependencies(
assign));
GrapplerItem item;
item.fetch.push_back("init");
TF_CHECK_OK(s.ToGraphDef(&item.graph));
GraphMemory memory(item);
Status status = memory.InferStatically(devices_);
TF_CHECK_OK(status);
const GraphMemory::MemoryUsage& mem = memory.GetPeakMemoryUsage("/CPU:0");
EXPECT_EQ(36, mem.used_memory);
std::set<string> tensors;
for (const auto& t : mem.live_tensors) {
tensors.insert(strings::StrCat(t.node, ":", t.output_id));
}
std::set<string> expected;
expected.insert("a:0");
expected.insert("v:0");
expected.insert("assign:0");
EXPECT_EQ(expected, tensors);
}
} // namespace
} // namespace grappler
} // namespace tensorflow
| sarvex/tensorflow | tensorflow/core/grappler/costs/graph_memory_test.cc | C++ | apache-2.0 | 7,766 |
// Copyright 2014 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util/mach/mach_message_server.h"
#include <string.h>
#include <limits>
#include "base/logging.h"
#include "base/mac/mach_logging.h"
#include "base/mac/scoped_mach_vm.h"
#include "util/mach/mach_message.h"
namespace crashpad {
namespace {
//! \brief Manages a dynamically-allocated buffer to be used for Mach messaging.
class MachMessageBuffer {
public:
MachMessageBuffer() : vm_() {}
~MachMessageBuffer() {}
//! \return A pointer to the buffer.
mach_msg_header_t* Header() const {
return reinterpret_cast<mach_msg_header_t*>(vm_.address());
}
//! \brief Ensures that this object has a buffer of exactly \a size bytes
//! available.
//!
//! If the existing buffer is a different size, it will be reallocated without
//! copying any of the old buffer’s contents to the new buffer. The contents
//! of the buffer are unspecified after this call, even if no reallocation is
//! performed.
kern_return_t Reallocate(vm_size_t size) {
// This test uses == instead of > so that a large reallocation to receive a
// large message doesn’t cause permanent memory bloat for the duration of
// a MachMessageServer::Run() loop.
if (size != vm_.size()) {
// reset() first, so that two allocations don’t exist simultaneously.
vm_.reset();
if (size) {
vm_address_t address;
kern_return_t kr =
vm_allocate(mach_task_self(),
&address,
size,
VM_FLAGS_ANYWHERE | VM_MAKE_TAG(VM_MEMORY_MACH_MSG));
if (kr != KERN_SUCCESS) {
return kr;
}
vm_.reset(address, size);
}
}
#if !defined(NDEBUG)
// Regardless of whether the allocation was changed, scribble over the
// memory to make sure that nothing relies on zero-initialization or stale
// contents.
memset(Header(), 0x66, size);
#endif
return KERN_SUCCESS;
}
private:
base::mac::ScopedMachVM vm_;
DISALLOW_COPY_AND_ASSIGN(MachMessageBuffer);
};
// Wraps MachMessageWithDeadline(), using a MachMessageBuffer argument which
// will be resized to |receive_size| (after being page-rounded). MACH_RCV_MSG
// is always combined into |options|.
mach_msg_return_t MachMessageAllocateReceive(MachMessageBuffer* request,
mach_msg_option_t options,
mach_msg_size_t receive_size,
mach_port_name_t receive_port,
MachMessageDeadline deadline,
mach_port_name_t notify_port,
bool run_even_if_expired) {
mach_msg_size_t request_alloc = round_page(receive_size);
kern_return_t kr = request->Reallocate(request_alloc);
if (kr != KERN_SUCCESS) {
return kr;
}
return MachMessageWithDeadline(request->Header(),
options | MACH_RCV_MSG,
receive_size,
receive_port,
deadline,
notify_port,
run_even_if_expired);
}
} // namespace
// This method implements a server similar to 10.9.4
// xnu-2422.110.17/libsyscall/mach/mach_msg.c mach_msg_server_once(). The server
// callback function and |max_size| parameter have been replaced with a C++
// interface. The |persistent| parameter has been added, allowing this method to
// serve as a stand-in for mach_msg_server(). The |timeout_ms| parameter has
// been added, allowing this function to not block indefinitely.
//
// static
mach_msg_return_t MachMessageServer::Run(Interface* interface,
mach_port_t receive_port,
mach_msg_options_t options,
Persistent persistent,
ReceiveLarge receive_large,
mach_msg_timeout_t timeout_ms) {
options &= ~(MACH_RCV_MSG | MACH_SEND_MSG);
const MachMessageDeadline deadline =
MachMessageDeadlineFromTimeout(timeout_ms);
if (receive_large == kReceiveLargeResize) {
options |= MACH_RCV_LARGE;
} else {
options &= ~MACH_RCV_LARGE;
}
const mach_msg_size_t trailer_alloc = REQUESTED_TRAILER_SIZE(options);
const mach_msg_size_t expected_receive_size =
round_msg(interface->MachMessageServerRequestSize()) + trailer_alloc;
const mach_msg_size_t request_size = (receive_large == kReceiveLargeResize)
? round_page(expected_receive_size)
: expected_receive_size;
DCHECK_GE(request_size, sizeof(mach_msg_empty_rcv_t));
// mach_msg_server() and mach_msg_server_once() would consider whether
// |options| contains MACH_SEND_TRAILER and include MAX_TRAILER_SIZE in this
// computation if it does, but that option is ineffective on macOS.
const mach_msg_size_t reply_size = interface->MachMessageServerReplySize();
DCHECK_GE(reply_size, sizeof(mach_msg_empty_send_t));
const mach_msg_size_t reply_alloc = round_page(reply_size);
MachMessageBuffer request;
MachMessageBuffer reply;
bool received_any_request = false;
bool retry;
kern_return_t kr;
do {
retry = false;
kr = MachMessageAllocateReceive(&request,
options,
request_size,
receive_port,
deadline,
MACH_PORT_NULL,
!received_any_request);
if (kr == MACH_RCV_TOO_LARGE) {
switch (receive_large) {
case kReceiveLargeError:
break;
case kReceiveLargeIgnore:
// Try again, even in one-shot mode. The caller is expecting this
// method to take action on the first message in the queue, and has
// indicated that they want large messages to be ignored. The
// alternatives, which might involve returning MACH_MSG_SUCCESS,
// MACH_RCV_TIMED_OUT, or MACH_RCV_TOO_LARGE to a caller that
// specified one-shot behavior, all seem less correct than retrying.
MACH_LOG(WARNING, kr) << "mach_msg: ignoring large message";
retry = true;
continue;
case kReceiveLargeResize: {
mach_msg_size_t this_request_size = round_page(
round_msg(request.Header()->msgh_size) + trailer_alloc);
DCHECK_GT(this_request_size, request_size);
kr = MachMessageAllocateReceive(&request,
options & ~MACH_RCV_LARGE,
this_request_size,
receive_port,
deadline,
MACH_PORT_NULL,
!received_any_request);
break;
}
}
}
if (kr != MACH_MSG_SUCCESS) {
return kr;
}
received_any_request = true;
kr = reply.Reallocate(reply_alloc);
if (kr != KERN_SUCCESS) {
return kr;
}
mach_msg_header_t* request_header = request.Header();
mach_msg_header_t* reply_header = reply.Header();
bool destroy_complex_request = false;
interface->MachMessageServerFunction(
request_header, reply_header, &destroy_complex_request);
if (!(reply_header->msgh_bits & MACH_MSGH_BITS_COMPLEX)) {
// This only works if the reply message is not complex, because otherwise,
// the location of the RetCode field is not known. It should be possible
// to locate the RetCode field by looking beyond the descriptors in a
// complex reply message, but this is not currently done. This behavior
// has not proven itself necessary in practice, and it’s not done by
// mach_msg_server() or mach_msg_server_once() either.
mig_reply_error_t* reply_mig =
reinterpret_cast<mig_reply_error_t*>(reply_header);
if (reply_mig->RetCode == MIG_NO_REPLY) {
reply_header->msgh_remote_port = MACH_PORT_NULL;
} else if (reply_mig->RetCode != KERN_SUCCESS &&
request_header->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
destroy_complex_request = true;
}
}
if (destroy_complex_request &&
request_header->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
request_header->msgh_remote_port = MACH_PORT_NULL;
mach_msg_destroy(request_header);
}
if (reply_header->msgh_remote_port != MACH_PORT_NULL) {
// Avoid blocking indefinitely. This duplicates the logic in 10.9.5
// xnu-2422.115.4/libsyscall/mach/mach_msg.c mach_msg_server_once(),
// although the special provision for sending to a send-once right is not
// made, because kernel keeps sends to a send-once right on the fast path
// without considering the user-specified timeout. See 10.9.5
// xnu-2422.115.4/osfmk/ipc/ipc_mqueue.c ipc_mqueue_send().
const MachMessageDeadline send_deadline =
deadline == kMachMessageDeadlineWaitIndefinitely
? kMachMessageDeadlineNonblocking
: deadline;
kr = MachMessageWithDeadline(reply_header,
options | MACH_SEND_MSG,
0,
MACH_PORT_NULL,
send_deadline,
MACH_PORT_NULL,
true);
if (kr != MACH_MSG_SUCCESS) {
if (kr == MACH_SEND_INVALID_DEST ||
kr == MACH_SEND_TIMED_OUT ||
kr == MACH_SEND_INTERRUPTED) {
mach_msg_destroy(reply_header);
}
return kr;
}
}
} while (persistent == kPersistent || retry);
return kr;
}
} // namespace crashpad
| atom/crashpad | util/mach/mach_message_server.cc | C++ | apache-2.0 | 10,737 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.roots.ExternalLibraryDescriptor;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.DependencyScope;
import com.intellij.openapi.roots.JavaProjectModelModificationService;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReference;
import com.intellij.util.Consumer;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author nik
*/
class AddExternalLibraryToDependenciesQuickFix extends OrderEntryFix {
private final Module myCurrentModule;
private final PsiReference myReference;
private final ExternalLibraryDescriptor myLibraryDescriptor;
private final String myQualifiedClassName;
public AddExternalLibraryToDependenciesQuickFix(@NotNull Module currentModule,
@NotNull ExternalLibraryDescriptor libraryDescriptor, @NotNull PsiReference reference,
@Nullable String qualifiedClassName) {
myCurrentModule = currentModule;
myReference = reference;
myLibraryDescriptor = libraryDescriptor;
myQualifiedClassName = qualifiedClassName;
}
@Nls
@NotNull
@Override
public String getText() {
return "Add '" + myLibraryDescriptor.getPresentableName() + "' to classpath";
}
@Nls
@NotNull
@Override
public String getFamilyName() {
return getText();
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
return !project.isDisposed() && !myCurrentModule.isDisposed();
}
@Override
public void invoke(@NotNull Project project, final Editor editor, PsiFile file) throws IncorrectOperationException {
DependencyScope scope = suggestScopeByLocation(myCurrentModule, myReference.getElement());
JavaProjectModelModificationService.getInstance(project).addDependency(myCurrentModule, myLibraryDescriptor, scope).done(
new Consumer<Void>() {
@Override
public void consume(Void aVoid) {
new WriteAction() {
protected void run(@NotNull final Result result) {
importClass(myCurrentModule, editor, myReference, myQualifiedClassName);
}
}.execute();
}
});
}
}
| MichaelNedzelsky/intellij-community | java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddExternalLibraryToDependenciesQuickFix.java | Java | apache-2.0 | 3,201 |
package com.alibaba.otter.canal.instance.manager;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import com.alibaba.otter.canal.common.CanalException;
import com.alibaba.otter.canal.common.alarm.CanalAlarmHandler;
import com.alibaba.otter.canal.common.alarm.LogAlarmHandler;
import com.alibaba.otter.canal.common.utils.JsonUtils;
import com.alibaba.otter.canal.common.zookeeper.ZkClientx;
import com.alibaba.otter.canal.filter.aviater.AviaterRegexFilter;
import com.alibaba.otter.canal.instance.core.CanalInstance;
import com.alibaba.otter.canal.instance.core.CanalInstanceSupport;
import com.alibaba.otter.canal.instance.manager.model.Canal;
import com.alibaba.otter.canal.instance.manager.model.CanalParameter;
import com.alibaba.otter.canal.instance.manager.model.CanalParameter.DataSourcing;
import com.alibaba.otter.canal.instance.manager.model.CanalParameter.HAMode;
import com.alibaba.otter.canal.instance.manager.model.CanalParameter.IndexMode;
import com.alibaba.otter.canal.instance.manager.model.CanalParameter.MetaMode;
import com.alibaba.otter.canal.instance.manager.model.CanalParameter.SourcingType;
import com.alibaba.otter.canal.instance.manager.model.CanalParameter.StorageMode;
import com.alibaba.otter.canal.instance.manager.model.CanalParameter.StorageScavengeMode;
import com.alibaba.otter.canal.meta.CanalMetaManager;
import com.alibaba.otter.canal.meta.MemoryMetaManager;
import com.alibaba.otter.canal.meta.PeriodMixedMetaManager;
import com.alibaba.otter.canal.meta.ZooKeeperMetaManager;
import com.alibaba.otter.canal.parse.CanalEventParser;
import com.alibaba.otter.canal.parse.ha.CanalHAController;
import com.alibaba.otter.canal.parse.ha.HeartBeatHAController;
import com.alibaba.otter.canal.parse.inbound.AbstractEventParser;
import com.alibaba.otter.canal.parse.inbound.group.GroupEventParser;
import com.alibaba.otter.canal.parse.inbound.mysql.LocalBinlogEventParser;
import com.alibaba.otter.canal.parse.inbound.mysql.MysqlEventParser;
import com.alibaba.otter.canal.parse.index.CanalLogPositionManager;
import com.alibaba.otter.canal.parse.index.FailbackLogPositionManager;
import com.alibaba.otter.canal.parse.index.MemoryLogPositionManager;
import com.alibaba.otter.canal.parse.index.MetaLogPositionManager;
import com.alibaba.otter.canal.parse.index.PeriodMixedLogPositionManager;
import com.alibaba.otter.canal.parse.index.ZooKeeperLogPositionManager;
import com.alibaba.otter.canal.parse.support.AuthenticationInfo;
import com.alibaba.otter.canal.protocol.CanalEntry.Entry;
import com.alibaba.otter.canal.protocol.ClientIdentity;
import com.alibaba.otter.canal.protocol.position.EntryPosition;
import com.alibaba.otter.canal.sink.CanalEventSink;
import com.alibaba.otter.canal.sink.entry.EntryEventSink;
import com.alibaba.otter.canal.sink.entry.group.GroupEventSink;
import com.alibaba.otter.canal.store.AbstractCanalStoreScavenge;
import com.alibaba.otter.canal.store.CanalEventStore;
import com.alibaba.otter.canal.store.memory.MemoryEventStoreWithBuffer;
import com.alibaba.otter.canal.store.model.BatchMode;
import com.alibaba.otter.canal.store.model.Event;
/**
* 单个canal实例,比如一个destination会独立一个实例
*
* @author jianghang 2012-7-11 下午09:26:51
* @version 1.0.0
*/
public class CanalInstanceWithManager extends CanalInstanceSupport implements CanalInstance {
private static final Logger logger = LoggerFactory.getLogger(CanalInstanceWithManager.class);
protected Long canalId; // 和manager交互唯一标示
protected String destination; // 队列名字
protected String filter; // 过滤表达式
protected CanalParameter parameters; // 对应参数
protected CanalMetaManager metaManager; // 消费信息管理器
protected CanalEventStore<Event> eventStore; // 有序队列
protected CanalEventParser eventParser; // 解析对应的数据信息
protected CanalEventSink<List<Entry>> eventSink; // 链接parse和store的桥接器
protected CanalAlarmHandler alarmHandler; // alarm报警机制
protected ZkClientx zkClientx;
public CanalInstanceWithManager(Canal canal){
this(canal, null);
}
public CanalInstanceWithManager(Canal canal, String filter){
this.parameters = canal.getCanalParameter();
this.canalId = canal.getId();
this.destination = canal.getName();
this.filter = filter;
logger.info("init CannalInstance for {}-{} with parameters:{}", canalId, destination, parameters);
// 初始化报警机制
initAlarmHandler();
// 初始化metaManager
initMetaManager();
// 初始化eventStore
initEventStore();
// 初始化eventSink
initEventSink();
// 初始化eventParser;
initEventParser();
// 基础工具,需要提前start,会有先订阅再根据filter条件启动paser的需求
if (!alarmHandler.isStart()) {
alarmHandler.start();
}
if (!metaManager.isStart()) {
metaManager.start();
}
logger.info("init successful....");
}
public void start() {
super.start();
// 初始化metaManager
logger.info("start CannalInstance for {}-{} with parameters:{}", canalId, destination, parameters);
if (!metaManager.isStart()) {
metaManager.start();
}
if (!alarmHandler.isStart()) {
alarmHandler.start();
}
if (!eventStore.isStart()) {
eventStore.start();
}
if (!eventSink.isStart()) {
eventSink.start();
}
if (!eventParser.isStart()) {
beforeStartEventParser(eventParser);
eventParser.start();
}
logger.info("start successful....");
}
public void stop() {
logger.info("stop CannalInstance for {}-{} ", new Object[] { canalId, destination });
if (eventParser.isStart()) {
eventParser.stop();
afterStopEventParser(eventParser);
}
if (eventSink.isStart()) {
eventSink.stop();
}
if (eventStore.isStart()) {
eventStore.stop();
}
if (metaManager.isStart()) {
metaManager.stop();
}
if (alarmHandler.isStart()) {
alarmHandler.stop();
}
// if (zkClientx != null) {
// zkClientx.close();
// }
super.stop();
logger.info("stop successful....");
}
public boolean subscribeChange(ClientIdentity identity) {
if (StringUtils.isNotEmpty(identity.getFilter())) {
AviaterRegexFilter aviaterFilter = new AviaterRegexFilter(identity.getFilter());
boolean isGroup = (eventParser instanceof GroupEventParser);
if (isGroup) {
// 处理group的模式
List<CanalEventParser> eventParsers = ((GroupEventParser) eventParser).getEventParsers();
for (CanalEventParser singleEventParser : eventParsers) {// 需要遍历启动
((AbstractEventParser) singleEventParser).setEventFilter(aviaterFilter);
}
} else {
((AbstractEventParser) eventParser).setEventFilter(aviaterFilter);
}
}
// filter的处理规则
// a. parser处理数据过滤处理
// b. sink处理数据的路由&分发,一份parse数据经过sink后可以分发为多份,每份的数据可以根据自己的过滤规则不同而有不同的数据
// 后续内存版的一对多分发,可以考虑
return true;
}
protected void afterStartEventParser(CanalEventParser eventParser) {
super.afterStartEventParser(eventParser);
// 读取一下历史订阅的filter信息
List<ClientIdentity> clientIdentitys = metaManager.listAllSubscribeInfo(destination);
for (ClientIdentity clientIdentity : clientIdentitys) {
subscribeChange(clientIdentity);
}
}
protected void initAlarmHandler() {
logger.info("init alarmHandler begin...");
alarmHandler = new LogAlarmHandler();
logger.info("init alarmHandler end! \n\t load CanalAlarmHandler:{} ", alarmHandler.getClass().getName());
}
protected void initMetaManager() {
logger.info("init metaManager begin...");
MetaMode mode = parameters.getMetaMode();
if (mode.isMemory()) {
metaManager = new MemoryMetaManager();
} else if (mode.isZookeeper()) {
metaManager = new ZooKeeperMetaManager();
((ZooKeeperMetaManager) metaManager).setZkClientx(getZkclientx());
} else if (mode.isMixed()) {
// metaManager = new MixedMetaManager();
metaManager = new PeriodMixedMetaManager();// 换用优化过的mixed, at
// 2012-09-11
// 设置内嵌的zk metaManager
ZooKeeperMetaManager zooKeeperMetaManager = new ZooKeeperMetaManager();
zooKeeperMetaManager.setZkClientx(getZkclientx());
((PeriodMixedMetaManager) metaManager).setZooKeeperMetaManager(zooKeeperMetaManager);
} else {
throw new CanalException("unsupport MetaMode for " + mode);
}
logger.info("init metaManager end! \n\t load CanalMetaManager:{} ", metaManager.getClass().getName());
}
protected void initEventStore() {
logger.info("init eventStore begin...");
StorageMode mode = parameters.getStorageMode();
if (mode.isMemory()) {
MemoryEventStoreWithBuffer memoryEventStore = new MemoryEventStoreWithBuffer();
memoryEventStore.setBufferSize(parameters.getMemoryStorageBufferSize());
memoryEventStore.setBufferMemUnit(parameters.getMemoryStorageBufferMemUnit());
memoryEventStore.setBatchMode(BatchMode.valueOf(parameters.getStorageBatchMode().name()));
memoryEventStore.setDdlIsolation(parameters.getDdlIsolation());
eventStore = memoryEventStore;
} else if (mode.isFile()) {
// 后续版本支持
throw new CanalException("unsupport MetaMode for " + mode);
} else if (mode.isMixed()) {
// 后续版本支持
throw new CanalException("unsupport MetaMode for " + mode);
} else {
throw new CanalException("unsupport MetaMode for " + mode);
}
if (eventStore instanceof AbstractCanalStoreScavenge) {
StorageScavengeMode scavengeMode = parameters.getStorageScavengeMode();
AbstractCanalStoreScavenge eventScavengeStore = (AbstractCanalStoreScavenge) eventStore;
eventScavengeStore.setDestination(destination);
eventScavengeStore.setCanalMetaManager(metaManager);
eventScavengeStore.setOnAck(scavengeMode.isOnAck());
eventScavengeStore.setOnFull(scavengeMode.isOnFull());
eventScavengeStore.setOnSchedule(scavengeMode.isOnSchedule());
if (scavengeMode.isOnSchedule()) {
eventScavengeStore.setScavengeSchedule(parameters.getScavengeSchdule());
}
}
logger.info("init eventStore end! \n\t load CanalEventStore:{}", eventStore.getClass().getName());
}
protected void initEventSink() {
logger.info("init eventSink begin...");
int groupSize = getGroupSize();
if (groupSize <= 1) {
eventSink = new EntryEventSink();
} else {
eventSink = new GroupEventSink(groupSize);
}
if (eventSink instanceof EntryEventSink) {
((EntryEventSink) eventSink).setFilterTransactionEntry(false);
((EntryEventSink) eventSink).setEventStore(getEventStore());
}
// if (StringUtils.isNotEmpty(filter)) {
// AviaterRegexFilter aviaterFilter = new AviaterRegexFilter(filter);
// ((AbstractCanalEventSink) eventSink).setFilter(aviaterFilter);
// }
logger.info("init eventSink end! \n\t load CanalEventSink:{}", eventSink.getClass().getName());
}
protected void initEventParser() {
logger.info("init eventParser begin...");
SourcingType type = parameters.getSourcingType();
List<List<DataSourcing>> groupDbAddresses = parameters.getGroupDbAddresses();
if (!CollectionUtils.isEmpty(groupDbAddresses)) {
int size = groupDbAddresses.get(0).size();// 取第一个分组的数量,主备分组的数量必须一致
List<CanalEventParser> eventParsers = new ArrayList<CanalEventParser>();
for (int i = 0; i < size; i++) {
List<InetSocketAddress> dbAddress = new ArrayList<InetSocketAddress>();
SourcingType lastType = null;
for (List<DataSourcing> groupDbAddress : groupDbAddresses) {
if (lastType != null && !lastType.equals(groupDbAddress.get(i).getType())) {
throw new CanalException(String.format("master/slave Sourcing type is unmatch. %s vs %s",
lastType,
groupDbAddress.get(i).getType()));
}
lastType = groupDbAddress.get(i).getType();
dbAddress.add(groupDbAddress.get(i).getDbAddress());
}
// 初始化其中的一个分组parser
eventParsers.add(doInitEventParser(lastType, dbAddress));
}
if (eventParsers.size() > 1) { // 如果存在分组,构造分组的parser
GroupEventParser groupEventParser = new GroupEventParser();
groupEventParser.setEventParsers(eventParsers);
this.eventParser = groupEventParser;
} else {
this.eventParser = eventParsers.get(0);
}
} else {
// 创建一个空数据库地址的parser,可能使用了tddl指定地址,启动的时候才会从tddl获取地址
this.eventParser = doInitEventParser(type, new ArrayList<InetSocketAddress>());
}
logger.info("init eventParser end! \n\t load CanalEventParser:{}", eventParser.getClass().getName());
}
private CanalEventParser doInitEventParser(SourcingType type, List<InetSocketAddress> dbAddresses) {
CanalEventParser eventParser;
if (type.isMysql()) {
MysqlEventParser mysqlEventParser = new MysqlEventParser();
mysqlEventParser.setDestination(destination);
// 编码参数
mysqlEventParser.setConnectionCharset(Charset.forName(parameters.getConnectionCharset()));
mysqlEventParser.setConnectionCharsetNumber(parameters.getConnectionCharsetNumber());
// 网络相关参数
mysqlEventParser.setDefaultConnectionTimeoutInSeconds(parameters.getDefaultConnectionTimeoutInSeconds());
mysqlEventParser.setSendBufferSize(parameters.getSendBufferSize());
mysqlEventParser.setReceiveBufferSize(parameters.getReceiveBufferSize());
// 心跳检查参数
mysqlEventParser.setDetectingEnable(parameters.getDetectingEnable());
mysqlEventParser.setDetectingSQL(parameters.getDetectingSQL());
mysqlEventParser.setDetectingIntervalInSeconds(parameters.getDetectingIntervalInSeconds());
// 数据库信息参数
mysqlEventParser.setSlaveId(parameters.getSlaveId());
if (!CollectionUtils.isEmpty(dbAddresses)) {
mysqlEventParser.setMasterInfo(new AuthenticationInfo(dbAddresses.get(0),
parameters.getDbUsername(),
parameters.getDbPassword(),
parameters.getDefaultDatabaseName()));
if (dbAddresses.size() > 1) {
mysqlEventParser.setStandbyInfo(new AuthenticationInfo(dbAddresses.get(1),
parameters.getDbUsername(),
parameters.getDbPassword(),
parameters.getDefaultDatabaseName()));
}
}
if (!CollectionUtils.isEmpty(parameters.getPositions())) {
EntryPosition masterPosition = JsonUtils.unmarshalFromString(parameters.getPositions().get(0),
EntryPosition.class);
// binlog位置参数
mysqlEventParser.setMasterPosition(masterPosition);
if (parameters.getPositions().size() > 1) {
EntryPosition standbyPosition = JsonUtils.unmarshalFromString(parameters.getPositions().get(0),
EntryPosition.class);
mysqlEventParser.setStandbyPosition(standbyPosition);
}
}
mysqlEventParser.setFallbackIntervalInSeconds(parameters.getFallbackIntervalInSeconds());
mysqlEventParser.setProfilingEnabled(false);
mysqlEventParser.setFilterTableError(parameters.getFilterTableError());
eventParser = mysqlEventParser;
} else if (type.isLocalBinlog()) {
LocalBinlogEventParser localBinlogEventParser = new LocalBinlogEventParser();
localBinlogEventParser.setDestination(destination);
localBinlogEventParser.setBufferSize(parameters.getReceiveBufferSize());
localBinlogEventParser.setConnectionCharset(Charset.forName(parameters.getConnectionCharset()));
localBinlogEventParser.setConnectionCharsetNumber(parameters.getConnectionCharsetNumber());
localBinlogEventParser.setDirectory(parameters.getLocalBinlogDirectory());
localBinlogEventParser.setProfilingEnabled(false);
localBinlogEventParser.setDetectingEnable(parameters.getDetectingEnable());
localBinlogEventParser.setDetectingIntervalInSeconds(parameters.getDetectingIntervalInSeconds());
localBinlogEventParser.setFilterTableError(parameters.getFilterTableError());
// 数据库信息,反查表结构时需要
if (!CollectionUtils.isEmpty(dbAddresses)) {
localBinlogEventParser.setMasterInfo(new AuthenticationInfo(dbAddresses.get(0),
parameters.getDbUsername(),
parameters.getDbPassword(),
parameters.getDefaultDatabaseName()));
}
eventParser = localBinlogEventParser;
} else if (type.isOracle()) {
throw new CanalException("unsupport SourcingType for " + type);
} else {
throw new CanalException("unsupport SourcingType for " + type);
}
// add transaction support at 2012-12-06
if (eventParser instanceof AbstractEventParser) {
AbstractEventParser abstractEventParser = (AbstractEventParser) eventParser;
abstractEventParser.setTransactionSize(parameters.getTransactionSize());
abstractEventParser.setLogPositionManager(initLogPositionManager());
abstractEventParser.setAlarmHandler(getAlarmHandler());
abstractEventParser.setEventSink(getEventSink());
if (StringUtils.isNotEmpty(filter)) {
AviaterRegexFilter aviaterFilter = new AviaterRegexFilter(filter);
abstractEventParser.setEventFilter(aviaterFilter);
}
// 设置黑名单
if (StringUtils.isNotEmpty(parameters.getBlackFilter())) {
AviaterRegexFilter aviaterFilter = new AviaterRegexFilter(parameters.getBlackFilter());
abstractEventParser.setEventBlackFilter(aviaterFilter);
}
}
if (eventParser instanceof MysqlEventParser) {
MysqlEventParser mysqlEventParser = (MysqlEventParser) eventParser;
// 初始化haController,绑定与eventParser的关系,haController会控制eventParser
CanalHAController haController = initHaController();
mysqlEventParser.setHaController(haController);
}
return eventParser;
}
protected CanalHAController initHaController() {
logger.info("init haController begin...");
HAMode haMode = parameters.getHaMode();
CanalHAController haController = null;
if (haMode.isHeartBeat()) {
haController = new HeartBeatHAController();
((HeartBeatHAController) haController).setDetectingRetryTimes(parameters.getDetectingRetryTimes());
((HeartBeatHAController) haController).setSwitchEnable(parameters.getHeartbeatHaEnable());
} else {
throw new CanalException("unsupport HAMode for " + haMode);
}
logger.info("init haController end! \n\t load CanalHAController:{}", haController.getClass().getName());
return haController;
}
protected CanalLogPositionManager initLogPositionManager() {
logger.info("init logPositionPersistManager begin...");
IndexMode indexMode = parameters.getIndexMode();
CanalLogPositionManager logPositionManager = null;
if (indexMode.isMemory()) {
logPositionManager = new MemoryLogPositionManager();
} else if (indexMode.isZookeeper()) {
logPositionManager = new ZooKeeperLogPositionManager();
((ZooKeeperLogPositionManager) logPositionManager).setZkClientx(getZkclientx());
} else if (indexMode.isMixed()) {
logPositionManager = new PeriodMixedLogPositionManager();
ZooKeeperLogPositionManager zooKeeperLogPositionManager = new ZooKeeperLogPositionManager();
zooKeeperLogPositionManager.setZkClientx(getZkclientx());
((PeriodMixedLogPositionManager) logPositionManager).setZooKeeperLogPositionManager(zooKeeperLogPositionManager);
} else if (indexMode.isMeta()) {
logPositionManager = new MetaLogPositionManager();
((MetaLogPositionManager) logPositionManager).setMetaManager(metaManager);
} else if (indexMode.isMemoryMetaFailback()) {
MemoryLogPositionManager primaryLogPositionManager = new MemoryLogPositionManager();
MetaLogPositionManager failbackLogPositionManager = new MetaLogPositionManager();
failbackLogPositionManager.setMetaManager(metaManager);
logPositionManager = new FailbackLogPositionManager();
((FailbackLogPositionManager) logPositionManager).setPrimary(primaryLogPositionManager);
((FailbackLogPositionManager) logPositionManager).setFailback(failbackLogPositionManager);
} else {
throw new CanalException("unsupport indexMode for " + indexMode);
}
logger.info("init logPositionManager end! \n\t load CanalLogPositionManager:{}", logPositionManager.getClass()
.getName());
return logPositionManager;
}
protected void startEventParserInternal(CanalEventParser eventParser, boolean isGroup) {
if (eventParser instanceof AbstractEventParser) {
AbstractEventParser abstractEventParser = (AbstractEventParser) eventParser;
abstractEventParser.setAlarmHandler(getAlarmHandler());
}
super.startEventParserInternal(eventParser, isGroup);
}
private int getGroupSize() {
List<List<DataSourcing>> groupDbAddresses = parameters.getGroupDbAddresses();
if (!CollectionUtils.isEmpty(groupDbAddresses)) {
return groupDbAddresses.get(0).size();
} else {
// 可能是基于tddl的启动
return 1;
}
}
private synchronized ZkClientx getZkclientx() {
// 做一下排序,保证相同的机器只使用同一个链接
List<String> zkClusters = new ArrayList<String>(parameters.getZkClusters());
Collections.sort(zkClusters);
return ZkClientx.getZkClient(StringUtils.join(zkClusters, ";"));
}
// =====================================
public String getDestination() {
return destination;
}
public CanalMetaManager getMetaManager() {
return metaManager;
}
public CanalEventStore<Event> getEventStore() {
return eventStore;
}
public CanalEventParser getEventParser() {
return eventParser;
}
public CanalEventSink<List<Entry>> getEventSink() {
return eventSink;
}
public CanalAlarmHandler getAlarmHandler() {
return alarmHandler;
}
public void setAlarmHandler(CanalAlarmHandler alarmHandler) {
this.alarmHandler = alarmHandler;
}
}
| yonglehou/canal | instance/manager/src/main/java/com/alibaba/otter/canal/instance/manager/CanalInstanceWithManager.java | Java | apache-2.0 | 25,518 |
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
******************************************************************************/
package org.apache.sling.scripting.sightly.impl.engine.runtime;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.sling.api.adapter.Adaptable;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.scripting.sightly.Record;
import org.apache.sling.scripting.sightly.render.AbstractRuntimeObjectModel;
public class SlingRuntimeObjectModel extends AbstractRuntimeObjectModel {
protected Object getProperty(Object target, Object propertyObj) {
String property = toString(propertyObj);
if (StringUtils.isEmpty(property)) {
throw new IllegalArgumentException("Invalid property name");
}
if (target == null) {
return null;
}
Object result = null;
if (target instanceof Map) {
result = getMapProperty((Map) target, property);
}
if (result == null && target instanceof Record) {
result = ((Record) target).getProperty(property);
}
if (result == null) {
result = getObjectProperty(target, property);
}
if (result == null && target instanceof Adaptable) {
ValueMap valueMap = ((Adaptable) target).adaptTo(ValueMap.class);
if (valueMap != null) {
result = valueMap.get(property);
}
}
return result;
}
}
| Nimco/sling | bundles/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/runtime/SlingRuntimeObjectModel.java | Java | apache-2.0 | 2,349 |
// 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 org.intellij.lang.xpath.xslt.psi.impl;
import com.intellij.psi.xml.XmlTag;
import org.intellij.lang.xpath.psi.XPathExpression;
import org.intellij.lang.xpath.xslt.psi.XsltApplyTemplates;
import org.intellij.lang.xpath.xslt.util.QNameUtil;
import org.intellij.lang.xpath.xslt.util.XsltCodeInsightUtil;
import org.jetbrains.annotations.Nullable;
import javax.xml.namespace.QName;
public class XsltApplyTemplatesImpl extends XsltTemplateInvocationBase implements XsltApplyTemplates {
protected XsltApplyTemplatesImpl(XmlTag target) {
super(target);
}
@Override
public String toString() {
return "XsltApplyTemplates[" + getSelect() + "]";
}
@Override
@Nullable
public XPathExpression getSelect() {
return XsltCodeInsightUtil.getXPathExpression(this, "select");
}
@Override
public QName getMode() {
final String mode = getTag().getAttributeValue("mode");
return mode != null ? QNameUtil.createQName(mode, getTag()) : null;
}
} | siosio/intellij-community | plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/psi/impl/XsltApplyTemplatesImpl.java | Java | apache-2.0 | 1,162 |
cask "vu" do
version "1.2,6,1523016199"
sha256 "a51884117a8e33339429a93a84c70eb82db46dc50ebe827ab7b7c9a0c6ced313"
url "https://dl.devmate.com/com.boriskarulin.vu/#{version.csv.second}/#{version.csv.third}/vu-#{version.csv.second}.dmg",
verified: "dl.devmate.com/com.boriskarulin.vu/"
name "vu"
desc "Instagram client"
homepage "https://datastills.com/vu/"
livecheck do
url "https://updates.devmate.com/com.boriskarulin.vu.xml"
strategy :sparkle do |item|
match = item.url.match(%r{/(\d+)/vu-(\d+(?:\.\d+)*)\.dmg}i)
next if match.blank?
"#{item.short_version},#{item.version},#{match[1]}"
end
end
depends_on macos: ">= :sierra"
app "vu.app"
end
| nrlquaker/homebrew-cask | Casks/vu.rb | Ruby | bsd-2-clause | 705 |
# -*- coding: utf-8 -*-
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Mathieu Blondel <mathieu@mblondel.org>
# Robert Layton <robertlayton@gmail.com>
# Andreas Mueller <amueller@ais.uni-bonn.de>
# Philippe Gervais <philippe.gervais@inria.fr>
# Lars Buitinck <larsmans@gmail.com>
# Joel Nothman <joel.nothman@gmail.com>
# License: BSD 3 clause
import itertools
import numpy as np
from scipy.spatial import distance
from scipy.sparse import csr_matrix
from scipy.sparse import issparse
from ..utils import check_array
from ..utils import gen_even_slices
from ..utils import gen_batches
from ..utils.fixes import partial
from ..utils.extmath import row_norms, safe_sparse_dot
from ..preprocessing import normalize
from ..externals.joblib import Parallel
from ..externals.joblib import delayed
from ..externals.joblib.parallel import cpu_count
from .pairwise_fast import _chi2_kernel_fast, _sparse_manhattan
# Utility Functions
def _return_float_dtype(X, Y):
"""
1. If dtype of X and Y is float32, then dtype float32 is returned.
2. Else dtype float is returned.
"""
if not issparse(X) and not isinstance(X, np.ndarray):
X = np.asarray(X)
if Y is None:
Y_dtype = X.dtype
elif not issparse(Y) and not isinstance(Y, np.ndarray):
Y = np.asarray(Y)
Y_dtype = Y.dtype
else:
Y_dtype = Y.dtype
if X.dtype == Y_dtype == np.float32:
dtype = np.float32
else:
dtype = np.float
return X, Y, dtype
def check_pairwise_arrays(X, Y, precomputed=False):
""" Set X and Y appropriately and checks inputs
If Y is None, it is set as a pointer to X (i.e. not a copy).
If Y is given, this does not happen.
All distance metrics should use this function first to assert that the
given parameters are correct and safe to use.
Specifically, this function first ensures that both X and Y are arrays,
then checks that they are at least two dimensional while ensuring that
their elements are floats. Finally, the function checks that the size
of the second dimension of the two arrays is equal, or the equivalent
check for a precomputed distance matrix.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples_a, n_features)
Y : {array-like, sparse matrix}, shape (n_samples_b, n_features)
precomputed : bool
True if X is to be treated as precomputed distances to the samples in
Y.
Returns
-------
safe_X : {array-like, sparse matrix}, shape (n_samples_a, n_features)
An array equal to X, guaranteed to be a numpy array.
safe_Y : {array-like, sparse matrix}, shape (n_samples_b, n_features)
An array equal to Y if Y was not None, guaranteed to be a numpy array.
If Y was None, safe_Y will be a pointer to X.
"""
X, Y, dtype = _return_float_dtype(X, Y)
if Y is X or Y is None:
X = Y = check_array(X, accept_sparse='csr', dtype=dtype)
else:
X = check_array(X, accept_sparse='csr', dtype=dtype)
Y = check_array(Y, accept_sparse='csr', dtype=dtype)
if precomputed:
if X.shape[1] != Y.shape[0]:
raise ValueError("Precomputed metric requires shape "
"(n_queries, n_indexed). Got (%d, %d) "
"for %d indexed." %
(X.shape[0], X.shape[1], Y.shape[0]))
elif X.shape[1] != Y.shape[1]:
raise ValueError("Incompatible dimension for X and Y matrices: "
"X.shape[1] == %d while Y.shape[1] == %d" % (
X.shape[1], Y.shape[1]))
return X, Y
def check_paired_arrays(X, Y):
""" Set X and Y appropriately and checks inputs for paired distances
All paired distance metrics should use this function first to assert that
the given parameters are correct and safe to use.
Specifically, this function first ensures that both X and Y are arrays,
then checks that they are at least two dimensional while ensuring that
their elements are floats. Finally, the function checks that the size
of the dimensions of the two arrays are equal.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples_a, n_features)
Y : {array-like, sparse matrix}, shape (n_samples_b, n_features)
Returns
-------
safe_X : {array-like, sparse matrix}, shape (n_samples_a, n_features)
An array equal to X, guaranteed to be a numpy array.
safe_Y : {array-like, sparse matrix}, shape (n_samples_b, n_features)
An array equal to Y if Y was not None, guaranteed to be a numpy array.
If Y was None, safe_Y will be a pointer to X.
"""
X, Y = check_pairwise_arrays(X, Y)
if X.shape != Y.shape:
raise ValueError("X and Y should be of same shape. They were "
"respectively %r and %r long." % (X.shape, Y.shape))
return X, Y
# Pairwise distances
def euclidean_distances(X, Y=None, Y_norm_squared=None, squared=False,
X_norm_squared=None):
"""
Considering the rows of X (and Y=X) as vectors, compute the
distance matrix between each pair of vectors.
For efficiency reasons, the euclidean distance between a pair of row
vector x and y is computed as::
dist(x, y) = sqrt(dot(x, x) - 2 * dot(x, y) + dot(y, y))
This formulation has two advantages over other ways of computing distances.
First, it is computationally efficient when dealing with sparse data.
Second, if one argument varies but the other remains unchanged, then
`dot(x, x)` and/or `dot(y, y)` can be pre-computed.
However, this is not the most precise way of doing this computation, and
the distance matrix returned by this function may not be exactly
symmetric as required by, e.g., ``scipy.spatial.distance`` functions.
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples_1, n_features)
Y : {array-like, sparse matrix}, shape (n_samples_2, n_features)
Y_norm_squared : array-like, shape (n_samples_2, ), optional
Pre-computed dot-products of vectors in Y (e.g.,
``(Y**2).sum(axis=1)``)
squared : boolean, optional
Return squared Euclidean distances.
X_norm_squared : array-like, shape = [n_samples_1], optional
Pre-computed dot-products of vectors in X (e.g.,
``(X**2).sum(axis=1)``)
Returns
-------
distances : {array, sparse matrix}, shape (n_samples_1, n_samples_2)
Examples
--------
>>> from sklearn.metrics.pairwise import euclidean_distances
>>> X = [[0, 1], [1, 1]]
>>> # distance between rows of X
>>> euclidean_distances(X, X)
array([[ 0., 1.],
[ 1., 0.]])
>>> # get distance to origin
>>> euclidean_distances(X, [[0, 0]])
array([[ 1. ],
[ 1.41421356]])
See also
--------
paired_distances : distances betweens pairs of elements of X and Y.
"""
X, Y = check_pairwise_arrays(X, Y)
if X_norm_squared is not None:
XX = check_array(X_norm_squared)
if XX.shape == (1, X.shape[0]):
XX = XX.T
elif XX.shape != (X.shape[0], 1):
raise ValueError(
"Incompatible dimensions for X and X_norm_squared")
else:
XX = row_norms(X, squared=True)[:, np.newaxis]
if X is Y: # shortcut in the common case euclidean_distances(X, X)
YY = XX.T
elif Y_norm_squared is not None:
YY = check_array(Y_norm_squared)
if YY.shape != (1, Y.shape[0]):
raise ValueError(
"Incompatible dimensions for Y and Y_norm_squared")
else:
YY = row_norms(Y, squared=True)[np.newaxis, :]
distances = safe_sparse_dot(X, Y.T, dense_output=True)
distances *= -2
distances += XX
distances += YY
np.maximum(distances, 0, out=distances)
if X is Y:
# Ensure that distances between vectors and themselves are set to 0.0.
# This may not be the case due to floating point rounding errors.
distances.flat[::distances.shape[0] + 1] = 0.0
return distances if squared else np.sqrt(distances, out=distances)
def pairwise_distances_argmin_min(X, Y, axis=1, metric="euclidean",
batch_size=500, metric_kwargs=None):
"""Compute minimum distances between one point and a set of points.
This function computes for each row in X, the index of the row of Y which
is closest (according to the specified distance). The minimal distances are
also returned.
This is mostly equivalent to calling:
(pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis),
pairwise_distances(X, Y=Y, metric=metric).min(axis=axis))
but uses much less memory, and is faster for large arrays.
Parameters
----------
X, Y : {array-like, sparse matrix}
Arrays containing points. Respective shapes (n_samples1, n_features)
and (n_samples2, n_features)
batch_size : integer
To reduce memory consumption over the naive solution, data are
processed in batches, comprising batch_size rows of X and
batch_size rows of Y. The default value is quite conservative, but
can be changed for fine-tuning. The larger the number, the larger the
memory usage.
metric : string or callable, default 'euclidean'
metric to use for distance computation. Any metric from scikit-learn
or scipy.spatial.distance can be used.
If metric is a callable function, it is called on each
pair of instances (rows) and the resulting value recorded. The callable
should take two arrays as input and return one value indicating the
distance between them. This works for Scipy's metrics, but is less
efficient than passing the metric name as a string.
Distance matrices are not supported.
Valid values for metric are:
- from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
'manhattan']
- from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev',
'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski',
'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto',
'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath',
'sqeuclidean', 'yule']
See the documentation for scipy.spatial.distance for details on these
metrics.
metric_kwargs : dict, optional
Keyword arguments to pass to specified metric function.
axis : int, optional, default 1
Axis along which the argmin and distances are to be computed.
Returns
-------
argmin : numpy.ndarray
Y[argmin[i], :] is the row in Y that is closest to X[i, :].
distances : numpy.ndarray
distances[i] is the distance between the i-th row in X and the
argmin[i]-th row in Y.
See also
--------
sklearn.metrics.pairwise_distances
sklearn.metrics.pairwise_distances_argmin
"""
dist_func = None
if metric in PAIRWISE_DISTANCE_FUNCTIONS:
dist_func = PAIRWISE_DISTANCE_FUNCTIONS[metric]
elif not callable(metric) and not isinstance(metric, str):
raise ValueError("'metric' must be a string or a callable")
X, Y = check_pairwise_arrays(X, Y)
if metric_kwargs is None:
metric_kwargs = {}
if axis == 0:
X, Y = Y, X
# Allocate output arrays
indices = np.empty(X.shape[0], dtype=np.intp)
values = np.empty(X.shape[0])
values.fill(np.infty)
for chunk_x in gen_batches(X.shape[0], batch_size):
X_chunk = X[chunk_x, :]
for chunk_y in gen_batches(Y.shape[0], batch_size):
Y_chunk = Y[chunk_y, :]
if dist_func is not None:
if metric == 'euclidean': # special case, for speed
d_chunk = safe_sparse_dot(X_chunk, Y_chunk.T,
dense_output=True)
d_chunk *= -2
d_chunk += row_norms(X_chunk, squared=True)[:, np.newaxis]
d_chunk += row_norms(Y_chunk, squared=True)[np.newaxis, :]
np.maximum(d_chunk, 0, d_chunk)
else:
d_chunk = dist_func(X_chunk, Y_chunk, **metric_kwargs)
else:
d_chunk = pairwise_distances(X_chunk, Y_chunk,
metric=metric, **metric_kwargs)
# Update indices and minimum values using chunk
min_indices = d_chunk.argmin(axis=1)
min_values = d_chunk[np.arange(chunk_x.stop - chunk_x.start),
min_indices]
flags = values[chunk_x] > min_values
indices[chunk_x][flags] = min_indices[flags] + chunk_y.start
values[chunk_x][flags] = min_values[flags]
if metric == "euclidean" and not metric_kwargs.get("squared", False):
np.sqrt(values, values)
return indices, values
def pairwise_distances_argmin(X, Y, axis=1, metric="euclidean",
batch_size=500, metric_kwargs=None):
"""Compute minimum distances between one point and a set of points.
This function computes for each row in X, the index of the row of Y which
is closest (according to the specified distance).
This is mostly equivalent to calling:
pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis)
but uses much less memory, and is faster for large arrays.
This function works with dense 2D arrays only.
Parameters
----------
X : array-like
Arrays containing points. Respective shapes (n_samples1, n_features)
and (n_samples2, n_features)
Y : array-like
Arrays containing points. Respective shapes (n_samples1, n_features)
and (n_samples2, n_features)
batch_size : integer
To reduce memory consumption over the naive solution, data are
processed in batches, comprising batch_size rows of X and
batch_size rows of Y. The default value is quite conservative, but
can be changed for fine-tuning. The larger the number, the larger the
memory usage.
metric : string or callable
metric to use for distance computation. Any metric from scikit-learn
or scipy.spatial.distance can be used.
If metric is a callable function, it is called on each
pair of instances (rows) and the resulting value recorded. The callable
should take two arrays as input and return one value indicating the
distance between them. This works for Scipy's metrics, but is less
efficient than passing the metric name as a string.
Distance matrices are not supported.
Valid values for metric are:
- from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
'manhattan']
- from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev',
'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski',
'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto',
'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath',
'sqeuclidean', 'yule']
See the documentation for scipy.spatial.distance for details on these
metrics.
metric_kwargs : dict
keyword arguments to pass to specified metric function.
axis : int, optional, default 1
Axis along which the argmin and distances are to be computed.
Returns
-------
argmin : numpy.ndarray
Y[argmin[i], :] is the row in Y that is closest to X[i, :].
See also
--------
sklearn.metrics.pairwise_distances
sklearn.metrics.pairwise_distances_argmin_min
"""
if metric_kwargs is None:
metric_kwargs = {}
return pairwise_distances_argmin_min(X, Y, axis, metric, batch_size,
metric_kwargs)[0]
def manhattan_distances(X, Y=None, sum_over_features=True,
size_threshold=5e8):
""" Compute the L1 distances between the vectors in X and Y.
With sum_over_features equal to False it returns the componentwise
distances.
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : array_like
An array with shape (n_samples_X, n_features).
Y : array_like, optional
An array with shape (n_samples_Y, n_features).
sum_over_features : bool, default=True
If True the function returns the pairwise distance matrix
else it returns the componentwise L1 pairwise-distances.
Not supported for sparse matrix inputs.
size_threshold : int, default=5e8
Unused parameter.
Returns
-------
D : array
If sum_over_features is False shape is
(n_samples_X * n_samples_Y, n_features) and D contains the
componentwise L1 pairwise-distances (ie. absolute difference),
else shape is (n_samples_X, n_samples_Y) and D contains
the pairwise L1 distances.
Examples
--------
>>> from sklearn.metrics.pairwise import manhattan_distances
>>> manhattan_distances(3, 3)#doctest:+ELLIPSIS
array([[ 0.]])
>>> manhattan_distances(3, 2)#doctest:+ELLIPSIS
array([[ 1.]])
>>> manhattan_distances(2, 3)#doctest:+ELLIPSIS
array([[ 1.]])
>>> manhattan_distances([[1, 2], [3, 4]],\
[[1, 2], [0, 3]])#doctest:+ELLIPSIS
array([[ 0., 2.],
[ 4., 4.]])
>>> import numpy as np
>>> X = np.ones((1, 2))
>>> y = 2 * np.ones((2, 2))
>>> manhattan_distances(X, y, sum_over_features=False)#doctest:+ELLIPSIS
array([[ 1., 1.],
[ 1., 1.]]...)
"""
X, Y = check_pairwise_arrays(X, Y)
if issparse(X) or issparse(Y):
if not sum_over_features:
raise TypeError("sum_over_features=%r not supported"
" for sparse matrices" % sum_over_features)
X = csr_matrix(X, copy=False)
Y = csr_matrix(Y, copy=False)
D = np.zeros((X.shape[0], Y.shape[0]))
_sparse_manhattan(X.data, X.indices, X.indptr,
Y.data, Y.indices, Y.indptr,
X.shape[1], D)
return D
if sum_over_features:
return distance.cdist(X, Y, 'cityblock')
D = X[:, np.newaxis, :] - Y[np.newaxis, :, :]
D = np.abs(D, D)
return D.reshape((-1, X.shape[1]))
def cosine_distances(X, Y=None):
"""
Compute cosine distance between samples in X and Y.
Cosine distance is defined as 1.0 minus the cosine similarity.
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : array_like, sparse matrix
with shape (n_samples_X, n_features).
Y : array_like, sparse matrix (optional)
with shape (n_samples_Y, n_features).
Returns
-------
distance matrix : array
An array with shape (n_samples_X, n_samples_Y).
See also
--------
sklearn.metrics.pairwise.cosine_similarity
scipy.spatial.distance.cosine (dense matrices only)
"""
# 1.0 - cosine_similarity(X, Y) without copy
S = cosine_similarity(X, Y)
S *= -1
S += 1
return S
# Paired distances
def paired_euclidean_distances(X, Y):
"""
Computes the paired euclidean distances between X and Y
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Y : array-like, shape (n_samples, n_features)
Returns
-------
distances : ndarray (n_samples, )
"""
X, Y = check_paired_arrays(X, Y)
return row_norms(X - Y)
def paired_manhattan_distances(X, Y):
"""Compute the L1 distances between the vectors in X and Y.
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Y : array-like, shape (n_samples, n_features)
Returns
-------
distances : ndarray (n_samples, )
"""
X, Y = check_paired_arrays(X, Y)
diff = X - Y
if issparse(diff):
diff.data = np.abs(diff.data)
return np.squeeze(np.array(diff.sum(axis=1)))
else:
return np.abs(diff).sum(axis=-1)
def paired_cosine_distances(X, Y):
"""
Computes the paired cosine distances between X and Y
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Y : array-like, shape (n_samples, n_features)
Returns
-------
distances : ndarray, shape (n_samples, )
Notes
------
The cosine distance is equivalent to the half the squared
euclidean distance if each sample is normalized to unit norm
"""
X, Y = check_paired_arrays(X, Y)
return .5 * row_norms(normalize(X) - normalize(Y), squared=True)
PAIRED_DISTANCES = {
'cosine': paired_cosine_distances,
'euclidean': paired_euclidean_distances,
'l2': paired_euclidean_distances,
'l1': paired_manhattan_distances,
'manhattan': paired_manhattan_distances,
'cityblock': paired_manhattan_distances}
def paired_distances(X, Y, metric="euclidean", **kwds):
"""
Computes the paired distances between X and Y.
Computes the distances between (X[0], Y[0]), (X[1], Y[1]), etc...
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : ndarray (n_samples, n_features)
Array 1 for distance computation.
Y : ndarray (n_samples, n_features)
Array 2 for distance computation.
metric : string or callable
The metric to use when calculating distance between instances in a
feature array. If metric is a string, it must be one of the options
specified in PAIRED_DISTANCES, including "euclidean",
"manhattan", or "cosine".
Alternatively, if metric is a callable function, it is called on each
pair of instances (rows) and the resulting value recorded. The callable
should take two arrays from X as input and return a value indicating
the distance between them.
Returns
-------
distances : ndarray (n_samples, )
Examples
--------
>>> from sklearn.metrics.pairwise import paired_distances
>>> X = [[0, 1], [1, 1]]
>>> Y = [[0, 1], [2, 1]]
>>> paired_distances(X, Y)
array([ 0., 1.])
See also
--------
pairwise_distances : pairwise distances.
"""
if metric in PAIRED_DISTANCES:
func = PAIRED_DISTANCES[metric]
return func(X, Y)
elif callable(metric):
# Check the matrix first (it is usually done by the metric)
X, Y = check_paired_arrays(X, Y)
distances = np.zeros(len(X))
for i in range(len(X)):
distances[i] = metric(X[i], Y[i])
return distances
else:
raise ValueError('Unknown distance %s' % metric)
# Kernels
def linear_kernel(X, Y=None):
"""
Compute the linear kernel between X and Y.
Read more in the :ref:`User Guide <linear_kernel>`.
Parameters
----------
X : array of shape (n_samples_1, n_features)
Y : array of shape (n_samples_2, n_features)
Returns
-------
Gram matrix : array of shape (n_samples_1, n_samples_2)
"""
X, Y = check_pairwise_arrays(X, Y)
return safe_sparse_dot(X, Y.T, dense_output=True)
def polynomial_kernel(X, Y=None, degree=3, gamma=None, coef0=1):
"""
Compute the polynomial kernel between X and Y::
K(X, Y) = (gamma <X, Y> + coef0)^degree
Read more in the :ref:`User Guide <polynomial_kernel>`.
Parameters
----------
X : ndarray of shape (n_samples_1, n_features)
Y : ndarray of shape (n_samples_2, n_features)
coef0 : int, default 1
degree : int, default 3
Returns
-------
Gram matrix : array of shape (n_samples_1, n_samples_2)
"""
X, Y = check_pairwise_arrays(X, Y)
if gamma is None:
gamma = 1.0 / X.shape[1]
K = safe_sparse_dot(X, Y.T, dense_output=True)
K *= gamma
K += coef0
K **= degree
return K
def sigmoid_kernel(X, Y=None, gamma=None, coef0=1):
"""
Compute the sigmoid kernel between X and Y::
K(X, Y) = tanh(gamma <X, Y> + coef0)
Read more in the :ref:`User Guide <sigmoid_kernel>`.
Parameters
----------
X : ndarray of shape (n_samples_1, n_features)
Y : ndarray of shape (n_samples_2, n_features)
coef0 : int, default 1
Returns
-------
Gram matrix: array of shape (n_samples_1, n_samples_2)
"""
X, Y = check_pairwise_arrays(X, Y)
if gamma is None:
gamma = 1.0 / X.shape[1]
K = safe_sparse_dot(X, Y.T, dense_output=True)
K *= gamma
K += coef0
np.tanh(K, K) # compute tanh in-place
return K
def rbf_kernel(X, Y=None, gamma=None):
"""
Compute the rbf (gaussian) kernel between X and Y::
K(x, y) = exp(-gamma ||x-y||^2)
for each pair of rows x in X and y in Y.
Read more in the :ref:`User Guide <rbf_kernel>`.
Parameters
----------
X : array of shape (n_samples_X, n_features)
Y : array of shape (n_samples_Y, n_features)
gamma : float
Returns
-------
kernel_matrix : array of shape (n_samples_X, n_samples_Y)
"""
X, Y = check_pairwise_arrays(X, Y)
if gamma is None:
gamma = 1.0 / X.shape[1]
K = euclidean_distances(X, Y, squared=True)
K *= -gamma
np.exp(K, K) # exponentiate K in-place
return K
def cosine_similarity(X, Y=None, dense_output=True):
"""Compute cosine similarity between samples in X and Y.
Cosine similarity, or the cosine kernel, computes similarity as the
normalized dot product of X and Y:
K(X, Y) = <X, Y> / (||X||*||Y||)
On L2-normalized data, this function is equivalent to linear_kernel.
Read more in the :ref:`User Guide <cosine_similarity>`.
Parameters
----------
X : ndarray or sparse array, shape: (n_samples_X, n_features)
Input data.
Y : ndarray or sparse array, shape: (n_samples_Y, n_features)
Input data. If ``None``, the output will be the pairwise
similarities between all samples in ``X``.
dense_output : boolean (optional), default True
Whether to return dense output even when the input is sparse. If
``False``, the output is sparse if both input arrays are sparse.
Returns
-------
kernel matrix : array
An array with shape (n_samples_X, n_samples_Y).
"""
# to avoid recursive import
X, Y = check_pairwise_arrays(X, Y)
X_normalized = normalize(X, copy=True)
if X is Y:
Y_normalized = X_normalized
else:
Y_normalized = normalize(Y, copy=True)
K = safe_sparse_dot(X_normalized, Y_normalized.T, dense_output=dense_output)
return K
def additive_chi2_kernel(X, Y=None):
"""Computes the additive chi-squared kernel between observations in X and Y
The chi-squared kernel is computed between each pair of rows in X and Y. X
and Y have to be non-negative. This kernel is most commonly applied to
histograms.
The chi-squared kernel is given by::
k(x, y) = -Sum [(x - y)^2 / (x + y)]
It can be interpreted as a weighted difference per entry.
Read more in the :ref:`User Guide <chi2_kernel>`.
Notes
-----
As the negative of a distance, this kernel is only conditionally positive
definite.
Parameters
----------
X : array-like of shape (n_samples_X, n_features)
Y : array of shape (n_samples_Y, n_features)
Returns
-------
kernel_matrix : array of shape (n_samples_X, n_samples_Y)
References
----------
* Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C.
Local features and kernels for classification of texture and object
categories: A comprehensive study
International Journal of Computer Vision 2007
http://eprints.pascal-network.org/archive/00002309/01/Zhang06-IJCV.pdf
See also
--------
chi2_kernel : The exponentiated version of the kernel, which is usually
preferable.
sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation
to this kernel.
"""
if issparse(X) or issparse(Y):
raise ValueError("additive_chi2 does not support sparse matrices.")
X, Y = check_pairwise_arrays(X, Y)
if (X < 0).any():
raise ValueError("X contains negative values.")
if Y is not X and (Y < 0).any():
raise ValueError("Y contains negative values.")
result = np.zeros((X.shape[0], Y.shape[0]), dtype=X.dtype)
_chi2_kernel_fast(X, Y, result)
return result
def chi2_kernel(X, Y=None, gamma=1.):
"""Computes the exponential chi-squared kernel X and Y.
The chi-squared kernel is computed between each pair of rows in X and Y. X
and Y have to be non-negative. This kernel is most commonly applied to
histograms.
The chi-squared kernel is given by::
k(x, y) = exp(-gamma Sum [(x - y)^2 / (x + y)])
It can be interpreted as a weighted difference per entry.
Read more in the :ref:`User Guide <chi2_kernel>`.
Parameters
----------
X : array-like of shape (n_samples_X, n_features)
Y : array of shape (n_samples_Y, n_features)
gamma : float, default=1.
Scaling parameter of the chi2 kernel.
Returns
-------
kernel_matrix : array of shape (n_samples_X, n_samples_Y)
References
----------
* Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C.
Local features and kernels for classification of texture and object
categories: A comprehensive study
International Journal of Computer Vision 2007
http://eprints.pascal-network.org/archive/00002309/01/Zhang06-IJCV.pdf
See also
--------
additive_chi2_kernel : The additive version of this kernel
sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation
to the additive version of this kernel.
"""
K = additive_chi2_kernel(X, Y)
K *= gamma
return np.exp(K, K)
# Helper functions - distance
PAIRWISE_DISTANCE_FUNCTIONS = {
# If updating this dictionary, update the doc in both distance_metrics()
# and also in pairwise_distances()!
'cityblock': manhattan_distances,
'cosine': cosine_distances,
'euclidean': euclidean_distances,
'l2': euclidean_distances,
'l1': manhattan_distances,
'manhattan': manhattan_distances,
'precomputed': None, # HACK: precomputed is always allowed, never called
}
def distance_metrics():
"""Valid metrics for pairwise_distances.
This function simply returns the valid pairwise distance metrics.
It exists to allow for a description of the mapping for
each of the valid strings.
The valid distance metrics, and the function they map to, are:
============ ====================================
metric Function
============ ====================================
'cityblock' metrics.pairwise.manhattan_distances
'cosine' metrics.pairwise.cosine_distances
'euclidean' metrics.pairwise.euclidean_distances
'l1' metrics.pairwise.manhattan_distances
'l2' metrics.pairwise.euclidean_distances
'manhattan' metrics.pairwise.manhattan_distances
============ ====================================
Read more in the :ref:`User Guide <metrics>`.
"""
return PAIRWISE_DISTANCE_FUNCTIONS
def _parallel_pairwise(X, Y, func, n_jobs, **kwds):
"""Break the pairwise matrix in n_jobs even slices
and compute them in parallel"""
if n_jobs < 0:
n_jobs = max(cpu_count() + 1 + n_jobs, 1)
if Y is None:
Y = X
if n_jobs == 1:
# Special case to avoid picklability checks in delayed
return func(X, Y, **kwds)
# TODO: in some cases, backend='threading' may be appropriate
fd = delayed(func)
ret = Parallel(n_jobs=n_jobs, verbose=0)(
fd(X, Y[s], **kwds)
for s in gen_even_slices(Y.shape[0], n_jobs))
return np.hstack(ret)
def _pairwise_callable(X, Y, metric, **kwds):
"""Handle the callable case for pairwise_{distances,kernels}
"""
X, Y = check_pairwise_arrays(X, Y)
if X is Y:
# Only calculate metric for upper triangle
out = np.zeros((X.shape[0], Y.shape[0]), dtype='float')
iterator = itertools.combinations(range(X.shape[0]), 2)
for i, j in iterator:
out[i, j] = metric(X[i], Y[j], **kwds)
# Make symmetric
# NB: out += out.T will produce incorrect results
out = out + out.T
# Calculate diagonal
# NB: nonzero diagonals are allowed for both metrics and kernels
for i in range(X.shape[0]):
x = X[i]
out[i, i] = metric(x, x, **kwds)
else:
# Calculate all cells
out = np.empty((X.shape[0], Y.shape[0]), dtype='float')
iterator = itertools.product(range(X.shape[0]), range(Y.shape[0]))
for i, j in iterator:
out[i, j] = metric(X[i], Y[j], **kwds)
return out
_VALID_METRICS = ['euclidean', 'l2', 'l1', 'manhattan', 'cityblock',
'braycurtis', 'canberra', 'chebyshev', 'correlation',
'cosine', 'dice', 'hamming', 'jaccard', 'kulsinski',
'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto',
'russellrao', 'seuclidean', 'sokalmichener',
'sokalsneath', 'sqeuclidean', 'yule', "wminkowski"]
def pairwise_distances(X, Y=None, metric="euclidean", n_jobs=1, **kwds):
""" Compute the distance matrix from a vector array X and optional Y.
This method takes either a vector array or a distance matrix, and returns
a distance matrix. If the input is a vector array, the distances are
computed. If the input is a distances matrix, it is returned instead.
This method provides a safe way to take a distance matrix as input, while
preserving compatibility with many other algorithms that take a vector
array.
If Y is given (default is None), then the returned matrix is the pairwise
distance between the arrays from both X and Y.
Valid values for metric are:
- From scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
'manhattan']. These metrics support sparse matrix inputs.
- From scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev',
'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis',
'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean',
'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule']
See the documentation for scipy.spatial.distance for details on these
metrics. These metrics do not support sparse matrix inputs.
Note that in the case of 'cityblock', 'cosine' and 'euclidean' (which are
valid scipy.spatial.distance metrics), the scikit-learn implementation
will be used, which is faster and has support for sparse matrices (except
for 'cityblock'). For a verbose description of the metrics from
scikit-learn, see the __doc__ of the sklearn.pairwise.distance_metrics
function.
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : array [n_samples_a, n_samples_a] if metric == "precomputed", or, \
[n_samples_a, n_features] otherwise
Array of pairwise distances between samples, or a feature array.
Y : array [n_samples_b, n_features], optional
An optional second feature array. Only allowed if metric != "precomputed".
metric : string, or callable
The metric to use when calculating distance between instances in a
feature array. If metric is a string, it must be one of the options
allowed by scipy.spatial.distance.pdist for its metric parameter, or
a metric listed in pairwise.PAIRWISE_DISTANCE_FUNCTIONS.
If metric is "precomputed", X is assumed to be a distance matrix.
Alternatively, if metric is a callable function, it is called on each
pair of instances (rows) and the resulting value recorded. The callable
should take two arrays from X as input and return a value indicating
the distance between them.
n_jobs : int
The number of jobs to use for the computation. This works by breaking
down the pairwise matrix into n_jobs even slices and computing them in
parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
`**kwds` : optional keyword parameters
Any further parameters are passed directly to the distance function.
If using a scipy.spatial.distance metric, the parameters are still
metric dependent. See the scipy docs for usage examples.
Returns
-------
D : array [n_samples_a, n_samples_a] or [n_samples_a, n_samples_b]
A distance matrix D such that D_{i, j} is the distance between the
ith and jth vectors of the given matrix X, if Y is None.
If Y is not None, then D_{i, j} is the distance between the ith array
from X and the jth array from Y.
"""
if (metric not in _VALID_METRICS and
not callable(metric) and metric != "precomputed"):
raise ValueError("Unknown metric %s. "
"Valid metrics are %s, or 'precomputed', or a "
"callable" % (metric, _VALID_METRICS))
if metric == "precomputed":
X, _ = check_pairwise_arrays(X, Y, precomputed=True)
return X
elif metric in PAIRWISE_DISTANCE_FUNCTIONS:
func = PAIRWISE_DISTANCE_FUNCTIONS[metric]
elif callable(metric):
func = partial(_pairwise_callable, metric=metric, **kwds)
else:
if issparse(X) or issparse(Y):
raise TypeError("scipy distance metrics do not"
" support sparse matrices.")
X, Y = check_pairwise_arrays(X, Y)
if n_jobs == 1 and X is Y:
return distance.squareform(distance.pdist(X, metric=metric,
**kwds))
func = partial(distance.cdist, metric=metric, **kwds)
return _parallel_pairwise(X, Y, func, n_jobs, **kwds)
# Helper functions - distance
PAIRWISE_KERNEL_FUNCTIONS = {
# If updating this dictionary, update the doc in both distance_metrics()
# and also in pairwise_distances()!
'additive_chi2': additive_chi2_kernel,
'chi2': chi2_kernel,
'linear': linear_kernel,
'polynomial': polynomial_kernel,
'poly': polynomial_kernel,
'rbf': rbf_kernel,
'sigmoid': sigmoid_kernel,
'cosine': cosine_similarity, }
def kernel_metrics():
""" Valid metrics for pairwise_kernels
This function simply returns the valid pairwise distance metrics.
It exists, however, to allow for a verbose description of the mapping for
each of the valid strings.
The valid distance metrics, and the function they map to, are:
=============== ========================================
metric Function
=============== ========================================
'additive_chi2' sklearn.pairwise.additive_chi2_kernel
'chi2' sklearn.pairwise.chi2_kernel
'linear' sklearn.pairwise.linear_kernel
'poly' sklearn.pairwise.polynomial_kernel
'polynomial' sklearn.pairwise.polynomial_kernel
'rbf' sklearn.pairwise.rbf_kernel
'sigmoid' sklearn.pairwise.sigmoid_kernel
'cosine' sklearn.pairwise.cosine_similarity
=============== ========================================
Read more in the :ref:`User Guide <metrics>`.
"""
return PAIRWISE_KERNEL_FUNCTIONS
KERNEL_PARAMS = {
"additive_chi2": (),
"chi2": (),
"cosine": (),
"exp_chi2": frozenset(["gamma"]),
"linear": (),
"poly": frozenset(["gamma", "degree", "coef0"]),
"polynomial": frozenset(["gamma", "degree", "coef0"]),
"rbf": frozenset(["gamma"]),
"sigmoid": frozenset(["gamma", "coef0"]),
}
def pairwise_kernels(X, Y=None, metric="linear", filter_params=False,
n_jobs=1, **kwds):
"""Compute the kernel between arrays X and optional array Y.
This method takes either a vector array or a kernel matrix, and returns
a kernel matrix. If the input is a vector array, the kernels are
computed. If the input is a kernel matrix, it is returned instead.
This method provides a safe way to take a kernel matrix as input, while
preserving compatibility with many other algorithms that take a vector
array.
If Y is given (default is None), then the returned matrix is the pairwise
kernel between the arrays from both X and Y.
Valid values for metric are::
['rbf', 'sigmoid', 'polynomial', 'poly', 'linear', 'cosine']
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : array [n_samples_a, n_samples_a] if metric == "precomputed", or, \
[n_samples_a, n_features] otherwise
Array of pairwise kernels between samples, or a feature array.
Y : array [n_samples_b, n_features]
A second feature array only if X has shape [n_samples_a, n_features].
metric : string, or callable
The metric to use when calculating kernel between instances in a
feature array. If metric is a string, it must be one of the metrics
in pairwise.PAIRWISE_KERNEL_FUNCTIONS.
If metric is "precomputed", X is assumed to be a kernel matrix.
Alternatively, if metric is a callable function, it is called on each
pair of instances (rows) and the resulting value recorded. The callable
should take two arrays from X as input and return a value indicating
the distance between them.
n_jobs : int
The number of jobs to use for the computation. This works by breaking
down the pairwise matrix into n_jobs even slices and computing them in
parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
filter_params: boolean
Whether to filter invalid parameters or not.
`**kwds` : optional keyword parameters
Any further parameters are passed directly to the kernel function.
Returns
-------
K : array [n_samples_a, n_samples_a] or [n_samples_a, n_samples_b]
A kernel matrix K such that K_{i, j} is the kernel between the
ith and jth vectors of the given matrix X, if Y is None.
If Y is not None, then K_{i, j} is the kernel between the ith array
from X and the jth array from Y.
Notes
-----
If metric is 'precomputed', Y is ignored and X is returned.
"""
if metric == "precomputed":
X, _ = check_pairwise_arrays(X, Y, precomputed=True)
return X
elif metric in PAIRWISE_KERNEL_FUNCTIONS:
if filter_params:
kwds = dict((k, kwds[k]) for k in kwds
if k in KERNEL_PARAMS[metric])
func = PAIRWISE_KERNEL_FUNCTIONS[metric]
elif callable(metric):
func = partial(_pairwise_callable, metric=metric, **kwds)
else:
raise ValueError("Unknown kernel %r" % metric)
return _parallel_pairwise(X, Y, func, n_jobs, **kwds)
| mfjb/scikit-learn | sklearn/metrics/pairwise.py | Python | bsd-3-clause | 44,015 |
// 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 System;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Xunit;
namespace XDocumentTests.SDMSample
{
public class SDM_Element
{
/// <summary>
/// Validate behavior of XElement simple creation.
/// </summary>
[Fact]
public void CreateElementSimple()
{
const string ElementName = "Element";
XElement element;
// Test the constructor that takes only a name.
element = new XElement(ElementName);
Assert.Equal(ElementName, element.Name.ToString());
Assert.Throws<ArgumentNullException>(() => new XElement((XName)null));
}
/// <summary>
/// Validate behavior of XElement creation with content supplied.
/// </summary>
[Fact]
public void CreateElementWithContent()
{
// Test the constructor that takes a name and some content.
XElement level2Element = new XElement("Level2", "TextValue");
XAttribute attribute = new XAttribute("Attribute", "AttributeValue");
XCData cdata = new XCData("abcdefgh");
string someValue = "text";
XElement element = new XElement("Level1", level2Element, cdata, someValue, attribute);
Assert.Equal("Level1", element.Name.ToString());
Assert.Equal(
new XNode[] { level2Element, cdata, new XText(someValue) },
element.Nodes(),
XNode.EqualityComparer);
Assert.Equal(new[] { attribute.Name }, element.Attributes().Select(x => x.Name));
Assert.Equal(new[] { attribute.Value }, element.Attributes().Select(x => x.Value));
}
/// <summary>
/// Validate behavior of XElement creation with copy constructor.
/// </summary>
[Fact]
public void CreateElementCopy()
{
// With attributes
XElement level2Element = new XElement("Level2", "TextValue");
XAttribute attribute = new XAttribute("Attribute", "AttributeValue");
XCData cdata = new XCData("abcdefgh");
string someValue = "text";
XElement element = new XElement("Level1", level2Element, cdata, someValue, attribute);
XElement elementCopy = new XElement(element);
Assert.Equal("Level1", element.Name.ToString());
Assert.Equal(
new XNode[] { level2Element, cdata, new XText(someValue) },
elementCopy.Nodes(),
XNode.EqualityComparer);
Assert.Equal(new[] { attribute.Name }, element.Attributes().Select(x => x.Name));
Assert.Equal(new[] { attribute.Value }, element.Attributes().Select(x => x.Value));
// Without attributes
element = new XElement("Level1", level2Element, cdata, someValue);
elementCopy = new XElement(element);
Assert.Equal("Level1", element.Name.ToString());
Assert.Equal(
new XNode[] { level2Element, cdata, new XText(someValue) },
elementCopy.Nodes(),
XNode.EqualityComparer);
Assert.Empty(elementCopy.Attributes());
// Hsh codes of equal elements should be equal.
Assert.Equal(XNode.EqualityComparer.GetHashCode(element), XNode.EqualityComparer.GetHashCode(elementCopy));
// Null element is not allowed.
Assert.Throws<ArgumentNullException>(() => new XElement((XElement)null));
}
/// <summary>
/// Validate behavior of XElement creation from an XmlReader.
/// </summary>
[Fact]
public void CreateElementFromReader()
{
string xml = "<Level1 a1='1' a2='2'><Level2><![CDATA[12345678]]>text</Level2></Level1>";
string xml2 = "<Level1 />";
string xml3 = "<x><?xml version='1.0' encoding='utf-8'?></x>";
// With attributes
using (TextReader textReader = new StringReader(xml))
using (XmlReader xmlReader = XmlReader.Create(textReader))
{
xmlReader.Read();
XElement element = (XElement)XNode.ReadFrom(xmlReader);
Assert.Equal("Level1", element.Name.ToString());
Assert.Equal(new[] { "Level2" }, element.Elements().Select(x => x.Name.ToString()));
Assert.Equal(new[] { "a1", "a2" }, element.Attributes().Select(x => x.Name.ToString()));
Assert.Equal(new[] { "1", "2" }, element.Attributes().Select(x => x.Value));
Assert.Equal("12345678text", element.Element("Level2").Value);
}
// Without attributes
using (TextReader textReader = new StringReader(xml2))
using (XmlReader xmlReader = XmlReader.Create(textReader))
{
xmlReader.Read();
var element = (XElement)XNode.ReadFrom(xmlReader);
Assert.Equal("Level1", element.Name.ToString());
Assert.Empty(element.Elements());
Assert.Empty(element.Attributes());
Assert.Empty(element.Value);
}
// XmlReader in start state results in exception
using (TextReader textReader = new StringReader(xml))
using (XmlReader xmlReader = XmlReader.Create(textReader))
{
Assert.Throws<InvalidOperationException>(() => (XElement)XNode.ReadFrom(xmlReader));
}
// XmlReader not on an element results in exception.
using (TextReader textReader = new StringReader(xml))
using (XmlReader xmlReader = XmlReader.Create(textReader))
{
xmlReader.Read();
xmlReader.MoveToAttribute("a1");
Assert.Throws<InvalidOperationException>(() => (XElement)XNode.ReadFrom(xmlReader));
}
// Illegal xml triggers exception that is bubbled out.
using (TextReader textReader = new StringReader(xml3))
using (XmlReader xmlReader = XmlReader.Create(textReader))
{
xmlReader.Read();
Assert.Throws<XmlException>(() => (XElement)XNode.ReadFrom(xmlReader));
}
}
/// <summary>
/// Validate behavior of XElement EmptySequence method.
/// </summary>
[Fact]
public void ElementEmptyElementSequence()
{
Assert.Empty(XElement.EmptySequence);
Assert.Empty(XElement.EmptySequence);
}
/// <summary>
/// Validate behavior of XElement HasAttributes/HasElements properties.
/// </summary>
[Fact]
public void ElementHasAttributesAndElements()
{
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", new XAttribute("a", "value"));
XElement e3 = new XElement("x", new XElement("y"));
XElement e4 = new XElement("x", new XCData("cdata-value"));
Assert.False(e1.HasAttributes);
Assert.True(e2.HasAttributes);
Assert.False(e1.HasElements);
Assert.False(e2.HasElements);
Assert.True(e3.HasElements);
Assert.False(e4.HasElements);
}
/// <summary>
/// Validate behavior of the IsEmpty property.
/// </summary>
[Fact]
public void ElementIsEmpty()
{
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", 10);
XElement e3 = new XElement("x", string.Empty);
Assert.True(e1.IsEmpty);
Assert.False(e2.IsEmpty);
Assert.False(e3.IsEmpty);
}
/// <summary>
/// Validate behavior of the Value property on XElement.
/// </summary>
[Fact]
public void ElementValue()
{
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "value");
XElement e3 = new XElement("x", 100, 200);
XElement e4 = new XElement("x", 100, "value", 200);
XElement e5 = new XElement("x", string.Empty);
XElement e6 = new XElement("x", 1, string.Empty, 5);
XElement e7 = new XElement("x", new XElement("y", "inner1", new XElement("z", "foo"), "inner2"));
XElement e8 = new XElement("x", "text1", new XElement("y", "inner"), "text2");
XElement e9 = new XElement("x", "text1", new XText("abcd"), new XElement("y", "y"));
XElement e10 = new XElement("x", new XComment("my comment"));
Assert.Empty(e1.Value);
Assert.Equal("value", e2.Value);
Assert.Equal("100200", e3.Value);
Assert.Equal("100value200", e4.Value);
Assert.Empty(e5.Value);
Assert.Equal("15", e6.Value);
Assert.Equal("inner1fooinner2", e7.Value);
Assert.Equal("text1innertext2", e8.Value);
Assert.Equal("text1abcdy", e9.Value);
Assert.Empty(e10.Value);
Assert.Throws<ArgumentNullException>(() => e1.Value = null);
e1.Value = string.Empty;
e2.Value = "not-empty";
Assert.Empty(e1.Value);
Assert.Equal("not-empty", e2.Value);
}
/// <summary>
/// Validates the explicit string conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToString()
{
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", string.Empty);
XElement e3 = new XElement("x", "value");
Assert.Null((string)((XElement)null));
Assert.Empty((string)e1);
Assert.Empty((string)e2);
Assert.Equal("value", (string)e3);
}
/// <summary>
/// Validates the explicit boolean conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToBoolean()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (bool)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "true");
XElement e4 = new XElement("x", "false");
XElement e5 = new XElement("x", "0");
XElement e6 = new XElement("x", "1");
Assert.Throws<FormatException>(() => (bool)e1);
Assert.Throws<FormatException>(() => (bool)e2);
Assert.True((bool)e3);
Assert.False((bool)e4);
Assert.False((bool)e5);
Assert.True((bool)e6);
}
/// <summary>
/// Validates the explicit int32 conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToInt32()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (int)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "2147483648");
XElement e4 = new XElement("x", "5");
Assert.Throws<FormatException>(() => (int)e1);
Assert.Throws<FormatException>(() => (int)e2);
Assert.Throws<OverflowException>(() => (int)e3);
Assert.Equal(5, (int)e4);
}
/// <summary>
/// Validates the explicit uint32 conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToUInt32()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (uint)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "4294967296");
XElement e4 = new XElement("x", "5");
Assert.Throws<FormatException>(() => (uint)e1);
Assert.Throws<FormatException>(() => (uint)e2);
Assert.Throws<OverflowException>(() => (uint)e3);
Assert.Equal(5u, (uint)e4);
}
/// <summary>
/// Validates the explicit int64 conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToInt64()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (long)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "18446744073709551616");
XElement e4 = new XElement("x", "5");
Assert.Throws<FormatException>(() => (long)e1);
Assert.Throws<FormatException>(() => (long)e2);
Assert.Throws<OverflowException>(() => (long)e3);
Assert.Equal(5L, (long)e4);
}
/// <summary>
/// Validates the explicit uint64 conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToUInt64()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (ulong)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "18446744073709551616");
XElement e4 = new XElement("x", "5");
Assert.Throws<FormatException>(() => (ulong)e1);
Assert.Throws<FormatException>(() => (ulong)e2);
Assert.Throws<OverflowException>(() => (ulong)e3);
Assert.Equal(5UL, (ulong)e4);
}
/// <summary>
/// Validates the explicit float conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToFloat()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (float)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "5e+500");
XElement e4 = new XElement("x", "5.0");
Assert.Throws<FormatException>(() => (float)e1);
Assert.Throws<FormatException>(() => (float)e2);
Assert.Throws<OverflowException>(() => (float)e3);
Assert.Equal(5.0f, (float)e4);
}
/// <summary>
/// Validates the explicit double conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToDouble()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (double)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "5e+5000");
XElement e4 = new XElement("x", "5.0");
Assert.Throws<FormatException>(() => (double)e1);
Assert.Throws<FormatException>(() => (double)e2);
Assert.Throws<OverflowException>(() => (double)e3);
Assert.Equal(5.0, (double)e4);
}
/// <summary>
/// Validates the explicit decimal conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToDecimal()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (decimal)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "111111111111111111111111111111111111111111111111");
XElement e4 = new XElement("x", "5.0");
Assert.Throws<FormatException>(() => (decimal)e1);
Assert.Throws<FormatException>(() => (decimal)e2);
Assert.Throws<OverflowException>(() => (decimal)e3);
Assert.Equal(5.0m, (decimal)e4);
}
/// <summary>
/// Validates the explicit DateTime conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToDateTime()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (DateTime)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "1968-01-07");
Assert.Throws<FormatException>(() => (DateTime)e1);
Assert.Throws<FormatException>(() => (DateTime)e2);
Assert.Equal(new DateTime(1968, 1, 7), (DateTime)e3);
}
/// <summary>
/// Validates the explicit TimeSpan conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToTimeSpan()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (TimeSpan)((XElement)null));
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", "PT1H2M3S");
Assert.Throws<FormatException>(() => (TimeSpan)e1);
Assert.Throws<FormatException>(() => (TimeSpan)e2);
Assert.Equal(new TimeSpan(1, 2, 3), (TimeSpan)e3);
}
/// <summary>
/// Validates the explicit guid conversion operator on XElement.
/// </summary>
[Fact]
public void ElementExplicitToGuid()
{
// Calling explicit operator with null should result in exception.
Assert.Throws<ArgumentNullException>(() => (Guid)((XElement)null));
string guid = "2b67e9fb-97ad-4258-8590-8bc8c2d32df5";
// Test various values.
XElement e1 = new XElement("x");
XElement e2 = new XElement("x", "bogus");
XElement e3 = new XElement("x", guid);
Assert.Throws<FormatException>(() => (Guid)e1);
Assert.Throws<FormatException>(() => (Guid)e2);
Assert.Equal(new Guid(guid), (Guid)e3);
}
/// <summary>
/// Validates the explicit conversion operators on XElement
/// for nullable value types.
/// </summary>
[Fact]
public void ElementExplicitToNullables()
{
string guid = "cd8d69ed-fef9-4283-aaf4-216463e4496f";
bool? b = (bool?)new XElement("x", true);
int? i = (int?)new XElement("x", 5);
uint? u = (uint?)new XElement("x", 5);
long? l = (long?)new XElement("x", 5);
ulong? ul = (ulong?)new XElement("x", 5);
float? f = (float?)new XElement("x", 5);
double? n = (double?)new XElement("x", 5);
decimal? d = (decimal?)new XElement("x", 5);
DateTime? dt = (DateTime?)new XElement("x", "1968-01-07");
TimeSpan? ts = (TimeSpan?)new XElement("x", "PT1H2M3S");
Guid? g = (Guid?)new XElement("x", guid);
Assert.True(b.Value);
Assert.Equal(5, i.Value);
Assert.Equal(5u, u.Value);
Assert.Equal(5L, l.Value);
Assert.Equal(5uL, ul.Value);
Assert.Equal(5.0f, f.Value);
Assert.Equal(5.0, n.Value);
Assert.Equal(5.0m, d.Value);
Assert.Equal(new DateTime(1968, 1, 7), dt.Value);
Assert.Equal(new TimeSpan(1, 2, 3), ts.Value);
Assert.Equal(new Guid(guid), g.Value);
b = (bool?)((XElement)null);
i = (int?)((XElement)null);
u = (uint?)((XElement)null);
l = (long?)((XElement)null);
ul = (ulong?)((XElement)null);
f = (float?)((XElement)null);
n = (double?)((XElement)null);
d = (decimal?)((XElement)null);
dt = (DateTime?)((XElement)null);
ts = (TimeSpan?)((XElement)null);
g = (Guid?)((XElement)null);
Assert.Null(b);
Assert.Null(i);
Assert.Null(u);
Assert.Null(l);
Assert.Null(ul);
Assert.Null(f);
Assert.Null(n);
Assert.Null(d);
Assert.Null(dt);
Assert.Null(ts);
Assert.Null(g);
}
/// <summary>
/// Validate enumeration of element ancestors.
/// </summary>
[Fact]
public void ElementAncestors()
{
XElement level3 = new XElement("Level3");
XElement level2 = new XElement("Level2", level3);
XElement level1 = new XElement("Level1", level2);
XElement level0 = new XElement("Level1", level1);
Assert.Equal(new XElement[] { level2, level1, level0 }, level3.Ancestors(), XNode.EqualityComparer);
Assert.Equal(new XElement[] { level1, level0 }, level3.Ancestors("Level1"), XNode.EqualityComparer);
Assert.Empty(level3.Ancestors(null));
Assert.Equal(
new XElement[] { level3, level2, level1, level0 },
level3.AncestorsAndSelf(),
XNode.EqualityComparer);
Assert.Equal(new XElement[] { level3 }, level3.AncestorsAndSelf("Level3"), XNode.EqualityComparer);
Assert.Empty(level3.AncestorsAndSelf(null));
}
/// <summary>
/// Validate enumeration of element descendents.
/// </summary>
[Fact]
public void ElementDescendents()
{
XComment comment = new XComment("comment");
XElement level3 = new XElement("Level3");
XElement level2 = new XElement("Level2", level3);
XElement level1 = new XElement("Level1", level2, comment);
XElement level0 = new XElement("Level1", level1);
Assert.Equal(new XElement[] { level1, level2, level3 }, level1.DescendantsAndSelf(), XNode.EqualityComparer);
Assert.Equal(
new XNode[] { level0, level1, level2, level3, comment },
level0.DescendantNodesAndSelf(),
XNode.EqualityComparer);
Assert.Empty(level0.DescendantsAndSelf(null));
Assert.Equal(new XElement[] { level0, level1 }, level0.DescendantsAndSelf("Level1"), XNode.EqualityComparer);
}
/// <summary>
/// Validate enumeration of element attributes.
/// </summary>
[Fact]
public void ElementAttributes()
{
XElement e1 = new XElement("x");
XElement e2 = new XElement(
"x",
new XAttribute("a1", "1"),
new XAttribute("a2", "2"),
new XAttribute("a3", "3"),
new XAttribute("a4", "4"),
new XAttribute("a5", "5"));
XElement e3 = new XElement(
"x",
new XAttribute("a1", "1"),
new XAttribute("a2", "2"),
new XAttribute("a3", "3"));
Assert.Null(e1.Attribute("foo"));
Assert.Null(e2.Attribute("foo"));
Assert.Equal(e2.Attribute("a3").Name.ToString(), "a3");
Assert.Equal(e2.Attribute("a3").Value, "3");
Assert.Equal(new[] { "a1", "a2", "a3", "a4", "a5" }, e2.Attributes().Select(x => x.Name.ToString()));
Assert.Equal(new[] { "1", "2", "3", "4", "5" }, e2.Attributes().Select(x => x.Value));
Assert.Equal(new[] { "a1" }, e2.Attributes("a1").Select(x => x.Name.ToString()));
Assert.Equal(new[] { "5" }, e2.Attributes("a5").Select(x => x.Value));
Assert.Empty(e2.Attributes(null));
e2.RemoveAttributes();
Assert.Empty(e2.Attributes());
// Removal of non-existent attribute
e1.SetAttributeValue("foo", null);
Assert.Empty(e1.Attributes());
// Add of non-existent attribute
e1.SetAttributeValue("foo", "foo-value");
Assert.Equal(e1.Attribute("foo").Name.ToString(), "foo");
Assert.Equal(e1.Attribute("foo").Value, "foo-value");
// Overwriting of existing attribute
e1.SetAttributeValue("foo", "noo-value");
Assert.Equal(e1.Attribute("foo").Name.ToString(), "foo");
Assert.Equal(e1.Attribute("foo").Value, "noo-value");
// Effective removal of existing attribute
e1.SetAttributeValue("foo", null);
Assert.Empty(e1.Attributes());
// These 3 are in a specific order to exercise the attribute removal code.
e3.SetAttributeValue("a2", null);
Assert.Equal(2, e3.Attributes().Count());
e3.SetAttributeValue("a3", null);
Assert.Equal(1, e3.Attributes().Count());
e3.SetAttributeValue("a1", null);
Assert.Empty(e3.Attributes());
}
/// <summary>
/// Validates remove methods on elements.
/// </summary>
[Fact]
public void ElementRemove()
{
XElement e = new XElement(
"x",
new XAttribute("a1", 1),
new XAttribute("a2", 2),
new XText("abcd"),
10,
new XElement("y", new XComment("comment")),
new XElement("z"));
Assert.Equal(5, e.DescendantNodesAndSelf().Count());
Assert.Equal(2, e.Attributes().Count());
e.RemoveAll();
Assert.Equal(1, e.DescendantNodesAndSelf().Count());
Assert.Empty(e.Attributes());
// Removing all from an already empty one.
e.RemoveAll();
Assert.Equal(1, e.DescendantNodesAndSelf().Count());
Assert.Empty(e.Attributes());
}
/// <summary>
/// Validate enumeration of the SetElementValue method on element/
/// </summary>
[Fact]
public void ElementSetElementValue()
{
XElement e1 = new XElement("x");
// Removal of non-existent element
e1.SetElementValue("foo", null);
Assert.Empty(e1.Elements());
// Add of non-existent element
e1.SetElementValue("foo", "foo-value");
Assert.Equal(new XElement[] { new XElement("foo", "foo-value") }, e1.Elements(), XNode.EqualityComparer);
// Overwriting of existing element
e1.SetElementValue("foo", "noo-value");
Assert.Equal(new XElement[] { new XElement("foo", "noo-value") }, e1.Elements(), XNode.EqualityComparer);
// Effective removal of existing element
e1.SetElementValue("foo", null);
Assert.Empty(e1.Elements());
}
/// <summary>
/// Tests XElement.GetDefaultNamespace().
/// </summary>
[Fact]
public void ElementGetDefaultNamespace()
{
XNamespace ns = XNamespace.Get("http://test");
XElement e = new XElement(ns + "foo");
XNamespace n = e.GetDefaultNamespace();
Assert.NotNull(n);
Assert.Equal(XNamespace.None, n);
e.SetAttributeValue("xmlns", ns);
n = e.GetDefaultNamespace();
Assert.NotNull(n);
Assert.Equal(ns, n);
}
/// <summary>
/// Tests XElement.GetNamespaceOfPrefix().
/// </summary>
[Fact]
public void ElementGetNamespaceOfPrefix()
{
XNamespace ns = XNamespace.Get("http://test");
XElement e = new XElement(ns + "foo");
Assert.Throws<ArgumentNullException>(() => e.GetNamespaceOfPrefix(null));
Assert.Throws<ArgumentException>(() => e.GetNamespaceOfPrefix(string.Empty));
XNamespace n = e.GetNamespaceOfPrefix("xmlns");
Assert.Equal("http://www.w3.org/2000/xmlns/", n.NamespaceName);
n = e.GetNamespaceOfPrefix("xml");
Assert.Equal("http://www.w3.org/XML/1998/namespace", n.NamespaceName);
n = e.GetNamespaceOfPrefix("myns");
Assert.Null(n);
XDocument doc = new XDocument(e);
e.SetAttributeValue("{http://www.w3.org/2000/xmlns/}myns", ns);
n = e.GetNamespaceOfPrefix("myns");
Assert.NotNull(n);
Assert.Equal(ns, n);
}
/// <summary>
/// Tests XElement.GetPrefixOfNamespace().
/// </summary>
[Fact]
public void ElementGetPrefixOfNamespace()
{
Assert.Throws<ArgumentNullException>(() => new XElement("foo").GetPrefixOfNamespace(null));
XNamespace ns = XNamespace.Get("http://test");
XElement e = new XElement(ns + "foo");
string prefix = e.GetPrefixOfNamespace(ns);
Assert.Null(prefix);
prefix = e.GetPrefixOfNamespace(XNamespace.Xmlns);
Assert.Equal("xmlns", prefix);
prefix = e.GetPrefixOfNamespace(XNamespace.Xml);
Assert.Equal("xml", prefix);
XElement parent = new XElement("parent", e);
parent.SetAttributeValue("{http://www.w3.org/2000/xmlns/}myns", ns);
prefix = e.GetPrefixOfNamespace(ns);
Assert.Equal("myns", prefix);
e = XElement.Parse("<foo:element xmlns:foo='http://xxx'></foo:element>");
prefix = e.GetPrefixOfNamespace("http://xxx");
Assert.Equal("foo", prefix);
e =
XElement.Parse(
"<foo:element xmlns:foo='http://foo' xmlns:bar='http://bar'><bar:element /></foo:element>");
prefix = e.GetPrefixOfNamespace("http://foo");
Assert.Equal("foo", prefix);
prefix = e.Element(XName.Get("{http://bar}element")).GetPrefixOfNamespace("http://foo");
Assert.Equal("foo", prefix);
prefix = e.Element(XName.Get("{http://bar}element")).GetPrefixOfNamespace("http://bar");
Assert.Equal("bar", prefix);
}
/// <summary>
/// Tests cases where we're exporting unqualified elements that have xmlns attributes.
/// In this specific scenario we expect XmlExceptions because the element itself
/// is written to an XmlWriter with the empty namespace, and then when the attribute
/// is written to the XmlWriter an exception occurs because the xmlns attribute
/// would cause a retroactive change to the namespace of the already-written element.
/// That is not allowed -- the element must be qualified.
/// </summary>
[Fact]
public void ElementWithXmlnsAttribute()
{
// And with just xmlns local name
XElement element = new XElement("MyElement", new XAttribute("xmlns", "http://tempuri/test"));
Assert.Throws<XmlException>(() => element.ToString());
// A qualified element name works.
element = new XElement("{http://tempuri/test}MyElement", new XAttribute("xmlns", "http://tempuri/test"));
Assert.Equal("<MyElement xmlns=\"http://tempuri/test\" />", element.ToString());
}
/// <summary>
/// Tests the Equals methods on XElement.
/// </summary>
[Fact]
public void ElementEquality()
{
XElement e1 = XElement.Parse("<x/>");
XElement e2 = XElement.Parse("<x/>");
XElement e3 = XElement.Parse("<x a='a'/>");
XElement e4 = XElement.Parse("<x>x</x>");
XElement e5 = XElement.Parse("<y/>");
// Internal method.
Assert.True(XNode.DeepEquals(e1, e1));
Assert.True(XNode.DeepEquals(e1, e2));
Assert.False(XNode.DeepEquals(e1, e3));
Assert.False(XNode.DeepEquals(e1, e4));
Assert.False(XNode.DeepEquals(e1, e5));
// object.Equals override
Assert.True(e1.Equals(e1));
Assert.False(e1.Equals(e2));
Assert.False(e1.Equals(e3));
Assert.False(e1.Equals(e4));
Assert.False(e1.Equals(e5));
Assert.False(e1.Equals(null));
Assert.False(e1.Equals("foo"));
// Hash codes. The most we can say is that identical elements
// should have the same hash codes.
XElement e1a = XElement.Parse("<x/>");
XElement e1b = XElement.Parse("<x/>");
XElement e2a = XElement.Parse("<x>abc</x>");
XElement e2b = XElement.Parse("<x>abc</x>");
XElement e3a = XElement.Parse("<x><y/></x>");
XElement e3b = XElement.Parse("<x><y/></x>");
XElement e4a = XElement.Parse("<x><y/><!--comment--></x>");
XElement e4b = XElement.Parse("<x><!--comment--><y/></x>");
XElement e5a = XElement.Parse("<x a='a'/>");
XElement e5b = XElement.Parse("<x a='a'/>");
int hash = XNode.EqualityComparer.GetHashCode(e1a);
Assert.Equal(XNode.EqualityComparer.GetHashCode(e1b), hash);
hash = XNode.EqualityComparer.GetHashCode(e2a);
Assert.Equal(XNode.EqualityComparer.GetHashCode(e2b), hash);
hash = XNode.EqualityComparer.GetHashCode(e3a);
Assert.Equal(XNode.EqualityComparer.GetHashCode(e3b), hash);
hash = XNode.EqualityComparer.GetHashCode(e4a);
Assert.Equal(XNode.EqualityComparer.GetHashCode(e4b), hash);
hash = XNode.EqualityComparer.GetHashCode(e5a);
Assert.Equal(XNode.EqualityComparer.GetHashCode(e5b), hash);
// Attribute comparison
e1 = XElement.Parse("<x a='a' />");
e2 = XElement.Parse("<x b='b' />");
e3 = XElement.Parse("<x a='a' b='b' />");
e4 = XElement.Parse("<x b='b' a='a' />");
e5 = XElement.Parse("<x a='b' />");
Assert.False(XNode.DeepEquals(e1, e2));
Assert.False(XNode.DeepEquals(e1, e3));
Assert.False(XNode.DeepEquals(e1, e4));
Assert.False(XNode.DeepEquals(e1, e5));
Assert.False(XNode.DeepEquals(e2, e3));
Assert.False(XNode.DeepEquals(e2, e4));
Assert.False(XNode.DeepEquals(e2, e5));
Assert.False(XNode.DeepEquals(e3, e4));
Assert.False(XNode.DeepEquals(e3, e5));
Assert.False(XNode.DeepEquals(e4, e5));
}
/// <summary>
/// Tests that an element appended as a child element during iteration of its new
/// parent's content is returned in iteration.
/// </summary>
[Fact]
public void ElementAppendedChildIsIterated()
{
XElement parent = new XElement("element", new XElement("child1"), new XElement("child2"));
bool b1 = false, b2 = false, b3 = false, b4 = false;
foreach (XElement child in parent.Elements())
{
switch (child.Name.LocalName)
{
case "child1":
b1 = true;
parent.Add(new XElement("extra1"));
break;
case "child2":
b2 = true;
parent.Add(new XElement("extra2"));
break;
case "extra1":
b3 = true;
break;
case "extra2":
b4 = true;
break;
default:
Assert.True(false, string.Format("Uexpected element '{0}'", child.Name));
break;
}
}
Assert.True(b1 || b2 || b3 || b4, "Appended child elements not included in parent iteration");
}
}
}
| dotnet-bot/corefx | src/System.Private.Xml.Linq/tests/SDMSample/SDMElement.cs | C# | mit | 37,040 |
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Grid\DataExtractor;
use Sylius\Component\Grid\Definition\Field;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
class PropertyAccessDataExtractor implements DataExtractorInterface
{
/**
* @var PropertyAccessorInterface
*/
private $propertyAccessor;
/**
* @param PropertyAccessorInterface $propertyAccessor
*/
public function __construct(PropertyAccessorInterface $propertyAccessor)
{
$this->propertyAccessor = $propertyAccessor;
}
/**
* {@inheritdoc}
*/
public function get(Field $field, $data)
{
return $this->propertyAccessor->getValue($data, $field->getPath());
}
}
| psyray/Sylius | src/Sylius/Component/Grid/DataExtractor/PropertyAccessDataExtractor.php | PHP | mit | 981 |
#!/usr/bin/env ruby
require 'soap/rpc/standaloneServer'
require 'calc2'
class CalcServer2 < SOAP::RPC::StandaloneServer
def on_init
servant = CalcService2.new
add_method(servant, 'set_value', 'newValue')
add_method(servant, 'get_value')
add_method_as(servant, '+', 'add', 'lhs')
add_method_as(servant, '-', 'sub', 'lhs')
add_method_as(servant, '*', 'multi', 'lhs')
add_method_as(servant, '/', 'div', 'lhs')
end
end
if $0 == __FILE__
status = CalcServer2.new('CalcServer', 'http://tempuri.org/calcService', '0.0.0.0', 17171).start
end
| cykod/Webiva | vendor/gems/soap4r-1.5.8/test/soap/calc/server2.rb | Ruby | mit | 571 |
/* eslint no-console: 0 */
var _ = require('underscore');
var files = require('./files.js');
var Console = require('./console.js').Console;
// This file implements "upgraders" --- functions which upgrade a Meteor app to
// a new version. Each upgrader has a name (registered in upgradersByName).
//
// You can test upgraders by running "meteor admin run-upgrader myupgradername".
//
// Upgraders are run automatically by "meteor update". It looks at the
// .meteor/.finished-upgraders file in the app and runs every upgrader listed
// here that is not in that file; then it appends their names to that file.
// Upgraders are run in the order they are listed in upgradersByName below.
//
// Upgraders receive a projectContext that has been fully prepared for build.
var printedNoticeHeaderThisProcess = false;
var maybePrintNoticeHeader = function () {
if (printedNoticeHeaderThisProcess)
return;
console.log();
console.log("-- Notice --");
console.log();
printedNoticeHeaderThisProcess = true;
};
// How to do package-specific notices:
// (a) A notice that occurs if a package is used indirectly or directly.
// if (projectContext.packageMap.getInfo('accounts-ui')) {
// console.log(
// "\n" +
// " Accounts UI has totally changed, yo.");
// }
//
// (b) A notice that occurs if a package is used directly.
// if (projectContext.projectConstraintsFile.getConstraint('accounts-ui')) {
// console.log(
// "\n" +
// " Accounts UI has totally changed, yo.");
// }
var upgradersByName = {
"notices-for-0.9.0": function (projectContext) {
maybePrintNoticeHeader();
var smartJsonPath =
files.pathJoin(projectContext.projectDir, 'smart.json');
if (files.exists(smartJsonPath)) {
// Meteorite apps:
console.log(
"0.9.0: Welcome to the new Meteor package system! You can now add any Meteor\n" +
" package to your app (from more than 1800 packages available on the\n" +
" Meteor Package Server) just by typing 'meteor add <packagename>', no\n" +
" Meteorite required.\n" +
"\n" +
" It looks like you have been using Meteorite with this project. To\n" +
" migrate your project automatically to the new system:\n" +
" (1) upgrade your Meteorite with 'npm install -g meteorite', then\n" +
" (2) run 'mrt migrate-app' inside the project.\n" +
" Having done this, you no longer need 'mrt' and can just use 'meteor'.\n");
} else {
// Non-Meteorite apps:
console.log(
"0.9.0: Welcome to the new Meteor package system! You can now add any Meteor\n" +
" package to your app (from more than 1800 packages available on the\n" +
" Meteor Package Server) just by typing 'meteor add <packagename>'. Check\n" +
" out the available packages by typing 'meteor search <term>' or by\n" +
" visiting atmospherejs.com.\n");
}
console.log();
},
"notices-for-0.9.1": function () {
maybePrintNoticeHeader();
console.log(
"0.9.1: Meteor 0.9.1 includes changes to the Blaze API, in preparation for 1.0.\n" +
" Many previously undocumented APIs are now public and documented. Most\n" +
" changes are backwards compatible, except that templates can no longer\n" +
" be named \"body\" or \"instance\".\n");
console.log();
},
// In 0.9.4, the platforms file contains "server" and "browser" as platforms,
// and before it only had "ios" and/or "android". We auto-fix that in
// PlatformList anyway, but we also need to pull platforms from the old
// cordova-platforms filename.
"0.9.4-platform-file": function (projectContext) {
var oldPlatformsPath =
files.pathJoin(projectContext.projectDir, ".meteor", "cordova-platforms");
try {
var oldPlatformsFile = files.readFile(oldPlatformsPath);
} catch (e) {
// If the file doesn't exist, there's no transition to do.
if (e && e.code === 'ENOENT')
return;
throw e;
}
var oldPlatforms = _.compact(_.map(
files.splitBufferToLines(oldPlatformsFile), files.trimSpaceAndComments));
// This method will automatically add "server" and "browser" and sort, etc.
projectContext.platformList.write(oldPlatforms);
files.unlink(oldPlatformsPath);
},
"notices-for-facebook-graph-api-2": function (projectContext) {
// Note: this will print if the app has facebook as a dependency, whether
// direct or indirect. (This is good, since most apps will be pulling it in
// indirectly via accounts-facebook.)
if (projectContext.packageMap.getInfo('facebook')) {
maybePrintNoticeHeader();
Console.info(
"This version of Meteor now uses version 2.2 of the Facebook API",
"for authentication, instead of 1.0. If you use additional Facebook",
"API methods beyond login, you may need to request new",
"permissions.\n\n",
"Facebook will automatically switch all apps to API",
"version 2.0 on April 30th, 2015. Please make sure to update your",
"application's permissions and API calls by that date.\n\n",
"For more details, see",
"https://github.com/meteor/meteor/wiki/Facebook-Graph-API-Upgrade",
Console.options({ bulletPoint: "1.0.5: " })
);
}
},
"1.2.0-standard-minifiers-package": function (projectContext) {
// Minifiers are extracted into a new package called "standard-minifiers"
projectContext.projectConstraintsFile.addConstraints(
['standard-minifiers']);
projectContext.projectConstraintsFile.writeIfModified();
}
////////////
// PLEASE. When adding new upgraders that print mesasges, follow the
// examples for 0.9.0 and 0.9.1 above. Specifically, formatting
// should be:
//
// 1.x.y: Lorem ipsum messages go here...
// ...and linewrapped on the right column
//
// (Or just use Console.info with bulletPoint)
////////////
};
exports.runUpgrader = function (projectContext, upgraderName) {
// This should only be called from the hidden run-upgrader command or by
// "meteor update" with an upgrader from one of our releases, so it's OK if
// error handling is just an exception.
if (! _.has(upgradersByName, upgraderName))
throw new Error("Unknown upgrader: " + upgraderName);
upgradersByName[upgraderName](projectContext);
};
exports.upgradersToRun = function (projectContext) {
var ret = [];
var finishedUpgraders = projectContext.finishedUpgraders.readUpgraders();
// This relies on the fact that Node guarantees object iteration ordering.
_.each(upgradersByName, function (func, name) {
if (! _.contains(finishedUpgraders, name)) {
ret.push(name);
}
});
return ret;
};
exports.allUpgraders = function () {
return _.keys(upgradersByName);
};
| arunoda/meteor | tools/upgraders.js | JavaScript | mit | 6,784 |
/*
* Copyright (C) 2012-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "FileItem.h"
#include "addons/include/xbmc_pvr_types.h"
#include "pvr/PVRManager.h"
#include "pvr/channels/PVRChannelGroupsContainer.h"
#include "pvr/recordings/PVRRecordings.h"
#include "pvr/timers/PVRTimers.h"
#include "utils/TextSearch.h"
#include "utils/log.h"
#include "EpgContainer.h"
#include "EpgSearchFilter.h"
using namespace EPG;
using namespace PVR;
void EpgSearchFilter::Reset()
{
m_strSearchTerm = "";
m_bIsCaseSensitive = false;
m_bSearchInDescription = false;
m_iGenreType = EPG_SEARCH_UNSET;
m_iGenreSubType = EPG_SEARCH_UNSET;
m_iMinimumDuration = EPG_SEARCH_UNSET;
m_iMaximumDuration = EPG_SEARCH_UNSET;
m_startDateTime.SetFromUTCDateTime(g_EpgContainer.GetFirstEPGDate());
m_endDateTime.SetFromUTCDateTime(g_EpgContainer.GetLastEPGDate());
m_bIncludeUnknownGenres = false;
m_bPreventRepeats = false;
/* pvr specific filters */
m_iChannelNumber = EPG_SEARCH_UNSET;
m_bFTAOnly = false;
m_iChannelGroup = EPG_SEARCH_UNSET;
m_bIgnorePresentTimers = true;
m_bIgnorePresentRecordings = true;
m_iUniqueBroadcastId = EPG_SEARCH_UNSET;
}
bool EpgSearchFilter::MatchGenre(const CEpgInfoTag &tag) const
{
bool bReturn(true);
if (m_iGenreType != EPG_SEARCH_UNSET)
{
bool bIsUnknownGenre(tag.GenreType() > EPG_EVENT_CONTENTMASK_USERDEFINED ||
tag.GenreType() < EPG_EVENT_CONTENTMASK_MOVIEDRAMA);
bReturn = ((m_bIncludeUnknownGenres && bIsUnknownGenre) || tag.GenreType() == m_iGenreType);
}
return bReturn;
}
bool EpgSearchFilter::MatchDuration(const CEpgInfoTag &tag) const
{
bool bReturn(true);
if (m_iMinimumDuration != EPG_SEARCH_UNSET)
bReturn = (tag.GetDuration() > m_iMinimumDuration * 60);
if (bReturn && m_iMaximumDuration != EPG_SEARCH_UNSET)
bReturn = (tag.GetDuration() < m_iMaximumDuration * 60);
return bReturn;
}
bool EpgSearchFilter::MatchStartAndEndTimes(const CEpgInfoTag &tag) const
{
return (tag.StartAsLocalTime() >= m_startDateTime && tag.EndAsLocalTime() <= m_endDateTime);
}
bool EpgSearchFilter::MatchSearchTerm(const CEpgInfoTag &tag) const
{
bool bReturn(true);
if (!m_strSearchTerm.empty())
{
CTextSearch search(m_strSearchTerm, m_bIsCaseSensitive, SEARCH_DEFAULT_OR);
bReturn = search.Search(tag.Title()) ||
search.Search(tag.PlotOutline());
}
return bReturn;
}
bool EpgSearchFilter::MatchBroadcastId(const CEpgInfoTag &tag) const
{
if (m_iUniqueBroadcastId != EPG_SEARCH_UNSET)
return (tag.UniqueBroadcastID() == m_iUniqueBroadcastId);
return true;
}
bool EpgSearchFilter::FilterEntry(const CEpgInfoTag &tag) const
{
return (MatchGenre(tag) &&
MatchBroadcastId(tag) &&
MatchDuration(tag) &&
MatchStartAndEndTimes(tag) &&
MatchSearchTerm(tag)) &&
(!tag.HasPVRChannel() ||
(MatchChannelType(tag) &&
MatchChannelNumber(tag) &&
MatchChannelGroup(tag) &&
(!m_bFTAOnly || !tag.ChannelTag()->IsEncrypted())));
}
int EpgSearchFilter::RemoveDuplicates(CFileItemList &results)
{
unsigned int iSize = results.Size();
for (unsigned int iResultPtr = 0; iResultPtr < iSize; iResultPtr++)
{
const CEpgInfoTagPtr epgentry_1(results.Get(iResultPtr)->GetEPGInfoTag());
if (!epgentry_1)
continue;
for (unsigned int iTagPtr = 0; iTagPtr < iSize; iTagPtr++)
{
if (iResultPtr == iTagPtr)
continue;
const CEpgInfoTagPtr epgentry_2(results.Get(iTagPtr)->GetEPGInfoTag());
if (!epgentry_2)
continue;
if (epgentry_1->Title() != epgentry_2->Title() ||
epgentry_1->Plot() != epgentry_2->Plot() ||
epgentry_1->PlotOutline() != epgentry_2->PlotOutline())
continue;
results.Remove(iTagPtr);
iResultPtr--;
iTagPtr--;
iSize--;
}
}
return iSize;
}
bool EpgSearchFilter::MatchChannelType(const CEpgInfoTag &tag) const
{
return (g_PVRManager.IsStarted() && tag.ChannelTag()->IsRadio() == m_bIsRadio);
}
bool EpgSearchFilter::MatchChannelNumber(const CEpgInfoTag &tag) const
{
bool bReturn(true);
if (m_iChannelNumber != EPG_SEARCH_UNSET && g_PVRManager.IsStarted())
{
CPVRChannelGroupPtr group = (m_iChannelGroup != EPG_SEARCH_UNSET) ? g_PVRChannelGroups->GetByIdFromAll(m_iChannelGroup) : g_PVRChannelGroups->GetGroupAllTV();
if (!group)
group = CPVRManager::GetInstance().ChannelGroups()->GetGroupAllTV();
bReturn = (m_iChannelNumber == (int) group->GetChannelNumber(tag.ChannelTag()));
}
return bReturn;
}
bool EpgSearchFilter::MatchChannelGroup(const CEpgInfoTag &tag) const
{
bool bReturn(true);
if (m_iChannelGroup != EPG_SEARCH_UNSET && g_PVRManager.IsStarted())
{
CPVRChannelGroupPtr group = g_PVRChannelGroups->GetByIdFromAll(m_iChannelGroup);
bReturn = (group && group->IsGroupMember(tag.ChannelTag()));
}
return bReturn;
}
int EpgSearchFilter::FilterRecordings(CFileItemList &results)
{
int iRemoved(0);
if (!g_PVRManager.IsStarted())
return iRemoved;
CFileItemList recordings;
g_PVRRecordings->GetAll(recordings);
// TODO inefficient!
CPVRRecordingPtr recording;
for (int iRecordingPtr = 0; iRecordingPtr < recordings.Size(); iRecordingPtr++)
{
recording = recordings.Get(iRecordingPtr)->GetPVRRecordingInfoTag();
if (!recording)
continue;
for (int iResultPtr = 0; iResultPtr < results.Size(); iResultPtr++)
{
const CEpgInfoTagPtr epgentry(results.Get(iResultPtr)->GetEPGInfoTag());
/* no match */
if (!epgentry ||
epgentry->Title() != recording->m_strTitle ||
epgentry->Plot() != recording->m_strPlot)
continue;
results.Remove(iResultPtr);
iResultPtr--;
++iRemoved;
}
}
return iRemoved;
}
int EpgSearchFilter::FilterTimers(CFileItemList &results)
{
int iRemoved(0);
if (!g_PVRManager.IsStarted())
return iRemoved;
std::vector<CFileItemPtr> timers = g_PVRTimers->GetActiveTimers();
// TODO inefficient!
for (unsigned int iTimerPtr = 0; iTimerPtr < timers.size(); iTimerPtr++)
{
CFileItemPtr fileItem = timers.at(iTimerPtr);
if (!fileItem || !fileItem->HasPVRTimerInfoTag())
continue;
CPVRTimerInfoTagPtr timer = fileItem->GetPVRTimerInfoTag();
if (!timer)
continue;
for (int iResultPtr = 0; iResultPtr < results.Size(); iResultPtr++)
{
const CEpgInfoTagPtr epgentry(results.Get(iResultPtr)->GetEPGInfoTag());
if (!epgentry ||
*epgentry->ChannelTag() != *timer->ChannelTag() ||
epgentry->StartAsUTC() < timer->StartAsUTC() ||
epgentry->EndAsUTC() > timer->EndAsUTC())
continue;
results.Remove(iResultPtr);
iResultPtr--;
++iRemoved;
}
}
return iRemoved;
}
| mikkle/xbmc | xbmc/epg/EpgSearchFilter.cpp | C++ | gpl-2.0 | 7,599 |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the sqs-2012-11-05.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.SQS.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.SQS.Model.Internal.MarshallTransformations
{
/// <summary>
/// GetQueueUrl Request Marshaller
/// </summary>
public class GetQueueUrlRequestMarshaller : IMarshaller<IRequest, GetQueueUrlRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((GetQueueUrlRequest)input);
}
public IRequest Marshall(GetQueueUrlRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.SQS");
request.Parameters.Add("Action", "GetQueueUrl");
request.Parameters.Add("Version", "2012-11-05");
if(publicRequest != null)
{
if(publicRequest.IsSetQueueName())
{
request.Parameters.Add("QueueName", StringUtils.FromString(publicRequest.QueueName));
}
if(publicRequest.IsSetQueueOwnerAWSAccountId())
{
request.Parameters.Add("QueueOwnerAWSAccountId", StringUtils.FromString(publicRequest.QueueOwnerAWSAccountId));
}
}
return request;
}
}
} | ykbarros/aws-sdk-xamarin | AWS.XamarinSDK/AWSSDK_iOS/Amazon.SQS/Model/Model/Internal/MarshallTransformations/GetQueueUrlRequestMarshaller.cs | C# | apache-2.0 | 2,252 |
package org.apache.lucene.codecs.sep;
/*
* 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.
*/
import java.io.Closeable;
import java.io.IOException;
import org.apache.lucene.store.DataInput;
/** Defines basic API for writing ints to an IndexOutput.
* IntBlockCodec interacts with this API. @see
* IntBlockReader
*
* @lucene.experimental */
public abstract class IntIndexInput implements Closeable {
public abstract Reader reader() throws IOException;
@Override
public abstract void close() throws IOException;
public abstract Index index() throws IOException;
/** Records a single skip-point in the {@link IntIndexInput.Reader}. */
public abstract static class Index {
public abstract void read(DataInput indexIn, boolean absolute) throws IOException;
/** Seeks primary stream to the last read offset */
public abstract void seek(IntIndexInput.Reader stream) throws IOException;
public abstract void copyFrom(Index other);
@Override
public abstract Index clone();
}
/** Reads int values. */
public abstract static class Reader {
/** Reads next single int */
public abstract int next() throws IOException;
}
}
| smartan/lucene | src/main/java/org/apache/lucene/codecs/sep/IntIndexInput.java | Java | apache-2.0 | 1,932 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.rest.messages.job.metrics;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonInclude;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty;
import javax.annotation.Nullable;
import static java.util.Objects.requireNonNull;
/**
* Response type for aggregated metrics. Contains the metric name and optionally the sum, average, minimum and maximum.
*/
public class AggregatedMetric {
private static final String FIELD_NAME_ID = "id";
private static final String FIELD_NAME_MIN = "min";
private static final String FIELD_NAME_MAX = "max";
private static final String FIELD_NAME_AVG = "avg";
private static final String FIELD_NAME_SUM = "sum";
@JsonProperty(value = FIELD_NAME_ID, required = true)
private final String id;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(FIELD_NAME_MIN)
private final Double min;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(FIELD_NAME_MAX)
private final Double max;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(FIELD_NAME_AVG)
private final Double avg;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(FIELD_NAME_SUM)
private final Double sum;
@JsonCreator
public AggregatedMetric(
final @JsonProperty(value = FIELD_NAME_ID, required = true) String id,
final @Nullable @JsonProperty(FIELD_NAME_MIN) Double min,
final @Nullable @JsonProperty(FIELD_NAME_MAX) Double max,
final @Nullable @JsonProperty(FIELD_NAME_AVG) Double avg,
final @Nullable @JsonProperty(FIELD_NAME_SUM) Double sum) {
this.id = requireNonNull(id, "id must not be null");
this.min = min;
this.max = max;
this.avg = avg;
this.sum = sum;
}
public AggregatedMetric(final @JsonProperty(value = FIELD_NAME_ID, required = true) String id) {
this(id, null, null, null, null);
}
@JsonIgnore
public String getId() {
return id;
}
@JsonIgnore
public Double getMin() {
return min;
}
@JsonIgnore
public Double getMax() {
return max;
}
@JsonIgnore
public Double getSum() {
return sum;
}
@JsonIgnore
public Double getAvg() {
return avg;
}
@Override
public String toString() {
return "AggregatedMetric{" +
"id='" + id + '\'' +
", mim='" + min + '\'' +
", max='" + max + '\'' +
", avg='" + avg + '\'' +
", sum='" + sum + '\'' +
'}';
}
}
| hequn8128/flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/job/metrics/AggregatedMetric.java | Java | apache-2.0 | 3,347 |
/**
* 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.falcon.service;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.testng.Assert;
import java.util.List;
/**
* Unit tests for GroupsService.
*/
public class GroupsServiceTest {
private GroupsService service;
@BeforeClass
public void setUp() throws Exception {
service = new GroupsService();
service.init();
}
@AfterClass
public void tearDown() throws Exception {
service.destroy();
}
@Test
public void testGetName() throws Exception {
Assert.assertEquals(service.getName(), GroupsService.SERVICE_NAME);
}
@Test
public void testGroupsService() throws Exception {
List<String> g = service.getGroups(System.getProperty("user.name"));
Assert.assertNotSame(g.size(), 0);
}
}
| sriksun/falcon | common/src/test/java/org/apache/falcon/service/GroupsServiceTest.java | Java | apache-2.0 | 1,688 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.datanode;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.timeout;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.client.BlockReportOptions;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocolPB.DatanodeProtocolClientSideTranslatorPB;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsDatasetSpi;
import org.apache.hadoop.hdfs.server.protocol.DatanodeRegistration;
import org.apache.hadoop.hdfs.server.protocol.DatanodeStorage;
import org.apache.hadoop.hdfs.server.protocol.ReceivedDeletedBlockInfo;
import org.apache.hadoop.hdfs.server.protocol.StorageReceivedDeletedBlocks;
import org.apache.hadoop.hdfs.server.protocol.ReceivedDeletedBlockInfo.BlockStatus;
import org.apache.hadoop.metrics2.MetricsRecordBuilder;
import org.apache.hadoop.test.MetricsAsserts;
import org.junit.Test;
import org.mockito.Mockito;
/**
* Test counters for number of blocks in pending IBR.
*/
public class TestBlockCountersInPendingIBR {
@Test
public void testBlockCounters() throws Exception {
final Configuration conf = new HdfsConfiguration();
/*
* Set a really long value for dfs.blockreport.intervalMsec and
* dfs.heartbeat.interval, so that incremental block reports and heartbeats
* won't be sent during this test unless they're triggered manually.
*/
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10800000L);
conf.setLong(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1080L);
final MiniDFSCluster cluster =
new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
cluster.waitActive();
final DatanodeProtocolClientSideTranslatorPB spy =
InternalDataNodeTestUtils.spyOnBposToNN(
cluster.getDataNodes().get(0), cluster.getNameNode());
final DataNode datanode = cluster.getDataNodes().get(0);
/* We should get 0 incremental block report. */
Mockito.verify(spy, timeout(60000).times(0)).blockReceivedAndDeleted(
any(DatanodeRegistration.class),
anyString(),
any(StorageReceivedDeletedBlocks[].class));
/*
* Create fake blocks notification on the DataNode. This will be sent with
* the next incremental block report.
*/
final BPServiceActor actor =
datanode.getAllBpOs().get(0).getBPServiceActors().get(0);
final FsDatasetSpi<?> dataset = datanode.getFSDataset();
final DatanodeStorage storage;
try (FsDatasetSpi.FsVolumeReferences volumes =
dataset.getFsVolumeReferences()) {
storage = dataset.getStorage(volumes.get(0).getStorageID());
}
ReceivedDeletedBlockInfo rdbi = null;
/* block at status of RECEIVING_BLOCK */
rdbi = new ReceivedDeletedBlockInfo(
new Block(5678, 512, 1000), BlockStatus.RECEIVING_BLOCK, null);
actor.getIbrManager().addRDBI(rdbi, storage);
/* block at status of RECEIVED_BLOCK */
rdbi = new ReceivedDeletedBlockInfo(
new Block(5679, 512, 1000), BlockStatus.RECEIVED_BLOCK, null);
actor.getIbrManager().addRDBI(rdbi, storage);
/* block at status of DELETED_BLOCK */
rdbi = new ReceivedDeletedBlockInfo(
new Block(5680, 512, 1000), BlockStatus.DELETED_BLOCK, null);
actor.getIbrManager().addRDBI(rdbi, storage);
/* verify counters before sending IBR */
verifyBlockCounters(datanode, 3, 1, 1, 1);
/* Manually trigger a block report. */
datanode.triggerBlockReport(
new BlockReportOptions.Factory().
setIncremental(true).
build()
);
/*
* triggerBlockReport returns before the block report is actually sent. Wait
* for it to be sent here.
*/
Mockito.verify(spy, timeout(60000).times(1)).
blockReceivedAndDeleted(
any(DatanodeRegistration.class),
anyString(),
any(StorageReceivedDeletedBlocks[].class));
/* verify counters after sending IBR */
verifyBlockCounters(datanode, 0, 0, 0, 0);
cluster.shutdown();
}
private void verifyBlockCounters(final DataNode datanode,
final long blocksInPendingIBR, final long blocksReceivingInPendingIBR,
final long blocksReceivedInPendingIBR,
final long blocksDeletedInPendingIBR) {
final MetricsRecordBuilder m = MetricsAsserts
.getMetrics(datanode.getMetrics().name());
MetricsAsserts.assertGauge("BlocksInPendingIBR",
blocksInPendingIBR, m);
MetricsAsserts.assertGauge("BlocksReceivingInPendingIBR",
blocksReceivingInPendingIBR, m);
MetricsAsserts.assertGauge("BlocksReceivedInPendingIBR",
blocksReceivedInPendingIBR, m);
MetricsAsserts.assertGauge("BlocksDeletedInPendingIBR",
blocksDeletedInPendingIBR, m);
}
}
| dennishuo/hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestBlockCountersInPendingIBR.java | Java | apache-2.0 | 5,773 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.tests.integration.ra;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.resource.ResourceException;
import javax.resource.spi.InvalidPropertyException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.apache.activemq.artemis.api.core.client.ClientProducer;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.apache.activemq.artemis.api.core.client.ClientSession.QueueQuery;
import org.apache.activemq.artemis.api.core.client.SessionFailureListener;
import org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryInternal;
import org.apache.activemq.artemis.core.postoffice.Binding;
import org.apache.activemq.artemis.core.postoffice.impl.LocalQueueBinding;
import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
import org.apache.activemq.artemis.ra.ActiveMQResourceAdapter;
import org.apache.activemq.artemis.ra.inflow.ActiveMQActivation;
import org.apache.activemq.artemis.ra.inflow.ActiveMQActivationSpec;
import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger;
import org.junit.Test;
public class ActiveMQMessageHandlerTest extends ActiveMQRATestBase {
@Override
public boolean useSecurity() {
return false;
}
@Test
public void testSimpleMessageReceivedOnQueue() throws Exception {
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestinationType("javax.jms.Queue");
spec.setDestination(MDBQUEUE);
qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
CountDownLatch latch = new CountDownLatch(1);
DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
ClientSession session = locator.createSessionFactory().createSession();
ClientProducer clientProducer = session.createProducer(MDBQUEUEPREFIXED);
ClientMessage message = session.createMessage(true);
message.getBodyBuffer().writeString("teststring");
clientProducer.send(message);
session.close();
latch.await(5, TimeUnit.SECONDS);
assertNotNull(endpoint.lastMessage);
assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "teststring");
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
qResourceAdapter.stop();
}
@Test
public void testObjectMessageReceiveSerializationControl() throws Exception {
String blackList = "org.apache.activemq.artemis.tests.integration.ra";
String whiteList = "*";
testDeserialization(blackList, whiteList, false);
}
@Test
public void testObjectMessageReceiveSerializationControl1() throws Exception {
String blackList = "some.other.pkg";
String whiteList = "org.apache.activemq.artemis.tests.integration.ra";
testDeserialization(blackList, whiteList, true);
}
@Test
public void testObjectMessageReceiveSerializationControl2() throws Exception {
String blackList = "*";
String whiteList = "org.apache.activemq.artemis.tests.integration.ra";
testDeserialization(blackList, whiteList, false);
}
@Test
public void testObjectMessageReceiveSerializationControl3() throws Exception {
String blackList = "org.apache.activemq.artemis.tests";
String whiteList = "org.apache.activemq.artemis.tests.integration.ra";
testDeserialization(blackList, whiteList, false);
}
@Test
public void testObjectMessageReceiveSerializationControl4() throws Exception {
String blackList = null;
String whiteList = "some.other.pkg";
testDeserialization(blackList, whiteList, false);
}
@Test
public void testObjectMessageReceiveSerializationControl5() throws Exception {
String blackList = null;
String whiteList = null;
testDeserialization(blackList, whiteList, true);
}
private void testDeserialization(String blackList, String whiteList, boolean shouldSucceed) throws Exception {
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
qResourceAdapter.setDeserializationBlackList(blackList);
qResourceAdapter.setDeserializationWhiteList(whiteList);
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestinationType("javax.jms.Queue");
spec.setDestination(MDBQUEUE);
qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
CountDownLatch latch = new CountDownLatch(1);
DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
//send using jms
ActiveMQConnectionFactory jmsFactory = new ActiveMQConnectionFactory("vm://0");
Connection connection = jmsFactory.createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue jmsQueue = session.createQueue(MDBQUEUE);
ObjectMessage objMsg = session.createObjectMessage();
objMsg.setObject(new DummySerializable());
MessageProducer producer = session.createProducer(jmsQueue);
producer.send(objMsg);
} finally {
connection.close();
}
latch.await(5, TimeUnit.SECONDS);
assertNotNull(endpoint.lastMessage);
ObjectMessage objMsg = (ObjectMessage) endpoint.lastMessage;
try {
Object obj = objMsg.getObject();
assertTrue("deserialization should fail but got: " + obj, shouldSucceed);
assertTrue(obj instanceof DummySerializable);
} catch (JMSException e) {
assertFalse("got unexpected exception: " + e, shouldSucceed);
}
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
qResourceAdapter.stop();
}
@Test
public void testSimpleMessageReceivedOnQueueManyMessages() throws Exception {
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestinationType("javax.jms.Queue");
spec.setDestination(MDBQUEUE);
qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
CountDownLatch latch = new CountDownLatch(15);
MultipleEndpoints endpoint = new MultipleEndpoints(latch, null, false);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
ClientSession session = locator.createSessionFactory().createSession();
ClientProducer clientProducer = session.createProducer(MDBQUEUEPREFIXED);
for (int i = 0; i < 15; i++) {
ClientMessage message = session.createMessage(true);
message.getBodyBuffer().writeString("teststring" + i);
clientProducer.send(message);
}
session.close();
latch.await(5, TimeUnit.SECONDS);
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
qResourceAdapter.stop();
}
@Test
public void testSimpleMessageReceivedOnQueueManyMessagesAndInterrupt() throws Exception {
final int SIZE = 14;
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestinationType("javax.jms.Queue");
spec.setDestination(MDBQUEUE);
qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
CountDownLatch latch = new CountDownLatch(SIZE);
CountDownLatch latchDone = new CountDownLatch(SIZE);
MultipleEndpoints endpoint = new MultipleEndpoints(latch, latchDone, true);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
ClientSession session = locator.createSessionFactory().createSession();
ClientProducer clientProducer = session.createProducer(MDBQUEUEPREFIXED);
for (int i = 0; i < SIZE; i++) {
ClientMessage message = session.createMessage(true);
message.getBodyBuffer().writeString("teststring" + i);
clientProducer.send(message);
}
session.close();
assertTrue(latch.await(5, TimeUnit.SECONDS));
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
latchDone.await(5, TimeUnit.SECONDS);
assertEquals(SIZE, endpoint.messages.intValue());
assertEquals(0, endpoint.interrupted.intValue());
qResourceAdapter.stop();
}
@Test
public void testSimpleMessageReceivedOnQueueManyMessagesAndInterruptTimeout() throws Exception {
final int SIZE = 14;
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setCallTimeout(500L);
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestinationType("javax.jms.Queue");
spec.setDestination(MDBQUEUE);
qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
CountDownLatch latch = new CountDownLatch(SIZE);
CountDownLatch latchDone = new CountDownLatch(SIZE);
MultipleEndpoints endpoint = new MultipleEndpoints(latch, latchDone, true);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
ClientSession session = locator.createSessionFactory().createSession();
ClientProducer clientProducer = session.createProducer(MDBQUEUEPREFIXED);
for (int i = 0; i < SIZE; i++) {
ClientMessage message = session.createMessage(true);
message.getBodyBuffer().writeString("teststring" + i);
clientProducer.send(message);
}
session.close();
assertTrue(latch.await(5, TimeUnit.SECONDS));
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
latchDone.await(5, TimeUnit.SECONDS);
assertEquals(SIZE, endpoint.messages.intValue());
//half onmessage interrupted
assertEquals(SIZE / 2, endpoint.interrupted.intValue());
qResourceAdapter.stop();
}
/**
* @return
*/
@Override
protected ActiveMQResourceAdapter newResourceAdapter() {
ActiveMQResourceAdapter qResourceAdapter = new ActiveMQResourceAdapter();
qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
return qResourceAdapter;
}
@Test
public void testServerShutdownAndReconnect() throws Exception {
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
qResourceAdapter.setReconnectAttempts(-1);
qResourceAdapter.setCallTimeout(500L);
qResourceAdapter.setRetryInterval(500L);
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
// This is just to register a listener
final CountDownLatch failedLatch = new CountDownLatch(1);
ClientSessionFactoryInternal factoryListener = (ClientSessionFactoryInternal) qResourceAdapter.getDefaultActiveMQConnectionFactory().getServerLocator().createSessionFactory();
factoryListener.addFailureListener(new SessionFailureListener() {
@Override
public void connectionFailed(ActiveMQException exception, boolean failedOver) {
}
@Override
public void connectionFailed(ActiveMQException exception, boolean failedOver, String scaleDownTargetNodeID) {
connectionFailed(exception, failedOver);
}
@Override
public void beforeReconnect(ActiveMQException exception) {
failedLatch.countDown();
}
});
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestinationType("javax.jms.Queue");
spec.setDestination(MDBQUEUE);
CountDownLatch latch = new CountDownLatch(1);
DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
ClientSession session = locator.createSessionFactory().createSession();
ClientProducer clientProducer = session.createProducer(MDBQUEUEPREFIXED);
ClientMessage message = session.createMessage(true);
message.getBodyBuffer().writeString("teststring");
clientProducer.send(message);
session.close();
latch.await(5, TimeUnit.SECONDS);
assertNotNull(endpoint.lastMessage);
assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "teststring");
server.stop();
assertTrue(failedLatch.await(5, TimeUnit.SECONDS));
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
qResourceAdapter.stop();
}
@Test
public void testInvalidAckMode() throws Exception {
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
try {
spec.setAcknowledgeMode("CLIENT_ACKNOWLEDGE");
fail("should throw exception");
} catch (java.lang.IllegalArgumentException e) {
//pass
}
qResourceAdapter.stop();
}
@Test
public void testSimpleMessageReceivedOnQueueInLocalTX() throws Exception {
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
qResourceAdapter.setUseLocalTx(true);
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestinationType("javax.jms.Queue");
spec.setDestination(MDBQUEUE);
qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
CountDownLatch latch = new CountDownLatch(1);
ExceptionDummyMessageEndpoint endpoint = new ExceptionDummyMessageEndpoint(latch);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
ClientSession session = locator.createSessionFactory().createSession();
ClientProducer clientProducer = session.createProducer(MDBQUEUEPREFIXED);
ClientMessage message = session.createMessage(true);
message.getBodyBuffer().writeString("teststring");
clientProducer.send(message);
latch.await(5, TimeUnit.SECONDS);
assertNull(endpoint.lastMessage);
latch = new CountDownLatch(1);
endpoint.reset(latch);
clientProducer.send(message);
session.close();
latch.await(5, TimeUnit.SECONDS);
assertNotNull(endpoint.lastMessage);
assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "teststring");
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
qResourceAdapter.stop();
}
@Test
public void testSimpleMessageReceivedOnQueueWithSelector() throws Exception {
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestinationType("javax.jms.Queue");
spec.setDestination(MDBQUEUE);
spec.setMessageSelector("color='red'");
qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
CountDownLatch latch = new CountDownLatch(1);
DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
ClientSession session = locator.createSessionFactory().createSession();
ClientProducer clientProducer = session.createProducer(MDBQUEUEPREFIXED);
ClientMessage message = session.createMessage(true);
message.getBodyBuffer().writeString("blue");
message.putStringProperty("color", "blue");
clientProducer.send(message);
message = session.createMessage(true);
message.getBodyBuffer().writeString("red");
message.putStringProperty("color", "red");
clientProducer.send(message);
session.close();
latch.await(5, TimeUnit.SECONDS);
assertNotNull(endpoint.lastMessage);
assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "red");
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
qResourceAdapter.stop();
}
@Test
public void testEndpointDeactivated() throws Exception {
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestinationType("javax.jms.Queue");
spec.setDestination(MDBQUEUE);
qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
CountDownLatch latch = new CountDownLatch(1);
DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
Binding binding = server.getPostOffice().getBinding(MDBQUEUEPREFIXEDSIMPLE);
assertEquals(((LocalQueueBinding) binding).getQueue().getConsumerCount(), 15);
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
assertEquals(((LocalQueueBinding) binding).getQueue().getConsumerCount(), 0);
assertTrue(endpoint.released);
qResourceAdapter.stop();
}
@Test
public void testMaxSessions() throws Exception {
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setMaxSession(1);
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestinationType("javax.jms.Queue");
spec.setDestination(MDBQUEUE);
qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
CountDownLatch latch = new CountDownLatch(1);
DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
Binding binding = server.getPostOffice().getBinding(MDBQUEUEPREFIXEDSIMPLE);
assertEquals(((LocalQueueBinding) binding).getQueue().getConsumerCount(), 1);
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
qResourceAdapter.stop();
}
@Test
public void testSimpleTopic() throws Exception {
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestinationType("javax.jms.Topic");
spec.setDestination("mdbTopic");
qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
CountDownLatch latch = new CountDownLatch(1);
DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
ClientSession session = locator.createSessionFactory().createSession();
ClientProducer clientProducer = session.createProducer("mdbTopic");
ClientMessage message = session.createMessage(true);
message.getBodyBuffer().writeString("test");
clientProducer.send(message);
latch.await(5, TimeUnit.SECONDS);
assertNotNull(endpoint.lastMessage);
assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "test");
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
qResourceAdapter.stop();
}
@Test
public void testDurableSubscription() throws Exception {
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestinationType("javax.jms.Topic");
spec.setDestination("mdbTopic");
spec.setSubscriptionDurability("Durable");
spec.setSubscriptionName("durable-mdb");
spec.setClientID("id-1");
qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
CountDownLatch latch = new CountDownLatch(1);
DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
ClientSession session = locator.createSessionFactory().createSession();
ClientProducer clientProducer = session.createProducer("mdbTopic");
ClientMessage message = session.createMessage(true);
message.getBodyBuffer().writeString("1");
clientProducer.send(message);
latch.await(5, TimeUnit.SECONDS);
assertNotNull(endpoint.lastMessage);
assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "1");
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
message = session.createMessage(true);
message.getBodyBuffer().writeString("2");
clientProducer.send(message);
latch = new CountDownLatch(1);
endpoint = new DummyMessageEndpoint(latch);
endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
latch.await(5, TimeUnit.SECONDS);
assertNotNull(endpoint.lastMessage);
assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "2");
latch = new CountDownLatch(1);
endpoint.reset(latch);
message = session.createMessage(true);
message.getBodyBuffer().writeString("3");
clientProducer.send(message);
latch.await(5, TimeUnit.SECONDS);
assertNotNull(endpoint.lastMessage);
assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "3");
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
qResourceAdapter.stop();
}
@Test
public void testNonDurableSubscription() throws Exception {
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestinationType("javax.jms.Topic");
spec.setDestination("mdbTopic");
qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
CountDownLatch latch = new CountDownLatch(1);
DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
ClientSession session = locator.createSessionFactory().createSession();
ClientProducer clientProducer = session.createProducer("mdbTopic");
ClientMessage message = session.createMessage(true);
message.getBodyBuffer().writeString("1");
clientProducer.send(message);
latch.await(5, TimeUnit.SECONDS);
assertNotNull(endpoint.lastMessage);
assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "1");
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
message = session.createMessage(true);
message.getBodyBuffer().writeString("2");
clientProducer.send(message);
latch = new CountDownLatch(1);
endpoint = new DummyMessageEndpoint(latch);
endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
message = session.createMessage(true);
message.getBodyBuffer().writeString("3");
clientProducer.send(message);
latch.await(5, TimeUnit.SECONDS);
assertNotNull(endpoint.lastMessage);
assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "3");
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
qResourceAdapter.stop();
}
//https://issues.jboss.org/browse/JBPAPP-8017
@Test
public void testNonDurableSubscriptionDeleteAfterCrash() throws Exception {
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestinationType("javax.jms.Topic");
spec.setDestination("mdbTopic");
qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
CountDownLatch latch = new CountDownLatch(1);
DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
ClientSession session = locator.createSessionFactory().createSession();
ClientProducer clientProducer = session.createProducer("mdbTopic");
ClientMessage message = session.createMessage(true);
message.getBodyBuffer().writeString("1");
clientProducer.send(message);
latch.await(5, TimeUnit.SECONDS);
assertNotNull(endpoint.lastMessage);
assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "1");
ActiveMQActivation activation = lookupActivation(qResourceAdapter);
SimpleString tempQueueName = activation.getTopicTemporaryQueue();
QueueQuery query = session.queueQuery(tempQueueName);
assertTrue(query.isExists());
//this should be enough to simulate the crash
qResourceAdapter.getDefaultActiveMQConnectionFactory().close();
qResourceAdapter.stop();
query = session.queueQuery(tempQueueName);
assertFalse(query.isExists());
}
@Test
public void testSelectorChangedWithTopic() throws Exception {
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestinationType("javax.jms.Topic");
spec.setDestination("mdbTopic");
spec.setSubscriptionDurability("Durable");
spec.setSubscriptionName("durable-mdb");
spec.setClientID("id-1");
spec.setMessageSelector("foo='bar'");
qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
CountDownLatch latch = new CountDownLatch(1);
DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
ClientSession session = locator.createSessionFactory().createSession();
ClientProducer clientProducer = session.createProducer("mdbTopic");
ClientMessage message = session.createMessage(true);
message.getBodyBuffer().writeString("1");
message.putStringProperty("foo", "bar");
clientProducer.send(message);
latch.await(5, TimeUnit.SECONDS);
assertNotNull(endpoint.lastMessage);
assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "1");
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
message = session.createMessage(true);
message.getBodyBuffer().writeString("2");
message.putStringProperty("foo", "bar");
clientProducer.send(message);
latch = new CountDownLatch(1);
endpoint = new DummyMessageEndpoint(latch);
//change the selector forcing the queue to be recreated
spec.setMessageSelector("foo='abar'");
endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
message = session.createMessage(true);
message.getBodyBuffer().writeString("3");
message.putStringProperty("foo", "abar");
clientProducer.send(message);
latch.await(5, TimeUnit.SECONDS);
assertNotNull(endpoint.lastMessage);
assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "3");
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
qResourceAdapter.stop();
}
@Test
public void testSharedSubscription() throws Exception {
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestinationType("javax.jms.Topic");
spec.setDestination("mdbTopic");
spec.setSubscriptionDurability("Durable");
spec.setSubscriptionName("durable-mdb");
spec.setClientID("id-1");
spec.setSetupAttempts(1);
spec.setShareSubscriptions(true);
spec.setMaxSession(1);
ActiveMQActivationSpec spec2 = new ActiveMQActivationSpec();
spec2.setResourceAdapter(qResourceAdapter);
spec2.setUseJNDI(false);
spec2.setDestinationType("javax.jms.Topic");
spec2.setDestination("mdbTopic");
spec2.setSubscriptionDurability("Durable");
spec2.setSubscriptionName("durable-mdb");
spec2.setClientID("id-1");
spec2.setSetupAttempts(1);
spec2.setShareSubscriptions(true);
spec2.setMaxSession(1);
CountDownLatch latch = new CountDownLatch(5);
DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
CountDownLatch latch2 = new CountDownLatch(5);
DummyMessageEndpoint endpoint2 = new DummyMessageEndpoint(latch2);
DummyMessageEndpointFactory endpointFactory2 = new DummyMessageEndpointFactory(endpoint2, false);
qResourceAdapter.endpointActivation(endpointFactory2, spec2);
ClientSession session = locator.createSessionFactory().createSession();
ClientProducer clientProducer = session.createProducer("mdbTopic");
for (int i = 0; i < 10; i++) {
ClientMessage message = session.createMessage(true);
message.getBodyBuffer().writeString("" + i);
clientProducer.send(message);
}
session.commit();
assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(latch2.await(5, TimeUnit.SECONDS));
assertNotNull(endpoint.lastMessage);
assertNotNull(endpoint2.lastMessage);
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
qResourceAdapter.endpointDeactivation(endpointFactory2, spec2);
qResourceAdapter.stop();
}
@Test
public void testNullSubscriptionName() throws Exception {
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestination("mdbTopic");
spec.setSubscriptionDurability("Durable");
spec.setClientID("id-1");
spec.setSetupAttempts(1);
spec.setShareSubscriptions(true);
spec.setMaxSession(1);
CountDownLatch latch = new CountDownLatch(5);
DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
try {
qResourceAdapter.endpointActivation(endpointFactory, spec);
fail();
} catch (Exception e) {
assertTrue(e instanceof InvalidPropertyException);
assertEquals("subscriptionName", ((InvalidPropertyException) e).getInvalidPropertyDescriptors()[0].getName());
}
}
@Test
public void testBadDestinationType() throws Exception {
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestinationType("badDestinationType");
spec.setDestination("mdbTopic");
spec.setSetupAttempts(1);
spec.setShareSubscriptions(true);
spec.setMaxSession(1);
CountDownLatch latch = new CountDownLatch(5);
DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
try {
qResourceAdapter.endpointActivation(endpointFactory, spec);
fail();
} catch (Exception e) {
assertTrue(e instanceof InvalidPropertyException);
assertEquals("destinationType", ((InvalidPropertyException) e).getInvalidPropertyDescriptors()[0].getName());
}
}
@Test
public void testSelectorNotChangedWithTopic() throws Exception {
ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
MyBootstrapContext ctx = new MyBootstrapContext();
qResourceAdapter.start(ctx);
ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
spec.setResourceAdapter(qResourceAdapter);
spec.setUseJNDI(false);
spec.setDestinationType("javax.jms.Topic");
spec.setDestination("mdbTopic");
spec.setSubscriptionDurability("Durable");
spec.setSubscriptionName("durable-mdb");
spec.setClientID("id-1");
spec.setMessageSelector("foo='bar'");
qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
CountDownLatch latch = new CountDownLatch(1);
DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch);
DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
ClientSession session = locator.createSessionFactory().createSession();
ClientProducer clientProducer = session.createProducer("mdbTopic");
ClientMessage message = session.createMessage(true);
message.getBodyBuffer().writeString("1");
message.putStringProperty("foo", "bar");
clientProducer.send(message);
latch.await(5, TimeUnit.SECONDS);
assertNotNull(endpoint.lastMessage);
assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "1");
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
message = session.createMessage(true);
message.getBodyBuffer().writeString("2");
message.putStringProperty("foo", "bar");
clientProducer.send(message);
latch = new CountDownLatch(1);
endpoint = new DummyMessageEndpoint(latch);
endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
qResourceAdapter.endpointActivation(endpointFactory, spec);
latch.await(5, TimeUnit.SECONDS);
assertNotNull(endpoint.lastMessage);
assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "2");
qResourceAdapter.endpointDeactivation(endpointFactory, spec);
qResourceAdapter.stop();
}
class ExceptionDummyMessageEndpoint extends DummyMessageEndpoint {
boolean throwException = true;
ExceptionDummyMessageEndpoint(CountDownLatch latch) {
super(latch);
}
@Override
public void onMessage(Message message) {
if (throwException) {
throwException = false;
throw new IllegalStateException("boo!");
}
super.onMessage(message);
}
}
class MultipleEndpoints extends DummyMessageEndpoint {
private final CountDownLatch latch;
private final CountDownLatch latchDone;
private final boolean pause;
AtomicInteger messages = new AtomicInteger(0);
AtomicInteger interrupted = new AtomicInteger(0);
MultipleEndpoints(CountDownLatch latch, CountDownLatch latchDone, boolean pause) {
super(latch);
this.latch = latch;
this.latchDone = latchDone;
this.pause = pause;
}
@Override
public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException {
}
@Override
public void afterDelivery() throws ResourceException {
}
@Override
public void release() {
}
@Override
public void onMessage(Message message) {
try {
latch.countDown();
if (pause && messages.getAndIncrement() % 2 == 0) {
try {
IntegrationTestLogger.LOGGER.info("pausing for 2 secs");
Thread.sleep(2000);
} catch (InterruptedException e) {
interrupted.incrementAndGet();
}
}
} finally {
if (latchDone != null) {
latchDone.countDown();
}
}
}
}
static class DummySerializable implements Serializable {
}
}
| cshannon/activemq-artemis | tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ra/ActiveMQMessageHandlerTest.java | Java | apache-2.0 | 40,944 |
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package server
import (
"net/http"
"strings"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apiserver/pkg/authentication/authenticator"
"k8s.io/apiserver/pkg/authentication/user"
"k8s.io/apiserver/pkg/authorization/authorizer"
)
// KubeletAuth implements AuthInterface
type KubeletAuth struct {
// authenticator identifies the user for requests to the Kubelet API
authenticator.Request
// authorizerAttributeGetter builds authorization.Attributes for a request to the Kubelet API
authorizer.RequestAttributesGetter
// authorizer determines whether a given authorization.Attributes is allowed
authorizer.Authorizer
}
// NewKubeletAuth returns a kubelet.AuthInterface composed of the given authenticator, attribute getter, and authorizer
func NewKubeletAuth(authenticator authenticator.Request, authorizerAttributeGetter authorizer.RequestAttributesGetter, authorizer authorizer.Authorizer) AuthInterface {
return &KubeletAuth{authenticator, authorizerAttributeGetter, authorizer}
}
func NewNodeAuthorizerAttributesGetter(nodeName types.NodeName) authorizer.RequestAttributesGetter {
return nodeAuthorizerAttributesGetter{nodeName: nodeName}
}
type nodeAuthorizerAttributesGetter struct {
nodeName types.NodeName
}
func isSubpath(subpath, path string) bool {
path = strings.TrimSuffix(path, "/")
return subpath == path || (strings.HasPrefix(subpath, path) && subpath[len(path)] == '/')
}
// GetRequestAttributes populates authorizer attributes for the requests to the kubelet API.
// Default attributes are: {apiVersion=v1,verb=<http verb from request>,resource=nodes,name=<node name>,subresource=proxy}
// More specific verb/resource is set for the following request patterns:
// /stats/* => verb=<api verb from request>, resource=nodes, name=<node name>, subresource=stats
// /metrics/* => verb=<api verb from request>, resource=nodes, name=<node name>, subresource=metrics
// /logs/* => verb=<api verb from request>, resource=nodes, name=<node name>, subresource=log
// /spec/* => verb=<api verb from request>, resource=nodes, name=<node name>, subresource=spec
func (n nodeAuthorizerAttributesGetter) GetRequestAttributes(u user.Info, r *http.Request) authorizer.Attributes {
apiVerb := ""
switch r.Method {
case "POST":
apiVerb = "create"
case "GET":
apiVerb = "get"
case "PUT":
apiVerb = "update"
case "PATCH":
apiVerb = "patch"
case "DELETE":
apiVerb = "delete"
}
requestPath := r.URL.Path
// Default attributes mirror the API attributes that would allow this access to the kubelet API
attrs := authorizer.AttributesRecord{
User: u,
Verb: apiVerb,
Namespace: "",
APIGroup: "",
APIVersion: "v1",
Resource: "nodes",
Subresource: "proxy",
Name: string(n.nodeName),
ResourceRequest: true,
Path: requestPath,
}
// Override subresource for specific paths
// This allows subdividing access to the kubelet API
switch {
case isSubpath(requestPath, statsPath):
attrs.Subresource = "stats"
case isSubpath(requestPath, metricsPath):
attrs.Subresource = "metrics"
case isSubpath(requestPath, logsPath):
// "log" to match other log subresources (pods/log, etc)
attrs.Subresource = "log"
case isSubpath(requestPath, specPath):
attrs.Subresource = "spec"
}
glog.V(5).Infof("Node request attributes: user=%#v attrs=%#v", attrs.GetUser(), attrs)
return attrs
}
| liyinan926/kubernetes | pkg/kubelet/server/auth.go | GO | apache-2.0 | 4,024 |
/*
* SSDPDeviceDescriptionParser
* Connect SDK
*
* Copyright (c) 2014 LG Electronics.
* Created by Hyun Kook Khang on 6 Jan 2015
*
* 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.connectsdk.discovery.provider.ssdp;
import java.util.HashMap;
import java.util.Map;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SSDPDeviceDescriptionParser extends DefaultHandler {
public static final String TAG_DEVICE_TYPE = "deviceType";
public static final String TAG_FRIENDLY_NAME = "friendlyName";
public static final String TAG_MANUFACTURER = "manufacturer";
public static final String TAG_MANUFACTURER_URL = "manufacturerURL";
public static final String TAG_MODEL_DESCRIPTION = "modelDescription";
public static final String TAG_MODEL_NAME = "modelName";
public static final String TAG_MODEL_NUMBER = "modelNumber";
public static final String TAG_MODEL_URL = "modelURL";
public static final String TAG_SERIAL_NUMBER = "serialNumber";
public static final String TAG_UDN = "UDN";
public static final String TAG_UPC = "UPC";
public static final String TAG_ICON_LIST = "iconList";
public static final String TAG_SERVICE_LIST = "serviceList";
public static final String TAG_SEC_CAPABILITY = "sec:Capability";
public static final String TAG_PORT = "port";
public static final String TAG_LOCATION = "location";
String currentValue = null;
Icon currentIcon;
Service currentService;
SSDPDevice device;
Map<String, String> data;
public SSDPDeviceDescriptionParser(SSDPDevice device) {
this.device = device;
data = new HashMap<String, String>();
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentValue == null) {
currentValue = new String(ch, start, length);
}
else {
// append to existing string (needed for parsing character entities)
currentValue += new String(ch, start, length);
}
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (Icon.TAG.equals(qName)) {
currentIcon = new Icon();
} else if (Service.TAG.equals(qName)) {
currentService = new Service();
currentService.baseURL = device.baseURL;
} else if (TAG_SEC_CAPABILITY.equals(qName)) { // Samsung MultiScreen Capability
String port = null;
String location = null;
for (int i = 0; i < attributes.getLength(); i++) {
if (TAG_PORT.equals(attributes.getLocalName(i))) {
port = attributes.getValue(i);
}
else if (TAG_LOCATION.equals(attributes.getLocalName(i))) {
location = attributes.getValue(i);
}
}
if (port == null) {
device.serviceURI = String.format("%s%s", device.serviceURI, location);
}
else {
device.serviceURI = String.format("%s:%s%s", device.serviceURI, port, location);
}
}
currentValue = null;
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
/* Parse device-specific information */
if (TAG_DEVICE_TYPE.equals(qName)) {
device.deviceType = currentValue;
} else if (TAG_FRIENDLY_NAME.equals(qName)) {
device.friendlyName = currentValue;
} else if (TAG_MANUFACTURER.equals(qName)) {
device.manufacturer = currentValue;
// } else if (TAG_MANUFACTURER_URL.equals(qName)) {
// device.manufacturerURL = currentValue;
} else if (TAG_MODEL_DESCRIPTION.equals(qName)) {
device.modelDescription = currentValue;
} else if (TAG_MODEL_NAME.equals(qName)) {
device.modelName = currentValue;
} else if (TAG_MODEL_NUMBER.equals(qName)) {
device.modelNumber = currentValue;
// } else if (TAG_MODEL_URL.equals(qName)) {
// device.modelURL = currentValue;
// } else if (TAG_SERIAL_NUMBER.equals(qName)) {
// device.serialNumber = currentValue;
} else if (TAG_UDN.equals(qName)) {
device.UDN = currentValue;
// } else if (TAG_UPC.equals(qName)) {
// device.UPC = currentValue;
}
// /* Parse icon-list information */
// else if (Icon.TAG_MIME_TYPE.equals(qName)) {
// currentIcon.mimetype = currentValue;
// } else if (Icon.TAG_WIDTH.equals(qName)) {
// currentIcon.width = currentValue;
// } else if (Icon.TAG_HEIGHT.equals(qName)) {
// currentIcon.height = currentValue;
// } else if (Icon.TAG_DEPTH.equals(qName)) {
// currentIcon.depth = currentValue;
// } else if (Icon.TAG_URL.equals(qName)) {
// currentIcon.url = currentValue;
// } else if (Icon.TAG.equals(qName)) {
// device.iconList.add(currentIcon);
// }
/* Parse service-list information */
else if (Service.TAG_SERVICE_TYPE.equals(qName)) {
currentService.serviceType = currentValue;
} else if (Service.TAG_SERVICE_ID.equals(qName)) {
currentService.serviceId = currentValue;
} else if (Service.TAG_SCPD_URL.equals(qName)) {
currentService.SCPDURL = currentValue;
} else if (Service.TAG_CONTROL_URL.equals(qName)) {
currentService.controlURL = currentValue;
} else if (Service.TAG_EVENTSUB_URL.equals(qName)) {
currentService.eventSubURL = currentValue;
} else if (Service.TAG.equals(qName)) {
device.serviceList.add(currentService);
}
data.put(qName, currentValue);
currentValue = null;
}
}
| AspiroTV/Connect-SDK-Android-Core | src/com/connectsdk/discovery/provider/ssdp/SSDPDeviceDescriptionParser.java | Java | apache-2.0 | 6,517 |
/**
* 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 com.datatorrent.lib.util;
import java.util.AbstractMap;
/**
*
* A single KeyValPair for basic data passing, It is a write once, and read often model. <p>
* <br>
* Key and Value are to be treated as immutable objects.
*
* @param <K>
* @param <V>
* @since 0.3.2
*/
public class KeyValPair<K, V> extends AbstractMap.SimpleEntry<K, V>
{
private static final long serialVersionUID = 201301281547L;
/**
* Added default constructor for deserializer.
*/
private KeyValPair()
{
super(null, null);
}
/**
* Constructor
*
* @param k sets key
* @param v sets value
*/
public KeyValPair(K k, V v)
{
super(k, v);
}
}
| PramodSSImmaneni/apex-malhar | library/src/main/java/com/datatorrent/lib/util/KeyValPair.java | Java | apache-2.0 | 1,480 |
//=================================================================================================
/*!
// \file src/mathtest/dmatdmatadd/U3x3bU3x3a.cpp
// \brief Source file for the U3x3bU3x3a dense matrix/dense matrix addition math test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/StaticMatrix.h>
#include <blaze/math/UpperMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatdmatadd/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'U3x3bU3x3a'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
typedef blaze::UpperMatrix< blaze::StaticMatrix<TypeB,3UL,3UL> > U3x3b;
typedef blaze::UpperMatrix< blaze::StaticMatrix<TypeA,3UL,3UL> > U3x3a;
// Creator type definitions
typedef blazetest::Creator<U3x3b> CU3x3b;
typedef blazetest::Creator<U3x3a> CU3x3a;
// Running the tests
RUN_DMATDMATADD_OPERATION_TEST( CU3x3b(), CU3x3a() );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix addition:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| honnibal/blaze-lib | blazetest/src/mathtest/dmatdmatadd/U3x3bU3x3a.cpp | C++ | bsd-3-clause | 3,767 |
#include <exception>
#include <stdio.h>
int throws_exception_on_even (int value);
int intervening_function (int value);
int catches_exception (int value);
int
catches_exception (int value)
{
try
{
return intervening_function(value); // This is the line you should stop at for catch
}
catch (int value)
{
return value;
}
}
int
intervening_function (int value)
{
return throws_exception_on_even (2 * value);
}
int
throws_exception_on_even (int value)
{
printf ("Mod two works: %d.\n", value%2);
if (value % 2 == 0)
throw 30;
else
return value;
}
int
main ()
{
catches_exception (10); // Stop here
return 5;
}
| endlessm/chromium-browser | third_party/llvm/lldb/test/API/lang/cpp/exceptions/exceptions.cpp | C++ | bsd-3-clause | 696 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/host/capture_scheduler.h"
#include <algorithm>
#include "base/logging.h"
#include "base/sys_info.h"
#include "base/time.h"
namespace {
// Number of samples to average the most recent capture and encode time
// over.
const int kStatisticsWindow = 3;
// The hard limit is 20fps or 50ms per recording cycle.
const int64 kMinimumRecordingDelay = 50;
// Controls how much CPU time we can use for encode and capture.
// Range of this value is between 0 to 1. 0 means using 0% of of all CPUs
// available while 1 means using 100% of all CPUs available.
const double kRecordingCpuConsumption = 0.5;
} // namespace
namespace remoting {
// We assume that the number of available cores is constant.
CaptureScheduler::CaptureScheduler()
: num_of_processors_(base::SysInfo::NumberOfProcessors()),
capture_time_(kStatisticsWindow),
encode_time_(kStatisticsWindow) {
DCHECK(num_of_processors_);
}
CaptureScheduler::~CaptureScheduler() {
}
base::TimeDelta CaptureScheduler::NextCaptureDelay() {
// Delay by an amount chosen such that if capture and encode times
// continue to follow the averages, then we'll consume the target
// fraction of CPU across all cores.
double delay =
(capture_time_.Average() + encode_time_.Average()) /
(kRecordingCpuConsumption * num_of_processors_);
if (delay < kMinimumRecordingDelay)
return base::TimeDelta::FromMilliseconds(kMinimumRecordingDelay);
return base::TimeDelta::FromMilliseconds(delay);
}
void CaptureScheduler::RecordCaptureTime(base::TimeDelta capture_time) {
capture_time_.Record(capture_time.InMilliseconds());
}
void CaptureScheduler::RecordEncodeTime(base::TimeDelta encode_time) {
encode_time_.Record(encode_time.InMilliseconds());
}
} // namespace remoting
| zcbenz/cefode-chromium | remoting/host/capture_scheduler.cc | C++ | bsd-3-clause | 1,951 |
require 'optparse'
require 'stringio'
module Spec
module Runner
class OptionParser < ::OptionParser
class << self
def parse(args, err, out)
parser = new(err, out)
parser.parse(args)
parser.options
end
def spec_command?
$0.split('/').last == 'spec'
end
end
attr_reader :options
OPTIONS = {
:pattern => ["-p", "--pattern [PATTERN]","Limit files loaded to those matching this pattern. Defaults to '**/*_spec.rb'",
"Separate multiple patterns with commas.",
"Applies only to directories named on the command line (files",
"named explicitly on the command line will be loaded regardless)."],
:diff => ["-D", "--diff [FORMAT]","Show diff of objects that are expected to be equal when they are not",
"Builtin formats: unified|u|context|c",
"You can also specify a custom differ class",
"(in which case you should also specify --require)"],
:colour => ["-c", "--colour", "--color", "Show coloured (red/green) output"],
:example => ["-e", "--example [NAME|FILE_NAME]", "Execute example(s) with matching name(s). If the argument is",
"the path to an existing file (typically generated by a previous",
"run using --format failing_examples:file.txt), then the examples",
"on each line of that file will be executed. If the file is empty,",
"all examples will be run (as if --example was not specified).",
" ",
"If the argument is not an existing file, then it is treated as",
"an example name directly, causing RSpec to run just the example",
"matching that name"],
:specification => ["-s", "--specification [NAME]", "DEPRECATED - use -e instead", "(This will be removed when autotest works with -e)"],
:line => ["-l", "--line LINE_NUMBER", Integer, "Execute example group or example at given line.",
"(does not work for dynamically generated examples)"],
:format => ["-f", "--format FORMAT[:WHERE]","Specifies what format to use for output. Specify WHERE to tell",
"the formatter where to write the output. All built-in formats",
"expect WHERE to be a file name, and will write to $stdout if it's",
"not specified. The --format option may be specified several times",
"if you want several outputs",
" ",
"Builtin formats:",
"silent|l : No output", "progress|p : Text-based progress bar",
"profile|o : Text-based progress bar with profiling of 10 slowest examples",
"specdoc|s : Code example doc strings",
"nested|n : Code example doc strings with nested groups indented",
"html|h : A nice HTML report",
"failing_examples|e : Write all failing examples - input for --example",
"failing_example_groups|g : Write all failing example groups - input for --example",
" ",
"FORMAT can also be the name of a custom formatter class",
"(in which case you should also specify --require to load it)"],
:require => ["-r", "--require FILE", "Require FILE before running specs",
"Useful for loading custom formatters or other extensions.",
"If this option is used it must come before the others"],
:backtrace => ["-b", "--backtrace", "Output full backtrace"],
:loadby => ["-L", "--loadby STRATEGY", "Specify the strategy by which spec files should be loaded.",
"STRATEGY can currently only be 'mtime' (File modification time)",
"By default, spec files are loaded in alphabetical order if --loadby",
"is not specified."],
:reverse => ["-R", "--reverse", "Run examples in reverse order"],
:timeout => ["-t", "--timeout FLOAT", "Interrupt and fail each example that doesn't complete in the",
"specified time"],
:heckle => ["-H", "--heckle CODE", "If all examples pass, this will mutate the classes and methods",
"identified by CODE little by little and run all the examples again",
"for each mutation. The intent is that for each mutation, at least",
"one example *should* fail, and RSpec will tell you if this is not the",
"case. CODE should be either Some::Module, Some::Class or",
"Some::Fabulous#method}"],
:dry_run => ["-d", "--dry-run", "Invokes formatters without executing the examples."],
:options_file => ["-O", "--options PATH", "Read options from a file"],
:generate_options => ["-G", "--generate-options PATH", "Generate an options file for --options"],
:runner => ["-U", "--runner RUNNER", "Use a custom Runner."],
:debug => ["-u", "--debugger", "Enable ruby-debugging."],
:drb => ["-X", "--drb", "Run examples via DRb. (For example against script/spec_server)"],
:drb_port => ["--port PORT", "Port for DRb server. (Ignored without --drb)"],
:version => ["-v", "--version", "Show version"],
:help => ["-h", "--help", "You're looking at it"]
}
def initialize(err, out)
super()
@error_stream = err
@out_stream = out
@options = Options.new(@error_stream, @out_stream)
@file_factory = File
self.banner = "Usage: spec (FILE(:LINE)?|DIRECTORY|GLOB)+ [options]"
self.separator ""
on(*OPTIONS[:pattern]) {|pattern| @options.filename_pattern = pattern}
on(*OPTIONS[:diff]) {|diff| @options.parse_diff(diff)}
on(*OPTIONS[:colour]) {@options.colour = true}
on(*OPTIONS[:example]) {|example| @options.parse_example(example)}
on(*OPTIONS[:specification]) {|example| @options.parse_example(example)}
on(*OPTIONS[:line]) {|line_number| @options.line_number = line_number.to_i}
on(*OPTIONS[:format]) {|format| @options.parse_format(format)}
on(*OPTIONS[:require]) {|requires| invoke_requires(requires)}
on(*OPTIONS[:backtrace]) {@options.backtrace_tweaker = NoisyBacktraceTweaker.new}
on(*OPTIONS[:loadby]) {|loadby| @options.loadby = loadby}
on(*OPTIONS[:reverse]) {@options.reverse = true}
on(*OPTIONS[:timeout]) {|timeout| @options.timeout = timeout.to_f}
on(*OPTIONS[:heckle]) {|heckle| @options.load_heckle_runner(heckle)}
on(*OPTIONS[:dry_run]) {@options.dry_run = true}
on(*OPTIONS[:options_file]) {|options_file|}
on(*OPTIONS[:generate_options]) {|options_file|}
on(*OPTIONS[:runner]) {|runner| @options.user_input_for_runner = runner}
on(*OPTIONS[:debug]) {@options.debug = true}
on(*OPTIONS[:drb]) {}
on(*OPTIONS[:drb_port]) {|port| @options.drb_port = port}
on(*OPTIONS[:version]) {parse_version}
on("--autospec") {@options.autospec = true}
on_tail(*OPTIONS[:help]) {parse_help}
end
def order!(argv, &blk)
@argv = argv.dup
@argv = (@argv.empty? & self.class.spec_command?) ? ['--help'] : @argv
# Parse options file first
parse_file_options(:options_file, :parse_options_file)
@options.argv = @argv.dup
return if parse_file_options(:generate_options, :write_options_file)
return if parse_drb
super(@argv) do |file|
if file =~ /^(.+):(\d+)$/
file = $1
@options.line_number = $2.to_i
end
@options.files << file
blk.call(file) if blk
end
@options
end
protected
def invoke_requires(requires)
requires.split(",").each do |file|
require file
end
end
def parse_file_options(option_name, action)
# Remove the file option and the argument before handling the file
options_file = nil
options_list = OPTIONS[option_name][0..1]
options_list[1].gsub!(" PATH", "")
options_list.each do |option|
if index = @argv.index(option)
@argv.delete_at(index)
options_file = @argv.delete_at(index)
end
end
if options_file.nil? &&
File.exist?('spec/spec.opts') &&
!@argv.any?{|a| a =~ /^\-/ }
options_file = 'spec/spec.opts'
end
if options_file
send(action, options_file)
return true
else
return false
end
end
def parse_options_file(options_file)
option_file_args = File.readlines(options_file).map {|l| l.chomp.split " "}.flatten
@argv.push(*option_file_args)
end
def write_options_file(options_file)
File.open(options_file, 'w') do |io|
io.puts @argv.join("\n")
end
@out_stream.puts "\nOptions written to #{options_file}. You can now use these options with:"
@out_stream.puts "spec --options #{options_file}"
@options.examples_should_not_be_run
end
def parse_drb
argv = @options.argv
is_drb = false
is_drb ||= argv.delete(OPTIONS[:drb][0])
is_drb ||= argv.delete(OPTIONS[:drb][1])
return false unless is_drb
if DrbCommandLine.run(self.class.parse(argv, @error_stream, @out_stream))
@options.examples_should_not_be_run
true
else
@error_stream.puts "Running specs locally:"
false
end
end
def parse_version
@out_stream.puts ::Spec::VERSION::SUMMARY
exit if stdout?
end
def parse_help
@out_stream.puts self
exit if stdout?
end
def stdout?
@out_stream == $stdout
end
end
end
end
| dnclabs/lockbox | vendor/plugins/rspec/lib/spec/runner/option_parser.rb | Ruby | bsd-3-clause | 11,779 |
// 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 System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
namespace System.Reflection.TypeLoading.Ecma
{
/// <summary>
/// Base class for all Module objects created by a MetadataLoadContext and get its metadata from a PEReader.
/// </summary>
internal sealed partial class EcmaModule
{
internal unsafe InternalManifestResourceInfo GetInternalManifestResourceInfo(string resourceName)
{
MetadataReader reader = Reader;
InternalManifestResourceInfo result = new InternalManifestResourceInfo();
ManifestResourceHandleCollection manifestResources = reader.ManifestResources;
foreach (ManifestResourceHandle resourceHandle in manifestResources)
{
ManifestResource resource = resourceHandle.GetManifestResource(reader);
if (resource.Name.Equals(resourceName, reader))
{
result.Found = true;
if (resource.Implementation.IsNil)
{
checked
{
// Embedded data resource
result.ResourceLocation = ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile;
PEReader pe = _guardedPEReader.PEReader;
PEMemoryBlock resourceDirectory = pe.GetSectionData(pe.PEHeaders.CorHeader.ResourcesDirectory.RelativeVirtualAddress);
BlobReader blobReader = resourceDirectory.GetReader((int)resource.Offset, resourceDirectory.Length - (int)resource.Offset);
uint length = blobReader.ReadUInt32();
result.PointerToResource = blobReader.CurrentPointer;
// Length check the size of the resource to ensure it fits in the PE file section, note, this is only safe as its in a checked region
if (length + sizeof(int) > blobReader.Length)
throw new BadImageFormatException();
result.SizeOfResource = length;
}
}
else
{
if (resource.Implementation.Kind == HandleKind.AssemblyFile)
{
// Get file name
result.ResourceLocation = default;
AssemblyFile file = ((AssemblyFileHandle)resource.Implementation).GetAssemblyFile(reader);
result.FileName = file.Name.GetString(reader);
if (file.ContainsMetadata)
{
EcmaModule module = (EcmaModule)Assembly.GetModule(result.FileName);
if (module == null)
throw new BadImageFormatException(SR.Format(SR.ManifestResourceInfoReferencedBadModule, result.FileName));
result = module.GetInternalManifestResourceInfo(resourceName);
}
}
else if (resource.Implementation.Kind == HandleKind.AssemblyReference)
{
// Resolve assembly reference
result.ResourceLocation = ResourceLocation.ContainedInAnotherAssembly;
RoAssemblyName destinationAssemblyName = ((AssemblyReferenceHandle)resource.Implementation).ToRoAssemblyName(reader);
result.ReferencedAssembly = Loader.ResolveAssembly(destinationAssemblyName);
}
}
}
}
return result;
}
}
}
| ViktorHofer/corefx | src/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Modules/Ecma/EcmaModule.ManifestResources.cs | C# | mit | 4,067 |
var _ = require('underscore');
var os = require('os');
var utils = require('./utils.js');
/* Meteor's current architecture scheme defines the following virtual
* machine types, which are defined by specifying what is promised by
* the host enviroment:
*
* browser.w3c
* A web browser compliant with modern standards. This is
* intentionally a broad definition. In the coming years, as web
* standards evolve, we will likely tighten it up.
*
* browser.ie[678]
* Old versions of Internet Explorer (not sure yet exactly which
* versions to distinguish -- maybe 6 and 8?)
*
* os.linux.x86_32
* os.linux.x86_64
* Linux on Intel x86 architecture. x86_64 means a system that can
* run 64-bit images, furnished with 64-bit builds of shared
* libraries (there is no guarantee that 32-bit builds of shared
* libraries will be available). x86_32 means a system that can run
* 32-bit images, furnished with 32-bit builds of shared libraries.
* Additionally, if a package contains shared libraries (for use by
* other packages), then if the package is built for x86_64, it
* should contain a 64-bit version of the library, and likewise for
* 32-bit.
*
* Operationally speaking, if you worked at it, under this
* definition it would be possible to build a Linux system that can
* run both x86_64 and x86_32 images (eg, by using a 64-bit kernel
* and making sure that both versions of all relevant libraries were
* installed). But we require such a host to decide whether it is
* x86_64 or x86_32, and stick with it. You can't load a combination
* of packages from each and expect them to work together, because
* if they contain shared libraries they all need to have the same
* architecture.
*
* Basically the punchline is: if you installed the 32-bit version
* of Ubuntu, you've got a os.linux.x86_32 system and you will
* use exclusively os.linux.x86_32 packages, and likewise
* 64-bit. They are two parallel universes and which one you're in
* is determined by which version of Red Hat or Ubuntu you
* installed.
*
* os.osx.x86_64
* OS X (technically speaking, Darwin) on Intel x86 architecture,
* with a kernel capable of loading 64-bit images, and 64-bit builds
* of shared libraries available. If a os.osx.x86_64 package
* contains a shared library, it is only required to provide a
* 64-bit version of the library (it is not required to provide a
* fat binary with both 32-bit and 64-bit builds).
*
* Note that in modern Darwin, both the 32 and 64 bit versions of
* the kernel can load 64-bit images, and the Apple-supplied shared
* libraries are fat binaries that include both 32-bit and 64-bit
* builds in a single file. So it is technically fine (but
* discouraged) for a os.osx.x86_64 to include a 32-bit
* executable, if it only uses the system's shared libraries, but
* you'll run into problems if shared libraries from other packages
* are used.
*
* There is no os.osx.x86_32. Our experience is that such
* hardware is virtually extinct. Meteor has never supported it and
* nobody has asked for it.
*
* os.windows.x86_32
* This is 32 and 64 bit Windows. It seems like there is not much of
* a benefit to using 64 bit Node on Windows, and 32 bit works properly
* even on 64 bit systems.
*
* To be (more but far from completely) precise, the ABI for os.*
* architectures includes a CPU type, a mode in which the code will be
* run (eg, 64 bit), an executable file format (eg, ELF), a promise to
* make any shared libraries available in a particular architecture,
* and promise to set up the shared library search path
* "appropriately". In the future it will also include some guarantees
* about the directory layout in the environment, eg, location of a
* directory where temporary files may be freely written. It does not
* include any syscalls (beyond those used by code that customarily is
* statically linked into every executable built on a platform, eg,
* exit(2)). It does not guarantee the presence of any particular
* shared libraries or programs (including any particular shell or
* traditional tools like 'grep' or 'find').
*
* To model the shared libraries that are required on a system (and
* the particular versions that are required), and to model
* dependencies on command-line programs like 'bash' and 'grep', the
* idea is to have a package named something like 'posix-base' that
* rolls up a reasonable base environment (including such modern
* niceties as libopenssl) and is supplied by the container. This
* allows it to be versioned, unlike architectures, which we hope to
* avoid versioning.
*
* Q: What does "x86" mean?
* A: It refers to the traditional Intel architecture, which
* originally surfaced in CPUs such as the 8086 and the 80386. Those
* of us who are older should remember that the last time that Intel
* used this branding was the 80486, introduced in 1989, and that
* today, parts that use this architecture bear names like "Core",
* "Atom", and "Phenom", with no "86" it sight. We use it in the
* architecture name anyway because we don't want to depart too far
* from Linux's architecture names.
*
* Q: Why do we call it "x86_32" instead of the customary "i386" or
* "i686"?
* A: We wanted to have one name for 32-bit and one name for 64-bit,
* rather than several names for each that are virtual synonyms for
* each (eg, x86_64 vs amd64 vs ia64, i386 vs i686 vs x86). For the
* moment anyway, we're willing to adopt a "one size fits all"
* attitude to get there (no ability to have separate builds for 80386
* CPUs that don't support Pentium Pro extensions, for example --
* you'll have to do runtime detection if you need that). And as long
* as we have to pick a name, we wanted to pick one that was super
* clear (it is not obvious to many people that "i686" means "32-bit
* Intel", because why should it be?) and didn't imply too close of an
* equivalence to the precise meanings that other platforms may assign
* to some of these strings.
*/
// Returns the fully qualified arch of this host -- something like
// "os.linux.x86_32" or "os.osx.x86_64". Must be called inside
// a fiber. Throws an error if it's not a supported architecture.
//
// If you change this, also change scripts/admin/launch-meteor
var _host = null; // memoize
var host = function () {
if (! _host) {
var run = function (...args) {
var result = utils.execFileSync(args[0], args.slice(1)).stdout;
if (! result) {
throw new Error("can't get arch with " + args.join(" ") + "?");
}
return result.replace(/\s*$/, ''); // trailing whitespace
};
var platform = os.platform();
if (platform === "darwin") {
// Can't just test uname -m = x86_64, because Snow Leopard can
// return other values.
if (run('uname', '-p') !== "i386" ||
run('sysctl', '-n', 'hw.cpu64bit_capable') !== "1") {
throw new Error("Only 64-bit Intel processors are supported on OS X");
}
_host = "os.osx.x86_64";
}
else if (platform === "linux") {
var machine = run('uname', '-m');
if (_.contains(["i386", "i686", "x86"], machine)) {
_host = "os.linux.x86_32";
} else if (_.contains(["x86_64", "amd64", "ia64"], machine)) {
_host = "os.linux.x86_64";
} else {
throw new Error("Unsupported architecture: " + machine);
}
}
else if (platform === "win32") {
// We also use 32 bit builds on 64 bit Windows architectures.
_host = "os.windows.x86_32";
} else {
throw new Error("Unsupported operating system: " + platform);
}
}
return _host;
};
// True if `host` (an architecture name such as 'os.linux.x86_64') can run
// programs of architecture `program` (which might be something like 'os',
// 'os.linux', or 'os.linux.x86_64').
//
// `host` and `program` are just mnemonics -- `host` does not
// necessariy have to be a fully qualified architecture name. This
// function just checks to see if `program` describes a set of
// enviroments that is a (non-strict) superset of `host`.
var matches = function (host, program) {
return host.substr(0, program.length) === program &&
(host.length === program.length ||
host.substr(program.length, 1) === ".");
};
// Like `supports`, but instead taken an array of possible
// architectures as its second argument. Returns the most specific
// match, or null if none match. Throws an error if `programs`
// contains exact duplicates.
var mostSpecificMatch = function (host, programs) {
var seen = {};
var best = null;
_.each(programs, function (p) {
if (seen[p]) {
throw new Error("Duplicate architecture: " + p);
}
seen[p] = true;
if (archinfo.matches(host, p) &&
(! best || p.length > best.length)) {
best = p;
}
});
return best;
};
// `programs` is a set of architectures (as an array of string, which
// may contain duplicates). Determine if there exists any architecture
// that is compatible with all of the architectures in the set. If so,
// returns the least specific such architecture. Otherwise (the
// architectures are disjoin) raise an exception.
//
// For example, for 'os' and 'os.osx', return 'os.osx'. For 'os' and
// 'os.linux.x86_64', return 'os.linux.x86_64'. For 'os' and 'browser', throw an
// exception.
var leastSpecificDescription = function (programs) {
if (programs.length === 0) {
return '';
}
// Find the longest string
var longest = _.max(programs, function (p) { return p.length; });
// If everything else in the list is compatible with the longest,
// then it must be the most specific, and if everything is
// compatible with the most specific then it must be the least
// specific compatible description.
_.each(programs, function (p) {
if (! archinfo.matches(longest, p)) {
throw new Error("Incompatible architectures: '" + p + "' and '" +
longest + "'");
}
});
return longest;
};
var withoutSpecificOs = function (arch) {
if (arch.substr(0, 3) === 'os.') {
return 'os';
}
return arch;
};
var archinfo = exports;
_.extend(archinfo, {
host: host,
matches: matches,
mostSpecificMatch: mostSpecificMatch,
leastSpecificDescription: leastSpecificDescription,
withoutSpecificOs: withoutSpecificOs
});
| lpinto93/meteor | tools/utils/archinfo.js | JavaScript | mit | 10,422 |
# Ansible module to manage CheckPoint Firewall (c) 2019
#
# 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/>.
#
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import pytest
from units.modules.utils import set_module_args, exit_json, fail_json, AnsibleExitJson
from ansible.module_utils import basic
from ansible.modules.network.check_point import cp_mgmt_time_facts
OBJECT = {
"from": 1,
"to": 1,
"total": 6,
"objects": [
"53de74b7-8f19-4cbe-99fc-a81ef0759bad"
]
}
SHOW_PLURAL_PAYLOAD = {
'limit': 1,
'details_level': 'uid'
}
SHOW_SINGLE_PAYLOAD = {
'name': 'object_which_is_not_exist'
}
api_call_object = 'time'
api_call_object_plural_version = 'times'
failure_msg = '''{u'message': u'Requested object [object_which_is_not_exist] not found', u'code': u'generic_err_object_not_found'}'''
class TestCheckpointTimeFacts(object):
module = cp_mgmt_time_facts
@pytest.fixture(autouse=True)
def module_mock(self, mocker):
return mocker.patch.multiple(basic.AnsibleModule, exit_json=exit_json, fail_json=fail_json)
@pytest.fixture
def connection_mock(self, mocker):
connection_class_mock = mocker.patch('ansible.module_utils.network.checkpoint.checkpoint.Connection')
return connection_class_mock.return_value
def test_show_single_object_which_is_not_exist(self, mocker, connection_mock):
connection_mock.send_request.return_value = (404, failure_msg)
try:
result = self._run_module(SHOW_SINGLE_PAYLOAD)
except Exception as e:
result = e.args[0]
assert result['failed']
assert 'Checkpoint device returned error 404 with message ' + failure_msg == result['msg']
def test_show_few_objects(self, mocker, connection_mock):
connection_mock.send_request.return_value = (200, OBJECT)
result = self._run_module(SHOW_PLURAL_PAYLOAD)
assert not result['changed']
assert OBJECT == result['ansible_facts'][api_call_object_plural_version]
def _run_module(self, module_args):
set_module_args(module_args)
with pytest.raises(AnsibleExitJson) as ex:
self.module.main()
return ex.value.args[0]
| thaim/ansible | test/units/modules/network/check_point/test_cp_mgmt_time_facts.py | Python | mit | 2,820 |
module.exports = {
justNow: "ligenu",
secondsAgo: "{{time}} sekunder siden",
aMinuteAgo: "et minut siden",
minutesAgo: "{{time}} minutter siden",
anHourAgo: "en time siden",
hoursAgo: "{{time}} timer siden",
aDayAgo: "i går",
daysAgo: "{{time}} dage siden",
aWeekAgo: "en uge siden",
weeksAgo: "{{time}} uger siden",
aMonthAgo: "en måned siden",
monthsAgo: "{{time}} måneder siden",
aYearAgo: "et år siden",
yearsAgo: "{{time}} år siden",
overAYearAgo: "over et år siden",
secondsFromNow: "om {{time}} sekunder",
aMinuteFromNow: "om et minut",
minutesFromNow: "om {{time}} minutter",
anHourFromNow: "om en time",
hoursFromNow: "om {{time}} timer",
aDayFromNow: "i morgen",
daysFromNow: "om {{time}} dage",
aWeekFromNow: "om en uge",
weeksFromNow: "om {{time}} uger",
aMonthFromNow: "om en måned",
monthsFromNow: "om {{time}} måneder",
aYearFromNow: "om et år",
yearsFromNow: "om {{time}} år",
overAYearFromNow: "om over et år"
}
| joegesualdo/dotfiles | npm-global/lib/node_modules/npm/node_modules/tiny-relative-date/translations/da.js | JavaScript | mit | 998 |
<?php
/*
* This file is part of the Assetic package, an OpenSky project.
*
* (c) 2010-2011 OpenSky Project Inc
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Assetic\Asset;
use Assetic\Filter\FilterInterface;
/**
* An asset has a mutable URL and content and can be loaded and dumped.
*
* @author Kris Wallsmith <kris.wallsmith@gmail.com>
*/
interface AssetInterface
{
/**
* Ensures the current asset includes the supplied filter.
*
* @param FilterInterface $filter A filter
*/
function ensureFilter(FilterInterface $filter);
/**
* Returns an array of filters currently applied.
*
* @return array An array of filters
*/
function getFilters();
/**
* Loads the asset into memory and applies load filters.
*
* You may provide an additional filter to apply during load.
*
* @param FilterInterface $additionalFilter An additional filter
*/
function load(FilterInterface $additionalFilter = null);
/**
* Applies dump filters and returns the asset as a string.
*
* You may provide an additional filter to apply during dump.
*
* Dumping an asset should not change its state.
*
* If the current asset has not been loaded yet, it should be
* automatically loaded at this time.
*
* @param FilterInterface $additionalFilter An additional filter
*
* @return string The filtered content of the current asset
*/
function dump(FilterInterface $additionalFilter = null);
/**
* Returns the loaded content of the current asset.
*
* @return string The content
*/
function getContent();
/**
* Sets the content of the current asset.
*
* Filters can use this method to change the content of the asset.
*
* @param string $content The asset content
*/
function setContent($content);
/**
* Returns an absolute path or URL to the source asset's root directory.
*
* This value should be an absolute path to a directory in the filesystem,
* an absolute URL with no path, or null.
*
* For example:
*
* * '/path/to/web'
* * 'http://example.com'
* * null
*
* @return string|null The asset's root
*/
function getSourceRoot();
/**
* Returns the relative path for the source asset.
*
* This value can be combined with the asset's source root (if both are
* non-null) to get something compatible with file_get_contents().
*
* For example:
*
* * 'js/main.js'
* * 'main.js'
* * null
*
* @return string|null The source asset path
*/
function getSourcePath();
/**
* Returns the URL for the current asset.
*
* @return string|null A web URL where the asset will be dumped
*/
function getTargetPath();
/**
* Sets the URL for the current asset.
*
* @param string $targetPath A web URL where the asset will be dumped
*/
function setTargetPath($targetPath);
/**
* Returns the time the current asset was last modified.
*
* @return integer|null A UNIX timestamp
*/
function getLastModified();
}
| VelvetMirror/doctrine | vendor/assetic/src/Assetic/Asset/AssetInterface.php | PHP | mit | 3,333 |
// 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 System.Collections;
using System.Globalization;
using System.Net.NetworkInformation;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
namespace System.Net
{
[Serializable]
public class WebProxy : IWebProxy, ISerializable
{
private ArrayList _bypassList;
private Regex[] _regExBypassList;
public WebProxy() : this((Uri)null, false, null, null) { }
public WebProxy(Uri Address) : this(Address, false, null, null) { }
public WebProxy(Uri Address, bool BypassOnLocal) : this(Address, BypassOnLocal, null, null) { }
public WebProxy(Uri Address, bool BypassOnLocal, string[] BypassList) : this(Address, BypassOnLocal, BypassList, null) { }
public WebProxy(Uri Address, bool BypassOnLocal, string[] BypassList, ICredentials Credentials)
{
this.Address = Address;
this.Credentials = Credentials;
this.BypassProxyOnLocal = BypassOnLocal;
if (BypassList != null)
{
_bypassList = new ArrayList(BypassList);
UpdateRegExList(true);
}
}
public WebProxy(string Host, int Port)
: this(new Uri("http://" + Host + ":" + Port.ToString(CultureInfo.InvariantCulture)), false, null, null)
{
}
public WebProxy(string Address)
: this(CreateProxyUri(Address), false, null, null)
{
}
public WebProxy(string Address, bool BypassOnLocal)
: this(CreateProxyUri(Address), BypassOnLocal, null, null)
{
}
public WebProxy(string Address, bool BypassOnLocal, string[] BypassList)
: this(CreateProxyUri(Address), BypassOnLocal, BypassList, null)
{
}
public WebProxy(string Address, bool BypassOnLocal, string[] BypassList, ICredentials Credentials)
: this(CreateProxyUri(Address), BypassOnLocal, BypassList, Credentials)
{
}
public Uri Address { get; set; }
public bool BypassProxyOnLocal { get; set; }
public string[] BypassList
{
get { return _bypassList != null ? (string[])_bypassList.ToArray(typeof(string)) : Array.Empty<string>(); }
set
{
_bypassList = new ArrayList(value);
UpdateRegExList(true);
}
}
public ArrayList BypassArrayList => _bypassList ?? (_bypassList = new ArrayList());
public ICredentials Credentials { get; set; }
public bool UseDefaultCredentials
{
get { return Credentials == CredentialCache.DefaultCredentials; }
set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
}
public Uri GetProxy(Uri destination)
{
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
return IsBypassed(destination) ? destination : Address;
}
private static Uri CreateProxyUri(string address) =>
address == null ? null :
address.IndexOf("://") == -1 ? new Uri("http://" + address) :
new Uri(address);
private void UpdateRegExList(bool canThrow)
{
Regex[] regExBypassList = null;
ArrayList bypassList = _bypassList;
try
{
if (bypassList != null && bypassList.Count > 0)
{
regExBypassList = new Regex[bypassList.Count];
for (int i = 0; i < bypassList.Count; i++)
{
regExBypassList[i] = new Regex((string)bypassList[i], RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
}
}
}
catch
{
if (!canThrow)
{
_regExBypassList = null;
return;
}
throw;
}
// Update field here, as it could throw earlier in the loop
_regExBypassList = regExBypassList;
}
private bool IsMatchInBypassList(Uri input)
{
UpdateRegExList(false);
if (_regExBypassList != null)
{
string matchUriString = input.IsDefaultPort ?
input.Scheme + "://" + input.Host :
input.Scheme + "://" + input.Host + ":" + input.Port.ToString();
foreach (Regex r in _regExBypassList)
{
if (r.IsMatch(matchUriString))
{
return true;
}
}
}
return false;
}
private bool IsLocal(Uri host)
{
string hostString = host.Host;
IPAddress hostAddress;
if (IPAddress.TryParse(hostString, out hostAddress))
{
return IPAddress.IsLoopback(hostAddress) || IsAddressLocal(hostAddress);
}
// No dot? Local.
int dot = hostString.IndexOf('.');
if (dot == -1)
{
return true;
}
// If it matches the primary domain, it's local. (Whether or not the hostname matches.)
string local = "." + IPGlobalProperties.GetIPGlobalProperties().DomainName;
return
local.Length == (hostString.Length - dot) &&
string.Compare(local, 0, hostString, dot, local.Length, StringComparison.OrdinalIgnoreCase) == 0;
}
private static bool IsAddressLocal(IPAddress ipAddress)
{
// Perf note: The .NET Framework caches this and then uses network change notifications to track
// whether the set should be recomputed. We could consider doing the same if this is observed as
// a bottleneck, but that tracking has its own costs.
IPAddress[] localAddresses = Dns.GetHostEntryAsync(Dns.GetHostName()).GetAwaiter().GetResult().AddressList; // TODO: Use synchronous GetHostEntry when available
for (int i = 0; i < localAddresses.Length; i++)
{
if (ipAddress.Equals(localAddresses[i]))
{
return true;
}
}
return false;
}
public bool IsBypassed(Uri host)
{
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
return
Address == null ||
host.IsLoopback ||
(BypassProxyOnLocal && IsLocal(host)) ||
IsMatchInBypassList(host);
}
protected WebProxy(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
BypassProxyOnLocal = serializationInfo.GetBoolean("_BypassOnLocal");
Address = (Uri)serializationInfo.GetValue("_ProxyAddress", typeof(Uri));
_bypassList = (ArrayList)serializationInfo.GetValue("_BypassList", typeof(ArrayList));
UseDefaultCredentials = serializationInfo.GetBoolean("_UseDefaultCredentials");
}
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
GetObjectData(serializationInfo, streamingContext);
}
protected virtual void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
serializationInfo.AddValue("_BypassOnLocal", BypassProxyOnLocal);
serializationInfo.AddValue("_ProxyAddress", Address);
serializationInfo.AddValue("_BypassList", _bypassList);
serializationInfo.AddValue("_UseDefaultCredentials", UseDefaultCredentials);
}
[Obsolete("This method has been deprecated. Please use the proxy selected for you by default. http://go.microsoft.com/fwlink/?linkid=14202")]
public static WebProxy GetDefaultProxy()
{
// The .NET Framework here returns a proxy that fetches IE settings and
// executes JavaScript to determine the correct proxy.
throw new PlatformNotSupportedException();
}
}
}
| Petermarcu/corefx | src/System.Net.WebProxy/src/System/Net/WebProxy.cs | C# | mit | 8,613 |
<?php
namespace Drupal\Core;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Utility\UnroutedUrlAssemblerInterface;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Defines an object that holds information about a URL.
*/
class Url {
use DependencySerializationTrait;
/**
* The URL generator.
*
* @var \Drupal\Core\Routing\UrlGeneratorInterface
*/
protected $urlGenerator;
/**
* The unrouted URL assembler.
*
* @var \Drupal\Core\Utility\UnroutedUrlAssemblerInterface
*/
protected $urlAssembler;
/**
* The access manager
*
* @var \Drupal\Core\Access\AccessManagerInterface
*/
protected $accessManager;
/**
* The route name.
*
* @var string
*/
protected $routeName;
/**
* The route parameters.
*
* @var array
*/
protected $routeParameters = array();
/**
* The URL options.
*
* See \Drupal\Core\Url::fromUri() for details on the options.
*
* @var array
*/
protected $options = array();
/**
* Indicates whether this object contains an external URL.
*
* @var bool
*/
protected $external = FALSE;
/**
* Indicates whether this URL is for a URI without a Drupal route.
*
* @var bool
*/
protected $unrouted = FALSE;
/**
* The non-route URI.
*
* Only used if self::$unrouted is TRUE.
*
* @var string
*/
protected $uri;
/**
* Stores the internal path, if already requested by getInternalPath().
*
* @var string
*/
protected $internalPath;
/**
* Constructs a new Url object.
*
* In most cases, use Url::fromRoute() or Url::fromUri() rather than
* constructing Url objects directly in order to avoid ambiguity and make your
* code more self-documenting.
*
* @param string $route_name
* The name of the route
* @param array $route_parameters
* (optional) An associative array of parameter names and values.
* @param array $options
* See \Drupal\Core\Url::fromUri() for details.
*
* @see static::fromRoute()
* @see static::fromUri()
*
* @todo Update this documentation for non-routed URIs in
* https://www.drupal.org/node/2346787
*/
public function __construct($route_name, $route_parameters = array(), $options = array()) {
$this->routeName = $route_name;
$this->routeParameters = $route_parameters;
$this->options = $options;
}
/**
* Creates a new Url object for a URL that has a Drupal route.
*
* This method is for URLs that have Drupal routes (that is, most pages
* generated by Drupal). For non-routed local URIs relative to the base
* path (like robots.txt) use Url::fromUri() with the base: scheme.
*
* @param string $route_name
* The name of the route
* @param array $route_parameters
* (optional) An associative array of route parameter names and values.
* @param array $options
* See \Drupal\Core\Url::fromUri() for details.
*
* @return \Drupal\Core\Url
* A new Url object for a routed (internal to Drupal) URL.
*
* @see \Drupal\Core\Url::fromUserInput()
* @see \Drupal\Core\Url::fromUri()
*/
public static function fromRoute($route_name, $route_parameters = array(), $options = array()) {
return new static($route_name, $route_parameters, $options);
}
/**
* Creates a new URL object from a route match.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match.
*
* @return $this
*/
public static function fromRouteMatch(RouteMatchInterface $route_match) {
if ($route_match->getRouteObject()) {
return new static($route_match->getRouteName(), $route_match->getRawParameters()->all());
}
else {
throw new \InvalidArgumentException('Route required');
}
}
/**
* Creates a Url object for a relative URI reference submitted by user input.
*
* Use this method to create a URL for user-entered paths that may or may not
* correspond to a valid Drupal route.
*
* @param string $user_input
* User input for a link or path. The first character must be one of the
* following characters:
* - '/': A path within the current site. This path might be to a Drupal
* route (e.g., '/admin'), to a file (e.g., '/README.txt'), or to
* something processed by a non-Drupal script (e.g.,
* '/not/a/drupal/page'). If the path matches a Drupal route, then the
* URL generation will include Drupal's path processors (e.g.,
* language-prefixing and aliasing). Otherwise, the URL generation will
* just append the passed-in path to Drupal's base path.
* - '?': A query string for the current page or resource.
* - '#': A fragment (jump-link) on the current page or resource.
* This helps reduce ambiguity for user-entered links and paths, and
* supports user interfaces where users may normally use auto-completion
* to search for existing resources, but also may type one of these
* characters to link to (e.g.) a specific path on the site.
* (With regard to the URI specification, the user input is treated as a
* @link https://tools.ietf.org/html/rfc3986#section-4.2 relative URI reference @endlink
* where the relative part is of type
* @link https://tools.ietf.org/html/rfc3986#section-3.3 path-abempty @endlink.)
* @param array $options
* (optional) An array of options. See Url::fromUri() for details.
*
* @return static
* A new Url object based on user input.
*
* @throws \InvalidArgumentException
* Thrown when the user input does not begin with one of the following
* characters: '/', '?', or '#'.
*/
public static function fromUserInput($user_input, $options = []) {
// Ensuring one of these initial characters also enforces that what is
// passed is a relative URI reference rather than an absolute URI,
// because these are URI reserved characters that a scheme name may not
// start with.
if ((strpos($user_input, '/') !== 0) && (strpos($user_input, '#') !== 0) && (strpos($user_input, '?') !== 0)) {
throw new \InvalidArgumentException("The user-entered string '$user_input' must begin with a '/', '?', or '#'.");
}
// fromUri() requires an absolute URI, so prepend the appropriate scheme
// name.
return static::fromUri('internal:' . $user_input, $options);
}
/**
* Creates a new Url object from a URI.
*
* This method is for generating URLs for URIs that:
* - do not have Drupal routes: both external URLs and unrouted local URIs
* like base:robots.txt
* - do have a Drupal route but have a custom scheme to simplify linking.
* Currently, there is only the entity: scheme (This allows URIs of the
* form entity:{entity_type}/{entity_id}. For example: entity:node/1
* resolves to the entity.node.canonical route with a node parameter of 1.)
*
* For URLs that have Drupal routes (that is, most pages generated by Drupal),
* use Url::fromRoute().
*
* @param string $uri
* The URI of the resource including the scheme. For user input that may
* correspond to a Drupal route, use internal: for the scheme. For paths
* that are known not to be handled by the Drupal routing system (such as
* static files), use base: for the scheme to get a link relative to the
* Drupal base path (like the <base> HTML element). For a link to an entity
* you may use entity:{entity_type}/{entity_id} URIs. The internal: scheme
* should be avoided except when processing actual user input that may or
* may not correspond to a Drupal route. Normally use Url::fromRoute() for
* code linking to any any Drupal page.
* @param array $options
* (optional) An associative array of additional URL options, with the
* following elements:
* - 'query': An array of query key/value-pairs (without any URL-encoding)
* to append to the URL.
* - 'fragment': A fragment identifier (named anchor) to append to the URL.
* Do not include the leading '#' character.
* - 'absolute': Defaults to FALSE. Whether to force the output to be an
* absolute link (beginning with http:). Useful for links that will be
* displayed outside the site, such as in an RSS feed.
* - 'attributes': An associative array of HTML attributes that will be
* added to the anchor tag if you use the \Drupal\Core\Link class to make
* the link.
* - 'language': An optional language object used to look up the alias
* for the URL. If $options['language'] is omitted, it defaults to the
* current language for the language type LanguageInterface::TYPE_URL.
* - 'https': Whether this URL should point to a secure location. If not
* defined, the current scheme is used, so the user stays on HTTP or HTTPS
* respectively. TRUE enforces HTTPS and FALSE enforces HTTP.
*
* @return \Drupal\Core\Url
* A new Url object with properties depending on the URI scheme. Call the
* access() method on this to do access checking.
*
* @throws \InvalidArgumentException
* Thrown when the passed in path has no scheme.
*
* @see \Drupal\Core\Url::fromRoute()
* @see \Drupal\Core\Url::fromUserInput()
*/
public static function fromUri($uri, $options = []) {
// parse_url() incorrectly parses base:number/... as hostname:port/...
// and not the scheme. Prevent that by prefixing the path with a slash.
if (preg_match('/^base:\d/', $uri)) {
$uri = str_replace('base:', 'base:/', $uri);
}
$uri_parts = parse_url($uri);
if ($uri_parts === FALSE) {
throw new \InvalidArgumentException("The URI '$uri' is malformed.");
}
if (empty($uri_parts['scheme'])) {
throw new \InvalidArgumentException("The URI '$uri' is invalid. You must use a valid URI scheme.");
}
$uri_parts += ['path' => ''];
// Discard empty fragment in $options for consistency with parse_url().
if (isset($options['fragment']) && strlen($options['fragment']) == 0) {
unset($options['fragment']);
}
// Extract query parameters and fragment and merge them into $uri_options,
// but preserve the original $options for the fallback case.
$uri_options = $options;
if (isset($uri_parts['fragment'])) {
$uri_options += ['fragment' => $uri_parts['fragment']];
unset($uri_parts['fragment']);
}
if (!empty($uri_parts['query'])) {
$uri_query = [];
parse_str($uri_parts['query'], $uri_query);
$uri_options['query'] = isset($uri_options['query']) ? $uri_options['query'] + $uri_query : $uri_query;
unset($uri_parts['query']);
}
if ($uri_parts['scheme'] === 'entity') {
$url = static::fromEntityUri($uri_parts, $uri_options, $uri);
}
elseif ($uri_parts['scheme'] === 'internal') {
$url = static::fromInternalUri($uri_parts, $uri_options);
}
elseif ($uri_parts['scheme'] === 'route') {
$url = static::fromRouteUri($uri_parts, $uri_options, $uri);
}
else {
$url = new static($uri, array(), $options);
if ($uri_parts['scheme'] !== 'base') {
$url->external = TRUE;
$url->setOption('external', TRUE);
}
$url->setUnrouted();
}
return $url;
}
/**
* Create a new Url object for entity URIs.
*
* @param array $uri_parts
* Parts from an URI of the form entity:{entity_type}/{entity_id} as from
* parse_url().
* @param array $options
* An array of options, see \Drupal\Core\Url::fromUri() for details.
* @param string $uri
* The original entered URI.
*
* @return \Drupal\Core\Url
* A new Url object for an entity's canonical route.
*
* @throws \InvalidArgumentException
* Thrown if the entity URI is invalid.
*/
protected static function fromEntityUri(array $uri_parts, array $options, $uri) {
list($entity_type_id, $entity_id) = explode('/', $uri_parts['path'], 2);
if ($uri_parts['scheme'] != 'entity' || $entity_id === '') {
throw new \InvalidArgumentException("The entity URI '$uri' is invalid. You must specify the entity id in the URL. e.g., entity:node/1 for loading the canonical path to node entity with id 1.");
}
return new static("entity.$entity_type_id.canonical", [$entity_type_id => $entity_id], $options);
}
/**
* Creates a new Url object for 'internal:' URIs.
*
* Important note: the URI minus the scheme can NOT simply be validated by a
* \Drupal\Core\Path\PathValidatorInterface implementation. The semantics of
* the 'internal:' URI scheme are different:
* - PathValidatorInterface accepts paths without a leading slash (e.g.
* 'node/add') as well as 2 special paths: '<front>' and '<none>', which are
* mapped to the correspondingly named routes.
* - 'internal:' URIs store paths with a leading slash that represents the
* root — i.e. the front page — (e.g. 'internal:/node/add'), and doesn't
* have any exceptions.
*
* To clarify, a few examples of path plus corresponding 'internal:' URI:
* - 'node/add' -> 'internal:/node/add'
* - 'node/add?foo=bar' -> 'internal:/node/add?foo=bar'
* - 'node/add#kitten' -> 'internal:/node/add#kitten'
* - '<front>' -> 'internal:/'
* - '<front>foo=bar' -> 'internal:/?foo=bar'
* - '<front>#kitten' -> 'internal:/#kitten'
* - '<none>' -> 'internal:'
* - '<none>foo=bar' -> 'internal:?foo=bar'
* - '<none>#kitten' -> 'internal:#kitten'
*
* Therefore, when using a PathValidatorInterface to validate 'internal:'
* URIs, we must map:
* - 'internal:' (path component is '') to the special '<none>' path
* - 'internal:/' (path component is '/') to the special '<front>' path
* - 'internal:/some-path' (path component is '/some-path') to 'some-path'
*
* @param array $uri_parts
* Parts from an URI of the form internal:{path} as from parse_url().
* @param array $options
* An array of options, see \Drupal\Core\Url::fromUri() for details.
*
* @return \Drupal\Core\Url
* A new Url object for a 'internal:' URI.
*
* @throws \InvalidArgumentException
* Thrown when the URI's path component doesn't have a leading slash.
*/
protected static function fromInternalUri(array $uri_parts, array $options) {
// Both PathValidator::getUrlIfValidWithoutAccessCheck() and 'base:' URIs
// only accept/contain paths without a leading slash, unlike 'internal:'
// URIs, for which the leading slash means "relative to Drupal root" and
// "relative to Symfony app root" (just like in Symfony/Drupal 8 routes).
if (empty($uri_parts['path'])) {
$uri_parts['path'] = '<none>';
}
elseif ($uri_parts['path'] === '/') {
$uri_parts['path'] = '<front>';
}
else {
if ($uri_parts['path'][0] !== '/') {
throw new \InvalidArgumentException("The internal path component '{$uri_parts['path']}' is invalid. Its path component must have a leading slash, e.g. internal:/foo.");
}
// Remove the leading slash.
$uri_parts['path'] = substr($uri_parts['path'], 1);
if (UrlHelper::isExternal($uri_parts['path'])) {
throw new \InvalidArgumentException("The internal path component '{$uri_parts['path']}' is external. You are not allowed to specify an external URL together with internal:/.");
}
}
$url = \Drupal::pathValidator()
->getUrlIfValidWithoutAccessCheck($uri_parts['path']) ?: static::fromUri('base:' . $uri_parts['path'], $options);
// Allow specifying additional options.
$url->setOptions($options + $url->getOptions());
return $url;
}
/**
* Creates a new Url object for 'route:' URIs.
*
* @param array $uri_parts
* Parts from an URI of the form route:{route_name};{route_parameters} as
* from parse_url(), where the path is the route name optionally followed by
* a ";" followed by route parameters in key=value format with & separators.
* @param array $options
* An array of options, see \Drupal\Core\Url::fromUri() for details.
* @param string $uri
* The original passed in URI.
*
* @return \Drupal\Core\Url
* A new Url object for a 'route:' URI.
*
* @throws \InvalidArgumentException
* Thrown when the route URI does not have a route name.
*/
protected static function fromRouteUri(array $uri_parts, array $options, $uri) {
$route_parts = explode(';', $uri_parts['path'], 2);
$route_name = $route_parts[0];
if ($route_name === '') {
throw new \InvalidArgumentException("The route URI '$uri' is invalid. You must have a route name in the URI. e.g., route:system.admin");
}
$route_parameters = [];
if (!empty($route_parts[1])) {
parse_str($route_parts[1], $route_parameters);
}
return new static($route_name, $route_parameters, $options);
}
/**
* Returns the Url object matching a request.
*
* SECURITY NOTE: The request path is not checked to be valid and accessible
* by the current user to allow storing and reusing Url objects by different
* users. The 'path.validator' service getUrlIfValid() method should be used
* instead of this one if validation and access check is desired. Otherwise,
* 'access_manager' service checkNamedRoute() method should be used on the
* router name and parameters stored in the Url object returned by this
* method.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* A request object.
*
* @return static
* A Url object. Warning: the object is created even if the current user
* would get an access denied running the same request via the normal page
* flow.
*
* @throws \Drupal\Core\Routing\MatchingRouteNotFoundException
* Thrown when the request cannot be matched.
*/
public static function createFromRequest(Request $request) {
// We use the router without access checks because URL objects might be
// created and stored for different users.
$result = \Drupal::service('router.no_access_checks')->matchRequest($request);
$route_name = $result[RouteObjectInterface::ROUTE_NAME];
$route_parameters = $result['_raw_variables']->all();
return new static($route_name, $route_parameters);
}
/**
* Sets this Url to encapsulate an unrouted URI.
*
* @return $this
*/
protected function setUnrouted() {
$this->unrouted = TRUE;
// What was passed in as the route name is actually the URI.
// @todo Consider fixing this in https://www.drupal.org/node/2346787.
$this->uri = $this->routeName;
// Set empty route name and parameters.
$this->routeName = NULL;
$this->routeParameters = array();
return $this;
}
/**
* Generates a URI string that represents tha data in the Url object.
*
* The URI will typically have the scheme of route: even if the object was
* constructed using an entity: or internal: scheme. A internal: URI that
* does not match a Drupal route with be returned here with the base: scheme,
* and external URLs will be returned in their original form.
*
* @return string
* A URI representation of the Url object data.
*/
public function toUriString() {
if ($this->isRouted()) {
$uri = 'route:' . $this->routeName;
if ($this->routeParameters) {
$uri .= ';' . UrlHelper::buildQuery($this->routeParameters);
}
}
else {
$uri = $this->uri;
}
$query = !empty($this->options['query']) ? ('?' . UrlHelper::buildQuery($this->options['query'])) : '';
$fragment = isset($this->options['fragment']) && strlen($this->options['fragment']) ? '#' . $this->options['fragment'] : '';
return $uri . $query . $fragment;
}
/**
* Indicates if this Url is external.
*
* @return bool
*/
public function isExternal() {
return $this->external;
}
/**
* Indicates if this Url has a Drupal route.
*
* @return bool
*/
public function isRouted() {
return !$this->unrouted;
}
/**
* Returns the route name.
*
* @return string
*
* @throws \UnexpectedValueException.
* If this is a URI with no corresponding route.
*/
public function getRouteName() {
if ($this->unrouted) {
throw new \UnexpectedValueException('External URLs do not have an internal route name.');
}
return $this->routeName;
}
/**
* Returns the route parameters.
*
* @return array
*
* @throws \UnexpectedValueException.
* If this is a URI with no corresponding route.
*/
public function getRouteParameters() {
if ($this->unrouted) {
throw new \UnexpectedValueException('External URLs do not have internal route parameters.');
}
return $this->routeParameters;
}
/**
* Sets the route parameters.
*
* @param array $parameters
* The array of parameters.
*
* @return $this
*
* @throws \UnexpectedValueException.
* If this is a URI with no corresponding route.
*/
public function setRouteParameters($parameters) {
if ($this->unrouted) {
throw new \UnexpectedValueException('External URLs do not have route parameters.');
}
$this->routeParameters = $parameters;
return $this;
}
/**
* Sets a specific route parameter.
*
* @param string $key
* The key of the route parameter.
* @param mixed $value
* The route parameter.
*
* @return $this
*
* @throws \UnexpectedValueException.
* If this is a URI with no corresponding route.
*/
public function setRouteParameter($key, $value) {
if ($this->unrouted) {
throw new \UnexpectedValueException('External URLs do not have route parameters.');
}
$this->routeParameters[$key] = $value;
return $this;
}
/**
* Returns the URL options.
*
* @return array
* The array of options. See \Drupal\Core\Url::fromUri() for details on what
* it contains.
*/
public function getOptions() {
return $this->options;
}
/**
* Gets a specific option.
*
* See \Drupal\Core\Url::fromUri() for details on the options.
*
* @param string $name
* The name of the option.
*
* @return mixed
* The value for a specific option, or NULL if it does not exist.
*/
public function getOption($name) {
if (!isset($this->options[$name])) {
return NULL;
}
return $this->options[$name];
}
/**
* Sets the URL options.
*
* @param array $options
* The array of options. See \Drupal\Core\Url::fromUri() for details on what
* it contains.
*
* @return $this
*/
public function setOptions($options) {
$this->options = $options;
return $this;
}
/**
* Sets a specific option.
*
* See \Drupal\Core\Url::fromUri() for details on the options.
*
* @param string $name
* The name of the option.
* @param mixed $value
* The option value.
*
* @return $this
*/
public function setOption($name, $value) {
$this->options[$name] = $value;
return $this;
}
/**
* Returns the URI value for this Url object.
*
* Only to be used if self::$unrouted is TRUE.
*
* @return string
* A URI not connected to a route. May be an external URL.
*
* @throws \UnexpectedValueException
* Thrown when the URI was requested for a routed URL.
*/
public function getUri() {
if (!$this->unrouted) {
throw new \UnexpectedValueException('This URL has a Drupal route, so the canonical form is not a URI.');
}
return $this->uri;
}
/**
* Sets the value of the absolute option for this Url.
*
* @param bool $absolute
* (optional) Whether to make this Url absolute or not. Defaults to TRUE.
*
* @return $this
*/
public function setAbsolute($absolute = TRUE) {
$this->options['absolute'] = $absolute;
return $this;
}
/**
* Generates the string URL representation for this Url object.
*
* For an external URL, the string will contain the input plus any query
* string or fragment specified by the options array.
*
* If this Url object was constructed from a Drupal route or from an internal
* URI (URIs using the internal:, base:, or entity: schemes), the returned
* string will either be a relative URL like /node/1 or an absolute URL like
* http://example.com/node/1 depending on the options array, plus any
* specified query string or fragment.
*
* @param bool $collect_bubbleable_metadata
* (optional) Defaults to FALSE. When TRUE, both the generated URL and its
* associated bubbleable metadata are returned.
*
* @return string|\Drupal\Core\GeneratedUrl
* A string URL.
* When $collect_bubbleable_metadata is TRUE, a GeneratedUrl object is
* returned, containing the generated URL plus bubbleable metadata.
*/
public function toString($collect_bubbleable_metadata = FALSE) {
if ($this->unrouted) {
return $this->unroutedUrlAssembler()->assemble($this->getUri(), $this->getOptions(), $collect_bubbleable_metadata);
}
return $this->urlGenerator()->generateFromRoute($this->getRouteName(), $this->getRouteParameters(), $this->getOptions(), $collect_bubbleable_metadata);
}
/**
* Returns the route information for a render array.
*
* @return array
* An associative array suitable for a render array.
*/
public function toRenderArray() {
$render_array = [
'#url' => $this,
'#options' => $this->getOptions(),
];
if (!$this->unrouted) {
$render_array['#access_callback'] = [get_class(), 'renderAccess'];
}
return $render_array;
}
/**
* Returns the internal path (system path) for this route.
*
* This path will not include any prefixes, fragments, or query strings.
*
* @return string
* The internal path for this route.
*
* @throws \UnexpectedValueException.
* If this is a URI with no corresponding system path.
*/
public function getInternalPath() {
if ($this->unrouted) {
throw new \UnexpectedValueException('Unrouted URIs do not have internal representations.');
}
if (!isset($this->internalPath)) {
$this->internalPath = $this->urlGenerator()->getPathFromRoute($this->getRouteName(), $this->getRouteParameters());
}
return $this->internalPath;
}
/**
* Checks this Url object against applicable access check services.
*
* Determines whether the route is accessible or not.
*
* @param \Drupal\Core\Session\AccountInterface $account
* (optional) Run access checks for this account. Defaults to the current
* user.
*
* @return bool
* Returns TRUE if the user has access to the url, otherwise FALSE.
*/
public function access(AccountInterface $account = NULL) {
if ($this->isRouted()) {
return $this->accessManager()->checkNamedRoute($this->getRouteName(), $this->getRouteParameters(), $account);
}
return TRUE;
}
/**
* Checks a Url render element against applicable access check services.
*
* @param array $element
* A render element as returned from \Drupal\Core\Url::toRenderArray().
*
* @return bool
* Returns TRUE if the current user has access to the url, otherwise FALSE.
*/
public static function renderAccess(array $element) {
return $element['#url']->access();
}
/**
* @return \Drupal\Core\Access\AccessManagerInterface
*/
protected function accessManager() {
if (!isset($this->accessManager)) {
$this->accessManager = \Drupal::service('access_manager');
}
return $this->accessManager;
}
/**
* Gets the URL generator.
*
* @return \Drupal\Core\Routing\UrlGeneratorInterface
* The URL generator.
*/
protected function urlGenerator() {
if (!$this->urlGenerator) {
$this->urlGenerator = \Drupal::urlGenerator();
}
return $this->urlGenerator;
}
/**
* Gets the unrouted URL assembler for non-Drupal URLs.
*
* @return \Drupal\Core\Utility\UnroutedUrlAssemblerInterface
* The unrouted URL assembler.
*/
protected function unroutedUrlAssembler() {
if (!$this->urlAssembler) {
$this->urlAssembler = \Drupal::service('unrouted_url_assembler');
}
return $this->urlAssembler;
}
/**
* Sets the URL generator.
*
* @param \Drupal\Core\Routing\UrlGeneratorInterface
* (optional) The URL generator, specify NULL to reset it.
*
* @return $this
*/
public function setUrlGenerator(UrlGeneratorInterface $url_generator = NULL) {
$this->urlGenerator = $url_generator;
$this->internalPath = NULL;
return $this;
}
/**
* Sets the unrouted URL assembler.
*
* @param \Drupal\Core\Utility\UnroutedUrlAssemblerInterface
* The unrouted URL assembler.
*
* @return $this
*/
public function setUnroutedUrlAssembler(UnroutedUrlAssemblerInterface $url_assembler) {
$this->urlAssembler = $url_assembler;
return $this;
}
}
| 318io/318-io | expo/www/core/lib/Drupal/Core/Url.php | PHP | gpl-2.0 | 29,307 |
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qnetworkaccessfilebackend_p.h"
#include "qfileinfo.h"
#include "qurlinfo.h"
#include "qdir.h"
#include "private/qnoncontiguousbytedevice_p.h"
#include <QtCore/QCoreApplication>
QT_BEGIN_NAMESPACE
QNetworkAccessBackend *
QNetworkAccessFileBackendFactory::create(QNetworkAccessManager::Operation op,
const QNetworkRequest &request) const
{
// is it an operation we know of?
switch (op) {
case QNetworkAccessManager::GetOperation:
case QNetworkAccessManager::PutOperation:
break;
default:
// no, we can't handle this operation
return 0;
}
QUrl url = request.url();
if (url.scheme().compare(QLatin1String("qrc"), Qt::CaseInsensitive) == 0 || url.isLocalFile()) {
return new QNetworkAccessFileBackend;
} else if (!url.isEmpty() && url.authority().isEmpty()) {
// check if QFile could, in theory, open this URL via the file engines
// it has to be in the format:
// prefix:path/to/file
// or prefix:/path/to/file
//
// this construct here must match the one below in open()
QFileInfo fi(url.toString(QUrl::RemoveAuthority | QUrl::RemoveFragment | QUrl::RemoveQuery));
// On Windows and Symbian the drive letter is detected as the scheme.
if (fi.exists() && (url.scheme().isEmpty() || (url.scheme().length() == 1)))
qWarning("QNetworkAccessFileBackendFactory: URL has no schema set, use file:// for files");
if (fi.exists() || (op == QNetworkAccessManager::PutOperation && fi.dir().exists()))
return new QNetworkAccessFileBackend;
}
return 0;
}
QNetworkAccessFileBackend::QNetworkAccessFileBackend()
: uploadByteDevice(0), totalBytes(0), hasUploadFinished(false)
{
}
QNetworkAccessFileBackend::~QNetworkAccessFileBackend()
{
}
void QNetworkAccessFileBackend::open()
{
QUrl url = this->url();
if (url.host() == QLatin1String("localhost"))
url.setHost(QString());
#if !defined(Q_OS_WIN)
// do not allow UNC paths on Unix
if (!url.host().isEmpty()) {
// we handle only local files
error(QNetworkReply::ProtocolInvalidOperationError,
QCoreApplication::translate("QNetworkAccessFileBackend", "Request for opening non-local file %1").arg(url.toString()));
finished();
return;
}
#endif // !defined(Q_OS_WIN)
if (url.path().isEmpty())
url.setPath(QLatin1String("/"));
setUrl(url);
QString fileName = url.toLocalFile();
if (fileName.isEmpty()) {
if (url.scheme() == QLatin1String("qrc"))
fileName = QLatin1Char(':') + url.path();
else
fileName = url.toString(QUrl::RemoveAuthority | QUrl::RemoveFragment | QUrl::RemoveQuery);
}
file.setFileName(fileName);
if (operation() == QNetworkAccessManager::GetOperation) {
if (!loadFileInfo())
return;
}
QIODevice::OpenMode mode;
switch (operation()) {
case QNetworkAccessManager::GetOperation:
mode = QIODevice::ReadOnly;
break;
case QNetworkAccessManager::PutOperation:
mode = QIODevice::WriteOnly | QIODevice::Truncate;
uploadByteDevice = createUploadByteDevice();
QObject::connect(uploadByteDevice, SIGNAL(readyRead()), this, SLOT(uploadReadyReadSlot()));
QMetaObject::invokeMethod(this, "uploadReadyReadSlot", Qt::QueuedConnection);
break;
default:
Q_ASSERT_X(false, "QNetworkAccessFileBackend::open",
"Got a request operation I cannot handle!!");
return;
}
mode |= QIODevice::Unbuffered;
bool opened = file.open(mode);
// could we open the file?
if (!opened) {
QString msg = QCoreApplication::translate("QNetworkAccessFileBackend", "Error opening %1: %2")
.arg(this->url().toString(), file.errorString());
// why couldn't we open the file?
// if we're opening for reading, either it doesn't exist, or it's access denied
// if we're opening for writing, not existing means it's access denied too
if (file.exists() || operation() == QNetworkAccessManager::PutOperation)
error(QNetworkReply::ContentAccessDenied, msg);
else
error(QNetworkReply::ContentNotFoundError, msg);
finished();
}
}
void QNetworkAccessFileBackend::uploadReadyReadSlot()
{
if (hasUploadFinished)
return;
forever {
qint64 haveRead;
const char *readPointer = uploadByteDevice->readPointer(-1, haveRead);
if (haveRead == -1) {
// EOF
hasUploadFinished = true;
file.flush();
file.close();
finished();
break;
} else if (haveRead == 0 || readPointer == 0) {
// nothing to read right now, we will be called again later
break;
} else {
qint64 haveWritten;
haveWritten = file.write(readPointer, haveRead);
if (haveWritten < 0) {
// write error!
QString msg = QCoreApplication::translate("QNetworkAccessFileBackend", "Write error writing to %1: %2")
.arg(url().toString(), file.errorString());
error(QNetworkReply::ProtocolFailure, msg);
finished();
return;
} else {
uploadByteDevice->advanceReadPointer(haveWritten);
}
file.flush();
}
}
}
void QNetworkAccessFileBackend::closeDownstreamChannel()
{
if (operation() == QNetworkAccessManager::GetOperation) {
file.close();
}
}
void QNetworkAccessFileBackend::downstreamReadyWrite()
{
Q_ASSERT_X(operation() == QNetworkAccessManager::GetOperation, "QNetworkAccessFileBackend",
"We're being told to download data but operation isn't GET!");
readMoreFromFile();
}
bool QNetworkAccessFileBackend::loadFileInfo()
{
QFileInfo fi(file);
setHeader(QNetworkRequest::LastModifiedHeader, fi.lastModified());
setHeader(QNetworkRequest::ContentLengthHeader, fi.size());
// signal we're open
metaDataChanged();
if (fi.isDir()) {
error(QNetworkReply::ContentOperationNotPermittedError,
QCoreApplication::translate("QNetworkAccessFileBackend", "Cannot open %1: Path is a directory").arg(url().toString()));
finished();
return false;
}
return true;
}
bool QNetworkAccessFileBackend::readMoreFromFile()
{
qint64 wantToRead;
while ((wantToRead = nextDownstreamBlockSize()) > 0) {
// ### FIXME!!
// Obtain a pointer from the ringbuffer!
// Avoid extra copy
QByteArray data;
data.reserve(wantToRead);
qint64 actuallyRead = file.read(data.data(), wantToRead);
if (actuallyRead <= 0) {
// EOF or error
if (file.error() != QFile::NoError) {
QString msg = QCoreApplication::translate("QNetworkAccessFileBackend", "Read error reading from %1: %2")
.arg(url().toString(), file.errorString());
error(QNetworkReply::ProtocolFailure, msg);
finished();
return false;
}
finished();
return true;
}
data.resize(actuallyRead);
totalBytes += actuallyRead;
QByteDataBuffer list;
list.append(data);
data.clear(); // important because of implicit sharing!
writeDownstreamData(list);
}
return true;
}
QT_END_NAMESPACE
| dulton/vlc-2.1.4.32.subproject-2013-update2 | win32/include/qt4/src/network/access/qnetworkaccessfilebackend.cpp | C++ | gpl-2.0 | 9,651 |
<?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
/**
* Doctrine_Search_QueryWeight_TestCase
*
* @package Doctrine
* @author Konsta Vesterinen <kvesteri@cc.hut.fi>
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @category Object Relational Mapping
* @link www.doctrine-project.org
* @since 1.0
* @version $Revision$
*/
class Doctrine_Search_QueryWeight_TestCase extends Doctrine_UnitTestCase
{
public function testQuerySupportsMultiWordOrOperatorSearchWithQuotes()
{
$q = new Doctrine_Search_Query('SearchTestIndex');
$q->search("doctrine^2 OR 'dbal database'");
$sql = 'SELECT foreign_id, SUM(relevancy) AS relevancy_sum '
. 'FROM (SELECT COUNT(keyword) * 2 AS relevancy, foreign_id '
. 'FROM search_index '
. 'WHERE keyword = ? '
. 'GROUP BY foreign_id '
. 'UNION '
. 'SELECT COUNT(keyword) AS relevancy, foreign_id '
. 'FROM search_index) AS query_alias '
. 'WHERE keyword = ? AND (position + 1) = (SELECT position FROM search_index WHERE keyword = ?) '
. 'GROUP BY foreign_id) '
. 'GROUP BY foreign_id '
. 'ORDER BY relevancy_sum';
$this->assertEqual($q->getSqlQuery(), $sql);
}
public function testSearchSupportsMixingOfOperatorsParenthesisAndWeights()
{
$q = new Doctrine_Search_Query('SearchTestIndex');
$q->search('(doctrine^2 OR orm) AND dbal');
$sql = "SELECT foreign_id, SUM(relevancy) AS relevancy_sum FROM
(SELECT COUNT(keyword) * 2 AS relevancy, foreign_id
FROM search_index
WHERE keyword = 'doctrine'
GROUP BY foreign_id
UNION
SELECT COUNT(keyword) * 2 AS relevancy, foreign_id
FROM search_index
WHERE keyword = 'orm'
GROUP BY foreign_id
INTERSECT
SELECT COUNT(keyword) AS relevancy, foreign_id
FROM search_index) AS query_alias
WHERE keyword = 'dbal'
GROUP BY foreign_id)
GROUP BY foreign_id
ORDER BY relevancy_sum";
$this->assertEqual($q->getSqlQuery(), $sql);
}
public function testQuerySupportsMultiWordAndOperatorSearchWithQuotesAndWeights()
{
$q = new Doctrine_Search_Query('SearchTestIndex');
$q->search("doctrine^2 'dbal database'");
$sql = "SELECT foreign_id, SUM(relevancy) AS relevancy_sum FROM
(SELECT COUNT(keyword) * 2 AS relevancy, foreign_id
FROM search_index
WHERE keyword = 'doctrine'
GROUP BY foreign_id
INTERSECT
SELECT COUNT(keyword) AS relevancy, foreign_id
FROM search_index) AS query_alias
WHERE keyword = 'dbal' AND (position + 1) = (SELECT position FROM search_index WHERE keyword = 'database')
GROUP BY foreign_id)
GROUP BY foreign_id
ORDER BY relevancy_sum";
$this->assertEqual($q->getSqlQuery(), $sql);
}
public function testQuerySupportsMultiWordNegationOperatorSearchWithQuotesWeights()
{
$q = new Doctrine_Search_Query('SearchTestIndex');
$q->search("doctrine^2 'dbal database' -rdbms");
$sql = "SELECT foreign_id, SUM(relevancy) AS relevancy_sum FROM
(SELECT COUNT(keyword) * 2 AS relevancy, foreign_id
FROM search_index
WHERE keyword = 'doctrine'
GROUP BY foreign_id
INTERSECT
SELECT COUNT(keyword) AS relevancy, foreign_id
FROM search_index) AS query_alias
WHERE keyword = 'dbal' AND (position + 1) = (SELECT position FROM search_index WHERE keyword = 'database')
GROUP BY foreign_id
EXCEPT
SELECT COUNT(keyword) AS relevancy, foreign_id
FROM search_index) AS query_alias
WHERE keyword != 'rdbms'
GROUP BY foreign_id
)
GROUP BY foreign_id
ORDER BY relevancy_sum";
$this->assertEqual($q->getSqlQuery(), $sql);
}
}
| 1ed/doctrine1 | tests/Search/QueryWeightTestCase.php | PHP | lgpl-2.1 | 5,743 |
/*
* Copyright (C) 2015 RECRUIT LIFESTYLE CO., LTD.
*
* 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 jp.co.recruit_lifestyle.android.widget.character;
import android.graphics.Path;
/**
* @author amyu
*/
public class ButterflyPath {
public static Path getButterflyPath(float width, float[] centerPoint){
Path path = new Path();
path.moveTo(centerPoint[0] - width / 2 + 0.501f * width, centerPoint[1] - width / 2 + 0.666f * width);
path.cubicTo(
centerPoint[0] - width / 2 + 0.47f * width, centerPoint[1] - width / 2 + 0.668f * width,
centerPoint[0] - width / 2 + 0.48f * width, centerPoint[1] - width / 2 + 0.548f * width,
centerPoint[0] - width / 2 + 0.479f * width, centerPoint[1] - width / 2 + 0.545f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.478f * width, centerPoint[1] - width / 2 + 0.541f * width,
centerPoint[0] - width / 2 + 0.479f * width, centerPoint[1] - width / 2 + 0.534f * width,
centerPoint[0] - width / 2 + 0.478f * width, centerPoint[1] - width / 2 + 0.532f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.476f * width, centerPoint[1] - width / 2 + 0.529f * width,
centerPoint[0] - width / 2 + 0.467f * width, centerPoint[1] - width / 2 + 0.54f * width,
centerPoint[0] - width / 2 + 0.447f * width, centerPoint[1] - width / 2 + 0.572f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.427f * width, centerPoint[1] - width / 2 + 0.605f * width,
centerPoint[0] - width / 2 + 0.378f * width, centerPoint[1] - width / 2 + 0.729f * width,
centerPoint[0] - width / 2 + 0.369f * width, centerPoint[1] - width / 2 + 0.734f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.361f * width, centerPoint[1] - width / 2 + 0.739f * width,
centerPoint[0] - width / 2 + 0.352f * width, centerPoint[1] - width / 2 + 0.733f * width,
centerPoint[0] - width / 2 + 0.348f * width, centerPoint[1] - width / 2 + 0.733f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.344f * width, centerPoint[1] - width / 2 + 0.732f * width,
centerPoint[0] - width / 2 + 0.341f * width, centerPoint[1] - width / 2 + 0.739f * width,
centerPoint[0] - width / 2 + 0.341f * width, centerPoint[1] - width / 2 + 0.755f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.341f * width, centerPoint[1] - width / 2 + 0.77f * width,
centerPoint[0] - width / 2 + 0.319f * width, centerPoint[1] - width / 2 + 0.787f * width,
centerPoint[0] - width / 2 + 0.31f * width, centerPoint[1] - width / 2 + 0.785f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.302f * width, centerPoint[1] - width / 2 + 0.783f * width,
centerPoint[0] - width / 2 + 0.303f * width, centerPoint[1] - width / 2 + 0.757f * width,
centerPoint[0] - width / 2 + 0.295f * width, centerPoint[1] - width / 2 + 0.755f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.287f * width, centerPoint[1] - width / 2 + 0.752f * width,
centerPoint[0] - width / 2 + 0.275f * width, centerPoint[1] - width / 2 + 0.77f * width,
centerPoint[0] - width / 2 + 0.271f * width, centerPoint[1] - width / 2 + 0.77f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.266f * width, centerPoint[1] - width / 2 + 0.77f * width,
centerPoint[0] - width / 2 + 0.266f * width, centerPoint[1] - width / 2 + 0.764f * width,
centerPoint[0] - width / 2 + 0.264f * width, centerPoint[1] - width / 2 + 0.755f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.263f * width, centerPoint[1] - width / 2 + 0.745f * width,
centerPoint[0] - width / 2 + 0.262f * width, centerPoint[1] - width / 2 + 0.744f * width,
centerPoint[0] - width / 2 + 0.252f * width, centerPoint[1] - width / 2 + 0.743f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.241f * width, centerPoint[1] - width / 2 + 0.743f * width,
centerPoint[0] - width / 2 + 0.206f * width, centerPoint[1] - width / 2 + 0.774f * width,
centerPoint[0] - width / 2 + 0.188f * width, centerPoint[1] - width / 2 + 0.803f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.17f * width, centerPoint[1] - width / 2 + 0.832f * width,
centerPoint[0] - width / 2 + 0.119f * width, centerPoint[1] - width / 2 + 0.857f * width,
centerPoint[0] - width / 2 + 0.109f * width, centerPoint[1] - width / 2 + 0.844f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.098f * width, centerPoint[1] - width / 2 + 0.831f * width,
centerPoint[0] - width / 2 + 0.111f * width, centerPoint[1] - width / 2 + 0.82f * width,
centerPoint[0] - width / 2 + 0.126f * width, centerPoint[1] - width / 2 + 0.803f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.141f * width, centerPoint[1] - width / 2 + 0.786f * width,
centerPoint[0] - width / 2 + 0.175f * width, centerPoint[1] - width / 2 + 0.765f * width,
centerPoint[0] - width / 2 + 0.188f * width, centerPoint[1] - width / 2 + 0.757f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.2f * width, centerPoint[1] - width / 2 + 0.749f * width,
centerPoint[0] - width / 2 + 0.23f * width, centerPoint[1] - width / 2 + 0.723f * width,
centerPoint[0] - width / 2 + 0.241f * width, centerPoint[1] - width / 2 + 0.701f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.252f * width, centerPoint[1] - width / 2 + 0.678f * width,
centerPoint[0] - width / 2 + 0.234f * width, centerPoint[1] - width / 2 + 0.669f * width,
centerPoint[0] - width / 2 + 0.224f * width, centerPoint[1] - width / 2 + 0.663f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.214f * width, centerPoint[1] - width / 2 + 0.656f * width,
centerPoint[0] - width / 2 + 0.225f * width, centerPoint[1] - width / 2 + 0.641f * width,
centerPoint[0] - width / 2 + 0.229f * width, centerPoint[1] - width / 2 + 0.634f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.232f * width, centerPoint[1] - width / 2 + 0.628f * width,
centerPoint[0] - width / 2 + 0.23f * width, centerPoint[1] - width / 2 + 0.62f * width,
centerPoint[0] - width / 2 + 0.223f * width, centerPoint[1] - width / 2 + 0.616f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.215f * width, centerPoint[1] - width / 2 + 0.612f * width,
centerPoint[0] - width / 2 + 0.207f * width, centerPoint[1] - width / 2 + 0.599f * width,
centerPoint[0] - width / 2 + 0.208f * width, centerPoint[1] - width / 2 + 0.59f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.21f * width, centerPoint[1] - width / 2 + 0.582f * width,
centerPoint[0] - width / 2 + 0.213f * width, centerPoint[1] - width / 2 + 0.578f * width,
centerPoint[0] - width / 2 + 0.212f * width, centerPoint[1] - width / 2 + 0.574f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.211f * width, centerPoint[1] - width / 2 + 0.569f * width,
centerPoint[0] - width / 2 + 0.199f * width, centerPoint[1] - width / 2 + 0.562f * width,
centerPoint[0] - width / 2 + 0.196f * width, centerPoint[1] - width / 2 + 0.555f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.193f * width, centerPoint[1] - width / 2 + 0.549f * width,
centerPoint[0] - width / 2 + 0.215f * width, centerPoint[1] - width / 2 + 0.531f * width,
centerPoint[0] - width / 2 + 0.217f * width, centerPoint[1] - width / 2 + 0.529f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.219f * width, centerPoint[1] - width / 2 + 0.527f * width,
centerPoint[0] - width / 2 + 0.22f * width, centerPoint[1] - width / 2 + 0.517f * width,
centerPoint[0] - width / 2 + 0.221f * width, centerPoint[1] - width / 2 + 0.511f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.222f * width, centerPoint[1] - width / 2 + 0.505f * width,
centerPoint[0] - width / 2 + 0.257f * width, centerPoint[1] - width / 2 + 0.488f * width,
centerPoint[0] - width / 2 + 0.259f * width, centerPoint[1] - width / 2 + 0.486f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.262f * width, centerPoint[1] - width / 2 + 0.483f * width,
centerPoint[0] - width / 2 + 0.262f * width, centerPoint[1] - width / 2 + 0.478f * width,
centerPoint[0] - width / 2 + 0.251f * width, centerPoint[1] - width / 2 + 0.48f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.24f * width, centerPoint[1] - width / 2 + 0.482f * width,
centerPoint[0] - width / 2 + 0.216f * width, centerPoint[1] - width / 2 + 0.471f * width,
centerPoint[0] - width / 2 + 0.207f * width, centerPoint[1] - width / 2 + 0.463f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.198f * width, centerPoint[1] - width / 2 + 0.456f * width,
centerPoint[0] - width / 2 + 0.188f * width, centerPoint[1] - width / 2 + 0.433f * width,
centerPoint[0] - width / 2 + 0.186f * width, centerPoint[1] - width / 2 + 0.425f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.184f * width, centerPoint[1] - width / 2 + 0.418f * width,
centerPoint[0] - width / 2 + 0.182f * width, centerPoint[1] - width / 2 + 0.414f * width,
centerPoint[0] - width / 2 + 0.176f * width, centerPoint[1] - width / 2 + 0.407f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.171f * width, centerPoint[1] - width / 2 + 0.401f * width,
centerPoint[0] - width / 2 + 0.17f * width, centerPoint[1] - width / 2 + 0.39f * width,
centerPoint[0] - width / 2 + 0.168f * width, centerPoint[1] - width / 2 + 0.385f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.166f * width, centerPoint[1] - width / 2 + 0.38f * width,
centerPoint[0] - width / 2 + 0.153f * width, centerPoint[1] - width / 2 + 0.364f * width,
centerPoint[0] - width / 2 + 0.149f * width, centerPoint[1] - width / 2 + 0.357f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.144f * width, centerPoint[1] - width / 2 + 0.35f * width,
centerPoint[0] - width / 2 + 0.146f * width, centerPoint[1] - width / 2 + 0.345f * width,
centerPoint[0] - width / 2 + 0.144f * width, centerPoint[1] - width / 2 + 0.34f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.143f * width, centerPoint[1] - width / 2 + 0.334f * width,
centerPoint[0] - width / 2 + 0.132f * width, centerPoint[1] - width / 2 + 0.322f * width,
centerPoint[0] - width / 2 + 0.129f * width, centerPoint[1] - width / 2 + 0.317f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.126f * width, centerPoint[1] - width / 2 + 0.311f * width,
centerPoint[0] - width / 2 + 0.125f * width, centerPoint[1] - width / 2 + 0.3f * width,
centerPoint[0] - width / 2 + 0.123f * width, centerPoint[1] - width / 2 + 0.297f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.121f * width, centerPoint[1] - width / 2 + 0.293f * width,
centerPoint[0] - width / 2 + 0.112f * width, centerPoint[1] - width / 2 + 0.277f * width,
centerPoint[0] - width / 2 + 0.11f * width, centerPoint[1] - width / 2 + 0.272f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.108f * width, centerPoint[1] - width / 2 + 0.268f * width,
centerPoint[0] - width / 2 + 0.104f * width, centerPoint[1] - width / 2 + 0.259f * width,
centerPoint[0] - width / 2 + 0.097f * width, centerPoint[1] - width / 2 + 0.251f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.091f * width, centerPoint[1] - width / 2 + 0.244f * width,
centerPoint[0] - width / 2 + 0.066f * width, centerPoint[1] - width / 2 + 0.2f * width,
centerPoint[0] - width / 2 + 0.061f * width, centerPoint[1] - width / 2 + 0.184f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.056f * width, centerPoint[1] - width / 2 + 0.168f * width,
centerPoint[0] - width / 2 + 0.073f * width, centerPoint[1] - width / 2 + 0.157f * width,
centerPoint[0] - width / 2 + 0.104f * width, centerPoint[1] - width / 2 + 0.153f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.136f * width, centerPoint[1] - width / 2 + 0.149f * width,
centerPoint[0] - width / 2 + 0.173f * width, centerPoint[1] - width / 2 + 0.162f * width,
centerPoint[0] - width / 2 + 0.223f * width, centerPoint[1] - width / 2 + 0.184f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.273f * width, centerPoint[1] - width / 2 + 0.206f * width,
centerPoint[0] - width / 2 + 0.316f * width, centerPoint[1] - width / 2 + 0.25f * width,
centerPoint[0] - width / 2 + 0.367f * width, centerPoint[1] - width / 2 + 0.3f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.418f * width, centerPoint[1] - width / 2 + 0.349f * width,
centerPoint[0] - width / 2 + 0.48f * width, centerPoint[1] - width / 2 + 0.462f * width,
centerPoint[0] - width / 2 + 0.482f * width, centerPoint[1] - width / 2 + 0.461f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.484f * width, centerPoint[1] - width / 2 + 0.461f * width,
centerPoint[0] - width / 2 + 0.482f * width, centerPoint[1] - width / 2 + 0.455f * width,
centerPoint[0] - width / 2 + 0.48f * width, centerPoint[1] - width / 2 + 0.449f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.478f * width, centerPoint[1] - width / 2 + 0.444f * width,
centerPoint[0] - width / 2 + 0.483f * width, centerPoint[1] - width / 2 + 0.436f * width,
centerPoint[0] - width / 2 + 0.483f * width, centerPoint[1] - width / 2 + 0.436f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.483f * width, centerPoint[1] - width / 2 + 0.433f * width,
centerPoint[0] - width / 2 + 0.484f * width, centerPoint[1] - width / 2 + 0.433f * width,
centerPoint[0] - width / 2 + 0.484f * width, centerPoint[1] - width / 2 + 0.433f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.484f * width, centerPoint[1] - width / 2 + 0.433f * width,
centerPoint[0] - width / 2 + 0.481f * width, centerPoint[1] - width / 2 + 0.427f * width,
centerPoint[0] - width / 2 + 0.482f * width, centerPoint[1] - width / 2 + 0.421f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.483f * width, centerPoint[1] - width / 2 + 0.416f * width,
centerPoint[0] - width / 2 + 0.491f * width, centerPoint[1] - width / 2 + 0.414f * width,
centerPoint[0] - width / 2 + 0.491f * width, centerPoint[1] - width / 2 + 0.414f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.485f * width, centerPoint[1] - width / 2 + 0.406f * width,
centerPoint[0] - width / 2 + 0.401f * width, centerPoint[1] - width / 2 + 0.307f * width,
centerPoint[0] - width / 2 + 0.401f * width, centerPoint[1] - width / 2 + 0.307f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.394f * width, centerPoint[1] - width / 2 + 0.305f * width,
centerPoint[0] - width / 2 + 0.385f * width, centerPoint[1] - width / 2 + 0.294f * width,
centerPoint[0] - width / 2 + 0.387f * width, centerPoint[1] - width / 2 + 0.293f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.389f * width, centerPoint[1] - width / 2 + 0.292f * width,
centerPoint[0] - width / 2 + 0.392f * width, centerPoint[1] - width / 2 + 0.291f * width,
centerPoint[0] - width / 2 + 0.405f * width, centerPoint[1] - width / 2 + 0.305f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.418f * width, centerPoint[1] - width / 2 + 0.32f * width,
centerPoint[0] - width / 2 + 0.495f * width, centerPoint[1] - width / 2 + 0.413f * width,
centerPoint[0] - width / 2 + 0.495f * width, centerPoint[1] - width / 2 + 0.413f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.495f * width, centerPoint[1] - width / 2 + 0.413f * width,
centerPoint[0] - width / 2 + 0.498f * width, centerPoint[1] - width / 2 + 0.413f * width,
centerPoint[0] - width / 2 + 0.5f * width, centerPoint[1] - width / 2 + 0.413f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.502f * width, centerPoint[1] - width / 2 + 0.413f * width,
centerPoint[0] - width / 2 + 0.505f * width, centerPoint[1] - width / 2 + 0.413f * width,
centerPoint[0] - width / 2 + 0.505f * width, centerPoint[1] - width / 2 + 0.413f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.505f * width, centerPoint[1] - width / 2 + 0.413f * width,
centerPoint[0] - width / 2 + 0.582f * width, centerPoint[1] - width / 2 + 0.32f * width,
centerPoint[0] - width / 2 + 0.595f * width, centerPoint[1] - width / 2 + 0.305f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.608f * width, centerPoint[1] - width / 2 + 0.291f * width,
centerPoint[0] - width / 2 + 0.611f * width, centerPoint[1] - width / 2 + 0.292f * width,
centerPoint[0] - width / 2 + 0.613f * width, centerPoint[1] - width / 2 + 0.293f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.615f * width, centerPoint[1] - width / 2 + 0.294f * width,
centerPoint[0] - width / 2 + 0.606f * width, centerPoint[1] - width / 2 + 0.305f * width,
centerPoint[0] - width / 2 + 0.599f * width, centerPoint[1] - width / 2 + 0.307f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.599f * width, centerPoint[1] - width / 2 + 0.307f * width,
centerPoint[0] - width / 2 + 0.515f * width, centerPoint[1] - width / 2 + 0.406f * width,
centerPoint[0] - width / 2 + 0.509f * width, centerPoint[1] - width / 2 + 0.414f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.509f * width, centerPoint[1] - width / 2 + 0.414f * width,
centerPoint[0] - width / 2 + 0.517f * width, centerPoint[1] - width / 2 + 0.416f * width,
centerPoint[0] - width / 2 + 0.518f * width, centerPoint[1] - width / 2 + 0.421f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.519f * width, centerPoint[1] - width / 2 + 0.427f * width,
centerPoint[0] - width / 2 + 0.516f * width, centerPoint[1] - width / 2 + 0.433f * width,
centerPoint[0] - width / 2 + 0.516f * width, centerPoint[1] - width / 2 + 0.433f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.516f * width, centerPoint[1] - width / 2 + 0.433f * width,
centerPoint[0] - width / 2 + 0.517f * width, centerPoint[1] - width / 2 + 0.433f * width,
centerPoint[0] - width / 2 + 0.517f * width, centerPoint[1] - width / 2 + 0.436f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.517f * width, centerPoint[1] - width / 2 + 0.436f * width,
centerPoint[0] - width / 2 + 0.522f * width, centerPoint[1] - width / 2 + 0.444f * width,
centerPoint[0] - width / 2 + 0.52f * width, centerPoint[1] - width / 2 + 0.449f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.518f * width, centerPoint[1] - width / 2 + 0.455f * width,
centerPoint[0] - width / 2 + 0.516f * width, centerPoint[1] - width / 2 + 0.461f * width,
centerPoint[0] - width / 2 + 0.518f * width, centerPoint[1] - width / 2 + 0.461f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.52f * width, centerPoint[1] - width / 2 + 0.462f * width,
centerPoint[0] - width / 2 + 0.582f * width, centerPoint[1] - width / 2 + 0.349f * width,
centerPoint[0] - width / 2 + 0.633f * width, centerPoint[1] - width / 2 + 0.3f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.684f * width, centerPoint[1] - width / 2 + 0.25f * width,
centerPoint[0] - width / 2 + 0.727f * width, centerPoint[1] - width / 2 + 0.206f * width,
centerPoint[0] - width / 2 + 0.777f * width, centerPoint[1] - width / 2 + 0.184f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.827f * width, centerPoint[1] - width / 2 + 0.162f * width,
centerPoint[0] - width / 2 + 0.864f * width, centerPoint[1] - width / 2 + 0.149f * width,
centerPoint[0] - width / 2 + 0.896f * width, centerPoint[1] - width / 2 + 0.153f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.927f * width, centerPoint[1] - width / 2 + 0.157f * width,
centerPoint[0] - width / 2 + 0.944f * width, centerPoint[1] - width / 2 + 0.168f * width,
centerPoint[0] - width / 2 + 0.939f * width, centerPoint[1] - width / 2 + 0.184f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.934f * width, centerPoint[1] - width / 2 + 0.2f * width,
centerPoint[0] - width / 2 + 0.909f * width, centerPoint[1] - width / 2 + 0.244f * width,
centerPoint[0] - width / 2 + 0.903f * width, centerPoint[1] - width / 2 + 0.251f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.896f * width, centerPoint[1] - width / 2 + 0.259f * width,
centerPoint[0] - width / 2 + 0.892f * width, centerPoint[1] - width / 2 + 0.268f * width,
centerPoint[0] - width / 2 + 0.89f * width, centerPoint[1] - width / 2 + 0.272f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.888f * width, centerPoint[1] - width / 2 + 0.277f * width,
centerPoint[0] - width / 2 + 0.879f * width, centerPoint[1] - width / 2 + 0.293f * width,
centerPoint[0] - width / 2 + 0.877f * width, centerPoint[1] - width / 2 + 0.297f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.875f * width, centerPoint[1] - width / 2 + 0.3f * width,
centerPoint[0] - width / 2 + 0.874f * width, centerPoint[1] - width / 2 + 0.311f * width,
centerPoint[0] - width / 2 + 0.871f * width, centerPoint[1] - width / 2 + 0.317f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.868f * width, centerPoint[1] - width / 2 + 0.322f * width,
centerPoint[0] - width / 2 + 0.857f * width, centerPoint[1] - width / 2 + 0.334f * width,
centerPoint[0] - width / 2 + 0.856f * width, centerPoint[1] - width / 2 + 0.34f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.854f * width, centerPoint[1] - width / 2 + 0.345f * width,
centerPoint[0] - width / 2 + 0.856f * width, centerPoint[1] - width / 2 + 0.35f * width,
centerPoint[0] - width / 2 + 0.851f * width, centerPoint[1] - width / 2 + 0.357f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.847f * width, centerPoint[1] - width / 2 + 0.364f * width,
centerPoint[0] - width / 2 + 0.834f * width, centerPoint[1] - width / 2 + 0.38f * width,
centerPoint[0] - width / 2 + 0.832f * width, centerPoint[1] - width / 2 + 0.385f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.83f * width, centerPoint[1] - width / 2 + 0.39f * width,
centerPoint[0] - width / 2 + 0.829f * width, centerPoint[1] - width / 2 + 0.401f * width,
centerPoint[0] - width / 2 + 0.824f * width, centerPoint[1] - width / 2 + 0.407f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.818f * width, centerPoint[1] - width / 2 + 0.414f * width,
centerPoint[0] - width / 2 + 0.816f * width, centerPoint[1] - width / 2 + 0.418f * width,
centerPoint[0] - width / 2 + 0.814f * width, centerPoint[1] - width / 2 + 0.425f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.812f * width, centerPoint[1] - width / 2 + 0.433f * width,
centerPoint[0] - width / 2 + 0.802f * width, centerPoint[1] - width / 2 + 0.456f * width,
centerPoint[0] - width / 2 + 0.793f * width, centerPoint[1] - width / 2 + 0.463f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.784f * width, centerPoint[1] - width / 2 + 0.471f * width,
centerPoint[0] - width / 2 + 0.76f * width, centerPoint[1] - width / 2 + 0.482f * width,
centerPoint[0] - width / 2 + 0.749f * width, centerPoint[1] - width / 2 + 0.48f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.738f * width, centerPoint[1] - width / 2 + 0.478f * width,
centerPoint[0] - width / 2 + 0.738f * width, centerPoint[1] - width / 2 + 0.483f * width,
centerPoint[0] - width / 2 + 0.741f * width, centerPoint[1] - width / 2 + 0.486f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.743f * width, centerPoint[1] - width / 2 + 0.488f * width,
centerPoint[0] - width / 2 + 0.778f * width, centerPoint[1] - width / 2 + 0.505f * width,
centerPoint[0] - width / 2 + 0.779f * width, centerPoint[1] - width / 2 + 0.511f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.78f * width, centerPoint[1] - width / 2 + 0.517f * width,
centerPoint[0] - width / 2 + 0.781f * width, centerPoint[1] - width / 2 + 0.527f * width,
centerPoint[0] - width / 2 + 0.783f * width, centerPoint[1] - width / 2 + 0.529f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.785f * width, centerPoint[1] - width / 2 + 0.531f * width,
centerPoint[0] - width / 2 + 0.807f * width, centerPoint[1] - width / 2 + 0.549f * width,
centerPoint[0] - width / 2 + 0.804f * width, centerPoint[1] - width / 2 + 0.555f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.801f * width, centerPoint[1] - width / 2 + 0.562f * width,
centerPoint[0] - width / 2 + 0.789f * width, centerPoint[1] - width / 2 + 0.569f * width,
centerPoint[0] - width / 2 + 0.788f * width, centerPoint[1] - width / 2 + 0.574f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.787f * width, centerPoint[1] - width / 2 + 0.578f * width,
centerPoint[0] - width / 2 + 0.79f * width, centerPoint[1] - width / 2 + 0.582f * width,
centerPoint[0] - width / 2 + 0.792f * width, centerPoint[1] - width / 2 + 0.59f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.793f * width, centerPoint[1] - width / 2 + 0.599f * width,
centerPoint[0] - width / 2 + 0.785f * width, centerPoint[1] - width / 2 + 0.612f * width,
centerPoint[0] - width / 2 + 0.777f * width, centerPoint[1] - width / 2 + 0.616f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.77f * width, centerPoint[1] - width / 2 + 0.62f * width,
centerPoint[0] - width / 2 + 0.768f * width, centerPoint[1] - width / 2 + 0.628f * width,
centerPoint[0] - width / 2 + 0.771f * width, centerPoint[1] - width / 2 + 0.634f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.775f * width, centerPoint[1] - width / 2 + 0.641f * width,
centerPoint[0] - width / 2 + 0.786f * width, centerPoint[1] - width / 2 + 0.656f * width,
centerPoint[0] - width / 2 + 0.776f * width, centerPoint[1] - width / 2 + 0.663f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.766f * width, centerPoint[1] - width / 2 + 0.669f * width,
centerPoint[0] - width / 2 + 0.748f * width, centerPoint[1] - width / 2 + 0.678f * width,
centerPoint[0] - width / 2 + 0.759f * width, centerPoint[1] - width / 2 + 0.701f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.77f * width, centerPoint[1] - width / 2 + 0.723f * width,
centerPoint[0] - width / 2 + 0.8f * width, centerPoint[1] - width / 2 + 0.749f * width,
centerPoint[0] - width / 2 + 0.812f * width, centerPoint[1] - width / 2 + 0.757f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.825f * width, centerPoint[1] - width / 2 + 0.765f * width,
centerPoint[0] - width / 2 + 0.859f * width, centerPoint[1] - width / 2 + 0.786f * width,
centerPoint[0] - width / 2 + 0.874f * width, centerPoint[1] - width / 2 + 0.803f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.889f * width, centerPoint[1] - width / 2 + 0.82f * width,
centerPoint[0] - width / 2 + 0.902f * width, centerPoint[1] - width / 2 + 0.831f * width,
centerPoint[0] - width / 2 + 0.891f * width, centerPoint[1] - width / 2 + 0.844f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.881f * width, centerPoint[1] - width / 2 + 0.857f * width,
centerPoint[0] - width / 2 + 0.83f * width, centerPoint[1] - width / 2 + 0.832f * width,
centerPoint[0] - width / 2 + 0.812f * width, centerPoint[1] - width / 2 + 0.803f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.794f * width, centerPoint[1] - width / 2 + 0.774f * width,
centerPoint[0] - width / 2 + 0.759f * width, centerPoint[1] - width / 2 + 0.743f * width,
centerPoint[0] - width / 2 + 0.748f * width, centerPoint[1] - width / 2 + 0.743f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.738f * width, centerPoint[1] - width / 2 + 0.744f * width,
centerPoint[0] - width / 2 + 0.738f * width, centerPoint[1] - width / 2 + 0.745f * width,
centerPoint[0] - width / 2 + 0.736f * width, centerPoint[1] - width / 2 + 0.755f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.734f * width, centerPoint[1] - width / 2 + 0.764f * width,
centerPoint[0] - width / 2 + 0.734f * width, centerPoint[1] - width / 2 + 0.77f * width,
centerPoint[0] - width / 2 + 0.729f * width, centerPoint[1] - width / 2 + 0.77f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.725f * width, centerPoint[1] - width / 2 + 0.77f * width,
centerPoint[0] - width / 2 + 0.713f * width, centerPoint[1] - width / 2 + 0.752f * width,
centerPoint[0] - width / 2 + 0.705f * width, centerPoint[1] - width / 2 + 0.755f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.697f * width, centerPoint[1] - width / 2 + 0.757f * width,
centerPoint[0] - width / 2 + 0.698f * width, centerPoint[1] - width / 2 + 0.783f * width,
centerPoint[0] - width / 2 + 0.69f * width, centerPoint[1] - width / 2 + 0.785f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.681f * width, centerPoint[1] - width / 2 + 0.787f * width,
centerPoint[0] - width / 2 + 0.659f * width, centerPoint[1] - width / 2 + 0.77f * width,
centerPoint[0] - width / 2 + 0.659f * width, centerPoint[1] - width / 2 + 0.755f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.659f * width, centerPoint[1] - width / 2 + 0.739f * width,
centerPoint[0] - width / 2 + 0.656f * width, centerPoint[1] - width / 2 + 0.732f * width,
centerPoint[0] - width / 2 + 0.652f * width, centerPoint[1] - width / 2 + 0.733f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.648f * width, centerPoint[1] - width / 2 + 0.733f * width,
centerPoint[0] - width / 2 + 0.639f * width, centerPoint[1] - width / 2 + 0.739f * width,
centerPoint[0] - width / 2 + 0.631f * width, centerPoint[1] - width / 2 + 0.734f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.622f * width, centerPoint[1] - width / 2 + 0.729f * width,
centerPoint[0] - width / 2 + 0.573f * width, centerPoint[1] - width / 2 + 0.605f * width,
centerPoint[0] - width / 2 + 0.553f * width, centerPoint[1] - width / 2 + 0.572f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.533f * width, centerPoint[1] - width / 2 + 0.54f * width,
centerPoint[0] - width / 2 + 0.524f * width, centerPoint[1] - width / 2 + 0.529f * width,
centerPoint[0] - width / 2 + 0.522f * width, centerPoint[1] - width / 2 + 0.532f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.521f * width, centerPoint[1] - width / 2 + 0.534f * width,
centerPoint[0] - width / 2 + 0.522f * width, centerPoint[1] - width / 2 + 0.541f * width,
centerPoint[0] - width / 2 + 0.521f * width, centerPoint[1] - width / 2 + 0.545f * width
);
path.cubicTo(
centerPoint[0] - width / 2 + 0.52f * width, centerPoint[1] - width / 2 + 0.548f * width,
centerPoint[0] - width / 2 + 0.532f * width, centerPoint[1] - width / 2 + 0.668f * width,
centerPoint[0] - width / 2 + 0.501f * width, centerPoint[1] - width / 2 + 0.666f * width
);
return path;
}
}
| cheyiliu/test4XXX | test4ColoringLoading/src/jp/co/recruit_lifestyle/android/widget/character/ButterflyPath.java | Java | apache-2.0 | 33,662 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Serializer\Mapping\Loader;
use Symfony\Component\Serializer\Exception\MappingException;
use Symfony\Component\Serializer\Mapping\ClassMetadataInterface;
/**
* Calls multiple {@link LoaderInterface} instances in a chain.
*
* This class accepts multiple instances of LoaderInterface to be passed to the
* constructor. When {@link loadClassMetadata()} is called, the same method is called
* in <em>all</em> of these loaders, regardless of whether any of them was
* successful or not.
*
* @author Bernhard Schussek <bschussek@gmail.com>
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class LoaderChain implements LoaderInterface
{
private $loaders;
/**
* Accepts a list of LoaderInterface instances.
*
* @param LoaderInterface[] $loaders An array of LoaderInterface instances
*
* @throws MappingException If any of the loaders does not implement LoaderInterface
*/
public function __construct(array $loaders)
{
foreach ($loaders as $loader) {
if (!$loader instanceof LoaderInterface) {
throw new MappingException(sprintf('Class %s is expected to implement LoaderInterface', get_class($loader)));
}
}
$this->loaders = $loaders;
}
/**
* {@inheritdoc}
*/
public function loadClassMetadata(ClassMetadataInterface $metadata)
{
$success = false;
foreach ($this->loaders as $loader) {
$success = $loader->loadClassMetadata($metadata) || $success;
}
return $success;
}
/**
* @return LoaderInterface[]
*/
public function getLoaders()
{
return $this->loaders;
}
}
| MisterNono/camping | vendor/symfony/symfony/src/Symfony/Component/Serializer/Mapping/Loader/LoaderChain.php | PHP | apache-2.0 | 1,953 |
/*=============================================================================
Library: XNAT/Core
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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 "ctkXnatObjectPrivate.h"
#include <QString>
//----------------------------------------------------------------------------
ctkXnatObjectPrivate::ctkXnatObjectPrivate()
: fetched(false)
, parent(0)
{
}
//----------------------------------------------------------------------------
ctkXnatObjectPrivate::~ctkXnatObjectPrivate()
{
}
| pieper/CTK | Libs/XNAT/Core/ctkXnatObjectPrivate.cpp | C++ | apache-2.0 | 1,167 |
module Metric::Processing
DERIVED_COLS = [
:derived_cpu_available,
:derived_cpu_reserved,
:derived_host_count_off,
:derived_host_count_on,
:derived_host_count_total,
:derived_memory_available,
:derived_memory_reserved,
:derived_memory_used,
:derived_host_sockets,
:derived_vm_allocated_disk_storage,
:derived_vm_count_off,
:derived_vm_count_on,
:derived_vm_count_total,
:derived_vm_numvcpus, # TODO: This is cpu_total_cores and needs to be renamed, but reports depend on the name :numvcpus
# See also #TODO on VimPerformanceState.capture
:derived_vm_used_disk_storage,
# TODO(lsmola) as described below, this field should be named derived_cpu_used
:cpu_usagemhz_rate_average
]
VALID_PROCESS_TARGETS = [
VmOrTemplate,
Container,
ContainerGroup,
ContainerNode,
ContainerProject,
ContainerReplicator,
ContainerService,
Host,
AvailabilityZone,
HostAggregate,
EmsCluster,
ExtManagementSystem,
MiqRegion,
MiqEnterprise
]
def self.process_derived_columns(obj, attrs, ts = nil)
unless VALID_PROCESS_TARGETS.any? { |t| obj.kind_of?(t) }
raise _("object %{name} is not one of %{items}") % {:name => obj,
:items => VALID_PROCESS_TARGETS.collect(&:name).join(", ")}
end
ts = attrs[:timestamp] if ts.nil?
state = obj.vim_performance_state_for_ts(ts)
total_cpu = state.total_cpu || 0
total_mem = state.total_mem || 0
result = {}
have_cpu_metrics = attrs[:cpu_usage_rate_average] || attrs[:cpu_usagemhz_rate_average]
have_mem_metrics = attrs[:mem_usage_absolute_average] || attrs[:derived_memory_used]
DERIVED_COLS.each do |col|
dummy, group, typ, mode = col.to_s.split("_")
case typ
when "available"
# Do not derive "available" values if there haven't been any usage
# values collected
if group == "cpu"
result[col] = total_cpu if have_cpu_metrics && total_cpu > 0
else
result[col] = total_mem if have_mem_metrics && total_mem > 0
end
when "allocated"
method = col.to_s.split("_")[1..-1].join("_")
result[col] = state.send(method) if state.respond_to?(method)
when "used"
if group == "cpu"
# TODO: This branch is never called because there isn't a column
# called derived_cpu_used. The callers, such as chargeback, generally
# use cpu_usagemhz_rate_average directly, and the column may not be
# needed, but perhaps should be added to normalize like is done for
# memory. The derivation here could then use cpu_usagemhz_rate_average
# directly if avaiable, otherwise do the calculation below.
result[col] = (attrs[:cpu_usage_rate_average] / 100 * total_cpu) unless total_cpu == 0 || attrs[:cpu_usage_rate_average].nil?
elsif group == "memory"
if attrs[:mem_usage_absolute_average].nil?
# If we can't get percentage usage, just used RAM in MB, lets compute percentage usage
attrs[:mem_usage_absolute_average] = 100.0 / total_mem * attrs[:derived_memory_used] if total_mem > 0 && !attrs[:derived_memory_used].nil?
else
# We have percentage usage of RAM, lets compute consumed RAM in MB
result[col] = (attrs[:mem_usage_absolute_average] / 100 * total_mem) unless total_mem == 0 || attrs[:mem_usage_absolute_average].nil?
end
else
method = col.to_s.split("_")[1..-1].join("_")
result[col] = state.send(method) if state.respond_to?(method)
end
when "rate"
if col.to_s == "cpu_usagemhz_rate_average" && attrs[:cpu_usagemhz_rate_average].blank?
# TODO(lsmola) for some reason, this column is used in chart, although from processing code above, it should
# be named derived_cpu_used. Investigate what is the right solution and make it right. For now lets fill
# the column shown in charts.
result[col] = (attrs[:cpu_usage_rate_average] / 100 * total_cpu) unless total_cpu == 0 || attrs[:cpu_usage_rate_average].nil?
end
when "reserved"
method = group == "cpu" ? :reserve_cpu : :reserve_mem
result[col] = state.send(method)
when "count"
method = [group, typ, mode].join("_")
result[col] = state.send(method)
when "numvcpus" # This is actually logical cpus. See note above.
# Do not derive "available" values if there haven't been any usage
# values collected
result[col] = state.numvcpus if have_cpu_metrics && state.try(:numvcpus).to_i > 0
when "sockets"
result[col] = state.host_sockets
end
end
result[:assoc_ids] = state.assoc_ids
result[:tag_names] = state.tag_names
result[:parent_host_id] = state.parent_host_id
result[:parent_storage_id] = state.parent_storage_id
result[:parent_ems_id] = state.parent_ems_id
result[:parent_ems_cluster_id] = state.parent_ems_cluster_id
result
end
def self.add_missing_intervals(obj, interval_name, start_time, end_time)
klass, meth = Metric::Helper.class_and_association_for_interval_name(interval_name)
scope = obj.send(meth).for_time_range(start_time, end_time)
scope = scope.where(:capture_interval_name => interval_name) if interval_name != "realtime"
extrapolate(klass, scope)
end
def self.extrapolate(klass, scope)
last_perf = {}
scope.order("timestamp, capture_interval_name").each do |perf|
interval = interval_name_to_interval(perf.capture_interval_name)
last_perf[interval] = perf if last_perf[interval].nil?
if (perf.timestamp - last_perf[interval].timestamp) <= interval
last_perf[interval] = perf
next
end
new_perf = create_new_metric(klass, last_perf[interval], perf, interval)
new_perf.save!
last_perf[interval] = perf
end
end
def self.create_new_metric(klass, last_perf, perf, interval)
attrs = last_perf.attributes
attrs.delete('id')
attrs['timestamp'] += interval
attrs['capture_interval'] = 0
new_perf = klass.new(attrs)
Metric::Rollup::ROLLUP_COLS.each do |c|
next if new_perf.send(c).nil? || perf.send(c).nil?
new_perf.send(c.to_s + "=", (new_perf.send(c) + perf.send(c)) / 2)
end
unless perf.assoc_ids.nil?
Metric::Rollup::ASSOC_KEYS.each do |assoc|
next if new_perf.assoc_ids.nil? || new_perf.assoc_ids[assoc].blank? || perf.assoc_ids[assoc].blank?
new_perf.assoc_ids[assoc][:on] ||= []
new_perf.assoc_ids[assoc][:off] ||= []
new_perf.assoc_ids[assoc][:on] = (new_perf.assoc_ids[assoc][:on] + perf.assoc_ids[assoc][:on]).uniq!
new_perf.assoc_ids[assoc][:off] = (new_perf.assoc_ids[assoc][:off] + perf.assoc_ids[assoc][:off]).uniq!
end
end
new_perf
end
private_class_method :extrapolate, :create_new_metric
def self.interval_name_to_interval(name)
case name
when "realtime" then 20
when "hourly" then 1.hour.to_i
when "daily" then 1.day.to_i
else raise _("unknown interval name: [%{name}]") % {:name => name}
end
end
end
| mfeifer/manageiq | app/models/metric/processing.rb | Ruby | apache-2.0 | 7,255 |
class Pianod < Formula
homepage "http://deviousfish.com/pianod/"
url "http://deviousfish.com/Downloads/pianod/pianod-173.tar.gz"
sha256 "d91a890561037ee3faf5d4d1d4de546c8ff8c828eced91eea6be026c4fcf16fd"
devel do
url "http://deviousfish.com/Downloads/pianod/pianod-174.tar.gz"
sha256 "8b46cf57a785256bb9d5543022c1b630a5d45580800b6eb6c170712c6c78d879"
end
bottle do
sha256 "c445526d673caadf44783aa2992817f1a172a4ad83376b8c5ee0c62e94c3ef01" => :yosemite
sha256 "77975c68192f2fc203decc2122e05e720f6fb248b3aec061540536ea4371a871" => :mavericks
sha256 "dc09efd35ee5e55e5196c2a72ca8b3ca61b4a437fb66ff481e80be1782e9931a" => :mountain_lion
end
depends_on "pkg-config" => :build
depends_on "libao"
depends_on "libgcrypt"
depends_on "gnutls"
depends_on "json-c"
depends_on "faad2" => :recommended
depends_on "mad" => :recommended
def install
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
system "make", "install"
end
test do
system "#{bin}/pianod", "-v"
end
end
| bendemaree/homebrew | Library/Formula/pianod.rb | Ruby | bsd-2-clause | 1,178 |
( function ( mw, $ ) {
mw.page = {};
// Client profile classes for <html>
// Allows for easy hiding/showing of JS or no-JS-specific UI elements
$( 'html' )
.addClass( 'client-js' )
.removeClass( 'client-nojs' );
$( function () {
// Initialize utilities as soon as the document is ready (mw.util.$content,
// messageBoxNew, profile, tooltip access keys, Table of contents toggle, ..).
// In the domready here instead of in mediawiki.page.ready to ensure that it gets enqueued
// before other modules hook into domready, so that mw.util.$content (defined by
// mw.util.init), is defined for them.
mw.util.init();
/**
* @event wikipage_content
* @member mw.hook
* @param {jQuery} $content
*/
mw.hook( 'wikipage.content' ).fire( $( '#mw-content-text' ) );
} );
}( mediaWiki, jQuery ) );
| BRL-CAD/web | wiki/resources/mediawiki.page/mediawiki.page.startup.js | JavaScript | bsd-2-clause | 826 |
//=================================================================================================
/*!
// \file src/mathtest/dvectdvecmult/VHbVDb.cpp
// \brief Source file for the VHbVDb dense vector/dense vector outer product math test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DynamicVector.h>
#include <blaze/math/HybridVector.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dvectdvecmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'VHbVDb'..." << std::endl;
using blazetest::mathtest::TypeB;
try
{
// Vector type definitions
typedef blaze::HybridVector<TypeB,128UL> VHb;
typedef blaze::DynamicVector<TypeB> VDb;
// Creator type definitions
typedef blazetest::Creator<VHb> CVHb;
typedef blazetest::Creator<VDb> CVDb;
// Running tests with small vectors
for( size_t i=0UL; i<=6UL; ++i ) {
for( size_t j=0UL; j<=6UL; ++j ) {
RUN_DVECTDVECMULT_OPERATION_TEST( CVHb( i ), CVDb( j ) );
}
}
// Running tests with large vectors
RUN_DVECTDVECMULT_OPERATION_TEST( CVHb( 67UL ), CVDb( 67UL ) );
RUN_DVECTDVECMULT_OPERATION_TEST( CVHb( 67UL ), CVDb( 127UL ) );
RUN_DVECTDVECMULT_OPERATION_TEST( CVHb( 127UL ), CVDb( 67UL ) );
RUN_DVECTDVECMULT_OPERATION_TEST( CVHb( 127UL ), CVDb( 127UL ) );
RUN_DVECTDVECMULT_OPERATION_TEST( CVHb( 64UL ), CVDb( 64UL ) );
RUN_DVECTDVECMULT_OPERATION_TEST( CVHb( 64UL ), CVDb( 128UL ) );
RUN_DVECTDVECMULT_OPERATION_TEST( CVHb( 128UL ), CVDb( 64UL ) );
RUN_DVECTDVECMULT_OPERATION_TEST( CVHb( 128UL ), CVDb( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense vector/dense vector outer product:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| yzxyzh/blaze-lib | blazetest/src/mathtest/dvectdvecmult/VHbVDb.cpp | C++ | bsd-3-clause | 4,422 |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.3/15.3.5/15.3.5.4/15.3.5.4_2-77gs.js
* @description Strict mode - checking access to strict function caller from non-strict function (non-strict function declaration called by strict Function constructor)
* @noStrict
*/
function f() {return gNonStrict();};
(function () {"use strict"; return Function("return f();")(); })();
function gNonStrict() {
return gNonStrict.caller;
}
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch15/15.3/15.3.5/15.3.5.4/15.3.5.4_2-77gs.js | JavaScript | bsd-3-clause | 476 |
//=================================================================================================
/*!
// \file src/mathtest/tdvecdvecmult/V4aV4b.cpp
// \brief Source file for the V4aV4b dense vector/dense vector inner product math test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/StaticVector.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/tdvecdvecmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'V4aV4b'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Vector type definitions
typedef blaze::StaticVector<TypeA,4UL> V4a;
typedef blaze::StaticVector<TypeB,4UL> V4b;
// Creator type definitions
typedef blazetest::Creator<V4a> CV4a;
typedef blazetest::Creator<V4b> CV4b;
// Running the tests
RUN_TDVECDVECMULT_OPERATION_TEST( CV4a(), CV4b() );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense vector/dense vector inner product:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| honnibal/blaze-lib | blazetest/src/mathtest/tdvecdvecmult/V4aV4b.cpp | C++ | bsd-3-clause | 3,667 |
"""SCons.Scanner.IDL
This module implements the depenency scanner for IDL (Interface
Definition Language) files.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Scanner/IDL.py 4043 2009/02/23 09:06:45 scons"
import SCons.Node.FS
import SCons.Scanner
def IDLScan():
"""Return a prototype Scanner instance for scanning IDL source files"""
cs = SCons.Scanner.ClassicCPP("IDLScan",
"$IDLSUFFIXES",
"CPPPATH",
'^[ \t]*(?:#[ \t]*include|[ \t]*import)[ \t]+(<|")([^>"]+)(>|")')
return cs
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| mastbaum/rat-pac | python/SCons/Scanner/IDL.py | Python | bsd-3-clause | 1,852 |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch10/10.6/10.6-11-b-1.js
* @description Arguments Object has index property '0' as its own property, it shoulde be writable, enumerable, configurable and does not invoke the setter defined on Object.prototype[0] (Step 11.b)
*/
function testcase() {
try {
var data = "data";
var getFunc = function () {
return data;
};
var setFunc = function (value) {
data = value;
};
Object.defineProperty(Object.prototype, "0", {
get: getFunc,
set: setFunc,
configurable: true
});
var argObj = (function () { return arguments })(1);
var verifyValue = false;
verifyValue = (argObj[0] === 1);
var verifyEnumerable = false;
for (var p in argObj) {
if (p === "0" && argObj.hasOwnProperty("0")) {
verifyEnumerable = true;
}
}
var verifyWritable = false;
argObj[0] = 1001;
verifyWritable = (argObj[0] === 1001);
var verifyConfigurable = false;
delete argObj[0];
verifyConfigurable = argObj.hasOwnProperty("0");
return verifyValue && verifyWritable && verifyEnumerable && !verifyConfigurable && data === "data";
} finally {
delete Object.prototype[0];
}
}
runTestCase(testcase);
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch10/10.6/10.6-11-b-1.js | JavaScript | bsd-3-clause | 1,560 |
// Copyright 2009 the Sputnik authors. All rights reserved.
/**
* The [[Value]] property of the newly constructed object
* is set by following steps:
* 1. Call ToNumber(year)
* 2. Call ToNumber(month)
* 3. If date is supplied use ToNumber(date)
* 4. If hours is supplied use ToNumber(hours)
* 5. If minutes is supplied use ToNumber(minutes)
* 6. If seconds is supplied use ToNumber(seconds)
* 7. If ms is supplied use ToNumber(ms)
*
* @path ch15/15.9/15.9.3/S15.9.3.1_A4_T4.js
* @description 5 arguments, (year, month, date, hours, minutes)
*/
var myObj = function(val){
this.value = val;
this.valueOf = function(){throw "valueOf-"+this.value;};
this.toString = function(){throw "toString-"+this.value;};
};
//CHECK#1
try{
var x1 = new Date(new myObj(1), new myObj(2), new myObj(3), new myObj(4), new myObj(5));
$ERROR("#1: The 1st step is calling ToNumber(year)");
}
catch(e){
if(e !== "valueOf-1"){
$ERROR("#1: The 1st step is calling ToNumber(year)");
}
}
//CHECK#2
try{
var x2 = new Date(1, new myObj(2), new myObj(3), new myObj(4), new myObj(5));
$ERROR("#2: The 2nd step is calling ToNumber(month)");
}
catch(e){
if(e !== "valueOf-2"){
$ERROR("#2: The 2nd step is calling ToNumber(month)");
}
}
//CHECK#3
try{
var x3 = new Date(1, 2, new myObj(3), new myObj(4), new myObj(5));
$ERROR("#3: The 3rd step is calling ToNumber(date)");
}
catch(e){
if(e !== "valueOf-3"){
$ERROR("#3: The 3rd step is calling ToNumber(date)");
}
}
//CHECK#4
try{
var x4 = new Date(1, 2, 3, new myObj(4), new myObj(5));
$ERROR("#4: The 4th step is calling ToNumber(hours)");
}
catch(e){
if(e !== "valueOf-4"){
$ERROR("#4: The 4th step is calling ToNumber(hours)");
}
}
//CHECK#5
try{
var x5 = new Date(1, 2, 3, 4, new myObj(5));
$ERROR("#5: The 5th step is calling ToNumber(minutes)");
}
catch(e){
if(e !== "valueOf-5"){
$ERROR("#5: The 5th step is calling ToNumber(minutes)");
}
}
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch15/15.9/15.9.3/S15.9.3.1_A4_T4.js | JavaScript | bsd-3-clause | 1,950 |
// Copyright 2009 the Sputnik authors. All rights reserved.
/**
* Number.MIN_VALUE has the attribute DontEnum
*
* @path ch15/15.7/15.7.3/15.7.3.3/S15.7.3.3_A4.js
* @description Checking if enumerating Number.MIN_VALUE fails
*/
//CHECK#1
for(var x in Number) {
if(x === "MIN_VALUE") {
$ERROR('#1: Number.MIN_VALUE has the attribute DontEnum');
}
}
if (Number.propertyIsEnumerable('MIN_VALUE')) {
$ERROR('#2: Number.MIN_VALUE has the attribute DontEnum');
}
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch15/15.7/15.7.3/15.7.3.3/S15.7.3.3_A4.js | JavaScript | bsd-3-clause | 475 |
/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <Array.hpp>
namespace opencl
{
template<typename T, bool is_color>
Array<T> meanshift(const Array<T> &in, const float &s_sigma, const float &c_sigma, const unsigned iter);
}
| marbre/arrayfire | src/backend/opencl/meanshift.hpp | C++ | bsd-3-clause | 519 |
//
// FPEnvironment_SUN.cpp
//
// $Id: //poco/1.4/Foundation/src/FPEnvironment_SUN.cpp#1 $
//
// Library: Foundation
// Package: Core
// Module: FPEnvironment
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include <math.h>
#include "Poco/FPEnvironment_SUN.h"
namespace Poco {
FPEnvironmentImpl::FPEnvironmentImpl()
{
_rnd = fpgetround();
_exc = fpgetmask();
}
FPEnvironmentImpl::FPEnvironmentImpl(const FPEnvironmentImpl& env)
{
_rnd = env._rnd;
_exc = env._exc;
}
FPEnvironmentImpl::~FPEnvironmentImpl()
{
fpsetround(_rnd);
fpsetmask(_exc);
}
FPEnvironmentImpl& FPEnvironmentImpl::operator = (const FPEnvironmentImpl& env)
{
_rnd = env._rnd;
_exc = env._exc;
return *this;
}
bool FPEnvironmentImpl::isInfiniteImpl(float value)
{
int cls = fpclass(value);
return cls == FP_PINF || cls == FP_NINF;
}
bool FPEnvironmentImpl::isInfiniteImpl(double value)
{
int cls = fpclass(value);
return cls == FP_PINF || cls == FP_NINF;
}
bool FPEnvironmentImpl::isInfiniteImpl(long double value)
{
int cls = fpclass(value);
return cls == FP_PINF || cls == FP_NINF;
}
bool FPEnvironmentImpl::isNaNImpl(float value)
{
return isnanf(value) != 0;
}
bool FPEnvironmentImpl::isNaNImpl(double value)
{
return isnan(value) != 0;
}
bool FPEnvironmentImpl::isNaNImpl(long double value)
{
return isnan((double) value) != 0;
}
float FPEnvironmentImpl::copySignImpl(float target, float source)
{
return (float) copysign(target, source);
}
double FPEnvironmentImpl::copySignImpl(double target, double source)
{
return (float) copysign(target, source);
}
long double FPEnvironmentImpl::copySignImpl(long double target, long double source)
{
return (source > 0 && target > 0) || (source < 0 && target < 0) ? target : -target;
}
void FPEnvironmentImpl::keepCurrentImpl()
{
fpsetround(_rnd);
fpsetmask(_exc);
}
void FPEnvironmentImpl::clearFlagsImpl()
{
fpsetsticky(0);
}
bool FPEnvironmentImpl::isFlagImpl(FlagImpl flag)
{
return (fpgetsticky() & flag) != 0;
}
void FPEnvironmentImpl::setRoundingModeImpl(RoundingModeImpl mode)
{
fpsetround((fp_rnd) mode);
}
FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::getRoundingModeImpl()
{
return (FPEnvironmentImpl::RoundingModeImpl) fpgetround();
}
} // namespace Poco
| weinzierl-engineering/baos | thirdparty/poco/Foundation/src/FPEnvironment_SUN.cpp | C++ | mit | 2,352 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_admin
*
* @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
?>
<fieldset class="adminform">
<legend><?php echo JText::_('COM_ADMIN_PHP_INFORMATION'); ?></legend>
<?php echo $this->php_info; ?>
</fieldset>
| renebentes/joomla-3.x | administrator/components/com_admin/views/sysinfo/tmpl/default_phpinfo.php | PHP | gpl-2.0 | 422 |
/*
* Copyright (c) 2015, 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 jdk.tools.jlink.internal;
import java.security.BasicPermission;
/**
* The permission required to use jlink API. The permission target_name is
* "jlink". e.g.: permission jdk.tools.jlink.plugins.JlinkPermission "jlink";
*
*/
public final class JlinkPermission extends BasicPermission {
private static final long serialVersionUID = -3687912306077727801L;
public JlinkPermission(String name) {
super(name);
}
}
| md-5/jdk10 | src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkPermission.java | Java | gpl-2.0 | 1,652 |
r"""
==============================================================
Compressed Sparse Graph Routines (:mod:`scipy.sparse.csgraph`)
==============================================================
.. currentmodule:: scipy.sparse.csgraph
Fast graph algorithms based on sparse matrix representations.
Contents
========
.. autosummary::
:toctree: generated/
connected_components -- determine connected components of a graph
laplacian -- compute the laplacian of a graph
shortest_path -- compute the shortest path between points on a positive graph
dijkstra -- use Dijkstra's algorithm for shortest path
floyd_warshall -- use the Floyd-Warshall algorithm for shortest path
bellman_ford -- use the Bellman-Ford algorithm for shortest path
johnson -- use Johnson's algorithm for shortest path
breadth_first_order -- compute a breadth-first order of nodes
depth_first_order -- compute a depth-first order of nodes
breadth_first_tree -- construct the breadth-first tree from a given node
depth_first_tree -- construct a depth-first tree from a given node
minimum_spanning_tree -- construct the minimum spanning tree of a graph
reverse_cuthill_mckee -- compute permutation for reverse Cuthill-McKee ordering
maximum_bipartite_matching -- compute permutation to make diagonal zero free
Graph Representations
=====================
This module uses graphs which are stored in a matrix format. A
graph with N nodes can be represented by an (N x N) adjacency matrix G.
If there is a connection from node i to node j, then G[i, j] = w, where
w is the weight of the connection. For nodes i and j which are
not connected, the value depends on the representation:
- for dense array representations, non-edges are represented by
G[i, j] = 0, infinity, or NaN.
- for dense masked representations (of type np.ma.MaskedArray), non-edges
are represented by masked values. This can be useful when graphs with
zero-weight edges are desired.
- for sparse array representations, non-edges are represented by
non-entries in the matrix. This sort of sparse representation also
allows for edges with zero weights.
As a concrete example, imagine that you would like to represent the following
undirected graph::
G
(0)
/ \
1 2
/ \
(2) (1)
This graph has three nodes, where node 0 and 1 are connected by an edge of
weight 2, and nodes 0 and 2 are connected by an edge of weight 1.
We can construct the dense, masked, and sparse representations as follows,
keeping in mind that an undirected graph is represented by a symmetric matrix::
>>> G_dense = np.array([[0, 2, 1],
... [2, 0, 0],
... [1, 0, 0]])
>>> G_masked = np.ma.masked_values(G_dense, 0)
>>> from scipy.sparse import csr_matrix
>>> G_sparse = csr_matrix(G_dense)
This becomes more difficult when zero edges are significant. For example,
consider the situation when we slightly modify the above graph::
G2
(0)
/ \
0 2
/ \
(2) (1)
This is identical to the previous graph, except nodes 0 and 2 are connected
by an edge of zero weight. In this case, the dense representation above
leads to ambiguities: how can non-edges be represented if zero is a meaningful
value? In this case, either a masked or sparse representation must be used
to eliminate the ambiguity::
>>> G2_data = np.array([[np.inf, 2, 0 ],
... [2, np.inf, np.inf],
... [0, np.inf, np.inf]])
>>> G2_masked = np.ma.masked_invalid(G2_data)
>>> from scipy.sparse.csgraph import csgraph_from_dense
>>> # G2_sparse = csr_matrix(G2_data) would give the wrong result
>>> G2_sparse = csgraph_from_dense(G2_data, null_value=np.inf)
>>> G2_sparse.data
array([ 2., 0., 2., 0.])
Here we have used a utility routine from the csgraph submodule in order to
convert the dense representation to a sparse representation which can be
understood by the algorithms in submodule. By viewing the data array, we
can see that the zero values are explicitly encoded in the graph.
Directed vs. Undirected
-----------------------
Matrices may represent either directed or undirected graphs. This is
specified throughout the csgraph module by a boolean keyword. Graphs are
assumed to be directed by default. In a directed graph, traversal from node
i to node j can be accomplished over the edge G[i, j], but not the edge
G[j, i]. In a non-directed graph, traversal from node i to node j can be
accomplished over either G[i, j] or G[j, i]. If both edges are not null,
and the two have unequal weights, then the smaller of the two is used.
Note that a symmetric matrix will represent an undirected graph, regardless
of whether the 'directed' keyword is set to True or False. In this case,
using ``directed=True`` generally leads to more efficient computation.
The routines in this module accept as input either scipy.sparse representations
(csr, csc, or lil format), masked representations, or dense representations
with non-edges indicated by zeros, infinities, and NaN entries.
"""
from __future__ import division, print_function, absolute_import
__docformat__ = "restructuredtext en"
__all__ = ['cs_graph_components',
'connected_components',
'laplacian',
'shortest_path',
'floyd_warshall',
'dijkstra',
'bellman_ford',
'johnson',
'breadth_first_order',
'depth_first_order',
'breadth_first_tree',
'depth_first_tree',
'minimum_spanning_tree',
'reverse_cuthill_mckee',
'maximum_bipartite_matching',
'construct_dist_matrix',
'reconstruct_path',
'csgraph_from_dense',
'csgraph_masked_from_dense',
'csgraph_to_dense',
'csgraph_to_masked',
'NegativeCycleError']
from ._components import cs_graph_components
from ._laplacian import laplacian
from ._shortest_path import shortest_path, floyd_warshall, dijkstra,\
bellman_ford, johnson, NegativeCycleError
from ._traversal import breadth_first_order, depth_first_order, \
breadth_first_tree, depth_first_tree, connected_components
from ._min_spanning_tree import minimum_spanning_tree
from ._reordering import reverse_cuthill_mckee, maximum_bipartite_matching
from ._tools import construct_dist_matrix, reconstruct_path,\
csgraph_from_dense, csgraph_to_dense, csgraph_masked_from_dense,\
csgraph_from_masked
from numpy import deprecate as _deprecate
cs_graph_components = _deprecate(cs_graph_components,
message=("In the future, use "
"csgraph.connected_components. Note "
"that this new function has a "
"slightly different interface: see "
"the docstring for more "
"information."))
from numpy.testing import Tester
test = Tester().test
| valexandersaulys/airbnb_kaggle_contest | venv/lib/python3.4/site-packages/scipy/sparse/csgraph/__init__.py | Python | gpl-2.0 | 7,254 |
/**
* Copyright (c) 2009--2010 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.domain.action.kickstart;
/**
* KickstartInitiateAction
* @version $Rev$
*/
public class KickstartInitiateAction extends KickstartAction {
}
| shastah/spacewalk | java/code/src/com/redhat/rhn/domain/action/kickstart/KickstartInitiateAction.java | Java | gpl-2.0 | 798 |
<?php
/**
* Joomla! Content Management System
*
* @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\CMS\Feed\Parser;
defined('JPATH_PLATFORM') or die;
use Joomla\CMS\Feed\Feed;
use Joomla\CMS\Feed\FeedEntry;
use Joomla\CMS\Feed\FeedLink;
use Joomla\CMS\Feed\FeedParser;
use Joomla\CMS\Feed\FeedPerson;
/**
* RSS Feed Parser class.
*
* @link http://cyber.law.harvard.edu/rss/rss.html
* @since 3.1.4
*/
class RssParser extends FeedParser
{
/**
* @var string The feed element name for the entry elements.
* @since 3.1.4
*/
protected $entryElementName = 'item';
/**
* @var string The feed format version.
* @since 3.1.4
*/
protected $version;
/**
* Method to handle the `<category>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleCategory(Feed $feed, \SimpleXMLElement $el)
{
// Get the data from the element.
$domain = (string) $el['domain'];
$category = (string) $el;
$feed->addCategory($category, $domain);
}
/**
* Method to handle the `<cloud>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleCloud(Feed $feed, \SimpleXMLElement $el)
{
$cloud = new \stdClass;
$cloud->domain = (string) $el['domain'];
$cloud->port = (string) $el['port'];
$cloud->path = (string) $el['path'];
$cloud->protocol = (string) $el['protocol'];
$cloud->registerProcedure = (string) $el['registerProcedure'];
$feed->cloud = $cloud;
}
/**
* Method to handle the `<copyright>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleCopyright(Feed $feed, \SimpleXMLElement $el)
{
$feed->copyright = (string) $el;
}
/**
* Method to handle the `<description>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleDescription(Feed $feed, \SimpleXMLElement $el)
{
$feed->description = (string) $el;
}
/**
* Method to handle the `<generator>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleGenerator(Feed $feed, \SimpleXMLElement $el)
{
$feed->generator = (string) $el;
}
/**
* Method to handle the `<image>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleImage(Feed $feed, \SimpleXMLElement $el)
{
// Create a feed link object for the image.
$image = new FeedLink(
(string) $el->url,
null,
'logo',
null,
(string) $el->title
);
// Populate extra fields if they exist.
$image->link = (string) $el->link;
$image->description = (string) $el->description;
$image->height = (string) $el->height;
$image->width = (string) $el->width;
$feed->image = $image;
}
/**
* Method to handle the `<language>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleLanguage(Feed $feed, \SimpleXMLElement $el)
{
$feed->language = (string) $el;
}
/**
* Method to handle the `<lastBuildDate>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleLastBuildDate(Feed $feed, \SimpleXMLElement $el)
{
$feed->updatedDate = (string) $el;
}
/**
* Method to handle the `<link>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleLink(Feed $feed, \SimpleXMLElement $el)
{
$link = new FeedLink;
$link->uri = (string) $el['href'];
$feed->link = $link;
}
/**
* Method to handle the `<managingEditor>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleManagingEditor(Feed $feed, \SimpleXMLElement $el)
{
$feed->author = $this->processPerson((string) $el);
}
/**
* Method to handle the `<skipDays>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleSkipDays(Feed $feed, \SimpleXMLElement $el)
{
// Initialise the array.
$days = array();
// Add all of the day values from the feed to the array.
foreach ($el->day as $day)
{
$days[] = (string) $day;
}
$feed->skipDays = $days;
}
/**
* Method to handle the `<skipHours>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleSkipHours(Feed $feed, \SimpleXMLElement $el)
{
// Initialise the array.
$hours = array();
// Add all of the day values from the feed to the array.
foreach ($el->hour as $hour)
{
$hours[] = (int) $hour;
}
$feed->skipHours = $hours;
}
/**
* Method to handle the `<pubDate>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handlePubDate(Feed $feed, \SimpleXMLElement $el)
{
$feed->publishedDate = (string) $el;
}
/**
* Method to handle the `<title>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleTitle(Feed $feed, \SimpleXMLElement $el)
{
$feed->title = (string) $el;
}
/**
* Method to handle the `<ttl>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleTtl(Feed $feed, \SimpleXMLElement $el)
{
$feed->ttl = (integer) $el;
}
/**
* Method to handle the `<webmaster>` element for the feed.
*
* @param Feed $feed The Feed object being built from the parsed feed.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function handleWebmaster(Feed $feed, \SimpleXMLElement $el)
{
// Get the tag contents and split it over the first space.
$tmp = (string) $el;
$tmp = explode(' ', $tmp, 2);
// This is really cheap parsing. Probably need to create a method to do this more robustly.
$name = null;
if (isset($tmp[1]))
{
$name = trim($tmp[1], ' ()');
}
$email = trim($tmp[0]);
$feed->addContributor($name, $email, null, 'webmaster');
}
/**
* Method to initialise the feed for parsing. Here we detect the version and advance the stream
* reader so that it is ready to parse feed elements.
*
* @return void
*
* @since 3.1.4
*/
protected function initialise()
{
// Read the version attribute.
$this->version = $this->stream->getAttribute('version');
// We want to move forward to the first element after the <channel> element.
$this->moveToNextElement('channel');
$this->moveToNextElement();
}
/**
* Method to handle a `<item>` element for the feed.
*
* @param FeedEntry $entry The FeedEntry object being built from the parsed feed entry.
* @param \SimpleXMLElement $el The current XML element object to handle.
*
* @return void
*
* @since 3.1.4
*/
protected function processFeedEntry(FeedEntry $entry, \SimpleXMLElement $el)
{
$entry->uri = (string) $el->link;
$entry->title = (string) $el->title;
$entry->publishedDate = (string) $el->pubDate;
$entry->updatedDate = (string) $el->pubDate;
$entry->content = (string) $el->description;
$entry->guid = (string) $el->guid;
$entry->isPermaLink = $entry->guid === '' || (string) $el->guid['isPermaLink'] === 'false' ? false : true;
$entry->comments = (string) $el->comments;
// Add the feed entry author if available.
$author = (string) $el->author;
if (!empty($author))
{
$entry->author = $this->processPerson($author);
}
// Add any categories to the entry.
foreach ($el->category as $category)
{
$entry->addCategory((string) $category, (string) $category['domain']);
}
// Add any enclosures to the entry.
foreach ($el->enclosure as $enclosure)
{
$link = new FeedLink(
(string) $enclosure['url'],
null,
(string) $enclosure['type'],
null,
null,
(int) $enclosure['length']
);
$entry->addLink($link);
}
}
/**
* Method to parse a string with person data and return a FeedPerson object.
*
* @param string $data The string to parse for a person.
*
* @return FeedPerson
*
* @since 3.1.4
*/
protected function processPerson($data)
{
// Create a new person object.
$person = new FeedPerson;
// This is really cheap parsing, but so far good enough. :)
$data = explode(' ', $data, 2);
if (isset($data[1]))
{
$person->name = trim($data[1], ' ()');
}
// Set the email for the person.
$person->email = trim($data[0]);
return $person;
}
}
| IOC/joomla3 | libraries/src/Feed/Parser/RssParser.php | PHP | gpl-2.0 | 11,247 |
// Copyright 2010 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include "InputCommon/ControllerEmu/ControllerEmu.h"
#include <memory>
#include <mutex>
#include <string>
#include "Common/IniFile.h"
#include "InputCommon/ControlReference/ControlReference.h"
#include "InputCommon/ControllerEmu/Control/Control.h"
#include "InputCommon/ControllerEmu/ControlGroup/ControlGroup.h"
#include "InputCommon/ControllerEmu/ControlGroup/Extension.h"
#include "InputCommon/ControllerInterface/ControllerInterface.h"
namespace ControllerEmu
{
static std::recursive_mutex s_get_state_mutex;
EmulatedController::~EmulatedController() = default;
// This should be called before calling GetState() or State() on a control reference
// to prevent a race condition.
// This is a recursive mutex because UpdateReferences is recursive.
std::unique_lock<std::recursive_mutex> EmulatedController::GetStateLock()
{
std::unique_lock<std::recursive_mutex> lock(s_get_state_mutex);
return lock;
}
void EmulatedController::UpdateReferences(const ControllerInterface& devi)
{
const auto lock = GetStateLock();
m_default_device_is_connected = devi.HasConnectedDevice(m_default_device);
for (auto& ctrlGroup : groups)
{
for (auto& control : ctrlGroup->controls)
control->control_ref.get()->UpdateReference(devi, GetDefaultDevice());
// extension
if (ctrlGroup->type == GroupType::Extension)
{
for (auto& attachment : ((Extension*)ctrlGroup.get())->attachments)
attachment->UpdateReferences(devi);
}
}
}
bool EmulatedController::IsDefaultDeviceConnected() const
{
return m_default_device_is_connected;
}
const ciface::Core::DeviceQualifier& EmulatedController::GetDefaultDevice() const
{
return m_default_device;
}
void EmulatedController::SetDefaultDevice(const std::string& device)
{
ciface::Core::DeviceQualifier devq;
devq.FromString(device);
SetDefaultDevice(std::move(devq));
}
void EmulatedController::SetDefaultDevice(ciface::Core::DeviceQualifier devq)
{
m_default_device = std::move(devq);
for (auto& ctrlGroup : groups)
{
// extension
if (ctrlGroup->type == GroupType::Extension)
{
for (auto& ai : ((Extension*)ctrlGroup.get())->attachments)
{
ai->SetDefaultDevice(m_default_device);
}
}
}
}
void EmulatedController::LoadConfig(IniFile::Section* sec, const std::string& base)
{
std::string defdev = GetDefaultDevice().ToString();
if (base.empty())
{
sec->Get(base + "Device", &defdev, "");
SetDefaultDevice(defdev);
}
for (auto& cg : groups)
cg->LoadConfig(sec, defdev, base);
}
void EmulatedController::SaveConfig(IniFile::Section* sec, const std::string& base)
{
const std::string defdev = GetDefaultDevice().ToString();
if (base.empty())
sec->Set(/*std::string(" ") +*/ base + "Device", defdev, "");
for (auto& ctrlGroup : groups)
ctrlGroup->SaveConfig(sec, defdev, base);
}
void EmulatedController::LoadDefaults(const ControllerInterface& ciface)
{
// load an empty inifile section, clears everything
IniFile::Section sec;
LoadConfig(&sec);
const std::string& default_device_string = ciface.GetDefaultDeviceString();
if (!default_device_string.empty())
{
SetDefaultDevice(default_device_string);
}
}
} // namespace ControllerEmu
| delroth/dolphin | Source/Core/InputCommon/ControllerEmu/ControllerEmu.cpp | C++ | gpl-2.0 | 3,349 |
<?php
/**
* File containing the eZURLAliasMLTest class
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
* @version //autogentag//
* @package tests
*/
class eZURLAliasMLTest extends ezpDatabaseTestCase
{
public function __construct()
{
parent::__construct();
$this->setName( "URL Alias ML Unit Tests" );
}
public function setUp()
{
parent::setUp();
$this->language = eZContentLanguage::addLanguage( "nor-NO", "Norsk" );
// Make sure all tests are done using utf-8 as charset
$this->charset = $GLOBALS['eZTextCodecInternalCharsetReal'];
$GLOBALS['eZTextCodecInternalCharsetReal'] = 'utf-8';
}
public function tearDown()
{
$GLOBALS['eZTextCodecInternalCharsetReal'] = $this->charset;
eZContentLanguage::removeLanguage( $this->language->ID );
parent::tearDown();
}
public function testStrtolower()
{
$testString = "ÂLL WORK AND NO PLAY MAKES ウーラ A DULL BOY.";
$testStringLowerCase = "âll work and no play makes ウーラ a dull boy.";
$resultString = eZURLAliasML::strtolower( $testString );
self::assertEquals( $testStringLowerCase, $resultString );
}
public function testCreate()
{
$text = "test";
$action = "eznode:5";
$parentID = 2;
$language = 2;
$url = eZURLAliasML::create( $text, $action, $parentID, $language );
self::assertEquals( $text, $url->attribute( 'text' ) );
self::assertEquals( $action, $url->attribute( 'action' ) );
self::assertEquals( $parentID, $url->attribute( 'parent' ) );
self::assertEquals( $language, $url->attribute( 'lang_mask' ) );
}
public function testRemoveByAction()
{
$nodeID = mt_rand();
$action = "eznode:$nodeID";
$url = eZURLAliasML::create( __FUNCTION__, $action, 1, 2 );
$url->store();
$db = eZDB::instance();
$query = "SELECT * from ezurlalias_ml where action = '$action'";
// Make sure we have one and only one url
$result = $db->arrayQuery( $query );
if ( count( $result ) !== 1 )
self::fail( "There was already an url with same action ($action) as our test in the database." );
// Remove the url and verify that it's gone
eZURLAliasML::removeByAction( "eznode", $nodeID );
$result = $db->arrayQuery( $query );
self::assertEquals( count( $result ), 0 );
}
public function testGetChildren()
{
$action = "eznode:" . mt_rand();
$parent = eZURLAliasML::create( __FUNCTION__ . "Parent", $action, 1, 2 );
$parent->store();
$child1 = eZURLAliasML::create( __FUNCTION__ . "Child1", $action, $parent->ID, 2 );
$child1->store();
$child2 = eZURLAliasML::create( __FUNCTION__ . "Child2", $action, $parent->ID, 2 );
$child2->store();
$child3 = eZURLAliasML::create( __FUNCTION__ . "Child3", $action, $parent->ID, 4 );
$child3->store();
$children = $parent->getChildren();
// Number of children should be 2 (child3 has different language and
// should not be included in getChildren()).
self::assertEquals( 2, count( $children ) );
self::assertEquals( (int) $child1->attribute( 'id' ), (int) $children[0]->attribute( 'id' ) );
self::assertEquals( (int) $child2->attribute( 'id' ), (int) $children[1]->attribute( 'id' ) );
}
public function testGetPath()
{
$action = "eznode:" . mt_rand();
$expectedPath = "/testGetPathParent/testGetPathChild1/testGetPathChild2";
$parent = eZURLAliasML::create( __FUNCTION__ . "Parent", $action, 1, 2 );
$parent->store();
$child1 = eZURLAliasML::create( __FUNCTION__ . "Child1", $action, $parent->ID, 2 );
$child1->store();
$child2 = eZURLAliasML::create( __FUNCTION__ . "Child2", $action, $child1->ID, 4 );
$child2->store();
self::assertEquals( $expectedPath, $child2->getPath() );
}
public function testFindUniqueText()
{
$action = "eznode:" . mt_rand();
$childName = __FUNCTION__ . mt_rand() . " Child";
// Create a few children
$child1 = eZURLAliasML::create( $childName, $action, 0, 2 );
$child1->store();
$child2 = eZURLAliasML::create( $childName . "2", $action, 0, 2 );
$child2->store();
$child3 = eZURLAliasML::create( $childName . "3", $action, 0, 4 );
$child3->store();
// Since "Child", "Child2" and "Child3" is taken we should get "Child4" back.
$uniqueText = eZURLAliasML::findUniqueText( 0, $childName, "" );
self::assertEquals( $childName . "4", $uniqueText );
// By specifing action it should not check URLs which has the same
// action. This means we get the the name back, without any changes to it.
$uniqueText = eZURLAliasML::findUniqueText( 0, $childName, $action );
self::assertEquals( $childName, $uniqueText );
// Specify language of ezurlalias_ml entries we should check the text
// uniqeness against.
$uniqueText = eZURLAliasML::findUniqueText( 0, $childName . "3", "", false, 4 );
self::assertEquals( $childName . "32", $uniqueText );
}
public function testFindUniqueText_ReservedWords()
{
// Make sure a text with the same name as the "content" module will be
// changed to "content2"
$uniqueText = eZURLAliasML::findUniqueText( 0, "content", "" );
self::assertEquals( "content2", $uniqueText );
}
public function testSetLangMaskAlwaysAvailable()
{
$nodeID = mt_rand();
// Create an ezurlalias_ml entry
$url = eZURLAliasML::create( __FUNCTION__ . $nodeID, "eznode:" . $nodeID, 0, 2 );
$url->store();
// Update lang_mask by setting always available,
eZURLAliasML::setLangMaskAlwaysAvailable( 2, "eznode", $nodeID );
// Verify that language mask was increased to 3.
$urls = eZURLAliasML::fetchByAction( 'eznode', $nodeID );
self::assertEquals( 3, (int) $urls[0]->attribute( 'lang_mask' ) );
// Update lang_mask by removing always available,
eZURLAliasML::setLangMaskAlwaysAvailable( false, "eznode", $nodeID );
// Verify that language mask was reduced back to 2.
$urls = eZURLAliasML::fetchByAction( 'eznode', $nodeID );
self::assertEquals( 2, (int) $urls[0]->attribute( 'lang_mask' ) );
}
//
public function testChoosePrioritizedRow()
{
// Make sure we can see all languages
ezpINIHelper::setINISetting( 'site.ini', 'RegionalSettings', 'ShowUntranslatedObjects', 'enabled' );
$action = "eznode:" . mt_rand();
$name = __FUNCTION__ . mt_rand();
$engGB = eZContentLanguage::fetchByLocale( 'eng-GB' );
$norNO = eZContentLanguage::fetchByLocale( 'nor-NO' );
// Create an english entry
$url1 = eZURLAliasML::create( $name . " en", $action, 0, $engGB->attribute( 'id' ) );
$url1->store();
// Create a norwegian entry
$url2 = eZURLAliasML::create( $name . " no", $action, 0, $norNO->attribute( 'id' ) );
$url2->store();
// Fetch the created entries. choosePrioritizedRow() wants rows from the
// database so our eZURLAliasML objects wont work.
$db = eZDB::instance();
$rows = $db->arrayQuery( "SELECT * FROM ezurlalias_ml where action = '$action'" );
// -------------------------------------------------------------------
// TEST PART 1 - NORMAL PRIORITIZATION -------------------------------
// The order of the language array also determines the prioritization.
// In this case 'eng-GB' should be prioritized before 'nor-NO'.
$languageList = array( "eng-GB", "nor-NO" );
ezpINIHelper::setINISetting( 'site.ini', 'RegionalSettings', 'SiteLanguageList', $languageList );
eZContentLanguage::clearPrioritizedLanguages();
$row = eZURLAliasML::choosePrioritizedRow( $rows );
// The prioritzed language should be 'eng-GB'
self::assertEquals( $engGB->attribute( 'id' ), $row["lang_mask"] );
// -------------------------------------------------------------------
// TEST PART 2 - REVERSED PRIORITIZATION -----------------------------
// Reverse the order of the specified languages, this will also
// reverse the priority.
$languageList = array_reverse( $languageList );
ezpINIHelper::setINISetting( 'site.ini', 'RegionalSettings', 'SiteLanguageList', $languageList );
eZContentLanguage::clearPrioritizedLanguages();
$row = eZURLAliasML::choosePrioritizedRow( $rows );
// The prioritzed language should be 'nor-NO'
self::assertEquals( $norNO->attribute( 'id' ), $row["lang_mask"] );
// -------------------------------------------------------------------
// TEST TEAR DOWN ----------------------------------------------------
ezpINIHelper::restoreINISettings();
// -------------------------------------------------------------------
}
public function testActionToURL()
{
$action1 = "nop:5";
$action2 = "module:content";
$action3 = "eznode:500";
$invalidAction1 = "eznode:invalid";
$invalidAction2 = "unknownaction:invalid";
$invalidAction3 = "this is a invalid action";
// Test valid actions
self::assertEquals( "/", eZURLAliasML::actionToURL( $action1 ) );
self::assertEquals( "content", eZURLAliasML::actionToURL( $action2 ) );
self::assertEquals( "content/view/full/500", eZURLAliasML::actionToURL( $action3 ) );
// Test invalid actions
self::assertEquals( false, eZURLAliasML::actionToURL( $invalidAction1 ) );
self::assertEquals( false, eZURLAliasML::actionToURL( $invalidAction2 ) );
self::assertEquals( false, eZURLAliasML::actionToURL( $invalidAction3 ) );
}
public function testURLToAction()
{
$url1 = "content/view/full/123";
$url2 = "user/register";
$invalidUrl1 = "/content/view/full/123";
$invalidUrl2 = "unknown/module";
// Test valid urls
self::assertEquals( "eznode:123", eZURLAliasML::urlToAction( $url1 ) );
self::assertEquals( "module:user/register", eZURLAliasML::urlToAction( $url2 ) );
// Test invalid urls
self::assertEquals( false, eZURLAliasML::urlToAction( $invalidUrl1 ) );
self::assertEquals( false, eZURLAliasML::urlToAction( $invalidUrl2 ) );
}
public function testCleanURL()
{
$url1 = "/content/view/full/2";
$url2 = "/////content/view/full/2/";
$url3 = "/content/view/full/2///";
$url4 = "///content/view/full/2///";
$url5 = "/content/view//full/2/";
self::assertEquals( "content/view/full/2", eZURLAliasML::cleanURL( $url1 ) );
self::assertEquals( "content/view/full/2", eZURLAliasML::cleanURL( $url2 ) );
self::assertEquals( "content/view/full/2", eZURLAliasML::cleanURL( $url3 ) );
self::assertEquals( "content/view/full/2", eZURLAliasML::cleanURL( $url4 ) );
self::assertEquals( "content/view//full/2", eZURLAliasML::cleanURL( $url5 ) );
// Make sure funky characters doesn't get messed up
$invalidUrl = "/ウーラ/";
self::assertEquals( "ウーラ", eZURLAliasML::cleanURL( $invalidUrl ) );
}
public function testSanitizeURL()
{
$url1 = "/content/view/full/2";
$url2 = "/////content/view/full/2/";
$url3 = "/content/view/full/2///";
$url4 = "///content/view/full/2///";
$url5 = "///content///view////full//2///";
self::assertEquals( "content/view/full/2", eZURLAliasML::sanitizeURL( $url1 ) );
self::assertEquals( "content/view/full/2", eZURLAliasML::sanitizeURL( $url2 ) );
self::assertEquals( "content/view/full/2", eZURLAliasML::sanitizeURL( $url3 ) );
self::assertEquals( "content/view/full/2", eZURLAliasML::sanitizeURL( $url4 ) );
self::assertEquals( "content/view/full/2", eZURLAliasML::sanitizeURL( $url5 ) );
// Make sure funky characters doesn't get messed up
$invalidUrl = "//ウ//ー//ラ//";
self::assertEquals( "ウ/ー/ラ", eZURLAliasML::sanitizeURL( $invalidUrl ) );
}
public function testConvertToAlias_Unicode()
{
// We set the below ini settings to make sure they are not accidentally
// overriden in somewhere in the test installation.
ezpINIHelper::setINISetting( 'site.ini', 'URLTranslator', 'WordSeparator', 'dash' );
ezpINIHelper::setINISetting( 'site.ini', 'URLTranslator', 'TransformationGroup', 'urlalias_iri' );
// ---------------------------------------------------------------- //
// Not safe characters, all of these should be removed.
$e1 = " &;/:=?%[]()+#\t";
$e1Result = "_1";
// Safe characters. No char should be removed.
// (dot isallowed exepct beginning/end of url).
$e2 = "$-_.!*',{}^§±@";
$e2Result = $e2;
// Random selection of funky characters. No chars should be removed.
$e3 = "ウңҏѫあギᄍㄇᠢ⻲㆞ญ฿";
$e3Result = $e3;
// Make sure multiple dots are turned into a seperator (-)
$e4 = "..a...........b..";
$e4Result = "a-b";
self::assertEquals( $e1Result, eZURLAliasML::convertToAlias( $e1 ) );
self::assertEquals( $e2Result, eZURLAliasML::convertToAlias( $e2 ) );
self::assertEquals( $e3Result, eZURLAliasML::convertToAlias( $e3 ) );
self::assertEquals( $e4Result, eZURLAliasML::convertToAlias( $e4 ) );
// ---------------------------------------------------------------- //
// Restore ini settings to their original values
ezpINIHelper::restoreINISettings();
}
public function testConvertToAlias_NonUnicode()
{
// We set the below ini settings to make sure they are not accidentally
// overriden in somewhere in the test installation.
ezpINIHelper::setINISetting( 'site.ini', 'URLTranslator', 'WordSeparator', 'dash' );
ezpINIHelper::setINISetting( 'site.ini', 'URLTranslator', 'TransformationGroup', 'urlalias' );
// ---------------------------------------------------------------- //
// Not safe characters, all of these should be removed.
$e1 = " &;/:=?[]()+#/{}$*',^§±@";
$e1Result = "_1";
// Safe characters. No char should be removed.
// (dot is allowed except beginning/end of url). Double dots are removed.
$e2 = "abcdefghijklmnopqrstuvwxyz0123456789_.a";
$e2Result = "abcdefghijklmnopqrstuvwxyz0123456789_.a";
// Random selection of funky characters. All chars should be removed.
$e3 = "ウңҏѫあギᄍㄇᠢ⻲㆞ญ฿";
$e3Result = "_1";
// Make sure multiple dots are turned into a seperator (-) (dot is
// allowed exepct beginning/end of url).
$e4 = "..a...........b..";
$e4Result = "a-b";
self::assertEquals( $e1Result, eZURLAliasML::convertToAlias( $e1 ) );
self::assertEquals( $e2Result, eZURLAliasML::convertToAlias( $e2 ) );
self::assertEquals( $e3Result, eZURLAliasML::convertToAlias( $e3 ) );
self::assertEquals( $e4Result, eZURLAliasML::convertToAlias( $e4 ) );
// ---------------------------------------------------------------- //
ezpINIHelper::restoreINISettings();
}
public function testConvertToAlias_Compat()
{
// We set the below ini settings to make sure they are not accidentally
// overriden in somewhere in the test installation.
ezpINIHelper::setINISetting( 'site.ini', 'URLTranslator', 'WordSeparator', 'underscore' );
ezpINIHelper::setINISetting( 'site.ini', 'URLTranslator', 'TransformationGroup', 'urlalias_compat' );
// ---------------------------------------------------------------- //
// Not safe characters, all of these should be removed.
$e1 = " &;/:=?[]()+#/{}$*',^§±@.!_";
$e1Result = "_1";
// Safe characters. No char should be removed.
$e2 = "abcdefghijklmnopqrstuvwxyz0123456789";
$e2Result = $e2;
// Random selection of funky characters. All chars should be removed.
$e3 = "ウңҏѫあギᄍㄇᠢ⻲㆞ญ฿";
$e3Result = "_1";
// Make sure uppercase chars gets converted to lowercase.
$e4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$e4Result = "abcdefghijklmnopqrstuvwxyz";
// Make sure multiple dots are turned into a seperator (-) (dot is
// allowed exepct beginning/end of url).
$e5 = "..a...........b..";
$e5Result = "a_b";
self::assertEquals( $e1Result, eZURLAliasML::convertToAlias( $e1 ) );
self::assertEquals( $e2Result, eZURLAliasML::convertToAlias( $e2 ) );
self::assertEquals( $e3Result, eZURLAliasML::convertToAlias( $e3 ) );
self::assertEquals( $e4Result, eZURLAliasML::convertToAlias( $e4 ) );
self::assertEquals( $e5Result, eZURLAliasML::convertToAlias( $e5 ) );
// ---------------------------------------------------------------- //
ezpINIHelper::restoreINISettings();
}
public function testNodeIDFromAction()
{
$action1 = "eznod:2"; // not valid action
$action2 = " "; // not valid action
$action3 = "eznode;2"; // not valid action
$action4 = "ezblaa:2"; // not valid action
$action5 = "eznode:2"; // valid action
self::assertEquals( false, eZURLAliasML::nodeIDFromAction( $action1 ) );
self::assertEquals( false, eZURLAliasML::nodeIDFromAction( $action2 ) );
self::assertEquals( false, eZURLAliasML::nodeIDFromAction( $action3 ) );
self::assertEquals( false, eZURLAliasML::nodeIDFromAction( $action4 ) );
self::assertEquals( (int) 2, eZURLAliasML::nodeIDFromAction( $action5 ) );
}
}
?>
| petrmifek/ezpublish-legacy | tests/tests/kernel/classes/urlaliasml_test.php | PHP | gpl-2.0 | 18,346 |
from sympy import *
from sympy.printing import print_ccode
from sympy.physics.vector import ReferenceFrame, gradient, divergence
from sympy.vector import CoordSysCartesian
R = ReferenceFrame('R');
x = R[0]; y = R[1];
a=-0.5; b=1.5;
visc=1e-1;
lambda_=(1/(2*visc)-sqrt(1/(4*visc**2)+4*pi**2));
print(" visc=%f" % visc)
u=[0,0]
u[0]=1-exp(lambda_*x)*cos(2*pi*y);
u[1]=lambda_/(2*pi)*exp(lambda_*x)*sin(2*pi*y);
p=(exp(3*lambda_)-exp(-lambda_))/(8*lambda_)-exp(2*lambda_*x)/2;
p=p - integrate(p, (x,a,b));
grad_p = gradient(p, R).to_matrix(R)
f0 = -divergence(visc*gradient(u[0], R), R) + grad_p[0];
f1 = -divergence(visc*gradient(u[1], R), R) + grad_p[1];
f2 = divergence(u[0]*R.x + u[1]*R.y, R);
print("\n * RHS:")
print(ccode(f0, assign_to = "values[0]"));
print(ccode(f1, assign_to = "values[1]"));
print(ccode(f2, assign_to = "values[2]"));
print("\n * ExactSolution:")
print(ccode(u[0], assign_to = "values[0]"));
print(ccode(u[1], assign_to = "values[1]"));
print(ccode(p, assign_to = "values[2]"));
print("")
print("pressure mean:", N(integrate(p,(x,a,b))))
| pesser/dealii | examples/step-55/reference.py | Python | lgpl-2.1 | 1,071 |
package store
import (
"strings"
"github.com/docker/swarmkit/api"
"github.com/docker/swarmkit/manager/state"
memdb "github.com/hashicorp/go-memdb"
)
const tableService = "service"
func init() {
register(ObjectStoreConfig{
Name: tableService,
Table: &memdb.TableSchema{
Name: tableService,
Indexes: map[string]*memdb.IndexSchema{
indexID: {
Name: indexID,
Unique: true,
Indexer: serviceIndexerByID{},
},
indexName: {
Name: indexName,
Unique: true,
Indexer: serviceIndexerByName{},
},
},
},
Save: func(tx ReadTx, snapshot *api.StoreSnapshot) error {
var err error
snapshot.Services, err = FindServices(tx, All)
return err
},
Restore: func(tx Tx, snapshot *api.StoreSnapshot) error {
services, err := FindServices(tx, All)
if err != nil {
return err
}
for _, s := range services {
if err := DeleteService(tx, s.ID); err != nil {
return err
}
}
for _, s := range snapshot.Services {
if err := CreateService(tx, s); err != nil {
return err
}
}
return nil
},
ApplyStoreAction: func(tx Tx, sa *api.StoreAction) error {
switch v := sa.Target.(type) {
case *api.StoreAction_Service:
obj := v.Service
switch sa.Action {
case api.StoreActionKindCreate:
return CreateService(tx, obj)
case api.StoreActionKindUpdate:
return UpdateService(tx, obj)
case api.StoreActionKindRemove:
return DeleteService(tx, obj.ID)
}
}
return errUnknownStoreAction
},
NewStoreAction: func(c state.Event) (api.StoreAction, error) {
var sa api.StoreAction
switch v := c.(type) {
case state.EventCreateService:
sa.Action = api.StoreActionKindCreate
sa.Target = &api.StoreAction_Service{
Service: v.Service,
}
case state.EventUpdateService:
sa.Action = api.StoreActionKindUpdate
sa.Target = &api.StoreAction_Service{
Service: v.Service,
}
case state.EventDeleteService:
sa.Action = api.StoreActionKindRemove
sa.Target = &api.StoreAction_Service{
Service: v.Service,
}
default:
return api.StoreAction{}, errUnknownStoreAction
}
return sa, nil
},
})
}
type serviceEntry struct {
*api.Service
}
func (s serviceEntry) ID() string {
return s.Service.ID
}
func (s serviceEntry) Meta() api.Meta {
return s.Service.Meta
}
func (s serviceEntry) SetMeta(meta api.Meta) {
s.Service.Meta = meta
}
func (s serviceEntry) Copy() Object {
return serviceEntry{s.Service.Copy()}
}
func (s serviceEntry) EventCreate() state.Event {
return state.EventCreateService{Service: s.Service}
}
func (s serviceEntry) EventUpdate() state.Event {
return state.EventUpdateService{Service: s.Service}
}
func (s serviceEntry) EventDelete() state.Event {
return state.EventDeleteService{Service: s.Service}
}
// CreateService adds a new service to the store.
// Returns ErrExist if the ID is already taken.
func CreateService(tx Tx, s *api.Service) error {
// Ensure the name is not already in use.
if tx.lookup(tableService, indexName, strings.ToLower(s.Spec.Annotations.Name)) != nil {
return ErrNameConflict
}
return tx.create(tableService, serviceEntry{s})
}
// UpdateService updates an existing service in the store.
// Returns ErrNotExist if the service doesn't exist.
func UpdateService(tx Tx, s *api.Service) error {
// Ensure the name is either not in use or already used by this same Service.
if existing := tx.lookup(tableService, indexName, strings.ToLower(s.Spec.Annotations.Name)); existing != nil {
if existing.ID() != s.ID {
return ErrNameConflict
}
}
return tx.update(tableService, serviceEntry{s})
}
// DeleteService removes a service from the store.
// Returns ErrNotExist if the service doesn't exist.
func DeleteService(tx Tx, id string) error {
return tx.delete(tableService, id)
}
// GetService looks up a service by ID.
// Returns nil if the service doesn't exist.
func GetService(tx ReadTx, id string) *api.Service {
s := tx.get(tableService, id)
if s == nil {
return nil
}
return s.(serviceEntry).Service
}
// FindServices selects a set of services and returns them.
func FindServices(tx ReadTx, by By) ([]*api.Service, error) {
checkType := func(by By) error {
switch by.(type) {
case byName, byIDPrefix:
return nil
default:
return ErrInvalidFindBy
}
}
serviceList := []*api.Service{}
appendResult := func(o Object) {
serviceList = append(serviceList, o.(serviceEntry).Service)
}
err := tx.find(tableService, by, checkType, appendResult)
return serviceList, err
}
type serviceIndexerByID struct{}
func (si serviceIndexerByID) FromArgs(args ...interface{}) ([]byte, error) {
return fromArgs(args...)
}
func (si serviceIndexerByID) FromObject(obj interface{}) (bool, []byte, error) {
s, ok := obj.(serviceEntry)
if !ok {
panic("unexpected type passed to FromObject")
}
// Add the null character as a terminator
val := s.Service.ID + "\x00"
return true, []byte(val), nil
}
func (si serviceIndexerByID) PrefixFromArgs(args ...interface{}) ([]byte, error) {
return prefixFromArgs(args...)
}
type serviceIndexerByName struct{}
func (si serviceIndexerByName) FromArgs(args ...interface{}) ([]byte, error) {
return fromArgs(args...)
}
func (si serviceIndexerByName) FromObject(obj interface{}) (bool, []byte, error) {
s, ok := obj.(serviceEntry)
if !ok {
panic("unexpected type passed to FromObject")
}
// Add the null character as a terminator
return true, []byte(strings.ToLower(s.Spec.Annotations.Name) + "\x00"), nil
}
| jlebon/docker | vendor/src/github.com/docker/swarmkit/manager/state/store/services.go | GO | apache-2.0 | 5,558 |
/*
* 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.axis2.jaxws.sample;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.axis2.jaxws.TestLogger;
import org.apache.axis2.jaxws.dispatch.DispatchTestConstants;
import org.apache.axis2.jaxws.framework.AbstractTestCase;
import org.apache.axis2.jaxws.sample.faults.FaultyWebServiceFault_Exception;
import org.apache.axis2.jaxws.sample.faults.FaultyWebServicePortType;
import org.apache.axis2.jaxws.sample.faults.FaultyWebServiceService;
import org.apache.axis2.jaxws.sample.wrap.sei.DocLitWrap;
import org.apache.axis2.jaxws.sample.wrap.sei.DocLitWrapService;
import org.apache.axis2.testutils.AllTestsWithRuntimeIgnore;
import org.junit.runner.RunWith;
import org.test.faults.FaultyWebServiceResponse;
import javax.xml.ws.AsyncHandler;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Response;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.soap.SOAPFaultException;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@RunWith(AllTestsWithRuntimeIgnore.class)
public class FaultyWebServiceTests extends AbstractTestCase {
String axisEndpoint = "http://localhost:6060/axis2/services/FaultyWebServiceService.FaultyWebServicePortTypeImplPort";
public static Test suite() {
return getTestSetup(new TestSuite(FaultyWebServiceTests.class));
}
public void testFaultyWebService(){
TestLogger.logger.debug("----------------------------------");
TestLogger.logger.debug("test: " + getName());
FaultyWebServiceService service = new FaultyWebServiceService();
FaultyWebServicePortType proxy = service.getFaultyWebServicePort();
FaultyWebServiceFault_Exception exception = null;
try{
exception = null;
BindingProvider p = (BindingProvider)proxy;
p.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,axisEndpoint);
// the invoke will throw an exception, if the test is performed right
int total = proxy.faultyWebService(10);
}catch(FaultyWebServiceFault_Exception e){
exception = e;
}catch(Exception e) {
e.printStackTrace();
fail(e.toString());
}
TestLogger.logger.debug("----------------------------------");
assertNotNull(exception);
assertEquals("custom exception", exception.getMessage());
assertNotNull(exception.getFaultInfo());
assertEquals("bean custom fault info", exception.getFaultInfo().getFaultInfo());
assertEquals("bean custom message", exception.getFaultInfo().getMessage());
// Repeat to verify behavior
try{
exception = null;
BindingProvider p = (BindingProvider)proxy;
p.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,axisEndpoint);
// the invoke will throw an exception, if the test is performed right
int total = proxy.faultyWebService(10);
}catch(FaultyWebServiceFault_Exception e){
exception = e;
}catch(Exception e) {
e.printStackTrace();
fail(e.toString());
}
TestLogger.logger.debug("----------------------------------");
assertNotNull(exception);
assertEquals("custom exception", exception.getMessage());
assertNotNull(exception.getFaultInfo());
assertEquals("bean custom fault info", exception.getFaultInfo().getFaultInfo());
assertEquals("bean custom message", exception.getFaultInfo().getMessage());
}
public void testFaultyWebService_badEndpoint() throws Exception {
String host = "this.is.a.bad.endpoint.terrible.in.fact";
String badEndpoint = "http://" + host;
checkUnknownHostURL(badEndpoint);
TestLogger.logger.debug("----------------------------------");
TestLogger.logger.debug("test: " + getName());
FaultyWebServiceService service = new FaultyWebServiceService();
FaultyWebServicePortType proxy = service.getFaultyWebServicePort();
WebServiceException exception = null;
try{
exception = null;
BindingProvider p = (BindingProvider)proxy;
p.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,badEndpoint);
// the invoke will throw an exception, if the test is performed right
int total = proxy.faultyWebService(10);
}catch(FaultyWebServiceFault_Exception e) {
// shouldn't get this exception
fail(e.toString());
}catch(WebServiceException e) {
exception = e;
}catch(Exception e) {
fail("This testcase should only produce a WebServiceException. We got: " + e.toString());
}
TestLogger.logger.debug("----------------------------------");
assertNotNull(exception);
assertTrue(exception.getCause() instanceof UnknownHostException);
assertTrue(exception.getCause().getMessage().indexOf(host)!=-1);
// Repeat to verify behavior
try{
exception = null;
BindingProvider p = (BindingProvider)proxy;
p.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,badEndpoint);
// the invoke will throw an exception, if the test is performed right
int total = proxy.faultyWebService(10);
}catch(FaultyWebServiceFault_Exception e) {
// shouldn't get this exception
fail(e.toString());
}catch(WebServiceException e) {
exception = e;
}catch(Exception e) {
fail("This testcase should only produce a WebServiceException. We got: " + e.toString());
}
TestLogger.logger.debug("----------------------------------");
assertNotNull(exception);
assertTrue(exception.getCause() instanceof UnknownHostException);
assertTrue(exception.getCause().getMessage().indexOf(host)!=-1);
}
// TODO should also have an invoke oneway bad endpoint test to make sure
// we get an exception as indicated in JAXWS 6.4.2.
public void testFaultyWebService_badEndpoint_oneWay() throws Exception {
String host = "this.is.a.bad.endpoint.terrible.in.fact";
String badEndpoint = "http://" + host;
checkUnknownHostURL(badEndpoint);
DocLitWrapService service = new DocLitWrapService();
DocLitWrap proxy = service.getDocLitWrapPort();
BindingProvider p = (BindingProvider)proxy;
p.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,badEndpoint);
WebServiceException exception = null;
TestLogger.logger.debug("------------------------------");
TestLogger.logger.debug("Test : " + getName());
try{
exception = null;
proxy.oneWayVoid();
}catch(WebServiceException e) {
exception = e;
}catch(Exception e) {
fail("This testcase should only produce a WebServiceException. We got: " + e.toString());
}
TestLogger.logger.debug("----------------------------------");
assertNotNull(exception);
assertTrue(exception.getCause() instanceof UnknownHostException);
assertTrue(exception.getCause().getMessage().indexOf(host)!=-1);
// Repeat to verify behavior
try{
exception = null;
proxy.oneWayVoid();
}catch(WebServiceException e) {
exception = e;
}catch(Exception e) {
fail("This testcase should only produce a WebServiceException. We got: " + e.toString());
}
TestLogger.logger.debug("----------------------------------");
assertNotNull(exception);
assertTrue(exception.getCause() instanceof UnknownHostException);
assertTrue(exception.getCause().getMessage().indexOf(host)!=-1);
}
public void testFaultyWebService_badEndpoint_AsyncCallback()
throws Exception {
String host = "this.is.a.bad.endpoint.terrible.in.fact";
String badEndpoint = "http://" + host;
TestLogger.logger.debug("------------------------------");
TestLogger.logger.debug("Test : " + getName());
FaultyWebServiceService service = new FaultyWebServiceService();
FaultyWebServicePortType proxy = service.getFaultyWebServicePort();
BindingProvider p = (BindingProvider) proxy;
p.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
badEndpoint);
FaultyAsyncHandler callback = new FaultyAsyncHandler();
Future<?> future = proxy.faultyWebServiceAsync(1, callback);
while (!future.isDone()) {
Thread.sleep(1000);
TestLogger.logger.debug("Async invocation incomplete");
}
Exception e = callback.getException();
// Section 4.3.3 states that the top level Exception should be
// an ExecutionException, with a WebServiceException underneath.
assertNotNull("The exception was null.", e);
assertTrue("The thrown exception should be an ExecutionException.", e
.getClass().equals(ExecutionException.class));
assertTrue(
"The expected fault type under the ExecutionException should be a "
+ "SOAPFaultException. Found type: "
+ e.getCause().getClass(), e.getCause().getClass()
.isAssignableFrom(SOAPFaultException.class));
// Repeat to verify behavior
callback = new FaultyAsyncHandler();
future = proxy.faultyWebServiceAsync(1, callback);
while (!future.isDone()) {
Thread.sleep(1000);
TestLogger.logger.debug("Async invocation incomplete");
}
e = callback.getException();
// Section 4.3.3 states that the top level Exception should be
// an ExecutionException, with a WebServiceException underneath.
assertNotNull("The exception was null.", e);
assertTrue("The thrown exception should be an ExecutionException.", e
.getClass().equals(ExecutionException.class));
assertTrue(
"The expected fault type under the ExecutionException should be a "
+ "SOAPFaultException. Found type: "
+ e.getCause().getClass(), e.getCause().getClass()
.isAssignableFrom(SOAPFaultException.class));
}
public void testFaultyWebService_badEndpoint_AsyncPolling()
throws Exception {
String host = "this.is.a.bad.endpoint.terrible.in.fact";
String badEndpoint = "http://" + host;
TestLogger.logger.debug("------------------------------");
TestLogger.logger.debug("Test : " + getName());
FaultyWebServiceService service = new FaultyWebServiceService();
FaultyWebServicePortType proxy = service.getFaultyWebServicePort();
BindingProvider p = (BindingProvider) proxy;
p.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
badEndpoint);
Future<?> future = proxy.faultyWebServiceAsync(1);
while (!future.isDone()) {
Thread.sleep(1000);
TestLogger.logger.debug("Async invocation incomplete");
}
Exception e = null;
try {
Object obj = future.get();
} catch (Exception ex) {
e = ex;
}
// Section 4.3.3 states that the top level Exception should be
// an ExecutionException, with a WebServiceException underneath.
assertNotNull("The exception was null.", e);
assertTrue("The thrown exception should be an ExecutionException.", e
.getClass().equals(ExecutionException.class));
assertTrue(
"The expected fault type under the ExecutionException should be a "
+ "SOAPFaultException. Found type: "
+ e.getCause().getClass(), e.getCause().getClass()
.isAssignableFrom(SOAPFaultException.class));
// Repeat to verify behavior
proxy.faultyWebServiceAsync(1);
while (!future.isDone()) {
Thread.sleep(1000);
TestLogger.logger.debug("Async invocation incomplete");
}
e = null;
try {
Object obj = future.get();
} catch (Exception ex) {
e = ex;
}
// Section 4.3.3 states that the top level Exception should be
// an ExecutionException, with a WebServiceException underneath.
assertNotNull("The exception was null.", e);
assertTrue("The thrown exception should be an ExecutionException.", e
.getClass().equals(ExecutionException.class));
assertTrue(
"The expected fault type under the ExecutionException should be a "
+ "SOAPFaultException. Found type: "
+ e.getCause().getClass(), e.getCause().getClass()
.isAssignableFrom(SOAPFaultException.class));
}
/*
* Tests fault processing for user defined fault types
*/
public void testCustomFault_AsyncCallback() throws Exception {
TestLogger.logger.debug("------------------------------");
TestLogger.logger.debug("test: " + getName());
FaultyWebServiceService service = new FaultyWebServiceService();
FaultyWebServicePortType proxy = service.getFaultyWebServicePort();
BindingProvider p = (BindingProvider) proxy;
p.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, axisEndpoint);
FaultyAsyncHandler callback = new FaultyAsyncHandler();
Future<?> future = proxy.faultyWebServiceAsync(1, callback);
while (!future.isDone()) {
Thread.sleep(1000);
TestLogger.logger.debug("Async invocation incomplete");
}
Exception e = callback.getException();
e.printStackTrace();
// Section 4.3.3 states that the top level Exception should be
// an ExecutionException, with a WebServiceException underneath.
assertNotNull("The exception was null.", e);
assertTrue("The thrown exception should be an ExecutionException.",
e.getClass().equals(ExecutionException.class));
assertTrue("The expected fault type under the ExecutionException should be a " +
"FaultyWebServiceFault_Exception. Found type: " + e.getCause().getClass(),
e.getCause().getClass().isAssignableFrom(FaultyWebServiceFault_Exception.class));
// Repeat to verify behavior
callback = new FaultyAsyncHandler();
future = proxy.faultyWebServiceAsync(1, callback);
while (!future.isDone()) {
Thread.sleep(1000);
TestLogger.logger.debug("Async invocation incomplete");
}
e = callback.getException();
e.printStackTrace();
// Section 4.3.3 states that the top level Exception should be
// an ExecutionException, with a WebServiceException underneath.
assertNotNull("The exception was null.", e);
assertTrue("The thrown exception should be an ExecutionException.",
e.getClass().equals(ExecutionException.class));
assertTrue("The expected fault type under the ExecutionException should be a " +
"FaultyWebServiceFault_Exception. Found type: " + e.getCause().getClass(),
e.getCause().getClass().isAssignableFrom(FaultyWebServiceFault_Exception.class));
}
/*
* A callback implementation that can be used to collect the exceptions
*/
class FaultyAsyncHandler implements AsyncHandler<FaultyWebServiceResponse> {
Exception exception;
public void handleResponse(Response<FaultyWebServiceResponse> response) {
try {
TestLogger.logger.debug("FaultyAsyncHandler.handleResponse() was called");
FaultyWebServiceResponse r = response.get();
TestLogger.logger.debug("No exception was thrown from Response.get()");
}
catch (Exception e) {
TestLogger.logger.debug("An exception was thrown: " + e.getClass());
exception = e;
}
}
public Exception getException() {
return exception;
}
}
}
| arunasujith/wso2-axis2 | modules/jaxws-integration/test/org/apache/axis2/jaxws/sample/FaultyWebServiceTests.java | Java | apache-2.0 | 18,011 |
/*
* Copyright (C) 2010 Apple 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "stdafx.h"
#include "BrowserWindow.h"
#include "MiniBrowser.h"
#include <assert.h>
MiniBrowser::MiniBrowser()
: m_instance(0)
{
}
MiniBrowser& MiniBrowser::shared()
{
static MiniBrowser miniBrowser;
return miniBrowser;
}
void MiniBrowser::initialize(HINSTANCE instance)
{
assert(!m_instance);
m_instance = instance;
}
void MiniBrowser::createNewWindow()
{
static const wchar_t* kDefaultURLString = L"http://webkit.org/";
BrowserWindow* browserWindow = BrowserWindow::create();
browserWindow->createWindow(0, 0, 800, 600);
browserWindow->showWindow();
browserWindow->goToURL(kDefaultURLString);
}
void MiniBrowser::registerWindow(BrowserWindow* window)
{
m_browserWindows.insert(window);
}
void MiniBrowser::unregisterWindow(BrowserWindow* window)
{
m_browserWindows.erase(window);
if (m_browserWindows.empty())
::PostQuitMessage(0);
}
bool MiniBrowser::handleMessage(const MSG* message)
{
for (std::set<BrowserWindow*>::const_iterator it = m_browserWindows.begin(), end = m_browserWindows.end(); it != end; ++it) {
BrowserWindow* browserWindow = *it;
if (browserWindow->handleMessage(message))
return true;
}
return false;
}
| mogoweb/webkit_for_android5.1 | webkit/Tools/MiniBrowser/win/MiniBrowser.cpp | C++ | apache-2.0 | 2,604 |
/*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "ZlibStreamCompressor.h"
#include <folly/Bits.h>
#include <folly/io/Cursor.h>
using namespace folly;
using folly::IOBuf;
using std::unique_ptr;
// IOBuf uses 24 bytes of data for bookeeping purposes, so requesting for 4073
// bytes of data will be rounded up to an allocation of 1 page.
#ifndef NO_LIB_GFLAGS
DEFINE_int64(zlib_compressor_buffer_growth, 2024,
"The buffer growth size to use during IOBuf zlib deflation");
DEFINE_int64(zlib_compressor_buffer_minsize, 1024,
"The minimum buffer size to use before growing during IOBuf "
"zlib deflation");
#endif
namespace proxygen {
#ifdef NO_LIB_GFLAGS
int64_t FLAGS_zlib_compressor_buffer_growth = 2024;
int64_t FLAGS_zlib_compressor_buffer_minsize = 1024;
#endif
void ZlibStreamCompressor::init(ZlibCompressionType type, int32_t level) {
DCHECK(type_ == ZlibCompressionType::NONE)
<< "Attempt to re-initialize compression stream";
type_ = type;
level_ = level;
status_ = Z_OK;
zlibStream_.zalloc = Z_NULL;
zlibStream_.zfree = Z_NULL;
zlibStream_.opaque = Z_NULL;
zlibStream_.total_in = 0;
zlibStream_.next_in = Z_NULL;
zlibStream_.avail_in = 0;
zlibStream_.avail_out = 0;
zlibStream_.next_out = Z_NULL;
DCHECK(level_ >= Z_NO_COMPRESSION && level_ <= Z_BEST_COMPRESSION)
<< "Invalid Zlib compression level. level=" << level_;
switch (type_) {
case ZlibCompressionType::GZIP:
status_ = deflateInit2(&zlibStream_,
level_,
Z_DEFLATED,
static_cast<int32_t>(type),
MAX_MEM_LEVEL,
Z_DEFAULT_STRATEGY);
break;
case ZlibCompressionType::DEFLATE:
status_ = deflateInit(&zlibStream_, level);
break;
default:
DCHECK(false) << "Unsupported zlib compression type.";
break;
}
if (status_ != Z_OK) {
LOG(ERROR) << "error initializing zlib stream. r=" << status_ ;
}
}
ZlibStreamCompressor::ZlibStreamCompressor(ZlibCompressionType type, int level)
: status_(Z_OK) {
init(type, level);
}
ZlibStreamCompressor::~ZlibStreamCompressor() {
if (type_ != ZlibCompressionType::NONE) {
status_ = deflateEnd(&zlibStream_);
}
}
// Compress an IOBuf chain. Compress can be called multiple times and the
// Zlib stream will be synced after each call. trailer must be set to
// true on the final compression call.
std::unique_ptr<IOBuf> ZlibStreamCompressor::compress(const IOBuf* in,
bool trailer) {
const IOBuf* crtBuf{in};
size_t offset{0};
int flush{Z_NO_FLUSH};
auto out = IOBuf::create(FLAGS_zlib_compressor_buffer_growth);
auto appender = folly::io::Appender(out.get(),
FLAGS_zlib_compressor_buffer_growth);
auto chunkSize = FLAGS_zlib_compressor_buffer_minsize;
do {
// Advance to the next IOBuf if necessary
DCHECK_GE(crtBuf->length(), offset);
if (crtBuf->length() == offset) {
crtBuf = crtBuf->next();
if (crtBuf == in) {
// We hit the end of the IOBuf chain, and are done.
// Need to flush the stream
// Completely flush if the final call, otherwise flush state
if (trailer) {
flush = Z_FINISH;
} else {
flush = Z_SYNC_FLUSH;
}
} else {
// Prepare to process next buffer
offset = 0;
}
}
if (status_ == Z_STREAM_ERROR) {
LOG(ERROR) << "error compressing buffer. r=" << status_;
return nullptr;
}
const size_t origAvailIn = crtBuf->length() - offset;
zlibStream_.next_in = const_cast<uint8_t*>(crtBuf->data() + offset);
zlibStream_.avail_in = origAvailIn;
// Zlib may not write it's entire state on the first pass.
do {
appender.ensure(chunkSize);
zlibStream_.next_out = appender.writableData();
zlibStream_.avail_out = chunkSize;
status_ = deflate(&zlibStream_, flush);
// Move output buffer ahead
auto outMove = chunkSize - zlibStream_.avail_out;
appender.append(outMove);
} while (zlibStream_.avail_out == 0);
DCHECK(zlibStream_.avail_in == 0);
// Adjust the input offset ahead
auto inConsumed = origAvailIn - zlibStream_.avail_in;
offset += inConsumed;
} while (flush != Z_FINISH && flush != Z_SYNC_FLUSH);
return out;
}
}
| raphaelamorim/proxygen | proxygen/lib/utils/ZlibStreamCompressor.cpp | C++ | bsd-3-clause | 4,682 |
<?php
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
namespace Propel\Tests\Generator\Builder\Om;
use Propel\Generator\Util\QuickBuilder;
use Propel\Runtime\Propel;
use Propel\Runtime\ActiveQuery\Criteria;
/**
* Tests the generated queries for array column types filters
*
* @author Francois Zaninotto
*/
class GeneratedQueryArrayColumnTypeTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
if (!class_exists('\ComplexColumnTypeEntity11')) {
$schema = <<<EOF
<database name="generated_object_complex_type_test_11">
<table name="complex_column_type_entity_11">
<column name="id" primaryKey="true" type="INTEGER" autoIncrement="true" />
<column name="tags" type="ARRAY" />
<column name="value_set" type="ARRAY" />
</table>
</database>
EOF;
QuickBuilder::buildSchema($schema);
$e0 = new \ComplexColumnTypeEntity11();
$e0->save();
$e1 = new \ComplexColumnTypeEntity11();
$e1->setTags(array('foo', 'bar', 'baz'));
$e1->save();
$e2 = new \ComplexColumnTypeEntity11();
$e2->setTags(array('bar'));
$e2->save();
$e3 = new \ComplexColumnTypeEntity11();
$e3->setTags(array('bar23'));
$e3->save();
}
}
public function testActiveQueryMethods()
{
$this->assertTrue(method_exists('\ComplexColumnTypeEntity11Query', 'filterByTags'));
$this->assertTrue(method_exists('\ComplexColumnTypeEntity11Query', 'filterByTag'));
// only plural column names get a singular filter
$this->assertTrue(method_exists('\ComplexColumnTypeEntity11Query', 'filterByValueSet'));
}
public function testColumnHydration()
{
$e = \ComplexColumnTypeEntity11Query::create()->orderById()->offset(1)->findOne();
$this->assertEquals(array('foo', 'bar', 'baz'), $e->getTags(), 'array columns are correctly hydrated');
}
public function testWhere()
{
$e = \ComplexColumnTypeEntity11Query::create()
->where('ComplexColumnTypeEntity11.Tags LIKE ?', '%| bar23 |%')
->find();
$this->assertEquals(1, $e->count());
$this->assertEquals(array('bar23'), $e[0]->getTags(), 'array columns are searchable by serialized object using where()');
$e = \ComplexColumnTypeEntity11Query::create()
->where('ComplexColumnTypeEntity11.Tags = ?', array('bar23'))
->find();
$this->assertEquals(1, $e->count());
$this->assertEquals(array('bar23'), $e[0]->getTags(), 'array columns are searchable by object using where()');
}
public function testFilterByColumn()
{
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTags(array('bar'))
->orderById()
->find();
$this->assertEquals(array('foo', 'bar', 'baz'), $e[0]->getTags(), 'array columns are searchable by element');
$this->assertEquals(array('bar'), $e[1]->getTags(), 'array columns are searchable by element');
$this->assertEquals(2, $e->count(), 'array columns do not return false positives');
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTags(array('bar23'))
->findOne();
$this->assertEquals(array('bar23'), $e->getTags(), 'array columns are searchable by element');
}
public function testFilterByColumnUsingContainsAll()
{
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTags(array(), Criteria::CONTAINS_ALL)
->find();
$this->assertEquals(4, $e->count());
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTags(array('bar'), Criteria::CONTAINS_ALL)
->orderById()
->find();
$this->assertEquals(2, $e->count());
$this->assertEquals(array('foo', 'bar', 'baz'), $e[0]->getTags());
$this->assertEquals(array('bar'), $e[1]->getTags());
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTags(array('bar23'), Criteria::CONTAINS_ALL)
->find();
$this->assertEquals(1, $e->count());
$this->assertEquals(array('bar23'), $e[0]->getTags());
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTags(array('foo', 'bar'), Criteria::CONTAINS_ALL)
->find();
$this->assertEquals(1, $e->count());
$this->assertEquals(array('foo', 'bar', 'baz'), $e[0]->getTags());
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTags(array('foo', 'bar23'), Criteria::CONTAINS_ALL)
->find();
$this->assertEquals(0, $e->count());
}
public function testFilterByColumnUsingContainsSome()
{
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTags(array(), Criteria::CONTAINS_SOME)
->find();
$this->assertEquals(4, $e->count());
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTags(array('bar'), Criteria::CONTAINS_SOME)
->orderById()
->find();
$this->assertEquals(2, $e->count());
$this->assertEquals(array('foo', 'bar', 'baz'), $e[0]->getTags());
$this->assertEquals(array('bar'), $e[1]->getTags());
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTags(array('bar23'), Criteria::CONTAINS_SOME)
->find();
$this->assertEquals(1, $e->count());
$this->assertEquals(array('bar23'), $e[0]->getTags());
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTags(array('foo', 'bar'), Criteria::CONTAINS_SOME)
->orderById()
->find();
$this->assertEquals(2, $e->count());
$this->assertEquals(array('foo', 'bar', 'baz'), $e[0]->getTags());
$this->assertEquals(array('bar'), $e[1]->getTags());
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTags(array('foo', 'bar23'), Criteria::CONTAINS_SOME)
->find();
$this->assertEquals(2, $e->count());
$this->assertEquals(array('foo', 'bar', 'baz'), $e[0]->getTags());
$this->assertEquals(array('bar23'), $e[1]->getTags());
}
public function testFilterByColumnUsingContainsNone()
{
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTags(array(), Criteria::CONTAINS_NONE)
->find();
$this->assertEquals(1, $e->count());
$this->assertEquals(array(), $e[0]->getTags());
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTags(array('bar'), Criteria::CONTAINS_NONE)
->orderById()
->find();
$this->assertEquals(2, $e->count());
$this->assertEquals(array(), $e[0]->getTags());
$this->assertEquals(array('bar23'), $e[1]->getTags());
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTags(array('bar23'), Criteria::CONTAINS_NONE)
->find();
$this->assertEquals(3, $e->count());
$this->assertEquals(array(), $e[0]->getTags());
$this->assertEquals(array('foo', 'bar', 'baz'), $e[1]->getTags());
$this->assertEquals(array('bar'), $e[2]->getTags());
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTags(array('foo', 'bar'), Criteria::CONTAINS_NONE)
->orderById()
->find();
$this->assertEquals(2, $e->count());
$this->assertEquals(array(), $e[0]->getTags());
$this->assertEquals(array('bar23'), $e[1]->getTags());
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTags(array('foo', 'bar23'), Criteria::CONTAINS_NONE)
->find();
$this->assertEquals(2, $e->count());
$this->assertEquals(array(), $e[0]->getTags());
$this->assertEquals(array('bar'), $e[1]->getTags());
}
public function testFilterBySingularColumn()
{
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTag('bar')
->orderById()
->find();
$this->assertEquals(array('foo', 'bar', 'baz'), $e[0]->getTags(), 'array columns are searchable by element');
$this->assertEquals(array('bar'), $e[1]->getTags(), 'array columns are searchable by element');
$this->assertEquals(2, $e->count(), 'array columns do not return false positives');
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTag('bar23')
->findOne();
$this->assertEquals(array('bar23'), $e->getTags(), 'array columns are searchable by element');
}
public function testFilterBySingularColumnUsingContainsAll()
{
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTag('bar', Criteria::CONTAINS_ALL)
->orderById()
->find();
$this->assertEquals(2, $e->count(), 'array columns are searchable by element using Criteria::CONTAINS_ALL');
$this->assertEquals(array('foo', 'bar', 'baz'), $e[0]->getTags(), 'array columns are searchable by element using Criteria::CONTAINS_ALL');
$this->assertEquals(array('bar'), $e[1]->getTags(), 'array columns are searchable by element using Criteria::CONTAINS_ALL');
}
public function testFilterBySingularColumnUsingContainsNone()
{
$e = \ComplexColumnTypeEntity11Query::create()
->filterByTag('bar', Criteria::CONTAINS_NONE)
->orderById()
->find();
$this->assertEquals(2, $e->count(), 'array columns are searchable by element using Criteria::CONTAINS_NONE');
$this->assertEquals(array(), $e[0]->getTags(), 'array columns are searchable by element using Criteria::CONTAINS_NONE');
$this->assertEquals(array('bar23'), $e[1]->getTags(), 'array columns are searchable by element using Criteria::CONTAINS_NONE');
}
}
| bitclaw/slim-api | vendor/propel/propel/tests/Propel/Tests/Generator/Builder/Om/GeneratedQueryArrayColumnTypeTest.php | PHP | mit | 10,110 |
// stdafx.cpp : source file that includes just the standard includes
// KronFit.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| plliao/FASTEN | src/stdafx.cpp | C++ | mit | 294 |
// Type definitions for textr 0.3
// Project: https://github.com/shuvalov-anton/textr
// Definitions by: Adam Zerella <https://github.com/adamzerella>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
type TextrArgs = string | object;
interface textr {
/**
* Register new middleware and array of middlewares.
*/
use(...fn: any): textr;
/**
* Process given text by the middlewares.
*/
exec(text: string, options?: object): string;
/**
* List of registred middlewares.
*/
mws(): string[];
}
declare function textr(defaults?: TextrArgs): textr;
export = textr;
| markogresak/DefinitelyTyped | types/textr/index.d.ts | TypeScript | mit | 633 |
<?php
namespace Illuminate\Tests\Cookie\Middleware;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Router;
use PHPUnit\Framework\TestCase;
use Illuminate\Cookie\CookieJar;
use Illuminate\Events\Dispatcher;
use Illuminate\Routing\Controller;
use Illuminate\Container\Container;
use Illuminate\Encryption\Encrypter;
use Symfony\Component\HttpFoundation\Cookie;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Contracts\Encryption\Encrypter as EncrypterContract;
class EncryptCookiesTest extends TestCase
{
/**
* @var Router
*/
protected $router;
protected $setCookiePath = 'cookie/set';
protected $queueCookiePath = 'cookie/queue';
public function setUp()
{
parent::setUp();
$container = new Container;
$container->singleton(EncrypterContract::class, function () {
return new Encrypter(str_repeat('a', 16));
});
$this->router = new Router(new Dispatcher, $container);
}
public function testSetCookieEncryption()
{
$this->router->get($this->setCookiePath, [
'middleware' => 'Illuminate\Tests\Cookie\Middleware\EncryptCookiesTestMiddleware',
'uses' => 'Illuminate\Tests\Cookie\Middleware\EncryptCookiesTestController@setCookies',
]);
$response = $this->router->dispatch(Request::create($this->setCookiePath, 'GET'));
$cookies = $response->headers->getCookies();
$this->assertCount(2, $cookies);
$this->assertEquals('encrypted_cookie', $cookies[0]->getName());
$this->assertNotEquals('value', $cookies[0]->getValue());
$this->assertEquals('unencrypted_cookie', $cookies[1]->getName());
$this->assertEquals('value', $cookies[1]->getValue());
}
public function testQueuedCookieEncryption()
{
$this->router->get($this->queueCookiePath, [
'middleware' => ['Illuminate\Tests\Cookie\Middleware\EncryptCookiesTestMiddleware', 'Illuminate\Tests\Cookie\Middleware\AddQueuedCookiesToResponseTestMiddleware'],
'uses' => 'Illuminate\Tests\Cookie\Middleware\EncryptCookiesTestController@queueCookies',
]);
$response = $this->router->dispatch(Request::create($this->queueCookiePath, 'GET'));
$cookies = $response->headers->getCookies();
$this->assertCount(2, $cookies);
$this->assertEquals('encrypted_cookie', $cookies[0]->getName());
$this->assertNotEquals('value', $cookies[0]->getValue());
$this->assertEquals('unencrypted_cookie', $cookies[1]->getName());
$this->assertEquals('value', $cookies[1]->getValue());
}
}
class EncryptCookiesTestController extends Controller
{
public function setCookies()
{
$response = new Response;
$response->headers->setCookie(new Cookie('encrypted_cookie', 'value'));
$response->headers->setCookie(new Cookie('unencrypted_cookie', 'value'));
return $response;
}
public function queueCookies()
{
return new Response;
}
}
class EncryptCookiesTestMiddleware extends EncryptCookies
{
protected $except = [
'unencrypted_cookie',
];
}
class AddQueuedCookiesToResponseTestMiddleware extends AddQueuedCookiesToResponse
{
public function __construct()
{
$cookie = new CookieJar;
$cookie->queue(new Cookie('encrypted_cookie', 'value'));
$cookie->queue(new Cookie('unencrypted_cookie', 'value'));
$this->cookies = $cookie;
}
}
| guiwoda/framework | tests/Cookie/Middleware/EncryptCookiesTest.php | PHP | mit | 3,594 |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 96);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports) {
module.exports = jQuery;
/***/ }),
/***/ 1:
/***/ (function(module, exports) {
module.exports = {Foundation: window.Foundation};
/***/ }),
/***/ 2:
/***/ (function(module, exports) {
module.exports = {Plugin: window.Foundation.Plugin};
/***/ }),
/***/ 3:
/***/ (function(module, exports) {
module.exports = {rtl: window.Foundation.rtl, GetYoDigits: window.Foundation.GetYoDigits, transitionend: window.Foundation.transitionend};
/***/ }),
/***/ 30:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foundation_core__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foundation_core___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__foundation_core__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_sticky__ = __webpack_require__(60);
__WEBPACK_IMPORTED_MODULE_0__foundation_core__["Foundation"].plugin(__WEBPACK_IMPORTED_MODULE_1__foundation_sticky__["a" /* Sticky */], 'Sticky');
/***/ }),
/***/ 4:
/***/ (function(module, exports) {
module.exports = {Motion: window.Foundation.Motion, Move: window.Foundation.Move};
/***/ }),
/***/ 6:
/***/ (function(module, exports) {
module.exports = {MediaQuery: window.Foundation.MediaQuery};
/***/ }),
/***/ 60:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Sticky; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_core__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_core___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1__foundation_util_core__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_plugin__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_plugin___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3__foundation_plugin__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__foundation_util_triggers__ = __webpack_require__(7);
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Sticky module.
* @module foundation.sticky
* @requires foundation.util.triggers
* @requires foundation.util.mediaQuery
*/
var Sticky = function (_Plugin) {
_inherits(Sticky, _Plugin);
function Sticky() {
_classCallCheck(this, Sticky);
return _possibleConstructorReturn(this, (Sticky.__proto__ || Object.getPrototypeOf(Sticky)).apply(this, arguments));
}
_createClass(Sticky, [{
key: '_setup',
/**
* Creates a new instance of a sticky thing.
* @class
* @param {jQuery} element - jQuery object to make sticky.
* @param {Object} options - options object passed when creating the element programmatically.
*/
value: function _setup(element, options) {
this.$element = element;
this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Sticky.defaults, this.$element.data(), options);
// Triggers init is idempotent, just need to make sure it is initialized
__WEBPACK_IMPORTED_MODULE_4__foundation_util_triggers__["a" /* Triggers */].init(__WEBPACK_IMPORTED_MODULE_0_jquery___default.a);
this._init();
}
/**
* Initializes the sticky element by adding classes, getting/setting dimensions, breakpoints and attributes
* @function
* @private
*/
}, {
key: '_init',
value: function _init() {
__WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__["MediaQuery"]._init();
var $parent = this.$element.parent('[data-sticky-container]'),
id = this.$element[0].id || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__foundation_util_core__["GetYoDigits"])(6, 'sticky'),
_this = this;
if ($parent.length) {
this.$container = $parent;
} else {
this.wasWrapped = true;
this.$element.wrap(this.options.container);
this.$container = this.$element.parent();
}
this.$container.addClass(this.options.containerClass);
this.$element.addClass(this.options.stickyClass).attr({ 'data-resize': id, 'data-mutate': id });
if (this.options.anchor !== '') {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + _this.options.anchor).attr({ 'data-mutate': id });
}
this.scrollCount = this.options.checkEvery;
this.isStuck = false;
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).one('load.zf.sticky', function () {
//We calculate the container height to have correct values for anchor points offset calculation.
_this.containerHeight = _this.$element.css("display") == "none" ? 0 : _this.$element[0].getBoundingClientRect().height;
_this.$container.css('height', _this.containerHeight);
_this.elemHeight = _this.containerHeight;
if (_this.options.anchor !== '') {
_this.$anchor = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + _this.options.anchor);
} else {
_this._parsePoints();
}
_this._setSizes(function () {
var scroll = window.pageYOffset;
_this._calc(false, scroll);
//Unstick the element will ensure that proper classes are set.
if (!_this.isStuck) {
_this._removeSticky(scroll >= _this.topPoint ? false : true);
}
});
_this._events(id.split('-').reverse().join('-'));
});
}
/**
* If using multiple elements as anchors, calculates the top and bottom pixel values the sticky thing should stick and unstick on.
* @function
* @private
*/
}, {
key: '_parsePoints',
value: function _parsePoints() {
var top = this.options.topAnchor == "" ? 1 : this.options.topAnchor,
btm = this.options.btmAnchor == "" ? document.documentElement.scrollHeight : this.options.btmAnchor,
pts = [top, btm],
breaks = {};
for (var i = 0, len = pts.length; i < len && pts[i]; i++) {
var pt;
if (typeof pts[i] === 'number') {
pt = pts[i];
} else {
var place = pts[i].split(':'),
anchor = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + place[0]);
pt = anchor.offset().top;
if (place[1] && place[1].toLowerCase() === 'bottom') {
pt += anchor[0].getBoundingClientRect().height;
}
}
breaks[i] = pt;
}
this.points = breaks;
return;
}
/**
* Adds event handlers for the scrolling element.
* @private
* @param {String} id - pseudo-random id for unique scroll event listener.
*/
}, {
key: '_events',
value: function _events(id) {
var _this = this,
scrollListener = this.scrollListener = 'scroll.zf.' + id;
if (this.isOn) {
return;
}
if (this.canStick) {
this.isOn = true;
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(scrollListener).on(scrollListener, function (e) {
if (_this.scrollCount === 0) {
_this.scrollCount = _this.options.checkEvery;
_this._setSizes(function () {
_this._calc(false, window.pageYOffset);
});
} else {
_this.scrollCount--;
_this._calc(false, window.pageYOffset);
}
});
}
this.$element.off('resizeme.zf.trigger').on('resizeme.zf.trigger', function (e, el) {
_this._eventsHandler(id);
});
this.$element.on('mutateme.zf.trigger', function (e, el) {
_this._eventsHandler(id);
});
if (this.$anchor) {
this.$anchor.on('mutateme.zf.trigger', function (e, el) {
_this._eventsHandler(id);
});
}
}
/**
* Handler for events.
* @private
* @param {String} id - pseudo-random id for unique scroll event listener.
*/
}, {
key: '_eventsHandler',
value: function _eventsHandler(id) {
var _this = this,
scrollListener = this.scrollListener = 'scroll.zf.' + id;
_this._setSizes(function () {
_this._calc(false);
if (_this.canStick) {
if (!_this.isOn) {
_this._events(id);
}
} else if (_this.isOn) {
_this._pauseListeners(scrollListener);
}
});
}
/**
* Removes event handlers for scroll and change events on anchor.
* @fires Sticky#pause
* @param {String} scrollListener - unique, namespaced scroll listener attached to `window`
*/
}, {
key: '_pauseListeners',
value: function _pauseListeners(scrollListener) {
this.isOn = false;
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(scrollListener);
/**
* Fires when the plugin is paused due to resize event shrinking the view.
* @event Sticky#pause
* @private
*/
this.$element.trigger('pause.zf.sticky');
}
/**
* Called on every `scroll` event and on `_init`
* fires functions based on booleans and cached values
* @param {Boolean} checkSizes - true if plugin should recalculate sizes and breakpoints.
* @param {Number} scroll - current scroll position passed from scroll event cb function. If not passed, defaults to `window.pageYOffset`.
*/
}, {
key: '_calc',
value: function _calc(checkSizes, scroll) {
if (checkSizes) {
this._setSizes();
}
if (!this.canStick) {
if (this.isStuck) {
this._removeSticky(true);
}
return false;
}
if (!scroll) {
scroll = window.pageYOffset;
}
if (scroll >= this.topPoint) {
if (scroll <= this.bottomPoint) {
if (!this.isStuck) {
this._setSticky();
}
} else {
if (this.isStuck) {
this._removeSticky(false);
}
}
} else {
if (this.isStuck) {
this._removeSticky(true);
}
}
}
/**
* Causes the $element to become stuck.
* Adds `position: fixed;`, and helper classes.
* @fires Sticky#stuckto
* @function
* @private
*/
}, {
key: '_setSticky',
value: function _setSticky() {
var _this = this,
stickTo = this.options.stickTo,
mrgn = stickTo === 'top' ? 'marginTop' : 'marginBottom',
notStuckTo = stickTo === 'top' ? 'bottom' : 'top',
css = {};
css[mrgn] = this.options[mrgn] + 'em';
css[stickTo] = 0;
css[notStuckTo] = 'auto';
this.isStuck = true;
this.$element.removeClass('is-anchored is-at-' + notStuckTo).addClass('is-stuck is-at-' + stickTo).css(css)
/**
* Fires when the $element has become `position: fixed;`
* Namespaced to `top` or `bottom`, e.g. `sticky.zf.stuckto:top`
* @event Sticky#stuckto
*/
.trigger('sticky.zf.stuckto:' + stickTo);
this.$element.on("transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd", function () {
_this._setSizes();
});
}
/**
* Causes the $element to become unstuck.
* Removes `position: fixed;`, and helper classes.
* Adds other helper classes.
* @param {Boolean} isTop - tells the function if the $element should anchor to the top or bottom of its $anchor element.
* @fires Sticky#unstuckfrom
* @private
*/
}, {
key: '_removeSticky',
value: function _removeSticky(isTop) {
var stickTo = this.options.stickTo,
stickToTop = stickTo === 'top',
css = {},
anchorPt = (this.points ? this.points[1] - this.points[0] : this.anchorHeight) - this.elemHeight,
mrgn = stickToTop ? 'marginTop' : 'marginBottom',
notStuckTo = stickToTop ? 'bottom' : 'top',
topOrBottom = isTop ? 'top' : 'bottom';
css[mrgn] = 0;
css['bottom'] = 'auto';
if (isTop) {
css['top'] = 0;
} else {
css['top'] = anchorPt;
}
this.isStuck = false;
this.$element.removeClass('is-stuck is-at-' + stickTo).addClass('is-anchored is-at-' + topOrBottom).css(css)
/**
* Fires when the $element has become anchored.
* Namespaced to `top` or `bottom`, e.g. `sticky.zf.unstuckfrom:bottom`
* @event Sticky#unstuckfrom
*/
.trigger('sticky.zf.unstuckfrom:' + topOrBottom);
}
/**
* Sets the $element and $container sizes for plugin.
* Calls `_setBreakPoints`.
* @param {Function} cb - optional callback function to fire on completion of `_setBreakPoints`.
* @private
*/
}, {
key: '_setSizes',
value: function _setSizes(cb) {
this.canStick = __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__["MediaQuery"].is(this.options.stickyOn);
if (!this.canStick) {
if (cb && typeof cb === 'function') {
cb();
}
}
var _this = this,
newElemWidth = this.$container[0].getBoundingClientRect().width,
comp = window.getComputedStyle(this.$container[0]),
pdngl = parseInt(comp['padding-left'], 10),
pdngr = parseInt(comp['padding-right'], 10);
if (this.$anchor && this.$anchor.length) {
this.anchorHeight = this.$anchor[0].getBoundingClientRect().height;
} else {
this._parsePoints();
}
this.$element.css({
'max-width': newElemWidth - pdngl - pdngr + 'px'
});
var newContainerHeight = this.$element[0].getBoundingClientRect().height || this.containerHeight;
if (this.$element.css("display") == "none") {
newContainerHeight = 0;
}
this.containerHeight = newContainerHeight;
this.$container.css({
height: newContainerHeight
});
this.elemHeight = newContainerHeight;
if (!this.isStuck) {
if (this.$element.hasClass('is-at-bottom')) {
var anchorPt = (this.points ? this.points[1] - this.$container.offset().top : this.anchorHeight) - this.elemHeight;
this.$element.css('top', anchorPt);
}
}
this._setBreakPoints(newContainerHeight, function () {
if (cb && typeof cb === 'function') {
cb();
}
});
}
/**
* Sets the upper and lower breakpoints for the element to become sticky/unsticky.
* @param {Number} elemHeight - px value for sticky.$element height, calculated by `_setSizes`.
* @param {Function} cb - optional callback function to be called on completion.
* @private
*/
}, {
key: '_setBreakPoints',
value: function _setBreakPoints(elemHeight, cb) {
if (!this.canStick) {
if (cb && typeof cb === 'function') {
cb();
} else {
return false;
}
}
var mTop = emCalc(this.options.marginTop),
mBtm = emCalc(this.options.marginBottom),
topPoint = this.points ? this.points[0] : this.$anchor.offset().top,
bottomPoint = this.points ? this.points[1] : topPoint + this.anchorHeight,
// topPoint = this.$anchor.offset().top || this.points[0],
// bottomPoint = topPoint + this.anchorHeight || this.points[1],
winHeight = window.innerHeight;
if (this.options.stickTo === 'top') {
topPoint -= mTop;
bottomPoint -= elemHeight + mTop;
} else if (this.options.stickTo === 'bottom') {
topPoint -= winHeight - (elemHeight + mBtm);
bottomPoint -= winHeight - mBtm;
} else {
//this would be the stickTo: both option... tricky
}
this.topPoint = topPoint;
this.bottomPoint = bottomPoint;
if (cb && typeof cb === 'function') {
cb();
}
}
/**
* Destroys the current sticky element.
* Resets the element to the top position first.
* Removes event listeners, JS-added css properties and classes, and unwraps the $element if the JS added the $container.
* @function
*/
}, {
key: '_destroy',
value: function _destroy() {
this._removeSticky(true);
this.$element.removeClass(this.options.stickyClass + ' is-anchored is-at-top').css({
height: '',
top: '',
bottom: '',
'max-width': ''
}).off('resizeme.zf.trigger').off('mutateme.zf.trigger');
if (this.$anchor && this.$anchor.length) {
this.$anchor.off('change.zf.sticky');
}
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(this.scrollListener);
if (this.wasWrapped) {
this.$element.unwrap();
} else {
this.$container.removeClass(this.options.containerClass).css({
height: ''
});
}
}
}]);
return Sticky;
}(__WEBPACK_IMPORTED_MODULE_3__foundation_plugin__["Plugin"]);
Sticky.defaults = {
/**
* Customizable container template. Add your own classes for styling and sizing.
* @option
* @type {string}
* @default '<div data-sticky-container></div>'
*/
container: '<div data-sticky-container></div>',
/**
* Location in the view the element sticks to. Can be `'top'` or `'bottom'`.
* @option
* @type {string}
* @default 'top'
*/
stickTo: 'top',
/**
* If anchored to a single element, the id of that element.
* @option
* @type {string}
* @default ''
*/
anchor: '',
/**
* If using more than one element as anchor points, the id of the top anchor.
* @option
* @type {string}
* @default ''
*/
topAnchor: '',
/**
* If using more than one element as anchor points, the id of the bottom anchor.
* @option
* @type {string}
* @default ''
*/
btmAnchor: '',
/**
* Margin, in `em`'s to apply to the top of the element when it becomes sticky.
* @option
* @type {number}
* @default 1
*/
marginTop: 1,
/**
* Margin, in `em`'s to apply to the bottom of the element when it becomes sticky.
* @option
* @type {number}
* @default 1
*/
marginBottom: 1,
/**
* Breakpoint string that is the minimum screen size an element should become sticky.
* @option
* @type {string}
* @default 'medium'
*/
stickyOn: 'medium',
/**
* Class applied to sticky element, and removed on destruction. Foundation defaults to `sticky`.
* @option
* @type {string}
* @default 'sticky'
*/
stickyClass: 'sticky',
/**
* Class applied to sticky container. Foundation defaults to `sticky-container`.
* @option
* @type {string}
* @default 'sticky-container'
*/
containerClass: 'sticky-container',
/**
* Number of scroll events between the plugin's recalculating sticky points. Setting it to `0` will cause it to recalc every scroll event, setting it to `-1` will prevent recalc on scroll.
* @option
* @type {number}
* @default -1
*/
checkEvery: -1
};
/**
* Helper function to calculate em values
* @param Number {em} - number of em's to calculate into pixels
*/
function emCalc(em) {
return parseInt(window.getComputedStyle(document.body, null).fontSize, 10) * em;
}
/***/ }),
/***/ 7:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Triggers; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_motion___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__);
var MutationObserver = function () {
var prefixes = ['WebKit', 'Moz', 'O', 'Ms', ''];
for (var i = 0; i < prefixes.length; i++) {
if (prefixes[i] + 'MutationObserver' in window) {
return window[prefixes[i] + 'MutationObserver'];
}
}
return false;
}();
var triggers = function (el, type) {
el.data(type).split(' ').forEach(function (id) {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + id)[type === 'close' ? 'trigger' : 'triggerHandler'](type + '.zf.trigger', [el]);
});
};
var Triggers = {
Listeners: {
Basic: {},
Global: {}
},
Initializers: {}
};
Triggers.Listeners.Basic = {
openListener: function () {
triggers(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), 'open');
},
closeListener: function () {
var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('close');
if (id) {
triggers(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), 'close');
} else {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('close.zf.trigger');
}
},
toggleListener: function () {
var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('toggle');
if (id) {
triggers(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), 'toggle');
} else {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('toggle.zf.trigger');
}
},
closeableListener: function (e) {
e.stopPropagation();
var animation = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('closable');
if (animation !== '') {
Foundation.Motion.animateOut(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), animation, function () {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('closed.zf');
});
} else {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).fadeOut().trigger('closed.zf');
}
},
toggleFocusListener: function () {
var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('toggle-focus');
__WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + id).triggerHandler('toggle.zf.trigger', [__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this)]);
}
};
// Elements with [data-open] will reveal a plugin that supports it when clicked.
Triggers.Initializers.addOpenListener = function ($elem) {
$elem.off('click.zf.trigger', Triggers.Listeners.Basic.openListener);
$elem.on('click.zf.trigger', '[data-open]', Triggers.Listeners.Basic.openListener);
};
// Elements with [data-close] will close a plugin that supports it when clicked.
// If used without a value on [data-close], the event will bubble, allowing it to close a parent component.
Triggers.Initializers.addCloseListener = function ($elem) {
$elem.off('click.zf.trigger', Triggers.Listeners.Basic.closeListener);
$elem.on('click.zf.trigger', '[data-close]', Triggers.Listeners.Basic.closeListener);
};
// Elements with [data-toggle] will toggle a plugin that supports it when clicked.
Triggers.Initializers.addToggleListener = function ($elem) {
$elem.off('click.zf.trigger', Triggers.Listeners.Basic.toggleListener);
$elem.on('click.zf.trigger', '[data-toggle]', Triggers.Listeners.Basic.toggleListener);
};
// Elements with [data-closable] will respond to close.zf.trigger events.
Triggers.Initializers.addCloseableListener = function ($elem) {
$elem.off('close.zf.trigger', Triggers.Listeners.Basic.closeableListener);
$elem.on('close.zf.trigger', '[data-closeable]', Triggers.Listeners.Basic.closeableListener);
};
// Elements with [data-toggle-focus] will respond to coming in and out of focus
Triggers.Initializers.addToggleFocusListener = function ($elem) {
$elem.off('focus.zf.trigger blur.zf.trigger', Triggers.Listeners.Basic.toggleFocusListener);
$elem.on('focus.zf.trigger blur.zf.trigger', '[data-toggle-focus]', Triggers.Listeners.Basic.toggleFocusListener);
};
// More Global/complex listeners and triggers
Triggers.Listeners.Global = {
resizeListener: function ($nodes) {
if (!MutationObserver) {
//fallback for IE 9
$nodes.each(function () {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).triggerHandler('resizeme.zf.trigger');
});
}
//trigger all listening elements and signal a resize event
$nodes.attr('data-events', "resize");
},
scrollListener: function ($nodes) {
if (!MutationObserver) {
//fallback for IE 9
$nodes.each(function () {
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).triggerHandler('scrollme.zf.trigger');
});
}
//trigger all listening elements and signal a scroll event
$nodes.attr('data-events', "scroll");
},
closeMeListener: function (e, pluginId) {
var plugin = e.namespace.split('.')[0];
var plugins = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-' + plugin + ']').not('[data-yeti-box="' + pluginId + '"]');
plugins.each(function () {
var _this = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this);
_this.triggerHandler('close.zf.trigger', [_this]);
});
}
};
// Global, parses whole document.
Triggers.Initializers.addClosemeListener = function (pluginName) {
var yetiBoxes = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-yeti-box]'),
plugNames = ['dropdown', 'tooltip', 'reveal'];
if (pluginName) {
if (typeof pluginName === 'string') {
plugNames.push(pluginName);
} else if (typeof pluginName === 'object' && typeof pluginName[0] === 'string') {
plugNames.concat(pluginName);
} else {
console.error('Plugin names must be strings');
}
}
if (yetiBoxes.length) {
var listeners = plugNames.map(function (name) {
return 'closeme.zf.' + name;
}).join(' ');
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(listeners).on(listeners, Triggers.Listeners.Global.closeMeListener);
}
};
function debounceGlobalListener(debounce, trigger, listener) {
var timer = void 0,
args = Array.prototype.slice.call(arguments, 3);
__WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(trigger).on(trigger, function (e) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
listener.apply(null, args);
}, debounce || 10); //default time to emit scroll event
});
}
Triggers.Initializers.addResizeListener = function (debounce) {
var $nodes = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-resize]');
if ($nodes.length) {
debounceGlobalListener(debounce, 'resize.zf.trigger', Triggers.Listeners.Global.resizeListener, $nodes);
}
};
Triggers.Initializers.addScrollListener = function (debounce) {
var $nodes = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-scroll]');
if ($nodes.length) {
debounceGlobalListener(debounce, 'scroll.zf.trigger', Triggers.Listeners.Global.scrollListener, $nodes);
}
};
Triggers.Initializers.addMutationEventsListener = function ($elem) {
if (!MutationObserver) {
return false;
}
var $nodes = $elem.find('[data-resize], [data-scroll], [data-mutate]');
//element callback
var listeningElementsMutation = function (mutationRecordsList) {
var $target = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(mutationRecordsList[0].target);
//trigger the event handler for the element depending on type
switch (mutationRecordsList[0].type) {
case "attributes":
if ($target.attr("data-events") === "scroll" && mutationRecordsList[0].attributeName === "data-events") {
$target.triggerHandler('scrollme.zf.trigger', [$target, window.pageYOffset]);
}
if ($target.attr("data-events") === "resize" && mutationRecordsList[0].attributeName === "data-events") {
$target.triggerHandler('resizeme.zf.trigger', [$target]);
}
if (mutationRecordsList[0].attributeName === "style") {
$target.closest("[data-mutate]").attr("data-events", "mutate");
$target.closest("[data-mutate]").triggerHandler('mutateme.zf.trigger', [$target.closest("[data-mutate]")]);
}
break;
case "childList":
$target.closest("[data-mutate]").attr("data-events", "mutate");
$target.closest("[data-mutate]").triggerHandler('mutateme.zf.trigger', [$target.closest("[data-mutate]")]);
break;
default:
return false;
//nothing
}
};
if ($nodes.length) {
//for each element that needs to listen for resizing, scrolling, or mutation add a single observer
for (var i = 0; i <= $nodes.length - 1; i++) {
var elementObserver = new MutationObserver(listeningElementsMutation);
elementObserver.observe($nodes[i], { attributes: true, childList: true, characterData: false, subtree: true, attributeFilter: ["data-events", "style"] });
}
}
};
Triggers.Initializers.addSimpleListeners = function () {
var $document = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(document);
Triggers.Initializers.addOpenListener($document);
Triggers.Initializers.addCloseListener($document);
Triggers.Initializers.addToggleListener($document);
Triggers.Initializers.addCloseableListener($document);
Triggers.Initializers.addToggleFocusListener($document);
};
Triggers.Initializers.addGlobalListeners = function () {
var $document = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(document);
Triggers.Initializers.addMutationEventsListener($document);
Triggers.Initializers.addResizeListener();
Triggers.Initializers.addScrollListener();
Triggers.Initializers.addClosemeListener();
};
Triggers.init = function ($, Foundation) {
if (typeof $.triggersInitialized === 'undefined') {
var $document = $(document);
if (document.readyState === "complete") {
Triggers.Initializers.addSimpleListeners();
Triggers.Initializers.addGlobalListeners();
} else {
$(window).on('load', function () {
Triggers.Initializers.addSimpleListeners();
Triggers.Initializers.addGlobalListeners();
});
}
$.triggersInitialized = true;
}
if (Foundation) {
Foundation.Triggers = Triggers;
// Legacy included to be backwards compatible for now.
Foundation.IHearYou = Triggers.Initializers.addGlobalListeners;
}
};
/***/ }),
/***/ 96:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(30);
/***/ })
/******/ }); | jeromelebleu/foundation-sites | dist/js/plugins/foundation.sticky.js | JavaScript | mit | 34,861 |
//
// [The "BSD license"]
// Copyright (c) 2012 Terence Parr
// Copyright (c) 2012 Sam Harwell
// Copyright (c) 2014 Eric Vergnaud
// 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 name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR 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 embodiment of the adaptive LL(*), ALL(*), parsing strategy.
//
// <p>
// The basic complexity of the adaptive strategy makes it harder to understand.
// We begin with ATN simulation to build paths in a DFA. Subsequent prediction
// requests go through the DFA first. If they reach a state without an edge for
// the current symbol, the algorithm fails over to the ATN simulation to
// complete the DFA path for the current input (until it finds a conflict state
// or uniquely predicting state).</p>
//
// <p>
// All of that is done without using the outer context because we want to create
// a DFA that is not dependent upon the rule invocation stack when we do a
// prediction. One DFA works in all contexts. We avoid using context not
// necessarily because it's slower, although it can be, but because of the DFA
// caching problem. The closure routine only considers the rule invocation stack
// created during prediction beginning in the decision rule. For example, if
// prediction occurs without invoking another rule's ATN, there are no context
// stacks in the configurations. When lack of context leads to a conflict, we
// don't know if it's an ambiguity or a weakness in the strong LL(*) parsing
// strategy (versus full LL(*)).</p>
//
// <p>
// When SLL yields a configuration set with conflict, we rewind the input and
// retry the ATN simulation, this time using full outer context without adding
// to the DFA. Configuration context stacks will be the full invocation stacks
// from the start rule. If we get a conflict using full context, then we can
// definitively say we have a true ambiguity for that input sequence. If we
// don't get a conflict, it implies that the decision is sensitive to the outer
// context. (It is not context-sensitive in the sense of context-sensitive
// grammars.)</p>
//
// <p>
// The next time we reach this DFA state with an SLL conflict, through DFA
// simulation, we will again retry the ATN simulation using full context mode.
// This is slow because we can't save the results and have to "interpret" the
// ATN each time we get that input.</p>
//
// <p>
// <strong>CACHING FULL CONTEXT PREDICTIONS</strong></p>
//
// <p>
// We could cache results from full context to predicted alternative easily and
// that saves a lot of time but doesn't work in presence of predicates. The set
// of visible predicates from the ATN start state changes depending on the
// context, because closure can fall off the end of a rule. I tried to cache
// tuples (stack context, semantic context, predicted alt) but it was slower
// than interpreting and much more complicated. Also required a huge amount of
// memory. The goal is not to create the world's fastest parser anyway. I'd like
// to keep this algorithm simple. By launching multiple threads, we can improve
// the speed of parsing across a large number of files.</p>
//
// <p>
// There is no strict ordering between the amount of input used by SLL vs LL,
// which makes it really hard to build a cache for full context. Let's say that
// we have input A B C that leads to an SLL conflict with full context X. That
// implies that using X we might only use A B but we could also use A B C D to
// resolve conflict. Input A B C D could predict alternative 1 in one position
// in the input and A B C E could predict alternative 2 in another position in
// input. The conflicting SLL configurations could still be non-unique in the
// full context prediction, which would lead us to requiring more input than the
// original A B C. To make a prediction cache work, we have to track the exact
// input used during the previous prediction. That amounts to a cache that maps
// X to a specific DFA for that context.</p>
//
// <p>
// Something should be done for left-recursive expression predictions. They are
// likely LL(1) + pred eval. Easier to do the whole SLL unless error and retry
// with full LL thing Sam does.</p>
//
// <p>
// <strong>AVOIDING FULL CONTEXT PREDICTION</strong></p>
//
// <p>
// We avoid doing full context retry when the outer context is empty, we did not
// dip into the outer context by falling off the end of the decision state rule,
// or when we force SLL mode.</p>
//
// <p>
// As an example of the not dip into outer context case, consider as super
// constructor calls versus function calls. One grammar might look like
// this:</p>
//
// <pre>
// ctorBody
// : '{' superCall? stat* '}'
// ;
// </pre>
//
// <p>
// Or, you might see something like</p>
//
// <pre>
// stat
// : superCall ';'
// | expression ';'
// | ...
// ;
// </pre>
//
// <p>
// In both cases I believe that no closure operations will dip into the outer
// context. In the first case ctorBody in the worst case will stop at the '}'.
// In the 2nd case it should stop at the ';'. Both cases should stay within the
// entry rule and not dip into the outer context.</p>
//
// <p>
// <strong>PREDICATES</strong></p>
//
// <p>
// Predicates are always evaluated if present in either SLL or LL both. SLL and
// LL simulation deals with predicates differently. SLL collects predicates as
// it performs closure operations like ANTLR v3 did. It delays predicate
// evaluation until it reaches and accept state. This allows us to cache the SLL
// ATN simulation whereas, if we had evaluated predicates on-the-fly during
// closure, the DFA state configuration sets would be different and we couldn't
// build up a suitable DFA.</p>
//
// <p>
// When building a DFA accept state during ATN simulation, we evaluate any
// predicates and return the sole semantically valid alternative. If there is
// more than 1 alternative, we report an ambiguity. If there are 0 alternatives,
// we throw an exception. Alternatives without predicates act like they have
// true predicates. The simple way to think about it is to strip away all
// alternatives with false predicates and choose the minimum alternative that
// remains.</p>
//
// <p>
// When we start in the DFA and reach an accept state that's predicated, we test
// those and return the minimum semantically viable alternative. If no
// alternatives are viable, we throw an exception.</p>
//
// <p>
// During full LL ATN simulation, closure always evaluates predicates and
// on-the-fly. This is crucial to reducing the configuration set size during
// closure. It hits a landmine when parsing with the Java grammar, for example,
// without this on-the-fly evaluation.</p>
//
// <p>
// <strong>SHARING DFA</strong></p>
//
// <p>
// All instances of the same parser share the same decision DFAs through a
// static field. Each instance gets its own ATN simulator but they share the
// same {@link //decisionToDFA} field. They also share a
// {@link PredictionContextCache} object that makes sure that all
// {@link PredictionContext} objects are shared among the DFA states. This makes
// a big size difference.</p>
//
// <p>
// <strong>THREAD SAFETY</strong></p>
//
// <p>
// The {@link ParserATNSimulator} locks on the {@link //decisionToDFA} field when
// it adds a new DFA object to that array. {@link //addDFAEdge}
// locks on the DFA for the current decision when setting the
// {@link DFAState//edges} field. {@link //addDFAState} locks on
// the DFA for the current decision when looking up a DFA state to see if it
// already exists. We must make sure that all requests to add DFA states that
// are equivalent result in the same shared DFA object. This is because lots of
// threads will be trying to update the DFA at once. The
// {@link //addDFAState} method also locks inside the DFA lock
// but this time on the shared context cache when it rebuilds the
// configurations' {@link PredictionContext} objects using cached
// subgraphs/nodes. No other locking occurs, even during DFA simulation. This is
// safe as long as we can guarantee that all threads referencing
// {@code s.edge[t]} get the same physical target {@link DFAState}, or
// {@code null}. Once into the DFA, the DFA simulation does not reference the
// {@link DFA//states} map. It follows the {@link DFAState//edges} field to new
// targets. The DFA simulator will either find {@link DFAState//edges} to be
// {@code null}, to be non-{@code null} and {@code dfa.edges[t]} null, or
// {@code dfa.edges[t]} to be non-null. The
// {@link //addDFAEdge} method could be racing to set the field
// but in either case the DFA simulator works; if {@code null}, and requests ATN
// simulation. It could also race trying to get {@code dfa.edges[t]}, but either
// way it will work because it's not doing a test and set operation.</p>
//
// <p>
// <strong>Starting with SLL then failing to combined SLL/LL (Two-Stage
// Parsing)</strong></p>
//
// <p>
// Sam pointed out that if SLL does not give a syntax error, then there is no
// point in doing full LL, which is slower. We only have to try LL if we get a
// syntax error. For maximum speed, Sam starts the parser set to pure SLL
// mode with the {@link BailErrorStrategy}:</p>
//
// <pre>
// parser.{@link Parser//getInterpreter() getInterpreter()}.{@link //setPredictionMode setPredictionMode}{@code (}{@link PredictionMode//SLL}{@code )};
// parser.{@link Parser//setErrorHandler setErrorHandler}(new {@link BailErrorStrategy}());
// </pre>
//
// <p>
// If it does not get a syntax error, then we're done. If it does get a syntax
// error, we need to retry with the combined SLL/LL strategy.</p>
//
// <p>
// The reason this works is as follows. If there are no SLL conflicts, then the
// grammar is SLL (at least for that input set). If there is an SLL conflict,
// the full LL analysis must yield a set of viable alternatives which is a
// subset of the alternatives reported by SLL. If the LL set is a singleton,
// then the grammar is LL but not SLL. If the LL set is the same size as the SLL
// set, the decision is SLL. If the LL set has size > 1, then that decision
// is truly ambiguous on the current input. If the LL set is smaller, then the
// SLL conflict resolution might choose an alternative that the full LL would
// rule out as a possibility based upon better context information. If that's
// the case, then the SLL parse will definitely get an error because the full LL
// analysis says it's not viable. If SLL conflict resolution chooses an
// alternative within the LL set, them both SLL and LL would choose the same
// alternative because they both choose the minimum of multiple conflicting
// alternatives.</p>
//
// <p>
// Let's say we have a set of SLL conflicting alternatives {@code {1, 2, 3}} and
// a smaller LL set called <em>s</em>. If <em>s</em> is {@code {2, 3}}, then SLL
// parsing will get an error because SLL will pursue alternative 1. If
// <em>s</em> is {@code {1, 2}} or {@code {1, 3}} then both SLL and LL will
// choose the same alternative because alternative one is the minimum of either
// set. If <em>s</em> is {@code {2}} or {@code {3}} then SLL will get a syntax
// error. If <em>s</em> is {@code {1}} then SLL will succeed.</p>
//
// <p>
// Of course, if the input is invalid, then we will get an error for sure in
// both SLL and LL parsing. Erroneous input will therefore require 2 passes over
// the input.</p>
//
var Utils = require('./../Utils');
var Set = Utils.Set;
var BitSet = Utils.BitSet;
var DoubleDict = Utils.DoubleDict;
var ATN = require('./ATN').ATN;
var ATNConfig = require('./ATNConfig').ATNConfig;
var ATNConfigSet = require('./ATNConfigSet').ATNConfigSet;
var Token = require('./../Token').Token;
var DFAState = require('./../dfa/DFAState').DFAState;
var PredPrediction = require('./../dfa/DFAState').PredPrediction;
var ATNSimulator = require('./ATNSimulator').ATNSimulator;
var PredictionMode = require('./PredictionMode').PredictionMode;
var RuleContext = require('./../RuleContext').RuleContext;
var ParserRuleContext = require('./../ParserRuleContext').ParserRuleContext;
var SemanticContext = require('./SemanticContext').SemanticContext;
var StarLoopEntryState = require('./ATNState').StarLoopEntryState;
var RuleStopState = require('./ATNState').RuleStopState;
var PredictionContext = require('./../PredictionContext').PredictionContext;
var Interval = require('./../IntervalSet').Interval;
var Transitions = require('./Transition');
var Transition = Transitions.Transition;
var SetTransition = Transitions.SetTransition;
var NotSetTransition = Transitions.NotSetTransition;
var RuleTransition = Transitions.RuleTransition;
var ActionTransition = Transitions.ActionTransition;
var NoViableAltException = require('./../error/Errors').NoViableAltException;
var SingletonPredictionContext = require('./../PredictionContext').SingletonPredictionContext;
var predictionContextFromRuleContext = require('./../PredictionContext').predictionContextFromRuleContext;
function ParserATNSimulator(parser, atn, decisionToDFA, sharedContextCache) {
ATNSimulator.call(this, atn, sharedContextCache);
this.parser = parser;
this.decisionToDFA = decisionToDFA;
// SLL, LL, or LL + exact ambig detection?//
this.predictionMode = PredictionMode.LL;
// LAME globals to avoid parameters!!!!! I need these down deep in predTransition
this._input = null;
this._startIndex = 0;
this._outerContext = null;
this._dfa = null;
// Each prediction operation uses a cache for merge of prediction contexts.
// Don't keep around as it wastes huge amounts of memory. DoubleKeyMap
// isn't synchronized but we're ok since two threads shouldn't reuse same
// parser/atnsim object because it can only handle one input at a time.
// This maps graphs a and b to merged result c. (a,b)→c. We can avoid
// the merge if we ever see a and b again. Note that (b,a)→c should
// also be examined during cache lookup.
//
this.mergeCache = null;
return this;
}
ParserATNSimulator.prototype = Object.create(ATNSimulator.prototype);
ParserATNSimulator.prototype.constructor = ParserATNSimulator;
ParserATNSimulator.prototype.debug = false;
ParserATNSimulator.prototype.debug_list_atn_decisions = false;
ParserATNSimulator.prototype.dfa_debug = false;
ParserATNSimulator.prototype.retry_debug = false;
ParserATNSimulator.prototype.reset = function() {
};
ParserATNSimulator.prototype.adaptivePredict = function(input, decision, outerContext) {
if (this.debug || this.debug_list_atn_decisions) {
console.log("adaptivePredict decision " + decision +
" exec LA(1)==" + this.getLookaheadName(input) +
" line " + input.LT(1).line + ":" +
input.LT(1).column);
}
this._input = input;
this._startIndex = input.index;
this._outerContext = outerContext;
var dfa = this.decisionToDFA[decision];
this._dfa = dfa;
var m = input.mark();
var index = input.index;
// Now we are certain to have a specific decision's DFA
// But, do we still need an initial state?
try {
var s0;
if (dfa.precedenceDfa) {
// the start state for a precedence DFA depends on the current
// parser precedence, and is provided by a DFA method.
s0 = dfa.getPrecedenceStartState(this.parser.getPrecedence());
} else {
// the start state for a "regular" DFA is just s0
s0 = dfa.s0;
}
if (s0===null) {
if (outerContext===null) {
outerContext = RuleContext.EMPTY;
}
if (this.debug || this.debug_list_atn_decisions) {
console.log("predictATN decision " + dfa.decision +
" exec LA(1)==" + this.getLookaheadName(input) +
", outerContext=" + outerContext.toString(this.parser.ruleNames));
}
// If this is not a precedence DFA, we check the ATN start state
// to determine if this ATN start state is the decision for the
// closure block that determines whether a precedence rule
// should continue or complete.
//
if (!dfa.precedenceDfa && (dfa.atnStartState instanceof StarLoopEntryState)) {
if (dfa.atnStartState.precedenceRuleDecision) {
dfa.setPrecedenceDfa(true);
}
}
var fullCtx = false;
var s0_closure = this.computeStartState(dfa.atnStartState, RuleContext.EMPTY, fullCtx);
if( dfa.precedenceDfa) {
// If this is a precedence DFA, we use applyPrecedenceFilter
// to convert the computed start state to a precedence start
// state. We then use DFA.setPrecedenceStartState to set the
// appropriate start state for the precedence level rather
// than simply setting DFA.s0.
//
s0_closure = this.applyPrecedenceFilter(s0_closure);
s0 = this.addDFAState(dfa, new DFAState(null, s0_closure));
dfa.setPrecedenceStartState(this.parser.getPrecedence(), s0);
} else {
s0 = this.addDFAState(dfa, new DFAState(null, s0_closure));
dfa.s0 = s0;
}
}
var alt = this.execATN(dfa, s0, input, index, outerContext);
if (this.debug) {
console.log("DFA after predictATN: " + dfa.toString(this.parser.literalNames));
}
return alt;
} finally {
this._dfa = null;
this.mergeCache = null; // wack cache after each prediction
input.seek(index);
input.release(m);
}
};
// Performs ATN simulation to compute a predicted alternative based
// upon the remaining input, but also updates the DFA cache to avoid
// having to traverse the ATN again for the same input sequence.
// There are some key conditions we're looking for after computing a new
// set of ATN configs (proposed DFA state):
// if the set is empty, there is no viable alternative for current symbol
// does the state uniquely predict an alternative?
// does the state have a conflict that would prevent us from
// putting it on the work list?
// We also have some key operations to do:
// add an edge from previous DFA state to potentially new DFA state, D,
// upon current symbol but only if adding to work list, which means in all
// cases except no viable alternative (and possibly non-greedy decisions?)
// collecting predicates and adding semantic context to DFA accept states
// adding rule context to context-sensitive DFA accept states
// consuming an input symbol
// reporting a conflict
// reporting an ambiguity
// reporting a context sensitivity
// reporting insufficient predicates
// cover these cases:
// dead end
// single alt
// single alt + preds
// conflict
// conflict + preds
//
ParserATNSimulator.prototype.execATN = function(dfa, s0, input, startIndex, outerContext ) {
if (this.debug || this.debug_list_atn_decisions) {
console.log("execATN decision " + dfa.decision +
" exec LA(1)==" + this.getLookaheadName(input) +
" line " + input.LT(1).line + ":" + input.LT(1).column);
}
var alt;
var previousD = s0;
if (this.debug) {
console.log("s0 = " + s0);
}
var t = input.LA(1);
while(true) { // while more work
var D = this.getExistingTargetState(previousD, t);
if(D===null) {
D = this.computeTargetState(dfa, previousD, t);
}
if(D===ATNSimulator.ERROR) {
// if any configs in previous dipped into outer context, that
// means that input up to t actually finished entry rule
// at least for SLL decision. Full LL doesn't dip into outer
// so don't need special case.
// We will get an error no matter what so delay until after
// decision; better error message. Also, no reachable target
// ATN states in SLL implies LL will also get nowhere.
// If conflict in states that dip out, choose min since we
// will get error no matter what.
var e = this.noViableAlt(input, outerContext, previousD.configs, startIndex);
input.seek(startIndex);
alt = this.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previousD.configs, outerContext);
if(alt!==ATN.INVALID_ALT_NUMBER) {
return alt;
} else {
throw e;
}
}
if(D.requiresFullContext && this.predictionMode !== PredictionMode.SLL) {
// IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error)
var conflictingAlts = null;
if (D.predicates!==null) {
if (this.debug) {
console.log("DFA state has preds in DFA sim LL failover");
}
var conflictIndex = input.index;
if(conflictIndex !== startIndex) {
input.seek(startIndex);
}
conflictingAlts = this.evalSemanticContext(D.predicates, outerContext, true);
if (conflictingAlts.length===1) {
if(this.debug) {
console.log("Full LL avoided");
}
return conflictingAlts.minValue();
}
if (conflictIndex !== startIndex) {
// restore the index so reporting the fallback to full
// context occurs with the index at the correct spot
input.seek(conflictIndex);
}
}
if (this.dfa_debug) {
console.log("ctx sensitive state " + outerContext +" in " + D);
}
var fullCtx = true;
var s0_closure = this.computeStartState(dfa.atnStartState, outerContext, fullCtx);
this.reportAttemptingFullContext(dfa, conflictingAlts, D.configs, startIndex, input.index);
alt = this.execATNWithFullContext(dfa, D, s0_closure, input, startIndex, outerContext);
return alt;
}
if (D.isAcceptState) {
if (D.predicates===null) {
return D.prediction;
}
var stopIndex = input.index;
input.seek(startIndex);
var alts = this.evalSemanticContext(D.predicates, outerContext, true);
if (alts.length===0) {
throw this.noViableAlt(input, outerContext, D.configs, startIndex);
} else if (alts.length===1) {
return alts.minValue();
} else {
// report ambiguity after predicate evaluation to make sure the correct set of ambig alts is reported.
this.reportAmbiguity(dfa, D, startIndex, stopIndex, false, alts, D.configs);
return alts.minValue();
}
}
previousD = D;
if (t !== Token.EOF) {
input.consume();
t = input.LA(1);
}
}
};
//
// Get an existing target state for an edge in the DFA. If the target state
// for the edge has not yet been computed or is otherwise not available,
// this method returns {@code null}.
//
// @param previousD The current DFA state
// @param t The next input symbol
// @return The existing target DFA state for the given input symbol
// {@code t}, or {@code null} if the target state for this edge is not
// already cached
//
ParserATNSimulator.prototype.getExistingTargetState = function(previousD, t) {
var edges = previousD.edges;
if (edges===null) {
return null;
} else {
return edges[t + 1] || null;
}
};
//
// Compute a target state for an edge in the DFA, and attempt to add the
// computed state and corresponding edge to the DFA.
//
// @param dfa The DFA
// @param previousD The current DFA state
// @param t The next input symbol
//
// @return The computed target DFA state for the given input symbol
// {@code t}. If {@code t} does not lead to a valid DFA state, this method
// returns {@link //ERROR}.
//
ParserATNSimulator.prototype.computeTargetState = function(dfa, previousD, t) {
var reach = this.computeReachSet(previousD.configs, t, false);
if(reach===null) {
this.addDFAEdge(dfa, previousD, t, ATNSimulator.ERROR);
return ATNSimulator.ERROR;
}
// create new target state; we'll add to DFA after it's complete
var D = new DFAState(null, reach);
var predictedAlt = this.getUniqueAlt(reach);
if (this.debug) {
var altSubSets = PredictionMode.getConflictingAltSubsets(reach);
console.log("SLL altSubSets=" + Utils.arrayToString(altSubSets) +
", previous=" + previousD.configs +
", configs=" + reach +
", predict=" + predictedAlt +
", allSubsetsConflict=" +
PredictionMode.allSubsetsConflict(altSubSets) + ", conflictingAlts=" +
this.getConflictingAlts(reach));
}
if (predictedAlt!==ATN.INVALID_ALT_NUMBER) {
// NO CONFLICT, UNIQUELY PREDICTED ALT
D.isAcceptState = true;
D.configs.uniqueAlt = predictedAlt;
D.prediction = predictedAlt;
} else if (PredictionMode.hasSLLConflictTerminatingPrediction(this.predictionMode, reach)) {
// MORE THAN ONE VIABLE ALTERNATIVE
D.configs.conflictingAlts = this.getConflictingAlts(reach);
D.requiresFullContext = true;
// in SLL-only mode, we will stop at this state and return the minimum alt
D.isAcceptState = true;
D.prediction = D.configs.conflictingAlts.minValue();
}
if (D.isAcceptState && D.configs.hasSemanticContext) {
this.predicateDFAState(D, this.atn.getDecisionState(dfa.decision));
if( D.predicates!==null) {
D.prediction = ATN.INVALID_ALT_NUMBER;
}
}
// all adds to dfa are done after we've created full D state
D = this.addDFAEdge(dfa, previousD, t, D);
return D;
};
ParserATNSimulator.prototype.predicateDFAState = function(dfaState, decisionState) {
// We need to test all predicates, even in DFA states that
// uniquely predict alternative.
var nalts = decisionState.transitions.length;
// Update DFA so reach becomes accept state with (predicate,alt)
// pairs if preds found for conflicting alts
var altsToCollectPredsFrom = this.getConflictingAltsOrUniqueAlt(dfaState.configs);
var altToPred = this.getPredsForAmbigAlts(altsToCollectPredsFrom, dfaState.configs, nalts);
if (altToPred!==null) {
dfaState.predicates = this.getPredicatePredictions(altsToCollectPredsFrom, altToPred);
dfaState.prediction = ATN.INVALID_ALT_NUMBER; // make sure we use preds
} else {
// There are preds in configs but they might go away
// when OR'd together like {p}? || NONE == NONE. If neither
// alt has preds, resolve to min alt
dfaState.prediction = altsToCollectPredsFrom.minValue();
}
};
// comes back with reach.uniqueAlt set to a valid alt
ParserATNSimulator.prototype.execATNWithFullContext = function(dfa, D, // how far we got before failing over
s0,
input,
startIndex,
outerContext) {
if (this.debug || this.debug_list_atn_decisions) {
console.log("execATNWithFullContext "+s0);
}
var fullCtx = true;
var foundExactAmbig = false;
var reach = null;
var previous = s0;
input.seek(startIndex);
var t = input.LA(1);
var predictedAlt = -1;
while (true) { // while more work
reach = this.computeReachSet(previous, t, fullCtx);
if (reach===null) {
// if any configs in previous dipped into outer context, that
// means that input up to t actually finished entry rule
// at least for LL decision. Full LL doesn't dip into outer
// so don't need special case.
// We will get an error no matter what so delay until after
// decision; better error message. Also, no reachable target
// ATN states in SLL implies LL will also get nowhere.
// If conflict in states that dip out, choose min since we
// will get error no matter what.
var e = this.noViableAlt(input, outerContext, previous, startIndex);
input.seek(startIndex);
var alt = this.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previous, outerContext);
if(alt!==ATN.INVALID_ALT_NUMBER) {
return alt;
} else {
throw e;
}
}
var altSubSets = PredictionMode.getConflictingAltSubsets(reach);
if(this.debug) {
console.log("LL altSubSets=" + altSubSets + ", predict=" +
PredictionMode.getUniqueAlt(altSubSets) + ", resolvesToJustOneViableAlt=" +
PredictionMode.resolvesToJustOneViableAlt(altSubSets));
}
reach.uniqueAlt = this.getUniqueAlt(reach);
// unique prediction?
if(reach.uniqueAlt!==ATN.INVALID_ALT_NUMBER) {
predictedAlt = reach.uniqueAlt;
break;
} else if (this.predictionMode !== PredictionMode.LL_EXACT_AMBIG_DETECTION) {
predictedAlt = PredictionMode.resolvesToJustOneViableAlt(altSubSets);
if(predictedAlt !== ATN.INVALID_ALT_NUMBER) {
break;
}
} else {
// In exact ambiguity mode, we never try to terminate early.
// Just keeps scarfing until we know what the conflict is
if (PredictionMode.allSubsetsConflict(altSubSets) && PredictionMode.allSubsetsEqual(altSubSets)) {
foundExactAmbig = true;
predictedAlt = PredictionMode.getSingleViableAlt(altSubSets);
break;
}
// else there are multiple non-conflicting subsets or
// we're not sure what the ambiguity is yet.
// So, keep going.
}
previous = reach;
if( t !== Token.EOF) {
input.consume();
t = input.LA(1);
}
}
// If the configuration set uniquely predicts an alternative,
// without conflict, then we know that it's a full LL decision
// not SLL.
if (reach.uniqueAlt !== ATN.INVALID_ALT_NUMBER ) {
this.reportContextSensitivity(dfa, predictedAlt, reach, startIndex, input.index);
return predictedAlt;
}
// We do not check predicates here because we have checked them
// on-the-fly when doing full context prediction.
//
// In non-exact ambiguity detection mode, we might actually be able to
// detect an exact ambiguity, but I'm not going to spend the cycles
// needed to check. We only emit ambiguity warnings in exact ambiguity
// mode.
//
// For example, we might know that we have conflicting configurations.
// But, that does not mean that there is no way forward without a
// conflict. It's possible to have nonconflicting alt subsets as in:
// altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}]
// from
//
// [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]),
// (13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])]
//
// In this case, (17,1,[5 $]) indicates there is some next sequence that
// would resolve this without conflict to alternative 1. Any other viable
// next sequence, however, is associated with a conflict. We stop
// looking for input because no amount of further lookahead will alter
// the fact that we should predict alternative 1. We just can't say for
// sure that there is an ambiguity without looking further.
this.reportAmbiguity(dfa, D, startIndex, input.index, foundExactAmbig, null, reach);
return predictedAlt;
};
ParserATNSimulator.prototype.computeReachSet = function(closure, t, fullCtx) {
if (this.debug) {
console.log("in computeReachSet, starting closure: " + closure);
}
if( this.mergeCache===null) {
this.mergeCache = new DoubleDict();
}
var intermediate = new ATNConfigSet(fullCtx);
// Configurations already in a rule stop state indicate reaching the end
// of the decision rule (local context) or end of the start rule (full
// context). Once reached, these configurations are never updated by a
// closure operation, so they are handled separately for the performance
// advantage of having a smaller intermediate set when calling closure.
//
// For full-context reach operations, separate handling is required to
// ensure that the alternative matching the longest overall sequence is
// chosen when multiple such configurations can match the input.
var skippedStopStates = null;
// First figure out where we can reach on input t
for (var i=0; i<closure.items.length;i++) {
var c = closure.items[i];
if(this.debug) {
console.log("testing " + this.getTokenName(t) + " at " + c);
}
if (c.state instanceof RuleStopState) {
if (fullCtx || t === Token.EOF) {
if (skippedStopStates===null) {
skippedStopStates = [];
}
skippedStopStates.push(c);
if(this.debug) {
console.log("added " + c + " to skippedStopStates");
}
}
continue;
}
for(var j=0;j<c.state.transitions.length;j++) {
var trans = c.state.transitions[j];
var target = this.getReachableTarget(trans, t);
if (target!==null) {
var cfg = new ATNConfig({state:target}, c);
intermediate.add(cfg, this.mergeCache);
if(this.debug) {
console.log("added " + cfg + " to intermediate");
}
}
}
}
// Now figure out where the reach operation can take us...
var reach = null;
// This block optimizes the reach operation for intermediate sets which
// trivially indicate a termination state for the overall
// adaptivePredict operation.
//
// The conditions assume that intermediate
// contains all configurations relevant to the reach set, but this
// condition is not true when one or more configurations have been
// withheld in skippedStopStates, or when the current symbol is EOF.
//
if (skippedStopStates===null && t!==Token.EOF) {
if (intermediate.items.length===1) {
// Don't pursue the closure if there is just one state.
// It can only have one alternative; just add to result
// Also don't pursue the closure if there is unique alternative
// among the configurations.
reach = intermediate;
} else if (this.getUniqueAlt(intermediate)!==ATN.INVALID_ALT_NUMBER) {
// Also don't pursue the closure if there is unique alternative
// among the configurations.
reach = intermediate;
}
}
// If the reach set could not be trivially determined, perform a closure
// operation on the intermediate set to compute its initial value.
//
if (reach===null) {
reach = new ATNConfigSet(fullCtx);
var closureBusy = new Set();
var treatEofAsEpsilon = t === Token.EOF;
for (var k=0; k<intermediate.items.length;k++) {
this.closure(intermediate.items[k], reach, closureBusy, false, fullCtx, treatEofAsEpsilon);
}
}
if (t === Token.EOF) {
// After consuming EOF no additional input is possible, so we are
// only interested in configurations which reached the end of the
// decision rule (local context) or end of the start rule (full
// context). Update reach to contain only these configurations. This
// handles both explicit EOF transitions in the grammar and implicit
// EOF transitions following the end of the decision or start rule.
//
// When reach==intermediate, no closure operation was performed. In
// this case, removeAllConfigsNotInRuleStopState needs to check for
// reachable rule stop states as well as configurations already in
// a rule stop state.
//
// This is handled before the configurations in skippedStopStates,
// because any configurations potentially added from that list are
// already guaranteed to meet this condition whether or not it's
// required.
//
reach = this.removeAllConfigsNotInRuleStopState(reach, reach === intermediate);
}
// If skippedStopStates!==null, then it contains at least one
// configuration. For full-context reach operations, these
// configurations reached the end of the start rule, in which case we
// only add them back to reach if no configuration during the current
// closure operation reached such a state. This ensures adaptivePredict
// chooses an alternative matching the longest overall sequence when
// multiple alternatives are viable.
//
if (skippedStopStates!==null && ( (! fullCtx) || (! PredictionMode.hasConfigInRuleStopState(reach)))) {
for (var l=0; l<skippedStopStates.length;l++) {
reach.add(skippedStopStates[l], this.mergeCache);
}
}
if (reach.items.length===0) {
return null;
} else {
return reach;
}
};
//
// Return a configuration set containing only the configurations from
// {@code configs} which are in a {@link RuleStopState}. If all
// configurations in {@code configs} are already in a rule stop state, this
// method simply returns {@code configs}.
//
// <p>When {@code lookToEndOfRule} is true, this method uses
// {@link ATN//nextTokens} for each configuration in {@code configs} which is
// not already in a rule stop state to see if a rule stop state is reachable
// from the configuration via epsilon-only transitions.</p>
//
// @param configs the configuration set to update
// @param lookToEndOfRule when true, this method checks for rule stop states
// reachable by epsilon-only transitions from each configuration in
// {@code configs}.
//
// @return {@code configs} if all configurations in {@code configs} are in a
// rule stop state, otherwise return a new configuration set containing only
// the configurations from {@code configs} which are in a rule stop state
//
ParserATNSimulator.prototype.removeAllConfigsNotInRuleStopState = function(configs, lookToEndOfRule) {
if (PredictionMode.allConfigsInRuleStopStates(configs)) {
return configs;
}
var result = new ATNConfigSet(configs.fullCtx);
for(var i=0; i<configs.items.length;i++) {
var config = configs.items[i];
if (config.state instanceof RuleStopState) {
result.add(config, this.mergeCache);
continue;
}
if (lookToEndOfRule && config.state.epsilonOnlyTransitions) {
var nextTokens = this.atn.nextTokens(config.state);
if (nextTokens.contains(Token.EPSILON)) {
var endOfRuleState = this.atn.ruleToStopState[config.state.ruleIndex];
result.add(new ATNConfig({state:endOfRuleState}, config), this.mergeCache);
}
}
}
return result;
};
ParserATNSimulator.prototype.computeStartState = function(p, ctx, fullCtx) {
// always at least the implicit call to start rule
var initialContext = predictionContextFromRuleContext(this.atn, ctx);
var configs = new ATNConfigSet(fullCtx);
for(var i=0;i<p.transitions.length;i++) {
var target = p.transitions[i].target;
var c = new ATNConfig({ state:target, alt:i+1, context:initialContext }, null);
var closureBusy = new Set();
this.closure(c, configs, closureBusy, true, fullCtx, false);
}
return configs;
};
//
// This method transforms the start state computed by
// {@link //computeStartState} to the special start state used by a
// precedence DFA for a particular precedence value. The transformation
// process applies the following changes to the start state's configuration
// set.
//
// <ol>
// <li>Evaluate the precedence predicates for each configuration using
// {@link SemanticContext//evalPrecedence}.</li>
// <li>Remove all configurations which predict an alternative greater than
// 1, for which another configuration that predicts alternative 1 is in the
// same ATN state with the same prediction context. This transformation is
// valid for the following reasons:
// <ul>
// <li>The closure block cannot contain any epsilon transitions which bypass
// the body of the closure, so all states reachable via alternative 1 are
// part of the precedence alternatives of the transformed left-recursive
// rule.</li>
// <li>The "primary" portion of a left recursive rule cannot contain an
// epsilon transition, so the only way an alternative other than 1 can exist
// in a state that is also reachable via alternative 1 is by nesting calls
// to the left-recursive rule, with the outer calls not being at the
// preferred precedence level.</li>
// </ul>
// </li>
// </ol>
//
// <p>
// The prediction context must be considered by this filter to address
// situations like the following.
// </p>
// <code>
// <pre>
// grammar TA;
// prog: statement* EOF;
// statement: letterA | statement letterA 'b' ;
// letterA: 'a';
// </pre>
// </code>
// <p>
// If the above grammar, the ATN state immediately before the token
// reference {@code 'a'} in {@code letterA} is reachable from the left edge
// of both the primary and closure blocks of the left-recursive rule
// {@code statement}. The prediction context associated with each of these
// configurations distinguishes between them, and prevents the alternative
// which stepped out to {@code prog} (and then back in to {@code statement}
// from being eliminated by the filter.
// </p>
//
// @param configs The configuration set computed by
// {@link //computeStartState} as the start state for the DFA.
// @return The transformed configuration set representing the start state
// for a precedence DFA at a particular precedence level (determined by
// calling {@link Parser//getPrecedence}).
//
ParserATNSimulator.prototype.applyPrecedenceFilter = function(configs) {
var config;
var statesFromAlt1 = [];
var configSet = new ATNConfigSet(configs.fullCtx);
for(var i=0; i<configs.items.length; i++) {
config = configs.items[i];
// handle alt 1 first
if (config.alt !== 1) {
continue;
}
var updatedContext = config.semanticContext.evalPrecedence(this.parser, this._outerContext);
if (updatedContext===null) {
// the configuration was eliminated
continue;
}
statesFromAlt1[config.state.stateNumber] = config.context;
if (updatedContext !== config.semanticContext) {
configSet.add(new ATNConfig({semanticContext:updatedContext}, config), this.mergeCache);
} else {
configSet.add(config, this.mergeCache);
}
}
for(i=0; i<configs.items.length; i++) {
config = configs.items[i];
if (config.alt === 1) {
// already handled
continue;
}
// In the future, this elimination step could be updated to also
// filter the prediction context for alternatives predicting alt>1
// (basically a graph subtraction algorithm).
if (!config.precedenceFilterSuppressed) {
var context = statesFromAlt1[config.state.stateNumber] || null;
if (context!==null && context.equals(config.context)) {
// eliminated
continue;
}
}
configSet.add(config, this.mergeCache);
}
return configSet;
};
ParserATNSimulator.prototype.getReachableTarget = function(trans, ttype) {
if (trans.matches(ttype, 0, this.atn.maxTokenType)) {
return trans.target;
} else {
return null;
}
};
ParserATNSimulator.prototype.getPredsForAmbigAlts = function(ambigAlts, configs, nalts) {
// REACH=[1|1|[]|0:0, 1|2|[]|0:1]
// altToPred starts as an array of all null contexts. The entry at index i
// corresponds to alternative i. altToPred[i] may have one of three values:
// 1. null: no ATNConfig c is found such that c.alt==i
// 2. SemanticContext.NONE: At least one ATNConfig c exists such that
// c.alt==i and c.semanticContext==SemanticContext.NONE. In other words,
// alt i has at least one unpredicated config.
// 3. Non-NONE Semantic Context: There exists at least one, and for all
// ATNConfig c such that c.alt==i, c.semanticContext!=SemanticContext.NONE.
//
// From this, it is clear that NONE||anything==NONE.
//
var altToPred = [];
for(var i=0;i<configs.items.length;i++) {
var c = configs.items[i];
if(ambigAlts.contains( c.alt )) {
altToPred[c.alt] = SemanticContext.orContext(altToPred[c.alt] || null, c.semanticContext);
}
}
var nPredAlts = 0;
for (i =1;i< nalts+1;i++) {
var pred = altToPred[i] || null;
if (pred===null) {
altToPred[i] = SemanticContext.NONE;
} else if (pred !== SemanticContext.NONE) {
nPredAlts += 1;
}
}
// nonambig alts are null in altToPred
if (nPredAlts===0) {
altToPred = null;
}
if (this.debug) {
console.log("getPredsForAmbigAlts result " + Utils.arrayToString(altToPred));
}
return altToPred;
};
ParserATNSimulator.prototype.getPredicatePredictions = function(ambigAlts, altToPred) {
var pairs = [];
var containsPredicate = false;
for (var i=1; i<altToPred.length;i++) {
var pred = altToPred[i];
// unpredicated is indicated by SemanticContext.NONE
if( ambigAlts!==null && ambigAlts.contains( i )) {
pairs.push(new PredPrediction(pred, i));
}
if (pred !== SemanticContext.NONE) {
containsPredicate = true;
}
}
if (! containsPredicate) {
return null;
}
return pairs;
};
//
// This method is used to improve the localization of error messages by
// choosing an alternative rather than throwing a
// {@link NoViableAltException} in particular prediction scenarios where the
// {@link //ERROR} state was reached during ATN simulation.
//
// <p>
// The default implementation of this method uses the following
// algorithm to identify an ATN configuration which successfully parsed the
// decision entry rule. Choosing such an alternative ensures that the
// {@link ParserRuleContext} returned by the calling rule will be complete
// and valid, and the syntax error will be reported later at a more
// localized location.</p>
//
// <ul>
// <li>If a syntactically valid path or paths reach the end of the decision rule and
// they are semantically valid if predicated, return the min associated alt.</li>
// <li>Else, if a semantically invalid but syntactically valid path exist
// or paths exist, return the minimum associated alt.
// </li>
// <li>Otherwise, return {@link ATN//INVALID_ALT_NUMBER}.</li>
// </ul>
//
// <p>
// In some scenarios, the algorithm described above could predict an
// alternative which will result in a {@link FailedPredicateException} in
// the parser. Specifically, this could occur if the <em>only</em> configuration
// capable of successfully parsing to the end of the decision rule is
// blocked by a semantic predicate. By choosing this alternative within
// {@link //adaptivePredict} instead of throwing a
// {@link NoViableAltException}, the resulting
// {@link FailedPredicateException} in the parser will identify the specific
// predicate which is preventing the parser from successfully parsing the
// decision rule, which helps developers identify and correct logic errors
// in semantic predicates.
// </p>
//
// @param configs The ATN configurations which were valid immediately before
// the {@link //ERROR} state was reached
// @param outerContext The is the \gamma_0 initial parser context from the paper
// or the parser stack at the instant before prediction commences.
//
// @return The value to return from {@link //adaptivePredict}, or
// {@link ATN//INVALID_ALT_NUMBER} if a suitable alternative was not
// identified and {@link //adaptivePredict} should report an error instead.
//
ParserATNSimulator.prototype.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule = function(configs, outerContext) {
var cfgs = this.splitAccordingToSemanticValidity(configs, outerContext);
var semValidConfigs = cfgs[0];
var semInvalidConfigs = cfgs[1];
var alt = this.getAltThatFinishedDecisionEntryRule(semValidConfigs);
if (alt!==ATN.INVALID_ALT_NUMBER) { // semantically/syntactically viable path exists
return alt;
}
// Is there a syntactically valid path with a failed pred?
if (semInvalidConfigs.items.length>0) {
alt = this.getAltThatFinishedDecisionEntryRule(semInvalidConfigs);
if (alt!==ATN.INVALID_ALT_NUMBER) { // syntactically viable path exists
return alt;
}
}
return ATN.INVALID_ALT_NUMBER;
};
ParserATNSimulator.prototype.getAltThatFinishedDecisionEntryRule = function(configs) {
var alts = [];
for(var i=0;i<configs.items.length; i++) {
var c = configs.items[i];
if (c.reachesIntoOuterContext>0 || ((c.state instanceof RuleStopState) && c.context.hasEmptyPath())) {
if(alts.indexOf(c.alt)<0) {
alts.push(c.alt);
}
}
}
if (alts.length===0) {
return ATN.INVALID_ALT_NUMBER;
} else {
return Math.min.apply(null, alts);
}
};
// Walk the list of configurations and split them according to
// those that have preds evaluating to true/false. If no pred, assume
// true pred and include in succeeded set. Returns Pair of sets.
//
// Create a new set so as not to alter the incoming parameter.
//
// Assumption: the input stream has been restored to the starting point
// prediction, which is where predicates need to evaluate.
//
ParserATNSimulator.prototype.splitAccordingToSemanticValidity = function( configs, outerContext) {
var succeeded = new ATNConfigSet(configs.fullCtx);
var failed = new ATNConfigSet(configs.fullCtx);
for(var i=0;i<configs.items.length; i++) {
var c = configs.items[i];
if (c.semanticContext !== SemanticContext.NONE) {
var predicateEvaluationResult = c.semanticContext.evaluate(this.parser, outerContext);
if (predicateEvaluationResult) {
succeeded.add(c);
} else {
failed.add(c);
}
} else {
succeeded.add(c);
}
}
return [succeeded, failed];
};
// Look through a list of predicate/alt pairs, returning alts for the
// pairs that win. A {@code NONE} predicate indicates an alt containing an
// unpredicated config which behaves as "always true." If !complete
// then we stop at the first predicate that evaluates to true. This
// includes pairs with null predicates.
//
ParserATNSimulator.prototype.evalSemanticContext = function(predPredictions, outerContext, complete) {
var predictions = new BitSet();
for(var i=0;i<predPredictions.length;i++) {
var pair = predPredictions[i];
if (pair.pred === SemanticContext.NONE) {
predictions.add(pair.alt);
if (! complete) {
break;
}
continue;
}
var predicateEvaluationResult = pair.pred.evaluate(this.parser, outerContext);
if (this.debug || this.dfa_debug) {
console.log("eval pred " + pair + "=" + predicateEvaluationResult);
}
if (predicateEvaluationResult) {
if (this.debug || this.dfa_debug) {
console.log("PREDICT " + pair.alt);
}
predictions.add(pair.alt);
if (! complete) {
break;
}
}
}
return predictions;
};
// TODO: If we are doing predicates, there is no point in pursuing
// closure operations if we reach a DFA state that uniquely predicts
// alternative. We will not be caching that DFA state and it is a
// waste to pursue the closure. Might have to advance when we do
// ambig detection thought :(
//
ParserATNSimulator.prototype.closure = function(config, configs, closureBusy, collectPredicates, fullCtx, treatEofAsEpsilon) {
var initialDepth = 0;
this.closureCheckingStopState(config, configs, closureBusy, collectPredicates,
fullCtx, initialDepth, treatEofAsEpsilon);
};
ParserATNSimulator.prototype.closureCheckingStopState = function(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon) {
if (this.debug) {
console.log("closure(" + config.toString(this.parser,true) + ")");
console.log("configs(" + configs.toString() + ")");
if(config.reachesIntoOuterContext>50) {
throw "problem";
}
}
if (config.state instanceof RuleStopState) {
// We hit rule end. If we have context info, use it
// run thru all possible stack tops in ctx
if (! config.context.isEmpty()) {
for ( var i =0; i<config.context.length; i++) {
if (config.context.getReturnState(i) === PredictionContext.EMPTY_RETURN_STATE) {
if (fullCtx) {
configs.add(new ATNConfig({state:config.state, context:PredictionContext.EMPTY}, config), this.mergeCache);
continue;
} else {
// we have no context info, just chase follow links (if greedy)
if (this.debug) {
console.log("FALLING off rule " + this.getRuleName(config.state.ruleIndex));
}
this.closure_(config, configs, closureBusy, collectPredicates,
fullCtx, depth, treatEofAsEpsilon);
}
continue;
}
returnState = this.atn.states[config.context.getReturnState(i)];
newContext = config.context.getParent(i); // "pop" return state
var parms = {state:returnState, alt:config.alt, context:newContext, semanticContext:config.semanticContext};
c = new ATNConfig(parms, null);
// While we have context to pop back from, we may have
// gotten that context AFTER having falling off a rule.
// Make sure we track that we are now out of context.
c.reachesIntoOuterContext = config.reachesIntoOuterContext;
this.closureCheckingStopState(c, configs, closureBusy, collectPredicates, fullCtx, depth - 1, treatEofAsEpsilon);
}
return;
} else if( fullCtx) {
// reached end of start rule
configs.add(config, this.mergeCache);
return;
} else {
// else if we have no context info, just chase follow links (if greedy)
if (this.debug) {
console.log("FALLING off rule " + this.getRuleName(config.state.ruleIndex));
}
}
}
this.closure_(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon);
};
// Do the actual work of walking epsilon edges//
ParserATNSimulator.prototype.closure_ = function(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon) {
var p = config.state;
// optimization
if (! p.epsilonOnlyTransitions) {
configs.add(config, this.mergeCache);
// make sure to not return here, because EOF transitions can act as
// both epsilon transitions and non-epsilon transitions.
}
for(var i = 0;i<p.transitions.length; i++) {
var t = p.transitions[i];
var continueCollecting = collectPredicates && !(t instanceof ActionTransition);
var c = this.getEpsilonTarget(config, t, continueCollecting, depth === 0, fullCtx, treatEofAsEpsilon);
if (c!==null) {
if (!t.isEpsilon && closureBusy.add(c)!==c){
// avoid infinite recursion for EOF* and EOF+
continue;
}
var newDepth = depth;
if ( config.state instanceof RuleStopState) {
// target fell off end of rule; mark resulting c as having dipped into outer context
// We can't get here if incoming config was rule stop and we had context
// track how far we dip into outer context. Might
// come in handy and we avoid evaluating context dependent
// preds if this is > 0.
if (closureBusy.add(c)!==c) {
// avoid infinite recursion for right-recursive rules
continue;
}
if (this._dfa !== null && this._dfa.precedenceDfa) {
if (t.outermostPrecedenceReturn === this._dfa.atnStartState.ruleIndex) {
c.precedenceFilterSuppressed = true;
}
}
c.reachesIntoOuterContext += 1;
configs.dipsIntoOuterContext = true; // TODO: can remove? only care when we add to set per middle of this method
newDepth -= 1;
if (this.debug) {
console.log("dips into outer ctx: " + c);
}
} else if (t instanceof RuleTransition) {
// latch when newDepth goes negative - once we step out of the entry context we can't return
if (newDepth >= 0) {
newDepth += 1;
}
}
this.closureCheckingStopState(c, configs, closureBusy, continueCollecting, fullCtx, newDepth, treatEofAsEpsilon);
}
}
};
ParserATNSimulator.prototype.getRuleName = function( index) {
if (this.parser!==null && index>=0) {
return this.parser.ruleNames[index];
} else {
return "<rule " + index + ">";
}
};
ParserATNSimulator.prototype.getEpsilonTarget = function(config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon) {
switch(t.serializationType) {
case Transition.RULE:
return this.ruleTransition(config, t);
case Transition.PRECEDENCE:
return this.precedenceTransition(config, t, collectPredicates, inContext, fullCtx);
case Transition.PREDICATE:
return this.predTransition(config, t, collectPredicates, inContext, fullCtx);
case Transition.ACTION:
return this.actionTransition(config, t);
case Transition.EPSILON:
return new ATNConfig({state:t.target}, config);
case Transition.ATOM:
case Transition.RANGE:
case Transition.SET:
// EOF transitions act like epsilon transitions after the first EOF
// transition is traversed
if (treatEofAsEpsilon) {
if (t.matches(Token.EOF, 0, 1)) {
return new ATNConfig({state: t.target}, config);
}
}
return null;
default:
return null;
}
};
ParserATNSimulator.prototype.actionTransition = function(config, t) {
if (this.debug) {
console.log("ACTION edge " + t.ruleIndex + ":" + t.actionIndex);
}
return new ATNConfig({state:t.target}, config);
};
ParserATNSimulator.prototype.precedenceTransition = function(config, pt, collectPredicates, inContext, fullCtx) {
if (this.debug) {
console.log("PRED (collectPredicates=" + collectPredicates + ") " +
pt.precedence + ">=_p, ctx dependent=true");
if (this.parser!==null) {
console.log("context surrounding pred is " + Utils.arrayToString(this.parser.getRuleInvocationStack()));
}
}
var c = null;
if (collectPredicates && inContext) {
if (fullCtx) {
// In full context mode, we can evaluate predicates on-the-fly
// during closure, which dramatically reduces the size of
// the config sets. It also obviates the need to test predicates
// later during conflict resolution.
var currentPosition = this._input.index;
this._input.seek(this._startIndex);
var predSucceeds = pt.getPredicate().evaluate(this.parser, this._outerContext);
this._input.seek(currentPosition);
if (predSucceeds) {
c = new ATNConfig({state:pt.target}, config); // no pred context
}
} else {
newSemCtx = SemanticContext.andContext(config.semanticContext, pt.getPredicate());
c = new ATNConfig({state:pt.target, semanticContext:newSemCtx}, config);
}
} else {
c = new ATNConfig({state:pt.target}, config);
}
if (this.debug) {
console.log("config from pred transition=" + c);
}
return c;
};
ParserATNSimulator.prototype.predTransition = function(config, pt, collectPredicates, inContext, fullCtx) {
if (this.debug) {
console.log("PRED (collectPredicates=" + collectPredicates + ") " + pt.ruleIndex +
":" + pt.predIndex + ", ctx dependent=" + pt.isCtxDependent);
if (this.parser!==null) {
console.log("context surrounding pred is " + Utils.arrayToString(this.parser.getRuleInvocationStack()));
}
}
var c = null;
if (collectPredicates && ((pt.isCtxDependent && inContext) || ! pt.isCtxDependent)) {
if (fullCtx) {
// In full context mode, we can evaluate predicates on-the-fly
// during closure, which dramatically reduces the size of
// the config sets. It also obviates the need to test predicates
// later during conflict resolution.
var currentPosition = this._input.index;
this._input.seek(this._startIndex);
var predSucceeds = pt.getPredicate().evaluate(this.parser, this._outerContext);
this._input.seek(currentPosition);
if (predSucceeds) {
c = new ATNConfig({state:pt.target}, config); // no pred context
}
} else {
var newSemCtx = SemanticContext.andContext(config.semanticContext, pt.getPredicate());
c = new ATNConfig({state:pt.target, semanticContext:newSemCtx}, config);
}
} else {
c = new ATNConfig({state:pt.target}, config);
}
if (this.debug) {
console.log("config from pred transition=" + c);
}
return c;
};
ParserATNSimulator.prototype.ruleTransition = function(config, t) {
if (this.debug) {
console.log("CALL rule " + this.getRuleName(t.target.ruleIndex) + ", ctx=" + config.context);
}
var returnState = t.followState;
var newContext = SingletonPredictionContext.create(config.context, returnState.stateNumber);
return new ATNConfig({state:t.target, context:newContext}, config );
};
ParserATNSimulator.prototype.getConflictingAlts = function(configs) {
var altsets = PredictionMode.getConflictingAltSubsets(configs);
return PredictionMode.getAlts(altsets);
};
// Sam pointed out a problem with the previous definition, v3, of
// ambiguous states. If we have another state associated with conflicting
// alternatives, we should keep going. For example, the following grammar
//
// s : (ID | ID ID?) ';' ;
//
// When the ATN simulation reaches the state before ';', it has a DFA
// state that looks like: [12|1|[], 6|2|[], 12|2|[]]. Naturally
// 12|1|[] and 12|2|[] conflict, but we cannot stop processing this node
// because alternative to has another way to continue, via [6|2|[]].
// The key is that we have a single state that has config's only associated
// with a single alternative, 2, and crucially the state transitions
// among the configurations are all non-epsilon transitions. That means
// we don't consider any conflicts that include alternative 2. So, we
// ignore the conflict between alts 1 and 2. We ignore a set of
// conflicting alts when there is an intersection with an alternative
// associated with a single alt state in the state→config-list map.
//
// It's also the case that we might have two conflicting configurations but
// also a 3rd nonconflicting configuration for a different alternative:
// [1|1|[], 1|2|[], 8|3|[]]. This can come about from grammar:
//
// a : A | A | A B ;
//
// After matching input A, we reach the stop state for rule A, state 1.
// State 8 is the state right before B. Clearly alternatives 1 and 2
// conflict and no amount of further lookahead will separate the two.
// However, alternative 3 will be able to continue and so we do not
// stop working on this state. In the previous example, we're concerned
// with states associated with the conflicting alternatives. Here alt
// 3 is not associated with the conflicting configs, but since we can continue
// looking for input reasonably, I don't declare the state done. We
// ignore a set of conflicting alts when we have an alternative
// that we still need to pursue.
//
ParserATNSimulator.prototype.getConflictingAltsOrUniqueAlt = function(configs) {
var conflictingAlts = null;
if (configs.uniqueAlt!== ATN.INVALID_ALT_NUMBER) {
conflictingAlts = new BitSet();
conflictingAlts.add(configs.uniqueAlt);
} else {
conflictingAlts = configs.conflictingAlts;
}
return conflictingAlts;
};
ParserATNSimulator.prototype.getTokenName = function( t) {
if (t===Token.EOF) {
return "EOF";
}
if( this.parser!==null && this.parser.literalNames!==null) {
if (t >= this.parser.literalNames.length) {
console.log("" + t + " ttype out of range: " + this.parser.literalNames);
console.log("" + this.parser.getInputStream().getTokens());
} else {
return this.parser.literalNames[t] + "<" + t + ">";
}
}
return "" + t;
};
ParserATNSimulator.prototype.getLookaheadName = function(input) {
return this.getTokenName(input.LA(1));
};
// Used for debugging in adaptivePredict around execATN but I cut
// it out for clarity now that alg. works well. We can leave this
// "dead" code for a bit.
//
ParserATNSimulator.prototype.dumpDeadEndConfigs = function(nvae) {
console.log("dead end configs: ");
var decs = nvae.getDeadEndConfigs();
for(var i=0; i<decs.length; i++) {
var c = decs[i];
var trans = "no edges";
if (c.state.transitions.length>0) {
var t = c.state.transitions[0];
if (t instanceof AtomTransition) {
trans = "Atom "+ this.getTokenName(t.label);
} else if (t instanceof SetTransition) {
var neg = (t instanceof NotSetTransition);
trans = (neg ? "~" : "") + "Set " + t.set;
}
}
console.error(c.toString(this.parser, true) + ":" + trans);
}
};
ParserATNSimulator.prototype.noViableAlt = function(input, outerContext, configs, startIndex) {
return new NoViableAltException(this.parser, input, input.get(startIndex), input.LT(1), configs, outerContext);
};
ParserATNSimulator.prototype.getUniqueAlt = function(configs) {
var alt = ATN.INVALID_ALT_NUMBER;
for(var i=0;i<configs.items.length;i++) {
var c = configs.items[i];
if (alt === ATN.INVALID_ALT_NUMBER) {
alt = c.alt // found first alt
} else if( c.alt!==alt) {
return ATN.INVALID_ALT_NUMBER;
}
}
return alt;
};
//
// Add an edge to the DFA, if possible. This method calls
// {@link //addDFAState} to ensure the {@code to} state is present in the
// DFA. If {@code from} is {@code null}, or if {@code t} is outside the
// range of edges that can be represented in the DFA tables, this method
// returns without adding the edge to the DFA.
//
// <p>If {@code to} is {@code null}, this method returns {@code null}.
// Otherwise, this method returns the {@link DFAState} returned by calling
// {@link //addDFAState} for the {@code to} state.</p>
//
// @param dfa The DFA
// @param from The source state for the edge
// @param t The input symbol
// @param to The target state for the edge
//
// @return If {@code to} is {@code null}, this method returns {@code null};
// otherwise this method returns the result of calling {@link //addDFAState}
// on {@code to}
//
ParserATNSimulator.prototype.addDFAEdge = function(dfa, from_, t, to) {
if( this.debug) {
console.log("EDGE " + from_ + " -> " + to + " upon " + this.getTokenName(t));
}
if (to===null) {
return null;
}
to = this.addDFAState(dfa, to); // used existing if possible not incoming
if (from_===null || t < -1 || t > this.atn.maxTokenType) {
return to;
}
if (from_.edges===null) {
from_.edges = [];
}
from_.edges[t+1] = to; // connect
if (this.debug) {
var names = this.parser===null ? null : this.parser.literalNames;
console.log("DFA=\n" + dfa.toString(names));
}
return to;
};
//
// Add state {@code D} to the DFA if it is not already present, and return
// the actual instance stored in the DFA. If a state equivalent to {@code D}
// is already in the DFA, the existing state is returned. Otherwise this
// method returns {@code D} after adding it to the DFA.
//
// <p>If {@code D} is {@link //ERROR}, this method returns {@link //ERROR} and
// does not change the DFA.</p>
//
// @param dfa The dfa
// @param D The DFA state to add
// @return The state stored in the DFA. This will be either the existing
// state if {@code D} is already in the DFA, or {@code D} itself if the
// state was not already present.
//
ParserATNSimulator.prototype.addDFAState = function(dfa, D) {
if (D == ATNSimulator.ERROR) {
return D;
}
var hash = D.hashString();
var existing = dfa.states[hash] || null;
if(existing!==null) {
return existing;
}
D.stateNumber = dfa.states.length;
if (! D.configs.readonly) {
D.configs.optimizeConfigs(this);
D.configs.setReadonly(true);
}
dfa.states[hash] = D;
if (this.debug) {
console.log("adding new DFA state: " + D);
}
return D;
};
ParserATNSimulator.prototype.reportAttemptingFullContext = function(dfa, conflictingAlts, configs, startIndex, stopIndex) {
if (this.debug || this.retry_debug) {
var interval = new Interval(startIndex, stopIndex + 1);
console.log("reportAttemptingFullContext decision=" + dfa.decision + ":" + configs +
", input=" + this.parser.getTokenStream().getText(interval));
}
if (this.parser!==null) {
this.parser.getErrorListenerDispatch().reportAttemptingFullContext(this.parser, dfa, startIndex, stopIndex, conflictingAlts, configs);
}
};
ParserATNSimulator.prototype.reportContextSensitivity = function(dfa, prediction, configs, startIndex, stopIndex) {
if (this.debug || this.retry_debug) {
var interval = new Interval(startIndex, stopIndex + 1);
console.log("reportContextSensitivity decision=" + dfa.decision + ":" + configs +
", input=" + this.parser.getTokenStream().getText(interval));
}
if (this.parser!==null) {
this.parser.getErrorListenerDispatch().reportContextSensitivity(this.parser, dfa, startIndex, stopIndex, prediction, configs);
}
};
// If context sensitive parsing, we know it's ambiguity not conflict//
ParserATNSimulator.prototype.reportAmbiguity = function(dfa, D, startIndex, stopIndex,
exact, ambigAlts, configs ) {
if (this.debug || this.retry_debug) {
var interval = new Interval(startIndex, stopIndex + 1);
console.log("reportAmbiguity " + ambigAlts + ":" + configs +
", input=" + this.parser.getTokenStream().getText(interval));
}
if (this.parser!==null) {
this.parser.getErrorListenerDispatch().reportAmbiguity(this.parser, dfa, startIndex, stopIndex, exact, ambigAlts, configs);
}
};
exports.ParserATNSimulator = ParserATNSimulator; | alberto-chiesa/grunt-jsl10n | tasks/antlr4/atn/ParserATNSimulator.js | JavaScript | mit | 74,098 |
<?php
$type='TrueTypeUnicode';
$name='DejaVuSansCondensed-BoldOblique';
$desc=array('Ascent'=>928,'Descent'=>-236,'CapHeight'=>-46,'Flags'=>96,'FontBBox'=>'[-960 -385 1804 1121]','ItalicAngle'=>-11,'StemV'=>120,'MissingWidth'=>540);
$up=-63;
$ut=44;
$dw=540;
$cw=array(
0=>540,32=>313,33=>410,34=>469,35=>626,36=>626,37=>901,38=>785,39=>275,40=>411,
41=>411,42=>470,43=>754,44=>342,45=>374,46=>342,47=>329,48=>626,49=>626,50=>626,
51=>626,52=>626,53=>626,54=>626,55=>626,56=>626,57=>626,58=>360,59=>360,60=>754,
61=>754,62=>754,63=>522,64=>900,65=>696,66=>686,67=>660,68=>747,69=>615,70=>615,
71=>738,72=>753,73=>334,74=>334,75=>697,76=>573,77=>896,78=>753,79=>765,80=>659,
81=>765,82=>693,83=>648,84=>614,85=>730,86=>696,87=>993,88=>694,89=>651,90=>652,
91=>411,92=>329,93=>411,94=>754,95=>450,96=>450,97=>607,98=>644,99=>533,100=>644,
101=>610,102=>391,103=>644,104=>641,105=>308,106=>308,107=>598,108=>308,109=>938,110=>641,
111=>618,112=>644,113=>644,114=>444,115=>536,116=>430,117=>641,118=>586,119=>831,120=>580,
121=>586,122=>523,123=>641,124=>329,125=>641,126=>754,8364=>626,8218=>342,402=>391,8222=>580,
8230=>900,8224=>450,8225=>450,710=>450,8240=>1309,352=>648,8249=>371,338=>1050,381=>652,8216=>342,
8217=>342,8220=>580,8221=>580,8226=>575,8211=>450,8212=>900,732=>450,8482=>900,353=>536,8250=>371,
339=>984,382=>523,376=>651,160=>313,161=>410,162=>626,163=>626,164=>572,165=>626,166=>329,
167=>450,168=>450,169=>900,170=>507,171=>584,172=>754,173=>374,174=>900,175=>450,176=>450,
177=>754,178=>394,179=>394,180=>450,181=>662,182=>572,183=>342,184=>450,185=>394,186=>507,
187=>584,188=>932,189=>932,190=>932,191=>522,192=>696,193=>696,194=>696,195=>696,196=>696,
197=>696,198=>976,199=>660,200=>615,201=>615,202=>615,203=>615,204=>334,205=>334,206=>334,
207=>334,208=>760,209=>753,210=>765,211=>765,212=>765,213=>765,214=>765,215=>754,216=>765,
217=>730,218=>730,219=>730,220=>730,221=>651,222=>668,223=>647,224=>607,225=>607,226=>607,
227=>607,228=>607,229=>607,230=>943,231=>533,232=>610,233=>610,234=>610,235=>610,236=>308,
237=>308,238=>308,239=>308,240=>618,241=>641,242=>618,243=>618,244=>618,245=>618,246=>618,
247=>754,248=>618,249=>641,250=>641,251=>641,252=>641,253=>586,254=>644,255=>586,256=>696,
257=>607,258=>696,259=>607,260=>696,261=>607,262=>660,263=>533,264=>660,265=>533,266=>660,
267=>533,268=>660,269=>533,270=>747,271=>644,272=>760,273=>644,274=>615,275=>610,276=>615,
277=>610,278=>615,279=>610,280=>615,281=>610,282=>615,283=>610,284=>738,285=>644,286=>738,
287=>644,288=>738,289=>644,290=>738,291=>644,292=>753,293=>641,294=>876,295=>711,296=>334,
297=>308,298=>334,299=>308,300=>334,301=>308,302=>334,303=>308,304=>334,305=>308,306=>669,
307=>617,308=>334,309=>308,310=>697,311=>598,312=>598,313=>573,314=>308,315=>573,316=>308,
317=>573,318=>308,319=>573,320=>308,321=>594,322=>337,323=>753,324=>641,325=>753,326=>641,
327=>753,328=>641,329=>884,330=>753,331=>641,332=>765,333=>618,334=>765,335=>618,336=>765,
337=>618,340=>693,341=>444,342=>693,343=>444,344=>693,345=>444,346=>648,347=>536,348=>648,
349=>536,350=>648,351=>536,354=>614,355=>430,356=>614,357=>430,358=>614,359=>430,360=>730,
361=>641,362=>730,363=>641,364=>730,365=>641,366=>730,367=>641,368=>730,369=>641,370=>730,
371=>641,372=>993,373=>831,374=>651,375=>586,377=>652,378=>523,379=>652,380=>523,383=>391,
384=>644,385=>729,386=>686,387=>644,388=>686,389=>644,390=>660,391=>660,392=>533,393=>760,
394=>791,395=>686,396=>644,397=>618,398=>615,399=>765,400=>626,401=>615,403=>738,404=>713,
405=>940,406=>392,407=>350,408=>697,409=>598,410=>324,411=>532,412=>938,413=>753,414=>641,
415=>765,416=>765,417=>618,418=>1002,419=>866,420=>703,421=>644,422=>693,423=>648,424=>536,
425=>615,426=>497,427=>430,428=>636,429=>430,430=>614,431=>730,432=>641,433=>692,434=>732,
435=>717,436=>700,437=>652,438=>523,439=>695,440=>695,441=>576,442=>523,443=>626,444=>695,
445=>576,446=>515,447=>644,448=>334,449=>593,450=>489,451=>334,452=>1393,453=>1305,454=>1176,
455=>879,456=>881,457=>603,458=>1074,459=>1091,460=>957,461=>696,462=>607,463=>334,464=>308,
465=>765,466=>618,467=>730,468=>641,469=>730,470=>641,471=>730,472=>641,473=>730,474=>641,
475=>730,476=>641,477=>610,478=>696,479=>607,480=>696,481=>607,482=>976,483=>943,484=>738,
485=>644,486=>738,487=>644,488=>697,489=>598,490=>765,491=>618,492=>765,493=>618,494=>695,
495=>523,496=>308,497=>1393,498=>1305,499=>1176,500=>738,501=>644,502=>1160,503=>708,504=>753,
505=>641,506=>696,507=>607,508=>976,509=>943,510=>765,511=>618,512=>696,513=>607,514=>696,
515=>607,516=>615,517=>610,518=>615,519=>610,520=>334,521=>308,522=>334,523=>308,524=>765,
525=>618,526=>765,527=>618,528=>693,529=>444,530=>693,531=>444,532=>730,533=>641,534=>730,
535=>641,536=>648,537=>536,538=>614,539=>430,540=>621,541=>546,542=>753,543=>641,544=>753,
545=>778,546=>728,547=>593,548=>652,549=>523,550=>696,551=>607,552=>615,553=>610,554=>765,
555=>618,556=>765,557=>618,558=>765,559=>618,560=>765,561=>618,562=>651,563=>586,564=>442,
565=>780,566=>460,567=>308,568=>979,569=>979,570=>696,571=>660,572=>533,573=>573,574=>614,
575=>536,576=>523,577=>703,578=>553,579=>686,580=>730,581=>696,582=>615,583=>610,584=>334,
585=>308,586=>774,587=>712,588=>693,589=>444,590=>651,591=>586,592=>607,593=>644,594=>644,
595=>644,596=>533,597=>533,598=>712,599=>712,600=>610,601=>610,602=>788,603=>501,604=>490,
605=>696,606=>658,607=>308,608=>712,609=>644,610=>564,611=>661,612=>571,613=>641,614=>641,
615=>641,616=>491,617=>396,618=>491,619=>502,620=>624,621=>308,622=>757,623=>938,624=>938,
625=>938,626=>641,627=>713,628=>578,629=>618,630=>817,631=>613,632=>716,633=>484,634=>484,
635=>584,636=>444,637=>444,638=>536,639=>536,640=>578,641=>578,642=>536,643=>374,644=>391,
645=>544,646=>497,647=>430,648=>430,649=>828,650=>692,651=>603,652=>586,653=>831,654=>586,
655=>651,656=>624,657=>615,658=>576,659=>576,660=>515,661=>515,662=>515,663=>515,664=>765,
665=>569,666=>658,667=>616,668=>622,669=>308,670=>659,671=>485,672=>712,673=>515,674=>515,
675=>1040,676=>1093,677=>1039,678=>876,679=>691,680=>836,681=>923,682=>712,683=>702,684=>532,
685=>374,686=>609,687=>710,688=>410,689=>410,690=>197,691=>284,692=>284,693=>284,694=>369,
695=>532,696=>375,697=>271,698=>469,699=>342,700=>342,701=>342,702=>330,703=>330,704=>293,
705=>293,706=>450,707=>450,708=>450,709=>450,711=>450,712=>275,713=>450,714=>450,715=>450,
716=>275,717=>450,718=>450,719=>450,720=>303,721=>303,722=>330,723=>330,724=>450,725=>450,
726=>374,727=>295,728=>450,729=>450,730=>450,731=>450,733=>450,734=>315,735=>450,736=>370,
737=>197,738=>343,739=>371,740=>293,741=>450,742=>450,743=>450,744=>450,745=>450,748=>450,
749=>450,750=>580,755=>450,759=>450,768=>0,769=>0,770=>0,771=>0,772=>0,773=>0,
774=>0,775=>0,776=>0,777=>0,778=>0,779=>0,780=>0,781=>0,782=>0,783=>0,
784=>0,785=>0,786=>0,787=>0,788=>0,789=>0,790=>0,791=>0,792=>0,793=>0,
794=>0,795=>0,796=>0,797=>0,798=>0,799=>0,800=>0,801=>0,802=>0,803=>0,
804=>0,805=>0,806=>0,807=>0,808=>0,809=>0,810=>0,811=>0,812=>0,813=>0,
814=>0,815=>0,816=>0,817=>0,818=>0,819=>0,820=>0,821=>0,822=>0,823=>0,
824=>0,825=>0,826=>0,827=>0,828=>0,829=>0,830=>0,831=>0,832=>0,833=>0,
834=>0,835=>0,836=>0,837=>0,838=>0,839=>0,840=>0,841=>0,842=>0,843=>0,
844=>0,845=>0,846=>0,847=>0,849=>0,850=>0,851=>0,855=>0,856=>0,858=>0,
860=>0,861=>0,862=>0,863=>0,864=>0,865=>0,866=>0,880=>628,881=>508,882=>919,
883=>752,884=>271,885=>271,886=>753,887=>630,890=>450,891=>533,892=>495,893=>494,894=>360,
900=>397,901=>450,902=>717,903=>342,904=>761,905=>908,906=>507,908=>801,910=>882,911=>804,
912=>351,913=>696,914=>686,915=>573,916=>696,917=>615,918=>652,919=>753,920=>765,921=>334,
922=>697,923=>696,924=>896,925=>753,926=>568,927=>765,928=>753,929=>659,931=>615,932=>614,
933=>651,934=>765,935=>694,936=>765,937=>765,938=>334,939=>651,940=>618,941=>501,942=>641,
943=>351,944=>607,945=>618,946=>644,947=>613,948=>618,949=>501,950=>532,951=>641,952=>618,
953=>351,954=>639,955=>569,956=>662,957=>613,958=>532,959=>618,960=>712,961=>644,962=>533,
963=>701,964=>574,965=>607,966=>704,967=>580,968=>714,969=>782,970=>351,971=>607,972=>618,
973=>607,974=>782,975=>697,976=>585,977=>594,978=>671,979=>883,980=>671,981=>716,982=>782,
983=>669,984=>765,985=>618,986=>660,987=>533,988=>615,989=>444,990=>632,991=>593,992=>827,
993=>564,994=>983,995=>753,996=>749,997=>644,998=>835,999=>669,1000=>660,1001=>585,1002=>709,
1003=>604,1004=>677,1005=>644,1006=>614,1007=>531,1008=>669,1009=>644,1010=>533,1011=>308,1012=>765,
1013=>580,1014=>580,1015=>668,1016=>644,1017=>660,1018=>896,1019=>659,1020=>644,1021=>660,1022=>660,
1023=>628,1024=>615,1025=>615,1026=>791,1027=>573,1028=>660,1029=>648,1030=>334,1031=>334,1032=>334,
1033=>1039,1034=>1017,1035=>791,1036=>735,1037=>753,1038=>694,1039=>753,1040=>696,1041=>686,1042=>686,
1043=>573,1044=>801,1045=>615,1046=>1102,1047=>639,1048=>753,1049=>753,1050=>735,1051=>747,1052=>896,
1053=>753,1054=>765,1055=>753,1056=>659,1057=>660,1058=>614,1059=>694,1060=>892,1061=>694,1062=>835,
1063=>727,1064=>1112,1065=>1193,1066=>845,1067=>932,1068=>686,1069=>660,1070=>1056,1071=>693,1072=>607,
1073=>628,1074=>569,1075=>470,1076=>727,1077=>610,1078=>896,1079=>523,1080=>630,1081=>630,1082=>611,
1083=>659,1084=>735,1085=>622,1086=>618,1087=>622,1088=>644,1089=>533,1090=>521,1091=>586,1092=>893,
1093=>580,1094=>667,1095=>618,1096=>956,1097=>995,1098=>676,1099=>813,1100=>569,1101=>533,1102=>875,
1103=>578,1104=>610,1105=>610,1106=>642,1107=>470,1108=>533,1109=>536,1110=>308,1111=>308,1112=>308,
1113=>892,1114=>860,1115=>661,1116=>611,1117=>630,1118=>586,1119=>622,1120=>983,1121=>782,1122=>756,
1123=>662,1124=>911,1125=>755,1126=>893,1127=>749,1128=>1222,1129=>1009,1130=>765,1131=>618,1132=>1112,
1133=>906,1134=>626,1135=>501,1136=>967,1137=>955,1138=>765,1139=>618,1140=>765,1141=>625,1142=>765,
1143=>625,1144=>1033,1145=>939,1146=>967,1147=>776,1148=>1265,1149=>1055,1150=>983,1151=>782,1152=>660,
1153=>533,1154=>587,1155=>0,1156=>0,1157=>0,1158=>0,1159=>0,1160=>376,1161=>376,1162=>844,
1163=>725,1164=>686,1165=>550,1166=>662,1167=>646,1168=>573,1169=>470,1170=>599,1171=>488,1172=>709,
1173=>470,1174=>1102,1175=>896,1176=>639,1177=>523,1178=>697,1179=>611,1180=>735,1181=>611,1182=>735,
1183=>611,1184=>914,1185=>743,1186=>753,1187=>622,1188=>992,1189=>783,1190=>1129,1191=>880,1192=>851,
1193=>773,1194=>660,1195=>533,1196=>614,1197=>521,1198=>651,1199=>586,1200=>651,1201=>586,1202=>694,
1203=>580,1204=>993,1205=>901,1206=>727,1207=>618,1208=>727,1209=>618,1210=>727,1211=>641,1212=>923,
1213=>729,1214=>923,1215=>729,1216=>334,1217=>1102,1218=>896,1219=>700,1220=>566,1221=>839,1222=>724,
1223=>753,1224=>622,1225=>844,1226=>725,1227=>727,1228=>618,1229=>986,1230=>838,1231=>308,1232=>696,
1233=>607,1234=>696,1235=>607,1236=>976,1237=>943,1238=>615,1239=>610,1240=>765,1241=>610,1242=>765,
1243=>610,1244=>1102,1245=>896,1246=>639,1247=>523,1248=>695,1249=>576,1250=>753,1251=>630,1252=>753,
1253=>630,1254=>765,1255=>618,1256=>765,1257=>618,1258=>765,1259=>618,1260=>660,1261=>533,1262=>694,
1263=>586,1264=>694,1265=>586,1266=>694,1267=>586,1268=>727,1269=>618,1270=>573,1271=>470,1272=>932,
1273=>813,1274=>599,1275=>488,1276=>694,1277=>580,1278=>694,1279=>580,1280=>686,1281=>547,1282=>1043,
1283=>804,1284=>1007,1285=>828,1286=>745,1287=>624,1288=>1117,1289=>915,1290=>1160,1291=>912,1292=>755,
1293=>574,1294=>844,1295=>722,1296=>626,1297=>501,1298=>747,1299=>659,1300=>1157,1301=>963,1302=>958,
1303=>883,1304=>973,1305=>864,1306=>765,1307=>644,1308=>993,1309=>831,1312=>1123,1313=>920,1314=>1128,
1315=>880,1316=>861,1317=>726,1329=>886,1330=>730,1331=>886,1332=>886,1333=>730,1334=>699,1335=>730,
1336=>730,1337=>877,1338=>886,1339=>730,1340=>639,1341=>970,1342=>1022,1343=>730,1344=>639,1345=>681,
1346=>886,1347=>789,1348=>886,1349=>714,1350=>886,1351=>730,1352=>730,1353=>730,1354=>862,1355=>699,
1356=>886,1357=>730,1358=>886,1359=>648,1360=>730,1361=>714,1362=>805,1363=>765,1364=>842,1365=>765,
1366=>648,1369=>330,1370=>342,1371=>495,1372=>495,1373=>342,1374=>491,1375=>468,1377=>938,1378=>641,
1379=>779,1380=>781,1381=>641,1382=>735,1383=>588,1384=>641,1385=>729,1386=>735,1387=>641,1388=>448,
1389=>916,1390=>644,1391=>641,1392=>641,1393=>644,1394=>737,1395=>641,1396=>676,1397=>308,1398=>794,
1399=>502,1400=>641,1401=>502,1402=>938,1403=>502,1404=>777,1405=>641,1406=>732,1407=>938,1408=>641,
1409=>644,1410=>514,1411=>938,1412=>700,1413=>618,1414=>648,1415=>776,1417=>360,1418=>438,1456=>0,
1457=>0,1458=>0,1459=>0,1460=>0,1461=>0,1462=>0,1463=>0,1464=>0,1465=>0,1466=>0,
1467=>0,1468=>0,1469=>0,1470=>374,1471=>0,1472=>334,1473=>0,1474=>0,1475=>334,1478=>447,
1479=>0,1488=>676,1489=>605,1490=>483,1491=>589,1492=>641,1493=>308,1494=>442,1495=>641,1496=>651,
1497=>308,1498=>584,1499=>584,1500=>611,1501=>641,1502=>698,1503=>308,1504=>447,1505=>696,1506=>610,
1507=>646,1508=>618,1509=>565,1510=>676,1511=>656,1512=>584,1513=>854,1514=>676,1520=>598,1521=>598,
1522=>597,1523=>399,1524=>639,3647=>626,3713=>734,3714=>673,3716=>674,3719=>512,3720=>668,3722=>669,
3725=>685,3732=>635,3733=>633,3734=>672,3735=>737,3737=>657,3738=>654,3739=>654,3740=>830,3741=>744,
3742=>779,3743=>779,3745=>752,3746=>685,3747=>692,3749=>691,3751=>642,3754=>744,3755=>928,3757=>651,
3758=>705,3759=>840,3760=>620,3761=>0,3762=>549,3763=>549,3764=>0,3765=>0,3766=>0,3767=>0,
3768=>0,3769=>0,3771=>0,3772=>0,3773=>603,3776=>464,3777=>774,3778=>464,3779=>584,3780=>569,
3782=>683,3784=>0,3785=>0,3786=>0,3787=>0,3788=>0,3789=>0,3792=>694,3793=>694,3794=>624,
3795=>752,3796=>655,3797=>655,3798=>764,3799=>710,3800=>683,3801=>818,3804=>1227,3805=>1227,4256=>826,
4257=>669,4258=>665,4259=>753,4260=>584,4261=>696,4262=>771,4263=>800,4264=>477,4265=>570,4266=>771,
4267=>810,4268=>579,4269=>813,4270=>732,4271=>677,4272=>782,4273=>579,4274=>579,4275=>797,4276=>797,
4277=>660,4278=>587,4279=>579,4280=>582,4281=>579,4282=>710,4283=>812,4284=>570,4285=>557,4286=>579,
4287=>700,4288=>802,4289=>541,4290=>668,4291=>554,4292=>570,4293=>668,4304=>497,4305=>497,4306=>536,
4307=>734,4308=>505,4309=>506,4310=>497,4311=>744,4312=>497,4313=>488,4314=>967,4315=>506,4316=>507,
4317=>730,4318=>497,4319=>532,4320=>740,4321=>506,4322=>621,4323=>525,4324=>732,4325=>505,4326=>731,
4327=>506,4328=>506,4329=>507,4330=>568,4331=>506,4332=>506,4333=>497,4334=>506,4335=>506,4336=>501,
4337=>543,4338=>497,4339=>497,4340=>497,4341=>544,4342=>767,4343=>571,4344=>506,4345=>536,4346=>487,
4347=>615,4348=>331,5121=>696,5122=>696,5123=>696,5124=>696,5125=>814,5126=>814,5127=>814,5129=>814,
5130=>814,5131=>814,5132=>916,5133=>908,5134=>916,5135=>908,5136=>916,5137=>908,5138=>1034,5139=>1025,
5140=>1034,5141=>1025,5142=>814,5143=>1034,5144=>1028,5145=>1034,5146=>1028,5147=>814,5149=>278,5150=>476,
5151=>382,5152=>382,5153=>355,5154=>355,5155=>355,5156=>355,5157=>507,5158=>423,5159=>278,5160=>355,
5161=>355,5162=>355,5163=>1092,5164=>888,5165=>1094,5166=>1167,5167=>696,5168=>696,5169=>696,5170=>696,
5171=>797,5172=>797,5173=>797,5175=>797,5176=>797,5177=>797,5178=>916,5179=>908,5180=>916,5181=>908,
5182=>916,5183=>908,5184=>1034,5185=>1025,5186=>1034,5187=>1025,5188=>1034,5189=>1028,5190=>1034,5191=>1028,
5192=>797,5193=>518,5194=>206,5196=>730,5197=>730,5198=>730,5199=>730,5200=>734,5201=>734,5202=>734,
5204=>734,5205=>734,5206=>734,5207=>950,5208=>943,5209=>950,5210=>943,5211=>950,5212=>943,5213=>954,
5214=>949,5215=>954,5216=>949,5217=>954,5218=>946,5219=>954,5220=>946,5221=>954,5222=>435,5223=>904,
5224=>904,5225=>921,5226=>915,5227=>668,5228=>668,5229=>668,5230=>668,5231=>668,5232=>668,5233=>668,
5234=>668,5235=>668,5236=>926,5237=>877,5238=>882,5239=>877,5240=>882,5241=>877,5242=>926,5243=>877,
5244=>926,5245=>877,5246=>882,5247=>877,5248=>882,5249=>877,5250=>882,5251=>451,5252=>451,5253=>844,
5254=>844,5255=>844,5256=>844,5257=>668,5258=>668,5259=>668,5260=>668,5261=>668,5262=>668,5263=>668,
5264=>668,5265=>668,5266=>926,5267=>877,5268=>926,5269=>877,5270=>926,5271=>877,5272=>926,5273=>877,
5274=>926,5275=>877,5276=>926,5277=>877,5278=>926,5279=>877,5280=>926,5281=>451,5282=>451,5283=>563,
5284=>563,5285=>563,5286=>563,5287=>563,5288=>563,5289=>563,5290=>563,5291=>563,5292=>793,5293=>769,
5294=>777,5295=>786,5296=>777,5297=>786,5298=>793,5299=>786,5300=>793,5301=>786,5302=>777,5303=>786,
5304=>777,5305=>786,5306=>777,5307=>392,5308=>493,5309=>392,5312=>889,5313=>889,5314=>889,5315=>889,
5316=>838,5317=>838,5318=>838,5319=>838,5320=>838,5321=>1114,5322=>1122,5323=>1080,5324=>1105,5325=>1080,
5326=>1105,5327=>838,5328=>593,5329=>447,5330=>593,5331=>889,5332=>889,5333=>889,5334=>889,5335=>838,
5336=>838,5337=>838,5338=>838,5339=>838,5340=>1107,5341=>1122,5342=>1155,5343=>1105,5344=>1155,5345=>1105,
5346=>1105,5347=>1093,5348=>1105,5349=>1093,5350=>1155,5351=>1105,5352=>1155,5353=>1105,5354=>593,5356=>797,
5357=>657,5358=>657,5359=>657,5360=>657,5361=>657,5362=>657,5363=>657,5364=>657,5365=>657,5366=>897,
5367=>862,5368=>870,5369=>890,5370=>870,5371=>890,5372=>897,5373=>862,5374=>897,5375=>862,5376=>870,
5377=>890,5378=>870,5379=>890,5380=>870,5381=>443,5382=>414,5383=>443,5392=>831,5393=>831,5394=>831,
5395=>1022,5396=>1022,5397=>1022,5398=>1022,5399=>1088,5400=>1081,5401=>1088,5402=>1081,5403=>1088,5404=>1081,
5405=>1288,5406=>1278,5407=>1288,5408=>1278,5409=>1288,5410=>1278,5411=>1288,5412=>1278,5413=>671,5414=>698,
5415=>698,5416=>698,5417=>698,5418=>698,5419=>698,5420=>698,5421=>698,5422=>698,5423=>902,5424=>903,
5425=>911,5426=>896,5427=>911,5428=>896,5429=>902,5430=>903,5431=>902,5432=>903,5433=>911,5434=>896,
5435=>911,5436=>896,5437=>911,5438=>445,5440=>355,5441=>458,5442=>929,5443=>929,5444=>878,5445=>878,
5446=>878,5447=>878,5448=>659,5449=>659,5450=>659,5451=>659,5452=>659,5453=>659,5454=>902,5455=>863,
5456=>445,5458=>797,5459=>696,5460=>696,5461=>696,5462=>696,5463=>835,5464=>835,5465=>835,5466=>835,
5467=>1055,5468=>1028,5469=>542,5470=>730,5471=>730,5472=>730,5473=>730,5474=>730,5475=>730,5476=>734,
5477=>734,5478=>734,5479=>734,5480=>954,5481=>946,5482=>493,5492=>879,5493=>879,5494=>879,5495=>879,
5496=>879,5497=>879,5498=>879,5499=>556,5500=>753,5501=>458,5502=>1114,5503=>1114,5504=>1114,5505=>1114,
5506=>1114,5507=>1114,5508=>1114,5509=>890,5514=>879,5515=>879,5516=>879,5517=>879,5518=>1432,5519=>1432,
5520=>1432,5521=>1165,5522=>1165,5523=>1432,5524=>1432,5525=>763,5526=>1146,5536=>889,5537=>889,5538=>838,
5539=>838,5540=>838,5541=>838,5542=>593,5543=>698,5544=>698,5545=>698,5546=>698,5547=>698,5548=>698,
5549=>698,5550=>445,5551=>668,5598=>747,5601=>747,5702=>446,5703=>446,5742=>371,5743=>1114,5744=>1432,
5745=>1814,5746=>1814,5747=>1548,5748=>1510,5749=>1814,5750=>1814,7424=>586,7425=>750,7426=>943,7427=>547,
7428=>533,7429=>608,7430=>608,7431=>502,7432=>501,7433=>308,7434=>444,7435=>598,7436=>485,7437=>735,
7438=>630,7439=>618,7440=>533,7441=>594,7442=>594,7443=>594,7444=>984,7446=>618,7447=>618,7448=>500,
7449=>578,7450=>578,7451=>521,7452=>571,7453=>663,7454=>853,7455=>625,7456=>586,7457=>831,7458=>523,
7459=>581,7462=>485,7463=>586,7464=>622,7465=>500,7466=>703,7467=>659,7468=>438,7469=>615,7470=>432,
7472=>470,7473=>387,7474=>387,7475=>465,7476=>474,7477=>211,7478=>211,7479=>439,7480=>361,7481=>563,
7482=>474,7483=>474,7484=>481,7485=>458,7486=>415,7487=>436,7488=>387,7489=>460,7490=>625,7491=>412,
7492=>412,7493=>431,7494=>641,7495=>431,7496=>431,7497=>431,7498=>431,7499=>347,7500=>347,7501=>431,
7502=>197,7503=>438,7504=>597,7505=>410,7506=>439,7507=>372,7508=>439,7509=>439,7510=>431,7511=>349,
7512=>410,7513=>416,7514=>597,7515=>451,7517=>405,7518=>386,7519=>389,7520=>443,7521=>365,7522=>197,
7523=>284,7524=>410,7525=>451,7526=>405,7527=>386,7528=>405,7529=>443,7530=>365,7543=>644,7544=>474,
7547=>491,7549=>672,7557=>462,7579=>431,7580=>372,7581=>372,7582=>439,7583=>347,7584=>339,7585=>313,
7586=>431,7587=>410,7588=>312,7589=>253,7590=>312,7591=>312,7592=>388,7593=>293,7594=>296,7595=>333,
7596=>598,7597=>597,7598=>505,7599=>505,7600=>403,7601=>439,7602=>488,7603=>379,7604=>356,7605=>349,
7606=>524,7607=>444,7608=>359,7609=>405,7610=>451,7611=>375,7612=>471,7613=>422,7614=>409,7615=>382,
7620=>0,7621=>0,7622=>0,7623=>0,7624=>0,7625=>0,7680=>696,7681=>607,7682=>686,7683=>644,
7684=>686,7685=>644,7686=>686,7687=>644,7688=>660,7689=>533,7690=>747,7691=>644,7692=>747,7693=>644,
7694=>747,7695=>644,7696=>747,7697=>644,7698=>747,7699=>644,7700=>615,7701=>610,7702=>615,7703=>610,
7704=>615,7705=>610,7706=>615,7707=>610,7708=>615,7709=>610,7710=>615,7711=>391,7712=>738,7713=>644,
7714=>753,7715=>641,7716=>753,7717=>641,7718=>753,7719=>641,7720=>753,7721=>641,7722=>753,7723=>641,
7724=>334,7725=>308,7726=>334,7727=>308,7728=>697,7729=>598,7730=>697,7731=>598,7732=>697,7733=>598,
7734=>573,7735=>308,7736=>573,7737=>308,7738=>573,7739=>308,7740=>573,7741=>308,7742=>896,7743=>938,
7744=>896,7745=>938,7746=>896,7747=>938,7748=>753,7749=>641,7750=>753,7751=>641,7752=>753,7753=>641,
7754=>753,7755=>641,7756=>765,7757=>618,7758=>765,7759=>618,7760=>765,7761=>618,7762=>765,7763=>618,
7764=>659,7765=>644,7766=>659,7767=>644,7768=>693,7769=>444,7770=>693,7771=>444,7772=>693,7773=>444,
7774=>693,7775=>444,7776=>648,7777=>536,7778=>648,7779=>536,7780=>648,7781=>536,7782=>648,7783=>536,
7784=>648,7785=>536,7786=>614,7787=>430,7788=>614,7789=>430,7790=>614,7791=>430,7792=>614,7793=>430,
7794=>730,7795=>641,7796=>730,7797=>641,7798=>730,7799=>641,7800=>730,7801=>641,7802=>730,7803=>641,
7804=>696,7805=>586,7806=>696,7807=>586,7808=>993,7809=>831,7810=>993,7811=>831,7812=>993,7813=>831,
7814=>993,7815=>831,7816=>993,7817=>831,7818=>694,7819=>580,7820=>694,7821=>580,7822=>651,7823=>586,
7824=>652,7825=>523,7826=>652,7827=>523,7828=>652,7829=>523,7830=>641,7831=>430,7832=>831,7833=>586,
7834=>607,7835=>391,7836=>391,7837=>391,7838=>806,7839=>618,7840=>696,7841=>607,7842=>696,7843=>607,
7844=>696,7845=>607,7846=>696,7847=>607,7848=>696,7849=>607,7850=>696,7851=>607,7852=>696,7853=>607,
7854=>696,7855=>607,7856=>696,7857=>607,7858=>696,7859=>607,7860=>696,7861=>607,7862=>696,7863=>607,
7864=>615,7865=>610,7866=>615,7867=>610,7868=>615,7869=>610,7870=>615,7871=>610,7872=>615,7873=>610,
7874=>615,7875=>610,7876=>615,7877=>610,7878=>615,7879=>610,7880=>334,7881=>308,7882=>334,7883=>308,
7884=>765,7885=>618,7886=>765,7887=>618,7888=>765,7889=>618,7890=>765,7891=>618,7892=>765,7893=>618,
7894=>765,7895=>618,7896=>765,7897=>618,7898=>765,7899=>618,7900=>765,7901=>618,7902=>765,7903=>618,
7904=>765,7905=>618,7906=>765,7907=>618,7908=>730,7909=>641,7910=>730,7911=>641,7912=>730,7913=>641,
7914=>730,7915=>641,7916=>730,7917=>641,7918=>730,7919=>641,7920=>730,7921=>641,7922=>651,7923=>586,
7924=>651,7925=>586,7926=>651,7927=>586,7928=>651,7929=>586,7930=>857,7931=>579,7936=>618,7937=>618,
7938=>618,7939=>618,7940=>618,7941=>618,7942=>618,7943=>618,7944=>696,7945=>696,7946=>937,7947=>939,
7948=>841,7949=>866,7950=>751,7951=>773,7952=>501,7953=>501,7954=>501,7955=>501,7956=>501,7957=>501,
7960=>712,7961=>715,7962=>989,7963=>986,7964=>920,7965=>947,7968=>641,7969=>641,7970=>641,7971=>641,
7972=>641,7973=>641,7974=>641,7975=>641,7976=>851,7977=>856,7978=>1125,7979=>1125,7980=>1062,7981=>1085,
7982=>948,7983=>956,7984=>351,7985=>351,7986=>351,7987=>351,7988=>351,7989=>351,7990=>351,7991=>351,
7992=>435,7993=>440,7994=>699,7995=>707,7996=>641,7997=>664,7998=>544,7999=>544,8000=>618,8001=>618,
8002=>618,8003=>618,8004=>618,8005=>618,8008=>802,8009=>839,8010=>1099,8011=>1101,8012=>947,8013=>974,
8016=>607,8017=>607,8018=>607,8019=>607,8020=>607,8021=>607,8022=>607,8023=>607,8025=>837,8027=>1065,
8029=>1079,8031=>944,8032=>782,8033=>782,8034=>782,8035=>782,8036=>782,8037=>782,8038=>782,8039=>782,
8040=>817,8041=>862,8042=>1121,8043=>1126,8044=>968,8045=>994,8046=>925,8047=>968,8048=>618,8049=>618,
8050=>501,8051=>501,8052=>641,8053=>641,8054=>351,8055=>351,8056=>618,8057=>618,8058=>607,8059=>607,
8060=>782,8061=>782,8064=>618,8065=>618,8066=>618,8067=>618,8068=>618,8069=>618,8070=>618,8071=>618,
8072=>696,8073=>696,8074=>937,8075=>939,8076=>841,8077=>866,8078=>751,8079=>773,8080=>641,8081=>641,
8082=>641,8083=>641,8084=>641,8085=>641,8086=>641,8087=>641,8088=>851,8089=>856,8090=>1125,8091=>1125,
8092=>1062,8093=>1085,8094=>948,8095=>956,8096=>782,8097=>782,8098=>782,8099=>782,8100=>782,8101=>782,
8102=>782,8103=>782,8104=>817,8105=>862,8106=>1121,8107=>1126,8108=>968,8109=>994,8110=>925,8111=>968,
8112=>618,8113=>618,8114=>618,8115=>618,8116=>618,8118=>618,8119=>618,8120=>696,8121=>696,8122=>789,
8123=>717,8124=>696,8125=>450,8126=>450,8127=>450,8128=>450,8129=>450,8130=>641,8131=>641,8132=>641,
8134=>641,8135=>641,8136=>836,8137=>761,8138=>972,8139=>908,8140=>753,8141=>450,8142=>450,8143=>450,
8144=>351,8145=>351,8146=>351,8147=>351,8150=>351,8151=>351,8152=>334,8153=>334,8154=>559,8155=>507,
8157=>450,8158=>450,8159=>450,8160=>607,8161=>607,8162=>607,8163=>607,8164=>644,8165=>644,8166=>607,
8167=>607,8168=>651,8169=>651,8170=>918,8171=>882,8172=>754,8173=>450,8174=>450,8175=>450,8178=>782,
8179=>782,8180=>782,8182=>782,8183=>782,8184=>958,8185=>801,8186=>976,8187=>804,8188=>765,8189=>450,
8190=>450,8192=>450,8193=>900,8194=>450,8195=>900,8196=>296,8197=>225,8198=>150,8199=>626,8200=>342,
8201=>180,8202=>89,8203=>0,8204=>0,8205=>0,8206=>0,8207=>0,8208=>374,8209=>374,8210=>626,
8213=>900,8214=>450,8215=>450,8219=>342,8223=>591,8227=>575,8228=>342,8229=>616,8231=>313,8232=>0,
8233=>0,8234=>0,8235=>0,8236=>0,8237=>0,8238=>0,8239=>180,8241=>1717,8242=>237,8243=>402,
8244=>567,8245=>237,8246=>402,8247=>567,8248=>659,8251=>875,8252=>564,8253=>522,8254=>450,8255=>745,
8256=>745,8257=>296,8258=>920,8259=>450,8260=>150,8261=>411,8262=>411,8263=>927,8264=>746,8265=>746,
8266=>461,8267=>618,8268=>450,8269=>450,8270=>470,8271=>360,8272=>745,8273=>470,8274=>500,8275=>754,
8276=>745,8277=>754,8278=>615,8279=>731,8280=>754,8281=>754,8282=>342,8283=>784,8284=>754,8285=>342,
8286=>342,8287=>200,8288=>0,8289=>0,8290=>0,8291=>0,8292=>0,8298=>0,8299=>0,8300=>0,
8301=>0,8302=>0,8303=>0,8304=>394,8305=>197,8308=>394,8309=>394,8310=>394,8311=>394,8312=>394,
8313=>394,8314=>475,8315=>475,8316=>475,8317=>259,8318=>259,8319=>410,8320=>394,8321=>394,8322=>394,
8323=>394,8324=>394,8325=>394,8326=>394,8327=>394,8328=>394,8329=>394,8330=>475,8331=>475,8332=>475,
8333=>259,8334=>259,8336=>412,8337=>431,8338=>439,8339=>371,8340=>431,8352=>836,8353=>626,8354=>626,
8355=>626,8356=>626,8357=>938,8358=>753,8359=>1339,8360=>1084,8361=>993,8362=>768,8363=>626,8365=>626,
8366=>626,8367=>1252,8368=>626,8369=>626,8370=>626,8371=>626,8372=>773,8373=>626,8376=>626,8377=>626,
8400=>0,8401=>0,8406=>0,8407=>0,8411=>0,8412=>0,8417=>0,8448=>995,8449=>995,8450=>660,
8451=>1090,8452=>807,8453=>1002,8454=>1033,8455=>626,8456=>628,8457=>856,8459=>965,8460=>822,8461=>799,
8462=>641,8463=>641,8464=>537,8465=>627,8466=>771,8467=>424,8468=>876,8469=>753,8470=>1083,8471=>900,
8472=>627,8473=>675,8474=>765,8475=>844,8476=>732,8477=>721,8478=>807,8479=>639,8480=>917,8481=>1115,
8483=>751,8484=>679,8485=>560,8486=>765,8487=>692,8488=>686,8489=>272,8490=>697,8491=>696,8492=>835,
8493=>736,8494=>769,8495=>572,8496=>656,8497=>727,8498=>615,8499=>1065,8500=>418,8501=>714,8502=>658,
8503=>444,8504=>615,8505=>342,8506=>851,8507=>1232,8508=>710,8509=>663,8510=>589,8511=>776,8512=>756,
8513=>707,8514=>518,8515=>573,8516=>684,8517=>747,8518=>644,8519=>610,8520=>308,8521=>308,8523=>785,
8526=>492,8528=>932,8529=>932,8530=>1334,8531=>932,8532=>932,8533=>932,8534=>932,8535=>932,8536=>932,
8537=>932,8538=>932,8539=>932,8540=>932,8541=>932,8542=>932,8543=>554,8544=>334,8545=>593,8546=>851,
8547=>989,8548=>696,8549=>989,8550=>1247,8551=>1505,8552=>1008,8553=>694,8554=>1008,8555=>1266,8556=>573,
8557=>660,8558=>747,8559=>896,8560=>308,8561=>546,8562=>785,8563=>885,8564=>586,8565=>866,8566=>1104,
8567=>1342,8568=>872,8569=>580,8570=>872,8571=>1110,8572=>308,8573=>533,8574=>644,8575=>938,8576=>1160,
8577=>747,8578=>1160,8579=>660,8580=>533,8581=>660,8585=>932,8592=>754,8593=>754,8594=>754,8595=>754,
8596=>754,8597=>754,8598=>754,8599=>754,8600=>754,8601=>754,8602=>754,8603=>754,8604=>754,8605=>754,
8606=>754,8607=>754,8608=>754,8609=>754,8610=>754,8611=>754,8612=>754,8613=>754,8614=>754,8615=>754,
8616=>754,8617=>754,8618=>754,8619=>754,8620=>754,8621=>754,8622=>754,8623=>754,8624=>754,8625=>754,
8626=>754,8627=>754,8628=>754,8629=>754,8630=>754,8631=>754,8632=>754,8633=>754,8634=>754,8635=>754,
8636=>754,8637=>754,8638=>754,8639=>754,8640=>754,8641=>754,8642=>754,8643=>754,8644=>754,8645=>754,
8646=>754,8647=>754,8648=>754,8649=>754,8650=>754,8651=>754,8652=>754,8653=>754,8654=>754,8655=>754,
8656=>754,8657=>754,8658=>754,8659=>754,8660=>754,8661=>754,8662=>754,8663=>754,8664=>754,8665=>754,
8666=>754,8667=>754,8668=>754,8669=>754,8670=>754,8671=>754,8672=>754,8673=>754,8674=>754,8675=>754,
8676=>754,8677=>754,8678=>754,8679=>754,8680=>754,8681=>754,8682=>754,8683=>754,8684=>754,8685=>754,
8686=>754,8687=>754,8688=>754,8689=>754,8690=>754,8691=>754,8692=>754,8693=>754,8694=>754,8695=>754,
8696=>754,8697=>754,8698=>754,8699=>754,8700=>754,8701=>754,8702=>754,8703=>754,8704=>696,8705=>626,
8706=>489,8707=>615,8708=>615,8709=>771,8710=>627,8711=>627,8712=>807,8713=>807,8714=>675,8715=>807,
8716=>807,8717=>675,8718=>572,8719=>708,8720=>708,8721=>646,8722=>754,8723=>754,8724=>626,8725=>329,
8726=>626,8727=>754,8728=>563,8729=>342,8730=>600,8731=>600,8732=>600,8733=>641,8734=>750,8735=>754,
8736=>807,8737=>807,8738=>754,8739=>450,8740=>450,8741=>450,8742=>450,8743=>730,8744=>730,8745=>730,
8746=>730,8747=>549,8748=>835,8749=>1165,8750=>506,8751=>879,8752=>1181,8753=>506,8754=>506,8755=>506,
8756=>626,8757=>626,8758=>264,8759=>626,8760=>754,8761=>754,8762=>754,8763=>754,8764=>754,8765=>754,
8766=>754,8767=>754,8768=>337,8769=>754,8770=>754,8771=>754,8772=>754,8773=>754,8774=>754,8775=>754,
8776=>754,8777=>754,8778=>754,8779=>754,8780=>754,8781=>754,8782=>754,8783=>754,8784=>754,8785=>754,
8786=>754,8787=>754,8788=>956,8789=>956,8790=>754,8791=>754,8792=>754,8793=>754,8794=>754,8795=>754,
8796=>754,8797=>754,8798=>754,8799=>754,8800=>754,8801=>754,8802=>754,8803=>754,8804=>754,8805=>754,
8806=>754,8807=>754,8808=>756,8809=>756,8810=>942,8811=>942,8812=>450,8813=>754,8814=>754,8815=>754,
8816=>754,8817=>754,8818=>754,8819=>754,8820=>754,8821=>754,8822=>754,8823=>754,8824=>754,8825=>754,
8826=>754,8827=>754,8828=>754,8829=>754,8830=>754,8831=>754,8832=>754,8833=>754,8834=>754,8835=>754,
8836=>754,8837=>754,8838=>754,8839=>754,8840=>754,8841=>754,8842=>754,8843=>754,8844=>730,8845=>730,
8846=>730,8847=>754,8848=>754,8849=>754,8850=>754,8851=>716,8852=>716,8853=>754,8854=>754,8855=>754,
8856=>754,8857=>754,8858=>754,8859=>754,8860=>754,8861=>754,8862=>754,8863=>754,8864=>754,8865=>754,
8866=>822,8867=>822,8868=>822,8869=>822,8870=>488,8871=>488,8872=>822,8873=>822,8874=>822,8875=>822,
8876=>822,8877=>822,8878=>822,8879=>822,8880=>754,8881=>754,8882=>754,8883=>754,8884=>754,8885=>754,
8886=>900,8887=>900,8888=>754,8889=>754,8890=>488,8891=>730,8892=>730,8893=>730,8894=>754,8895=>754,
8896=>758,8897=>758,8898=>758,8899=>758,8900=>444,8901=>342,8902=>563,8903=>754,8904=>900,8905=>900,
8906=>900,8907=>900,8908=>900,8909=>754,8910=>730,8911=>730,8912=>754,8913=>754,8914=>754,8915=>754,
8916=>754,8917=>754,8918=>754,8919=>754,8920=>1280,8921=>1280,8922=>754,8923=>754,8924=>754,8925=>754,
8926=>754,8927=>754,8928=>754,8929=>754,8930=>754,8931=>754,8932=>754,8933=>754,8934=>754,8935=>754,
8936=>754,8937=>754,8938=>754,8939=>754,8940=>754,8941=>754,8942=>900,8943=>900,8944=>900,8945=>900,
8946=>1042,8947=>807,8948=>675,8949=>807,8950=>807,8951=>675,8952=>807,8953=>807,8954=>1042,8955=>807,
8956=>675,8957=>807,8958=>675,8959=>807,8960=>542,8961=>542,8962=>644,8963=>754,8964=>754,8965=>754,
8966=>754,8967=>439,8968=>411,8969=>411,8970=>411,8971=>411,8972=>728,8973=>728,8974=>728,8975=>728,
8976=>754,8977=>484,8984=>835,8985=>754,8988=>422,8989=>422,8990=>422,8991=>422,8992=>549,8993=>549,
8996=>1037,8997=>1037,8998=>1272,8999=>1037,9000=>1299,9003=>1272,9004=>786,9075=>351,9076=>644,9077=>782,
9082=>618,9085=>776,9095=>1037,9108=>786,9115=>450,9116=>450,9117=>450,9118=>450,9119=>450,9120=>450,
9121=>450,9122=>450,9123=>450,9124=>450,9125=>450,9126=>450,9127=>675,9128=>675,9129=>675,9130=>675,
9131=>675,9132=>675,9133=>675,9134=>549,9166=>754,9167=>850,9187=>786,9189=>692,9192=>626,9250=>644,
9251=>644,9312=>762,9313=>762,9314=>762,9315=>762,9316=>762,9317=>762,9318=>762,9319=>762,9320=>762,
9321=>762,9600=>692,9601=>692,9602=>692,9603=>692,9604=>692,9605=>692,9606=>692,9607=>692,9608=>692,
9609=>692,9610=>692,9611=>692,9612=>692,9613=>692,9614=>692,9615=>692,9616=>692,9617=>692,9618=>692,
9619=>692,9620=>692,9621=>692,9622=>692,9623=>692,9624=>692,9625=>692,9626=>692,9627=>692,9628=>692,
9629=>692,9630=>692,9631=>692,9632=>850,9633=>850,9634=>850,9635=>850,9636=>850,9637=>850,9638=>850,
9639=>850,9640=>850,9641=>850,9642=>610,9643=>610,9644=>850,9645=>850,9646=>495,9647=>495,9648=>692,
9649=>692,9650=>692,9651=>692,9652=>452,9653=>452,9654=>692,9655=>692,9656=>452,9657=>452,9658=>692,
9659=>692,9660=>692,9661=>692,9662=>452,9663=>452,9664=>692,9665=>692,9666=>452,9667=>452,9668=>692,
9669=>692,9670=>692,9671=>692,9672=>692,9673=>785,9674=>444,9675=>785,9676=>785,9677=>785,9678=>785,
9679=>785,9680=>785,9681=>785,9682=>785,9683=>785,9684=>785,9685=>785,9686=>474,9687=>474,9688=>756,
9689=>873,9690=>873,9691=>873,9692=>348,9693=>348,9694=>348,9695=>348,9696=>692,9697=>692,9698=>692,
9699=>692,9700=>692,9701=>692,9702=>575,9703=>850,9704=>850,9705=>850,9706=>850,9707=>850,9708=>692,
9709=>692,9710=>692,9711=>1007,9712=>850,9713=>850,9714=>850,9715=>850,9716=>785,9717=>785,9718=>785,
9719=>785,9720=>692,9721=>692,9722=>692,9723=>747,9724=>747,9725=>659,9726=>659,9727=>692,9728=>807,
9729=>900,9730=>807,9731=>807,9732=>807,9733=>807,9734=>807,9735=>515,9736=>806,9737=>807,9738=>799,
9739=>799,9740=>604,9741=>911,9742=>1121,9743=>1125,9744=>807,9745=>807,9746=>807,9747=>479,9748=>807,
9749=>807,9750=>807,9751=>807,9752=>807,9753=>807,9754=>807,9755=>807,9756=>807,9757=>548,9758=>807,
9759=>548,9760=>807,9761=>807,9762=>807,9763=>807,9764=>602,9765=>671,9766=>584,9767=>705,9768=>490,
9769=>807,9770=>807,9771=>807,9772=>639,9773=>807,9774=>807,9775=>807,9776=>807,9777=>807,9778=>807,
9779=>807,9780=>807,9781=>807,9782=>807,9783=>807,9784=>807,9785=>807,9786=>807,9787=>807,9788=>807,
9789=>807,9790=>807,9791=>552,9792=>659,9793=>659,9794=>807,9795=>807,9796=>807,9797=>807,9798=>807,
9799=>807,9800=>807,9801=>807,9802=>807,9803=>807,9804=>807,9805=>807,9806=>807,9807=>807,9808=>807,
9809=>807,9810=>807,9811=>807,9812=>807,9813=>807,9814=>807,9815=>807,9816=>807,9817=>807,9818=>807,
9819=>807,9820=>807,9821=>807,9822=>807,9823=>807,9824=>807,9825=>807,9826=>807,9827=>807,9828=>807,
9829=>807,9830=>807,9831=>807,9832=>807,9833=>424,9834=>574,9835=>807,9836=>807,9837=>424,9838=>321,
9839=>435,9840=>673,9841=>689,9842=>807,9843=>807,9844=>807,9845=>807,9846=>807,9847=>807,9848=>807,
9849=>807,9850=>807,9851=>807,9852=>807,9853=>807,9854=>807,9855=>807,9856=>782,9857=>782,9858=>782,
9859=>782,9860=>782,9861=>782,9862=>807,9863=>807,9864=>807,9865=>807,9866=>807,9867=>807,9868=>807,
9869=>807,9870=>807,9871=>807,9872=>807,9873=>807,9874=>807,9875=>807,9876=>807,9877=>487,9878=>807,
9879=>807,9880=>807,9881=>807,9882=>807,9883=>807,9884=>807,9888=>807,9889=>632,9890=>904,9891=>980,
9892=>1057,9893=>813,9894=>754,9895=>754,9896=>754,9897=>754,9898=>754,9899=>754,9900=>754,9901=>754,
9902=>754,9903=>754,9904=>759,9905=>754,9906=>659,9907=>659,9908=>659,9909=>659,9910=>765,9911=>659,
9912=>659,9920=>754,9921=>754,9922=>754,9923=>754,9985=>754,9986=>754,9987=>754,9988=>754,9990=>754,
9991=>754,9992=>754,9993=>754,9996=>754,9997=>754,9998=>754,9999=>754,10000=>754,10001=>754,10002=>754,
10003=>754,10004=>754,10005=>754,10006=>754,10007=>754,10008=>754,10009=>754,10010=>754,10011=>754,10012=>754,
10013=>754,10014=>754,10015=>754,10016=>754,10017=>754,10018=>754,10019=>754,10020=>754,10021=>754,10022=>754,
10023=>754,10025=>754,10026=>754,10027=>754,10028=>754,10029=>754,10030=>754,10031=>754,10032=>754,10033=>754,
10034=>754,10035=>754,10036=>754,10037=>754,10038=>754,10039=>754,10040=>754,10041=>754,10042=>754,10043=>754,
10044=>754,10045=>754,10046=>754,10047=>754,10048=>754,10049=>754,10050=>754,10051=>754,10052=>754,10053=>754,
10054=>754,10055=>754,10056=>754,10057=>754,10058=>754,10059=>754,10061=>807,10063=>807,10064=>807,10065=>807,
10066=>807,10070=>807,10072=>754,10073=>754,10074=>754,10075=>290,10076=>290,10077=>484,10078=>484,10081=>754,
10082=>754,10083=>754,10084=>754,10085=>754,10086=>754,10087=>754,10088=>754,10089=>754,10090=>754,10091=>754,
10092=>754,10093=>754,10094=>754,10095=>754,10096=>754,10097=>754,10098=>754,10099=>754,10100=>754,10101=>754,
10102=>762,10103=>762,10104=>762,10105=>762,10106=>762,10107=>762,10108=>762,10109=>762,10110=>762,10111=>762,
10112=>754,10113=>754,10114=>754,10115=>754,10116=>754,10117=>754,10118=>754,10119=>754,10120=>754,10121=>754,
10122=>754,10123=>754,10124=>754,10125=>754,10126=>754,10127=>754,10128=>754,10129=>754,10130=>754,10131=>754,
10132=>754,10136=>754,10137=>754,10138=>754,10139=>754,10140=>754,10141=>754,10142=>754,10143=>754,10144=>754,
10145=>754,10146=>754,10147=>754,10148=>754,10149=>754,10150=>754,10151=>754,10152=>754,10153=>754,10154=>754,
10155=>754,10156=>754,10157=>754,10158=>754,10159=>754,10161=>754,10162=>754,10163=>754,10164=>754,10165=>754,
10166=>754,10167=>754,10168=>754,10169=>754,10170=>754,10171=>754,10172=>754,10173=>754,10174=>754,10181=>411,
10182=>411,10208=>444,10214=>438,10215=>438,10216=>411,10217=>411,10218=>648,10219=>648,10224=>754,10225=>754,
10226=>754,10227=>754,10228=>1042,10229=>1290,10230=>1290,10231=>1290,10232=>1290,10233=>1290,10234=>1290,10235=>1290,
10236=>1290,10237=>1290,10238=>1290,10239=>1290,10240=>703,10241=>703,10242=>703,10243=>703,10244=>703,10245=>703,
10246=>703,10247=>703,10248=>703,10249=>703,10250=>703,10251=>703,10252=>703,10253=>703,10254=>703,10255=>703,
10256=>703,10257=>703,10258=>703,10259=>703,10260=>703,10261=>703,10262=>703,10263=>703,10264=>703,10265=>703,
10266=>703,10267=>703,10268=>703,10269=>703,10270=>703,10271=>703,10272=>703,10273=>703,10274=>703,10275=>703,
10276=>703,10277=>703,10278=>703,10279=>703,10280=>703,10281=>703,10282=>703,10283=>703,10284=>703,10285=>703,
10286=>703,10287=>703,10288=>703,10289=>703,10290=>703,10291=>703,10292=>703,10293=>703,10294=>703,10295=>703,
10296=>703,10297=>703,10298=>703,10299=>703,10300=>703,10301=>703,10302=>703,10303=>703,10304=>703,10305=>703,
10306=>703,10307=>703,10308=>703,10309=>703,10310=>703,10311=>703,10312=>703,10313=>703,10314=>703,10315=>703,
10316=>703,10317=>703,10318=>703,10319=>703,10320=>703,10321=>703,10322=>703,10323=>703,10324=>703,10325=>703,
10326=>703,10327=>703,10328=>703,10329=>703,10330=>703,10331=>703,10332=>703,10333=>703,10334=>703,10335=>703,
10336=>703,10337=>703,10338=>703,10339=>703,10340=>703,10341=>703,10342=>703,10343=>703,10344=>703,10345=>703,
10346=>703,10347=>703,10348=>703,10349=>703,10350=>703,10351=>703,10352=>703,10353=>703,10354=>703,10355=>703,
10356=>703,10357=>703,10358=>703,10359=>703,10360=>703,10361=>703,10362=>703,10363=>703,10364=>703,10365=>703,
10366=>703,10367=>703,10368=>703,10369=>703,10370=>703,10371=>703,10372=>703,10373=>703,10374=>703,10375=>703,
10376=>703,10377=>703,10378=>703,10379=>703,10380=>703,10381=>703,10382=>703,10383=>703,10384=>703,10385=>703,
10386=>703,10387=>703,10388=>703,10389=>703,10390=>703,10391=>703,10392=>703,10393=>703,10394=>703,10395=>703,
10396=>703,10397=>703,10398=>703,10399=>703,10400=>703,10401=>703,10402=>703,10403=>703,10404=>703,10405=>703,
10406=>703,10407=>703,10408=>703,10409=>703,10410=>703,10411=>703,10412=>703,10413=>703,10414=>703,10415=>703,
10416=>703,10417=>703,10418=>703,10419=>703,10420=>703,10421=>703,10422=>703,10423=>703,10424=>703,10425=>703,
10426=>703,10427=>703,10428=>703,10429=>703,10430=>703,10431=>703,10432=>703,10433=>703,10434=>703,10435=>703,
10436=>703,10437=>703,10438=>703,10439=>703,10440=>703,10441=>703,10442=>703,10443=>703,10444=>703,10445=>703,
10446=>703,10447=>703,10448=>703,10449=>703,10450=>703,10451=>703,10452=>703,10453=>703,10454=>703,10455=>703,
10456=>703,10457=>703,10458=>703,10459=>703,10460=>703,10461=>703,10462=>703,10463=>703,10464=>703,10465=>703,
10466=>703,10467=>703,10468=>703,10469=>703,10470=>703,10471=>703,10472=>703,10473=>703,10474=>703,10475=>703,
10476=>703,10477=>703,10478=>703,10479=>703,10480=>703,10481=>703,10482=>703,10483=>703,10484=>703,10485=>703,
10486=>703,10487=>703,10488=>703,10489=>703,10490=>703,10491=>703,10492=>703,10493=>703,10494=>703,10495=>703,
10502=>754,10503=>754,10506=>754,10507=>754,10560=>754,10561=>754,10627=>678,10628=>678,10702=>754,10703=>941,
10704=>941,10705=>900,10706=>900,10707=>900,10708=>900,10709=>900,10731=>444,10746=>754,10747=>754,10752=>900,
10753=>900,10754=>900,10764=>1495,10765=>506,10766=>506,10767=>506,10768=>506,10769=>506,10770=>506,10771=>506,
10772=>506,10773=>506,10774=>506,10775=>506,10776=>506,10777=>506,10778=>506,10779=>506,10780=>506,10799=>754,
10877=>754,10878=>754,10879=>754,10880=>754,10881=>754,10882=>754,10883=>754,10884=>754,10885=>754,10886=>754,
10887=>754,10888=>754,10889=>754,10890=>754,10891=>754,10892=>754,10893=>754,10894=>754,10895=>754,10896=>754,
10897=>754,10898=>754,10899=>754,10900=>754,10901=>754,10902=>754,10903=>754,10904=>754,10905=>754,10906=>754,
10907=>754,10908=>754,10909=>754,10910=>754,10911=>754,10912=>754,10926=>754,10927=>754,10928=>754,10929=>754,
10930=>754,10931=>754,10932=>754,10933=>754,10934=>754,10935=>754,10936=>754,10937=>754,10938=>754,11001=>754,
11002=>754,11008=>754,11009=>754,11010=>754,11011=>754,11012=>754,11013=>754,11014=>754,11015=>754,11016=>754,
11017=>754,11018=>754,11019=>754,11020=>754,11021=>754,11022=>754,11023=>754,11024=>754,11025=>754,11026=>850,
11027=>850,11028=>850,11029=>850,11030=>692,11031=>692,11032=>692,11033=>692,11034=>850,11039=>782,11040=>782,
11041=>786,11042=>786,11043=>786,11044=>1007,11091=>782,11092=>782,11360=>573,11361=>324,11362=>573,11363=>659,
11364=>693,11365=>607,11366=>430,11367=>860,11368=>641,11369=>697,11370=>598,11371=>652,11372=>523,11373=>774,
11374=>896,11375=>696,11376=>774,11377=>700,11378=>1099,11379=>950,11380=>586,11381=>628,11382=>508,11383=>704,
11385=>484,11386=>618,11387=>502,11388=>197,11389=>438,11390=>648,11391=>652,11800=>527,11810=>411,11811=>411,
11812=>411,11813=>411,11822=>522,19904=>807,19905=>807,19906=>807,19907=>807,19908=>807,19909=>807,19910=>807,
19911=>807,19912=>807,19913=>807,19914=>807,19915=>807,19916=>807,19917=>807,19918=>807,19919=>807,19920=>807,
19921=>807,19922=>807,19923=>807,19924=>807,19925=>807,19926=>807,19927=>807,19928=>807,19929=>807,19930=>807,
19931=>807,19932=>807,19933=>807,19934=>807,19935=>807,19936=>807,19937=>807,19938=>807,19939=>807,19940=>807,
19941=>807,19942=>807,19943=>807,19944=>807,19945=>807,19946=>807,19947=>807,19948=>807,19949=>807,19950=>807,
19951=>807,19952=>807,19953=>807,19954=>807,19955=>807,19956=>807,19957=>807,19958=>807,19959=>807,19960=>807,
19961=>807,19962=>807,19963=>807,19964=>807,19965=>807,19966=>807,19967=>807,42564=>648,42565=>536,42566=>392,
42567=>396,42572=>1265,42573=>1055,42576=>1110,42577=>924,42580=>1056,42581=>875,42582=>990,42583=>872,42594=>990,
42595=>846,42596=>986,42597=>823,42598=>1134,42599=>896,42600=>765,42601=>618,42602=>933,42603=>781,42604=>1266,
42605=>995,42606=>865,42634=>849,42635=>673,42636=>614,42637=>521,42644=>727,42645=>641,42760=>450,42761=>450,
42762=>450,42763=>450,42764=>450,42765=>450,42766=>450,42767=>450,42768=>450,42769=>450,42770=>450,42771=>450,
42772=>450,42773=>450,42774=>450,42779=>360,42780=>360,42781=>258,42782=>258,42783=>258,42786=>399,42787=>351,
42788=>486,42789=>486,42790=>753,42791=>641,42792=>928,42793=>771,42794=>626,42795=>501,42800=>502,42801=>536,
42802=>1214,42803=>946,42804=>1156,42805=>958,42806=>1120,42807=>947,42808=>971,42809=>830,42810=>971,42811=>830,
42812=>932,42813=>830,42814=>628,42815=>494,42822=>765,42823=>488,42824=>614,42825=>478,42826=>826,42827=>732,
42830=>1266,42831=>995,42832=>659,42833=>644,42834=>853,42835=>843,42838=>765,42839=>644,42852=>664,42853=>644,
42854=>664,42855=>644,42880=>573,42881=>308,42882=>753,42883=>641,42889=>360,42890=>356,42891=>410,42892=>275,
42893=>727,43003=>615,43004=>659,43005=>896,43006=>334,43007=>1192,61184=>194,61185=>218,61186=>240,61187=>249,
61188=>254,61189=>218,61190=>194,61191=>218,61192=>240,61193=>249,61194=>240,61195=>218,61196=>194,61197=>218,
61198=>240,61199=>249,61200=>240,61201=>218,61202=>194,61203=>218,61204=>254,61205=>249,61206=>240,61207=>218,
61208=>194,61209=>254,62917=>618,64256=>749,64257=>708,64258=>708,64259=>1024,64260=>1024,64261=>727,64262=>917,
64275=>1249,64276=>1245,64277=>1240,64278=>1245,64279=>1542,64285=>308,64286=>0,64287=>597,64288=>647,64289=>867,
64290=>801,64291=>889,64292=>867,64293=>844,64294=>889,64295=>889,64296=>878,64297=>754,64298=>854,64299=>854,
64300=>854,64301=>854,64302=>676,64303=>676,64304=>676,64305=>605,64306=>483,64307=>589,64308=>641,64309=>308,
64310=>442,64312=>651,64313=>420,64314=>584,64315=>584,64316=>611,64318=>698,64320=>447,64321=>696,64323=>646,
64324=>618,64326=>676,64327=>656,64328=>584,64329=>854,64330=>676,64331=>308,64332=>605,64333=>584,64334=>618,
64335=>585,65024=>0,65025=>0,65026=>0,65027=>0,65028=>0,65029=>0,65030=>0,65031=>0,65032=>0,
65033=>0,65034=>0,65035=>0,65036=>0,65037=>0,65038=>0,65039=>0,65056=>0,65057=>0,65058=>0,
65059=>0,65529=>0,65530=>0,65531=>0,65532=>0,65533=>1002);
$enc='';
$diff='';
$file='dejavusanscondensedbi.z';
$ctg='dejavusanscondensedbi.ctg.z';
$originalsize=543704;
// --- EOF --- | himan5050/hpbc | tcpdf/fonts/dejavusanscondensedbi.php | PHP | gpl-2.0 | 45,561 |
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* 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.
*
*/
#include "mutationofjb/widgets/imagewidget.h"
#include "graphics/managed_surface.h"
namespace MutationOfJB {
ImageWidget::ImageWidget(GuiScreen &gui, const Common::Rect &area, const Graphics::Surface &image) :
Widget(gui, area),
_image(image) {}
void ImageWidget::draw(Graphics::ManagedSurface &surface) {
surface.blitFrom(_image, Common::Point(_area.left, _area.top));
}
}
| alexbevi/scummvm | engines/mutationofjb/widgets/imagewidget.cpp | C++ | gpl-2.0 | 1,331 |
/*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ObjectMgr.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "zulgurub.h"
enum Yells
{
SAY_AGGRO = 0,
EMOTE_ZANZIL_ZOMBIES = 1, // ID - 96319 Zanzil's Resurrection Elixir
SAY_ZANZIL_ZOMBIES = 2, // ID - 96319 Zanzil's Resurrection Elixir
EMOTE_ZANZIL_GRAVEYARD_GAS = 3, // ID - 96338 Zanzil's Graveyard Gas
SAY_ZANZIL_GRAVEYARD_GAS = 4, // ID - 96338 Zanzil's Graveyard Gas
EMOTE_ZANZIL_BERSEKER = 5, // ID - 96316 Zanzil's Resurrection Elixir
SAY_ZANZIL_BERSEKER = 6, // ID - 96316 Zanzil's Resurrection Elixir
SAY_PLAYER_KILL = 7,
SAY_DEATH = 8
};
enum Spells
{
};
enum Events
{
};
class boss_zanzil : public CreatureScript
{
public:
boss_zanzil() : CreatureScript("boss_zanzil") { }
struct boss_zanzilAI : public BossAI
{
boss_zanzilAI(Creature* creature) : BossAI(creature, DATA_ZANZIL) { }
void Reset()
{
_Reset();
}
void EnterCombat(Unit* /*who*/)
{
_EnterCombat();
Talk(SAY_AGGRO);
}
void JustDied(Unit* /*killer*/)
{
_JustDied();
Talk(SAY_DEATH);
}
void KilledUnit(Unit* victim)
{
if (victim->GetTypeId() == TYPEID_PLAYER)
Talk(SAY_PLAYER_KILL);
}
void UpdateAI(uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
/*
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
default:
break;
}
}
*/
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const
{
return GetZulGurubAI<boss_zanzilAI>(creature);
}
};
void AddSC_boss_zanzil()
{
new boss_zanzil();
}
| heros/multi_realm_cell | src/src_cata/server/scripts/EasternKingdoms/ZulGurub/boss_zanzil.cpp | C++ | gpl-2.0 | 3,051 |
<?php
/**
* @package Joomla.Site
* @subpackage Layout
*
* @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('JPATH_BASE') or die;
extract($displayData);
/**
* Layout variables
* ------------------
* @param string $selector Unique DOM identifier for the modal. CSS id without #
* @param array $params Modal parameters. Default supported parameters:
* - title string The modal title
* - backdrop mixed A boolean select if a modal-backdrop element should be included (default = true)
* The string 'static' includes a backdrop which doesn't close the modal on click.
* - keyboard boolean Closes the modal when escape key is pressed (default = true)
* - closeButton boolean Display modal close button (default = true)
* - animation boolean Fade in from the top of the page (default = true)
* - footer string Optional markup for the modal footer
* - url string URL of a resource to be inserted as an <iframe> inside the modal body
* - height string height of the <iframe> containing the remote resource
* - width string width of the <iframe> containing the remote resource
* - bodyHeight int Optional height of the modal body in viewport units (vh)
* - modalWidth int Optional width of the modal in viewport units (vh)
* @param string $body Markup for the modal body. Appended after the <iframe> if the URL option is set
*
*/
$bodyClass = 'modal-body';
$bodyHeight = isset($params['bodyHeight']) ? round((int) $params['bodyHeight'], -1) : '';
if ($bodyHeight && $bodyHeight >= 20 && $bodyHeight < 90)
{
$bodyClass .= ' jviewport-height' . $bodyHeight;
}
?>
<div class="<?php echo $bodyClass; ?>">
<?php echo $body; ?>
</div>
| ciar4n/joomla-cms | layouts/joomla/modal/body.php | PHP | gpl-2.0 | 2,238 |
<?php
namespace Guzzle\Tests\Http;
use Guzzle\Http\QueryString;
use Guzzle\Http\Url;
/**
* @covers Guzzle\Http\Url
*/
class UrlTest extends \Guzzle\Tests\GuzzleTestCase
{
public function testEmptyUrl()
{
$url = Url::factory('');
$this->assertEquals('', (string) $url);
}
public function testPortIsDeterminedFromScheme()
{
$this->assertEquals(80, Url::factory('http://www.test.com/')->getPort());
$this->assertEquals(443, Url::factory('https://www.test.com/')->getPort());
$this->assertEquals(null, Url::factory('ftp://www.test.com/')->getPort());
$this->assertEquals(8192, Url::factory('http://www.test.com:8192/')->getPort());
}
public function testCloneCreatesNewInternalObjects()
{
$u1 = Url::factory('http://www.test.com/');
$u2 = clone $u1;
$this->assertNotSame($u1->getQuery(), $u2->getQuery());
}
public function testValidatesUrlPartsInFactory()
{
$url = Url::factory('/index.php');
$this->assertEquals('/index.php', (string) $url);
$this->assertFalse($url->isAbsolute());
$url = 'http://michael:test@test.com:80/path/123?q=abc#test';
$u = Url::factory($url);
$this->assertEquals('http://michael:test@test.com/path/123?q=abc#test', (string) $u);
$this->assertTrue($u->isAbsolute());
}
public function testAllowsFalsyUrlParts()
{
$url = Url::factory('http://0:50/0?0#0');
$this->assertSame('0', $url->getHost());
$this->assertEquals(50, $url->getPort());
$this->assertSame('/0', $url->getPath());
$this->assertEquals('0=', (string) $url->getQuery());
$this->assertSame('0', $url->getFragment());
$this->assertEquals('http://0:50/0?0=#0', (string) $url);
$url = Url::factory('');
$this->assertSame('', (string) $url);
$url = Url::factory('0');
$this->assertSame('0', (string) $url);
}
public function testBuildsRelativeUrlsWithFalsyParts()
{
$url = Url::buildUrl(array(
'host' => '0',
'path' => '0',
));
$this->assertSame('//0/0', $url);
$url = Url::buildUrl(array(
'path' => '0',
));
$this->assertSame('0', $url);
}
public function testUrlStoresParts()
{
$url = Url::factory('http://test:pass@www.test.com:8081/path/path2/?a=1&b=2#fragment');
$this->assertEquals('http', $url->getScheme());
$this->assertEquals('test', $url->getUsername());
$this->assertEquals('pass', $url->getPassword());
$this->assertEquals('www.test.com', $url->getHost());
$this->assertEquals(8081, $url->getPort());
$this->assertEquals('/path/path2/', $url->getPath());
$this->assertEquals('fragment', $url->getFragment());
$this->assertEquals('a=1&b=2', (string) $url->getQuery());
$this->assertEquals(array(
'fragment' => 'fragment',
'host' => 'www.test.com',
'pass' => 'pass',
'path' => '/path/path2/',
'port' => 8081,
'query' => 'a=1&b=2',
'scheme' => 'http',
'user' => 'test'
), $url->getParts());
}
public function testHandlesPathsCorrectly()
{
$url = Url::factory('http://www.test.com');
$this->assertEquals('', $url->getPath());
$url->setPath('test');
$this->assertEquals('test', $url->getPath());
$url->setPath('/test/123/abc');
$this->assertEquals(array('test', '123', 'abc'), $url->getPathSegments());
$parts = parse_url('http://www.test.com/test');
$parts['path'] = '';
$this->assertEquals('http://www.test.com', Url::buildUrl($parts));
$parts['path'] = 'test';
$this->assertEquals('http://www.test.com/test', Url::buildUrl($parts));
}
public function testAddsQueryStringIfPresent()
{
$this->assertEquals('?foo=bar', Url::buildUrl(array(
'query' => 'foo=bar'
)));
}
public function testAddsToPath()
{
// Does nothing here
$this->assertEquals('http://e.com/base?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath(false));
$this->assertEquals('http://e.com/base?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath(''));
$this->assertEquals('http://e.com/base?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath('/'));
$this->assertEquals('http://e.com/base/relative?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath('relative'));
$this->assertEquals('http://e.com/base/relative?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath('/relative'));
}
/**
* URL combination data provider
*
* @return array
*/
public function urlCombineDataProvider()
{
return array(
array('http://www.example.com/', 'http://www.example.com/', 'http://www.example.com/'),
array('http://www.example.com/path', '/absolute', 'http://www.example.com/absolute'),
array('http://www.example.com/path', '/absolute?q=2', 'http://www.example.com/absolute?q=2'),
array('http://www.example.com/path', 'more', 'http://www.example.com/path/more'),
array('http://www.example.com/path', 'more?q=1', 'http://www.example.com/path/more?q=1'),
array('http://www.example.com/', '?q=1', 'http://www.example.com/?q=1'),
array('http://www.example.com/path', 'http://test.com', 'http://test.com'),
array('http://www.example.com:8080/path', 'http://test.com', 'http://test.com'),
array('http://www.example.com:8080/path', '?q=2#abc', 'http://www.example.com:8080/path?q=2#abc'),
array('http://u:a@www.example.com/path', 'test', 'http://u:a@www.example.com/path/test'),
array('http://www.example.com/path', 'http://u:a@www.example.com/', 'http://u:a@www.example.com/'),
array('/path?q=2', 'http://www.test.com/', 'http://www.test.com/path?q=2'),
array('http://api.flickr.com/services/', 'http://www.flickr.com/services/oauth/access_token', 'http://www.flickr.com/services/oauth/access_token')
);
}
/**
* @dataProvider urlCombineDataProvider
*/
public function testCombinesUrls($a, $b, $c)
{
$this->assertEquals($c, (string) Url::factory($a)->combine($b));
}
public function testHasGettersAndSetters()
{
$url = Url::factory('http://www.test.com/');
$this->assertEquals('example.com', $url->setHost('example.com')->getHost());
$this->assertEquals('8080', $url->setPort(8080)->getPort());
$this->assertEquals('/foo/bar', $url->setPath(array('foo', 'bar'))->getPath());
$this->assertEquals('a', $url->setPassword('a')->getPassword());
$this->assertEquals('b', $url->setUsername('b')->getUsername());
$this->assertEquals('abc', $url->setFragment('abc')->getFragment());
$this->assertEquals('https', $url->setScheme('https')->getScheme());
$this->assertEquals('a=123', (string) $url->setQuery('a=123')->getQuery());
$this->assertEquals('https://b:a@example.com:8080/foo/bar?a=123#abc', (string) $url);
$this->assertEquals('b=boo', (string) $url->setQuery(new QueryString(array(
'b' => 'boo'
)))->getQuery());
$this->assertEquals('https://b:a@example.com:8080/foo/bar?b=boo#abc', (string) $url);
}
public function testSetQueryAcceptsArray()
{
$url = Url::factory('http://www.test.com');
$url->setQuery(array('a' => 'b'));
$this->assertEquals('http://www.test.com?a=b', (string) $url);
}
public function urlProvider()
{
return array(
array('/foo/..', '/'),
array('//foo//..', '/'),
array('/foo/../..', '/'),
array('/foo/../.', '/'),
array('/./foo/..', '/'),
array('/./foo', '/foo'),
array('/./foo/', '/foo/'),
array('/./foo/bar/baz/pho/../..', '/foo/bar'),
array('*', '*'),
array('/foo', '/foo'),
array('/abc/123/../foo/', '/abc/foo/'),
array('/a/b/c/./../../g', '/a/g'),
array('/b/c/./../../g', '/g'),
array('/b/c/./../../g', '/g'),
array('/c/./../../g', '/g'),
array('/./../../g', '/g'),
);
}
/**
* @dataProvider urlProvider
*/
public function testNormalizesPaths($path, $result)
{
$url = Url::factory('http://www.example.com/');
$url->setPath($path)->normalizePath();
$this->assertEquals($result, $url->getPath());
}
public function testSettingHostWithPortModifiesPort()
{
$url = Url::factory('http://www.example.com');
$url->setHost('foo:8983');
$this->assertEquals('foo', $url->getHost());
$this->assertEquals(8983, $url->getPort());
}
/**
* @expectedException \Guzzle\Common\Exception\InvalidArgumentException
*/
public function testValidatesUrlCanBeParsed()
{
Url::factory('foo:////');
}
public function testConvertsSpecialCharsInPathWhenCastingToString()
{
$url = Url::factory('http://foo.com/baz bar?a=b');
$url->addPath('?');
$this->assertEquals('http://foo.com/baz%20bar/%3F?a=b', (string) $url);
}
}
| dat0106/wordpress | wp-content/plugins/wp-statistics/vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/UrlTest.php | PHP | gpl-2.0 | 9,506 |
<?php
/*
* LibreNMS
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*
* @package LibreNMS
* @subpackage webui
* @link http://librenms.org
* @copyright 2017 LibreNMS
* @author LibreNMS Contributors
*/
$graph_type = 'sensor_temperature';
$unit = '°C';
$class = 'temperature';
require 'pages/health/sensors.inc.php';
| pheinrichs/librenms | html/pages/health/temperature.inc.php | PHP | gpl-3.0 | 648 |
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import os
from powerline.bindings.vim import buffer_name
def commandt(matcher_info):
name = buffer_name(matcher_info)
return name and os.path.basename(name) == b'GoToFile'
| gorczynski/dotfiles | vim/bundle/powerline/powerline/matchers/vim/plugin/commandt.py | Python | gpl-3.0 | 293 |
/*****************************************************************************
*
* PROJECT: Multi Theft Auto v1.0
* LICENSE: See LICENSE in the top level directory
* FILE: core/CCore.cpp
* PURPOSE: Base core class
* DEVELOPERS: Cecill Etheredge <ijsf@gmx.net>
* Chris McArthur <>
* Christian Myhre Lundheim <>
* Derek Abdine <>
* Ed Lyons <eai@opencoding.net>
* Jax <>
*
* Multi Theft Auto is available from http://www.multitheftauto.com/
*
*****************************************************************************/
#include "StdInc.h"
#include <game/CGame.h>
#include <Accctrl.h>
#include <Aclapi.h>
#include "Userenv.h" // This will enable SharedUtil::ExpandEnvString
#define ALLOC_STATS_MODULE_NAME "core"
#include "SharedUtil.hpp"
#include <clocale>
#include "CTimingCheckpoints.hpp"
#include "CModelCacheManager.h"
using SharedUtil::CalcMTASAPath;
using namespace std;
static float fTest = 1;
extern CCore* g_pCore;
bool g_bBoundsChecker = false;
BOOL AC_RestrictAccess( VOID )
{
EXPLICIT_ACCESS NewAccess;
PACL pTempDacl;
HANDLE hProcess;
DWORD dwFlags;
DWORD dwErr;
///////////////////////////////////////////////
// Get the HANDLE to the current process.
hProcess = GetCurrentProcess();
///////////////////////////////////////////////
// Setup which accesses we want to deny.
dwFlags = GENERIC_WRITE|PROCESS_ALL_ACCESS|WRITE_DAC|DELETE|WRITE_OWNER|READ_CONTROL;
///////////////////////////////////////////////
// Build our EXPLICIT_ACCESS structure.
BuildExplicitAccessWithName( &NewAccess, "CURRENT_USER", dwFlags, DENY_ACCESS, NO_INHERITANCE );
///////////////////////////////////////////////
// Create our Discretionary Access Control List.
if ( ERROR_SUCCESS != (dwErr = SetEntriesInAcl( 1, &NewAccess, NULL, &pTempDacl )) )
{
#ifdef DEBUG
// pConsole->Con_Printf("Error at SetEntriesInAcl(): %i", dwErr);
#endif
return FALSE;
}
////////////////////////////////////////////////
// Set the new DACL to our current process.
if ( ERROR_SUCCESS != (dwErr = SetSecurityInfo( hProcess, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, pTempDacl, NULL )) )
{
#ifdef DEBUG
// pConsole->Con_Printf("Error at SetSecurityInfo(): %i", dwErr);
#endif
return FALSE;
}
////////////////////////////////////////////////
// Free the DACL (see msdn on SetEntriesInAcl)
LocalFree( pTempDacl );
CloseHandle( hProcess );
return TRUE;
}
template<> CCore * CSingleton< CCore >::m_pSingleton = NULL;
CCore::CCore ( void )
{
// Initialize the global pointer
g_pCore = this;
#if !defined(MTA_DEBUG) && !defined(MTA_ALLOW_DEBUG)
AC_RestrictAccess ();
#endif
m_pConfigFile = NULL;
// Set our locale to the C locale, except for character handling which is the system's default
std::setlocale(LC_ALL,"C");
std::setlocale(LC_CTYPE,"");
// check LC_COLLATE is the old-time raw ASCII sort order
assert ( strcoll( "a", "B" ) > 0 );
// Parse the command line
const char* pszNoValOptions[] =
{
"window",
NULL
};
ParseCommandLine ( m_CommandLineOptions, m_szCommandLineArgs, pszNoValOptions );
// Load our settings and localization as early as possible
CreateXML ( );
g_pLocalization = new CLocalization;
// Create a logger instance.
m_pConsoleLogger = new CConsoleLogger ( );
// Create interaction objects.
m_pCommands = new CCommands;
m_pConnectManager = new CConnectManager;
// Create the GUI manager and the graphics lib wrapper
m_pLocalGUI = new CLocalGUI;
m_pGraphics = new CGraphics ( m_pLocalGUI );
g_pGraphics = m_pGraphics;
m_pGUI = NULL;
m_pWebCore = NULL;
// Create the mod manager
m_pModManager = new CModManager;
CCrashDumpWriter::SetHandlers();
m_pfnMessageProcessor = NULL;
m_pMessageBox = NULL;
m_bFirstFrame = true;
m_bIsOfflineMod = false;
m_bQuitOnPulse = false;
m_bDestroyMessageBox = false;
m_bCursorToggleControls = false;
m_bLastFocused = true;
m_bWaitToSetNick = false;
m_DiagnosticDebug = EDiagnosticDebug::NONE;
// Create our Direct3DData handler.
m_pDirect3DData = new CDirect3DData;
WriteDebugEvent ( "CCore::CCore" );
m_pKeyBinds = new CKeyBinds ( this );
m_pMouseControl = new CMouseControl();
// Create our hook objects.
//m_pFileSystemHook = new CFileSystemHook ( );
m_pDirect3DHookManager = new CDirect3DHookManager ( );
m_pDirectInputHookManager = new CDirectInputHookManager ( );
m_pMessageLoopHook = new CMessageLoopHook ( );
m_pSetCursorPosHook = new CSetCursorPosHook ( );
m_pTCPManager = new CTCPManager ( );
// Register internal commands.
RegisterCommands ( );
// Setup our hooks.
ApplyHooks ( );
// Reset the screenshot flag
bScreenShot = false;
//Create our current server and set the update time to zero
m_pCurrentServer = new CXfireServerInfo();
m_tXfireUpdate = 0;
// No initial fps limit
m_bDoneFrameRateLimit = false;
m_uiFrameRateLimit = 0;
m_uiServerFrameRateLimit = 0;
m_uiNewNickWaitFrames = 0;
m_iUnminimizeFrameCounter = 0;
m_bDidRecreateRenderTargets = false;
m_fMinStreamingMemory = 0;
m_fMaxStreamingMemory = 0;
m_bGettingIdleCallsFromMultiplayer = false;
m_bWindowsTimerEnabled = false;
}
CCore::~CCore ( void )
{
WriteDebugEvent ( "CCore::~CCore" );
// Delete the mod manager
delete m_pModManager;
SAFE_DELETE ( m_pMessageBox );
// Destroy early subsystems
m_bModulesLoaded = false;
DestroyNetwork ();
DestroyMultiplayer ();
DestroyGame ();
// Remove global events
g_pCore->m_pGUI->ClearInputHandlers( INPUT_CORE );
// Remove input hook
CMessageLoopHook::GetSingleton ( ).RemoveHook ( );
// Store core variables to cvars
CVARS_SET ( "console_pos", m_pLocalGUI->GetConsole ()->GetPosition () );
CVARS_SET ( "console_size", m_pLocalGUI->GetConsole ()->GetSize () );
// Delete interaction objects.
delete m_pCommands;
delete m_pConnectManager;
delete m_pDirect3DData;
// Delete hooks.
delete m_pSetCursorPosHook;
//delete m_pFileSystemHook;
delete m_pDirect3DHookManager;
delete m_pDirectInputHookManager;
delete m_pTCPManager;
// Delete the GUI manager
delete m_pLocalGUI;
delete m_pGraphics;
// Delete the web
delete m_pWebCore;
// Delete lazy subsystems
DestroyGUI ();
DestroyXML ();
// Delete keybinds
delete m_pKeyBinds;
// Delete Mouse Control
delete m_pMouseControl;
// Delete the logger
delete m_pConsoleLogger;
//Delete the Current Server
delete m_pCurrentServer;
// Delete last so calls to GetHookedWindowHandle do not crash
delete m_pMessageLoopHook;
}
eCoreVersion CCore::GetVersion ( void )
{
return MTACORE_20;
}
CConsoleInterface* CCore::GetConsole ( void )
{
return m_pLocalGUI->GetConsole ();
}
CCommandsInterface* CCore::GetCommands ( void )
{
return m_pCommands;
}
CGame* CCore::GetGame ( void )
{
return m_pGame;
}
CGraphicsInterface* CCore::GetGraphics ( void )
{
return m_pGraphics;
}
CModManagerInterface* CCore::GetModManager ( void )
{
return m_pModManager;
}
CMultiplayer* CCore::GetMultiplayer ( void )
{
return m_pMultiplayer;
}
CXMLNode* CCore::GetConfig ( void )
{
if ( !m_pConfigFile )
return NULL;
CXMLNode* pRoot = m_pConfigFile->GetRootNode ();
if ( !pRoot )
pRoot = m_pConfigFile->CreateRootNode ( CONFIG_ROOT );
return pRoot;
}
CGUI* CCore::GetGUI ( void )
{
return m_pGUI;
}
CNet* CCore::GetNetwork ( void )
{
return m_pNet;
}
CKeyBindsInterface* CCore::GetKeyBinds ( void )
{
return m_pKeyBinds;
}
CLocalGUI* CCore::GetLocalGUI ( void )
{
return m_pLocalGUI;
}
void CCore::SaveConfig ( void )
{
if ( m_pConfigFile )
{
CXMLNode* pBindsNode = GetConfig ()->FindSubNode ( CONFIG_NODE_KEYBINDS );
if ( !pBindsNode )
pBindsNode = GetConfig ()->CreateSubNode ( CONFIG_NODE_KEYBINDS );
m_pKeyBinds->SaveToXML ( pBindsNode );
GetVersionUpdater ()->SaveConfigToXML ();
GetServerCache ()->SaveServerCache ();
m_pConfigFile->Write ();
}
}
void CCore::ChatEcho ( const char* szText, bool bColorCoded )
{
CChat* pChat = m_pLocalGUI->GetChat ();
if ( pChat )
{
CColor color ( 255, 255, 255, 255 );
pChat->SetTextColor ( color );
}
// Echo it to the console and chat
m_pLocalGUI->EchoChat ( szText, bColorCoded );
if ( bColorCoded )
{
m_pLocalGUI->EchoConsole ( RemoveColorCodes( szText ) );
}
else
m_pLocalGUI->EchoConsole ( szText );
}
void CCore::DebugEcho ( const char* szText )
{
CDebugView * pDebugView = m_pLocalGUI->GetDebugView ();
if ( pDebugView )
{
CColor color ( 255, 255, 255, 255 );
pDebugView->SetTextColor ( color );
}
m_pLocalGUI->EchoDebug ( szText );
}
void CCore::DebugPrintf ( const char* szFormat, ... )
{
// Convert it to a string buffer
char szBuffer [1024];
va_list ap;
va_start ( ap, szFormat );
VSNPRINTF ( szBuffer, 1024, szFormat, ap );
va_end ( ap );
DebugEcho ( szBuffer );
}
void CCore::SetDebugVisible ( bool bVisible )
{
if ( m_pLocalGUI )
{
m_pLocalGUI->SetDebugViewVisible ( bVisible );
}
}
bool CCore::IsDebugVisible ( void )
{
if ( m_pLocalGUI )
return m_pLocalGUI->IsDebugViewVisible ();
else
return false;
}
void CCore::DebugEchoColor ( const char* szText, unsigned char R, unsigned char G, unsigned char B )
{
// Set the color
CDebugView * pDebugView = m_pLocalGUI->GetDebugView ();
if ( pDebugView )
{
CColor color ( R, G, B, 255 );
pDebugView->SetTextColor ( color );
}
m_pLocalGUI->EchoDebug ( szText );
}
void CCore::DebugPrintfColor ( const char* szFormat, unsigned char R, unsigned char G, unsigned char B, ... )
{
// Set the color
if ( szFormat )
{
// Convert it to a string buffer
char szBuffer [1024];
va_list ap;
va_start ( ap, B );
VSNPRINTF ( szBuffer, 1024, szFormat, ap );
va_end ( ap );
// Echo it to the console and chat
DebugEchoColor ( szBuffer, R, G, B );
}
}
void CCore::DebugClear ( void )
{
CDebugView * pDebugView = m_pLocalGUI->GetDebugView ();
if ( pDebugView )
{
pDebugView->Clear();
}
}
void CCore::ChatEchoColor ( const char* szText, unsigned char R, unsigned char G, unsigned char B, bool bColorCoded )
{
// Set the color
CChat* pChat = m_pLocalGUI->GetChat ();
if ( pChat )
{
CColor color ( R, G, B, 255 );
pChat->SetTextColor ( color );
}
// Echo it to the console and chat
m_pLocalGUI->EchoChat ( szText, bColorCoded );
if ( bColorCoded )
{
m_pLocalGUI->EchoConsole ( RemoveColorCodes( szText ) );
}
else
m_pLocalGUI->EchoConsole ( szText );
}
void CCore::ChatPrintf ( const char* szFormat, bool bColorCoded, ... )
{
// Convert it to a string buffer
char szBuffer [1024];
va_list ap;
va_start ( ap, bColorCoded );
VSNPRINTF ( szBuffer, 1024, szFormat, ap );
va_end ( ap );
// Echo it to the console and chat
ChatEcho ( szBuffer, bColorCoded );
}
void CCore::ChatPrintfColor ( const char* szFormat, bool bColorCoded, unsigned char R, unsigned char G, unsigned char B, ... )
{
// Set the color
if ( szFormat )
{
if ( m_pLocalGUI )
{
// Convert it to a string buffer
char szBuffer [1024];
va_list ap;
va_start ( ap, B );
VSNPRINTF ( szBuffer, 1024, szFormat, ap );
va_end ( ap );
// Echo it to the console and chat
ChatEchoColor ( szBuffer, R, G, B, bColorCoded );
}
}
}
void CCore::SetChatVisible ( bool bVisible )
{
if ( m_pLocalGUI )
{
m_pLocalGUI->SetChatBoxVisible ( bVisible );
}
}
bool CCore::IsChatVisible ( void )
{
if ( m_pLocalGUI )
{
return m_pLocalGUI->IsChatBoxVisible ();
}
return false;
}
void CCore::TakeScreenShot ( void )
{
bScreenShot = true;
}
void CCore::EnableChatInput ( char* szCommand, DWORD dwColor )
{
if ( m_pLocalGUI )
{
if ( m_pGame->GetSystemState () == 9 /* GS_PLAYING_GAME */ &&
m_pModManager->GetCurrentMod () != NULL &&
!IsOfflineMod () &&
!m_pGame->IsAtMenu () &&
!m_pLocalGUI->GetMainMenu ()->IsVisible () &&
!m_pLocalGUI->GetConsole ()->IsVisible () &&
!m_pLocalGUI->IsChatBoxInputEnabled () )
{
CChat* pChat = m_pLocalGUI->GetChat ();
pChat->SetCommand ( szCommand );
m_pLocalGUI->SetChatBoxInputEnabled ( true );
}
}
}
bool CCore::IsChatInputEnabled ( void )
{
if ( m_pLocalGUI )
{
return ( m_pLocalGUI->IsChatBoxInputEnabled () );
}
return false;
}
bool CCore::IsSettingsVisible ( void )
{
if ( m_pLocalGUI )
{
return ( m_pLocalGUI->GetMainMenu ()->GetSettingsWindow ()->IsVisible () );
}
return false;
}
bool CCore::IsMenuVisible ( void )
{
if ( m_pLocalGUI )
{
return ( m_pLocalGUI->GetMainMenu ()->IsVisible () );
}
return false;
}
bool CCore::IsCursorForcedVisible ( void )
{
if ( m_pLocalGUI )
{
return ( m_pLocalGUI->IsCursorForcedVisible () );
}
return false;
}
void CCore::ApplyConsoleSettings ( void )
{
CVector2D vec;
CConsole * pConsole = m_pLocalGUI->GetConsole ();
CVARS_GET ( "console_pos", vec );
pConsole->SetPosition ( vec );
CVARS_GET ( "console_size", vec );
pConsole->SetSize ( vec );
}
void CCore::ApplyGameSettings ( void )
{
bool bval;
int iVal;
CControllerConfigManager * pController = m_pGame->GetControllerConfigManager ();
CVARS_GET ( "invert_mouse", bval ); pController->SetMouseInverted ( bval );
CVARS_GET ( "fly_with_mouse", bval ); pController->SetFlyWithMouse ( bval );
CVARS_GET ( "steer_with_mouse", bval ); pController->SetSteerWithMouse ( bval );
CVARS_GET ( "classic_controls", bval ); pController->SetClassicControls ( bval );
CVARS_GET ( "volumetric_shadows", bval ); m_pGame->GetSettings ()->SetVolumetricShadowsEnabled ( bval );
CVARS_GET ( "aspect_ratio", iVal ); m_pGame->GetSettings ()->SetAspectRatio ( (eAspectRatio)iVal, CVARS_GET_VALUE < bool > ( "hud_match_aspect_ratio" ) );
CVARS_GET ( "grass", bval ); m_pGame->GetSettings ()->SetGrassEnabled ( bval );
CVARS_GET ( "heat_haze", bval ); m_pMultiplayer->SetHeatHazeEnabled ( bval );
CVARS_GET ( "fast_clothes_loading", iVal ); m_pMultiplayer->SetFastClothesLoading ( (CMultiplayer::EFastClothesLoading)iVal );
CVARS_GET ( "tyre_smoke_enabled", bval ); m_pMultiplayer->SetTyreSmokeEnabled ( bval );
pController->SetVerticalAimSensitivityRawValue( CVARS_GET_VALUE < float > ( "vertical_aim_sensitivity" ) );
}
void CCore::ApplyCommunityState ( void )
{
bool bLoggedIn = g_pCore->GetCommunity()->IsLoggedIn();
if ( bLoggedIn )
m_pLocalGUI->GetMainMenu ()->GetSettingsWindow()->OnLoginStateChange ( true );
}
void CCore::SetConnected ( bool bConnected )
{
m_pLocalGUI->GetMainMenu ( )->SetIsIngame ( bConnected );
UpdateIsWindowMinimized (); // Force update of stuff
}
bool CCore::IsConnected ( void )
{
return m_pLocalGUI->GetMainMenu ( )->GetIsIngame ();
}
bool CCore::Reconnect ( const char* szHost, unsigned short usPort, const char* szPassword, bool bSave, bool bForceInternalHTTPServer )
{
return m_pConnectManager->Reconnect ( szHost, usPort, szPassword, bSave, bForceInternalHTTPServer );
}
bool CCore::ShouldUseInternalHTTPServer( void )
{
return m_pConnectManager->ShouldUseInternalHTTPServer();
}
void CCore::SetOfflineMod ( bool bOffline )
{
m_bIsOfflineMod = bOffline;
}
const char* CCore::GetModInstallRoot ( const char* szModName )
{
m_strModInstallRoot = CalcMTASAPath ( PathJoin ( "mods", szModName ) );
return m_strModInstallRoot;
}
void CCore::ForceCursorVisible ( bool bVisible, bool bToggleControls )
{
m_bCursorToggleControls = bToggleControls;
m_pLocalGUI->ForceCursorVisible ( bVisible );
}
void CCore::SetMessageProcessor ( pfnProcessMessage pfnMessageProcessor )
{
m_pfnMessageProcessor = pfnMessageProcessor;
}
void CCore::ShowMessageBox ( const char* szTitle, const char* szText, unsigned int uiFlags, GUI_CALLBACK * ResponseHandler )
{
if ( m_pMessageBox )
delete m_pMessageBox;
// Create the message box
m_pMessageBox = m_pGUI->CreateMessageBox ( szTitle, szText, uiFlags );
if ( ResponseHandler ) m_pMessageBox->SetClickHandler ( *ResponseHandler );
// Make sure it doesn't auto-destroy, or we'll crash if the msgbox had buttons and the user clicks OK
m_pMessageBox->SetAutoDestroy ( false );
}
void CCore::RemoveMessageBox ( bool bNextFrame )
{
if ( bNextFrame )
{
m_bDestroyMessageBox = true;
}
else
{
if ( m_pMessageBox )
{
delete m_pMessageBox;
m_pMessageBox = NULL;
}
}
}
//
// Show message box with possibility of on-line help
//
void CCore::ShowErrorMessageBox( const SString& strTitle, SString strMessage, const SString& strTroubleLink )
{
if ( strTroubleLink.empty() )
{
CCore::GetSingleton ().ShowMessageBox ( strTitle, strMessage, MB_BUTTON_OK | MB_ICON_ERROR );
}
else
{
strMessage += "\n\n";
strMessage += _("Do you want to see some on-line help about this problem ?");
CQuestionBox* pQuestionBox = CCore::GetSingleton ().GetLocalGUI ()->GetMainMenu ()->GetQuestionWindow ();
pQuestionBox->Reset ();
pQuestionBox->SetTitle ( strTitle );
pQuestionBox->SetMessage ( strMessage );
pQuestionBox->SetButton ( 0, _("No") );
pQuestionBox->SetButton ( 1, _("Yes") );
pQuestionBox->SetCallback ( CCore::ErrorMessageBoxCallBack, new SString( strTroubleLink ) );
pQuestionBox->Show ();
}
}
//
// Show message box with possibility of on-line help
// + with net error code appended to message and trouble link
//
void CCore::ShowNetErrorMessageBox( const SString& strTitle, SString strMessage, SString strTroubleLink, bool bLinkRequiresErrorCode )
{
uint uiErrorCode = CCore::GetSingleton ().GetNetwork ()->GetExtendedErrorCode ();
if ( uiErrorCode != 0 )
{
// Do anti-virus check soon
SetApplicationSettingInt( "noav-user-says-skip", 1 );
strMessage += SString ( " \nCode: %08X", uiErrorCode );
if ( !strTroubleLink.empty() )
strTroubleLink += SString ( "&neterrorcode=%08X", uiErrorCode );
}
else
if ( bLinkRequiresErrorCode )
strTroubleLink = ""; // No link if no error code
AddReportLog( 7100, SString( "Core - NetError (%s) (%s)", *strTitle, *strMessage ) );
ShowErrorMessageBox( strTitle, strMessage, strTroubleLink );
}
//
// Callback used in CCore::ShowErrorMessageBox
//
void CCore::ErrorMessageBoxCallBack( void* pData, uint uiButton )
{
CCore::GetSingleton ().GetLocalGUI ()->GetMainMenu ()->GetQuestionWindow ()->Reset ();
SString* pstrTroubleLink = (SString*)pData;
if ( uiButton == 1 )
{
uint uiErrorCode = (uint)pData;
BrowseToSolution ( *pstrTroubleLink, EXIT_GAME_FIRST );
}
delete pstrTroubleLink;
}
//
// Check for disk space problems
// Returns false if low disk space, and dialog is being shown
//
bool CCore::CheckDiskSpace( uint uiResourcesPathMinMB, uint uiDataPathMinMB )
{
SString strDriveWithNoSpace = GetDriveNameWithNotEnoughSpace( uiResourcesPathMinMB, uiDataPathMinMB );
if ( !strDriveWithNoSpace.empty() )
{
SString strMessage( _("MTA:SA cannot continue because drive %s does not have enough space."), *strDriveWithNoSpace );
SString strTroubleLink( SString( "low-disk-space&drive=%s", *strDriveWithNoSpace.Left( 1 ) ) );
g_pCore->ShowErrorMessageBox ( _("Fatal error")+_E("CC43"), strMessage, strTroubleLink );
return false;
}
return true;
}
HWND CCore::GetHookedWindow ( void )
{
return CMessageLoopHook::GetSingleton ().GetHookedWindowHandle ();
}
void CCore::HideMainMenu ( void )
{
m_pLocalGUI->GetMainMenu ()->SetVisible ( false );
}
void CCore::HideQuickConnect ( void )
{
m_pLocalGUI->GetMainMenu ()->GetQuickConnectWindow()->SetVisible( false );
}
void CCore::ShowServerInfo ( unsigned int WindowType )
{
RemoveMessageBox ();
CServerInfo::GetSingletonPtr()->Show( (eWindowType)WindowType );
}
void CCore::ApplyHooks ( )
{
WriteDebugEvent ( "CCore::ApplyHooks" );
// Create our hooks.
m_pDirectInputHookManager->ApplyHook ( );
//m_pDirect3DHookManager->ApplyHook ( );
//m_pFileSystemHook->ApplyHook ( );
m_pSetCursorPosHook->ApplyHook ( );
// Redirect basic files.
//m_pFileSystemHook->RedirectFile ( "main.scm", "../../mta/gtafiles/main.scm" );
}
bool UsingAltD3DSetup()
{
static bool bAltStartup = GetApplicationSettingInt( "nvhacks", "optimus-alt-startup" ) ? true : false;
return bAltStartup;
}
void CCore::ApplyHooks2 ( )
{
WriteDebugEvent ( "CCore::ApplyHooks2" );
// Try this one a little later
if ( !UsingAltD3DSetup() )
m_pDirect3DHookManager->ApplyHook ( );
else
{
// Done a little later to get past the loading time required to decrypt the gta
// executable into memory...
if ( !CCore::GetSingleton ( ).AreModulesLoaded ( ) )
{
CCore::GetSingleton ( ).SetModulesLoaded ( true );
CCore::GetSingleton ( ).CreateNetwork ( );
CCore::GetSingleton ( ).CreateGame ( );
CCore::GetSingleton ( ).CreateMultiplayer ( );
CCore::GetSingleton ( ).CreateXML ( );
CCore::GetSingleton ( ).CreateGUI ( );
}
}
}
void CCore::ApplyHooks3( bool bEnable )
{
if ( bEnable )
CDirect3DHook9::GetSingletonPtr()->ApplyHook();
else
CDirect3DHook9::GetSingletonPtr()->RemoveHook();
}
void CCore::SetCenterCursor ( bool bEnabled )
{
if ( bEnabled )
m_pSetCursorPosHook->EnableSetCursorPos ();
else
m_pSetCursorPosHook->DisableSetCursorPos ();
}
////////////////////////////////////////////////////////////////////////
//
// LoadModule
//
// Attempt to load a module. Returns if successful.
// On failure, displays message box and terminates the current process.
//
////////////////////////////////////////////////////////////////////////
void LoadModule ( CModuleLoader& m_Loader, const SString& strName, const SString& strModuleName )
{
WriteDebugEvent ( "Loading " + strName.ToLower () );
// Ensure DllDirectory has not been changed
SString strDllDirectory = GetSystemDllDirectory();
if ( CalcMTASAPath ( "mta" ).CompareI ( strDllDirectory ) == false )
{
AddReportLog ( 3119, SString ( "DllDirectory wrong: DllDirectory:'%s' Path:'%s'", *strDllDirectory, *CalcMTASAPath ( "mta" ) ) );
SetDllDirectory( CalcMTASAPath ( "mta" ) );
}
// Save current directory (shouldn't change anyway)
SString strSavedCwd = GetSystemCurrentDirectory();
// Load approrpiate compilation-specific library.
#ifdef MTA_DEBUG
SString strModuleFileName = strModuleName + "_d.dll";
#else
SString strModuleFileName = strModuleName + ".dll";
#endif
m_Loader.LoadModule ( CalcMTASAPath ( PathJoin ( "mta", strModuleFileName ) ) );
if ( m_Loader.IsOk () == false )
{
SString strMessage( "Error loading %s module! (%s)", *strName.ToLower (), *m_Loader.GetLastErrorMessage () );
BrowseToSolution ( strModuleName + "-not-loadable", ASK_GO_ONLINE | TERMINATE_PROCESS, strMessage );
}
// Restore current directory
SetCurrentDirectory ( strSavedCwd );
WriteDebugEvent ( strName + " loaded." );
}
////////////////////////////////////////////////////////////////////////
//
// InitModule
//
// Attempt to initialize a loaded module. Returns if successful.
// On failure, displays message box and terminates the current process.
//
////////////////////////////////////////////////////////////////////////
template < class T, class U >
T* InitModule ( CModuleLoader& m_Loader, const SString& strName, const SString& strInitializer, U* pObj )
{
// Save current directory (shouldn't change anyway)
SString strSavedCwd = GetSystemCurrentDirectory();
// Get initializer function from DLL.
typedef T* (*PFNINITIALIZER) ( U* );
PFNINITIALIZER pfnInit = static_cast < PFNINITIALIZER > ( m_Loader.GetFunctionPointer ( strInitializer ) );
if ( pfnInit == NULL )
{
MessageBoxUTF8 ( 0, SString(_("%s module is incorrect!"),*strName), "Error"+_E("CC40"), MB_OK | MB_ICONEXCLAMATION | MB_TOPMOST );
TerminateProcess ( GetCurrentProcess (), 1 );
}
// If we have a valid initializer, call it.
T* pResult = pfnInit ( pObj );
// Restore current directory
SetCurrentDirectory ( strSavedCwd );
WriteDebugEvent ( strName + " initialized." );
return pResult;
}
////////////////////////////////////////////////////////////////////////
//
// CreateModule
//
// Attempt to load and initialize a module. Returns if successful.
// On failure, displays message box and terminates the current process.
//
////////////////////////////////////////////////////////////////////////
template < class T, class U >
T* CreateModule ( CModuleLoader& m_Loader, const SString& strName, const SString& strModuleName, const SString& strInitializer, U* pObj )
{
LoadModule ( m_Loader, strName, strModuleName );
return InitModule < T > ( m_Loader, strName, strInitializer, pObj );
}
void CCore::CreateGame ( )
{
m_pGame = CreateModule < CGame > ( m_GameModule, "Game", "game_sa", "GetGameInterface", this );
if ( m_pGame->GetGameVersion () >= VERSION_11 )
{
BrowseToSolution ( "downgrade", TERMINATE_PROCESS, "Only GTA:SA version 1.0 is supported!\n\nYou are now being redirected to a page where you can patch your version." );
}
}
void CCore::CreateMultiplayer ( )
{
m_pMultiplayer = CreateModule < CMultiplayer > ( m_MultiplayerModule, "Multiplayer", "multiplayer_sa", "InitMultiplayerInterface", this );
if ( m_pMultiplayer )
m_pMultiplayer->SetIdleHandler ( CCore::StaticIdleHandler );
}
void CCore::DeinitGUI ( void )
{
}
void CCore::InitGUI ( IDirect3DDevice9* pDevice )
{
m_pGUI = InitModule < CGUI > ( m_GUIModule, "GUI", "InitGUIInterface", pDevice );
// and set the screenshot path to this default library (screenshots shouldnt really be made outside mods)
std::string strScreenShotPath = CalcMTASAPath ( "screenshots" );
CVARS_SET ( "screenshot_path", strScreenShotPath );
CScreenShot::SetPath ( strScreenShotPath.c_str() );
}
void CCore::CreateGUI ( void )
{
LoadModule ( m_GUIModule, "GUI", "cgui" );
}
void CCore::DestroyGUI ( )
{
WriteDebugEvent ( "CCore::DestroyGUI" );
if ( m_pGUI )
{
m_pGUI = NULL;
}
m_GUIModule.UnloadModule ();
}
void CCore::CreateNetwork ( )
{
m_pNet = CreateModule < CNet > ( m_NetModule, "Network", "netc", "InitNetInterface", this );
// Network module compatibility check
typedef unsigned long (*PFNCHECKCOMPATIBILITY) ( unsigned long, unsigned long* );
PFNCHECKCOMPATIBILITY pfnCheckCompatibility = static_cast< PFNCHECKCOMPATIBILITY > ( m_NetModule.GetFunctionPointer ( "CheckCompatibility" ) );
if ( !pfnCheckCompatibility || !pfnCheckCompatibility ( MTA_DM_CLIENT_NET_MODULE_VERSION, NULL ) )
{
// net.dll doesn't like our version number
ulong ulNetModuleVersion = 0;
pfnCheckCompatibility ( 1, &ulNetModuleVersion );
SString strMessage( "Network module not compatible! (Expected 0x%x, got 0x%x)", MTA_DM_CLIENT_NET_MODULE_VERSION, ulNetModuleVersion );
BrowseToSolution ( "netc-not-compatible", ASK_GO_ONLINE | TERMINATE_PROCESS, strMessage );
}
// Set mta version for report log here
SetApplicationSetting ( "mta-version-ext", SString ( "%d.%d.%d-%d.%05d.%d.%03d"
,MTASA_VERSION_MAJOR
,MTASA_VERSION_MINOR
,MTASA_VERSION_MAINTENANCE
,MTASA_VERSION_TYPE
,MTASA_VERSION_BUILD
,m_pNet->GetNetRev ()
,m_pNet->GetNetRel ()
) );
char szSerial [ 64 ];
m_pNet->GetSerial ( szSerial, sizeof ( szSerial ) );
SetApplicationSetting ( "serial", szSerial );
}
void CCore::CreateXML ( )
{
if ( !m_pXML )
m_pXML = CreateModule < CXML > ( m_XMLModule, "XML", "xmll", "InitXMLInterface", *CalcMTASAPath ( "MTA" ) );
if ( !m_pConfigFile )
{
// Load config XML file
m_pConfigFile = m_pXML->CreateXML ( CalcMTASAPath ( MTA_CONFIG_PATH ) );
if ( !m_pConfigFile ) {
assert ( false );
return;
}
m_pConfigFile->Parse ();
}
// Load the keybinds (loads defaults if the subnode doesn't exist)
if ( m_pKeyBinds )
{
m_pKeyBinds->LoadFromXML ( GetConfig ()->FindSubNode ( CONFIG_NODE_KEYBINDS ) );
m_pKeyBinds->LoadDefaultCommands( false );
}
// Load XML-dependant subsystems
m_ClientVariables.Load ( );
}
void CCore::DestroyGame ( )
{
WriteDebugEvent ( "CCore::DestroyGame" );
if ( m_pGame )
{
m_pGame->Terminate ();
m_pGame = NULL;
}
m_GameModule.UnloadModule();
}
void CCore::DestroyMultiplayer ( )
{
WriteDebugEvent ( "CCore::DestroyMultiplayer" );
if ( m_pMultiplayer )
{
m_pMultiplayer = NULL;
}
m_MultiplayerModule.UnloadModule();
}
void CCore::DestroyXML ( )
{
WriteDebugEvent ( "CCore::DestroyXML" );
// Save and unload configuration
if ( m_pConfigFile ) {
SaveConfig ();
delete m_pConfigFile;
}
if ( m_pXML )
{
m_pXML = NULL;
}
m_XMLModule.UnloadModule();
}
void CCore::DestroyNetwork ( )
{
WriteDebugEvent ( "CCore::DestroyNetwork" );
if ( m_pNet )
{
m_pNet->Shutdown();
m_pNet = NULL;
}
m_NetModule.UnloadModule();
}
void CCore::InitialiseWeb ()
{
// Don't initialise webcore twice
if ( m_pWebCore )
return;
m_pWebCore = new CWebCore;
m_pWebCore->Initialise ();
}
void CCore::UpdateIsWindowMinimized ( void )
{
m_bIsWindowMinimized = IsIconic ( GetHookedWindow () ) ? true : false;
// Update CPU saver for when minimized and not connected
g_pCore->GetMultiplayer ()->SetIsMinimizedAndNotConnected ( m_bIsWindowMinimized && !IsConnected () );
g_pCore->GetMultiplayer ()->SetMirrorsEnabled ( !m_bIsWindowMinimized );
// Enable timer if not connected at least once
bool bEnableTimer = !m_bGettingIdleCallsFromMultiplayer;
if ( m_bWindowsTimerEnabled != bEnableTimer )
{
m_bWindowsTimerEnabled = bEnableTimer;
if ( bEnableTimer )
SetTimer( GetHookedWindow(), IDT_TIMER1, 50, (TIMERPROC) NULL );
else
KillTimer( GetHookedWindow(), IDT_TIMER1 );
}
}
bool CCore::IsWindowMinimized ( void )
{
return m_bIsWindowMinimized;
}
void CCore::DoPreFramePulse ( )
{
TIMING_CHECKPOINT( "+CorePreFrame" );
m_pKeyBinds->DoPreFramePulse ();
// Notify the mod manager
m_pModManager->DoPulsePreFrame ();
m_pLocalGUI->DoPulse ();
CCrashDumpWriter::UpdateCounters();
TIMING_CHECKPOINT( "-CorePreFrame" );
}
void CCore::DoPostFramePulse ( )
{
TIMING_CHECKPOINT( "+CorePostFrame1" );
if ( m_bQuitOnPulse )
Quit ();
if ( m_bDestroyMessageBox )
{
RemoveMessageBox ();
m_bDestroyMessageBox = false;
}
static bool bFirstPulse = true;
if ( bFirstPulse )
{
bFirstPulse = false;
// Validate CVARS
CClientVariables::GetSingleton().ValidateValues ();
// Apply all settings
ApplyConsoleSettings ();
ApplyGameSettings ();
m_pGUI->SelectInputHandlers( INPUT_CORE );
m_Community.Initialize ();
}
if ( m_pGame->GetSystemState () == 5 ) // GS_INIT_ONCE
{
WatchDogCompletedSection ( "L2" ); // gta_sa.set seems ok
WatchDogCompletedSection ( "L3" ); // No hang on startup
}
// This is the first frame in the menu?
if ( m_pGame->GetSystemState () == 7 ) // GS_FRONTEND
{
// Wait 250 frames more than the time it took to get status 7 (fade-out time)
static short WaitForMenu = 0;
// Do crash dump encryption while the credit screen is displayed
if ( WaitForMenu == 0 )
HandleCrashDumpEncryption();
// Cope with early finish
if ( m_pGame->HasCreditScreenFadedOut () )
WaitForMenu = 250;
if ( WaitForMenu >= 250 )
{
if ( m_bFirstFrame )
{
m_bFirstFrame = false;
// Disable vsync while it's all dark
m_pGame->DisableVSync ();
// Parse the command line
// Does it begin with mtasa://?
if ( m_szCommandLineArgs && strnicmp ( m_szCommandLineArgs, "mtasa://", 8 ) == 0 )
{
SString strArguments = GetConnectCommandFromURI ( m_szCommandLineArgs );
// Run the connect command
if ( strArguments.length () > 0 && !m_pCommands->Execute ( strArguments ) )
{
ShowMessageBox ( _("Error")+_E("CC41"), _("Error executing URL"), MB_BUTTON_OK | MB_ICON_ERROR );
}
}
else
{
// We want to load a mod?
const char* szOptionValue;
if ( szOptionValue = GetCommandLineOption( "l" ) )
{
// Try to load the mod
if ( !m_pModManager->Load ( szOptionValue, m_szCommandLineArgs ) )
{
SString strTemp ( _("Error running mod specified in command line ('%s')"), szOptionValue );
ShowMessageBox ( _("Error")+_E("CC42"), strTemp, MB_BUTTON_OK | MB_ICON_ERROR ); // Command line Mod load failed
}
}
// We want to connect to a server?
else if ( szOptionValue = GetCommandLineOption ( "c" ) )
{
CCommandFuncs::Connect ( szOptionValue );
}
}
}
}
else
{
WaitForMenu++;
}
if ( m_bWaitToSetNick && GetLocalGUI()->GetMainMenu()->IsVisible() && !GetLocalGUI()->GetMainMenu()->IsFading() )
{
if ( m_uiNewNickWaitFrames > 75 )
{
// Request a new nickname if we're waiting for one
GetLocalGUI()->GetMainMenu()->GetSettingsWindow()->RequestNewNickname();
m_bWaitToSetNick = false;
}
else
m_uiNewNickWaitFrames++;
}
}
if ( !IsFocused() && m_bLastFocused )
{
// Fix for #4948
m_pKeyBinds->CallAllGTAControlBinds ( CONTROL_BOTH, false );
m_bLastFocused = false;
}
else if ( IsFocused() && !m_bLastFocused )
{
m_bLastFocused = true;
}
GetJoystickManager ()->DoPulse (); // Note: This may indirectly call CMessageLoopHook::ProcessMessage
m_pKeyBinds->DoPostFramePulse ();
if ( m_pWebCore )
m_pWebCore->DoPulse ();
// Notify the mod manager and the connect manager
TIMING_CHECKPOINT( "-CorePostFrame1" );
m_pModManager->DoPulsePostFrame ();
TIMING_CHECKPOINT( "+CorePostFrame2" );
GetMemStats ()->Draw ();
GetGraphStats ()->Draw();
m_pConnectManager->DoPulse ();
m_Community.DoPulse ();
//XFire polling
if ( IsConnected() )
{
time_t ttime;
ttime = time ( NULL );
if ( ttime >= m_tXfireUpdate + XFIRE_UPDATE_RATE )
{
if ( m_pCurrentServer->IsSocketClosed() )
{
//Init our socket
m_pCurrentServer->Init();
}
//Get our xfire query reply
SString strReply = UpdateXfire( );
//If we Parsed or if the reply failed wait another XFIRE_UPDATE_RATE until trying again
if ( strReply == "ParsedQuery" || strReply == "NoReply" )
{
m_tXfireUpdate = time ( NULL );
//Close the socket
m_pCurrentServer->SocketClose();
}
}
}
//Set our update time to zero to ensure that the first xfire update happens instantly when joining
else
{
XfireSetCustomGameData ( 0, NULL, NULL );
if ( m_tXfireUpdate != 0 )
m_tXfireUpdate = 0;
}
TIMING_CHECKPOINT( "-CorePostFrame2" );
}
// Called after MOD is unloaded
void CCore::OnModUnload ( )
{
// reattach the global event
m_pGUI->SelectInputHandlers( INPUT_CORE );
// remove unused events
m_pGUI->ClearInputHandlers( INPUT_MOD );
// Ensure all these have been removed
m_pKeyBinds->RemoveAllFunctions ();
m_pKeyBinds->RemoveAllControlFunctions ();
// Reset client script frame rate limit
m_uiClientScriptFrameRateLimit = 0;
// Clear web whitelist
m_pWebCore->ResetFilter ();
}
void CCore::RegisterCommands ( )
{
//m_pCommands->Add ( "e", CCommandFuncs::Editor );
//m_pCommands->Add ( "clear", CCommandFuncs::Clear );
m_pCommands->Add ( "help", _("this help screen"), CCommandFuncs::Help );
m_pCommands->Add ( "exit", _("exits the application"), CCommandFuncs::Exit );
m_pCommands->Add ( "quit", _("exits the application"), CCommandFuncs::Exit );
m_pCommands->Add ( "ver", _("shows the version"), CCommandFuncs::Ver );
m_pCommands->Add ( "time", _("shows the time"), CCommandFuncs::Time );
m_pCommands->Add ( "showhud", _("shows the hud"), CCommandFuncs::HUD );
m_pCommands->Add ( "binds", _("shows all the binds"), CCommandFuncs::Binds );
m_pCommands->Add ( "serial", _("shows your serial"), CCommandFuncs::Serial );
#if 0
m_pCommands->Add ( "vid", "changes the video settings (id)", CCommandFuncs::Vid );
m_pCommands->Add ( "window", "enter/leave windowed mode", CCommandFuncs::Window );
m_pCommands->Add ( "load", "loads a mod (name args)", CCommandFuncs::Load );
m_pCommands->Add ( "unload", "unloads a mod (name)", CCommandFuncs::Unload );
#endif
m_pCommands->Add ( "connect", _("connects to a server (host port nick pass)"), CCommandFuncs::Connect );
m_pCommands->Add ( "reconnect", _("connects to a previous server"), CCommandFuncs::Reconnect );
m_pCommands->Add ( "bind", _("binds a key (key control)"), CCommandFuncs::Bind );
m_pCommands->Add ( "unbind", _("unbinds a key (key)"), CCommandFuncs::Unbind );
m_pCommands->Add ( "copygtacontrols", _("copies the default gta controls"), CCommandFuncs::CopyGTAControls );
m_pCommands->Add ( "screenshot", _("outputs a screenshot"), CCommandFuncs::ScreenShot );
m_pCommands->Add ( "saveconfig", _("immediately saves the config"), CCommandFuncs::SaveConfig );
m_pCommands->Add ( "cleardebug", _("clears the debug view"), CCommandFuncs::DebugClear );
m_pCommands->Add ( "chatscrollup", _("scrolls the chatbox upwards"), CCommandFuncs::ChatScrollUp );
m_pCommands->Add ( "chatscrolldown", _("scrolls the chatbox downwards"), CCommandFuncs::ChatScrollDown );
m_pCommands->Add ( "debugscrollup", _("scrolls the debug view upwards"), CCommandFuncs::DebugScrollUp );
m_pCommands->Add ( "debugscrolldown", _("scrolls the debug view downwards"), CCommandFuncs::DebugScrollDown );
m_pCommands->Add ( "test", "", CCommandFuncs::Test );
m_pCommands->Add ( "showmemstat", _("shows the memory statistics"), CCommandFuncs::ShowMemStat );
m_pCommands->Add ( "showframegraph", _("shows the frame timing graph"), CCommandFuncs::ShowFrameGraph );
m_pCommands->Add ( "jinglebells", "", CCommandFuncs::JingleBells );
#if defined(MTA_DEBUG) || defined(MTA_BETA)
m_pCommands->Add ( "fakelag", "", CCommandFuncs::FakeLag );
#endif
}
void CCore::SwitchRenderWindow ( HWND hWnd, HWND hWndInput )
{
assert ( 0 );
#if 0
// Make GTA windowed
m_pGame->GetSettings()->SetCurrentVideoMode(0);
// Get the destination window rectangle
RECT rect;
GetWindowRect ( hWnd, &rect );
// Size the GTA window size to the same size as the destination window rectangle
HWND hDeviceWindow = CDirect3DData::GetSingleton ().GetDeviceWindow ();
MoveWindow ( hDeviceWindow,
0,
0,
rect.right - rect.left,
rect.bottom - rect.top,
TRUE );
// Turn the GTA window into a child window of our static render container window
SetParent ( hDeviceWindow, hWnd );
SetWindowLong ( hDeviceWindow, GWL_STYLE, WS_VISIBLE | WS_CHILD );
#endif
}
bool CCore::IsValidNick ( const char* szNick )
{
// Grab the size of the nick. Check that it's within the player
size_t sizeNick = strlen(szNick);
if (sizeNick < MIN_PLAYER_NICK_LENGTH || sizeNick > MAX_PLAYER_NICK_LENGTH)
{
return false;
}
// Check that each character is valid (visible characters exluding space)
unsigned char ucTemp;
for (size_t i = 0; i < sizeNick; i++)
{
ucTemp = szNick[i];
if (ucTemp < 33 || ucTemp > 126)
{
return false;
}
}
// Nickname is valid, return true
return true;
}
void CCore::Quit ( bool bInstantly )
{
if ( bInstantly )
{
AddReportLog( 7101, "Core - Quit" );
// Show that we are quiting (for the crash dump filename)
SetApplicationSettingInt ( "last-server-ip", 1 );
WatchDogBeginSection( "Q0" ); // Allow loader to detect freeze on exit
// Destroy the client
CModManager::GetSingleton ().Unload ();
// Destroy ourself
delete CCore::GetSingletonPtr ();
WatchDogCompletedSection( "Q0" );
// Use TerminateProcess for now as exiting the normal way crashes
TerminateProcess ( GetCurrentProcess (), 0 );
//PostQuitMessage ( 0 );
}
else
{
m_bQuitOnPulse = true;
}
}
bool CCore::WasLaunchedWithConnectURI ( void )
{
if ( m_szCommandLineArgs && strnicmp ( m_szCommandLineArgs, "mtasa://", 8 ) == 0 )
return true;
return false;
}
void CCore::ParseCommandLine ( std::map < std::string, std::string > & options, const char*& szArgs, const char** pszNoValOptions )
{
std::set < std::string > noValOptions;
if ( pszNoValOptions )
{
while ( *pszNoValOptions )
{
noValOptions.insert ( *pszNoValOptions );
pszNoValOptions++;
}
}
const char* szCmdLine = GetCommandLine ();
char szCmdLineCopy[512];
STRNCPY ( szCmdLineCopy, szCmdLine, sizeof(szCmdLineCopy) );
char* pCmdLineEnd = szCmdLineCopy + strlen ( szCmdLineCopy );
char* pStart = szCmdLineCopy;
char* pEnd = pStart;
bool bInQuoted = false;
std::string strKey;
szArgs = NULL;
while ( pEnd != pCmdLineEnd )
{
pEnd = strchr ( pEnd + 1, ' ' );
if ( !pEnd )
pEnd = pCmdLineEnd;
if ( bInQuoted && *(pEnd - 1) == '"' )
bInQuoted = false;
else if ( *pStart == '"' )
bInQuoted = true;
if ( !bInQuoted )
{
*pEnd = 0;
if ( strKey.empty () )
{
if ( *pStart == '-' )
{
strKey = pStart + 1;
if ( noValOptions.find ( strKey ) != noValOptions.end () )
{
options [ strKey ] = "";
strKey.clear ();
}
}
else
{
szArgs = pStart - szCmdLineCopy + szCmdLine;
break;
}
}
else
{
if ( *pStart == '-' )
{
options [ strKey ] = "";
strKey = pStart + 1;
}
else
{
if ( *pStart == '"' )
pStart++;
if ( *(pEnd - 1) == '"' )
*(pEnd - 1) = 0;
options [ strKey ] = pStart;
strKey.clear ();
}
}
pStart = pEnd;
while ( pStart != pCmdLineEnd && *(++pStart) == ' ' );
pEnd = pStart;
}
}
}
const char* CCore::GetCommandLineOption ( const char* szOption )
{
std::map < std::string, std::string >::iterator it = m_CommandLineOptions.find ( szOption );
if ( it != m_CommandLineOptions.end () )
return it->second.c_str ();
else
return NULL;
}
SString CCore::GetConnectCommandFromURI ( const char* szURI )
{
unsigned short usPort;
std::string strHost, strNick, strPassword;
GetConnectParametersFromURI ( szURI, strHost, usPort, strNick, strPassword );
// Generate a string with the arguments to send to the mod IF we got a host
SString strDest;
if ( strHost.size() > 0 )
{
if ( strPassword.size() > 0 )
strDest.Format ( "connect %s %u %s %s", strHost.c_str (), usPort, strNick.c_str (), strPassword.c_str () );
else
strDest.Format ( "connect %s %u %s", strHost.c_str (), usPort, strNick.c_str () );
}
return strDest;
}
void CCore::GetConnectParametersFromURI ( const char* szURI, std::string &strHost, unsigned short &usPort, std::string &strNick, std::string &strPassword )
{
// Grab the length of the string
size_t sizeURI = strlen ( szURI );
// Parse it right to left
char szLeft [256];
szLeft [255] = 0;
char* szLeftIter = szLeft + 255;
char szRight [256];
szRight [255] = 0;
char* szRightIter = szRight + 255;
const char* szIterator = szURI + sizeURI;
bool bHitAt = false;
for ( ; szIterator >= szURI + 8; szIterator-- )
{
if ( !bHitAt && *szIterator == '@' )
{
bHitAt = true;
}
else
{
if ( bHitAt )
{
if ( szLeftIter > szLeft )
{
*(--szLeftIter) = *szIterator;
}
}
else
{
if ( szRightIter > szRight )
{
*(--szRightIter) = *szIterator;
}
}
}
}
// Parse the host/port
char szHost [64];
char szPort [12];
char* szHostIter = szHost;
char* szPortIter = szPort;
memset ( szHost, 0, sizeof(szHost) );
memset ( szPort, 0, sizeof(szPort) );
bool bIsInPort = false;
size_t sizeRight = strlen ( szRightIter );
for ( size_t i = 0; i < sizeRight; i++ )
{
if ( !bIsInPort && szRightIter [i] == ':' )
{
bIsInPort = true;
}
else
{
if ( bIsInPort )
{
if ( szPortIter < szPort + 11 )
{
*(szPortIter++) = szRightIter [i];
}
}
else
{
if ( szHostIter < szHost + 63 )
{
*(szHostIter++) = szRightIter [i];
}
}
}
}
// Parse the nickname / password
char szNickname [64];
char szPassword [64];
char* szNicknameIter = szNickname;
char* szPasswordIter = szPassword;
memset ( szNickname, 0, sizeof(szNickname) );
memset ( szPassword, 0, sizeof(szPassword) );
bool bIsInPassword = false;
size_t sizeLeft = strlen ( szLeftIter );
for ( size_t i = 0; i < sizeLeft; i++ )
{
if ( !bIsInPassword && szLeftIter [i] == ':' )
{
bIsInPassword = true;
}
else
{
if ( bIsInPassword )
{
if ( szPasswordIter < szPassword + 63 )
{
*(szPasswordIter++) = szLeftIter [i];
}
}
else
{
if ( szNicknameIter < szNickname + 63 )
{
*(szNicknameIter++) = szLeftIter [i];
}
}
}
}
// If we got any port, convert it to an integral type
usPort = 22003;
if ( strlen ( szPort ) > 0 )
{
usPort = static_cast < unsigned short > ( atoi ( szPort ) );
}
// Grab the nickname
if ( strlen ( szNickname ) > 0 )
{
strNick = szNickname;
}
else
{
CVARS_GET ( "nick", strNick );
}
strHost = szHost;
strPassword = szPassword;
}
void CCore::UpdateRecentlyPlayed()
{
//Get the current host and port
unsigned int uiPort;
std::string strHost;
CVARS_GET ( "host", strHost );
CVARS_GET ( "port", uiPort );
// Save the connection details into the recently played servers list
in_addr Address;
if ( CServerListItem::Parse ( strHost.c_str(), Address ) )
{
CServerBrowser* pServerBrowser = CCore::GetSingleton ().GetLocalGUI ()->GetMainMenu ()->GetServerBrowser ();
CServerList* pRecentList = pServerBrowser->GetRecentList ();
pRecentList->Remove ( Address, uiPort );
pRecentList->AddUnique ( Address, uiPort, true );
pServerBrowser->SaveRecentlyPlayedList();
if ( !m_pConnectManager->m_strLastPassword.empty() )
pServerBrowser->SetServerPassword ( strHost + ":" + SString("%u",uiPort), m_pConnectManager->m_strLastPassword );
}
//Save our configuration file
CCore::GetSingleton ().SaveConfig ();
}
void CCore::SetCurrentServer( in_addr Addr, unsigned short usGamePort )
{
//Set the current server info so we can query it with ASE for xfire
m_pCurrentServer->ChangeAddress( Addr, usGamePort );
}
SString CCore::UpdateXfire( void )
{
//Check if a current server exists
if ( m_pCurrentServer )
{
//Get the result from the Pulse method
std::string strResult = m_pCurrentServer->Pulse();
//Have we parsed the query this function call?
if ( strResult == "ParsedQuery" )
{
//Get our Nick from CVARS
std::string strNick;
CVARS_GET ( "nick", strNick );
//Format a player count
SString strPlayerCount("%i / %i", m_pCurrentServer->nPlayers, m_pCurrentServer->nMaxPlayers);
// Set as our custom date
SetXfireData( m_pCurrentServer->strName, m_pCurrentServer->strVersion, m_pCurrentServer->bPassworded, m_pCurrentServer->strGameMode, m_pCurrentServer->strMap, strNick, strPlayerCount );
}
//Return the result
return strResult;
}
return "";
}
void CCore::SetXfireData ( std::string strServerName, std::string strVersion, bool bPassworded, std::string strGamemode, std::string strMap, std::string strPlayerName, std::string strPlayerCount )
{
if ( XfireIsLoaded () )
{
//Set our "custom data"
const char *szKey[7], *szValue[7];
szKey[0] = "Server Name";
szValue[0] = strServerName.c_str();
szKey[1] = "Server Version";
szValue[1] = strVersion.c_str();
szKey[2] = "Passworded";
szValue[2] = bPassworded ? "Yes" : "No";
szKey[3] = "Gamemode";
szValue[3] = strGamemode.c_str();
szKey[4] = "Map";
szValue[4] = strMap.c_str();
szKey[5] = "Player Name";
szValue[5] = strPlayerName.c_str();
szKey[6] = "Player Count";
szValue[6] = strPlayerCount.c_str();
XfireSetCustomGameData ( 7, szKey, szValue );
}
}
//
// Recalculate FPS limit to use
//
// Uses client rate from config
// Uses client rate from script
// Uses server rate from argument, or last time if not supplied
//
void CCore::RecalculateFrameRateLimit ( uint uiServerFrameRateLimit, bool bLogToConsole )
{
// Save rate from server if valid
if ( uiServerFrameRateLimit != -1 )
m_uiServerFrameRateLimit = uiServerFrameRateLimit;
// Start with value set by the server
m_uiFrameRateLimit = m_uiServerFrameRateLimit;
// Apply client config setting
uint uiClientConfigRate;
g_pCore->GetCVars ()->Get ( "fps_limit", uiClientConfigRate );
// Lowest wins (Although zero is highest)
if ( ( m_uiFrameRateLimit == 0 || uiClientConfigRate < m_uiFrameRateLimit ) && uiClientConfigRate > 0 )
m_uiFrameRateLimit = uiClientConfigRate;
// Apply client script setting
uint uiClientScriptRate = m_uiClientScriptFrameRateLimit;
// Lowest wins (Although zero is highest)
if ( ( m_uiFrameRateLimit == 0 || uiClientScriptRate < m_uiFrameRateLimit ) && uiClientScriptRate > 0 )
m_uiFrameRateLimit = uiClientScriptRate;
// Print new limits to the console
if ( bLogToConsole )
{
SString strStatus ( "Server FPS limit: %d", m_uiServerFrameRateLimit );
if ( m_uiFrameRateLimit != m_uiServerFrameRateLimit )
strStatus += SString ( " (Using %d)", m_uiFrameRateLimit );
CCore::GetSingleton ().GetConsole ()->Print( strStatus );
}
}
//
// Change client rate as set by script
//
void CCore::SetClientScriptFrameRateLimit ( uint uiClientScriptFrameRateLimit )
{
m_uiClientScriptFrameRateLimit = uiClientScriptFrameRateLimit;
RecalculateFrameRateLimit( -1, false );
}
//
// Make sure the frame rate limit has been applied since the last call
//
void CCore::EnsureFrameRateLimitApplied ( void )
{
if ( !m_bDoneFrameRateLimit )
{
ApplyFrameRateLimit ();
}
m_bDoneFrameRateLimit = false;
}
//
// Do FPS limiting
//
// This is called once a frame even if minimized
//
void CCore::ApplyFrameRateLimit ( uint uiOverrideRate )
{
TIMING_CHECKPOINT( "-CallIdle1" );
ms_TimingCheckpoints.EndTimingCheckpoints ();
// Frame rate limit stuff starts here
m_bDoneFrameRateLimit = true;
uint uiUseRate = uiOverrideRate != -1 ? uiOverrideRate : m_uiFrameRateLimit;
TIMING_GRAPH("Limiter");
if ( uiUseRate < 1 )
return DoReliablePulse ();
if ( m_DiagnosticDebug != EDiagnosticDebug::D3D_6732 )
Sleep( 1 ); // Make frame rate smoother maybe
// Calc required time in ms between frames
const double dTargetTimeToUse = 1000.0 / uiUseRate;
// Time now
double dTimeMs = GetTickCount32 ();
// Get delta time in ms since last frame
double dTimeUsed = dTimeMs - m_dLastTimeMs;
// Apply any over/underrun carried over from the previous frame
dTimeUsed += m_dPrevOverrun;
if ( dTimeUsed < dTargetTimeToUse )
{
// Have time spare - maybe eat some of that now
double dSpare = dTargetTimeToUse - dTimeUsed;
double dUseUpNow = dSpare - dTargetTimeToUse * 0.2f;
if ( dUseUpNow >= 1 )
Sleep( static_cast < DWORD > ( floor ( dUseUpNow ) ) );
// Redo timing calcs
dTimeMs = GetTickCount32 ();
dTimeUsed = dTimeMs - m_dLastTimeMs;
dTimeUsed += m_dPrevOverrun;
}
// Update over/underrun for next frame
m_dPrevOverrun = dTimeUsed - dTargetTimeToUse;
// Limit carry over
m_dPrevOverrun = Clamp ( dTargetTimeToUse * -0.9f, m_dPrevOverrun, dTargetTimeToUse * 0.1f );
m_dLastTimeMs = dTimeMs;
DoReliablePulse ();
TIMING_GRAPH("FrameEnd");
TIMING_GRAPH("");
}
//
// DoReliablePulse
//
// This is called once a frame even if minimized
//
void CCore::DoReliablePulse ( void )
{
ms_TimingCheckpoints.BeginTimingCheckpoints ();
TIMING_CHECKPOINT( "+CallIdle2" );
UpdateIsWindowMinimized ();
// Non frame rate limit stuff
if ( IsWindowMinimized () )
m_iUnminimizeFrameCounter = 4; // Tell script we have unminimized after a short delay
UpdateModuleTickCount64 ();
}
//
// Debug timings
//
bool CCore::IsTimingCheckpoints ( void )
{
return ms_TimingCheckpoints.IsTimingCheckpoints ();
}
void CCore::OnTimingCheckpoint ( const char* szTag )
{
ms_TimingCheckpoints.OnTimingCheckpoint ( szTag );
}
void CCore::OnTimingDetail ( const char* szTag )
{
ms_TimingCheckpoints.OnTimingDetail ( szTag );
}
//
// OnDeviceRestore
//
void CCore::OnDeviceRestore ( void )
{
m_iUnminimizeFrameCounter = 4; // Tell script we have restored after 4 frames to avoid double sends
m_bDidRecreateRenderTargets = true;
}
//
// OnPreFxRender
//
void CCore::OnPreFxRender ( void )
{
// Don't do nothing if nothing won't be drawn
if ( !CGraphics::GetSingleton ().HasMaterialLine3DQueueItems () )
return;
CGraphics::GetSingleton ().EnteringMTARenderZone();
CGraphics::GetSingleton ().DrawMaterialLine3DQueue ();
CGraphics::GetSingleton ().LeavingMTARenderZone();
}
//
// OnPreHUDRender
//
void CCore::OnPreHUDRender ( void )
{
IDirect3DDevice9* pDevice = CGraphics::GetSingleton ().GetDevice ();
// Handle saving depth buffer
CGraphics::GetSingleton ().GetRenderItemManager ()->SaveReadableDepthBuffer();
CGraphics::GetSingleton ().EnteringMTARenderZone();
// Maybe capture screen and other stuff
CGraphics::GetSingleton ().GetRenderItemManager ()->DoPulse ();
// Handle script stuffs
if ( m_iUnminimizeFrameCounter && --m_iUnminimizeFrameCounter == 0 )
{
m_pModManager->DoPulsePreHUDRender ( true, m_bDidRecreateRenderTargets );
m_bDidRecreateRenderTargets = false;
}
else
m_pModManager->DoPulsePreHUDRender ( false, false );
// Restore in case script forgets
CGraphics::GetSingleton ().GetRenderItemManager ()->RestoreDefaultRenderTarget ();
// Draw pre-GUI primitives
CGraphics::GetSingleton ().DrawPreGUIQueue ();
CGraphics::GetSingleton ().LeavingMTARenderZone();
}
//
// CCore::CalculateStreamingMemoryRange
//
// Streaming memory range based on system installed memory:
//
// System RAM MB min max
// 512 = 64 96
// 1024 = 96 128
// 2048 = 128 256
//
// Also:
// Max should be no more than 2 * installed video memory
// Min should be no more than 1 * installed video memory
// Max should be no less than 96MB
// Gap between min and max should be no less than 32MB
//
void CCore::CalculateStreamingMemoryRange ( void )
{
// Only need to do this once
if ( m_fMinStreamingMemory != 0 )
return;
// Get system info
int iSystemRamMB = static_cast < int > ( GetWMITotalPhysicalMemory () / 1024LL / 1024LL );
int iVideoMemoryMB = g_pDeviceState->AdapterState.InstalledMemoryKB / 1024;
// Calc min and max from lookup table
SSamplePoint < float > minPoints[] = { {512, 64}, {1024, 96}, {2048, 128} };
SSamplePoint < float > maxPoints[] = { {512, 96}, {1024, 128}, {2048, 256} };
float fMinAmount = EvalSamplePosition < float > ( minPoints, NUMELMS ( minPoints ), iSystemRamMB );
float fMaxAmount = EvalSamplePosition < float > ( maxPoints, NUMELMS ( maxPoints ), iSystemRamMB );
// Apply cap dependant on video memory
fMaxAmount = Min ( fMaxAmount, iVideoMemoryMB * 2.f );
fMinAmount = Min ( fMinAmount, iVideoMemoryMB * 1.f );
// Apply 96MB lower limit
fMaxAmount = Max ( fMaxAmount, 96.f );
// Apply gap limit
fMinAmount = fMaxAmount - Max ( fMaxAmount - fMinAmount, 32.f );
m_fMinStreamingMemory = fMinAmount;
m_fMaxStreamingMemory = fMaxAmount;
}
//
// GetMinStreamingMemory
//
uint CCore::GetMinStreamingMemory ( void )
{
CalculateStreamingMemoryRange ();
#ifdef MTA_DEBUG
return 1;
#endif
return m_fMinStreamingMemory;
}
//
// GetMaxStreamingMemory
//
uint CCore::GetMaxStreamingMemory ( void )
{
CalculateStreamingMemoryRange ();
return m_fMaxStreamingMemory;
}
//
// OnCrashAverted
//
void CCore::OnCrashAverted ( uint uiId )
{
CCrashDumpWriter::OnCrashAverted ( uiId );
}
//
// OnEnterCrashZone
//
void CCore::OnEnterCrashZone ( uint uiId )
{
CCrashDumpWriter::OnEnterCrashZone ( uiId );
}
//
// LogEvent
//
void CCore::LogEvent ( uint uiDebugId, const char* szType, const char* szContext, const char* szBody, uint uiAddReportLogId )
{
if ( uiAddReportLogId )
AddReportLog ( uiAddReportLogId, SString ( "%s - %s", szContext, szBody ) );
if ( GetDebugIdEnabled ( uiDebugId ) )
{
CCrashDumpWriter::LogEvent ( szType, szContext, szBody );
OutputDebugLine ( SString ( "[LogEvent] %d %s %s %s", uiDebugId, szType, szContext, szBody ) );
}
}
//
// GetDebugIdEnabled
//
bool CCore::GetDebugIdEnabled ( uint uiDebugId )
{
static CFilterMap debugIdFilterMap ( GetVersionUpdater ()->GetDebugFilterString () );
return ( uiDebugId == 0 ) || !debugIdFilterMap.IsFiltered ( uiDebugId );
}
EDiagnosticDebugType CCore::GetDiagnosticDebug ( void )
{
return m_DiagnosticDebug;
}
void CCore::SetDiagnosticDebug ( EDiagnosticDebugType value )
{
m_DiagnosticDebug = value;
}
CModelCacheManager* CCore::GetModelCacheManager ( void )
{
if ( !m_pModelCacheManager )
m_pModelCacheManager = NewModelCacheManager ();
return m_pModelCacheManager;
}
void CCore::AddModelToPersistentCache ( ushort usModelId )
{
return GetModelCacheManager ()->AddModelToPersistentCache ( usModelId );
}
void CCore::StaticIdleHandler ( void )
{
g_pCore->IdleHandler ();
}
// Gets called every game loop, after GTA has been loaded for the first time
void CCore::IdleHandler ( void )
{
m_bGettingIdleCallsFromMultiplayer = true;
HandleIdlePulse();
}
// Gets called every 50ms, before GTA has been loaded for the first time
void CCore::WindowsTimerHandler ( void )
{
if ( !m_bGettingIdleCallsFromMultiplayer )
HandleIdlePulse();
}
// Always called, even if minimized
void CCore::HandleIdlePulse ( void )
{
UpdateIsWindowMinimized();
if ( IsWindowMinimized() )
{
DoPreFramePulse();
DoPostFramePulse();
}
if ( m_pModManager->GetCurrentMod() )
m_pModManager->GetCurrentMod()->IdleHandler();
}
//
// Handle encryption of Windows crash dump files
//
void CCore::HandleCrashDumpEncryption( void )
{
const int iMaxFiles = 10;
SString strDumpDirPath = CalcMTASAPath( "mta\\dumps" );
SString strDumpDirPrivatePath = PathJoin( strDumpDirPath, "private" );
SString strDumpDirPublicPath = PathJoin( strDumpDirPath, "public" );
MakeSureDirExists( strDumpDirPrivatePath + "/" );
MakeSureDirExists( strDumpDirPublicPath + "/" );
SString strMessage = "Dump files in this directory are encrypted and copied to 'dumps\\public' during startup\n\n";
FileSave( PathJoin( strDumpDirPrivatePath, "README.txt" ), strMessage );
// Move old dumps to the private folder
{
std::vector < SString > legacyList = FindFiles( PathJoin( strDumpDirPath, "*.dmp" ), true, false );
for ( uint i = 0 ; i < legacyList.size() ; i++ )
{
const SString& strFilename = legacyList[i];
SString strSrcPathFilename = PathJoin( strDumpDirPath, strFilename );
SString strDestPathFilename = PathJoin( strDumpDirPrivatePath, strFilename );
FileRename( strSrcPathFilename, strDestPathFilename );
}
}
// Limit number of files in the private folder
{
std::vector < SString > privateList = FindFiles( PathJoin( strDumpDirPrivatePath, "*.dmp" ), true, false, true );
for ( int i = 0 ; i < (int)privateList.size() - iMaxFiles ; i++ )
FileDelete( PathJoin( strDumpDirPrivatePath, privateList[i] ) );
}
// Copy and encrypt private files to public if they don't already exist
{
std::vector < SString > privateList = FindFiles( PathJoin( strDumpDirPrivatePath, "*.dmp" ), true, false );
for ( uint i = 0 ; i < privateList.size() ; i++ )
{
const SString& strPrivateFilename = privateList[i];
SString strPublicFilename = ExtractBeforeExtension( strPrivateFilename ) + ".rsa." + ExtractExtension( strPrivateFilename );
SString strPrivatePathFilename = PathJoin( strDumpDirPrivatePath, strPrivateFilename );
SString strPublicPathFilename = PathJoin( strDumpDirPublicPath, strPublicFilename );
if ( !FileExists( strPublicPathFilename ) )
{
GetNetwork()->EncryptDumpfile( strPrivatePathFilename, strPublicPathFilename );
}
}
}
// Limit number of files in the public folder
{
std::vector < SString > publicList = FindFiles( PathJoin( strDumpDirPublicPath, "*.dmp" ), true, false, true );
for ( int i = 0 ; i < (int)publicList.size() - iMaxFiles ; i++ )
FileDelete( PathJoin( strDumpDirPublicPath, publicList[i] ) );
}
// And while we are here, limit number of items in core.log as well
{
SString strCoreLogPathFilename = CalcMTASAPath( "mta\\core.log" );
SString strFileContents;
FileLoad( strCoreLogPathFilename, strFileContents );
SString strDelmiter = "** -- Unhandled exception -- **";
std::vector < SString > parts;
strFileContents.Split( strDelmiter, parts );
if ( parts.size() > iMaxFiles )
{
strFileContents = strDelmiter + strFileContents.Join( strDelmiter, parts, parts.size() - iMaxFiles );
FileSave( strCoreLogPathFilename, strFileContents );
}
}
}
//
// Flag to make sure stuff only gets done when everything is ready
//
void CCore::SetModulesLoaded( bool bLoaded )
{
m_bModulesLoaded = bLoaded;
}
bool CCore::AreModulesLoaded( void )
{
return m_bModulesLoaded;
}
//
// Handle dummy progress when game seems stalled
//
int ms_iDummyProgressTimerCounter = 0;
void CALLBACK TimerProc( void* lpParametar, BOOLEAN TimerOrWaitFired )
{
ms_iDummyProgressTimerCounter++;
}
//
// Refresh progress output
//
void CCore::UpdateDummyProgress( int iValue, const char* szType )
{
if ( iValue != -1 )
{
m_iDummyProgressValue = iValue;
m_strDummyProgressType = szType;
}
if ( m_DummyProgressTimerHandle == NULL )
{
// Using this timer is quicker than checking tick count with every call to UpdateDummyProgress()
::CreateTimerQueueTimer( &m_DummyProgressTimerHandle, NULL, TimerProc, this, DUMMY_PROGRESS_ANIMATION_INTERVAL, DUMMY_PROGRESS_ANIMATION_INTERVAL, WT_EXECUTEINTIMERTHREAD );
}
if ( !ms_iDummyProgressTimerCounter )
return;
ms_iDummyProgressTimerCounter = 0;
// Compose message with amount
SString strMessage;
if ( m_iDummyProgressValue )
strMessage = SString( "%d%s", m_iDummyProgressValue, *m_strDummyProgressType );
CGraphics::GetSingleton().SetProgressMessage( strMessage );
}
//
// Do SetCursorPos if allowed
//
void CCore::CallSetCursorPos( int X, int Y )
{
if ( CCore::GetSingleton ( ).IsFocused ( ) && !CLocalGUI::GetSingleton ( ).IsMainMenuVisible ( ) )
m_pLocalGUI->SetCursorPos ( X, Y );
}
bool CCore::GetRequiredDisplayResolution( int& iOutWidth, int& iOutHeight, int& iOutColorBits, int& iOutAdapterIndex, bool& bOutAllowUnsafeResolutions )
{
CVARS_GET( "show_unsafe_resolutions", bOutAllowUnsafeResolutions );
return GetVideoModeManager()->GetRequiredDisplayResolution( iOutWidth, iOutHeight, iOutColorBits, iOutAdapterIndex );
}
bool CCore::GetDeviceSelectionEnabled( void )
{
return GetApplicationSettingInt ( "device-selection-disabled" ) ? false : true;
}
void CCore::NotifyRenderingGrass( bool bIsRenderingGrass )
{
m_bIsRenderingGrass = bIsRenderingGrass;
CDirect3DEvents9::CloseActiveShader();
}
| BozhkoAlexander/mtasa-blue | MTA10/core/CCore.cpp | C++ | gpl-3.0 | 69,554 |
/* md5.cc
Jeremy Barnes, 25 October 2012
Copyright (c) 2012 Datacratic. All rights reserved.
*/
#include "hash.h"
#include "string_functions.h"
#include <boost/algorithm/string.hpp>
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include "crypto++/sha.h"
#include "crypto++/md5.h"
#include "crypto++/hmac.h"
#include "crypto++/base64.h"
using namespace std;
namespace ML {
std::string md5HashToHex(const std::string & str)
{
return md5HashToHex(str.c_str(), str.length());
}
std::string md5HashToHex(const char * buf, size_t nBytes)
{
typedef CryptoPP::Weak::MD5 Hash;
size_t digestLen = Hash::DIGESTSIZE;
byte digest[digestLen];
Hash hash;
hash.CalculateDigest(digest, (byte *)buf, nBytes);
string md5;
for (unsigned i = 0; i < digestLen; ++i) {
md5 += ML::format("%02x", digest[i]);
}
return md5;
}
std::string md5HashToBase64(const std::string & str)
{
return md5HashToBase64(str.c_str(), str.length());
}
std::string md5HashToBase64(const char * buf, size_t nBytes)
{
typedef CryptoPP::Weak::MD5 Hash;
size_t digestLen = Hash::DIGESTSIZE;
byte digest[digestLen];
Hash hash;
hash.CalculateDigest(digest, (byte *)buf, nBytes);
// base64
char outBuf[256];
CryptoPP::Base64Encoder baseEncoder;
baseEncoder.Put(digest, digestLen);
baseEncoder.MessageEnd();
size_t got = baseEncoder.Get((byte *)outBuf, 256);
outBuf[got] = 0;
//cerr << "got " << got << " characters" << endl;
return boost::trim_copy(std::string(outBuf));
}
std::string hmacSha1Base64(const std::string & stringToSign,
const std::string & privateKey)
{
typedef CryptoPP::SHA1 Hash;
size_t digestLen = Hash::DIGESTSIZE;
byte digest[digestLen];
CryptoPP::HMAC<Hash> hmac((byte *)privateKey.c_str(), privateKey.length());
hmac.CalculateDigest(digest,
(byte *)stringToSign.c_str(),
stringToSign.length());
// base64
char outBuf[256];
CryptoPP::Base64Encoder baseEncoder;
baseEncoder.Put(digest, digestLen);
baseEncoder.MessageEnd();
size_t got = baseEncoder.Get((byte *)outBuf, 256);
outBuf[got] = 0;
string base64digest(outBuf, outBuf + got - 1);
return base64digest;
}
std::string hmacSha256Base64(const std::string & stringToSign,
const std::string & privateKey)
{
typedef CryptoPP::SHA256 Hash;
size_t digestLen = Hash::DIGESTSIZE;
byte digest[digestLen];
CryptoPP::HMAC<Hash> hmac((byte *)privateKey.c_str(), privateKey.length());
hmac.CalculateDigest(digest,
(byte *)stringToSign.c_str(),
stringToSign.length());
// base64
char outBuf[256];
CryptoPP::Base64Encoder baseEncoder;
baseEncoder.Put(digest, digestLen);
baseEncoder.MessageEnd();
size_t got = baseEncoder.Get((byte *)outBuf, 256);
outBuf[got] = 0;
string base64digest(outBuf, outBuf + got - 1);
return base64digest;
}
} // namespace ML
| WitchKing-Helkar/rtbkit | jml/utils/hash.cc | C++ | apache-2.0 | 3,112 |
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package tests
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/httpstream"
remotecommandconsts "k8s.io/apimachinery/pkg/util/remotecommand"
restclient "k8s.io/client-go/rest"
remoteclient "k8s.io/client-go/tools/remotecommand"
"k8s.io/client-go/transport/spdy"
"k8s.io/kubernetes/pkg/api/legacyscheme"
api "k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/pkg/kubelet/server/remotecommand"
)
type fakeExecutor struct {
t *testing.T
testName string
errorData string
stdoutData string
stderrData string
expectStdin bool
stdinReceived bytes.Buffer
tty bool
messageCount int
command []string
exec bool
}
func (ex *fakeExecutor) ExecInContainer(name string, uid types.UID, container string, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool, resize <-chan remoteclient.TerminalSize, timeout time.Duration) error {
return ex.run(name, uid, container, cmd, in, out, err, tty)
}
func (ex *fakeExecutor) AttachContainer(name string, uid types.UID, container string, in io.Reader, out, err io.WriteCloser, tty bool, resize <-chan remoteclient.TerminalSize) error {
return ex.run(name, uid, container, nil, in, out, err, tty)
}
func (ex *fakeExecutor) run(name string, uid types.UID, container string, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool) error {
ex.command = cmd
ex.tty = tty
if e, a := "pod", name; e != a {
ex.t.Errorf("%s: pod: expected %q, got %q", ex.testName, e, a)
}
if e, a := "uid", uid; e != string(a) {
ex.t.Errorf("%s: uid: expected %q, got %q", ex.testName, e, a)
}
if ex.exec {
if e, a := "ls /", strings.Join(ex.command, " "); e != a {
ex.t.Errorf("%s: command: expected %q, got %q", ex.testName, e, a)
}
} else {
if len(ex.command) > 0 {
ex.t.Errorf("%s: command: expected nothing, got %v", ex.testName, ex.command)
}
}
if len(ex.errorData) > 0 {
return errors.New(ex.errorData)
}
if len(ex.stdoutData) > 0 {
for i := 0; i < ex.messageCount; i++ {
fmt.Fprint(out, ex.stdoutData)
}
}
if len(ex.stderrData) > 0 {
for i := 0; i < ex.messageCount; i++ {
fmt.Fprint(err, ex.stderrData)
}
}
if ex.expectStdin {
io.Copy(&ex.stdinReceived, in)
}
return nil
}
func fakeServer(t *testing.T, requestReceived chan struct{}, testName string, exec bool, stdinData, stdoutData, stderrData, errorData string, tty bool, messageCount int, serverProtocols []string) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
executor := &fakeExecutor{
t: t,
testName: testName,
errorData: errorData,
stdoutData: stdoutData,
stderrData: stderrData,
expectStdin: len(stdinData) > 0,
tty: tty,
messageCount: messageCount,
exec: exec,
}
opts, err := remotecommand.NewOptions(req)
require.NoError(t, err)
if exec {
cmd := req.URL.Query()[api.ExecCommandParam]
remotecommand.ServeExec(w, req, executor, "pod", "uid", "container", cmd, opts, 0, 10*time.Second, serverProtocols)
} else {
remotecommand.ServeAttach(w, req, executor, "pod", "uid", "container", opts, 0, 10*time.Second, serverProtocols)
}
if e, a := strings.Repeat(stdinData, messageCount), executor.stdinReceived.String(); e != a {
t.Errorf("%s: stdin: expected %q, got %q", testName, e, a)
}
close(requestReceived)
})
}
func TestStream(t *testing.T) {
testCases := []struct {
TestName string
Stdin string
Stdout string
Stderr string
Error string
Tty bool
MessageCount int
ClientProtocols []string
ServerProtocols []string
}{
{
TestName: "error",
Error: "bail",
Stdout: "a",
ClientProtocols: []string{remotecommandconsts.StreamProtocolV2Name},
ServerProtocols: []string{remotecommandconsts.StreamProtocolV2Name},
},
{
TestName: "in/out/err",
Stdin: "a",
Stdout: "b",
Stderr: "c",
MessageCount: 100,
ClientProtocols: []string{remotecommandconsts.StreamProtocolV2Name},
ServerProtocols: []string{remotecommandconsts.StreamProtocolV2Name},
},
{
TestName: "oversized stdin",
Stdin: strings.Repeat("a", 20*1024*1024),
Stdout: "b",
Stderr: "",
MessageCount: 1,
ClientProtocols: []string{remotecommandconsts.StreamProtocolV2Name},
ServerProtocols: []string{remotecommandconsts.StreamProtocolV2Name},
},
{
TestName: "in/out/tty",
Stdin: "a",
Stdout: "b",
Tty: true,
MessageCount: 100,
ClientProtocols: []string{remotecommandconsts.StreamProtocolV2Name},
ServerProtocols: []string{remotecommandconsts.StreamProtocolV2Name},
},
}
for _, testCase := range testCases {
for _, exec := range []bool{true, false} {
var name string
if exec {
name = testCase.TestName + " (exec)"
} else {
name = testCase.TestName + " (attach)"
}
var (
streamIn io.Reader
streamOut, streamErr io.Writer
)
localOut := &bytes.Buffer{}
localErr := &bytes.Buffer{}
requestReceived := make(chan struct{})
server := httptest.NewServer(fakeServer(t, requestReceived, name, exec, testCase.Stdin, testCase.Stdout, testCase.Stderr, testCase.Error, testCase.Tty, testCase.MessageCount, testCase.ServerProtocols))
url, _ := url.ParseRequestURI(server.URL)
config := restclient.ClientContentConfig{
GroupVersion: schema.GroupVersion{Group: "x"},
Negotiator: runtime.NewClientNegotiator(legacyscheme.Codecs.WithoutConversion(), schema.GroupVersion{Group: "x"}),
}
c, err := restclient.NewRESTClient(url, "", config, nil, nil)
if err != nil {
t.Fatalf("failed to create a client: %v", err)
}
req := c.Post().Resource("testing")
if exec {
req.Param("command", "ls")
req.Param("command", "/")
}
if len(testCase.Stdin) > 0 {
req.Param(api.ExecStdinParam, "1")
streamIn = strings.NewReader(strings.Repeat(testCase.Stdin, testCase.MessageCount))
}
if len(testCase.Stdout) > 0 {
req.Param(api.ExecStdoutParam, "1")
streamOut = localOut
}
if testCase.Tty {
req.Param(api.ExecTTYParam, "1")
} else if len(testCase.Stderr) > 0 {
req.Param(api.ExecStderrParam, "1")
streamErr = localErr
}
conf := &restclient.Config{
Host: server.URL,
}
transport, upgradeTransport, err := spdy.RoundTripperFor(conf)
if err != nil {
t.Errorf("%s: unexpected error: %v", name, err)
continue
}
e, err := remoteclient.NewSPDYExecutorForProtocols(transport, upgradeTransport, "POST", req.URL(), testCase.ClientProtocols...)
if err != nil {
t.Errorf("%s: unexpected error: %v", name, err)
continue
}
err = e.Stream(remoteclient.StreamOptions{
Stdin: streamIn,
Stdout: streamOut,
Stderr: streamErr,
Tty: testCase.Tty,
})
hasErr := err != nil
if len(testCase.Error) > 0 {
if !hasErr {
t.Errorf("%s: expected an error", name)
} else {
if e, a := testCase.Error, err.Error(); !strings.Contains(a, e) {
t.Errorf("%s: expected error stream read %q, got %q", name, e, a)
}
}
server.Close()
continue
}
if hasErr {
t.Errorf("%s: unexpected error: %v", name, err)
server.Close()
continue
}
if len(testCase.Stdout) > 0 {
if e, a := strings.Repeat(testCase.Stdout, testCase.MessageCount), localOut; e != a.String() {
t.Errorf("%s: expected stdout data %q, got %q", name, e, a)
}
}
if testCase.Stderr != "" {
if e, a := strings.Repeat(testCase.Stderr, testCase.MessageCount), localErr; e != a.String() {
t.Errorf("%s: expected stderr data %q, got %q", name, e, a)
}
}
select {
case <-requestReceived:
case <-time.After(time.Minute):
t.Errorf("%s: expected fakeServerInstance to receive request", name)
}
server.Close()
}
}
}
type fakeUpgrader struct {
req *http.Request
resp *http.Response
conn httpstream.Connection
err, connErr error
checkResponse bool
called bool
t *testing.T
}
func (u *fakeUpgrader) RoundTrip(req *http.Request) (*http.Response, error) {
u.called = true
u.req = req
return u.resp, u.err
}
func (u *fakeUpgrader) NewConnection(resp *http.Response) (httpstream.Connection, error) {
if u.checkResponse && u.resp != resp {
u.t.Errorf("response objects passed did not match: %#v", resp)
}
return u.conn, u.connErr
}
type fakeConnection struct {
httpstream.Connection
}
// Dial is the common functionality between any stream based upgrader, regardless of protocol.
// This method ensures that someone can use a generic stream executor without being dependent
// on the core Kube client config behavior.
func TestDial(t *testing.T) {
upgrader := &fakeUpgrader{
t: t,
checkResponse: true,
conn: &fakeConnection{},
resp: &http.Response{
StatusCode: http.StatusSwitchingProtocols,
Body: ioutil.NopCloser(&bytes.Buffer{}),
},
}
dialer := spdy.NewDialer(upgrader, &http.Client{Transport: upgrader}, "POST", &url.URL{Host: "something.com", Scheme: "https"})
conn, protocol, err := dialer.Dial("protocol1")
if err != nil {
t.Fatal(err)
}
if conn != upgrader.conn {
t.Errorf("unexpected connection: %#v", conn)
}
if !upgrader.called {
t.Errorf("request not called")
}
_ = protocol
}
| Miciah/origin | vendor/k8s.io/kubernetes/pkg/client/tests/remotecommand_test.go | GO | apache-2.0 | 10,299 |
(function() {
'use strict';
Polymer({
is: 'iron-overlay-backdrop',
properties: {
/**
* Returns true if the backdrop is opened.
*/
opened: {
reflectToAttribute: true,
type: Boolean,
value: false,
observer: '_openedChanged'
}
},
listeners: {
'transitionend': '_onTransitionend'
},
created: function() {
// Used to cancel previous requestAnimationFrame calls when opened changes.
this.__openedRaf = null;
},
attached: function() {
this.opened && this._openedChanged(this.opened);
},
/**
* Appends the backdrop to document body if needed.
*/
prepare: function() {
if (this.opened && !this.parentNode) {
Polymer.dom(document.body).appendChild(this);
}
},
/**
* Shows the backdrop.
*/
open: function() {
this.opened = true;
},
/**
* Hides the backdrop.
*/
close: function() {
this.opened = false;
},
/**
* Removes the backdrop from document body if needed.
*/
complete: function() {
if (!this.opened && this.parentNode === document.body) {
Polymer.dom(this.parentNode).removeChild(this);
}
},
_onTransitionend: function(event) {
if (event && event.target === this) {
this.complete();
}
},
/**
* @param {boolean} opened
* @private
*/
_openedChanged: function(opened) {
if (opened) {
// Auto-attach.
this.prepare();
} else {
// Animation might be disabled via the mixin or opacity custom property.
// If it is disabled in other ways, it's up to the user to call complete.
var cs = window.getComputedStyle(this);
if (cs.transitionDuration === '0s' || cs.opacity == 0) {
this.complete();
}
}
if (!this.isAttached) {
return;
}
// Always cancel previous requestAnimationFrame.
if (this.__openedRaf) {
window.cancelAnimationFrame(this.__openedRaf);
this.__openedRaf = null;
}
// Force relayout to ensure proper transitions.
this.scrollTop = this.scrollTop;
this.__openedRaf = window.requestAnimationFrame(function() {
this.__openedRaf = null;
this.toggleClass('opened', this.opened);
}.bind(this));
}
});
})(); | axinging/chromium-crosswalk | third_party/polymer/v1_0/components-chromium/iron-overlay-behavior/iron-overlay-backdrop-extracted.js | JavaScript | bsd-3-clause | 2,415 |
'use strict';
$(function () {
//Simple implementation of direct chat contact pane toggle (TEMPORARY)
$('[data-widget="chat-pane-toggle"]').click(function(){
$("#myDirectChat").toggleClass('direct-chat-contacts-open');
});
/* ChartJS
* -------
* Here we will create a few charts using ChartJS
*/
//-----------------------
//- MONTHLY SALES CHART -
//-----------------------
// Get context with jQuery - using jQuery's .get() method.
var salesChartCanvas = $("#salesChart").get(0).getContext("2d");
// This will get the first returned node in the jQuery collection.
var salesChart = new Chart(salesChartCanvas);
var salesChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "Electronics",
fillColor: "rgb(210, 214, 222)",
strokeColor: "rgb(210, 214, 222)",
pointColor: "rgb(210, 214, 222)",
pointStrokeColor: "#c1c7d1",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgb(220,220,220)",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "Digital Goods",
fillColor: "rgba(60,141,188,0.9)",
strokeColor: "rgba(60,141,188,0.8)",
pointColor: "#3b8bba",
pointStrokeColor: "rgba(60,141,188,1)",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(60,141,188,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var salesChartOptions = {
//Boolean - If we should show the scale at all
showScale: true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines: false,
//String - Colour of the grid lines
scaleGridLineColor: "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth: 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - Whether the line is curved between points
bezierCurve: true,
//Number - Tension of the bezier curve between points
bezierCurveTension: 0.3,
//Boolean - Whether to show a dot for each point
pointDot: false,
//Number - Radius of each point dot in pixels
pointDotRadius: 4,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth: 1,
//Number - amount extra to add to the radius to cater for hit detection outside the drawn point
pointHitDetectionRadius: 20,
//Boolean - Whether to show a stroke for datasets
datasetStroke: true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth: 2,
//Boolean - Whether to fill the dataset with a color
datasetFill: true,
//String - A legend template
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].lineColor%>\"></span><%=datasets[i].label%></li><%}%></ul>",
//Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: false,
//Boolean - whether to make the chart responsive to window resizing
responsive: true
};
//Create the line chart
salesChart.Line(salesChartData, salesChartOptions);
//---------------------------
//- END MONTHLY SALES CHART -
//---------------------------
//-------------
//- PIE CHART -
//-------------
// Get context with jQuery - using jQuery's .get() method.
var pieChartCanvas = $("#pieChart").get(0).getContext("2d");
var pieChart = new Chart(pieChartCanvas);
var PieData = [
{
value: 700,
color: "#f56954",
highlight: "#f56954",
label: "Chrome"
},
{
value: 500,
color: "#00a65a",
highlight: "#00a65a",
label: "IE"
},
{
value: 400,
color: "#f39c12",
highlight: "#f39c12",
label: "FireFox"
},
{
value: 600,
color: "#00c0ef",
highlight: "#00c0ef",
label: "Safari"
},
{
value: 300,
color: "#3c8dbc",
highlight: "#3c8dbc",
label: "Opera"
},
{
value: 100,
color: "#d2d6de",
highlight: "#d2d6de",
label: "Navigator"
}
];
var pieOptions = {
//Boolean - Whether we should show a stroke on each segment
segmentShowStroke: true,
//String - The colour of each segment stroke
segmentStrokeColor: "#fff",
//Number - The width of each segment stroke
segmentStrokeWidth: 2,
//Number - The percentage of the chart that we cut out of the middle
percentageInnerCutout: 50, // This is 0 for Pie charts
//Number - Amount of animation steps
animationSteps: 100,
//String - Animation easing effect
animationEasing: "easeOutBounce",
//Boolean - Whether we animate the rotation of the Doughnut
animateRotate: true,
//Boolean - Whether we animate scaling the Doughnut from the centre
animateScale: false,
//Boolean - whether to make the chart responsive to window resizing
responsive: true,
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: false,
//String - A legend template
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>",
//String - A tooltip template
tooltipTemplate: "<%=value %> <%=label%> users"
};
//Create pie or douhnut chart
// You can switch between pie and douhnut using the method below.
pieChart.Doughnut(PieData, pieOptions);
//-----------------
//- END PIE CHART -
//-----------------
/* jVector Maps
* ------------
* Create a world map with markers
*/
$('#world-map-markers').vectorMap({
map: 'world_mill_en',
normalizeFunction: 'polynomial',
hoverOpacity: 0.7,
hoverColor: false,
backgroundColor: 'transparent',
regionStyle: {
initial: {
fill: 'rgba(210, 214, 222, 1)',
"fill-opacity": 1,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 1
},
hover: {
"fill-opacity": 0.7,
cursor: 'pointer'
},
selected: {
fill: 'yellow'
},
selectedHover: {
}
},
markerStyle: {
initial: {
fill: '#00a65a',
stroke: '#111'
}
},
markers: [
{latLng: [41.90, 12.45], name: 'Vatican City'},
{latLng: [43.73, 7.41], name: 'Monaco'},
{latLng: [-0.52, 166.93], name: 'Nauru'},
{latLng: [-8.51, 179.21], name: 'Tuvalu'},
{latLng: [43.93, 12.46], name: 'San Marino'},
{latLng: [47.14, 9.52], name: 'Liechtenstein'},
{latLng: [7.11, 171.06], name: 'Marshall Islands'},
{latLng: [17.3, -62.73], name: 'Saint Kitts and Nevis'},
{latLng: [3.2, 73.22], name: 'Maldives'},
{latLng: [35.88, 14.5], name: 'Malta'},
{latLng: [12.05, -61.75], name: 'Grenada'},
{latLng: [13.16, -61.23], name: 'Saint Vincent and the Grenadines'},
{latLng: [13.16, -59.55], name: 'Barbados'},
{latLng: [17.11, -61.85], name: 'Antigua and Barbuda'},
{latLng: [-4.61, 55.45], name: 'Seychelles'},
{latLng: [7.35, 134.46], name: 'Palau'},
{latLng: [42.5, 1.51], name: 'Andorra'},
{latLng: [14.01, -60.98], name: 'Saint Lucia'},
{latLng: [6.91, 158.18], name: 'Federated States of Micronesia'},
{latLng: [1.3, 103.8], name: 'Singapore'},
{latLng: [1.46, 173.03], name: 'Kiribati'},
{latLng: [-21.13, -175.2], name: 'Tonga'},
{latLng: [15.3, -61.38], name: 'Dominica'},
{latLng: [-20.2, 57.5], name: 'Mauritius'},
{latLng: [26.02, 50.55], name: 'Bahrain'},
{latLng: [0.33, 6.73], name: 'São Tomé and Príncipe'}
]
});
/* SPARKLINE CHARTS
* ----------------
* Create a inline charts with spark line
*/
//-----------------
//- SPARKLINE BAR -
//-----------------
$('.sparkbar').each(function () {
var $this = $(this);
$this.sparkline('html', {
type: 'bar',
height: $this.data('height') ? $this.data('height') : '30',
barColor: $this.data('color')
});
});
//-----------------
//- SPARKLINE PIE -
//-----------------
$('.sparkpie').each(function () {
var $this = $(this);
$this.sparkline('html', {
type: 'pie',
height: $this.data('height') ? $this.data('height') : '90',
sliceColors: $this.data('color')
});
});
//------------------
//- SPARKLINE LINE -
//------------------
$('.sparkline').each(function () {
var $this = $(this);
$this.sparkline('html', {
type: 'line',
height: $this.data('height') ? $this.data('height') : '90',
width: '100%',
lineColor: $this.data('linecolor'),
fillColor: $this.data('fillcolor'),
spotColor: $this.data('spotcolor')
});
});
}); | johan--/ember-admin-dashboards | vendor/AdminLTE/dist/js/pages/dashboard2.js | JavaScript | mit | 9,137 |
/*
* Copyright (c) 1996, 2010, 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 sun.awt.windows;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.peer.*;
import java.beans.*;
import java.lang.reflect.*;
import java.util.*;
import java.util.List;
import sun.util.logging.PlatformLogger;
import sun.awt.*;
import sun.java2d.pipe.Region;
public class WWindowPeer extends WPanelPeer implements WindowPeer,
DisplayChangedListener
{
private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.windows.WWindowPeer");
private static final PlatformLogger screenLog = PlatformLogger.getLogger("sun.awt.windows.screen.WWindowPeer");
// we can't use WDialogPeer as blocker may be an instance of WPrintDialogPeer that
// extends WWindowPeer, not WDialogPeer
private WWindowPeer modalBlocker = null;
private boolean isOpaque;
private TranslucentWindowPainter painter;
/*
* A key used for storing a list of active windows in AppContext. The value
* is a list of windows, sorted by the time of activation: later a window is
* activated, greater its index is in the list.
*/
private final static StringBuffer ACTIVE_WINDOWS_KEY =
new StringBuffer("active_windows_list");
/*
* Listener for 'activeWindow' KFM property changes. It is added to each
* AppContext KFM. See ActiveWindowListener inner class below.
*/
private static PropertyChangeListener activeWindowListener =
new ActiveWindowListener();
/*
* The object is a listener for the AppContext.GUI_DISPOSED property.
*/
private final static PropertyChangeListener guiDisposedListener =
new GuiDisposedListener();
/*
* Called (on the Toolkit thread) before the appropriate
* WindowStateEvent is posted to the EventQueue.
*/
private WindowListener windowListener;
/**
* Initialize JNI field IDs
*/
private static native void initIDs();
static {
initIDs();
}
// WComponentPeer overrides
protected void disposeImpl() {
AppContext appContext = SunToolkit.targetToAppContext(target);
synchronized (appContext) {
List<WWindowPeer> l = (List<WWindowPeer>)appContext.get(ACTIVE_WINDOWS_KEY);
if (l != null) {
l.remove(this);
}
}
// Remove ourself from the Map of DisplayChangeListeners
GraphicsConfiguration gc = getGraphicsConfiguration();
((Win32GraphicsDevice)gc.getDevice()).removeDisplayChangedListener(this);
synchronized (getStateLock()) {
TranslucentWindowPainter currentPainter = painter;
if (currentPainter != null) {
currentPainter.flush();
// don't set the current one to null here; reduces the chances of
// MT issues (like NPEs)
}
}
super.disposeImpl();
}
// WindowPeer implementation
public void toFront() {
updateFocusableWindowState();
_toFront();
}
native void _toFront();
public native void toBack();
public native void setAlwaysOnTopNative(boolean value);
public void setAlwaysOnTop(boolean value) {
if ((value && ((Window)target).isVisible()) || !value) {
setAlwaysOnTopNative(value);
}
}
public void updateFocusableWindowState() {
setFocusableWindow(((Window)target).isFocusableWindow());
}
native void setFocusableWindow(boolean value);
// FramePeer & DialogPeer partial shared implementation
public void setTitle(String title) {
// allow a null title to pass as an empty string.
if (title == null) {
title = "";
}
_setTitle(title);
}
native void _setTitle(String title);
public void setResizable(boolean resizable) {
_setResizable(resizable);
}
public native void _setResizable(boolean resizable);
// Toolkit & peer internals
WWindowPeer(Window target) {
super(target);
}
void initialize() {
super.initialize();
updateInsets(insets_);
Font f = ((Window)target).getFont();
if (f == null) {
f = defaultFont;
((Window)target).setFont(f);
setFont(f);
}
// Express our interest in display changes
GraphicsConfiguration gc = getGraphicsConfiguration();
((Win32GraphicsDevice)gc.getDevice()).addDisplayChangedListener(this);
initActiveWindowsTracking((Window)target);
updateIconImages();
Shape shape = ((Window)target).getShape();
if (shape != null) {
applyShape(Region.getInstance(shape, null));
}
float opacity = ((Window)target).getOpacity();
if (opacity < 1.0f) {
setOpacity(opacity);
}
synchronized (getStateLock()) {
// default value of a boolean field is 'false', so set isOpaque to
// true here explicitly
this.isOpaque = true;
setOpaque(((Window)target).isOpaque());
}
}
native void createAwtWindow(WComponentPeer parent);
private volatile Window.Type windowType = Window.Type.NORMAL;
// This method must be called for Window, Dialog, and Frame before creating
// the hwnd
void preCreate(WComponentPeer parent) {
windowType = ((Window)target).getType();
}
void create(WComponentPeer parent) {
preCreate(parent);
createAwtWindow(parent);
}
// should be overriden in WDialogPeer
protected void realShow() {
super.show();
}
public void show() {
updateFocusableWindowState();
boolean alwaysOnTop = ((Window)target).isAlwaysOnTop();
// Fix for 4868278.
// If we create a window with a specific GraphicsConfig, and then move it with
// setLocation() or setBounds() to another one before its peer has been created,
// then calling Window.getGraphicsConfig() returns wrong config. That may lead
// to some problems like wrong-placed tooltips. It is caused by calling
// super.displayChanged() in WWindowPeer.displayChanged() regardless of whether
// GraphicsDevice was really changed, or not. So we need to track it here.
updateGC();
realShow();
updateMinimumSize();
if (((Window)target).isAlwaysOnTopSupported() && alwaysOnTop) {
setAlwaysOnTop(alwaysOnTop);
}
synchronized (getStateLock()) {
if (!isOpaque) {
updateWindow(true);
}
}
}
// Synchronize the insets members (here & in helper) with actual window
// state.
native void updateInsets(Insets i);
static native int getSysMinWidth();
static native int getSysMinHeight();
static native int getSysIconWidth();
static native int getSysIconHeight();
static native int getSysSmIconWidth();
static native int getSysSmIconHeight();
/**windows/classes/sun/awt/windows/
* Creates native icon from specified raster data and updates
* icon for window and all descendant windows that inherit icon.
* Raster data should be passed in the ARGB form.
* Note that raster data format was changed to provide support
* for XP icons with alpha-channel
*/
native void setIconImagesData(int[] iconRaster, int w, int h,
int[] smallIconRaster, int smw, int smh);
synchronized native void reshapeFrame(int x, int y, int width, int height);
public boolean requestWindowFocus(CausedFocusEvent.Cause cause) {
if (!focusAllowedFor()) {
return false;
}
return requestWindowFocus(cause == CausedFocusEvent.Cause.MOUSE_EVENT);
}
public native boolean requestWindowFocus(boolean isMouseEventCause);
public boolean focusAllowedFor() {
Window window = (Window)this.target;
if (!window.isVisible() ||
!window.isEnabled() ||
!window.isFocusableWindow())
{
return false;
}
if (isModalBlocked()) {
return false;
}
return true;
}
public void hide() {
WindowListener listener = windowListener;
if (listener != null) {
// We're not getting WINDOW_CLOSING from the native code when hiding
// the window programmatically. So, create it and notify the listener.
listener.windowClosing(new WindowEvent((Window)target, WindowEvent.WINDOW_CLOSING));
}
super.hide();
}
// WARNING: it's called on the Toolkit thread!
void preprocessPostEvent(AWTEvent event) {
if (event instanceof WindowEvent) {
WindowListener listener = windowListener;
if (listener != null) {
switch(event.getID()) {
case WindowEvent.WINDOW_CLOSING:
listener.windowClosing((WindowEvent)event);
break;
case WindowEvent.WINDOW_ICONIFIED:
listener.windowIconified((WindowEvent)event);
break;
}
}
}
}
synchronized void addWindowListener(WindowListener l) {
windowListener = AWTEventMulticaster.add(windowListener, l);
}
synchronized void removeWindowListener(WindowListener l) {
windowListener = AWTEventMulticaster.remove(windowListener, l);
}
public void updateMinimumSize() {
Dimension minimumSize = null;
if (((Component)target).isMinimumSizeSet()) {
minimumSize = ((Component)target).getMinimumSize();
}
if (minimumSize != null) {
int msw = getSysMinWidth();
int msh = getSysMinHeight();
int w = (minimumSize.width >= msw) ? minimumSize.width : msw;
int h = (minimumSize.height >= msh) ? minimumSize.height : msh;
setMinSize(w, h);
} else {
setMinSize(0, 0);
}
}
public void updateIconImages() {
java.util.List<Image> imageList = ((Window)target).getIconImages();
if (imageList == null || imageList.size() == 0) {
setIconImagesData(null, 0, 0, null, 0, 0);
} else {
int w = getSysIconWidth();
int h = getSysIconHeight();
int smw = getSysSmIconWidth();
int smh = getSysSmIconHeight();
DataBufferInt iconData = SunToolkit.getScaledIconData(imageList,
w, h);
DataBufferInt iconSmData = SunToolkit.getScaledIconData(imageList,
smw, smh);
if (iconData != null && iconSmData != null) {
setIconImagesData(iconData.getData(), w, h,
iconSmData.getData(), smw, smh);
} else {
setIconImagesData(null, 0, 0, null, 0, 0);
}
}
}
native void setMinSize(int width, int height);
/*
* ---- MODALITY SUPPORT ----
*/
/**
* Some modality-related code here because WFileDialogPeer, WPrintDialogPeer and
* WPageDialogPeer are descendants of WWindowPeer, not WDialogPeer
*/
public boolean isModalBlocked() {
return modalBlocker != null;
}
public void setModalBlocked(Dialog dialog, boolean blocked) {
synchronized (((Component)getTarget()).getTreeLock()) // State lock should always be after awtLock
{
// use WWindowPeer instead of WDialogPeer because of FileDialogs and PrintDialogs
WWindowPeer blockerPeer = (WWindowPeer)dialog.getPeer();
if (blocked)
{
modalBlocker = blockerPeer;
// handle native dialogs separately, as they may have not
// got HWND yet; modalEnable/modalDisable is called from
// their setHWnd() methods
if (blockerPeer instanceof WFileDialogPeer) {
((WFileDialogPeer)blockerPeer).blockWindow(this);
} else if (blockerPeer instanceof WPrintDialogPeer) {
((WPrintDialogPeer)blockerPeer).blockWindow(this);
} else {
modalDisable(dialog, blockerPeer.getHWnd());
}
} else {
modalBlocker = null;
if (blockerPeer instanceof WFileDialogPeer) {
((WFileDialogPeer)blockerPeer).unblockWindow(this);
} else if (blockerPeer instanceof WPrintDialogPeer) {
((WPrintDialogPeer)blockerPeer).unblockWindow(this);
} else {
modalEnable(dialog);
}
}
}
}
native void modalDisable(Dialog blocker, long blockerHWnd);
native void modalEnable(Dialog blocker);
/*
* Returns all the ever active windows from the current AppContext.
* The list is sorted by the time of activation, so the latest
* active window is always at the end.
*/
public static long[] getActiveWindowHandles() {
AppContext appContext = AppContext.getAppContext();
synchronized (appContext) {
List<WWindowPeer> l = (List<WWindowPeer>)appContext.get(ACTIVE_WINDOWS_KEY);
if (l == null) {
return null;
}
long[] result = new long[l.size()];
for (int j = 0; j < l.size(); j++) {
result[j] = l.get(j).getHWnd();
}
return result;
}
}
/*
* ----DISPLAY CHANGE SUPPORT----
*/
/*
* Called from native code when we have been dragged onto another screen.
*/
void draggedToNewScreen() {
SunToolkit.executeOnEventHandlerThread((Component)target,new Runnable()
{
public void run() {
displayChanged();
}
});
}
public void updateGC() {
int scrn = getScreenImOn();
if (screenLog.isLoggable(PlatformLogger.FINER)) {
log.finer("Screen number: " + scrn);
}
// get current GD
Win32GraphicsDevice oldDev = (Win32GraphicsDevice)winGraphicsConfig
.getDevice();
Win32GraphicsDevice newDev;
GraphicsDevice devs[] = GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getScreenDevices();
// Occasionally during device addition/removal getScreenImOn can return
// a non-existing screen number. Use the default device in this case.
if (scrn >= devs.length) {
newDev = (Win32GraphicsDevice)GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice();
} else {
newDev = (Win32GraphicsDevice)devs[scrn];
}
// Set winGraphicsConfig to the default GC for the monitor this Window
// is now mostly on.
winGraphicsConfig = (Win32GraphicsConfig)newDev
.getDefaultConfiguration();
if (screenLog.isLoggable(PlatformLogger.FINE)) {
if (winGraphicsConfig == null) {
screenLog.fine("Assertion (winGraphicsConfig != null) failed");
}
}
// if on a different display, take off old GD and put on new GD
if (oldDev != newDev) {
oldDev.removeDisplayChangedListener(this);
newDev.addDisplayChangedListener(this);
}
AWTAccessor.getComponentAccessor().
setGraphicsConfiguration((Component)target, winGraphicsConfig);
}
/**
* From the DisplayChangedListener interface.
*
* This method handles a display change - either when the display settings
* are changed, or when the window has been dragged onto a different
* display.
* Called after a change in the display mode. This event
* triggers replacing the surfaceData object (since that object
* reflects the current display depth information, which has
* just changed).
*/
public void displayChanged() {
updateGC();
}
/**
* Part of the DisplayChangedListener interface: components
* do not need to react to this event
*/
public void paletteChanged() {
}
private native int getScreenImOn();
// Used in Win32GraphicsDevice.
public final native void setFullScreenExclusiveModeState(boolean state);
/*
* ----END DISPLAY CHANGE SUPPORT----
*/
public void grab() {
nativeGrab();
}
public void ungrab() {
nativeUngrab();
}
private native void nativeGrab();
private native void nativeUngrab();
private final boolean hasWarningWindow() {
return ((Window)target).getWarningString() != null;
}
boolean isTargetUndecorated() {
return true;
}
// These are the peer bounds. They get updated at:
// 1. the WWindowPeer.setBounds() method.
// 2. the native code (on WM_SIZE/WM_MOVE)
private volatile int sysX = 0;
private volatile int sysY = 0;
private volatile int sysW = 0;
private volatile int sysH = 0;
public native void repositionSecurityWarning();
@Override
public void setBounds(int x, int y, int width, int height, int op) {
sysX = x;
sysY = y;
sysW = width;
sysH = height;
super.setBounds(x, y, width, height, op);
}
@Override
public void print(Graphics g) {
// We assume we print the whole frame,
// so we expect no clip was set previously
Shape shape = AWTAccessor.getWindowAccessor().getShape((Window)target);
if (shape != null) {
g.setClip(shape);
}
super.print(g);
}
private void replaceSurfaceDataRecursively(Component c) {
if (c instanceof Container) {
for (Component child : ((Container)c).getComponents()) {
replaceSurfaceDataRecursively(child);
}
}
ComponentPeer cp = c.getPeer();
if (cp instanceof WComponentPeer) {
((WComponentPeer)cp).replaceSurfaceDataLater();
}
}
public final Graphics getTranslucentGraphics() {
synchronized (getStateLock()) {
return isOpaque ? null : painter.getBackBuffer(false).getGraphics();
}
}
@Override
public void setBackground(Color c) {
super.setBackground(c);
synchronized (getStateLock()) {
if (!isOpaque && ((Window)target).isVisible()) {
updateWindow(true);
}
}
}
private native void setOpacity(int iOpacity);
private float opacity = 1.0f;
public void setOpacity(float opacity) {
if (!((SunToolkit)((Window)target).getToolkit()).
isWindowOpacitySupported())
{
return;
}
if (opacity < 0.0f || opacity > 1.0f) {
throw new IllegalArgumentException(
"The value of opacity should be in the range [0.0f .. 1.0f].");
}
if (((this.opacity == 1.0f && opacity < 1.0f) ||
(this.opacity < 1.0f && opacity == 1.0f)) &&
!Win32GraphicsEnvironment.isVistaOS())
{
// non-Vista OS: only replace the surface data if opacity status
// changed (see WComponentPeer.isAccelCapable() for more)
replaceSurfaceDataRecursively((Component)getTarget());
}
this.opacity = opacity;
final int maxOpacity = 0xff;
int iOpacity = (int)(opacity * maxOpacity);
if (iOpacity < 0) {
iOpacity = 0;
}
if (iOpacity > maxOpacity) {
iOpacity = maxOpacity;
}
setOpacity(iOpacity);
synchronized (getStateLock()) {
if (!isOpaque && ((Window)target).isVisible()) {
updateWindow(true);
}
}
}
private native void setOpaqueImpl(boolean isOpaque);
public void setOpaque(boolean isOpaque) {
synchronized (getStateLock()) {
if (this.isOpaque == isOpaque) {
return;
}
}
Window target = (Window)getTarget();
if (!isOpaque) {
SunToolkit sunToolkit = (SunToolkit)target.getToolkit();
if (!sunToolkit.isWindowTranslucencySupported() ||
!sunToolkit.isTranslucencyCapable(target.getGraphicsConfiguration()))
{
return;
}
}
boolean isVistaOS = Win32GraphicsEnvironment.isVistaOS();
if (this.isOpaque != isOpaque && !isVistaOS) {
// non-Vista OS: only replace the surface data if the opacity
// status changed (see WComponentPeer.isAccelCapable() for more)
replaceSurfaceDataRecursively(target);
}
synchronized (getStateLock()) {
this.isOpaque = isOpaque;
setOpaqueImpl(isOpaque);
if (isOpaque) {
TranslucentWindowPainter currentPainter = painter;
if (currentPainter != null) {
currentPainter.flush();
painter = null;
}
} else {
painter = TranslucentWindowPainter.createInstance(this);
}
}
if (isVistaOS) {
// On Vista: setting the window non-opaque makes the window look
// rectangular, though still catching the mouse clicks within
// its shape only. To restore the correct visual appearance
// of the window (i.e. w/ the correct shape) we have to reset
// the shape.
Shape shape = ((Window)target).getShape();
if (shape != null) {
((Window)target).setShape(shape);
}
}
if (((Window)target).isVisible()) {
updateWindow(true);
}
}
public native void updateWindowImpl(int[] data, int width, int height);
public void updateWindow() {
updateWindow(false);
}
private void updateWindow(boolean repaint) {
Window w = (Window)target;
synchronized (getStateLock()) {
if (isOpaque || !w.isVisible() ||
(w.getWidth() <= 0) || (w.getHeight() <= 0))
{
return;
}
TranslucentWindowPainter currentPainter = painter;
if (currentPainter != null) {
currentPainter.updateWindow(repaint);
} else if (log.isLoggable(PlatformLogger.FINER)) {
log.finer("Translucent window painter is null in updateWindow");
}
}
}
/*
* The method maps the list of the active windows to the window's AppContext,
* then the method registers ActiveWindowListener, GuiDisposedListener listeners;
* it executes the initilialization only once per AppContext.
*/
private static void initActiveWindowsTracking(Window w) {
AppContext appContext = AppContext.getAppContext();
synchronized (appContext) {
List<WWindowPeer> l = (List<WWindowPeer>)appContext.get(ACTIVE_WINDOWS_KEY);
if (l == null) {
l = new LinkedList<WWindowPeer>();
appContext.put(ACTIVE_WINDOWS_KEY, l);
appContext.addPropertyChangeListener(AppContext.GUI_DISPOSED, guiDisposedListener);
KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
kfm.addPropertyChangeListener("activeWindow", activeWindowListener);
}
}
}
/*
* The GuiDisposedListener class listens for the AppContext.GUI_DISPOSED property,
* it removes the list of the active windows from the disposed AppContext and
* unregisters ActiveWindowListener listener.
*/
private static class GuiDisposedListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent e) {
boolean isDisposed = (Boolean)e.getNewValue();
if (isDisposed != true) {
if (log.isLoggable(PlatformLogger.FINE)) {
log.fine(" Assertion (newValue != true) failed for AppContext.GUI_DISPOSED ");
}
}
AppContext appContext = AppContext.getAppContext();
synchronized (appContext) {
appContext.remove(ACTIVE_WINDOWS_KEY);
appContext.removePropertyChangeListener(AppContext.GUI_DISPOSED, this);
KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
kfm.removePropertyChangeListener("activeWindow", activeWindowListener);
}
}
}
/*
* Static inner class, listens for 'activeWindow' KFM property changes and
* updates the list of active windows per AppContext, so the latest active
* window is always at the end of the list. The list is stored in AppContext.
*/
private static class ActiveWindowListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent e) {
Window w = (Window)e.getNewValue();
if (w == null) {
return;
}
AppContext appContext = SunToolkit.targetToAppContext(w);
synchronized (appContext) {
WWindowPeer wp = (WWindowPeer)w.getPeer();
// add/move wp to the end of the list
List<WWindowPeer> l = (List<WWindowPeer>)appContext.get(ACTIVE_WINDOWS_KEY);
if (l != null) {
l.remove(wp);
l.add(wp);
}
}
}
}
}
| rokn/Count_Words_2015 | testing/openjdk/jdk/src/windows/classes/sun/awt/windows/WWindowPeer.java | Java | mit | 27,167 |
/*!
* Bootstrap v3.2.0 (http://getbootstrap.com)
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery') }
/* ========================================================================
* Bootstrap: transition.js v3.2.0
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
/* ========================================================================
* Bootstrap: alert.js v3.2.0
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.2.0'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.hasClass('alert') ? $this : $this.parent()
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: button.js v3.2.0
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.VERSION = '3.2.0'
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function (state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state = state + 'Text'
if (data.resetText == null) $el.data('resetText', $el[val]())
$el[val](data[state] == null ? this.options[state] : data[state])
// push to event loop to allow forms to submit
setTimeout($.proxy(function () {
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d)
}
}, this), 0)
}
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
else $parent.find('.active').removeClass('active')
}
if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
}
if (changed) this.$element.toggleClass('active')
}
// BUTTON PLUGIN DEFINITION
// ========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
var old = $.fn.button
$.fn.button = Plugin
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function () {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document)
.on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
Plugin.call($btn, 'toggle')
e.preventDefault()
})
.on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
$(e.target).closest('.btn').toggleClass('focus', e.type == 'focus')
})
}(jQuery);
/* ========================================================================
* Bootstrap: carousel.js v3.2.0
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function (element, options) {
this.$element = $(element).on('keydown.bs.carousel', $.proxy(this.keydown, this))
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused =
this.sliding =
this.interval =
this.$active =
this.$items = null
this.options.pause == 'hover' && this.$element
.on('mouseenter.bs.carousel', $.proxy(this.pause, this))
.on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
}
Carousel.VERSION = '3.2.0'
Carousel.TRANSITION_DURATION = 600
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true
}
Carousel.prototype.keydown = function (e) {
switch (e.which) {
case 37: this.prev(); break
case 39: this.next(); break
default: return
}
e.preventDefault()
}
Carousel.prototype.cycle = function (e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getItemIndex = function (item) {
this.$items = item.parent().children('.item')
return this.$items.index(item || this.$active)
}
Carousel.prototype.getItemForDirection = function (direction, active) {
var delta = direction == 'prev' ? -1 : 1
var activeIndex = this.getItemIndex(active)
var itemIndex = (activeIndex + delta) % this.$items.length
return this.$items.eq(itemIndex)
}
Carousel.prototype.to = function (pos) {
var that = this
var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
}
Carousel.prototype.pause = function (e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function () {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function () {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function (type, next) {
var $active = this.$element.find('.item.active')
var $next = next || this.getItemForDirection(type, $active)
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var fallback = type == 'next' ? 'first' : 'last'
var that = this
if (!$next.length) {
if (!this.options.wrap) return
$next = this.$element.find('.item')[fallback]()
}
if ($next.hasClass('active')) return (this.sliding = false)
var relatedTarget = $next[0]
var slideEvent = $.Event('slide.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
})
this.$element.trigger(slideEvent)
if (slideEvent.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator && $nextIndicator.addClass('active')
}
var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one('bsTransitionEnd', function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () {
that.$element.trigger(slidEvent)
}, 0)
})
.emulateTransitionEnd(Carousel.TRANSITION_DURATION)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger(slidEvent)
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
var old = $.fn.carousel
$.fn.carousel = Plugin
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function () {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
$(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
var href
var $this = $(this)
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
if (!$target.hasClass('carousel')) return
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
Plugin.call($target, options)
if (slideIndex) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
})
$(window).on('load', function () {
$('[data-ride="carousel"]').each(function () {
var $carousel = $(this)
Plugin.call($carousel, $carousel.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.2.0
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.transitioning = null
if (this.options.parent) this.$parent = $(this.options.parent)
if (this.options.toggle) this.toggle()
}
Collapse.VERSION = '3.2.0'
Collapse.TRANSITION_DURATION = 350
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function () {
if (this.transitioning || this.$element.hasClass('in')) return
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var actives = this.$parent && this.$parent.find('> .panel > .in')
if (actives && actives.length) {
var hasData = actives.data('bs.collapse')
if (hasData && hasData.transitioning) return
Plugin.call(actives, 'hide')
hasData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')[dimension](0)
this.transitioning = 1
var complete = function () {
this.$element
.removeClass('collapsing')
.addClass('collapse in')[dimension]('')
this.transitioning = 0
this.$element
.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function () {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse in')
this.transitioning = 1
var complete = function () {
this.transitioning = 0
this.$element
.trigger('hidden.bs.collapse')
.removeClass('collapsing')
.addClass('collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element
[dimension](0)
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)
}
Collapse.prototype.toggle = function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && option == 'show') option = !option
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.collapse
$.fn.collapse = Plugin
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
var href
var $this = $(this)
var target = $this.attr('data-target')
|| e.preventDefault()
|| (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
var $target = $(target)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
var parent = $this.attr('data-parent')
var $parent = parent && $(parent)
if (!data || !data.transitioning) {
if ($parent) $parent.find('[data-toggle="collapse"][data-parent="' + parent + '"]').not($this).addClass('collapsed')
$this.toggleClass('collapsed', $target.hasClass('in'))
}
Plugin.call($target, option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: dropdown.js v3.2.0
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle="dropdown"]'
var Dropdown = function (element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.VERSION = '3.2.0'
Dropdown.prototype.toggle = function (e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
}
var relatedTarget = { relatedTarget: this }
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this
.trigger('focus')
.attr('aria-expanded', 'true')
$parent
.toggleClass('open')
.trigger('shown.bs.dropdown', relatedTarget)
}
return false
}
Dropdown.prototype.keydown = function (e) {
if (!/(38|40|27)/.test(e.keyCode)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if (!isActive || (isActive && e.keyCode == 27)) {
if (e.which == 27) $parent.find(toggle).trigger('focus')
return $this.trigger('click')
}
var desc = ' li:not(.divider):visible a'
var $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc)
if (!$items.length) return
var index = $items.index($items.filter(':focus'))
if (e.keyCode == 38 && index > 0) index-- // up
if (e.keyCode == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).trigger('focus')
}
function clearMenus(e) {
if (e && e.which === 3) return
$(backdrop).remove()
$(toggle).each(function () {
var $this = $(this)
var $parent = getParent($this)
var relatedTarget = { relatedTarget: this }
if (!$parent.hasClass('open')) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this.attr('aria-expanded', 'false')
$parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget)
})
}
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.dropdown
$.fn.dropdown = Plugin
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function () {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle + ', [role="menu"], [role="listbox"]', Dropdown.prototype.keydown)
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.2.0
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$backdrop =
this.isShown = null
this.scrollbarWidth = 0
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.2.0'
Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.$body.addClass('modal-open')
this.setScrollbar()
this.escape()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element
.addClass('in')
.attr('aria-hidden', false)
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$element.find('.modal-dialog') // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.$body.removeClass('modal-open')
this.resetScrollbar()
this.escape()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.attr('aria-hidden', true)
.off('click.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
.appendTo(this.$body)
this.$element.on('mousedown.dismiss.bs.modal', $.proxy(function (e) {
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus.call(this.$element[0])
: this.hide.call(this)
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function () {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callbackRemove()
} else if (callback) {
callback()
}
}
Modal.prototype.checkScrollbar = function () {
if (document.body.clientWidth >= window.innerWidth) return
this.scrollbarWidth = this.scrollbarWidth || this.measureScrollbar()
}
Modal.prototype.setScrollbar = function () {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
if (this.scrollbarWidth) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function () {
this.$body.css('padding-right', '')
}
Modal.prototype.measureScrollbar = function () { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
/* ========================================================================
* Bootstrap: tooltip.js v3.2.0
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function (element, options) {
this.type =
this.options =
this.enabled =
this.timeout =
this.hoverState =
this.$element = null
this.init('tooltip', element, options)
}
Tooltip.VERSION = '3.2.0'
Tooltip.TRANSITION_DURATION = 150
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false,
viewport: {
selector: 'body',
padding: 0
}
}
Tooltip.prototype.init = function (type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.$viewport = this.options.viewport && $(this.options.viewport.selector || this.options.viewport)
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function () {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function (options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function () {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function (key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function () {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.leave = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function () {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function () {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
var inDom = $.contains(document.documentElement, this.$element[0])
if (e.isDefaultPrevented() || !inDom) return
var that = this
var $tip = this.tip()
var tipId = this.getUID(this.type)
this.setContent()
$tip.attr('id', tipId)
this.$element.attr('aria-describedby', tipId)
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({ top: 0, left: 0, display: 'block' })
.addClass(placement)
.data('bs.' + this.type, this)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var orgPlacement = placement
var $parent = this.$element.parent()
var parentDim = this.getPosition($parent)
placement = placement == 'bottom' && pos.top + pos.height + actualHeight - parentDim.scroll > parentDim.height ? 'top' :
placement == 'top' && pos.top - parentDim.scroll - actualHeight < 0 ? 'bottom' :
placement == 'right' && pos.right + actualWidth > parentDim.width ? 'left' :
placement == 'left' && pos.left - actualWidth < parentDim.left ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
var complete = function () {
that.$element.trigger('shown.bs.' + that.type)
that.hoverState = null
}
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
}
}
Tooltip.prototype.applyPlacement = function (offset, placement) {
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top = offset.top + marginTop
offset.left = offset.left + marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function (props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
offset.top = offset.top + height - actualHeight
}
var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
if (delta.left) offset.left += delta.left
else offset.top += delta.top
var arrowDelta = delta.left ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
var arrowPosition = delta.left ? 'left' : 'top'
var arrowOffsetPosition = delta.left ? 'offsetWidth' : 'offsetHeight'
$tip.offset(offset)
this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], arrowPosition)
}
Tooltip.prototype.replaceArrow = function (delta, dimension, position) {
this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + '%') : '')
}
Tooltip.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function () {
var that = this
var $tip = this.tip()
var e = $.Event('hide.bs.' + this.type)
this.$element.removeAttr('aria-describedby')
function complete() {
if (that.hoverState != 'in') $tip.detach()
that.$element.trigger('hidden.bs.' + that.type)
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
this.hoverState = null
return this
}
Tooltip.prototype.fixTitle = function () {
var $e = this.$element
if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function () {
return this.getTitle()
}
Tooltip.prototype.getPosition = function ($element) {
$element = $element || this.$element
var el = $element[0]
var isBody = el.tagName == 'BODY'
var isSvg = window.SVGElement && el instanceof window.SVGElement
var elRect = el.getBoundingClientRect ? el.getBoundingClientRect() : null
var elOffset = isBody ? { top: 0, left: 0 } : $element.offset()
var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
var outerDims = isSvg ? {} : {
width: isBody ? $(window).width() : $element.outerWidth(),
height: isBody ? $(window).height() : $element.outerHeight()
}
return $.extend({}, elRect, scroll, outerDims, elOffset)
}
Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
}
Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
var delta = { top: 0, left: 0 }
if (!this.$viewport) return delta
var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
var viewportDimensions = this.getPosition(this.$viewport)
if (/right|left/.test(placement)) {
var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if (topEdgeOffset < viewportDimensions.top) { // top overflow
delta.top = viewportDimensions.top - topEdgeOffset
} else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
}
} else {
var leftEdgeOffset = pos.left - viewportPadding
var rightEdgeOffset = pos.left + viewportPadding + actualWidth
if (leftEdgeOffset < viewportDimensions.left) { // left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
} else if (rightEdgeOffset > viewportDimensions.width) { // right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
}
}
return delta
}
Tooltip.prototype.getTitle = function () {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.getUID = function (prefix) {
do prefix += ~~(Math.random() * 1000000)
while (document.getElementById(prefix))
return prefix
}
Tooltip.prototype.tip = function () {
return (this.$tip = this.$tip || $(this.options.template))
}
Tooltip.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
}
Tooltip.prototype.validate = function () {
if (!this.$element[0].parentNode) {
this.hide()
this.$element = null
this.options = null
}
}
Tooltip.prototype.enable = function () {
this.enabled = true
}
Tooltip.prototype.disable = function () {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function () {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function (e) {
var self = this
if (e) {
self = $(e.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(e.currentTarget, this.getDelegateOptions())
$(e.currentTarget).data('bs.' + this.type, self)
}
}
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
Tooltip.prototype.destroy = function () {
clearTimeout(this.timeout)
this.hide().$element.off('.' + this.type).removeData('bs.' + this.type)
}
// TOOLTIP PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && option == 'destroy') return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tooltip
$.fn.tooltip = Plugin
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function () {
$.fn.tooltip = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: popover.js v3.2.0
* http://getbootstrap.com/javascript/#popovers
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function (element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.VERSION = '3.2.0'
Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function () {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content').empty()[ // we use append for html objects to maintain js events
this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
](content)
$tip.removeClass('fade top bottom left right in')
// IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
// this manually by checking the contents.
if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
}
Popover.prototype.hasContent = function () {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function () {
var $e = this.$element
var o = this.options
return $e.attr('data-content')
|| (typeof o.content == 'function' ?
o.content.call($e[0]) :
o.content)
}
Popover.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
}
Popover.prototype.tip = function () {
if (!this.$tip) this.$tip = $(this.options.template)
return this.$tip
}
// POPOVER PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data && option == 'destroy') return
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.popover
$.fn.popover = Plugin
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.2.0
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
var process = $.proxy(this.process, this)
this.$body = $('body')
this.$scrollElement = $(element).is('body') ? $(window) : $(element)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target || '') + ' .nav li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
this.$scrollElement.on('scroll.bs.scrollspy', process)
this.refresh()
this.process()
}
ScrollSpy.VERSION = '3.2.0'
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function () {
var offsetMethod = 'offset'
var offsetBase = 0
if (!$.isWindow(this.$scrollElement[0])) {
offsetMethod = 'position'
offsetBase = this.$scrollElement.scrollTop()
}
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
var self = this
this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href
&& $href.length
&& $href.is(':visible')
&& [[$href[offsetMethod]().top + offsetBase, href]]) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
self.offsets.push(this[0])
self.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.getScrollHeight()
var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (this.scrollHeight != scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop <= offsets[0]) {
return activeTarget != (i = targets[0]) && this.activate(i)
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (!offsets[i + 1] || scrollTop <= offsets[i + 1])
&& this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
$(this.selector)
.parentsUntil(this.options.target, '.active')
.removeClass('active')
var selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.scrollspy
$.fn.scrollspy = Plugin
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function () {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load.bs.scrollspy.data-api', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
Plugin.call($spy, $spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.2.0
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function (element) {
this.element = $(element)
}
Tab.VERSION = '3.2.0'
Tab.TRANSITION_DURATION = 150
Tab.prototype.show = function () {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var previous = $ul.find('.active:last a')[0]
var e = $.Event('show.bs.tab', {
relatedTarget: previous
})
$this.trigger(e)
if (e.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.closest('li'), $ul)
this.activate($target, $target.parent(), function () {
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: previous
})
})
}
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& (($active.length && $active.hasClass('fade')) || !!container.find('> .fade').length)
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
element.addClass('active')
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu')) {
element.closest('li.dropdown').addClass('active')
}
callback && callback()
}
$active.length && transition ?
$active
.one('bsTransitionEnd', next)
.emulateTransitionEnd(Tab.TRANSITION_DURATION) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tab
$.fn.tab = Plugin
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
$(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
e.preventDefault()
Plugin.call($(this), 'show')
})
}(jQuery);
/* ========================================================================
* Bootstrap: affix.js v3.2.0
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function (element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$target = $(this.options.target)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed =
this.unpin =
this.pinnedOffset = null
this.checkPosition()
}
Affix.VERSION = '3.2.0'
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0,
target: window
}
Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
var targetHeight = this.$target.height()
if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
if (this.affixed == 'bottom') {
if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
}
var initializing = this.affixed == null
var colliderTop = initializing ? scrollTop : position.top
var colliderHeight = initializing ? targetHeight : height
if (offsetTop != null && colliderTop <= offsetTop) return 'top'
if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
return false
}
Affix.prototype.getPinnedOffset = function () {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var height = this.$element.height()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
var scrollHeight = $('body').height()
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
if (this.affixed != affix) {
if (this.unpin != null) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
}
if (affix == 'bottom') {
this.$element.offset({
top: scrollHeight - height - offsetBottom
})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.affix
$.fn.affix = Plugin
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom) data.offset.bottom = data.offsetBottom
if (data.offsetTop) data.offset.top = data.offsetTop
Plugin.call($spy, data)
})
})
}(jQuery);
| Czarnodziej/final-omnislash | web/assetic/bootstrap_js.js | JavaScript | mit | 62,681 |
import { ColorPalette20 } from "../../";
export = ColorPalette20;
| markogresak/DefinitelyTyped | types/carbon__icons-react/lib/color-palette/20.d.ts | TypeScript | mit | 67 |
/**
* Copyright (c) 2010-2016, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.intertechno.internal;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Extension of the default OSGi bundle activator
*
* @author Till Klocke
* @since 1.4.0
*/
public final class CULIntertechnoActivator implements BundleActivator {
private static Logger logger = LoggerFactory.getLogger(CULIntertechnoActivator.class);
private static BundleContext context;
/**
* Called whenever the OSGi framework starts our bundle
*/
@Override
public void start(BundleContext bc) throws Exception {
context = bc;
logger.debug("CULIntertechno binding has been started.");
}
/**
* Called whenever the OSGi framework stops our bundle
*/
@Override
public void stop(BundleContext bc) throws Exception {
context = null;
logger.debug("CULIntertechno binding has been stopped.");
}
/**
* Returns the bundle context of this bundle
*
* @return the bundle context
*/
public static BundleContext getContext() {
return context;
}
}
| paolodenti/openhab | bundles/binding/org.openhab.binding.intertechno/src/main/java/org/openhab/binding/intertechno/internal/CULIntertechnoActivator.java | Java | epl-1.0 | 1,485 |
/*global $:false*/
define([
"manager",
"constants",
"lang",
"generator"
], function(manager, C, L, generator) {
"use strict";
/**
* @name Composite
* @description JS code for the Composite Data Type.
* @see DataType
* @namespace
*/
/* @private */
var MODULE_ID = "data-type-Composite";
var LANG = L.dataTypePlugins.Composite;
var _validate = function(rows) {
var visibleProblemRows = [];
var problemFields = [];
for (var i=0; i<rows.length; i++) {
if ($("#dtOption_" + rows[i]).val() === "") {
var visibleRowNum = generator.getVisibleRowOrderByRowNum(rows[i]);
visibleProblemRows.push(visibleRowNum);
problemFields.push($("#option_" + rows[i]));
}
}
var errors = [];
if (visibleProblemRows.length) {
errors.push({ els: problemFields, error: L.AlphaNumeric_incomplete_fields + " <b>" + visibleProblemRows.join(", ") + "</b>"});
}
return errors;
};
var _loadRow = function(rowNum, data) {
return {
execute: function() {
$("#dtExample_" + rowNum).val(data.example);
$("#dtOption_" + rowNum).val(data.option);
},
isComplete: function() { return $("#dtOption_" + rowNum).length > 0; }
};
};
var _saveRow = function(rowNum) {
return {
"example": $("#dtExample_" + rowNum).val(),
"option": $("#dtOption_" + rowNum).val()
};
};
manager.registerDataType(MODULE_ID, {
validate: _validate,
loadRow: _loadRow,
saveRow: _saveRow
});
});
| vivekmalikymca/generatedata | plugins/dataTypes/Composite/Composite.js | JavaScript | gpl-3.0 | 1,444 |
define(["../SimpleTheme", "./common"], function(SimpleTheme, themes){
themes.Minty = new SimpleTheme({
colors: [
"#80ccbb",
"#539e8b",
"#335f54",
"#8dd1c2",
"#68c5ad"
]
});
return themes.Minty;
});
| avz-cmf/zaboy-middleware | www/js/dojox/charting/themes/Minty.js | JavaScript | gpl-3.0 | 220 |
define(
({
"preview": "Anteprima"
})
);
| avz-cmf/zaboy-middleware | www/js/dojox/editor/plugins/nls/it/Preview.js | JavaScript | gpl-3.0 | 41 |
module SearchesHelper
def show_birthdays?
return false unless params[:birthday]
params[:birthday][:month].present? ||
params[:birthday][:day].present?
end
def show_testimonies?
params[:testimony].present?
end
def types_for_select
t('search.form.types').invert.to_a +
(Setting.get(:features, :custom_person_type) ? Person.custom_types : [])
end
def search_path(*args)
if params[:controller] == 'searches' and params[:family_id] and @family
family_search_path(*args)
else
super
end
end
end
| davidleach/onebody | app/helpers/searches_helper.rb | Ruby | agpl-3.0 | 557 |
import mechanize._clientcookie
import mechanize._testcase
def cookie_args(
version=1, name="spam", value="eggs",
port="80", port_specified=True,
domain="example.com", domain_specified=False, domain_initial_dot=False,
path="/", path_specified=False,
secure=False,
expires=0,
discard=True,
comment=None,
comment_url=None,
rest={},
rfc2109=False,
):
return locals()
def make_cookie(*args, **kwds):
return mechanize._clientcookie.Cookie(**cookie_args(*args, **kwds))
class Test(mechanize._testcase.TestCase):
def test_equality(self):
# not using assertNotEqual here since operator used varies across
# Python versions
self.assertEqual(make_cookie(), make_cookie())
self.assertFalse(make_cookie(name="ham") == make_cookie())
def test_inequality(self):
# not using assertNotEqual here since operator used varies across
# Python versions
self.assertTrue(make_cookie(name="ham") != make_cookie())
self.assertFalse(make_cookie() != make_cookie())
def test_all_state_included(self):
def non_equal_value(value):
if value is None:
new_value = "80"
elif isinstance(value, basestring):
new_value = value + "1"
elif isinstance(value, bool):
new_value = not value
elif isinstance(value, dict):
new_value = dict(value)
new_value["spam"] = "eggs"
elif isinstance(value, int):
new_value = value + 1
else:
assert False, value
assert new_value != value, value
return new_value
cookie = make_cookie()
for arg, default_value in cookie_args().iteritems():
new_value = non_equal_value(default_value)
self.assertNotEqual(make_cookie(**{arg: new_value}), cookie)
| mzdaniel/oh-mainline | vendor/packages/mechanize/test/test_cookie.py | Python | agpl-3.0 | 1,934 |
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2015 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.indentation;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
/**
* Handler for try blocks.
*
* @author jrichard
*/
public class TryHandler extends BlockParentHandler {
/**
* Construct an instance of this handler with the given indentation check,
* abstract syntax tree, and parent handler.
*
* @param indentCheck the indentation check
* @param ast the abstract syntax tree
* @param parent the parent handler
*/
public TryHandler(IndentationCheck indentCheck,
DetailAST ast, AbstractExpressionHandler parent) {
super(indentCheck, "try", ast, parent);
}
@Override
public IndentLevel suggestedChildLevel(AbstractExpressionHandler child) {
if (child instanceof CatchHandler
|| child instanceof FinallyHandler) {
return getLevel();
}
return super.suggestedChildLevel(child);
}
}
| attatrol/checkstyle | src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/TryHandler.java | Java | lgpl-2.1 | 2,009 |
# -*- coding: utf-8 -*-
#
# Clang documentation build configuration file, created by
# sphinx-quickstart on Sun Dec 9 20:01:55 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
from datetime import date
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.todo', 'sphinx.ext.mathjax']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Clang'
copyright = u'2007-%d, The Clang Team' % date.today().year
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '3.9'
# The full version, including alpha/beta/rc tags.
release = '3.9'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build', 'analyzer']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'friendly'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'haiku'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Clangdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Clang.tex', u'Clang Documentation',
u'The Clang Team', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = []
# Automatically derive the list of man pages from the contents of the command
# guide subdirectory. This was copied from llvm/docs/conf.py.
basedir = os.path.dirname(__file__)
man_page_authors = u'Maintained by the Clang / LLVM Team (<http://clang.llvm.org>)'
command_guide_subpath = 'CommandGuide'
command_guide_path = os.path.join(basedir, command_guide_subpath)
for name in os.listdir(command_guide_path):
# Ignore non-ReST files and the index page.
if not name.endswith('.rst') or name in ('index.rst',):
continue
# Otherwise, automatically extract the description.
file_subpath = os.path.join(command_guide_subpath, name)
with open(os.path.join(command_guide_path, name)) as f:
title = f.readline().rstrip('\n')
header = f.readline().rstrip('\n')
if len(header) != len(title):
print >>sys.stderr, (
"error: invalid header in %r (does not match title)" % (
file_subpath,))
if ' - ' not in title:
print >>sys.stderr, (
("error: invalid title in %r "
"(expected '<name> - <description>')") % (
file_subpath,))
# Split the name out of the title.
name,description = title.split(' - ', 1)
man_pages.append((file_subpath.replace('.rst',''), name,
description, man_page_authors, 1))
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Clang', u'Clang Documentation',
u'The Clang Team', 'Clang', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
| cd80/UtilizedLLVM | tools/clang/docs/conf.py | Python | unlicense | 9,132 |
# 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.
import sys
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
from libcloud.compute.base import NodeAuthPassword
ECSDriver = get_driver(Provider.ALIYUN_ECS)
region = 'cn-hangzhou'
your_access_key_id = ''
your_access_key_secret = ''
ecs = ECSDriver(your_access_key_id, your_access_key_secret, region=region)
sizes = ecs.list_sizes()
small = sizes[1]
locations = ecs.list_locations()
location = None
for each in locations:
if each.id == region:
location = each
break
if location is None:
print('could not find cn-qingdao location')
sys.exit(-1)
print(location.name)
images = ecs.list_images()
print('Found %d images' % len(images))
for each in images:
if 'ubuntu' in each.id.lower():
image = each
break
else:
image = images[0]
print('Use image %s' % image)
sgs = ecs.ex_list_security_groups()
print('Found %d security groups' % len(sgs))
if len(sgs) == 0:
sg = ecs.ex_create_security_group(description='test')
print('Create security group %s' % sg)
else:
sg = sgs[0].id
print('Use security group %s' % sg)
nodes = ecs.list_nodes()
print('Found %d nodes' % len(nodes))
if len(nodes) == 0:
print('Starting create a new node')
data_disk = {
'size': 5,
'category': ecs.disk_categories.CLOUD,
'disk_name': 'data_disk1',
'delete_with_instance': True}
auth = NodeAuthPassword('P@$$w0rd')
ex_internet_charge_type = ecs.internet_charge_types.BY_TRAFFIC
node = ecs.create_node(image=image, size=small, name='test',
ex_security_group_id=sg,
ex_internet_charge_type=ex_internet_charge_type,
ex_internet_max_bandwidth_out=1,
ex_data_disk=data_disk,
auth=auth)
print('Created node %s' % node)
nodes = ecs.list_nodes()
for each in nodes:
print('Found node %s' % each)
| StackPointCloud/libcloud | demos/example_aliyun_ecs.py | Python | apache-2.0 | 2,755 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.IO;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public class TempDirectory
{
private readonly string _path;
private readonly TempRoot _root;
protected TempDirectory(TempRoot root)
: this(CreateUniqueDirectory(TempRoot.Root), root)
{
}
private TempDirectory(string path, TempRoot root)
{
Debug.Assert(path != null);
Debug.Assert(root != null);
_path = path;
_root = root;
}
private static string CreateUniqueDirectory(string basePath)
{
while (true)
{
string dir = System.IO.Path.Combine(basePath, Guid.NewGuid().ToString());
try
{
Directory.CreateDirectory(dir);
return dir;
}
catch (IOException)
{
// retry
}
}
}
public string Path
{
get { return _path; }
}
/// <summary>
/// Creates a file in this directory.
/// </summary>
/// <param name="name">File name.</param>
public TempFile CreateFile(string name)
{
string filePath = System.IO.Path.Combine(_path, name);
TempRoot.CreateStream(filePath, FileMode.CreateNew);
return _root.AddFile(new DisposableFile(filePath));
}
/// <summary>
/// Creates a file or opens an existing file in this directory.
/// </summary>
public TempFile CreateOrOpenFile(string name)
{
string filePath = System.IO.Path.Combine(_path, name);
TempRoot.CreateStream(filePath, FileMode.OpenOrCreate);
return _root.AddFile(new DisposableFile(filePath));
}
/// <summary>
/// Creates a file in this directory that is a copy of the specified file.
/// </summary>
public TempFile CopyFile(string originalPath, string name = null)
{
string filePath = System.IO.Path.Combine(_path, name ?? System.IO.Path.GetFileName(originalPath));
File.Copy(originalPath, filePath);
return _root.AddFile(new DisposableFile(filePath));
}
/// <summary>
/// Creates a subdirectory in this directory.
/// </summary>
/// <param name="name">Directory name or unrooted directory path.</param>
public TempDirectory CreateDirectory(string name)
{
string dirPath = System.IO.Path.Combine(_path, name);
Directory.CreateDirectory(dirPath);
return new TempDirectory(dirPath, _root);
}
public override string ToString()
{
return _path;
}
}
}
| brettfo/roslyn | src/Test/Utilities/Portable/TempFiles/TempDirectory.cs | C# | apache-2.0 | 3,117 |
<table id="<?php echo $id ?>" width="100%">
<?php if (isset($options['title'])): ?>
<tr><td bgcolor="<?php echo $op_color["core_color_5"] ?>">
<font color="<?php echo $op_color["core_color_25"] ?>"><?php echo $options['title'] ?></font><br>
</td></tr>
<?php else: ?>
<tr><td bgcolor="<?php echo $op_color["core_color_7"] ?>">
<hr color="<?php echo $op_color["core_color_12"] ?>">
</td></tr>
<?php endif; ?>
<?php foreach ($options['list'] as $key => $value): ?>
<tr><td bgcolor="<?php echo cycle_vars($id, $op_color["core_color_6"].','.$op_color["core_color_7"]) ?>">
<?php echo $options['list']->getRaw($key) ?><br>
</td></tr>
<?php if (!empty($options['border'])): ?>
<tr><td bgcolor="<?php echo $op_color["core_color_7"] ?>">
<hr color="<?php echo $op_color["core_color_12"] ?>">
</td></tr>
<?php endif; ?>
<?php endforeach; ?>
<?php if (isset($options['moreInfo'])): ?>
<tr><td align="right">
<?php foreach ($options['moreInfo'] as $key => $value): ?>
<?php echo $options['moreInfo']->getRaw($key) ?><br>
<?php endforeach; ?>
</td></tr>
<?php endif; ?>
</table>
<br>
| smart-e/lifemap | apps/mobile_frontend/templates/_partsListBox.php | PHP | apache-2.0 | 1,074 |
/*
* 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 sample.eventing;
import org.apache.axiom.om.OMElement;
public class ListnerService2 {
String name = "ListnerService2";
public void publish(OMElement param) throws Exception {
System.out.println("\n");
System.out.println("'" + name + "' got a new publication...");
System.out.println(param);
System.out.println("\n");
}
}
| Nipuni/wso2-axis2 | modules/samples/eventing/src/sample/eventing/ListnerService2.java | Java | apache-2.0 | 1,154 |
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
class MyArray extends Array { }
Object.prototype[Symbol.species] = MyArray;
delete Array[Symbol.species];
__v_1 = Math.pow(2, 31);
__v_2 = [];
__v_2[__v_1] = 31;
__v_4 = [];
__v_4[__v_1 - 2] = 33;
assertThrows(() => __v_2.concat(__v_4), RangeError);
| weolar/miniblink49 | v8_7_5/test/mjsunit/regress/regress-crbug-592340.js | JavaScript | apache-2.0 | 418 |