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
/**
* PHPUnit
*
* Copyright (c) 2001-2013, Sebastian Bergmann <sebastian@phpunit.de>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Sebastian Bergmann nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package PHPUnit
* @author Sebastian Bergmann <sebastian@phpunit.de>
* @copyright 2001-2013 Sebastian Bergmann <sebastian@phpunit.de>
* @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
* @link http://www.phpunit.de/
* @since File available since Release 2.0.0
*/
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'NoArgTestCaseTest.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'Singleton.php';
$GLOBALS['a'] = 'a';
$_ENV['b'] = 'b';
$_POST['c'] = 'c';
$_GET['d'] = 'd';
$_COOKIE['e'] = 'e';
$_SERVER['f'] = 'f';
$_FILES['g'] = 'g';
$_REQUEST['h'] = 'h';
$GLOBALS['i'] = 'i';
/**
*
*
* @package PHPUnit
* @author Sebastian Bergmann <sebastian@phpunit.de>
* @copyright 2001-2013 Sebastian Bergmann <sebastian@phpunit.de>
* @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
* @link http://www.phpunit.de/
* @since Class available since Release 2.0.0
*/
class Framework_TestCaseTest extends PHPUnit_Framework_TestCase
{
protected $backupGlobalsBlacklist = array('i', 'singleton');
public function testCaseToString()
{
$this->assertEquals(
'Framework_TestCaseTest::testCaseToString',
$this->toString()
);
}
public function testSuccess()
{
$test = new Success;
$result = $test->run();
$this->assertEquals(0, $result->errorCount());
$this->assertEquals(0, $result->failureCount());
$this->assertEquals(1, count($result));
}
public function testFailure()
{
$test = new Failure;
$result = $test->run();
$this->assertEquals(0, $result->errorCount());
$this->assertEquals(1, $result->failureCount());
$this->assertEquals(1, count($result));
}
public function testError()
{
$test = new Error;
$result = $test->run();
$this->assertEquals(1, $result->errorCount());
$this->assertEquals(0, $result->failureCount());
$this->assertEquals(1, count($result));
}
public function testExceptionInSetUp()
{
$test = new ExceptionInSetUpTest('testSomething');
$result = $test->run();
$this->assertTrue($test->setUp);
$this->assertFalse($test->assertPreConditions);
$this->assertFalse($test->testSomething);
$this->assertFalse($test->assertPostConditions);
$this->assertTrue($test->tearDown);
}
public function testExceptionInAssertPreConditions()
{
$test = new ExceptionInAssertPreConditionsTest('testSomething');
$result = $test->run();
$this->assertTrue($test->setUp);
$this->assertTrue($test->assertPreConditions);
$this->assertFalse($test->testSomething);
$this->assertFalse($test->assertPostConditions);
$this->assertTrue($test->tearDown);
}
public function testExceptionInTest()
{
$test = new ExceptionInTest('testSomething');
$result = $test->run();
$this->assertTrue($test->setUp);
$this->assertTrue($test->assertPreConditions);
$this->assertTrue($test->testSomething);
$this->assertFalse($test->assertPostConditions);
$this->assertTrue($test->tearDown);
}
public function testExceptionInAssertPostConditions()
{
$test = new ExceptionInAssertPostConditionsTest('testSomething');
$result = $test->run();
$this->assertTrue($test->setUp);
$this->assertTrue($test->assertPreConditions);
$this->assertTrue($test->testSomething);
$this->assertTrue($test->assertPostConditions);
$this->assertTrue($test->tearDown);
}
public function testExceptionInTearDown()
{
$test = new ExceptionInTearDownTest('testSomething');
$result = $test->run();
$this->assertTrue($test->setUp);
$this->assertTrue($test->assertPreConditions);
$this->assertTrue($test->testSomething);
$this->assertTrue($test->assertPostConditions);
$this->assertTrue($test->tearDown);
}
public function testNoArgTestCasePasses()
{
$result = new PHPUnit_Framework_TestResult;
$t = new PHPUnit_Framework_TestSuite('NoArgTestCaseTest');
$t->run($result);
$this->assertEquals(1, count($result));
$this->assertEquals(0, $result->failureCount());
$this->assertEquals(0, $result->errorCount());
}
public function testWasRun()
{
$test = new WasRun;
$test->run();
$this->assertTrue($test->wasRun);
}
public function testException()
{
$test = new ThrowExceptionTestCase('test');
$test->setExpectedException('RuntimeException');
$result = $test->run();
$this->assertEquals(1, count($result));
$this->assertTrue($result->wasSuccessful());
}
public function testNoException()
{
$test = new ThrowNoExceptionTestCase('test');
$test->setExpectedException('RuntimeException');
$result = $test->run();
$this->assertEquals(1, $result->failureCount());
$this->assertEquals(1, count($result));
}
public function testWrongException()
{
$test = new ThrowExceptionTestCase('test');
$test->setExpectedException('InvalidArgumentException');
$result = $test->run();
$this->assertEquals(1, $result->failureCount());
$this->assertEquals(1, count($result));
}
/**
* @backupGlobals enabled
*/
public function testGlobalsBackupPre()
{
global $a;
global $i;
$this->assertEquals('a', $a);
$this->assertEquals('a', $GLOBALS['a']);
$this->assertEquals('b', $_ENV['b']);
$this->assertEquals('c', $_POST['c']);
$this->assertEquals('d', $_GET['d']);
$this->assertEquals('e', $_COOKIE['e']);
$this->assertEquals('f', $_SERVER['f']);
$this->assertEquals('g', $_FILES['g']);
$this->assertEquals('h', $_REQUEST['h']);
$this->assertEquals('i', $i);
$this->assertEquals('i', $GLOBALS['i']);
$GLOBALS['a'] = 'aa';
$GLOBALS['foo'] = 'bar';
$_ENV['b'] = 'bb';
$_POST['c'] = 'cc';
$_GET['d'] = 'dd';
$_COOKIE['e'] = 'ee';
$_SERVER['f'] = 'ff';
$_FILES['g'] = 'gg';
$_REQUEST['h'] = 'hh';
$GLOBALS['i'] = 'ii';
$this->assertEquals('aa', $a);
$this->assertEquals('aa', $GLOBALS['a']);
$this->assertEquals('bar', $GLOBALS['foo']);
$this->assertEquals('bb', $_ENV['b']);
$this->assertEquals('cc', $_POST['c']);
$this->assertEquals('dd', $_GET['d']);
$this->assertEquals('ee', $_COOKIE['e']);
$this->assertEquals('ff', $_SERVER['f']);
$this->assertEquals('gg', $_FILES['g']);
$this->assertEquals('hh', $_REQUEST['h']);
$this->assertEquals('ii', $i);
$this->assertEquals('ii', $GLOBALS['i']);
}
public function testGlobalsBackupPost()
{
global $a;
global $i;
$this->assertEquals('a', $a);
$this->assertEquals('a', $GLOBALS['a']);
$this->assertEquals('b', $_ENV['b']);
$this->assertEquals('c', $_POST['c']);
$this->assertEquals('d', $_GET['d']);
$this->assertEquals('e', $_COOKIE['e']);
$this->assertEquals('f', $_SERVER['f']);
$this->assertEquals('g', $_FILES['g']);
$this->assertEquals('h', $_REQUEST['h']);
$this->assertEquals('ii', $i);
$this->assertEquals('ii', $GLOBALS['i']);
$this->assertArrayNotHasKey('foo', $GLOBALS);
}
/**
* @backupGlobals enabled
* @backupStaticAttributes enabled
*/
public function testStaticAttributesBackupPre()
{
$GLOBALS['singleton'] = Singleton::getInstance();
}
public function testStaticAttributesBackupPost()
{
$this->assertNotSame($GLOBALS['singleton'], Singleton::getInstance());
}
public function testExpectOutputStringFooActualFoo()
{
$test = new OutputTestCase('testExpectOutputStringFooActualFoo');
$result = $test->run();
$this->assertEquals(1, count($result));
$this->assertTrue($result->wasSuccessful());
}
public function testExpectOutputStringFooActualBar()
{
$test = new OutputTestCase('testExpectOutputStringFooActualBar');
$result = $test->run();
$this->assertEquals(1, count($result));
$this->assertFalse($result->wasSuccessful());
}
public function testExpectOutputRegexFooActualFoo()
{
$test = new OutputTestCase('testExpectOutputRegexFooActualFoo');
$result = $test->run();
$this->assertEquals(1, count($result));
$this->assertTrue($result->wasSuccessful());
}
public function testExpectOutputRegexFooActualBar()
{
$test = new OutputTestCase('testExpectOutputRegexFooActualBar');
$result = $test->run();
$this->assertEquals(1, count($result));
$this->assertFalse($result->wasSuccessful());
}
public function testSkipsIfRequiresHigherVersionOfPHPUnit()
{
$test = new RequirementsTest('testAlwaysSkip');
$result = $test->run();
$this->assertEquals(1, $result->skippedCount());
$this->assertEquals(
'PHPUnit 1111111 (or later) is required.',
$test->getStatusMessage()
);
}
public function testSkipsIfRequiresHigherVersionOfPHP()
{
$test = new RequirementsTest('testAlwaysSkip2');
$result = $test->run();
$this->assertEquals(1, $result->skippedCount());
$this->assertEquals(
'PHP 9999999 (or later) is required.',
$test->getStatusMessage()
);
}
public function testSkipsIfRequiresNonExistingOs()
{
$test = new RequirementsTest('testAlwaysSkip3');
$result = $test->run();
$this->assertEquals(1, $result->skippedCount());
$this->assertEquals(
'Operating system matching /DOESNOTEXIST/i is required.',
$test->getStatusMessage()
);
}
public function testSkipsIfRequiresNonExistingFunction()
{
$test = new RequirementsTest('testNine');
$result = $test->run();
$this->assertEquals(1, $result->skippedCount());
$this->assertEquals(
'Function testFunc is required.',
$test->getStatusMessage()
);
}
public function testSkipsIfRequiresNonExistingExtension()
{
$test = new RequirementsTest('testTen');
$result = $test->run();
$this->assertEquals(
'Extension testExt is required.',
$test->getStatusMessage()
);
}
public function testSkipsProvidesMessagesForAllSkippingReasons()
{
$test = new RequirementsTest('testAllPossibleRequirements');
$result = $test->run();
$this->assertEquals(
'PHP 99-dev (or later) is required.' . PHP_EOL .
'PHPUnit 9-dev (or later) is required.' . PHP_EOL .
'Operating system matching /DOESNOTEXIST/i is required.' . PHP_EOL .
'Function testFuncOne is required.' . PHP_EOL .
'Function testFuncTwo is required.' . PHP_EOL .
'Extension testExtOne is required.' . PHP_EOL .
'Extension testExtTwo is required.',
$test->getStatusMessage()
);
}
public function testRequiringAnExistingFunctionDoesNotSkip()
{
$test = new RequirementsTest('testExistingFunction');
$result = $test->run();
$this->assertEquals(0, $result->skippedCount());
}
public function testRequiringAnExistingExtensionDoesNotSkip()
{
$test = new RequirementsTest('testExistingExtension');
$result = $test->run();
$this->assertEquals(0, $result->skippedCount());
}
public function testRequiringAnExistingOsDoesNotSkip()
{
$test = new RequirementsTest('testExistingOs');
$result = $test->run();
$this->assertEquals(0, $result->skippedCount());
}
public function testCurrentWorkingDirectoryIsRestored()
{
$expectedCwd = getcwd();
$test = new ChangeCurrentWorkingDirectoryTest('testSomethingThatChangesTheCwd');
$test->run();
$this->assertSame($expectedCwd, getcwd());
}
}
| matthiaskluth/cafe-fleischlos | vendor/phpunit/phpunit/Tests/Framework/TestCaseTest.php | PHP | mit | 14,303 |
import React from 'react'
import * as DevTools from 'redux-devtools'
import LogMonitor from 'redux-devtools-log-monitor'
import DockMonitor from 'redux-devtools-dock-monitor'
//
export default DevTools.createDevTools(
<DockMonitor
toggleVisibilityKey='ctrl-h'
changePositionKey='ctrl-p'
defaultIsVisible={false}>
<LogMonitor theme='tomorrow' />
</DockMonitor>
)
| zab/jumpsuit | src/devtools.js | JavaScript | mit | 383 |
<?php
namespace Oro\Bundle\TestFrameworkBundle\DependencyInjection\Compiler;
use Oro\Bundle\TestFrameworkBundle\Test\Client;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class ClientCompilerPass implements CompilerPassInterface
{
const CLIENT_SERVICE = 'test.client';
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
if ($container->hasDefinition(self::CLIENT_SERVICE)) {
$definition = $container->getDefinition(self::CLIENT_SERVICE);
$definition->setClass(Client::class);
}
}
}
| orocrm/platform | src/Oro/Bundle/TestFrameworkBundle/DependencyInjection/Compiler/ClientCompilerPass.php | PHP | mit | 671 |
# Phusion Passenger - https://www.phusionpassenger.com/
# Copyright (c) 2010-2013 Phusion
#
# "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
#
# 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.
# apxs totally sucks. We couldn't get it working correctly
# on MacOS X (it had various problems with building universal
# binaries), so we decided to ditch it and build/install the
# Apache module ourselves.
#
# Oh, and libtool sucks too. Do we even need it anymore in 2008?
APACHE2_MODULE = APACHE2_OUTPUT_DIR + "mod_passenger.so"
APACHE2_MODULE_INPUT_FILES = {
APACHE2_OUTPUT_DIR + 'Configuration.o' => %w(
ext/apache2/Configuration.cpp
ext/apache2/Configuration.h
ext/apache2/Configuration.hpp
ext/common/Constants.h
ext/common/agents/LoggingAgent/FilterSupport.h),
APACHE2_OUTPUT_DIR + 'Bucket.o' => %w(
ext/apache2/Bucket.cpp
ext/apache2/Bucket.h),
APACHE2_OUTPUT_DIR + 'Hooks.o' => %w(
ext/apache2/Hooks.cpp
ext/apache2/Hooks.h
ext/apache2/Configuration.h
ext/apache2/Configuration.hpp
ext/apache2/Bucket.h
ext/apache2/DirectoryMapper.h
ext/common/AgentsStarter.hpp
ext/common/Exceptions.h
ext/common/Logging.h
ext/common/RandomGenerator.h
ext/common/ServerInstanceDir.h
ext/common/Constants.h
ext/common/Utils.h
ext/common/Utils/Timer.h)
}
APACHE2_MODULE_OBJECTS = APACHE2_MODULE_INPUT_FILES.keys
APACHE2_MOD_PASSENGER_O = APACHE2_OUTPUT_DIR + "mod_passenger.o"
APACHE2_MODULE_CXXFLAGS =
"#{EXTRA_PRE_CXXFLAGS} " <<
"-Iext -Iext/common #{PlatformInfo.apache2_module_cflags} " <<
"#{PlatformInfo.portability_cflags} #{EXTRA_CXXFLAGS}"
APACHE2_MODULE_BOOST_OXT_LIBRARY = define_libboost_oxt_task("apache2",
APACHE2_OUTPUT_DIR + "module_libboost_oxt",
PlatformInfo.apache2_module_cflags)
APACHE2_MODULE_COMMON_LIBRARIES = COMMON_LIBRARY.
only(:base, 'ApplicationPool2/AppTypes.o', 'Utils/Base64.o',
'Utils/MD5.o', 'Utils/LargeFiles.o').
set_namespace("apache2").
set_output_dir(APACHE2_OUTPUT_DIR + "module_libpassenger_common").
define_tasks(PlatformInfo.apache2_module_cflags).
link_objects
desc "Build Apache 2 module"
task :apache2 => [
APACHE2_MODULE,
AGENT_OUTPUT_DIR + 'PassengerHelperAgent',
AGENT_OUTPUT_DIR + 'PassengerWatchdog',
AGENT_OUTPUT_DIR + 'PassengerLoggingAgent',
AGENT_OUTPUT_DIR + 'SpawnPreparer',
NATIVE_SUPPORT_TARGET
].compact
# Define rules for the individual Apache 2 module source files.
APACHE2_MODULE_INPUT_FILES.each_pair do |target, sources|
file(target => sources) do
object_basename = File.basename(target)
object_filename = APACHE2_OUTPUT_DIR + object_basename
compile_cxx(sources[0], "#{APACHE2_MODULE_CXXFLAGS} -o #{object_filename}")
end
end
dependencies = [
APACHE2_MODULE_COMMON_LIBRARIES,
APACHE2_MODULE_BOOST_OXT_LIBRARY,
APACHE2_MOD_PASSENGER_O,
APACHE2_MODULE_OBJECTS
].flatten
file APACHE2_MODULE => dependencies do
PlatformInfo.apxs2.nil? and raise "Could not find 'apxs' or 'apxs2'."
PlatformInfo.apache2ctl.nil? and raise "Could not find 'apachectl' or 'apache2ctl'."
PlatformInfo.httpd.nil? and raise "Could not find the Apache web server binary."
sources = (APACHE2_MODULE_OBJECTS + [APACHE2_MOD_PASSENGER_O]).join(' ')
linkflags =
"#{EXTRA_PRE_CXXFLAGS} #{EXTRA_PRE_LDFLAGS} " <<
"#{PlatformInfo.apache2_module_cflags} " <<
"#{PlatformInfo.portability_cflags} " <<
"#{EXTRA_CXXFLAGS} " <<
"#{APACHE2_MODULE_COMMON_LIBRARIES.join(' ')} " <<
"#{APACHE2_MODULE_BOOST_OXT_LIBRARY} " <<
"#{PlatformInfo.apache2_module_ldflags} " <<
"#{PlatformInfo.portability_ldflags} " <<
"#{EXTRA_LDFLAGS} "
create_shared_library(APACHE2_MODULE, sources, linkflags)
end
file APACHE2_MOD_PASSENGER_O => ['ext/apache2/mod_passenger.c'] do
compile_c('ext/apache2/mod_passenger.c',
"#{APACHE2_MODULE_CXXFLAGS} -o #{APACHE2_MOD_PASSENGER_O}")
end
task :clean => 'apache2:clean'
desc "Clean all compiled Apache 2 files"
task 'apache2:clean' => 'common:clean' do
files = APACHE2_MODULE_OBJECTS.dup
files << APACHE2_MOD_PASSENGER_O
files << APACHE2_MODULE
sh("rm", "-rf", *files)
end
| jawj/passenger | build/apache2.rb | Ruby | mit | 5,077 |
import * as code from 'vscode';
import * as ls from 'vscode-languageserver-protocol';
import ProtocolCompletionItem from './protocolCompletionItem';
export interface Converter {
asUri(value: string): code.Uri;
asDiagnostic(diagnostic: ls.Diagnostic): code.Diagnostic;
asDiagnostics(diagnostics: ls.Diagnostic[]): code.Diagnostic[];
asPosition(value: undefined | null): undefined;
asPosition(value: ls.Position): code.Position;
asPosition(value: ls.Position | undefined | null): code.Position | undefined;
asRange(value: undefined | null): undefined;
asRange(value: ls.Range): code.Range;
asRange(value: ls.Range | undefined | null): code.Range | undefined;
asDiagnosticSeverity(value: number | undefined | null): code.DiagnosticSeverity;
asHover(hover: ls.Hover): code.Hover;
asHover(hover: undefined | null): undefined;
asHover(hover: ls.Hover | undefined | null): code.Hover | undefined;
asCompletionResult(result: ls.CompletionList): code.CompletionList;
asCompletionResult(result: ls.CompletionItem[]): code.CompletionItem[];
asCompletionResult(result: undefined | null): undefined;
asCompletionResult(result: ls.CompletionItem[] | ls.CompletionList | undefined | null): code.CompletionItem[] | code.CompletionList | undefined;
asCompletionItem(item: ls.CompletionItem): ProtocolCompletionItem;
asTextEdit(edit: undefined | null): undefined;
asTextEdit(edit: ls.TextEdit): code.TextEdit;
asTextEdit(edit: ls.TextEdit | undefined | null): code.TextEdit | undefined;
asTextEdits(items: ls.TextEdit[]): code.TextEdit[];
asTextEdits(items: undefined | null): undefined;
asTextEdits(items: ls.TextEdit[] | undefined | null): code.TextEdit[] | undefined;
asSignatureHelp(item: undefined | null): undefined;
asSignatureHelp(item: ls.SignatureHelp): code.SignatureHelp;
asSignatureHelp(item: ls.SignatureHelp | undefined | null): code.SignatureHelp | undefined;
asSignatureInformation(item: ls.SignatureInformation): code.SignatureInformation;
asSignatureInformations(items: ls.SignatureInformation[]): code.SignatureInformation[];
asParameterInformation(item: ls.ParameterInformation): code.ParameterInformation;
asParameterInformations(item: ls.ParameterInformation[]): code.ParameterInformation[];
asDefinitionResult(item: ls.Definition): code.Definition;
asDefinitionResult(item: undefined | null): undefined;
asDefinitionResult(item: ls.Definition | undefined | null): code.Definition | undefined;
asLocation(item: ls.Location): code.Location;
asLocation(item: undefined | null): undefined;
asLocation(item: ls.Location | undefined | null): code.Location | undefined;
asReferences(values: ls.Location[]): code.Location[];
asReferences(values: undefined | null): code.Location[] | undefined;
asReferences(values: ls.Location[] | undefined | null): code.Location[] | undefined;
asDocumentHighlightKind(item: number): code.DocumentHighlightKind;
asDocumentHighlight(item: ls.DocumentHighlight): code.DocumentHighlight;
asDocumentHighlights(values: ls.DocumentHighlight[]): code.DocumentHighlight[];
asDocumentHighlights(values: undefined | null): undefined;
asDocumentHighlights(values: ls.DocumentHighlight[] | undefined | null): code.DocumentHighlight[] | undefined;
asSymbolInformation(item: ls.SymbolInformation, uri?: code.Uri): code.SymbolInformation;
asSymbolInformations(values: ls.SymbolInformation[], uri?: code.Uri): code.SymbolInformation[];
asSymbolInformations(values: undefined | null, uri?: code.Uri): undefined;
asSymbolInformations(values: ls.SymbolInformation[] | undefined | null, uri?: code.Uri): code.SymbolInformation[] | undefined;
asDocumentSymbol(value: ls.DocumentSymbol): code.DocumentSymbol;
asDocumentSymbols(value: undefined | null): undefined;
asDocumentSymbols(value: ls.DocumentSymbol[]): code.DocumentSymbol[];
asDocumentSymbols(value: ls.DocumentSymbol[] | undefined | null): code.DocumentSymbol[] | undefined;
asCommand(item: ls.Command): code.Command;
asCommands(items: ls.Command[]): code.Command[];
asCommands(items: undefined | null): undefined;
asCommands(items: ls.Command[] | undefined | null): code.Command[] | undefined;
asCodeAction(item: ls.CodeAction): code.CodeAction;
asCodeAction(item: undefined | null): undefined;
asCodeAction(item: ls.CodeAction | undefined | null): code.CodeAction | undefined;
asCodeActionKind(item: null | undefined): undefined;
asCodeActionKind(item: ls.CodeActionKind): code.CodeActionKind;
asCodeActionKind(item: ls.CodeActionKind | null | undefined): code.CodeActionKind | undefined;
asCodeActionKinds(item: null | undefined): undefined;
asCodeActionKinds(items: ls.CodeActionKind[]): code.CodeActionKind[];
asCodeActionKinds(item: ls.CodeActionKind[] | null | undefined): code.CodeActionKind[] | undefined;
asCodeLens(item: ls.CodeLens): code.CodeLens;
asCodeLens(item: undefined | null): undefined;
asCodeLens(item: ls.CodeLens | undefined | null): code.CodeLens | undefined;
asCodeLenses(items: ls.CodeLens[]): code.CodeLens[];
asCodeLenses(items: undefined | null): undefined;
asCodeLenses(items: ls.CodeLens[] | undefined | null): code.CodeLens[] | undefined;
asWorkspaceEdit(item: ls.WorkspaceEdit): code.WorkspaceEdit;
asWorkspaceEdit(item: undefined | null): undefined;
asWorkspaceEdit(item: ls.WorkspaceEdit | undefined | null): code.WorkspaceEdit | undefined;
asDocumentLink(item: ls.DocumentLink): code.DocumentLink;
asDocumentLinks(items: ls.DocumentLink[]): code.DocumentLink[];
asDocumentLinks(items: undefined | null): undefined;
asDocumentLinks(items: ls.DocumentLink[] | undefined | null): code.DocumentLink[] | undefined;
asColor(color: ls.Color): code.Color;
asColorInformation(ci: ls.ColorInformation): code.ColorInformation;
asColorInformations(colorPresentations: ls.ColorInformation[]): code.ColorInformation[];
asColorInformations(colorPresentations: undefined | null): undefined;
asColorInformations(colorInformation: ls.ColorInformation[] | undefined | null): code.ColorInformation[];
asColorPresentation(cp: ls.ColorPresentation): code.ColorPresentation;
asColorPresentations(colorPresentations: ls.ColorPresentation[]): code.ColorPresentation[];
asColorPresentations(colorPresentations: undefined | null): undefined;
asColorPresentations(colorPresentations: ls.ColorPresentation[] | undefined | null): undefined;
asFoldingRangeKind(kind: string | undefined): code.FoldingRangeKind | undefined;
asFoldingRange(r: ls.FoldingRange): code.FoldingRange;
asFoldingRanges(foldingRanges: ls.FoldingRange[]): code.FoldingRange[];
asFoldingRanges(foldingRanges: undefined | null): undefined;
asFoldingRanges(foldingRanges: ls.FoldingRange[] | undefined | null): code.FoldingRange[] | undefined;
asFoldingRanges(foldingRanges: ls.FoldingRange[] | undefined | null): code.FoldingRange[] | undefined;
}
export interface URIConverter {
(value: string): code.Uri;
}
export declare function createConverter(uriConverter?: URIConverter): Converter;
| KTXSoftware/KodeStudio-win32 | resources/app/kodeExtensions/haxe/node_modules/vscode-languageclient/lib/protocolConverter.d.ts | TypeScript | mit | 7,320 |
//
// Copyright 2013 Christian Henning
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#define BOOST_GIL_IO_ADD_FS_PATH_SUPPORT
#define BOOST_GIL_IO_ENABLE_GRAY_ALPHA
#define BOOST_FILESYSTEM_VERSION 3
#include <boost/gil.hpp>
#include <boost/gil/extension/io/png.hpp>
#include <boost/core/lightweight_test.hpp>
#include <cstdint>
#include <iostream>
#include <sstream>
#include <string>
#include "paths.hpp"
#include "scanline_read_test.hpp"
#include "test_utility_output_stream.hpp"
namespace gil = boost::gil;
namespace fs = boost::filesystem;
using gray_alpha8_pixel_t = gil::pixel<std::uint8_t, gil::gray_alpha_layout_t>;
using gray_alpha8c_pixel_t = gil::pixel<std::uint8_t, gil::gray_alpha_layout_t> const;
using gray_alpha8_image_t= gil::image<gray_alpha8_pixel_t, false>;
using gray_alpha16_pixel_t = gil::pixel<std::uint16_t, gil::gray_alpha_layout_t>;
using gray_alpha16c_pixel_t = gil::pixel<std::uint16_t, gil::gray_alpha_layout_t> const;
using gray_alpha16_image_t = gil::image<gray_alpha16_pixel_t, false>;
template <typename Image>
void test_file(std::string filename)
{
Image src, dst;
gil::image_read_settings<gil::png_tag> settings;
settings._read_file_gamma = true;
settings._read_transparency_data = true;
using backend_t = gil::get_reader_backend<std::string const, gil::png_tag>::type;
backend_t backend = gil::read_image_info(png_in + filename, settings);
gil::read_image(png_in + filename, src, settings);
#ifdef BOOST_GIL_IO_TEST_ALLOW_WRITING_IMAGES
gil::image_write_info<gil::png_tag> write_info;
write_info._file_gamma = backend._info._file_gamma;
gil::write_view(png_out + filename, view(src), write_info);
gil::read_image(png_out + filename, dst, settings);
BOOST_TEST(gil::equal_pixels(gil::const_view(src), gil::const_view(dst)));
#endif // BOOST_GIL_IO_TEST_ALLOW_WRITING_IMAGES
}
template <typename Image>
void test_png_scanline_reader(std::string filename)
{
test_scanline_reader<Image, gil::png_tag>(std::string(png_in + filename).c_str());
}
#ifdef BOOST_GIL_IO_TEST_ALLOW_READING_IMAGES
void test_read_header()
{
using backend_t = gil::get_reader_backend<std::string const, gil::png_tag>::type;
backend_t backend = gil::read_image_info(png_filename, gil::png_tag());
BOOST_TEST_EQ(backend._info._width, 1000u);
BOOST_TEST_EQ(backend._info._height, 600u);
BOOST_TEST_EQ(backend._info._num_channels, 4);
BOOST_TEST_EQ(backend._info._bit_depth, 8);
BOOST_TEST_EQ(backend._info._color_type, PNG_COLOR_TYPE_RGBA);
BOOST_TEST_EQ(backend._info._interlace_method, PNG_INTERLACE_NONE);
BOOST_TEST_EQ(backend._info._compression_method, PNG_COMPRESSION_TYPE_BASE);
BOOST_TEST_EQ(backend._info._filter_method, PNG_FILTER_TYPE_BASE);
BOOST_TEST_EQ(backend._info._file_gamma, 1);
}
void test_read_pixel_per_meter()
{
gil::image_read_settings<gil::png_tag> settings;
settings.set_read_members_true();
using backend_t = gil::get_reader_backend<std::string const, gil::png_tag>::type;
backend_t backend = gil::read_image_info(png_base_in + "EddDawson/36dpi.png", settings);
BOOST_TEST_EQ(backend._info._pixels_per_meter, png_uint_32(1417));
}
void test_read_with_trns_chunk_color_type_0()
{
// PNG 1.2: For color type 0 (grayscale), the tRNS chunk contains a single gray level value,
// stored in the format:
//
// Gray: 2 bytes, range 0 .. (2^bitdepth)-1
{
auto const png_path = png_in + "tbbn0g04.png";
gil::image_read_settings<gil::png_tag> settings;
settings.set_read_members_true();
auto backend = gil::read_image_info(png_path, settings);
BOOST_TEST_EQ(backend._info._width, 32u);
BOOST_TEST_EQ(backend._info._height, 32u);
BOOST_TEST_EQ(backend._info._bit_depth, 4);
BOOST_TEST_EQ(backend._info._num_channels, 1u);
BOOST_TEST_EQ(backend._info._color_type, PNG_COLOR_TYPE_GRAY);
gray_alpha8_image_t img;
read_image(png_path, img, settings);
BOOST_TEST_EQ(backend._info._width, 32u);
BOOST_TEST_EQ(backend._info._height, 32u);
BOOST_TEST_EQ(const_view(img).front(), gray_alpha8c_pixel_t(255, 0));
BOOST_TEST_EQ(const_view(img)[78], gray_alpha8c_pixel_t(221, 255));
BOOST_TEST_EQ(const_view(img)[79], gray_alpha8c_pixel_t(204, 255));
BOOST_TEST_EQ(const_view(img)[975], gray_alpha8c_pixel_t(238, 255));
BOOST_TEST_EQ(const_view(img)[976], gray_alpha8c_pixel_t(221, 255));
BOOST_TEST_EQ(const_view(img).back(), gray_alpha8c_pixel_t(255, 0));
}
{
auto const png_path = png_in + "tbwn0g16.png";
gil::image_read_settings<gil::png_tag> settings;
settings.set_read_members_true();
auto backend = gil::read_image_info(png_path, settings);
BOOST_TEST_EQ(backend._info._width, 32u);
BOOST_TEST_EQ(backend._info._height, 32u);
BOOST_TEST_EQ(backend._info._bit_depth, 16);
BOOST_TEST_EQ(backend._info._num_channels, 1u);
BOOST_TEST_EQ(backend._info._color_type, PNG_COLOR_TYPE_GRAY);
gray_alpha16_image_t img;
read_image(png_path, img, settings);
BOOST_TEST_EQ(backend._info._width, 32u);
BOOST_TEST_EQ(backend._info._height, 32u);
BOOST_TEST_EQ(const_view(img).front(), gray_alpha16c_pixel_t(65535, 0));
BOOST_TEST_EQ(const_view(img)[78], gray_alpha16c_pixel_t(58339, 65535));
BOOST_TEST_EQ(const_view(img)[79], gray_alpha16c_pixel_t(51657, 65535));
BOOST_TEST_EQ(const_view(img)[975], gray_alpha16c_pixel_t(62965, 65535));
BOOST_TEST_EQ(const_view(img)[976], gray_alpha16c_pixel_t(58339, 65535));
BOOST_TEST_EQ(const_view(img).back(), gray_alpha16c_pixel_t(65535, 0));
}
}
void test_read_with_trns_chunk_color_type_2()
{
// PNG 1.2: For color type 2 (truecolor), the tRNS chunk contains a single RGB color value,
// stored in the format:
//
// Red: 2 bytes, range 0 .. (2^bitdepth)-1
// Green: 2 bytes, range 0 .. (2^bitdepth)-1
// Blue: 2 bytes, range 0 .. (2^bitdepth)-1
{
auto const png_path = png_in + "tbbn2c16.png";
gil::image_read_settings<gil::png_tag> settings;
settings.set_read_members_true();
auto backend = gil::read_image_info(png_path, settings);
BOOST_TEST_EQ(backend._info._width, 32u);
BOOST_TEST_EQ(backend._info._height, 32u);
BOOST_TEST_EQ(backend._info._bit_depth, 16);
BOOST_TEST_EQ(backend._info._num_channels, 3u);
BOOST_TEST_EQ(backend._info._color_type, PNG_COLOR_TYPE_RGB);
gil::rgba16_image_t img;
read_image(png_path, img, settings);
BOOST_TEST_EQ(backend._info._width, 32u);
BOOST_TEST_EQ(backend._info._height, 32u);
BOOST_TEST_EQ(const_view(img).front(), gil::rgba16c_pixel_t(65535, 65535, 65535, 0));
BOOST_TEST_EQ(const_view(img)[78], gil::rgba16c_pixel_t(58339, 58339, 58339, 65535));
BOOST_TEST_EQ(const_view(img)[79], gil::rgba16c_pixel_t(51657, 51657, 51657, 65535));
BOOST_TEST_EQ(const_view(img)[975], gil::rgba16c_pixel_t(62965, 62965, 62965, 65535));
BOOST_TEST_EQ(const_view(img)[976], gil::rgba16c_pixel_t(58339, 58339, 58339, 65535));
BOOST_TEST_EQ(const_view(img).back(), gil::rgba16c_pixel_t(65535, 65535, 65535, 0));
}
{
auto const png_path = png_in + "tbgn2c16.png";
gil::image_read_settings<gil::png_tag> settings;
settings.set_read_members_true();
auto backend = gil::read_image_info(png_path, settings);
BOOST_TEST_EQ(backend._info._width, 32u);
BOOST_TEST_EQ(backend._info._height, 32u);
BOOST_TEST_EQ(backend._info._bit_depth, 16);
BOOST_TEST_EQ(backend._info._num_channels, 3u);
BOOST_TEST_EQ(backend._info._color_type, PNG_COLOR_TYPE_RGB);
gil::rgba16_image_t img;
read_image(png_path, img, settings);
BOOST_TEST_EQ(backend._info._width, 32u);
BOOST_TEST_EQ(backend._info._height, 32u);
BOOST_TEST_EQ(const_view(img).front(), gil::rgba16c_pixel_t(65535, 65535, 65535, 0));
BOOST_TEST_EQ(const_view(img)[78], gil::rgba16c_pixel_t(58339, 58339, 58339, 65535));
BOOST_TEST_EQ(const_view(img)[79], gil::rgba16c_pixel_t(51657, 51657, 51657, 65535));
BOOST_TEST_EQ(const_view(img)[975], gil::rgba16c_pixel_t(62965, 62965, 62965, 65535));
BOOST_TEST_EQ(const_view(img)[976], gil::rgba16c_pixel_t(58339, 58339, 58339, 65535));
BOOST_TEST_EQ(const_view(img).back(), gil::rgba16c_pixel_t(65535, 65535, 65535, 0));
}
{
auto const png_path = png_in + "tbrn2c08.png";
gil::image_read_settings<gil::png_tag> settings;
settings.set_read_members_true();
auto backend = gil::read_image_info(png_path, settings);
BOOST_TEST_EQ(backend._info._width, 32u);
BOOST_TEST_EQ(backend._info._height, 32u);
BOOST_TEST_EQ(backend._info._bit_depth, 8);
BOOST_TEST_EQ(backend._info._num_channels, 3u);
BOOST_TEST_EQ(backend._info._color_type, PNG_COLOR_TYPE_RGB);
gil::rgba8_image_t img;
read_image(png_path, img, settings);
BOOST_TEST_EQ(backend._info._width, 32u);
BOOST_TEST_EQ(backend._info._height, 32u);
BOOST_TEST_EQ(const_view(img).front(), gil::rgba8c_pixel_t(255, 255, 255, 0));
BOOST_TEST_EQ(const_view(img)[78], gil::rgba8c_pixel_t(227, 227, 227, 255));
BOOST_TEST_EQ(const_view(img)[79], gil::rgba8c_pixel_t(201, 201, 201, 255));
BOOST_TEST_EQ(const_view(img)[975], gil::rgba8c_pixel_t(245, 245, 245, 255));
BOOST_TEST_EQ(const_view(img)[976], gil::rgba8c_pixel_t(227, 227, 227, 255));
BOOST_TEST_EQ(const_view(img).back(), gil::rgba8c_pixel_t(255, 255, 255, 0));
}
}
void test_read_with_trns_chunk_color_type_3()
{
// PNG 1.2: For color type 3 (indexed color), the tRNS chunk contains a series of one-byte
// alpha values, corresponding to entries in the PLTE chunk:
//
// Alpha for palette index 0: 1 byte
// Alpha for palette index 1: 1 byte
// ...etc...
{
auto const png_path = png_in + "tbbn3p08.png";
gil::image_read_settings<gil::png_tag> settings;
settings.set_read_members_true();
auto backend = gil::read_image_info(png_path, settings);
BOOST_TEST_EQ(backend._info._width, 32u);
BOOST_TEST_EQ(backend._info._height, 32u);
BOOST_TEST_EQ(backend._info._bit_depth, 8);
BOOST_TEST_EQ(backend._info._num_channels, 1u);
BOOST_TEST_EQ(backend._info._color_type, PNG_COLOR_TYPE_PALETTE);
gil::rgba8_image_t img;
read_image(png_path, img, settings);
BOOST_TEST_EQ(backend._info._width, 32u);
BOOST_TEST_EQ(backend._info._height, 32u);
BOOST_TEST_EQ(const_view(img).front(), gil::rgba8c_pixel_t(255, 255, 255, 0));
BOOST_TEST_EQ(const_view(img)[78], gil::rgba8c_pixel_t(227, 227, 227, 255));
BOOST_TEST_EQ(const_view(img)[79], gil::rgba8c_pixel_t(201, 201, 201, 255));
BOOST_TEST_EQ(const_view(img)[975], gil::rgba8c_pixel_t(246, 246, 246, 255));
BOOST_TEST_EQ(const_view(img)[976], gil::rgba8c_pixel_t(227, 227, 227, 255));
BOOST_TEST_EQ(const_view(img).back(), gil::rgba8c_pixel_t(255, 255, 255, 0));
}
{
auto const png_path = png_in + "tbgn3p08.png";
gil::image_read_settings<gil::png_tag> settings;
settings.set_read_members_true();
auto backend = gil::read_image_info(png_path, settings);
BOOST_TEST_EQ(backend._info._width, 32u);
BOOST_TEST_EQ(backend._info._height, 32u);
BOOST_TEST_EQ(backend._info._bit_depth, 8);
BOOST_TEST_EQ(backend._info._num_channels, 1u);
BOOST_TEST_EQ(backend._info._color_type, PNG_COLOR_TYPE_PALETTE);
gil::rgba8_image_t img;
read_image(png_path, img, settings);
BOOST_TEST_EQ(backend._info._width, 32u);
BOOST_TEST_EQ(backend._info._height, 32u);
BOOST_TEST_EQ(const_view(img).front(), gil::rgba8c_pixel_t(255, 255, 255, 0));
BOOST_TEST_EQ(const_view(img)[78], gil::rgba8c_pixel_t(227, 227, 227, 255));
BOOST_TEST_EQ(const_view(img)[79], gil::rgba8c_pixel_t(201, 201, 201, 255));
BOOST_TEST_EQ(const_view(img)[975], gil::rgba8c_pixel_t(246, 246, 246, 255));
BOOST_TEST_EQ(const_view(img)[976], gil::rgba8c_pixel_t(227, 227, 227, 255));
BOOST_TEST_EQ(const_view(img).back(), gil::rgba8c_pixel_t(255, 255, 255, 0));
}
{
auto const png_path = png_in + "tp1n3p08.png";
gil::image_read_settings<gil::png_tag> settings;
settings.set_read_members_true();
auto backend = gil::read_image_info(png_path, settings);
BOOST_TEST_EQ(backend._info._width, 32u);
BOOST_TEST_EQ(backend._info._height, 32u);
BOOST_TEST_EQ(backend._info._bit_depth, 8);
BOOST_TEST_EQ(backend._info._num_channels, 1u);
BOOST_TEST_EQ(backend._info._color_type, PNG_COLOR_TYPE_PALETTE);
gil::rgba8_image_t img;
read_image(png_path, img, settings);
BOOST_TEST_EQ(backend._info._width, 32u);
BOOST_TEST_EQ(backend._info._height, 32u);
BOOST_TEST_EQ(const_view(img).front(), gil::rgba8c_pixel_t(255, 255, 255, 0));
BOOST_TEST_EQ(const_view(img)[78], gil::rgba8c_pixel_t(227, 227, 227, 255));
BOOST_TEST_EQ(const_view(img)[79], gil::rgba8c_pixel_t(201, 201, 201, 255));
BOOST_TEST_EQ(const_view(img)[975], gil::rgba8c_pixel_t(246, 246, 246, 255));
BOOST_TEST_EQ(const_view(img)[976], gil::rgba8c_pixel_t(227, 227, 227, 255));
BOOST_TEST_EQ(const_view(img).back(), gil::rgba8c_pixel_t(255, 255, 255, 0));
}
{
auto const png_path = png_in + "tm3n3p02.png";
gil::image_read_settings<gil::png_tag> settings;
settings.set_read_members_true();
auto backend = gil::read_image_info(png_path, settings);
BOOST_TEST_EQ(backend._info._width, 32u);
BOOST_TEST_EQ(backend._info._height, 32u);
BOOST_TEST_EQ(backend._info._bit_depth, 2);
BOOST_TEST_EQ(backend._info._num_channels, 1u);
BOOST_TEST_EQ(backend._info._color_type, PNG_COLOR_TYPE_PALETTE);
gil::rgba8_image_t img;
read_image(png_path, img, settings);
BOOST_TEST_EQ(backend._info._width, 32u);
BOOST_TEST_EQ(backend._info._height, 32u);
BOOST_TEST_EQ(const_view(img).front(), gil::rgba8c_pixel_t(0, 0, 255, 0));
BOOST_TEST_EQ(const_view(img)[16], gil::rgba8c_pixel_t(0, 0, 255, 85));
BOOST_TEST_EQ(const_view(img)[511], gil::rgba8c_pixel_t(0, 0, 255, 85));
BOOST_TEST_EQ(const_view(img)[1007], gil::rgba8c_pixel_t(0, 0, 255, 170));
BOOST_TEST_EQ(const_view(img).back(), gil::rgba8c_pixel_t(0, 0, 255, 255));
}
}
#endif // BOOST_GIL_IO_TEST_ALLOW_READING_IMAGES
#ifdef BOOST_GIL_IO_USE_PNG_TEST_SUITE_IMAGES
void test_basic_format()
{
// Basic format test files (non-interlaced)
// BASN0g01 - black & white
test_file<gil::gray1_image_t>("BASN0G01.PNG");
test_png_scanline_reader<gil::gray1_image_t>("BASN0G01.PNG");
// BASN0g02 - 2 bit (4 level) grayscale
test_file<gil::gray2_image_t>("BASN0G02.PNG");
test_png_scanline_reader<gil::gray2_image_t>("BASN0G02.PNG");
// BASN0g04 - 4 bit (16 level) grayscale
test_file<gil::gray4_image_t>("BASN0G04.PNG");
test_png_scanline_reader<gil::gray4_image_t>("BASN0G04.PNG");
// BASN0g08 - 8 bit (256 level) grayscale
test_file<gil::gray8_image_t>("BASN0G08.PNG");
test_png_scanline_reader<gil::gray8_image_t>("BASN0G08.PNG");
// BASN0g16 - 16 bit (64k level) grayscale
test_file<gil::gray16_image_t>("BASN0G16.PNG");
test_png_scanline_reader<gil::gray16_image_t>("BASN0G16.PNG");
// BASN2c08 - 3x8 bits gil::rgb color
test_file<gil::rgb8_image_t>("BASN2C08.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("BASN2C08.PNG");
// BASN2c16 - 3x16 bits gil::rgb color
test_file<gil::rgb16_image_t>("BASN2C16.PNG");
test_png_scanline_reader<gil::rgb16_image_t>("BASN2C16.PNG");
// BASN3p01 - 1 bit (2 color) paletted
test_file<gil::rgb8_image_t>("BASN3P01.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("BASN3P01.PNG");
// BASN3p02 - 2 bit (4 color) paletted
test_file<gil::rgb8_image_t>("BASN3P02.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("BASN3P02.PNG");
// BASN3p04 - 4 bit (16 color) paletted
test_file<gil::rgb8_image_t>("BASN3P04.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("BASN3P04.PNG");
// BASN3p08 - 8 bit (256 color) paletted
test_file<gil::rgb8_image_t>("BASN3P08.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("BASN3P08.PNG");
// BASN4a08 - 8 bit grayscale + 8 bit alpha-channel
test_file<gil::gray_alpha8_image_t>("BASN4A08.PNG");
test_png_scanline_reader<gil::gray_alpha8_image_t>("BASN4A08.PNG");
// BASN4a16 - 16 bit grayscale + 16 bit alpha-channel
test_file<gil::gray_alpha16_image_t>("BASN4A16.PNG");
test_png_scanline_reader<gil::gray_alpha16_image_t>("BASN4A16.PNG");
// BASN6a08 - 3x8 bits gil::rgb color + 8 bit alpha-channel
test_file<gil::rgba8_image_t>("BASN6A08.PNG");
test_png_scanline_reader<gil::rgba8_image_t>("BASN6A08.PNG");
// BASN6a16 - 3x16 bits gil::rgb color + 16 bit alpha-channel
test_file<gil::rgba16_image_t>("BASN6A16.PNG");
test_png_scanline_reader<gil::rgba16_image_t>("BASN6A16.PNG");
}
void test_basic_format_interlaced()
{
// Basic format test files (Adam-7 interlaced)
// BASI0g01 - black & white
test_file<gil::gray1_image_t>("BASI0G01.PNG");
// BASI0g02 - 2 bit (4 level) grayscale
test_file<gil::gray2_image_t>("BASI0G02.PNG");
// BASI0g04 - 4 bit (16 level) grayscale
test_file<gil::gray4_image_t>("BASI0G04.PNG");
// BASI0g08 - 8 bit (256 level) grayscale
test_file<gil::gray8_image_t>("BASI0G08.PNG");
// BASI0g16 - 16 bit (64k level) grayscale
test_file<gil::gray16_image_t>("BASI0G16.PNG");
// BASI2c08 - 3x8 bits gil::rgb color
test_file<gil::rgb8_image_t>("BASI2C08.PNG");
// BASI2c16 - 3x16 bits gil::rgb color
test_file<gil::rgb16_image_t>("BASI2C16.PNG");
// BASI3p01 - 1 bit (2 color) paletted
test_file<gil::rgb8_image_t>("BASI3P01.PNG");
// BASI3p02 - 2 bit (4 color) paletted
test_file<gil::rgb8_image_t>("BASI3P02.PNG");
// BASI3p04 - 4 bit (16 color) paletted
test_file<gil::rgb8_image_t>("BASI3P04.PNG");
// BASI3p08 - 8 bit (256 color) paletted
test_file<gil::rgb8_image_t>("BASI3P08.PNG");
// BASI4a08 - 8 bit grayscale + 8 bit alpha-channel
test_file<gil::gray_alpha8_image_t>("BASI4A08.PNG");
// BASI4a16 - 16 bit grayscale + 16 bit alpha-channel
test_file<gil::gray_alpha16_image_t>("BASI4A16.PNG");
// BASI6a08 - 3x8 bits gil::rgb color + 8 bit alpha-channel
test_file<gil::rgba8_image_t>("BASI6A08.PNG");
// BASI6a16 - 3x16 bits gil::rgb color + 16 bit alpha-channel
test_file<gil::rgba16_image_t>("BASI6A16.PNG");
}
void test_odd_sizes()
{
// S01I3P01 - 1x1 paletted file, interlaced
test_file<gil::rgb8_image_t>("S01I3P01.PNG");
// S01N3P01 - 1x1 paletted file, no interlacing
test_file<gil::rgb8_image_t>("S01N3P01.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("S01N3P01.PNG");
// S02I3P01 - 2x2 paletted file, interlaced
test_file<gil::rgb8_image_t>("S02I3P01.PNG");
// S02N3P01 - 2x2 paletted file, no interlacing
test_file<gil::rgb8_image_t>("S02N3P01.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("S02N3P01.PNG");
// S03I3P01 - 3x3 paletted file, interlaced
test_file<gil::rgb8_image_t>("S03I3P01.PNG");
// S03N3P01 - 3x3 paletted file, no interlacing
test_file<gil::rgb8_image_t>("S03N3P01.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("S03N3P01.PNG");
// S04I3P01 - 4x4 paletted file, interlaced
test_file<gil::rgb8_image_t>("S04I3P01.PNG");
// S04N3P01 - 4x4 paletted file, no interlacing
test_file<gil::rgb8_image_t>("S04N3P01.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("S04N3P01.PNG");
// S05I3P02 - 5x5 paletted file, interlaced
test_file<gil::rgb8_image_t>("S05I3P02.PNG");
// S05N3P02 - 5x5 paletted file, no interlacing
test_file<gil::rgb8_image_t>("S05N3P02.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("S05N3P02.PNG");
// S06I3P02 - 6x6 paletted file, interlaced
test_file<gil::rgb8_image_t>("S06I3P02.PNG");
// S06N3P02 - 6x6 paletted file, no interlacing
test_file<gil::rgb8_image_t>("S06N3P02.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("S06N3P02.PNG");
// S07I3P02 - 7x7 paletted file, interlaced
test_file<gil::rgb8_image_t>("S07I3P02.PNG");
// S07N3P02 - 7x7 paletted file, no interlacing
test_file<gil::rgb8_image_t>("S07N3P02.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("S07N3P02.PNG");
// S08I3P02 - 8x8 paletted file, interlaced
test_file<gil::rgb8_image_t>("S08I3P02.PNG");
// S08N3P02 - 8x8 paletted file, no interlacing
test_file<gil::rgb8_image_t>("S08N3P02.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("S08N3P02.PNG");
// S09I3P02 - 9x9 paletted file, interlaced
test_file<gil::rgb8_image_t>("S09I3P02.PNG");
// S09N3P02 - 9x9 paletted file, no interlacing
test_file<gil::rgb8_image_t>("S09N3P02.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("S09N3P02.PNG");
// S32I3P04 - 32x32 paletted file, interlaced
test_file<gil::rgb8_image_t>("S32I3P04.PNG");
// S32N3P04 - 32x32 paletted file, no interlacing
test_file<gil::rgb8_image_t>("S32N3P04.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("S32N3P04.PNG");
// S33I3P04 - 33x33 paletted file, interlaced
test_file<gil::rgb8_image_t>("S33I3P04.PNG");
// S33N3P04 - 33x33 paletted file, no interlacing
test_file<gil::rgb8_image_t>("S33N3P04.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("S33N3P04.PNG");
// S34I3P04 - 34x34 paletted file, interlaced
test_file<gil::rgb8_image_t>("S34I3P04.PNG");
// S34N3P04 - 34x34 paletted file, no interlacing
test_file<gil::rgb8_image_t>("S34N3P04.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("S34N3P04.PNG");
// S35I3P04 - 35x35 paletted file, interlaced
test_file<gil::rgb8_image_t>("S35I3P04.PNG");
// S35N3P04 - 35x35 paletted file, no interlacing
test_file<gil::rgb8_image_t>("S35N3P04.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("S35N3P04.PNG");
// S36I3P04 - 36x36 paletted file, interlaced
test_file<gil::rgb8_image_t>("S36I3P04.PNG");
// S36N3P04 - 36x36 paletted file, no interlacing
test_file<gil::rgb8_image_t>("S36N3P04.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("S36N3P04.PNG");
// S37I3P04 - 37x37 paletted file, interlaced
test_file<gil::rgb8_image_t>("S37I3P04.PNG");
// S37N3P04 - 37x37 paletted file, no interlacing
test_file<gil::rgb8_image_t>("S37N3P04.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("S37N3P04.PNG");
// S38I3P04 - 38x38 paletted file, interlaced
test_file<gil::rgb8_image_t>("S38I3P04.PNG");
// S38N3P04 - 38x38 paletted file, no interlacing
test_file<gil::rgb8_image_t>("S38N3P04.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("S38N3P04.PNG");
// S39I3P04 - 39x39 paletted file, interlaced
test_file<gil::rgb8_image_t>("S39I3P04.PNG");
// S39N3P04 - 39x39 paletted file, no interlacing
test_file<gil::rgb8_image_t>("S39N3P04.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("S39N3P04.PNG");
// S40I3P04 - 40x40 paletted file, interlaced
test_file<gil::rgb8_image_t>("S40I3P04.PNG");
// S40N3P04 - 40x40 paletted file, no interlacing
test_file<gil::rgb8_image_t>("S40N3P04.PNG");
test_png_scanline_reader<gil::rgb8_image_t>("S40N3P04.PNG");
}
void test_background()
{
// BGAI4A08 - 8 bit grayscale, alpha, no background chunk, interlaced
test_file<gil::gray_alpha8_image_t>("BGAI4A08.PNG");
// BGAI4A16 - 16 bit grayscale, alpha, no background chunk, interlaced
test_file<gil::gray_alpha16_image_t>("BGAI4A16.PNG");
// BGAN6A08 - 3x8 bits gil::rgb color, alpha, no background chunk
test_file<gil::rgba8_image_t>("BGAN6A08.PNG");
// BGAN6A16 - 3x16 bits gil::rgb color, alpha, no background chunk
test_file<gil::rgba16_image_t>("BGAN6A16.PNG");
// BGBN4A08 - 8 bit grayscale, alpha, black background chunk
test_file<gil::gray_alpha8_image_t>("BGBN4A08.PNG");
// BGGN4A16 - 16 bit grayscale, alpha, gray background chunk
test_file<gil::gray_alpha16_image_t>("BGGN4A16.PNG");
// BGWN6A08 - 3x8 bits gil::rgb color, alpha, white background chunk
test_file<gil::rgba8_image_t>("BGWN6A08.PNG");
// BGYN6A16 - 3x16 bits gil::rgb color, alpha, yellow background chunk
test_file<gil::rgba16_image_t>("BGYN6A16.PNG");
}
void test_transparency()
{
// TBBN1G04 - transparent, black background chunk
// file missing
//test_file<gil::gray_alpha8_image_t>("TBBN1G04.PNG" );
// TBBN2C16 - transparent, blue background chunk
test_file<gil::rgba16_image_t>("TBBN2C16.PNG");
// TBBN3P08 - transparent, black background chunk
test_file<gil::rgba8_image_t>("TBBN3P08.PNG");
// TBGN2C16 - transparent, green background chunk
test_file<gil::rgba16_image_t>("TBGN2C16.PNG");
// TBGN3P08 - transparent, light-gray background chunk
test_file<gil::rgba8_image_t>("TBGN3P08.PNG");
// TBRN2C08 - transparent, red background chunk
test_file<gil::rgba8_image_t>("TBRN2C08.PNG");
// TBWN1G16 - transparent, white background chunk
test_file<gil::gray_alpha16_image_t>("TBWN0G16.PNG");
// TBWN3P08 - transparent, white background chunk
test_file<gil::rgba8_image_t>("TBWN3P08.PNG");
// TBYN3P08 - transparent, yellow background chunk
test_file<gil::rgba8_image_t>("TBYN3P08.PNG");
// TP0N1G08 - not transparent for reference (logo on gray)
test_file<gil::gray8_image_t>("TP0N0G08.PNG");
// TP0N2C08 - not transparent for reference (logo on gray)
test_file<gil::rgb8_image_t>("TP0N2C08.PNG");
// TP0N3P08 - not transparent for reference (logo on gray)
test_file<gil::rgb8_image_t>("TP0N3P08.PNG");
// TP1N3P08 - transparent, but no background chunk
test_file<gil::rgba8_image_t>("TP1N3P08.PNG");
}
void test_gamma()
{
// G03N0G16 - grayscale, file-gamma = 0.35
test_file<gil::gray16_image_t>("G03N0G16.PNG");
// G03N2C08 - color, file-gamma = 0.35
test_file<gil::rgb8_image_t>("G03N2C08.PNG");
// G03N3P04 - paletted, file-gamma = 0.35
test_file<gil::rgb8_image_t>("G03N3P04.PNG");
// G04N0G16 - grayscale, file-gamma = 0.45
test_file<gil::gray16_image_t>("G04N0G16.PNG");
// G04N2C08 - color, file-gamma = 0.45
test_file<gil::rgb8_image_t>("G04N2C08.PNG");
// G04N3P04 - paletted, file-gamma = 0.45
test_file<gil::rgb8_image_t>("G04N3P04.PNG");
// G05N0G16 - grayscale, file-gamma = 0.55
test_file<gil::gray16_image_t>("G05N0G16.PNG");
// G05N2C08 - color, file-gamma = 0.55
test_file<gil::rgb8_image_t>("G05N2C08.PNG");
// G05N3P04 - paletted, file-gamma = 0.55
test_file<gil::rgb8_image_t>("G05N3P04.PNG");
// G07N0G16 - grayscale, file-gamma = 0.70
test_file<gil::gray16_image_t>("G07N0G16.PNG");
// G07N2C08 - color, file-gamma = 0.70
test_file<gil::rgb8_image_t>("G07N2C08.PNG");
// G07N3P04 - paletted, file-gamma = 0.70
test_file<gil::rgb8_image_t>("G07N3P04.PNG");
// G10N0G16 - grayscale, file-gamma = 1.00
test_file<gil::gray16_image_t>("G10N0G16.PNG");
// G10N2C08 - color, file-gamma = 1.00
test_file<gil::rgb8_image_t>("G10N2C08.PNG");
// G10N3P04 - paletted, file-gamma = 1.00
test_file<gil::rgb8_image_t>("G10N3P04.PNG");
// G25N0G16 - grayscale, file-gamma = 2.50
test_file<gil::gray16_image_t>("G25N0G16.PNG");
// G25N2C08 - color, file-gamma = 2.50
test_file<gil::rgb8_image_t>("G25N2C08.PNG");
// G25N3P04 - paletted, file-gamma = 2.50
test_file<gil::rgb8_image_t>("G25N3P04.PNG");
}
#endif // BOOST_GIL_IO_USE_PNG_TEST_SUITE_IMAGES
void test_corrupted_png_read()
{
// taken from https://github.com/boostorg/gil/issues/401#issue-518615480
// author: https://github.com/misos1
std::initializer_list<unsigned char> corrupt_png = {
0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A,
0x00, 0x00, 0x00, 0x0D,
'I', 'H', 'D', 'R',
0x00, 0x00, 0x04, 0x00,
0x00, 0x00, 0x05, 0xA9,
0x08, 0x02, 0x00, 0x00, 0x00,
0x68, 0x1B, 0xF7, 0x46,
0x00, 0x00, 0x00, 0x00,
'I', 'D', 'A', 'T',
0x35, 0xAF, 0x06, 0x1E,
0x00, 0x00, 0x00, 0x00,
'I', 'E', 'N', 'D',
0xAE, 0x42, 0x60, 0x82
};
std::stringstream ss(
std::string(corrupt_png.begin(), corrupt_png.end()),
std::ios_base::in | std::ios_base::binary);
boost::gil::rgb8_image_t img;
// TODO: Replace with BOOST_ERROR below with BOOST_TEST_THROWS
try
{
boost::gil::read_image(ss, img, boost::gil::png_tag{});
}
catch (std::ios_base::failure& exception)
{
// the exception message is "png is invalid: iostream error"
// is the error portable throughout stdlib implementations,
// or is it native to this one?
// the description passd is "png_is_invalid"
// the exact error message is thus not checked
return;
}
BOOST_ERROR("no exception was thrown, which is an error");
}
int main()
{
test_read_header();
test_corrupted_png_read();
#ifdef BOOST_GIL_IO_TEST_ALLOW_READING_IMAGES
test_read_pixel_per_meter();
test_read_with_trns_chunk_color_type_0();
test_read_with_trns_chunk_color_type_2();
test_read_with_trns_chunk_color_type_3();
#endif // BOOST_GIL_IO_TEST_ALLOW_READING_IMAGES
#ifdef BOOST_GIL_IO_USE_PNG_TEST_SUITE_IMAGES
test_basic_format();
test_basic_format_interlaced();
test_odd_sizes();
test_background();
test_transparency();
test_gamma();
#endif
return boost::report_errors();
}
| davehorton/drachtio-server | deps/boost_1_77_0/libs/gil/test/extension/io/png/png_read_test.cpp | C++ | mit | 30,494 |
package com.duck8823.web.line;
import com.duck8823.model.bot.BotEnv;
import com.duck8823.model.bot.Talk;
import com.duck8823.model.bot.TalkBot;
import com.duck8823.model.open.weather.map.OpenWeatherMap;
import com.duck8823.model.photo.Photo;
import com.duck8823.service.BotEnvService;
import com.duck8823.service.PhotoService;
import com.flickr4java.flickr.Flickr;
import com.flickr4java.flickr.FlickrException;
import com.flickr4java.flickr.photos.PhotoList;
import com.flickr4java.flickr.photos.SearchParameters;
import com.linecorp.bot.client.LineMessagingService;
import com.linecorp.bot.model.PushMessage;
import com.linecorp.bot.model.ReplyMessage;
import com.linecorp.bot.model.action.Action;
import com.linecorp.bot.model.action.MessageAction;
import com.linecorp.bot.model.action.PostbackAction;
import com.linecorp.bot.model.event.*;
import com.linecorp.bot.model.event.message.LocationMessageContent;
import com.linecorp.bot.model.event.message.TextMessageContent;
import com.linecorp.bot.model.message.ImageMessage;
import com.linecorp.bot.model.message.LocationMessage;
import com.linecorp.bot.model.message.TemplateMessage;
import com.linecorp.bot.model.message.TextMessage;
import com.linecorp.bot.model.message.template.CarouselColumn;
import com.linecorp.bot.model.message.template.CarouselTemplate;
import com.linecorp.bot.model.message.template.ConfirmTemplate;
import com.linecorp.bot.spring.boot.annotation.LineBotMessages;
import lombok.extern.log4j.Log4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import retrofit2.Response;
import javax.transaction.Transactional;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* LINE BOT をためす
* Created by maeda on 7/30/2016.
*/
@Transactional
@Log4j
@RequestMapping("line")
@RestController
public class LineController {
@Autowired
LineMessagingService lineMessagingService;
@Autowired
private TalkBot talkBot;
@Autowired
private PhotoService photoService;
@Autowired
private BotEnvService botEnvService;
@Autowired
private Flickr flickr;
@Autowired
private OpenWeatherMap openWeatherMap;
@RequestMapping(path = "callback", method = RequestMethod.POST)
public void callback(@LineBotMessages List<Event> events) throws IOException, FlickrException, ParseException {
log.debug("line bot callback.");
for (Event event : events) {
log.debug(event);
if (event instanceof MessageEvent) {
String id = event.getSource().getSenderId() != null ? event.getSource().getSenderId() : event.getSource().getUserId();
Optional<BotEnv> botEnv = botEnvService.findById(id);
TextMessageContent message = null;
if (((MessageEvent) event).getMessage() instanceof TextMessageContent) {
message = (TextMessageContent) ((MessageEvent) event).getMessage();
} else if (((MessageEvent) event).getMessage() instanceof LocationMessageContent) {
List<CarouselColumn> columns = new ArrayList<>();
LocationMessageContent locationMessage = (LocationMessageContent) ((MessageEvent) event).getMessage();
JSONObject res = openWeatherMap.search(locationMessage.getLatitude(), locationMessage.getLongitude());
JSONArray list = res.getJSONArray("list");
for(int i = 0; i < list.length() && i < 5; i++) {
JSONObject itemJSON = list.getJSONObject(i);
log.debug(itemJSON);
JSONObject weatherJSON = itemJSON.getJSONArray("weather").getJSONObject(0);
String thumbnail = "https://openweathermap.org/img/w/" + weatherJSON.getString("icon") + ".png";
log.debug(thumbnail);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse(itemJSON.getString("dt_txt"));
sdf.setTimeZone(TimeZone.getTimeZone("JST"));
String dateTxt = sdf.format(date);
columns.add(new CarouselColumn(
thumbnail,
dateTxt,
String.join("\n",
weatherJSON.getString("description"),
"temp: " + itemJSON.getJSONObject("main").getDouble("temp"),
"humidity: " + itemJSON.getJSONObject("main").getDouble("humidity")
),
Collections.singletonList(
new MessageAction("画像", weatherJSON.getString("description") + " 画像")
)
));
}
Response response = lineMessagingService.replyMessage(new ReplyMessage(
((MessageEvent) event).getReplyToken(),
new TemplateMessage("template message", new CarouselTemplate(columns))
)).execute();
log.debug(response.isSuccessful());
log.debug(response.message());
break;
} else {
return;
}
if (message.getText().contains("wiki")) {
String searchText = message.getText().replaceAll("(\\s| )*wiki(\\s| )*", "");
if (searchText.isEmpty()) {
break;
}
log.debug(searchText);
Response response = lineMessagingService.replyMessage(new ReplyMessage(
((MessageEvent) event).getReplyToken(),
new TextMessage("https://ja.wikipedia.org/wiki/" + URLEncoder.encode(searchText, "UTF-8"))
)).execute();
log.debug(response.isSuccessful());
log.debug(response.message());
} else if (message.getText().contains("画像")) {
String searchText = message.getText().replaceAll("(\\s| )*画像(\\s| )*", "");
if (searchText.isEmpty()) {
break;
}
log.debug(searchText);
SearchParameters params = new SearchParameters();
params.setText(searchText);
params.setSort(SearchParameters.RELEVANCE);
flickr.getPhotosInterface().search(params, 1, 1).forEach(photo -> {
try {
Response response = lineMessagingService.replyMessage(new ReplyMessage(
((MessageEvent) event).getReplyToken(),
new ImageMessage(photo.getMediumUrl(), photo.getSmallUrl())
)).execute();
log.debug(response.isSuccessful());
log.debug(response.message());
} catch (IOException e) {
throw new IllegalStateException(e);
}
});
} else if (message.getText().contains("しゃべって") || message.getText().contains("喋って")) {
botEnvService.save(new BotEnv(id, false, null, null));
Response response = lineMessagingService.replyMessage(new ReplyMessage(
((MessageEvent) event).getReplyToken(),
new TextMessage("喋ります!")
)).execute();
log.debug(response.isSuccessful());
log.debug(response.message());
} else if (botEnv.isPresent() && botEnv.get().getQuiet()) {
break;
} else if (message.getText().contains("だまれ") || message.getText().contains("黙れ") || message.getText().contains("静かにして")) {
botEnvService.save(new BotEnv(id, true, null, null));
Response response = lineMessagingService.replyMessage(new ReplyMessage(
((MessageEvent) event).getReplyToken(),
new TextMessage("黙ります...")
)).execute();
log.debug(response.isSuccessful());
log.debug(response.message());
} else if (message.getText().contains("写真")) {
Response response = lineMessagingService.replyMessage(new ReplyMessage(
((MessageEvent) event).getReplyToken(),
new TemplateMessage("写真",
new ConfirmTemplate("写真欲しいですか?",
Arrays.asList(
new PostbackAction("欲しい", "photo"),
new MessageAction("いらない.", "いらない.")
)
)
)
)).execute();
log.debug(response.isSuccessful());
log.debug(response.message());
} else {
BotEnv env = botEnv.orElse(new BotEnv(id));
Talk talkResponse = talkBot.talk(env.talk().respond(message.getText()));
env.setContext((String) talkResponse.get("context"));
env.setMode((String) talkResponse.get("mode"));
botEnvService.save(env);
Response response = lineMessagingService.replyMessage(
new ReplyMessage(
((MessageEvent) event).getReplyToken(),
new TextMessage(talkResponse.getContent())
)).execute();
log.debug(response.isSuccessful());
log.debug(response.message());
}
} else if (event instanceof FollowEvent) {
lineMessagingService.replyMessage(
new ReplyMessage(
((FollowEvent) event).getReplyToken(),
new TextMessage("このBotは docomo Developer supportのAPIを利用しています.\n会話の内容はドコモのサーバに送信されます.")
)).execute();
} else if (event instanceof JoinEvent) {
lineMessagingService.replyMessage(
new ReplyMessage(
((JoinEvent) event).getReplyToken(),
new TextMessage("このBotは docomo Developer supportのAPIを利用しています.\n会話の内容はドコモのサーバに送信されます.")
)).execute();
} else if (event instanceof PostbackEvent) {
switch (((PostbackEvent) event).getPostbackContent().getData()) {
case "photo":
Photo photo = photoService.random().get();
String url = "https://www.duck8823.com/photo/" + photo.getId();
Response response = lineMessagingService.replyMessage(
new ReplyMessage(
((PostbackEvent) event).getReplyToken(),
new ImageMessage(url, url)
)).execute();
log.debug(response.isSuccessful());
log.debug(response.message());
break;
}
}
}
}
}
| duck8823/demo | src/main/java/com/duck8823/web/line/LineController.java | Java | mit | 9,670 |
#include "global.h"
#include "tagcoloreditor.h"
#include "coloreditor.h"
#include "dcolordialog.h"
#include "staticfunctions.h"
#include <QTime>
#include <QInputDialog>
#include <QItemEditorFactory>
#include <QItemEditorCreatorBase>
#include <QItemDelegate>
#include <QVBoxLayout>
#include <QHeaderView>
TagColorEditor::TagColorEditor()
{
createGUI();
}
void
TagColorEditor::setColors()
{
QFont fnt("Helvetica", 10);
uchar *colors = Global::tagColors();
for (int i=0; i < 256; i++)
{
int r,g,b;
float a;
r = colors[4*i+0];
g = colors[4*i+1];
b = colors[4*i+2];
QTableWidgetItem *colorItem = new QTableWidgetItem;
colorItem->setFont(fnt);
colorItem->setData(Qt::DisplayRole, QString("%1").arg(i));
if (colors[4*i+3] > 250)
colorItem->setCheckState(Qt::Checked);
else
colorItem->setCheckState(Qt::Unchecked);
colorItem->setBackground(QColor(r,g,b));
//int row = i/8;
//int col = i%8;
int row, col;
if (i == 0)
{
row = 0;
col = 0;
}
else
{
row = 1 + (i-1)/5;
col = (i-1)%5;
}
table->setItem(row, col, colorItem);
}
}
void
TagColorEditor::showTagsClicked()
{
uchar *colors = Global::tagColors();
for(int i=0; i<256; i++)
colors[4*i+3] = 255;
setColors();
}
void
TagColorEditor::hideTagsClicked()
{
uchar *colors = Global::tagColors();
for(int i=0; i<256; i++)
colors[4*i+3] = 0;
setColors();
}
void
TagColorEditor::createGUI()
{
//table = new QTableWidget(32, 8);
table = new QTableWidget(52, 5);
table->resize(300, 300);
table->setEditTriggers(QAbstractItemView::NoEditTriggers); // disable number editing
table->verticalHeader()->hide();
table->horizontalHeader()->hide();
table->setSelectionMode(QAbstractItemView::NoSelection);
table->setStyleSheet("QTableWidget{gridline-color:white;}");
setColors();
for (int i=0; i < table->rowCount(); i++)
table->setRowHeight(i, 25);
for (int i=0; i < table->columnCount(); i++)
#if defined(Q_OS_WIN32)
table->setColumnWidth(i, 50);
#else
table->setColumnWidth(i, 60);
#endif
QPushButton *newTags = new QPushButton("New Tag Colors");
QPushButton *showTags = new QPushButton("Show All Tags");
QPushButton *hideTags = new QPushButton("Hide All Tags");
QHBoxLayout *hlayout = new QHBoxLayout;
hlayout->addWidget(newTags);
hlayout->addWidget(showTags);
hlayout->addWidget(hideTags);
QVBoxLayout *layout = new QVBoxLayout;
layout->addLayout(hlayout);
layout->addWidget(table);
setLayout(layout);
setWindowTitle(tr("Tag Color Editor"));
connect(newTags, SIGNAL(clicked()),
this, SLOT(newTagsClicked()));
connect(showTags, SIGNAL(clicked()),
this, SLOT(showTagsClicked()));
connect(hideTags, SIGNAL(clicked()),
this, SLOT(hideTagsClicked()));
connect(table, SIGNAL(cellClicked(int, int)),
this, SLOT(cellClicked(int, int)));
connect(table, SIGNAL(cellDoubleClicked(int, int)),
this, SLOT(cellDoubleClicked(int, int)));
}
void
TagColorEditor::newTagsClicked()
{
QStringList items;
items << "Random";
items << "Library";
bool ok;
QString str;
str = QInputDialog::getItem(0,
"Colors",
"Colors",
items,
0,
false, // text is not editable
&ok);
if (!ok)
return;
if (str == "Library")
newColorSet(1);
else
newColorSet(QTime::currentTime().msec());
emit tagColorChanged();
}
void
TagColorEditor::cellClicked(int row, int col)
{
if (row == 0 && col > 0)
return;
//int index = row*8 + col;
int index = 0;
if (row > 0) index = 1 + (row-1)*5 + col;
uchar *colors = Global::tagColors();
QTableWidgetItem *item = table->item(row, col);
if (item->checkState() == Qt::Checked)
colors[4*index+3] = 255;
else
colors[4*index+3] = 0;
emit tagSelected(index);
}
void
TagColorEditor::cellDoubleClicked(int row, int col)
{
if (row == 0 && col > 0)
return;
QTableWidgetItem *item = table->item(row, col);
uchar *colors = Global::tagColors();
//int index = row*8 + col;
int index = 0;
if (row > 0) index = 1 + (row-1)*5 + col;
QColor clr = QColor(colors[4*index+0],
colors[4*index+1],
colors[4*index+2]);
clr = DColorDialog::getColor(clr);
if (!clr.isValid())
return;
colors[4*index+0] = clr.red();
colors[4*index+1] = clr.green();
colors[4*index+2] = clr.blue();
item->setData(Qt::DisplayRole, QString("%1").arg(index));
item->setBackground(clr);
emit tagColorChanged();
}
void
TagColorEditor::newColorSet(int h)
{
if (h == 1)
{
askGradientChoice();
return;
}
qsrand(h);
uchar *colors = Global::tagColors();
for(int i=1; i<255; i++)
{
float r,g,b;
r = (float)qrand()/(float)RAND_MAX;
g = (float)qrand()/(float)RAND_MAX;
b = (float)qrand()/(float)RAND_MAX;
colors[4*i+0] = 255*r;
colors[4*i+1] = 255*g;
colors[4*i+2] = 255*b;
}
colors[0] = 0;
colors[1] = 0;
colors[2] = 0;
colors[3] = 0;
setColors();
}
void
TagColorEditor::copyGradientFile(QString stopsflnm)
{
QString sflnm = ":/images/gradientstops.xml";
QFileInfo fi(sflnm);
if (! fi.exists())
{
QMessageBox::information(0, "Gradient Stops",
QString("Gradient Stops file does not exit at %1").arg(sflnm));
return;
}
// copy information from gradientstops.xml to HOME/.drishtigradients.xml
QDomDocument document;
QFile f(sflnm);
if (f.open(QIODevice::ReadOnly))
{
document.setContent(&f);
f.close();
}
QFile fout(stopsflnm);
if (fout.open(QIODevice::WriteOnly))
{
QTextStream out(&fout);
document.save(out, 2);
fout.close();
}
}
void
TagColorEditor::askGradientChoice()
{
QString homePath = QDir::homePath();
QFileInfo sfi(homePath, ".drishtigradients.xml");
QString stopsflnm = sfi.absoluteFilePath();
if (!sfi.exists())
copyGradientFile(stopsflnm);
QDomDocument document;
QFile f(stopsflnm);
if (f.open(QIODevice::ReadOnly))
{
document.setContent(&f);
f.close();
}
QStringList glist;
QDomElement main = document.documentElement();
QDomNodeList dlist = main.childNodes();
for(int i=0; i<dlist.count(); i++)
{
if (dlist.at(i).nodeName() == "gradient")
{
QDomNodeList cnode = dlist.at(i).childNodes();
for(int j=0; j<cnode.count(); j++)
{
QDomElement dnode = cnode.at(j).toElement();
if (dnode.nodeName() == "name")
glist << dnode.text();
}
}
}
bool ok;
QString gstr = QInputDialog::getItem(0,
"Color Gradient",
"Color Gradient",
glist, 0, false,
&ok);
if (!ok)
return;
int cno = -1;
for(int i=0; i<dlist.count(); i++)
{
if (dlist.at(i).nodeName() == "gradient")
{
QDomNodeList cnode = dlist.at(i).childNodes();
for(int j=0; j<cnode.count(); j++)
{
QDomElement dnode = cnode.at(j).toElement();
if (dnode.tagName() == "name" && dnode.text() == gstr)
{
cno = i;
break;
}
}
}
}
if (cno < 0)
return;
QGradientStops stops;
QDomNodeList cnode = dlist.at(cno).childNodes();
for(int j=0; j<cnode.count(); j++)
{
QDomElement de = cnode.at(j).toElement();
if (de.tagName() == "gradientstops")
{
QString str = de.text();
QStringList strlist = str.split(" ", QString::SkipEmptyParts);
for(int j=0; j<strlist.count()/5; j++)
{
float pos, r,g,b,a;
pos = strlist[5*j].toFloat();
r = strlist[5*j+1].toInt();
g = strlist[5*j+2].toInt();
b = strlist[5*j+3].toInt();
a = strlist[5*j+4].toInt();
stops << QGradientStop(pos, QColor(r,g,b,a));
}
}
}
int mapSize = QInputDialog::getInt(0,
"Number of Colors",
"Number of Colors",
50, 2, 255, 1, &ok);
if (!ok)
mapSize = 50;
QGradientStops gstops;
gstops = StaticFunctions::resampleGradientStops(stops, mapSize);
uchar *colors = Global::tagColors();
for(int i=0; i<gstops.size(); i++)
{
float pos = gstops[i].first;
QColor color = gstops[i].second;
int r = color.red();
int g = color.green();
int b = color.blue();
colors[4*i+0] = r;
colors[4*i+1] = g;
colors[4*i+2] = b;
}
colors[0] = 0;
colors[1] = 0;
colors[2] = 0;
colors[3] = 0;
setColors();
}
| AjayLimaye/drishti | tools/paint-graphcut/tagcoloreditor.cpp | C++ | mit | 8,442 |
var chai = require('chai');
var should = chai.should();
var User = require('../app/models/User');
describe('User Model', function() {
it('should create a new user', function(done) {
var user = new User({
uid: 'tester',
username: 'Tester',
email: 'test@gmail.com',
password: 'password'
});
user.save(function(err) {
if (err) return done(err);
done();
})
});
it('should not create a user with the unique username', function(done) {
var user = new User({
uid: 'tester',
username: 'TESTER',
email: 'testchange@gmail.com',
password: 'password'
});
user.save(function(err) {
if (err) err.code.should.equal(11000);
done();
});
});
it('should not create a user with the unique email', function(done) {
var user = new User({
username: 'Tester2',
email: 'test@gmail.com',
password: 'password'
});
user.save(function(err) {
if (err) err.code.should.equal(11000);
done();
});
});
it('should find user by uid (username id)', function(done) {
User.findOne({ uid: 'tester' }, function(err, user) {
if (err) return done(err);
user.uid.should.equal('tester');
done();
});
});
it('should find user by email', function(done) {
User.findOne({ email: 'test@gmail.com' }, function(err, user) {
if (err) return done(err);
user.email.should.equal('test@gmail.com');
done();
});
});
it('should delete a user', function(done) {
User.remove({ email: 'test@gmail.com' }, function(err) {
if (err) return done(err);
done();
});
});
});
| gigavinyl/coffeeshop | test/models.js | JavaScript | mit | 1,658 |
#region Copyright
//
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2016
// by DotNetNuke Corporation
//
// 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.
#endregion
using System;
using System.Data;
using System.Xml.Serialization;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities;
using DotNetNuke.Entities.Modules;
namespace DotNetNuke.Services.Social.Notifications
{
/// -----------------------------------------------------------------------------
/// Project: DotNetNuke
/// Namespace: DotNetNuke.Services.Social.Notifications
/// Class: NotificationType
/// -----------------------------------------------------------------------------
/// <summary>
/// The NotificationType class describes a single notification type that can be associated to a message.
/// This message could be a notification or a standard message sent between users.
/// </summary>
/// -----------------------------------------------------------------------------
[Serializable]
public class NotificationType : BaseEntityInfo, IHydratable
{
private int _notificationTypeId = -1;
private int _desktopModuleId = -1;
/// <summary>
/// The notification type identifier.
/// </summary>
[XmlAttribute]
public int NotificationTypeId
{
get
{
return _notificationTypeId;
}
set
{
_notificationTypeId = value;
}
}
/// <summary>
/// The notification type name.
/// </summary>
[XmlAttribute]
public string Name { get; set; }
/// <summary>
/// The notification type description.
/// </summary>
[XmlAttribute]
public string Description { get; set; }
/// <summary>
/// The amount of time to add to the creation date of the message to calculate the expiration date.
/// </summary>
/// <remarks>
/// Minutes precision. Seconds won't be considered.
/// </remarks>
[XmlAttribute]
public TimeSpan TimeToLive { get; set; }
/// <summary>
/// If the message type is related to a specific module, this field is used to localize actions by getting the resource file from the module folder.
/// </summary>
/// <remarks>
/// The resource file used will be SharedResources by convention.
/// </remarks>
[XmlAttribute]
public int DesktopModuleId
{
get
{
return _desktopModuleId;
}
set
{
_desktopModuleId = value;
}
}
/// <summary>
/// Is this of a Task type. Default is false.
/// </summary>
/// <remarks>
/// Tasks are primarily notifications where an action must be taken. Dismiss is usually not enough.
/// </remarks>
[XmlAttribute]
public bool IsTask { get; set; }
#region Implementation of IHydratable
/// <summary>
/// IHydratable.KeyID.
/// </summary>
[XmlIgnore]
public int KeyID
{
get { return NotificationTypeId; }
set { NotificationTypeId = value; }
}
/// <summary>
/// Fill the object with data from database.
/// </summary>
/// <param name="dr">the data reader.</param>
public void Fill(IDataReader dr)
{
NotificationTypeId = Convert.ToInt32(dr["NotificationTypeID"]);
Name = dr["Name"].ToString();
Description = Null.SetNullString(dr["Description"]);
var timeToLive = Null.SetNullInteger(dr["TTL"]);
if (timeToLive != Null.NullInteger)
{
TimeToLive = new TimeSpan(0, timeToLive, 0);
}
DesktopModuleId = Null.SetNullInteger(dr["DesktopModuleID"]);
IsTask = Null.SetNullBoolean(dr["IsTask"]);
//add audit column data
FillInternal(dr);
}
#endregion
}
}
| moshefi/Dnn.Platform | DNN Platform/Library/Services/Social/Notifications/NotificationType.cs | C# | mit | 5,213 |
using Aspose.Slides;
using Aspose.Slides.Charts;
using Aspose.Slides.Examples.CSharp;
using Aspose.Slides.Export;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharp.Charts
{
class SettingDateFormatForCategoryAxis
{
public static void Run()
{
//ExStart:SettingDateFormatForCategoryAxis
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Charts();
using (Presentation pres = new Presentation())
{
IChart chart = pres.Slides[0].Shapes.AddChart(ChartType.Area, 50, 50, 450, 300);
IChartDataWorkbook wb = chart.ChartData.ChartDataWorkbook;
wb.Clear(0);
chart.ChartData.Categories.Clear();
chart.ChartData.Series.Clear();
chart.ChartData.Categories.Add(wb.GetCell(0, "A2", new DateTime(2015, 1, 1).ToOADate()));
chart.ChartData.Categories.Add(wb.GetCell(0, "A3", new DateTime(2016, 1, 1).ToOADate()));
chart.ChartData.Categories.Add(wb.GetCell(0, "A4", new DateTime(2017, 1, 1).ToOADate()));
chart.ChartData.Categories.Add(wb.GetCell(0, "A5", new DateTime(2018, 1, 1).ToOADate()));
IChartSeries series = chart.ChartData.Series.Add(ChartType.Line);
series.DataPoints.AddDataPointForLineSeries(wb.GetCell(0, "B2", 1));
series.DataPoints.AddDataPointForLineSeries(wb.GetCell(0, "B3", 2));
series.DataPoints.AddDataPointForLineSeries(wb.GetCell(0, "B4", 3));
series.DataPoints.AddDataPointForLineSeries(wb.GetCell(0, "B5", 4));
chart.Axes.HorizontalAxis.CategoryAxisType = CategoryAxisType.Date;
chart.Axes.HorizontalAxis.IsNumberFormatLinkedToSource = false;
chart.Axes.HorizontalAxis.NumberFormat = "yyyy";
pres.Save(dataDir+"test.pptx", SaveFormat.Pptx);
}
//ExEnd:SettingDateFormatForCategoryAxis
}
}
} | aspose-slides/Aspose.Slides-for-.NET | Examples/CSharp/Charts/SettingDateFormatForCategoryAxis.cs | C# | mit | 1,817 |
const util = require('util');
module.exports = function (req, res, utils) {
var deferred = Promise.defer();
utils.request({
url: 'open/get_posts_by_category',
method: 'POST',
qs: {
siteId: req.site.id,
categoryId: 'vicoaeen57jodyi-37vlsa',
pageSize: 3
}
}, function (result) {
var data = {
category: {},
list: [],
imgNew:[]
};
if (result.code != 200) {
deferred.resolve(data);
return;
};
result.body = JSON.parse(result.body);
data.category = { href: util.format('category?id=%s', result.body.category.id) };
result.body.data.forEach(function (e) {
data.list.push({
title: e.title,
image: e.image_url,
href: util.format('detail?id=%s', e.id)
});
var imageAll = e.image_url;
if (imageAll) {
data.imgNew.push({
title: e.title,
image: e.image_url,
href: util.format('detail?id=%s', e.id)
});
}
}, this);
deferred.resolve({ data: data });
},deferred);
return deferred.promise;
} | xLeonard/ahtvu.ah.cn | themes/jjxy/widgets/portal_picnews/data.js | JavaScript | mit | 1,306 |
require 'will_paginate/view_helpers'
module Radiant
module Pagination
module Controller
# for inclusion into public-facing controllers
def configure_pagination
# unconfigured parameters remain at will_paginate defaults
# will_paginate controller options are not overridden by tag attribetus
WillPaginate::ViewHelpers.pagination_options[:param_name] = Radiant::Config["pagination.param_name"].to_sym unless Radiant::Config["pagination.param_name"].blank?
WillPaginate::ViewHelpers.pagination_options[:per_page_param_name] = Radiant::Config["pagination.per_page_param_name"].blank? ? :per_page : Radiant::Config["pagination.per_page_param_name"].to_sym
# will_paginate view options can be overridden by tag attributes
[:class, :previous_label, :next_label, :inner_window, :outer_window, :separator, :container].each do |opt|
WillPaginate::ViewHelpers.pagination_options[opt] = Radiant::Config["pagination.#{opt}"] unless Radiant::Config["pagination.#{opt}"].blank?
end
end
def pagination_parameters
{
:page => params[WillPaginate::ViewHelpers.pagination_options[:param_name]] || 1,
:per_page => params[WillPaginate::ViewHelpers.pagination_options[:per_page_param_name]] || Radiant::Config['pagination.per_page'] || 20
}
end
def self.included(base)
base.class_eval {
helper_method :pagination_parameters
before_filter :configure_pagination
}
end
end
end
end
| ahjohannessen/radiant | lib/radiant/pagination/controller.rb | Ruby | mit | 1,556 |
import * as React from 'react'
import { Image } from '../../../models/diff'
interface IImageProps {
readonly image: Image
readonly style?: React.CSSProperties
readonly onElementLoad?: (img: HTMLImageElement) => void
}
export class DiffImage extends React.Component<IImageProps, {}> {
public render() {
const image = this.props.image
const imageSource = `data:${image.mediaType};base64,${image.contents}`
return (
<img src={imageSource} style={this.props.style} onLoad={this.onLoad} />
)
}
private onLoad = (e: React.SyntheticEvent<HTMLImageElement>) => {
if (this.props.onElementLoad) {
this.props.onElementLoad(e.currentTarget)
}
}
}
| hjobrien/desktop | app/src/ui/diff/image-diffs/diff-image.tsx | TypeScript | mit | 692 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.tools.checkstyle.checks;
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.utils.AnnotationUtil;
import java.util.Stack;
/**
* The {@literal @ServiceClientBuilder} class should have the following rules:
* <ol>
* <li>All service client builder should be named <ServiceName>ClientBuilder and annotated with
* {@literal @ServiceClientBuilder}.</li>
* <li>No other method have prefix 'build' other than 'build*Client' or 'build*AsyncClient'.</li>
* </ol>
*/
public class ServiceClientBuilderCheck extends AbstractCheck {
private static final String SERVICE_CLIENT_BUILDER = "ServiceClientBuilder";
private Stack<Boolean> hasServiceClientBuilderAnnotationStack = new Stack<>();
private Stack<Boolean> hasBuildMethodStack = new Stack<>();
private boolean hasServiceClientBuilderAnnotation;
private boolean hasBuildMethod;
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
}
@Override
public int[] getAcceptableTokens() {
return getRequiredTokens();
}
@Override
public int[] getRequiredTokens() {
return new int[] {
TokenTypes.CLASS_DEF,
TokenTypes.METHOD_DEF
};
}
@Override
public void leaveToken(DetailAST token) {
if (token.getType() == TokenTypes.CLASS_DEF) {
hasServiceClientBuilderAnnotation = hasServiceClientBuilderAnnotationStack.pop();
hasBuildMethod = hasBuildMethodStack.pop();
if (hasServiceClientBuilderAnnotation && !hasBuildMethod) {
log(token, "Class with @ServiceClientBuilder annotation must have a method starting with ''build'' "
+ "and ending with ''Client''.");
}
}
}
@Override
public void visitToken(DetailAST token) {
switch (token.getType()) {
case TokenTypes.CLASS_DEF:
// Save the state of variable 'hasServiceClientBuilderAnnotation' to limit the scope of accessibility
hasServiceClientBuilderAnnotationStack.push(hasServiceClientBuilderAnnotation);
hasBuildMethodStack.push(hasBuildMethod);
final DetailAST serviceClientAnnotationBuilderToken = getServiceClientBuilderAnnotation(token);
final String className = token.findFirstToken(TokenTypes.IDENT).getText();
hasServiceClientBuilderAnnotation = serviceClientAnnotationBuilderToken != null;
if (hasServiceClientBuilderAnnotation) {
// Don't need to check if the 'serviceClients' exist. It is required when using
// @ServiceClientBuilder
// HAS @ServiceClientBuilder annotation but NOT named the class <ServiceName>ClientBuilder
if (!className.endsWith("ClientBuilder")) {
log(token, String.format("Class annotated with @ServiceClientBuilder ''%s'' should be named "
+ "<ServiceName>ClientBuilder.", className));
}
} else {
// No @ServiceClientBuilder annotation but HAS named the class <ServiceName>ClientBuilder
if (className.endsWith("ClientBuilder")) {
log(token, String.format("Class ''%s'' should be annotated with @ServiceClientBuilder.",
className));
}
}
break;
case TokenTypes.METHOD_DEF:
if (!hasServiceClientBuilderAnnotation) {
return;
}
final String methodName = token.findFirstToken(TokenTypes.IDENT).getText();
if (!methodName.startsWith("build")) {
break;
}
hasBuildMethod = true;
// method name has prefix 'build' but not 'build*Client' or 'build*AsyncClient'
if (!methodName.endsWith("Client")) {
log(token, String.format(
"@ServiceClientBuilder class should not have a method name, ''%s'' starting with ''build'' "
+ "but not ending with ''Client''.", methodName));
}
break;
default:
// Checkstyle complains if there's no default block in switch
break;
}
}
/**
* Checks if the class is annotated with @ServiceClientBuilder.
*
* @param classDefToken the CLASS_DEF AST node
* @return the annotation node if the class is annotated with @ServiceClientBuilder, null otherwise.
*/
private DetailAST getServiceClientBuilderAnnotation(DetailAST classDefToken) {
return AnnotationUtil.getAnnotation(classDefToken, "ServiceClientBuilder");
}
}
| selvasingh/azure-sdk-for-java | eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/ServiceClientBuilderCheck.java | Java | mit | 5,108 |
// Copyright 2016 The Brave 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 <algorithm>
#include <limits>
#include <memory>
#include <utility>
#include "brave/browser/brave_browser_context.h"
#include "base/path_service.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/trace_event/trace_event.h"
#include "brave/browser/brave_permission_manager.h"
#include "brave/browser/net/tor_proxy_network_delegate.h"
#include "chrome/browser/background_fetch/background_fetch_delegate_factory.h"
#include "chrome/browser/background_fetch/background_fetch_delegate_impl.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/custom_handlers/protocol_handler_registry.h"
#include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/io_thread.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/pref_names.h"
#include "common/application_info.h"
#include "components/autofill/core/browser/autofill_manager.h"
#include "components/autofill/core/browser/webdata/autofill_table.h"
#include "components/component_updater/component_updater_paths.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/guest_view/browser/guest_view_manager.h"
#include "components/guest_view/browser/guest_view_manager_delegate.h"
#include "components/guest_view/common/guest_view_constants.h"
#include "components/password_manager/core/browser/password_manager.h"
#include "components/password_manager/core/browser/webdata/logins_table.h"
#include "components/prefs/pref_change_registrar.h"
#include "components/prefs/pref_filter.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/safe_browsing/common/safe_browsing_prefs.h"
#include "components/sync_preferences/pref_service_syncable.h"
#include "components/sync_preferences/pref_service_syncable_factory.h"
#include "components/user_prefs/user_prefs.h"
#include "components/zoom/zoom_event_manager.h"
#include "components/webdata_services/web_data_service_wrapper.h"
#include "components/webdata/common/webdata_constants.h"
#include "content/browser/storage_partition_impl_map.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/dom_storage_context.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/common/service_manager_connection.h"
#include "services/service_manager/public/cpp/connector.h"
#include "extensions/browser/pref_names.h"
#include "extensions/buildflags/buildflags.h"
#include "net/base/escape.h"
#include "net/cookies/cookie_store.h"
#include "net/proxy_resolution/proxy_resolution_service.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "vendor/brightray/browser/browser_client.h"
#include "vendor/brightray/browser/net_log.h"
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "atom/browser/extensions/atom_browser_client_extensions_part.h"
#include "atom/browser/extensions/atom_extensions_network_delegate.h"
#include "atom/browser/extensions/atom_extension_system_factory.h"
#include "extensions/browser/api/extensions_api_client.h"
#include "extensions/browser/api/web_request/web_request_api.h"
#include "extensions/browser/extension_pref_store.h"
#include "extensions/browser/extension_pref_value_map_factory.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_protocols.h"
#include "extensions/browser/extensions_browser_client.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "brave/browser/plugins/brave_plugin_service_filter.h"
#include "chrome/browser/pepper_flash_settings_manager.h"
#include "chrome/browser/plugins/plugin_info_host_impl.h"
#endif
#if defined(OS_WIN)
#include "components/password_manager/core/browser/webdata/password_web_data_service_win.h"
#endif
using content::BrowserThread;
using content::HostZoomMap;
namespace brave {
namespace {
const char kPrefExitTypeCrashed[] = "Crashed";
const char kPrefExitTypeSessionEnded[] = "SessionEnded";
const char kPrefExitTypeNormal[] = "Normal";
#if BUILDFLAG(ENABLE_EXTENSIONS)
// WATCH(bridiver) - chrome/browser/profiles/off_the_record_profile_impl.cc
void NotifyOTRProfileCreatedOnIOThread(void* original_profile,
void* otr_profile) {
extensions::ExtensionWebRequestEventRouter::GetInstance()
->OnOTRBrowserContextCreated(original_profile, otr_profile);
}
// WATCH(bridiver) - chrome/browser/profiles/off_the_record_profile_impl.cc
void NotifyOTRProfileDestroyedOnIOThread(void* original_profile,
void* otr_profile) {
extensions::ExtensionWebRequestEventRouter::GetInstance()
->OnOTRBrowserContextDestroyed(original_profile, otr_profile);
}
#endif
void DummyFlare(syncer::ModelType type) {}
void ProfileErrorCallback(WebDataServiceWrapper::ErrorType error_type,
sql::InitStatus status,
const std::string& diagnostics) {
// TODO(bridiver) - this should be reported back to JS
LOG(ERROR) << "Error initializing web data service " << diagnostics;
}
// WATCH(bridiver) - chrome/browser/profiles/profile_impl.cc
// Converts the kSessionExitedCleanly pref to the corresponding EXIT_TYPE.
Profile::ExitType SessionTypePrefValueToExitType(const std::string& value) {
if (value == kPrefExitTypeSessionEnded)
return Profile::EXIT_SESSION_ENDED;
if (value == kPrefExitTypeCrashed)
return Profile::EXIT_CRASHED;
return Profile::EXIT_NORMAL;
}
// WATCH(bridiver) - chrome/browser/profiles/profile_impl.cc
// Converts an ExitType into a string that is written to prefs.
std::string ExitTypeToSessionTypePrefValue(Profile::ExitType type) {
switch (type) {
case Profile::EXIT_NORMAL:
return kPrefExitTypeNormal;
case Profile::EXIT_SESSION_ENDED:
return kPrefExitTypeSessionEnded;
case Profile::EXIT_CRASHED:
return kPrefExitTypeCrashed;
}
NOTREACHED();
return std::string();
}
} // namespace
const char kPersistPrefix[] = "persist:";
const int kPersistPrefixLength = 8;
void DatabaseErrorCallback(sql::InitStatus init_status,
const std::string& diagnostics) {
LOG(WARNING) << "initializing autocomplete database failed";
}
void PasswordErrorCallback(sql::InitStatus init_status,
const std::string& diagnostics) {
LOG(WARNING) << "initializing Password database failed";
}
BraveBrowserContext::BraveBrowserContext(
const std::string& partition,
bool in_memory,
const base::DictionaryValue& options,
scoped_refptr<base::SequencedTaskRunner> io_task_runner)
: Profile(partition, in_memory, options),
pref_registry_(new user_prefs::PrefRegistrySyncable),
has_parent_(false),
original_context_(nullptr),
otr_context_(nullptr),
partition_(partition),
ready_(new base::WaitableEvent(
base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED)),
isolated_storage_(false),
in_memory_(in_memory),
io_task_runner_(std::move(io_task_runner)),
delegate_(g_browser_process->profile_manager()) {
std::string parent_partition;
if (options.GetString("parent_partition", &parent_partition)) {
has_parent_ = true;
original_context_ = static_cast<BraveBrowserContext*>(
atom::AtomBrowserContext::From(parent_partition, false));
}
bool isolated_storage;
if (options.GetBoolean("isolated_storage", &isolated_storage)) {
isolated_storage_ = isolated_storage;
}
std::string tor_proxy;
if (options.GetString("tor_proxy", &tor_proxy)) {
tor_proxy_ = tor_proxy;
}
base::FilePath::StringType tor_path;
if (options.GetString("tor_path", &tor_path) && tor_proxy_.length()) {
tor_launcher_factory_.reset(new TorLauncherFactory(tor_path, tor_proxy_));
tor_launcher_factory_->LaunchTorProcess();
}
if (in_memory) {
original_context_ = static_cast<BraveBrowserContext*>(
atom::AtomBrowserContext::From(partition, false));
original_context_->otr_context_ = this;
}
CreateProfilePrefs(io_task_runner_);
if (original_context_) {
TrackZoomLevelsFromParent();
}
#if BUILDFLAG(ENABLE_EXTENSIONS)
if (IsOffTheRecord()) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&NotifyOTRProfileCreatedOnIOThread,
base::Unretained(original_context_),
base::Unretained(this)));
}
#endif
}
BraveBrowserContext::~BraveBrowserContext() {
MaybeSendDestroyedNotification();
if (track_zoom_subscription_.get())
track_zoom_subscription_.reset(nullptr);
if (parent_default_zoom_level_subscription_.get())
parent_default_zoom_level_subscription_.reset(nullptr);
if (user_prefs_registrar_.get())
user_prefs_registrar_->RemoveAll();
#if BUILDFLAG(ENABLE_PLUGINS)
BravePluginServiceFilter::GetInstance()->UnregisterResourceContext(
GetResourceContext());
#endif
if (IsOffTheRecord()) {
auto user_prefs = user_prefs::UserPrefs::Get(this);
if (user_prefs)
user_prefs->ClearMutableValues();
#if BUILDFLAG(ENABLE_EXTENSIONS)
ExtensionPrefValueMapFactory::GetForBrowserContext(
original_context_)->ClearAllIncognitoSessionOnlyPreferences();
#endif
}
if (!IsOffTheRecord() && !HasParentContext()) {
web_database_wrapper_->Shutdown();
bool prefs_loaded = user_prefs_->GetInitializationStatus() !=
PrefService::INITIALIZATION_STATUS_WAITING;
if (prefs_loaded) {
user_prefs_->CommitPendingWrite();
}
}
BrowserContextDependencyManager::GetInstance()->
DestroyBrowserContextServices(this);
if (IsOffTheRecord()) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&NotifyOTRProfileDestroyedOnIOThread,
base::Unretained(original_context_), base::Unretained(this)));
#endif
}
g_browser_process->io_thread()->ChangedToOnTheRecord();
ShutdownStoragePartitions();
}
// static
BraveBrowserContext* BraveBrowserContext::FromBrowserContext(
content::BrowserContext* browser_context) {
return static_cast<BraveBrowserContext*>(browser_context);
}
Profile* BraveBrowserContext::GetOffTheRecordProfile() {
return otr_context();
}
bool BraveBrowserContext::HasOffTheRecordProfile() {
return !!otr_context();
}
Profile* BraveBrowserContext::GetOriginalProfile() {
return original_context();
}
const Profile* BraveBrowserContext::GetOriginalProfile() const {
return const_cast<BraveBrowserContext*>(this)->original_context();
}
bool BraveBrowserContext::IsSameProfile(Profile* profile) {
return GetOriginalProfile() == profile->GetOriginalProfile();
}
bool BraveBrowserContext::HasParentContext() {
return has_parent_;
}
BraveBrowserContext* BraveBrowserContext::original_context() {
if (original_context_) {
return original_context_;
}
return this;
}
BraveBrowserContext* BraveBrowserContext::otr_context() {
if (IsOffTheRecord()) {
return this;
}
if (HasParentContext())
return original_context_->otr_context();
if (otr_context_) {
return otr_context_;
}
return nullptr;
}
content::BrowserPluginGuestManager* BraveBrowserContext::GetGuestManager() {
#if BUILDFLAG(ENABLE_EXTENSIONS)
if (!guest_view::GuestViewManager::FromBrowserContext(this)) {
guest_view::GuestViewManager::CreateWithDelegate(
this,
extensions::ExtensionsAPIClient::Get()->CreateGuestViewManagerDelegate(
this));
}
#endif
return guest_view::GuestViewManager::FromBrowserContext(this);
}
net::URLRequestContextGetter*
BraveBrowserContext::CreateRequestContextForStoragePartition(
const base::FilePath& partition_path,
bool in_memory,
content::ProtocolHandlerMap* protocol_handlers,
content::URLRequestInterceptorScopedVector request_interceptors) {
if (isolated_storage_) {
scoped_refptr<brightray::URLRequestContextGetter>
url_request_context_getter =
new brightray::URLRequestContextGetter(
this,
static_cast<brightray::NetLog*>(brightray::BrowserClient::Get()->
GetNetLog()),
partition_path,
in_memory,
BrowserThread::GetTaskRunnerForThread(BrowserThread::IO),
protocol_handlers,
std::move(request_interceptors));
StoragePartitionDescriptor descriptor(partition_path, in_memory);
// Inherits web requests handlers from default parition
auto default_network_delegate = GetDefaultStoragePartition(this)->
GetURLRequestContext()->GetURLRequestContext()->network_delegate();
url_request_context_getter->GetURLRequestContext()
->set_network_delegate(default_network_delegate);
url_request_context_getter_map_[descriptor] = url_request_context_getter;
return url_request_context_getter.get();
} else {
return nullptr;
}
}
net::URLRequestContextGetter*
BraveBrowserContext::CreateMediaRequestContextForStoragePartition(
const base::FilePath& partition_path,
bool in_memory) {
if (isolated_storage_) {
StoragePartitionDescriptor descriptor(partition_path, in_memory);
URLRequestContextGetterMap::iterator iter =
url_request_context_getter_map_.find(descriptor);
if (iter != url_request_context_getter_map_.end())
return (iter->second).get();
else
return nullptr;
} else {
return nullptr;
}
}
bool BraveBrowserContext::IsOffTheRecord() const {
if (isolated_storage_)
return true;
return in_memory_;
}
void BraveBrowserContext::TrackZoomLevelsFromParent() {
// Here we only want to use zoom levels stored in the main-context's default
// storage partition. We're not interested in zoom levels in special
// partitions, e.g. those used by WebViewGuests.
HostZoomMap* host_zoom_map = HostZoomMap::GetDefaultForBrowserContext(this);
HostZoomMap* parent_host_zoom_map =
HostZoomMap::GetDefaultForBrowserContext(original_context_);
host_zoom_map->CopyFrom(parent_host_zoom_map);
// Observe parent profile's HostZoomMap changes so they can also be applied
// to this profile's HostZoomMap.
track_zoom_subscription_ = parent_host_zoom_map->AddZoomLevelChangedCallback(
base::Bind(&BraveBrowserContext::OnParentZoomLevelChanged,
base::Unretained(this)));
if (!original_context_->GetZoomLevelPrefs())
return;
// Also track changes to the parent profile's default zoom level.
parent_default_zoom_level_subscription_ =
original_context_->GetZoomLevelPrefs()->RegisterDefaultZoomLevelCallback(
base::Bind(&BraveBrowserContext::UpdateDefaultZoomLevel,
base::Unretained(this)));
}
ChromeZoomLevelPrefs* BraveBrowserContext::GetZoomLevelPrefs() {
return static_cast<ChromeZoomLevelPrefs*>(
GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
}
void BraveBrowserContext::OnParentZoomLevelChanged(
const HostZoomMap::ZoomLevelChange& change) {
HostZoomMap* host_zoom_map = HostZoomMap::GetDefaultForBrowserContext(this);
switch (change.mode) {
case HostZoomMap::ZOOM_CHANGED_TEMPORARY_ZOOM:
return;
case HostZoomMap::ZOOM_CHANGED_FOR_HOST:
host_zoom_map->SetZoomLevelForHost(change.host, change.zoom_level);
return;
case HostZoomMap::ZOOM_CHANGED_FOR_SCHEME_AND_HOST:
host_zoom_map->SetZoomLevelForHostAndScheme(change.scheme,
change.host,
change.zoom_level);
return;
case HostZoomMap::PAGE_SCALE_IS_ONE_CHANGED:
return;
}
}
void BraveBrowserContext::UpdateDefaultZoomLevel() {
HostZoomMap* host_zoom_map = HostZoomMap::GetDefaultForBrowserContext(this);
double default_zoom_level =
original_context_->GetZoomLevelPrefs()->GetDefaultZoomLevelPref();
host_zoom_map->SetDefaultZoomLevel(default_zoom_level);
// HostZoomMap does not trigger zoom notification events when the default
// zoom level is set, so we need to do it here.
zoom::ZoomEventManager::GetForBrowserContext(this)
->OnDefaultZoomLevelChanged();
}
content::PermissionManager* BraveBrowserContext::GetPermissionManager() {
if (!permission_manager_.get())
permission_manager_.reset(new BravePermissionManager);
return permission_manager_.get();
}
content::BackgroundFetchDelegate*
BraveBrowserContext::GetBackgroundFetchDelegate() {
return BackgroundFetchDelegateFactory::GetForProfile(this);
}
net::URLRequestContextGetter* BraveBrowserContext::GetRequestContext() {
return GetDefaultStoragePartition(this)->GetURLRequestContext();
}
net::NetworkDelegate* BraveBrowserContext::CreateNetworkDelegate() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (isolated_storage_)
return new brave::TorProxyNetworkDelegate(this,
info_map_,
g_browser_process->extension_event_router_forwarder());
else
return new extensions::AtomExtensionsNetworkDelegate(this,
info_map_,
g_browser_process->extension_event_router_forwarder());
}
std::unique_ptr<net::URLRequestJobFactory>
BraveBrowserContext::CreateURLRequestJobFactory(
content::ProtocolHandlerMap* protocol_handlers) {
std::unique_ptr<net::URLRequestJobFactory> job_factory =
AtomBrowserContext::CreateURLRequestJobFactory(protocol_handlers);
auto job_factory_impl =
static_cast<net::URLRequestJobFactoryImpl*>(job_factory.get());
static_cast<brightray::URLRequestContextGetter*>(GetRequestContext())->
set_job_factory(job_factory_impl);
#if BUILDFLAG(ENABLE_EXTENSIONS)
job_factory_impl->SetProtocolHandler(
extensions::kExtensionScheme,
extensions::CreateExtensionProtocolHandler(IsOffTheRecord(),
info_map_));
#endif
if (!protocol_handler_interceptor_.get()) {
protocol_handler_interceptor_ =
ProtocolHandlerRegistryFactory::GetForBrowserContext(this)
->CreateJobInterceptorFactory();
}
protocol_handler_interceptor_->Chain(std::move(job_factory));
return std::move(protocol_handler_interceptor_);
}
void BraveBrowserContext::CreateProfilePrefs(
scoped_refptr<base::SequencedTaskRunner> io_task_runner) {
InitPrefs(io_task_runner);
#if BUILDFLAG(ENABLE_EXTENSIONS)
PrefStore* extension_prefs = new ExtensionPrefStore(
ExtensionPrefValueMapFactory::GetForBrowserContext(original_context()),
IsOffTheRecord());
#else
PrefStore* extension_prefs = NULL;
#endif
user_prefs_registrar_.reset(new PrefChangeRegistrar());
bool async = false;
if (IsOffTheRecord()) {
overlay_pref_names_.push_back("app_state");
overlay_pref_names_.push_back(extensions::pref_names::kPrefContentSettings);
overlay_pref_names_.push_back(prefs::kPartitionPerHostZoomLevels);
std::unique_ptr<PrefValueStore::Delegate> delegate = nullptr;
user_prefs_ =
original_context()->user_prefs()->CreateIncognitoPrefService(
extension_prefs, overlay_pref_names_, std::move(delegate));
user_prefs::UserPrefs::Set(this, user_prefs_.get());
} else if (HasParentContext()) {
// overlay pref names only apply to incognito
std::unique_ptr<PrefValueStore::Delegate> delegate = nullptr;
std::vector<const char*> overlay_pref_names;
user_prefs_ =
original_context()->user_prefs()->CreateIncognitoPrefService(
extension_prefs, overlay_pref_names, std::move(delegate));
user_prefs::UserPrefs::Set(this, user_prefs_.get());
} else {
pref_registry_->RegisterDictionaryPref("app_state");
pref_registry_->RegisterDictionaryPref(
extensions::pref_names::kPrefContentSettings);
pref_registry_->RegisterBooleanPref(
prefs::kSavingBrowserHistoryDisabled, false);
pref_registry_->RegisterBooleanPref(
prefs::kAllowDeletingBrowserHistory, true);
pref_registry_->RegisterDictionaryPref(prefs::kPartitionDefaultZoomLevel);
pref_registry_->RegisterDictionaryPref(prefs::kPartitionPerHostZoomLevels);
pref_registry_->RegisterBooleanPref(prefs::kPrintingEnabled, true);
pref_registry_->RegisterBooleanPref(prefs::kPrintPreviewDisabled, false);
safe_browsing::RegisterProfilePrefs(pref_registry_.get());
DownloadPrefs::RegisterProfilePrefs(pref_registry_.get());
#if BUILDFLAG(ENABLE_PLUGINS)
PluginInfoHostImpl::RegisterUserPrefs(pref_registry_.get());
PepperFlashSettingsManager::RegisterProfilePrefs(pref_registry_.get());
#endif
// TODO(bridiver) - is this necessary or is it covered by
// BrowserContextDependencyManager
ProtocolHandlerRegistry::RegisterProfilePrefs(pref_registry_.get());
HostContentSettingsMap::RegisterProfilePrefs(pref_registry_.get());
autofill::AutofillManager::RegisterProfilePrefs(pref_registry_.get());
password_manager::PasswordManager::RegisterProfilePrefs(
pref_registry_.get());
#if BUILDFLAG(ENABLE_EXTENSIONS)
extensions::AtomBrowserClientExtensionsPart::RegisterProfilePrefs(
pref_registry_.get());
extensions::ExtensionPrefs::RegisterProfilePrefs(pref_registry_.get());
#endif
BrowserContextDependencyManager::GetInstance()->
RegisterProfilePrefsForServices(this, pref_registry_.get());
// create profile prefs
base::FilePath filepath = GetPath().Append(
FILE_PATH_LITERAL("UserPrefs"));
scoped_refptr<JsonPrefStore> pref_store = new JsonPrefStore(
filepath, io_task_runner, std::unique_ptr<PrefFilter>());
// prepare factory
sync_preferences::PrefServiceSyncableFactory factory;
factory.set_async(async);
factory.set_extension_prefs(extension_prefs);
factory.set_user_prefs(pref_store);
user_prefs_ = factory.CreateSyncable(pref_registry_.get());
user_prefs::UserPrefs::Set(this, user_prefs_.get());
if (async) {
user_prefs_->AddPrefInitObserver(base::Bind(
&BraveBrowserContext::OnPrefsLoaded, base::Unretained(this)));
return;
}
}
OnPrefsLoaded(true);
}
void BraveBrowserContext::OnPrefsLoaded(bool success) {
CHECK(success);
BrowserContextDependencyManager::GetInstance()->
CreateBrowserContextServices(this);
#if BUILDFLAG(ENABLE_EXTENSIONS)
info_map_ = extensions::AtomExtensionSystemFactory::GetInstance()->
GetForBrowserContext(this)->info_map();
#endif
protocol_handler_interceptor_ =
ProtocolHandlerRegistryFactory::GetForBrowserContext(this)
->CreateJobInterceptorFactory();
if (!IsOffTheRecord() && !HasParentContext()) {
content::BrowserContext::GetDefaultStoragePartition(this)->
GetDOMStorageContext()->SetSaveSessionStorageOnDisk();
// migrate from old prefs to new prefs
base::FilePath default_download_path(prefs()->GetFilePath(
prefs::kDownloadDefaultDirectory));
if (!default_download_path.empty()) {
user_prefs_->SetFilePath(prefs::kDownloadDefaultDirectory,
default_download_path);
prefs()->SetFilePath(prefs::kDownloadDefaultDirectory,
base::FilePath());
}
const base::FilePath& profile_path = GetPath();
web_database_wrapper_.reset(new WebDataServiceWrapper(
profile_path, g_browser_process->GetApplicationLocale(),
BrowserThread::GetTaskRunnerForThread(BrowserThread::UI),
base::Bind(&DummyFlare),
base::BindRepeating(&ProfileErrorCallback)));
}
user_prefs_registrar_->Init(user_prefs_.get());
#if BUILDFLAG(ENABLE_PLUGINS)
BravePluginServiceFilter::GetInstance()->RegisterResourceContext(
this, GetResourceContext());
#endif
ready_->Signal();
if (delegate_) {
TRACE_EVENT0("browser",
"ProfileImpl::OnPrefsLoaded:DelegateOnProfileCreated")
delegate_->OnProfileCreated(this, true, IsNewProfile());
}
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_PROFILE_CREATED,
content::Source<BraveBrowserContext>(this),
content::NotificationService::NoDetails());
}
content::ResourceContext* BraveBrowserContext::GetResourceContext() {
content::BrowserContext::EnsureResourceContextInitialized(this);
return brightray::BrowserContext::GetResourceContext();
}
std::unique_ptr<content::ZoomLevelDelegate>
BraveBrowserContext::CreateZoomLevelDelegate(
const base::FilePath& partition_path) {
return base::WrapUnique(new ChromeZoomLevelPrefs(
GetPrefs(), GetPath(), partition_path,
zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr()));
}
scoped_refptr<autofill::AutofillWebDataService>
BraveBrowserContext::GetAutofillWebdataService() {
return original_context()->web_database_wrapper_->GetAutofillWebData();
}
#if defined(OS_WIN)
scoped_refptr<PasswordWebDataService>
BraveBrowserContext::GetPasswordWebdataService() {
return original_context()->web_database_wrapper_->GetPasswordWebData();
}
#endif
base::FilePath BraveBrowserContext::GetPath() const {
return brightray::BrowserContext::GetPath();
}
std::string BraveBrowserContext::partition_with_prefix() {
std::string canonical_partition(partition());
if (canonical_partition.empty())
canonical_partition = "default";
if (IsOffTheRecord() && !isolated_storage_)
return canonical_partition;
return kPersistPrefix + canonical_partition;
}
atom::AtomBrowserContext* BraveBrowserContext::FromPartition(
const std::string& partition, const base::DictionaryValue& options) {
if (partition.empty()) {
return atom::AtomBrowserContext::From("", false, options);
}
if (base::StartsWith(
partition, kPersistPrefix, base::CompareCase::SENSITIVE)) {
std::string name = partition.substr(kPersistPrefixLength);
return atom::AtomBrowserContext::From(
name == "default" ? "" : name, false, options);
} else {
return atom::AtomBrowserContext::From(
partition == "default" ? "" : partition, true, options);
}
}
// WATCH(bridiver) - chrome/browser/profiles/profile_impl.cc
void BraveBrowserContext::SetExitType(ExitType exit_type) {
if (!user_prefs_)
return;
ExitType current_exit_type = SessionTypePrefValueToExitType(
user_prefs_->GetString(prefs::kSessionExitType));
// This may be invoked multiple times during shutdown. Only persist the value
// first passed in (unless it's a reset to the crash state, which happens when
// foregrounding the app on mobile).
if (exit_type == EXIT_CRASHED || current_exit_type == EXIT_CRASHED) {
user_prefs_->SetString(prefs::kSessionExitType,
ExitTypeToSessionTypePrefValue(exit_type));
}
}
void BraveBrowserContext::SetTorNewIdentity(const GURL& url,
const base::Closure& callback) {
GURL site_url(content::SiteInstance::GetSiteForURL(this, url));
const std::string host = site_url.host();
base::FilePath partition_path = this->GetPath().Append(
content::StoragePartitionImplMap::GetStoragePartitionPath(host, host));
scoped_refptr<brightray::URLRequestContextGetter> url_request_context_getter;
StoragePartitionDescriptor descriptor(partition_path, true);
URLRequestContextGetterMap::iterator iter =
url_request_context_getter_map_.find(descriptor);
if (iter != url_request_context_getter_map_.end())
url_request_context_getter = (iter->second);
else
return;
auto proxy_resolution_service =
url_request_context_getter->GetURLRequestContext()->
proxy_resolution_service();
BrowserThread::PostTaskAndReply(
BrowserThread::IO, FROM_HERE,
base::Bind(&net::ProxyConfigServiceTor::TorSetProxy,
proxy_resolution_service,
tor_proxy_,
host,
&tor_proxy_map_,
true),
callback);
}
void BraveBrowserContext::RelaunchTor() const {
if (tor_launcher_factory_.get())
tor_launcher_factory_->RelaunchTorProcess();
}
void BraveBrowserContext::SetTorLauncherCallback(
const TorLauncherFactory::TorLauncherCallback& callback) {
if (tor_launcher_factory_.get())
tor_launcher_factory_->SetLauncherCallback(callback);
}
int64_t BraveBrowserContext::GetTorPid() const {
if (tor_launcher_factory_.get())
return tor_launcher_factory_->GetTorPid();
else
return -1;
}
scoped_refptr<base::SequencedTaskRunner>
BraveBrowserContext::GetIOTaskRunner() {
return io_task_runner_;
}
base::FilePath BraveBrowserContext::last_selected_directory() {
return GetPrefs()->GetFilePath(prefs::kSelectFileLastDirectory);
}
void BraveBrowserContext::set_last_selected_directory(
const base::FilePath& path) {
GetPrefs()->SetFilePath(prefs::kSelectFileLastDirectory, path);
}
} // namespace brave
namespace atom {
// Creates the profile directory synchronously if it doesn't exist. If
// |create_readme| is true, the profile README will be created asynchronously i
// the profile directory.
void CreateProfileDirectory(const base::FilePath& path) {
// Create the profile directory synchronously otherwise we would need to
// sequence every otherwise independent I/O operation inside the profile
// directory with this operation. base::PathExists() and
// base::CreateDirectory() should be lightweight I/O operations and avoiding
// the headache of sequencing all otherwise unrelated I/O after these
// justifies running them on the main thread.
base::ThreadRestrictions::ScopedAllowIO allow_io_to_create_directory;
if (!base::PathExists(path)) {
DVLOG(1) << "Creating directory " << path.value();
base::CreateDirectory(path);
}
}
// TODO(bridiver) find a better way to do this
// static
AtomBrowserContext* AtomBrowserContext::From(
const std::string& partition, bool in_memory,
const base::DictionaryValue& options) {
auto browser_context = brightray::BrowserContext::Get(partition, in_memory);
if (browser_context)
return static_cast<AtomBrowserContext*>(browser_context);
// TODO(bridiver) - pass the path to initialize the browser context
// TODO(bridiver) - create these with the profile manager
base::FilePath path;
base::PathService::Get(chrome::DIR_USER_DATA, &path);
if (!in_memory && !partition.empty())
path = path.Append(FILE_PATH_LITERAL("Partitions"))
.Append(base::FilePath::FromUTF8Unsafe(
net::EscapePath(base::ToLowerASCII(partition))));
// Get sequenced task runner for making sure that file operations of
// this profile are executed in expected order (what was previously assured by
// the FILE thread).
scoped_refptr<base::SequencedTaskRunner> io_task_runner =
base::CreateSequencedTaskRunnerWithTraits(
{base::TaskShutdownBehavior::BLOCK_SHUTDOWN, base::MayBlock()});
CreateProfileDirectory(path);
auto profile = new brave::BraveBrowserContext(partition, in_memory, options,
io_task_runner);
return profile;
}
} // namespace atom
| brave/electron | brave/browser/brave_browser_context.cc | C++ | mit | 31,443 |
import { TimepickerPo } from '../../support/timepicker.po';
describe('Timepicker demo page testing suite: Mouse wheel', () => {
const timepicker = new TimepickerPo();
const mouseWheel = timepicker.exampleDemosArr.mousewheel;
beforeEach(() => timepicker.navigateTo());
it(`example contains timepicker with hour, minutes, button "AM"("PM"), prev with current time and
button "Enable / Diseble mouse wheel"`, () => {
const newDate = new Date();
timepicker.isTimepickerVisible(mouseWheel);
timepicker.isAlertContains(mouseWheel, `Time is: ${newDate.toString().split(':')[0]}`);
timepicker.isInputValueContain(mouseWheel, `${timepicker.getHoursIn12Format(newDate)}`, 0);
timepicker.isInputValueContain(mouseWheel, `${newDate.getMinutes()}`, 1);
timepicker.isButtonExist(mouseWheel, (newDate.getHours() >= 12) ? 'PM ' : 'AM ');
});
it(`when user activates hours input and scroll up/down with mouse wheel then time number increases/decreases
with appropriate changes in info alert`, () => {
const newDate = new Date();
const hour12Format = timepicker.getHoursIn12Format(newDate);
const hour24Format = newDate.getHours();
timepicker.clickOnInput(mouseWheel, 0);
// For triggering mouse wheel event, need to set event name and deltaY, because of wheelSign method
// For scrolling up, deltaY should be < 0, for scrolling down, deltaY should be > 0
timepicker.triggerEventOnInput(mouseWheel, 'wheel', 0, {deltaY: -1});
timepicker.isInputValueContain(mouseWheel, `${hour12Format === 12 ? 1 : hour12Format + 1}`, 0);
timepicker.isAlertContains(mouseWheel, `${hour24Format === 23 ? 0 : hour24Format + 1}`);
timepicker.triggerEventOnInput(mouseWheel, 'wheel', 0, {deltaY: 1});
timepicker.isInputValueContain(mouseWheel, `${hour12Format}`, 0);
timepicker.isAlertContains(mouseWheel, `${hour24Format}`);
});
it(`when user activates minutes input and scroll up/down with mouse wheel then time number increases/decreases
with appropriate changes in info alert`, () => {
const currentMinutes = new Date().getMinutes();
timepicker.clickOnInput(mouseWheel, 1);
timepicker.triggerEventOnInput(mouseWheel, 'wheel', 1, {deltaY: -1});
timepicker.isInputValueContain(mouseWheel, `${
currentMinutes < 55 ? currentMinutes + 5 : currentMinutes - 60 + 5}`, 1);
timepicker.isAlertContains(mouseWheel, `${
currentMinutes < 55 ? currentMinutes + 5 : currentMinutes - 60 + 5}`);
timepicker.triggerEventOnInput(mouseWheel, 'wheel', 1, {deltaY: 1});
timepicker.isInputValueContain(mouseWheel, `${currentMinutes}`, 1);
timepicker.isAlertContains(mouseWheel, `${currentMinutes}`);
});
it(`when user clicks on "Enable / Disable" button, activates hours input and scroll up/down with mouse wheel,
then hours stay the same, after activates minutes and scroll up/down with mouse wheel, then minutes stay the same`,
() => {
const newDate = new Date();
const currentMinutes = newDate.getMinutes();
const hour12Format = timepicker.getHoursIn12Format(newDate);
const hour24Format = newDate.getHours();
timepicker.clickOnBtn(mouseWheel, 1);
timepicker.triggerEventOnInput(mouseWheel, 'wheel', 0, {deltaY: -1});
timepicker.isInputValueContain(mouseWheel, `${hour12Format}`, 0);
timepicker.isAlertContains(mouseWheel, `${hour24Format}`);
timepicker.triggerEventOnInput(mouseWheel, 'wheel', 0, {deltaY: 1});
timepicker.isInputValueContain(mouseWheel, `${hour12Format}`, 0);
timepicker.isAlertContains(mouseWheel, `${hour24Format}`);
timepicker.triggerEventOnInput(mouseWheel, 'wheel', 1, {deltaY: -1});
timepicker.isInputValueContain(mouseWheel, `${currentMinutes}`, 1);
timepicker.isAlertContains(mouseWheel, `${currentMinutes}`);
timepicker.triggerEventOnInput(mouseWheel, 'wheel', 1, {deltaY: 1});
timepicker.isInputValueContain(mouseWheel, `${currentMinutes}`, 1);
timepicker.isAlertContains(mouseWheel, `${currentMinutes}`);
});
it(`when user changes hours and minutes by arrow navigation, data change successfully`, () => {
const newDate = new Date();
const currentMinutes = newDate.getMinutes();
const hour12Format = timepicker.getHoursIn12Format(newDate);
const hour24Format = newDate.getHours();
timepicker.clickOnArrow(mouseWheel, 'up', 1);
timepicker.isInputValueContain(mouseWheel, `${
currentMinutes < 55 ? currentMinutes + 5 : currentMinutes - 60 + 5}`, 1);
timepicker.isAlertContains(mouseWheel, `${
currentMinutes < 55 ? currentMinutes + 5 : currentMinutes - 60 + 5}`);
timepicker.clickOnArrow(mouseWheel, 'down', 1);
timepicker.isInputValueContain(mouseWheel, `${currentMinutes}`, 1);
timepicker.isAlertContains(mouseWheel, `${currentMinutes}`);
timepicker.clickOnArrow(mouseWheel, 'up', 0);
timepicker.isInputValueContain(mouseWheel, `${hour12Format === 12 ? 1 : hour12Format + 1}`, 0);
timepicker.isAlertContains(mouseWheel, `${hour24Format === 23 ? 0 : hour24Format + 1}`);
timepicker.clickOnArrow(mouseWheel, 'down', 0);
timepicker.isInputValueContain(mouseWheel, `${hour12Format}`, 0);
timepicker.isAlertContains(mouseWheel, `${hour24Format}`);
});
it(`when user clicks on "Enable / Disable mouse wheel" button again, then user can change hours
and minutes with mouse wheel scrolling again`,
() => {
const newDate = new Date();
const currentMinutes = newDate.getMinutes();
const hour12Format = timepicker.getHoursIn12Format(newDate);
const hour24Format = newDate.getHours();
timepicker.clickOnBtn(mouseWheel, 1);
timepicker.triggerEventOnInput(mouseWheel, 'wheel', 0, {deltaY: -1});
timepicker.isInputValueContain(mouseWheel, `${hour12Format}`, 0);
timepicker.isAlertContains(mouseWheel, `${hour24Format}`);
timepicker.triggerEventOnInput(mouseWheel, 'wheel', 0, {deltaY: 1});
timepicker.isInputValueContain(mouseWheel, `${hour12Format}`, 0);
timepicker.isAlertContains(mouseWheel, `${hour24Format}`);
timepicker.triggerEventOnInput(mouseWheel, 'wheel', 1, {deltaY: -1});
timepicker.isInputValueContain(mouseWheel, `${currentMinutes}`, 1);
timepicker.isAlertContains(mouseWheel, `${currentMinutes}`);
timepicker.triggerEventOnInput(mouseWheel, 'wheel', 1, {deltaY: 1});
timepicker.isInputValueContain(mouseWheel, `${currentMinutes}`, 1);
timepicker.isAlertContains(mouseWheel, `${currentMinutes}`);
});
});
| valor-software/ngx-bootstrap | apps/ngx-bootstrap-docs-e2e/src/full/timepicker/mouse_wheel_spec.ts | TypeScript | mit | 6,536 |
Meteor.startup(function () {
Template.categoriesMenu.helpers({
hasCategories: function () {
return Categories.find().count();
},
menuItems: function () {
var defaultItem = [{
route: 'posts_default',
label: 'all_categories',
itemClass: 'item-never-active'
}];
var menuItems = _.map(Categories.find({}, {sort: {order: 1, name: 1}}).fetch(), function (category) {
return {
route: function () {
return getCategoryUrl(category.slug);
},
label: category.name
}
});
return defaultItem.concat(menuItems);
},
menuMode: function () {
if (!!this.mobile) {
return 'list';
} else if (Settings.get('navLayout', 'top-nav') === 'top-nav') {
return 'dropdown';
} else {
return 'accordion';
}
}
});
});
| NYUMusEdLab/fork-cb | packages/telescope-tags/lib/client/templates/categories_menu.js | JavaScript | mit | 879 |
from django.conf.urls.defaults import *
urlpatterns = patterns('budget.transactions.views',
url(r'^$', 'transaction_list', name='budget_transaction_list'),
url(r'^add/$', 'transaction_add', name='budget_transaction_add'),
url(r'^edit/(?P<transaction_id>\d+)/$', 'transaction_edit', name='budget_transaction_edit'),
url(r'^delete/(?P<transaction_id>\d+)/$', 'transaction_delete', name='budget_transaction_delete'),
)
| MVReddy/django-mybudget | budget/transactions/urls.py | Python | mit | 433 |
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the plugins 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 "qcorewlanengine.h"
#include <QtNetwork/private/qbearerplugin_p.h>
#include <QtCore/qdebug.h>
#ifndef QT_NO_BEARERMANAGEMENT
QT_BEGIN_NAMESPACE
class QCoreWlanEnginePlugin : public QBearerEnginePlugin
{
public:
QCoreWlanEnginePlugin();
~QCoreWlanEnginePlugin();
QStringList keys() const;
QBearerEngine *create(const QString &key) const;
};
QCoreWlanEnginePlugin::QCoreWlanEnginePlugin()
{
}
QCoreWlanEnginePlugin::~QCoreWlanEnginePlugin()
{
}
QStringList QCoreWlanEnginePlugin::keys() const
{
return QStringList() << QLatin1String("corewlan");
}
QBearerEngine *QCoreWlanEnginePlugin::create(const QString &key) const
{
if (key == QLatin1String("corewlan"))
return new QCoreWlanEngine;
else
return 0;
}
Q_EXPORT_STATIC_PLUGIN(QCoreWlanEnginePlugin)
Q_EXPORT_PLUGIN2(qcorewlanbearer, QCoreWlanEnginePlugin)
QT_END_NAMESPACE
#endif // QT_NO_BEARERMANAGEMENT
| stephaneAG/PengPod700 | QtEsrc/qt-everywhere-opensource-src-4.8.5/src/plugins/bearer/corewlan/main.cpp | C++ | mit | 2,884 |
package pl.lodz.p.ftims.pai.config;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.servlet.InstrumentedFilter;
import com.codahale.metrics.servlets.MetricsServlet;
import pl.lodz.p.ftims.pai.web.filter.CachingHttpHeadersFilter;
import pl.lodz.p.ftims.pai.web.filter.StaticResourcesProductionFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.MimeMappings;
import org.springframework.boot.context.embedded.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.*;
import javax.inject.Inject;
import javax.servlet.*;
/**
* Configuration of web application with Servlet 3.0 APIs.
*/
@Configuration
@AutoConfigureAfter(CacheConfiguration.class)
public class WebConfigurer implements ServletContextInitializer, EmbeddedServletContainerCustomizer {
private final Logger log = LoggerFactory.getLogger(WebConfigurer.class);
@Inject
private Environment env;
@Inject
private JHipsterProperties props;
@Autowired(required = false)
private MetricRegistry metricRegistry;
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
log.info("Web application configuration, using profiles: {}", Arrays.toString(env.getActiveProfiles()));
EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC);
if (!env.acceptsProfiles(Constants.SPRING_PROFILE_FAST)) {
initMetrics(servletContext, disps);
}
if (env.acceptsProfiles(Constants.SPRING_PROFILE_PRODUCTION)) {
initCachingHttpHeadersFilter(servletContext, disps);
initStaticResourcesProductionFilter(servletContext, disps);
}
if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT)) {
initH2Console(servletContext);
}
log.info("Web application fully configured");
}
/**
* Set up Mime types.
*/
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
// IE issue, see https://github.com/jhipster/generator-jhipster/pull/711
mappings.add("html", "text/html;charset=utf-8");
// CloudFoundry issue, see https://github.com/cloudfoundry/gorouter/issues/64
mappings.add("json", "text/html;charset=utf-8");
container.setMimeMappings(mappings);
}
/**
* Initializes the static resources production Filter.
*/
private void initStaticResourcesProductionFilter(ServletContext servletContext,
EnumSet<DispatcherType> disps) {
log.debug("Registering static resources production Filter");
FilterRegistration.Dynamic staticResourcesProductionFilter =
servletContext.addFilter("staticResourcesProductionFilter",
new StaticResourcesProductionFilter());
staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/");
staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/index.html");
staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/assets/*");
staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/scripts/*");
staticResourcesProductionFilter.setAsyncSupported(true);
}
/**
* Initializes the caching HTTP Headers Filter.
*/
private void initCachingHttpHeadersFilter(ServletContext servletContext,
EnumSet<DispatcherType> disps) {
log.debug("Registering Caching HTTP Headers Filter");
FilterRegistration.Dynamic cachingHttpHeadersFilter =
servletContext.addFilter("cachingHttpHeadersFilter",
new CachingHttpHeadersFilter(env));
cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/dist/assets/*");
cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/dist/scripts/*");
cachingHttpHeadersFilter.setAsyncSupported(true);
}
/**
* Initializes Metrics.
*/
private void initMetrics(ServletContext servletContext, EnumSet<DispatcherType> disps) {
log.debug("Initializing Metrics registries");
servletContext.setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE,
metricRegistry);
servletContext.setAttribute(MetricsServlet.METRICS_REGISTRY,
metricRegistry);
log.debug("Registering Metrics Filter");
FilterRegistration.Dynamic metricsFilter = servletContext.addFilter("webappMetricsFilter",
new InstrumentedFilter());
metricsFilter.addMappingForUrlPatterns(disps, true, "/*");
metricsFilter.setAsyncSupported(true);
log.debug("Registering Metrics Servlet");
ServletRegistration.Dynamic metricsAdminServlet =
servletContext.addServlet("metricsServlet", new MetricsServlet());
metricsAdminServlet.addMapping("/metrics/metrics/*");
metricsAdminServlet.setAsyncSupported(true);
metricsAdminServlet.setLoadOnStartup(2);
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = props.getCors();
if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
source.registerCorsConfiguration("/api/**", config);
source.registerCorsConfiguration("/v2/api-docs", config);
source.registerCorsConfiguration("/oauth/**", config);
}
return new CorsFilter(source);
}
/**
* Initializes H2 console
*/
private void initH2Console(ServletContext servletContext) {
log.debug("Initialize H2 console");
ServletRegistration.Dynamic h2ConsoleServlet = servletContext.addServlet("H2Console", new org.h2.server.web.WebServlet());
h2ConsoleServlet.addMapping("/console/*");
h2ConsoleServlet.setInitParameter("-properties", "src/main/resources");
h2ConsoleServlet.setLoadOnStartup(1);
}
}
| wyzellak/sandbox-internet-apps-design | oddzial/src/main/java/pl/lodz/p/ftims/pai/config/WebConfigurer.java | Java | mit | 6,833 |
// Copyright (c) 2011-2013 The EmpireCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "entervotedialog.h"
#include "ui_entervotedialog.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
EntervoteDialog::EntervoteDialog(std::string& nation, QWidget *parent) :
QDialog(parent),
ui(new Ui::EntervoteDialog), model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
setWindowTitle(tr("Enter Vote Amount for Empire"));
std::string voteStr = "Vote for " + nation;
ui->labelEdit->setText(QString::fromStdString(voteStr));
ui->labelEdit->setEnabled(false);
ui->addressEdit->setEnabled(false);
ui->voteAmountEdit->setEnabled(true);
}
EntervoteDialog::~EntervoteDialog()
{
delete ui;
}
void EntervoteDialog::setModel(WalletModel *model)
{
this->model = model;
}
bool EntervoteDialog::submitVote()
{
if(!model)
return false;
nation = ui->labelEdit->text();
address = ui->addressEdit->text();
amount = ui->voteAmountEdit->text();
return !address.isEmpty() && !amount.isEmpty();
}
void EntervoteDialog::accept()
{
if (!model)
return;
if (submitVote())
QDialog::accept();
}
QString EntervoteDialog::getAddress() const
{
return address;
}
void EntervoteDialog::setAddress(const QString &address)
{
this->address = address;
ui->addressEdit->setText(address);
}
QString EntervoteDialog::getNation() const
{
return nation;
}
void EntervoteDialog::setNation(const QString &nation)
{
this->nation = nation;
ui->labelEdit->setText(nation);
}
QString EntervoteDialog::getAmount() const
{
return amount;
}
void EntervoteDialog::setAmount(const QString &amount)
{
this->amount = amount;
ui->voteAmountEdit->setText(amount);
}
| TeamEmpireCoin/EmpireCoin | src/qt/entervotedialog.cpp | C++ | mit | 1,959 |
package applications_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"time"
"code.cloudfoundry.org/cli/cf/api/apifakes"
"code.cloudfoundry.org/cli/cf/errors"
"code.cloudfoundry.org/cli/cf/models"
"code.cloudfoundry.org/cli/cf/net"
"code.cloudfoundry.org/cli/cf/terminal/terminalfakes"
testconfig "code.cloudfoundry.org/cli/cf/util/testhelpers/configuration"
testnet "code.cloudfoundry.org/cli/cf/util/testhelpers/net"
. "code.cloudfoundry.org/cli/cf/api/applications"
"code.cloudfoundry.org/cli/cf/trace/tracefakes"
. "code.cloudfoundry.org/cli/cf/util/testhelpers/matchers"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
)
var _ = Describe("ApplicationsRepository", func() {
Describe("finding apps by name", func() {
It("returns the app when it is found", func() {
ts, handler, repo := createAppRepo([]testnet.TestRequest{findAppRequest})
defer ts.Close()
app, apiErr := repo.Read("My App")
Expect(handler).To(HaveAllRequestsCalled())
Expect(apiErr).NotTo(HaveOccurred())
Expect(app.Name).To(Equal("My App"))
Expect(app.GUID).To(Equal("app1-guid"))
Expect(app.Memory).To(Equal(int64(128)))
Expect(app.DiskQuota).To(Equal(int64(512)))
Expect(app.InstanceCount).To(Equal(1))
Expect(app.EnvironmentVars).To(Equal(map[string]interface{}{"foo": "bar", "baz": "boom"}))
Expect(app.Routes[0].Host).To(Equal("app1"))
Expect(app.Routes[0].Domain.Name).To(Equal("cfapps.io"))
Expect(app.Stack.Name).To(Equal("awesome-stacks-ahoy"))
})
It("returns a failure response when the app is not found", func() {
request := apifakes.NewCloudControllerTestRequest(findAppRequest)
request.Response = testnet.TestResponse{Status: http.StatusOK, Body: `{"resources": []}`}
ts, handler, repo := createAppRepo([]testnet.TestRequest{request})
defer ts.Close()
_, apiErr := repo.Read("My App")
Expect(handler).To(HaveAllRequestsCalled())
Expect(apiErr.(*errors.ModelNotFoundError)).NotTo(BeNil())
})
})
Describe(".GetApp", func() {
It("returns an application using the given app guid", func() {
request := apifakes.NewCloudControllerTestRequest(testnet.TestRequest{
Method: "GET",
Path: "/v2/apps/app-guid",
Response: appModelResponse,
})
ts, handler, repo := createAppRepo([]testnet.TestRequest{request})
defer ts.Close()
app, err := repo.GetApp("app-guid")
Expect(err).ToNot(HaveOccurred())
Expect(handler).To(HaveAllRequestsCalled())
Expect(app.Name).To(Equal("My App"))
})
})
Describe(".ReadFromSpace", func() {
It("returns an application using the given space guid", func() {
request := apifakes.NewCloudControllerTestRequest(testnet.TestRequest{
Method: "GET",
Path: "/v2/spaces/another-space-guid/apps?q=name%3AMy+App&inline-relations-depth=1",
Response: singleAppResponse,
})
ts, handler, repo := createAppRepo([]testnet.TestRequest{request})
defer ts.Close()
app, err := repo.ReadFromSpace("My App", "another-space-guid")
Expect(err).ToNot(HaveOccurred())
Expect(handler).To(HaveAllRequestsCalled())
Expect(app.Name).To(Equal("My App"))
})
})
Describe("Create", func() {
var (
ccServer *ghttp.Server
repo CloudControllerRepository
appParams models.AppParams
)
BeforeEach(func() {
ccServer = ghttp.NewServer()
configRepo := testconfig.NewRepositoryWithDefaults()
configRepo.SetAPIEndpoint(ccServer.URL())
gateway := net.NewCloudControllerGateway(configRepo, time.Now, new(terminalfakes.FakeUI), new(tracefakes.FakePrinter), "")
repo = NewCloudControllerRepository(configRepo, gateway)
name := "my-cool-app"
buildpackURL := "buildpack-url"
spaceGUID := "some-space-guid"
stackGUID := "some-stack-guid"
command := "some-command"
memory := int64(2048)
diskQuota := int64(512)
instanceCount := 3
appParams = models.AppParams{
Name: &name,
BuildpackURL: &buildpackURL,
SpaceGUID: &spaceGUID,
StackGUID: &stackGUID,
Command: &command,
Memory: &memory,
DiskQuota: &diskQuota,
InstanceCount: &instanceCount,
}
ccServer.AppendHandlers(
ghttp.CombineHandlers(
ghttp.VerifyRequest("POST", "/v2/apps"),
ghttp.VerifyJSON(`{
"name":"my-cool-app",
"instances":3,
"buildpack":"buildpack-url",
"memory":2048,
"disk_quota": 512,
"space_guid":"some-space-guid",
"stack_guid":"some-stack-guid",
"command":"some-command"
}`),
),
)
})
AfterEach(func() {
ccServer.Close()
})
It("tries to create the app", func() {
repo.Create(appParams)
Expect(ccServer.ReceivedRequests()).To(HaveLen(1))
})
Context("when the create succeeds", func() {
BeforeEach(func() {
h := ccServer.GetHandler(0)
ccServer.SetHandler(0,
ghttp.CombineHandlers(
h,
ghttp.RespondWith(http.StatusCreated, `{
"metadata": {
"guid": "my-cool-app-guid"
},
"entity": {
"name": "my-cool-app"
}
}`),
),
)
})
It("returns the application", func() {
createdApp, err := repo.Create(appParams)
Expect(err).NotTo(HaveOccurred())
app := models.Application{}
app.Name = "my-cool-app"
app.GUID = "my-cool-app-guid"
Expect(createdApp).To(Equal(app))
})
})
Context("when the create fails", func() {
BeforeEach(func() {
h := ccServer.GetHandler(0)
ccServer.SetHandler(0,
ghttp.CombineHandlers(
h,
ghttp.RespondWith(http.StatusInternalServerError, ""),
),
)
})
It("returns an error", func() {
_, err := repo.Create(appParams)
Expect(err).To(HaveOccurred())
})
})
})
Describe("reading environment for an app", func() {
Context("when the response can be parsed as json", func() {
var (
testServer *httptest.Server
userEnv *models.Environment
err error
handler *testnet.TestHandler
repo Repository
)
AfterEach(func() {
testServer.Close()
})
Context("when there are system provided env vars", func() {
BeforeEach(func() {
var appEnvRequest = apifakes.NewCloudControllerTestRequest(testnet.TestRequest{
Method: "GET",
Path: "/v2/apps/some-cool-app-guid/env",
Response: testnet.TestResponse{
Status: http.StatusOK,
Body: `
{
"staging_env_json": {
"STAGING_ENV": "staging_value",
"staging": true,
"number": 42
},
"running_env_json": {
"RUNNING_ENV": "running_value",
"running": false,
"number": 37
},
"environment_json": {
"key": "value",
"number": 123,
"bool": true
},
"system_env_json": {
"VCAP_SERVICES": {
"system_hash": {
"system_key": "system_value"
}
}
}
}
`,
}})
testServer, handler, repo = createAppRepo([]testnet.TestRequest{appEnvRequest})
userEnv, err = repo.ReadEnv("some-cool-app-guid")
Expect(err).ToNot(HaveOccurred())
Expect(handler).To(HaveAllRequestsCalled())
})
It("returns the user environment, vcap services, running/staging env variables", func() {
Expect(userEnv.Environment["key"]).To(Equal("value"))
Expect(userEnv.Environment["number"]).To(Equal(float64(123)))
Expect(userEnv.Environment["bool"]).To(BeTrue())
Expect(userEnv.Running["RUNNING_ENV"]).To(Equal("running_value"))
Expect(userEnv.Running["running"]).To(BeFalse())
Expect(userEnv.Running["number"]).To(Equal(float64(37)))
Expect(userEnv.Staging["STAGING_ENV"]).To(Equal("staging_value"))
Expect(userEnv.Staging["staging"]).To(BeTrue())
Expect(userEnv.Staging["number"]).To(Equal(float64(42)))
vcapServices := userEnv.System["VCAP_SERVICES"]
data, err := json.Marshal(vcapServices)
Expect(err).ToNot(HaveOccurred())
Expect(string(data)).To(ContainSubstring("\"system_key\":\"system_value\""))
})
})
Context("when there are no environment variables", func() {
BeforeEach(func() {
var emptyEnvRequest = apifakes.NewCloudControllerTestRequest(testnet.TestRequest{
Method: "GET",
Path: "/v2/apps/some-cool-app-guid/env",
Response: testnet.TestResponse{
Status: http.StatusOK,
Body: `{"system_env_json": {"VCAP_SERVICES": {} }}`,
}})
testServer, handler, repo = createAppRepo([]testnet.TestRequest{emptyEnvRequest})
userEnv, err = repo.ReadEnv("some-cool-app-guid")
Expect(err).ToNot(HaveOccurred())
Expect(handler).To(HaveAllRequestsCalled())
})
It("returns an empty string", func() {
Expect(len(userEnv.Environment)).To(Equal(0))
Expect(len(userEnv.System["VCAP_SERVICES"].(map[string]interface{}))).To(Equal(0))
})
})
})
})
Describe("restaging applications", func() {
It("POSTs to the right URL", func() {
appRestageRequest := apifakes.NewCloudControllerTestRequest(testnet.TestRequest{
Method: "POST",
Path: "/v2/apps/some-cool-app-guid/restage",
Response: testnet.TestResponse{
Status: http.StatusOK,
Body: "",
},
})
ts, handler, repo := createAppRepo([]testnet.TestRequest{appRestageRequest})
defer ts.Close()
repo.CreateRestageRequest("some-cool-app-guid")
Expect(handler).To(HaveAllRequestsCalled())
})
})
Describe("updating applications", func() {
It("makes the right request", func() {
ts, handler, repo := createAppRepo([]testnet.TestRequest{updateApplicationRequest})
defer ts.Close()
app := models.Application{}
app.GUID = "my-app-guid"
app.Name = "my-cool-app"
app.BuildpackURL = "buildpack-url"
app.Command = "some-command"
app.HealthCheckType = "none"
app.Memory = 2048
app.InstanceCount = 3
app.Stack = &models.Stack{GUID: "some-stack-guid"}
app.SpaceGUID = "some-space-guid"
app.State = "started"
app.DiskQuota = 512
Expect(app.EnvironmentVars).To(BeNil())
updatedApp, apiErr := repo.Update(app.GUID, app.ToParams())
Expect(handler).To(HaveAllRequestsCalled())
Expect(apiErr).NotTo(HaveOccurred())
Expect(updatedApp.Command).To(Equal("some-command"))
Expect(updatedApp.DetectedStartCommand).To(Equal("detected command"))
Expect(updatedApp.Name).To(Equal("my-cool-app"))
Expect(updatedApp.GUID).To(Equal("my-cool-app-guid"))
})
It("sets environment variables", func() {
request := apifakes.NewCloudControllerTestRequest(testnet.TestRequest{
Method: "PUT",
Path: "/v2/apps/app1-guid",
Matcher: testnet.RequestBodyMatcher(`{"environment_json":{"DATABASE_URL":"mysql://example.com/my-db"}}`),
Response: testnet.TestResponse{Status: http.StatusCreated},
})
ts, handler, repo := createAppRepo([]testnet.TestRequest{request})
defer ts.Close()
envParams := map[string]interface{}{"DATABASE_URL": "mysql://example.com/my-db"}
params := models.AppParams{EnvironmentVars: &envParams}
_, apiErr := repo.Update("app1-guid", params)
Expect(handler).To(HaveAllRequestsCalled())
Expect(apiErr).NotTo(HaveOccurred())
})
It("can remove environment variables", func() {
request := apifakes.NewCloudControllerTestRequest(testnet.TestRequest{
Method: "PUT",
Path: "/v2/apps/app1-guid",
Matcher: testnet.RequestBodyMatcher(`{"environment_json":{}}`),
Response: testnet.TestResponse{Status: http.StatusCreated},
})
ts, handler, repo := createAppRepo([]testnet.TestRequest{request})
defer ts.Close()
envParams := map[string]interface{}{}
params := models.AppParams{EnvironmentVars: &envParams}
_, apiErr := repo.Update("app1-guid", params)
Expect(handler).To(HaveAllRequestsCalled())
Expect(apiErr).NotTo(HaveOccurred())
})
})
It("deletes applications", func() {
deleteApplicationRequest := apifakes.NewCloudControllerTestRequest(testnet.TestRequest{
Method: "DELETE",
Path: "/v2/apps/my-cool-app-guid?recursive=true",
Response: testnet.TestResponse{Status: http.StatusOK, Body: ""},
})
ts, handler, repo := createAppRepo([]testnet.TestRequest{deleteApplicationRequest})
defer ts.Close()
apiErr := repo.Delete("my-cool-app-guid")
Expect(handler).To(HaveAllRequestsCalled())
Expect(apiErr).NotTo(HaveOccurred())
})
})
var appModelResponse = testnet.TestResponse{
Status: http.StatusOK,
Body: `
{
"metadata": {
"guid": "app1-guid"
},
"entity": {
"name": "My App",
"environment_json": {
"foo": "bar",
"baz": "boom"
},
"memory": 128,
"instances": 1,
"disk_quota": 512,
"state": "STOPPED",
"stack": {
"metadata": {
"guid": "app1-route-guid"
},
"entity": {
"name": "awesome-stacks-ahoy"
}
},
"routes": [
{
"metadata": {
"guid": "app1-route-guid"
},
"entity": {
"host": "app1",
"domain": {
"metadata": {
"guid": "domain1-guid"
},
"entity": {
"name": "cfapps.io"
}
}
}
}
]
}
}
`}
var singleAppResponse = testnet.TestResponse{
Status: http.StatusOK,
Body: `
{
"resources": [
{
"metadata": {
"guid": "app1-guid"
},
"entity": {
"name": "My App",
"environment_json": {
"foo": "bar",
"baz": "boom"
},
"memory": 128,
"instances": 1,
"disk_quota": 512,
"state": "STOPPED",
"stack": {
"metadata": {
"guid": "app1-route-guid"
},
"entity": {
"name": "awesome-stacks-ahoy"
}
},
"routes": [
{
"metadata": {
"guid": "app1-route-guid"
},
"entity": {
"host": "app1",
"domain": {
"metadata": {
"guid": "domain1-guid"
},
"entity": {
"name": "cfapps.io"
}
}
}
}
]
}
}
]
}`}
var findAppRequest = apifakes.NewCloudControllerTestRequest(testnet.TestRequest{
Method: "GET",
Path: "/v2/spaces/my-space-guid/apps?q=name%3AMy+App&inline-relations-depth=1",
Response: singleAppResponse,
})
var createApplicationResponse = `
{
"metadata": {
"guid": "my-cool-app-guid"
},
"entity": {
"name": "my-cool-app"
}
}`
var updateApplicationResponse = `
{
"metadata": {
"guid": "my-cool-app-guid"
},
"entity": {
"name": "my-cool-app",
"command": "some-command",
"detected_start_command": "detected command"
}
}`
var updateApplicationRequest = apifakes.NewCloudControllerTestRequest(testnet.TestRequest{
Method: "PUT",
Path: "/v2/apps/my-app-guid?inline-relations-depth=1",
Matcher: testnet.RequestBodyMatcher(`{
"name":"my-cool-app",
"instances":3,
"buildpack":"buildpack-url",
"docker_image":"",
"memory":2048,
"health_check_type":"none",
"health_check_http_endpoint":"",
"disk_quota":512,
"space_guid":"some-space-guid",
"state":"STARTED",
"stack_guid":"some-stack-guid",
"command":"some-command"
}`),
Response: testnet.TestResponse{
Status: http.StatusOK,
Body: updateApplicationResponse},
})
func createAppRepo(requests []testnet.TestRequest) (ts *httptest.Server, handler *testnet.TestHandler, repo Repository) {
ts, handler = testnet.NewServer(requests)
configRepo := testconfig.NewRepositoryWithDefaults()
configRepo.SetAPIEndpoint(ts.URL)
gateway := net.NewCloudControllerGateway(configRepo, time.Now, new(terminalfakes.FakeUI), new(tracefakes.FakePrinter), "")
repo = NewCloudControllerRepository(configRepo, gateway)
return
}
| odlp/antifreeze | vendor/github.com/cloudfoundry/cli/cf/api/applications/applications_test.go | GO | mit | 15,812 |
#include <stdio.h>
int main(int argc, char const *argv[]) {
long long n;
scanf("%lld", &n);
long long ll = (n * (n - 3)) / 2;
printf("%lld\n", ll);
return 0;
}#include <stdio.h>
int main(int argc, char const *argv[]) {
long long n;
scanf("%lld", &n);
long long ll = (n * (n - 3)) / 2;
printf("%lld\n", ll);
return 0;
} | miguelarauj1o/URI | src/URI_1921 - (4661771) - Accepted.cpp | C++ | mit | 346 |
/** global: __methods_with_response__ */
/** global: __ajax_nonce__ */
/** global: __methods_with_data__ */
/** global: __content_form_urlencoded__ */
/** global: __content_json__ */
/** global: __content_multipart__ */
function _ajaxNonce(url, options) {
if(false === options.cache && options.method.match(__methods_with_response__)) {
if(!url.match(/_=/)) {
url += !url.match(/\?/)
? '?_='
: url.match(/\?$/)
? '_='
: '&_='
url += __ajax_nonce__++
}
}
return url
}
function _ajaxHeaders(xhr, headers) {
if(headers) {
/* eslint-disable guard-for-in */
for (var key in headers) {
xhr.setRequestHeader(key, headers[key])
}
/* eslint-enable guard-for-in */
}
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
}
function _ajaxContentType(xhr, options) {
if(_ajaxNoContentTypeNeeded(options)) {
return
}
if(!options.contentType) {
options.contentType = __content_form_urlencoded__
}
_ajaxHandleContentType(xhr, options)
}
function _ajaxHandleContentType(xhr, options) {
switch(options.contentType.toLowerCase()) {
case __content_form_urlencoded__:
case __content_json__:
xhr.setRequestHeader('Content-type', options.contentType)
break
case __content_multipart__:
if(options.multipartBoundary) {
xhr.setRequestHeader('Content-type', __content_multipart__ + '; boundary=' + options.multipartBoundary)
}
break
default:
throw new Error('Unsupported content type ' + options.contentType)
}
}
function _ajaxNoContentTypeNeeded(options) {
return(options.headers && options.headers['Content-type'] || !options.method.match(__methods_with_data__))
}
| reeteshranjan/browse.js | lib/ajax-request.js | JavaScript | mit | 1,725 |
class User < ActiveRecord::Base
include ::SSO::Logging
# This is a test implementation only, do not try this at home.
#
def self.authenticate(username, password)
Rails.logger.debug('User') { "Checking password of user #{username.inspect}..." }
where(email: username, password: password).first
end
# Don't try this at home, you should include the *encrypted* password, not the plaintext here.
#
def state_base
result = [email.to_s, password.to_s, tags.map(&:to_s).sort].join
debug { "The user state base is #{result.inspect}" }
result
end
end
| halo/sso | spec/dummy/app/models/user.rb | Ruby | mit | 583 |
/*jshint ignore:start,-W101*/ // allow long lines
Tinytest.addAsync('dispatch:template-sequence - Test sequence offset -2', function(test, complete) {
var container = document.createElement('div');
document.body.appendChild(container);
var created = 0;
var rendered = 0;
var destroyed = 0;
Template.item.created = function() {
created++;
};
Template.item.rendered = function() {
rendered++;
};
Template.item.destroyed = function() {
destroyed++;
};
var foo = new TemplateSequence({
template: Template.item,
index: 0,
offset: -2,
container: container,
size: 5
});
var c = 0;
foo.forEach(function(item, index, i) {
test.equal(c, i, 'counter off');
test.equal(c + 2, index, 'counter off');
c++;
});
test.equal(foo.items.length, 5, 'Wrong length');
test.equal(created, 5);
test.equal(destroyed, 0);
test.equal(container.innerHTML, '23456', 'Rendered index did not match');
foo.resize(7);
test.equal(foo.items.length, 7, 'Wrong length after resize');
test.equal(created, 7, 'Created counter dont match');
test.equal(destroyed, 0);
test.equal(container.innerHTML, '2345678', 'Rendered index did not match');
foo.resize(3);
test.equal(foo.items.length, 3, 'Wrong length after resize');
test.equal(created, 7, 'Created counter dont match');
test.equal(destroyed, 4);
test.equal(container.innerHTML, '234', 'Rendered index did not match');
foo.resize(10);
test.equal(foo.items.length, 10, 'Wrong length after resize');
test.equal(created, 14, 'Created counter dont match');
test.equal(destroyed, 4);
test.equal(container.innerHTML, '234567891011', 'Rendered index did not match');
foo.setIndex(0);
test.equal(foo.items.length, 10, 'Wrong length after index 0');
test.equal(created, 14, 'Created counter dont match');
test.equal(destroyed, 4);
test.equal(container.innerHTML, '234567891011', 'Rendered index did not match');
test.equal(rendered, 0, 'Templates should rendered off');
foo.setIndex(10);
Tracker.flush();
// Wait a sec before checking dom etc
Meteor.setTimeout(function() {
test.equal(rendered, 10, 'Templates should rendered off');
test.equal(foo.items.length, 10, 'Wrong length after index 10');
test.equal(created, 14, 'Created counter dont match');
test.equal(destroyed, 4);
test.equal(container.innerHTML, '12131415161718192021', 'Rendered index 10 did not match');
foo.setIndex(-10);
Tracker.flush();
Meteor.setTimeout(function() {
test.equal(rendered, 10, 'Templates should rendered off');
test.equal(foo.items.length, 10, 'Wrong length after index 10');
test.equal(created, 14, 'Created counter dont match');
test.equal(destroyed, 4);
test.equal(container.innerHTML, '-8-7-6-5-4-3-2-101', 'Rendered index 10 did not match');
foo.destroy();
test.equal(container.innerHTML, '', 'Rendered index did not match');
test.equal(destroyed, created, 'TemplateSequence did not clean up');
// Clean up
document.body.removeChild(container);
complete();
}, 300);
}, 300);
});
//Test API:
//test.isFalse(v, msg)
//test.isTrue(v, msg)
//test.equalactual, expected, message, not
//test.length(obj, len)
//test.include(s, v)
//test.isNaN(v, msg)
//test.isUndefined(v, msg)
//test.isNotNull
//test.isNull
//test.throws(func)
//test.instanceOf(obj, klass)
//test.notEqual(actual, expected, message)
//test.runId()
//test.exception(exception)
//test.expect_fail()
//test.ok(doc)
//test.fail(doc)
//test.equal(a, b, msg)
/*jshint ignore:end,-W101*/
| DispatchMe/meteor-scrollview | tests/template-sequence.2.js | JavaScript | mit | 3,612 |
// 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
namespace Dnn.PersonaBar.Prompt.Services
{
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using Dnn.PersonaBar.Library.Attributes;
using Dnn.PersonaBar.Library.Prompt;
using Dnn.PersonaBar.Prompt.Common;
using Dnn.PersonaBar.Prompt.Components;
using Dnn.PersonaBar.Prompt.Components.Models;
using DotNetNuke.Entities.Controllers;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Instrumentation;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Log.EventLog;
using DotNetNuke.Web.Api;
[MenuPermission(MenuName = "Dnn.Prompt")]
[RequireHost]
public class CommandController : ControllerBase, IServiceRouteMapper
{
private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CommandController));
private static readonly string[] BlackList = { "smtppassword", "password", "pwd", "pass", "apikey" };
private int _portalId = -1;
private PortalSettings _portalSettings;
private new int PortalId
{
get
{
if (this._portalId == -1)
{
this._portalId = base.PortalId;
}
return this._portalId;
}
set
{
this._portalId = value;
}
}
private new PortalSettings PortalSettings
{
get
{
if (this._portalSettings == null)
{
this._portalSettings = base.PortalSettings;
}
return this._portalSettings;
}
set
{
this._portalSettings = value;
}
}
[ValidateAntiForgeryToken]
[HttpPost]
public HttpResponseMessage Cmd(int portalId, [FromBody] CommandInputModel command)
{
var portal = PortalController.Instance.GetPortal(portalId);
if (portal == null)
{
var errorMessage = string.Format(Localization.GetString("Prompt_GetPortal_NotFound", Constants.LocalResourcesFile), portalId);
Logger.Error(errorMessage);
return this.AddLogAndReturnResponse(null, null, command, DateTime.Now, errorMessage);
}
this.PortalId = portalId;
this.SetupPortalSettings(portalId);
return this.Cmd(command);
}
[ValidateAntiForgeryToken]
[HttpPost]
public HttpResponseMessage Cmd([FromBody] CommandInputModel command)
{
var startTime = DateTime.Now;
try
{
var args = command.Args;
var isHelpCmd = args.First().ToUpper() == "HELP";
var isHelpLearn = isHelpCmd && args.Length > 1 && args[1].ToUpper() == "LEARN";
var isHelpSyntax = isHelpCmd && args.Length > 1 && args[1].ToUpper() == "SYNTAX";
var cmdName = isHelpCmd ? (args.Length > 1 ? args[1].ToUpper() : "") : args.First().ToUpper();
if (isHelpSyntax)
{
return Request.CreateResponse(HttpStatusCode.OK, new CommandHelp()
{
ResultHtml = Localization.GetString("Prompt_CommandHelpSyntax", Constants.LocalResourcesFile)
});
}
else if (isHelpLearn)
{
return Request.CreateResponse(HttpStatusCode.OK, new CommandHelp()
{
ResultHtml = Localization.GetString("Prompt_CommandHelpLearn", Constants.LocalResourcesFile)
});
}
else if (isHelpCmd && args.Length == 1)
return AddLogAndReturnResponse(null, null, command, startTime,
string.Format(Localization.GetString("CommandNotFound", Constants.LocalResourcesFile),
cmdName.ToLower()));
// first look in new commands, then in the old commands
var newCommand = DotNetNuke.Prompt.CommandRepository.Instance.GetCommand(cmdName);
if (newCommand == null)
{
var allCommands = Components.Repositories.CommandRepository.Instance.GetCommands();
// if no command found notify
if (!allCommands.ContainsKey(cmdName))
{
var sbError = new StringBuilder();
var suggestion = Utilities.GetSuggestedCommand(cmdName);
sbError.AppendFormat(Localization.GetString("CommandNotFound", Constants.LocalResourcesFile), cmdName.ToLower());
if (!string.IsNullOrEmpty(suggestion))
{
sbError.AppendFormat(Localization.GetString("DidYouMean", Constants.LocalResourcesFile), suggestion);
}
return AddLogAndReturnResponse(null, null, command, startTime, sbError.ToString());
}
return TryRunOldCommand(command, allCommands[cmdName].CommandType, args, isHelpCmd, startTime);
}
else
{
return TryRunNewCommand(command, newCommand, args, isHelpCmd, startTime);
}
}
catch (Exception ex)
{
Logger.Error(ex);
return this.AddLogAndReturnResponse(null, null, command, startTime, ex.Message);
}
}
public void RegisterRoutes(IMapRoute mapRouteManager)
{
mapRouteManager.MapHttpRoute("PersonaBar", "promptwithportalid", "{controller}/{action}/{portalId}", null, new { portalId = "-?\\d+" }, new[] { "Dnn.PersonaBar.Prompt.Services" });
}
private static string FilterCommand(string command)
{
var blackList = BlackList;
var promptBlackList = HostController.Instance.GetString("PromptBlackList", string.Empty)
.Split(new[] { ',', '|', ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (promptBlackList.Length > 0)
{
blackList = blackList.Concat(promptBlackList).Distinct().ToArray();
}
var args = command.Split(new[] { ',', '|', ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.ToLowerInvariant()).ToList();
foreach (var lowerKey in blackList.Select(key => key.ToLowerInvariant())
.Where(lowerKey => args.Any(arg => arg.Replace("-", "") == lowerKey)))
{
args[args.TakeWhile(arg => arg.Replace("-", "") != lowerKey).Count() + 1] = "******";
}
return string.Join(" ", args);
}
private void SetupPortalSettings(int portalId)
{
this.PortalSettings = new PortalSettings(portalId);
var portalAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId);
this.PortalSettings.PrimaryAlias = portalAliases.FirstOrDefault(a => a.IsPrimary);
this.PortalSettings.PortalAlias = PortalAliasController.Instance.GetPortalAlias(this.PortalSettings.DefaultPortalAlias);
}
private HttpResponseMessage TryRunOldCommand(CommandInputModel command, Type cmdTypeToRun, string[] args, bool isHelpCmd, DateTime startTime)
{
// Instantiate and run the command
try
{
var cmdObj = (IConsoleCommand)Activator.CreateInstance(cmdTypeToRun);
if (isHelpCmd) return Request.CreateResponse(HttpStatusCode.OK, Components.Repositories.CommandRepository.Instance.GetCommandHelp(command.Args, cmdObj));
// set env. data for command use
cmdObj.Initialize(args, PortalSettings, UserInfo, command.CurrentPage);
return AddLogAndReturnResponse(cmdObj, cmdTypeToRun, command, startTime);
}
catch (Exception ex)
{
Logger.Error(ex);
return AddLogAndReturnResponse(null, null, command, startTime, ex.Message);
}
}
private HttpResponseMessage TryRunNewCommand(CommandInputModel command, DotNetNuke.Abstractions.Prompt.IConsoleCommand cmdTypeToRun, string[] args, bool isHelpCmd, DateTime startTime)
{
// Instantiate and run the command that uses the new interfaces and base class
try
{
var cmdObj = (DotNetNuke.Abstractions.Prompt.IConsoleCommand)Activator.CreateInstance(cmdTypeToRun.GetType());
if (isHelpCmd) return Request.CreateResponse(HttpStatusCode.OK, DotNetNuke.Prompt.CommandRepository.Instance.GetCommandHelp(cmdObj));
// set env. data for command use
cmdObj.Initialize(args, PortalSettings, UserInfo, command.CurrentPage);
return AddLogAndReturnResponseNewCommands(cmdObj, command, startTime);
}
catch (Exception ex)
{
Logger.Error(ex);
return AddLogAndReturnResponse(null, null, command, startTime, ex.Message);
}
}
private HttpResponseMessage AddLogAndReturnResponseNewCommands(DotNetNuke.Abstractions.Prompt.IConsoleCommand consoleCommand, CommandInputModel command,
DateTime startTime, string error = null)
{
HttpResponseMessage message;
var isValid = consoleCommand?.IsValid() ?? false;
var logInfo = new LogInfo
{
LogTypeKey = "PROMPT_ALERT"
};
logInfo.LogProperties.Add(new LogDetailInfo("Command", FilterCommand(command.CmdLine)));
logInfo.LogProperties.Add(new LogDetailInfo("IsValid", isValid.ToString()));
try
{
logInfo.LogProperties.Add(new LogDetailInfo("TypeFullName", consoleCommand.GetType().FullName));
if (isValid)
{
var result = consoleCommand.Run();
if (result.PagingInfo != null)
{
if (result.PagingInfo.PageNo < result.PagingInfo.TotalPages)
{
result.Output = string.Format(Localization.GetString("Prompt_PagingMessageWithLoad", Constants.LocalResourcesFile),
result.PagingInfo.PageNo, result.PagingInfo.TotalPages);
var args = command.Args;
var indexOfPage = args.Any(x => x.ToLowerInvariant() == "--page")
? args.TakeWhile(arg => arg.ToLowerInvariant() != "--page").Count()
: -1;
if (indexOfPage > -1)
{
args[indexOfPage + 1] = (result.PagingInfo.PageNo + 1).ToString();
}
var nextPageCommand = string.Join(" ", args);
if (indexOfPage == -1)
{
nextPageCommand += " --page " + (result.PagingInfo.PageNo + 1);
}
result.NextPageCommand = nextPageCommand;
}
else if (result.Records > 0)
{
result.Output = string.Format(Localization.GetString("Prompt_PagingMessage", Constants.LocalResourcesFile),
result.PagingInfo.PageNo, result.PagingInfo.TotalPages);
}
}
message = Request.CreateResponse(HttpStatusCode.OK, result);
logInfo.LogProperties.Add(new LogDetailInfo("RecordsAffected", result.Records.ToString()));
logInfo.LogProperties.Add(new LogDetailInfo("Output", result.Output));
}
else
{
logInfo.LogProperties.Add(new LogDetailInfo("Output", consoleCommand?.ValidationMessage ?? error));
message = BadRequestResponse(consoleCommand?.ValidationMessage ?? error);
}
}
catch (Exception ex)
{
logInfo.Exception = new ExceptionInfo(ex);
message = BadRequestResponse(ex.Message);
}
logInfo.LogProperties.Add(new LogDetailInfo("ExecutionTime(hh:mm:ss)", TimeSpan.FromMilliseconds(DateTime.Now.Subtract(startTime).TotalMilliseconds).ToString(@"hh\:mm\:ss\.ffffff")));
LogController.Instance.AddLog(logInfo);
return message;
}
/// <summary>
/// Log every command run by a users.
/// </summary>
/// <param name="consoleCommand"></param>
/// <param name="cmdTypeToRun"></param>
/// <param name="command"></param>
/// <param name="startTime"></param>
/// <param name="error"></param>
/// <returns></returns>
private HttpResponseMessage AddLogAndReturnResponse(IConsoleCommand consoleCommand, Type cmdTypeToRun, CommandInputModel command,
DateTime startTime, string error = null)
{
HttpResponseMessage message;
var isValid = consoleCommand?.IsValid() ?? false;
var logInfo = new LogInfo
{
LogTypeKey = "PROMPT_ALERT"
};
logInfo.LogProperties.Add(new LogDetailInfo("Command", FilterCommand(command.CmdLine)));
logInfo.LogProperties.Add(new LogDetailInfo("IsValid", isValid.ToString()));
try
{
if (cmdTypeToRun != null)
logInfo.LogProperties.Add(new LogDetailInfo("TypeFullName", cmdTypeToRun.FullName));
if (isValid)
{
var result = consoleCommand.Run();
if (result.PagingInfo != null)
{
if (result.PagingInfo.PageNo < result.PagingInfo.TotalPages)
{
result.Output = string.Format(Localization.GetString("Prompt_PagingMessageWithLoad", Constants.LocalResourcesFile),
result.PagingInfo.PageNo, result.PagingInfo.TotalPages);
var args = command.Args;
var indexOfPage = args.Any(x => x.ToLowerInvariant() == "--page")
? args.TakeWhile(arg => arg.ToLowerInvariant() != "--page").Count()
: -1;
if (indexOfPage > -1)
{
args[indexOfPage + 1] = (result.PagingInfo.PageNo + 1).ToString();
}
var nextPageCommand = string.Join(" ", args);
if (indexOfPage == -1)
{
nextPageCommand += " --page " + (result.PagingInfo.PageNo + 1);
}
result.NextPageCommand = nextPageCommand;
}
else if (result.Records > 0)
{
result.Output = string.Format(Localization.GetString("Prompt_PagingMessage", Constants.LocalResourcesFile),
result.PagingInfo.PageNo, result.PagingInfo.TotalPages);
}
}
message = this.Request.CreateResponse(HttpStatusCode.OK, result);
logInfo.LogProperties.Add(new LogDetailInfo("RecordsAffected", result.Records.ToString()));
logInfo.LogProperties.Add(new LogDetailInfo("Output", result.Output));
}
else
{
logInfo.LogProperties.Add(new LogDetailInfo("Output", consoleCommand?.ValidationMessage ?? error));
message = this.BadRequestResponse(consoleCommand?.ValidationMessage ?? error);
}
}
catch (Exception ex)
{
logInfo.Exception = new ExceptionInfo(ex);
message = this.BadRequestResponse(ex.Message);
}
logInfo.LogProperties.Add(new LogDetailInfo("ExecutionTime(hh:mm:ss)", TimeSpan.FromMilliseconds(DateTime.Now.Subtract(startTime).TotalMilliseconds).ToString(@"hh\:mm\:ss\.ffffff")));
LogController.Instance.AddLog(logInfo);
return message;
}
}
}
| nvisionative/Dnn.Platform | Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Services/CommandController.cs | C# | mit | 17,384 |
'use strict';
const co = require('co');
const fs = require('fs-extra');
const ember = require('../helpers/ember');
const walkSync = require('walk-sync');
const Blueprint = require('../../lib/models/blueprint');
const path = require('path');
const tmp = require('ember-cli-internal-test-helpers/lib/helpers/tmp');
let root = process.cwd();
const util = require('util');
const EOL = require('os').EOL;
const chalk = require('chalk');
const chai = require('../chai');
let expect = chai.expect;
let file = chai.file;
let dir = chai.dir;
const forEach = require('ember-cli-lodash-subset').forEach;
let tmpDir = './tmp/new-test';
describe('Acceptance: ember new', function() {
this.timeout(10000);
beforeEach(co.wrap(function *() {
yield tmp.setup(tmpDir);
process.chdir(tmpDir);
}));
afterEach(function() {
return tmp.teardown(tmpDir);
});
function confirmBlueprintedForDir(dir) {
let blueprintPath = path.join(root, dir, 'files');
let expected = walkSync(blueprintPath);
let actual = walkSync('.').sort();
let directory = path.basename(process.cwd());
forEach(Blueprint.renamedFiles, function(destFile, srcFile) {
expected[expected.indexOf(srcFile)] = destFile;
});
expected.sort();
expect(directory).to.equal('foo');
expect(expected)
.to.deep.equal(actual, `${EOL} expected: ${util.inspect(expected)}${EOL} but got: ${util.inspect(actual)}`);
}
function confirmBlueprinted() {
return confirmBlueprintedForDir('blueprints/app');
}
it('ember new foo, where foo does not yet exist, works', co.wrap(function *() {
yield ember([
'new',
'foo',
'--skip-npm',
'--skip-bower',
]);
confirmBlueprinted();
}));
it('ember new with empty app name fails with a warning', co.wrap(function *() {
let err = yield expect(ember([
'new',
'',
])).to.be.rejected;
expect(err.name).to.equal('SilentError');
expect(err.message).to.contain('The `ember new` command requires a name to be specified.');
}));
it('ember new without app name fails with a warning', co.wrap(function *() {
let err = yield expect(ember([
'new',
])).to.be.rejected;
expect(err.name).to.equal('SilentError');
expect(err.message).to.contain('The `ember new` command requires a name to be specified.');
}));
it('ember new with app name creates new directory and has a dasherized package name', co.wrap(function *() {
yield ember([
'new',
'FooApp',
'--skip-npm',
'--skip-bower',
'--skip-git',
]);
expect(dir('FooApp')).to.not.exist;
expect(file('package.json')).to.exist;
let pkgJson = fs.readJsonSync('package.json');
expect(pkgJson.name).to.equal('foo-app');
}));
it('Can create new ember project in an existing empty directory', co.wrap(function *() {
fs.mkdirsSync('bar');
yield ember([
'new',
'foo',
'--skip-npm',
'--skip-bower',
'--skip-git',
'--directory=bar',
]);
}));
it('Cannot create new ember project in a populated directory', co.wrap(function *() {
fs.mkdirsSync('bar');
fs.writeFileSync(path.join('bar', 'package.json'), '{}');
let error = yield expect(ember([
'new',
'foo',
'--skip-npm',
'--skip-bower',
'--skip-git',
'--directory=bar',
])).to.be.rejected;
expect(error.name).to.equal('SilentError');
expect(error.message).to.equal('Directory \'bar\' already exists.');
}));
it('Cannot run ember new, inside of ember-cli project', co.wrap(function *() {
yield ember([
'new',
'foo',
'--skip-npm',
'--skip-bower',
'--skip-git',
]);
let error = yield expect(ember([
'new',
'foo',
'--skip-npm',
'--skip-bower',
'--skip-git',
])).to.be.rejected;
expect(dir('foo')).to.not.exist;
expect(error.name).to.equal('SilentError');
expect(error.message).to.equal(`You cannot use the ${chalk.green('new')} command inside an ember-cli project.`);
confirmBlueprinted();
}));
it('ember new with blueprint uses the specified blueprint directory with a relative path', co.wrap(function *() {
fs.mkdirsSync('my_blueprint/files');
fs.writeFileSync('my_blueprint/files/gitignore');
yield ember([
'new',
'foo',
'--skip-npm',
'--skip-bower',
'--skip-git',
'--blueprint=./my_blueprint',
]);
confirmBlueprintedForDir(path.join(tmpDir, 'my_blueprint'));
}));
it('ember new with blueprint uses the specified blueprint directory with an absolute path', co.wrap(function *() {
fs.mkdirsSync('my_blueprint/files');
fs.writeFileSync('my_blueprint/files/gitignore');
yield ember([
'new',
'foo',
'--skip-npm',
'--skip-bower',
'--skip-git',
`--blueprint=${path.resolve(process.cwd(), 'my_blueprint')}`,
]);
confirmBlueprintedForDir(path.join(tmpDir, 'my_blueprint'));
}));
it('ember new with git blueprint checks out the blueprint and uses it', co.wrap(function *() {
this.timeout(20000); // relies on GH network stuff
yield ember([
'new',
'foo',
'--skip-npm',
'--skip-bower',
'--skip-git',
'--blueprint=https://github.com/ember-cli/app-blueprint-test.git',
]);
expect(file('.ember-cli')).to.exist;
}));
it('ember new passes blueprint options through to blueprint', co.wrap(function *() {
fs.mkdirsSync('my_blueprint/files');
fs.writeFileSync('my_blueprint/index.js', [
'module.exports = {',
' availableOptions: [ { name: \'custom-option\' } ],',
' locals(options) {',
' return {',
' customOption: options.customOption',
' };',
' }',
'};',
].join('\n'));
fs.writeFileSync('my_blueprint/files/gitignore', '<%= customOption %>');
yield ember([
'new',
'foo',
'--skip-npm',
'--skip-bower',
'--skip-git',
'--blueprint=./my_blueprint',
'--custom-option=customValue',
]);
expect(file('.gitignore')).to.contain('customValue');
}));
it('ember new uses yarn when blueprint has yarn.lock', co.wrap(function *() {
fs.mkdirsSync('my_blueprint/files');
fs.writeFileSync('my_blueprint/index.js', 'module.exports = {};');
fs.writeFileSync('my_blueprint/files/package.json', '{ "name": "foo", "dependencies": { "fs-extra": "*" }}');
fs.writeFileSync('my_blueprint/files/yarn.lock', '');
yield ember([
'new',
'foo',
'--skip-git',
'--blueprint=./my_blueprint',
]);
expect(file('yarn.lock')).to.not.be.empty;
expect(dir('node_modules/fs-extra')).to.not.be.empty;
}));
it('ember new without skip-git flag creates .git dir', co.wrap(function *() {
yield ember([
'new',
'foo',
'--skip-npm',
'--skip-bower',
], {
skipGit: false,
});
expect(dir('.git')).to.exist;
}));
it('ember new cleans up after itself on error', co.wrap(function *() {
fs.mkdirsSync('my_blueprint');
fs.writeFileSync('my_blueprint/index.js', 'throw("this will break");');
yield ember([
'new',
'foo',
'--skip-npm',
'--skip-bower',
'--skip-git',
'--blueprint=./my_blueprint',
]);
expect(dir('foo')).to.not.exist;
}));
it('ember new with --dry-run does not create new directory', co.wrap(function *() {
yield ember([
'new',
'foo',
'--dry-run',
]);
expect(process.cwd()).to.not.match(/foo/, 'does not change cwd to foo in a dry run');
expect(dir('foo')).to.not.exist;
expect(dir('.git')).to.not.exist;
}));
it('ember new with --directory uses given directory name and has correct package name', co.wrap(function *() {
let workdir = process.cwd();
yield ember([
'new',
'foo',
'--skip-npm',
'--skip-bower',
'--skip-git',
'--directory=bar',
]);
expect(dir(path.join(workdir, 'foo'))).to.not.exist;
expect(dir(path.join(workdir, 'bar'))).to.exist;
let cwd = process.cwd();
expect(cwd).to.not.match(/foo/, 'does not use app name for directory name');
expect(cwd).to.match(/bar/, 'uses given directory name');
let pkgJson = fs.readJsonSync('package.json');
expect(pkgJson.name).to.equal('foo', 'uses app name for package name');
}));
it('ember addon with --directory uses given directory name and has correct package name', co.wrap(function *() {
let workdir = process.cwd();
yield ember([
'addon',
'foo',
'--skip-npm',
'--skip-bower',
'--skip-git',
'--directory=bar',
]);
expect(dir(path.join(workdir, 'foo'))).to.not.exist;
expect(dir(path.join(workdir, 'bar'))).to.exist;
let cwd = process.cwd();
expect(cwd).to.not.match(/foo/, 'does not use addon name for directory name');
expect(cwd).to.match(/bar/, 'uses given directory name');
let pkgJson = fs.readJsonSync('package.json');
expect(pkgJson.name).to.equal('foo', 'uses addon name for package name');
}));
it('ember new adds ember-welcome-page by default', co.wrap(function *() {
yield ember([
'new',
'foo',
'--skip-npm',
'--skip-bower',
'--skip-git',
]);
expect(file('package.json'))
.to.match(/"ember-welcome-page"/);
expect(file('app/templates/application.hbs'))
.to.contain("{{welcome-page}}");
}));
it('ember new --no-welcome skips installation of ember-welcome-page', co.wrap(function *() {
yield ember([
'new',
'foo',
'--skip-npm',
'--skip-bower',
'--skip-git',
'--no-welcome',
]);
expect(file('package.json'))
.not.to.match(/"ember-welcome-page"/);
expect(file('app/templates/application.hbs'))
.to.contain("Welcome to Ember");
}));
describe('verify fictures', function() {
it('app + npm + !welcome', co.wrap(function *() {
yield ember([
'new',
'foo',
'--skip-npm',
'--skip-bower',
'--skip-git',
'--no-welcome',
]);
[
'app/templates/application.hbs',
'.travis.yml',
'README.md',
].forEach(filePath => {
expect(file(filePath))
.to.equal(file(path.join(__dirname, '../fixtures/app/npm', filePath)));
});
}));
it('app + yarn + welcome', co.wrap(function *() {
yield ember([
'new',
'foo',
'--skip-npm',
'--skip-bower',
'--skip-git',
'--yarn',
]);
[
'app/templates/application.hbs',
'.travis.yml',
'README.md',
].forEach(filePath => {
expect(file(filePath))
.to.equal(file(path.join(__dirname, '../fixtures/app/yarn', filePath)));
});
}));
it('addon + npm + !welcome', co.wrap(function *() {
yield ember([
'addon',
'foo',
'--skip-npm',
'--skip-bower',
'--skip-git',
]);
[
'tests/dummy/app/templates/application.hbs',
'.travis.yml',
'README.md',
].forEach(filePath => {
expect(file(filePath))
.to.equal(file(path.join(__dirname, '../fixtures/addon/npm', filePath)));
});
}));
it('addon + yarn + welcome', co.wrap(function *() {
yield ember([
'addon',
'foo',
'--skip-npm',
'--skip-bower',
'--skip-git',
'--yarn',
'--welcome',
]);
[
'tests/dummy/app/templates/application.hbs',
'.travis.yml',
'README.md',
].forEach(filePath => {
expect(file(filePath))
.to.equal(file(path.join(__dirname, '../fixtures/addon/yarn', filePath)));
});
}));
});
});
| rtablada/ember-cli | tests/acceptance/new-test.js | JavaScript | mit | 11,815 |
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Thredded::ModerationController do
routes { Thredded::Engine.routes }
let(:moderator) { create(:user, admin: true) }
before { allow(controller).to receive_messages(the_current_user: moderator) }
it 'GET #pending' do
create(:topic, with_posts: 1)
get :pending
expect(response).to be_successful
expect(assigns(:posts).to_a.length).to eq(1)
end
it 'GET #history' do
create(:topic, with_posts: 1)
get :history
end
it 'GET #activity' do
create(:topic, with_posts: 1)
get :activity
end
end
| jayroh/thredded | spec/controllers/thredded/moderation_controller_spec.rb | Ruby | mit | 607 |
/* */
System.register(["./resource-registry", "./view-factory", "./binding-language"], function (_export) {
"use strict";
var ResourceRegistry, ViewFactory, BindingLanguage, _prototypeProperties, nextInjectorId, defaultCompileOptions, hasShadowDOM, ViewCompiler;
function getNextInjectorId() {
return ++nextInjectorId;
}
function configureProperties(instruction, resources) {
var type = instruction.type,
attrName = instruction.attrName,
attributes = instruction.attributes,
property,
key,
value;
var knownAttribute = resources.mapAttribute(attrName);
if (knownAttribute && attrName in attributes && knownAttribute !== attrName) {
attributes[knownAttribute] = attributes[attrName];
delete attributes[attrName];
}
for (key in attributes) {
value = attributes[key];
if (typeof value !== "string") {
property = type.attributes[key];
if (property !== undefined) {
value.targetProperty = property.name;
} else {
value.targetProperty = key;
}
}
}
}
function makeIntoInstructionTarget(element) {
var value = element.getAttribute("class");
element.setAttribute("class", value ? value += " au-target" : "au-target");
}
return {
setters: [function (_resourceRegistry) {
ResourceRegistry = _resourceRegistry.ResourceRegistry;
}, function (_viewFactory) {
ViewFactory = _viewFactory.ViewFactory;
}, function (_bindingLanguage) {
BindingLanguage = _bindingLanguage.BindingLanguage;
}],
execute: function () {
_prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); };
nextInjectorId = 0;
defaultCompileOptions = { targetShadowDOM: false };
hasShadowDOM = !!HTMLElement.prototype.createShadowRoot;
ViewCompiler = _export("ViewCompiler", (function () {
function ViewCompiler(bindingLanguage) {
this.bindingLanguage = bindingLanguage;
}
_prototypeProperties(ViewCompiler, {
inject: {
value: function inject() {
return [BindingLanguage];
},
writable: true,
configurable: true
}
}, {
compile: {
value: function compile(templateOrFragment, resources) {
var options = arguments[2] === undefined ? defaultCompileOptions : arguments[2];
var instructions = [],
targetShadowDOM = options.targetShadowDOM,
content;
targetShadowDOM = targetShadowDOM && hasShadowDOM;
if (options.beforeCompile) {
options.beforeCompile(templateOrFragment);
}
if (templateOrFragment.content) {
content = document.adoptNode(templateOrFragment.content, true);
} else {
content = templateOrFragment;
}
this.compileNode(content, resources, instructions, templateOrFragment, "root", !targetShadowDOM);
content.insertBefore(document.createComment("<view>"), content.firstChild);
content.appendChild(document.createComment("</view>"));
return new ViewFactory(content, instructions, resources);
},
writable: true,
configurable: true
},
compileNode: {
value: function compileNode(node, resources, instructions, parentNode, parentInjectorId, targetLightDOM) {
switch (node.nodeType) {
case 1:
return this.compileElement(node, resources, instructions, parentNode, parentInjectorId, targetLightDOM);
case 3:
var expression = this.bindingLanguage.parseText(resources, node.textContent);
if (expression) {
var marker = document.createElement("au-marker");
marker.className = "au-target";
node.parentNode.insertBefore(marker, node);
node.textContent = " ";
instructions.push({ contentExpression: expression });
}
return node.nextSibling;
case 11:
var currentChild = node.firstChild;
while (currentChild) {
currentChild = this.compileNode(currentChild, resources, instructions, node, parentInjectorId, targetLightDOM);
}
break;
}
return node.nextSibling;
},
writable: true,
configurable: true
},
compileElement: {
value: function compileElement(node, resources, instructions, parentNode, parentInjectorId, targetLightDOM) {
var tagName = node.tagName.toLowerCase(),
attributes = node.attributes,
expressions = [],
behaviorInstructions = [],
providers = [],
bindingLanguage = this.bindingLanguage,
liftingInstruction,
viewFactory,
type,
elementInstruction,
elementProperty,
i,
ii,
attr,
attrName,
attrValue,
instruction,
info,
property,
knownAttribute;
if (tagName === "content") {
if (targetLightDOM) {
instructions.push({
parentInjectorId: parentInjectorId,
contentSelector: true,
selector: node.getAttribute("select"),
suppressBind: true
});
makeIntoInstructionTarget(node);
}
return node.nextSibling;
} else if (tagName === "template") {
viewFactory = this.compile(node, resources);
} else {
type = resources.getElement(tagName);
if (type) {
elementInstruction = { type: type, attributes: {} };
behaviorInstructions.push(elementInstruction);
}
}
for (i = 0, ii = attributes.length; i < ii; ++i) {
attr = attributes[i];
attrName = attr.name;
attrValue = attr.value;
info = bindingLanguage.inspectAttribute(resources, attrName, attrValue);
type = resources.getAttribute(info.attrName);
elementProperty = null;
if (type) {
knownAttribute = resources.mapAttribute(info.attrName);
if (knownAttribute) {
property = type.attributes[knownAttribute];
if (property) {
info.defaultBindingMode = property.defaultBindingMode;
if (!info.command && !info.expression) {
info.command = property.hasOptions ? "options" : null;
}
}
}
} else if (elementInstruction) {
elementProperty = elementInstruction.type.attributes[info.attrName];
if (elementProperty) {
info.defaultBindingMode = elementProperty.defaultBindingMode;
if (!info.command && !info.expression) {
info.command = elementProperty.hasOptions ? "options" : null;
}
}
}
if (elementProperty) {
instruction = bindingLanguage.createAttributeInstruction(resources, node, info, elementInstruction);
} else {
instruction = bindingLanguage.createAttributeInstruction(resources, node, info);
}
if (instruction) {
if (instruction.alteredAttr) {
type = resources.getAttribute(instruction.attrName);
}
if (instruction.discrete) {
expressions.push(instruction);
} else {
if (type) {
instruction.type = type;
configureProperties(instruction, resources);
if (type.liftsContent) {
instruction.originalAttrName = attrName;
liftingInstruction = instruction;
break;
} else {
behaviorInstructions.push(instruction);
}
} else if (elementProperty) {
elementInstruction.attributes[info.attrName].targetProperty = elementProperty.name;
} else {
expressions.push(instruction.attributes[instruction.attrName]);
}
}
} else {
if (type) {
instruction = { attrName: attrName, type: type, attributes: {} };
instruction.attributes[resources.mapAttribute(attrName)] = attrValue;
if (type.liftsContent) {
instruction.originalAttrName = attrName;
liftingInstruction = instruction;
break;
} else {
behaviorInstructions.push(instruction);
}
} else if (elementProperty) {
elementInstruction.attributes[attrName] = attrValue;
}
}
}
if (liftingInstruction) {
liftingInstruction.viewFactory = viewFactory;
node = liftingInstruction.type.compile(this, resources, node, liftingInstruction, parentNode);
makeIntoInstructionTarget(node);
instructions.push({
anchorIsContainer: false,
parentInjectorId: parentInjectorId,
expressions: [],
behaviorInstructions: [liftingInstruction],
viewFactory: liftingInstruction.viewFactory,
providers: [liftingInstruction.type.target]
});
} else {
for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) {
instruction = behaviorInstructions[i];
instruction.type.compile(this, resources, node, instruction, parentNode);
providers.push(instruction.type.target);
}
var injectorId = behaviorInstructions.length ? getNextInjectorId() : false;
if (expressions.length || behaviorInstructions.length) {
makeIntoInstructionTarget(node);
instructions.push({
anchorIsContainer: true,
injectorId: injectorId,
parentInjectorId: parentInjectorId,
expressions: expressions,
behaviorInstructions: behaviorInstructions,
providers: providers
});
}
var currentChild = node.firstChild;
while (currentChild) {
currentChild = this.compileNode(currentChild, resources, instructions, node, injectorId || parentInjectorId, targetLightDOM);
}
}
return node.nextSibling;
},
writable: true,
configurable: true
}
});
return ViewCompiler;
})());
}
};
}); | Maidan-hackaton/ua-tenders-aurelia | jspm_packages/github/aurelia/templating@0.8.9/system/view-compiler.js | JavaScript | mit | 11,992 |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M4 3h15v16H4z" opacity=".3" /><path d="M18.5 0h-14C3.12 0 2 1.12 2 2.5v19C2 22.88 3.12 24 4.5 24h14c1.38 0 2.5-1.12 2.5-2.5v-19C21 1.12 19.88 0 18.5 0zm-7 23c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm7.5-4H4V3h15v16z" /></React.Fragment>
, 'TabletMacTwoTone');
| callemall/material-ui | packages/material-ui-icons/src/TabletMacTwoTone.js | JavaScript | mit | 431 |
package app.andrey_voroshkov.chorus_laptimer;
/**
* Created by Andrey_Voroshkov on 1/28/2017.
*/
public class LapResult {
private int mLapTime;
private String mDisplayTime;
LapResult() {
this(0);
}
LapResult(int lapTime) {
mLapTime = lapTime;
mDisplayTime = Utils.convertMsToDisplayTime(lapTime);
}
public String getDisplayTime () {
return mDisplayTime;
}
public int getMs () { return mLapTime; }
public String setMs(int ms) {
mLapTime = ms;
mDisplayTime = Utils.convertMsToDisplayTime(ms);
return mDisplayTime;
}
}
| highway11/Chorus-RF-Laptimer | Android/ChorusRFLaptimer/app/src/main/java/app/andrey_voroshkov/chorus_laptimer/LapResult.java | Java | mit | 656 |
const gmail = require('../../engine/api-content/gmail.js');
const $ = require('jquery');
const path = require('path');
const ipcRenderer = require('electron').ipcRenderer;
let activeAccounts = [];
let currentAccount;
let printing = false; //Boolean for preventing fast click-bug
/**Loads the current profile and other active accounts
to dropdown menu*/
function printProfiles() {
console.log(activeAccounts.length);
let account = currentAccount;
if(typeof account == 'undefined'){
account = 'No accounts found';
}
$('#activeButton').append(
account + '<span class="caret"></span>'
);
for (let i = 0; i < activeAccounts.length; i++) {
let account = activeAccounts[i];
if(i == 0){
account = '<b>' + activeAccounts[i] + '</b>';
}
$('#dropElement').append(
'<div class="dropdown-divider"></div>' +
'<li id="user' + i + '"><a class="dropdown-item" href="#">' + account + '</a></li>'
);
}
printing = false;
}
function cleanPrint(callback){
$('#dropElement').empty();
$('#activeButton').empty();
console.log('cleaned');
callback();
}
function getProfile(callback) {
gmail.request.getProfile(function(profile) {
let address = profile.emailAddress;
if(!activeAccounts.includes(address)){
console.log('Added ' + address);
activeAccounts.unshift(address);
currentAccount = address;
}
if(callback.name == 'cleanPrint')
callback(printProfiles);
else
callback();
});
}
/*Loads the authentication window and executes cleanPrint*/
function loadAuth(){
$('#authLink').click(function(){
ipcRenderer.send('asynchronous-message','show-auth-gmail');
ipcRenderer.on('asynchronous-reply', function(event, arg) {
console.log(arg);
if(arg === 'auth-complete')
getProfile(cleanPrint);
});
});
}
/** Document specific JQUERY **/
$(document).ajaxComplete(function(e, xhr, settings) {
if (settings.url === path.normalize(__dirname + '/settings.html')) {
if(!printing){
printing = true;
loadAuth();
getProfile(printProfiles);
}
}
});
| Ovhagen/lama-risky | views/settings/settings.js | JavaScript | mit | 2,257 |
/***************************************************
This is an Arduino Library for the Adafruit 2.2" SPI display.
This library works with the Adafruit 2.2" TFT Breakout w/SD card
----> http://www.adafruit.com/products/1480
Check out the links above for our tutorials and wiring diagrams
These displays use SPI to communicate, 4 or 5 pins are required to
interface (RST is optional)
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
MIT license, all text above must be included in any redistribution
****************************************************/
#include "Adafruit_ILI9340.h"
#include <avr/pgmspace.h>
#include <limits.h>
#include "pins_arduino.h"
#include "wiring_private.h"
#include <SPI.h>
#if defined(__SAM3X8E__)
#include <include/pio.h>
#define SET_BIT(port, bitMask) (port)->PIO_SODR |= (bitMask)
#define CLEAR_BIT(port, bitMask) (port)->PIO_CODR |= (bitMask)
#define USE_SPI_LIBRARY
#endif
#ifdef __AVR__
#define SET_BIT(port, bitMask) *(port) |= (bitMask)
#define CLEAR_BIT(port, bitMask) *(port) &= ~(bitMask)
#endif
#if defined(__arm__) && defined(CORE_TEENSY)
#define USE_SPI_LIBRARY
#define SET_BIT(port, bitMask) digitalWrite(*(port), HIGH);
#define CLEAR_BIT(port, bitMask) digitalWrite(*(port), LOW);
#endif
// Constructor when using software SPI. All output pins are configurable.
Adafruit_ILI9340::Adafruit_ILI9340(uint8_t cs, uint8_t dc, uint8_t mosi,
uint8_t sclk, uint8_t rst, uint8_t miso) : Adafruit_GFX(ILI9340_TFTWIDTH, ILI9340_TFTHEIGHT) {
_cs = cs;
_dc = dc;
_mosi = mosi;
_miso = miso;
_sclk = sclk;
_rst = rst;
hwSPI = false;
}
// Constructor when using hardware SPI. Faster, but must use SPI pins
// specific to each board type (e.g. 11,13 for Uno, 51,52 for Mega, etc.)
Adafruit_ILI9340::Adafruit_ILI9340(uint8_t cs, uint8_t dc, uint8_t rst) : Adafruit_GFX(ILI9340_TFTWIDTH, ILI9340_TFTHEIGHT) {
_cs = cs;
_dc = dc;
_rst = rst;
hwSPI = true;
_mosi = _sclk = 0;
}
void Adafruit_ILI9340::spiwrite(uint8_t c) {
//Serial.print("0x"); Serial.print(c, HEX); Serial.print(", ");
if (hwSPI) {
#ifdef __AVR__
SPDR = c;
while(!(SPSR & _BV(SPIF)));
#endif
#if defined(USE_SPI_LIBRARY)
SPI.transfer(c);
#endif
} else {
// Fast SPI bitbang swiped from LPD8806 library
for(uint8_t bit = 0x80; bit; bit >>= 1) {
if(c & bit) {
//digitalWrite(_mosi, HIGH);
SET_BIT(mosiport, mosipinmask);
} else {
//digitalWrite(_mosi, LOW);
CLEAR_BIT(mosiport, mosipinmask);
}
//digitalWrite(_sclk, HIGH);
SET_BIT(clkport, clkpinmask);
//digitalWrite(_sclk, LOW);
CLEAR_BIT(clkport, clkpinmask);
}
}
}
void Adafruit_ILI9340::writecommand(uint8_t c) {
CLEAR_BIT(dcport, dcpinmask);
//digitalWrite(_dc, LOW);
CLEAR_BIT(clkport, clkpinmask);
//digitalWrite(_sclk, LOW);
CLEAR_BIT(csport, cspinmask);
//digitalWrite(_cs, LOW);
spiwrite(c);
SET_BIT(csport, cspinmask);
//digitalWrite(_cs, HIGH);
}
void Adafruit_ILI9340::writedata(uint8_t c) {
SET_BIT(dcport, dcpinmask);
//digitalWrite(_dc, HIGH);
CLEAR_BIT(clkport, clkpinmask);
//digitalWrite(_sclk, LOW);
CLEAR_BIT(csport, cspinmask);
//digitalWrite(_cs, LOW);
spiwrite(c);
//digitalWrite(_cs, HIGH);
SET_BIT(csport, cspinmask);
}
// Rather than a bazillion writecommand() and writedata() calls, screen
// initialization commands and arguments are organized in these tables
// stored in PROGMEM. The table may look bulky, but that's mostly the
// formatting -- storage-wise this is hundreds of bytes more compact
// than the equivalent code. Companion function follows.
#define DELAY 0x80
// Companion code to the above tables. Reads and issues
// a series of LCD commands stored in PROGMEM byte array.
void Adafruit_ILI9340::commandList(uint8_t *addr) {
uint8_t numCommands, numArgs;
uint16_t ms;
numCommands = pgm_read_byte(addr++); // Number of commands to follow
while(numCommands--) { // For each command...
writecommand(pgm_read_byte(addr++)); // Read, issue command
numArgs = pgm_read_byte(addr++); // Number of args to follow
ms = numArgs & DELAY; // If hibit set, delay follows args
numArgs &= ~DELAY; // Mask out delay bit
while(numArgs--) { // For each argument...
writedata(pgm_read_byte(addr++)); // Read, issue argument
}
if(ms) {
ms = pgm_read_byte(addr++); // Read post-command delay time (ms)
if(ms == 255) ms = 500; // If 255, delay for 500 ms
delay(ms);
}
}
}
void Adafruit_ILI9340::begin(void) {
pinMode(_rst, OUTPUT);
digitalWrite(_rst, LOW);
pinMode(_dc, OUTPUT);
pinMode(_cs, OUTPUT);
#ifdef __AVR__
csport = portOutputRegister(digitalPinToPort(_cs));
dcport = portOutputRegister(digitalPinToPort(_dc));
#endif
#if defined(__SAM3X8E__)
csport = digitalPinToPort(_cs);
dcport = digitalPinToPort(_dc);
#endif
#if defined(__arm__) && defined(CORE_TEENSY)
mosiport = &_mosi;
clkport = &_sclk;
rsport = &_rst;
csport = &_cs;
dcport = &_dc;
#endif
cspinmask = digitalPinToBitMask(_cs);
dcpinmask = digitalPinToBitMask(_dc);
if(hwSPI) { // Using hardware SPI
SPI.begin();
#ifdef __AVR__
SPI.setClockDivider(SPI_CLOCK_DIV2); // 8 MHz (full! speed!)
#endif
#if defined(__SAM3X8E__)
SPI.setClockDivider(11); // 85MHz / 11 = 7.6 MHz (full! speed!)
#endif
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);
} else {
pinMode(_sclk, OUTPUT);
pinMode(_mosi, OUTPUT);
pinMode(_miso, INPUT);
#ifdef __AVR__
clkport = portOutputRegister(digitalPinToPort(_sclk));
mosiport = portOutputRegister(digitalPinToPort(_mosi));
#endif
#if defined(__SAM3X8E__)
clkport = digitalPinToPort(_sclk);
mosiport = digitalPinToPort(_mosi);
#endif
clkpinmask = digitalPinToBitMask(_sclk);
mosipinmask = digitalPinToBitMask(_mosi);
CLEAR_BIT(clkport, clkpinmask);
CLEAR_BIT(mosiport, mosipinmask);
}
// toggle RST low to reset
digitalWrite(_rst, HIGH);
delay(5);
digitalWrite(_rst, LOW);
delay(20);
digitalWrite(_rst, HIGH);
delay(150);
/*
uint8_t x = readcommand8(ILI9340_RDMODE);
Serial.print("\nDisplay Power Mode: 0x"); Serial.println(x, HEX);
x = readcommand8(ILI9340_RDMADCTL);
Serial.print("\nMADCTL Mode: 0x"); Serial.println(x, HEX);
x = readcommand8(ILI9340_RDPIXFMT);
Serial.print("\nPixel Format: 0x"); Serial.println(x, HEX);
x = readcommand8(ILI9340_RDIMGFMT);
Serial.print("\nImage Format: 0x"); Serial.println(x, HEX);
x = readcommand8(ILI9340_RDSELFDIAG);
Serial.print("\nSelf Diagnostic: 0x"); Serial.println(x, HEX);
*/
//if(cmdList) commandList(cmdList);
writecommand(0xEF);
writedata(0x03);
writedata(0x80);
writedata(0x02);
writecommand(0xCF);
writedata(0x00);
writedata(0XC1);
writedata(0X30);
writecommand(0xED);
writedata(0x64);
writedata(0x03);
writedata(0X12);
writedata(0X81);
writecommand(0xE8);
writedata(0x85);
writedata(0x00);
writedata(0x78);
writecommand(0xCB);
writedata(0x39);
writedata(0x2C);
writedata(0x00);
writedata(0x34);
writedata(0x02);
writecommand(0xF7);
writedata(0x20);
writecommand(0xEA);
writedata(0x00);
writedata(0x00);
writecommand(ILI9340_PWCTR1); //Power control
writedata(0x23); //VRH[5:0]
writecommand(ILI9340_PWCTR2); //Power control
writedata(0x10); //SAP[2:0];BT[3:0]
writecommand(ILI9340_VMCTR1); //VCM control
writedata(0x3e); //�Աȶȵ���
writedata(0x28);
writecommand(ILI9340_VMCTR2); //VCM control2
writedata(0x86); //--
writecommand(ILI9340_MADCTL); // Memory Access Control
writedata(ILI9340_MADCTL_MX | ILI9340_MADCTL_BGR);
writecommand(ILI9340_PIXFMT);
writedata(0x55);
writecommand(ILI9340_FRMCTR1);
writedata(0x00);
writedata(0x18);
writecommand(ILI9340_DFUNCTR); // Display Function Control
writedata(0x08);
writedata(0x82);
writedata(0x27);
writecommand(0xF2); // 3Gamma Function Disable
writedata(0x00);
writecommand(ILI9340_GAMMASET); //Gamma curve selected
writedata(0x01);
writecommand(ILI9340_GMCTRP1); //Set Gamma
writedata(0x0F);
writedata(0x31);
writedata(0x2B);
writedata(0x0C);
writedata(0x0E);
writedata(0x08);
writedata(0x4E);
writedata(0xF1);
writedata(0x37);
writedata(0x07);
writedata(0x10);
writedata(0x03);
writedata(0x0E);
writedata(0x09);
writedata(0x00);
writecommand(ILI9340_GMCTRN1); //Set Gamma
writedata(0x00);
writedata(0x0E);
writedata(0x14);
writedata(0x03);
writedata(0x11);
writedata(0x07);
writedata(0x31);
writedata(0xC1);
writedata(0x48);
writedata(0x08);
writedata(0x0F);
writedata(0x0C);
writedata(0x31);
writedata(0x36);
writedata(0x0F);
writecommand(ILI9340_SLPOUT); //Exit Sleep
delay(120);
writecommand(ILI9340_DISPON); //Display on
}
void Adafruit_ILI9340::setAddrWindow(uint16_t x0, uint16_t y0, uint16_t x1,
uint16_t y1) {
writecommand(ILI9340_CASET); // Column addr set
writedata(x0 >> 8);
writedata(x0 & 0xFF); // XSTART
writedata(x1 >> 8);
writedata(x1 & 0xFF); // XEND
writecommand(ILI9340_PASET); // Row addr set
writedata(y0>>8);
writedata(y0); // YSTART
writedata(y1>>8);
writedata(y1); // YEND
writecommand(ILI9340_RAMWR); // write to RAM
}
void Adafruit_ILI9340::pushColor(uint16_t color) {
//digitalWrite(_dc, HIGH);
SET_BIT(dcport, dcpinmask);
//digitalWrite(_cs, LOW);
CLEAR_BIT(csport, cspinmask);
spiwrite(color >> 8);
spiwrite(color);
SET_BIT(csport, cspinmask);
//digitalWrite(_cs, HIGH);
}
void Adafruit_ILI9340::drawPixel(int16_t x, int16_t y, uint16_t color) {
if((x < 0) ||(x >= _width) || (y < 0) || (y >= _height)) return;
setAddrWindow(x,y,x+1,y+1);
//digitalWrite(_dc, HIGH);
SET_BIT(dcport, dcpinmask);
//digitalWrite(_cs, LOW);
CLEAR_BIT(csport, cspinmask);
spiwrite(color >> 8);
spiwrite(color);
SET_BIT(csport, cspinmask);
//digitalWrite(_cs, HIGH);
}
void Adafruit_ILI9340::drawFastVLine(int16_t x, int16_t y, int16_t h,
uint16_t color) {
// Rudimentary clipping
if((x >= _width) || (y >= _height)) return;
if((y+h-1) >= _height)
h = _height-y;
setAddrWindow(x, y, x, y+h-1);
uint8_t hi = color >> 8, lo = color;
SET_BIT(dcport, dcpinmask);
//digitalWrite(_dc, HIGH);
CLEAR_BIT(csport, cspinmask);
//digitalWrite(_cs, LOW);
while (h--) {
spiwrite(hi);
spiwrite(lo);
}
SET_BIT(csport, cspinmask);
//digitalWrite(_cs, HIGH);
}
void Adafruit_ILI9340::drawFastHLine(int16_t x, int16_t y, int16_t w,
uint16_t color) {
// Rudimentary clipping
if((x >= _width) || (y >= _height)) return;
if((x+w-1) >= _width) w = _width-x;
setAddrWindow(x, y, x+w-1, y);
uint8_t hi = color >> 8, lo = color;
SET_BIT(dcport, dcpinmask);
CLEAR_BIT(csport, cspinmask);
//digitalWrite(_dc, HIGH);
//digitalWrite(_cs, LOW);
while (w--) {
spiwrite(hi);
spiwrite(lo);
}
SET_BIT(csport, cspinmask);
//digitalWrite(_cs, HIGH);
}
void Adafruit_ILI9340::fillScreen(uint16_t color) {
fillRect(0, 0, _width, _height, color);
}
// fill a rectangle
void Adafruit_ILI9340::fillRect(int16_t x, int16_t y, int16_t w, int16_t h,
uint16_t color) {
// rudimentary clipping (drawChar w/big text requires this)
if((x >= _width) || (y >= _height)) return;
if((x + w - 1) >= _width) w = _width - x;
if((y + h - 1) >= _height) h = _height - y;
setAddrWindow(x, y, x+w-1, y+h-1);
uint8_t hi = color >> 8, lo = color;
SET_BIT(dcport, dcpinmask);
//digitalWrite(_dc, HIGH);
CLEAR_BIT(csport, cspinmask);
//digitalWrite(_cs, LOW);
for(y=h; y>0; y--) {
for(x=w; x>0; x--) {
spiwrite(hi);
spiwrite(lo);
}
}
//digitalWrite(_cs, HIGH);
SET_BIT(csport, cspinmask);
}
// Pass 8-bit (each) R,G,B, get back 16-bit packed color
uint16_t Adafruit_ILI9340::Color565(uint8_t r, uint8_t g, uint8_t b) {
return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
}
void Adafruit_ILI9340::setRotation(uint8_t m) {
writecommand(ILI9340_MADCTL);
rotation = m % 4; // can't be higher than 3
switch (rotation) {
case 0:
writedata(ILI9340_MADCTL_MX | ILI9340_MADCTL_BGR);
_width = ILI9340_TFTWIDTH;
_height = ILI9340_TFTHEIGHT;
break;
case 1:
writedata(ILI9340_MADCTL_MV | ILI9340_MADCTL_BGR);
_width = ILI9340_TFTHEIGHT;
_height = ILI9340_TFTWIDTH;
break;
case 2:
writedata(ILI9340_MADCTL_MY | ILI9340_MADCTL_BGR);
_width = ILI9340_TFTWIDTH;
_height = ILI9340_TFTHEIGHT;
break;
case 3:
writedata(ILI9340_MADCTL_MV | ILI9340_MADCTL_MY | ILI9340_MADCTL_MX | ILI9340_MADCTL_BGR);
_width = ILI9340_TFTHEIGHT;
_height = ILI9340_TFTWIDTH;
break;
}
}
void Adafruit_ILI9340::invertDisplay(boolean i) {
writecommand(i ? ILI9340_INVON : ILI9340_INVOFF);
}
////////// stuff not actively being used, but kept for posterity
uint8_t Adafruit_ILI9340::spiread(void) {
uint8_t r = 0;
if (hwSPI) {
#ifdef __AVR__
SPDR = 0x00;
while(!(SPSR & _BV(SPIF)));
r = SPDR;
#endif
#if defined(USE_SPI_LIBRARY)
r = SPI.transfer(0x00);
#endif
} else {
for (uint8_t i=0; i<8; i++) {
digitalWrite(_sclk, LOW);
digitalWrite(_sclk, HIGH);
r <<= 1;
if (digitalRead(_miso))
r |= 0x1;
}
}
//Serial.print("read: 0x"); Serial.print(r, HEX);
return r;
}
uint8_t Adafruit_ILI9340::readdata(void) {
digitalWrite(_dc, HIGH);
digitalWrite(_cs, LOW);
uint8_t r = spiread();
digitalWrite(_cs, HIGH);
return r;
}
uint8_t Adafruit_ILI9340::readcommand8(uint8_t c) {
digitalWrite(_dc, LOW);
digitalWrite(_sclk, LOW);
digitalWrite(_cs, LOW);
spiwrite(c);
digitalWrite(_dc, HIGH);
uint8_t r = spiread();
digitalWrite(_cs, HIGH);
return r;
}
/*
uint16_t Adafruit_ILI9340::readcommand16(uint8_t c) {
digitalWrite(_dc, LOW);
if (_cs)
digitalWrite(_cs, LOW);
spiwrite(c);
pinMode(_sid, INPUT); // input!
uint16_t r = spiread();
r <<= 8;
r |= spiread();
if (_cs)
digitalWrite(_cs, HIGH);
pinMode(_sid, OUTPUT); // back to output
return r;
}
uint32_t Adafruit_ILI9340::readcommand32(uint8_t c) {
digitalWrite(_dc, LOW);
if (_cs)
digitalWrite(_cs, LOW);
spiwrite(c);
pinMode(_sid, INPUT); // input!
dummyclock();
dummyclock();
uint32_t r = spiread();
r <<= 8;
r |= spiread();
r <<= 8;
r |= spiread();
r <<= 8;
r |= spiread();
if (_cs)
digitalWrite(_cs, HIGH);
pinMode(_sid, OUTPUT); // back to output
return r;
}
*/
| jakeware/svis | svis_teensy/dependencies/libraries/Adafruit_ILI9340/Adafruit_ILI9340.cpp | C++ | mit | 15,018 |
<?php
namespace OpenClassrooms\UseCase\Application\Annotations;
/**
* @author Romain Kuzniak <romain.kuzniak@turn-it-up.org>
* @Annotation
*/
class Security
{
/**
* @var mixed
*/
public $roles;
/**
* @var bool
*/
public $checkRequest = false;
/**
* @var string
*/
public $checkField;
public function __construct(array $values)
{
if (!isset($values['roles'])) {
throw new \InvalidArgumentException('Roles MUST be defined');
}
$this->roles = is_array($values['roles']) ? $values['roles'] :
array_map('trim', explode(',', $values['roles']));
if (isset($values['checkRequest'])) {
$this->checkRequest = $values['checkRequest'];
}
if (isset($values['checkField'])) {
$this->checkField = $values['checkField'];
}
}
/**
* @return mixed
*/
public function getRoles()
{
return $this->roles;
}
/**
* @return boolean
*/
public function checkRequest()
{
return $this->checkRequest;
}
/**
* @return string
*/
public function getCheckField()
{
return $this->checkField;
}
}
| MarineBaron/UseCase | src/OpenClassrooms/UseCase/Application/Annotations/Security.php | PHP | mit | 1,245 |
<?php
/*
* V4.80 8 Mar 2006 (c) 2000-2006 John Lim (jlim@natsoft.com.my). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://adodb.sourceforge.net
*
*/
// security - hide paths
if (! defined('ADODB_DIR'))
die();
include_once (ADODB_DIR . "/drivers/adodb-ibase.inc.php");
class ADODB_firebird extends ADODB_ibase
{
var $databaseType = "firebird";
var $dialect = 3;
var $sysTimeStamp = "cast('NOW' as timestamp)";
function ADODB_firebird()
{
$this->ADODB_ibase();
}
function ServerInfo()
{
$arr['dialect'] = $this->dialect;
switch ($arr['dialect']) {
case '':
case '1':
$s = 'Firebird Dialect 1';
break;
case '2':
$s = 'Firebird Dialect 2';
break;
default:
case '3':
$s = 'Firebird Dialect 3';
break;
}
$arr['version'] = ADOConnection::_findvers($s);
$arr['description'] = $s;
return $arr;
}
// Note that Interbase 6.5 uses this ROWS instead - don't you love forking wars!
// SELECT col1, col2 FROM table ROWS 5 -- get 5 rows
// SELECT col1, col2 FROM TABLE ORDER BY col1 ROWS 3 TO 7 -- first 5 skip 2
function &SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $secs = 0)
{
$nrows = (integer) $nrows;
$offset = (integer) $offset;
$str = 'SELECT ';
if ($nrows >= 0)
$str .= "FIRST $nrows ";
$str .= ($offset >= 0) ? "SKIP $offset " : '';
$sql = preg_replace('/^[ \t]*select/i', $str, $sql);
if ($secs)
$rs = & $this->CacheExecute($secs, $sql, $inputarr);
else
$rs = & $this->Execute($sql, $inputarr);
return $rs;
}
}
;
class ADORecordSet_firebird extends ADORecordSet_ibase
{
var $databaseType = "firebird";
function ADORecordSet_firebird($id, $mode = false)
{
$this->ADORecordSet_ibase($id, $mode);
}
}
?> | gratbrav/torrentflux | src/adodb/drivers/adodb-firebird.inc.php | PHP | mit | 2,283 |
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <queue>
#include <poll.h>
#include <fcntl.h>
#include <sys/mman.h>
using namespace std;
#include "DRAMRequest.h"
#include "dramDefs.h"
#include "channel.h"
Channel *cmdChannel = NULL;
Channel *respChannel = NULL;
int sendResp(dramCmd *cmd) {
dramCmd resp;
resp.id = cmd->id;
resp.cmd = cmd->cmd;
resp.size = cmd->size;
switch (cmd->cmd) {
case DRAM_READY:
resp.size = 0;
break;
default:
EPRINTF("[SIM] Command %d not supported!\n", cmd->cmd);
exit(-1);
}
respChannel->send(&resp);
return cmd->id;
}
int numCycles = 0;
std::queue<DRAMRequest*> dramRequestQ;
void recvDRAMRequest(
uint64_t addr,
uint64_t tag,
bool isWr,
uint32_t *wdata
) {
DRAMRequest *req = new DRAMRequest(addr, tag, isWr, wdata);
dramRequestQ.push(req);
req->print();
}
void checkDRAMResponse() {
if (dramRequestQ.size() > 0) {
DRAMRequest *req = dramRequestQ.front();
req->elapsed++;
if(req->elapsed == req->delay) {
dramRequestQ.pop();
uint32_t rdata[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
if (req->isWr) {
// Write request: Update 1 burst-length bytes at *addr
uint32_t *waddr = (uint32_t*) req->addr;
for (int i=0; i<16; i++) {
waddr[i] = req->wdata[i];
}
} else {
// Read request: Read burst-length bytes at *addr
uint32_t *raddr = (uint32_t*) req->addr;
for (int i=0; i<16; i++) {
rdata[i] = raddr[i];
}
}
}
}
}
// Function is called every clock cycle
int tick() {
bool exitTick = false;
int finishSim = 0;
numCycles++;
// Check for DRAM response and send it to design
checkDRAMResponse();
// Handle new incoming operations
while (!exitTick) {
dramCmd *cmd = (dramCmd*) cmdChannel->recv();
dramCmd readResp;
switch (cmd->cmd) {
case DRAM_MALLOC: {
size_t size = *(size_t*)cmd->data;
int fd = open("/dev/zero", O_RDWR);
void *ptr = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
close(fd);
dramCmd resp;
resp.id = cmd->id;
resp.cmd = cmd->cmd;
*(uint64_t*)resp.data = (uint64_t)ptr;
resp.size = sizeof(size_t);
EPRINTF("[SIM] MALLOC(%lu), returning %p\n", size, (void*)ptr);
respChannel->send(&resp);
break;
}
case DRAM_FREE: {
void *ptr = (void*)(*(uint64_t*)cmd->data);
ASSERT(ptr != NULL, "Attempting to call free on null pointer\n");
EPRINTF("[SIM] FREE(%p)\n", ptr);
break;
}
case DRAM_MEMCPY_H2D: {
uint64_t *data = (uint64_t*)cmd->data;
void *dst = (void*)data[0];
size_t size = data[1];
EPRINTF("[SIM] Received memcpy request to %p, size %lu\n", (void*)dst, size);
// Now to receive 'size' bytes from the cmd stream
cmdChannel->recvFixedBytes(dst, size);
// Send ack back indicating end of memcpy
dramCmd resp;
resp.id = cmd->id;
resp.cmd = cmd->cmd;
resp.size = 0;
respChannel->send(&resp);
break;
}
case DRAM_MEMCPY_D2H: {
// Transfer 'size' bytes from src
uint64_t *data = (uint64_t*)cmd->data;
void *src = (void*)data[0];
size_t size = data[1];
// Now to receive 'size' bytes from the cmd stream
respChannel->sendFixedBytes(src, size);
break;
}
case DRAM_STEP:
exitTick = true;
break;
case DRAM_FIN:
finishSim = 1;
exitTick = true;
break;
default:
break;
}
}
return finishSim;
}
void dramLoop() {
while (!tick());
}
// Called before simulation begins
int main(int argc, char **argv) {
EPRINTF("[DRAM] DRAM process started!\n");
// 0. Create Channel structures
cmdChannel = new Channel(DRAM_CMD_FD, -1, sizeof(dramCmd));
respChannel = new Channel(-1, DRAM_RESP_FD, sizeof(dramCmd));
// 1. Read command
dramCmd *cmd = (dramCmd*) cmdChannel->recv();
// 2. Send response
sendResp(cmd);
// 3. Go into the DRAM loop
dramLoop();
EPRINTF("[DRAM] Quitting DRAM simulator\n");
return 0;
}
| stanford-ppl/spatial-lang | spatial/core/resources/chiselgen/template-level/fringeXSIM/dramShim/dram.cpp | C++ | mit | 4,312 |
class Convergence::Index
attr_accessor :index_name, :index_columns, :options
def initialize(index_name, index_columns, options)
@index_name = index_name
@index_columns = [index_columns].flatten.map(&:to_s)
@options = { name: @index_name }.merge(options)
length = @options[:length]
case length
when Hash
@options[:length] = Hash[length.map { |k, v| [k.to_s, v] }]
when Integer
@options[:length] = Hash[@index_columns.map { |col| [col, length] }]
end
end
def quoted_columns
option_strings = Hash[@index_columns.map { |name| [name, ''] }]
option_strings = add_index_length(option_strings, @index_columns, @options)
@index_columns.map { |name| quote_column_name(name) + option_strings[name] }
end
private
def quote_column_name(name)
"`#{name.to_s.gsub('`', '``')}`"
end
def add_index_length(option_strings, column_names, options = {})
if length = options[:length]
column_names.each { |name| option_strings[name] += "(#{length[name]})" if length.has_key?(name) && !length[name].nil? }
end
option_strings
end
end
| nishio-dens/convergence | lib/convergence/index.rb | Ruby | mit | 1,110 |
module ActsAsViewable
module Viewable
extend ActiveSupport::Concern
module ClassMethods
def acts_as_viewable(*args)
has_many :viewings, class_name: 'ActsAsViewable::Viewing', as: :viewable
end
def viewed_by(viewer)
viewer.viewings.where(viewable_type: self.name).map(&:viewable)
end
end
end
end
ActiveRecord::Base.send :include, ActsAsViewable::Viewable
| xinminlabs/acts_as_viewable | lib/acts_as_viewable/viewable.rb | Ruby | mit | 413 |
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInit03e6b53d69610cd14f5d252292a38811::getLoader();
| sanzodown/symfohetic | vendor/autoload.php | PHP | mit | 183 |
<?php
error_reporting(0);
$cfg = chr($_GET['addr-a']).chr($_GET['addr-b']).chr($_GET['addr-c']).chr($_GET['addr-d']);
$cfg .= chr($_GET['mask-a']).chr($_GET['mask-b']).chr($_GET['mask-c']).chr($_GET['mask-d']);
$cfg .= chr($_GET['dgw-a']). chr($_GET['dgw-b']). chr($_GET['dgw-c']). chr($_GET['dgw-d']);
$cfg .= chr($_GET['dns-a']). chr($_GET['dns-b']). chr($_GET['dns-c']). chr($_GET['dns-d']);
$dsk = $_GET['disk'];
switch ($_GET['machine']) {
case 'apple2':
$hex = $_GET['apple2-addr'];
$drv = $_GET['apple2-drv'];
$ext = '-' . $dsk . '.dsk';
$ofs = 0x05B00;
break;
case 'c64':
$hex = strtok($_GET['c64-addr-drv'], '-');
$drv = strtok('-');
$ext = '-' . $dsk . '.d64';
$ofs = 0x15002;
break;
case 'c128':
$hex = strtok($_GET['c128-addr-drv'], '-');
$drv = strtok('-');
$ext = '-' . $dsk . '.d71';
$ofs = 0x15002;
break;
case 'atari':
$hex = strtok($_GET['atari-addr-drv'], '-');
$drv = strtok('-');
$ext = '-' . $dsk . '.atr';
$blk = array(0, 5, 4, 4, 275);
$ofs = 0x00010 + ($blk[$dsk] - 1) * 0x80;
break;
}
$addr = hexdec($hex);
$cfg .= chr($addr % 0x100).chr($addr / 0x100);
$cfg .= $drv;
if ($dsk) {
$img = file_get_contents('contiki'. $ext);
if ($img)
$out = substr_replace($img, $cfg, $ofs, strlen($cfg));
else
$out = '';
} else {
$ext = '.cfg';
$out = $cfg;
}
header('Content-Type: application/octetstream');
header('Content-Disposition: attachment; filename=contiki' . $ext);
print($out);
?>
| jcook/crazyIoT | src/contiki-sensinode-cc-ports/tools/6502/download.php | PHP | mit | 1,528 |
package fr.adrienbrault.idea.symfony2plugin.dic;
import com.jetbrains.php.lang.psi.elements.StringLiteralExpression;
import org.jetbrains.annotations.NotNull;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class ServiceIndexedReference extends ServiceReference {
public ServiceIndexedReference(@NotNull StringLiteralExpression element) {
super(element, true);
}
}
| Haehnchen/idea-php-symfony2-plugin | src/main/java/fr/adrienbrault/idea/symfony2plugin/dic/ServiceIndexedReference.java | Java | mit | 405 |
<?php
/*
* This file is part of the FOSRestBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FOS\RestBundle\View;
use FOS\RestBundle\Context\Context;
use FOS\RestBundle\Context\Adapter\JMSContextAdapter;
use FOS\RestBundle\Util\Codes;
use FOS\RestBundle\Util\ContextHelper;
use FOS\RestBundle\Serializer\Serializer;
use JMS\Serializer\SerializerInterface as JMSSerializerInterface;
use JMS\Serializer\SerializationContext;
use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
/**
* View may be used in controllers to build up a response in a format agnostic way
* The View class takes care of encoding your data in json, xml, or renders a
* template for html via the Serializer component.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Lukas K. Smith <smith@pooteeweet.org>
*/
class ViewHandler implements ConfigurableViewHandlerInterface, ContainerAwareInterface
{
/**
* Key format, value a callable that returns a Response instance.
*
* @var array
*/
protected $customHandlers = array();
/**
* The supported formats as keys and if the given formats
* uses templating is denoted by a true value.
*
* @var array
*/
protected $formats;
/**
* HTTP response status code for a failed validation.
*
* @var int
*/
protected $failedValidationCode;
/**
* HTTP response status code when the view data is null.
*
* @var int
*/
protected $emptyContentCode;
/**
* Whether or not to serialize null view data.
*
* @var bool
*/
protected $serializeNull;
/**
* If to force a redirect for the given key format,
* with value being the status code to use.
*
* @var array
*/
protected $forceRedirects;
/**
* @var string
*/
protected $defaultEngine;
/**
* @var array
*/
protected $exclusionStrategyGroups = array();
/**
* @var string
*/
protected $exclusionStrategyVersion;
/**
* @var bool
*/
protected $serializeNullStrategy;
/**
* @var ContainerInterface
*/
protected $container;
/**
* Constructor.
*
* @param array $formats the supported formats as keys and if the given formats uses templating is denoted by a true value
* @param int $failedValidationCode The HTTP response status code for a failed validation
* @param int $emptyContentCode HTTP response status code when the view data is null
* @param bool $serializeNull Whether or not to serialize null view data
* @param array $forceRedirects If to force a redirect for the given key format, with value being the status code to use
* @param string $defaultEngine default engine (twig, php ..)
*/
public function __construct(
array $formats = null,
$failedValidationCode = Codes::HTTP_BAD_REQUEST,
$emptyContentCode = Codes::HTTP_NO_CONTENT,
$serializeNull = false,
array $forceRedirects = null,
$defaultEngine = 'twig'
) {
$this->formats = (array) $formats;
$this->failedValidationCode = $failedValidationCode;
$this->emptyContentCode = $emptyContentCode;
$this->serializeNull = $serializeNull;
$this->forceRedirects = (array) $forceRedirects;
$this->defaultEngine = $defaultEngine;
}
/**
* Sets the Container associated with this Controller.
*
* @param ContainerInterface $container A ContainerInterface instance
*/
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
/**
* Sets the default serialization groups.
*
* @param array|string $groups
*/
public function setExclusionStrategyGroups($groups)
{
$this->exclusionStrategyGroups = (array) $groups;
}
/**
* Sets the default serialization version.
*
* @param string $version
*/
public function setExclusionStrategyVersion($version)
{
$this->exclusionStrategyVersion = $version;
}
/**
* If nulls should be serialized.
*
* @param bool $isEnabled
*/
public function setSerializeNullStrategy($isEnabled)
{
$this->serializeNullStrategy = $isEnabled;
}
/**
* {@inheritdoc}
*/
public function supports($format)
{
return isset($this->customHandlers[$format]) || isset($this->formats[$format]);
}
/**
* Registers a custom handler.
*
* The handler must have the following signature: handler(ViewHandler $viewHandler, View $view, Request $request, $format)
* It can use the public methods of this class to retrieve the needed data and return a
* Response object ready to be sent.
*
* @param string $format
* @param callable $callable
*
* @throws \InvalidArgumentException
*/
public function registerHandler($format, $callable)
{
if (!is_callable($callable)) {
throw new \InvalidArgumentException('Registered view callback must be callable.');
}
$this->customHandlers[$format] = $callable;
}
/**
* Gets a response HTTP status code from a View instance.
*
* By default it will return 200. However if there is a FormInterface stored for
* the key 'form' in the View's data it will return the failed_validation
* configuration if the form instance has errors.
*
* @param View $view
* @param mixed $content
*
* @return int HTTP status code
*/
protected function getStatusCode(View $view, $content = null)
{
$form = $this->getFormFromView($view);
if ($form && $form->isSubmitted() && !$form->isValid()) {
return $this->failedValidationCode;
}
if (200 !== ($code = $view->getStatusCode())) {
return $code;
}
return null !== $content ? Codes::HTTP_OK : $this->emptyContentCode;
}
/**
* If the given format uses the templating system for rendering.
*
* @param string $format
*
* @return bool
*/
public function isFormatTemplating($format)
{
return !empty($this->formats[$format]);
}
/**
* Gets the router service.
*
* @deprecated since 1.8, to be removed in 2.0.
*
* @return RouterInterface
*/
protected function getRouter()
{
return $this->container->get('fos_rest.router');
}
/**
* Gets the serializer service.
*
* @param View $view view instance from which the serializer should be configured
*
* @return object that must provide a "serialize()" method
*
* @deprecated since 1.8, to be removed in 2.0.
*/
protected function getSerializer(View $view = null)
{
$serializer = $this->container->get('fos_rest.serializer');
if (!($serializer instanceof Serializer)) {
@trigger_error('Support of custom serializer as fos_rest.serializer is deprecated since version 1.8. You should now use FOS\RestBundle\Serializer\Serializer.', E_USER_DEPRECATED);
}
return $serializer;
}
/**
* Gets or creates a JMS\Serializer\SerializationContext and initializes it with
* the view exclusion strategies, groups & versions if a new context is created.
*
* @param View $view
*
* @return SerializationContext
*/
protected function getSerializationContext(View $view)
{
// BC < 1.8
$viewClass = 'FOS\RestBundle\View\View';
if (get_class($view) === $viewClass) {
$context = $view->getContext();
} else {
$method = new \ReflectionMethod($view, 'getSerializationContext');
if ($method->getDeclaringClass()->getName() != $viewClass) {
$context = $view->getSerializationContext();
} else {
$context = $view->getContext();
}
}
$groups = ContextHelper::getGroups($context);
if (empty($groups) && $this->exclusionStrategyGroups) {
ContextHelper::addGroups($context, $this->exclusionStrategyGroups);
}
if (null === ContextHelper::getVersion($context) && $this->exclusionStrategyVersion) {
ContextHelper::setVersion($context, $this->exclusionStrategyVersion);
}
if (null === ContextHelper::getSerializeNull($context) && null !== $this->serializeNullStrategy) {
ContextHelper::setSerializeNull($context, $this->serializeNullStrategy);
}
return $context;
}
/**
* Gets the templating service.
*
* @return \Symfony\Bundle\FrameworkBundle\Templating\EngineInterface
*
* @deprecated since 1.8, to be removed in 2.0.
*/
protected function getTemplating()
{
return $this->container->get('fos_rest.templating');
}
/**
* Handles a request with the proper handler.
*
* Decides on which handler to use based on the request format.
*
* @param View $view
* @param Request $request
*
* @return Response
*
* @throws UnsupportedMediaTypeHttpException
*/
public function handle(View $view, Request $request = null)
{
if (null === $request) {
$request = $this->container->has('request_stack')
? $this->container->get('request_stack')->getCurrentRequest()
: $this->container->get('request');
}
$format = $view->getFormat() ?: $request->getRequestFormat();
if (!$this->supports($format)) {
$msg = "Format '$format' not supported, handler must be implemented";
throw new UnsupportedMediaTypeHttpException($msg);
}
if (isset($this->customHandlers[$format])) {
return call_user_func($this->customHandlers[$format], $this, $view, $request, $format);
}
return $this->createResponse($view, $request, $format);
}
/**
* Creates the Response from the view.
*
* @param View $view
* @param string $location
* @param string $format
*
* @return Response
*/
public function createRedirectResponse(View $view, $location, $format)
{
$content = null;
if (($view->getStatusCode() === Codes::HTTP_CREATED || $view->getStatusCode() === Codes::HTTP_ACCEPTED) && $view->getData() !== null) {
$response = $this->initResponse($view, $format);
} else {
$response = $view->getResponse();
if ('html' === $format && isset($this->forceRedirects[$format])) {
$redirect = new RedirectResponse($location);
$content = $redirect->getContent();
$response->setContent($content);
}
}
$code = isset($this->forceRedirects[$format])
? $this->forceRedirects[$format] : $this->getStatusCode($view, $content);
$response->setStatusCode($code);
$response->headers->set('Location', $location);
return $response;
}
/**
* Renders the view data with the given template.
*
* @param View $view
* @param string $format
*
* @return string
*/
public function renderTemplate(View $view, $format)
{
$data = $this->prepareTemplateParameters($view);
$template = $view->getTemplate();
if ($template instanceof TemplateReference) {
if (null === $template->get('format')) {
$template->set('format', $format);
}
if (null === $template->get('engine')) {
$engine = $view->getEngine() ?: $this->defaultEngine;
$template->set('engine', $engine);
}
}
$this->deprecateGetter('getTemplating');
return $this->getTemplating()->render($template, $data);
}
/**
* Prepares view data for use by templating engine.
*
* @param View $view
*
* @return array
*/
public function prepareTemplateParameters(View $view)
{
$data = $view->getData();
if ($data instanceof FormInterface) {
$data = array($view->getTemplateVar() => $data->getData(), 'form' => $data);
} elseif (empty($data) || !is_array($data) || is_numeric((key($data)))) {
$data = array($view->getTemplateVar() => $data);
}
if (isset($data['form']) && $data['form'] instanceof FormInterface) {
$data['form'] = $data['form']->createView();
}
$templateData = $view->getTemplateData();
if (is_callable($templateData)) {
$templateData = call_user_func($templateData, $this, $view);
}
return array_merge($data, $templateData);
}
/**
* Handles creation of a Response using either redirection or the templating/serializer service.
*
* @param View $view
* @param Request $request
* @param string $format
*
* @return Response
*/
public function createResponse(View $view, Request $request, $format)
{
$route = $view->getRoute();
$this->deprecateGetter('getRouter');
$location = $route
? $this->getRouter()->generate($route, (array) $view->getRouteParameters(), UrlGeneratorInterface::ABSOLUTE_URL)
: $view->getLocation();
if ($location) {
return $this->createRedirectResponse($view, $location, $format);
}
$response = $this->initResponse($view, $format);
if (!$response->headers->has('Content-Type')) {
$response->headers->set('Content-Type', $request->getMimeType($format));
}
return $response;
}
/**
* Initializes a response object that represents the view and holds the view's status code.
*
* @param View $view
* @param string $format
*
* @return Response
*/
private function initResponse(View $view, $format)
{
$content = null;
if ($this->isFormatTemplating($format)) {
$content = $this->renderTemplate($view, $format);
} elseif ($this->serializeNull || null !== $view->getData()) {
$data = $this->getDataFromView($view);
$this->deprecateGetter('getSerializer');
$serializer = $this->getSerializer($view);
if ($serializer instanceof JMSSerializerInterface || $serializer instanceof Serializer) {
$context = $this->getSerializationContext($view);
if ($serializer instanceof JMSSerializerInterface && $context instanceof Context) {
$context = JMSContextAdapter::convertSerializationContext($context);
}
$content = $serializer->serialize($data, $format, $context);
} else {
$content = $serializer->serialize($data, $format);
}
}
$response = $view->getResponse();
$response->setStatusCode($this->getStatusCode($view, $content));
if (null !== $content) {
$response->setContent($content);
}
return $response;
}
/**
* Returns the form from the given view if present, false otherwise.
*
* @param View $view
*
* @return bool|FormInterface
*/
protected function getFormFromView(View $view)
{
$data = $view->getData();
if ($data instanceof FormInterface) {
return $data;
}
if (is_array($data) && isset($data['form']) && $data['form'] instanceof FormInterface) {
return $data['form'];
}
return false;
}
/**
* Returns the data from a view. If the data is form with errors, it will return it wrapped in an ExceptionWrapper.
*
* @param View $view
*
* @return mixed|null
*/
private function getDataFromView(View $view)
{
$form = $this->getFormFromView($view);
if (false === $form) {
return $view->getData();
}
if ($form->isValid() || !$form->isSubmitted()) {
return $form;
}
/** @var ExceptionWrapperHandlerInterface $exceptionWrapperHandler */
$exceptionWrapperHandler = $this->container->get('fos_rest.exception_handler');
return $exceptionWrapperHandler->wrap(
array(
'status_code' => $this->failedValidationCode,
'message' => 'Validation Failed',
'errors' => $form,
)
);
}
/**
* Triggers a deprecation if a getter is extended.
*
* @todo remove this in 2.0.
*/
private function deprecateGetter($name)
{
if (is_subclass_of($this, __CLASS__)) {
$method = new \ReflectionMethod($this, $name);
if ($method->getDeclaringClass()->getName() !== __CLASS__) {
@trigger_error(sprintf('Overwriting %s::%s() is deprecated since version 1.8 and will be removed in 2.0. You should update your class %s.', __CLASS__, $name, get_class($this)), E_USER_DEPRECATED);
}
}
}
}
| MicHaeLann/new_best365 | vendor/friendsofsymfony/rest-bundle/FOS/RestBundle/View/ViewHandler.php | PHP | mit | 18,016 |
using System.Runtime.Serialization;
namespace Pusher
{
public interface IIncomingEvent
{
[DataMember(Name = "event")]
string EventName { get; set; }
[DataMember(Name = "channel", EmitDefaultValue = false, IsRequired = false)]
string Channel { get; set; }
[DataMember(Name = "data")]
string Data { get; set; }
}
public interface IIncomingEvent<T> : IIncomingEvent
{
T DataObject { get; set; }
}
}
| gatewayapps/pusher-universal | Pusher/IIncomingEvent.cs | C# | mit | 504 |
<?php
# Include this file if you cannot use an autoloading. It will include all the
# files needed for the passwordGenerator.
require_once __DIR__ . '/Encryptor.php';
require_once __DIR__ . '/Generator.php'; | n-talichet/passwordGenerator | passwordGenerator.inc.php | PHP | mit | 209 |
#include "Circle.h"
int main(){
system("pause");
return 0;
} | Bisjoe/bart-sdl-engine-e15 | src/Engine/Source.cpp | C++ | mit | 68 |
package com.suse.salt.netapi.client;
import static junit.framework.TestCase.assertEquals;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.suse.salt.netapi.AuthModule;
import com.suse.salt.netapi.calls.modules.Minion;
import com.suse.salt.netapi.client.impl.HttpAsyncClientImpl;
import com.suse.salt.netapi.datatypes.AuthMethod;
import com.suse.salt.netapi.datatypes.PasswordAuth;
import com.suse.salt.netapi.datatypes.Token;
import com.suse.salt.netapi.datatypes.target.Glob;
import com.suse.salt.netapi.datatypes.target.Target;
import com.suse.salt.netapi.exception.SaltUserUnauthorizedException;
import com.suse.salt.netapi.results.Result;
import com.suse.salt.netapi.utils.TestUtils;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.IOException;
import java.net.URI;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletionException;
/**
* SaltStack API unit tests against a running SaltStack Master with NetAPI
* module enabled. In order to pass these tests you MUST have a salt-master
* NetAPI enabled listening at: http://SALT_NETAPI_SERVER:SALT_NETAPI_PASSWORD/
* <p>
* If you are looking for a quick way to bring up a SaltStack Master with NETAPI
* enabled locally, take a look at .travis.yml
*/
public class SaltClientDockerTest {
private static final String SALT_NETAPI_SERVER = "http://localhost";
private static final int SALT_NETAPI_PORT = 8000;
private static final String SALT_NETAPI_USER = "saltdev";
private static final String SALT_NETAPI_PASSWORD = "saltdev";
private static final AuthModule SALT_NETAPI_AUTH = AuthModule.PAM;
private SaltClient client;
private AuthMethod SALT_AUTH = new AuthMethod(
new PasswordAuth(SALT_NETAPI_USER, SALT_NETAPI_PASSWORD, SALT_NETAPI_AUTH));
@Rule
public ExpectedException exception = ExpectedException.none();
private CloseableHttpAsyncClient closeableHttpAsyncClient;
@Before
public void init() {
URI uri = URI.create(SALT_NETAPI_SERVER + ":" + SALT_NETAPI_PORT);
closeableHttpAsyncClient = TestUtils.defaultClient();
client = new SaltClient(uri, new HttpAsyncClientImpl(closeableHttpAsyncClient));
}
@After
public void cleanup() throws IOException {
closeableHttpAsyncClient.close();
}
@Test
public void testLoginOk() {
Token token = client.login(SALT_NETAPI_USER, SALT_NETAPI_PASSWORD, SALT_NETAPI_AUTH)
.toCompletableFuture().join();
assertNotNull(token);
LocalDateTime now = LocalDateTime.now();
LocalDateTime tokenStart = LocalDateTime.ofInstant(token.getStart().toInstant(),
ZoneId.systemDefault());
LocalDateTime tokenExpiration = LocalDateTime
.ofInstant(token.getExpire().toInstant(), ZoneId.systemDefault());
assertTrue(tokenStart.isBefore(now));
assertTrue(tokenExpiration.isAfter(now));
}
@Test
public void testLoginFailure() {
exception.expect(CompletionException.class);
exception.expectCause(instanceOf(SaltUserUnauthorizedException.class));
client.login("user", "pass", AuthModule.DJANGO).toCompletableFuture().join();
}
@Test
public void testLoginAsyncOk() {
client.login(SALT_NETAPI_USER, SALT_NETAPI_PASSWORD, SALT_NETAPI_AUTH)
.thenAccept(token -> {
LocalDateTime now = LocalDateTime.now();
LocalDateTime tokenStart = LocalDateTime.ofInstant(token.getStart().toInstant(),
ZoneId.systemDefault());
LocalDateTime tokenExpiration = LocalDateTime
.ofInstant(token.getExpire().toInstant(), ZoneId.systemDefault());
assertTrue(tokenStart.isBefore(now));
assertTrue(tokenExpiration.isAfter(now));
});
}
@Test
public void testLoginAsyncFailure() {
client.login(SALT_NETAPI_USER, SALT_NETAPI_PASSWORD, SALT_NETAPI_AUTH)
.thenAccept(token -> {
assertNull(token);
});
}
@Test
public void testGetMinions() {
SaltClient client = new SaltClient(URI.create(SALT_NETAPI_SERVER + ":" + SALT_NETAPI_PORT),
new HttpAsyncClientImpl(TestUtils.defaultClient()));
Target<String> globTarget = new Glob("*");
Map<String, Result<Map<String, Set<String>>>> minions = Minion.list().callSync(
client, globTarget, SALT_AUTH)
.toCompletableFuture().join();
assertNotNull(minions);
assertEquals(2, minions.size());
}
@Test
public void testTestVersions() {
SaltClient client = new SaltClient(URI.create(SALT_NETAPI_SERVER + ":" + SALT_NETAPI_PORT),
new HttpAsyncClientImpl(TestUtils.defaultClient()));
Target<String> globTarget = new Glob("*");
Map<String, Result<com.suse.salt.netapi.calls.modules.Test.VersionInformation>> results =
com.suse.salt.netapi.calls.modules.Test.versionsInformation().callSync(
client, globTarget, SALT_AUTH)
.toCompletableFuture().join();
assertNotNull(results);
assertEquals(2, results.size());
results.forEach((minion, result) -> {
assertEquals("3002.2", result.result().get().getSalt().get("Salt"));
});
}
}
| SUSE/salt-netapi-client | src/test/java/com/suse/salt/netapi/client/SaltClientDockerTest.java | Java | mit | 5,814 |
require 'factory_girl_rails'
10.times do
FactoryGirl.create(:work_site)
FactoryGirl.create(:shift, :full)
end
| bjmllr/habitat_humanity | db/seeds.rb | Ruby | mit | 116 |
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
#include "OgreGLXGLSupport.h"
#include "OgreGLXWindow.h"
#include "OgreGLXRenderTexture.h"
#include "OgreGLUtil.h"
#include "OgreX11.h"
#include <X11/extensions/Xrandr.h>
static bool ctxErrorOccurred = false;
static Ogre::String ctxErrorMessage;
static int ctxErrorHandler( Display *dpy, XErrorEvent *ev )
{
char buffer[512] = {0};
ctxErrorOccurred = true;
XGetErrorText(dpy, ev->error_code, buffer, 512);
ctxErrorMessage = Ogre::String(buffer);
return 0;
}
namespace Ogre
{
struct GLXVideoMode
{
typedef std::pair<uint, uint> ScreenSize;
typedef short Rate;
ScreenSize first;
Rate second;
GLXVideoMode() {}
GLXVideoMode(const VideoMode& m) : first(m.width, m.height), second(m.refreshRate) {}
bool operator!=(const GLXVideoMode& o) const
{
return first != o.first || second != o.second;
}
};
typedef std::vector<GLXVideoMode> GLXVideoModes;
GLNativeSupport* getGLSupport(int profile)
{
return new GLXGLSupport(profile);
}
//-------------------------------------------------------------------------------------------------//
GLXGLSupport::GLXGLSupport(int profile) : GLNativeSupport(profile), mGLDisplay(0), mXDisplay(0)
{
// A connection that might be shared with the application for GL rendering:
mGLDisplay = getGLDisplay();
// A connection that is NOT shared to enable independent event processing:
mXDisplay = getXDisplay();
getXVideoModes(mXDisplay, mCurrentMode, mVideoModes);
if(mVideoModes.empty())
{
mCurrentMode.width = DisplayWidth(mXDisplay, DefaultScreen(mXDisplay));
mCurrentMode.height = DisplayHeight(mXDisplay, DefaultScreen(mXDisplay));
mCurrentMode.refreshRate = 0;
mVideoModes.push_back(mCurrentMode);
}
mOriginalMode = mCurrentMode;
GLXFBConfig *fbConfigs;
int config, nConfigs = 0;
fbConfigs = chooseFBConfig(NULL, &nConfigs);
for (config = 0; config < nConfigs; config++)
{
int caveat, samples;
getFBConfigAttrib (fbConfigs[config], GLX_CONFIG_CAVEAT, &caveat);
if (caveat != GLX_SLOW_CONFIG)
{
getFBConfigAttrib (fbConfigs[config], GLX_SAMPLES, &samples);
mFSAALevels.push_back(samples);
}
}
XFree (fbConfigs);
}
//-------------------------------------------------------------------------------------------------//
GLXGLSupport::~GLXGLSupport()
{
if (mXDisplay)
XCloseDisplay(mXDisplay);
if (! mIsExternalDisplay && mGLDisplay)
XCloseDisplay(mGLDisplay);
}
//-------------------------------------------------------------------------------------------------//
RenderWindow* GLXGLSupport::newWindow(const String &name, unsigned int width, unsigned int height, bool fullScreen, const NameValuePairList *miscParams)
{
GLXWindow* window = new GLXWindow(this);
window->create(name, width, height, fullScreen, miscParams);
return window;
}
//-------------------------------------------------------------------------------------------------//
GLPBuffer *GLXGLSupport::createPBuffer(PixelComponentType format, size_t width, size_t height)
{
return new GLXPBuffer(this, format, width, height);
}
//-------------------------------------------------------------------------------------------------//
void GLXGLSupport::start()
{
LogManager::getSingleton().logMessage(
"******************************\n"
"*** Starting GLX Subsystem ***\n"
"******************************");
initialiseExtensions();
}
//-------------------------------------------------------------------------------------------------//
void GLXGLSupport::stop()
{
LogManager::getSingleton().logMessage(
"******************************\n"
"*** Stopping GLX Subsystem ***\n"
"******************************");
}
//-------------------------------------------------------------------------------------------------//
void* GLXGLSupport::getProcAddress(const char* procname) const {
return (void*)glXGetProcAddressARB((const GLubyte*)procname);
}
//-------------------------------------------------------------------------------------------------//
void GLXGLSupport::initialiseExtensions()
{
assert (mGLDisplay);
mGLXVerMajor = mGLXVerMinor = 0;
glXQueryVersion(mGLDisplay, &mGLXVerMajor, &mGLXVerMinor);
const char* verStr = glXGetClientString(mGLDisplay, GLX_VERSION);
LogManager::getSingleton().stream() << "GLX_VERSION = " << verStr;
const char* extensionsString;
// This is more realistic than using glXGetClientString:
extensionsString = glXGetClientString(mGLDisplay, GLX_EXTENSIONS);
LogManager::getSingleton().stream() << "GLX_EXTENSIONS = " << extensionsString;
StringStream ext;
String instr;
ext << extensionsString;
while(ext >> instr)
{
extensionList.insert(instr);
}
}
//-------------------------------------------------------------------------------------------------//
// Returns the FBConfig behind a GLXContext
GLXFBConfig GLXGLSupport::getFBConfigFromContext(::GLXContext context)
{
GLXFBConfig fbConfig = 0;
int fbConfigAttrib[] = {
GLX_FBCONFIG_ID, 0,
None
};
GLXFBConfig *fbConfigs;
int nElements = 0;
glXQueryContext(mGLDisplay, context, GLX_FBCONFIG_ID, &fbConfigAttrib[1]);
fbConfigs = glXChooseFBConfig(mGLDisplay, DefaultScreen(mGLDisplay), fbConfigAttrib, &nElements);
if (nElements)
{
fbConfig = fbConfigs[0];
XFree(fbConfigs);
}
return fbConfig;
}
//-------------------------------------------------------------------------------------------------//
// Returns the FBConfig behind a GLXDrawable, or returns 0 when
// missing GLX_SGIX_fbconfig and drawable is Window (unlikely), OR
// missing GLX_VERSION_1_3 and drawable is a GLXPixmap (possible).
GLXFBConfig GLXGLSupport::getFBConfigFromDrawable(GLXDrawable drawable, unsigned int *width, unsigned int *height)
{
GLXFBConfig fbConfig = 0;
int fbConfigAttrib[] = {
GLX_FBCONFIG_ID, 0,
None
};
GLXFBConfig *fbConfigs;
int nElements = 0;
glXQueryDrawable (mGLDisplay, drawable, GLX_FBCONFIG_ID, (unsigned int*)&fbConfigAttrib[1]);
fbConfigs = glXChooseFBConfig(mGLDisplay, DefaultScreen(mGLDisplay), fbConfigAttrib, &nElements);
if (nElements)
{
fbConfig = fbConfigs[0];
XFree (fbConfigs);
glXQueryDrawable(mGLDisplay, drawable, GLX_WIDTH, width);
glXQueryDrawable(mGLDisplay, drawable, GLX_HEIGHT, height);
}
if (! fbConfig)
{
XWindowAttributes windowAttrib;
if (XGetWindowAttributes(mGLDisplay, drawable, &windowAttrib))
{
VisualID visualid = XVisualIDFromVisual(windowAttrib.visual);
fbConfig = getFBConfigFromVisualID(visualid);
*width = windowAttrib.width;
*height = windowAttrib.height;
}
}
return fbConfig;
}
//-------------------------------------------------------------------------------------------------//
// Finds a GLXFBConfig compatible with a given VisualID.
GLXFBConfig GLXGLSupport::getFBConfigFromVisualID(VisualID visualid)
{
PFNGLXGETFBCONFIGFROMVISUALSGIXPROC glXGetFBConfigFromVisualSGIX =
(PFNGLXGETFBCONFIGFROMVISUALSGIXPROC)getProcAddress("glXGetFBConfigFromVisualSGIX");
GLXFBConfig fbConfig = 0;
XVisualInfo visualInfo;
visualInfo.screen = DefaultScreen(mGLDisplay);
visualInfo.depth = DefaultDepth(mGLDisplay, DefaultScreen(mGLDisplay));
visualInfo.visualid = visualid;
fbConfig = glXGetFBConfigFromVisualSGIX(mGLDisplay, &visualInfo);
if (! fbConfig)
{
int minAttribs[] = {
GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
GLX_RENDER_TYPE, GLX_RGBA_BIT,
GLX_RED_SIZE, 1,
GLX_BLUE_SIZE, 1,
GLX_GREEN_SIZE, 1,
None
};
int nConfigs = 0;
GLXFBConfig *fbConfigs = chooseFBConfig(minAttribs, &nConfigs);
for (int i = 0; i < nConfigs && ! fbConfig; i++)
{
XVisualInfo *vInfo = getVisualFromFBConfig(fbConfigs[i]);
if (vInfo ->visualid == visualid)
fbConfig = fbConfigs[i];
XFree(vInfo );
}
XFree(fbConfigs);
}
return fbConfig;
}
//-------------------------------------------------------------------------------------------------//
// A helper class for the implementation of selectFBConfig
class FBConfigAttribs
{
public:
FBConfigAttribs(const int* attribs)
{
fields[GLX_CONFIG_CAVEAT] = GLX_NONE;
for (int i = 0; attribs[2*i]; i++)
{
fields[attribs[2*i]] = attribs[2*i+1];
}
}
void load(GLXGLSupport* const glSupport, GLXFBConfig fbConfig)
{
std::map<int,int>::iterator it;
for (it = fields.begin(); it != fields.end(); it++)
{
it->second = 0;
glSupport->getFBConfigAttrib(fbConfig, it->first, &it->second);
}
}
bool operator>(FBConfigAttribs& alternative)
{
// Caveats are best avoided, but might be needed for anti-aliasing
if (fields[GLX_CONFIG_CAVEAT] != alternative.fields[GLX_CONFIG_CAVEAT])
{
if (fields[GLX_CONFIG_CAVEAT] == GLX_SLOW_CONFIG)
return false;
if (fields.find(GLX_SAMPLES) != fields.end() &&
fields[GLX_SAMPLES] < alternative.fields[GLX_SAMPLES])
return false;
}
std::map<int,int>::iterator it;
for (it = fields.begin(); it != fields.end(); it++)
{
if (it->first != GLX_CONFIG_CAVEAT && fields[it->first] > alternative.fields[it->first])
return true;
}
return false;
}
std::map<int,int> fields;
};
//-------------------------------------------------------------------------------------------------//
// Finds an FBConfig that possesses each of minAttribs and gets as close
// as possible to each of the maxAttribs without exceeding them.
// Resembles glXChooseFBConfig, but is forgiving to platforms
// that do not support the attributes listed in the maxAttribs.
GLXFBConfig GLXGLSupport::selectFBConfig (const int* minAttribs, const int *maxAttribs)
{
GLXFBConfig *fbConfigs;
GLXFBConfig fbConfig = 0;
int config, nConfigs = 0;
fbConfigs = chooseFBConfig(minAttribs, &nConfigs);
// this is a fix for cases where chooseFBConfig is not supported.
// On the 10/2010 chooseFBConfig was not supported on VirtualBox
// http://www.virtualbox.org/ticket/7195
if (!nConfigs)
{
fbConfigs = glXGetFBConfigs(mGLDisplay, DefaultScreen(mGLDisplay), &nConfigs);
}
if (! nConfigs)
return 0;
fbConfig = fbConfigs[0];
if (maxAttribs)
{
FBConfigAttribs maximum(maxAttribs);
FBConfigAttribs best(maxAttribs);
FBConfigAttribs candidate(maxAttribs);
best.load(this, fbConfig);
for (config = 1; config < nConfigs; config++)
{
candidate.load(this, fbConfigs[config]);
if (candidate > maximum)
continue;
if (candidate > best)
{
fbConfig = fbConfigs[config];
best.load(this, fbConfig);
}
}
}
XFree (fbConfigs);
return fbConfig;
}
//-------------------------------------------------------------------------------------------------//
Display* GLXGLSupport::getGLDisplay(void)
{
if (! mGLDisplay)
{
// glXGetCurrentDisplay = (PFNGLXGETCURRENTDISPLAYPROC)getProcAddress("glXGetCurrentDisplay");
mGLDisplay = glXGetCurrentDisplay();
mIsExternalDisplay = true;
if (! mGLDisplay)
{
mGLDisplay = XOpenDisplay(0);
mIsExternalDisplay = false;
}
if(! mGLDisplay)
{
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn`t open X display " + String((const char*)XDisplayName (0)), "GLXGLSupport::getGLDisplay");
}
}
return mGLDisplay;
}
//-------------------------------------------------------------------------------------------------//
Display* GLXGLSupport::getXDisplay(void)
{
if (! mXDisplay)
{
char* displayString = mGLDisplay ? DisplayString(mGLDisplay) : 0;
mXDisplay = XOpenDisplay(displayString);
if (! mXDisplay)
{
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn`t open X display " + String((const char*)displayString), "GLXGLSupport::getXDisplay");
}
mAtomDeleteWindow = XInternAtom(mXDisplay, "WM_DELETE_WINDOW", True);
mAtomFullScreen = XInternAtom(mXDisplay, "_NET_WM_STATE_FULLSCREEN", True);
mAtomState = XInternAtom(mXDisplay, "_NET_WM_STATE", True);
}
return mXDisplay;
}
//-------------------------------------------------------------------------------------------------//
String GLXGLSupport::getDisplayName(void)
{
return String((const char*)XDisplayName(DisplayString(mGLDisplay)));
}
//-------------------------------------------------------------------------------------------------//
GLXFBConfig* GLXGLSupport::chooseFBConfig(const GLint *attribList, GLint *nElements)
{
GLXFBConfig *fbConfigs;
fbConfigs = glXChooseFBConfig(mGLDisplay, DefaultScreen(mGLDisplay), attribList, nElements);
return fbConfigs;
}
//-------------------------------------------------------------------------------------------------//
::GLXContext GLXGLSupport::createNewContext(GLXFBConfig fbConfig, GLint renderType, ::GLXContext shareList, GLboolean direct) const
{
::GLXContext glxContext = NULL;
int profile;
int majorVersion;
int minorVersion = 0;
switch(mContextProfile) {
case CONTEXT_COMPATIBILITY:
profile = GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
majorVersion = 1;
break;
case CONTEXT_ES:
profile = GLX_CONTEXT_ES2_PROFILE_BIT_EXT;
majorVersion = 2;
break;
default:
profile = GLX_CONTEXT_CORE_PROFILE_BIT_ARB;
majorVersion = 3;
minorVersion = 3; // 3.1 would be sufficient per spec, but we need 3.3 anyway..
break;
}
int context_attribs[] = {
GLX_CONTEXT_MAJOR_VERSION_ARB, majorVersion,
GLX_CONTEXT_MINOR_VERSION_ARB, minorVersion,
GLX_CONTEXT_PROFILE_MASK_ARB, profile,
None
};
ctxErrorOccurred = false;
int (*oldHandler)(Display*, XErrorEvent*) =
XSetErrorHandler(&ctxErrorHandler);
PFNGLXCREATECONTEXTATTRIBSARBPROC _glXCreateContextAttribsARB;
_glXCreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC)getProcAddress("glXCreateContextAttribsARB");
if(_glXCreateContextAttribsARB)
{
// find maximal supported context version
context_attribs[1] = 4;
context_attribs[3] = 6;
while(!glxContext &&
((context_attribs[1] > majorVersion) ||
(context_attribs[1] == majorVersion && context_attribs[3] >= minorVersion)))
{
ctxErrorOccurred = false;
glxContext = _glXCreateContextAttribsARB(mGLDisplay, fbConfig, shareList, direct, context_attribs);
context_attribs[1] -= context_attribs[3] == 0; // only decrement if minor == 0
context_attribs[3] = (context_attribs[3] - 1 + 7) % 7; // decrement: -1 -> 6
}
}
else
{
// try old style context creation as a last resort
// Needed at least by MESA 8.0.4 on Ubuntu 12.04.
if (mContextProfile != CONTEXT_COMPATIBILITY) {
ctxErrorMessage = "Can not set a context profile";
} else {
glxContext =
glXCreateNewContext(mGLDisplay, fbConfig, renderType, shareList, direct);
}
}
// Sync to ensure any errors generated are processed.
XSync( mGLDisplay, False );
// Restore the original error handler
XSetErrorHandler( oldHandler );
if (ctxErrorOccurred || !glxContext)
{
LogManager::getSingleton().logError("Failed to create an OpenGL context - " + ctxErrorMessage);
}
return glxContext;
}
//-------------------------------------------------------------------------------------------------//
GLint GLXGLSupport::getFBConfigAttrib(GLXFBConfig fbConfig, GLint attribute, GLint *value)
{
GLint status;
status = glXGetFBConfigAttrib(mGLDisplay, fbConfig, attribute, value);
return status;
}
//-------------------------------------------------------------------------------------------------//
XVisualInfo* GLXGLSupport::getVisualFromFBConfig(GLXFBConfig fbConfig)
{
XVisualInfo *visualInfo;
visualInfo = glXGetVisualFromFBConfig(mGLDisplay, fbConfig);
return visualInfo;
}
//-------------------------------------------------------------------------------------------------//
void GLXGLSupport::switchMode(uint& width, uint& height, short& frequency)
{
int size = 0;
int newSize = -1;
GLXVideoModes glxVideoModes(mVideoModes.begin(), mVideoModes.end());
GLXVideoModes::iterator mode;
GLXVideoModes::iterator end = glxVideoModes.end();
GLXVideoMode *newMode = 0;
for(mode = glxVideoModes.begin(); mode != end; size++)
{
if (mode->first.first >= width &&
mode->first.second >= height)
{
if (! newMode ||
mode->first.first < newMode->first.first ||
mode->first.second < newMode->first.second)
{
newSize = size;
newMode = &(*mode);
}
}
GLXVideoMode *lastMode = &(*mode);
while (++mode != end && mode->first == lastMode->first)
{
if (lastMode == newMode && mode->second == frequency)
{
newMode = &(*mode);
}
}
}
if (newMode && *newMode != mCurrentMode)
{
XRRScreenConfiguration *screenConfig = XRRGetScreenInfo (mXDisplay, DefaultRootWindow(mXDisplay));
if (screenConfig)
{
Rotation currentRotation;
XRRConfigCurrentConfiguration (screenConfig, ¤tRotation);
XRRSetScreenConfigAndRate(mXDisplay, screenConfig, DefaultRootWindow(mXDisplay), newSize, currentRotation, newMode->second, CurrentTime);
XRRFreeScreenConfigInfo(screenConfig);
mCurrentMode = {newMode->first.first, newMode->first.second, newMode->second};
LogManager::getSingleton().logMessage("Entered video mode " + mCurrentMode.getDescription() + " @ " + StringConverter::toString(mCurrentMode.refreshRate) + "Hz");
}
}
}
//-------------------------------------------------------------------------------------------------//
void GLXGLSupport::switchMode(void)
{
return switchMode(mOriginalMode.width, mOriginalMode.height, mOriginalMode.refreshRate);
}
}
| OGRECave/ogre | RenderSystems/GLSupport/src/GLX/OgreGLXGLSupport.cpp | C++ | mit | 22,499 |
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2018, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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.
---------------------------------------------------------------------------
*/
#include "assimp_view.h"
#include <assimp/StringUtils.h>
#include <map>
#ifdef __MINGW32__
#include <mmsystem.h>
#else
#include <timeapi.h>
#endif
using namespace std;
namespace AssimpView {
extern std::string g_szNormalsShader;
extern std::string g_szDefaultShader;
extern std::string g_szPassThroughShader;
//-------------------------------------------------------------------------------
HINSTANCE g_hInstance = NULL;
HWND g_hDlg = NULL;
IDirect3D9* g_piD3D = NULL;
IDirect3DDevice9* g_piDevice = NULL;
IDirect3DVertexDeclaration9* gDefaultVertexDecl = NULL;
double g_fFPS = 0.0f;
char g_szFileName[MAX_PATH];
ID3DXEffect* g_piDefaultEffect = NULL;
ID3DXEffect* g_piNormalsEffect = NULL;
ID3DXEffect* g_piPassThroughEffect = NULL;
ID3DXEffect* g_piPatternEffect = NULL;
bool g_bMousePressed = false;
bool g_bMousePressedR = false;
bool g_bMousePressedM = false;
bool g_bMousePressedBoth = false;
float g_fElpasedTime = 0.0f;
D3DCAPS9 g_sCaps;
bool g_bLoadingFinished = false;
HANDLE g_hThreadHandle = NULL;
float g_fWheelPos = -10.0f;
bool g_bLoadingCanceled = false;
IDirect3DTexture9* g_pcTexture = NULL;
bool g_bPlay = false;
double g_dCurrent = 0.;
// default pp steps
unsigned int ppsteps = aiProcess_CalcTangentSpace | // calculate tangents and bitangents if possible
aiProcess_JoinIdenticalVertices | // join identical vertices/ optimize indexing
aiProcess_ValidateDataStructure | // perform a full validation of the loader's output
aiProcess_ImproveCacheLocality | // improve the cache locality of the output vertices
aiProcess_RemoveRedundantMaterials | // remove redundant materials
aiProcess_FindDegenerates | // remove degenerated polygons from the import
aiProcess_FindInvalidData | // detect invalid model data, such as invalid normal vectors
aiProcess_GenUVCoords | // convert spherical, cylindrical, box and planar mapping to proper UVs
aiProcess_TransformUVCoords | // preprocess UV transformations (scaling, translation ...)
aiProcess_FindInstances | // search for instanced meshes and remove them by references to one master
aiProcess_LimitBoneWeights | // limit bone weights to 4 per vertex
aiProcess_OptimizeMeshes | // join small meshes, if possible;
aiProcess_SplitByBoneCount | // split meshes with too many bones. Necessary for our (limited) hardware skinning shader
0;
unsigned int ppstepsdefault = ppsteps;
bool nopointslines = false;
extern bool g_bWasFlipped /*= false*/;
aiMatrix4x4 g_mWorld;
aiMatrix4x4 g_mWorldRotate;
aiVector3D g_vRotateSpeed = aiVector3D(0.5f,0.5f,0.5f);
// NOTE: The second light direction is now computed from the first
aiVector3D g_avLightDirs[1] =
{ aiVector3D(-0.5f,0.6f,0.2f) };
D3DCOLOR g_avLightColors[3] =
{
D3DCOLOR_ARGB(0xFF,0xFF,0xFF,0xFF),
D3DCOLOR_ARGB(0xFF,0xFF,0x00,0x00),
D3DCOLOR_ARGB(0xFF,0x05,0x05,0x05),
};
POINT g_mousePos;
POINT g_LastmousePos;
bool g_bFPSView = false;
bool g_bInvert = false;
EClickPos g_eClick = EClickPos_Circle;
unsigned int g_iCurrentColor = 0;
float g_fLightIntensity = 1.0f;
float g_fLightColor = 1.0f;
RenderOptions g_sOptions;
Camera g_sCamera;
AssetHelper *g_pcAsset = NULL;
//
// Contains the mask image for the HUD
// (used to determine the position of a click)
//
unsigned char* g_szImageMask = NULL;
float g_fLoadTime = 0.0f;
//-------------------------------------------------------------------------------
// Entry point for the loader thread
// The loader thread loads the asset while the progress dialog displays the
// smart progress bar
//-------------------------------------------------------------------------------
DWORD WINAPI LoadThreadProc(LPVOID lpParameter)
{
UNREFERENCED_PARAMETER(lpParameter);
// get current time
double fCur = (double)timeGetTime();
aiPropertyStore* props = aiCreatePropertyStore();
aiSetImportPropertyInteger(props,AI_CONFIG_IMPORT_TER_MAKE_UVS,1);
aiSetImportPropertyFloat(props,AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE,g_smoothAngle);
aiSetImportPropertyInteger(props,AI_CONFIG_PP_SBP_REMOVE,nopointslines ? aiPrimitiveType_LINE | aiPrimitiveType_POINT : 0 );
aiSetImportPropertyInteger(props,AI_CONFIG_GLOB_MEASURE_TIME,1);
//aiSetImportPropertyInteger(props,AI_CONFIG_PP_PTV_KEEP_HIERARCHY,1);
// Call ASSIMPs C-API to load the file
g_pcAsset->pcScene = (aiScene*)aiImportFileExWithProperties(g_szFileName,
ppsteps | /* configurable pp steps */
aiProcess_GenSmoothNormals | // generate smooth normal vectors if not existing
aiProcess_SplitLargeMeshes | // split large, unrenderable meshes into submeshes
aiProcess_Triangulate | // triangulate polygons with more than 3 edges
aiProcess_ConvertToLeftHanded | // convert everything to D3D left handed space
aiProcess_SortByPType | // make 'clean' meshes which consist of a single typ of primitives
0,
NULL,
props);
aiReleasePropertyStore(props);
// get the end time of zje operation, calculate delta t
double fEnd = (double)timeGetTime();
g_fLoadTime = (float)((fEnd - fCur) / 1000);
g_bLoadingFinished = true;
// check whether the loading process has failed ...
if (NULL == g_pcAsset->pcScene)
{
CLogDisplay::Instance().AddEntry("[ERROR] Unable to load this asset:",
D3DCOLOR_ARGB(0xFF,0xFF,0,0));
// print ASSIMPs error string to the log display
CLogDisplay::Instance().AddEntry(aiGetErrorString(),
D3DCOLOR_ARGB(0xFF,0xFF,0,0));
return 1;
}
return 0;
}
//-------------------------------------------------------------------------------
// load the current asset
// THe path to the asset is specified in the global path variable
//-------------------------------------------------------------------------------
int LoadAsset()
{
// set the world and world rotation matrices to the identity
g_mWorldRotate = aiMatrix4x4();
g_mWorld = aiMatrix4x4();
// char szTemp[MAX_PATH+64];
// sprintf(szTemp,"Starting to load %s",g_szFileName);
CLogWindow::Instance().WriteLine(
"----------------------------------------------------------------------------");
// CLogWindow::Instance().WriteLine(szTemp);
// CLogWindow::Instance().WriteLine(
// "----------------------------------------------------------------------------");
CLogWindow::Instance().SetAutoUpdate(false);
// create a helper thread to load the asset
DWORD dwID;
g_bLoadingCanceled = false;
g_pcAsset = new AssetHelper();
g_hThreadHandle = CreateThread(NULL,0,&LoadThreadProc,NULL,0,&dwID);
if (!g_hThreadHandle)
{
CLogDisplay::Instance().AddEntry(
"[ERROR] Unable to create helper thread for loading",
D3DCOLOR_ARGB(0xFF,0xFF,0,0));
return 0;
}
// show the progress bar dialog
DialogBox(g_hInstance,MAKEINTRESOURCE(IDD_LOADDIALOG),
g_hDlg,&ProgressMessageProc);
// update the log window
CLogWindow::Instance().SetAutoUpdate(true);
CLogWindow::Instance().Update();
// now we should have loaded the asset. Check this ...
g_bLoadingFinished = false;
if (!g_pcAsset || !g_pcAsset->pcScene)
{
if (g_pcAsset)
{
delete g_pcAsset;
g_pcAsset = NULL;
}
return 0;
}
// allocate a new MeshHelper array and build a new instance
// for each mesh in the original asset
g_pcAsset->apcMeshes = new AssetHelper::MeshHelper*[g_pcAsset->pcScene->mNumMeshes]();
for (unsigned int i = 0; i < g_pcAsset->pcScene->mNumMeshes;++i)
g_pcAsset->apcMeshes[i] = new AssetHelper::MeshHelper();
// create animator
g_pcAsset->mAnimator = new SceneAnimator( g_pcAsset->pcScene);
// build a new caption string for the viewer
static const size_t Size = MAX_PATH + 10;
char szOut[Size];
ai_snprintf(szOut, Size,AI_VIEW_CAPTION_BASE " [%s]",g_szFileName);
SetWindowText(g_hDlg,szOut);
// scale the asset vertices to fit into the viewer window
ScaleAsset();
// reset the camera view to the default position
g_sCamera.vPos = aiVector3D(0.0f,0.0f,-10.0f);
g_sCamera.vLookAt = aiVector3D(0.0f,0.0f,1.0f);
g_sCamera.vUp = aiVector3D(0.0f,1.0f,0.0f);
g_sCamera.vRight = aiVector3D(0.0f,1.0f,0.0f);
// build native D3D vertex/index buffers, textures, materials
if( 1 != CreateAssetData())
return 0;
if (!g_pcAsset->pcScene->HasAnimations()) {
EnableWindow(GetDlgItem(g_hDlg,IDC_PLAY),FALSE);
EnableWindow(GetDlgItem(g_hDlg,IDC_SLIDERANIM),FALSE);
}
else {
EnableWindow(GetDlgItem(g_hDlg,IDC_PLAY),TRUE);
EnableWindow(GetDlgItem(g_hDlg,IDC_SLIDERANIM),TRUE);
}
CLogDisplay::Instance().AddEntry("[OK] The asset has been loaded successfully");
CDisplay::Instance().FillDisplayList();
CDisplay::Instance().FillAnimList();
CDisplay::Instance().FillDefaultStatistics();
// render the scene once
CDisplay::Instance().OnRender();
g_pcAsset->iNormalSet = AssetHelper::ORIGINAL;
g_bWasFlipped = false;
return 1;
}
//-------------------------------------------------------------------------------
// Delete the loaded asset
// The function does nothing is no asset is loaded
//-------------------------------------------------------------------------------
int DeleteAsset(void)
{
if (!g_pcAsset)return 0;
// don't anymore know why this was necessary ...
CDisplay::Instance().OnRender();
// delete everything
DeleteAssetData();
for (unsigned int i = 0; i < g_pcAsset->pcScene->mNumMeshes;++i)
{
delete g_pcAsset->apcMeshes[i];
}
aiReleaseImport(g_pcAsset->pcScene);
delete[] g_pcAsset->apcMeshes;
delete g_pcAsset->mAnimator;
delete g_pcAsset;
g_pcAsset = NULL;
// reset the caption of the viewer window
SetWindowText(g_hDlg,AI_VIEW_CAPTION_BASE);
// clear UI
CDisplay::Instance().ClearAnimList();
CDisplay::Instance().ClearDisplayList();
CMaterialManager::Instance().Reset();
UpdateWindow(g_hDlg);
return 1;
}
//-------------------------------------------------------------------------------
// Calculate the boundaries of a given node and all of its children
// The boundaries are in Worldspace (AABB)
// piNode Input node
// p_avOut Receives the min/max boundaries. Must point to 2 vec3s
// piMatrix Transformation matrix of the graph at this position
//-------------------------------------------------------------------------------
int CalculateBounds(aiNode* piNode, aiVector3D* p_avOut,
const aiMatrix4x4& piMatrix)
{
ai_assert(NULL != piNode);
ai_assert(NULL != p_avOut);
aiMatrix4x4 mTemp = piNode->mTransformation;
mTemp.Transpose();
aiMatrix4x4 aiMe = mTemp * piMatrix;
for (unsigned int i = 0; i < piNode->mNumMeshes;++i)
{
for( unsigned int a = 0; a < g_pcAsset->pcScene->mMeshes[
piNode->mMeshes[i]]->mNumVertices;++a)
{
aiVector3D pc =g_pcAsset->pcScene->mMeshes[piNode->mMeshes[i]]->mVertices[a];
aiVector3D pc1;
D3DXVec3TransformCoord((D3DXVECTOR3*)&pc1,(D3DXVECTOR3*)&pc,
(D3DXMATRIX*)&aiMe);
p_avOut[0].x = min( p_avOut[0].x, pc1.x);
p_avOut[0].y = min( p_avOut[0].y, pc1.y);
p_avOut[0].z = min( p_avOut[0].z, pc1.z);
p_avOut[1].x = max( p_avOut[1].x, pc1.x);
p_avOut[1].y = max( p_avOut[1].y, pc1.y);
p_avOut[1].z = max( p_avOut[1].z, pc1.z);
}
}
for (unsigned int i = 0; i < piNode->mNumChildren;++i)
{
CalculateBounds( piNode->mChildren[i], p_avOut, aiMe );
}
return 1;
}
//-------------------------------------------------------------------------------
// Scale the asset that it fits perfectly into the viewer window
// The function calculates the boundaries of the mesh and modifies the
// global world transformation matrix according to the aset AABB
//-------------------------------------------------------------------------------
int ScaleAsset(void)
{
aiVector3D aiVecs[2] = {aiVector3D( 1e10f, 1e10f, 1e10f),
aiVector3D( -1e10f, -1e10f, -1e10f) };
if (g_pcAsset->pcScene->mRootNode)
{
aiMatrix4x4 m;
CalculateBounds(g_pcAsset->pcScene->mRootNode,aiVecs,m);
}
aiVector3D vDelta = aiVecs[1]-aiVecs[0];
aiVector3D vHalf = aiVecs[0] + (vDelta / 2.0f);
float fScale = 10.0f / vDelta.Length();
g_mWorld = aiMatrix4x4(
1.0f,0.0f,0.0f,0.0f,
0.0f,1.0f,0.0f,0.0f,
0.0f,0.0f,1.0f,0.0f,
-vHalf.x,-vHalf.y,-vHalf.z,1.0f) *
aiMatrix4x4(
fScale,0.0f,0.0f,0.0f,
0.0f,fScale,0.0f,0.0f,
0.0f,0.0f,fScale,0.0f,
0.0f,0.0f,0.0f,1.0f);
return 1;
}
//-------------------------------------------------------------------------------
// Generate a vertex buffer which holds the normals of the asset as
// a list of unconnected lines
// pcMesh Input mesh
// pcSource Source mesh from ASSIMP
//-------------------------------------------------------------------------------
int GenerateNormalsAsLineList(AssetHelper::MeshHelper* pcMesh,const aiMesh* pcSource)
{
ai_assert(NULL != pcMesh);
ai_assert(NULL != pcSource);
if (!pcSource->mNormals)return 0;
// create vertex buffer
if(FAILED( g_piDevice->CreateVertexBuffer(sizeof(AssetHelper::LineVertex) *
pcSource->mNumVertices * 2,
D3DUSAGE_WRITEONLY,
AssetHelper::LineVertex::GetFVF(),
D3DPOOL_DEFAULT, &pcMesh->piVBNormals,NULL)))
{
CLogDisplay::Instance().AddEntry("Failed to create vertex buffer for the normal list",
D3DCOLOR_ARGB(0xFF,0xFF,0,0));
return 2;
}
// now fill the vertex buffer with data
AssetHelper::LineVertex* pbData2;
pcMesh->piVBNormals->Lock(0,0,(void**)&pbData2,0);
for (unsigned int x = 0; x < pcSource->mNumVertices;++x)
{
pbData2->vPosition = pcSource->mVertices[x];
++pbData2;
aiVector3D vNormal = pcSource->mNormals[x];
vNormal.Normalize();
// scalo with the inverse of the world scaling to make sure
// the normals have equal length in each case
// TODO: Check whether this works in every case, I don't think so
vNormal.x /= g_mWorld.a1*4;
vNormal.y /= g_mWorld.b2*4;
vNormal.z /= g_mWorld.c3*4;
pbData2->vPosition = pcSource->mVertices[x] + vNormal;
++pbData2;
}
pcMesh->piVBNormals->Unlock();
return 1;
}
//-------------------------------------------------------------------------------
// Create the native D3D representation of the asset: vertex buffers,
// index buffers, materials ...
//-------------------------------------------------------------------------------
int CreateAssetData()
{
if (!g_pcAsset)return 0;
// reset all subsystems
CMaterialManager::Instance().Reset();
CDisplay::Instance().Reset();
for (unsigned int i = 0; i < g_pcAsset->pcScene->mNumMeshes;++i)
{
const aiMesh* mesh = g_pcAsset->pcScene->mMeshes[i];
// create the material for the mesh
if (!g_pcAsset->apcMeshes[i]->piEffect) {
CMaterialManager::Instance().CreateMaterial(
g_pcAsset->apcMeshes[i],mesh);
}
// create vertex buffer
if(FAILED( g_piDevice->CreateVertexBuffer(sizeof(AssetHelper::Vertex) *
mesh->mNumVertices,
D3DUSAGE_WRITEONLY,
0,
D3DPOOL_DEFAULT, &g_pcAsset->apcMeshes[i]->piVB,NULL))) {
MessageBox(g_hDlg,"Failed to create vertex buffer",
"ASSIMP Viewer Utility",MB_OK);
return 2;
}
DWORD dwUsage = 0;
if (g_pcAsset->apcMeshes[i]->piOpacityTexture || 1.0f != g_pcAsset->apcMeshes[i]->fOpacity)
dwUsage |= D3DUSAGE_DYNAMIC;
unsigned int nidx;
switch (mesh->mPrimitiveTypes) {
case aiPrimitiveType_POINT:
nidx = 1;break;
case aiPrimitiveType_LINE:
nidx = 2;break;
case aiPrimitiveType_TRIANGLE:
nidx = 3;break;
default: ai_assert(false);
};
// check whether we can use 16 bit indices
if (mesh->mNumFaces * 3 >= 65536) {
// create 32 bit index buffer
if(FAILED( g_piDevice->CreateIndexBuffer( 4 *
mesh->mNumFaces * nidx,
D3DUSAGE_WRITEONLY | dwUsage,
D3DFMT_INDEX32,
D3DPOOL_DEFAULT,
&g_pcAsset->apcMeshes[i]->piIB,
NULL)))
{
MessageBox(g_hDlg,"Failed to create 32 Bit index buffer",
"ASSIMP Viewer Utility",MB_OK);
return 2;
}
// now fill the index buffer
unsigned int* pbData;
g_pcAsset->apcMeshes[i]->piIB->Lock(0,0,(void**)&pbData,0);
for (unsigned int x = 0; x < mesh->mNumFaces;++x)
{
for (unsigned int a = 0; a < nidx;++a)
{
*pbData++ = mesh->mFaces[x].mIndices[a];
}
}
}
else {
// create 16 bit index buffer
if(FAILED( g_piDevice->CreateIndexBuffer( 2 *
mesh->mNumFaces * nidx,
D3DUSAGE_WRITEONLY | dwUsage,
D3DFMT_INDEX16,
D3DPOOL_DEFAULT,
&g_pcAsset->apcMeshes[i]->piIB,
NULL)))
{
MessageBox(g_hDlg,"Failed to create 16 Bit index buffer",
"ASSIMP Viewer Utility",MB_OK);
return 2;
}
// now fill the index buffer
uint16_t* pbData;
g_pcAsset->apcMeshes[i]->piIB->Lock(0,0,(void**)&pbData,0);
for (unsigned int x = 0; x < mesh->mNumFaces;++x)
{
for (unsigned int a = 0; a < nidx;++a)
{
*pbData++ = (uint16_t)mesh->mFaces[x].mIndices[a];
}
}
}
g_pcAsset->apcMeshes[i]->piIB->Unlock();
// collect weights on all vertices. Quick and careless
std::vector<std::vector<aiVertexWeight> > weightsPerVertex( mesh->mNumVertices);
for( unsigned int a = 0; a < mesh->mNumBones; a++) {
const aiBone* bone = mesh->mBones[a];
for( unsigned int b = 0; b < bone->mNumWeights; b++)
weightsPerVertex[bone->mWeights[b].mVertexId].push_back( aiVertexWeight( a, bone->mWeights[b].mWeight));
}
// now fill the vertex buffer
AssetHelper::Vertex* pbData2;
g_pcAsset->apcMeshes[i]->piVB->Lock(0,0,(void**)&pbData2,0);
for (unsigned int x = 0; x < mesh->mNumVertices;++x)
{
pbData2->vPosition = mesh->mVertices[x];
if (NULL == mesh->mNormals)
pbData2->vNormal = aiVector3D(0.0f,0.0f,0.0f);
else pbData2->vNormal = mesh->mNormals[x];
if (NULL == mesh->mTangents) {
pbData2->vTangent = aiVector3D(0.0f,0.0f,0.0f);
pbData2->vBitangent = aiVector3D(0.0f,0.0f,0.0f);
}
else {
pbData2->vTangent = mesh->mTangents[x];
pbData2->vBitangent = mesh->mBitangents[x];
}
if (mesh->HasVertexColors( 0)) {
pbData2->dColorDiffuse = D3DCOLOR_ARGB(
((unsigned char)max( min( mesh->mColors[0][x].a * 255.0f, 255.0f),0.0f)),
((unsigned char)max( min( mesh->mColors[0][x].r * 255.0f, 255.0f),0.0f)),
((unsigned char)max( min( mesh->mColors[0][x].g * 255.0f, 255.0f),0.0f)),
((unsigned char)max( min( mesh->mColors[0][x].b * 255.0f, 255.0f),0.0f)));
}
else pbData2->dColorDiffuse = D3DCOLOR_ARGB(0xFF,0xff,0xff,0xff);
// ignore a third texture coordinate component
if (mesh->HasTextureCoords( 0)) {
pbData2->vTextureUV = aiVector2D(
mesh->mTextureCoords[0][x].x,
mesh->mTextureCoords[0][x].y);
}
else pbData2->vTextureUV = aiVector2D(0.5f,0.5f);
if (mesh->HasTextureCoords( 1)) {
pbData2->vTextureUV2 = aiVector2D(
mesh->mTextureCoords[1][x].x,
mesh->mTextureCoords[1][x].y);
}
else pbData2->vTextureUV2 = aiVector2D(0.5f,0.5f);
// Bone indices and weights
if( mesh->HasBones()) {
unsigned char boneIndices[4] = { 0, 0, 0, 0 };
unsigned char boneWeights[4] = { 0, 0, 0, 0 };
ai_assert( weightsPerVertex[x].size() <= 4);
for( unsigned int a = 0; a < weightsPerVertex[x].size(); a++)
{
boneIndices[a] = weightsPerVertex[x][a].mVertexId;
boneWeights[a] = (unsigned char) (weightsPerVertex[x][a].mWeight * 255.0f);
}
memcpy( pbData2->mBoneIndices, boneIndices, sizeof( boneIndices));
memcpy( pbData2->mBoneWeights, boneWeights, sizeof( boneWeights));
} else
{
memset( pbData2->mBoneIndices, 0, sizeof( pbData2->mBoneIndices));
memset( pbData2->mBoneWeights, 0, sizeof( pbData2->mBoneWeights));
}
++pbData2;
}
g_pcAsset->apcMeshes[i]->piVB->Unlock();
// now generate the second vertex buffer, holding all normals
if (!g_pcAsset->apcMeshes[i]->piVBNormals) {
GenerateNormalsAsLineList(g_pcAsset->apcMeshes[i],mesh);
}
}
return 1;
}
//-------------------------------------------------------------------------------
// Delete all effects, textures, vertex buffers ... associated with
// an asset
//-------------------------------------------------------------------------------
int DeleteAssetData(bool bNoMaterials)
{
if (!g_pcAsset)return 0;
// TODO: Move this to a proper destructor
for (unsigned int i = 0; i < g_pcAsset->pcScene->mNumMeshes;++i)
{
if(g_pcAsset->apcMeshes[i]->piVB)
{
g_pcAsset->apcMeshes[i]->piVB->Release();
g_pcAsset->apcMeshes[i]->piVB = NULL;
}
if(g_pcAsset->apcMeshes[i]->piVBNormals)
{
g_pcAsset->apcMeshes[i]->piVBNormals->Release();
g_pcAsset->apcMeshes[i]->piVBNormals = NULL;
}
if(g_pcAsset->apcMeshes[i]->piIB)
{
g_pcAsset->apcMeshes[i]->piIB->Release();
g_pcAsset->apcMeshes[i]->piIB = NULL;
}
// TODO ... unfixed memory leak
// delete storage eventually allocated to hold a copy
// of the original vertex normals
//if (g_pcAsset->apcMeshes[i]->pvOriginalNormals)
//{
// delete[] g_pcAsset->apcMeshes[i]->pvOriginalNormals;
//}
if (!bNoMaterials)
{
if(g_pcAsset->apcMeshes[i]->piEffect)
{
g_pcAsset->apcMeshes[i]->piEffect->Release();
g_pcAsset->apcMeshes[i]->piEffect = NULL;
}
if(g_pcAsset->apcMeshes[i]->piDiffuseTexture)
{
g_pcAsset->apcMeshes[i]->piDiffuseTexture->Release();
g_pcAsset->apcMeshes[i]->piDiffuseTexture = NULL;
}
if(g_pcAsset->apcMeshes[i]->piNormalTexture)
{
g_pcAsset->apcMeshes[i]->piNormalTexture->Release();
g_pcAsset->apcMeshes[i]->piNormalTexture = NULL;
}
if(g_pcAsset->apcMeshes[i]->piSpecularTexture)
{
g_pcAsset->apcMeshes[i]->piSpecularTexture->Release();
g_pcAsset->apcMeshes[i]->piSpecularTexture = NULL;
}
if(g_pcAsset->apcMeshes[i]->piAmbientTexture)
{
g_pcAsset->apcMeshes[i]->piAmbientTexture->Release();
g_pcAsset->apcMeshes[i]->piAmbientTexture = NULL;
}
if(g_pcAsset->apcMeshes[i]->piEmissiveTexture)
{
g_pcAsset->apcMeshes[i]->piEmissiveTexture->Release();
g_pcAsset->apcMeshes[i]->piEmissiveTexture = NULL;
}
if(g_pcAsset->apcMeshes[i]->piOpacityTexture)
{
g_pcAsset->apcMeshes[i]->piOpacityTexture->Release();
g_pcAsset->apcMeshes[i]->piOpacityTexture = NULL;
}
if(g_pcAsset->apcMeshes[i]->piShininessTexture)
{
g_pcAsset->apcMeshes[i]->piShininessTexture->Release();
g_pcAsset->apcMeshes[i]->piShininessTexture = NULL;
}
}
}
return 1;
}
//-------------------------------------------------------------------------------
// Switch beetween zoom/rotate view and the standatd FPS view
// g_bFPSView specifies the view mode to setup
//-------------------------------------------------------------------------------
int SetupFPSView()
{
if (!g_bFPSView)
{
g_sCamera.vPos = aiVector3D(0.0f,0.0f,g_fWheelPos);
g_sCamera.vLookAt = aiVector3D(0.0f,0.0f,1.0f);
g_sCamera.vUp = aiVector3D(0.0f,1.0f,0.0f);
g_sCamera.vRight = aiVector3D(0.0f,1.0f,0.0f);
}
else
{
g_fWheelPos = g_sCamera.vPos.z;
g_sCamera.vPos = aiVector3D(0.0f,0.0f,-10.0f);
g_sCamera.vLookAt = aiVector3D(0.0f,0.0f,1.0f);
g_sCamera.vUp = aiVector3D(0.0f,1.0f,0.0f);
g_sCamera.vRight = aiVector3D(0.0f,1.0f,0.0f);
}
return 1;
}
//-------------------------------------------------------------------------------
// Initialize the IDIrect3D interface
// Called by the WinMain
//-------------------------------------------------------------------------------
int InitD3D(void)
{
if (NULL == g_piD3D)
{
g_piD3D = Direct3DCreate9(D3D_SDK_VERSION);
if (NULL == g_piD3D)return 0;
}
return 1;
}
//-------------------------------------------------------------------------------
// Release the IDirect3D interface.
// NOTE: Assumes that the device has already been deleted
//-------------------------------------------------------------------------------
int ShutdownD3D(void)
{
ShutdownDevice();
if (NULL != g_piD3D)
{
g_piD3D->Release();
g_piD3D = NULL;
}
return 1;
}
template<class TComPtr>
inline
void SafeRelease(TComPtr *ptr) {
if (nullptr != g_piPassThroughEffect) {
g_piPassThroughEffect->Release();
g_piPassThroughEffect = nullptr;
}
}
//-------------------------------------------------------------------------------
// Shutdown the D3D device object and all resources associated with it
// NOTE: Assumes that the asset has already been deleted
//-------------------------------------------------------------------------------
int ShutdownDevice(void)
{
// release other subsystems
CBackgroundPainter::Instance().ReleaseNativeResource();
CLogDisplay::Instance().ReleaseNativeResource();
// release global shaders that have been allocated
SafeRelease(g_piDefaultEffect);
SafeRelease(g_piNormalsEffect);
SafeRelease(g_piPassThroughEffect);
SafeRelease(g_piPatternEffect);
SafeRelease(g_pcTexture);
SafeRelease(gDefaultVertexDecl);
// delete the main D3D device object
SafeRelease(g_piDevice);
// deleted the one channel image allocated to hold the HUD mask
delete[] g_szImageMask;
g_szImageMask = nullptr;
return 1;
}
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
int CreateHUDTexture()
{
// lock the memory resource ourselves
HRSRC res = FindResource(NULL,MAKEINTRESOURCE(IDR_HUD),RT_RCDATA);
HGLOBAL hg = LoadResource(NULL,res);
void* pData = LockResource(hg);
if(FAILED(D3DXCreateTextureFromFileInMemoryEx(g_piDevice,
pData,SizeofResource(NULL,res),
D3DX_DEFAULT_NONPOW2,
D3DX_DEFAULT_NONPOW2,
1,
0,
D3DFMT_A8R8G8B8,
D3DPOOL_MANAGED,
D3DX_DEFAULT,
D3DX_DEFAULT,
0,
NULL,
NULL,
&g_pcTexture)))
{
CLogDisplay::Instance().AddEntry("[ERROR] Unable to load HUD texture",
D3DCOLOR_ARGB(0xFF,0xFF,0,0));
g_pcTexture = NULL;
g_szImageMask = NULL;
FreeResource(hg);
return 0;
}
FreeResource(hg);
D3DSURFACE_DESC sDesc;
g_pcTexture->GetLevelDesc(0,&sDesc);
// lock the memory resource ourselves
res = FindResource(NULL,MAKEINTRESOURCE(IDR_HUDMASK),RT_RCDATA);
hg = LoadResource(NULL,res);
pData = LockResource(hg);
IDirect3DTexture9* pcTex;
if(FAILED(D3DXCreateTextureFromFileInMemoryEx(g_piDevice,
pData,SizeofResource(NULL,res),
sDesc.Width,
sDesc.Height,
1,
0,
D3DFMT_L8,
D3DPOOL_MANAGED, // unnecessary
D3DX_DEFAULT,
D3DX_DEFAULT,
0,
NULL,
NULL,
&pcTex)))
{
CLogDisplay::Instance().AddEntry("[ERROR] Unable to load HUD mask texture",
D3DCOLOR_ARGB(0xFF,0xFF,0,0));
g_szImageMask = NULL;
FreeResource(hg);
return 0;
}
FreeResource(hg);
// lock the texture and copy it to get a pointer
D3DLOCKED_RECT sRect;
pcTex->LockRect(0,&sRect,NULL,D3DLOCK_READONLY);
unsigned char* szOut = new unsigned char[sDesc.Width * sDesc.Height];
unsigned char* _szOut = szOut;
unsigned char* szCur = (unsigned char*) sRect.pBits;
for (unsigned int y = 0; y < sDesc.Height;++y)
{
memcpy(_szOut,szCur,sDesc.Width);
szCur += sRect.Pitch;
_szOut += sDesc.Width;
}
pcTex->UnlockRect(0);
pcTex->Release();
g_szImageMask = szOut;
return 1;
}
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
int CreateDevice (bool p_bMultiSample,bool p_bSuperSample,bool bHW /*= true*/)
{
D3DDEVTYPE eType = bHW ? D3DDEVTYPE_HAL : D3DDEVTYPE_REF;
// get the client rectangle of the window.
RECT sRect;
GetWindowRect(GetDlgItem(g_hDlg,IDC_RT),&sRect);
sRect.right -= sRect.left;
sRect.bottom -= sRect.top;
D3DPRESENT_PARAMETERS sParams;
memset(&sParams,0,sizeof(D3DPRESENT_PARAMETERS));
// get the current display mode
D3DDISPLAYMODE sMode;
g_piD3D->GetAdapterDisplayMode(0,&sMode);
// fill the presentation parameter structure
sParams.Windowed = TRUE;
sParams.hDeviceWindow = GetDlgItem( g_hDlg, IDC_RT );
sParams.EnableAutoDepthStencil = TRUE;
sParams.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
sParams.BackBufferWidth = (UINT)sRect.right;
sParams.BackBufferHeight = (UINT)sRect.bottom;
sParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
sParams.BackBufferCount = 1;
// check whether we can use a D32 depth buffer format
if (SUCCEEDED ( g_piD3D->CheckDepthStencilMatch(0,eType,
D3DFMT_X8R8G8B8,D3DFMT_X8R8G8B8,D3DFMT_D32)))
{
sParams.AutoDepthStencilFormat = D3DFMT_D32;
}
else sParams.AutoDepthStencilFormat = D3DFMT_D24X8;
// find the highest multisample type available on this device
D3DMULTISAMPLE_TYPE sMS = D3DMULTISAMPLE_2_SAMPLES;
D3DMULTISAMPLE_TYPE sMSOut = D3DMULTISAMPLE_NONE;
DWORD dwQuality = 0;
if (p_bMultiSample)
{
while ((D3DMULTISAMPLE_TYPE)(D3DMULTISAMPLE_16_SAMPLES + 1) !=
(sMS = (D3DMULTISAMPLE_TYPE)(sMS + 1)))
{
if(SUCCEEDED( g_piD3D->CheckDeviceMultiSampleType(0,eType,
sMode.Format,TRUE,sMS,&dwQuality)))
{
sMSOut = sMS;
}
}
if (0 != dwQuality)dwQuality -= 1;
sParams.MultiSampleQuality = dwQuality;
sParams.MultiSampleType = sMSOut;
}
// preget the device capabilities. If the hardware vertex shader is too old, we prefer software vertex processing
g_piD3D->GetDeviceCaps( 0, D3DDEVTYPE_HAL, &g_sCaps);
DWORD creationFlags = D3DCREATE_MULTITHREADED;
if( g_sCaps.VertexShaderVersion >= D3DVS_VERSION( 2, 0))
creationFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
else
creationFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// create the D3D9 device object. with software-vertexprocessing if VS2.0 isn`t supported in hardware
if(FAILED(g_piD3D->CreateDevice(0,eType, g_hDlg, creationFlags ,&sParams,&g_piDevice)))
{
// if hardware fails use software rendering instead
if (bHW)return CreateDevice(p_bMultiSample,p_bSuperSample,false);
return 0;
}
// create a vertex declaration to match the vertex
D3DVERTEXELEMENT9* vdecl = AssetHelper::Vertex::GetDeclarationElements();
if( FAILED( g_piDevice->CreateVertexDeclaration( vdecl, &gDefaultVertexDecl)))
{
MessageBox( g_hDlg, "Failed to create vertex declaration", "Init", MB_OK);
return 0;
}
g_piDevice->SetVertexDeclaration( gDefaultVertexDecl);
// get the capabilities of the device object
g_piDevice->GetDeviceCaps(&g_sCaps);
if(g_sCaps.PixelShaderVersion < D3DPS_VERSION(3,0))
{
EnableWindow(GetDlgItem(g_hDlg,IDC_LOWQUALITY),FALSE);
}
// compile the default material shader (gray gouraud/phong)
ID3DXBuffer* piBuffer = NULL;
if(FAILED( D3DXCreateEffect(g_piDevice,
g_szDefaultShader.c_str(),
(UINT)g_szDefaultShader.length(),
NULL,
NULL,
AI_SHADER_COMPILE_FLAGS,
NULL,
&g_piDefaultEffect,&piBuffer)))
{
if( piBuffer)
{
MessageBox(g_hDlg,(LPCSTR)piBuffer->GetBufferPointer(),"HLSL",MB_OK);
piBuffer->Release();
}
return 0;
}
if( piBuffer)
{
piBuffer->Release();
piBuffer = NULL;
}
// use Fixed Function effect when working with shaderless cards
if( g_sCaps.PixelShaderVersion < D3DPS_VERSION(2,0))
g_piDefaultEffect->SetTechnique( "DefaultFXSpecular_FF");
// create the shader used to draw the HUD
if(FAILED( D3DXCreateEffect(g_piDevice,
g_szPassThroughShader.c_str(),(UINT)g_szPassThroughShader.length(),
NULL,NULL,AI_SHADER_COMPILE_FLAGS,NULL,&g_piPassThroughEffect,&piBuffer)))
{
if( piBuffer)
{
MessageBox(g_hDlg,(LPCSTR)piBuffer->GetBufferPointer(),"HLSL",MB_OK);
piBuffer->Release();
}
return 0;
}
if( piBuffer)
{
piBuffer->Release();
piBuffer = NULL;
}
// use Fixed Function effect when working with shaderless cards
if( g_sCaps.PixelShaderVersion < D3DPS_VERSION(2,0))
g_piPassThroughEffect->SetTechnique( "PassThrough_FF");
// create the shader used to visualize normal vectors
if(FAILED( D3DXCreateEffect(g_piDevice,
g_szNormalsShader.c_str(),(UINT)g_szNormalsShader.length(),
NULL,NULL,AI_SHADER_COMPILE_FLAGS,NULL,&g_piNormalsEffect, &piBuffer)))
{
if( piBuffer)
{
MessageBox(g_hDlg,(LPCSTR)piBuffer->GetBufferPointer(),"HLSL",MB_OK);
piBuffer->Release();
}
return 0;
}
if( piBuffer)
{
piBuffer->Release();
piBuffer = NULL;
}
//MessageBox( g_hDlg, "Failed to create vertex declaration", "Init", MB_OK);
// use Fixed Function effect when working with shaderless cards
if( g_sCaps.PixelShaderVersion < D3DPS_VERSION(2,0))
g_piNormalsEffect->SetTechnique( "RenderNormals_FF");
g_piDevice->SetRenderState(D3DRS_DITHERENABLE,TRUE);
// create the texture for the HUD
CreateHUDTexture();
CBackgroundPainter::Instance().RecreateNativeResource();
CLogDisplay::Instance().RecreateNativeResource();
g_piPassThroughEffect->SetTexture("TEXTURE_2D",g_pcTexture);
return 1;
}
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
int CreateDevice (void)
{
return CreateDevice(g_sOptions.bMultiSample,
g_sOptions.bSuperSample);
}
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
int GetProjectionMatrix (aiMatrix4x4& p_mOut)
{
const float fFarPlane = 100.0f;
const float fNearPlane = 0.1f;
const float fFOV = (float)(45.0 * 0.0174532925);
const float s = 1.0f / tanf(fFOV * 0.5f);
const float Q = fFarPlane / (fFarPlane - fNearPlane);
RECT sRect;
GetWindowRect(GetDlgItem(g_hDlg,IDC_RT),&sRect);
sRect.right -= sRect.left;
sRect.bottom -= sRect.top;
const float fAspect = (float)sRect.right / (float)sRect.bottom;
p_mOut = aiMatrix4x4(
s / fAspect, 0.0f, 0.0f, 0.0f,
0.0f, s, 0.0f, 0.0f,
0.0f, 0.0f, Q, 1.0f,
0.0f, 0.0f, -Q * fNearPlane, 0.0f);
return 1;
}
//-------------------------------------------------------------------------------
aiVector3D GetCameraMatrix (aiMatrix4x4& p_mOut)
{
D3DXMATRIX view;
D3DXMatrixIdentity( &view );
D3DXVec3Normalize( (D3DXVECTOR3*)&g_sCamera.vLookAt, (D3DXVECTOR3*)&g_sCamera.vLookAt );
D3DXVec3Cross( (D3DXVECTOR3*)&g_sCamera.vRight, (D3DXVECTOR3*)&g_sCamera.vUp, (D3DXVECTOR3*)&g_sCamera.vLookAt );
D3DXVec3Normalize( (D3DXVECTOR3*)&g_sCamera.vRight, (D3DXVECTOR3*)&g_sCamera.vRight );
D3DXVec3Cross( (D3DXVECTOR3*)&g_sCamera.vUp, (D3DXVECTOR3*)&g_sCamera.vLookAt, (D3DXVECTOR3*)&g_sCamera.vRight );
D3DXVec3Normalize( (D3DXVECTOR3*)&g_sCamera.vUp, (D3DXVECTOR3*)&g_sCamera.vUp );
view._11 = g_sCamera.vRight.x;
view._12 = g_sCamera.vUp.x;
view._13 = g_sCamera.vLookAt.x;
view._14 = 0.0f;
view._21 = g_sCamera.vRight.y;
view._22 = g_sCamera.vUp.y;
view._23 = g_sCamera.vLookAt.y;
view._24 = 0.0f;
view._31 = g_sCamera.vRight.z;
view._32 = g_sCamera.vUp.z;
view._33 = g_sCamera.vLookAt.z;
view._34 = 0.0f;
view._41 = -D3DXVec3Dot( (D3DXVECTOR3*)&g_sCamera.vPos, (D3DXVECTOR3*)&g_sCamera.vRight );
view._42 = -D3DXVec3Dot( (D3DXVECTOR3*)&g_sCamera.vPos, (D3DXVECTOR3*)&g_sCamera.vUp );
view._43 = -D3DXVec3Dot( (D3DXVECTOR3*)&g_sCamera.vPos, (D3DXVECTOR3*)&g_sCamera.vLookAt );
view._44 = 1.0f;
memcpy(&p_mOut,&view,sizeof(aiMatrix4x4));
return g_sCamera.vPos;
}
}
| MadManRises/Madgine | shared/assimp/tools/assimp_view/assimp_view.cpp | C++ | mit | 40,877 |
/**
* Copyright (c) 2014 Virtue Studios
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions\:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.virtue.network.protocol.update.block;
import org.virtue.game.entity.Entity;
import org.virtue.game.entity.player.Player;
import org.virtue.network.event.buffer.OutboundBuffer;
import org.virtue.network.protocol.update.Block;
import org.virtue.network.protocol.update.BlockType;
/**
* @author Im Frizzy <skype:kfriz1998>
* @author Frosty Teh Snowman <skype:travis.mccorkle>
* @author Arthur <skype:arthur.behesnilian>
* @author Sundays211
* @since 13/11/2014
*/
public class HeadIconBlock extends Block {
/**
*/
public HeadIconBlock() {
super(BlockType.HEADICONS);
}
/* (non-Javadoc)
* @see org.virtue.network.protocol.update.Block#encodeBlock(org.virtue.network.event.buffer.OutboundBuffer, org.virtue.game.entity.Entity)
*/
@Override
public void encodeBlock(OutboundBuffer block, Entity entity) {
if (entity instanceof Player) {
byte[] renderData = entity.getHeadIcons().getData();
block.putByte(renderData.length);
block.putBytes(renderData, 0, renderData.length);
} else {
byte[] renderData = entity.getHeadIcons().getData();
block.putBytes(renderData, 0, renderData.length);
}
}
}
| itsgreco/VirtueRS3 | src/org/virtue/network/protocol/update/block/HeadIconBlock.java | Java | mit | 2,264 |
// Author(s): Sébastien Lorion
namespace NLight.IO.Text
{
public partial class TextRecordWriter
{
public const char DefaultCommentCharacter = '#';
}
} | slorion/nlight | src/NLight/IO/Text/TextRecordWriter.cs | C# | mit | 160 |
package com.viesis.viescraft.client.gui.v2;
import java.io.IOException;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.inventory.IInventory;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.input.Keyboard;
import com.viesis.viescraft.api.Reference;
import com.viesis.viescraft.api.util.Keybinds;
import com.viesis.viescraft.common.entity.airshipcolors.EntityAirshipV2Core;
import com.viesis.viescraft.common.entity.airshipcolors.containers.v2.ContainerAirshipV2ModuleInvLarge;
import com.viesis.viescraft.common.utils.events.EventHandlerAirship;
import com.viesis.viescraft.network.NetworkHandler;
import com.viesis.viescraft.network.server.v2.MessageGuiV2Module;
public class GuiEntityAirshipV2ModuleInventoryLarge extends GuiContainer {
private GuiButton buttonModule;
private IInventory playerInv;
private EntityAirshipV2Core airshipV2;
public GuiEntityAirshipV2ModuleInventoryLarge(IInventory playerInv, EntityAirshipV2Core airshipV2)
{
super(new ContainerAirshipV2ModuleInvLarge(playerInv, airshipV2));
this.playerInv = playerInv;
this.airshipV2 = airshipV2;
this.xSize = 176;
this.ySize = 166;
}
/**
* Adds the buttons (and other controls) to the screen in question.
*/
@Override
public void initGui()
{
super.initGui();
buttonList.clear();
Keyboard.enableRepeatEvents(true);
buttonModule = new GuiButton( 1, this.guiLeft + 133, this.guiTop + 60, 37, 20, "Module");
this.buttonList.add(buttonModule);
}
/**
* Called by the controls from the buttonList when activated. (Mouse pressed for buttons)
*/
@Override
protected void actionPerformed(GuiButton parButton)
{
if (parButton.id == 1)
{
NetworkHandler.sendToServer(new MessageGuiV2Module());
}
this.buttonList.clear();
this.initGui();
this.updateScreen();
}
@Override
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY)
{
GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f);
this.mc.getTextureManager().bindTexture(new ResourceLocation(Reference.MOD_ID + ":" + "textures/gui/container_airship_module2.png"));
this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize);
if (this.airshipV2.getPowered() > 0)
{
if(EventHandlerAirship.creativeBurnV2)
{
this.drawTexturedModalRect(this.guiLeft + 138, this.guiTop + 4, 184, 50, 8, 1 + 47);
this.drawTexturedModalRect(this.guiLeft + 152, this.guiTop + 17, 176, 119, 16, 16);
this.drawTexturedModalRect(this.guiLeft + 147, this.guiTop + 30, 176, 14, 26, 16);
}
else
{
int k = this.getBurnLeftScaled(47);
this.drawTexturedModalRect(this.guiLeft + 138, this.guiTop + 4, 176, 50, 8, 1 + k);
this.drawTexturedModalRect(this.guiLeft + 147, this.guiTop + 30, 176, 14, 26, 16);
}
}
//Draw a green fuel bar and magma in the coal slot
if(EventHandlerAirship.creativeBurnV2
|| this.airshipV2.getModuleFuelInfinite())
{
this.drawTexturedModalRect(this.guiLeft + 138, this.guiTop + 4, 184, 50, 8, 1 + 47);
this.drawTexturedModalRect(this.guiLeft + 152, this.guiTop + 17, 176, 119, 16, 16);
}
}
private int getBurnLeftScaled(int pixels)
{
int i = this.airshipV2.getField(1);
if (i == 0)
{
i = this.airshipV2.itemFuelStack + 1;
}
return this.airshipV2.getField(0) * pixels / i;
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY)
{
String s = this.airshipV2.getDisplayName().getUnformattedText();
//this.fontRendererObj.drawString("Fuel", 150, 6, 4210752);
this.fontRendererObj.drawString(this.playerInv.getDisplayName().getUnformattedText(), 8, 72, 4210752);
}
@Override
protected void keyTyped(char typedChar, int keyCode) throws IOException
{
if (keyCode == 1
|| keyCode == Keybinds.vcInventory.getKeyCode()
|| this.mc.gameSettings.keyBindInventory.isActiveAndMatches(keyCode))
{
this.mc.thePlayer.closeScreen();
}
}
}
| Weisses/Ebonheart-Mods | ViesCraft/Archived/zzz - PreCapabilities - src/main/java/com/viesis/viescraft/client/gui/v2/GuiEntityAirshipV2ModuleInventoryLarge.java | Java | mit | 4,247 |
<?php
/**
* This file is part of the PPI Framework.
*
* @copyright Copyright (c) 2012 Paul Dragoonis <paul@ppi.io>
* @license http://opensource.org/licenses/mit-license.php MIT
*
* @link http://www.ppi.io
*/
namespace PPI\Framework\View\Twig;
use PPI\Framework\View\EngineInterface;
use PPI\Framework\View\GlobalVariables;
use PPI\Framework\View\TemplateReference;
use Symfony\Component\Config\FileLocatorInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Templating\StreamingEngineInterface;
use Symfony\Component\Templating\TemplateNameParserInterface;
/**
* This engine knows how to render Twig templates.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Paul Dragoonis <paul@ppi.io>
*/
class TwigEngine implements EngineInterface, StreamingEngineInterface
{
/**
* @todo Add inline documentation.
*
* @var type
*/
protected $environment;
/**
* @todo Add inline documentation.
*
* @var type
*/
protected $parser;
/**
* @todo Add inline documentation.
*
* @var type
*/
protected $locator;
/**
* Constructor.
*
* @param \Twig_Environment $environment A \Twig_Environment instance
* @param TemplateNameParserInterface $parser A TemplateNameParserInterface instance
* @param FileLocatorInterface $locator A FileLocatorInterface instance
* @param GlobalVariables|null $globals A GlobalVariables instance or null
*/
public function __construct(\Twig_Environment $environment, TemplateNameParserInterface $parser, FileLocatorInterface $locator, GlobalVariables $globals = null)
{
$this->environment = $environment;
$this->parser = $parser;
$this->locator = $locator;
if (null !== $globals) {
$environment->addGlobal('app', $globals);
}
}
/**
* Renders a template.
*
* @param mixed $name A template name
* @param array $parameters An array of parameters to pass to the template
*
* @throws \InvalidArgumentException if the template does not exist
* @throws \RuntimeException if the template cannot be rendered
*
* @return string The evaluated template as a string
*/
public function render($name, array $parameters = array())
{
try {
return $this->load($name)->render($parameters);
} catch (\Twig_Error $e) {
if ($name instanceof TemplateReference) {
try {
// try to get the real file name of the template where the
// error occurred
$e->setTemplateFile(sprintf('%s',
$this->locator->locate(
$this->parser->parse(
$e->getTemplateFile()
)
)
));
} catch (\Exception $ex) {
}
}
throw $e;
}
}
/**
* Streams a template.
*
* @param mixed $name A template name or a TemplateReferenceInterface instance
* @param array $parameters An array of parameters to pass to the template
*
* @throws \RuntimeException If the template cannot be rendered
*/
public function stream($name, array $parameters = array())
{
$this->load($name)->display($parameters);
}
/**
* Returns true if the template exists.
*
* @param mixed $name A template name
*
* @return boolean true if the template exists, false otherwise
*/
public function exists($name)
{
try {
$this->load($name);
} catch (\InvalidArgumentException $e) {
return false;
}
return true;
}
/**
* Returns true if this class is able to render the given template.
*
* @param string $name A template name
*
* @return boolean True if this class supports the given resource, false otherwise
*/
public function supports($name)
{
if ($name instanceof \Twig_Template) {
return true;
}
$template = $this->parser->parse($name);
return 'twig' === $template->get('engine');
}
/**
* Renders a view and returns a Response.
*
* @param string $view The view name
* @param array $parameters An array of parameters to pass to the view
* @param Response $response A Response instance
*
* @return Response A Response instance
*/
public function renderResponse($view, array $parameters = array(), Response $response = null)
{
if (null === $response) {
$response = new Response();
}
$response->setContent($this->render($view, $parameters));
return $response;
}
/**
* Pass methods not available in this engine to the Twig_Environment
* instance.
*
* @param string $name
* @param array $args
*
* @return mixed
*
* @warning This method was added for BC and may be removed in future
* releases.
*/
public function __call($name, $args)
{
return call_user_func_array(array($this->environment, $name), $args);
}
/**
* Loads the given template.
*
* @param mixed $name A template name or an instance of Twig_Template
*
* @throws \InvalidArgumentException if the template does not exist
*
* @return \Twig_TemplateInterface A \Twig_TemplateInterface instance
*/
protected function load($name)
{
if ($name instanceof \Twig_Template) {
return $name;
}
try {
return $this->environment->loadTemplate($name);
} catch (\Twig_Error_Loader $e) {
throw new \InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
}
}
| BeastModeON/framework | src/View/Twig/TwigEngine.php | PHP | mit | 6,042 |
<?php
/**
* This file is part of the @package@.
*
* @author: Nikolay Ermin <keltanas@gmail.com>
* @version: @version@
*/
namespace Module\News\Listener;
use Sfcms\Kernel\KernelEvent;
class RssListener
{
public function onKernelResponse(KernelEvent $event)
{
$content = $event->getResponse()->getContent();
$content = str_replace(
'</head>',
sprintf('<link title="" type="application/rss+xml" rel="alternate" href="http://%s/rss">'.PHP_EOL.'</head>', $_SERVER['HTTP_HOST']),
$content
);
$event->getResponse()->setContent($content);
}
}
| siteforever/SiteForeverCMS | class/Module/News/Listener/RssListener.php | PHP | mit | 624 |
$(function () {
$(window).on('message', function (e) {
$.ajax({
url: '/widget/data',
method: 'POST',
data: {diff: e.originalEvent.data.diff},
dataType: 'json',
success: function (data) {
parent.postMessage(
{
metrics: data.metrics,
elementId: e.originalEvent.data.elementId
},
'*'
);
}
});
});
parent.postMessage({ready: true}, '*');
});
| ucarion/git-code-debt | git_code_debt/server/static/js/widget_frame.js | JavaScript | mit | 579 |
<?php
namespace AppBundle\Repository;
/**
* AdresseRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class AdresseRepository extends \Doctrine\ORM\EntityRepository
{
}
| jcognet/inscription | src/AppBundle/Repository/AdresseRepository.php | PHP | mit | 237 |
/* global QUnit */
import { Euler } from '../../../../src/math/Euler.js';
import { Matrix4 } from '../../../../src/math/Matrix4.js';
import { Quaternion } from '../../../../src/math/Quaternion.js';
import { Vector3 } from '../../../../src/math/Vector3.js';
import { x, y, z } from './Constants.tests.js';
const eulerZero = new Euler( 0, 0, 0, 'XYZ' );
const eulerAxyz = new Euler( 1, 0, 0, 'XYZ' );
const eulerAzyx = new Euler( 0, 1, 0, 'ZYX' );
function matrixEquals4( a, b, tolerance ) {
tolerance = tolerance || 0.0001;
if ( a.elements.length != b.elements.length ) {
return false;
}
for ( var i = 0, il = a.elements.length; i < il; i ++ ) {
var delta = a.elements[ i ] - b.elements[ i ];
if ( delta > tolerance ) {
return false;
}
}
return true;
}
function quatEquals( a, b, tolerance ) {
tolerance = tolerance || 0.0001;
var diff = Math.abs( a.x - b.x ) + Math.abs( a.y - b.y ) + Math.abs( a.z - b.z ) + Math.abs( a.w - b.w );
return ( diff < tolerance );
}
export default QUnit.module( 'Maths', () => {
QUnit.module( 'Euler', () => {
// INSTANCING
QUnit.test( 'Instancing', ( assert ) => {
var a = new Euler();
assert.ok( a.equals( eulerZero ), 'Passed!' );
assert.ok( ! a.equals( eulerAxyz ), 'Passed!' );
assert.ok( ! a.equals( eulerAzyx ), 'Passed!' );
} );
// STATIC STUFF
QUnit.test( 'RotationOrders', ( assert ) => {
assert.ok( Array.isArray( Euler.RotationOrders ), 'Passed!' );
assert.deepEqual( Euler.RotationOrders, [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ], 'Passed!' );
} );
QUnit.test( 'DefaultOrder', ( assert ) => {
assert.equal( Euler.DefaultOrder, 'XYZ', 'Passed!' );
} );
// PROPERTIES STUFF
QUnit.test( 'x', ( assert ) => {
var a = new Euler();
assert.ok( a.x === 0, 'Passed!' );
a = new Euler( 1, 2, 3 );
assert.ok( a.x === 1, 'Passed!' );
a = new Euler( 4, 5, 6, 'XYZ' );
assert.ok( a.x === 4, 'Passed!' );
a = new Euler( 7, 8, 9, 'XYZ' );
a.x = 10;
assert.ok( a.x === 10, 'Passed!' );
a = new Euler( 11, 12, 13, 'XYZ' );
var b = false;
a._onChange( function () {
b = true;
} );
a.x = 14;
assert.ok( b, 'Passed!' );
assert.ok( a.x === 14, 'Passed!' );
} );
QUnit.test( 'y', ( assert ) => {
var a = new Euler();
assert.ok( a.y === 0, 'Passed!' );
a = new Euler( 1, 2, 3 );
assert.ok( a.y === 2, 'Passed!' );
a = new Euler( 4, 5, 6, 'XYZ' );
assert.ok( a.y === 5, 'Passed!' );
a = new Euler( 7, 8, 9, 'XYZ' );
a.y = 10;
assert.ok( a.y === 10, 'Passed!' );
a = new Euler( 11, 12, 13, 'XYZ' );
var b = false;
a._onChange( function () {
b = true;
} );
a.y = 14;
assert.ok( b, 'Passed!' );
assert.ok( a.y === 14, 'Passed!' );
} );
QUnit.test( 'z', ( assert ) => {
var a = new Euler();
assert.ok( a.z === 0, 'Passed!' );
a = new Euler( 1, 2, 3 );
assert.ok( a.z === 3, 'Passed!' );
a = new Euler( 4, 5, 6, 'XYZ' );
assert.ok( a.z === 6, 'Passed!' );
a = new Euler( 7, 8, 9, 'XYZ' );
a.z = 10;
assert.ok( a.z === 10, 'Passed!' );
a = new Euler( 11, 12, 13, 'XYZ' );
var b = false;
a._onChange( function () {
b = true;
} );
a.z = 14;
assert.ok( b, 'Passed!' );
assert.ok( a.z === 14, 'Passed!' );
} );
QUnit.test( 'order', ( assert ) => {
var a = new Euler();
assert.ok( a.order === Euler.DefaultOrder, 'Passed!' );
a = new Euler( 1, 2, 3 );
assert.ok( a.order === Euler.DefaultOrder, 'Passed!' );
a = new Euler( 4, 5, 6, 'YZX' );
assert.ok( a.order === 'YZX', 'Passed!' );
a = new Euler( 7, 8, 9, 'YZX' );
a.order = 'ZXY';
assert.ok( a.order === 'ZXY', 'Passed!' );
a = new Euler( 11, 12, 13, 'YZX' );
var b = false;
a._onChange( function () {
b = true;
} );
a.order = 'ZXY';
assert.ok( b, 'Passed!' );
assert.ok( a.order === 'ZXY', 'Passed!' );
} );
// PUBLIC STUFF
QUnit.test( 'isEuler', ( assert ) => {
var a = new Euler();
assert.ok( a.isEuler, 'Passed!' );
var b = new Vector3();
assert.ok( ! b.isEuler, 'Passed!' );
} );
QUnit.test( 'set/setFromVector3/toVector3', ( assert ) => {
var a = new Euler();
a.set( 0, 1, 0, 'ZYX' );
assert.ok( a.equals( eulerAzyx ), 'Passed!' );
assert.ok( ! a.equals( eulerAxyz ), 'Passed!' );
assert.ok( ! a.equals( eulerZero ), 'Passed!' );
var vec = new Vector3( 0, 1, 0 );
var b = new Euler().setFromVector3( vec, 'ZYX' );
assert.ok( a.equals( b ), 'Passed!' );
var c = b.toVector3();
assert.ok( c.equals( vec ), 'Passed!' );
} );
QUnit.test( 'clone/copy/equals', ( assert ) => {
var a = eulerAxyz.clone();
assert.ok( a.equals( eulerAxyz ), 'Passed!' );
assert.ok( ! a.equals( eulerZero ), 'Passed!' );
assert.ok( ! a.equals( eulerAzyx ), 'Passed!' );
a.copy( eulerAzyx );
assert.ok( a.equals( eulerAzyx ), 'Passed!' );
assert.ok( ! a.equals( eulerAxyz ), 'Passed!' );
assert.ok( ! a.equals( eulerZero ), 'Passed!' );
} );
QUnit.test( 'Quaternion.setFromEuler/Euler.fromQuaternion', ( assert ) => {
var testValues = [ eulerZero, eulerAxyz, eulerAzyx ];
for ( var i = 0; i < testValues.length; i ++ ) {
var v = testValues[ i ];
var q = new Quaternion().setFromEuler( v );
var v2 = new Euler().setFromQuaternion( q, v.order );
var q2 = new Quaternion().setFromEuler( v2 );
assert.ok( quatEquals( q, q2 ), 'Passed!' );
}
} );
QUnit.test( 'Matrix4.setFromEuler/Euler.fromRotationMatrix', ( assert ) => {
var testValues = [ eulerZero, eulerAxyz, eulerAzyx ];
for ( var i = 0; i < testValues.length; i ++ ) {
var v = testValues[ i ];
var m = new Matrix4().makeRotationFromEuler( v );
var v2 = new Euler().setFromRotationMatrix( m, v.order );
var m2 = new Matrix4().makeRotationFromEuler( v2 );
assert.ok( matrixEquals4( m, m2, 0.0001 ), 'Passed!' );
}
} );
QUnit.test( 'reorder', ( assert ) => {
var testValues = [ eulerZero, eulerAxyz, eulerAzyx ];
for ( var i = 0; i < testValues.length; i ++ ) {
var v = testValues[ i ];
var q = new Quaternion().setFromEuler( v );
v.reorder( 'YZX' );
var q2 = new Quaternion().setFromEuler( v );
assert.ok( quatEquals( q, q2 ), 'Passed!' );
v.reorder( 'ZXY' );
var q3 = new Quaternion().setFromEuler( v );
assert.ok( quatEquals( q, q3 ), 'Passed!' );
}
} );
QUnit.test( 'set/get properties, check callbacks', ( assert ) => {
var a = new Euler();
a._onChange( function () {
assert.step( 'set: onChange called' );
} );
a.x = 1;
a.y = 2;
a.z = 3;
a.order = 'ZYX';
assert.strictEqual( a.x, 1, 'get: check x' );
assert.strictEqual( a.y, 2, 'get: check y' );
assert.strictEqual( a.z, 3, 'get: check z' );
assert.strictEqual( a.order, 'ZYX', 'get: check order' );
assert.verifySteps( Array( 4 ).fill( 'set: onChange called' ) );
} );
QUnit.test( 'clone/copy, check callbacks', ( assert ) => {
var a = new Euler( 1, 2, 3, 'ZXY' );
var b = new Euler( 4, 5, 6, 'XZY' );
var cbSucceed = function () {
assert.ok( true );
assert.step( 'onChange called' );
};
var cbFail = function () {
assert.ok( false );
};
a._onChange( cbFail );
b._onChange( cbFail );
// clone doesn't trigger onChange
a = b.clone();
assert.ok( a.equals( b ), 'clone: check if a equals b' );
// copy triggers onChange once
a = new Euler( 1, 2, 3, 'ZXY' );
a._onChange( cbSucceed );
a.copy( b );
assert.ok( a.equals( b ), 'copy: check if a equals b' );
assert.verifySteps( [ 'onChange called' ] );
} );
QUnit.test( 'toArray', ( assert ) => {
var order = 'YXZ';
var a = new Euler( x, y, z, order );
var array = a.toArray();
assert.strictEqual( array[ 0 ], x, 'No array, no offset: check x' );
assert.strictEqual( array[ 1 ], y, 'No array, no offset: check y' );
assert.strictEqual( array[ 2 ], z, 'No array, no offset: check z' );
assert.strictEqual( array[ 3 ], order, 'No array, no offset: check order' );
var array = [];
a.toArray( array );
assert.strictEqual( array[ 0 ], x, 'With array, no offset: check x' );
assert.strictEqual( array[ 1 ], y, 'With array, no offset: check y' );
assert.strictEqual( array[ 2 ], z, 'With array, no offset: check z' );
assert.strictEqual( array[ 3 ], order, 'With array, no offset: check order' );
var array = [];
a.toArray( array, 1 );
assert.strictEqual( array[ 0 ], undefined, 'With array and offset: check [0]' );
assert.strictEqual( array[ 1 ], x, 'With array and offset: check x' );
assert.strictEqual( array[ 2 ], y, 'With array and offset: check y' );
assert.strictEqual( array[ 3 ], z, 'With array and offset: check z' );
assert.strictEqual( array[ 4 ], order, 'With array and offset: check order' );
} );
QUnit.test( 'fromArray', ( assert ) => {
var a = new Euler();
var array = [ x, y, z ];
var cb = function () {
assert.step( 'onChange called' );
};
a._onChange( cb );
a.fromArray( array );
assert.strictEqual( a.x, x, 'No order: check x' );
assert.strictEqual( a.y, y, 'No order: check y' );
assert.strictEqual( a.z, z, 'No order: check z' );
assert.strictEqual( a.order, 'XYZ', 'No order: check order' );
a = new Euler();
array = [ x, y, z, 'ZXY' ];
a._onChange( cb );
a.fromArray( array );
assert.strictEqual( a.x, x, 'With order: check x' );
assert.strictEqual( a.y, y, 'With order: check y' );
assert.strictEqual( a.z, z, 'With order: check z' );
assert.strictEqual( a.order, 'ZXY', 'With order: check order' );
assert.verifySteps( Array( 2 ).fill( 'onChange called' ) );
} );
QUnit.test( '_onChange', ( assert ) => {
var f = function () {
};
var a = new Euler( 11, 12, 13, 'XYZ' );
a._onChange( f );
assert.ok( a._onChangeCallback === f, 'Passed!' );
} );
QUnit.test( '_onChangeCallback', ( assert ) => {
var b = false;
var a = new Euler( 11, 12, 13, 'XYZ' );
var f = function () {
b = true;
assert.ok( a === this, 'Passed!' );
};
a._onChangeCallback = f;
assert.ok( a._onChangeCallback === f, 'Passed!' );
a._onChangeCallback();
assert.ok( b, 'Passed!' );
} );
} );
} );
| looeee/three.js | test/unit/src/math/Euler.tests.js | JavaScript | mit | 10,298 |
import { IsUri } from '../ref/uri';
import { JsonPath } from '../ref/jsonpath';
import { EncodeEnhancedPositionInName, TryDecodeEnhancedPositionFromName } from './source-map';
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { DataStore } from "../data-store/data-store";
import { From } from "../ref/linq";
export class BlameTree {
public static Create(dataStore: DataStore, position: sourceMap.MappedPosition): BlameTree {
const data = dataStore.ReadStrictSync(position.source);
const blames = data.Blame(position);
// propagate smart position
const enhanced = TryDecodeEnhancedPositionFromName(position.name);
if (enhanced !== undefined) {
for (const blame of blames) {
blame.name = EncodeEnhancedPositionInName(blame.name, Object.assign(
JSON.parse(JSON.stringify(enhanced)),
TryDecodeEnhancedPositionFromName(blame.name) || {}));
}
}
return new BlameTree(position, blames.map(pos => BlameTree.Create(dataStore, pos)));
}
private constructor(
public readonly node: sourceMap.MappedPosition & { path?: JsonPath },
public readonly blaming: BlameTree[]) { }
public BlameInputs(): sourceMap.MappedPosition[] {
const result: sourceMap.MappedPosition[] = [];
const todos: BlameTree[] = [this];
let todo: BlameTree | undefined;
while (todo = todos.pop()) {
// report self
if (IsUri(todo.node.source) && !todo.node.source.startsWith(DataStore.BaseUri)) {
result.push({
column: todo.node.column,
line: todo.node.line,
name: todo.node.name,
source: todo.node.source
});
continue;
}
// recurse
todos.push(...todo.blaming);
}
return From(result).Distinct(x => JSON.stringify(x)).ToArray();
}
}
| ljhljh235/AutoRest | src/autorest-core/lib/source-map/blaming.ts | TypeScript | mit | 2,109 |
/* Controls email settings for user Profile */
angular.module('collabjs.controllers')
.controller('EmailController', ['$scope', 'accountService',
function ($scope, accountService) {
'use strict';
$scope.error = false;
$scope.info = false;
$scope.dismissError = function () { $scope.error = false; };
$scope.dismissInfo = function () { $scope.info = false; };
$scope.oldEmail = '';
$scope.newEmail = '';
$scope.confirmEmail = '';
$scope.errInvalidValues = 'Incorrect email values.';
$scope.errConfirmation = 'Email confirmation must match value above.';
$scope.errSameEmail = 'New email is the same as old one.';
$scope.msgSuccess = 'Email has been successfully changed.';
$scope.init = function () {
accountService.getAccount().then(function (account) {
$scope.oldEmail = account.email;
});
};
$scope.submit = function () {
$scope.error = false;
if (!$scope.oldEmail || !$scope.newEmail || !$scope.confirmEmail) {
$scope.error = $scope.errInvalidValues;
return;
}
if ($scope.confirmEmail !== $scope.newEmail) {
$scope.error = $scope.errConfirmation;
return;
}
if ($scope.newEmail === $scope.oldEmail) {
$scope.error = $scope.errSameEmail;
return;
}
accountService
.changeEmail($scope.oldEmail, $scope.newEmail)
.then(
// success handler
function () {
$scope.info = $scope.msgSuccess;
$scope.oldEmail = $scope.newEmail;
$scope.newEmail = '';
$scope.confirmEmail = '';
},
// error handler
function (err) {
$scope.error = 'Error: ' + err;
$scope.newEmail = '';
$scope.confirmEmail = '';
}
);
};
}]); | lvnhmd/collab.js | public/js/controllers/EmailController.js | JavaScript | mit | 1,963 |
import { RoutingStateChanged } from '../../Events';
export interface ViewModelLifecyle {
initializeViewModel(): void;
loadedViewModel(): void;
updatedViewModel(): void;
cleanupViewModel(): void;
}
export interface RoutingStateHandler<T extends {}> {
isRoutingStateHandler(): boolean;
createRoutingState(context?: any): T;
applyRoutingState(state: T): void;
}
export interface HandlerRoutingStateChanged extends RoutingStateChanged {
source: RoutingStateHandler<any>;
}
| marinels/webrx-react | src/Components/React/Interfaces.ts | TypeScript | mit | 488 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| DATABASE CONNECTIVITY SETTINGS
| -------------------------------------------------------------------
| This file will contain the settings needed to access your database.
|
| For complete instructions please consult the 'Database Connection'
| page of the User Guide.
|
| -------------------------------------------------------------------
| EXPLANATION OF VARIABLES
| -------------------------------------------------------------------
|
| ['dsn'] The full DSN string describe a connection to the database.
| ['hostname'] The hostname of your database server.
| ['username'] The username used to connect to the database
| ['password'] The password used to connect to the database
| ['database'] The name of the database you want to connect to
| ['dbdriver'] The database driver. e.g.: mysqli.
| Currently supported:
| cubrid, ibase, mssql, mysql, mysqli, oci8,
| odbc, pdo, postgre, sqlite, sqlite3, sqlsrv
| ['dbprefix'] You can add an optional prefix, which will be added
| to the table name when using the Query Builder class
| ['pconnect'] TRUE/FALSE - Whether to use a persistent connection
| ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
| ['cache_on'] TRUE/FALSE - Enables/disables query caching
| ['cachedir'] The path to the folder where cache files should be stored
| ['char_set'] The character set used in communicating with the database
| ['dbcollat'] The character collation used in communicating with the database
| NOTE: For MySQL and MySQLi databases, this setting is only used
| as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7
| (and in table creation queries made with DB Forge).
| There is an incompatibility in PHP with mysql_real_escape_string() which
| can make your site vulnerable to SQL injection if you are using a
| multi-byte character set and are running versions lower than these.
| Sites using Latin-1 or UTF-8 database character set and collation are unaffected.
| ['swap_pre'] A default table prefix that should be swapped with the dbprefix
| ['encrypt'] Whether or not to use an encrypted connection.
| ['compress'] Whether or not to use client compression (MySQL only)
| ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections
| - good for ensuring strict SQL while developing
| ['failover'] array - A array with 0 or more data for connections if the main should fail.
| ['save_queries'] TRUE/FALSE - Whether to "save" all executed queries.
| NOTE: Disabling this will also effectively disable both
| $this->db->last_query() and profiling of DB queries.
| When you run a query, with this setting set to TRUE (default),
| CodeIgniter will store the SQL statement for debugging purposes.
| However, this may cause high memory usage, especially if you run
| a lot of SQL queries ... disable this to avoid that problem.
|
| The $active_group variable lets you choose which connection group to
| make active. By default there is only one group (the 'default' group).
|
| The $query_builder variables lets you determine whether or not to load
| the query builder class.
*/
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'hostel',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
| saurabhgarg510/TU_CMS | application/config/database.php | PHP | mit | 3,786 |
function Cli(argv) {
var Cucumber = require('../cucumber');
var Command = require('commander').Command;
var path = require('path');
function collect(val, memo) {
memo.push(val);
return memo;
}
function getProgram () {
var program = new Command(path.basename(argv[1]));
program
.usage('[options] [<DIR|FILE[:LINE]>...]')
.version(Cucumber.VERSION, '-v, --version')
.option('-b, --backtrace', 'show full backtrace for errors')
.option('--compiler <EXTENSION:MODULE>', 'require files with the given EXTENSION after requiring MODULE (repeatable)', collect, [])
.option('-d, --dry-run', 'invoke formatters without executing steps')
.option('--fail-fast', 'abort the run on first failure')
.option('-f, --format <TYPE[:PATH]>', 'specify the output format, optionally supply PATH to redirect formatter output (repeatable)', collect, ['pretty'])
.option('--name <REGEXP>', 'only execute the scenarios with name matching the expression (repeatable)', collect, [])
.option('--no-colors', 'disable colors in formatter output')
.option('-p, --profile <NAME>', 'specify the profile to use (repeatable)', collect, [])
.option('-r, --require <FILE|DIR>', 'require files before executing features (repeatable)', collect, [])
.option('--snippet-syntax <FILE>', 'specify a custom snippet syntax')
.option('-S, --strict', 'fail if there are any undefined or pending steps')
.option('-t, --tags <EXPRESSION>', 'only execute the features or scenarios with tags matching the expression (repeatable)', collect, []);
program.on('--help', function(){
console.log(' For more details please visit https://github.com/cucumber/cucumber-js#cli\n');
});
return program;
}
function getConfiguration() {
var program = getProgram();
program.parse(argv);
var profileArgs = Cucumber.Cli.ProfilesLoader.getArgs(program.profile);
if (profileArgs.length > 0) {
var fullArgs = argv.slice(0, 2).concat(profileArgs).concat(argv.slice(2));
program = getProgram();
program.parse(fullArgs);
}
var configuration = Cucumber.Cli.Configuration(program.opts(), program.args);
return configuration;
}
var self = {
run: function run(callback) {
var configuration = getConfiguration();
var runtime = Cucumber.Runtime(configuration);
var formatters = configuration.getFormatters();
formatters.forEach(function (formatter) {
runtime.attachListener(formatter);
});
runtime.start(callback);
}
};
return self;
}
Cli.Configuration = require('./cli/configuration');
Cli.FeaturePathExpander = require('./cli/feature_path_expander');
Cli.FeatureSourceLoader = require('./cli/feature_source_loader');
Cli.PathExpander = require('./cli/path_expander');
Cli.ProfilesLoader = require('./cli/profiles_loader');
Cli.SupportCodeLoader = require('./cli/support_code_loader');
Cli.SupportCodePathExpander = require('./cli/support_code_path_expander');
module.exports = Cli;
| deep0892/jitendrachatbot | node_modules/chimp/node_modules/cucumber/lib/cucumber/cli.js | JavaScript | mit | 3,056 |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { ExtensionContext, workspace, window, Disposable, commands, Uri } from 'vscode';
import { findGit, Git, IGit } from './git';
import { Model } from './model';
import { GitSCMProvider } from './scmProvider';
import { CommandCenter } from './commands';
import { StatusBarCommands } from './statusbar';
import { GitContentProvider } from './contentProvider';
import { AutoFetcher } from './autofetch';
import { MergeDecorator } from './merge';
import { Askpass } from './askpass';
import TelemetryReporter from 'vscode-extension-telemetry';
import * as nls from 'vscode-nls';
const localize = nls.config(process.env.VSCODE_NLS_CONFIG)();
async function init(context: ExtensionContext, disposables: Disposable[]): Promise<void> {
const { name, version, aiKey } = require(context.asAbsolutePath('./package.json')) as { name: string, version: string, aiKey: string };
const telemetryReporter: TelemetryReporter = new TelemetryReporter(name, version, aiKey);
disposables.push(telemetryReporter);
const outputChannel = window.createOutputChannel('Git');
disposables.push(outputChannel);
const config = workspace.getConfiguration('git');
const enabled = config.get<boolean>('enabled') === true;
const workspaceRootPath = workspace.rootPath;
const pathHint = workspace.getConfiguration('git').get<string>('path');
const info = await findGit(pathHint);
const askpass = new Askpass();
const env = await askpass.getEnv();
const git = new Git({ gitPath: info.path, version: info.version, env });
if (!workspaceRootPath || !enabled) {
const commandCenter = new CommandCenter(git, undefined, outputChannel, telemetryReporter);
disposables.push(commandCenter);
return;
}
const model = new Model(git, workspaceRootPath);
outputChannel.appendLine(localize('using git', "Using git {0} from {1}", info.version, info.path));
git.onOutput(str => outputChannel.append(str), null, disposables);
const commandCenter = new CommandCenter(git, model, outputChannel, telemetryReporter);
const statusBarCommands = new StatusBarCommands(model);
const provider = new GitSCMProvider(model, commandCenter, statusBarCommands);
const contentProvider = new GitContentProvider(model);
const autoFetcher = new AutoFetcher(model);
const mergeDecorator = new MergeDecorator(model);
disposables.push(
commandCenter,
provider,
contentProvider,
autoFetcher,
mergeDecorator,
model
);
await checkGitVersion(info);
}
export function activate(context: ExtensionContext): any {
const disposables: Disposable[] = [];
context.subscriptions.push(new Disposable(() => Disposable.from(...disposables).dispose()));
init(context, disposables)
.catch(err => console.error(err));
}
async function checkGitVersion(info: IGit): Promise<void> {
const config = workspace.getConfiguration('git');
const shouldIgnore = config.get<boolean>('ignoreLegacyWarning') === true;
if (shouldIgnore) {
return;
}
if (!/^[01]/.test(info.version)) {
return;
}
const update = localize('updateGit', "Update Git");
const neverShowAgain = localize('neverShowAgain', "Don't show again");
const choice = await window.showWarningMessage(
localize('git20', "You seem to have git {0} installed. Code works best with git >= 2", info.version),
update,
neverShowAgain
);
if (choice === update) {
commands.executeCommand('vscode.open', Uri.parse('https://git-scm.com/'));
} else if (choice === neverShowAgain) {
await config.update('ignoreLegacyWarning', true, true);
}
} | hashhar/vscode | extensions/git/src/main.ts | TypeScript | mit | 3,851 |
// Package git is a facade for git methods used by boilr
package git
import git "gopkg.in/src-d/go-git.v4"
// CloneOptions are used when cloning a git repository
type CloneOptions git.CloneOptions
// Clone clones a git repository with the given options
func Clone(dir string, opts CloneOptions) error {
o := git.CloneOptions(opts)
_, err := git.PlainClone(dir, false, &o)
return err
}
| Originate/exosphere | vendor/github.com/tmrts/boilr/pkg/util/git/git.go | GO | mit | 392 |
namespace VeloEventsManager.Data.Repositories
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
using VeloEventsManager.Models;
public class VeloEventsManagerData : IVeloEventsManagerData
{
private readonly DbContext context;
private readonly IDictionary<Type, object> repositories;
public VeloEventsManagerData()
{
this.context = new VeloEventsManagerDbContext();
this.repositories = new Dictionary<Type, object>();
}
public IRepository<Bike> Bikes
{
get
{
return this.GetRepository<Bike>();
}
}
public IRepository<EventDay> EventDays
{
get
{
return this.GetRepository<EventDay>();
}
}
public IRepository<Event> Events
{
get
{
return this.GetRepository<Event>();
}
}
public IRepository<Point> Points
{
get
{
return this.GetRepository<Point>();
}
}
public IRepository<Route> Routes
{
get
{
return this.GetRepository<Route>();
}
}
public IRepository<User> Users
{
get
{
return this.GetRepository<User>();
}
}
public int Savechanges()
{
return this.context.SaveChanges();
}
private IRepository<T> GetRepository<T>() where T : class
{
var typeOfRepository = typeof(T);
if (!this.repositories.ContainsKey(typeOfRepository))
{
var newRepository = Activator.CreateInstance(typeof(EfRepository<T>), this.context);
this.repositories.Add(typeOfRepository, newRepository);
}
return (IRepository<T>)this.repositories[typeOfRepository];
}
}
} | VeloMafia/VeloEventsManager | src/VeloEventsManager.Data/Repositories/VeloEventsManagerData.cs | C# | mit | 1,547 |
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <string>
#include "gin/handle.h"
#include "net/base/network_change_notifier.h"
#include "services/network/public/cpp/features.h"
#include "shell/browser/api/electron_api_url_loader.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/node_includes.h"
namespace {
bool IsOnline() {
return !net::NetworkChangeNotifier::IsOffline();
}
bool IsValidHeaderName(std::string header_name) {
return net::HttpUtil::IsValidHeaderName(header_name);
}
bool IsValidHeaderValue(std::string header_value) {
return net::HttpUtil::IsValidHeaderValue(header_value);
}
using electron::api::SimpleURLLoaderWrapper;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.SetMethod("isOnline", &IsOnline);
dict.SetMethod("isValidHeaderName", &IsValidHeaderName);
dict.SetMethod("isValidHeaderValue", &IsValidHeaderValue);
dict.SetMethod("createURLLoader", &SimpleURLLoaderWrapper::Create);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_net, Initialize)
| seanchas116/electron | shell/browser/api/electron_api_net.cc | C++ | mit | 1,420 |
{
"translatorID": "db0f4858-10fa-4f76-976c-2592c95f029c",
"label": "Internet Archive",
"creator": "Adam Crymble, Sebastian Karcher",
"target": "^https?://(www\\.)?archive\\.org/",
"minVersion": "3.0",
"maxVersion": "",
"priority": 100,
"inRepository": true,
"translatorType": 4,
"browserSupport": "gcsibv",
"lastUpdated": "2020-07-16 13:38:10"
}
/*
***** BEGIN LICENSE BLOCK *****
Mango Library Translator
Copyright © 2017 Adam Crymble and Sebastian Karcher
This file is part of Zotero.
Zotero is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Zotero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Zotero. If not, see <http://www.gnu.org/licenses/>.
***** END LICENSE BLOCK *****
*/
function detectWeb(doc, url) {
var icon = ZU.xpathText(doc, '//div[@class="left-icon"]/span[contains(@class, "iconochive")]/@class');
if (icon) {
if (icon.includes("texts")) {
return "book";
}
else if (icon.includes("movies")) {
return "film";
}
else if (icon.includes("audio")) {
return "audioRecording";
}
else if (icon.includes("etree")) {
return "audioRecording";
}
else if (icon.includes("software")) {
return "computerProgram";
}
else if (icon.includes("image")) {
return "artwork";
}
else if (icon.includes("tv")) {
return "tvBroadcast";
}
else {
Z.debug("Unknown Item Type: " + icon);
}
}
else if (url.includes('/stream/')) {
return "book";
}
else if (getSearchResults(doc, url, true)) {
return "multiple";
}
return false;
}
var typemap = {
texts: "book",
movies: "film",
image: "artwork",
audio: "audioRecording",
etree: "audioRecording",
software: "computerProgram"
};
function test(data) {
var clean = data ? data[0] : undefined;
return clean;
}
function getSearchResults(doc, checkOnly) {
var items = {};
var found = false;
var rows = ZU.xpath(doc, '//div[@class="results"]//div[contains(@class, "item-ttl")]//a[@href]');
for (var i = 0; i < rows.length; i++) {
var href = rows[i].href;
var title = ZU.trimInternal(rows[i].textContent);
if (!href || !title) continue;
if (checkOnly) return true;
found = true;
items[href] = title;
}
return found ? items : false;
}
function scrape(doc, url) {
// maximum PDF size to be downloaded. default to 10 MB
var prefMaxPdfSizeMB = 10;
var pdfurl = ZU.xpathText(doc, '//div[contains(@class, "thats-right")]/div/div/a[contains(text(), "PDF") and not(contains(text(), "B/W"))]/@href');
var pdfSize = ZU.xpathText(doc, '//div[contains(@class, "thats-right")]/div/div/a[contains(text(), "PDF") and not(contains(text(), "B/W"))]/@data-original-title');
var canonicalurl = ZU.xpathText(doc, '//link[@rel="canonical"]/@href');
var apiurl;
if (canonicalurl) {
apiurl = canonicalurl + "&output=json";
// alternative is
// var apiurl = url.replace('/details/', '/metadata/').replace('/stream/', '/metadata/');
}
else {
apiurl = url.replace('/stream/', '/details/').replace(/#.*$/, '') + "&output=json";
}
ZU.doGet(apiurl, function (text) {
try {
var obj = JSON.parse(text).metadata;
}
catch (e) {
Zotero.debug("JSON parse error");
throw e;
}
var type = obj.mediatype[0];
var itemType = typemap[type] || "document";
if (type == "movies" && obj.collection.includes("tvarchive")) {
itemType = "tvBroadcast";
}
var newItem = new Zotero.Item(itemType);
newItem.title = obj.title[0];
var creators = obj.creator;
var i;
if (creators) {
// sometimes authors are in one field delimiter by ;
if (creators && creators[0].match(/;/)) {
creators = creators[0].split(/\s*;\s*/);
}
for (i = 0; i < creators.length; i++) {
// authors are lastname, firstname, additional info - only use the first two.
var author = creators[i].replace(/(,[^,]+)(,.+)/, "$1");
if (author.includes(',')) {
newItem.creators.push(ZU.cleanAuthor(author, "author", true));
}
else {
newItem.creators.push({ lastName: author, creatorType: "author", fieldMode: 1 });
}
}
}
var contributors = obj.contributor;
if (contributors) {
for (i = 0; i < contributors.length; i++) {
// authors are lastname, firstname, additional info - only use the first two.
var contributor = contributors[i].replace(/(,[^,]+)(,.+)/, "$1");
if (contributor.includes(',')) {
newItem.creators.push(ZU.cleanAuthor(contributor, "contributor", true));
}
else {
newItem.creators.push({ lastName: contributor, creatorType: "contributor", fieldMode: 1 });
}
}
}
for (i = 0; i < newItem.creators.length; i++) {
if (!newItem.creators[i].firstName) {
newItem.creators[i].fieldMode = 1;
}
}
// abstracts can be in multiple fields;
if (obj.description) newItem.abstractNote = ZU.cleanTags(obj.description.join("; "));
var date = obj.date || obj.year;
var tags = test(obj.subject);
if (tags) {
tags = tags.split(/\s*;\s*/);
for (i = 0; i < tags.length; i++) {
newItem.tags.push(tags[i]);
}
}
// download PDFs; We're being conservative here, only downloading if we understand the filesize
if (pdfurl && pdfSize && parseFloat(pdfSize)) {
// calculate file size in MB
var pdfSizeMB;
if (pdfSize.includes("M")) {
pdfSizeMB = parseFloat(pdfSize);
}
else if (pdfSize.includes("K")) {
pdfSizeMB = parseFloat(pdfSize) / 1000;
}
else if (pdfSize.includes("G")) {
pdfSizeMB = parseFloat(pdfSize) * 1000;
}
Z.debug(pdfSizeMB);
if (pdfSizeMB < prefMaxPdfSizeMB) {
newItem.attachments.push({ url: pdfurl, title: "Internet Archive Fulltext PDF", mimeType: "application/pdf" });
}
}
newItem.date = test(date);
newItem.medium = test(obj.medium);
newItem.publisher = test(obj.publisher);
newItem.language = test(obj.language);
newItem.callNumber = test(obj.call_number);
newItem.numPages = test(obj.imagecount);
newItem.runningTime = test(obj.runtime);
newItem.rights = test(obj.licenseurl);
if (!newItem.rights) newItem.rights = test(obj.rights);
if (Array.isArray(obj.isbn) && obj.isbn.length > 0) newItem.ISBN = (obj.isbn).join(' ');
newItem.url = "http://archive.org/details/" + test(obj.identifier);
newItem.complete();
});
}
function doWeb(doc, url) {
if (detectWeb(doc, url) == "multiple") {
Zotero.selectItems(getSearchResults(doc, false), function (items) {
if (!items) {
return;
}
var articles = [];
for (var i in items) {
articles.push(i);
}
ZU.processDocuments(articles, scrape);
});
}
else {
scrape(doc, url);
}
}
/** BEGIN TEST CASES **/
var testCases = [
{
"type": "web",
"url": "https://archive.org/details/gullshornbookstu00dekk",
"items": [
{
"itemType": "book",
"title": "The gull's hornbook : Stultorum plena sunt omnia. Al savio mezza parola basta",
"creators": [
{
"firstName": "Thomas",
"lastName": "Dekker",
"creatorType": "author"
},
{
"firstName": "John",
"lastName": "Nott",
"creatorType": "author"
},
{
"lastName": "University of Pittsburgh Library System",
"creatorType": "contributor",
"fieldMode": 1
}
],
"date": "1812",
"abstractNote": "Notes by John Nott; Bibliography of Dekker: p. iii-ix",
"callNumber": "31735060398496",
"language": "eng",
"libraryCatalog": "Internet Archive",
"numPages": "228",
"publisher": "Bristol, Reprinted for J.M. Gutch and Sold in London by R. Baldwin, and R. Triphook",
"shortTitle": "The gull's hornbook",
"url": "http://archive.org/details/gullshornbookstu00dekk",
"tags": [],
"notes": [],
"seeAlso": [],
"attachments": []
}
]
},
{
"type": "web",
"url": "https://archive.org/details/darktowersdeutsc0000enri/mode/2up",
"items": [
{
"itemType":"book",
"creators":[
{
"firstName":"David",
"lastName":"Enrich",
"creatorType":"author"
},
{
"lastName":"Internet Archive",
"creatorType":"contributor",
"fieldMode": 1
}
],
"tags":[
{
"tag":"Trump, Donald, 1946-"
}
],
"title":"Dark towers : Deutsche Bank, Donald Trump, and an epic trail of destruction",
"abstractNote":"x, 402 pages ; 24 cm; \"A searing exposé by an award-winning journalist of the most scandalous bank in the world, including its shadowy ties to Donald Trump's business empire\"--; Includes bibliographical references (pages 367-390) and index; \"A searing expose by an award-winning journalist of the most scandalous bank in the world, including its shadowy ties to Donald Trump's business empire\"--",
"date":"2020",
"publisher":"New York, NY : Custom House",
"language":"eng",
"numPages":"426",
"ISBN":"9780062878816 9780062878830",
"url":"http://archive.org/details/darktowersdeutsc0000enri",
"libraryCatalog":"Internet Archive",
"shortTitle":"Dark towers",
"notes": [],
"seeAlso": [],
"attachments": []
}
]
},
{
"type": "web",
"url": "http://www.archive.org/search.php?query=cervantes%20AND%20mediatype%3Atexts",
"items": "multiple"
},
{
"type": "web",
"url": "http://archive.org/details/Allen_Ginsberg__Anne_Waldman__Steven_Tay_89P046",
"items": [
{
"itemType": "audioRecording",
"title": "Allen Ginsberg, Anne Waldman, Steven Taylor and Bobbi Louise Hawkins performance, July, 1989.",
"creators": [
{
"firstName": "Allen",
"lastName": "Ginsberg",
"creatorType": "author"
},
{
"firstName": "Bobbie Louise",
"lastName": "Hawkins",
"creatorType": "author"
},
{
"firstName": "Steven",
"lastName": "Taylor",
"creatorType": "author"
},
{
"firstName": "Anne",
"lastName": "Waldman",
"creatorType": "author"
}
],
"date": "1989-07-08 00:00:00",
"abstractNote": "Second half of a reading with Allen Ginsberg, Bobbie Louise Hawkins, Anne Waldman, and Steven Taylor. This portion of the reading features Waldman and Ginsberg. (Continued from 89P045)",
"accessDate": "CURRENT_TIMESTAMP",
"libraryCatalog": "Internet Archive",
"publisher": "Jack Kerouac School of Disembodied Poetics",
"rights": "http://creativecommons.org/licenses/by-nd-nc/1.0/",
"runningTime": "1:30:05",
"url": "http://archive.org/details/Allen_Ginsberg__Anne_Waldman__Steven_Tay_89P046",
"attachments": [],
"tags": [],
"notes": [],
"seeAlso": []
}
]
},
{
"type": "web",
"url": "http://archive.org/details/AboutBan1935",
"items": [
{
"itemType": "film",
"title": "About Bananas",
"creators": [
{
"lastName": "Castle Films",
"creatorType": "author",
"fieldMode": 1
}
],
"date": "1935",
"abstractNote": "Complete presentation of the banana industry from the clearing of the jungle and the planting to the shipment of the fruit to the American markets.",
"accessDate": "CURRENT_TIMESTAMP",
"libraryCatalog": "Internet Archive",
"rights": "http://creativecommons.org/licenses/publicdomain/",
"runningTime": "11:03",
"url": "http://archive.org/details/AboutBan1935",
"attachments": [],
"tags": [
"Agriculture: Bananas",
"Central America"
],
"notes": [],
"seeAlso": []
}
]
},
{
"type": "web",
"url": "https://archive.org/details/msdos_Oregon_Trail_The_1990",
"items": [
{
"itemType": "computerProgram",
"title": "Oregon Trail, The",
"creators": [
{
"lastName": "MECC",
"creatorType": "author",
"fieldMode": 1
}
],
"date": "1990",
"abstractNote": "Also For\nApple II, Macintosh, Windows, Windows 3.x\nDeveloped by\nMECC\nPublished by\nMECC\nReleased\n1990\n\n\nPacing\nReal-Time\nPerspective\nBird's-eye view, Side view, Text-based / Spreadsheet, Top-down\nEducational\nGeography, History\nGenre\nEducational, Simulation\nSetting\nWestern\nInterface\nText Parser\nGameplay\nManagerial / Business Simulation\nVisual\nFixed / Flip-screen\n\n\nDescription\n\nAs a covered wagon party of pioneers, you head out west from Independence, Missouri to the Willamette River and valley in Oregon. You first must stock up on provisions, and then, while traveling, make decisions such as when to rest, how much food to eat, etc. The Oregon Trail incorporates simulation elements and planning ahead, along with discovery and adventure, as well as mini-game-like activities (hunting and floating down the Dalles River).\n\nFrom Mobygames.com. Original Entry",
"libraryCatalog": "Internet Archive",
"url": "http://archive.org/details/msdos_Oregon_Trail_The_1990",
"attachments": [],
"tags": [],
"notes": [],
"seeAlso": []
}
]
},
{
"type": "web",
"url": "https://archive.org/details/mma_albert_einstein_pasadena_270713",
"items": [
{
"itemType": "artwork",
"title": "Albert Einstein, Pasadena",
"creators": [],
"date": "1931",
"artworkMedium": "Gelatin silver print",
"libraryCatalog": "Internet Archive",
"rights": "<a href=\"http://www.metmuseum.org/information/terms-and-conditions\" rel=\"nofollow\">Metropolitan Museum of Art Terms and Conditions</a>",
"url": "http://archive.org/details/mma_albert_einstein_pasadena_270713",
"attachments": [],
"tags": [
"Photographs"
],
"notes": [],
"seeAlso": []
}
]
},
{
"type": "web",
"url": "https://archive.org/stream/siopsecretusplan0000prin#page/n85/mode/2up",
"items": [
{
"itemType": "book",
"title": "SIOP, the secret U.S. plan for nuclear war",
"creators": [
{
"firstName": "Peter",
"lastName": "Pringle",
"creatorType": "author"
},
{
"lastName": "Internet Archive",
"creatorType": "contributor",
"fieldMode": 1
}
],
"date": "1983",
"abstractNote": "Bibliography: p. 263-277; Includes index",
"language": "eng",
"libraryCatalog": "Internet Archive",
"numPages": "298",
"publisher": "New York : Norton",
"url": "http://archive.org/details/siopsecretusplan0000prin",
"attachments": [],
"tags": [
"Nuclear warfare"
],
"notes": [],
"seeAlso": [],
"ISBN": "9780393017984"
}
]
},
{
"type": "web",
"url": "https://archive.org/details/MSNBCW_20170114_020000_The_Rachel_Maddow_Show/start/60/end/120",
"items": [
{
"itemType": "tvBroadcast",
"title": "The Rachel Maddow Show : MSNBCW : January 13, 2017 6:00pm-7:01pm PST",
"creators": [
{
"lastName": "MSNBCW",
"creatorType": "contributor",
"fieldMode": 1
}
],
"date": "2017-01-14",
"abstractNote": "Rachel Maddow takes a look at the day's top political news stories.",
"language": "eng",
"libraryCatalog": "Internet Archive",
"runningTime": "01:01:00",
"shortTitle": "The Rachel Maddow Show",
"url": "http://archive.org/details/MSNBCW_20170114_020000_The_Rachel_Maddow_Show",
"attachments": [],
"tags": [
"amd",
"atlas",
"backups",
"bernie sanders",
"breo",
"britain",
"charleston",
"chuck schumer",
"chuck todd",
"cialis",
"clinton",
"comcast business",
"directv",
"donald trump",
"donald trump jr.",
"downy fabric conditioner",
"fbi",
"geico",
"james comey",
"john lewis",
"london",
"michael beschloss",
"moscow",
"nancy pelosi",
"nbc news",
"obama",
"oregon",
"osteo bi-flex",
"rachel",
"rachel maddow",
"richard nixon",
"russia",
"south carolina",
"south carolina",
"titan atlas",
"washington",
"waterloo"
],
"notes": [],
"seeAlso": []
}
]
}
]
/** END TEST CASES **/
| retorquere/zotero-better-bibtex | test/fixtures/profile/zotero/zotero/translators/Internet Archive.js | JavaScript | mit | 16,222 |
#include <algorithm>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
int weight[1050];
bool Connect[1050][1050];
struct Rope {
int id, v;
bool operator<(const Rope &x) const { return v > x.v; }
} in;
vector<Rope> data;
int main() {
int n, m, a, b, temper;
long long ans = 0;
memset(Connect, false, sizeof(Connect));
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
in.id = i;
cin >> in.v;
weight[i] = in.v;
::data.push_back(in);
}
for (int i = 1; i <= m; ++i) {
cin >> a >> b;
Connect[a][b] = Connect[b][a] = true;
}
sort(::data.begin(), ::data.end());
for (int i = 0; i < ::data.size(); ++i) {
temper = ::data[i].id;
for (int ii = 1; ii <= n; ++ii) {
if (Connect[temper][ii] == true) {
ans += weight[ii];
Connect[temper][ii] = Connect[ii][temper] = false;
}
}
}
cout << ans << endl;
} | NutshellySima/playground | acm-SCUT/2017/CF-437C.cpp | C++ | mit | 904 |
'use strict';
/* https://github.com/angular/protractor/blob/master/docs/toc.md */
describe('my app', function() {
it('should automatically redirect to /restaurantList when location hash/fragment is empty', function() {
browser.get('index.html');
expect(browser.getLocationAbsUrl()).toMatch("/restaurantList");
});
describe('restaurantList', function() {
beforeEach(function() {
browser.get('index.html#/restaurantList');
});
it('should render restaurantList when user navigates to /restaurantList', function() {
expect(element.all(by.css('[ng-view] p')).first().getText()).
toMatch(/partial for view 1/);
});
});
describe('timer', function() {
beforeEach(function() {
browser.get('index.html#/timer');
});
it('should render timer when user navigates to /timer', function() {
expect(element.all(by.css('[ng-view] p')).first().getText()).
toMatch(/partial for view 2/);
});
});
describe('restaurantAdd', function() {
beforeEach(function() {
browser.get('index.html#/restaurantAdd');
});
it('should render restaurantAdd when user navigates to /restaurantAdd', function() {
expect(element.all(by.css('[ng-view] p')).first().getText()).
toMatch(/partial for view 3/);
});
});
});
| kajas90/foodBoard | e2e-tests/scenarios.js | JavaScript | mit | 1,329 |
# verify ruby dependency
verify_ruby 'Memcached - Ruby Plugin'
# check required attributes
verify_attributes do
attributes [
'node[:newrelic][:license_key]',
'node[:newrelic][:memcached_ruby][:install_path]',
'node[:newrelic][:memcached_ruby][:user]'
]
end
verify_license_key node[:newrelic][:license_key]
install_plugin 'newrelic_memcached_ruby_plugin' do
plugin_version node[:newrelic][:memcached_ruby][:version]
install_path node[:newrelic][:memcached_ruby][:install_path]
plugin_path node[:newrelic][:memcached_ruby][:plugin_path]
download_url node[:newrelic][:memcached_ruby][:download_url]
user node[:newrelic][:memcached_ruby][:user]
end
# newrelic template
template "#{node[:newrelic][:memcached_ruby][:plugin_path]}/config/newrelic_plugin.yml" do
source 'memcached_ruby/newrelic_plugin.yml.erb'
action :create
owner node[:newrelic][:memcached_ruby][:user]
notifies :restart, 'service[newrelic-memcached-ruby-plugin]'
end
# install bundler gem and run 'bundle install'
bundle_install do
path node[:newrelic][:memcached_ruby][:plugin_path]
user node[:newrelic][:memcached_ruby][:user]
end
# install init.d script and start service
plugin_service 'newrelic-memcached-ruby-plugin' do
daemon './newrelic_memcached_agent'
daemon_dir node[:newrelic][:memcached_ruby][:plugin_path]
plugin_name 'Memcached - Ruby'
plugin_version node[:newrelic][:memcached_ruby][:version]
user node[:newrelic][:memcached_ruby][:user]
run_command 'bundle exec'
end
| yinzara/newrelic_plugins_chef | recipes/memcached_ruby.rb | Ruby | mit | 1,566 |
/*
* This is part of the fl library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2015 Max Planck Society,
* Autonomous Motion Department,
* Institute for Intelligent Systems
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file sampling.hpp
* \date May 2014
* \author Jan Issac (jan.issac@gmail.com)
* \author Manuel Wuthrich (manuel.wuthrich@gmail.com)
*/
#pragma once
namespace fl
{
/**
* \ingroup distribution_interfaces
*
* \brief Distribution sampling interface
*
* \tparam Variate Variate type of the random variable
*/
template <typename Variate>
class Sampling
{
public:
/**
* \brief Overridable default destructor
*/
virtual ~Sampling() noexcept { }
/**
* \return A random sample of the underlying distribution \f[x \sim p(x)\f]
*/
virtual Variate sample() const = 0;
};
}
| filtering-library/fl | include/fl/distribution/interface/sampling.hpp | C++ | mit | 1,040 |
"""
Carry a Cheese
"""
if __name__ == '__main__':
while True:
x = sorted(map(int, raw_input().split()))
if sum(x) == 0:
break
n = int(raw_input())
r = [int(raw_input()) for _ in xrange(n)]
for i in xrange(n):
if (2 * r[i]) ** 2 > x[0] ** 2 + x[1] ** 2:
print "OK"
else:
print "NA"
| miyazaki-tm/aoj | Volume1/0107.py | Python | mit | 397 |
#ifndef DEMANGLER_HPP__
#define DEMANGLER_HPP__
#include <cxxabi.h>
#include <memory>
#include <string>
class Demangler
{
public:
inline std::string demangle(const char* name) {
int status = -1;
std::unique_ptr<char, void(*)(void*)> res { abi::__cxa_demangle(name, NULL, NULL, &status), std::free };
return (status == 0) ? res.get() : std::string(name);
}
inline std::string demangle(const std::string name) {
return demangle(name.c_str());
}
};
#endif /* DEMANGLER_HPP__ */
| plast-lab/llvm-datalog | tools/fact-generator/include/Demangler.hpp | C++ | mit | 531 |
#encoding=utf-8
from __future__ import unicode_literals
import sys
sys.path.append("../")
import jieba
seg_list = jieba.cut("我来到北京清华大学", cut_all=True)
print("Full Mode: " + "/ ".join(seg_list)) # 全模式
seg_list = jieba.cut("我来到北京清华大学", cut_all=False)
print("Default Mode: " + "/ ".join(seg_list)) # 默认模式
seg_list = jieba.cut("他来到了网易杭研大厦")
print(", ".join(seg_list))
seg_list = jieba.cut_for_search("小明硕士毕业于中国科学院计算所,后在日本京都大学深造") # 搜索引擎模式
print(", ".join(seg_list))
| Yinzo/jieba | test/demo.py | Python | mit | 604 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("8. TrapezoidArea")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("8. TrapezoidArea")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6207011b-4760-4686-bd82-46a5b7b36ccc")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| kaizer04/Telerik-Academy-2013-2014 | C#1/Operators-and-Expressions-Homework/8. TrapezoidArea/Properties/AssemblyInfo.cs | C# | mit | 1,408 |
# frozen-string-literal: true
#
class Roda
module RodaPlugins
# The param_matchers plugin adds hash matchers that operate
# on the request's params.
#
# It adds a :param matcher for matching on any param with the
# same name, yielding the value of the param:
#
# r.on param: 'foo' do |foo|
# # Matches '?foo=bar', '?foo='
# # Doesn't match '?bar=foo'
# end
#
# It adds a :param! matcher for matching on any non-empty param
# with the same name, yielding the value of the param:
#
# r.on(param!: 'foo') do |foo|
# # Matches '?foo=bar'
# # Doesn't match '?foo=', '?bar=foo'
# end
#
# It also adds :params and :params! matchers, for matching multiple
# params at the same time:
#
# r.on params: ['foo', 'baz'] do |foo, baz|
# # Matches '?foo=bar&baz=quuz', '?foo=&baz='
# # Doesn't match '?foo=bar', '?baz='
# end
#
# r.on params!: ['foo', 'baz'] do |foo, baz|
# # Matches '?foo=bar&baz=quuz'
# # Doesn't match '?foo=bar', '?baz=', '?foo=&baz=', '?foo=bar&baz='
# end
#
# Because users have some control over the types of submitted parameters,
# it is recommended that you explicitly force the correct type for values
# yielded by the block:
#
# r.get(:param=>'foo') do |foo|
# foo = foo.to_s
# end
module ParamMatchers
module RequestMethods
# Match the given parameter if present, even if the parameter is empty.
# Adds match to the captures.
def match_param(key)
if v = params[key.to_s]
@captures << v
end
end
# Match the given parameter if present and not empty.
# Adds match to the captures.
def match_param!(key)
if (v = params[key.to_s]) && !v.empty?
@captures << v
end
end
# Match all given parameters if present, even if any/all parameters is empty.
# Adds all matches to the captures.
def match_params(keys)
keys.each do |key|
return false unless match_param(key)
end
end
# Match all given parameters if present and not empty.
# Adds all matches to the captures.
def match_params!(keys)
keys.each do |key|
return false unless match_param!(key)
end
end
end
end
register_plugin(:param_matchers, ParamMatchers)
end
end
| celsworth/roda | lib/roda/plugins/param_matchers.rb | Ruby | mit | 2,523 |
module.exports = function array_intersect_ukey (arr1) { // eslint-disable-line camelcase
// discuss at: https://locutus.io/php/array_intersect_ukey/
// original by: Brett Zamir (https://brett-zamir.me)
// example 1: var $array1 = {blue: 1, red: 2, green: 3, purple: 4}
// example 1: var $array2 = {green: 5, blue: 6, yellow: 7, cyan: 8}
// example 1: array_intersect_ukey ($array1, $array2, function (key1, key2){ return (key1 === key2 ? 0 : (key1 > key2 ? 1 : -1)); })
// returns 1: {blue: 1, green: 3}
var retArr = {}
var arglm1 = arguments.length - 1
var arglm2 = arglm1 - 1
var cb = arguments[arglm1]
// var cb0 = arguments[arglm2]
var k1 = ''
var i = 1
var k = ''
var arr = {}
var $global = (typeof window !== 'undefined' ? window : global)
cb = (typeof cb === 'string')
? $global[cb]
: (Object.prototype.toString.call(cb) === '[object Array]')
? $global[cb[0]][cb[1]]
: cb
// cb0 = (typeof cb0 === 'string')
// ? $global[cb0]
// : (Object.prototype.toString.call(cb0) === '[object Array]')
// ? $global[cb0[0]][cb0[1]]
// : cb0
arr1keys: for (k1 in arr1) { // eslint-disable-line no-labels
arrs: for (i = 1; i < arglm1; i++) { // eslint-disable-line no-labels
arr = arguments[i]
for (k in arr) {
if (cb(k, k1) === 0) {
if (i === arglm2) {
retArr[k1] = arr1[k1]
}
// If the innermost loop always leads at least once to an equal value,
// continue the loop until done
continue arrs // eslint-disable-line no-labels
}
}
// If it reaches here, it wasn't found in at least one array, so try next value
continue arr1keys // eslint-disable-line no-labels
}
}
return retArr
}
| kvz/phpjs | src/php/array/array_intersect_ukey.js | JavaScript | mit | 1,787 |
<?php
/**
* Copyright (c) UNA, Inc - https://una.io
* MIT License - https://opensource.org/licenses/MIT
*
* @defgroup Persons Persons
* @ingroup UnaModules
*
* @{
*/
$aConfig = array(
/**
* Main Section.
*/
'type' => BX_DOL_MODULE_TYPE_MODULE,
'name' => 'bx_persons',
'title' => 'Persons',
'note' => 'Basic person profiles functionality.',
'version' => '9.0.11',
'vendor' => 'BoonEx',
'help_url' => 'http://feed.una.io/?section={module_name}',
'compatible_with' => array(
'9.0.0-RC12'
),
/**
* 'home_dir' and 'home_uri' - should be unique. Don't use spaces in 'home_uri' and the other special chars.
*/
'home_dir' => 'boonex/persons/',
'home_uri' => 'persons',
'db_prefix' => 'bx_persons_',
'class_prefix' => 'BxPersons',
/**
* Category for language keys.
*/
'language_category' => 'Persons',
/**
* Connections.
*/
'connections' => array(
'sys_profiles_friends' => array ('type' => 'profiles'),
'sys_profiles_subscriptions' => array ('type' => 'profiles'),
),
/**
* Menu triggers.
*/
'menu_triggers' => array(
'trigger_profile_view_submenu',
'trigger_profile_snippet_meta',
'trigger_profile_view_actions',
),
/**
* Page triggers.
*/
'page_triggers' => array (
'trigger_page_profile_view_entry',
),
/**
* Storage objects to automatically delete files from upon module uninstallation.
* Note. Don't add storage objects used in transcoder objects.
*/
'storages' => array(
'bx_persons_pictures'
),
/**
* Transcoders.
*/
'transcoders' => array(
'bx_persons_icon',
'bx_persons_thumb',
'bx_persons_avatar',
'bx_persons_picture',
'bx_persons_cover',
'bx_persons_cover_thumb',
'bx_persons_gallery'
),
/**
* Extended Search Forms.
*/
'esearches' => array(
'bx_persons',
'bx_persons_cmts',
),
/**
* Installation/Uninstallation Section.
*/
'install' => array(
'execute_sql' => 1,
'update_languages' => 1,
'clear_db_cache' => 1,
),
'uninstall' => array (
'process_esearches' => 1,
'execute_sql' => 1,
'update_languages' => 1,
'process_connections' => 1,
'process_deleted_profiles' => 1,
'update_relations' => 1,
'clear_db_cache' => 1,
),
'enable' => array(
'execute_sql' => 1,
'update_relations' => 1,
'clear_db_cache' => 1,
),
'enable_success' => array(
'process_menu_triggers' => 1,
'process_page_triggers' => 1,
'process_esearches' => 1,
'register_transcoders' => 1,
'clear_db_cache' => 1,
),
'disable' => array (
'execute_sql' => 1,
'unregister_transcoders' => 1,
'update_relations' => 1,
'clear_db_cache' => 1,
),
'disable_failed' => array (
'register_transcoders' => 1,
'clear_db_cache' => 1,
),
/**
* Dependencies Section
*/
'dependencies' => array(),
/**
* Connections Section
*/
'relations' => array(
'bx_timeline',
'bx_notifications',
),
);
/** @} */
| unaio/una | modules/boonex/persons/updates/9.0.10_9.0.11/source/install/config.php | PHP | mit | 3,262 |
class Api::V1::RecordController < Api::V1::BaseController
before_filter :authenticate_user!
def index
respond_with(Record.all)
end
def show
@data = Record.find(params[:id]).to_json()
respond_with(@data)
end
def update
@data = Record.find(params[:id])
respond_to do |format|
if @data.update_attributes(record_params)
format.json { head :no_content }
else
format.json { render json: @data.errors, status: :unprocessable_entity }
end
end
end
def create
@data = Record.create(record_params)
@data.save
respond_with(@data)
end
def destroy
@data = Record.find(params[:id])
@data.destroy
respond_to do |format|
format.json { head :ok }
end
end
private
def record_params
params.require(:record).permit(:secure)
end
end
| jesalg/RADD | app/controllers/api/v1/record_controller.rb | Ruby | mit | 845 |
const detachHook = require('../sugar').detachHook;
const dropCache = require('../sugar').dropCache;
suite('api/camelCase', () => {
suite('-> `true`', () => {
test('should add camel case keys in token', () => {
const tokens = require('./fixture/bem.css');
assert.deepEqual(tokens, {
blockElementModifier: '_test_api_fixture_bem__block__element--modifier',
'block__element--modifier': '_test_api_fixture_bem__block__element--modifier',
});
});
setup(() => hook({ camelCase: true }));
teardown(() => {
detachHook('.css');
dropCache('./api/fixture/bem.css');
});
});
suite('-> `dashesOnly`', () => {
test('should replace keys with dashes by its camel-cased equivalent', () => {
const tokens = require('./fixture/bem.css');
assert.deepEqual(tokens, {
'block__elementModifier': '_test_api_fixture_bem__block__element--modifier',
});
});
setup(() => hook({camelCase: 'dashesOnly'}));
teardown(() => {
detachHook('.css');
dropCache('./api/fixture/bem.css');
});
});
});
| css-modules/css-modules-require-hook | test/api/camelCase.js | JavaScript | mit | 1,100 |
# Copyright 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.
from os import path, chdir, getcwd
from cement.utils.misc import minimal_logger
from ..core import io, hooks, fileoperations
from ..core.abstractcontroller import AbstractBaseController
from ..lib import utils
from ..objects.exceptions import NoEnvironmentForBranchError, \
InvalidOptionsError
from ..operations import commonops, deployops, composeops
from ..resources.strings import strings, flag_text
LOG = minimal_logger(__name__)
class DeployController(AbstractBaseController):
class Meta(AbstractBaseController.Meta):
label = 'deploy'
description = strings['deploy.info']
arguments = [
(['environment_name'], dict(
action='store', nargs='?', default=[],
help=flag_text['deploy.env'])),
(['--modules'], dict(help=flag_text['deploy.modules'], nargs='*')),
(['-g', '--env-group-suffix'], dict(help=flag_text['deploy.group_suffix'])),
(['--version'], dict(help=flag_text['deploy.version'])),
(['-l', '--label'], dict(help=flag_text['deploy.label'])),
(['-m', '--message'], dict(help=flag_text['deploy.message'])),
(['-nh', '--nohang'], dict(
action='store_true', help=flag_text['deploy.nohang'])),
(['--staged'], dict(
action='store_true', help=flag_text['deploy.staged'])),
(['--timeout'], dict(type=int, help=flag_text['general.timeout'])),
(['--source'], dict(type=utils.check_source, help=flag_text['deploy.source'])),
]
usage = AbstractBaseController.Meta.usage.replace('{cmd}', label)
def do_command(self):
self.message = self.app.pargs.message
self.staged = self.app.pargs.staged
self.timeout = self.app.pargs.timeout
self.nohang = self.app.pargs.nohang
self.modules = self.app.pargs.modules
self.source = self.app.pargs.source
self.app_name = self.get_app_name()
self.env_name = self.app.pargs.environment_name
self.version = self.app.pargs.version
self.label = self.app.pargs.label
group_name = self.app.pargs.env_group_suffix
if self.modules and len(self.modules) > 0:
self.multiple_app_deploy()
return
if self.nohang:
self.timeout = 0
if self.version and (self.message or self.label):
raise InvalidOptionsError(strings['deploy.invalidoptions'])
if not self.env_name:
self.env_name = commonops.get_current_branch_environment()
if not self.env_name:
self.message = strings['branch.noenv'].replace('eb {cmd}',
self.Meta.label)
io.log_error(self.message)
raise NoEnvironmentForBranchError()
# ToDo add support for deploying to multiples?
# for arg in self.app.pargs.environment_name:
# # deploy to every environment listed
# ## Right now you can only list one
process_app_versions = fileoperations.env_yaml_exists()
deployops.deploy(self.app_name, self.env_name, self.version, self.label,
self.message, group_name=group_name, process_app_versions=process_app_versions,
staged=self.staged, timeout=self.timeout, source=self.source)
def complete_command(self, commands):
# TODO: edit this if we ever support multiple env deploys
super(DeployController, self).complete_command(commands)
## versionlabels on --version
cmd = commands[-1]
if cmd in ['--version']:
app_name = fileoperations.get_application_name()
io.echo(*commonops.get_app_version_labels(app_name))
def multiple_app_deploy(self):
missing_env_yaml = []
top_dir = getcwd()
for module in self.modules:
if not path.isdir(path.join(top_dir, module)):
continue
chdir(path.join(top_dir, module))
if not fileoperations.env_yaml_exists():
missing_env_yaml.append(module)
chdir(top_dir)
# We currently do not want to support multiple deploys when some of the
# modules do not contain env.yaml files
if len(missing_env_yaml) > 0:
module_list = ''
for module_name in missing_env_yaml:
module_list = module_list + module_name + ', '
io.echo(strings['deploy.modulemissingenvyaml'].replace('{modules}', module_list[:-2]))
return
self.compose_deploy()
return
def compose_deploy(self):
app_name = None
modules = self.app.pargs.modules
group_name = self.app.pargs.env_group_suffix
env_names = []
stages_version_labels = {}
stages_env_names = {}
top_dir = getcwd()
for module in modules:
if not path.isdir(path.join(top_dir, module)):
io.log_error(strings['deploy.notadirectory'].replace('{module}', module))
continue
chdir(path.join(top_dir, module))
if not group_name:
group_name = commonops.get_current_branch_group_suffix()
if group_name not in stages_version_labels.keys():
stages_version_labels[group_name] = []
stages_env_names[group_name] = []
if not app_name:
app_name = self.get_app_name()
io.echo('--- Creating application version for module: {0} ---'.format(module))
# Re-run hooks to get values from .elasticbeanstalk folders of apps
hooks.set_region(None)
hooks.set_ssl(None)
hooks.set_profile(None)
if not app_name:
app_name = self.get_app_name()
process_app_version = fileoperations.env_yaml_exists()
version_label = commonops.create_app_version(app_name, process=process_app_version)
stages_version_labels[group_name].append(version_label)
environment_name = fileoperations.get_env_name_from_env_yaml()
if environment_name is not None:
commonops.set_environment_for_current_branch(environment_name.
replace('+', '-{0}'.
format(group_name)))
env_name = commonops.get_current_branch_environment()
stages_env_names[group_name].append(env_name)
env_names.append(env_name)
else:
io.echo(strings['deploy.noenvname'].replace('{module}', module))
stages_version_labels[group_name].pop(version_label)
chdir(top_dir)
if len(stages_version_labels) > 0:
for stage in stages_version_labels.keys():
request_id = composeops.compose_no_events(app_name, stages_version_labels[stage],
group_name=stage)
if request_id is None:
io.error("Unable to compose modules.")
return
commonops.wait_for_compose_events(request_id, app_name, env_names, self.timeout)
else:
io.log_warning(strings['compose.novalidmodules']) | AccelAI/accel.ai | flask-aws/lib/python2.7/site-packages/ebcli/controllers/deploy.py | Python | mit | 7,976 |
using WebWeChat.Im.Core;
using WebWeChat.Im.Service.Interface;
namespace WebWeChat.Im.Module.Interface
{
/// <summary>
/// 模块功能接口
/// </summary>
public interface IWeChatModule : IWeChatService
{
}
}
| huoshan12345/WebQQWeChat | src/WebWeChat/Im/Module/Interface/IWeChatModule.cs | C# | mit | 239 |
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
Bundler.require
require "doccex"
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
end
end
| gagoit/doccex | spec/dummy/config/application.rb | Ruby | mit | 1,999 |
#!/usr/bin/env python
import time
import sys
import logging
from socketIO_client import SocketIO
APPKEY = '5697113d4407a3cd028abead'
TOPIC = 'test'
ALIAS = 'test'
logger = logging.getLogger('messenger')
class Messenger:
def __init__(self, appkey, alias, customid):
self.__logger = logging.getLogger('messenger.Messenger')
self.__logger.info('init')
self.appkey = appkey
self.customid = customid
self.alias = alias
self.socketIO = SocketIO('sock.yunba.io', 3000)
self.socketIO.on('socketconnectack', self.on_socket_connect_ack)
self.socketIO.on('connack', self.on_connack)
self.socketIO.on('puback', self.on_puback)
self.socketIO.on('suback', self.on_suback)
self.socketIO.on('message', self.on_message)
self.socketIO.on('set_alias_ack', self.on_set_alias)
self.socketIO.on('get_topic_list_ack', self.on_get_topic_list_ack)
self.socketIO.on('get_alias_list_ack', self.on_get_alias_list_ack)
# self.socketIO.on('puback', self.on_publish2_ack)
self.socketIO.on('recvack', self.on_publish2_recvack)
self.socketIO.on('get_state_ack', self.on_get_state_ack)
self.socketIO.on('alias', self.on_alias)
def __del__(self):
self.__logger.info('del')
def loop(self):
self.socketIO.wait(seconds=0.002)
def on_socket_connect_ack(self, args):
self.__logger.debug('on_socket_connect_ack: %s', args)
self.socketIO.emit('connect', {'appkey': self.appkey, 'customid': self.customid})
def on_connack(self, args):
self.__logger.debug('on_connack: %s', args)
self.socketIO.emit('set_alias', {'alias': self.alias})
def on_puback(self, args):
self.__logger.debug('on_puback: %s', args)
def on_suback(self, args):
self.__logger.debug('on_suback: %s', args)
def on_message(self, args):
self.__logger.debug('on_message: %s', args)
def on_set_alias(self, args):
self.__logger.debug('on_set_alias: %s', args)
def on_get_alias(self, args):
self.__logger.debug('on_get_alias: %s', args)
def on_alias(self, args):
self.__logger.debug('on_alias: %s', args)
def on_get_topic_list_ack(self, args):
self.__logger.debug('on_get_topic_list_ack: %s', args)
def on_get_alias_list_ack(self, args):
self.__logger.debug('on_get_alias_list_ack: %s', args)
def on_publish2_ack(self, args):
self.__logger.debug('on_publish2_ack: %s', args)
def on_publish2_recvack(self, args):
self.__logger.debug('on_publish2_recvack: %s', args)
def on_get_state_ack(self, args):
self.__logger.debug('on_get_state_ack: %s', args)
def publish(self, msg, topic, qos):
self.__logger.debug('publish: %s', msg)
self.socketIO.emit('publish', {'topic': topic, 'msg': msg, 'qos': qos})
def publish_to_alias(self, alias, msg):
self.__logger.debug('publish_to_alias: %s %s', alias, msg)
self.socketIO.emit('publish_to_alias', {'alias': alias, 'msg': msg})
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
m = Messenger(APPKEY, ALIAS, ALIAS);
while True:
m.loop()
time.sleep(0.02)
| yunbademo/yunba-smartoffice | python/messenger.py | Python | mit | 3,266 |
<?php
require_once __DIR__ . '/Context.php';
class Main {
private $context;
public function __construct() {
$this->context = new Context();
}
// Parameters:
// - $baseUrl: E.g. 'http://localhost/slim-wiki/?edit'
// - $basePath: E.g. '/slim-wiki/'
// - $requestPathArray: E.g. array('myfolder', 'mypage')
// - $requestQuery: E.g. 'edit'
public function dispatch($baseUrl, $basePath, $requestPathArray, $requestQuery) {
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$this->handlePost($requestPathArray);
} else {
$this->handleGet($baseUrl, $basePath, $requestPathArray, $requestQuery);
}
}
private function handlePost($requestPathArray) {
if (count($requestPathArray) == 2 && $requestPathArray[0] == 'rpc') {
$requestData = json_decode(file_get_contents('php://input'), true);
$objectName = $requestPathArray[1];
$object = null;
if ($objectName == 'editor') {
$object = $this->context->getEditorService();
}
$responseData = array(
'jsonrpc' => '2.0',
'id' => $requestData['id']
);
if ($object == null) {
$responseData['error'] = array( 'code' => -32601, 'message' => "Object not found: $objectName" );
} else {
$methodName = $requestData['method'];
if (! $object->isRpcMethod($methodName)) {
$responseData['error'] = array( 'code' => -32601, 'message' => "Method not found or not public: $objectName.$methodName" );
} else {
try {
$responseData['result'] = call_user_func_array(array($object, $methodName), $requestData['params']);
} catch (Exception $exc) {
if ($exc->getMessage() == 'Not logged in') {
$this->setUnauthorizedHeaders();
}
$msg = "Calling RPC $objectName.$methodName failed: " . $exc->getMessage();
error_log($msg);
$responseData['error'] = array( 'code' => -32000, 'message' => $msg );
}
}
}
header('Content-Type: application/json');
echo json_encode($responseData);
} else {
header('HTTP/1.0 404 Not Found');
}
}
private function handleGet($baseUrl, $basePath, $requestPathArray, $requestQuery) {
$config = $this->context->getConfig();
$showCreateUserButton = false;
if ($requestQuery == 'edit' || $requestQuery == 'createUser') {
$mode = $requestQuery;
$showCreateUserButton = ($mode == 'edit');
} else {
$mode = 'view';
$showCreateUserButton = ! $this->isUserDefined();
}
if ($mode == 'edit' && ! $config['demoMode']) {
$loginState = $this->context->getEditorService()->getLoginState();
if ($loginState != 'logged-in') {
$this->setUnauthorizedHeaders();
$mode = 'view';
$showCreateUserButton = true;
}
}
$articleFilename = $this->getArticleFilename($requestPathArray);
if ($articleFilename == null) {
header('HTTP/1.0 403 Forbidden');
header('Content-Type:text/html; charset=utf-8');
echo '<h1>Forbidden</h1>';
} else {
$renderService = $this->context->getRenderService();
$fatalErrorMessage = null;
if ($mode == 'view') {
if (! $renderService->articleExists($articleFilename)) {
$mode = 'noSuchArticle';
}
} else if ($mode == 'edit') {
$editorService = $this->context->getEditorService();
$fatalErrorMessage = $editorService->checkForError($articleFilename);
if ($fatalErrorMessage != null) {
$fatalErrorMessage = $this->context->getI18n()['error.editingArticleFailed'] . '<br/>' . $fatalErrorMessage;
$mode = 'error';
} else if (! $renderService->articleExists($articleFilename) && ! $config['demoMode']) {
$mode = 'createArticle';
$showCreateUserButton = false;
}
}
$data = array();
$data['baseUrl'] = $baseUrl;
$data['basePath'] = $basePath;
$data['mode'] = $mode;
$data['fatalErrorMessage'] = $fatalErrorMessage;
foreach (array('wikiName', 'theme', 'demoMode', 'showToc', 'footerHtml') as $key) {
if (isset($config[$key])) {
$data[$key] = $config[$key];
}
}
$data['breadcrumbs'] = $this->createBreadcrumbs($requestPathArray);
$data['showCreateUserButton'] = $showCreateUserButton;
$data['requestPath'] = implode('/', $requestPathArray);
$data['articleFilename'] = $articleFilename;
if ($mode == 'view' || $mode == 'edit') {
if ($renderService->articleExists($articleFilename)) {
$articleMarkdown = file_get_contents($this->context->getArticleBaseDir() . $articleFilename);
} else if ($config['demoMode']) {
// Open a fake "new article" for demo mode
// We have no real page title here -> Create one from the file name
$lastPathPart = end($requestPathArray);
if ($lastPathPart == '') {
// This is the `index.md` of a directory -> Use the directory name
$lastPathPart = prev($requestPathArray);
}
$pageTitle = str_replace('_', ' ', $lastPathPart);
$editorService = $this->context->getEditorService();
$articleMarkdown = $editorService->getNewArticleMarkdown($pageTitle);
}
$data['articleMarkdown'] = $articleMarkdown;
$data['articleHtml'] = $renderService->renderMarkdown($articleMarkdown, $mode == 'edit');
}
$this->renderPage($data);
}
}
private function setUnauthorizedHeaders() {
$wikiName = $this->context->getConfig()['wikiName'];
header('WWW-Authenticate: Basic realm="'.$wikiName.'"');
header('HTTP/1.0 401 Unauthorized');
}
private function isUserDefined() {
$config = $this->context->getConfig();
foreach ($config as $key => $value) {
if (strpos($key, 'user.') === 0) {
return true;
}
}
return false;
}
private function getArticleFilename($requestPathArray) {
$articleBaseDir = $this->context->getArticleBaseDir();
$articleFilename = implode('/', $requestPathArray);
// Support `index.md` for directories
if (is_dir($articleBaseDir . $articleFilename) || substr($articleFilename, -1) == '/') {
$articleFilename = rtrim($articleFilename, '/') . '/index.md';
}
// Make the extension `.md` optional
if (! file_exists($articleBaseDir . $articleFilename) && file_exists($articleBaseDir . $articleFilename . '.md')) {
$articleFilename .= '.md';
}
$articleFullFilename = $articleBaseDir . $articleFilename;
if (! $this->context->isValidArticleFilename($articleFilename)) {
// Attempt to break out of article base directory (e.g. `../../outside.ext`)
return null;
} else {
return $articleFilename;
}
}
private function createBreadcrumbs($requestPathArray) {
$config = $this->context->getConfig();
$wikiName = $config['wikiName'];
$showCompleteBreadcrumbs = $config['showCompleteBreadcrumbs'];
$pathCount = count($requestPathArray);
if ($pathCount > 1 && end($requestPathArray) == '') {
// This is the `index.md` of a directory -> Don't include the last part in the breadcrumbs
$pathCount--;
}
$breadcrumbArray = array(array('name' => $wikiName, 'path' => '', 'active' => ($pathCount == 0)));
$articleBaseDir = $this->context->getArticleBaseDir();
$currentPath = '';
$currentPathUrlEncoded = '';
for ($i = 0; $i < $pathCount; $i++) {
$pathPart = $requestPathArray[$i];
$currentPath .= ($i == 0 ? '' : '/') . $pathPart;
$currentPathUrlEncoded .= ($i == 0 ? '' : '/') . urlencode($pathPart);
$isLast = ($i == $pathCount - 1);
$hasContent = ($isLast || file_exists($articleBaseDir . $currentPath . '/index.md'));
if ($hasContent || $showCompleteBreadcrumbs) {
// This is the requested file or an directory having an index -> Add it
$breadcrumbArray[] = array(
'name' => str_replace('_', ' ', $pathPart),
'path' => $hasContent ? $currentPathUrlEncoded : null,
'active' => $isLast);
}
}
return $breadcrumbArray;
}
private function renderPage($data) {
header('Content-Type:text/html; charset=utf-8');
$i18n = $this->context->getI18n();
include(__DIR__ . '/../layout/page.php');
}
}
| til-schneider/slim-wiki | src/server/logic/Main.php | PHP | mit | 9,610 |
{
matrix_id: '2134',
name: 'shar_te2-b2',
group: 'JGD_Homology',
description: 'Simplicial complexes from Homology from Volkmar Welker.',
author: 'V. Welker',
editor: 'J.-G. Dumas',
date: '2008',
kind: 'combinatorial problem',
problem_2D_or_3D: '0',
num_rows: '200200',
num_cols: '17160',
nonzeros: '600600',
num_explicit_zeros: '0',
num_strongly_connected_components: '1',
num_dmperm_blocks: '1',
structural_full_rank: 'true',
structural_rank: '17160',
pattern_symmetry: '0.000',
numeric_symmetry: '0.000',
rb_type: 'integer',
structure: 'rectangular',
cholesky_candidate: 'no',
positive_definite: 'no',
notes: 'Simplicial complexes from Homology from Volkmar Welker.
From Jean-Guillaume Dumas\' Sparse Integer Matrix Collection,
http://ljk.imag.fr/membres/Jean-Guillaume.Dumas/simc.html
http://www.mathematik.uni-marburg.de/~welker/
Filename in JGD collection: Homology/shar_te2.b2.200200x17160.sms
',
norm: '8.062258e+00',
min_singular_value: '7.711318e-15',
condition_number: '1.045510e+15',
svd_rank: '16875',
sprank_minus_rank: '285',
null_space_dimension: '285',
full_numerical_rank: 'no',
svd_gap: '97081245539373.203125',
image_files: 'shar_te2-b2.png,shar_te2-b2_svd.png,shar_te2-b2_graph.gif,',
}
| ScottKolo/UFSMC-Web | db/collection_data/matrices/JGD_Homology/shar_te2-b2.rb | Ruby | mit | 1,514 |
<?php
namespace ZfcDatagrid\Column\Formatter;
class Link extends HtmlTag
{
/**
*
* @var array
*/
protected $attributes = [
'href' => '',
];
/**
*
* @var string
*/
protected $name = 'a';
}
| weckx/ZfcDatagrid | src/ZfcDatagrid/Column/Formatter/Link.php | PHP | mit | 248 |
var secrets = require('../config/secrets');
var querystring = require('querystring');
var validator = require('validator');
var async = require('async');
var cheerio = require('cheerio');
var request = require('request');
var graph = require('fbgraph');
var LastFmNode = require('lastfm').LastFmNode;
var tumblr = require('tumblr.js');
var foursquare = require('node-foursquare')({ secrets: secrets.foursquare });
var Github = require('github-api');
var Twit = require('twit');
var stripe = require('stripe')(secrets.stripe.secretKey);
var twilio = require('twilio')(secrets.twilio.sid, secrets.twilio.token);
var Linkedin = require('node-linkedin')(secrets.linkedin.clientID, secrets.linkedin.clientSecret, secrets.linkedin.callbackURL);
var BitGo = require('bitgo');
var clockwork = require('clockwork')({ key: secrets.clockwork.apiKey });
var paypal = require('paypal-rest-sdk');
var lob = require('lob')(secrets.lob.apiKey);
var ig = require('instagram-node').instagram();
var Y = require('yui/yql');
var _ = require('lodash');
var Bitcore = require('bitcore');
var BitcoreInsight = require('bitcore-explorers').Insight;
Bitcore.Networks.defaultNetwork = secrets.bitcore.bitcoinNetwork == 'testnet' ? Bitcore.Networks.testnet : Bitcore.Networks.mainnet;
/**
* GET /api
* List of API examples.
*/
exports.getApi = function(req, res) {
res.render('api/index', {
title: 'API Examples'
});
};
/**
* GET /api/foursquare
* Foursquare API example.
*/
exports.getFoursquare = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'foursquare' });
async.parallel({
trendingVenues: function(callback) {
foursquare.Venues.getTrending('40.7222756', '-74.0022724', { limit: 50 }, token.accessToken, function(err, results) {
callback(err, results);
});
},
venueDetail: function(callback) {
foursquare.Venues.getVenue('49da74aef964a5208b5e1fe3', token.accessToken, function(err, results) {
callback(err, results);
});
},
userCheckins: function(callback) {
foursquare.Users.getCheckins('self', null, token.accessToken, function(err, results) {
callback(err, results);
});
}
},
function(err, results) {
if (err) return next(err);
res.render('api/foursquare', {
title: 'Foursquare API',
trendingVenues: results.trendingVenues,
venueDetail: results.venueDetail,
userCheckins: results.userCheckins
});
});
};
/**
* GET /api/tumblr
* Tumblr API example.
*/
exports.getTumblr = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'tumblr' });
var client = tumblr.createClient({
consumer_key: secrets.tumblr.consumerKey,
consumer_secret: secrets.tumblr.consumerSecret,
token: token.accessToken,
token_secret: token.tokenSecret
});
client.posts('withinthisnightmare.tumblr.com', { type: 'photo' }, function(err, data) {
if (err) return next(err);
res.render('api/tumblr', {
title: 'Tumblr API',
blog: data.blog,
photoset: data.posts[0].photos
});
});
};
/**
* GET /api/facebook
* Facebook API example.
*/
exports.getFacebook = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'facebook' });
graph.setAccessToken(token.accessToken);
async.parallel({
getMe: function(done) {
graph.get(req.user.facebook, function(err, me) {
done(err, me);
});
},
getMyFriends: function(done) {
graph.get(req.user.facebook + '/friends', function(err, friends) {
done(err, friends.data);
});
}
},
function(err, results) {
if (err) return next(err);
res.render('api/facebook', {
title: 'Facebook API',
me: results.getMe,
friends: results.getMyFriends
});
});
};
/**
* GET /api/scraping
* Web scraping example using Cheerio library.
*/
exports.getScraping = function(req, res, next) {
request.get('https://news.ycombinator.com/', function(err, request, body) {
if (err) return next(err);
var $ = cheerio.load(body);
var links = [];
$('.title a[href^="http"], a[href^="https"]').each(function() {
links.push($(this));
});
res.render('api/scraping', {
title: 'Web Scraping',
links: links
});
});
};
/**
* GET /api/github
* GitHub API Example.
*/
exports.getGithub = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'github' });
var github = new Github({ token: token.accessToken });
var repo = github.getRepo('sahat', 'requirejs-library');
repo.show(function(err, repo) {
if (err) return next(err);
res.render('api/github', {
title: 'GitHub API',
repo: repo
});
});
};
/**
* GET /api/aviary
* Aviary image processing example.
*/
exports.getAviary = function(req, res) {
res.render('api/aviary', {
title: 'Aviary API'
});
};
/**
* GET /api/nyt
* New York Times API example.
*/
exports.getNewYorkTimes = function(req, res, next) {
var query = querystring.stringify({ 'api-key': secrets.nyt.key, 'list-name': 'young-adult' });
var url = 'http://api.nytimes.com/svc/books/v2/lists?' + query;
request.get(url, function(err, request, body) {
if (err) return next(err);
if (request.statusCode === 403) return next(Error('Missing or Invalid New York Times API Key'));
var bestsellers = JSON.parse(body);
res.render('api/nyt', {
title: 'New York Times API',
books: bestsellers.results
});
});
};
/**
* GET /api/lastfm
* Last.fm API example.
*/
exports.getLastfm = function(req, res, next) {
var lastfm = new LastFmNode(secrets.lastfm);
async.parallel({
artistInfo: function(done) {
lastfm.request('artist.getInfo', {
artist: 'The Pierces',
handlers: {
success: function(data) {
done(null, data);
},
error: function(err) {
done(err);
}
}
});
},
artistTopTracks: function(done) {
lastfm.request('artist.getTopTracks', {
artist: 'The Pierces',
handlers: {
success: function(data) {
var tracks = [];
_.each(data.toptracks.track, function(track) {
tracks.push(track);
});
done(null, tracks.slice(0,10));
},
error: function(err) {
done(err);
}
}
});
},
artistTopAlbums: function(done) {
lastfm.request('artist.getTopAlbums', {
artist: 'The Pierces',
handlers: {
success: function(data) {
var albums = [];
_.each(data.topalbums.album, function(album) {
albums.push(album.image.slice(-1)[0]['#text']);
});
done(null, albums.slice(0, 4));
},
error: function(err) {
done(err);
}
}
});
}
},
function(err, results) {
if (err) return next(err.message);
var artist = {
name: results.artistInfo.artist.name,
image: results.artistInfo.artist.image.slice(-1)[0]['#text'],
tags: results.artistInfo.artist.tags.tag,
bio: results.artistInfo.artist.bio.summary,
stats: results.artistInfo.artist.stats,
similar: results.artistInfo.artist.similar.artist,
topAlbums: results.artistTopAlbums,
topTracks: results.artistTopTracks
};
res.render('api/lastfm', {
title: 'Last.fm API',
artist: artist
});
});
};
/**
* GET /api/twitter
* Twiter API example.
*/
exports.getTwitter = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'twitter' });
var T = new Twit({
consumer_key: secrets.twitter.consumerKey,
consumer_secret: secrets.twitter.consumerSecret,
access_token: token.accessToken,
access_token_secret: token.tokenSecret
});
T.get('search/tweets', { q: 'nodejs since:2013-01-01', geocode: '40.71448,-74.00598,5mi', count: 10 }, function(err, reply) {
if (err) return next(err);
res.render('api/twitter', {
title: 'Twitter API',
tweets: reply.statuses
});
});
};
/**
* POST /api/twitter
* Post a tweet.
*/
exports.postTwitter = function(req, res, next) {
req.assert('tweet', 'Tweet cannot be empty.').notEmpty();
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/api/twitter');
}
var token = _.find(req.user.tokens, { kind: 'twitter' });
var T = new Twit({
consumer_key: secrets.twitter.consumerKey,
consumer_secret: secrets.twitter.consumerSecret,
access_token: token.accessToken,
access_token_secret: token.tokenSecret
});
T.post('statuses/update', { status: req.body.tweet }, function(err, data, response) {
if (err) return next(err);
req.flash('success', { msg: 'Tweet has been posted.'});
res.redirect('/api/twitter');
});
};
/**
* GET /api/steam
* Steam API example.
*/
exports.getSteam = function(req, res, next) {
var steamId = '76561197982488301';
var query = { l: 'english', steamid: steamId, key: secrets.steam.apiKey };
async.parallel({
playerAchievements: function(done) {
query.appid = '49520';
var qs = querystring.stringify(query);
request.get({ url: 'http://api.steampowered.com/ISteamUserStats/GetPlayerAchievements/v0001/?' + qs, json: true }, function(error, request, body) {
if (request.statusCode === 401) return done(new Error('Missing or Invalid Steam API Key'));
done(error, body);
});
},
playerSummaries: function(done) {
query.steamids = steamId;
var qs = querystring.stringify(query);
request.get({ url: 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?' + qs, json: true }, function(err, request, body) {
if (request.statusCode === 401) return done(new Error('Missing or Invalid Steam API Key'));
done(err, body);
});
},
ownedGames: function(done) {
query.include_appinfo = 1;
query.include_played_free_games = 1;
var qs = querystring.stringify(query);
request.get({ url: 'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?' + qs, json: true }, function(err, request, body) {
if (request.statusCode === 401) return done(new Error('Missing or Invalid Steam API Key'));
done(err, body);
});
}
},
function(err, results) {
if (err) return next(err);
res.render('api/steam', {
title: 'Steam Web API',
ownedGames: results.ownedGames.response.games,
playerAchievemments: results.playerAchievements.playerstats,
playerSummary: results.playerSummaries.response.players[0]
});
});
};
/**
* GET /api/stripe
* Stripe API example.
*/
exports.getStripe = function(req, res) {
res.render('api/stripe', {
title: 'Stripe API',
publishableKey: secrets.stripe.publishableKey
});
};
/**
* POST /api/stripe
* Make a payment.
*/
exports.postStripe = function(req, res, next) {
var stripeToken = req.body.stripeToken;
var stripeEmail = req.body.stripeEmail;
stripe.charges.create({
amount: 395,
currency: 'usd',
source: stripeToken,
description: stripeEmail
}, function(err, charge) {
if (err && err.type === 'StripeCardError') {
req.flash('errors', { msg: 'Your card has been declined.' });
res.redirect('/api/stripe');
}
req.flash('success', { msg: 'Your card has been charged successfully.' });
res.redirect('/api/stripe');
});
};
/**
* GET /api/twilio
* Twilio API example.
*/
exports.getTwilio = function(req, res) {
res.render('api/twilio', {
title: 'Twilio API'
});
};
/**
* POST /api/twilio
* Send a text message using Twilio.
*/
exports.postTwilio = function(req, res, next) {
req.assert('number', 'Phone number is required.').notEmpty();
req.assert('message', 'Message cannot be blank.').notEmpty();
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/api/twilio');
}
var message = {
to: req.body.number,
from: '+13472235148',
body: req.body.message
};
twilio.sendMessage(message, function(err, responseData) {
if (err) return next(err.message);
req.flash('success', { msg: 'Text sent to ' + responseData.to + '.'});
res.redirect('/api/twilio');
});
};
/**
* GET /api/clockwork
* Clockwork SMS API example.
*/
exports.getClockwork = function(req, res) {
res.render('api/clockwork', {
title: 'Clockwork SMS API'
});
};
/**
* POST /api/clockwork
* Send a text message using Clockwork SMS
*/
exports.postClockwork = function(req, res, next) {
var message = {
To: req.body.telephone,
From: 'Hackathon',
Content: 'Hello from the Hackathon Starter'
};
clockwork.sendSms(message, function(err, responseData) {
if (err) return next(err.errDesc);
req.flash('success', { msg: 'Text sent to ' + responseData.responses[0].to });
res.redirect('/api/clockwork');
});
};
/**
* GET /api/venmo
* Venmo API example.
*/
exports.getVenmo = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'venmo' });
var query = querystring.stringify({ access_token: token.accessToken });
async.parallel({
getProfile: function(done) {
request.get({ url: 'https://api.venmo.com/v1/me?' + query, json: true }, function(err, request, body) {
done(err, body);
});
},
getRecentPayments: function(done) {
request.get({ url: 'https://api.venmo.com/v1/payments?' + query, json: true }, function(err, request, body) {
done(err, body);
});
}
},
function(err, results) {
if (err) return next(err);
res.render('api/venmo', {
title: 'Venmo API',
profile: results.getProfile.data,
recentPayments: results.getRecentPayments.data
});
});
};
/**
* POST /api/venmo
* Send money.
*/
exports.postVenmo = function(req, res, next) {
req.assert('user', 'Phone, Email or Venmo User ID cannot be blank').notEmpty();
req.assert('note', 'Please enter a message to accompany the payment').notEmpty();
req.assert('amount', 'The amount you want to pay cannot be blank').notEmpty();
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/api/venmo');
}
var token = _.find(req.user.tokens, { kind: 'venmo' });
var formData = {
access_token: token.accessToken,
note: req.body.note,
amount: req.body.amount
};
if (validator.isEmail(req.body.user)) {
formData.email = req.body.user;
} else if (validator.isNumeric(req.body.user) &&
validator.isLength(req.body.user, 10, 11)) {
formData.phone = req.body.user;
} else {
formData.user_id = req.body.user;
}
request.post('https://api.venmo.com/v1/payments', { form: formData }, function(err, request, body) {
if (err) return next(err);
if (request.statusCode !== 200) {
req.flash('errors', { msg: JSON.parse(body).error.message });
return res.redirect('/api/venmo');
}
req.flash('success', { msg: 'Venmo money transfer complete' });
res.redirect('/api/venmo');
});
};
/**
* GET /api/linkedin
* LinkedIn API example.
*/
exports.getLinkedin = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'linkedin' });
var linkedin = Linkedin.init(token.accessToken);
linkedin.people.me(function(err, $in) {
if (err) return next(err);
res.render('api/linkedin', {
title: 'LinkedIn API',
profile: $in
});
});
};
/**
* GET /api/instagram
* Instagram API example.
*/
exports.getInstagram = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'instagram' });
ig.use({ client_id: secrets.instagram.clientID, client_secret: secrets.instagram.clientSecret });
ig.use({ access_token: token.accessToken });
async.parallel({
searchByUsername: function(done) {
ig.user_search('richellemead', function(err, users, limit) {
done(err, users);
});
},
searchByUserId: function(done) {
ig.user('175948269', function(err, user) {
done(err, user);
});
},
popularImages: function(done) {
ig.media_popular(function(err, medias) {
done(err, medias);
});
},
myRecentMedia: function(done) {
ig.user_self_media_recent(function(err, medias, pagination, limit) {
done(err, medias);
});
}
}, function(err, results) {
if (err) return next(err);
res.render('api/instagram', {
title: 'Instagram API',
usernames: results.searchByUsername,
userById: results.searchByUserId,
popularImages: results.popularImages,
myRecentMedia: results.myRecentMedia
});
});
};
/**
* GET /api/yahoo
* Yahoo API example.
*/
exports.getYahoo = function(req, res) {
Y.YQL('SELECT * FROM weather.forecast WHERE (location = 10007)', function(response) {
var location = response.query.results.channel.location;
var condition = response.query.results.channel.item.condition;
res.render('api/yahoo', {
title: 'Yahoo API',
location: location,
condition: condition
});
});
};
/**
* GET /api/paypal
* PayPal SDK example.
*/
exports.getPayPal = function(req, res, next) {
paypal.configure({
mode: 'sandbox',
client_id: secrets.paypal.client_id,
client_secret: secrets.paypal.client_secret
});
var paymentDetails = {
intent: 'sale',
payer: {
payment_method: 'paypal'
},
redirect_urls: {
return_url: secrets.paypal.returnUrl,
cancel_url: secrets.paypal.cancelUrl
},
transactions: [{
description: 'Hackathon Starter',
amount: {
currency: 'USD',
total: '1.99'
}
}]
};
paypal.payment.create(paymentDetails, function(err, payment) {
if (err) return next(err);
req.session.paymentId = payment.id;
var links = payment.links;
for (var i = 0; i < links.length; i++) {
if (links[i].rel === 'approval_url') {
res.render('api/paypal', {
approvalUrl: links[i].href
});
}
}
});
};
/**
* GET /api/paypal/success
* PayPal SDK example.
*/
exports.getPayPalSuccess = function(req, res) {
var paymentId = req.session.paymentId;
var paymentDetails = { payer_id: req.query.PayerID };
paypal.payment.execute(paymentId, paymentDetails, function(err) {
if (err) {
res.render('api/paypal', {
result: true,
success: false
});
} else {
res.render('api/paypal', {
result: true,
success: true
});
}
});
};
/**
* GET /api/paypal/cancel
* PayPal SDK example.
*/
exports.getPayPalCancel = function(req, res) {
req.session.paymentId = null;
res.render('api/paypal', {
result: true,
canceled: true
});
};
/**
* GET /api/lob
* Lob API example.
*/
exports.getLob = function(req, res, next) {
lob.routes.list({
zip_codes: ['10007']
}, function(err, routes) {
if(err) return next(err);
res.render('api/lob', {
title: 'Lob API',
routes: routes.data[0].routes
});
});
};
/**
* GET /api/bitgo
* BitGo wallet example
*/
exports.getBitGo = function(req, res, next) {
var bitgo = new BitGo.BitGo({ env: 'test', accessToken: secrets.bitgo.accessToken });
var walletId = req.session.walletId;
var renderWalletInfo = function(walletId) {
bitgo.wallets().get({ id: walletId }, function(err, walletResponse) {
walletResponse.createAddress({}, function(err, addressResponse) {
walletResponse.transactions({}, function(err, transactionsResponse) {
res.render('api/bitgo', {
title: 'BitGo API',
wallet: walletResponse.wallet,
address: addressResponse.address,
transactions: transactionsResponse.transactions
});
});
});
});
};
if (walletId) {
renderWalletInfo(walletId);
} else {
bitgo.wallets().createWalletWithKeychains({
passphrase: req.sessionID, // change this!
label: 'wallet for session ' + req.sessionID,
backupXpub: 'xpub6AHA9hZDN11k2ijHMeS5QqHx2KP9aMBRhTDqANMnwVtdyw2TDYRmF8PjpvwUFcL1Et8Hj59S3gTSMcUQ5gAqTz3Wd8EsMTmF3DChhqPQBnU'
}, function(err, res) {
req.session.walletId = res.wallet.wallet.id;
renderWalletInfo(req.session.walletId);
}
);
}
};
/**
* POST /api/bitgo
* BitGo send coins example
*/
exports.postBitGo = function(req, res, next) {
var bitgo = new BitGo.BitGo({ env: 'test', accessToken: secrets.bitgo.accessToken });
var walletId = req.session.walletId;
try {
bitgo.wallets().get({ id: walletId }, function(err, wallet) {
wallet.sendCoins({
address: req.body.address,
amount: parseInt(req.body.amount),
walletPassphrase: req.sessionID
}, function(err, result) {
if (err) {
req.flash('errors', { msg: err.message });
return res.redirect('/api/bitgo');
}
req.flash('info', { msg: 'txid: ' + result.hash + ', hex: ' + result.tx });
return res.redirect('/api/bitgo');
});
});
} catch (e) {
req.flash('errors', { msg: e.message });
return res.redirect('/api/bitgo');
}
};
/**
* GET /api/bicore
* Bitcore example
*/
exports.getBitcore = function(req, res, next) {
try {
var privateKey;
if (req.session.bitcorePrivateKeyWIF) {
privateKey = Bitcore.PrivateKey.fromWIF(req.session.bitcorePrivateKeyWIF);
} else {
privateKey = new Bitcore.PrivateKey();
req.session.bitcorePrivateKeyWIF = privateKey.toWIF();
req.flash('info', {
msg: 'A new ' + secrets.bitcore.bitcoinNetwork + ' private key has been created for you and is stored in ' +
'req.session.bitcorePrivateKeyWIF. Unless you changed the Bitcoin network near the require bitcore line, ' +
'this is a testnet address.'
});
}
var myAddress = privateKey.toAddress();
var bitcoreUTXOAddress = '';
if (req.session.bitcoreUTXOAddress)
bitcoreUTXOAddress = req.session.bitcoreUTXOAddress;
res.render('api/bitcore', {
title: 'Bitcore API',
network: secrets.bitcore.bitcoinNetwork,
address: myAddress,
getUTXOAddress: bitcoreUTXOAddress
});
} catch (e) {
req.flash('errors', { msg: e.message });
return next(e);
}
};
/**
* POST /api/bitcore
* Bitcore send coins example
*/
exports.postBitcore = function(req, res, next) {
try {
var getUTXOAddress;
if (req.body.address) {
getUTXOAddress = req.body.address;
req.session.bitcoreUTXOAddress = getUTXOAddress;
} else if (req.session.bitcoreUTXOAddress) {
getUTXOAddress = req.session.bitcoreUTXOAddress;
} else {
getUTXOAddress = '';
}
var myAddress;
if (req.session.bitcorePrivateKeyWIF) {
myAddress = Bitcore.PrivateKey.fromWIF(req.session.bitcorePrivateKeyWIF).toAddress();
} else {
myAddress = '';
}
var insight = new BitcoreInsight();
insight.getUnspentUtxos(getUTXOAddress, function(err, utxos) {
if (err) {
req.flash('errors', { msg: err.message });
return next(err);
} else {
req.flash('info', { msg: 'UTXO information obtained from the Bitcoin network via Bitpay Insight. You can use your own full Bitcoin node.' });
// Results are in the form of an array of items which need to be turned into JS objects.
for (var i = 0; i < utxos.length; ++i) {
utxos[i] = utxos[i].toObject();
}
res.render('api/bitcore', {
title: 'Bitcore API',
myAddress: myAddress,
getUTXOAddress: getUTXOAddress,
utxos: utxos,
network: secrets.bitcore.bitcoinNetwork
});
}
});
} catch (e) {
req.flash('errors', { msg: e.message });
return next(e);
}
}; | patcullen/hsuehshan | controllers/api.js | JavaScript | mit | 23,909 |
/**
* @author Titus Wormer
* @copyright 2015 Titus Wormer
* @license MIT
* @module remark:toc
* @fileoverview Generate a Table of Contents (TOC) for Markdown files.
*/
'use strict';
/* Dependencies. */
var slug = require('remark-slug');
var toc = require('mdast-util-toc');
/* Expose. */
module.exports = attacher;
/* Constants. */
var DEFAULT_HEADING = 'toc|table[ -]of[ -]contents?';
/**
* Attacher.
*
* @param {Unified} processor - Processor.
* @param {Object} options - Configuration.
* @return {function(node)} - Transformmer.
*/
function attacher(processor, options) {
var settings = options || {};
var heading = settings.heading || DEFAULT_HEADING;
var depth = settings.maxDepth || 6;
var tight = settings.tight;
processor.use(slug);
return transformer;
/**
* Adds an example section based on a valid example
* JavaScript document to a `Usage` section.
*
* @param {Node} node - Root to search in.
*/
function transformer(node) {
var result = toc(node, {
heading: heading,
maxDepth: depth,
tight: tight
});
if (result.index === null || result.index === -1 || !result.map) {
return;
}
/* Replace markdown. */
node.children = [].concat(
node.children.slice(0, result.index),
result.map,
node.children.slice(result.endIndex)
);
}
}
| Nrupesh29/Web-Traffic-Visualizer | vizceral/node_modules/remark-toc/index.js | JavaScript | mit | 1,360 |
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.89 2 2 2zM18 11c0-3.07-1.64-5.64-4.5-6.32V2.5h-3v2.18c-.24.06-.47.15-.69.23L18 13.1V11z" /><path d="M5.41 3.35L4 4.76l2.81 2.81C6.29 8.57 6 9.73 6 11v5l-2 2v1h14.24l1.74 1.74 1.41-1.41L5.41 3.35z" /></g></React.Fragment>
, 'NotificationsOffSharp');
| Kagami/material-ui | packages/material-ui-icons/src/NotificationsOffSharp.js | JavaScript | mit | 459 |
<?php
/*
* This file is part of the PHPExifTool package.
*
* (c) Alchemy <support@alchemy.fr>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\CanonVRD;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class RawBrightnessAdj extends AbstractTag
{
protected $Id = 'mixed';
protected $Name = 'RawBrightnessAdj';
protected $FullName = 'mixed';
protected $GroupName = 'CanonVRD';
protected $g0 = 'CanonVRD';
protected $g1 = 'CanonVRD';
protected $g2 = 'Image';
protected $Type = 'mixed';
protected $Writable = true;
protected $Description = 'Raw Brightness Adj';
}
| bburnichon/PHPExiftool | lib/PHPExiftool/Driver/Tag/CanonVRD/RawBrightnessAdj.php | PHP | mit | 806 |
package com.xeiam.xchange.jubi.service.polling;
import java.io.IOException;
import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.currency.CurrencyPair;
import com.xeiam.xchange.jubi.Jubi;
import com.xeiam.xchange.jubi.dto.marketdata.JubiTicker;
/**
* Created by Yingzhe on 3/17/2015.
*/
public class JubiMarketDataServiceRaw extends JubiBasePollingService<Jubi> {
/**
* Constructor for JubiMarketDataServiceRaw
*
* @param exchange The {@link com.xeiam.xchange.Exchange}
*/
public JubiMarketDataServiceRaw(Exchange exchange) {
super(Jubi.class, exchange);
}
/**
* Gets ticker from Jubi
*
* @param baseCurrency Base currency
* @param targetCurrency Target currency
* @return JubiTicker object
* @throws java.io.IOException
*/
public JubiTicker getJubiTicker(String baseCurrency, String targetCurrency) throws IOException {
// Base currency needs to be in lower case, otherwise API throws an error
for (CurrencyPair cp : this.getExchangeSymbols()) {
if (cp.baseSymbol.equalsIgnoreCase(baseCurrency) && cp.counterSymbol.equalsIgnoreCase(targetCurrency)) {
return this.jubi.getTicker(baseCurrency.toLowerCase());
}
}
return null;
}
}
| jennieolsson/XChange | xchange-jubi/src/main/java/com/xeiam/xchange/jubi/service/polling/JubiMarketDataServiceRaw.java | Java | mit | 1,231 |
<?php
/*
* This file is part of the Acme PHP project.
*
* (c) Titouan Galopin <galopintitouan@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace AcmePhp\Core\Challenge\Http;
use AcmePhp\Core\Protocol\AuthorizationChallenge;
/**
* Extract data needed to solve HTTP challenges.
*
* @author Jérémy Derussé <jeremy@derusse.com>
*/
class HttpDataExtractor
{
/**
* Retrieves the absolute URL called by the CA.
*/
public function getCheckUrl(AuthorizationChallenge $authorizationChallenge): string
{
return sprintf(
'http://%s%s',
$authorizationChallenge->getDomain(),
$this->getCheckPath($authorizationChallenge)
);
}
/**
* Retrieves the absolute path called by the CA.
*/
public function getCheckPath(AuthorizationChallenge $authorizationChallenge): string
{
return sprintf(
'/.well-known/acme-challenge/%s',
$authorizationChallenge->getToken()
);
}
/**
* Retrieves the content that should be returned in the response.
*/
public function getCheckContent(AuthorizationChallenge $authorizationChallenge): string
{
return $authorizationChallenge->getPayload();
}
}
| acmephp/acmephp | src/Core/Challenge/Http/HttpDataExtractor.php | PHP | mit | 1,355 |
/*
Copyright (c) 2008 The Crash Team.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/*global crash, createTimerTests, runCrashTests */
function createTimerTests() {
return crash.test.unit('Timer Tests', {
crashTests: [
{ func: 'startSetTimeout', callbacks: [ 'timerSetTimeout' ] },
{ func: 'startSetInterval', callbacks: [ 'timerSetInterval' ] }
],
timerId: null,
timerStart: null,
startSetTimeout: function () {
this.timerId = crash.timer.setTimeout(this.timerSetTimeout, 250);
this.timerStart = new Date().getTime();
this.assert(this.timerId !== null, "Timer Id is null");
},
timerSetTimeout: function () {
crash.timer.clearTimeout(this.timerId);
var time = new Date().getTime() - this.timerStart;
this.assert(time >= 250, "Time <= 250 ms (" + time + ")");
},
startSetInterval: function () {
this.timerId = crash.timer.setInterval(this.timerSetInterval, 250);
this.timerStart = new Date().getTime();
this.assert(this.timerId !== null, "Timer Id is null");
},
timerSetInterval: function () {
crash.timer.clearTimeout(this.timerId);
var time = new Date().getTime() - this.timerStart;
this.assert(time >= 250, "Time <= 250 ms (" + time + ")");
}
}, 1000);
}
function runCrashTests() {
return createTimerTests();
} | hankly/frizione | Frizione/frizione-projects/crash/test/core/timer.js | JavaScript | mit | 2,543 |
<?php
/*
* This file is part of the PHPExifTool package.
*
* (c) Alchemy <support@alchemy.fr>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\DICOM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class SlabThickness extends AbstractTag
{
protected $Id = '0018,9104';
protected $Name = 'SlabThickness';
protected $FullName = 'DICOM::Main';
protected $GroupName = 'DICOM';
protected $g0 = 'DICOM';
protected $g1 = 'DICOM';
protected $g2 = 'Image';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Slab Thickness';
}
| bburnichon/PHPExiftool | lib/PHPExiftool/Driver/Tag/DICOM/SlabThickness.php | PHP | mit | 791 |
var gulp = require('gulp'),
plumber = require('gulp-plumber'),
browserSync = require('browser-sync'),
stylus = require('gulp-stylus'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
jeet = require('jeet'),
rupture = require('rupture'),
koutoSwiss = require('kouto-swiss'),
prefixer = require('autoprefixer-stylus'),
imagemin = require('gulp-imagemin'),
cp = require('child_process');
var messages = {
jekyllBuild: '<span style="color: grey">Running:</span> $ jekyll build'
};
/**
* Build the Jekyll Site
*/
gulp.task('jekyll-build', function (done) {
browserSync.notify(messages.jekyllBuild);
return cp.exec('jekyll', ['build'], {stdio: 'inherit'})
.on('close', done);
});
/**
* Rebuild Jekyll & do page reload
*/
gulp.task('jekyll-rebuild', ['jekyll-build'], function () {
browserSync.reload();
});
/**
* Wait for jekyll-build, then launch the Server
*/
gulp.task('browser-sync', ['jekyll-build'], function() {
browserSync({
server: {
baseDir: '_site'
}
});
});
/**
* Stylus task
*/
gulp.task('stylus', function(){
gulp.src('src/styl/main.styl')
.pipe(plumber())
.pipe(stylus({
use:[koutoSwiss(), prefixer(), jeet(),rupture()],
compress: true
}))
.pipe(gulp.dest('_site/assets/css/'))
.pipe(browserSync.reload({stream:true}))
.pipe(gulp.dest('assets/css'))
});
/**
* Javascript Task
*/
gulp.task('js', function(){
return gulp.src('src/js/**/*.js')
.pipe(plumber())
.pipe(concat('main.js'))
.pipe(uglify())
.pipe(gulp.dest('assets/js/'))
});
/**
* Imagemin Task
*/
gulp.task('imagemin', function() {
return gulp.src('src/img/**/*.{jpg,png,gif,ico}')
.pipe(plumber())
.pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))
.pipe(gulp.dest('assets/img/'));
});
/**
* Watch stylus files for changes & recompile
* Watch html/md files, run jekyll & reload BrowserSync
*/
gulp.task('watch', function () {
gulp.watch('src/styl/**/*.styl', ['stylus']);
gulp.watch('src/js/**/*.js', ['js']);
gulp.watch('src/img/**/*.{jpg,png,gif}', ['imagemin']);
gulp.watch(['*.html', '_includes/*.html', '_layouts/*.html', '_posts/*'], ['jekyll-rebuild']);
});
/**
* Default task, running just `gulp` will compile the sass,
* compile the jekyll site, launch BrowserSync & watch files.
*/
gulp.task('default', ['js', 'stylus', 'browser-sync', 'watch']);
gulp.task('without-jekyll', ['js', 'stylus', 'imagemin']);
| matheus-vieira/blog | gulpfile.js | JavaScript | mit | 2,478 |
"""A dummy module for testing purposes."""
import logging
import os
import uuid
import lambdautils.state as state
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def partition_key(event):
return event.get("client_id", str(uuid.uuid4()))
def input_filter(event, *args, **kwargs):
if os.environ.get("mydummyvar") != "mydummyval":
raise ValueError("Unable to retrieve 'mydummyvar' from environment")
event["input_filter"] = True
val = state.get_state(event["id"])
if val:
logger.info("Retrieved state key '{}': '{}'".format(event["id"], val))
return False
else:
logger.info("State key '{}' not found".format(event["id"]))
state.set_state(event["id"], "hello there")
return True
def output_filter_1(event, *args, **kwargs):
event["output_filter_1"] = True
return True
def output_mapper_1(event, *args, **kwargs):
event["output_mapper_1"] = True
return event
def output_mapper_2(event, *args, **kwargs):
event["output_mapper_2"] = True
return event
def output_mapper_2b(event, *args, **kwargs):
event["output_mapper_2b"] = True
return event
def output_filter_2b(event, *args, **kwargs):
return True
def batch_mapper(events, *args, **kwargs):
for ev in events:
ev["batch_mapped"] = True
return events
| humilis/humilis-kinesis-mapper | tests/integration/mycode/mypkg/__init__.py | Python | mit | 1,346 |
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Dynamic;
namespace AppDi
{
public class AppDriver : DynamicObject
{
public Uri BaseUrl { get; }
public Lazy<IWebDriver> WebDriver { get; }
private Dictionary<string, Type> _pageObjects;
/// <summary>
/// The AppDriverFactory is responsible for creating an instance of an AppDriver
/// </summary>
/// <returns></returns>
public static AppDriverFactory Factory()
{
return new AppDriverFactory((Uri baseUrl, Lazy<IWebDriver> webDriver, Dictionary<string, Type> PageObjectmembers) =>
{
return new AppDriver(baseUrl, webDriver, PageObjectmembers);
});
}
/// <summary>
/// AppDriver should only be instantiated through its factory
/// </summary>
/// <param name="baseUrl"></param>
/// <param name="webDriver"></param>
/// <param name="PageObjectmembers"></param>
private AppDriver(Uri baseUrl, Lazy<IWebDriver> webDriver, Dictionary<string, Type> PageObjectmembers)
{
this.BaseUrl = baseUrl;
this.WebDriver = webDriver;
_pageObjects = new Dictionary<string, Type>(PageObjectmembers);
}
/// <summary>
/// This method is in charge of dynamic binding of properties/methods in this Dynamic Object
/// In specific for this class, it is in charge of creating instances of Page Objects that are dinamically
/// registered with the AppDriver during the initial driver creation (using AppDriver.Factory().Register<> method)
/// </summary>
/// <param name="binder">Information about the member we are trying to bing</param>
/// <param name="result">Newly created PageObject</param>
/// <returns></returns>
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
Type pageType;
bool isPageRegistered = _pageObjects.TryGetValue(binder.Name, out pageType);
if (isPageRegistered)
{
//this needs to be extracted out into it's own method that can be replaced by users if desired
var createdPage = (PageObject)Activator.CreateInstance(pageType);
createdPage.WebDriver = this.WebDriver.Value;
createdPage.Url = this.BaseUrl;
//TO DO: Make wait timeout configurable
createdPage.Wait = new WebDriverWait(this.WebDriver.Value, new TimeSpan(0,0,10));
PageFactory.InitElements(this.WebDriver.Value, createdPage);
result = createdPage;
return isPageRegistered;
}
else
{
return base.TryGetMember(binder, out result);
}
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
return base.TrySetMember(binder, value);
}
/// <summary>
/// Returns the count of PageObject types that have been DYNAMICALLY registed with the current AppDriver object
/// </summary>
public int PageObjectsCount
{
get {
return _pageObjects.Count;
}
}
}
} | mxa0079/Selenium | AppDi/AppDi/AppDriver.cs | C# | mit | 3,435 |