code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
#ifndef CPP_UNIT_TESTDECORATOR_H
#define CPP_UNIT_TESTDECORATOR_H
#include "CppUnitCommon.h"
#include "Test.h"
class TestDecorator : public Test
{
protected:
Test *m_test;
public:
TestDecorator (Test *test);
~TestDecorator ();
int countTestCases ();
void run (TestResult *result);
TString toString ();
};
inline TestDecorator::TestDecorator (Test *test)
{
m_test = test;
}
inline TestDecorator::~TestDecorator ()
{
delete m_test;
}
inline TestDecorator::countTestCases ()
{
return m_test->countTestCases ();
}
inline void TestDecorator::run (TestResult *result)
{
m_test->run (result);
}
inline TString TestDecorator::toString ()
{
return m_test->toString ();
}
#endif
|
zer0infinity/CuteTestForCoastTest
|
testfw/testext/TestDecorator.h
|
C
|
bsd-3-clause
| 696 |
/*
* Copyright (c) 2016, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file includes functions for debugging.
*/
#ifndef LOGGING_HPP_
#define LOGGING_HPP_
#include "openthread-core-config.h"
#include <ctype.h>
#include <stdio.h>
#include "utils/wrap_string.h"
#include <openthread/instance.h>
#include <openthread/types.h>
#include <openthread/platform/logging.h>
#ifdef WINDOWS_LOGGING
#ifdef _KERNEL_MODE
#include <wdm.h>
#endif
#include "openthread/platform/logging-windows.h"
#ifdef WPP_NAME
#include WPP_NAME
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifndef WINDOWS_LOGGING
#define otLogFuncEntry()
#define otLogFuncEntryMsg(aFormat, ...)
#define otLogFuncExit()
#define otLogFuncExitMsg(aFormat, ...)
#define otLogFuncExitErr(error)
#endif
/**
* @def otLogCrit
*
* Logging at log level critical.
*
* @param[in] aInstance A pointer to the OpenThread instance.
* @param[in] aRegion The log region.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_CRIT
#define otLogCrit(aInstance, aRegion, aFormat, ...) \
_otLogFormatter(aInstance, OT_LOG_LEVEL_CRIT, aRegion, aFormat, ## __VA_ARGS__)
#else
#define otLogCrit(aInstance, aRegion, aFormat, ...)
#endif
/**
* @def otLogWarn
*
* Logging at log level warning.
*
* @param[in] aInstance A pointer to the OpenThread instance.
* @param[in] aRegion The log region.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN
#define otLogWarn(aInstance, aRegion, aFormat, ...) \
_otLogFormatter(aInstance, OT_LOG_LEVEL_WARN, aRegion, aFormat, ## __VA_ARGS__)
#else
#define otLogWarn(aInstance, aRegion, aFormat, ...)
#endif
/**
* @def otLogInfo
*
* Logging at log level info.
*
* @param[in] aInstance A pointer to the OpenThread instance.
* @param[in] aRegion The log region.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO
#define otLogInfo(aInstance, aRegion, aFormat, ...) \
_otLogFormatter(aInstance, OT_LOG_LEVEL_INFO, aRegion, aFormat, ## __VA_ARGS__)
#else
#define otLogInfo(aInstance, aRegion, aFormat, ...)
#endif
/**
* @def otLogDebg
*
* Logging at log level debug.
*
* @param[in] aInstance A pointer to the OpenThread instance.
* @param[in] aRegion The log region.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG
#define otLogDebg(aInstance, aRegion, aFormat, ...) \
_otLogFormatter(aInstance, OT_LOG_LEVEL_DEBG, aRegion, aFormat, ## __VA_ARGS__)
#else
#define otLogDebg(aInstance, aRegion, aFormat, ...)
#endif
#ifndef WINDOWS_LOGGING
/**
* @def otLogCritApi
*
* This method generates a log with level critical for the API region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogWarnApi
*
* This method generates a log with level warning for the API region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogInfoApi
*
* This method generates a log with level info for the API region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogDebgApi
*
* This method generates a log with level debug for the API region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
#if OPENTHREAD_CONFIG_LOG_API == 1
#define otLogCritApi(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_API, aFormat, ## __VA_ARGS__)
#define otLogWarnApi(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_API, aFormat, ## __VA_ARGS__)
#define otLogInfoApi(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_API, aFormat, ## __VA_ARGS__)
#define otLogDebgApi(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_API, aFormat, ## __VA_ARGS__)
#else
#define otLogCritApi(aInstance, aFormat, ...)
#define otLogWarnApi(aInstance, aFormat, ...)
#define otLogInfoApi(aInstance, aFormat, ...)
#define otLogDebgApi(aInstance, aFormat, ...)
#endif
/**
* @def otLogCritMeshCoP
*
* This method generates a log with level critical for the MLE region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*
*/
/**
* @def otLogWarnMeshCoP
*
* This method generates a log with level warning for the MLE region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogInfoMeshCoP
*
* This method generates a log with level info for the MLE region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogDebgMeshCoP
*
* This method generates a log with level debug for the MLE region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
#if OPENTHREAD_CONFIG_LOG_MLE == 1
#define otLogCritMeshCoP(aInstance, aFormat, ...) \
otLogCrit(&aInstance, OT_LOG_REGION_MESH_COP, aFormat, ## __VA_ARGS__)
#define otLogWarnMeshCoP(aInstance, aFormat, ...) \
otLogWarn(&aInstance, OT_LOG_REGION_MESH_COP, aFormat, ## __VA_ARGS__)
#define otLogInfoMeshCoP(aInstance, aFormat, ...) \
otLogInfo(&aInstance, OT_LOG_REGION_MESH_COP, aFormat, ## __VA_ARGS__)
#define otLogDebgMeshCoP(aInstance, aFormat, ...) \
otLogDebg(&aInstance, OT_LOG_REGION_MESH_COP, aFormat, ## __VA_ARGS__)
#else
#define otLogCritMeshCoP(aInstance, aFormat, ...)
#define otLogWarnMeshCoP(aInstance, aFormat, ...)
#define otLogInfoMeshCoP(aInstance, aFormat, ...)
#define otLogDebgMeshCoP(aInstance, aFormat, ...)
#endif
#define otLogCritMbedTls(aInstance, aFormat, ...) otLogCritMeshCoP(aInstance, aFormat, ## __VA_ARGS__)
#define otLogWarnMbedTls(aInstance, aFormat, ...) otLogWarnMeshCoP(aInstance, aFormat, ## __VA_ARGS__)
#define otLogInfoMbedTls(aInstance, aFormat, ...) otLogInfoMeshCoP(aInstance, aFormat, ## __VA_ARGS__)
#define otLogDebgMbedTls(aInstance, aFormat, ...) otLogDebgMeshCoP(aInstance, aFormat, ## __VA_ARGS__)
/**
* @def otLogCritMle
*
* This method generates a log with level critical for the MLE region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogWarnMle
*
* This method generates a log with level warning for the MLE region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
* *
*/
/**
* @def otLogInfoMle
*
* This method generates a log with level info for the MLE region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
* *
*/
/**
* @def otLogDebgMle
*
* This method generates a log with level debug for the MLE region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*
*/
#if OPENTHREAD_CONFIG_LOG_MLE == 1
#define otLogCritMle(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_MLE, aFormat, ## __VA_ARGS__)
#define otLogWarnMle(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_MLE, aFormat, ## __VA_ARGS__)
#define otLogWarnMleErr(aInstance, aError, aFormat, ...) \
otLogWarn(&aInstance, OT_LOG_REGION_MLE, "Error %s: " aFormat, otThreadErrorToString(aError), ## __VA_ARGS__)
#define otLogInfoMle(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_MLE, aFormat, ## __VA_ARGS__)
#define otLogDebgMle(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_MLE, aFormat, ## __VA_ARGS__)
#else
#define otLogCritMle(aInstance, aFormat, ...)
#define otLogWarnMle(aInstance, aFormat, ...)
#define otLogWarnMleErr(aInstance, aError, aFormat, ...)
#define otLogInfoMle(aInstance, aFormat, ...)
#define otLogDebgMle(aInstance, aFormat, ...)
#endif
/**
* @def otLogCritArp
*
* This method generates a log with level critical for the EID-to-RLOC mapping region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*
*/
/**
* @def otLogWarnArp
*
* This method generates a log with level warning for the EID-to-RLOC mapping region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogInfoArp
*
* This method generates a log with level info for the EID-to-RLOC mapping region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogDebgArp
*
* This method generates a log with level debug for the EID-to-RLOC mapping region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
#if OPENTHREAD_CONFIG_LOG_ARP == 1
#define otLogCritArp(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_ARP, aFormat, ## __VA_ARGS__)
#define otLogWarnArp(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_ARP, aFormat, ## __VA_ARGS__)
#define otLogInfoArp(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_ARP, aFormat, ## __VA_ARGS__)
#define otLogDebgArp(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_ARP, aFormat, ## __VA_ARGS__)
#else
#define otLogCritArp(aInstance, aFormat, ...)
#define otLogWarnArp(aInstance, aFormat, ...)
#define otLogInfoArp(aInstance, aFormat, ...)
#define otLogDebgArp(aInstance, aFormat, ...)
#endif
/**
* @def otLogCritNetData
*
* This method generates a log with level critical for the Network Data region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogWarnNetData
*
* This method generates a log with level warning for the Network Data region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogInfoNetData
*
* This method generates a log with level info for the Network Data region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogDebgNetData
*
* This method generates a log with level debug for the Network Data region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
#if OPENTHREAD_CONFIG_LOG_NETDATA == 1
#define otLogCritNetData(aInstance, aFormat, ...) \
otLogCrit(&aInstance, OT_LOG_REGION_NET_DATA, aFormat, ## __VA_ARGS__)
#define otLogWarnNetData(aInstance, aFormat, ...) \
otLogWarn(&aInstance, OT_LOG_REGION_NET_DATA, aFormat, ## __VA_ARGS__)
#define otLogInfoNetData(aInstance, aFormat, ...) \
otLogInfo(&aInstance, OT_LOG_REGION_NET_DATA, aFormat, ## __VA_ARGS__)
#define otLogDebgNetData(aInstance, aFormat, ...) \
otLogDebg(&aInstance, OT_LOG_REGION_NET_DATA, aFormat, ## __VA_ARGS__)
#else
#define otLogCritNetData(aInstance, aFormat, ...)
#define otLogWarnNetData(aInstance, aFormat, ...)
#define otLogInfoNetData(aInstance, aFormat, ...)
#define otLogDebgNetData(aInstance, aFormat, ...)
#endif
/**
* @def otLogCritIcmp
*
* This method generates a log with level critical for the ICMPv6 region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogWarnIcmp
*
* This method generates a log with level warning for the ICMPv6 region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogInfoIcmp
*
* This method generates a log with level info for the ICMPv6 region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogDebgIcmp
*
* This method generates a log with level debug for the ICMPv6 region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
#if OPENTHREAD_CONFIG_LOG_ICMP == 1
#define otLogCritIcmp(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_ICMP, aFormat, ## __VA_ARGS__)
#define otLogWarnIcmp(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_ICMP, aFormat, ## __VA_ARGS__)
#define otLogInfoIcmp(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_ICMP, aFormat, ## __VA_ARGS__)
#define otLogDebgIcmp(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_ICMP, aFormat, ## __VA_ARGS__)
#else
#define otLogCritIcmp(aInstance, aFormat, ...)
#define otLogWarnIcmp(aInstance, aFormat, ...)
#define otLogInfoIcmp(aInstance, aFormat, ...)
#define otLogDebgIcmp(aInstance, aFormat, ...)
#endif
/**
* @def otLogCritIp6
*
* This method generates a log with level critical for the IPv6 region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogWarnIp6
*
* This method generates a log with level warning for the IPv6 region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogInfoIp6
*
* This method generates a log with level info for the IPv6 region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogDebgIp6
*
* This method generates a log with level debug for the IPv6 region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
#if OPENTHREAD_CONFIG_LOG_IP6 == 1
#define otLogCritIp6(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_IP6, aFormat, ## __VA_ARGS__)
#define otLogWarnIp6(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_IP6, aFormat, ## __VA_ARGS__)
#define otLogInfoIp6(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_IP6, aFormat, ## __VA_ARGS__)
#define otLogDebgIp6(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_IP6, aFormat, ## __VA_ARGS__)
#else
#define otLogCritIp6(aInstance, aFormat, ...)
#define otLogWarnIp6(aInstance, aFormat, ...)
#define otLogInfoIp6(aInstance, aFormat, ...)
#define otLogDebgIp6(aInstance, aFormat, ...)
#endif
/**
* @def otLogCritMac
*
* This method generates a log with level critical for the MAC region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogWarnMac
*
* This method generates a log with level warning for the MAC region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogInfoMac
*
* This method generates a log with level info for the MAC region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogDebgMac
*
* This method generates a log with level debug for the MAC region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
#if OPENTHREAD_CONFIG_LOG_MAC == 1
#define otLogCritMac(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_MAC, aFormat, ## __VA_ARGS__)
#define otLogWarnMac(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_MAC, aFormat, ## __VA_ARGS__)
#define otLogInfoMac(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_MAC, aFormat, ## __VA_ARGS__)
#define otLogDebgMac(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_MAC, aFormat, ## __VA_ARGS__)
#define otLogDebgMacErr(aInstance, aError, aFormat, ...) \
otLogWarn(aInstance, OT_LOG_REGION_MAC, "Error %s: " aFormat, otThreadErrorToString(aError), ## __VA_ARGS__)
#else
#define otLogCritMac(aInstance, aFormat, ...)
#define otLogWarnMac(aInstance, aFormat, ...)
#define otLogInfoMac(aInstance, aFormat, ...)
#define otLogDebgMac(aInstance, aFormat, ...)
#define otLogDebgMacErr(aInstance, aError, aFormat, ...)
#endif
/**
* @def otLogCritMem
*
* This method generates a log with level critical for the memory region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*
*/
/**
* @def otLogWarnMem
*
* This method generates a log with level warning for the memory region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*
*/
/**
* @def otLogInfoMem
*
* This method generates a log with level info for the memory region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogDebgMem
*
* This method generates a log with level debug for the memory region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
#if OPENTHREAD_CONFIG_LOG_MEM == 1
#define otLogCritMem(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_MEM, aFormat, ## __VA_ARGS__)
#define otLogWarnMem(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_MEM, aFormat, ## __VA_ARGS__)
#define otLogInfoMem(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_MEM, aFormat, ## __VA_ARGS__)
#define otLogDebgMem(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_MEM, aFormat, ## __VA_ARGS__)
#else
#define otLogCritMem(aInstance, aFormat, ...)
#define otLogWarnMem(aInstance, aFormat, ...)
#define otLogInfoMem(aInstance, aFormat, ...)
#define otLogDebgMem(aInstance, aFormat, ...)
#endif
/**
* @def otLogCritNetDiag
*
* This method generates a log with level critical for the NETDIAG region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogWarnNetDiag
*
* This method generates a log with level warning for the NETDIAG region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogInfoNetDiag
*
* This method generates a log with level info for the NETDIAG region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogDebgNetDiag
*
* This method generates a log with level debug for the NETDIAG region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
#if OPENTHREAD_CONFIG_LOG_NETDIAG == 1
#define otLogCritNetDiag(aInstance, aFormat, ...) \
otLogCrit(&aInstance, OT_LOG_REGION_NET_DIAG, aFormat, ## __VA_ARGS__)
#define otLogWarnNetDiag(aInstance, aFormat, ...) \
otLogWarn(&aInstance, OT_LOG_REGION_NET_DIAG, aFormat, ## __VA_ARGS__)
#define otLogInfoNetDiag(aInstance, aFormat, ...) \
otLogInfo(&aInstance, OT_LOG_REGION_NET_DIAG, aFormat, ## __VA_ARGS__)
#define otLogDebgNetDiag(aInstance, aFormat, ...) \
otLogDebg(&aInstance, OT_LOG_REGION_NET_DIAG, aFormat, ## __VA_ARGS__)
#else
#define otLogCritNetDiag(aInstance, aFormat, ...)
#define otLogWarnNetDiag(aInstance, aFormat, ...)
#define otLogInfoNetDiag(aInstance, aFormat, ...)
#define otLogDebgNetDiag(aInstance, aFormat, ...)
#endif
/**
* @def otLogCert
*
* This method generates a log with level none for the certification test.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*
*/
#if OPENTHREAD_ENABLE_CERT_LOG
#define otLogCertMeshCoP(aInstance, aFormat, ...) \
_otLogFormatter(&aInstance, OT_LOG_LEVEL_NONE, OT_LOG_REGION_MESH_COP, aFormat, ## __VA_ARGS__)
#else
#define otLogCertMeshCoP(aInstance, aFormat, ...)
#endif
/**
* @def otLogCritCli
*
* This method generates a log with level critical for the CLI region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogWarnCli
*
* This method generates a log with level warning for the CLI region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogInfoCli
*
* This method generates a log with level info for the CLI region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogDebgCli
*
* This method generates a log with level debug for the CLI region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
#if OPENTHREAD_CONFIG_LOG_CLI == 1
#define otLogCritCli(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_CLI, aFormat, ## __VA_ARGS__)
#define otLogWarnCli(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_CLI, aFormat, ## __VA_ARGS__)
#define otLogInfoCli(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_CLI, aFormat, ## __VA_ARGS__)
#define otLogInfoCliErr(aInstance, aError, aFormat, ...) \
otLogInfo(&aInstance, OT_LOG_REGION_CLI, "Error %s: " aFormat, otThreadErrorToString(aError), ## __VA_ARGS__)
#define otLogDebgCli(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_CLI, aFormat, ## __VA_ARGS__)
#else
#define otLogCritCli(aInstance, aFormat, ...)
#define otLogWarnCli(aInstance, aFormat, ...)
#define otLogInfoCli(aInstance, aFormat, ...)
#define otLogInfoCliErr(aInstance, aError, aFormat, ...)
#define otLogDebgCli(aInstance, aFormat, ...)
#endif
/**
* @def otLogCritCoap
*
* This method generates a log with level critical for the CoAP region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogWarnCoap
*
* This method generates a log with level warning for the CoAP region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogInfoCoap
*
* This method generates a log with level info for the CoAP region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogDebgCoap
*
* This method generates a log with level debug for the CoAP region.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
#if OPENTHREAD_CONFIG_LOG_COAP == 1
#define otLogCritCoap(aInstance, aFormat, ...) otLogCrit(&aInstance, OT_LOG_REGION_COAP, aFormat, ## __VA_ARGS__)
#define otLogWarnCoap(aInstance, aFormat, ...) otLogWarn(&aInstance, OT_LOG_REGION_COAP, aFormat, ## __VA_ARGS__)
#define otLogInfoCoap(aInstance, aFormat, ...) otLogInfo(&aInstance, OT_LOG_REGION_COAP, aFormat, ## __VA_ARGS__)
#define otLogInfoCoapErr(aInstance, aError, aFormat, ...) \
otLogInfo(&aInstance, OT_LOG_REGION_COAP, "Error %s: " aFormat, otThreadErrorToString(aError), ## __VA_ARGS__)
#define otLogDebgCoap(aInstance, aFormat, ...) otLogDebg(&aInstance, OT_LOG_REGION_COAP, aFormat, ## __VA_ARGS__)
#else
#define otLogCritCoap(aInstance, aFormat, ...)
#define otLogWarnCoap(aInstance, aFormat, ...)
#define otLogInfoCoap(aInstance, aFormat, ...)
#define otLogInfoCoapErr(aInstance, aError, aFormat, ...)
#define otLogDebgCoap(aInstance, aFormat, ...)
#endif
/**
* @def otLogCritPlat
*
* This method generates a log with level critical for the Platform region.
*
* @param[in] aInstance A pointer to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogWarnPlat
*
* This method generates a log with level warning for the Platform region.
*
* @param[in] aInstance A pointer to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogInfoPlat
*
* This method generates a log with level info for the Platform region.
*
* @param[in] aInstance A pointer to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
/**
* @def otLogDebgPlat
*
* This method generates a log with level debug for the Platform region.
*
* @param[in] aInstance A pointer to the OpenThread instance.
* @param[in] aFormat A pointer to the format string.
* @param[in] ... Arguments for the format specification.
*
*/
#if OPENTHREAD_CONFIG_LOG_PLATFORM == 1
#define otLogCritPlat(aInstance, aFormat, ...) otLogCrit(aInstance, OT_LOG_REGION_PLATFORM, aFormat, ## __VA_ARGS__)
#define otLogWarnPlat(aInstance, aFormat, ...) otLogWarn(aInstance, OT_LOG_REGION_PLATFORM, aFormat, ## __VA_ARGS__)
#define otLogInfoPlat(aInstance, aFormat, ...) otLogInfo(aInstance, OT_LOG_REGION_PLATFORM, aFormat, ## __VA_ARGS__)
#define otLogDebgPlat(aInstance, aFormat, ...) otLogDebg(aInstance, OT_LOG_REGION_PLATFORM, aFormat, ## __VA_ARGS__)
#else
#define otLogCritPlat(aInstance, aFormat, ...)
#define otLogWarnPlat(aInstance, aFormat, ...)
#define otLogInfoPlat(aInstance, aFormat, ...)
#define otLogDebgPlat(aInstance, aFormat, ...)
#endif
#endif // WINDOWS_LOGGING
/**
* @def otDumpCrit
*
* This method generates a memory dump with log level critical.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aRegion The log region.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_CRIT
#define otDumpCrit(aInstance, aRegion, aId, aBuf, aLength) \
otDump(&aInstance, OT_LOG_LEVEL_CRIT, aRegion, aId, aBuf, aLength)
#else
#define otDumpCrit(aInstance, aRegion, aId, aBuf, aLength)
#endif
/**
* @def otDumpWarn
*
* This method generates a memory dump with log level warning.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aRegion The log region.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN
#define otDumpWarn(aInstance, aRegion, aId, aBuf, aLength) \
otDump(&aInstance, OT_LOG_LEVEL_WARN, aRegion, aId, aBuf, aLength)
#else
#define otDumpWarn(aInstance, aRegion, aId, aBuf, aLength)
#endif
/**
* @def otDumpInfo
*
* This method generates a memory dump with log level info.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aRegion The log region.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO
#define otDumpInfo(aInstance, aRegion, aId, aBuf, aLength) \
otDump(&aInstance, OT_LOG_LEVEL_INFO, aRegion, aId, aBuf, aLength)
#else
#define otDumpInfo(aInstance, aRegion, aId, aBuf, aLength)
#endif
/**
* @def otDumpDebg
*
* This method generates a memory dump with log level debug.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aRegion The log region.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
#if OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG
#define otDumpDebg(aInstance, aRegion, aId, aBuf, aLength) \
otDump(&aInstance, OT_LOG_LEVEL_DEBG, aRegion, aId, aBuf, aLength)
#else
#define otDumpDebg(aInstance, aRegion, aId, aBuf, aLength)
#endif
/**
* @def otDumpCritNetData
*
* This method generates a memory dump with log level debug and region Network Data.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpWarnNetData
*
* This method generates a memory dump with log level warning and region Network Data.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpInfoNetData
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpDebgNetData
*
* This method generates a memory dump with log level debug and region Network Data.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
#if OPENTHREAD_CONFIG_LOG_NETDATA == 1
#define otDumpCritNetData(aInstance, aId, aBuf, aLength) \
otDumpCrit(aInstance, OT_LOG_REGION_NET_DATA, aId, aBuf, aLength)
#define otDumpWarnNetData(aInstance, aId, aBuf, aLength) \
otDumpWarn(aInstance, OT_LOG_REGION_NET_DATA, aId, aBuf, aLength)
#define otDumpInfoNetData(aInstance, aId, aBuf, aLength) \
otDumpInfo(aInstance, OT_LOG_REGION_NET_DATA, aId, aBuf, aLength)
#define otDumpDebgNetData(aInstance, aId, aBuf, aLength) \
otDumpDebg(aInstance, OT_LOG_REGION_NET_DATA, aId, aBuf, aLength)
#else
#define otDumpCritNetData(aInstance, aId, aBuf, aLength)
#define otDumpWarnNetData(aInstance, aId, aBuf, aLength)
#define otDumpInfoNetData(aInstance, aId, aBuf, aLength)
#define otDumpDebgNetData(aInstance, aId, aBuf, aLength)
#endif
/**
* @def otDumpCritMle
*
* This method generates a memory dump with log level debug and region MLE.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpWarnMle
*
* This method generates a memory dump with log level warning and region MLE.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpInfoMle
*
* This method generates a memory dump with log level info and region MLE.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpDebgMle
*
* This method generates a memory dump with log level debug and region MLE.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
#if OPENTHREAD_CONFIG_LOG_MLE == 1
#define otDumpCritMle(aInstance, aId, aBuf, aLength) otDumpCrit(aInstance, OT_LOG_REGION_MLE, aId, aBuf, aLength)
#define otDumpWarnMle(aInstance, aId, aBuf, aLength) otDumpWarn(aInstance, OT_LOG_REGION_MLE, aId, aBuf, aLength)
#define otDumpInfoMle(aInstance, aId, aBuf, aLength) otDumpInfo(aInstance, OT_LOG_REGION_MLE, aId, aBuf, aLength)
#define otDumpDebgMle(aInstance, aId, aBuf, aLength) otDumpDebg(aInstance, OT_LOG_REGION_MLE, aId, aBuf, aLength)
#else
#define otDumpCritMle(aInstance, aId, aBuf, aLength)
#define otDumpWarnMle(aInstance, aId, aBuf, aLength)
#define otDumpInfoMle(aInstance, aId, aBuf, aLength)
#define otDumpDebgMle(aInstance, aId, aBuf, aLength)
#endif
/**
* @def otDumpCritArp
*
* This method generates a memory dump with log level debug and region EID-to-RLOC mapping.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpWarnArp
*
* This method generates a memory dump with log level warning and region EID-to-RLOC mapping.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpInfoArp
*
* This method generates a memory dump with log level info and region EID-to-RLOC mapping.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpDebgArp
*
* This method generates a memory dump with log level debug and region EID-to-RLOC mapping.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
#if OPENTHREAD_CONFIG_LOG_ARP == 1
#define otDumpCritArp(aInstance, aId, aBuf, aLength) otDumpCrit(aInstance, OT_LOG_REGION_ARP, aId, aBuf, aLength)
#define otDumpWarnArp(aInstance, aId, aBuf, aLength) otDumpWarn(aInstance, OT_LOG_REGION_ARP, aId, aBuf, aLength)
#define otDumpInfoArp(aInstance, aId, aBuf, aLength) otDumpInfo(aInstance, OT_LOG_REGION_ARP, aId, aBuf, aLength)
#define otDumpDebgArp(aInstance, aId, aBuf, aLength) otDumpDebg(aInstance, OT_LOG_REGION_ARP, aId, aBuf, aLength)
#else
#define otDumpCritArp(aInstance, aId, aBuf, aLength)
#define otDumpWarnArp(aInstance, aId, aBuf, aLength)
#define otDumpInfoArp(aInstance, aId, aBuf, aLength)
#define otDumpDebgArp(aInstance, aId, aBuf, aLength)
#endif
/**
* @def otDumpCritIcmp
*
* This method generates a memory dump with log level debug and region ICMPv6.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpWarnIcmp
*
* This method generates a memory dump with log level warning and region ICMPv6.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpInfoIcmp
*
* This method generates a memory dump with log level info and region ICMPv6.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpDebgIcmp
*
* This method generates a memory dump with log level debug and region ICMPv6.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
#if OPENTHREAD_CONFIG_LOG_ICMP == 1
#define otDumpCritIcmp(aInstance, aId, aBuf, aLength) \
otDumpCrit(aInstance, OT_LOG_REGION_ICMP, aId, aBuf, aLength)
#define otDumpWarnIcmp(aInstance, aId, aBuf, aLength) \
otDumpWarn(aInstance, OT_LOG_REGION_ICMP, aId, aBuf, aLength)
#define otDumpInfoIcmp(aInstance, aId, aBuf, aLength) \
otDumpInfo(aInstance, OT_LOG_REGION_ICMP, aId, aBuf, aLength)
#define otDumpDebgIcmp(aInstance, aId, aBuf, aLength) \
otDumpDebg(aInstance, OT_LOG_REGION_ICMP, aId, aBuf, aLength)
#else
#define otDumpCritIcmp(aInstance, aId, aBuf, aLength)
#define otDumpWarnIcmp(aInstance, aId, aBuf, aLength)
#define otDumpInfoIcmp(aInstance, aId, aBuf, aLength)
#define otDumpDebgIcmp(aInstance, aId, aBuf, aLength)
#endif
/**
* @def otDumpCritIp6
*
* This method generates a memory dump with log level debug and region IPv6.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpWarnIp6
*
* This method generates a memory dump with log level warning and region IPv6.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpInfoIp6
*
* This method generates a memory dump with log level info and region IPv6.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpDebgIp6
*
* This method generates a memory dump with log level debug and region IPv6.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
#if OPENTHREAD_CONFIG_LOG_IP6 == 1
#define otDumpCritIp6(aInstance, aId, aBuf, aLength) otDumpCrit(aInstance, OT_LOG_REGION_IP6, aId, aBuf, aLength)
#define otDumpWarnIp6(aInstance, aId, aBuf, aLength) otDumpWarn(aInstance, OT_LOG_REGION_IP6, aId, aBuf, aLength)
#define otDumpInfoIp6(aInstance, aId, aBuf, aLength) otDumpInfo(aInstance, OT_LOG_REGION_IP6, aId, aBuf, aLength)
#define otDumpDebgIp6(aInstance, aId, aBuf, aLength) otDumpDebg(aInstance, OT_LOG_REGION_IP6, aId, aBuf, aLength)
#else
#define otDumpCritIp6(aInstance, aId, aBuf, aLength)
#define otDumpWarnIp6(aInstance, aId, aBuf, aLength)
#define otDumpInfoIp6(aInstance, aId, aBuf, aLength)
#define otDumpDebgIp6(aInstance, aId, aBuf, aLength)
#endif
/**
* @def otDumpCritMac
*
* This method generates a memory dump with log level debug and region MAC.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpWarnMac
*
* This method generates a memory dump with log level warning and region MAC.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpInfoMac
*
* This method generates a memory dump with log level info and region MAC.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpDebgMac
*
* This method generates a memory dump with log level debug and region MAC.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
#if OPENTHREAD_CONFIG_LOG_MAC == 1
#define otDumpCritMac(aInstance, aId, aBuf, aLength) otDumpCrit(aInstance, OT_LOG_REGION_MAC, aId, aBuf, aLength)
#define otDumpWarnMac(aInstance, aId, aBuf, aLength) otDumpWarn(aInstance, OT_LOG_REGION_MAC, aId, aBuf, aLength)
#define otDumpInfoMac(aInstance, aId, aBuf, aLength) otDumpInfo(aInstance, OT_LOG_REGION_MAC, aId, aBuf, aLength)
#define otDumpDebgMac(aInstance, aId, aBuf, aLength) otDumpDebg(aInstance, OT_LOG_REGION_MAC, aId, aBuf, aLength)
#else
#define otDumpCritMac(aInstance, aId, aBuf, aLength)
#define otDumpWarnMac(aInstance, aId, aBuf, aLength)
#define otDumpInfoMac(aInstance, aId, aBuf, aLength)
#define otDumpDebgMac(aInstance, aId, aBuf, aLength)
#endif
/**
* @def otDumpCritMem
*
* This method generates a memory dump with log level debug and region memory.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpWarnMem
*
* This method generates a memory dump with log level warning and region memory.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpInfoMem
*
* This method generates a memory dump with log level info and region memory.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
/**
* @def otDumpDebgMem
*
* This method generates a memory dump with log level debug and region memory.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
#if OPENTHREAD_CONFIG_LOG_MEM == 1
#define otDumpCritMem(aInstance, aId, aBuf, aLength) otDumpCrit(aInstance, OT_LOG_REGION_MEM, aId, aBuf, aLength)
#define otDumpWarnMem(aInstance, aId, aBuf, aLength) otDumpWarn(aInstance, OT_LOG_REGION_MEM, aId, aBuf, aLength)
#define otDumpInfoMem(aInstance, aId, aBuf, aLength) otDumpInfo(aInstance, OT_LOG_REGION_MEM, aId, aBuf, aLength)
#define otDumpDebgMem(aInstance, aId, aBuf, aLength) otDumpDebg(aInstance, OT_LOG_REGION_MEM, aId, aBuf, aLength)
#else
#define otDumpCritMem(aInstance, aId, aBuf, aLength)
#define otDumpWarnMem(aInstance, aId, aBuf, aLength)
#define otDumpInfoMem(aInstance, aId, aBuf, aLength)
#define otDumpDebgMem(aInstance, aId, aBuf, aLength)
#endif
/**
* @def otDumpCert
*
* This method generates a memory dump with log level none for the certification test.
*
* @param[in] aInstance A reference to the OpenThread instance.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
#if OPENTHREAD_ENABLE_CERT_LOG
#define otDumpCertMeshCoP(aInstance, aId, aBuf, aLength) \
otDump(&aInstance, OT_LOG_LEVEL_NONE, OT_LOG_REGION_MESH_COP, aId, aBuf, aLength)
#else
#define otDumpCertMeshCoP(aInstance, aId, aBuf, aLength)
#endif
/**
* This method dumps bytes to the log in a human-readable fashion.
*
* @param[in] aInstance A pointer to the instance.
* @param[in] aLevel The log level.
* @param[in] aRegion The log region.
* @param[in] aId A pointer to a NULL-terminated string that is printed before the bytes.
* @param[in] aBuf A pointer to the buffer.
* @param[in] aLength Number of bytes to print.
*
*/
void otDump(otInstance *aIntsance, otLogLevel aLevel, otLogRegion aRegion, const char *aId, const void *aBuf,
const size_t aLength);
#if OPENTHREAD_CONFIG_LOG_PREPEND_LEVEL == 1
/**
* This method converts the log level value into a string
*
* @param[in] aLevel The log level.
*
* @returns A const char pointer to the C string corresponding to the log level.
*
*/
const char *otLogLevelToString(otLogLevel aLevel);
#endif
#if OPENTHREAD_CONFIG_LOG_PREPEND_REGION == 1
/**
* This method converts the log region value into a string
*
* @param[in] aRegion The log region.
*
* @returns A const char pointer to the C string corresponding to the log region.
*
*/
const char *otLogRegionToString(otLogRegion aRegion);
#endif
#if OPENTHREAD_CONFIG_LOG_PREPEND_LEVEL == 1
#if OPENTHREAD_CONFIG_LOG_PREPEND_REGION == 1
/**
* Local/private macro to format the log message
*/
#define _otLogFormatter(aInstance, aLogLevel, aRegion, aFormat, ...) \
_otDynamicLog( \
aInstance, \
aLogLevel, \
aRegion, \
"[%s]%s: " aFormat OPENTHREAD_CONFIG_LOG_SUFFIX, \
otLogLevelToString(aLogLevel), \
otLogRegionToString(aRegion), \
## __VA_ARGS__ \
)
#else // OPENTHREAD_CONFIG_LOG_PREPEND_REGION
/**
* Local/private macro to format the log message
*/
#define _otLogFormatter(aInstanc, aLogLevel, aRegion, aFormat, ...) \
_otDynamicLog( \
aInstance, \
aLogLevel, \
aRegion, \
"[%s]: " aFormat OPENTHREAD_CONFIG_LOG_SUFFIX, \
otLogLevelToString(aLogLevel), \
## __VA_ARGS__ \
)
#endif
#else // OPENTHREAD_CONFIG_LOG_PREPEND_LEVEL
#if OPENTHREAD_CONFIG_LOG_PREPEND_REGION == 1
/**
* Local/private macro to format the log message
*/
#define _otLogFormatter(aInstance, aLogLevel, aRegion, aFormat, ...) \
_otDynamicLog( \
aInstance, \
aLogLevel, \
aRegion, \
"%s: " aFormat OPENTHREAD_CONFIG_LOG_SUFFIX, \
otLogRegionToString(aRegion), \
## __VA_ARGS__ \
)
#else // OPENTHREAD_CONFIG_LOG_PREPEND_REGION
/**
* Local/private macro to format the log message
*/
#define _otLogFormatter(aInstance, aLogLevel, aRegion, aFormat, ...) \
_otDynamicLog( \
aInstance, \
aLogLevel, \
aRegion, \
aFormat OPENTHREAD_CONFIG_LOG_SUFFIX, \
## __VA_ARGS__ \
)
#endif
#endif // OPENTHREAD_CONFIG_LOG_PREPEND_REGION
#if OPENTHREAD_CONFIG_ENABLE_DYNAMIC_LOG_LEVEL == 1
/**
* Local/private macro to dynamically filter log level.
*/
#define _otDynamicLog(aInstance, aLogLevel, aRegion, aFormat, ...) \
do { \
if (otGetDynamicLogLevel(aInstance) >= aLogLevel) \
_otPlatLog(aLogLevel, aRegion, aFormat, ## __VA_ARGS__); \
} while (false)
#else // OPENTHREAD_CONFIG_ENABLE_DYNAMIC_LOG_LEVEL
#define _otDynamicLog(aInstance, aLogLevel, aRegion, aFormat, ...) \
_otPlatLog(aLogLevel, aRegion, aFormat, ## __VA_ARGS__)
#endif // OPENTHREAD_CONFIG_ENABLE_DYNAMIC_LOG_LEVEL
/**
* `OPENTHREAD_CONFIG_PLAT_LOG_FUNCTION` is a configuration parameter (see `openthread-core-default-config.h`) which
* specifies the function/macro to be used for logging in OpenThread. By default it is set to `otPlatLog()`.
*/
#define _otPlatLog(aLogLevel, aRegion, aFormat, ...) \
OPENTHREAD_CONFIG_PLAT_LOG_FUNCTION(aLogLevel, aRegion, aFormat, ## __VA_ARGS__)
#ifdef __cplusplus
};
#endif
#endif // LOGGING_HPP_
|
fbsder/openthread
|
src/core/common/logging.hpp
|
C++
|
bsd-3-clause
| 57,051 |
{% extends "base.html" %}
{% block head_title %}{% if object %}Update Hypothesis {{object}}{% else %} New Hypothesis {% endif %}{% endblock %}
{% block title %}{% if object %}Update Hypothesis {{object}}{% else %} New Hypothesis {% endif %}{% endblock %}
{% block scripts %}
{% endblock %}
{% block content %}
<form method="POST" action=".">{% csrf_token %}
<table>{{ form }}</table>
<input type="submit" value="Submit" />
</form>
{% endblock %}
|
davebridges/ExperimentDB
|
hypotheses/templates/hypothesis_form.html
|
HTML
|
bsd-3-clause
| 447 |
package nodefs
import (
"log"
"sync"
"github.com/hanwen/go-fuse/fuse"
)
// An Inode reflects the kernel's idea of the inode. Inodes have IDs
// that are communicated to the kernel, and they have a tree
// structure: a directory Inode may contain named children. Each
// Inode object is paired with a Node object, which file system
// implementers should supply.
type Inode struct {
handled handled
// Generation number of the inode. Each (re)use of an inode
// should have a unique generation number.
generation uint64
// Number of open files and its protection.
openFilesMutex sync.Mutex
openFiles []*openedFile
fsInode Node
// Each inode belongs to exactly one fileSystemMount. This
// pointer is constant during the lifetime, except upon
// Unmount() when it is set to nil.
mount *fileSystemMount
// All data below is protected by treeLock.
children map[string]*Inode
// Non-nil if this inode is a mountpoint, ie. the Root of a
// NodeFileSystem.
mountPoint *fileSystemMount
}
func newInode(isDir bool, fsNode Node) *Inode {
me := new(Inode)
if isDir {
me.children = make(map[string]*Inode, initDirSize)
}
me.fsInode = fsNode
me.fsInode.SetInode(me)
return me
}
// public methods.
// Returns any open file, preferably a r/w one.
func (n *Inode) AnyFile() (file File) {
n.openFilesMutex.Lock()
for _, f := range n.openFiles {
if file == nil || f.WithFlags.OpenFlags&fuse.O_ANYWRITE != 0 {
file = f.WithFlags.File
}
}
n.openFilesMutex.Unlock()
return file
}
// Children returns all children of this inode.
func (n *Inode) Children() (out map[string]*Inode) {
n.mount.treeLock.RLock()
out = make(map[string]*Inode, len(n.children))
for k, v := range n.children {
out[k] = v
}
n.mount.treeLock.RUnlock()
return out
}
// FsChildren returns all the children from the same filesystem. It
// will skip mountpoints.
func (n *Inode) FsChildren() (out map[string]*Inode) {
n.mount.treeLock.RLock()
out = map[string]*Inode{}
for k, v := range n.children {
if v.mount == n.mount {
out[k] = v
}
}
n.mount.treeLock.RUnlock()
return out
}
// Node returns the file-system specific node.
func (n *Inode) Node() Node {
return n.fsInode
}
// Files() returns an opens file that have bits in common with the
// give mask. Use mask==0 to return all files.
func (n *Inode) Files(mask uint32) (files []WithFlags) {
n.openFilesMutex.Lock()
for _, f := range n.openFiles {
if mask == 0 || f.WithFlags.OpenFlags&mask != 0 {
files = append(files, f.WithFlags)
}
}
n.openFilesMutex.Unlock()
return files
}
// IsDir returns true if this is a directory.
func (n *Inode) IsDir() bool {
return n.children != nil
}
// NewChild adds a new child inode to this inode.
func (n *Inode) NewChild(name string, isDir bool, fsi Node) *Inode {
ch := newInode(isDir, fsi)
ch.mount = n.mount
n.generation = ch.mount.connector.nextGeneration()
n.AddChild(name, ch)
return ch
}
// GetChild returns a child inode with the given name, or nil if it
// does not exist.
func (n *Inode) GetChild(name string) (child *Inode) {
n.mount.treeLock.RLock()
child = n.children[name]
n.mount.treeLock.RUnlock()
return child
}
// AddChild adds a child inode. The parent inode must be a directory
// node.
func (n *Inode) AddChild(name string, child *Inode) {
if child == nil {
log.Panicf("adding nil child as %q", name)
}
n.mount.treeLock.Lock()
n.addChild(name, child)
n.mount.treeLock.Unlock()
}
// RmChild removes an inode by name, and returns it. It returns nil if
// child does not exist.
func (n *Inode) RmChild(name string) (ch *Inode) {
n.mount.treeLock.Lock()
ch = n.rmChild(name)
n.mount.treeLock.Unlock()
return
}
//////////////////////////////////////////////////////////////
// private
// Must be called with treeLock for the mount held.
func (n *Inode) addChild(name string, child *Inode) {
if paranoia {
ch := n.children[name]
if ch != nil {
log.Panicf("Already have an Inode with same name: %v: %v", name, ch)
}
}
n.children[name] = child
}
// Must be called with treeLock for the mount held.
func (n *Inode) rmChild(name string) (ch *Inode) {
ch = n.children[name]
if ch != nil {
delete(n.children, name)
}
return ch
}
// Can only be called on untouched root inodes.
func (n *Inode) mountFs(opts *Options) {
n.mountPoint = &fileSystemMount{
openFiles: newPortableHandleMap(),
mountInode: n,
options: opts,
}
n.mount = n.mountPoint
}
// Must be called with treeLock held.
func (n *Inode) canUnmount() bool {
for _, v := range n.children {
if v.mountPoint != nil {
// This access may be out of date, but it is no
// problem to err on the safe side.
return false
}
if !v.canUnmount() {
return false
}
}
n.openFilesMutex.Lock()
ok := len(n.openFiles) == 0
n.openFilesMutex.Unlock()
return ok
}
func (n *Inode) getMountDirEntries() (out []fuse.DirEntry) {
n.mount.treeLock.RLock()
for k, v := range n.children {
if v.mountPoint != nil {
out = append(out, fuse.DirEntry{
Name: k,
Mode: fuse.S_IFDIR,
})
}
}
n.mount.treeLock.RUnlock()
return out
}
const initDirSize = 20
func (n *Inode) verify(cur *fileSystemMount) {
n.handled.verify()
if n.mountPoint != nil {
if n != n.mountPoint.mountInode {
log.Panicf("mountpoint mismatch %v %v", n, n.mountPoint.mountInode)
}
cur = n.mountPoint
cur.treeLock.Lock()
defer cur.treeLock.Unlock()
}
if n.mount != cur {
log.Panicf("n.mount not set correctly %v %v", n.mount, cur)
}
for nm, ch := range n.children {
if ch == nil {
log.Panicf("Found nil child: %q", nm)
}
ch.verify(cur)
}
}
|
keybase/go-fuse
|
fuse/nodefs/inode.go
|
GO
|
bsd-3-clause
| 5,625 |
/**
* @file netconf_subscribed_notifications.h
* @author Michal Vasko <[email protected]>
* @brief ietf-subscribed-notifications callbacks header
*
* @copyright
* Copyright (c) 2019 - 2021 Deutsche Telekom AG.
* Copyright (c) 2017 - 2021 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*/
#ifndef NP2SRV_NETCONF_SUBSCRIBED_NOTIFICATIONS_H_
#define NP2SRV_NETCONF_SUBSCRIBED_NOTIFICATIONS_H_
#include <libyang/libyang.h>
#include <sysrepo.h>
#include "common.h"
/**
* @brief Type of a subscribed-notifications subscription.
*/
enum sub_ntf_type {
SUB_TYPE_SUB_NTF, /**< standard subscribed-notifications subscription */
SUB_TYPE_YANG_PUSH /**< yang-push subscription */
};
/**
* @brief Complete operational information about the subscriptions.
*/
struct np2srv_sub_ntf_info {
pthread_rwlock_t lock;
ATOMIC_T sub_id_lock; /* subscription ID that holds the lock, if a notification callback is called with this ID,
it must not attempt locking and can access this structure directly */
struct np2srv_sub_ntf {
uint32_t nc_id;
uint32_t nc_sub_id;
uint32_t *sub_ids;
ATOMIC_T sub_id_count;
const char *term_reason;
struct timespec stop_time;
int terminating; /* set flag means the WRITE lock for this subscription will not be granted */
ATOMIC_T sent_count; /* sent notifications counter */
ATOMIC_T denied_count; /* counter of notifications denied by NACM */
enum sub_ntf_type type;
void *data;
} *subs;
uint32_t count;
};
/*
* for specific subscriptions
*/
/**
* @brief Lock the sub-ntf lock, if possible, and return a subscription.
*
* @param[in] nc_sub_id NC sub ID of the subscription.
* @param[in] sub_id SR subscription ID in a callback, 0 if not in callback.
* @param[in] write Whether to write or read-lock.
* @return Found subscription.
* @return NULL if subscription was not found or it is terminating.
*/
struct np2srv_sub_ntf *sub_ntf_find_lock(uint32_t nc_sub_id, uint32_t sub_id, int write);
/**
* @brief Unlock the sub-ntf lock.
*
* @param[in] sub_id SR subscription ID in a callback, 0 if not in callback.
*/
void sub_ntf_unlock(uint32_t sub_id);
/**
* @brief Find the next matching sub-ntf subscription structure.
*
* @param[in] last Last found structure, NULL on first call.
* @param[in] sub_ntf_match_cb Callback for deciding a subscription match.
* @param[in] match_data Data passed to @p sub_ntf_match_cb based on which a match is decided.
* @return Next matching subscription.
* @return NULL if no more matching subscriptions found.
*/
struct np2srv_sub_ntf *sub_ntf_find_next(struct np2srv_sub_ntf *last,
int (*sub_ntf_match_cb)(struct np2srv_sub_ntf *sub, const void *match_data), const void *match_data);
/**
* @brief Send a notification.
*
* @param[in] ncs NETCONF session to use.
* @param[in] nc_sub_id NETCONF sub ID of the subscription.
* @param[in] timestamp Timestamp to use.
* @param[in,out] ly_ntf Notification to send.
* @param[in] use_ntf Whether to free @p ly_ntf and set to NULL or leave unchanged.
* @return Sysrepo error value.
*/
int sub_ntf_send_notif(struct nc_session *ncs, uint32_t nc_sub_id, struct timespec timestamp, struct lyd_node **ly_ntf,
int use_ntf);
/**
* @brief If holding the sub-ntf lock, pass it to another callback that will be called by some following code.
*
* Clear with sub_ntf_cb_lock_clear().
*
* @param[in] sub_id Sysrepo subscription ID obtained in the callback.
*/
void sub_ntf_cb_lock_pass(uint32_t sub_id);
/**
* @brief Clear the passed sub-ntf lock.
*
* @param[in] sub_id Sysrepo subscription ID that the lock was passed to.
*/
void sub_ntf_cb_lock_clear(uint32_t sub_id);
/**
* @brief Increase denied notification count for a subscription.
*
* @param[in] nc_sub_id NETCONF sub ID of the subscription.
*/
void sub_ntf_inc_denied(uint32_t nc_sub_id);
/**
* @brief Correctly terminate a ntf-sub subscription.
* ntf-sub lock is expected to be held.
*
* @param[in] sub Subscription to terminate, is freed.
* @param[in] ncs NETCONF session.
* @return Sysrepo error value.
*/
int sub_ntf_terminate_sub(struct np2srv_sub_ntf *sub, struct nc_session *ncs);
/**
* @brief Send a subscription-modified notification.
*
* @param[in] sub Subscription structure that was modified.
* @return Sysrepo error value.
*/
int sub_ntf_send_notif_modified(const struct np2srv_sub_ntf *sub);
/*
* for main.c
*/
void np2srv_sub_ntf_session_destroy(struct nc_session *ncs);
void np2srv_sub_ntf_destroy(void);
int np2srv_rpc_establish_sub_cb(sr_session_ctx_t *session, uint32_t sub_id, const char *op_path,
const struct lyd_node *input, sr_event_t event, uint32_t request_id, struct lyd_node *output, void *private_data);
int np2srv_rpc_modify_sub_cb(sr_session_ctx_t *session, uint32_t sub_id, const char *op_path, const struct lyd_node *input,
sr_event_t event, uint32_t request_id, struct lyd_node *output, void *private_data);
int np2srv_rpc_delete_sub_cb(sr_session_ctx_t *session, uint32_t sub_id, const char *op_path, const struct lyd_node *input,
sr_event_t event, uint32_t request_id, struct lyd_node *output, void *private_data);
int np2srv_rpc_kill_sub_cb(sr_session_ctx_t *session, uint32_t sub_id, const char *op_path, const struct lyd_node *input,
sr_event_t event, uint32_t request_id, struct lyd_node *output, void *private_data);
int np2srv_config_sub_ntf_filters_cb(sr_session_ctx_t *session, uint32_t sub_id, const char *module_name,
const char *xpath, sr_event_t event, uint32_t request_id, void *private_data);
int np2srv_oper_sub_ntf_streams_cb(sr_session_ctx_t *session, uint32_t sub_id, const char *module_name, const char *path,
const char *request_xpath, uint32_t request_id, struct lyd_node **parent, void *private_data);
int np2srv_oper_sub_ntf_subscriptions_cb(sr_session_ctx_t *session, uint32_t sub_id, const char *module_name,
const char *path, const char *request_xpath, uint32_t request_id, struct lyd_node **parent, void *private_data);
#endif /* NP2SRV_NETCONF_SUBSCRIBED_NOTIFICATIONS_H_ */
|
CESNET/Netopeer2
|
src/netconf_subscribed_notifications.h
|
C
|
bsd-3-clause
| 6,412 |
// DynamicSolid.h
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#pragma once
#include "../interface/ObjList.h"
class DynamicSolid:public ObjList{
public:
CFaceList* m_faces;
CEdgeList* m_edges;
CVertexList* m_vertices;
std::list<TopoDS_Shape> m_shapes;
DynamicSolid();
~DynamicSolid();
//virtual const DynamicSolid& operator=(const DynamicSolid& s);
int GetType()const{return SolidType;}
long GetMarkingMask()const{return MARKING_FILTER_SOLID;}
const wxChar* GetTypeString(void)const{return _("Solid");}
void ReloadPointers();
virtual SolidTypeEnum GetSolidType(){return SOLID_TYPE_UNKNOWN;}
virtual gp_Trsf GetTransform(){return gp_Trsf();}
void SetShapes(std::list<TopoDS_Shape>);
void DrawShapes();
virtual void Update(){}
};
|
jehc/heekscad
|
src/DynamicSolid.h
|
C
|
bsd-3-clause
| 830 |
BOSSA 1.4 for Arduino
This version of BOSSA is a fork of the original project and contains some
patches specific for the Arduino products that are unlike to be accepted
upstream.
The original software is developed by Scott Shumate and can be found here:
http://www.shumatech.com/web/products/bossa
BOSSA 1.5-arduino
-----------------
* Added Codelite project for easier development and debug.
* Improved support for SAMD21 chip by using existing applet already in use for other devices.
* Added time count for operations erase, write, read and verify.
* Added Devices.h for global definitions for each devices.
* NVMFlash::write() rewritten.
* Removed some useless functions from 1.4 release.
* Added a mask for SAMD chipid: DIE and REV bitfields are not taken into account as they may vary in the time without impacting the features.
* Improved write time performance by a factor of 2x
BOSSA 1.4-arduino
-----------------
* Added support for SAMD21 chip
BOSSA 1.2
---------
FILES
bossa-1.2.msi -- Windows 2000+
bossa64-1.2.msi -- Windows 2000+ 64-bit
bossa-i686-1.2.tgz -- Linux GTK
bossa-x86_64-1.2.tgz -- Linux GTK 64-bit
bossa-1.2.dmg -- MAC OS X 10.6+
NEW IN THIS RELEASE
* New BOSSA shell command line application to do basic memory, flash, and PIO diagnostics
* Workaround for SAM3U firmware bug
* Fixed a bug with setting boot to flash bit on SAM3 devices
RELEASE NOTES
* The OS X USB driver detects an Atmel device as a USB modem. When prompted about a new network interface, click Cancel to continue.
* Some stability issues have been seen with the OS X USB driver using BOSSA. When running BOSSA a second time to the same Atmel device, the USB driver can lock up causing BOSSA to freeze. As a workaround, always disconnect and reconnect the Atmel device before running BOSSA again.
* The firmware inside of SAM3U devices has a bug where non-word flash reads return zero instead of the real data. BOSSA implements a transparent workaround for flash operations that copies flash to SRAM before reading. Direct reads using the BOSSA shell will see the bug.
* There are reports that the USB controller in some AMD-based systems has difficulty communicating with SAM devices. The only known workaround is to use a different, preferrably Intel-based, system.
|
arduino-org/BOSSA
|
README.md
|
Markdown
|
bsd-3-clause
| 2,295 |
# Copyright 2015, MASSACHUSETTS INSTITUTE OF TECHNOLOGY
# Subject to FAR 52.227-11 – Patent Rights – Ownership by the Contractor (May 2014).
# SPDX-License-Identifier: BSD-3-Clause
# Native
import logging
logger = logging.getLogger(__name__)
import struct
import subprocess
import os
# Pysmartcard
from smartcard.sw.ISO7816_4ErrorChecker import ISO7816_4ErrorChecker
from smartcard.sw.ISO7816_8ErrorChecker import ISO7816_8ErrorChecker
from smartcard.sw.ISO7816_9ErrorChecker import ISO7816_9ErrorChecker
from smartcard.sw.ErrorCheckingChain import ErrorCheckingChain
from smartcard.sw.SWExceptions import SWException
# Pydes
import pyDes
# LL Smartcard
import apdu as APDU
class SmartCard:
# Setup our error chain
errorchain = []
errorchain = [ ErrorCheckingChain(errorchain, ISO7816_9ErrorChecker()),
ErrorCheckingChain(errorchain, ISO7816_8ErrorChecker()),
ErrorCheckingChain(errorchain, ISO7816_4ErrorChecker()) ]
def __init__(self, connection, log_level=None):
self.SECURE_CHANNEL = False
self.session_keys = None
if log_level is not None:
logging.basicConfig(level=log_level)
self.__conn = connection
def _log_apdu(self, apdu_data):
logger.debug("APDU: " + APDU.get_hex(apdu_data))
def _log_result(self, data, sw1, sw2):
logger.debug("RESULT: (%s,%s) %s (str: %s)" % (hex(sw1),
hex(sw2),
APDU.get_hex(data),
APDU.get_str(data)))
# See if our status word was an error
try:
self.errorchain[0]([], sw1, sw2)
except SWException, e:
# Did we get an unsuccessful attempt?
logger.debug(e)
def _send_apdu(self, apdu_data):
"""
Send the proper APDU, depending on what mode we are operating in.
@param apdu_data: RAW APDU data to send
@return: (data, sw1, sw2)
"""
if self.SECURE_CHANNEL is False or self.SECURE_CHANNEL == APDU.SECURE_CHANNEL.MODE.NONE:
return self._send_apdu_raw(apdu_data)
elif self.SECURE_CHANNEL == APDU.SECURE_CHANNEL.MODE.MAC:
return self._send_apdu_mac(apdu_data)
else:
logger.error("This Secure Channel APDU mode is not currently supported.")
def _send_apdu_raw(self, apdu_data):
"""
Send APDU to card and return the data and status words.
If the result has more data, this will also retrieve the additional
data.
@param apdu_data: RAW APDU to send stored in a list
@return: (data, sw1, sw2)
"""
# Send the APDU
self._log_apdu(apdu_data)
data, sw1, sw2 = self.__conn.transmit(apdu_data)
self._log_result(data, sw1, sw2)
# Is there more data in the response?
while sw1 == APDU.APDU_STATUS.MORE_DATA:
apdu_get_response = APDU.GET_RESPONSE(sw2)
self._log_apdu(apdu_get_response)
data2, sw1, sw2 = self.__conn.transmit(apdu_get_response)
data += data2
self._log_result(data2, sw1, sw2)
# Return our status and data
return (data, sw1, sw2)
def _send_apdu_mac(self, apdu_data):
"""
Send a secure APDU. This is done by calculating a C-MAC and
appending it to the end of the message
IMPORTANT: This will automatically adjust Lc for you!
@param apdu_data: APDU data to send
@return: data, sw1, sw2
"""
if self.session_keys is None:
logger.error("A secure session has not been established.")
return
if apdu_data[0] != 0x84:
logger.warn("Class is not 0x84 in secure message.")
apdu_data[0] = 0x84
# Trim Le if needed
Le = 0x00
if len(apdu_data) > 5 + apdu_data[4]:
Le = apdu_data[-1]
apdu_data = apdu_data[:-1]
# Increment Lc
apdu_data[4] = apdu_data[4] + 8
# Use our MAC key
mac_key = self.session_keys[APDU.AUTH_KEY_IDX.MAC]
# Setup our 3-DES MAC instance
des3_mac = pyDes.triple_des(mac_key, mode=pyDes.CBC,
IV="\x00\x00\x00\x00\x00\x00\x00\x00")
# Add padding and pack it up for pyDes
apdu_extern_auth_packed = [struct.pack('B', x) for x in self._pad_plaintext(apdu_data)]
c_mac = des3_mac.encrypt(apdu_extern_auth_packed)[-8:]
c_mac = list(struct.unpack('%dB' % len(c_mac), c_mac))
logger.debug("C-MAC: %s" % APDU.get_hex(c_mac))
# Append MAC to APDU
apdu_data += c_mac + [Le]
# Send appended APDU
return self._send_apdu_raw(apdu_data)
def _report_error(self, sw1, sw2, error):
""" Print Error """
# @todo: Figure out the SW1 SW2 meaning
print "ERROR (%s,%s): %s" % (hex(sw1), hex(sw2), error)
def _generate_random(self, length):
"""
Generate a list of random bytes
@param length: Number of bytes to generate
@return: List of random bytes
"""
rtn = []
for i in range(length):
rtn.append(ord(os.urandom(1)))
return rtn
def _pad_plaintext(self, plaintext):
"""
Pad out any plaintext to be fed into MAC functions
@param plaintext: plaintext to pad
@return: a copy of plaintext with padding appended
"""
# ensure the plaintext is divisible by 8 and that at least some padding is added
pad = False
plaintext = list(plaintext)
while len(plaintext) % 8 != 0 or not pad:
if pad:
plaintext.append(0x00)
else:
plaintext.append(0x80)
pad = True
return plaintext
def _str_privs(self, privs):
"""
"""
out = []
if 0b10000000 & privs:
out.append("Security Domain")
if 0b01000000 & privs:
out.append("DAP DES Verification")
if 0b00100000 & privs:
out.append("RFU")
if 0b00010000 & privs:
out.append("Card Manager Lock Privilege")
if 0b00001000 & privs:
out.append("Card Terminate Privilege")
if 0b00000100 & privs:
out.append("Default Selected Applet")
if 0b00000010 & privs:
out.append("PIN Change")
if 0b00000001 & privs:
out.append("RFU")
return out
def _print_gp_registry_data(self, input_data):
"""
Decode Applicaiton Data
Reference: GP 2.1.1 / page 115
"""
offset = 0
while offset < len(input_data):
t = input_data[offset]
if t == 0x9F and input_data[offset + 1] == 0x70:
t = 0x9f70
offset += 1
length = input_data[offset + 1]
value = input_data[offset + 2:offset + 2 + length]
if t == 0x4f:
print "AID: %s" % APDU.get_hex(value)
elif t == 0x9f70:
print " Life Cycle State: %08s" % '{0:08b}'.format(value[0])
elif t == 0xc5:
print " Application Privleges: %s %s" % (APDU.get_hex(value),
self._str_privs(value[0]))
elif t == 0x84:
print " Executable Module ID: %s" % (APDU.get_hex(value))
else:
print " UNKNOWN: t:%s, l:%s, v:%s" % (hex(t), hex(length),
APDU.get_hex(value))
offset += length + 2
def apdu_select_application(self, application_id, pix=[], p1=0x04, p2=0x00):
"""
Send APDU to select a Java Applet and return results
@param application_id: The AID of the application on the card in a list
@return: (data, sw1, sw2)
"""
apdu_select = APDU.SELECT(application_id + pix, P1=p1, P2=p2)
data, sw1, sw2 = self._send_apdu(apdu_select)
if sw1 != APDU.APDU_STATUS.SUCCESS:
print "ERROR (%s,%s): SELECT failed." % (hex(sw1), hex(sw2))
return (data, sw1, sw2)
def apdu_select_object(self, object_id, p1=0x02, p2=0x00):
"""
Send APDU to select a Java Applet and return results
@param object_id: The OID of the object on the card in a list
@return: (data, sw1, sw2)
"""
apdu_select = APDU.SELECT(object_id, P1=p1, P2=p2)
data, sw1, sw2 = self._send_apdu(apdu_select)
if sw1 != APDU.APDU_STATUS.SUCCESS:
print "ERROR (%s,%s): SELECT failed." % (hex(sw1), hex(sw2))
return (data, sw1, sw2)
def apdu_select_df(self, file_id, p1=0x01, p2=0x00):
"""
Send APDU to select a Directory File (Within master file)
@param file_id: 2 byte file ID to select
@param p2: 0x00 or 0x0c
@return: (data, sw1, sw2)
"""
apdu_select = APDU.SELECT(file_id, P1=p1, P2=p2)
data, sw1, sw2 = self._send_apdu(apdu_select)
if sw1 != APDU.APDU_STATUS.SUCCESS:
print "ERROR (%s,%s): SELECT failed." % (hex(sw1), hex(sw2))
return (data, sw1, sw2)
def apdu_select_ef(self, file_id, p1=0x02, p2=0x00):
"""
Send APDU to select a Elementary File (or Object)
@param file_id: 2 byte file ID to select
@param p2: 0x00 or 0x0c
@return: (data, sw1, sw2)
"""
apdu_select = APDU.SELECT(file_id, P1=p1, P2=p2)
data, sw1, sw2 = self._send_apdu(apdu_select)
if sw1 != APDU.APDU_STATUS.SUCCESS:
print "ERROR (%s,%s): SELECT failed." % (hex(sw1), hex(sw2))
return (data, sw1, sw2)
def apdu_select_mf(self, file_id, p1=0x03, p2=0x00):
"""
Send APDU to select a Master File
@param file_id: 2 byte file ID to select
@param p2: 0x00 or 0x0c
@return: (data, sw1, sw2)
"""
# @todo: Try all classes
apdu_select = APDU.SELECT(file_id, CLA=0x80, P1=p1, P2=p2)
data, sw1, sw2 = self._send_apdu(apdu_select)
if sw1 != APDU.APDU_STATUS.SUCCESS:
print "ERROR (%s,%s): SELECT failed." % (hex(sw1), hex(sw2))
return (data, sw1, sw2)
def apdu_get_data(self, address):
"""
Send APDU to get data and return results
@param p1: high order byte
@param p2: low order byte
@return: (data, sw1, sw2)
"""
p1 = address[0]
p2 = address[1]
apdu_get_data = APDU.GET_DATA(p1, p2)
data, sw1, sw2 = self._send_apdu(apdu_get_data)
if sw1 == APDU.APDU_STATUS.WRONG_LENGTH:
apdu_get_data2 = APDU.GET_DATA(p1, p2, Lc=sw2)
return self._send_apdu(apdu_get_data2)
return (data, sw1, sw2)
def apdu_read_record(self, p1, p2, cla=0x00):
"""
Send APDU to get data and return results
Reference: GP 2.1.1 / D.4.1
@param p1: high order byte
@param p2: low order byte
@return: (data, sw1, sw2)
"""
apdu_read_record = APDU.READ_RECORD(p1, p2, CLA=cla)
data, sw1, sw2 = self._send_apdu(apdu_read_record)
if sw1 == APDU.APDU_STATUS.WRONG_LENGTH:
apdu_read_record2 = APDU.READ_RECORD(p1, p2, CLA=cla, Le=sw2)
data, sw1, sw2 = self._send_apdu(apdu_read_record2)
return (data, sw1, sw2)
def apdu_init_update(self, p1, p2, challenge=None):
"""
Send Initialize Update APDU to initialize a new secure channel.
@param p1: Key version number (Default: 0)
@param p2: Key identifier (Default: 0)
@param challenge: 8 byte random number
"""
# Generate a new random number?
if challenge is None:
challenge = self._generate_random(8)
apdu_init_update = APDU.INIT_UPDATE(p1, p2, challenge)
data, sw1, sw2 = self._send_apdu(apdu_init_update)
return (data, sw1, sw2)
def print_applications(self):
"""
Once a secure channel is opened, list all Applications on the card.
"""
for domain in [0x80, 0x40, 0x20, 0x10]:
# Get Next
apdu = APDU.GET_STATUS(domain, 0x02, APDU.SEARCH_CRITERIA.AID)
data, sw1, sw2 = self._send_apdu(apdu)
offset = 0
while offset < len(data):
t = data[offset]
length = data[offset + 1]
value = data[offset + 2:offset + 2 + length]
if t == 0xE3:
self._print_gp_registry_data(value)
else:
logger.error("Invalid data returned.")
offset += length + 2
return (data, sw1, sw2)
def apdu_get_status(self, p1, p2, search_criteria):
"""
Send Get Status APDU
@param P1: 80 - Issuer Security Domain
40 - Application Security Domain
20 - Executable Load Files only
10 - Executable Load Files and their Executable Modules only
@param P2: 0bx0 - get all/first occurrence(s)
0bx1 - get next
0b0x - Response Structure 1
0b1x - Response Structure 2
@param search_criteria: 4f00 used to indicated AID
"""
apdu = APDU.GET_STATUS(p1, p2, search_criteria)
data, sw1, sw2 = self._send_apdu(apdu)
return (data, sw1, sw2)
def apdu_authenticate(self, card_challenge, rand_challenge, cryptogram,
security_level=APDU.SECURE_CHANNEL.MODE.NONE):
"""
Given both of our Nonces, send back our authentication apdu
@param card_challege: Nonce from card
@param rand_challege: Nonce generated by host
@param cryptogram: Cryptogram sent by card
@return: data, sw1, sw2
"""
if self.session_keys is None:
logger.error("Secure Channel hasn't be opened yet.")
return
# Get ready for authentication
auth_key = self.session_keys[APDU.AUTH_KEY_IDX.AUTH]
# Setup our 3-DES MAC instance
des3_auth = pyDes.triple_des(auth_key, mode=pyDes.CBC,
IV="\x00\x00\x00\x00\x00\x00\x00\x00")
#
# Validate our cryptogram
#
# Generate our plaintext
card_cryptogram_plaintext = rand_challenge + card_challenge
# Pad appropriately
card_cryptogram_plaintext = self._pad_plaintext(card_cryptogram_plaintext)
# Pack up for pyDes
card_cryptogram_plaintext = [struct.pack('B', x) for x in card_cryptogram_plaintext]
# Generate our cryptogram
cryptogram_host_ciphertext = des3_auth.encrypt(card_cryptogram_plaintext)
cryptogram_host_mac = cryptogram_host_ciphertext[-8:]
cryptogram_host = struct.unpack('%dB' % len(cryptogram_host_mac), cryptogram_host_mac)
cryptogram_host = list(cryptogram_host)
# Check our cryptogram
if cryptogram_host != cryptogram:
logger.error("Cryptogram Invalid for this card!")
return False
#
# Generate our authentication response
#
# Generate Plaintext
card_auth_plaintext = card_challenge + rand_challenge
# Pad appropriately
card_auth_plaintext = self._pad_plaintext(card_auth_plaintext)
# Pack up for pyDes
card_auth_plaintext = [struct.pack('B', x) for x in card_auth_plaintext]
# Generate our authentication response
auth_host_ciphertext = des3_auth.encrypt(card_auth_plaintext)[-8:]
auth_cryptogram = list(struct.unpack('%dB' % len(auth_host_ciphertext), auth_host_ciphertext))
logger.debug("Authentication Cryptogram: %s" % APDU.get_hex(auth_cryptogram))
# Generate our C-MAC for the response
apdu_extern_auth = APDU.EXTERNAL_AUTHENTICATE(security_level,
auth_cryptogram, [])
# Send the APDU in C-MAC mode
return self._send_apdu_mac(apdu_extern_auth)
def open_secure_channel(self, aid, keys,
security_level=APDU.SECURE_CHANNEL.MODE.NONE):
"""
Open secure channel to allow security functions
@param keys: Keys to use for this channel
@return: True/False
"""
self.keys = keys
#
# Define some supplementary functions
#
def fill_data(diversify_data, idx, diver_type=APDU.SECURE_CHANNEL.DIVERSIFY.VISA2):
"""
Given the diversity data from the card and the index for the key
to be generated, this will fill out the data appropriately to
generate a diversified key
@param diversify_data: diversity data from the card
@param idx: key index to generate the plaintext for
@diver_type: Type of diversification, VISA2 or default
"""
data = []
if diver_type == APDU.SECURE_CHANNEL.DIVERSIFY.VISA2:
# VISA2
data.append(diversify_data[0])
data.append(diversify_data[1])
data.append(diversify_data[4])
data.append(diversify_data[5])
data.append(diversify_data[6])
data.append(diversify_data[7])
data.append(0xF0)
data.append(idx)
data.append(diversify_data[0])
data.append(diversify_data[1])
data.append(diversify_data[4])
data.append(diversify_data[5])
data.append(diversify_data[6])
data.append(diversify_data[7])
data.append(0x0F)
data.append(idx)
elif diver_type is None:
# EMV
data.append(diversify_data[4])
data.append(diversify_data[5])
data.append(diversify_data[6])
data.append(diversify_data[7])
data.append(diversify_data[8])
data.append(diversify_data[9])
data.append(0xF0)
data.append(idx)
data.append(diversify_data[4])
data.append(diversify_data[5])
data.append(diversify_data[6])
data.append(diversify_data[7])
data.append(diversify_data[8])
data.append(diversify_data[9])
data.append(0x0F)
data.append(idx)
else:
return None
return data
def get_diversified_keys(keys, diversify_data, diver_type=APDU.SECURE_CHANNEL.DIVERSIFY.VISA2):
"""
Given the keys and diversity data from the card, generate the
diversified keys.
@param keys: keys to be diversified
@param diversify_data: Diversity data from the card
@param diver_type: VISA or default
@return: List of diversified keys
"""
logger.debug("Diversifying keys...")
# Diversify each key
for i in range(len(keys)):
# Get the data to encrypt
data = fill_data(diversify_data, i + 1, diver_type)
logger.debug("data: %s" % data)
logger.debug("key: %s" % keys[i])
# Unpack in the form that pyDes Expects
data = [struct.pack('B', x) for x in data]
# Encrypt data to get new key
des3 = pyDes.triple_des(keys[i])
keys[i] = des3.encrypt(data)
return keys
def get_session_keys(keys, rand_challenge, card_challenge):
"""
Derive the session keys using the two nonces and the input keys
@param keys: Keys to use for this session
@param rand_challenge: Nonce sent from host
@para card_challenge: Nonce sent from card
@return: list of session keys
"""
derivation_data = card_challenge[4:] + \
rand_challenge[0:4] + \
card_challenge[0:4] + \
rand_challenge[4:]
logger.debug("Deriving session keys..")
logger.debug("derivData: %s" % derivation_data)
# Unpack in the form that pyDes Expects
derivation_data = [struct.pack('B', x) for x in derivation_data]
session_keys = []
for i in range(len(keys) - 1):
# Pack in the form that pyDes Expects
des3 = pyDes.triple_des(keys[i])
session_key = des3.encrypt(derivation_data)
# session_key = struct.unpack('%dB' % len(session_key), session_key)
session_keys.append(session_key)
# The last key remains the same
session_keys.append(keys[2])
logger.debug("Session keys: %s" % session_keys)
return session_keys
#
# Begin actual function
#
logger.debug("Opening secure channel...")
# Save our keys
self.keys = []
for k in keys:
self.keys.append([struct.pack('B', x) for x in k])
# Generate an 8 byte nonce
rand_challenge = self._generate_random(8)
# Initialize our authentication
(data, sw1, sw2) = self.apdu_init_update(0, 0, challenge=rand_challenge)
# Override results for debugging?
# rand_challenge = [0xA6, 0x1E, 0xF6, 0x6D, 0x6A, 0x27, 0x0E, 0x9A]
# data = [0x00, 0x00, 0x21, 0x80, 0x88, 0x10, 0x0B, 0x15, 0x20, 0xCB, 0x01, 0x01, 0x23, 0xCC, 0x76, 0xF2, 0xB2, 0x88, 0x01, 0x73, 0x07, 0xAD, 0xEF, 0xAD, 0x97, 0xAA, 0xFC, 0x0B, 0x90, 0x00]
if (sw1, sw2) != APDU.STATUS_WORDS.SUCCESS:
logger.error("INIT UPDATE failed.")
return
# Extract the parameters from our data
key_diversification_data = data[0:10]
key_info = data[10:12]
card_challenge = data[12:20]
cryptogram_card = data[20:28]
# Log some stuff
logger.debug("Key Diversification: %s" % APDU.get_hex(key_diversification_data))
logger.debug("Key Info: %s" % APDU.get_hex(key_info))
logger.debug("Card Challenge: %s" % APDU.get_hex(card_challenge))
logger.debug("Card Cryptogram: %s" % APDU.get_hex(cryptogram_card))
# Diversify our keys
diversified_keys = get_diversified_keys(self.keys, key_diversification_data)
# Derive session keys
self.session_keys = get_session_keys(diversified_keys, rand_challenge, card_challenge)
# Authenticate to the card
self.apdu_authenticate(card_challenge, rand_challenge, cryptogram_card,
security_level=security_level)
logger.debug("Secure Channel Opened!")
self.SECURE_CHANNEL = security_level
def apdu_verify_pin(self, pin, location, pad_pin=8):
"""
Send a VERIFY PIN for smartcard
@param pin: pin to enter
@param location: location of pin (1 byte)
@param pad_pin: Number of bytes to pad pin to (padding is 0xff)
"""
# Do we need to pad the pin?
while len(pin) < pad_pin:
pin.append(0xff)
apdu = APDU.VERIFY_PIN(location, pin)
data, sw1, sw2 = self._send_apdu(apdu)
if sw1 != APDU.APDU_STATUS.SUCCESS:
print "ERROR (%s,%s): VERIFY PIN failed." % (hex(sw1), hex(sw2))
if sw1 == 0x63 and sw2 & 0xc0 == 0xc0:
print "WARNING: %d tries remaining!" % (sw2 & 0x0F)
else:
print "* Key Authentication Successful!"
return (data, sw1, sw2)
def apdu_change_reference_data(self, location, old_pin, new_pin,
pad_pin=8, first=False):
"""
Change the reference data on the card, e.g. PIN
@param location: 0x00 - Global,
0x80 - Application,
0x81, Application PUK
@param old_pin: Existing PIN
@param new_pin: New PIN
@param pad_pin: How many bytes should the PIN be?
@param first: Is this the first time setting the PIN?
@return (data, sw1, sw2)
"""
# Do we need to pad the pin?
while len(new_pin) < pad_pin:
new_pin.append(0xff)
while len(old_pin) < pad_pin:
old_pin.append(0xff)
if first:
P1 = 0x01
old_pin = []
else:
P1 = 0x00
P2 = location
apdu = APDU.CHANGE_REFERENCE_DATA(P1, P2, old_pin, new_pin)
data, sw1, sw2 = self._send_apdu(apdu)
return (data, sw1, sw2)
def apdu_reset_retry_counter(self, puk, location, new_pin, pad_pin=8):
"""
Reset the retry counter using the PUK
"""
# Do we need to pad the pin?
if puk is not None:
while len(puk) < pad_pin:
puk.append(0xff)
if new_pin is not None:
while len(new_pin) < pad_pin:
new_pin.append(0xff)
# This is according to the ISO spec, but doesn't seem to work
if new_pin is None and puk is None:
P1 = 0x03
elif new_pin is None:
P1 = 0x01
elif puk is None:
P1 = 0x02
else:
P1 = 0x00
if self.SECURE_CHANNEL is False:
P1 = 0x00
else:
P1 = 0x00
apdu = APDU.RESET_RETRY_COUNT(P1, location, puk, new_pin, CLA=0x00)
data, sw1, sw2 = self._send_apdu(apdu)
if sw1 != APDU.APDU_STATUS.SUCCESS:
print "ERROR (%s,%s): VERIFY PIN failed." % (hex(sw1), hex(sw2))
if sw1 == 0x63 and sw2 & 0xc0 == 0xc0:
print "WARNING: %d tries remaining!" % (sw2 & 0x0F)
else:
print "* PIN retry has been reset."
return (data, sw1, sw2)
def apdu_set_status(self, status_type, status_state, aid=[]):
"""
Set the status of an application on the smartcard
"""
apdu = APDU.SET_STATUS(status_type, status_state, aid)
return self._send_apdu(apdu)
def dump_records(self):
for sfi in range(32):
for rec in range (17):
logger.debug("REC %d SFI %d" % (rec, (sfi << 3) | 4))
data, sw1, sw2 = self.apdu_read_record(rec, (sfi << 3) | 4)
if sw1 == APDU.APDU_STATUS.SUCCESS:
print "REC %d SFI %d" % (rec, (sfi << 3) | 4)
print "Hex: %s" % APDU.get_hex(data)
print "Str: %s" % APDU.get_str(data)
def _decode_bcd(self, bcd_num):
"""
Given a 5 bit Binary Coded Decimal, decode back to the appropriate string
@param bcd_num : 5 bit Binary Coded Decimal number
@return: Character represenation
"""
bcd_table = {'0':0b00001,
'1':0b10000,
'2':0b01000,
'3':0b11001,
'4':0b00100,
'5':0b10101,
'6':0b01101,
'7':0b11100,
'8':0b00010,
'9':0b10011,
'SS':0b11010,
'FS':0b10110,
'ES':0b11111}
for char in bcd_table:
if bcd_table[char] == bcd_num:
return char
return None
def _get_ber_tlv(self, data, offset=0):
"""
Get the next BER-TLV value from data
@param data: Data encoded with BER-TLV
@param offset: Offset into data buffer
@return: [type, length, value, next_tlv]
"""
tlv_type = data[offset]
if data[offset + 1] == 0x81:
tlv_length = data[offset + 2]
tlv_value = data[offset + 3:offset + 3 + tlv_length]
next_tlv = tlv_length + 3
elif data[offset + 1] == 0x82:
tlv_length = data[offset + 2] << 8 | data[offset + 3]
tlv_value = data[offset + 4:offset + 4 + tlv_length]
next_tlv = tlv_length + 4
else:
tlv_length = data[offset + 1]
tlv_value = data[offset + 2:offset + 2 + tlv_length]
next_tlv = tlv_length + 2
return [tlv_type, tlv_value, next_tlv]
def _decode_ber_tlv(self, data):
"""
Read BER-TLV data and return list of [type, data] pairs
Ref: CAC Endpoint Implementation Guide v1
@param data:
@return: list of [type, data] pairs
"""
offset = 0
rtn_list = []
while offset < len(data):
# Get Data
tlv_type, tlv_value, next_tlv = self._get_ber_tlv(data, offset)
# Update pointer into buffer
offset += next_tlv
# append to our results
rtn_list.append([tlv_type, tlv_value])
# If its tag type 0x53, just return the data
tlv = self._get_ber_tlv(data)
if tlv[0] == 0x53:
data = tlv[1]
return self._decode_ber_tlv(data)
else:
return rtn_list
class CAC(SmartCard):
"""
This class implements some knwown functionality for the DoD CAC smartcard.
"""
def _lookup_agency(self, code):
"""
Converts agency code string in CHUID to the actual name of the agency
ref: http://csrc.nist.gov/publications/nistpubs/800-87-Rev1/SP800-87_Rev1-April2008Final.pdf
@param code: String code of Agency
@return: String name of Agency or Uknown
"""
agency_table = {'9700':'DEFENSE, Department of (except military departments)',
'5700':'AIR FORCE, Department of the (Headquarters, USAF) '}
if code in agency_table:
return agency_table[code]
else:
return "Unknown (See: SP800-87)"
def _lookup_oc(self, code):
"""
Convert organization code in CHUID to name of organization
@param code: character code of organization
@return: Name of organization
"""
table = {'1':'Federal Government Agency',
'2':'State Government Agency',
'3':'Commercial Enterprise',
'4':'Foreign Government'}
if code in table:
return "%s (%s)" % (table[code], int(code))
else:
return "Unknown (See: SP800-87)"
def _lookup_poa(self, code):
"""
Convert Personal Association Category code in CHUID to string name
@param code: Character poa code
@return: String of association
"""
table = {'1': 'Employee',
'2': 'Civil',
'3': 'Executive Staff',
'4': 'Uniformed Service',
'5': 'Contractor',
'6': 'Organizational Affiliate',
'7': 'Organizational Beneficiary'}
if code in table:
return "%s (%s)" % (table[code], int(code))
else:
return "%s (See: (See: SP800-87)" % hex(code)
def _lookup_card_app_type(self, code):
"""
Lookup Card Application Type from CardURL
@param code: Byte encoding app type
@return: Application type
"""
table = {0x01: 'genericContainer',
0x02: 'ski',
0x04: 'ski'}
if code in table:
return "%s (%s)" % (table[code], hex(code))
else:
return "%s (See: GSC-IS 7-1)" % hex(code)
def _lookup_card_object_id(self, code):
"""
Lookup Card Object ID from CardURL
@param code: Byte encoding object ID
@return: Object Name
"""
code = code[0] << 8 | code[1]
table = { 0x2000:'generalInfo',
0x2100:'proPersonalInfo',
0x3000:'accessControl',
0x4000:'login',
0x5000:'cardInfo',
0x6000:'biometrics',
0x7000:'digitalSigCert',
# -- CAC data model definitions
0x0200:'personInstance',
0x0202:'benefitsInfo',
0x0203:'otherBenefits',
0x0201:'personnel',
0x0300:'loginInfo',
0x02FE:'pkiCert',
# -- Common definitions
0x0007:'SEIWG'}
if code in table:
return "%s (%s)" % (table[code], hex(code))
else:
return "%s (See: GSC-IS 7-1)" % hex(code)
def _lookup_key_crypto(self, code):
"""
Lookup Key Crypto Algorithm from CardURL
@param code: Byte encoding of Key Crypto Algorithm
@return: Crypto Algorithm
"""
table = { 0x00:'DES3-16-ECB',
0x01:'DES3-16-CBC',
0x02:'DES-ECB',
0x03:'DES-CBC',
0x04:'RSA512',
0x05:'RSA768',
0x06:'RSA1024',
0x07:'RSA2048',
0x08:'AES128-ECB',
0x09:'AES128-CBC',
0x0a:'AES192-ECB',
0x0b:'AES192-CBC',
0x0c:'AES256-ECB',
0x0d:'AES256-CBC'}
if code in table:
return "%s (%s)" % (table[code], hex(code))
else:
return "%s (See: GSC-IS 7-1)" % hex(code)
def _lookup_card_type(self, code):
"""
Lookup Card Type
@param code: Byte encoding of Key Crypto Algorithm
@return: Crypto Algorithm
"""
table = { 0x01:'File System',
0x02:'Java Card'
}
if code in table:
return "%s (%s)" % (table[code], hex(code))
else:
return "%s (See: CAC End-Point Impelementation Guide)" % hex(code)
def _lookup_cert(self, registered_id, object_id):
"""
Lookup the name of the certificate given its RID and OID
@param registered_id: RID of cert in question
@param object_id: Object ID of cert in question
@return: Name of the cert being references
"""
table = { APDU.get_hex(APDU.OBJ_NIST_PIV.KEY_CRD_ATH):'Card Authentication (NIST)',
APDU.get_hex(APDU.OBJ_NIST_PIV.KEY_DIG_SIG):'Digital Signature (NIST)',
APDU.get_hex(APDU.OBJ_NIST_PIV.KEY_MNG):'Key Management (NIST)',
APDU.get_hex(APDU.OBJ_NIST_PIV.KEY_PIV_ATH):'PIV Authentication (NIST)',
APDU.get_hex(APDU.OBJ_DOD_CAC.KEY_PKI_ENC):'Encryption (CaC)',
APDU.get_hex(APDU.OBJ_DOD_CAC.KEY_PKI_ID):'Identification (CaC)',
APDU.get_hex(APDU.OBJ_DOD_CAC.KEY_PKI_SIG):'Signature (CaC'}
object_id = APDU.get_hex(object_id)
if object_id in table:
return "%s (%s)" % (table[object_id], object_id)
else:
return "Unknown (%s)" % object_id
def _splash(self, string):
""" Used to keep output pretty """
print "--------------------- %s ---------------------" % string
def _print_fasc_n(self, data):
"""
Will print the FASC-N in human-readable form
@param data: 25 byte bytestring containting FASC-N
"""
# Frist combine into 1 binary string
fasc_n = 0
for i in range(len(data)):
fasc_n = fasc_n << 8 | data[i]
# Now break out the 5 bit individual numbers
fasc_n_list = []
for i in reversed(range(40)):
mask = 0b11111 << i * 5
bcd_num = (fasc_n & mask) >> i * 5
# Decode and validate parity bits
fasc_n_list.append(self._decode_bcd(bcd_num))
# Extract all of the fields
agency_code = "".join(fasc_n_list[1:5])
system_code = "".join(fasc_n_list[6:10])
credential_number = "".join(fasc_n_list[11:17])
cs = fasc_n_list[18]
ici = fasc_n_list[20]
pi = "".join(fasc_n_list[22:32])
oc = fasc_n_list[32]
oi = "".join(fasc_n_list[33:37])
poa = fasc_n_list[37]
# print in nice format
print " FASC-N (SEIWG-012): %s" % hex(fasc_n)
print " Agency Code: %s / %s" % (agency_code, self._lookup_agency(agency_code))
print " System Code: %s" % system_code
print " Credential Number: %s" % credential_number
print " Credential Series: %s" % cs
print " Individual Credential Issue: %s" % ici
print " Person Identifier: %s" % pi
print " Organizational Category: %s / %s" % (oc, self._lookup_oc(oc))
print " Organizational Identifier: %s / %s" % (oi, self._lookup_agency(oi))
print " Person Association Category: %s / %s" % (poa, self._lookup_poa(poa))
def _print_ccc(self, tv_data, applet=None, object_id=None):
"""
Prints Card Capability Container
Ref: SP800-73-1
Ref: GSC-IS / Page 6-5
@param tv_data: Type/Value data returned from a read_object call
"""
# Print results to terminal
self._splash("CCC (%s)" % APDU.get_hex(applet))
# Loop over type/value pairs
for tv in tv_data:
tlv_type = tv[0]
tlv_value = tv[1]
if tlv_type == 0xf0:
print " Card Identifier [%s]" % APDU.get_hex(tlv_value)
print " GSC-RID: %s" % APDU.get_hex(tlv_value[0:5])
print " Manufacturer ID: %s" % hex(tlv_value[5])
print " Card Type: %s" % self._lookup_card_type(tlv_value[6])
print " Card ID: %s | %s" % (APDU.get_hex(tlv_value[7:17]),
APDU.get_hex(tlv_value[17:22]))
elif tlv_type == 0xf1:
print " Capability Container version number: %s" % APDU.get_hex(tlv_value)
elif tlv_type == 0xf2:
print " Capability Grammar version number: %s" % APDU.get_hex(tlv_value)
elif tlv_type == 0xf3:
print " Applications CardURL [%s]" % APDU.get_hex(tlv_value)
print " RID: %s" % APDU.get_hex(tlv_value[0:5])
print " Application Type: %s" % self._lookup_card_app_type(tlv_value[5])
print " Object ID: %s" % self._lookup_card_object_id(tlv_value[6:8])
print " Application ID: %s" % APDU.get_hex(tlv_value[8:10])
print " AccProfile: %s" % hex(tlv_value[10])
print " PIN ID: %s" % hex(tlv_value[11])
print " AccKey Info: %s" % APDU.get_hex(tlv_value[12:16])
print " -- Alternate ---"
print " PIN ID: %s" % hex(tlv_value[8])
print " Key File ID: %s" % APDU.get_hex(tlv_value[9:11])
print " Key Number: %s" % hex(tlv_value[11])
print " Key Algorithm: %s" % self._lookup_key_crypto(tlv_value[12])
print " Key Algorithm: %s" % self._lookup_key_crypto(tlv_value[13])
elif tlv_type == 0xf4:
print " PKCS#15: %s" % APDU.get_hex(tlv_value)
elif tlv_type == 0xf5:
print " Registered Data Model number: %s" % APDU.get_hex(tlv_value)
elif tlv_type == 0xf6:
print " Access Control Rule Table: %s" % APDU.get_hex(tlv_value)
elif tlv_type == 0xf7:
print " CARD APDUs: %s" % APDU.get_hex(tlv_value)
elif tlv_type == 0xfa:
print " Redirection Tag: %s" % APDU.get_hex(tlv_value)
elif tlv_type == 0xfb:
print " Capability Tuples (CTs): %s" % APDU.get_hex(tlv_value)
elif tlv_type == 0xfc:
print " Status Tuples (STs): %s" % APDU.get_hex(tlv_value)
elif tlv_type == 0xfd:
print " Next CCC: %s" % APDU.get_hex(tlv_value)
elif tlv_type == 0xfe:
print " Error Detection Code: %s" % APDU.get_hex(tlv_value)
else:
print " [TLV] Type: %s, Length: %d " % (hex(tlv_type), len(tlv_value))
self._splash("CCC (%s)" % APDU.get_hex(applet))
def _print_chuid(self, tv_data, applet=None, object_id=None):
"""
Will take CHUID data and print extracted information
Reference:
http://fips201ep.cio.gov/documents/TIG_SCEPACS_v2.2.pdf (Page 9)
http://csrc.nist.gov/publications/nistpubs/800-73-3/sp800-73-3_PART1_piv-card-applic-namespace-date-model-rep.pdf (Page 5)
@param tv_data: Type/Value data returned from a read_object call
"""
# Print results to terminal
self._splash("CHUID (%s)" % APDU.get_hex(applet))
# Loop over extracted data and print nicely formatted
for tv in tv_data:
tlv_type = tv[0]
tlv_value = tv[1]
if tlv_type == 0x30:
self._print_fasc_n(tlv_value)
print ""
elif tlv_type == 0x31:
print " Agency Code: %s" % APDU.get_hex(tlv_value)
elif tlv_type == 0x34:
print " GUID: %s" % APDU.get_hex(tlv_value)
elif tlv_type == 0x35:
print " Expiration Date (YYYYMMDD): %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x3E:
print " Asymmetric Signature: [length: %d]" % len(tlv_value)
elif tlv_type == 0xFE:
print "Error Detection Code Found."
else:
print " [TLV] Type: %s, Length: %d " % (hex(tlv_type),
len(tlv_value))
self._splash("CHUID (%s)" % APDU.get_hex(applet))
def _print_x509_cert(self, tv_data, registered_id, object_id):
"""
Read and decode the X.509 Certificate for PIV Authentication
X.509 Certificate for PIV Authentication 5FC105 M
X.509 Certificate for Digital Signature 5FC10A O
X.509 Certificate for Key Management 5FC10B O
X.509 Certificate for Card Authentication 5FC101 O
Ref: SP80-73-1 / Appendix A
@param cert_address: Address of certificate to read
"""
cert_name = self._lookup_cert(registered_id, object_id)
self._splash("X.509 %s Certificate (%s)" % (cert_name, APDU.get_hex(registered_id)))
# Loop over extracted data and print nicely formatted
for tv in tv_data:
tlv_type = tv[0]
tlv_value = tv[1]
if tlv_type == 0x70:
print "Certificate: [length: %d]" % len(tlv_value)
elif tlv_type == 0x71:
print "Certificate Info: %s" % APDU.get_hex(tlv_value)
elif tlv_type == 0x72:
print "MSCUID: %s" % APDU.get_hex(tlv_value)
elif tlv_type == 0xFE:
print "Error Detction Code Found."
else:
print "[TLV] %s : %s : %s" % (hex(tlv_type),
len(tlv_value),
APDU.get_hex(tlv_value))
self._splash("X.509 %s Certificate (%s)" % (cert_name, APDU.get_hex(registered_id)))
def _print_sec_obj(self, tv_data, registered_id, object_id):
"""
Print the Security Object (Ref: SP800-73-1)
"""
self._splash("Security Object (%s)" % (APDU.get_hex(object_id)))
# Loop over extracted data and print nicely formatted
for tv in tv_data:
tlv_type = tv[0]
tlv_value = tv[1]
if tlv_type == 0xBA:
print "Mapping of DG to ContainerID: %s" % APDU.get_hex(tlv_value)
elif tlv_type == 0xBB:
print "Security Object: [length: %d]" % len(tlv_value)
elif tlv_type == 0xFE:
print "Error Detction Code Found."
else:
print "[TLV] %s : %s : %s" % (hex(tlv_type),
len(tlv_value),
APDU.get_hex(tlv_value))
self._splash("Security Object (%s)" % (APDU.get_hex(object_id)))
def _print_fingerprint(self, tv_data, registered_id, object_id):
"""
Print Fingerprint data from PIV
REQUIRES PIN!
Ref: SP800-73-1
"""
self._splash("Fingerprint")
# Loop over extracted data and print nicely formatted
for tv in tv_data:
tlv_type = tv[0]
tlv_value = tv[1]
if tlv_type == 0xBC:
print "Fingerprint: [length %d]" % len(tlv_value)
elif tlv_type == 0xFE:
print "Error Detection Code Found."
else:
print "[TLV] %s : %s : %s" % (hex(tlv_type),
len(tlv_value),
APDU.get_hex(tlv_value))
self._splash("Fingerprint")
def _print_facial_info(self, tv_data, registered_id, object_id):
"""
Print Facial Information from PIV
REQUIRES PIN!
Ref: SP800-73-1
"""
self._splash("Facial Information")
for tv in tv_data:
tlv_type = tv[0]
tlv_value = tv[1]
if tlv_type == 0xBC:
print "Facial Image: [length %d]" % len(tlv_value)
elif tlv_type == 0xFE:
print "Error Detection Code Found."
else:
print "[TLV] %s : %s : %s" % (hex(tlv_type),
len(tlv_value),
APDU.get_hex(tlv_value))
self._splash("Facial Information")
def _print_person_info(self, tv_data, registered_id, object_id):
"""
Print Person Information
REQUIRES PIN!
Ref: NISTIR-6887
"""
self._splash("Person Instance Container")
for tv in tv_data:
tlv_type = tv[0]
tlv_value = tv[1]
if tlv_type == 0x01:
print "First Name: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x02:
print "Middle Name: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x03:
print "Last Name: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x04:
print "Candency Name: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x05:
print "Personal Identifier: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x06:
print "DOB: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x07:
print "Sex: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x08:
print "PI Type Code: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x11:
print "Blood Type: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x17:
print "DoD EDI PI: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x18:
print "Organ Donor: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x62:
print "Card Issue Date: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x63:
print "Card Expiration Date: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x65:
print "Date Demographic Data Loaded: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x66:
print "Date Demographic Data Expires: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x67:
print "Card Instance ID: %s" % APDU.get_str(tlv_value)
else:
print "[TLV] %s : %s : %s" % (hex(tlv_type),
len(tlv_value),
APDU.get_hex(tlv_value))
self._splash("Person Instance Container")
def _print_personnel(self, tv_data, registered_id, object_id):
"""
Print Person Information
REQUIRES PIN!
Ref: NISTIR-6887
"""
self._splash("Personnel Information")
for tv in tv_data:
tlv_type = tv[0]
tlv_value = tv[1]
if tlv_type == 0x19:
print "Contractor Function Code: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x20:
print "Gov Agency/Subagency Code: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x24:
print "Branch: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x25:
print "Pay Grade: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x26:
print "Rank Code: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x34:
print "Personnel Category Code: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x35:
print "Non-US Gov Agency/Subagency Code: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0x36:
print "Pay Plan Code: %s" % APDU.get_str(tlv_value)
elif tlv_type == 0xD3:
print "Personnel Entitlement Condition Code: %s" % APDU.get_str(tlv_value)
else:
print "[TLV] %s : %s : %s" % (hex(tlv_type),
len(tlv_value),
APDU.get_hex(tlv_value))
self._splash("Personnel Information")
def split_address(self, address):
""" Split a 2 byte address into 2 individual bytes """
P1 = (0b1111111100000000 & address) >> 8
P2 = 0b11111111 & address
return [P1, P2]
def read_tl_v_buffer(self, address):
"""
Read Type-Length buffer and Value buffer, concatenating all of the results
and returning a contiguous binary string
@param address: Address of buffer. Likely [0x00, 0x00]
@return: Binary string of buffers merged into one
"""
addr = self.split_address(address)
data, sw1, sw2 = self.apdu_read_buffer(addr[0], addr[1], 0x01, read_length=0x03)
if sw1 != APDU.APDU_STATUS.SUCCESS:
self._report_error(sw1, sw2, "Buffer read failed.")
return
# Figure out our length and where the data starts
# @todo: Confirm that 0x81 and 0x82 apply here.
if data[0] == 0x81:
buffer_length = data[1]
next_address = address + 3
elif data[0] == 0x82:
buffer_length = data[1] << 8 | data[2]
next_address = address + 4
else:
buffer_length = data[0]
next_address = address + 2
# Read Type-Length values (0x01)
addr = self.split_address(next_address)
tl_buffer, sw1, sw2 = self.apdu_read_buffer(addr[0], addr[1], 0x01, read_length=buffer_length)
tl_offset = 2
rtn_list = []
for i in range(buffer_length / 2):
addr = self.split_address(next_address)
tlv_type = tl_buffer[i * 2]
tlv_length = tl_buffer[i * 2 + 1]
data = []
# Read data (0x02)
if tlv_length > 0:
data, sw1, sw2 = self.apdu_read_buffer(0, tl_offset, 0x02, read_length=tlv_length)
tl_offset += tlv_length
rtn_list.append([tlv_type, data])
return rtn_list
def apdu_read_buffer(self, p1, p2, buffer_type, read_length=64):
"""
Send READ BUFFER APDU
@param p1: MSB of argument
@param p2: LSB of argument
@param buffer_type: 0x01 - Read Type-Length buffer,
0x02 - Read Value buffer
@param read_length: How many bytes to read
"""
apdu_read = APDU.READ_BUFFER(p1, p2, buffer_type, read_length=read_length)
data, sw1, sw2 = self._send_apdu(apdu_read)
if sw1 != APDU.APDU_STATUS.SUCCESS:
print "ERROR (%s,%s): READ BUFFER failed." % (hex(sw1), hex(sw2))
return (data, sw1, sw2)
def apdu_get_data_piv(self, address):
"""
GET DATA APDU
Ref: SP800-73-1 / Table 6
Card Capability Container 5FC107 M
Card Holder Unique Identifier 5FC102 M
X.509 Certificate for PIV Authentication 5FC105 M
Card Holder Fingerprint I 5FC103 M
Card Holder Fingerprint II 5FC104 M
Printed Information 5FC109 O
Card Holder Facial Image 5FC108 O
X.509 Certificate for Digital Signature 5FC10A O
X.509 Certificate for Key Management 5FC10B O
X.509 Certificate for Card Authentication 5FC101 O
Security Object 5FC106 M
@param address: 3 byte address list
@return (data,sw1,sw2)
"""
apdu_get_data = APDU.GET_DATA_PIV(address)
# Get returned data
data, sw1, sw2 = self._send_apdu(apdu_get_data)
if sw1 != APDU.APDU_STATUS.SUCCESS:
print "ERROR (%s,%s): GET DATA failed." % (hex(sw1), hex(sw2))
return data, sw1, sw2
def apdu_sign_decrypt(self, input_data):
"""
Send data to the CAC to be signed or decrypted.
Ref: SP800-73-1 / Page 14
@param data: Data to be signed or decrypted
@return: (data, sw1, sw2) - Returns data decrypted or signed if successful
"""
PADDING = 0xFF
MAX_LEN = 128 # must be a divisor of 256
# Pad the data
while len(input_data) % 256 != 0:
input_data.append(PADDING)
chunk_count = len(input_data) / MAX_LEN
for i in range(chunk_count):
# Set P1 to indicate more data is coming
P1 = 0b10000000
if i == chunk_count - 1:
P1 = 0x0
# Exract the chunk of the data we are sending
data_chunk = input_data[MAX_LEN * i:MAX_LEN * i + MAX_LEN]
# Send the APDU
apdu_cmd = APDU.SIGN_DECRYPT(data_chunk, P1=P1)
# Get returned data
data, sw1, sw2 = self._send_apdu(apdu_cmd)
if sw1 != APDU.APDU_STATUS.SUCCESS:
print "ERROR (%s,%s): SIGN/DECRYPT failed." % (hex(sw1), hex(sw2))
break
return (data, sw1, sw2)
def select_nist_piv(self):
""" SELECT NIST PIV """
data, sw1, sw2 = self.apdu_select_application(APDU.APPLET.NIST_PIV)
if sw1 != APDU.APDU_STATUS.SUCCESS:
print "ERROR (%s,%s): SELECT PIV RID (%s) failed." % (hex(sw1),
hex(sw2),
APDU.get_hex(APDU.APPLET.NIST_PIV))
return
def read_object(self, registered_id, object_id, pix=[], pin=None):
"""
Read a an Object from a given Applet (resource id) and return the
BER-TLV decoded data.
1. SELECTs the Applet/PIX
2. GET DATA from the Object
3. decode the BER-TLV format
@param registered_id: Applet's Registered ID (5 bytes)
@param pix: Proprietary Identifier Extension (2-11 bytes)
@param object_id: Object ID within the Resource
"""
# Select object from the Applet
if registered_id == APDU.APPLET.NIST_PIV:
# Select the Transitional PIV, then select the appropriate Object
self.apdu_select_application(registered_id)
if pin is not None:
data, sw1, sw2 = self.apdu_verify_pin(pin, 0x80)
data, sw1, sw2 = self.apdu_get_data_piv(object_id)
elif registered_id == APDU.APPLET.DOD_PIV or registered_id == APDU.APPLET.DOD_CAC:
# Select Applet and Object using SELECT applciation apdu
self.apdu_select_application(registered_id + pix)
if pin is not None:
data, sw1, sw2 = self.apdu_verify_pin(pin, 0x00)
data, sw1, sw2 = self.apdu_select_object(object_id)
else:
self._report_error(sw1, sw2, "Could not read Object (%s) from Applet (%s)." % (APDU.get_hex(registered_id),
APDU.get_hex(object_id))
)
return None
# @todo: Handle error cases
if sw1 != APDU.APDU_STATUS.SUCCESS:
self._report_error(sw1, sw2, "Read Object failed. (RID:%s, OID:%s)" % (APDU.get_hex(registered_id),
APDU.get_hex(object_id)))
return
# Extract our data
if registered_id == APDU.APPLET.NIST_PIV:
tv_data = self._decode_ber_tlv(data)
elif registered_id == APDU.APPLET.DOD_PIV or registered_id == APDU.APPLET.DOD_CAC:
tv_data = self.read_tl_v_buffer(0x000)
return tv_data
def extract_cert(self, registered_id, object_id, cert_filename):
"""
Will extract the certificate from the card and save it to a file on
disk.
@param registered_id: RID of the applet to extract the cert from.
@param object_id: Object ID of the cert to be extracted
@param cert_filename: Filename to save the cert as on disk
"""
# Read the data from the object
data = self.read_object(registered_id, object_id)
if data == None:
logger.error("Failed to extract %s." % self._lookup_cert(registered_id, object_id))
return
# We know that all certs have the same format and where the cert is
# Ref: SP800-73-1 / Page 47
cert_data = None
for tv in data:
# 0x70 for certificates
# 0x3E for CHUID cert
if tv[0] == 0x70 or tv[0] == 0x3E:
cert_data = tv[1]
break
if cert_data is None:
logger.error("Certificate %s not found in APDU response." % self._lookup_cert(registered_id, object_id))
return
# Create file and write to it
cert_f = open(cert_filename, "wb+")
cert_f.write(struct.pack("%dB" % len(cert_data), *cert_data))
cert_f.close()
print "Saved %s to %s" % (self._lookup_cert(registered_id, object_id),
cert_filename)
def save_nist_cert(self, oid, cert_filename):
"""
Function to extract NIST certificates from the DoD CaC and save
it as a file to disk. This will also extract the PEM version and
the public key with the appropriate file extensions.
This function calls shell functions. It's not the nicest way to do
it but I see no reason to require more Python modules.
@param oid: Object ID of the cert to be extracted
@param cert_filename: Filename to save the cert to disk as.
"""
# Extract the cert to disk (with gzip extension
self.extract_cert(APDU.APPLET.NIST_PIV,
oid,
cert_filename + ".gz")
# ungzip it (remember the gzip extension was appeneded)
subprocess.Popen(["gunzip", "-f", cert_filename + ".gz"])
# extract public cert and PEM version of the cert
p = subprocess.Popen(["openssl", "x509",
"-inform", "DER",
"-pubkey",
"-in", cert_filename,
"-out", cert_filename + ".pem"],
stdout=subprocess.PIPE)
out, err = p.communicate()
# Write our output file
f = open(cert_filename + ".pub", "w+")
f.write(out)
f.close()
def print_object(self, registered_id, object_id, pix=[], pin=None):
"""
Will read the Object from the given Applet/PIX and then print
the results in human readable form.
@param registered_id: Applet's Registered ID (5 bytes)
@param pix: Proprietary Identifier Extension (2-11 bytes)
@param object_id: Object ID within the Resource
"""
# Read the data from the object
tv_data = self.read_object(registered_id, object_id, pix=pix, pin=pin)
if tv_data == None:
logger.error("Could not retrive Object (%s) from Applet (%s)." % (APDU.get_hex(object_id),
APDU.get_hex(registered_id))
)
return
# See if we have a print function for this object
# CHUID
if object_id in [APDU.OBJ_DOD_PIV.CHUID, APDU.OBJ_NIST_PIV.CHUID]:
self._print_chuid(tv_data, registered_id, object_id)
# CCC
elif object_id in [APDU.OBJ_DOD_PIV.CCC, APDU.OBJ_NIST_PIV.CCC]:
self._print_ccc(tv_data, registered_id, object_id)
# X.509 PIV Cred Auth
elif object_id in [APDU.OBJ_NIST_PIV.KEY_CRD_ATH]:
self._print_x509_cert(tv_data, registered_id, object_id)
# X.509 Dig Sign
elif object_id in [APDU.OBJ_NIST_PIV.KEY_DIG_SIG]:
self._print_x509_cert(tv_data, registered_id, object_id)
# X.509 Key Management
elif object_id in [APDU.OBJ_NIST_PIV.KEY_MNG]:
self._print_x509_cert(tv_data, registered_id, object_id)
# X.509 PIV Auth
elif object_id in [APDU.OBJ_NIST_PIV.KEY_PIV_ATH]:
self._print_x509_cert(tv_data, registered_id, object_id)
# CAC PKI
elif object_id in [APDU.OBJ_DOD_CAC.KEY_PKI_ENC, APDU.OBJ_DOD_CAC.KEY_PKI_ID, APDU.OBJ_DOD_CAC.KEY_PKI_SIG]:
self._print_x509_cert(tv_data, registered_id, object_id)
# Security Object
elif object_id in [APDU.OBJ_DOD_PIV.SEC_OBJ, APDU.OBJ_NIST_PIV.SEC_OBJ]:
self._print_sec_obj(tv_data, registered_id, object_id)
# Fingerprints
elif object_id in [APDU.OBJ_DOD_PIV.FNGR_PRNT, APDU.OBJ_NIST_PIV.FNGR_P1, APDU.OBJ_NIST_PIV.FNGR_P2]:
self._print_fingerprint(tv_data, registered_id, object_id)
# Facial Image
elif object_id in [APDU.OBJ_DOD_PIV.FACE, APDU.OBJ_NIST_PIV.FACE]:
self._print_facial_info(tv_data, registered_id, object_id)
# Person Info
elif object_id in [APDU.OBJ_DOD_CAC.CAC_PERSON]:
self._print_person_info(tv_data, registered_id, object_id)
# Personnel Info
elif object_id in [APDU.OBJ_DOD_CAC.CAC_PERSONEL]:
self._print_personnel(tv_data, registered_id, object_id)
else:
logger.error("No function implemented to print Object (%s) from Applet (%s)." % (APDU.get_hex(object_id),
APDU.get_hex(registered_id))
)
print tv_data
return
class CreditCard(SmartCard):
"""
Implements some known features of Visa smartcards
"""
INFO_REC = 1
INFO_SFI = 12
def _parse_applet_info(self, data):
"""
Parse the data we get back from selecting the applet
"""
# Is this a FCI template?
if data[0] == 0x6f:
tlv = self._decode_ber_tlv(data)
logger.info("FCI Template")
template = self._decode_ber_tlv(tlv[0][1])
# Parse template info
for t in template:
if t[0] == 0x84:
df_name = "".join(["%02X"%x for x in t[1]])
logger.info("DF Name: %s"%df_name)
if t[0] == 0xa5:
logger.info(" FCI Proprietary Template")
prop_template = self._decode_ber_tlv(t[1])
# Parse embedded info
for pt in prop_template:
if pt[0] == 0x50:
app_label = "".join([str(unichr(x)) for x in pt[1]])
logger.info(" Application Label: %s"%app_label)
if pt[0] == 0x87:
logger.info(" Application Priority Indicator: %s"%pt[1][0])
def select_visa_applet(self):
"""
Will send the appropriate APDU to select the Visa applet
"""
data, sw1, sw2 = self.apdu_select_application(APDU.APPLET.VISA)
if sw1 != APDU.APDU_STATUS.SUCCESS:
print "ERROR: This does not appear to be a valid VISA card!"
else:
self._parse_applet_info(data)
def select_mastercard_applet(self):
"""
Will send the appropriate APDU to select the Visa applet
"""
data, sw1, sw2 = self.apdu_select_application(APDU.APPLET.MASTERCARD)
if sw1 != APDU.APDU_STATUS.SUCCESS:
print "ERROR: This does not appear to be a valid MasterCard!"
else:
self._parse_applet_info(data)
def read_card_info(self):
"""
Read known paramaters from a Visa smartcard
"""
# REad the record from teh card
data, sw1, sw2 = self.apdu_read_record(self.INFO_REC, self.INFO_SFI, cla=0x00)
# Was it a succes?
if sw1 == APDU.APDU_STATUS.SUCCESS:
# Setup our dict
info = {}
tlv = self._decode_ber_tlv(data)
# Is this application data?
if tlv[0][0] == 0x70:
# Parse the data in the application
cc_info = self._decode_ber_tlv(tlv[0][1])
for field in cc_info:
# Is it a name field?
if field[0] == 0x5f:
cc_data = "".join([chr(x) for x in field[1]])
cc_data = cc_data.split("/")
info['last_name'] = cc_data[0].strip()
info['first_name'] = cc_data[1].strip()
# Account info field?
if field[0] == 0x57:
cc_data = "".join(["%02X"%x for x in field[1]])
k = cc_data.find('D')
info['account_number'] = cc_data[:k]
info['exp_year'] = cc_data[k+1:k+3]
info['exp_month'] = cc_data[k+3:k+5]
info['service_first'] = cc_data[k+5]
info['service_second'] = cc_data[k+6]
info['service_third'] = cc_data[k+7]
return info
else:
logger.error("Couldn't read card data.")
return None
|
mit-ll/LL-Smartcard
|
llsmartcard/card.py
|
Python
|
bsd-3-clause
| 69,479 |
<?php
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\Region */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="region-form">
<?php $form = ActiveForm::begin([
'options' => ['class' => 'form-horizontal'],
'fieldConfig' => [
'template' => "{label}\n<div class=\"col-lg-4\">{input}</div>\n<div class=\"col-lg-6\">{error}</div>",
'labelOptions' => ['class' => 'col-lg-2 control-label'],
],
]); ?>
<?= $form->field($model, 'name', ['inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control']])->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'note')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'rec_status_id')->radioList(
ArrayHelper::map(\app\models\RecStatus::find()->active()->all(), 'id', 'name'),[
'class' => 'btn-group',
'data-toggle' => 'buttons',
'unselect' => null, // remove hidden field
'item' => function ($index, $label, $name, $checked, $value) {
return '<label class="btn btn-default' . ($checked ? ' active' : '') . '">' .
Html::radio($name, $checked, ['value' => $value, 'class' => 'project-status-btn']) . $label . '</label>';
},
]);
?>
<?= $form->field($model, 'user_id')->dropDownList(ArrayHelper::map(\app\models\User::find()->active()->all(), 'id', 'name'), ['prompt' => '']) ?>
<?= $form->field($model, 'dc')->textInput() ?>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Save') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
if($model->hasErrors()){
echo \kartik\growl\Growl::widget([
'type' => \kartik\growl\Growl::TYPE_DANGER,
'title' => 'Необходимо исправить следующие ошибки:',
'icon' => 'glyphicon glyphicon-exclamation-sign',
'body' => \yii\helpers\BaseHtml::errorSummary($model, ['header' => '']),
'showSeparator' => true,
'delay' => 10,
'pluginOptions' => [
'placement' => [
'from' => 'top',
'align' => 'right',
]
]
]);
}
?>
|
slavam/placement
|
views/region/_form.php
|
PHP
|
bsd-3-clause
| 2,478 |
/*
* SakuraShiori.java
* NanikaKit
*
* Created by tarchan on 2008/04/03.
* Copyright (c) 2008 tarchan. All rights reserved.
*/
package com.mac.tarchan.nanika;
import com.mac.tarchan.nanika.nar.NanikaArchive;
/**
* SHIORI を実装します。
*
* @since 1.0
* @author tarchan
*/
public class SakuraShiori
{
/**
* SHIORI をロードします。
*
* @param nar NAR ファイル
* @return ロードできた場合は true、そうでない場合は false
*/
public boolean load(NanikaArchive nar)
{
return true;
}
/**
* SHIORI のバージョンを返します。
*
* @return バージョン文字列
*/
public String getVersion()
{
return "SHIORI/3.0";
}
/**
* さくらスクリプトを返します。
*
* @param command コマンド
* @return さくらスクリプト
*/
public String request(String command)
{
return "\\0\\s[0]こんにちは。\\_w[1500]\\1\\s[10]よぉ。\\e";
}
/**
* SHIORI をアンロードします。
*
* @return アンロードできた場合は true、そうでない場合は false
*/
public boolean unload()
{
return true;
}
}
|
tarchan/NanikaKit
|
src/com/mac/tarchan/nanika/SakuraShiori.java
|
Java
|
bsd-3-clause
| 1,140 |
package eu.monnetproject.ontology;
import eu.monnetproject.data.*;
import java.io.Reader;
import java.io.Writer;
import java.net.URI;
/**
* A read/write mechanism for implementations of ontologies
*/
public interface OntologySerializer {
/**
* Create a new (empty) ontology
*/
Ontology create(URI uri);
/**
* Read an ontology from a data source
*/
@Deprecated
Ontology read(DataSource source);
/**
* Read an ontology from a data source
*/
Ontology read(Reader source);
/**
* Read an ontology from a data source
* @param source The location to read the ontology from
* @param graph The graph to insert the result into (if triple store)
*/
Ontology read(Reader source, URI graph);
/**
* Write an ontology to a data target
*/
@Deprecated
void write(Ontology ontology, DataTarget target);
/**
* Write an ontology to a data target using the specified format ("RDFXML", "OWLXML", "N3" or "TURTLE")
*/
@Deprecated
void write(Ontology ontology, DataTarget target, String format);
/**
* Write an ontology to a data target
*/
void write(Ontology ontology, Writer target);
/**
* Write an ontology to a data target using the specified format ("RDFXML", "OWLXML", "N3" or "TURTLE")
*/
void write(Ontology ontology, Writer target, OntologyFormat format);
}
|
monnetproject/ontology
|
main/src/main/java/eu/monnetproject/ontology/OntologySerializer.java
|
Java
|
bsd-3-clause
| 1,437 |
<?php
namespace backend\modules\system;
class System extends \yii\base\Module
{
public $controllerNamespace = 'backend\modules\system\controllers';
public function init()
{
parent::init();
// custom initialization code goes here
}
}
|
Gcaufy/shengzaizai
|
backend/modules/system/System.php
|
PHP
|
bsd-3-clause
| 269 |
require 'spec_helper'
describe RoutesController do
describe 'for logged in users' do
before(:each) do
@route = stub_model(Route, id: 1)
@user = stub_model(User, routes: [@route])
controller.stub(current_user: @user)
end
describe 'index' do
it 'should show the users routes' do
@user.should_receive(:routes)
get :index
end
it 'should assign @routes' do
get :index
assigns[:routes].should == [@route]
end
it 'should render json correctly' do
get :index, format: :json
response.should be_ok
response.body.should == [@route].to_json
response.content_type.should == 'application/json'
end
end
describe 'show' do
it 'should show the right route' do
@user.routes.should_receive(:find).with('123')
get :show, id: '123'
end
it 'should assign @route' do
@user.routes.stub(find: @route)
get :show, id: '123'
assigns[:route].should == @route
end
it 'should render json correctly' do
@user.routes.should_receive(:find).with('123').and_return(@route)
get :show, id: '123', format: :json
response.should be_ok
response.body.should == @route.to_json
response.content_type.should == 'application/json'
end
end
describe 'create' do
it 'should create the record and return the location in the header' do
@user.routes.should_receive(:create).with('name' => 'test_route').and_return(@route)
post :create, route: {'name' => 'test_route'}
end
it 'should redirect to index' do
@user.routes.stub(:create)
post :create, route: {name: 'test_route'}
response.should redirect_to action: :index
end
it 'should render json correctly' do
@user.routes.stub(create: @route)
post :create, route: {name: 'test_route'}, format: :json
response.should be_ok
response.body.should == @route.to_json
response.content_type.should == 'application/json'
end
end
describe 'update' do
it 'should use the correct route and updates' do
@user.routes.should_receive(:find).with('123').and_return(@route)
@route.should_receive(:update_attribute).with(:name, 'updated_test_route')
post :update, id: '123', route: {name: 'updated_test_route'}
end
it 'should redirect to index' do
@user.routes.stub(find: @route)
post :update, id: '123', route: {name: 'updated_test_route'}
response.should redirect_to action: :index
end
it 'should render json correctly' do
@user.routes.should_receive(:find).and_return(@route)
@route.stub(update_attribute: @route)
get :update, id: '123', format: :json, route: {name: 'updated_route_name'}
response.should be_ok
response.body.should == @route.to_json
response.content_type.should == 'application/json'
end
end
describe 'destroy' do
it 'should destroy the user route' do
@user.routes.should_receive(:find).with('123').and_return(@route)
@route.should_receive(:destroy)
get :destroy, id: '123'
end
it 'should redirect to index' do
@user.routes.stub(find: @route)
post :destroy, id: '123'
response.should redirect_to action: :index
end
it 'should use head for json requests' do
@user.routes.stub(find: @route)
post :destroy, id: '123', format: :json
response.should be_ok
response.body.should == " "
response.content_type.should == 'application/json'
end
end
end
end
|
JohnRandom/longitude
|
spec/controllers/routes_controllers_spec.rb
|
Ruby
|
bsd-3-clause
| 3,736 |
from text import *
|
jasminka/goska
|
deltalife/__init__.py
|
Python
|
bsd-3-clause
| 20 |
Spree::Core::Engine.routes.draw do
post '/newsletter/subscribe' => 'newsletter#store', :as => :newsletter_store
get '/admin/newsletter' => 'admin/newsletter/dashboard#show', :as => :admin_newsletter_dashboard
namespace :admin do
namespace :newsletter do
resources :newsletters
end
end
end
|
jdeen/spree_newsletter
|
config/routes.rb
|
Ruby
|
bsd-3-clause
| 314 |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>phpCAS</title>
</head>
<body>
<p><img src="images/phpcas.png" width="191" height="68"/></p>
<p>phpCAS documentation is hosted at <a href="https://wiki.jasig.org/display/CASC/phpCAS">https://wiki.jasig.org/display/CASC/phpCAS</a>.</p>
<ul>
<li><a href="examples">examples</a></li>
<li><a href="http://downloads.jasig.org/cas-clients/php/1.3.0/docs/api/">source documentation</a></li>
</ul>
<p><img src="images/esup-portail.png" width="182" height="68"/> <img src="images/jasig.png" width="169" height="87"/></p>
<p> </p>
</body>
</html>
|
jcu-eresearch/Edgar
|
webapplication/app/Vendor/CAS/docs/index.html
|
HTML
|
bsd-3-clause
| 819 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<!-- required because all the links are pseudo-absolute -->
<base href="../..">
<link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="static-assets/prettify.css">
<link rel="stylesheet" href="static-assets/css/bootstrap.min.css">
<link rel="stylesheet" href="static-assets/styles.css">
<meta name="description" content="">
<link rel="icon" href="static-assets/favicon.png">
<!-- Do not remove placeholder -->
<!-- Header Placeholder -->
</head>
<body>
<div id="overlay-under-drawer"></div>
<header class="container-fluid" id="title">
<nav class="navbar navbar-fixed-top">
<div class="container">
<button id="sidenav-left-toggle" type="button"> </button>
<ol class="breadcrumbs gt-separated hidden-xs">
<li><a href="index.html">hetimatorrent</a></li>
<li><a href="torrent_util/torrent_util-library.html">torrent_util</a></li>
<li><a href="torrent_util/BlockData-class.html">BlockData</a></li>
<li class="self-crumb">BlockData</li>
</ol>
<div class="self-name">BlockData</div>
</div>
</nav>
<div class="container masthead">
<ol class="breadcrumbs gt-separated visible-xs">
<li><a href="index.html">hetimatorrent</a></li>
<li><a href="torrent_util/torrent_util-library.html">torrent_util</a></li>
<li><a href="torrent_util/BlockData-class.html">BlockData</a></li>
<li class="self-crumb">BlockData</li>
</ol>
<div class="title-description">
<h1 class="title">
<div class="kind">constructor</div> BlockData
</h1>
<!-- p class="subtitle">
create BlockData
</p -->
</div>
<ul class="subnav">
</ul>
</div>
</header>
<div class="container body">
<div class="col-xs-6 col-sm-3 sidebar sidebar-offcanvas-left">
<h5><a href="index.html">hetimatorrent</a></h5>
<h5><a href="torrent_util/torrent_util-library.html">torrent_util</a></h5>
<h5><a href="torrent_util/BlockData-class.html">BlockData</a></h5>
<ol>
<li class="section-title"><a href="torrent_util/BlockData-class.html#instance-properties">Properties</a></li>
<li><a href="torrent_util/BlockData/bitfield.html">bitfield</a>
</li>
<li><a href="torrent_util/BlockData/bitSize.html">bitSize</a>
</li>
<li><a href="torrent_util/BlockData/blockSize.html">blockSize</a>
</li>
<li><a href="torrent_util/BlockData/dataSize.html">dataSize</a>
</li>
<li><a href="torrent_util/BlockData/rawHead.html">rawHead</a>
</li>
<li class="section-title"><a href="torrent_util/BlockData-class.html#constructors">Constructors</a></li>
<li><a href="torrent_util/BlockData/BlockData.html">BlockData</a></li>
<li class="section-title"><a href="torrent_util/BlockData-class.html#methods">Methods</a></li>
<li><a href="torrent_util/BlockData/getData.html">getData</a>
</li>
<li><a href="torrent_util/BlockData/getNextBlockPart.html">getNextBlockPart</a>
</li>
<li><a href="torrent_util/BlockData/getPieceInfo.html">getPieceInfo</a>
</li>
<li><a href="torrent_util/BlockData/have.html">have</a>
</li>
<li><a href="torrent_util/BlockData/haveAll.html">haveAll</a>
</li>
<li><a href="torrent_util/BlockData/isNotThrere.html">isNotThrere</a>
</li>
<li><a href="torrent_util/BlockData/pieceInfoBlockNums.html">pieceInfoBlockNums</a>
</li>
<li><a href="torrent_util/BlockData/readBlock.html">readBlock</a>
</li>
<li><a href="torrent_util/BlockData/writeBlock.html">writeBlock</a>
</li>
<li><a href="torrent_util/BlockData/writeFullData.html">writeFullData</a>
</li>
<li><a href="torrent_util/BlockData/writePartBlock.html">writePartBlock</a>
</li>
</ol>
</div><!--/.sidebar-offcanvas-left-->
<div class="col-xs-12 col-sm-9 col-md-6 main-content">
<section class="multi-line-signature">
<span class="name ">BlockData</span>(
<br>
<div class="parameters">
<span class="parameter" id="-param-data"><span class="type-annotation">HetimaData</span> <span class="parameter-name">data</span></span>,<br><span class="parameter" id="-param-head"><span class="type-annotation"><a href="hetimatorrent/Bitfield-class.html">Bitfield</a></span> <span class="parameter-name">head</span></span>,<br><span class="parameter" id="-param-blockSize"><span class="type-annotation">int</span> <span class="parameter-name">blockSize</span></span>,<br><span class="parameter" id="-param-dataSize"><span class="type-annotation">int</span> <span class="parameter-name">dataSize</span></span>
</div>
)
</section>
<section class="desc markdown">
<p>create BlockData</p>
</section>
</div> <!-- /.main-content -->
</div> <!-- container -->
<footer>
<div class="container-fluid">
<div class="container">
<p class="text-center">
<span class="no-break">
hetimatorrent 0.0.1 api docs
</span>
•
<span class="copyright no-break">
<a href="https://www.dartlang.org">
<img src="static-assets/favicon.png" alt="Dart" title="Dart"width="16" height="16">
</a>
</span>
•
<span class="copyright no-break">
<a href="http://creativecommons.org/licenses/by-sa/4.0/">cc license</a>
</span>
</p>
</div>
</div>
</footer>
<script src="static-assets/prettify.js"></script>
<script src="static-assets/script.js"></script>
<!-- Do not remove placeholder -->
<!-- Footer Placeholder -->
</body>
</html>
|
kyorohiro/dart_hetimatorrent
|
doc/api/torrent_util/BlockData/BlockData.html
|
HTML
|
bsd-3-clause
| 6,230 |
/******************************************************************************
* Copyright (c) 2012-2015, Vladimir Kravets *
* 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 the Fido4Java nor the names of its contributors *
* may be used to endorse or promote products derived from this software *
* without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"*
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, *
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR *
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR *
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, *
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;*
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, *
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR *
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, *
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
******************************************************************************/
package org.fidonet.binkp.common;
/**
* Created by IntelliJ IDEA.
* Author: Vladimir Kravets
* E-Mail: [email protected]
* Date: 9/19/12
* Time: 2:21 PM
*/
public enum SessionState {
STATE_WAITOK, // State for client role - waiting authorization answer
STATE_WAITPWD, // State for server role - waiting authorization step
STATE_WAITGET, // State for file sending in NR mode
STATE_IDLE,
STATE_TRANSFER, // State for client/server role - begin transfer phase
STATE_BSY, // State for client/server role - if server is busy.
STATE_END, // State for ending session (all files was recivied, all files was sent)
STATE_ERR // State if error was happen, meaning to end session with client/server
}
|
vkravets/Fido4Java
|
binkp/binkp-common/src/main/java/org/fidonet/binkp/common/SessionState.java
|
Java
|
bsd-3-clause
| 2,895 |
require_relative '../spec_helper'
describe 'bazel::python' do
[
%w[ ubuntu 14.04 ],
%w[ centos 7.2.1511 ],
].each do |platform, version|
context "on #{platform} #{version}" do
let(:chef_run) {
runner = ChefSpec::SoloRunner.new(platform: platform, version: version)
runner.converge(described_recipe)
}
it 'installs python2 runtime' do
expect(chef_run).to install_python_runtime('2')
end
it 'installs python3 runtime' do
expect(chef_run).to install_python_runtime('3')
end
it 'installs python package' do
expect(chef_run).to install_package('python')
end
end
end
context 'on mac_os_x' do
let(:chef_run) {
runner = ChefSpec::SoloRunner.new(platform: 'mac_os_x', version: '10.11.1')
runner.converge(described_recipe)
}
it 'uses preinstalled python2' do
expect(chef_run).not_to install_python_runtime(anything)
end
it 'installs python3 with homebrew' do
expect(chef_run).to install_package('python3')
end
end
end
|
gengo/cookbook-bazel
|
spec/recipes/python_spec.rb
|
Ruby
|
bsd-3-clause
| 1,081 |
<?php
/**
* MvcCore
*
* This source file is subject to the BSD 3 License
* For the full copyright and license information, please view
* the LICENSE.md file that are distributed with this source code.
*
* @copyright Copyright (c) 2016 Tom Flidr (https://github.com/mvccore)
* @license https://mvccore.github.io/docs/mvccore/5.0.0/LICENSE.md
*/
namespace MvcCore\Model;
/**
* @mixin \MvcCore\Model
*/
trait MetaData {
/**
* @inheritDocs
* @param int $propsFlags
* @param \int[] $additionalMaps Compatible format for extension `mvccore/ext-model-db`.
* @return array
*/
public static function GetMetaData ($propsFlags = 0, $additionalMaps = []) {
/** @var \MvcCore\Model $this */
/**
* This is static hidden property, so it has different values
* for each static call. Keys in this array are integer flags,
* values are arrays with metadata. Metadata array has key
* by properties names.
* @var array
*/
static $__metaData = [];
if ($propsFlags === 0)
$propsFlags = \MvcCore\IModel::PROPS_INHERIT | \MvcCore\IModel::PROPS_PROTECTED;
list (
$cacheFlags, $accessModFlags, $inclInherit
) = static::getMetaDataFlags($propsFlags);
if (isset($__metaData[$cacheFlags]))
return $__metaData[$cacheFlags];
$classFullName = get_called_class();
$metaDataItem = static::parseMetaData(
$classFullName, $accessModFlags, $inclInherit
);
$__metaData[$cacheFlags] = $metaDataItem;
return $metaDataItem;
}
/**
* Parse called class metadata with reflection.
* @param string $classFullName
* @param int $accessModFlags
* @param bool $inclInherit
* @throws \InvalidArgumentException
* @return array
*/
protected static function parseMetaData ($classFullName, $accessModFlags, $inclInherit) {
$metaDataItem = [];
$phpWithTypes = PHP_VERSION_ID >= 70400;
$phpWithUnionTypes = PHP_VERSION_ID >= 80000;
$props = (new \ReflectionClass($classFullName))
->getProperties($accessModFlags);
/** @var \ReflectionProperty $prop */
foreach ($props as $prop) {
if (
$prop->isStatic() ||
(!$inclInherit && $prop->class !== $classFullName) ||
isset(static::$protectedProperties[$prop->name])
) continue;
$metaDataItem[$prop->name] = static::parseMetaDataProperty(
$prop, [$phpWithTypes, $phpWithUnionTypes]
);
}
return $metaDataItem;
}
/**
* Return `array` with metadata:
* - `0` `boolean` `TRUE` for private property.
* - `1' `boolean` `TRUE` to allow `NULL` values.
* - `2` `string[]` Property types from code or from doc comments or empty array.
* @param \ReflectionProperty $prop
* @param array $params [bool $phpWithTypes, bool $phpWithUnionTypes]
* @return array
*/
protected static function parseMetaDataProperty (\ReflectionProperty $prop, $params) {
list ($phpWithTypes, $phpWithUnionTypes) = $params;
$types = [];
$allowNull = FALSE;
if ($phpWithTypes && $prop->hasType()) {
/** @var $reflType \ReflectionUnionType|\ReflectionNamedType */
$refType = $prop->getType();
if ($refType !== NULL) {
if ($phpWithUnionTypes && $refType instanceof \ReflectionUnionType) {
$refTypes = $refType->getTypes();
/** @var \ReflectionNamedType $refTypesItem */
$strIndex = NULL;
foreach ($refTypes as $index => $refTypesItem) {
$typeName = $refTypesItem->getName();
if ($strIndex === NULL && $typeName === 'string')
$strIndex = $index;
if ($typeName !== 'null')
$types[] = $typeName;
}
if ($strIndex !== NULL) {
unset($types[$strIndex]);
$types = array_values($types);
$types[] = 'string';
}
} else {
$types = [$refType->getName()];
}
$allowNull = $refType->allowsNull();
}
} else {
preg_match('/@var\s+([^\s]+)/', $prop->getDocComment(), $matches);
if ($matches) {
$rawTypes = '|'.$matches[1].'|';
$nullPos = mb_stripos($rawTypes,'|null|');
$qmPos = mb_strpos($rawTypes, '?');
$qmMatched = $qmPos !== FALSE;
$nullMatched = $nullPos !== FALSE;
$allowNull = $qmMatched || $nullMatched;
if ($qmMatched)
$rawTypes = str_replace('?', '', $rawTypes);
if ($nullMatched)
$rawTypes = (
mb_substr($rawTypes, 0, $nullPos) .
mb_substr($rawTypes, $nullPos + 5)
);
$rawTypes = mb_substr($rawTypes, 1, mb_strlen($rawTypes) - 2);
$types = explode('|', $rawTypes);
}
}
return [
$prop->isPrivate(), // boolean
$allowNull, // boolean
$types, // \string[]
];
}
/**
* Complete meta data cache key flag, reflection properties getter flags
* and boolean about to include inherit properties or not.
* @param int $propsFlags
* @return array [int, int, bool]
*/
protected static function getMetaDataFlags ($propsFlags) {
$cacheFlags = 0;
$accessModFlags = 0;
$inclInherit = FALSE;
if (($propsFlags & \MvcCore\IModel::PROPS_INHERIT) != 0) {
$cacheFlags |= \MvcCore\IModel::PROPS_INHERIT;
$inclInherit = TRUE;
}
if (($propsFlags & \MvcCore\IModel::PROPS_PRIVATE) != 0) {
$cacheFlags |= \MvcCore\IModel::PROPS_PRIVATE;
$accessModFlags |= \ReflectionProperty::IS_PRIVATE;
}
if (($propsFlags & \MvcCore\IModel::PROPS_PROTECTED) != 0) {
$cacheFlags |= \MvcCore\IModel::PROPS_PROTECTED;
$accessModFlags |= \ReflectionProperty::IS_PROTECTED;
}
if (($propsFlags & \MvcCore\IModel::PROPS_PUBLIC) != 0) {
$cacheFlags |= \MvcCore\IModel::PROPS_PUBLIC;
$accessModFlags |= \ReflectionProperty::IS_PUBLIC;
}
return [$cacheFlags, $accessModFlags, $inclInherit];
}
}
|
mvccore/mvccore
|
src/MvcCore/Model/MetaData.php
|
PHP
|
bsd-3-clause
| 5,595 |
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-missing-methods #-}
-- http://www.seas.upenn.edu/~cis194/spring13/hw/06-laziness.pdf
module Ch6
(
knapsackExample,
fib,
fibs1,
fibs2,
Stream (Empty, Stream),
streamToList,
streamRepeat,
streamMap,
streamFromSeed,
nats,
ruler,
fibs3,
Matrix2 (..),
fib4
) where
import Data.Array
import Debug.Trace
knapsack01 :: [Double] -- values
-> [Integer] -- nonnegative weights
-> Integer -- knapsack size
-> Double -- max possible value
knapsack01 vs ws maxW = m!(numItems-1, maxW)
where
numItems = length vs
m = array ((-1, 0), (numItems-1, maxW)) $
[((-1, w), 0) | w <- [0..maxW]] ++
[((i, 0), 0) | i <- [0..numItems-1]] ++
[((i, w), best) | i <- [0..numItems-1], w <- [1..maxW], let best | ws!!i > w = m!(i-1, w) | otherwise = max (m!(i-1, w)) (m!(i-1, w-ws!!i) + vs!!i)]
knapsackExample = knapsack01 [3, 4, 5, 8, 10] [2, 3, 4, 5, 9] 20
-- Exercise 1
-- fib n computes the nth Fibonacci number Fn
fib :: Integer -> Integer
fib n = fibInner n 0 1
fibInner :: Integer -> Integer -> Integer -> Integer
fibInner 0 a b = a
fibInner n a b = fibInner (n - 1) b (a + b)
-- The infinite list of all Fibonacci numbers
fibs1 :: [Integer]
fibs1 = map fib [1..]
-- Exercise 2
-- More efficient implementation for fibs
fibs2 :: [Integer]
fibs2 = fibs2Inner 1 1
fibs2Inner :: Integer -> Integer -> [Integer]
fibs2Inner a b = a: fibs2Inner b (a + b)
-- Exercise 3
data Stream a = Empty
| Stream a (Stream a)
streamToList :: Stream a -> [a]
streamToList Empty = []
streamToList (Stream x stream) = x: streamToList stream
instance Show a => Show (Stream a) where
show stream = unwords $ map show $ take 20 $ streamToList stream
-- Exercise 4
streamRepeat :: a -> Stream a
streamRepeat x = Stream x (streamRepeat x)
streamMap :: (a -> b) -> Stream a -> Stream b
streamMap _ Empty = Empty
streamMap fun (Stream x stream) = Stream (fun x) (streamMap fun stream)
streamFromSeed :: (a -> a) -> a -> Stream a
streamFromSeed transform seed = Stream seed (streamFromSeed transform (transform seed))
-- Exercise 5
nats :: Stream Integer
nats = streamFromSeed (+1) 0
-- interleave streams [[0, 0, ...], [1, 1, ...], [2, 2, ...], ...]
ruler :: Stream Integer
ruler = interleaveStreams (streamMap streamRepeat nats)
-- interleave two streams
interleaveTwoStreams :: Stream Integer -> Stream Integer -> Stream Integer
interleaveTwoStreams (Stream x stream1) stream2 = Stream x (interleaveTwoStreams stream2 stream1)
-- interleave the Stream of Stream of Integer
interleaveStreams :: Stream (Stream Integer) -> Stream Integer
interleaveStreams (Stream xs restStream) = interleaveTwoStreams xs (interleaveStreams restStream)
-- Exercise 6 (Optional)
--
-- The essential idea is to work with generating functions of the form
-- a0 + a1x + a2x2 + · · · + anxn + . . .
-- where x is just a “formal parameter” (that is, we will never actually
-- substitute any values for x; we just use it as a placeholder) and all the
-- coefficients ai are integers. We will store the coefficients a0, a1, a2, . . .
-- in a Stream Integer.
-- x = 0 + 1x + 0x^2 + 0x^3 + ...
-- x :: Stream Integer
instance Num (Stream Integer) where
-- n = n + 0x + 0x^2 + 0x^3 + ...
fromInteger n = Stream n (streamRepeat 0)
-- to negate a generating function, negate all its coefficients
negate = streamMap negate
-- (a0 + a1x + a2x^2 + . . .) + (b0 + b1x + b2x^2 + . . .) =
-- (a0 + b0) + (a1 + b1)x + (a2 + b2)x^2 + . . .
(+) (Stream x stream1) (Stream y stream2) = Stream (x + y) (stream1 + stream2)
(+) Empty stream2 = stream2
(+) stream1 Empty = stream1
-- Suppose A = a0 + xA' and B = b0 + xB'
-- AB = (a0 + xA')B
-- = a0B + xA'B
-- = a0(b0 + xB') + xA'B
-- = a0b0 + x(a0B' + A'B)
(*) (Stream a0 a') (Stream b0 b') = Stream (a0 * b0) (streamMap (* a0) b' + (a' * Stream b0 b'))
(*) Empty _ = Empty
(*) _ Empty = Empty
-- Suppose A = a0 + xA' and B = b0 + xB'
-- A/B = (a0 / b0) + x((1 / b0)(A' - QB'))
instance Fractional (Stream Integer) where
(Stream a0 a') / (Stream b0 b') = q where
tr x0 = floor (fromIntegral x0 / fromIntegral b0 :: Double)
hed = floor (fromIntegral a0 / fromIntegral b0 :: Double)
q = Stream hed (streamMap tr (a' - (q * b')))
-- F(x) = x / (1 - x - x^2)
fibs3 :: Stream Integer
fibs3 = Stream 0 (Stream 1 Empty) / Stream 1 (Stream (-1) (Stream (-1) Empty))
-- Exercise 7: Fibonacci numbers via matrices
--
data Matrix2 a = Matrix2 a a a a
deriving (Show, Eq)
instance Num (Matrix2 Integer) where
(*) (Matrix2 a00 a01 a10 a11) (Matrix2 b00 b01 b10 b11) =
Matrix2 (a00 * b00 + a01 * b10) (a00 * b01 + a01 * b11) (a10 * b00 + a11 * b10) (a10 * b01 + a11 * b11)
fib4 :: Integer -> Integer
fib4 0 = 0
fib4 n = a11 (fib4Inner m n) where
a11 (Matrix2 _ _ _ a) = a
fib4Inner m n = foldl (*) m (replicate (fromIntegral n) m)
m = Matrix2 1 1 1 0
|
wangwangwar/cis194
|
src/ch6/Ch6.hs
|
Haskell
|
bsd-3-clause
| 5,110 |
// RobotBuilder Version: 1.5
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc692.Demo2015.subsystems;
import org.usfirst.frc692.Demo2015.RobotMap;
import org.usfirst.frc692.Demo2015.commands.*;
import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
*/
public class compressor extends Subsystem {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
Compressor compressor1 = RobotMap.compressorCompressor1;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
}
|
sfhsfembot/Demo2015
|
src/org/usfirst/frc692/Demo2015/subsystems/compressor.java
|
Java
|
bsd-3-clause
| 1,410 |
#!/bin/bash
#
# Copyright (c) 2008-2016, Massachusetts Institute of Technology (MIT)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
if [ "$1" == "" ]
then
echo "You must specify a database name to create and populate."
exit 1
fi
if [ "$2" == "" ]
then
echo "You must specify a workspaceid to place the layer folders under."
exit 1
fi
# now create weather layers
# Old weather_folders.sql content
#E1F8E910-B773-4317-A4DF-DD6E0D50EDCD Near Real-Time Surface Analysis 371D4DE7-10BC-462B-81C2-4199C332BBEF 1 1
#F6C59F73-5F3E-4E43-BBC4-3586A9C4DFCC Near Real-Time Observations 371D4DE7-10BC-462B-81C2-4199C332BBEF 2 1
#FB9ABF2F-98C0-41C3-8C16-8324E1E701B9 Warnings 371D4DE7-10BC-462B-81C2-4199C332BBEF 0 1
#BFCC7A88-6625-4731-9713-A87102DC0EA5 Surface Forecasts 371D4DE7-10BC-462B-81C2-4199C332BBEF 3 1
# Weather Folders - these 4 lines are replacing the weather_folders.sql content
psql -c "insert into folder values('E1F8E910-B773-4317-A4DF-DD6E0D50EDCD','Near Real-Time Surface Analysis', (select folderid from folder where foldername='Weather' and workspaceid=$2), 1, $2)" $1
psql -c "insert into folder values('F6C59F73-5F3E-4E43-BBC4-3586A9C4DFCC','Near Real-Time Observations', (select folderid from folder where foldername='Weather' and workspaceid=$2), 2, $2)" $1
psql -c "insert into folder values('FB9ABF2F-98C0-41C3-8C16-8324E1E701B9','Warnings', (select folderid from folder where foldername='Weather' and workspaceid=$2), 0, $2)" $1
psql -c "insert into folder values('BFCC7A88-6625-4731-9713-A87102DC0EA5','Surface Forecasts', (select folderid from folder where foldername='Weather' and workspaceid=$2), 3, $2)" $1
psql -c "COPY datasource FROM '${PWD}/weather_datasource.sql'" $1
psql -c "COPY datalayersource FROM '${PWD}/weather_datalayersource.sql'" $1
psql -c "COPY datalayer FROM '${PWD}/weather_datalayer.sql'" $1
psql -c "COPY datalayerfolder FROM '${PWD}/weather_datalayerfolder.sql'" $1
|
hadrsystems/nics-db
|
datalayers/weather/weather_layers.sh
|
Shell
|
bsd-3-clause
| 3,376 |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\sss\A1002 */
$this->title = 'Create A1002';
$this->params['breadcrumbs'][] = ['label' => 'A1002s', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="a1002-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
|
farindra/advanced
|
lukisongroup/views/master/berita_acara/A1002/create.php
|
PHP
|
bsd-3-clause
| 412 |
package snippet;
public class Snippet {
wpilib - C:\Users\Makarand\wpilib\java\current\lib\WPILib.jar
networktables - C:\Users\Makarand\wpilib\java\current\lib\NetworkTables.jar
}
|
chriscush765/ArialAssistCMD
|
src/snippet/Snippet.java
|
Java
|
bsd-3-clause
| 184 |
# Filter structural variants against a set of genomic coordinates
Author: Bernie Pope ([email protected])
## License
3 Clause BSD License. See LICENSE.txt in source repository.
## Installation
#### External dependencies
`sv_filter` depends on the following programs and libraries:
* [python](https://www.python.org/download/releases/2.7.5/) (version 2.7.5)
* [bx-python](https://pypi.python.org/pypi/bx-python)
* [pyVCF](https://pypi.python.org/pypi/PyVCF)
* [pybedtools](https://pypi.python.org/pypi/pybedtools)
I recommend using a virtual environment:
```
cd /place/to/install
virtualenv sv_filter
source sv_filter/bin/activate
pip install -U https://github.com/bjpop/sv_filter
```
If you don't want to use a virtual environment then you can just install with pip:
```
pip install -U https://github.com/bjpop/sv_filter
```
## Worked example
## Usage
You can get a summary of the command line arguments like so:
```
sv_filter -h
```
|
bjpop/svfilter
|
README.md
|
Markdown
|
bsd-3-clause
| 960 |
/*
* Copyright I guess there should be some copywrite for this package,
*
* Copyright (c) 1992
*
* Liverpool University Department of Pure Mathematics,
* Liverpool, L69 3BX, England.
*
* Author Dr R. J. Morris.
*
* e-mail [email protected]
*
* This software is copyrighted as noted above. It may be freely copied,
* modified, and redistributed, provided that the copyright notice is
* preserved on all copies.
*
* There is no warranty or other guarantee of fitness for this software,
* it is provided solely "as is". Bug reports or fixes may be sent
* to the authors, who may or may not act on them as they desire.
*
* You may not include this software in a program or other software product
* without supplying the source, or without informing the end-user that the
* source is available for no extra charge.
*
* If you modify this software, you should include a notice giving the
* name of the person performing the modification, the date of modification,
* and the reason for such modification.
*
* All this software is public domain, as long as it is not used by any military
* establishment. Please note if you are a military establishment then a mutating
* virus has now escaped into you computer and is presently turning all your
* programs into socially useful, peaceful ones.
*
*/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#define I_AM_EQNFUNCTIONS
#include "eqn.h"
#include <varargs.h>
/*
#define SORT_ADD
#define PRINT_EXPANSION
#define PRINT_DIFF_FUN
*/
#define SILLYFUNS
#define grballoc(node) (node *) malloc(sizeof(node))
#define MAX(a,b) a > b ? a : b ;
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
/************************************************************************/
/* */
/* Now differentiate the equation. */
/* Using chain & product rule. */
/* No simplification occurs. */
/* */
/************************************************************************/
diff_wrt(base,var_name)
eqnode *base;
char *var_name;
{
eqnode *left1, *left2, *right1, *right2, *leftnode, *rightnode;
int i,failed,leftcount,rightcount;
if( base == NULL )
{
fprintf(stderr,"Tried to differentiate a NULL equation\n");
return;
}
failed = ! isalpha(var_name[0]);
i = 1;
while( var_name[i] != '\0' && !failed )
{
if( !isalnum(var_name[i]) && var_name[i] != '_' )
failed = TRUE;
++i;
}
if(failed)
{
fprintf(stderr,"bad name for differentiation %s\n",var_name);
return;
}
switch( base->op )
{
case FUNCTION:
if(base->u.f.f->type != CONSTANT_FUN )
return(diff_fun_wrt(base,var_name));
case NUMBER:
base->op = NUMBER;
base->u.num = 0.0;
break;
case BRACKET:
return(diff_wrt(base->u.n.r,var_name));
case NAME:
if( !strcmp(var_name,base->u.str) )
{
free( base->u.str );
base->op = NUMBER;
base->u.num = 1.0;
}
else
{
free( base->u.str );
base->op = NUMBER;
base->u.num = 0.0;
}
break;
case '+': case '-': case '=': case ',':
diff_wrt(base->u.n.l,var_name);
diff_wrt(base->u.n.r,var_name);
break;
case '^': /* a^n -> (n * a') * (a^(n-1)) */
/* should really be a^b -> d(a^b)_da da_dx + d(a^b)_db db_dx */
leftcount = count_eqn_args(base->u.n.l);
rightcount = count_eqn_args(base->u.n.r);
if(leftcount != rightcount )
{
fprintf(stderr,"Different counts while differentiating '^' %d %d\n",leftcount,rightcount);
diff_wrt(base->u.n.l,var_name);
diff_wrt(base->u.n.r,var_name);
break;
}
else if( leftcount == 1 )
{
left1 = base->u.n.l;
left2 = duplicate(left1);
right1 = base->u.n.r;
diff_wrt(left1,var_name);
base->op = '*';
base->u.n.l = grballoc(eqnode);
base->u.n.l->op = '*';
base->u.n.l->u.n.l = duplicate(right1);
base->u.n.l->u.n.r = left1;
base->u.n.r = grballoc(eqnode);
base->u.n.r->op = '^';
base->u.n.r->u.n.l = left2;
base->u.n.r->u.n.r = grballoc(eqnode);
base->u.n.r->u.n.r->op = '-';
base->u.n.r->u.n.r->u.n.l = right1;
base->u.n.r->u.n.r->u.n.r = grballoc(eqnode);
base->u.n.r->u.n.r->u.n.r->op = NUMBER;
base->u.n.r->u.n.r->u.n.r->u.num = 1.0;
break;
}
/* if leftcount != 1 fall through to do cross product */
case '*': case '.': /* a * b -> ( da * b ) + ( a * db ) */
left1 = base->u.n.l;
left2 = duplicate( left1 );
right1 = base->u.n.r;
right2 = duplicate( right1 );
diff_wrt(left1,var_name);
diff_wrt(right2,var_name);
leftnode = grballoc( eqnode );
rightnode = grballoc( eqnode );
leftnode->op = base->op;
rightnode->op = base->op;
leftnode->u.n.l = left1;
leftnode->u.n.r = right1;
rightnode->u.n.l = left2;
rightnode->u.n.r = right2;
base->op = '+';
base->u.n.l = leftnode;
base->u.n.r = rightnode;
break;
case '/': /* a / b -> (a' * b - a * b')/(b * b) */
left1 = base->u.n.l;
left2 = duplicate(left1);
right1 = base->u.n.r;
right2 = duplicate( right1 );
diff_wrt(left1,var_name);
diff_wrt(right2,var_name);
base->op = '/';
base->u.n.l = grballoc(eqnode);
base->u.n.l->op = '-';
base->u.n.l->u.n.l = grballoc(eqnode);
base->u.n.l->u.n.l->op = '*';
base->u.n.l->u.n.l->u.n.l = left1;
base->u.n.l->u.n.l->u.n.r = right1;
base->u.n.l->u.n.r = grballoc(eqnode);
base->u.n.l->u.n.r->op = '*';
base->u.n.l->u.n.r->u.n.l = left2;
base->u.n.l->u.n.r->u.n.r = right2;
base->u.n.r = grballoc(eqnode);
base->u.n.r->op = '*';
base->u.n.r->u.n.l = duplicate(right1);
base->u.n.r->u.n.r = duplicate(right1);
break;
default:
fprintf(stderr,"diff_wrt couldn't handel code %d\n",base->op);
} /* end switch */
return(TRUE);
}
/************************************************************************/
/* */
/* Now to differentiate a function */
/* df(a,b,c)_dx = df_da da_dx + df_db db_dx + df_dc dc_dx */
/* */
/************************************************************************/
diff_fun_wrt(base,name)
eqnode *base;
char *name;
{
eqnode *args,*diff,*temp,*diffarg,*new = NULL;
eqnode sub,subvarnode;
eqn_funs *fun;
int i,j;
char newvar[3];
int failed;
if( base == NULL )
{
fprintf(stderr,"Tried to differentiate a NULL equation\n");
return;
}
if( base->op != FUNCTION )
{
fprintf(stderr,"Tried to differentiate a function which is not a function\n");
return;
}
if( base->u.f.f->type == OPERATOR )
{
fprintf(stderr,"Don't know how to differentiate operator %s\n",
base->u.f.f->name);
return;
}
failed = ! isalpha(name[0]);
i = 1;
while( name[i] != '\0' && !failed )
{
if( !isalnum(name[i]) && name[i] != '_' )
failed = TRUE;
++i;
}
if(failed)
{
fprintf(stderr,"bad name for differentiation %s\n",name);
return;
}
/* Make a copy of arguments */
#ifdef PRINT_DIFF_FUN
fprintf(stderr,"diff_fun_wrt:\n");
fprint_eqn(stderr,base);
fprintf(stderr,"\n");
#endif
args = duplicate(base->u.f.a);
diff_wrt(base->u.f.a,name); /* a,b,c --> da,db,dc */
/* Initilise two nodes for substitution */
sub.op = '=';
subvarnode.op = NAME;
subvarnode.u.str = newvar;
newvar[0] = '@'; newvar[2] = '\0';
/* Get pointer to function */
fun = base->u.f.f;
base->u.n.r = base->u.f.a;
/* Now loop through all arguments replacing da by da * df_da */
for(i=0; i< fun->nvars; ++i)
{
diff = duplicate(fun->diff[i]);
/* replace the varible names in diff by @1 @2 @3 etc */
sub.u.n.r = &subvarnode;
sub.u.n.l = grballoc(eqnode);
sub.u.n.l->op = NAME;
for(j=0;j<fun->nvars;++j)
{
sub.u.n.l->u.str = fun->vars[j];
newvar[1] = '1'+j;
substitute(diff,&sub);
}
/* Now substitute the arguments into diff */
free(sub.u.n.l);
sub.u.n.l = &subvarnode;
diffarg = args;
for(j=0;j<fun->nvars;++j)
{
newvar[1] = '1'+j;
sub.u.n.r = get_eqn_arg(args,j+1);
substitute(diff,&sub);
}
/* Great now have da_dx, next use chain rule
multiply by df_da and add to new */
if( new == NULL )
{
new = grballoc(eqnode);
new->op = '*';
new->u.n.l = diff;
new->u.n.r = duplicate(get_eqn_arg(base->u.n.r,i+1));
}
else
{
temp = grballoc(eqnode);
temp->op = '+';
temp->u.n.l = new;
temp->u.n.r = grballoc(eqnode);
temp->u.n.r->op = '*';
temp->u.n.r->u.n.l = diff;
temp->u.n.r->u.n.r = duplicate(get_eqn_arg(base->u.n.r,i+1));
new = temp;
}
}
free_eqn_tree(base->u.n.r);
free_eqn_tree(args);
copy_node(base,new);
return(TRUE);
}
/*
* Function: diff_wrt_eqn
* Action: performs differentiation of left wrt right
* where left and right are seperated by a comma
*/
eqnode *diff_wrt_eqn(eqn)
eqnode *eqn;
{
eqn_node *temp;
if( eqn == NULL )
{
fprintf(stderr,"Tried to differentiate a null equation\n");
return(NULL);
}
if( eqnop(eqn) != ',' || eqnop(eqnr(eqn)) != NAME )
{
fprintf(stderr,"Must have 'eqn,name' for differentiation\n");
fprint_eqn(stderr,eqn);
fprintf(stderr,"\n");
return(eqn);
}
temp = eqnl(eqn);
diff_wrt(temp,eqnname(eqnr(eqn)));
free_eqn_node(eqnr(eqn));
free_eqn_node(eqn);
return(temp);
}
|
CavendishAstrophysics/anmap
|
eqn_lib/eqndiff.c
|
C
|
bsd-3-clause
| 9,023 |
"""
Permission classes for the dashboard
"""
from django.contrib.auth.models import User
from django.http import Http404
from rest_framework.generics import get_object_or_404
from rest_framework.permissions import BasePermission
from roles.roles import (
Instructor,
Staff,
)
class CanReadIfStaffOrSelf(BasePermission):
"""
Only staff on a program the learner is enrolled in can
see their dashboard. Learners can view their own dashboard.
"""
def has_permission(self, request, view):
if request.user.is_anonymous:
raise Http404
user = get_object_or_404(
User,
username=view.kwargs['username'],
)
# if the user is looking for their own profile, they're good
if request.user == user:
return True
# if the user is looking for someone enrolled in a program they
# are staff on, they're good
if request.user.role_set.filter(
role__in=(Staff.ROLE_ID, Instructor.ROLE_ID),
program__programenrollment__user=user,
).exists():
return True
else:
raise Http404
|
mitodl/micromasters
|
dashboard/permissions.py
|
Python
|
bsd-3-clause
| 1,168 |
# $Filename$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
#
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
# 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 the German Aerospace Center nor the names of
# its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
#A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#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.
"""
Contains the test of the search dialog.
"""
__version__ = "$Revision-Id:$"
|
DLR-SC/DataFinder
|
test/unittest/datafinder_test/gui/user/dialogs/search_dialog/__init__.py
|
Python
|
bsd-3-clause
| 1,787 |
<?php
/**
* Created by PhpStorm.
* User: admin
* Date: 30.01.2015
* Time: 14:06
*/
namespace yiicms\components\core;
use DateInterval;
use yii\helpers\FormatConverter;
/**
* Class DateTime
* @package sfw\fw\components
*/
class DateTime extends \DateTime
{
const DP_MINUTE = 'minute';
const DP_HOUR = 'hour';
const DP_DAY = 'day';
const DP_MONTH = 'month';
const DP_YEAR = 'year';
/**
* внутренний формат даты/времени
*/
const DATETIME_FORMAT = 'yyyy-MM-dd HH:mm:ss';
/**
* внутренний формат даты
*/
const DATE_FORMAT = 'yyyy-MM-dd';
/**
* @param string|integer $time время в любом поддерживаемом формате или Unix TimeStamp
* @param \DateTimeZone|string $timezone часовой пояс
*/
public function __construct($time = 'now', $timezone = null)
{
if (is_numeric($time)) {
//UNIX Timestamp
$time = '@' . $time;
$timezone = null;
} elseif ($timezone === null) {
$timezone = new \DateTimeZone('UTC');
} elseif (is_string($timezone)) {
$timezone = new \DateTimeZone($timezone);
}
parent::__construct($time, $timezone);
}
/**
* Set the TimeZone associated with the DateTime
* @param \DateTimeZone|string $timezone часовой пояс
* @return $this
* @link http://php.net/manual/en/datetime.settimezone.php
*/
public function setTimezone($timezone)
{
if (is_string($timezone)) {
$timezone = new \DateTimeZone($timezone);
}
return parent::setTimezone($timezone);
}
/**
* добавляет к дате интервал времени (для уменьшения перед $delta надо поставить "-")
* Y years P1Y
* M months
* D days P3D
* W weeks. These get converted into days, so can not be combined with D.
* H hours PT1H
* M minutes PT10M
* S seconds
* @param DateInterval|string $interval какой интервал добавить
* @return $this
*/
public function add($interval)
{
if ($interval instanceof DateInterval) {
parent::add($interval);
} else {
/** @noinspection OffsetOperationsInspection */
if ($interval{0} === '-') {
$this->sub(new \DateInterval(ltrim($interval, '-')));
} else {
parent::add(new \DateInterval($interval));
}
}
return $this;
}
/**
* @return string
*/
public function __toString()
{
/** @noinspection MagicMethodsValidityInspection */
return \Yii::$app->formatter->asDatetime($this, self::DATETIME_FORMAT);
}
/**
* @param string $format
* @return string
*/
public function asDateString($format = null)
{
if ($format === null) {
$format = self::DATE_FORMAT;
}
$date = clone $this;
$date->truncDate(self::DP_DAY);
return $date->format($format);
}
/**
* форматирует дату в соответствии с указанным форматом
* @param string $format формат в стандарте ICU. для использования стандарта PHP должно начинаться с php:
* @return string
*/
public function format($format)
{
$formatter = \Yii::$app->formatter;
if (strncmp($format, 'php:', 4) === 0) {
$format = FormatConverter::convertDatePhpToIcu(substr($format, 4));
}
return (new \IntlDateFormatter($formatter->locale, \IntlDateFormatter::NONE, \IntlDateFormatter::NONE, $this->getTimezone(), null, $format))
->format($this);
}
/**
* Возвращает разницу между двумя датами
* @param DateTime $datetime2
* @return integer
*/
public function diffSecond($datetime2)
{
return $datetime2->getTimestamp() - $this->getTimestamp();
}
/**
* отбрасывает дату до указанного поля
* @param string $part до какого поля отбросить дату
* @return DateTime
*/
public function truncDate($part)
{
switch ($part) {
case self::DP_MINUTE:
$format = 'yyyy-MM-dd HH:mm';
break;
case self::DP_HOUR:
$format = 'yyyy-MM-dd HH:00';
break;
case self::DP_DAY:
$format = 'yyyy-MM-dd';
break;
case self::DP_MONTH:
$format = 'yyyy-MM-01';
break;
case self::DP_YEAR:
$format = 'yyyy-01-01';
break;
default:
$format = self::DATETIME_FORMAT;
break;
}
parent::setTimestamp((new DateTime($this->format($format)))->getTimestamp());
return $this;
}
/**
* определяет сколько дней между датами
* если $to_date < $from_date выдает отрицательные значения
* @param string|DateTime $toDate до какой даты
* @return integer количество дней
*/
public function daysDiff($toDate)
{
$toDate = $toDate instanceof DateTime ? $toDate : new DateTime($toDate);
$days = $this->diff($toDate, false)->days;
return $this < $toDate ? $days : -$days;
}
/**
* @return string дата в строковом формате во внутреннем формате
*/
public function getIso()
{
return $this->format(DateTime::DATETIME_FORMAT);
}
/**
* функция определяет это последний день в месяце или нет
* @return bool
*/
public function getIsLastDayInMonth()
{
return (int)$this->format('d') === $this->getDaysInMonth();
}
/**
* определяет переданная дата это первый день месяца или нет
* @return bool
*/
public function getIsFirstDayInMonth()
{
return (int)$this->format('d') === 1;
}
/** @var array массив с количеством дней в каждом месяце */
private static $_dayInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
/**
* функция определяет сколько дней в месяце к которому принадлежит $date
* @return integer количество дней в месяце
*/
public function getDaysInMonth()
{
$year = $this->format('yyyy');
//в високосные года добавляем 1 день в февраль
if (($year % 4) === 0 && ($year % 400) !== 0) {
self::$_dayInMonth[1]++;
}
return self::$_dayInMonth[$this->format('M') - 1];
}
/**
* @var self
*/
private static $_runTime;
/**
* функция возвращает текущее время сервера в UTC в формате ISO
* в рамках одного запуска скрипта выдает всегда одно и оже время, время первого обращения
* @return DateTime
*/
public static function runTime()
{
if (self::$_runTime === null) {
self::$_runTime = new DateTime('now', \Yii::$app->formatter->timeZone);
}
return clone self::$_runTime;
}
private static $_runDate;
/**
* функция возвращает текущую дату сервера в UTC в формате ISO
* в рамках одного запуска скрипта выдает всегда одно и оже время, время первого обращения
* @return DateTime
*/
public static function runDate()
{
if (self::$_runDate === null) {
$runTime = self::runTime();
self::$_runDate = clone $runTime;
self::$_runDate->truncDate(self::DP_DAY);
}
return clone self::$_runDate;
}
/**
* выполняет преобразование даты/времени в строковый формат (в часовом поясе UTC) пригодный для хранения в БД
* @param string|\DateTime $datetime
* @param string|\DateTimeZone $timeZone часовой пояс. Если передан объект \DateTime то переданное значение
* часового пояса игнорируется и берется из свойста объекта \DateTime
* если передано строковое представление даты/времени и $valueTimeZone=null то используется часовой пояс форматтера
* @param string $format шаблон форматирования выходных данных по умолчанию self::DATETIME_FORMAT
* @return string дата/время в формате $format
*/
public static function convertToDbFormat($datetime, $timeZone = null, $format = null)
{
if (empty($datetime)) {
return null;
}
if ($format === null) {
$format = self::DATETIME_FORMAT;
}
$formatter = \Yii::$app->formatter;
if ($datetime instanceof DateTime) {
$dateObj = $datetime;
} else {
if ($timeZone instanceof \DateTimeZone) {
$timeZoneObj = $timeZone;
} elseif ($timeZone === null) {
$timeZoneObj = new \DateTimeZone($formatter->timeZone);
} else {
$timeZoneObj = new \DateTimeZone($timeZone);
}
$dateObj = new DateTime($datetime, $timeZoneObj);
}
return $dateObj->setTimezone('UTC')->format($format);
}
/**
* определяет сколько дней между датами
* если $to_date < $from_date выдает отрицательные значения
* @param string|DateTime $fromDate с какой даты
* @param string|DateTime $toDate по какую дату
* @param bool $include включать обе границы диапазона в количество дней
* @return false|int количество дней false если не удалось определить
*/
public static function daysBetweenDates($fromDate, $toDate, $include = false)
{
$_fromDate = $fromDate instanceof DateTime ? clone $fromDate : new DateTime($fromDate);
$_toDate = $toDate instanceof DateTime ? clone $toDate : new DateTime($toDate);
$flip = false;
if ($_toDate < $_fromDate) {
$tmp = $_toDate;
$_toDate = $_fromDate;
$_fromDate = $tmp;
$flip = true;
}
if ($include) {
$_fromDate->add('-P1D');
}
$days = $_toDate->diff($_fromDate)->days;
if ($days === false) {
return false;
}
return (int)($flip ? -$days : $days);
}
/**
* определяет сколько дней между датами
* если $to_date < $from_date выдает отрицательные значения
* @param string|DateTime $fromDate с какой даты
* @param string|DateTime $toDate по какую дату
* @param bool $include включать ли первый день в границы (добавляет 1 день)
* @return false|int количество дней false если не удалось определить
*/
public static function monthsBetweenDates($fromDate, $toDate, $include = false)
{
$_fromDate = $fromDate instanceof DateTime ? clone $fromDate : new DateTime($fromDate);
$_toDate = $toDate instanceof DateTime ? clone $toDate : new DateTime($toDate);
$flip = false;
if ($_toDate < $_fromDate) {
$tmp = $_toDate;
$_toDate = $_fromDate;
$_fromDate = $tmp;
$flip = true;
}
if ($include) {
$_toDate->add('P1D');
}
$months = $_toDate->diff($_fromDate)->m;
$days = $_toDate->diff($_fromDate)->d;
if ($months === false || $days === false) {
return false;
}
$months += $days / $_toDate->getDaysInMonth();
return (float)($flip ? -$months : $months);
}
/**
* выдает массив дат между $from_day и $to_day включительно например между '2013-01-01' и '2013-01-04'
* выдаст array('2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04')
* @param string|DateTime $fromDay дата в любом поддерживаемом формате
* @param string|DateTime $toDay дата в любом поддерживаемом формате
* @param bool $firstDayInclude включать ли стартовую дату в результирующий массив
* @return DateTime[]
*/
public static function rangeDate($fromDay, $toDay, $firstDayInclude = true)
{
$result = [];
$fromDate = $fromDay instanceof DateTime ? clone $fromDay : new DateTime($fromDay);
$toDate = $toDay instanceof DateTime ? clone $toDay : new DateTime($toDay);
$oneDay = new \DateInterval('P1D');
//если стартовый день не включать то передвигаем дату старнта на 1 день вперед
$fromDate->truncDate(self::DP_DAY);
$toDate->truncDate(self::DP_DAY);
if (!$firstDayInclude) {
$fromDate->add($oneDay);
}
while ($fromDate <= $toDate) {
$result[] = clone $fromDate;
$fromDate->add($oneDay);
}
return $result;
}
/**
* выдает текущую микросекунду
*/
public static function getMicrotime()
{
$t = gettimeofday();
return ($t['sec'] - floor($t['sec'] / 10000) * 10000) * 1000 + $t['usec'] / 1000;
}
/**
* выдает интервал времени в человекоудобном формате
* @param integer $second интервал в секундах
* @return string
* @deprecated
*/
public static function dateInterval($second)
{
$d = floor($second / 86400);
$s = $second - ($d * 86400);
$h = floor($s / 3600);
$s -= ($h * 3600);
$m = floor($s / 60);
$s -= ($m * 60);
$ret = $d !== 0 ? $d . \Yii::t('yiicms', ' д, ') : '';
$ret .= ($h !== 0) ? $h . \Yii::t('yiicms', ' ч, ') : '';
$ret .= ($m !== 0) ? $m . \Yii::t('yiicms', ' м, ') : '';
$ret .= ($s !== 0) ? $s . \Yii::t('yiicms', ' с, ') : '';
return rtrim($ret, ', ');
}
}
|
muratymt/yiicms
|
components/core/DateTime.php
|
PHP
|
bsd-3-clause
| 15,320 |
module LanguageChooser
def self.included(base)
base.class_eval {
around_filter :set_locale
}
end
private
# Set the locale from the parameters, the session, or the navigator
# If none of these works, the Globalite default locale is set (en-*)
def set_locale
# Get the current path and request method (useful in the layout for changing the language)
@current_path = request.env['PATH_INFO']
@request_method = request.env['REQUEST_METHOD']
# Try to get the locale from the parameters, from the session, and then from the navigator
if params[:user_locale]
# Store the locale in the session
Locale.code = params[:user_locale][:code]
session[:locale] = Locale.code
elsif session[:locale]
Locale.code = session[:locale]
else
Locale.code = local_case(get_valid_lang_from_accept_header)
end
logger.debug "[globalite] Locale set to #{Locale.code}"
# render the page
yield
# reset the locale to its default value
Locale.reset!
end
# Get a sorted array of the navigator languages
def get_sorted_langs_from_accept_header
accept_langs = (request.env['HTTP_ACCEPT_LANGUAGE'] || "en-us,en;q=0.5").split(/,/) rescue nil
return nil unless accept_langs
# Extract langs and sort by weight
# Example HTTP_ACCEPT_LANGUAGE: "en-au,en-gb;q=0.8,en;q=0.5,ja;q=0.3"
wl = {}
accept_langs.each {|accept_lang|
if (accept_lang + ';q=1') =~ /^(.+?);q=([^;]+).*/
wl[($2.to_f rescue -1.0)]= $1
end
}
logger.debug "[globalite] client accepted locales: #{wl.sort{|a,b| b[0] <=> a[0] }.map{|a| a[1] }.to_sentence}"
sorted_langs = wl.sort{|a,b| b[0] <=> a[0] }.map{|a| a[1] }
end
# Returns a valid language that best suits the HTTP_ACCEPT_LANGUAGE request header.
# If no valid language can be deduced, then <tt>nil</tt> is returned.
def get_valid_lang_from_accept_header
# Get the sorted navigator languages and find the first one that matches our available languages
get_sorted_langs_from_accept_header.detect{|l| get_matching_ui_locale(l) }
end
# Returns the UI locale that best matches with the parameter
# or nil if not found
def get_matching_ui_locale(locale)
lang = locale[0,2].downcase
# Check with exact matching
if Globalite.ui_locales.values.include?(local_case(locale))
local_case(locale)
end
# Check on the language only
Globalite.ui_locales.values.each do |value|
value.to_s =~ /#{lang}-*/ ? value : nil
end
end
def local_case(l)
if l[3,5]
"#{l[0,2]}-#{l[3,5].upcase}".to_sym
else
"#{l[0,2]}-*".to_sym
end
end
# can be used as a shortcut for translation
def t(replacement_string = '__localization_missing__', override_key = nil)
(override_key || replacement_string.downcase.gsub(/\s/, "_").to_sym).l(replacement_string)
end
end
# Locale.code = params[:user_locale][:code] #get_matching_ui_locale(params[:user_locale][:code]) #|| session[:locale] || get_valid_lang_from_accept_header || Globalite.default_language
|
wparkman/spree
|
vendor/extensions/language_chooser/lib/language_chooser.rb
|
Ruby
|
bsd-3-clause
| 3,080 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "extensions/browser/guest_view/web_view/web_view_guest.h"
#include "content/nw/src/nw_content.h"
#include "content/public/common/content_client.h"
#include "content/public/browser/content_browser_client.h"
#include <stddef.h>
#include "content/nw/src/nw_content.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/manifest_handlers/webview_info.h"
#include <map>
#include <memory>
#include <string>
#include <utility>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/lazy_instance.h"
#include "base/metrics/user_metrics.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/post_task.h"
#include "build/build_config.h"
#include "components/guest_view/browser/guest_view_event.h"
#include "components/guest_view/browser/guest_view_manager.h"
#include "components/guest_view/common/guest_view_constants.h"
#include "components/web_cache/browser/web_cache_manager.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/storage_partition_config.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/stop_find_action.h"
#include "content/public/common/url_constants.h"
#include "extensions/browser/api/declarative/rules_registry_service.h"
#include "extensions/browser/api/extensions_api_client.h"
#include "extensions/browser/api/guest_view/web_view/web_view_internal_api.h"
#include "extensions/browser/api/web_request/web_request_api.h"
#include "extensions/browser/bad_message.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/extension_util.h"
#include "extensions/browser/extension_web_contents_observer.h"
#include "extensions/browser/extensions_browser_client.h"
#include "extensions/browser/guest_view/web_view/web_view_constants.h"
#include "extensions/browser/guest_view/web_view/web_view_content_script_manager.h"
#include "extensions/browser/guest_view/web_view/web_view_permission_helper.h"
#include "extensions/browser/guest_view/web_view/web_view_permission_types.h"
#include "extensions/browser/guest_view/web_view/web_view_renderer_state.h"
#include "extensions/browser/process_manager.h"
#include "extensions/browser/url_loader_factory_manager.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension_messages.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/strings/grit/extensions_strings.h"
#include "ipc/ipc_message_macros.h"
#include "net/base/escape.h"
#include "net/base/net_errors.h"
#include "net/cookies/canonical_cookie.h"
#include "third_party/blink/public/common/logging/logging_utils.h"
#include "third_party/blink/public/common/mediastream/media_stream_request.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "ui/base/models/simple_menu_model.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "url/url_constants.h"
using base::UserMetricsAction;
using content::GlobalRequestID;
using content::RenderFrameHost;
using content::RenderProcessHost;
using content::StoragePartition;
using content::WebContents;
using guest_view::GuestViewBase;
using guest_view::GuestViewEvent;
using guest_view::GuestViewManager;
using zoom::ZoomController;
namespace extensions {
namespace {
// Strings used to encode blob url fallback mode in site URLs.
constexpr char kNoFallback[] = "nofallback";
constexpr char kInMemoryFallback[] = "inmemoryfallback";
constexpr char kOnDiskFallback[] = "ondiskfallback";
// Returns storage partition removal mask from web_view clearData mask. Note
// that storage partition mask is a subset of webview's data removal mask.
uint32_t GetStoragePartitionRemovalMask(uint32_t web_view_removal_mask) {
uint32_t mask = 0;
if (web_view_removal_mask & webview::WEB_VIEW_REMOVE_DATA_MASK_APPCACHE)
mask |= StoragePartition::REMOVE_DATA_MASK_APPCACHE;
if (web_view_removal_mask &
(webview::WEB_VIEW_REMOVE_DATA_MASK_COOKIES |
webview::WEB_VIEW_REMOVE_DATA_MASK_SESSION_COOKIES |
webview::WEB_VIEW_REMOVE_DATA_MASK_PERSISTENT_COOKIES)) {
mask |= StoragePartition::REMOVE_DATA_MASK_COOKIES;
}
if (web_view_removal_mask & webview::WEB_VIEW_REMOVE_DATA_MASK_FILE_SYSTEMS)
mask |= StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS;
if (web_view_removal_mask & webview::WEB_VIEW_REMOVE_DATA_MASK_INDEXEDDB)
mask |= StoragePartition::REMOVE_DATA_MASK_INDEXEDDB;
if (web_view_removal_mask & webview::WEB_VIEW_REMOVE_DATA_MASK_LOCAL_STORAGE)
mask |= StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE;
if (web_view_removal_mask & webview::WEB_VIEW_REMOVE_DATA_MASK_WEBSQL)
mask |= StoragePartition::REMOVE_DATA_MASK_WEBSQL;
return mask;
}
std::string WindowOpenDispositionToString(
WindowOpenDisposition window_open_disposition) {
switch (window_open_disposition) {
case WindowOpenDisposition::IGNORE_ACTION:
return "ignore";
case WindowOpenDisposition::SAVE_TO_DISK:
return "save_to_disk";
case WindowOpenDisposition::CURRENT_TAB:
return "current_tab";
case WindowOpenDisposition::NEW_BACKGROUND_TAB:
return "new_background_tab";
case WindowOpenDisposition::NEW_FOREGROUND_TAB:
return "new_foreground_tab";
case WindowOpenDisposition::NEW_WINDOW:
return "new_window";
case WindowOpenDisposition::NEW_POPUP:
return "new_popup";
default:
NOTREACHED() << "Unknown Window Open Disposition";
return "ignore";
}
}
static std::string TerminationStatusToString(base::TerminationStatus status) {
switch (status) {
case base::TERMINATION_STATUS_NORMAL_TERMINATION:
return "normal";
case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
case base::TERMINATION_STATUS_STILL_RUNNING:
return "abnormal";
#if defined(OS_CHROMEOS)
case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM:
return "oom killed";
#endif
case base::TERMINATION_STATUS_OOM:
return "oom";
case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
return "killed";
case base::TERMINATION_STATUS_PROCESS_CRASHED:
return "crashed";
case base::TERMINATION_STATUS_LAUNCH_FAILED:
return "failed to launch";
#if defined(OS_WIN)
case base::TERMINATION_STATUS_INTEGRITY_FAILURE:
return "integrity failure";
#endif
case base::TERMINATION_STATUS_MAX_ENUM:
break;
}
NOTREACHED() << "Unknown Termination Status.";
return "unknown";
}
std::string GetStoragePartitionIdFromSiteURL(const GURL& site_url) {
const std::string& partition_id = site_url.query();
bool persist_storage = site_url.path().find("persist") != std::string::npos;
return (persist_storage ? webview::kPersistPrefix : "") + partition_id;
}
void ParsePartitionParam(const base::DictionaryValue& create_params,
std::string* storage_partition_id,
bool* persist_storage) {
std::string partition_str;
if (!create_params.GetString(webview::kStoragePartitionId, &partition_str)) {
return;
}
// Since the "persist:" prefix is in ASCII, base::StartsWith will work fine on
// UTF-8 encoded |partition_id|. If the prefix is a match, we can safely
// remove the prefix without splicing in the middle of a multi-byte codepoint.
// We can use the rest of the string as UTF-8 encoded one.
if (base::StartsWith(partition_str, "persist:",
base::CompareCase::SENSITIVE)) {
size_t index = partition_str.find(":");
CHECK(index != std::string::npos);
// It is safe to do index + 1, since we tested for the full prefix above.
*storage_partition_id = partition_str.substr(index + 1);
if (storage_partition_id->empty()) {
// TODO(lazyboy): Better way to deal with this error.
return;
}
*persist_storage = true;
} else {
*storage_partition_id = partition_str;
*persist_storage = false;
}
}
double ConvertZoomLevelToZoomFactor(double zoom_level) {
double zoom_factor = blink::PageZoomLevelToZoomFactor(zoom_level);
// Because the conversion from zoom level to zoom factor isn't perfect, the
// resulting zoom factor is rounded to the nearest 6th decimal place.
zoom_factor = round(zoom_factor * 1000000) / 1000000;
return zoom_factor;
}
using WebViewKey = std::pair<int, int>;
using WebViewKeyToIDMap = std::map<WebViewKey, int>;
static base::LazyInstance<WebViewKeyToIDMap>::DestructorAtExit
web_view_key_to_id_map = LAZY_INSTANCE_INITIALIZER;
bool IsInWebViewMainFrame(content::NavigationHandle* navigation_handle) {
// TODO(1261928): Due to the use of inner WebContents, a WebView's main frame
// is considered primary. This will no longer be the case once we migrate
// guest views to MPArch.
return navigation_handle->IsInPrimaryMainFrame();
}
} // namespace
WebViewGuest::NewWindowInfo::NewWindowInfo(const GURL& url,
const std::string& name)
: name(name), url(url) {}
WebViewGuest::NewWindowInfo::NewWindowInfo(const WebViewGuest::NewWindowInfo&) =
default;
WebViewGuest::NewWindowInfo::~NewWindowInfo() = default;
// static
void WebViewGuest::CleanUp(content::BrowserContext* browser_context,
int embedder_process_id,
int view_instance_id) {
GuestViewBase::CleanUp(browser_context, embedder_process_id,
view_instance_id);
// Clean up rules registries for the WebView.
WebViewKey key(embedder_process_id, view_instance_id);
auto it = web_view_key_to_id_map.Get().find(key);
if (it != web_view_key_to_id_map.Get().end()) {
auto rules_registry_id = it->second;
web_view_key_to_id_map.Get().erase(it);
RulesRegistryService* rrs =
RulesRegistryService::GetIfExists(browser_context);
if (rrs)
rrs->RemoveRulesRegistriesByID(rules_registry_id);
}
// Clean up web request event listeners for the WebView.
ExtensionWebRequestEventRouter::GetInstance()->RemoveWebViewEventListeners(
browser_context, embedder_process_id, view_instance_id);
// Clean up content scripts for the WebView.
auto* csm = WebViewContentScriptManager::Get(browser_context);
csm->RemoveAllContentScriptsForWebView(embedder_process_id, view_instance_id);
// Allow an extensions browser client to potentially perform more cleanup.
ExtensionsBrowserClient::Get()->CleanUpWebView(
browser_context, embedder_process_id, view_instance_id);
}
// static
GuestViewBase* WebViewGuest::Create(WebContents* owner_web_contents) {
return new WebViewGuest(owner_web_contents);
}
// static
bool WebViewGuest::GetGuestPartitionConfigForSite(
content::BrowserContext* browser_context,
const GURL& site,
content::StoragePartitionConfig* storage_partition_config) {
if (!site.SchemeIs(content::kGuestScheme))
return false;
// The partition name is user supplied value, which we have encoded when the
// URL was created, so it needs to be decoded. Since it was created via
// EscapeQueryParamValue(), it should have no path separators or control codes
// when unescaped, but safest to check for that and fail if it does.
std::string partition_name;
if (!net::UnescapeBinaryURLComponentSafe(site.query_piece(),
true /* fail_on_path_separators */,
&partition_name)) {
return false;
}
// Since guest URLs are only used for packaged apps, there must be an app
// id in the URL.
CHECK(site.has_host());
// Since persistence is optional, the path must either be empty or the
// literal string.
bool in_memory = (site.path() != "/persist");
*storage_partition_config = content::StoragePartitionConfig::Create(
browser_context, site.host(), partition_name, in_memory);
// A <webview> inside a chrome app needs to be able to resolve Blob URLs that
// were created by the chrome app. The chrome app has the same
// partition_domain but empty partition_name. Setting this flag on the
// partition config causes it to be used as fallback for the purpose of
// resolving blob URLs.
// Default to having the fallback partition on disk, as that matches most
// closely what we would have done before fallback behavior started being
// encoded in the site URL.
content::StoragePartitionConfig::FallbackMode fallback_mode =
content::StoragePartitionConfig::FallbackMode::kFallbackPartitionOnDisk;
if (site.ref() == kNoFallback) {
fallback_mode = content::StoragePartitionConfig::FallbackMode::kNone;
} else if (site.ref() == kInMemoryFallback) {
fallback_mode = content::StoragePartitionConfig::FallbackMode::
kFallbackPartitionInMemory;
} else if (site.ref() == kOnDiskFallback) {
fallback_mode =
content::StoragePartitionConfig::FallbackMode::kFallbackPartitionOnDisk;
}
storage_partition_config->set_fallback_to_partition_domain_for_blob_urls(
fallback_mode);
return true;
}
// static
GURL WebViewGuest::GetSiteForGuestPartitionConfig(
const content::StoragePartitionConfig& storage_partition_config) {
std::string url_encoded_partition = net::EscapeQueryParamValue(
storage_partition_config.partition_name(), false);
const char* fallback = "";
switch (
storage_partition_config.fallback_to_partition_domain_for_blob_urls()) {
case content::StoragePartitionConfig::FallbackMode::kNone:
fallback = kNoFallback;
break;
case content::StoragePartitionConfig::FallbackMode::
kFallbackPartitionOnDisk:
fallback = kOnDiskFallback;
break;
case content::StoragePartitionConfig::FallbackMode::
kFallbackPartitionInMemory:
fallback = kInMemoryFallback;
break;
}
return GURL(
base::StringPrintf("%s://%s/%s?%s#%s", content::kGuestScheme,
storage_partition_config.partition_domain().c_str(),
storage_partition_config.in_memory() ? "" : "persist",
url_encoded_partition.c_str(), fallback));
}
// static
std::string WebViewGuest::GetPartitionID(
RenderProcessHost* render_process_host) {
WebViewRendererState* renderer_state = WebViewRendererState::GetInstance();
int process_id = render_process_host->GetID();
std::string partition_id;
if (renderer_state->IsGuest(process_id))
renderer_state->GetPartitionID(process_id, &partition_id);
return partition_id;
}
// static
const char WebViewGuest::Type[] = "webview";
// static
int WebViewGuest::GetOrGenerateRulesRegistryID(
int embedder_process_id,
int webview_instance_id) {
bool is_web_view = embedder_process_id && webview_instance_id;
if (!is_web_view)
return RulesRegistryService::kDefaultRulesRegistryID;
WebViewKey key = std::make_pair(embedder_process_id, webview_instance_id);
auto it = web_view_key_to_id_map.Get().find(key);
if (it != web_view_key_to_id_map.Get().end())
return it->second;
auto* rph = RenderProcessHost::FromID(embedder_process_id);
int rules_registry_id =
RulesRegistryService::Get(rph->GetBrowserContext())->
GetNextRulesRegistryID();
web_view_key_to_id_map.Get()[key] = rules_registry_id;
return rules_registry_id;
}
void WebViewGuest::CreateWebContents(const base::DictionaryValue& create_params,
WebContentsCreatedCallback callback) {
RenderProcessHost* owner_render_process_host =
owner_web_contents()->GetMainFrame()->GetProcess();
DCHECK_EQ(browser_context(), owner_render_process_host->GetBrowserContext());
std::string storage_partition_id;
bool persist_storage = false;
ParsePartitionParam(create_params, &storage_partition_id, &persist_storage);
bool allow_nw = false;
create_params.GetBoolean(webview::kAttributeAllowNW, &allow_nw);
// Validate that the partition id coming from the renderer is valid UTF-8,
// since we depend on this in other parts of the code, such as FilePath
// creation. If the validation fails, treat it as a bad message and kill the
// renderer process.
if (!base::IsStringUTF8(storage_partition_id)) {
bad_message::ReceivedBadMessage(owner_render_process_host,
bad_message::WVG_PARTITION_ID_NOT_UTF8);
std::move(callback).Run(nullptr);
return;
}
std::string partition_domain = GetOwnerSiteURL().host();
auto partition_config = content::StoragePartitionConfig::Create(
browser_context(), partition_domain, storage_partition_id,
!persist_storage /* in_memory */);
if (GetOwnerSiteURL().SchemeIs(extensions::kExtensionScheme)) {
auto owner_config =
extensions::util::GetStoragePartitionConfigForExtensionId(
GetOwnerSiteURL().host(), browser_context());
if (browser_context()->IsOffTheRecord()) {
DCHECK(owner_config.in_memory());
}
if (!owner_config.is_default()) {
partition_config.set_fallback_to_partition_domain_for_blob_urls(
owner_config.in_memory()
? content::StoragePartitionConfig::FallbackMode::
kFallbackPartitionInMemory
: content::StoragePartitionConfig::FallbackMode::
kFallbackPartitionOnDisk);
DCHECK(owner_config == partition_config.GetFallbackForBlobUrls().value());
}
}
GURL guest_site = GetSiteForGuestPartitionConfig(partition_config);
// If we already have a webview tag in the same app using the same storage
// partition, we should use the same SiteInstance so the existing tag and
// the new tag can script each other.
auto* guest_view_manager =
GuestViewManager::FromBrowserContext(browser_context());
scoped_refptr<content::SiteInstance> guest_site_instance =
guest_view_manager->GetGuestSiteInstance(guest_site);
if (!guest_site_instance) {
// Create the SiteInstance in a new BrowsingInstance, which will ensure
// that webview tags are also not allowed to send messages across
// different partitions.
guest_site_instance =
content::SiteInstance::CreateForGuest(browser_context(), guest_site);
}
WebContents::CreateParams params(browser_context(),
std::move(guest_site_instance));
params.guest_delegate = this;
// TODO(erikchen): Fix ownership semantics for guest views.
// https://crbug.com/832879.
WebContents* new_contents = WebContents::Create(params).release();
// Grant access to the origin of the embedder to the guest process. This
// allows blob: and filesystem: URLs with the embedder origin to be created
// inside the guest. It is possible to do this by running embedder code
// through webview accessible_resources.
//
// TODO(dcheng): Is granting commit origin really the right thing to do here?
content::ChildProcessSecurityPolicy::GetInstance()->GrantCommitOrigin(
new_contents->GetMainFrame()->GetProcess()->GetID(),
url::Origin::Create(GetOwnerSiteURL()));
std::move(callback).Run(new_contents);
}
void WebViewGuest::DidAttachToEmbedder() {
ApplyAttributes(*attach_params());
}
void WebViewGuest::DidInitialize(const base::DictionaryValue& create_params) {
script_executor_ = std::make_unique<ScriptExecutor>(web_contents());
ExtensionsAPIClient::Get()->AttachWebContentsHelpers(web_contents());
web_view_permission_helper_ = std::make_unique<WebViewPermissionHelper>(this);
rules_registry_id_ = GetOrGenerateRulesRegistryID(
owner_web_contents()->GetMainFrame()->GetProcess()->GetID(),
view_instance_id());
// We must install the mapping from guests to WebViews prior to resuming
// suspended resource loads so that the WebRequest API will catch resource
// requests.
PushWebViewStateToIOThread();
ApplyAttributes(create_params);
}
void WebViewGuest::ClearCodeCache(base::Time remove_since,
uint32_t removal_mask,
base::OnceClosure callback) {
content::StoragePartition* partition =
web_contents()->GetBrowserContext()->GetStoragePartition(
web_contents()->GetSiteInstance());
DCHECK(partition);
base::OnceClosure code_cache_removal_done_callback = base::BindOnce(
&WebViewGuest::ClearDataInternal, weak_ptr_factory_.GetWeakPtr(),
remove_since, removal_mask, std::move(callback));
partition->ClearCodeCaches(remove_since, base::Time::Now(),
base::RepeatingCallback<bool(const GURL&)>(),
std::move(code_cache_removal_done_callback));
}
void WebViewGuest::ClearDataInternal(base::Time remove_since,
uint32_t removal_mask,
base::OnceClosure callback) {
uint32_t storage_partition_removal_mask =
GetStoragePartitionRemovalMask(removal_mask);
if (!storage_partition_removal_mask) {
std::move(callback).Run();
return;
}
auto cookie_delete_filter = network::mojom::CookieDeletionFilter::New();
// Intentionally do not set the deletion filter time interval because the
// time interval parameters to ClearData() will be used.
// TODO(cmumford): Make this (and webview::* constants) constexpr.
const uint32_t ALL_COOKIES_MASK =
webview::WEB_VIEW_REMOVE_DATA_MASK_SESSION_COOKIES |
webview::WEB_VIEW_REMOVE_DATA_MASK_PERSISTENT_COOKIES;
if ((removal_mask & ALL_COOKIES_MASK) == ALL_COOKIES_MASK) {
cookie_delete_filter->session_control =
network::mojom::CookieDeletionSessionControl::IGNORE_CONTROL;
} else if (removal_mask &
webview::WEB_VIEW_REMOVE_DATA_MASK_SESSION_COOKIES) {
cookie_delete_filter->session_control =
network::mojom::CookieDeletionSessionControl::SESSION_COOKIES;
} else if (removal_mask &
webview::WEB_VIEW_REMOVE_DATA_MASK_PERSISTENT_COOKIES) {
cookie_delete_filter->session_control =
network::mojom::CookieDeletionSessionControl::PERSISTENT_COOKIES;
}
bool perform_cleanup = remove_since.is_null();
content::StoragePartition* partition =
web_contents()->GetBrowserContext()->GetStoragePartition(
web_contents()->GetSiteInstance());
partition->ClearData(
storage_partition_removal_mask,
content::StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL,
content::StoragePartition::OriginMatcherFunction(),
std::move(cookie_delete_filter), perform_cleanup, remove_since,
base::Time::Max(), std::move(callback));
}
void WebViewGuest::GuestViewDidStopLoading() {
auto args = std::make_unique<base::DictionaryValue>();
DispatchEventToView(std::make_unique<GuestViewEvent>(webview::kEventLoadStop,
std::move(args)));
}
void WebViewGuest::EmbedderFullscreenToggled(bool entered_fullscreen) {
is_embedder_fullscreen_ = entered_fullscreen;
// If the embedder has got out of fullscreen, we get out of fullscreen
// mode as well.
if (!entered_fullscreen)
SetFullscreenState(false);
}
bool WebViewGuest::ZoomPropagatesFromEmbedderToGuest() const {
// We use the embedder's zoom iff we haven't set a zoom ourselves using
// e.g. webview.setZoom().
return !did_set_explicit_zoom_;
}
const char* WebViewGuest::GetAPINamespace() const {
return webview::kAPINamespace;
}
int WebViewGuest::GetTaskPrefix() const {
return IDS_EXTENSION_TASK_MANAGER_WEBVIEW_TAG_PREFIX;
}
void WebViewGuest::GuestDestroyed() {
WebViewRendererState::GetInstance()->RemoveGuest(
web_contents()
->GetMainFrame()
->GetRenderViewHost()
->GetProcess()
->GetID(),
web_contents()->GetMainFrame()->GetRenderViewHost()->GetRoutingID());
}
void WebViewGuest::GuestReady() {
// The guest RenderView should always live in an isolated guest process.
CHECK(web_contents()->GetMainFrame()->GetProcess()->IsForGuestsOnly());
ExtensionWebContentsObserver::GetForWebContents(web_contents())
->GetLocalFrame(web_contents()->GetMainFrame())
->SetFrameName(name_);
// We don't want to accidentally set the opacity of an interstitial page.
// WebContents::GetRenderWidgetHostView will return the RWHV of an
// interstitial page if one is showing at this time. We only want opacity
// to apply to web pages.
SetTransparency();
}
void WebViewGuest::GuestSizeChangedDueToAutoSize(const gfx::Size& old_size,
const gfx::Size& new_size) {
auto args = std::make_unique<base::DictionaryValue>();
args->SetInteger(webview::kOldHeight, old_size.height());
args->SetInteger(webview::kOldWidth, old_size.width());
args->SetInteger(webview::kNewHeight, new_size.height());
args->SetInteger(webview::kNewWidth, new_size.width());
DispatchEventToView(std::make_unique<GuestViewEvent>(
webview::kEventSizeChanged, std::move(args)));
}
bool WebViewGuest::IsAutoSizeSupported() const {
return true;
}
void WebViewGuest::GuestZoomChanged(double old_zoom_level,
double new_zoom_level) {
// Dispatch the zoomchange event.
double old_zoom_factor = ConvertZoomLevelToZoomFactor(old_zoom_level);
double new_zoom_factor = ConvertZoomLevelToZoomFactor(new_zoom_level);
auto args = std::make_unique<base::DictionaryValue>();
args->SetDoubleKey(webview::kOldZoomFactor, old_zoom_factor);
args->SetDoubleKey(webview::kNewZoomFactor, new_zoom_factor);
DispatchEventToView(std::make_unique<GuestViewEvent>(
webview::kEventZoomChange, std::move(args)));
}
void WebViewGuest::WillDestroy() {
if (!attached() && GetOpener())
GetOpener()->pending_new_windows_.erase(this);
}
void WebViewGuest::CloseContents(WebContents* source) {
auto args = std::make_unique<base::DictionaryValue>();
DispatchEventToView(
std::make_unique<GuestViewEvent>(webview::kEventClose, std::move(args)));
}
void WebViewGuest::FindReply(WebContents* source,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) {
GuestViewBase::FindReply(source, request_id, number_of_matches,
selection_rect, active_match_ordinal, final_update);
find_helper_.FindReply(request_id, number_of_matches, selection_rect,
active_match_ordinal, final_update);
}
double WebViewGuest::GetZoom() const {
double zoom_level =
ZoomController::FromWebContents(web_contents())->GetZoomLevel();
return ConvertZoomLevelToZoomFactor(zoom_level);
}
ZoomController::ZoomMode WebViewGuest::GetZoomMode() {
return ZoomController::FromWebContents(web_contents())->zoom_mode();
}
bool WebViewGuest::HandleContextMenu(
content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) {
return web_view_guest_delegate_ &&
web_view_guest_delegate_->HandleContextMenu(render_frame_host, params);
}
bool WebViewGuest::HandleKeyboardEvent(
WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (HandleKeyboardShortcuts(event))
return true;
return GuestViewBase::HandleKeyboardEvent(source, event);
}
bool WebViewGuest::PreHandleGestureEvent(WebContents* source,
const blink::WebGestureEvent& event) {
return !allow_scaling_ && GuestViewBase::PreHandleGestureEvent(source, event);
}
void WebViewGuest::LoadAbort(bool is_top_level,
const GURL& url,
int error_code) {
auto args = std::make_unique<base::DictionaryValue>();
args->SetBoolean(guest_view::kIsTopLevel, is_top_level);
args->SetString(guest_view::kUrl, url.possibly_invalid_spec());
args->SetInteger(guest_view::kCode, error_code);
args->SetString(guest_view::kReason, net::ErrorToShortString(error_code));
DispatchEventToView(std::make_unique<GuestViewEvent>(webview::kEventLoadAbort,
std::move(args)));
}
void WebViewGuest::CreateNewGuestWebViewWindow(
const content::OpenURLParams& params) {
GuestViewManager* guest_manager =
GuestViewManager::FromBrowserContext(browser_context());
// Set the attach params to use the same partition as the opener.
// We pull the partition information from the site's URL, which is of the
// form guest://site/{persist}?{partition_name}.
const GURL& site_url = web_contents()->GetSiteInstance()->GetSiteURL();
const std::string storage_partition_id =
GetStoragePartitionIdFromSiteURL(site_url);
base::DictionaryValue create_params;
create_params.SetString(webview::kStoragePartitionId, storage_partition_id);
guest_manager->CreateGuest(
WebViewGuest::Type, embedder_web_contents(), create_params,
base::BindOnce(&WebViewGuest::NewGuestWebViewCallback,
weak_ptr_factory_.GetWeakPtr(), params));
}
void WebViewGuest::NewGuestWebViewCallback(const content::OpenURLParams& params,
WebContents* guest_web_contents) {
WebViewGuest* new_guest = WebViewGuest::FromWebContents(guest_web_contents);
new_guest->SetOpener(this);
// Take ownership of |new_guest|.
pending_new_windows_.insert(
std::make_pair(new_guest, NewWindowInfo(params.url, std::string())));
// Request permission to show the new window.
RequestNewWindowPermission(params.disposition,
gfx::Rect(),
new_guest->web_contents());
}
// TODO(fsamuel): Find a reliable way to test the 'responsive' and
// 'unresponsive' events.
void WebViewGuest::RendererResponsive(
WebContents* source,
content::RenderWidgetHost* render_widget_host) {
auto args = std::make_unique<base::DictionaryValue>();
args->SetInteger(webview::kProcessId,
render_widget_host->GetProcess()->GetID());
DispatchEventToView(std::make_unique<GuestViewEvent>(
webview::kEventResponsive, std::move(args)));
}
void WebViewGuest::RendererUnresponsive(
WebContents* source,
content::RenderWidgetHost* render_widget_host,
base::RepeatingClosure hang_monitor_restarter) {
auto args = std::make_unique<base::DictionaryValue>();
args->SetInteger(webview::kProcessId,
render_widget_host->GetProcess()->GetID());
DispatchEventToView(std::make_unique<GuestViewEvent>(
webview::kEventUnresponsive, std::move(args)));
}
void WebViewGuest::StartFind(
const std::u16string& search_text,
blink::mojom::FindOptionsPtr options,
scoped_refptr<WebViewInternalFindFunction> find_function) {
find_helper_.Find(web_contents(), search_text, std::move(options),
find_function);
}
void WebViewGuest::StopFinding(content::StopFindAction action) {
find_helper_.CancelAllFindSessions();
web_contents()->StopFinding(action);
}
bool WebViewGuest::Go(int relative_index) {
content::NavigationController& controller = web_contents()->GetController();
if (!controller.CanGoToOffset(relative_index))
return false;
controller.GoToOffset(relative_index);
return true;
}
void WebViewGuest::Reload() {
// TODO(fsamuel): Don't check for repost because we don't want to show
// Chromium's repost warning. We might want to implement a separate API
// for registering a callback if a repost is about to happen.
web_contents()->GetController().Reload(content::ReloadType::NORMAL, false);
}
void WebViewGuest::SetUserAgentOverride(
const std::string& user_agent_override) {
is_overriding_user_agent_ = !user_agent_override.empty();
if (is_overriding_user_agent_) {
base::RecordAction(UserMetricsAction("WebView.Guest.OverrideUA"));
}
web_contents()->SetUserAgentOverride(
blink::UserAgentOverride::UserAgentOnly(user_agent_override), false);
}
void WebViewGuest::Stop() {
web_contents()->Stop();
}
void WebViewGuest::Terminate() {
base::RecordAction(UserMetricsAction("WebView.Guest.Terminate"));
base::ProcessHandle process_handle =
web_contents()->GetMainFrame()->GetProcess()->GetProcess().Handle();
if (process_handle) {
web_contents()->GetMainFrame()->GetProcess()->Shutdown(
content::RESULT_CODE_KILLED);
}
}
bool WebViewGuest::ClearData(base::Time remove_since,
uint32_t removal_mask,
base::OnceClosure callback) {
base::RecordAction(UserMetricsAction("WebView.Guest.ClearData"));
content::StoragePartition* partition =
web_contents()->GetBrowserContext()->GetStoragePartition(
web_contents()->GetSiteInstance());
if (!partition)
return false;
if (removal_mask & webview::WEB_VIEW_REMOVE_DATA_MASK_CACHE) {
// First clear http cache data and then clear the code cache in
// |ClearCodeCache| and the rest is cleared in |ClearDataInternal|.
int render_process_id =
web_contents()->GetMainFrame()->GetProcess()->GetID();
// We need to clear renderer cache separately for our process because
// StoragePartitionHttpCacheDataRemover::ClearData() does not clear that.
web_cache::WebCacheManager::GetInstance()->ClearCacheForProcess(
render_process_id);
base::OnceClosure cache_removal_done_callback = base::BindOnce(
&WebViewGuest::ClearCodeCache, weak_ptr_factory_.GetWeakPtr(),
remove_since, removal_mask, std::move(callback));
// We cannot use |BrowsingDataRemover| here since it doesn't support
// non-default StoragePartition.
partition->GetNetworkContext()->ClearHttpCache(
remove_since, base::Time::Now(), nullptr /* ClearDataFilter */,
std::move(cache_removal_done_callback));
return true;
}
ClearDataInternal(remove_since, removal_mask, std::move(callback));
return true;
}
WebViewGuest::WebViewGuest(WebContents* owner_web_contents)
: GuestView<WebViewGuest>(owner_web_contents),
rules_registry_id_(RulesRegistryService::kInvalidRulesRegistryID),
find_helper_(this),
is_overriding_user_agent_(false),
allow_transparency_(false),
allow_nw_(false),
javascript_dialog_helper_(this),
allow_scaling_(false),
is_guest_fullscreen_(false),
is_embedder_fullscreen_(false),
last_fullscreen_permission_was_allowed_by_embedder_(false),
pending_zoom_factor_(0.0),
did_set_explicit_zoom_(false),
is_spatial_navigation_enabled_(
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableSpatialNavigation)) {
web_view_guest_delegate_.reset(
ExtensionsAPIClient::Get()->CreateWebViewGuestDelegate(this));
}
WebViewGuest::~WebViewGuest() {
}
void WebViewGuest::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (navigation_handle->IsErrorPage() || !navigation_handle->HasCommitted()) {
// Suppress loadabort for "mailto" URLs.
// Also during destruction, owner_web_contents() is null so there's no point
// trying to send the event.
if (!navigation_handle->GetURL().SchemeIs(url::kMailToScheme) &&
owner_web_contents()) {
// If a load is blocked, either by WebRequest or security checks, the
// navigation may or may not have committed. So if we don't see an error
// code, mark it as blocked.
int error_code = navigation_handle->GetNetErrorCode();
if (error_code == net::OK)
error_code = net::ERR_BLOCKED_BY_CLIENT;
LoadAbort(IsInWebViewMainFrame(navigation_handle),
navigation_handle->GetURL(), error_code);
}
// Originally, on failed navigations the webview we would fire a loadabort
// (for the failed navigation) and a loadcommit (for the error page).
if (!navigation_handle->IsErrorPage())
return;
}
if (IsInWebViewMainFrame(navigation_handle) && pending_zoom_factor_) {
// Handle a pending zoom if one exists.
SetZoom(pending_zoom_factor_);
pending_zoom_factor_ = 0.0;
}
auto args = std::make_unique<base::DictionaryValue>();
args->SetString(guest_view::kUrl, navigation_handle->GetURL().spec());
args->SetString(webview::kInternalVisibleUrl,
web_contents()->GetVisibleURL().spec());
args->SetBoolean(guest_view::kIsTopLevel,
IsInWebViewMainFrame(navigation_handle));
args->SetString(webview::kInternalBaseURLForDataURL,
web_contents()
->GetController()
.GetLastCommittedEntry()
->GetBaseURLForDataURL()
.spec());
args->SetInteger(webview::kInternalCurrentEntryIndex,
web_contents()->GetController().GetCurrentEntryIndex());
args->SetInteger(webview::kInternalEntryCount,
web_contents()->GetController().GetEntryCount());
args->SetInteger(webview::kInternalProcessId,
web_contents()->GetMainFrame()->GetProcess()->GetID());
DispatchEventToView(std::make_unique<GuestViewEvent>(
webview::kEventLoadCommit, std::move(args)));
find_helper_.CancelAllFindSessions();
}
void WebViewGuest::LoadProgressChanged(double progress) {
auto args = std::make_unique<base::DictionaryValue>();
args->SetString(guest_view::kUrl, web_contents()->GetURL().spec());
args->SetDoubleKey(webview::kProgress, progress);
DispatchEventToView(std::make_unique<GuestViewEvent>(
webview::kEventLoadProgress, std::move(args)));
}
void WebViewGuest::DocumentOnLoadCompletedInMainFrame(
content::RenderFrameHost* render_frame_host) {
auto args = std::make_unique<base::DictionaryValue>();
DispatchEventToView(std::make_unique<GuestViewEvent>(
webview::kEventContentLoad, std::move(args)));
}
void WebViewGuest::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
WebViewGuest* opener = GetOpener();
if (opener && IsInWebViewMainFrame(navigation_handle)) {
auto it = opener->pending_new_windows_.find(this);
if (it != opener->pending_new_windows_.end()) {
NewWindowInfo& info = it->second;
info.did_start_navigating_away_from_initial_url = true;
}
}
// loadStart shouldn't be sent for same document navigations.
if (navigation_handle->IsSameDocument())
return;
auto args = std::make_unique<base::DictionaryValue>();
args->SetString(guest_view::kUrl, navigation_handle->GetURL().spec());
args->SetBoolean(guest_view::kIsTopLevel,
IsInWebViewMainFrame(navigation_handle));
DispatchEventToView(std::make_unique<GuestViewEvent>(webview::kEventLoadStart,
std::move(args)));
}
void WebViewGuest::DidRedirectNavigation(
content::NavigationHandle* navigation_handle) {
auto args = std::make_unique<base::DictionaryValue>();
args->SetBoolean(guest_view::kIsTopLevel,
IsInWebViewMainFrame(navigation_handle));
args->SetString(webview::kNewURL, navigation_handle->GetURL().spec());
auto redirect_chain = navigation_handle->GetRedirectChain();
DCHECK_GE(redirect_chain.size(), 2u);
auto old_url = redirect_chain[redirect_chain.size() - 2];
args->SetString(webview::kOldURL, old_url.spec());
DispatchEventToView(std::make_unique<GuestViewEvent>(
webview::kEventLoadRedirect, std::move(args)));
}
void WebViewGuest::PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) {
// Cancel all find sessions in progress.
find_helper_.CancelAllFindSessions();
auto args = std::make_unique<base::DictionaryValue>();
args->SetInteger(webview::kProcessId,
web_contents()->GetMainFrame()->GetProcess()->GetID());
args->SetString(webview::kReason, TerminationStatusToString(status));
DispatchEventToView(
std::make_unique<GuestViewEvent>(webview::kEventExit, std::move(args)));
}
void WebViewGuest::UserAgentOverrideSet(
const blink::UserAgentOverride& ua_override) {
content::NavigationController& controller = web_contents()->GetController();
content::NavigationEntry* entry = controller.GetVisibleEntry();
if (!entry)
return;
entry->SetIsOverridingUserAgent(!ua_override.ua_string_override.empty());
web_contents()->GetController().Reload(content::ReloadType::NORMAL, false);
}
void WebViewGuest::FrameNameChanged(RenderFrameHost* render_frame_host,
const std::string& name) {
if (render_frame_host->GetParent())
return;
if (name_ == name)
return;
ReportFrameNameChange(name);
}
void WebViewGuest::OnAudioStateChanged(bool audible) {
auto args = std::make_unique<base::DictionaryValue>();
args->Set(webview::kAudible, std::make_unique<base::Value>(audible));
DispatchEventToView(std::make_unique<GuestViewEvent>(
webview::kEventAudioStateChanged, std::move(args)));
}
void WebViewGuest::OnDidAddMessageToConsole(
content::RenderFrameHost* source_frame,
blink::mojom::ConsoleMessageLevel log_level,
const std::u16string& message,
int32_t line_no,
const std::u16string& source_id,
const absl::optional<std::u16string>& untrusted_stack_trace) {
auto args = std::make_unique<base::DictionaryValue>();
// Log levels are from base/logging.h: LogSeverity.
args->SetInteger(webview::kLevel,
blink::ConsoleMessageLevelToLogSeverity(log_level));
args->SetString(webview::kMessage, message);
args->SetInteger(webview::kLine, line_no);
args->SetString(webview::kSourceId, source_id);
DispatchEventToView(std::make_unique<GuestViewEvent>(
webview::kEventConsoleMessage, std::move(args)));
}
void WebViewGuest::ReportFrameNameChange(const std::string& name) {
name_ = name;
auto args = std::make_unique<base::DictionaryValue>();
args->SetString(webview::kName, name);
DispatchEventToView(std::make_unique<GuestViewEvent>(
webview::kEventFrameNameChanged, std::move(args)));
}
void WebViewGuest::PushWebViewStateToIOThread() {
const GURL& site_url = web_contents()->GetSiteInstance()->GetSiteURL();
content::StoragePartitionConfig storage_partition_config =
content::StoragePartitionConfig::CreateDefault(browser_context());
if (!GetGuestPartitionConfigForSite(browser_context(), site_url,
&storage_partition_config)) {
NOTREACHED();
return;
}
WebViewRendererState::WebViewInfo web_view_info;
web_view_info.embedder_process_id =
owner_web_contents()->GetMainFrame()->GetProcess()->GetID();
web_view_info.instance_id = view_instance_id();
web_view_info.partition_id = storage_partition_config.partition_name();
web_view_info.owner_host = owner_host();
web_view_info.rules_registry_id = rules_registry_id_;
// Get content scripts IDs added by the guest.
WebViewContentScriptManager* manager =
WebViewContentScriptManager::Get(browser_context());
DCHECK(manager);
web_view_info.content_script_ids = manager->GetContentScriptIDSet(
web_view_info.embedder_process_id, web_view_info.instance_id);
WebViewRendererState::GetInstance()->AddGuest(
web_contents()
->GetMainFrame()
->GetRenderViewHost()
->GetProcess()
->GetID(),
web_contents()->GetMainFrame()->GetRenderViewHost()->GetRoutingID(),
web_view_info);
}
void WebViewGuest::RequestMediaAccessPermission(
WebContents* source,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) {
web_view_permission_helper_->RequestMediaAccessPermission(
source, request, std::move(callback));
}
bool WebViewGuest::CheckMediaAccessPermission(
content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type) {
return web_view_permission_helper_->CheckMediaAccessPermission(
render_frame_host, security_origin, type);
}
void WebViewGuest::CanDownload(const GURL& url,
const std::string& request_method,
base::OnceCallback<void(bool)> callback) {
web_view_permission_helper_->CanDownload(url, request_method,
std::move(callback));
}
void WebViewGuest::SignalWhenReady(base::OnceClosure callback) {
auto* manager = WebViewContentScriptManager::Get(browser_context());
manager->SignalOnScriptsUpdated(std::move(callback));
}
void WebViewGuest::WillAttachToEmbedder() {
rules_registry_id_ = GetOrGenerateRulesRegistryID(
owner_web_contents()->GetMainFrame()->GetProcess()->GetID(),
view_instance_id());
// We must install the mapping from guests to WebViews prior to resuming
// suspended resource loads so that the WebRequest API will catch resource
// requests.
PushWebViewStateToIOThread();
}
content::JavaScriptDialogManager* WebViewGuest::GetJavaScriptDialogManager(
WebContents* source) {
return &javascript_dialog_helper_;
}
void WebViewGuest::NavigateGuest(const std::string& src,
bool force_navigation) {
if (src.empty())
return;
GURL url = ResolveURL(src);
// We wait for all the content scripts to load and then navigate the guest
// if the navigation is embedder-initiated. For browser-initiated navigations,
// content scripts will be ready.
if (force_navigation) {
SignalWhenReady(
base::BindOnce(&WebViewGuest::LoadURLWithParams,
weak_ptr_factory_.GetWeakPtr(), url, content::Referrer(),
ui::PAGE_TRANSITION_AUTO_TOPLEVEL, force_navigation));
return;
}
LoadURLWithParams(url, content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL,
force_navigation);
}
bool WebViewGuest::HandleKeyboardShortcuts(
const content::NativeWebKeyboardEvent& event) {
// <webview> outside of Chrome Apps do not handle keyboard shortcuts.
if (!GuestViewManager::FromBrowserContext(browser_context())->
IsOwnedByExtension(this)) {
return false;
}
if (event.GetType() != blink::WebInputEvent::Type::kRawKeyDown)
return false;
// If the user hits the escape key without any modifiers then unlock the
// mouse if necessary.
if ((event.windows_key_code == ui::VKEY_ESCAPE) &&
!(event.GetModifiers() & blink::WebInputEvent::kInputModifiers)) {
return web_contents()->GotResponseToLockMouseRequest(
blink::mojom::PointerLockResult::kUserRejected);
}
#if defined(OS_MAC)
if (event.GetModifiers() != blink::WebInputEvent::kMetaKey)
return false;
if (event.windows_key_code == ui::VKEY_OEM_4) {
Go(-1);
return true;
}
if (event.windows_key_code == ui::VKEY_OEM_6) {
Go(1);
return true;
}
#else
if (event.windows_key_code == ui::VKEY_BROWSER_BACK) {
Go(-1);
return true;
}
if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) {
Go(1);
return true;
}
#endif
return false;
}
void WebViewGuest::ApplyAttributes(const base::DictionaryValue& params) {
std::string name;
if (params.GetString(webview::kAttributeName, &name)) {
// If the guest window's name is empty, then the WebView tag's name is
// assigned. Otherwise, the guest window's name takes precedence over the
// WebView tag's name.
if (name_.empty())
SetName(name);
}
if (attached())
ReportFrameNameChange(name_);
std::string user_agent_override;
params.GetString(webview::kParameterUserAgentOverride, &user_agent_override);
SetUserAgentOverride(user_agent_override);
absl::optional<bool> allow_transparency =
params.FindBoolKey(webview::kAttributeAllowTransparency);
if (allow_transparency) {
// We need to set the background opaque flag after navigation to ensure that
// there is a RenderWidgetHostView available.
SetAllowTransparency(*allow_transparency);
}
absl::optional<bool> allow_scaling =
params.FindBoolKey(webview::kAttributeAllowScaling);
if (allow_scaling)
SetAllowScaling(*allow_scaling);
bool allow_nw = false;
if (params.GetBoolean(webview::kAttributeAllowNW,
&allow_nw)) {
allow_nw_ = allow_nw;
}
// Check for a pending zoom from before the first navigation.
pending_zoom_factor_ = params.FindDoubleKey(webview::kInitialZoomFactor)
.value_or(pending_zoom_factor_);
bool is_pending_new_window = false;
WebViewGuest* opener = GetOpener();
if (opener) {
// We need to do a navigation here if the target URL has changed between
// the time the WebContents was created and the time it was attached.
// We also need to do an initial navigation if a RenderView was never
// created for the new window in cases where there is no referrer.
auto it = opener->pending_new_windows_.find(this);
if (it != opener->pending_new_windows_.end()) {
const NewWindowInfo& new_window_info = it->second;
if (!new_window_info.did_start_navigating_away_from_initial_url &&
(new_window_info.url_changed_via_open_url ||
!web_contents()->HasOpener())) {
NavigateGuest(new_window_info.url.spec(), false /* force_navigation */);
}
// Once a new guest is attached to the DOM of the embedder page, then the
// lifetime of the new guest is no longer managed by the opener guest.
opener->pending_new_windows_.erase(this);
is_pending_new_window = true;
}
}
// Only read the src attribute if this is not a New Window API flow.
if (!is_pending_new_window) {
std::string src;
if (params.GetString(webview::kAttributeSrc, &src))
NavigateGuest(src, true /* force_navigation */);
}
}
void WebViewGuest::ShowContextMenu(int request_id) {
if (web_view_guest_delegate_)
web_view_guest_delegate_->OnShowContextMenu(request_id);
}
void WebViewGuest::SetName(const std::string& name) {
if (name_ == name)
return;
name_ = name;
// Return early if this method is called before RenderFrameCreated().
// In that case, we still have a chance to update the name at GuestReady().
if (!web_contents()->GetMainFrame()->IsRenderFrameLive())
return;
ExtensionWebContentsObserver::GetForWebContents(web_contents())
->GetLocalFrame(web_contents()->GetMainFrame())
->SetFrameName(name_);
}
void WebViewGuest::SetSpatialNavigationEnabled(bool enabled) {
if (is_spatial_navigation_enabled_ == enabled)
return;
is_spatial_navigation_enabled_ = enabled;
ExtensionWebContentsObserver::GetForWebContents(web_contents())
->GetLocalFrame(web_contents()->GetMainFrame())
->SetSpatialNavigationEnabled(enabled);
}
bool WebViewGuest::IsSpatialNavigationEnabled() const {
return is_spatial_navigation_enabled_;
}
void WebViewGuest::SetZoom(double zoom_factor) {
did_set_explicit_zoom_ = true;
auto* zoom_controller = ZoomController::FromWebContents(web_contents());
DCHECK(zoom_controller);
double zoom_level = blink::PageZoomFactorToZoomLevel(zoom_factor);
zoom_controller->SetZoomLevel(zoom_level);
}
void WebViewGuest::SetZoomMode(ZoomController::ZoomMode zoom_mode) {
ZoomController::FromWebContents(web_contents())->SetZoomMode(zoom_mode);
}
void WebViewGuest::SetAllowTransparency(bool allow) {
if (allow_transparency_ == allow)
return;
allow_transparency_ = allow;
if (!web_contents()
->GetMainFrame()
->GetRenderViewHost()
->GetWidget()
->GetView())
return;
SetTransparency();
}
void WebViewGuest::SetTransparency() {
auto* view = web_contents()
->GetMainFrame()
->GetRenderViewHost()
->GetWidget()
->GetView();
if (allow_transparency_)
view->SetBackgroundColor(SK_ColorTRANSPARENT);
else
view->SetBackgroundColor(SK_ColorWHITE);
}
void WebViewGuest::SetAllowScaling(bool allow) {
allow_scaling_ = allow;
}
bool WebViewGuest::LoadDataWithBaseURL(const GURL& data_url,
const GURL& base_url,
const GURL& virtual_url,
std::string* error) {
// Check that the provided URLs are valid.
// |data_url| must be a valid data URL.
if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme)) {
base::SStringPrintf(error, webview::kAPILoadDataInvalidDataURL,
data_url.possibly_invalid_spec().c_str());
return false;
}
const url::Origin& owner_origin =
owner_web_contents()->GetMainFrame()->GetLastCommittedOrigin();
bool owner_is_nwjs =
content::GetContentClient()->browser()->IsNWOrigin(owner_origin, browser_context());
const bool base_in_owner_origin =
owner_origin.IsSameOriginWith(url::Origin::Create(base_url));
// |base_url| must be a valid URL. It is also limited to URLs that the owner
// is trusted to have control over.
if (!base_url.is_valid() ||
(!base_url.SchemeIsHTTPOrHTTPS() && !base_in_owner_origin &&
!owner_is_nwjs)) {
base::SStringPrintf(error, webview::kAPILoadDataInvalidBaseURL,
base_url.possibly_invalid_spec().c_str());
return false;
}
// |virtual_url| must be a valid URL.
if (!virtual_url.is_valid()) {
base::SStringPrintf(error, webview::kAPILoadDataInvalidVirtualURL,
virtual_url.possibly_invalid_spec().c_str());
return false;
}
// Set up the parameters to load |data_url| with the specified |base_url|.
content::NavigationController::LoadURLParams load_params(data_url);
load_params.load_type = content::NavigationController::LOAD_TYPE_DATA;
load_params.base_url_for_data_url = base_url;
load_params.virtual_url_for_data_url = virtual_url;
load_params.override_user_agent =
content::NavigationController::UA_OVERRIDE_INHERIT;
// Navigate to the data URL.
web_contents()->GetController().LoadURLWithParams(load_params);
return true;
}
void WebViewGuest::AddNewContents(WebContents* source,
std::unique_ptr<WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const gfx::Rect& initial_rect,
bool user_gesture,
bool* was_blocked) {
// TODO(erikchen): Fix ownership semantics for WebContents inside this class.
// https://crbug.com/832879.
if (was_blocked)
*was_blocked = false;
RequestNewWindowPermission(disposition, initial_rect, new_contents.release());
}
WebContents* WebViewGuest::OpenURLFromTab(
WebContents* source,
const content::OpenURLParams& params) {
// Most navigations should be handled by WebViewGuest::LoadURLWithParams,
// which takes care of blocking chrome:// URLs and other web-unsafe schemes.
// (NavigateGuest and CreateNewGuestWebViewWindow also go through
// LoadURLWithParams.)
//
// We make an exception here for context menu items, since the Language
// Settings item uses a browser-initiated navigation to a chrome:// URL.
// These can be passed to the embedder's WebContentsDelegate so that the
// browser performs the action for the <webview>. Navigations to a new
// tab, etc., are also handled by the WebContentsDelegate.
if (!params.is_renderer_initiated &&
(!content::ChildProcessSecurityPolicy::GetInstance()->IsWebSafeScheme(
params.url.scheme()) ||
params.disposition != WindowOpenDisposition::CURRENT_TAB)) {
if (!owner_web_contents()->GetDelegate())
return nullptr;
return owner_web_contents()->GetDelegate()->OpenURLFromTab(
owner_web_contents(), params);
}
if (!attached()) {
WebViewGuest* opener = GetOpener();
// If the guest wishes to navigate away prior to attachment then we save the
// navigation to perform upon attachment. Navigation initializes a lot of
// state that assumes an embedder exists, such as RenderWidgetHostViewGuest.
// Navigation also resumes resource loading. If we were created using
// newwindow (i.e. we have an opener), we don't allow navigation until
// attachment.
if (opener) {
auto it = opener->pending_new_windows_.find(this);
if (it == opener->pending_new_windows_.end())
return nullptr;
const NewWindowInfo& info = it->second;
NewWindowInfo new_window_info(params.url, info.name);
new_window_info.url_changed_via_open_url =
new_window_info.url != info.url;
it->second = new_window_info;
return nullptr;
}
}
// This code path is taken if RenderFrameImpl::DecidePolicyForNavigation
// decides that a fork should happen. At the time of writing this comment,
// the only way a well behaving guest could hit this code path is if it
// navigates to the New Tab page URL of the default search engine (see
// search::GetNewTabPageURL). Validity checks are performed inside
// LoadURLWithParams such that if the guest attempts to navigate to a URL that
// it is not allowed to navigate to, a 'loadabort' event will fire in the
// embedder, and the guest will be navigated to about:blank.
if (params.disposition == WindowOpenDisposition::CURRENT_TAB) {
LoadURLWithParams(params.url, params.referrer, params.transition,
true /* force_navigation */);
return web_contents();
}
// This code path is taken if Ctrl+Click, middle click or any of the
// keyboard/mouse combinations are used to open a link in a new tab/window.
// This code path is also taken on client-side redirects from about:blank.
CreateNewGuestWebViewWindow(params);
return nullptr;
}
void WebViewGuest::WebContentsCreated(WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const std::string& frame_name,
const GURL& target_url,
WebContents* new_contents,
const std::u16string& nw_window_manifest) {
auto* guest = WebViewGuest::FromWebContents(new_contents);
CHECK(guest);
guest->SetOpener(this);
guest->name_ = frame_name;
pending_new_windows_.insert(
std::make_pair(guest, NewWindowInfo(target_url, frame_name)));
}
void WebViewGuest::EnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) {
// Ask the embedder for permission.
base::DictionaryValue request_info;
const GURL& origin =
requesting_frame->GetLastCommittedURL().DeprecatedGetOriginAsURL();
request_info.SetString(webview::kOrigin, origin.spec());
web_view_permission_helper_->RequestPermission(
WEB_VIEW_PERMISSION_TYPE_FULLSCREEN, request_info,
base::BindOnce(&WebViewGuest::OnFullscreenPermissionDecided,
weak_ptr_factory_.GetWeakPtr()),
false /* allowed_by_default */);
// TODO(lazyboy): Right now the guest immediately goes fullscreen within its
// bounds. If the embedder denies the permission then we will see a flicker.
// Once we have the ability to "cancel" a renderer/ fullscreen request:
// http://crbug.com/466854 this won't be necessary and we should be
// Calling SetFullscreenState(true) once the embedder allowed the request.
// Otherwise we would cancel renderer/ fullscreen if the embedder denied.
SetFullscreenState(true);
}
void WebViewGuest::ExitFullscreenModeForTab(WebContents* web_contents) {
SetFullscreenState(false);
}
bool WebViewGuest::IsFullscreenForTabOrPending(
const WebContents* web_contents) {
return is_guest_fullscreen_;
}
void WebViewGuest::RequestToLockMouse(WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) {
web_view_permission_helper_->RequestPointerLockPermission(
user_gesture, last_unlocked_by_target,
base::BindOnce(
base::IgnoreResult(&WebContents::GotLockMousePermissionResponse),
base::Unretained(web_contents)));
}
bool WebViewGuest::CanLoadFileSubresource(const GURL& url) {
GURL test_file_url("file:///");
const Extension* extension =
ExtensionRegistry::Get(browser_context())->enabled_extensions().GetByID(owner_host());
if (extension && WebviewInfo::IsURLWebviewAccessible(extension,
GetPartitionID(web_contents()->GetRenderViewHost()->GetProcess()),
test_file_url))
return true;
return false;
}
void WebViewGuest::LoadURLWithParams(
const GURL& url,
const content::Referrer& referrer,
ui::PageTransition transition_type,
bool force_navigation) {
if (!url.is_valid()) {
LoadAbort(true /* is_top_level */, url, net::ERR_INVALID_URL);
NavigateGuest(url::kAboutBlankURL, false /* force_navigation */);
return;
}
bool scheme_is_blocked =
(!content::ChildProcessSecurityPolicy::GetInstance()->IsWebSafeScheme(
url.scheme()) &&
!url.SchemeIs(url::kAboutScheme)) ||
url.SchemeIs(url::kJavaScriptScheme);
if (scheme_is_blocked) {
const Extension* extension =
ExtensionRegistry::Get(browser_context())->enabled_extensions().GetByID(owner_host());
if (extension && WebviewInfo::IsURLWebviewAccessible(extension,
GetPartitionID(web_contents()->GetRenderViewHost()->GetProcess()),
url)) {
scheme_is_blocked = false;
}
}
// Do not allow navigating a guest to schemes other than known safe schemes.
// This will block the embedder trying to load unwanted schemes, e.g.
// chrome://.
if (scheme_is_blocked) {
LoadAbort(true /* is_top_level */, url, net::ERR_DISALLOWED_URL_SCHEME);
NavigateGuest(url::kAboutBlankURL, false /* force_navigation */);
return;
}
if (!force_navigation) {
content::NavigationEntry* last_committed_entry =
web_contents()->GetController().GetLastCommittedEntry();
if (last_committed_entry && last_committed_entry->GetURL() == url) {
return;
}
}
GURL validated_url(url);
web_contents()->GetMainFrame()->GetProcess()->FilterURL(false,
&validated_url);
// As guests do not swap processes on navigation, only navigations to
// normal web URLs are supported. No protocol handlers are installed for
// other schemes (e.g., WebUI or extensions), and no permissions or bindings
// can be granted to the guest process.
content::NavigationController::LoadURLParams load_url_params(validated_url);
load_url_params.referrer = referrer;
load_url_params.transition_type = transition_type;
load_url_params.extra_headers = std::string();
if (is_overriding_user_agent_) {
load_url_params.override_user_agent =
content::NavigationController::UA_OVERRIDE_TRUE;
}
nw::SetInWebViewApplyAttr(true, allow_nw_);
web_contents()->GetController().LoadURLWithParams(load_url_params);
nw::SetInWebViewApplyAttr(false, allow_nw_);
}
void WebViewGuest::RequestNewWindowPermission(WindowOpenDisposition disposition,
const gfx::Rect& initial_bounds,
WebContents* new_contents) {
auto* guest = WebViewGuest::FromWebContents(new_contents);
if (!guest)
return;
auto it = pending_new_windows_.find(guest);
if (it == pending_new_windows_.end())
return;
const NewWindowInfo& new_window_info = it->second;
// Retrieve the opener partition info if we have it.
const GURL& site_url = new_contents->GetSiteInstance()->GetSiteURL();
std::string storage_partition_id = GetStoragePartitionIdFromSiteURL(site_url);
base::DictionaryValue request_info;
request_info.SetInteger(webview::kInitialHeight, initial_bounds.height());
request_info.SetInteger(webview::kInitialWidth, initial_bounds.width());
request_info.SetString(webview::kTargetURL, new_window_info.url.spec());
request_info.SetString(webview::kName, new_window_info.name);
request_info.SetInteger(webview::kWindowID, guest->guest_instance_id());
// We pass in partition info so that window-s created through newwindow
// API can use it to set their partition attribute.
request_info.SetString(webview::kStoragePartitionId, storage_partition_id);
request_info.SetString(webview::kWindowOpenDisposition,
WindowOpenDispositionToString(disposition));
web_view_permission_helper_->RequestPermission(
WEB_VIEW_PERMISSION_TYPE_NEW_WINDOW, request_info,
base::BindOnce(&WebViewGuest::OnWebViewNewWindowResponse,
weak_ptr_factory_.GetWeakPtr(),
guest->guest_instance_id()),
false /* allowed_by_default */);
}
GURL WebViewGuest::ResolveURL(const std::string& src) {
if (!GuestViewManager::FromBrowserContext(browser_context())->
IsOwnedByExtension(this)) {
return GURL(src);
}
GURL default_url(base::StringPrintf("%s://%s/",
kExtensionScheme,
owner_host().c_str()));
return default_url.Resolve(src);
}
void WebViewGuest::OnWebViewNewWindowResponse(
int new_window_instance_id,
bool allow,
const std::string& user_input) {
auto* guest = WebViewGuest::From(
owner_web_contents()->GetMainFrame()->GetProcess()->GetID(),
new_window_instance_id);
if (!guest)
return;
if (!allow)
guest->Destroy(true);
}
void WebViewGuest::OnFullscreenPermissionDecided(
bool allowed,
const std::string& user_input) {
last_fullscreen_permission_was_allowed_by_embedder_ = allowed;
SetFullscreenState(allowed);
}
void WebViewGuest::ShowDevTools(bool show, int proc_id, int guest_id) {
if (proc_id > 0 && guest_id >= 0) {
auto* that =
WebViewGuest::From(owner_web_contents()->GetRenderViewHost()->GetProcess()->GetID(),
guest_id);
nw::ShowDevtools(show, web_contents(), that->web_contents());
return;
}
nw::ShowDevtools(show, web_contents());
}
void WebViewGuest::InspectElement(int x, int y) {
nw::InspectElement(web_contents(), x, y);
}
bool WebViewGuest::GuestMadeEmbedderFullscreen() const {
return last_fullscreen_permission_was_allowed_by_embedder_ &&
is_embedder_fullscreen_;
}
void WebViewGuest::SetFullscreenState(bool is_fullscreen) {
if (is_fullscreen == is_guest_fullscreen_)
return;
bool was_fullscreen = is_guest_fullscreen_;
is_guest_fullscreen_ = is_fullscreen;
// If the embedder entered fullscreen because of us, it should exit fullscreen
// when we exit fullscreen.
if (was_fullscreen && GuestMadeEmbedderFullscreen()) {
// Dispatch a message so we can call document.webkitCancelFullscreen()
// on the embedder.
auto args = std::make_unique<base::DictionaryValue>();
DispatchEventToView(std::make_unique<GuestViewEvent>(
webview::kEventExitFullscreen, std::move(args)));
}
// Since we changed fullscreen state, sending a SynchronizeVisualProperties
// message ensures that renderer/ sees the change.
web_contents()
->GetMainFrame()
->GetRenderViewHost()
->GetWidget()
->SynchronizeVisualProperties();
}
} // namespace extensions
|
nwjs/chromium.src
|
extensions/browser/guest_view/web_view/web_view_guest.cc
|
C++
|
bsd-3-clause
| 68,606 |
/*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
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 the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "GuiCommandHandler.h"
#ifndef UNDER_CE
# include <sys/stat.h>
# include <dirent.h>
#endif
#include "MsgBufferEnums.h"
#include "Module.h"
#include "Buffer.h"
#include "nav2util.h"
#include "CtrlHub.h"
#include "isabTime.h"
#include "Quality.h"
#include "PositionState.h"
#include "RouteEnums.h"
#include "NavTask.h"
#include "NavPacket.h"
#include "MapEnums.h"
#include "NavServerComEnums.h"
#include "GuiProt/ServerEnums.h"
#include "NavServerCom.h"
#include "ParameterEnums.h"
#include "Parameter.h"
#include "../NavTask/Point.h"
#include "../NavTask/Route.h"
#include "Gps.h"
#include "NavTaskInternal.h"
# define DBG m_navTask->m_log->debug
# define INFO m_navTask->m_log->info
# define WARN m_navTask->m_log->warning
# define ERR m_navTask->m_log->error
using namespace isab;
GuiCommandHandler::GuiCommandHandler(class NavTask* nt)
{
m_navTask = nt;
}
GuiCommandHandler::~GuiCommandHandler()
{
}
void GuiCommandHandler::HandleOperationSelect(class GuiFileOperationSelect* /*op*/)
{
}
void GuiCommandHandler::HandleOperationSelectReply(
class GuiFileOperationSelectReply* op, uint32 src)
{
const uint16 opCommand = op->command();
switch(opCommand)
{
case command_select_load:
{
const class FileLocation *FileLoc = op->location();
char* sLoadFile = NULL;
if (FileLoc) {
sLoadFile = createFullPathName_new(FileLoc->m_dir, FileLoc->m_name);
}
//Save selected index to parameter file.
int32 selectedIndex = op->selected();
m_navTask->m_parameter->setParam(ParameterEnums::R_lastIndex, &selectedIndex);
int retval = m_navTask->m_receiveRoute->readRoute(sLoadFile);
if (retval == 0) {
m_navTask->m_awaitingRouteReply = true;
m_navTask->switchToNewRoute();
}
else {
DBG("Could not load route.");
}
if (sLoadFile) {
delete[] sLoadFile;
}
}
break;
case command_select_simulate:
{
const class FileLocation *FileLoc = op->location();
char* sLoadFile = NULL;
if (FileLoc) {
sLoadFile = createFullPathName_new(FileLoc->m_dir, FileLoc->m_name);
}
int retval = m_navTask->m_receiveRoute->readRoute(sLoadFile);
if (retval == 0) {
m_navTask->m_awaitingRouteReply = true;
m_navTask->switchToNewRoute();
m_navTask->setupGpsSimulation(src);
}
else {
DBG("Could not load route.");
}
if (sLoadFile) {
delete[] sLoadFile;
}
}
break;
case command_select_save:
{
const class FileLocation *FileLoc = op->location();
char* sSaveFile = NULL;
char* paramFileName = NULL;
if (FileLoc) {
sSaveFile = createFullPathName_new(FileLoc->m_dir, op->fileName());
//Save filename to paramfile as default filename.
paramFileName = addFileExtension_new(op->fileName());
m_navTask->m_parameter->setParam(ParameterEnums::R_routeName, ¶mFileName);
}
//Check if file already exists.
FILE* pSaveFile = fopen(sSaveFile, "r");
if (pSaveFile != NULL) {
fclose(pSaveFile);
char* sFileName = addFileExtension_new(op->fileName());
class FileLocation *FileLocTmp =
new FileLocation(sFileName,
strdup_new(FileLoc->m_dir),
strdup_new(FileLoc->m_dirname),
file_type_plain_file);
char* sAdditional = strdup_new(sFileName);
class GuiFileOperationConfirm *opConfirm =
new GuiFileOperationConfirm(0, command_confirm_overwrite,
FileLocTmp, sAdditional);
m_navTask->m_navTaskConsumer->sendFileOperation(opConfirm,
m_navTask->m_fileOperationRequester);
}
else {
int retval = m_navTask->m_route->writeRoute(sSaveFile);
if (retval == 0) {
DBG("Saved route to stable media");
}
else {
DBG("Could not save route.");
}
}
if (sSaveFile) {
delete[] sSaveFile;
}
if (paramFileName) {
delete[] paramFileName;
}
}
break;
case command_select_delete:
{
//If file exists send confirm operation.
const class FileLocation *FileLoc = op->location();
char* sDeleteFile = NULL;
if (FileLoc) {
sDeleteFile = createFullPathName_new(FileLoc->m_dir, op->fileName());
}
//Check if file exists.
FILE* pDeleteFile = fopen(sDeleteFile, "r");
if (pDeleteFile != NULL) {
fclose(pDeleteFile);
char* sFileName = addFileExtension_new(op->fileName());
class FileLocation *FileLocTmp =
new FileLocation(sFileName,
strdup_new(FileLoc->m_dir),
strdup_new(FileLoc->m_dirname),
file_type_plain_file);
char* sAdditional = strdup_new(sFileName);
class GuiFileOperationConfirm *opConfirm =
new GuiFileOperationConfirm(0, command_confirm_delete,
FileLocTmp, sAdditional);
m_navTask->m_navTaskConsumer->sendFileOperation(opConfirm,
m_navTask->m_fileOperationRequester);
}
else {
DBG("GuiCommand: Delete - This should never happen.");
}
if (sDeleteFile) {
delete[] sDeleteFile;
}
}
break;
case command_cancel:
{
//Do nothing!
}
break;
}
}
void GuiCommandHandler::HandleOperationConfirm(class GuiFileOperationConfirm* /*op*/)
{
}
void GuiCommandHandler::HandleOperationConfirmReply(class GuiFileOperationConfirmReply* op)
{
const uint16 opCommand = op->command();
switch(opCommand){
case command_confirm_overwrite:
{
const class FileLocation *FileLoc = op->location();
char* sSaveFile = NULL;
if (FileLoc) {
sSaveFile = createFullPathName_new(FileLoc->m_dir, FileLoc->m_name);
}
int retval = m_navTask->m_route->writeRoute(sSaveFile);
if (retval == 0) {
DBG("Saved route to stable media");
}
else {
DBG("Could not save route.");
}
if (sSaveFile) {
delete[] sSaveFile;
}
}
break;
case command_confirm_delete:
{
//Do the real file deleting here.
const class FileLocation *FileLoc = op->location();
char* sDeleteFile = NULL;
if (FileLoc) {
sDeleteFile = createFullPathName_new(FileLoc->m_dir, FileLoc->m_name);
int retval = m_navTask->m_route->deleteRoute(sDeleteFile);
if (retval == 0) {
DBG("Deleted route from stable media");
} else {
DBG("Could not delete route. errcode %d", retval);
}
delete[] sDeleteFile;
}
}
break;
case command_cancel:
//Do nothing!
DBG("command_cancel redId: %"PRIx16, op->seqId());
break;
case command_confirm_no:
//Do nothing!
DBG("command_confirm_no redId: %"PRIx16, op->seqId());
break;
}
}
void GuiCommandHandler::HandleOperationCommand(
class GuiFileOperationCommand* op, uint32 src)
{
const uint16 opCommand = op->command();
switch(opCommand)
{
case command_load:
{
LocationVector *locations = new LocationVector;
locations->reserve(4);
LocationVector *driveList = new LocationVector;
driveList->reserve(2);
getDriveList(driveList);
findSavedRoutes(locations, driveList);
char* sFileName = NULL;
if (locations->size() > 0) {
class FileLocation *FileLocTmp = *locations->begin();
sFileName = strdup_new(FileLocTmp->m_name);
}
//Last used index read from parameter file.
int32 lastIndex = m_navTask->getRouteLastUsedIndex();
class GuiFileOperationSelect *opSelect =
new GuiFileOperationSelect(0, lastIndex, command_select_load, sFileName, locations);
m_navTask->m_navTaskConsumer->sendFileOperation(opSelect,
m_navTask->m_fileOperationRequester);
if (driveList) {
LocationVector::iterator it = driveList->begin();
while (it != driveList->end()) {
delete (*it);
it++;
}
driveList->clear();
}
delete driveList;
}
break;
case command_load_and_simulate:
{
LocationVector *locations = new LocationVector;
locations->reserve(4);
LocationVector *driveList = new LocationVector;
driveList->reserve(2);
getDriveList(driveList);
findSavedRoutes(locations, driveList);
char* sFileName = NULL;
if (locations->size() > 0) {
class FileLocation *FileLocTmp = *locations->begin();
sFileName = strdup_new(FileLocTmp->m_name);
}
//Last used index read from parameter file.
int32 lastIndex = m_navTask->getRouteLastUsedIndex();
class GuiFileOperationSelect *opSelect =
new GuiFileOperationSelect(0, lastIndex, command_select_simulate, sFileName, locations);
m_navTask->m_navTaskConsumer->sendFileOperation(opSelect,
m_navTask->m_fileOperationRequester);
if (driveList) {
LocationVector::iterator it = driveList->begin();
while (it != driveList->end()) {
delete (*it);
it++;
}
driveList->clear();
}
delete driveList;
}
break;
case command_save:
{
LocationVector *locations = new LocationVector;
locations->reserve(2);
getDriveList(locations);
char* sFileName = NULL;
//sFileName read from parameter file.
sFileName = strdup_new(m_navTask->getRouteFileName());
class GuiFileOperationSelect *opSelect =
new GuiFileOperationSelect(0, 0, command_select_save, sFileName, locations);
m_navTask->m_navTaskConsumer->sendFileOperation(opSelect,
m_navTask->m_fileOperationRequester);
}
break;
case command_delete:
{
//Show list of file to delete from stable media.
LocationVector *locations = new LocationVector;
locations->reserve(4);
LocationVector *driveList = new LocationVector;
driveList->reserve(2);
getDriveList(driveList);
findSavedRoutes(locations, driveList);
char* sFileName = NULL;
if (locations->size() > 0) {
class FileLocation *FileLocTmp = *locations->begin();
sFileName = strdup_new(FileLocTmp->m_name);
}
class GuiFileOperationSelect *opSelect =
new GuiFileOperationSelect(0, 0, command_select_delete, sFileName, locations);
m_navTask->m_navTaskConsumer->sendFileOperation(opSelect,
m_navTask->m_fileOperationRequester);
if (driveList) {
LocationVector::iterator it = driveList->begin();
while (it != driveList->end()) {
delete (*it);
it++;
}
driveList->clear();
}
delete driveList;
}
break;
case command_delete_all:
{
//Delete all routes from stable media.
}
break;
case command_simulate_start:
{
m_navTask->setupGpsSimulation(src);
}
break;
case command_simulate_stop:
{
m_navTask->setSimStop(src);
}
break;
case command_simulate_pause:
{
m_navTask->setSimPaused(src);
}
break;
case command_simulate_resume:
{
m_navTask->resumeSimPaused(src);
}
break;
case command_simulate_inc_speed:
{
m_navTask->incSimSpeed(src);
}
break;
case command_simulate_dec_speed:
{
m_navTask->decSimSpeed(src);
}
break;
case command_simulate_rep_on:
{
m_navTask->setSimRepeat(src);
}
break;
case command_simulate_rep_off:
{
m_navTask->stopSimRepeat(src);
}
break;
}
}
void GuiCommandHandler::findSavedRoutes(LocationVector* locations,
LocationVector* driveList)
{
#ifndef UNDER_CE
//iterate over drivelists
LocationVector::iterator it = driveList->begin();
while (it != driveList->end()) {
FileLocation* fileloc = *it;
char sFullPath[256];
//open dir in drivelist iterator
DIR *pDir = opendir(fileloc->m_dir);
struct dirent *pDirentStruct;
struct stat st;
if (pDir != NULL) {
while((pDirentStruct = readdir(pDir))) {
//skip if find . and ..
if ((strcmp(pDirentStruct->d_name, ".") == 0 ||
strcmp(pDirentStruct->d_name, "..") == 0)) {
continue;
}
//only get the route files (.rut)
if (strstr(pDirentStruct->d_name, ".rut")) {
char* sCurrentFile = strdup_new(pDirentStruct->d_name);
char* sSaveDir = strdup_new(fileloc->m_dir);
char* sSaveDirName = strdup_new(fileloc->m_dirname);
strcpy(sFullPath, "");
strcat(sFullPath, sSaveDir);
strcat(sFullPath, sCurrentFile);
int statret = stat(sFullPath, &st);
if (statret != -1 && S_ISDIR(st.st_mode)) {
//This is a directory not a route file.
delete[] sCurrentFile;
delete[] sSaveDir;
} else {
class FileLocation *FileLoc =
new FileLocation(sCurrentFile, sSaveDir,
sSaveDirName, file_type_plain_file);
locations->push_back(FileLoc);
}
}
}
closedir(pDir);
}
it++;
}
#else
WIN32_FIND_DATA wfd,wffd;
WCHAR* sFullMask = new WCHAR[MAX_PATH];
LocationVector::iterator it = driveList->begin();
while (it != driveList->end()) {
FileLocation* fileloc = *it;
// convert the UTF8 text to Unicode
MultiByteToWideChar(CP_ACP,
0,
fileloc->m_dir,
-1,
sFullMask,
MAX_PATH);
BOOL bRootDir = FALSE;
//check if we have root directory
if (!wcscmp(sFullMask,L"\\")){
bRootDir = TRUE;
} else if (sFullMask[wcslen(sFullMask) - 1] == L'\\') {
//remove slash at the end of the path, if it exists
sFullMask[wcslen(sFullMask) - 1] = L'\0';
}
HANDLE hDir = FindFirstFile(sFullMask,&wfd);
if (hDir != INVALID_HANDLE_VALUE &&
(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
if(bRootDir){
wcscat(sFullMask,L"*.rut");
} else {
wcscat(sFullMask,L"\\*.rut");
}
HANDLE hFind = FindFirstFile(sFullMask,&wffd);
if (hFind != INVALID_HANDLE_VALUE) {
do {
if (!(wffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
//determine size of buffer needed for UTF-8 string
int nLength = WideCharToMultiByte(CP_ACP, 0, wffd.cFileName,
-1, NULL, 0, NULL, NULL);
char* sCurrentFile= new char[nLength];
/* convert the Unicode text to UTF-8 */
WideCharToMultiByte(CP_ACP,
0,
wffd.cFileName,
-1,
sCurrentFile,
nLength,
NULL,
NULL);
char* sSaveDir = strdup_new(fileloc->m_dir);
char* sSaveDirName = strdup_new(fileloc->m_dirname);
class FileLocation *FileLoc =
new FileLocation(sCurrentFile,
sSaveDir,
sSaveDirName,
file_type_plain_file);
locations->push_back(FileLoc);
}
} while (FindNextFile(hFind, &wffd));
}
FindClose(hFind);
}
FindClose(hDir);
it++;
}
delete[] sFullMask;
#endif
}
char* GuiCommandHandler::createFullPathName_new(const char* sDir, const char* sName)
{
if (sDir && sName) {
char* sFullPath = new char[strlen(sDir) + strlen(sName) + 5];
strcpy(sFullPath, sDir);
strcat(sFullPath, sName);
if (! strstr(sName, ".rut")) {
strcat(sFullPath, ".rut");
}
return sFullPath;
} else {
return NULL;
}
}
char* GuiCommandHandler::addFileExtension_new(const char* sFileName)
{
if (sFileName) {
char* sFullName = new char[strlen(sFileName) + 5];
strcpy(sFullName, sFileName);
if (! strstr(sFileName, ".rut")) {
strcat(sFullName, ".rut");
}
return sFullName;
} else {
return NULL;
}
}
|
wayfinder/Wayfinder-CppCore-v2
|
cpp/Modules/NavTask/GuiCommandHandler.cpp
|
C++
|
bsd-3-clause
| 20,586 |
.pg_form_login input[type="text"] {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.pg_form_login input[type="password"] {
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.pg_form_login button{
padding: 10px;
font-family: 'Roboto', sans-serif;
font-weight: 300;
text-transform: uppercase;
}
.pg_form_login .not_register{
margin-top: 25px;
padding-top: 25px;
border-top: solid 1px #cccccc;
}
|
andrearruda/atitudes-positivas
|
public/assets/css/pg_form_login.css
|
CSS
|
bsd-3-clause
| 512 |
<?php
namespace backend\models;
use yii\mongodb\ActiveRecord;
class Customer extends ActiveRecord
{
public static function collectionName()
{
return 'customer';
}
public function saveInfo()
{
$customer = new Customer ();
$customer->name = '111';
$customer->email = '222';
$customer->insert ();
return $customer;
}
public function attributes()
{
return [
'_id',
'name',
'email',
'address',
'status'
];
}
}
|
Akishimo/imi-aug
|
backend/models/Customer.php
|
PHP
|
bsd-3-clause
| 546 |
add_library(iface INTERFACE)
target_sources(iface INTERFACE empty_1.cpp)
add_executable(main main.cpp)
target_link_libraries(main iface)
|
hlzz/dotfiles
|
dev/cmake-3.5.1/Tests/RunCMake/TargetSources/RelativePathInInterface.cmake
|
CMake
|
bsd-3-clause
| 139 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tf.gpx.edit.values;
import javafx.event.ActionEvent;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.StrokeLineCap;
import javafx.stage.Modality;
import javafx.stage.WindowEvent;
import jfxtras.styles.jmetro.JMetro;
import jfxtras.styles.jmetro.Style;
import tf.gpx.edit.extension.GarminColor;
import tf.gpx.edit.extension.LineStyle;
import tf.gpx.edit.main.GPXEditor;
import tf.helper.javafx.AbstractStage;
import tf.helper.javafx.ColorSelection;
/**
* Editor for line style attributes incl. preview of settings:
* color, width, opacity, linecap
*
* @author thomas
*/
public class EditLineStyle extends AbstractStage {
// this is a singleton for everyones use
// http://www.javaworld.com/article/2073352/core-java/simply-singleton.html
private final static EditLineStyle INSTANCE = new EditLineStyle();
private LineStyle myLineStyle;
private GPXEditor myGPXEditor;
// UI elements used in various methods need to be class-wide
private final ComboBox<Line> myColorList = ColorSelection.getInstance().createColorSelectionComboBox(GarminColor.getGarminColorsAsJavaFXColors());
private final Slider myWidthSlider = new Slider(0, 10, 0);
private final Slider myOpacitySlider = new Slider(0, 1, 0);
private final ComboBox<String> myCapList = new ComboBox<>();
private final Line myDemoLine = new Line();
private EditLineStyle() {
super();
initViewer();
}
public static EditLineStyle getInstance() {
return INSTANCE;
}
private void initViewer() {
(new JMetro(Style.LIGHT)).setScene(getScene());
getScene().getStylesheets().add(EditLineStyle.class.getResource("/GPXEditor.min.css").toExternalForm());
// create new scene
setTitle("Edit LineStyle Properties");
initModality(Modality.APPLICATION_MODAL);
int rowNum = 0;
// 1st row: color
final Label colorLbl = new Label("Color:");
getGridPane().add(colorLbl, 0, rowNum);
GridPane.setMargin(colorLbl, INSET_TOP);
getGridPane().add(myColorList, 1, rowNum);
GridPane.setMargin(myColorList, INSET_TOP);
rowNum++;
// 2nd row: width
final Label widthLbl = new Label("Width:");
getGridPane().add(widthLbl, 0, rowNum);
GridPane.setMargin(widthLbl, INSET_TOP);
myWidthSlider.setShowTickLabels(true);
myWidthSlider.setShowTickMarks(true);
myWidthSlider.setMajorTickUnit(1);
myWidthSlider.setMinorTickCount(0);
myWidthSlider.setBlockIncrement(1);
myWidthSlider.setSnapToTicks(true);
getGridPane().add(myWidthSlider, 1, rowNum);
GridPane.setMargin(myWidthSlider, INSET_TOP);
rowNum++;
// 3rd row: opacity
final Label opacityLbl = new Label("Opacity:");
getGridPane().add(opacityLbl, 0, rowNum);
GridPane.setMargin(opacityLbl, INSET_TOP);
myOpacitySlider.setShowTickLabels(true);
myOpacitySlider.setShowTickMarks(true);
myOpacitySlider.setMajorTickUnit(0.1);
myOpacitySlider.setMinorTickCount(10);
myOpacitySlider.setBlockIncrement(0.05);
myOpacitySlider.setSnapToTicks(true);
getGridPane().add(myOpacitySlider, 1, rowNum);
GridPane.setMargin(myOpacitySlider, INSET_TOP);
rowNum++;
// 4th row: line cap
final Label linecapLbl = new Label("Cap:");
getGridPane().add(linecapLbl, 0, rowNum);
GridPane.setMargin(linecapLbl, INSET_TOP);
for (LineStyle.Linecap cap : LineStyle.Linecap.values()) {
myCapList.getItems().add(cap.name());
}
getGridPane().add(myCapList, 1, rowNum);
GridPane.setMargin(myCapList, INSET_TOP);
rowNum++;
// line that updates according to settings
final HBox lineBox = new HBox();
lineBox.setMinHeight(20);
lineBox.setAlignment(Pos.CENTER);
myDemoLine.setStartX(0);
myDemoLine.setStartY(0);
myDemoLine.setEndX(200);
myDemoLine.setEndY(0);
// and now the listeners for changing of values
myColorList.getSelectionModel().selectedItemProperty().addListener((ov, t, t1) -> {
if (t1 == null) {
return;
}
myDemoLine.setStroke(t1.getStroke());
});
myWidthSlider.valueProperty().addListener((ov, t, t1) -> {
if (t1 == null) {
return;
}
myDemoLine.setStrokeWidth(t1.doubleValue());
});
myOpacitySlider.valueProperty().addListener((ov, t, t1) -> {
if (t1 == null) {
return;
}
myDemoLine.setOpacity(t1.doubleValue());
});
myCapList.getSelectionModel().selectedItemProperty().addListener((ov, t, t1) -> {
if (t1 == null) {
return;
}
myDemoLine.setStrokeLineCap(StrokeLineCap.valueOf(t1.toUpperCase()));
});
lineBox.getChildren().add(myDemoLine);
getGridPane().add(lineBox, 0, rowNum, 2, 1);
GridPane.setHalignment(lineBox, HPos.CENTER);
GridPane.setMargin(lineBox, INSET_TOP_BOTTOM);
rowNum++;
// 16th row: store properties
final HBox buttonBox = new HBox();
final Button saveButton = new Button("Save LineStyle");
saveButton.setOnAction((ActionEvent event) -> {
setLineStyle();
// callback to do the actual updates
myGPXEditor.updateLineStyle(myLineStyle);
// done, lets get out of here...
close();
});
setActionAccelerator(saveButton);
buttonBox.getChildren().add(saveButton);
HBox.setMargin(saveButton, INSET_NONE);
final Region spacer = new Region();
buttonBox.getChildren().add(spacer);
HBox.setHgrow(spacer, Priority.ALWAYS);
final Button cancelBtn = new Button("Cancel");
cancelBtn.setOnAction((ActionEvent event) -> {
close();
});
setCancelAccelerator(cancelBtn);
buttonBox.getChildren().add(cancelBtn);
HBox.setMargin(cancelBtn, INSET_NONE);
getGridPane().add(buttonBox, 0, rowNum, 2, 1);
GridPane.setHalignment(buttonBox, HPos.CENTER);
GridPane.setMargin(buttonBox, INSET_TOP_BOTTOM);
addEventFilter(WindowEvent.WINDOW_HIDING, (t) -> {
t.consume();
});
}
public void setCallback(final GPXEditor gpxEditor) {
myGPXEditor = gpxEditor;
}
public boolean editLineStyle(final LineStyle lineStyle) {
assert lineStyle != null;
myLineStyle = new LineStyle(lineStyle);
if (isShowing()) {
close();
}
initProperties();
showAndWait();
return ButtonPressed.ACTION_BUTTON.equals(getButtonPressed());
}
private void initProperties() {
ColorSelection.getInstance().selectColorInComboBox(myColorList, myLineStyle.getColor().getJavaFXColor());
myWidthSlider.setValue(myLineStyle.getWidth());
myOpacitySlider.setValue(myLineStyle.getOpacity());
for (String cap : myCapList.getItems()) {
if (cap.equals(myLineStyle.getLinecap().name())) {
myCapList.getSelectionModel().select(cap);
myDemoLine.setStrokeLineCap(StrokeLineCap.valueOf(cap.toUpperCase()));
break;
}
}
// format demo line
myDemoLine.setStroke(myLineStyle.getColor().getJavaFXColor());
myDemoLine.setStrokeWidth(myLineStyle.getWidth());
myDemoLine.setOpacity(myLineStyle.getOpacity());
}
private void setLineStyle() {
myLineStyle.setColor(GarminColor.getGarminColorForJavaFXColor((Color) myColorList.getSelectionModel().getSelectedItem().getUserData()));
myLineStyle.setWidth((int) Math.round(myWidthSlider.getValue()));
myLineStyle.setOpacity(myOpacitySlider.getValue());
myLineStyle.setLinecap(LineStyle.Linecap.valueOf(myCapList.getSelectionModel().getSelectedItem()));
}
}
|
ThomasDaheim/GPXEditor
|
src/main/java/tf/gpx/edit/values/EditLineStyle.java
|
Java
|
bsd-3-clause
| 8,919 |
var minifyCSS = require('./minify-css');
var minifyJS = require('./minify-js');
var processCode = require('../process-code');
var file = require('../file');
module.exports = {
css: processCode.with(file.type.CSS, minifyCSS),
js: processCode.with(file.type.JS, minifyJS)
};
|
ZocDoc/Bundler
|
src/minify/index.js
|
JavaScript
|
bsd-3-clause
| 289 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE191_Integer_Underflow__int64_t_fscanf_multiply_72a.cpp
Label Definition File: CWE191_Integer_Underflow.label.xml
Template File: sources-sinks-72a.tmpl.cpp
*/
/*
* @description
* CWE: 191 Integer Underflow
* BadSource: fscanf Read data from the console using fscanf()
* GoodSource: Set data to a small, non-zero number (negative two)
* Sinks: multiply
* GoodSink: Ensure there will not be an underflow before multiplying data by 2
* BadSink : If data is negative, multiply by 2, which can cause an underflow
* Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files
*
* */
#include <inttypes.h>
#include "std_testcase.h"
#include <vector>
using namespace std;
namespace CWE191_Integer_Underflow__int64_t_fscanf_multiply_72
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(vector<int64_t> dataVector);
void bad()
{
int64_t data;
vector<int64_t> dataVector;
data = 0LL;
/* POTENTIAL FLAW: Use a value input from the console */
fscanf (stdin, "%" SCNd64, &data);
/* Put data in a vector */
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
badSink(dataVector);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(vector<int64_t> dataVector);
static void goodG2B()
{
int64_t data;
vector<int64_t> dataVector;
data = 0LL;
/* FIX: Use a small, non-zero value that will not cause an underflow in the sinks */
data = -2;
/* Put data in a vector */
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
goodG2BSink(dataVector);
}
/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink(vector<int64_t> dataVector);
static void goodB2G()
{
int64_t data;
vector<int64_t> dataVector;
data = 0LL;
/* POTENTIAL FLAW: Use a value input from the console */
fscanf (stdin, "%" SCNd64, &data);
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
goodB2GSink(dataVector);
}
void good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE191_Integer_Underflow__int64_t_fscanf_multiply_72; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
JianpingZeng/xcc
|
xcc/test/juliet/testcases/CWE191_Integer_Underflow/s01/CWE191_Integer_Underflow__int64_t_fscanf_multiply_72a.cpp
|
C++
|
bsd-3-clause
| 3,336 |
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'defaultRoute'=>'index/index',
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'frontend\controllers',
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
];
|
baiqiqi/family
|
frontend/config/main.php
|
PHP
|
bsd-3-clause
| 950 |
// This file has been generated by Py++.
#include "boost/python.hpp"
#include "indexing_suite/container_suite.hpp"
#include "indexing_suite/map.hpp"
#include "wrap_osg.h"
#include "usagemap.pypp.hpp"
namespace bp = boost::python;
void register_UsageMap_class(){
bp::class_< std::map< std::string, std::string > >( "UsageMap" )
.def( bp::indexing::map_suite< std::map< std::string, std::string > >() );
}
|
JaneliaSciComp/osgpyplusplus
|
src/modules/osg/generated_code/UsageMap.pypp.cpp
|
C++
|
bsd-3-clause
| 425 |
-- phpMyAdmin SQL Dump
-- version 4.1.14
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jan 08, 2015 at 10:31 PM
-- Server version: 5.6.17
-- PHP Version: 5.5.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `booking`
--
-- --------------------------------------------------------
--
-- Table structure for table `message`
--
CREATE TABLE IF NOT EXISTS `message` (
`MessageId` int(50) NOT NULL AUTO_INCREMENT,
`MessageAuthorId` int(50) NOT NULL,
`MessageAuthorRole` varchar(255) COLLATE utf8_bin NOT NULL,
`MessageReceiverId` int(50) NOT NULL,
`MessageReceiverRole` varchar(255) COLLATE utf8_bin NOT NULL,
`MessageSubject` varchar(255) COLLATE utf8_bin NOT NULL,
`MessageData` text COLLATE utf8_bin NOT NULL,
`MessageLayout` varchar(255) COLLATE utf8_bin NOT NULL,
`MessageIsReaded` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`MessageIsDeletedByAuthor` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`MessageIsDeletedByReceiver` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`MessageDatetime` datetime NOT NULL,
PRIMARY KEY (`MessageId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=11 ;
--
-- Dumping data for table `message`
--
INSERT INTO `message` (`MessageId`, `MessageAuthorId`, `MessageAuthorRole`, `MessageReceiverId`, `MessageReceiverRole`, `MessageSubject`, `MessageData`, `MessageLayout`, `MessageIsReaded`, `MessageIsDeletedByAuthor`, `MessageIsDeletedByReceiver`, `MessageDatetime`) VALUES
(7, 60, 'COMPANY', 58, 'SEAMAN', 'New vacancy added', 'a:1:{s:9:"VacancyId";i:10;}', 'vacancy', 'READED', NULL, NULL, '2015-01-08 21:09:13'),
(8, 60, 'COMPANY', 62, 'SEAMAN', 'New vacancy added', 'a:1:{s:9:"VacancyId";i:10;}', 'vacancy', NULL, NULL, NULL, '2015-01-08 13:45:58'),
(10, 60, 'COMPANY', 58, 'SEAMAN', 'New vacancy added', 'a:1:{s:9:"VacancyId";i:13;}', 'vacancy', 'READED', NULL, NULL, '2015-01-08 21:10:20');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
olegkaliuga/seaman
|
assets/sql/message.sql
|
SQL
|
bsd-3-clause
| 2,365 |
/*================================================================================
Copyright (c) 2009 VMware, Inc. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* 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 VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. 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 com.vmware.vim25;
/**
@author Steve Jin ([email protected])
*/
public class CustomizationLinuxIdentityFailed extends CustomizationFailed
{
}
|
mikem2005/vijava
|
src/com/vmware/vim25/CustomizationLinuxIdentityFailed.java
|
Java
|
bsd-3-clause
| 1,792 |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import collections
import page_sets
import re
from core import perf_benchmark
from telemetry import benchmark
from telemetry.core import util
from telemetry.page import action_runner
from telemetry.page import page_test
from telemetry.timeline import async_slice as async_slice_module
from telemetry.timeline import slice as slice_module
from telemetry.value import scalar
from measurements import timeline_controller
from metrics import speedindex
class _ServiceWorkerTimelineMetric(object):
def AddResultsOfCounters(self, process, counter_regex_string, results):
counter_filter = re.compile(counter_regex_string)
for counter_name, counter in process.counters.iteritems():
if not counter_filter.search(counter_name):
continue
total = sum(counter.totals)
# Results objects cannot contain the '.' character, so remove that here.
sanitized_counter_name = counter_name.replace('.', '_')
results.AddValue(scalar.ScalarValue(
results.current_page, sanitized_counter_name, 'count', total))
results.AddValue(scalar.ScalarValue(
results.current_page, sanitized_counter_name + '_avg', 'count',
total / float(len(counter.totals))))
def AddResultsOfEvents(
self, process, thread_regex_string, event_regex_string, results):
thread_filter = re.compile(thread_regex_string)
event_filter = re.compile(event_regex_string)
for thread in process.threads.itervalues():
thread_name = thread.name.replace('/', '_')
if not thread_filter.search(thread_name):
continue
filtered_events = []
for event in thread.IterAllEvents():
event_name = event.name.replace('.', '_')
if event_filter.search(event_name):
filtered_events.append(event)
async_events_by_name = collections.defaultdict(list)
sync_events_by_name = collections.defaultdict(list)
for event in filtered_events:
if isinstance(event, async_slice_module.AsyncSlice):
async_events_by_name[event.name].append(event)
elif isinstance(event, slice_module.Slice):
sync_events_by_name[event.name].append(event)
for event_name, event_group in async_events_by_name.iteritems():
times = [e.duration for e in event_group]
self._AddResultOfEvent(thread_name, event_name, times, results)
for event_name, event_group in sync_events_by_name.iteritems():
times = [e.self_time for e in event_group]
self._AddResultOfEvent(thread_name, event_name, times, results)
def _AddResultOfEvent(self, thread_name, event_name, times, results):
total = sum(times)
biggest_jank = max(times)
# Results objects cannot contain the '.' character, so remove that here.
sanitized_event_name = event_name.replace('.', '_')
full_name = thread_name + '|' + sanitized_event_name
results.AddValue(scalar.ScalarValue(
results.current_page, full_name, 'ms', total))
results.AddValue(scalar.ScalarValue(
results.current_page, full_name + '_max', 'ms', biggest_jank))
results.AddValue(scalar.ScalarValue(
results.current_page, full_name + '_avg', 'ms', total / len(times)))
class _ServiceWorkerMeasurement(page_test.PageTest):
"""Measure Speed Index and TRACE_EVENTs"""
def __init__(self):
super(_ServiceWorkerMeasurement, self).__init__()
self._timeline_controller = timeline_controller.TimelineController()
self._speed_index = speedindex.SpeedIndexMetric()
self._page_open_times = collections.defaultdict(int)
# TODO(falken): Remove when reference build rolls. crbug.com/458538
def CustomizeBrowserOptions(self, options):
options.AppendExtraBrowserArgs([
'--enable-experimental-web-platform-features'
])
def WillNavigateToPage(self, page, tab):
self._timeline_controller.SetUp(page, tab)
self._timeline_controller.Start(tab)
self._speed_index.Start(page, tab)
def ValidateAndMeasurePage(self, page, tab, results):
runner = action_runner.ActionRunner(tab)
# timeline_controller requires creation of at least a single interaction
# record. service_worker should be refactored to follow the
# timeline_based_measurement or it should not re-use timeline_controller
# logic for start & stop tracing.
with runner.CreateInteraction('_DummyInteraction'):
pass
tab.WaitForDocumentReadyStateToBeComplete(40)
self._timeline_controller.Stop(tab, results)
# Retrieve TRACE_EVENTs
timeline_metric = _ServiceWorkerTimelineMetric()
browser_process = self._timeline_controller.model.browser_process
filter_text = '(RegisterServiceWorker|'\
'UnregisterServiceWorker|'\
'ProcessAllocate|'\
'FindRegistrationForDocument|'\
'DispatchFetchEvent)'
timeline_metric.AddResultsOfEvents(
browser_process, 'IOThread', filter_text , results)
# Record Speed Index
def SpeedIndexIsFinished():
return self._speed_index.IsFinished(tab)
util.WaitFor(SpeedIndexIsFinished, 60)
self._speed_index.Stop(page, tab)
# Distinguish the first and second load from the subsequent loads
url = str(page)
chart_prefix = 'page_load'
self._page_open_times[url] += 1
if self._page_open_times[url] == 1:
chart_prefix += '_1st'
elif self._page_open_times[url] == 2:
chart_prefix += '_2nd'
else:
chart_prefix += '_later'
self._speed_index.AddResults(tab, results, chart_prefix)
class _ServiceWorkerMicroBenchmarkMeasurement(page_test.PageTest):
"""Record results reported by the JS microbenchmark."""
def __init__(self):
super(_ServiceWorkerMicroBenchmarkMeasurement, self).__init__()
def ValidateAndMeasurePage(self, page, tab, results):
tab.WaitForJavaScriptExpression('window.done', 40)
json = tab.EvaluateJavaScript('window.results || {}')
for key, value in json.iteritems():
results.AddValue(scalar.ScalarValue(
results.current_page, key, value['units'], value['value']))
class ServiceWorkerPerfTest(perf_benchmark.PerfBenchmark):
"""Performance test of pages using ServiceWorker.
The page set contains pages like Trained to Thrill and svgomg.
Execution time of these pages will be shown as Speed Index, and TRACE_EVENTs
are subsidiary information to understand performance regressions in more
detail.
"""
test = _ServiceWorkerMeasurement
page_set = page_sets.ServiceWorkerPageSet
@classmethod
def Name(cls):
return 'service_worker.service_worker'
# The reference build is disabled. crbug.com/442752
# TODO(horo): Enable after the reference build newer than M39 will be rolled.
@benchmark.Disabled('reference')
class ServiceWorkerMicroBenchmarkPerfTest(perf_benchmark.PerfBenchmark):
"""This test is a microbenchmark of service worker.
The page set is a benchmark page that generates many concurrent requests
handled by a service worker that does respondWith(new Response()). The test
result is the response times.
"""
test = _ServiceWorkerMicroBenchmarkMeasurement
page_set = page_sets.ServiceWorkerMicroBenchmarkPageSet
@classmethod
def Name(cls):
return 'service_worker.service_worker_micro_benchmark'
|
Workday/OpenFrame
|
tools/perf/benchmarks/service_worker.py
|
Python
|
bsd-3-clause
| 7,416 |
/*
* Copyright (c) 2002-2021, City of Paris
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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.
*
* License 1.0
*/
package fr.paris.lutece.portal.service.prefs;
import fr.paris.lutece.portal.business.prefs.IPreferencesDAO;
import org.springframework.beans.factory.InitializingBean;
import java.util.List;
/**
* Abstract User Preferences Service
*
* @since 4.0
*/
public class BaseUserPreferencesServiceImpl implements IUserPreferencesService, InitializingBean
{
private static final String TRUE = "true";
private static final String FALSE = "false";
private static BaseUserPreferencesCacheService _cache;
private IPreferencesDAO _dao;
/**
* Constructor
*/
protected BaseUserPreferencesServiceImpl( )
{
}
/**
* Sets the DAO
*
* @param dao
* The DAO
*/
public void setDao( IPreferencesDAO dao )
{
_dao = dao;
}
/**
* {@inheritDoc }
*/
@Override
public String get( String strUserId, String strKey, String strDefault )
{
String strCacheKey = _cache.getCacheKey( strUserId, strKey );
String strValue = (String) _cache.getFromCache( strCacheKey );
if ( strValue == null )
{
strValue = _dao.load( strUserId, strKey, strDefault );
_cache.putInCache( strCacheKey, strValue );
}
return strValue;
}
/**
* {@inheritDoc }
*/
@Override
public int getInt( String strUserId, String strKey, int nDefault )
{
return Integer.parseInt( get( strUserId, strKey, String.valueOf( nDefault ) ) );
}
/**
* {@inheritDoc }
*/
@Override
public boolean getBoolean( String strUserId, String strKey, boolean bDefault )
{
String strDefault = bDefault ? TRUE : FALSE;
String strValue = get( strUserId, strKey, strDefault );
return strValue.equals( TRUE );
}
/**
* {@inheritDoc }
*/
@Override
public void put( String strUserId, String strKey, String strValue )
{
_dao.store( strUserId, strKey, strValue );
_cache.putInCache( _cache.getCacheKey( strUserId, strKey ), strValue );
}
/**
* {@inheritDoc }
*/
@Override
public void putInt( String strUserId, String strKey, int nValue )
{
put( strUserId, strKey, String.valueOf( nValue ) );
}
/**
* {@inheritDoc }
*/
@Override
public void putBoolean( String strUserId, String strKey, boolean bValue )
{
String strValue = bValue ? TRUE : FALSE;
put( strUserId, strKey, strValue );
}
/**
* {@inheritDoc }
*/
@Override
public List<String> keys( String strUserId )
{
return _dao.keys( strUserId );
}
/**
* {@inheritDoc }
*/
@Override
public void clear( String strUserId )
{
_dao.remove( strUserId );
_cache.removeCacheValuesOfUser( strUserId );
}
/**
* {@inheritDoc }
*/
@Override
public void clearKey( String strUserId, String strKey )
{
_dao.removeKey( strUserId, strKey );
_cache.removeCacheValuesOfUser( strUserId );
}
/**
* {@inheritDoc }
*/
@Override
public void clearKeyPrefix( String strUserId, String strPrefix )
{
_dao.removeKeyPrefix( strUserId, strPrefix );
_cache.removeCacheValuesOfUser( strUserId );
}
/**
* {@inheritDoc }
*/
@Override
public boolean existsKey( String strUserId, String strKey )
{
return _dao.existsKey( strUserId, strKey );
}
/**
* {@inheritDoc }
*/
@Override
public List<String> getUsers( String strKey, String strValue )
{
return _dao.getUserId( strKey, strValue );
}
/**
* {@inheritDoc}
*/
@Override
public void afterPropertiesSet( ) throws Exception
{
synchronized( BaseUserPreferencesServiceImpl.class )
{
if ( _cache == null )
{
_cache = new BaseUserPreferencesCacheService( );
_cache.initCache( );
}
}
}
@Override
public boolean existsValueForKey( String strKey, String strValue )
{
return _dao.existsValueForKey( strKey, strValue );
}
}
|
rzara/lutece-core
|
src/java/fr/paris/lutece/portal/service/prefs/BaseUserPreferencesServiceImpl.java
|
Java
|
bsd-3-clause
| 5,801 |
import code
import pathlib
import sys
from util.nick import nickeq, nicklower
class Repl(code.InteractiveConsole):
def __init__(self, circa, channel):
code.InteractiveConsole.__init__(self, {"circa": circa})
self.circa = circa
self.channel = channel
self.buf = ""
def write(self, data):
self.buf += data
def flush(self):
msg = self.buf.rstrip("\n")
if len(msg) > 0:
self.circa.say(self.channel, msg)
self.buf = ""
def run(self, code):
sys.stdout = sys.interp = self
self.push(code)
sys.stdout = sys.__stdout__
self.flush()
def showtraceback(self):
type, value, lasttb = sys.exc_info()
fname = pathlib.Path(lasttb.tb_frame.f_code.co_filename).name
self.circa.say(self.channel, "\x02\x034{0}\x03\x02: {1} ({2}:{3})".format( \
type.__name__, value, fname, lasttb.tb_lineno))
def showsyntaxerror(self, filename):
self.showtraceback()
class ReplModule:
require = "cmd"
def __init__(self, circa):
self.circa = circa
self.repls = {}
self.events = {
"message": [self.handle_repl]
}
self.docs = "Any message beginning with '>>> ' executes Python code. Admins only."
def handle_repl(self, fr, to, text, m):
if text.startswith(">>> "):
self.repl(nicklower(fr), nicklower(fr) if nickeq(to, self.circa.nick) \
else nicklower(to), text[len(">>> "):], m)
def repl(self, fr, to, command, m):
if self.circa.is_admin(m.prefix):
if to not in self.repls:
self.repls[to] = Repl(self.circa, to)
self.repls[to].run(command)
module = ReplModule
|
sammdot/circa
|
modules/repl.py
|
Python
|
bsd-3-clause
| 1,520 |
module Tilia
module DavAcl
module PrincipalBackend
class Mock < AbstractBackend
attr_accessor :group_members
attr_accessor :principals
def initialize(principals = nil)
@group_members = {}
@principals = principals
unless principals
@principals = [
{
'uri' => 'principals/user1',
'{DAV:}displayname' => 'User 1',
'{http://sabredav.org/ns}email-address' => '[email protected]',
'{http://sabredav.org/ns}vcard-url' => 'addressbooks/user1/book1/vcard1.vcf'
},
{
'uri' => 'principals/admin',
'{DAV:}displayname' => 'Admin'
},
{
'uri' => 'principals/user2',
'{DAV:}displayname' => 'User 2',
'{http://sabredav.org/ns}email-address' => '[email protected]'
}
]
end
end
def principals_by_prefix(prefix)
prefix = prefix.gsub(%r{^/+|/+$}, '')
prefix << '/' unless prefix.blank?
to_return = []
@principals.each do |principal|
next if prefix.present? && principal['uri'].index(prefix) != 0
to_return << principal
end
to_return
end
def add_principal(principal)
@principals << principal
end
def principal_by_path(path)
principals_by_prefix('principals').each do |principal|
return principal if principal['uri'] == path
end
nil
end
def search_principals(prefix_path, search_properties, test = 'allof')
matches = []
principals_by_prefix(prefix_path).each do |principal|
skip = false
search_properties.each do |key, value|
unless principal.key?(key)
skip = true
break
end
unless principal[key].downcase.index(value.downcase)
skip = true
break
end
# We have a match for this searchProperty!
if test == 'allof'
next
else
break
end
end
next if skip
matches << principal['uri']
end
matches
end
def group_member_set(path)
@group_members.key?(path) ? @group_members[path] : []
end
def group_membership(path)
membership = []
@group_members.each do |group, members|
membership << group if members.include?(path)
end
membership
end
def update_group_member_set(path, members)
@group_members[path] = members
end
# Updates one ore more webdav properties on a principal.
#
# The list of mutations is stored in a Sabre\DAV\PropPatch object.
# To do the actual updates, you must tell this object which properties
# you're going to process with the handle method.
#
# Calling the handle method is like telling the PropPatch object "I
# promise I can handle updating this property".
#
# Read the PropPatch documenation for more info and examples.
#
# @param string path
# @param \Sabre\DAV\PropPatch prop_patch
def update_principal(path, prop_patch)
value = nil
principal_index = nil
principal = nil
@principals.each_with_index do |value, i|
principal_index = i
if value['uri'] == path
principal = value
break
end
end
return nil unless principal
prop_patch.handle_remaining(
lambda do |mutations|
mutations.each do |prop, value|
if value.nil? && principal.key?(prop)
principal.delete(prop)
else
principal[prop] = value
end
end
@principals[principal_index] = principal
return true
end
)
end
end
end
end
end
|
tilia/tilia-dav
|
test/dav_acl/principal_backend/mock.rb
|
Ruby
|
bsd-3-clause
| 4,440 |
/**/
#include<stdio.h>
#include<math.h>
int main (void)
{
char a[4095];
int n =0, sum = 0, checksum;
n=0;
printf("Enter an abitrarily long string, ending with carriage return > ");
scanf("%s",a);
while (a[n] != '\0')
{
sum += (int)(a[n]);
n++;
}
checksum = (sum%64)+32;
printf("Check sum is %c\n", (char)checksum);
return(0);
}
|
ProgramRepair/IntroClass
|
checksum/d5cc7acaad4f01271abd8e5e7aecd52ad0fd82b2ea0c14dec8df934c2339b522dd2ed9549605a6405048bcbd89256e7ec818001899fecaa1ec147265783608f9/001/checksum.c
|
C
|
bsd-3-clause
| 343 |
/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** 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 the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#pragma once
#include "Expression.h"
DECLARE_TYPED_LIST(OOMODEL_API, OOModel, ThisExpression)
namespace OOModel {
class OOMODEL_API ThisExpression: public Super<Expression>
{
COMPOSITENODE_DECLARE_STANDARD_METHODS(ThisExpression)
public:
virtual Type* type();
};
}
|
patrick-luethi/Envision
|
OOModel/src/expressions/ThisExpression.h
|
C
|
bsd-3-clause
| 2,083 |
using System;
using System.Text;
using System.Xml;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using ADODB;
namespace MyMeta
{
#if ENTERPRISE
using System.Runtime.InteropServices;
[ComVisible(false), ClassInterface(ClassInterfaceType.AutoDual)]
#endif
public class Database : Single, IDatabase, INameValueItem
{
protected Hashtable dataTypeTables = new Hashtable();
public Database()
{
}
virtual public IResultColumns ResultColumnsFromSQL(string sql)
{
IResultColumns columns = null;
using (OleDbConnection cn = new OleDbConnection(dbRoot.ConnectionString))
{
cn.Open();
columns = ResultColumnsFromSQL(sql, cn);
}
return columns;
}
virtual public ADODB.Recordset ExecuteSql(string sql)
{
Recordset oRS = new Recordset();
OleDbConnection cn = null;
OleDbDataReader reader = null;
try
{
cn = new OleDbConnection(dbRoot.ConnectionString);
cn.Open();
try
{
cn.ChangeDatabase(this.Name);
}
catch { } // some databases don't have the concept of catalogs. Catch this and throw it out
OleDbCommand command = new OleDbCommand(sql, cn);
command.CommandType = CommandType.Text;
reader = command.ExecuteReader();
DataTable schema;
string dataType, fieldname;
int length;
bool firstTime = true;
while (reader.Read())
{
if (firstTime)
{
schema = reader.GetSchemaTable();
foreach (DataRow row in schema.Rows)
{
fieldname = row["ColumnName"].ToString();
dataType = row["DataType"].ToString();
length = Convert.ToInt32(row["ColumnSize"]);
oRS.Fields.Append(fieldname, GetADOType(dataType), length,
FieldAttributeEnum.adFldIsNullable, System.Reflection.Missing.Value);
}
oRS.Open(System.Reflection.Missing.Value, System.Reflection.Missing.Value,
CursorTypeEnum.adOpenStatic, LockTypeEnum.adLockOptimistic, 1);
firstTime = false;
}
oRS.AddNew(System.Reflection.Missing.Value, System.Reflection.Missing.Value);
for(int i = 0; i < reader.FieldCount; i++)
{
if (reader[i] is System.Guid)
{
oRS.Fields[i].Value = "{" + reader[i].ToString() + "}";
}
else
{
oRS.Fields[i].Value = reader[i];
}
}
}
cn.Close();
//Move to the first record
if (!firstTime)
{
oRS.MoveFirst();
}
else
{
oRS = null;
}
}
catch (Exception ex)
{
if ((reader != null) && (!reader.IsClosed))
{
reader.Close();
reader = null;
}
if ((cn != null) && (cn.State == ConnectionState.Open))
{
cn.Close();
cn = null;
}
throw ex;
}
return oRS;
}
/// <summary>
///
/// </summary>
/// <param name="oledbType"></param>
/// <param name="providerTypeInt"></param>
/// <param name="dataType"></param>
/// <param name="length"></param>
/// <param name="numericPrecision"></param>
/// <param name="numericScale"></param>
/// <param name="isLong"></param>
/// <param name="dbTypeName"></param>
/// <param name="dbTypeNameComplete"></param>
/// <returns></returns>
protected virtual bool GetNativeType(
OleDbType oledbType, int providerTypeInt, string dataType,
int length, int numericPrecision, int numericScale, bool isLong,
out string dbTypeName, out string dbTypeNameComplete)
{
bool rval = false;
IProviderType provType = null;
if (providerTypeInt >= 0)
{
if (!dataTypeTables.ContainsKey(providerTypeInt))
{
foreach (IProviderType ptypeLoop in dbRoot.ProviderTypes)
{
if (ptypeLoop.DataType == providerTypeInt)
{
if ((provType == null) ||
(ptypeLoop.BestMatch && !provType.BestMatch) ||
(isLong && ptypeLoop.IsLong && !provType.IsLong) ||
(!ptypeLoop.IsFixedLength && provType.IsFixedLength))
{
provType = ptypeLoop;
}
}
}
dataTypeTables[providerTypeInt] = provType;
}
else
{
provType = dataTypeTables[providerTypeInt] as IProviderType;
}
}
if (provType != null)
{
string dtype = provType.Type;
string[] parms = provType.CreateParams.Split(',');
if (parms.Length > 0)
{
dtype += "(";
int xx = 0;
for (int i = 0; i < parms.Length; i++)
{
switch (parms[i])
{
case "precision":
dtype += (xx > 0 ? ", " : "") + numericPrecision.ToString();
xx++;
break;
case "scale":
dtype += (xx > 0 ? ", " : "") + numericScale.ToString();
xx++;
break;
case "length":
case "max length":
dtype += (xx > 0 ? ", " : "") + length.ToString();
xx++;
break;
}
}
dtype += ")";
if (xx == 0) dtype = dtype.Substring(0, dtype.Length - 2);
}
dbTypeName = provType.Type;
dbTypeNameComplete = dtype;
rval = true;
}
else
{
dbTypeName = string.Empty;
dbTypeNameComplete = string.Empty;
}
return rval;
}
protected IResultColumns ResultColumnsFromSQL(string sql, IDbConnection cn)
{
MyMetaPluginContext context = new MyMetaPluginContext(null, null);
DataTable metaData = context.CreateResultColumnsDataTable();
Plugin.PluginResultColumns resultCols = new Plugin.PluginResultColumns(null);
resultCols.dbRoot = dbRoot;
IDbCommand command = cn.CreateCommand();
command.CommandText = sql;
command.CommandType = CommandType.Text;
using (IDataReader reader = command.ExecuteReader())
{
DataTable schema;
//DataTable data;
string dataType, fieldname;
int length;
// Skip columns contains the index of any columns that we cannot handle, array types and such ...
Hashtable skipColumns = null;
reader.Read();
schema = reader.GetSchemaTable();
IProviderType provType = null;
int columnOrdinal = 0, numericPrecision = 0, numericScale = 0, providerTypeInt = -1, colID = 0;
bool isLong = false;
string dbTypeName = string.Empty, dbTypeNameComplete = string.Empty;
foreach (DataRow row in schema.Rows)
{
DataRow metarow = metaData.NewRow();
fieldname = row["ColumnName"].ToString();
dataType = row["DataType"].ToString();
length = 0;
provType = null;
columnOrdinal = 0;
numericPrecision = 0;
numericScale = 0;
providerTypeInt = -1;
isLong = false;
if (row["ColumnSize"] != DBNull.Value) length = Convert.ToInt32(row["ColumnSize"]);
if (row["ColumnOrdinal"] != DBNull.Value) columnOrdinal = Convert.ToInt32(row["ColumnOrdinal"]);
if (row["NumericPrecision"] != DBNull.Value) numericPrecision = Convert.ToInt32(row["NumericPrecision"]);
if (row["NumericScale"] != DBNull.Value) numericScale = Convert.ToInt32(row["NumericScale"]);
if (row["IsLong"] != DBNull.Value) isLong = Convert.ToBoolean(row["IsLong"]);
if (row["ProviderType"] != DBNull.Value) providerTypeInt = Convert.ToInt32(row["ProviderType"]);
OleDbType oledbType;
try { oledbType = (OleDbType)providerTypeInt; }
catch { oledbType = OleDbType.IUnknown; }
this.GetNativeType(oledbType, providerTypeInt, dataType, length, numericPrecision, numericScale, isLong, out dbTypeName, out dbTypeNameComplete);
metarow["COLUMN_NAME"] = fieldname;
metarow["ORDINAL_POSITION"] = columnOrdinal;
metarow["DATA_TYPE"] = providerTypeInt;
metarow["TYPE_NAME"] = dbTypeName;
metarow["TYPE_NAME_COMPLETE"] = dbTypeNameComplete;
metaData.Rows.Add(metarow);
}
resultCols.Populate(metaData);
}
return resultCols;
}
protected ADODB.Recordset ExecuteIntoRecordset(string sql, IDbConnection cn)
{
Recordset oRS = new Recordset();
IDataReader reader = null;
try
{
IDbCommand command = cn.CreateCommand();
command.CommandText = sql;
command.CommandType = CommandType.Text;
reader = command.ExecuteReader();
DataTable schema;
string dataType, fieldname;
int length;
bool firstTime = true;
// Skip columns contains the index of any columns that we cannot handle, array types and such ...
Hashtable skipColumns = null;
while (reader.Read())
{
if (firstTime)
{
skipColumns = new Hashtable();
schema = reader.GetSchemaTable();
int colID = 0;
foreach (DataRow row in schema.Rows)
{
fieldname = row["ColumnName"].ToString();
dataType = row["DataType"].ToString();
length = Convert.ToInt32(row["ColumnSize"]);
try
{
oRS.Fields.Append(fieldname, GetADOType(dataType), length,
FieldAttributeEnum.adFldIsNullable, System.Reflection.Missing.Value);
}
catch
{
// We can't handle this column type, ie, Firebird array types
skipColumns[colID] = colID;
}
colID++;
}
oRS.Open(System.Reflection.Missing.Value, System.Reflection.Missing.Value,
CursorTypeEnum.adOpenStatic, LockTypeEnum.adLockOptimistic, 1);
firstTime = false;
}
oRS.AddNew(System.Reflection.Missing.Value, System.Reflection.Missing.Value);
for(int i = 0, j = 0; i < reader.FieldCount; i++)
{
// Skip columns that we cannot handle
if(!skipColumns.ContainsKey(i))
{
if (reader[j] is System.Guid)
{
oRS.Fields[j].Value = "{" + reader[j].ToString() + "}";
}
else
{
try
{
oRS.Fields[j].Value = reader[j];
}
catch
{
// For some reason it wouldn't accept this value?
oRS.Fields[j].Value = DBNull.Value;
}
}
j++;
}
}
}
cn.Close();
//Move to the first record
if (!firstTime)
{
oRS.MoveFirst();
}
else
{
oRS = null;
}
}
catch (Exception ex)
{
if ((reader != null) && (!reader.IsClosed))
{
reader.Close();
reader = null;
}
if ((cn != null) && (cn.State == ConnectionState.Open))
{
cn.Close();
cn = null;
}
throw ex;
}
return oRS;
}
protected DataTypeEnum GetADOType(string sType)
{
switch(sType)
{
case null:
return DataTypeEnum.adEmpty;
case "System.Byte":
return DataTypeEnum.adUnsignedTinyInt;
case "System.SByte":
return DataTypeEnum.adTinyInt;
case "System.Boolean":
return DataTypeEnum.adBoolean;
case "System.Int16":
return DataTypeEnum.adSmallInt;
case "System.Int32":
return DataTypeEnum.adInteger;
case "System.Int64":
return DataTypeEnum.adBigInt;
case "System.Single":
return DataTypeEnum.adSingle;
case "System.Double":
return DataTypeEnum.adDouble;
case "System.Decimal":
return DataTypeEnum.adDecimal;
case "System.DateTime":
return DataTypeEnum.adDate;
case "System.Guid":
return DataTypeEnum.adGUID;
case "System.String":
return DataTypeEnum.adBSTR; //.adChar;
case "System.Byte[]":
return DataTypeEnum.adBinary;
case "System.Array":
return DataTypeEnum.adArray;
case "System.Object":
return DataTypeEnum.adVariant;
default:
return 0;
}
}
virtual public ITables Tables
{
get
{
if(null == _tables)
{
_tables = (Tables)this.dbRoot.ClassFactory.CreateTables();
_tables.dbRoot = this._dbRoot;
_tables.Database = this;
_tables.LoadAll();
}
return _tables;
}
}
virtual public IViews Views
{
get
{
if(null == _views)
{
_views = (Views)this.dbRoot.ClassFactory.CreateViews();
_views.dbRoot = this._dbRoot;
_views.Database = this;
_views.LoadAll();
}
return _views;
}
}
virtual public IProcedures Procedures
{
get
{
if(null == _procedures)
{
_procedures = (Procedures)this.dbRoot.ClassFactory.CreateProcedures();
_procedures.dbRoot = this._dbRoot;
_procedures.Database = this;
_procedures.LoadAll();
}
return _procedures;
}
}
virtual public IDomains Domains
{
get
{
if(null == _domains)
{
_domains = (Domains)this.dbRoot.ClassFactory.CreateDomains();
_domains.dbRoot = this._dbRoot;
_domains.Database = this;
_domains.LoadAll();
}
return _domains;
}
}
// virtual public IPropertyCollection GlobalProperties
// {
// get
// {
// Database db = this as Database;
// if(null == db._columnProperties)
// {
// db._columnProperties = new PropertyCollection();
// db._columnProperties.Parent = this;
//
// string xPath = this.GlobalUserDataXPath;
// XmlNode xmlNode = this.dbRoot.UserData.SelectSingleNode(xPath, null);
//
// if(xmlNode == null)
// {
// XmlNode parentNode = db.CreateGlobalXmlNode();
//
// xmlNode = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Database", null);
// parentNode.AppendChild(xmlNode);
// }
//
// db._columnProperties.LoadAllGlobal(xmlNode);
// }
//
// return db._columnProperties;
// }
// }
#if ENTERPRISE
[DispId(0)]
#endif
override public string Alias
{
get
{
XmlNode node = null;
if(this.GetXmlNode(out node, false))
{
string niceName = null;
if(this.GetUserData(node, "n", out niceName))
{
if(string.Empty != niceName)
return niceName;
}
}
// There was no nice name
return this.Name;
}
set
{
XmlNode node = null;
if(this.GetXmlNode(out node, true))
{
this.SetUserData(node, "n", value);
}
}
}
public virtual string XmlMetaDataKey
{
get
{
if (dbRoot.UserDataDatabaseMappings.ContainsKey(Name))
{
return dbRoot.UserDataDatabaseMappings[Name];
}
else
{
return Name;
}
}
}
override public string Name
{
get
{
return this.GetString(Databases.f_Catalog);
}
}
virtual public string Description
{
get
{
return this.GetString(Databases.f_Description);
}
}
virtual public string SchemaName
{
get
{
return this.GetString(Databases.f_SchemaName);
}
}
virtual public string SchemaOwner
{
get
{
return this.GetString(Databases.f_SchemaOwner);
}
}
virtual public string DefaultCharSetCatalog
{
get
{
return this.GetString(Databases.f_DefCharSetCat);
}
}
virtual public string DefaultCharSetSchema
{
get
{
return this.GetString(Databases.f_DefCharSetSchema);
}
}
virtual public string DefaultCharSetName
{
get
{
return this.GetString(Databases.f_DefCharSetName);
}
}
virtual public dbRoot Root
{
get
{
return this.dbRoot;
}
}
#region XML User Data
#if ENTERPRISE
[ComVisible(false)]
#endif
override public string UserDataXPath
{
get
{
return Databases.UserDataXPath + @"/Database[@p='" + this.XmlMetaDataKey + "']";
}
}
#if ENTERPRISE
[ComVisible(false)]
#endif
override public string GlobalUserDataXPath
{
get
{
return @"//MyMeta/Global/Databases/Database[@p='" + this.XmlMetaDataKey + "']";
}
}
#if ENTERPRISE
[ComVisible(false)]
#endif
override internal bool GetXmlNode(out XmlNode node, bool forceCreate)
{
node = null;
bool success = false;
if(null == _xmlNode)
{
// Get the parent node
XmlNode parentNode = null;
if(this.Databases.GetXmlNode(out parentNode, forceCreate))
{
// See if our user data already exists
string xPath = @"./Database[@p='" + this.XmlMetaDataKey + "']";
if(!GetUserData(xPath, parentNode, out _xmlNode) && forceCreate)
{
// Create it, and try again
this.CreateUserMetaData(parentNode);
GetUserData(xPath, parentNode, out _xmlNode);
}
}
}
if(null != _xmlNode)
{
node = _xmlNode;
success = true;
}
return success;
}
#if ENTERPRISE
[ComVisible(false)]
#endif
internal XmlNode CreateGlobalXmlNode()
{
XmlNode node = null;
XmlNode parentNode = null;
this.dbRoot.GetXmlNode(out parentNode, true);
node = parentNode.SelectSingleNode(@"./Global");
if(node == null)
{
node = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Global", null);
parentNode.AppendChild(node);
}
parentNode = node;
node = parentNode.SelectSingleNode(@"./Databases");
if(node == null)
{
node = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Databases", null);
parentNode.AppendChild(node);
}
parentNode = node;
node = parentNode.SelectSingleNode(@"./Database[@p='" + this.XmlMetaDataKey + "']");
if(node == null)
{
node = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Database", null);
parentNode.AppendChild(node);
XmlAttribute attr;
attr = node.OwnerDocument.CreateAttribute("p");
attr.Value = this.XmlMetaDataKey;
node.Attributes.Append(attr);
}
return node;
}
#if ENTERPRISE
[ComVisible(false)]
#endif
override public void CreateUserMetaData(XmlNode parentNode)
{
XmlNode myNode = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Database", null);
parentNode.AppendChild(myNode);
XmlAttribute attr;
attr = parentNode.OwnerDocument.CreateAttribute("p");
attr.Value = this.XmlMetaDataKey;
myNode.Attributes.Append(attr);
attr = parentNode.OwnerDocument.CreateAttribute("n");
attr.Value = "";
myNode.Attributes.Append(attr);
}
#endregion
#region INameValueCollection Members
public string ItemName
{
get
{
return this.Name;
}
}
public string ItemValue
{
get
{
return this.Name;
}
}
#endregion
internal Databases Databases = null;
protected Tables _tables = null;
protected Views _views = null;
protected Procedures _procedures = null;
protected Domains _domains = null;
// Global properties are per Database
internal PropertyCollection _columnProperties = null;
internal PropertyCollection _databaseProperties = null;
internal PropertyCollection _foreignkeyProperties = null;
internal PropertyCollection _indexProperties = null;
internal PropertyCollection _parameterProperties = null;
internal PropertyCollection _procedureProperties = null;
internal PropertyCollection _resultColumnProperties = null;
internal PropertyCollection _tableProperties = null;
internal PropertyCollection _viewProperties = null;
internal PropertyCollection _domainProperties = null;
}
}
|
cafephin/mygeneration
|
src/mymeta/Database.cs
|
C#
|
bsd-3-clause
| 20,796 |
<?php
/* @var $this yii\web\View */
?>
<h1>Hey <?php echo $name->first_name;?>, This Requires Upgrade</h1>
<p>
You can get the access you want by upgrading, but <?php echo $name->first_name;?>,
that's not all. You get to go everywhere, isn't that cool?
</p>
|
santhika29/yii2build
|
frontend/views/upgrade/index.php
|
PHP
|
bsd-3-clause
| 260 |
package schaugenau.core;
import java.util.LinkedList;
import com.jme3.collision.CollisionResults;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Ray;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
/**
* Distributed under the MIT License. (See accompanying file LICENSE or copy at
* https://github.com/raphaelmenges/schaugenau/blob/master/src/LICENSE)
*
* Container for multiple entities of same type.
*
* @author Raphael Menges
*
*/
public class MultiStaticEntity<T extends StaticEntity> {
/** fields **/
protected Node node;
protected Node parent = null;
protected LinkedList<T> list;
/** methods **/
public MultiStaticEntity(String name) {
list = new LinkedList<T>();
node = new Node(name);
}
/* add new static entity */
public void add(T staticEntity) {
staticEntity.attachTo(node);
list.add(staticEntity);
}
/* get list */
public LinkedList<T> getList() {
return list;
}
/* attach it to node */
public void attachTo(Node parent) {
this.parent = parent;
parent.attachChild(node);
}
/* detach from node */
public void detach() {
if (parent != null) {
parent.detachChild(node);
}
}
/* relative move */
public void move(Vector3f offset) {
node.move(offset);
}
/* relative rotate */
public void rotate(Vector3f angle) {
node.rotate(angle.x, angle.y, angle.z);
}
/* relative scale */
public void scale(float size) {
node.scale(size);
}
/* relative scale */
public void scale(Vector3f size) {
node.scale(size.x, size.y, size.z);
}
/* set local translation */
public void setLocalTranslation(Vector3f localTranslation) {
node.setLocalTranslation(localTranslation);
}
/* get world translation */
public Vector3f getWorldTranslation() {
return node.getWorldTranslation();
}
/* get name */
public String getName() {
return node.getName();
}
/* collide with ray */
public void collideWith(Ray ray, CollisionResults results) {
node.collideWith(ray, results);
}
/* change color parameter of materials */
public void setColorParameter(ColorRGBA color) {
for (T entity : list) {
entity.setColorParameter(color);
}
}
}
|
raphaelmenges/schaugenau
|
src/schaugenau/core/MultiStaticEntity.java
|
Java
|
bsd-3-clause
| 2,146 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title>Photocracy</title>
<link href="http://www.photocracy.org/stylesheets/main.css" media="screen" rel="stylesheet" type="text/css">
<!--[if IE]>
<link href="http://www.photocracy.org//stylesheets/main_ie.css?1237066382" media="screen" rel="stylesheet" type="text/css" />
<![endif]-->
<!--[if IE 6]>
<link href="http://www.photocracy.org//stylesheets/main_ie6.css?1237066382" media="screen" rel="stylesheet" type="text/css" />
<![endif]-->
<script src="http://www.photocracy.org/javascripts/jquery.js" type="text/javascript"></script>
<script src="http://www.photocracy.org/javascripts/jquery-ui.js" type="text/javascript"></script>
<script src="http://www.photocracy.org/javascripts/jrails.js" type="text/javascript"></script>
<script src="http://www.photocracy.org/javascripts/application.js" type="text/javascript"></script>
<script src="http://www.photocracy.org/javascripts/google.js" type="text/javascript"></script>
<script src="http://www.photocracy.org/javascripts/admin.js" type="text/javascript"></script>
</head><div FirebugVersion="1.3.3" style="display: none;" id="_firebugConsole"></div><body>
<div class="container" id="container">
<div class="header">
<form action="/profiles/language" method="post">
<p>language</p>
<select id="id" name="id" onchange="submit()"><option value="cn">中文 (Simplified)</option>
<option value="cn_t">中文 (Traditional)</option>
<option value="en" selected="selected">English</option>
<option value="jp">日本語</option></select>
</form>
<p><a href="http://www.photocracy.org/share">share</a></p>
</div>
<div class="links">
<div class="logo">
<a href="http://www.photocracy.org/" class="title"><img alt="Title" src="http://www.photocracy.org/images/title.png"></a>
<div class="title" id="stats">85017 votes on 486 photos</div>
</div>
<a href="http://www.photocracy.org/responses/0">vote</a>
<a href="http://www.photocracy.org/items/new">add a photo</a>
<a href="http://www.photocracy.org/items">view photos</a>
<a href="http://www.photocracy.org/responses">recent winners</a>
<a href="http://www.photocracy.org/about" class="active">about</a>
</div>
<div class="content">
<span id="flash_notice">
</span>
<span id="flash_error">
<h2 class="error">
<p>We're sorry, but something went wrong.</p>
<p>We've been notified about this issue and are investigating it.</p>
</h2>
<h2 class="error">
<p>对不起,竟然遇到问题</p>
<p>这被据报,等到查看</p>
</h2>
<h2 class="error">
<p>对對不起,竟然遇到問題</p>
<p>這被據報,等到查</p>
</h2>
<h2 class="error">
<p>申し訳ないですがちょっと問題が起りました。</p>
<p>この問題について知らせが届いたので今調査中です。</p>
</h2>
</span>
<div></div>
<div class="left">
<h1>About</h1>
<p class='block'>
Photocracy is searching for special photos and we've crowd-sourced the task to you. We ask you questions like "Which photo better represent the United States?" and then by combining your votes with the votes of others we are able to find photos that are strongly associated with specific countries. By having voters from all over the world we can learn about national identity and cross-national perceptions. In fact, everyone can
<a href="/items">see the results</a>.
</p>
<p>
We've also crowd-sourced the task of finding the photos to you. If you have a photo that you think represents China, Japan, or the United States, please
<a href="/items/new">upload it</a>
so that others can vote for it. We've even made it easy for you to
<a href="/items/new">upload photos directly from Flickr</a>.
</p>
<p>
Photocracy is an academic research project, and the initial data set will be used for a Senior Thesis at Princeton University. If you would like to help, please vote, encourage others to vote, and
<a href="/items/new">upload some photos</a>.
Feel free to contact us through
<a href="/feedback">our feedback form</a>
or
<a href="mailto:[email protected]">email</a>.
</p>
<br />
<p>
Sincerely,
<br />
<br />
<a href="http://sociology.princeton.edu/Faculty/Salganik/">Matthew Salganik</a>, Assistant Professor of Sociology
<br />
Josh Weinstein, Princeton University Class of 2009
</p>
</div>
<div class="divider"></div>
<div class="right">
<h2>Contributors and Contacts</h2>
<p class="block">
Matt Salganik
<br>
Assistant Professor of Sociology
</p>
<p>
Josh Weinstein
<br>
Princeton University Class of 2009
</p>
<p>
Peter Lubell-Doughtie
<br>
Web Development
</p>
<p>
For website specific inquiries, please contact: <a href="mailto:[email protected]">[email protected]</a>
</p>
</div>
</div>
</div>
<div class="footer">
<p><a href="http://www.photocracy.org/privacy">Privacy Policy</a></p>
<p><a href="http://www.photocracy.org/feedback">leave feedback</a></p>
</div>
<span id="tracking" style="display: none;"></span>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script><script src="google-analytics.com/ga.js" type="text/javascript"></script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-7217573-3");
pageTracker._trackPageview();
} catch(err) {}
</script>
</body></html>
|
pld/photocracy
|
public/500.html
|
HTML
|
bsd-3-clause
| 6,412 |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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 the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``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 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.
*/
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.IO;
using System.Text;
using Microsoft.CSharp;
//using Microsoft.JScript;
using Microsoft.VisualBasic;
using log4net;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenMetaverse;
namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
{
public class Compiler : ICompiler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// * Uses "LSL2Converter" to convert LSL to C# if necessary.
// * Compiles C#-code into an assembly
// * Returns assembly name ready for AppDomain load.
//
// Assembly is compiled using LSL_BaseClass as base. Look at debug C# code file created when LSL script is compiled for full details.
//
internal enum enumCompileType
{
lsl = 0,
cs = 1,
vb = 2,
js = 3,
yp = 4
}
/// <summary>
/// This contains number of lines WE use for header when compiling script. User will get error in line x-LinesToRemoveOnError when error occurs.
/// </summary>
public int LinesToRemoveOnError = 3;
private enumCompileType DefaultCompileLanguage;
private bool WriteScriptSourceToDebugFile;
private bool CompileWithDebugInformation;
private Dictionary<string, bool> AllowedCompilers = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase);
private Dictionary<string, enumCompileType> LanguageMapping = new Dictionary<string, enumCompileType>(StringComparer.CurrentCultureIgnoreCase);
private bool m_insertCoopTerminationCalls;
private string FilePrefix;
private string ScriptEnginesPath = null;
// mapping between LSL and C# line/column numbers
private ICodeConverter LSL_Converter;
private List<string> m_warnings = new List<string>();
// private object m_syncy = new object();
private static CSharpCodeProvider CScodeProvider = new CSharpCodeProvider();
private static VBCodeProvider VBcodeProvider = new VBCodeProvider();
// private static JScriptCodeProvider JScodeProvider = new JScriptCodeProvider();
private static CSharpCodeProvider YPcodeProvider = new CSharpCodeProvider(); // YP is translated into CSharp
private static YP2CSConverter YP_Converter = new YP2CSConverter();
// private static int instanceID = new Random().Next(0, int.MaxValue); // Unique number to use on our compiled files
private static UInt64 scriptCompileCounter = 0; // And a counter
public IScriptEngine m_scriptEngine;
private Dictionary<string, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>> m_lineMaps =
new Dictionary<string, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>>();
public bool in_startup = true;
public Compiler(IScriptEngine scriptEngine)
{
m_scriptEngine = scriptEngine;
ScriptEnginesPath = scriptEngine.ScriptEnginePath;
ReadConfig();
}
public void ReadConfig()
{
// Get some config
WriteScriptSourceToDebugFile = m_scriptEngine.Config.GetBoolean("WriteScriptSourceToDebugFile", false);
CompileWithDebugInformation = m_scriptEngine.Config.GetBoolean("CompileWithDebugInformation", true);
bool DeleteScriptsOnStartup = m_scriptEngine.Config.GetBoolean("DeleteScriptsOnStartup", true);
m_insertCoopTerminationCalls = m_scriptEngine.Config.GetString("ScriptStopStrategy", "abort") == "co-op";
// Get file prefix from scriptengine name and make it file system safe:
FilePrefix = "CommonCompiler";
foreach (char c in Path.GetInvalidFileNameChars())
{
FilePrefix = FilePrefix.Replace(c, '_');
}
if (in_startup)
{
in_startup = false;
CreateScriptsDirectory();
// First time we start? Delete old files
if (DeleteScriptsOnStartup)
DeleteOldFiles();
}
// Map name and enum type of our supported languages
LanguageMapping.Add(enumCompileType.cs.ToString(), enumCompileType.cs);
LanguageMapping.Add(enumCompileType.vb.ToString(), enumCompileType.vb);
LanguageMapping.Add(enumCompileType.lsl.ToString(), enumCompileType.lsl);
LanguageMapping.Add(enumCompileType.js.ToString(), enumCompileType.js);
LanguageMapping.Add(enumCompileType.yp.ToString(), enumCompileType.yp);
// Allowed compilers
string allowComp = m_scriptEngine.Config.GetString("AllowedCompilers", "lsl");
AllowedCompilers.Clear();
#if DEBUG
m_log.Debug("[Compiler]: Allowed languages: " + allowComp);
#endif
foreach (string strl in allowComp.Split(','))
{
string strlan = strl.Trim(" \t".ToCharArray()).ToLower();
if (!LanguageMapping.ContainsKey(strlan))
{
m_log.Error("[Compiler]: Config error. Compiler is unable to recognize language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
}
else
{
#if DEBUG
//m_log.Debug("[Compiler]: Config OK. Compiler recognized language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
#endif
}
AllowedCompilers.Add(strlan, true);
}
if (AllowedCompilers.Count == 0)
m_log.Error("[Compiler]: Config error. Compiler could not recognize any language in \"AllowedCompilers\". Scripts will not be executed!");
// Default language
string defaultCompileLanguage = m_scriptEngine.Config.GetString("DefaultCompileLanguage", "lsl").ToLower();
// Is this language recognized at all?
if (!LanguageMapping.ContainsKey(defaultCompileLanguage))
{
m_log.Error("[Compiler]: " +
"Config error. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is not recognized as a valid language. Changing default to: \"lsl\".");
defaultCompileLanguage = "lsl";
}
// Is this language in allow-list?
if (!AllowedCompilers.ContainsKey(defaultCompileLanguage))
{
m_log.Error("[Compiler]: " +
"Config error. Default language \"" + defaultCompileLanguage + "\"specified in \"DefaultCompileLanguage\" is not in list of \"AllowedCompilers\". Scripts may not be executed!");
}
else
{
#if DEBUG
// m_log.Debug("[Compiler]: " +
// "Config OK. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is recognized as a valid language.");
#endif
// LANGUAGE IS IN ALLOW-LIST
DefaultCompileLanguage = LanguageMapping[defaultCompileLanguage];
}
// We now have an allow-list, a mapping list, and a default language
}
/// <summary>
/// Create the directory where compiled scripts are stored.
/// </summary>
private void CreateScriptsDirectory()
{
if (!Directory.Exists(ScriptEnginesPath))
{
try
{
Directory.CreateDirectory(ScriptEnginesPath);
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + ScriptEnginesPath + "\": " + ex.ToString());
}
}
if (!Directory.Exists(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString())))
{
try
{
Directory.CreateDirectory(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()));
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()) + "\": " + ex.ToString());
}
}
}
/// <summary>
/// Delete old script files
/// </summary>
private void DeleteOldFiles()
{
foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()), FilePrefix + "_compiled*"))
{
try
{
File.Delete(file);
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying delete old script file \"" + file + "\": " + ex.ToString());
}
}
foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()), FilePrefix + "_source*"))
{
try
{
File.Delete(file);
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying delete old script file \"" + file + "\": " + ex.ToString());
}
}
}
////private ICodeCompiler icc = codeProvider.CreateCompiler();
//public string CompileFromFile(string LSOFileName)
//{
// switch (Path.GetExtension(LSOFileName).ToLower())
// {
// case ".txt":
// case ".lsl":
// Common.ScriptEngineBase.Shared.SendToDebug("Source code is LSL, converting to CS");
// return CompileFromLSLText(File.ReadAllText(LSOFileName));
// case ".cs":
// Common.ScriptEngineBase.Shared.SendToDebug("Source code is CS");
// return CompileFromCSText(File.ReadAllText(LSOFileName));
// default:
// throw new Exception("Unknown script type.");
// }
//}
public string GetCompilerOutput(string assetID)
{
return Path.Combine(ScriptEnginesPath, Path.Combine(
m_scriptEngine.World.RegionInfo.RegionID.ToString(),
FilePrefix + "_compiled_" + assetID + ".dll"));
}
public string GetCompilerOutput(UUID assetID)
{
return GetCompilerOutput(assetID.ToString());
}
/// <summary>
/// Converts script from LSL to CS and calls CompileFromCSText
/// </summary>
/// <param name="Script">LSL script</param>
/// <returns>Filename to .dll assembly</returns>
public void PerformScriptCompile(string Script, string asset, UUID ownerUUID,
out string assembly, out Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap)
{
// m_log.DebugFormat("[Compiler]: Compiling script\n{0}", Script);
IScriptModuleComms comms = m_scriptEngine.World.RequestModuleInterface<IScriptModuleComms>();
linemap = null;
m_warnings.Clear();
assembly = GetCompilerOutput(asset);
if (!Directory.Exists(ScriptEnginesPath))
{
try
{
Directory.CreateDirectory(ScriptEnginesPath);
}
catch (Exception)
{
}
}
if (!Directory.Exists(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString())))
{
try
{
Directory.CreateDirectory(ScriptEnginesPath);
}
catch (Exception)
{
}
}
// Don't recompile if we already have it
// Performing 3 file exists tests for every script can still be slow
if (File.Exists(assembly) && File.Exists(assembly + ".text") && File.Exists(assembly + ".map"))
{
// If we have already read this linemap file, then it will be in our dictionary.
// Don't build another copy of the dictionary (saves memory) and certainly
// don't keep reading the same file from disk multiple times.
if (!m_lineMaps.ContainsKey(assembly))
m_lineMaps[assembly] = ReadMapFile(assembly + ".map");
linemap = m_lineMaps[assembly];
return;
}
if (Script == String.Empty)
{
throw new Exception("Cannot find script assembly and no script text present");
}
enumCompileType language = DefaultCompileLanguage;
if (Script.StartsWith("//c#", true, CultureInfo.InvariantCulture))
language = enumCompileType.cs;
if (Script.StartsWith("//vb", true, CultureInfo.InvariantCulture))
{
language = enumCompileType.vb;
// We need to remove //vb, it won't compile with that
Script = Script.Substring(4, Script.Length - 4);
}
if (Script.StartsWith("//lsl", true, CultureInfo.InvariantCulture))
language = enumCompileType.lsl;
if (Script.StartsWith("//js", true, CultureInfo.InvariantCulture))
language = enumCompileType.js;
if (Script.StartsWith("//yp", true, CultureInfo.InvariantCulture))
language = enumCompileType.yp;
// m_log.DebugFormat("[Compiler]: Compile language is {0}", language);
if (!AllowedCompilers.ContainsKey(language.ToString()))
{
// Not allowed to compile to this language!
string errtext = String.Empty;
errtext += "The compiler for language \"" + language.ToString() + "\" is not in list of allowed compilers. Script will not be executed!";
throw new Exception(errtext);
}
if (m_scriptEngine.World.Permissions.CanCompileScript(ownerUUID, (int)language) == false)
{
// Not allowed to compile to this language!
string errtext = String.Empty;
errtext += ownerUUID + " is not in list of allowed users for this scripting language. Script will not be executed!";
throw new Exception(errtext);
}
string compileScript = Script;
if (language == enumCompileType.lsl)
{
// Its LSL, convert it to C#
LSL_Converter = (ICodeConverter)new CSCodeGenerator(comms, m_insertCoopTerminationCalls);
compileScript = LSL_Converter.Convert(Script);
// copy converter warnings into our warnings.
foreach (string warning in LSL_Converter.GetWarnings())
{
AddWarning(warning);
}
linemap = ((CSCodeGenerator)LSL_Converter).PositionMap;
// Write the linemap to a file and save it in our dictionary for next time.
m_lineMaps[assembly] = linemap;
WriteMapFile(assembly + ".map", linemap);
}
if (language == enumCompileType.yp)
{
// Its YP, convert it to C#
compileScript = YP_Converter.Convert(Script);
}
switch (language)
{
case enumCompileType.cs:
case enumCompileType.lsl:
compileScript = CreateCSCompilerScript(
compileScript,
m_scriptEngine.ScriptClassName,
m_scriptEngine.ScriptBaseClassName,
m_scriptEngine.ScriptBaseClassParameters);
break;
case enumCompileType.vb:
compileScript = CreateVBCompilerScript(
compileScript, m_scriptEngine.ScriptClassName, m_scriptEngine.ScriptBaseClassName);
break;
// case enumCompileType.js:
// compileScript = CreateJSCompilerScript(compileScript, m_scriptEngine.ScriptBaseClassName);
// break;
case enumCompileType.yp:
compileScript = CreateYPCompilerScript(
compileScript, m_scriptEngine.ScriptClassName,m_scriptEngine.ScriptBaseClassName);
break;
}
assembly = CompileFromDotNetText(compileScript, language, asset, assembly);
}
public string[] GetWarnings()
{
return m_warnings.ToArray();
}
private void AddWarning(string warning)
{
if (!m_warnings.Contains(warning))
{
m_warnings.Add(warning);
}
}
// private static string CreateJSCompilerScript(string compileScript)
// {
// compileScript = String.Empty +
// "import OpenSim.Region.ScriptEngine.Shared; import System.Collections.Generic;\r\n" +
// "package SecondLife {\r\n" +
// "class Script extends OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
// compileScript +
// "} }\r\n";
// return compileScript;
// }
private static string CreateCSCompilerScript(
string compileScript, string className, string baseClassName, ParameterInfo[] constructorParameters)
{
compileScript = string.Format(
@"using OpenSim.Region.ScriptEngine.Shared;
using System.Collections.Generic;
namespace SecondLife
{{
public class {0} : {1}
{{
public {0}({2}) : base({3}) {{}}
{4}
}}
}}",
className,
baseClassName,
constructorParameters != null
? string.Join(", ", Array.ConvertAll<ParameterInfo, string>(constructorParameters, pi => pi.ToString()))
: "",
constructorParameters != null
? string.Join(", ", Array.ConvertAll<ParameterInfo, string>(constructorParameters, pi => pi.Name))
: "",
compileScript);
return compileScript;
}
private static string CreateYPCompilerScript(string compileScript, string className, string baseClassName)
{
compileScript = String.Empty +
"using OpenSim.Region.ScriptEngine.Shared.YieldProlog; " +
"using OpenSim.Region.ScriptEngine.Shared; using System.Collections.Generic;\r\n" +
String.Empty + "namespace SecondLife { " +
String.Empty + "public class " + className + " : " + baseClassName + " { \r\n" +
//@"public Script() { } " +
@"static OpenSim.Region.ScriptEngine.Shared.YieldProlog.YP YP=null; " +
@"public " + className + "() { YP= new OpenSim.Region.ScriptEngine.Shared.YieldProlog.YP(); } " +
compileScript +
"} }\r\n";
return compileScript;
}
private static string CreateVBCompilerScript(string compileScript, string className, string baseClassName)
{
compileScript = String.Empty +
"Imports OpenSim.Region.ScriptEngine.Shared: Imports System.Collections.Generic: " +
String.Empty + "NameSpace SecondLife:" +
String.Empty + "Public Class " + className + ": Inherits " + baseClassName +
"\r\nPublic Sub New()\r\nEnd Sub: " +
compileScript +
":End Class :End Namespace\r\n";
return compileScript;
}
/// <summary>
/// Compile .NET script to .Net assembly (.dll)
/// </summary>
/// <param name="Script">CS script</param>
/// <returns>Filename to .dll assembly</returns>
internal string CompileFromDotNetText(string Script, enumCompileType lang, string asset, string assembly)
{
// m_log.DebugFormat("[Compiler]: Compiling to assembly\n{0}", Script);
string ext = "." + lang.ToString();
// Output assembly name
scriptCompileCounter++;
try
{
File.Delete(assembly);
}
catch (Exception e) // NOTLEGIT - Should be just FileIOException
{
throw new Exception("Unable to delete old existing " +
"script-file before writing new. Compile aborted: " +
e.ToString());
}
// DEBUG - write source to disk
if (WriteScriptSourceToDebugFile)
{
string srcFileName = FilePrefix + "_source_" +
Path.GetFileNameWithoutExtension(assembly) + ext;
try
{
File.WriteAllText(Path.Combine(Path.Combine(
ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()),
srcFileName), Script);
}
catch (Exception ex) //NOTLEGIT - Should be just FileIOException
{
m_log.Error("[Compiler]: Exception while " +
"trying to write script source to file \"" +
srcFileName + "\": " + ex.ToString());
}
}
// Do actual compile
CompilerParameters parameters = new CompilerParameters();
parameters.IncludeDebugInformation = true;
string rootPath = AppDomain.CurrentDomain.BaseDirectory;
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenSim.Region.ScriptEngine.Shared.dll"));
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll"));
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenMetaverseTypes.dll"));
if (m_scriptEngine.ScriptReferencedAssemblies != null)
Array.ForEach<string>(
m_scriptEngine.ScriptReferencedAssemblies,
a => parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, a)));
if (lang == enumCompileType.yp)
{
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenSim.Region.ScriptEngine.Shared.YieldProlog.dll"));
}
parameters.GenerateExecutable = false;
parameters.OutputAssembly = assembly;
parameters.IncludeDebugInformation = CompileWithDebugInformation;
//parameters.WarningLevel = 1; // Should be 4?
parameters.TreatWarningsAsErrors = false;
CompilerResults results;
switch (lang)
{
case enumCompileType.vb:
results = VBcodeProvider.CompileAssemblyFromSource(
parameters, Script);
break;
case enumCompileType.cs:
case enumCompileType.lsl:
bool complete = false;
bool retried = false;
do
{
lock (CScodeProvider)
{
results = CScodeProvider.CompileAssemblyFromSource(
parameters, Script);
}
// Deal with an occasional segv in the compiler.
// Rarely, if ever, occurs twice in succession.
// Line # == 0 and no file name are indications that
// this is a native stack trace rather than a normal
// error log.
if (results.Errors.Count > 0)
{
if (!retried && string.IsNullOrEmpty(results.Errors[0].FileName) &&
results.Errors[0].Line == 0)
{
// System.Console.WriteLine("retrying failed compilation");
retried = true;
}
else
{
complete = true;
}
}
else
{
complete = true;
}
} while (!complete);
break;
// case enumCompileType.js:
// results = JScodeProvider.CompileAssemblyFromSource(
// parameters, Script);
// break;
case enumCompileType.yp:
results = YPcodeProvider.CompileAssemblyFromSource(
parameters, Script);
break;
default:
throw new Exception("Compiler is not able to recongnize " +
"language type \"" + lang.ToString() + "\"");
}
// foreach (Type type in results.CompiledAssembly.GetTypes())
// {
// foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static))
// {
// m_log.DebugFormat("[COMPILER]: {0}.{1}", type.FullName, method.Name);
// }
// }
//
// WARNINGS AND ERRORS
//
bool hadErrors = false;
string errtext = String.Empty;
if (results.Errors.Count > 0)
{
foreach (CompilerError CompErr in results.Errors)
{
string severity = CompErr.IsWarning ? "Warning" : "Error";
KeyValuePair<int, int> errorPos;
// Show 5 errors max, but check entire list for errors
if (severity == "Error")
{
// C# scripts will not have a linemap since theres no line translation involved.
if (!m_lineMaps.ContainsKey(assembly))
errorPos = new KeyValuePair<int, int>(CompErr.Line, CompErr.Column);
else
errorPos = FindErrorPosition(CompErr.Line, CompErr.Column, m_lineMaps[assembly]);
string text = CompErr.ErrorText;
// Use LSL type names
if (lang == enumCompileType.lsl)
text = ReplaceTypes(CompErr.ErrorText);
// The Second Life viewer's script editor begins
// countingn lines and columns at 0, so we subtract 1.
errtext += String.Format("({0},{1}): {4} {2}: {3}\n",
errorPos.Key - 1, errorPos.Value - 1,
CompErr.ErrorNumber, text, severity);
hadErrors = true;
}
}
}
if (hadErrors)
{
throw new Exception(errtext);
}
// On today's highly asynchronous systems, the result of
// the compile may not be immediately apparent. Wait a
// reasonable amount of time before giving up on it.
if (!File.Exists(assembly))
{
for (int i = 0; i < 20 && !File.Exists(assembly); i++)
{
System.Threading.Thread.Sleep(250);
}
// One final chance...
if (!File.Exists(assembly))
{
errtext = String.Empty;
errtext += "No compile error. But not able to locate compiled file.";
throw new Exception(errtext);
}
}
// m_log.DebugFormat("[Compiler] Compiled new assembly "+
// "for {0}", asset);
// Because windows likes to perform exclusive locks, we simply
// write out a textual representation of the file here
//
// Read the binary file into a buffer
//
FileInfo fi = new FileInfo(assembly);
if (fi == null)
{
errtext = String.Empty;
errtext += "No compile error. But not able to stat file.";
throw new Exception(errtext);
}
Byte[] data = new Byte[fi.Length];
try
{
FileStream fs = File.Open(assembly, FileMode.Open, FileAccess.Read);
fs.Read(data, 0, data.Length);
fs.Close();
}
catch (Exception)
{
errtext = String.Empty;
errtext += "No compile error. But not able to open file.";
throw new Exception(errtext);
}
// Convert to base64
//
string filetext = System.Convert.ToBase64String(data);
Byte[] buf = Encoding.ASCII.GetBytes(filetext);
FileStream sfs = File.Create(assembly + ".text");
sfs.Write(buf, 0, buf.Length);
sfs.Close();
return assembly;
}
private class kvpSorter : IComparer<KeyValuePair<int, int>>
{
public int Compare(KeyValuePair<int, int> a,
KeyValuePair<int, int> b)
{
return a.Key.CompareTo(b.Key);
}
}
public static KeyValuePair<int, int> FindErrorPosition(int line,
int col, Dictionary<KeyValuePair<int, int>,
KeyValuePair<int, int>> positionMap)
{
if (positionMap == null || positionMap.Count == 0)
return new KeyValuePair<int, int>(line, col);
KeyValuePair<int, int> ret = new KeyValuePair<int, int>();
if (positionMap.TryGetValue(new KeyValuePair<int, int>(line, col),
out ret))
return ret;
List<KeyValuePair<int, int>> sorted =
new List<KeyValuePair<int, int>>(positionMap.Keys);
sorted.Sort(new kvpSorter());
int l = 1;
int c = 1;
foreach (KeyValuePair<int, int> cspos in sorted)
{
if (cspos.Key >= line)
{
if (cspos.Key > line)
return new KeyValuePair<int, int>(l, c);
if (cspos.Value > col)
return new KeyValuePair<int, int>(l, c);
c = cspos.Value;
if (c == 0)
c++;
}
else
{
l = cspos.Key;
}
}
return new KeyValuePair<int, int>(l, c);
}
string ReplaceTypes(string message)
{
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString",
"string");
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger",
"integer");
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat",
"float");
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.list",
"list");
return message;
}
private static void WriteMapFile(string filename, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap)
{
string mapstring = String.Empty;
foreach (KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> kvp in linemap)
{
KeyValuePair<int, int> k = kvp.Key;
KeyValuePair<int, int> v = kvp.Value;
mapstring += String.Format("{0},{1},{2},{3}\n", k.Key, k.Value, v.Key, v.Value);
}
Byte[] mapbytes = Encoding.ASCII.GetBytes(mapstring);
FileStream mfs = File.Create(filename);
mfs.Write(mapbytes, 0, mapbytes.Length);
mfs.Close();
}
private static Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> ReadMapFile(string filename)
{
Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap;
try
{
StreamReader r = File.OpenText(filename);
linemap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>();
string line;
while ((line = r.ReadLine()) != null)
{
String[] parts = line.Split(new Char[] { ',' });
int kk = System.Convert.ToInt32(parts[0]);
int kv = System.Convert.ToInt32(parts[1]);
int vk = System.Convert.ToInt32(parts[2]);
int vv = System.Convert.ToInt32(parts[3]);
KeyValuePair<int, int> k = new KeyValuePair<int, int>(kk, kv);
KeyValuePair<int, int> v = new KeyValuePair<int, int>(vk, vv);
linemap[k] = v;
}
}
catch
{
linemap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>();
}
return linemap;
}
}
}
|
justinccdev/opensim
|
OpenSim/Region/ScriptEngine/Shared/CodeTools/Compiler.cs
|
C#
|
bsd-3-clause
| 36,718 |
from django.db import models
from datetime import datetime
from delegate import DelegateManager, delegate
from signalqueue.worker.base import QueueBase
#from signalqueue.utils import logg
class SignalQuerySet(models.query.QuerySet):
"""
SignalQuerySet is a QuerySet that works as a signalqueue backend.
The actual QueueBase override methods are implemented here and delegated to
SignalManager, which is a DelegateManager subclass with the QueueBase
implementation "mixed in".
Since you can't nakedly instantiate managers outside of a model
class, we use a proxy class to hand off SignalQuerySet's delegated
manager to the queue config stuff. See the working implementation in
signalqueue.worker.backends.DatabaseQueueProxy for details.
"""
@delegate
def queued(self, enqueued=True):
return self.filter(queue_name=self.queue_name, enqueued=enqueued).order_by("createdate")
@delegate
def ping(self):
return True
@delegate
def push(self, value):
self.get_or_create(queue_name=self.queue_name, value=value, enqueued=True)
@delegate
def pop(self):
""" Dequeued signals are marked as such (but not deleted) by default. """
out = self.queued()[0]
out.enqueued = False
out.save()
return str(out.value)
def count(self, enqueued=True):
""" This override can't be delegated as the super() call isn't portable. """
return super(self.__class__, self.all().queued(enqueued=enqueued)).count()
@delegate
def clear(self):
self.queued().update(enqueued=False)
@delegate
def values(self, floor=0, ceil=-1):
if floor < 1:
floor = 0
if ceil < 1:
ceil = self.count()
out = self.queued()[floor:ceil]
return [str(value[0]) for value in out.values_list('value')]
@delegate
def __repr__(self):
return "[%s]" % ",".join([str(value[0]) for value in self.values_list('value')])
@delegate
def __str__(self):
return repr(self)
def __unicode__(self):
import json as library_json
return u"%s" % library_json.dumps(library_json.loads(repr(self)), indent=4)
class SignalManager(DelegateManager, QueueBase):
__queryset__ = SignalQuerySet
def __init__(self, *args, **kwargs):
self.runmode = kwargs.get('runmode', 4)
QueueBase.__init__(self, *args, **kwargs)
DelegateManager.__init__(self, *args, **kwargs)
def count(self, enqueued=True):
return self.queued(enqueued=enqueued).count()
def _get_queue_name(self):
if self._queue_name:
return self._queue_name
return None
def _set_queue_name(self, queue_name):
self._queue_name = queue_name
self.__queryset__.queue_name = queue_name
queue_name = property(_get_queue_name, _set_queue_name)
class EnqueuedSignal(models.Model):
class Meta:
abstract = False
verbose_name = "Enqueued Signal"
verbose_name_plural = "Enqueued Signals"
objects = SignalManager()
keys = set(
('signal', 'sender', 'enqueue_runmode'))
createdate = models.DateTimeField("Created on",
default=datetime.now,
blank=True,
null=True,
editable=False)
enqueued = models.BooleanField("Enqueued",
default=True,
editable=True)
queue_name = models.CharField(verbose_name="Queue Name",
max_length=255, db_index=True,
default="default",
unique=False,
blank=True,
null=False)
value = models.TextField(verbose_name="Serialized Signal Value",
editable=False,
unique=False,
db_index=True,
blank=True,
null=True)
def _get_struct(self):
if self.value:
from signalqueue.utils import json, ADict
return ADict(
json.loads(self.value))
return ADict()
def _set_struct(self, newstruct):
if self.keys.issuperset(newstruct.keys()):
from signalqueue.utils import json
self.value = json.dumps(newstruct)
struct = property(_get_struct, _set_struct)
def __repr__(self):
if self.value:
return str(self.value)
return "{'instance':null}"
def __str__(self):
return repr(self)
def __unicode__(self):
if self.value:
import json as library_json
return u"%s" % library_json.dumps(
library_json.loads(repr(self)),
indent=4)
return u"{'instance':null}"
|
Steckelfisch/django-signalqueue
|
signalqueue/models.py
|
Python
|
bsd-3-clause
| 4,742 |
/* Copyright 2021. Uecker Lab. University Medical Center Göttingen.
* All rights reserved. Use of this source code is governed by
* a BSD-style license which can be found in the LICENSE file.
*
* Authors: Moritz Blumenthal
*/
#include <complex.h>
#include <stdbool.h>
#include <assert.h>
#include <math.h>
#include "num/multind.h"
#include "num/flpmath.h"
#include "num/ops_p.h"
#include "num/ops.h"
#include "num/iovec.h"
#ifdef USE_CUDA
#include "num/gpuops.h"
#endif
#include "misc/misc.h"
#include "proj.h"
/**
* We write projections to a set M as proximal functions,
* i.e. f(x) = 0 if x in M and infinity else.
*
* Proximal function of f is defined as
* (prox_f)(z) = arg min_x 0.5 || z - x ||_2^2 + f(x)
*
* (prox_{mu f})(z) = arg min_x 0.5 || z - x ||_2^2 + mu f(x)
*/
/**
* Data for computing proj_pos_real_fun
*
* @param N number of dimensions
* @param dims dimensions
*/
struct proj_pos_real_s {
INTERFACE(operator_data_t);
long N;
const long* dims;
float min;
};
DEF_TYPEID(proj_pos_real_s);
static void proj_pos_real_fun(const operator_data_t* _data, unsigned int N, void* args[N])
{
assert(2 == N);
const auto data = CAST_DOWN(proj_pos_real_s, _data);
complex float* dst = args[0];
const complex float* src = args[1];
md_zsmax(data->N, data->dims, dst, src, data->min);
}
static void proj_pos_real_apply(const operator_data_t* _data, float mu, complex float* dst, const complex float* src)
{
UNUSED(mu);
proj_pos_real_fun(_data, 2, MAKE_ARRAY((void*)dst, (void*)src));
}
static void proj_pos_real_del(const operator_data_t* _data)
{
const auto data = CAST_DOWN(proj_pos_real_s, _data);
xfree(data->dims);
xfree(data);
}
/**
* Create operator projecting inputs to positive real values
*
* @param N
* @param dims
*/
const struct operator_p_s* operator_project_pos_real_create(long N, const long dims[N])
{
PTR_ALLOC(struct proj_pos_real_s, data);
SET_TYPEID(proj_pos_real_s, data);
data->N = N;
PTR_ALLOC(long[N], ndims);
md_copy_dims(N, *ndims, dims);
data->dims = *PTR_PASS(ndims);
data->min = 0;
return operator_p_create(N, dims, N, dims, CAST_UP(PTR_PASS(data)), proj_pos_real_apply, proj_pos_real_del);
}
/**
* Create operator projecting inputs to real values larger min
*
* @param N
* @param dims
* @param min
*/
const struct operator_p_s* operator_project_min_real_create(long N, const long dims[N], float min)
{
PTR_ALLOC(struct proj_pos_real_s, data);
SET_TYPEID(proj_pos_real_s, data);
data->N = N;
PTR_ALLOC(long[N], ndims);
md_copy_dims(N, *ndims, dims);
data->dims = *PTR_PASS(ndims);
data->min = min;
return operator_p_create(N, dims, N, dims, CAST_UP(PTR_PASS(data)), proj_pos_real_apply, proj_pos_real_del);
}
/**
* Data for computing proj_mean_free_fun
*
* @param N number of dimensions
* @param dims dimensions
* @param bflag independent dimensions
*/
struct proj_mean_free_s {
INTERFACE(operator_data_t);
long N;
const long* dims;
unsigned long bflag;
};
DEF_TYPEID(proj_mean_free_s);
static void proj_mean_free_fun(const operator_data_t* _data, unsigned int N, void* args[N])
{
assert(2 == N);
const auto data = CAST_DOWN(proj_mean_free_s, _data);
complex float* dst = args[0];
const complex float* src = args[1];
long batch_dims[data->N];
long mf_dims[data->N];
md_select_dims(data->N, data->bflag, batch_dims, data->dims);
md_select_dims(data->N, ~data->bflag, mf_dims, data->dims);
complex float* tmp = md_alloc_sameplace(data->N, batch_dims, CFL_SIZE, dst);
md_zsum(data->N, data->dims, ~data->bflag, tmp, src);
md_zsmul(data->N, batch_dims, tmp, tmp, 1./(float)md_calc_size(data->N, mf_dims));
md_zsub2(data->N, data->dims, MD_STRIDES(data->N, data->dims, CFL_SIZE), dst, MD_STRIDES(data->N, data->dims, CFL_SIZE), src, MD_STRIDES(data->N, batch_dims, CFL_SIZE), tmp);
md_free(tmp);
}
static void proj_mean_free_apply(const operator_data_t* _data, float mu, complex float* dst, const complex float* src)
{
UNUSED(mu);
proj_mean_free_fun(_data, 2, MAKE_ARRAY((void*)dst, (void*)src));
}
static void proj_mean_free_del(const operator_data_t* _data)
{
const auto data = CAST_DOWN(proj_mean_free_s, _data);
xfree(data->dims);
xfree(data);
}
/**
* Create operator subtracting the mean value
* Dimensions selected by bflag stay independent
*
* @param N
* @param dims
* @param bflag batch dims -> dimensions which stay independent
*/
const struct operator_p_s* operator_project_mean_free_create(long N, const long dims[N], unsigned long bflag)
{
PTR_ALLOC(struct proj_mean_free_s, data);
SET_TYPEID(proj_mean_free_s, data);
data->N = N;
PTR_ALLOC(long[N], ndims);
md_copy_dims(N, *ndims, dims);
data->dims = *PTR_PASS(ndims);
data->bflag = bflag;
return operator_p_create(N, dims, N , dims, CAST_UP(PTR_PASS(data)), proj_mean_free_apply, proj_mean_free_del);
}
/**
* Data for computing proj_sphere_fun
*
* @param N number of dimensions
* @param dims dimensions
* @param bflag independent dimensions
*/
struct proj_sphere_s {
INTERFACE(operator_data_t);
long N;
const long* dims;
unsigned long bflag;
};
DEF_TYPEID(proj_sphere_s);
static void proj_sphere_real_fun(const struct operator_data_s* _data, unsigned int N, void* args[N])
{
assert(2 == N);
assert(args[0] != args[1]);
const auto data = CAST_DOWN(proj_sphere_s, _data);
complex float* dst = args[0];
const complex float* src = args[1];
long bdims[data->N];
md_select_dims(data->N, data->bflag, bdims, data->dims);
complex float* tmp = md_alloc_sameplace(data->N, bdims, CFL_SIZE, dst);
md_zrmul(data->N, data->dims, dst, src, src);
md_zsum(data->N, data->dims, ~data->bflag, tmp, dst);
long rdims[data->N + 1];
long brdims[data->N + 1];
rdims[0] = 2;
brdims[0] = 2;
md_copy_dims(data->N, rdims + 1, data->dims);
md_copy_dims(data->N, brdims + 1, bdims);
md_sqrt(data->N + 1, brdims, (float*)tmp, (float*)tmp);
md_copy2(data->N, data->dims, MD_STRIDES(data->N, data->dims, CFL_SIZE), dst, MD_STRIDES(data->N, bdims, CFL_SIZE), tmp, CFL_SIZE);
md_div(data->N + 1, rdims, (float*)dst, (float*)src, (float*)dst);
md_free(tmp);
}
static void proj_sphere_complex_fun(const struct operator_data_s* _data, unsigned int N, void* args[N])
{
assert(2 == N);
assert(args[0] != args[1]);
const auto data = CAST_DOWN(proj_sphere_s, _data);
complex float* dst = args[0];
const complex float* src = args[1];
long bdims[data->N];
md_select_dims(data->N, data->bflag, bdims, data->dims);
complex float* tmp = md_alloc_sameplace(data->N, bdims, CFL_SIZE, dst);
md_zmulc(data->N, data->dims, dst, src, src);
md_zsum(data->N, data->dims, ~data->bflag, tmp, dst);
md_clear(data->N, bdims, dst, FL_SIZE);
md_real(data->N, bdims, (float*)dst, tmp); // I don't trust zmulc to have vanishing imag on gpu
md_sqrt(data->N, bdims, (float*)tmp, (float*)dst);//propably more efficient than md_zsqrt
md_clear(data->N, data->dims, dst, CFL_SIZE);
md_copy2(data->N, data->dims, MD_STRIDES(data->N, data->dims, CFL_SIZE), dst, MD_STRIDES(data->N, bdims, FL_SIZE), tmp, FL_SIZE);
md_zdiv(data->N, data->dims, dst, src, dst);
md_free(tmp);
}
static void proj_sphere_real_apply(const operator_data_t* _data, float mu, complex float* dst, const complex float* src)
{
UNUSED(mu);
proj_sphere_real_fun(_data, 2, MAKE_ARRAY((void*)dst, (void*)src));
}
static void proj_sphere_complex_apply(const operator_data_t* _data, float mu, complex float* dst, const complex float* src)
{
UNUSED(mu);
proj_sphere_complex_fun(_data, 2, MAKE_ARRAY((void*)dst, (void*)src));
}
static void proj_sphere_del(const operator_data_t* _data)
{
const auto data = CAST_DOWN(proj_sphere_s, _data);
xfree(data->dims);
xfree(data);
}
/**
* Create operator scaling inputs to unit sphere
*
* @param N
* @param dims
* @param bflag
* @param real if true, real and imaginary part are handeled independently (as bflag is set for dimension real/imag)
*/
const struct operator_p_s* operator_project_sphere_create(long N, const long dims[N], unsigned long bflag, bool real)
{
PTR_ALLOC(struct proj_sphere_s, data);
SET_TYPEID(proj_sphere_s, data);
data->N = N;
PTR_ALLOC(long[N], ndims);
md_copy_dims(N, *ndims, dims);
data->dims = *PTR_PASS(ndims);
data->bflag = bflag;
return operator_p_create(N, dims, N , dims, CAST_UP(PTR_PASS(data)), (real ? proj_sphere_real_apply : proj_sphere_complex_apply), proj_sphere_del);
}
/**
* Create operator projectiong to mean free unit sphere by first subtrct the mean and scale to unitsphere afterwards
* Real and imaginary part are considered independently
*
* @param N
* @param dims
* @param bflag
* @param real if real, real and imaginary part are handeled independently (as bflag is set for dimension real/imag)
*/
const struct operator_p_s* operator_project_mean_free_sphere_create(long N, const long dims[N], unsigned long bflag, bool real)
{
auto op_p_mean_free = operator_project_mean_free_create(N, dims, bflag);
auto op_p_sphere = operator_project_sphere_create(N, dims, bflag, real);
auto op_sphere = operator_p_bind(op_p_sphere, 1.);
auto result = operator_p_pst_chain(op_p_mean_free, op_sphere);
operator_p_free(op_p_mean_free);
operator_p_free(op_p_sphere);
operator_free(op_sphere);
return result;
}
|
mrirecon/bart
|
src/iter/proj.c
|
C
|
bsd-3-clause
| 9,222 |
<?php
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;
/* @var $this \yii\web\View */
/* @var $content string */
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title>EasyDelivery</title>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<div class="wrap">
<?php
NavBar::begin([
'brandLabel' => 'EasyDelivery',
'brandUrl' => Yii::$app->homeUrl,
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
],
]);
$menu = [
['label' => 'Home', 'url' => '/site'],
];
$session = \Yii::$app->session;
if($session->has('admin'))
{
$menu = [
['label' => 'Locales', 'url' => '/admin/local'],
['label' => 'Productos', 'url' => '/admin/producto'],
['label' => 'Transporte', 'url' => '/admin/transporte'],
['label' => 'Reporte', 'url' => '/admin/reporte'],
['label' => 'Logout (' . $session['admin']->razon_social . ')',
'url' => '/admin/empresa/logout',
'linkOptions' => ['data-method' => 'post']],
];
}
else if($session->has('local'))
{
$menu = [
['label' => 'Productos', 'url' => '/admin/local/productos'],
['label' => 'Asignar Pedidos', 'url' => '/admin/local/asignar'],
['label' => 'Pedidos En Camino', 'url' => '/admin/local/pedidos'],
['label' => 'Logout',
'url' => '/admin/local/logout',
'linkOptions' => ['data-method' => 'post']],
];
}
else
{
$menu[] = ['label' => 'Empresa', 'url' => '/admin/empresa/superlogin'];
$menu[] = ['label' => 'Local', 'url' => '/admin/local/login'];
}
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => $menu,
]);
NavBar::end();
?>
<div class="container">
<?= Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
<?= $content ?>
</div>
</div>
<footer class="footer">
<div class="container">
<p class="pull-left">© EasyDelivery <?= date('Y') ?></p>
<p class="pull-right"><?= Yii::powered() ?></p>
</div>
</footer>
<?php $this->endBody() ?>
<script type="text/javascript" src="/js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDjzEmhSjvEf09A___LMxgDhm-fL0cWacA&sensor=TRUE"></script>
<script type="text/javascript" src="/js/map.js"></script>
<script type="text/javascript" src="/js/mapSeguimientoLocal.js"></script>
<script type="text/javascript">
$("[name=\"Empresa[ruc]\"]").keyup(function(){
$.get("ruc?ruc="+$("[name=\"Empresa[ruc]\"]").val(), function(data){
data = JSON.parse(data);
if(!data.status)
{
//alert("No se encontró ese ruc en el sistema");
}
else
{
$("[name=\"Empresa[razon_social]\"]").val(data.respuesta.razon_social);
$("[name=\"Empresa[direccion]\"]").val(data.respuesta.direccion);
}
});
});
document.onload = initializeMap();
</script>
</body>
</html>
<?php $this->endPage() ?>
|
sburgos/easydelivery
|
modules/admin/views/layouts/admin.php
|
PHP
|
bsd-3-clause
| 3,539 |
/*-------------------------------------
| Floating Box
-------------------------------------*/
$(function() {
var $sidebar = $("#sidebar"),
$window = $(window),
offset = $sidebar.offset(),
topPadding = 15;
$window.scroll(function() {
if ($window.scrollTop() > offset.top) {
$sidebar.stop().animate({
marginTop: $window.scrollTop() - offset.top + topPadding
});
} else {
$sidebar.stop().animate({
marginTop: 0
});
}
});
});
// <!-- FOR STICKY MENU -->
// $(document).ready(function() {
// var stickyNavTop = $('#mainNav').offset().top;
// var stickyNav = function(){
// var scrollTop = $(window).scrollTop();
// if (scrollTop > stickyNavTop) {
// $('#mainNav').addClass('sticky');
// } else {
// $('#mainNav').removeClass('sticky');
// }
// };
// stickyNav();
// $(window).scroll(function() {
// stickyNav();
// });
// });
|
jamie-sholberg/pete-blog
|
_js/scripts.js
|
JavaScript
|
bsd-3-clause
| 1,007 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using Tao.OpenGl;
using Tao.Platform.Windows;
using ICSharpCode.SharpZipLib.Zip;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenMetaverse.Imaging;
using OpenMetaverse.Rendering;
namespace PrimWorkshop
{
public partial class frmBrowser : Form
{
const float DEG_TO_RAD = 0.0174532925f;
const uint TERRAIN_START = (uint)Int32.MaxValue + 1;
ContextMenu ExportPrimMenu;
ContextMenu ExportTerrainMenu;
GridClient Client;
Camera Camera;
Dictionary<uint, Primitive> RenderFoliageList = new Dictionary<uint, Primitive>();
Dictionary<uint, RenderablePrim> RenderPrimList = new Dictionary<uint, RenderablePrim>();
Dictionary<UUID, GlacialComponents.Controls.GLItem> DownloadList = new Dictionary<UUID, GlacialComponents.Controls.GLItem>();
EventHandler IdleEvent;
System.Timers.Timer ProgressTimer;
int TotalPrims;
// Textures
TexturePipeline TextureDownloader;
Dictionary<UUID, TextureInfo> Textures = new Dictionary<UUID, TextureInfo>();
// Terrain
float MaxHeight = 0.1f;
TerrainPatch[,] Heightmap;
HeightmapLookupValue[] LookupHeightTable;
// Picking globals
bool Clicked = false;
int ClickX = 0;
int ClickY = 0;
uint LastHit = 0;
//
Vector3 PivotPosition = Vector3.Zero;
bool Pivoting = false;
Point LastPivot;
//
const int SELECT_BUFSIZE = 512;
uint[] SelectBuffer = new uint[SELECT_BUFSIZE];
//
NativeMethods.Message msg;
private bool AppStillIdle
{
get { return !NativeMethods.PeekMessage(out msg, IntPtr.Zero, 0, 0, 0); }
}
/// <summary>
/// Default constructor
/// </summary>
public frmBrowser()
{
InitializeComponent();
// Setup OpenGL
glControl.InitializeContexts();
glControl.SwapBuffers();
glControl.MouseWheel += new MouseEventHandler(glControl_MouseWheel);
// Login server URLs
cboServer.Items.Add(Settings.AGNI_LOGIN_SERVER);
cboServer.Items.Add(Settings.ADITI_LOGIN_SERVER);
cboServer.Items.Add("http://osgrid.org:8002/");
cboServer.SelectedIndex = 0;
// Context menus
ExportPrimMenu = new ContextMenu();
ExportPrimMenu.MenuItems.Add("Download", new EventHandler(DownloadMenu_Clicked));
ExportPrimMenu.MenuItems.Add("Download All Objects", new EventHandler(DownloadAllMenu_Clicked));
ExportTerrainMenu = new ContextMenu();
ExportTerrainMenu.MenuItems.Add("Teleport", new EventHandler(TeleportMenu_Clicked));
ExportTerrainMenu.MenuItems.Add("Export Terrain", new EventHandler(ExportTerrainMenu_Clicked));
ExportTerrainMenu.MenuItems.Add("Import Object", new EventHandler(ImportObjectMenu_Clicked));
ExportTerrainMenu.MenuItems.Add("Import Sim", new EventHandler(ImportSimMenu_Clicked));
// Setup a timer for updating the progress bar
ProgressTimer = new System.Timers.Timer(250);
ProgressTimer.Elapsed +=
delegate(object sender, System.Timers.ElapsedEventArgs e)
{
UpdatePrimProgress();
};
ProgressTimer.Start();
IdleEvent = new EventHandler(Application_Idle);
Application.Idle += IdleEvent;
// Show a flat sim before login so the screen isn't so boring
InitHeightmap();
InitOpenGL();
InitCamera();
glControl_Resize(null, null);
}
private void InitLists()
{
TotalPrims = 0;
lock (Textures)
{
foreach (TextureInfo tex in Textures.Values)
{
int id = tex.ID;
Gl.glDeleteTextures(1, ref id);
}
Textures.Clear();
}
lock (RenderPrimList) RenderPrimList.Clear();
lock (RenderFoliageList) RenderFoliageList.Clear();
}
private void InitializeObjects()
{
InitLists();
if (DownloadList != null)
lock (DownloadList)
DownloadList.Clear();
// Initialize the SL client
Client = new GridClient();
Client.Settings.MULTIPLE_SIMS = false;
Client.Settings.ALWAYS_DECODE_OBJECTS = true;
Client.Settings.ALWAYS_REQUEST_OBJECTS = true;
Client.Settings.SEND_AGENT_UPDATES = true;
Client.Settings.USE_TEXTURE_CACHE = true;
Client.Settings.TEXTURE_CACHE_DIR = Application.StartupPath + System.IO.Path.DirectorySeparatorChar + "cache";
Client.Settings.ALWAYS_REQUEST_PARCEL_ACL = false;
Client.Settings.ALWAYS_REQUEST_PARCEL_DWELL = false;
// Crank up the throttle on texture downloads
Client.Throttle.Texture = 446000.0f;
// FIXME: Write our own avatar tracker so we don't double store prims
Client.Settings.OBJECT_TRACKING = false; // We use our own object tracking system
Client.Settings.AVATAR_TRACKING = true; //but we want to use the libsl avatar system
Client.Network.OnLogin += new NetworkManager.LoginCallback(Network_OnLogin);
Client.Network.OnDisconnected += new NetworkManager.DisconnectedCallback(Network_OnDisconnected);
Client.Network.OnCurrentSimChanged += new NetworkManager.CurrentSimChangedCallback(Network_OnCurrentSimChanged);
Client.Network.OnEventQueueRunning += new NetworkManager.EventQueueRunningCallback(Network_OnEventQueueRunning);
Client.Objects.OnNewPrim += new ObjectManager.NewPrimCallback(Objects_OnNewPrim);
Client.Objects.OnNewFoliage += new ObjectManager.NewFoliageCallback(Objects_OnNewFoliage);
Client.Objects.OnObjectKilled += new ObjectManager.KillObjectCallback(Objects_OnObjectKilled);
Client.Terrain.OnLandPatch += new TerrainManager.LandPatchCallback(Terrain_OnLandPatch);
Client.Parcels.OnSimParcelsDownloaded += new ParcelManager.SimParcelsDownloaded(Parcels_OnSimParcelsDownloaded);
// Initialize the texture download pipeline
if (TextureDownloader != null)
TextureDownloader.Shutdown();
TextureDownloader = new TexturePipeline(Client);
TextureDownloader.OnDownloadFinished += new TexturePipeline.DownloadFinishedCallback(TextureDownloader_OnDownloadFinished);
TextureDownloader.OnDownloadProgress += new TexturePipeline.DownloadProgressCallback(TextureDownloader_OnDownloadProgress);
// Initialize the camera object
InitCamera();
// Setup the libsl camera to match our Camera struct
UpdateCamera();
glControl_Resize(null, null);
/*
// Enable lighting
Gl.glEnable(Gl.GL_LIGHTING);
Gl.glEnable(Gl.GL_LIGHT0);
float[] lightPosition = { 128.0f, 64.0f, 96.0f, 0.0f };
Gl.glLightfv(Gl.GL_LIGHT0, Gl.GL_POSITION, lightPosition);
// Setup ambient property
float[] ambientLight = { 0.2f, 0.2f, 0.2f, 0.0f };
Gl.glLightfv(Gl.GL_LIGHT0, Gl.GL_AMBIENT, ambientLight);
// Setup specular property
float[] specularLight = { 0.5f, 0.5f, 0.5f, 0.0f };
Gl.glLightfv(Gl.GL_LIGHT0, Gl.GL_SPECULAR, specularLight);
*/
}
private void InitOpenGL()
{
Gl.glShadeModel(Gl.GL_SMOOTH);
Gl.glClearDepth(1.0f);
Gl.glEnable(Gl.GL_DEPTH_TEST);
Gl.glDepthMask(Gl.GL_TRUE);
Gl.glDepthFunc(Gl.GL_LEQUAL);
Gl.glHint(Gl.GL_PERSPECTIVE_CORRECTION_HINT, Gl.GL_NICEST);
}
private void InitHeightmap()
{
// Initialize the heightmap
Heightmap = new TerrainPatch[16, 16];
for (int y = 0; y < 16; y++)
{
for (int x = 0; x < 16; x++)
{
Heightmap[y, x] = new TerrainPatch();
Heightmap[y, x].Data = new float[16 * 16];
}
}
// Speed up terrain exports with a lookup table
LookupHeightTable = new HeightmapLookupValue[256 * 256];
for (int i = 0; i < 256; i++)
{
for (int j = 0; j < 256; j++)
{
LookupHeightTable[i + (j * 256)] = new HeightmapLookupValue(i + (j * 256), ((float)i * ((float)j / 127.0f)));
}
}
Array.Sort<HeightmapLookupValue>(LookupHeightTable);
}
private void InitCamera()
{
Camera = new Camera();
Camera.Position = new Vector3(128f, -192f, 90f);
Camera.FocalPoint = new Vector3(128f, 128f, 0f);
Camera.Zoom = 1.0d;
Camera.Far = 512.0d;
}
private void UpdatePrimProgress()
{
if (this.InvokeRequired)
{
BeginInvoke((MethodInvoker)delegate() { UpdatePrimProgress(); });
}
else
{
try
{
if (RenderPrimList != null && RenderFoliageList != null)
{
int count = RenderPrimList.Count + RenderFoliageList.Count;
lblPrims.Text = String.Format("Prims: {0} / {1}", count, TotalPrims);
progPrims.Maximum = (TotalPrims > count) ? TotalPrims : count;
progPrims.Value = count;
}
else
{
lblPrims.Text = String.Format("Prims: 0 / {0}", TotalPrims);
progPrims.Maximum = TotalPrims;
progPrims.Value = 0;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
private void UpdateCamera()
{
if (Client != null)
{
Client.Self.Movement.Camera.LookAt(Camera.Position, Camera.FocalPoint);
Client.Self.Movement.Camera.Far = (float)Camera.Far;
}
Gl.glPushMatrix();
Gl.glMatrixMode(Gl.GL_PROJECTION);
Gl.glLoadIdentity();
SetPerspective();
Gl.glMatrixMode(Gl.GL_MODELVIEW);
Gl.glPopMatrix();
}
private bool ExportObject(RenderablePrim parent, string fileName, out int prims, out int textures, out string error)
{
// Build a list of primitives (parent+children) to export
List<Primitive> primList = new List<Primitive>();
primList.Add(parent.Prim);
lock (RenderPrimList)
{
foreach (RenderablePrim render in RenderPrimList.Values)
{
if (render.Prim.ParentID == parent.Prim.LocalID)
primList.Add(render.Prim);
}
}
return ExportObjects(primList, fileName, out prims, out textures, out error);
}
private bool ExportSim(string fileName, out int prims, out int textures, out string error)
{
// Add all of the prims in this sim to the export list
List<Primitive> primList = new List<Primitive>();
lock (RenderPrimList)
{
foreach (RenderablePrim render in RenderPrimList.Values)
{
primList.Add(render.Prim);
}
}
return ExportObjects(primList, fileName, out prims, out textures, out error);
}
private bool ExportObjects(List<Primitive> primList, string fileName, out int prims, out int textures, out string error)
{
List<UUID> textureList = new List<UUID>();
prims = 0;
textures = 0;
// Write the LLSD to the hard drive in XML format
string output = LLSDParser.SerializeXmlString(Helpers.PrimListToLLSD(primList));
try
{
// Create a temporary directory
string tempPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName());
Directory.CreateDirectory(tempPath);
// Write the prim XML file
File.WriteAllText(System.IO.Path.Combine(tempPath, "prims.xml"), output);
prims = primList.Count;
// Build a list of all the referenced textures in this prim list
foreach (Primitive prim in primList)
{
for (int i = 0; i < prim.Textures.FaceTextures.Length; i++)
{
Primitive.TextureEntryFace face = prim.Textures.FaceTextures[i];
if (face != null && face.TextureID != UUID.Zero && face.TextureID != Primitive.TextureEntry.WHITE_TEXTURE)
{
if (!textureList.Contains(face.TextureID))
textureList.Add(face.TextureID);
}
}
}
// Copy all of relevant textures from the cache to the temp directory
foreach (UUID texture in textureList)
{
string tempFileName = Client.Assets.Cache.ImageFileName(texture);
if (!String.IsNullOrEmpty(tempFileName))
{
File.Copy(tempFileName, System.IO.Path.Combine(tempPath, texture.ToString() + ".jp2"));
++textures;
}
else
{
Console.WriteLine("Missing texture file during download: " + texture.ToString());
}
}
// Zip up the directory
string[] filenames = Directory.GetFiles(tempPath);
using (ZipOutputStream s = new ZipOutputStream(File.Create(fileName)))
{
s.SetLevel(9);
byte[] buffer = new byte[4096];
foreach (string file in filenames)
{
ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
s.Finish();
s.Close();
}
error = null;
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
private List<Primitive> ImportObjects(string fileName, out string tempPath, out string error)
{
tempPath = null;
error = null;
string primFile = null;
try
{
// Create a temporary directory
tempPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName());
Directory.CreateDirectory(tempPath);
// Unzip the primpackage
using (ZipInputStream s = new ZipInputStream(File.OpenRead(fileName)))
{
ZipEntry theEntry;
// Loop through and confirm there is a prims.xml file
while ((theEntry = s.GetNextEntry()) != null)
{
if (String.Equals("prims.xml", theEntry.Name.ToLower()))
{
primFile = theEntry.Name;
break;
}
}
if (primFile != null)
{
// Prepend the path to the primFile (that will be created in the next loop)
primFile = System.IO.Path.Combine(tempPath, primFile);
}
else
{
// Didn't find a prims.xml file, bail out
error = "No prims.xml file found in the archive";
return null;
}
// Reset to the beginning of the zip file
s.Seek(0, SeekOrigin.Begin);
Logger.DebugLog("Unpacking archive to " + tempPath);
// Unzip all of the texture and xml files
while ((theEntry = s.GetNextEntry()) != null)
{
string directory = System.IO.Path.GetDirectoryName(theEntry.Name);
string file = System.IO.Path.GetFileName(theEntry.Name);
// Skip directories
if (directory.Length > 0)
continue;
if (!String.IsNullOrEmpty(file))
{
string filelow = file.ToLower();
if (filelow.EndsWith(".jp2") || filelow.EndsWith(".tga") || filelow.EndsWith(".xml"))
{
Logger.DebugLog("Unpacking " + file);
// Create the full path from the temp path and new filename
string filePath = System.IO.Path.Combine(tempPath, file);
using (FileStream streamWriter = File.Create(filePath))
{
const int READ_BUFFER_SIZE = 2048;
int size = READ_BUFFER_SIZE;
byte[] data = new byte[READ_BUFFER_SIZE];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
streamWriter.Write(data, 0, size);
else
break;
}
}
}
else
{
Logger.Log("Skipping file " + file, Helpers.LogLevel.Info);
}
}
}
}
// Decode the .prims file
string raw = File.ReadAllText(primFile);
LLSD llsd = LLSDParser.DeserializeXml(raw);
return Helpers.LLSDToPrimList(llsd);
}
catch (Exception e)
{
error = e.Message;
return null;
}
}
private void DownloadMenu_Clicked(object sender, EventArgs e)
{
// Confirm that there actually is a selected object
RenderablePrim parent;
if (RenderPrimList.TryGetValue(LastHit, out parent))
{
if (parent.Prim.ParentID == 0)
{
// Valid parent prim is selected, throw up the save file dialog
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "Prim Package (*.zip)|*.zip";
if (dialog.ShowDialog() == DialogResult.OK)
{
string error;
int prims, textures;
if (ExportObject(parent, dialog.FileName, out prims, out textures, out error))
MessageBox.Show(String.Format("Exported {0} prims and {1} textures", prims, textures));
else
MessageBox.Show("Export failed: " + error);
}
}
else
{
// This should have already been fixed in the picking processing code
Console.WriteLine("Download menu clicked when a child prim is selected!");
glControl.ContextMenu = null;
LastHit = 0;
}
}
else
{
Console.WriteLine("Download menu clicked when there is no selected prim!");
glControl.ContextMenu = null;
LastHit = 0;
}
}
private void DownloadAllMenu_Clicked(object sender, EventArgs e)
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "Prim Package (*.zip)|*.zip";
if (dialog.ShowDialog() == DialogResult.OK)
{
string error;
int prims, textures;
if (ExportSim(dialog.FileName, out prims, out textures, out error))
MessageBox.Show(String.Format("Exported {0} prims and {1} textures", prims, textures));
else
MessageBox.Show("Export failed: " + error);
}
}
private void ExportTerrainMenu_Clicked(object sender, EventArgs e)
{
// Valid parent prim is selected, throw up the save file dialog
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "Terrain RAW (*.raw)|*.raw";
if (dialog.ShowDialog() == DialogResult.OK)
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate(object obj, DoWorkEventArgs args)
{
byte red, green, blue, alpha1, alpha2, alpha3, alpha4, alpha5, alpha6, alpha7, alpha8, alpha9, alpha10;
try
{
FileInfo file = new FileInfo(dialog.FileName);
FileStream s = file.Open(FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter binStream = new BinaryWriter(s);
for (int y = 0; y < 256; y++)
{
for (int x = 0; x < 256; x++)
{
int xBlock = x / 16;
int yBlock = y / 16;
int xOff = x - (xBlock * 16);
int yOff = y - (yBlock * 16);
float t = Heightmap[yBlock, xBlock].Data[yOff * 16 + xOff];
//float min = Single.MaxValue;
int index = 0;
// The lookup table is pre-sorted, so we either find an exact match or
// the next closest (smaller) match with a binary search
index = Array.BinarySearch<HeightmapLookupValue>(LookupHeightTable, new HeightmapLookupValue(0, t));
if (index < 0)
index = ~index - 1;
index = LookupHeightTable[index].Index;
/*for (int i = 0; i < 65536; i++)
{
if (Math.Abs(t - LookupHeightTable[i].Value) < min)
{
min = Math.Abs(t - LookupHeightTable[i].Value);
index = i;
}
}*/
red = (byte)(index & 0xFF);
green = (byte)((index >> 8) & 0xFF);
blue = 20;
alpha1 = 0; // Land Parcels
alpha2 = 0; // For Sale Land
alpha3 = 0; // Public Edit Object
alpha4 = 0; // Public Edit Land
alpha5 = 255; // Safe Land
alpha6 = 255; // Flying Allowed
alpha7 = 255; // Create Landmark
alpha8 = 255; // Outside Scripts
alpha9 = red;
alpha10 = green;
binStream.Write(red);
binStream.Write(green);
binStream.Write(blue);
binStream.Write(alpha1);
binStream.Write(alpha2);
binStream.Write(alpha3);
binStream.Write(alpha4);
binStream.Write(alpha5);
binStream.Write(alpha6);
binStream.Write(alpha7);
binStream.Write(alpha8);
binStream.Write(alpha9);
binStream.Write(alpha10);
}
}
binStream.Close();
s.Close();
BeginInvoke((MethodInvoker)delegate() { System.Windows.Forms.MessageBox.Show("Exported heightmap"); });
}
catch (Exception ex)
{
BeginInvoke((MethodInvoker)delegate() { System.Windows.Forms.MessageBox.Show("Error exporting heightmap: " + ex.Message); });
}
};
worker.RunWorkerAsync();
}
}
private void TeleportMenu_Clicked(object sender, EventArgs e)
{
if (Client != null && Client.Network.CurrentSim != null)
{
if (LastHit >= TERRAIN_START)
{
// Determine which piece of terrain was clicked on
int y = (int)(LastHit - TERRAIN_START) / 16;
int x = (int)(LastHit - (TERRAIN_START + (y * 16)));
Vector3 targetPos = new Vector3(x * 16 + 8, y * 16 + 8, 0f);
Console.WriteLine("Starting local teleport to " + targetPos.ToString());
Client.Self.RequestTeleport(Client.Network.CurrentSim.Handle, targetPos);
}
else
{
// This shouldn't have happened...
glControl.ContextMenu = null;
}
}
}
private void ImportObjectMenu_Clicked(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Prim Package (*.zip,*.primpackage)|*.zip;*.primpackage";
if (dialog.ShowDialog() == DialogResult.OK)
{
// FIXME: Disable any further imports or exports until this is finished
// Import the prims
string error, texturePath;
List<Primitive> primList = ImportObjects(dialog.FileName, out texturePath, out error);
if (primList != null)
{
// Determine the total height of the object
float minHeight = Single.MaxValue;
float maxHeight = Single.MinValue;
float totalHeight = 0f;
for (int i = 0; i < primList.Count; i++)
{
Primitive prim = primList[i];
// Find the largest scale dimension (quick cheat to avoid figuring in the rotation)
float scale = prim.Scale.X;
if (prim.Scale.Y > scale) scale = prim.Scale.Y;
if (prim.Scale.Z > scale) scale = prim.Scale.Z;
float top = prim.Position.Z + (scale * 0.5f);
float bottom = top - scale;
if (top > maxHeight) maxHeight = top;
if (bottom < minHeight) minHeight = bottom;
}
totalHeight = maxHeight - minHeight;
// Create a progress bar for the import process
ProgressBar prog = new ProgressBar();
prog.Minimum = 0;
prog.Maximum = primList.Count;
prog.Value = 0;
// List item
GlacialComponents.Controls.GLItem item = new GlacialComponents.Controls.GLItem();
item.SubItems[0].Text = "Import process";
item.SubItems[1].Control = prog;
lstDownloads.Items.Add(item);
lstDownloads.Invalidate();
// Start the import process in the background
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate(object s, DoWorkEventArgs ea)
{
// Set the spot choosing state
// Wait for a spot to be chosen
// mouse2dto3d()
// Add (0, 0, totalHeight * 0.5f) to the clicked position
for (int i = 0; i < primList.Count; i++)
{
Primitive prim = primList[i];
for (int j = 0; j < prim.Textures.FaceTextures.Length; j++)
{
// Check if this texture exists
// If not, wait while it uploads
}
// Create this prim (using weird SL math to get the correct position)
// Wait for the callback to fire for this prim being created
// Add this prim's localID to a list
// Set any additional properties. If this is the root prim, do not apply rotation
// Update the progress bar
BeginInvoke((MethodInvoker)delegate() { prog.Value = i; });
}
// Link all of the prims together
// Apply root prim rotation
};
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs ea)
{
BeginInvoke(
(MethodInvoker)delegate()
{
lstDownloads.Items.Remove(item);
lstDownloads.Invalidate();
});
};
worker.RunWorkerAsync();
}
else
{
// FIXME: Re-enable imports and exports
MessageBox.Show(error);
return;
}
}
}
private void ImportSimMenu_Clicked(object sender, EventArgs e)
{
}
private void SetPerspective()
{
Glu.gluPerspective(50.0d * Camera.Zoom, 1.0d, 0.1d, Camera.Far);
}
private void StartPicking(int cursorX, int cursorY)
{
int[] viewport = new int[4];
Gl.glSelectBuffer(SELECT_BUFSIZE, SelectBuffer);
Gl.glRenderMode(Gl.GL_SELECT);
Gl.glMatrixMode(Gl.GL_PROJECTION);
Gl.glPushMatrix();
Gl.glLoadIdentity();
Gl.glGetIntegerv(Gl.GL_VIEWPORT, viewport);
Glu.gluPickMatrix(cursorX, viewport[3] - cursorY, 5, 5, viewport);
SetPerspective();
Gl.glMatrixMode(Gl.GL_MODELVIEW);
Gl.glInitNames();
}
private void StopPicking()
{
int hits;
// Resotre the original projection matrix
Gl.glMatrixMode(Gl.GL_PROJECTION);
Gl.glPopMatrix();
Gl.glMatrixMode(Gl.GL_MODELVIEW);
Gl.glFlush();
// Return to normal rendering mode
hits = Gl.glRenderMode(Gl.GL_RENDER);
// If there are hits process them
if (hits != 0)
{
ProcessHits(hits, SelectBuffer);
}
else
{
LastHit = 0;
glControl.ContextMenu = null;
}
}
private void ProcessHits(int hits, uint[] selectBuffer)
{
uint names = 0;
uint numNames = 0;
uint minZ = 0xffffffff;
uint ptr = 0;
uint ptrNames = 0;
for (uint i = 0; i < hits; i++)
{
names = selectBuffer[ptr];
++ptr;
if (selectBuffer[ptr] < minZ)
{
numNames = names;
minZ = selectBuffer[ptr];
ptrNames = ptr + 2;
}
ptr += names + 2;
}
ptr = ptrNames;
for (uint i = 0; i < numNames; i++, ptr++)
{
LastHit = selectBuffer[ptr];
}
if (LastHit >= TERRAIN_START)
{
// Terrain was clicked on, turn off the context menu
glControl.ContextMenu = ExportTerrainMenu;
}
else
{
RenderablePrim render;
if (RenderPrimList.TryGetValue(LastHit, out render))
{
if (render.Prim.ParentID == 0)
{
Camera.FocalPoint = render.Prim.Position;
UpdateCamera();
}
else
{
// See if we have the parent
RenderablePrim renderParent;
if (RenderPrimList.TryGetValue(render.Prim.ParentID, out renderParent))
{
// Turn on the context menu
glControl.ContextMenu = ExportPrimMenu;
// Change the clicked on prim to the parent. Camera position stays on the
// clicked child but the highlighting is applied to all the children
LastHit = renderParent.Prim.LocalID;
Camera.FocalPoint = renderParent.Prim.Position + render.Prim.Position;
UpdateCamera();
}
else
{
Console.WriteLine("Clicked on a child prim with no parent!");
LastHit = 0;
}
}
}
}
}
private void Objects_OnNewPrim(Simulator simulator, Primitive prim, ulong regionHandle, ushort timeDilation)
{
RenderablePrim render = new RenderablePrim();
render.Prim = prim;
render.Mesh = Render.Plugin.GenerateFacetedMesh(prim, DetailLevel.High);
// Create a FaceData struct for each face that stores the 3D data
// in a Tao.OpenGL friendly format
for (int j = 0; j < render.Mesh.Faces.Count; j++)
{
Face face = render.Mesh.Faces[j];
FaceData data = new FaceData();
// Vertices for this face
data.Vertices = new float[face.Vertices.Count * 3];
for (int k = 0; k < face.Vertices.Count; k++)
{
data.Vertices[k * 3 + 0] = face.Vertices[k].Position.X;
data.Vertices[k * 3 + 1] = face.Vertices[k].Position.Y;
data.Vertices[k * 3 + 2] = face.Vertices[k].Position.Z;
}
// Indices for this face
data.Indices = face.Indices.ToArray();
// Texture transform for this face
Primitive.TextureEntryFace teFace = prim.Textures.GetFace((uint)j);
Render.Plugin.TransformTexCoords(face.Vertices, face.Center, teFace);
// Texcoords for this face
data.TexCoords = new float[face.Vertices.Count * 2];
for (int k = 0; k < face.Vertices.Count; k++)
{
data.TexCoords[k * 2 + 0] = face.Vertices[k].TexCoord.X;
data.TexCoords[k * 2 + 1] = face.Vertices[k].TexCoord.Y;
}
// Texture for this face
if (teFace.TextureID != UUID.Zero &&
teFace.TextureID != Primitive.TextureEntry.WHITE_TEXTURE)
{
lock (Textures)
{
if (!Textures.ContainsKey(teFace.TextureID))
{
// We haven't constructed this image in OpenGL yet, get ahold of it
TextureDownloader.RequestTexture(teFace.TextureID);
}
}
}
// Set the UserData for this face to our FaceData struct
face.UserData = data;
render.Mesh.Faces[j] = face;
}
lock (RenderPrimList) RenderPrimList[prim.LocalID] = render;
}
private void Objects_OnNewFoliage(Simulator simulator, Primitive foliage, ulong regionHandle, ushort timeDilation)
{
lock (RenderFoliageList)
RenderFoliageList[foliage.LocalID] = foliage;
}
private void Objects_OnObjectKilled(Simulator simulator, uint objectID)
{
//
}
private void Parcels_OnSimParcelsDownloaded(Simulator simulator, InternalDictionary<int, Parcel> simParcels, int[,] parcelMap)
{
TotalPrims = 0;
simParcels.ForEach(
delegate(Parcel parcel)
{
TotalPrims += parcel.TotalPrims;
});
UpdatePrimProgress();
}
private void Terrain_OnLandPatch(Simulator simulator, int x, int y, int width, float[] data)
{
if (Client != null && Client.Network.CurrentSim == simulator)
{
Heightmap[y, x].Data = data;
}
// Find the new max height
for (int i = 0; i < data.Length; i++)
{
if (data[i] > MaxHeight)
MaxHeight = data[i];
}
}
private void Network_OnLogin(LoginStatus login, string message)
{
if (login == LoginStatus.Success)
{
// Success!
}
else if (login == LoginStatus.Failed)
{
BeginInvoke(
(MethodInvoker)delegate()
{
MessageBox.Show(this, String.Format("Error logging in ({0}): {1}",
Client.Network.LoginErrorKey, Client.Network.LoginMessage));
cmdLogin.Text = "Login";
txtFirst.Enabled = txtLast.Enabled = txtPass.Enabled = true;
});
}
}
private void Network_OnDisconnected(NetworkManager.DisconnectType reason, string message)
{
BeginInvoke(
(MethodInvoker)delegate()
{
cmdTeleport.Enabled = false;
DoLogout();
});
}
private void Network_OnCurrentSimChanged(Simulator PreviousSimulator)
{
Console.WriteLine("CurrentSim set to " + Client.Network.CurrentSim + ", downloading parcel information");
BeginInvoke((MethodInvoker)delegate() { txtSim.Text = Client.Network.CurrentSim.Name; });
//InitHeightmap();
InitLists();
// Disable teleports until the new event queue comes online
if (!Client.Network.CurrentSim.Caps.IsEventQueueRunning)
BeginInvoke((MethodInvoker)delegate() { cmdTeleport.Enabled = false; });
}
private void Network_OnEventQueueRunning(Simulator simulator)
{
if (simulator == Client.Network.CurrentSim)
BeginInvoke((MethodInvoker)delegate() { cmdTeleport.Enabled = true; });
// Now seems like a good time to start requesting parcel information
Client.Parcels.RequestAllSimParcels(Client.Network.CurrentSim, false, 100);
}
private void RenderScene()
{
try
{
Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT);
Gl.glLoadIdentity();
Gl.glEnableClientState(Gl.GL_VERTEX_ARRAY);
Gl.glEnableClientState(Gl.GL_TEXTURE_COORD_ARRAY);
if (Clicked)
StartPicking(ClickX, ClickY);
// Setup wireframe or solid fill drawing mode
Gl.glPolygonMode(Gl.GL_FRONT, Gl.GL_LINE);
// Position the camera
Glu.gluLookAt(
Camera.Position.X, Camera.Position.Y, Camera.Position.Z,
Camera.FocalPoint.X, Camera.FocalPoint.Y, Camera.FocalPoint.Z,
0f, 0f, 1f);
RenderSkybox();
// Push the world matrix
Gl.glPushMatrix();
RenderTerrain();
RenderPrims();
RenderAvatars();
Gl.glDisableClientState(Gl.GL_TEXTURE_COORD_ARRAY);
Gl.glDisableClientState(Gl.GL_VERTEX_ARRAY);
if (Clicked)
{
Clicked = false;
StopPicking();
}
// Pop the world matrix
Gl.glPopMatrix();
Gl.glFlush();
glControl.Invalidate();
}
catch (Exception)
{
}
}
static readonly Vector3[] SkyboxVerts = new Vector3[]
{
// Right side
new Vector3( 10.0f, 10.0f, -10.0f ), //Top left
new Vector3( 10.0f, 10.0f, 10.0f ), //Top right
new Vector3( 10.0f, -10.0f, 10.0f ), //Bottom right
new Vector3( 10.0f, -10.0f, -10.0f ), //Bottom left
// Left side
new Vector3( -10.0f, 10.0f, 10.0f ), //Top left
new Vector3( -10.0f, 10.0f, -10.0f ), //Top right
new Vector3( -10.0f, -10.0f, -10.0f ), //Bottom right
new Vector3( -10.0f, -10.0f, 10.0f ), //Bottom left
// Top side
new Vector3( -10.0f, 10.0f, 10.0f ), //Top left
new Vector3( 10.0f, 10.0f, 10.0f ), //Top right
new Vector3( 10.0f, 10.0f, -10.0f ), //Bottom right
new Vector3( -10.0f, 10.0f, -10.0f ), //Bottom left
// Bottom side
new Vector3( -10.0f, -10.0f, -10.0f ), //Top left
new Vector3( 10.0f, -10.0f, -10.0f ), //Top right
new Vector3( 10.0f, -10.0f, 10.0f ), //Bottom right
new Vector3( -10.0f, -10.0f, 10.0f ), //Bottom left
// Front side
new Vector3( -10.0f, 10.0f, -10.0f ), //Top left
new Vector3( 10.0f, 10.0f, -10.0f ), //Top right
new Vector3( 10.0f, -10.0f, -10.0f ), //Bottom right
new Vector3( -10.0f, -10.0f, -10.0f ), //Bottom left
// Back side
new Vector3( 10.0f, 10.0f, 10.0f ), //Top left
new Vector3( -10.0f, 10.0f, 10.0f ), //Top right
new Vector3( -10.0f, -10.0f, 10.0f ), //Bottom right
new Vector3( 10.0f, -10.0f, 10.0f ), //Bottom left
};
private void RenderSkybox()
{
//Gl.glTranslatef(0f, 0f, 0f);
}
private void RenderTerrain()
{
if (Heightmap != null)
{
int i = 0;
// No texture
Gl.glBindTexture(Gl.GL_TEXTURE_2D, 0);
for (int hy = 0; hy < 16; hy++)
{
for (int hx = 0; hx < 16; hx++)
{
uint patchName = (uint)(TERRAIN_START + i);
Gl.glPushName(patchName);
++i;
// Check if this patch is currently selected
bool selected = (LastHit == patchName);
for (int y = 0; y < 15; y++)
{
Gl.glBegin(Gl.GL_TRIANGLE_STRIP);
for (int x = 0; x < 15; x++)
{
// Vertex 0
float height = Heightmap[hy, hx].Data[y * 16 + x];
float color = height / MaxHeight;
float red = (selected) ? 1f : color;
Gl.glColor3f(red, color, color);
Gl.glTexCoord2f(0f, 0f);
Gl.glVertex3f(hx * 16 + x, hy * 16 + y, height);
// Vertex 1
height = Heightmap[hy, hx].Data[y * 16 + (x + 1)];
color = height / MaxHeight;
red = (selected) ? 1f : color;
Gl.glColor3f(red, color, color);
Gl.glTexCoord2f(1f, 0f);
Gl.glVertex3f(hx * 16 + x + 1, hy * 16 + y, height);
// Vertex 2
height = Heightmap[hy, hx].Data[(y + 1) * 16 + x];
color = height / MaxHeight;
red = (selected) ? 1f : color;
Gl.glColor3f(red, color, color);
Gl.glTexCoord2f(0f, 1f);
Gl.glVertex3f(hx * 16 + x, hy * 16 + y + 1, height);
// Vertex 3
height = Heightmap[hy, hx].Data[(y + 1) * 16 + (x + 1)];
color = height / MaxHeight;
red = (selected) ? 1f : color;
Gl.glColor3f(red, color, color);
Gl.glTexCoord2f(1f, 1f);
Gl.glVertex3f(hx * 16 + x + 1, hy * 16 + y + 1, height);
}
Gl.glEnd();
}
Gl.glPopName();
}
}
}
}
int[] CubeMapDefines = new int[]
{
Gl.GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB,
Gl.GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB,
Gl.GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB,
Gl.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB,
Gl.GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB,
Gl.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB
};
private void RenderPrims()
{
if (RenderPrimList != null && RenderPrimList.Count > 0)
{
Gl.glEnable(Gl.GL_TEXTURE_2D);
lock (RenderPrimList)
{
bool firstPass = true;
Gl.glDisable(Gl.GL_BLEND);
Gl.glEnable(Gl.GL_DEPTH_TEST);
StartRender:
foreach (RenderablePrim render in RenderPrimList.Values)
{
RenderablePrim parentRender = RenderablePrim.Empty;
Primitive prim = render.Prim;
if (prim.ParentID != 0)
{
// Get the parent reference
if (!RenderPrimList.TryGetValue(prim.ParentID, out parentRender))
{
// Can't render a child with no parent prim, skip it
continue;
}
}
Gl.glPushName(prim.LocalID);
Gl.glPushMatrix();
if (prim.ParentID != 0)
{
// Child prim
Primitive parent = parentRender.Prim;
// Apply parent translation and rotation
Gl.glMultMatrixf(Math3D.CreateTranslationMatrix(parent.Position));
Gl.glMultMatrixf(Math3D.CreateRotationMatrix(parent.Rotation));
}
// Apply prim translation and rotation
Gl.glMultMatrixf(Math3D.CreateTranslationMatrix(prim.Position));
Gl.glMultMatrixf(Math3D.CreateRotationMatrix(prim.Rotation));
// Scale the prim
Gl.glScalef(prim.Scale.X, prim.Scale.Y, prim.Scale.Z);
// Draw the prim faces
for (int j = 0; j < render.Mesh.Faces.Count; j++)
{
Face face = render.Mesh.Faces[j];
FaceData data = (FaceData)face.UserData;
Color4 color = face.TextureFace.RGBA;
bool alpha = false;
int textureID = 0;
if (color.A < 1.0f)
alpha = true;
#region Texturing
TextureInfo info;
if (Textures.TryGetValue(face.TextureFace.TextureID, out info))
{
if (info.Alpha)
alpha = true;
textureID = info.ID;
// Enable texturing for this face
Gl.glPolygonMode(Gl.GL_FRONT_AND_BACK, Gl.GL_FILL);
}
else
{
if (face.TextureFace.TextureID == Primitive.TextureEntry.WHITE_TEXTURE ||
face.TextureFace.TextureID == UUID.Zero)
{
Gl.glPolygonMode(Gl.GL_FRONT, Gl.GL_FILL);
}
else
{
Gl.glPolygonMode(Gl.GL_FRONT, Gl.GL_LINE);
}
}
if (firstPass && !alpha || !firstPass && alpha)
{
// Color this prim differently based on whether it is selected or not
if (LastHit == prim.LocalID || (LastHit != 0 && LastHit == prim.ParentID))
{
Gl.glColor4f(1f, color.G * 0.3f, color.B * 0.3f, color.A);
}
else
{
Gl.glColor4f(color.R, color.G, color.B, color.A);
}
// Bind the texture
Gl.glBindTexture(Gl.GL_TEXTURE_2D, textureID);
Gl.glTexCoordPointer(2, Gl.GL_FLOAT, 0, data.TexCoords);
Gl.glVertexPointer(3, Gl.GL_FLOAT, 0, data.Vertices);
Gl.glDrawElements(Gl.GL_TRIANGLES, data.Indices.Length, Gl.GL_UNSIGNED_SHORT, data.Indices);
}
#endregion Texturing
}
Gl.glPopMatrix();
Gl.glPopName();
}
if (firstPass)
{
firstPass = false;
Gl.glEnable(Gl.GL_BLEND);
Gl.glBlendFunc(Gl.GL_SRC_ALPHA, Gl.GL_ONE_MINUS_SRC_ALPHA);
//Gl.glDisable(Gl.GL_DEPTH_TEST);
goto StartRender;
}
}
Gl.glEnable(Gl.GL_DEPTH_TEST);
Gl.glDisable(Gl.GL_TEXTURE_2D);
}
}
private void RenderAvatars()
{
if (Client != null && Client.Network.CurrentSim != null)
{
Gl.glColor3f(0f, 1f, 0f);
Client.Network.CurrentSim.ObjectsAvatars.ForEach(
delegate(Avatar avatar)
{
Gl.glPushMatrix();
Gl.glTranslatef(avatar.Position.X, avatar.Position.Y, avatar.Position.Z);
Glu.GLUquadric quad = Glu.gluNewQuadric();
Glu.gluSphere(quad, 1.0d, 10, 10);
Glu.gluDeleteQuadric(quad);
Gl.glPopMatrix();
}
);
Gl.glColor3f(1f, 1f, 1f);
}
}
#region Texture Downloading
private void TextureDownloader_OnDownloadFinished(UUID id, bool success)
{
bool alpha = false;
ManagedImage imgData = null;
byte[] raw = null;
try
{
// Load the image off the disk
if (success)
{
ImageDownload download = TextureDownloader.GetTextureToRender(id);
if (OpenJPEG.DecodeToImage(download.AssetData, out imgData))
{
raw = imgData.ExportRaw();
if ((imgData.Channels & ManagedImage.ImageChannels.Alpha) != 0)
alpha = true;
}
else
{
success = false;
Console.WriteLine("Failed to decode texture");
}
}
// Make sure the OpenGL commands run on the main thread
BeginInvoke(
(MethodInvoker)delegate()
{
if (success)
{
int textureID = 0;
try
{
Gl.glGenTextures(1, out textureID);
Gl.glBindTexture(Gl.GL_TEXTURE_2D, textureID);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR_MIPMAP_NEAREST); //Gl.GL_NEAREST);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_WRAP_S, Gl.GL_REPEAT);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_WRAP_T, Gl.GL_REPEAT);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_GENERATE_MIPMAP, Gl.GL_TRUE); //Gl.GL_FALSE);
//Gl.glTexImage2D(Gl.GL_TEXTURE_2D, 0, Gl.GL_RGBA, bitmap.Width, bitmap.Height, 0, Gl.GL_BGRA, Gl.GL_UNSIGNED_BYTE,
// bitmapData.Scan0);
//int error = Gl.glGetError();
int error = Glu.gluBuild2DMipmaps(Gl.GL_TEXTURE_2D, Gl.GL_RGBA, imgData.Width, imgData.Height, Gl.GL_BGRA,
Gl.GL_UNSIGNED_BYTE, raw);
if (error == 0)
{
Textures[id] = new TextureInfo(textureID, alpha);
Console.WriteLine("Created OpenGL texture for " + id.ToString());
}
else
{
Textures[id] = new TextureInfo(0, false);
Console.WriteLine("Error creating OpenGL texture: " + error);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
// Remove this image from the download listbox
lock (DownloadList)
{
GlacialComponents.Controls.GLItem item;
if (DownloadList.TryGetValue(id, out item))
{
DownloadList.Remove(id);
try { lstDownloads.Items.Remove(item); }
catch (Exception) { }
lstDownloads.Invalidate();
}
}
});
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private void TextureDownloader_OnDownloadProgress(UUID image, int recieved, int total)
{
lock (DownloadList)
{
GlacialComponents.Controls.GLItem item;
if (DownloadList.TryGetValue(image, out item))
{
// Update an existing item
BeginInvoke(
(MethodInvoker)delegate()
{
ProgressBar prog = (ProgressBar)item.SubItems[1].Control;
if (total >= recieved)
prog.Value = (int)Math.Round((((double)recieved / (double)total) * 100.0d));
});
}
else
{
// Progress bar
ProgressBar prog = new ProgressBar();
prog.Minimum = 0;
prog.Maximum = 100;
if (total >= recieved)
prog.Value = (int)Math.Round((((double)recieved / (double)total) * 100.0d));
else
prog.Value = 0;
// List item
item = new GlacialComponents.Controls.GLItem();
item.SubItems[0].Text = image.ToString();
item.SubItems[1].Control = prog;
DownloadList[image] = item;
BeginInvoke(
(MethodInvoker)delegate()
{
lstDownloads.Items.Add(item);
lstDownloads.Invalidate();
});
}
}
}
#endregion Texture Downloading
private void frmBrowser_FormClosing(object sender, FormClosingEventArgs e)
{
DoLogout();
Application.Idle -= IdleEvent;
}
private void Application_Idle(object sender, EventArgs e)
{
while (AppStillIdle)
{
RenderScene();
}
}
private void cmdLogin_Click(object sender, EventArgs e)
{
if (cmdLogin.Text == "Login")
{
// Check that all the input boxes are filled in
if (txtFirst.Text.Length == 0)
{
txtFirst.Select();
return;
}
if (txtLast.Text.Length == 0)
{
txtLast.Select();
return;
}
if (txtPass.Text.Length == 0)
{
txtPass.Select();
return;
}
// Disable input controls
txtFirst.Enabled = txtLast.Enabled = txtPass.Enabled = false;
cmdLogin.Text = "Logout";
// Sanity check that we aren't already logged in
if (Client != null && Client.Network.Connected)
{
Client.Network.Logout();
}
// Re-initialize everything
InitializeObjects();
// Start the login
LoginParams loginParams = Client.Network.DefaultLoginParams(txtFirst.Text, txtLast.Text,
txtPass.Text, "Prim Preview", "0.0.1");
if (!String.IsNullOrEmpty(cboServer.Text))
loginParams.URI = cboServer.Text;
Client.Network.BeginLogin(loginParams);
}
else
{
DoLogout();
}
}
private void DoLogout()
{
if (Client != null && Client.Network.Connected)
{
Client.Network.Logout();
return;
}
// Clear the download list
lstDownloads.Items.Clear();
// Set the login button back to login state
cmdLogin.Text = "Login";
// Shutdown the texture downloader
if (TextureDownloader != null)
TextureDownloader.Shutdown();
// Enable input controls
txtFirst.Enabled = txtLast.Enabled = txtPass.Enabled = true;
}
private void glControl_Resize(object sender, EventArgs e)
{
Gl.glClearColor(0.39f, 0.58f, 0.93f, 1.0f);
Gl.glViewport(0, 0, glControl.Width, glControl.Height);
Gl.glPushMatrix();
Gl.glMatrixMode(Gl.GL_PROJECTION);
Gl.glLoadIdentity();
SetPerspective();
Gl.glMatrixMode(Gl.GL_MODELVIEW);
Gl.glPopMatrix();
// Set the center of the glControl as the default pivot point
LastPivot = glControl.PointToScreen(new Point(glControl.Width / 2, glControl.Height / 2));
}
private void glControl_MouseClick(object sender, MouseEventArgs e)
{
if ((Control.ModifierKeys & Keys.Alt) == 0 && e.Button == MouseButtons.Left)
{
// Only allow clicking if alt is not being held down
ClickX = e.X;
ClickY = e.Y;
Clicked = true;
}
}
private void glControl_MouseDown(object sender, MouseEventArgs e)
{
if ((Control.ModifierKeys & Keys.Alt) != 0 && LastHit > 0)
{
// Alt is held down and we have a valid target
Pivoting = true;
PivotPosition = Camera.FocalPoint;
Control control = (Control)sender;
LastPivot = control.PointToScreen(new Point(e.X, e.Y));
}
}
private void glControl_MouseMove(object sender, MouseEventArgs e)
{
if (Pivoting)
{
float a,x,y,z;
Control control = (Control)sender;
Point mouse = control.PointToScreen(new Point(e.X, e.Y));
// Calculate the deltas from the center of the control to the current position
int deltaX = (int)((mouse.X - LastPivot.X) * -0.5d);
int deltaY = (int)((mouse.Y - LastPivot.Y) * -0.5d);
// Translate so the focal point is the origin
Vector3 altered = Camera.Position - Camera.FocalPoint;
// Rotate the translated point by deltaX
a = (float)deltaX * DEG_TO_RAD;
x = (float)((altered.X * Math.Cos(a)) - (altered.Y * Math.Sin(a)));
y = (float)((altered.X * Math.Sin(a)) + (altered.Y * Math.Cos(a)));
altered.X = x;
altered.Y = y;
// Rotate the translated point by deltaY
a = (float)deltaY * DEG_TO_RAD;
y = (float)((altered.Y * Math.Cos(a)) - (altered.Z * Math.Sin(a)));
z = (float)((altered.Y * Math.Sin(a)) + (altered.Z * Math.Cos(a)));
altered.Y = y;
altered.Z = z;
// Translate back to world space
altered += Camera.FocalPoint;
// Update the camera
Camera.Position = altered;
UpdateCamera();
// Update the pivot point
LastPivot = mouse;
}
}
private void glControl_MouseWheel(object sender, MouseEventArgs e)
{
/*if (e.Delta != 0)
{
Camera.Zoom = Camera.Zoom + (double)(e.Delta / 120) * -0.1d;
if (Camera.Zoom < 0.05d) Camera.Zoom = 0.05d;
UpdateCamera();
}*/
if (e.Delta != 0)
{
// Calculate the distance to move to/away
float dist = (float)(e.Delta / 120) * 10.0f;
if (Vector3.Distance(Camera.Position, Camera.FocalPoint) > dist)
{
// Move closer or further away from the focal point
Vector3 toFocal = Camera.FocalPoint - Camera.Position;
toFocal.Normalize();
toFocal = toFocal * dist;
Camera.Position += toFocal;
UpdateCamera();
}
}
}
private void glControl_MouseUp(object sender, MouseEventArgs e)
{
// Stop pivoting if we were previously
Pivoting = false;
}
private void txtLogin_Enter(object sender, EventArgs e)
{
TextBox input = (TextBox)sender;
input.SelectAll();
}
private void cmdTeleport_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(txtSim.Text))
{
// Parse X/Y/Z
int x, y, z;
if (!Int32.TryParse(txtX.Text, out x))
{
txtX.SelectAll();
return;
}
if (!Int32.TryParse(txtY.Text, out y))
{
txtY.SelectAll();
return;
}
if (!Int32.TryParse(txtZ.Text, out z))
{
txtZ.SelectAll();
return;
}
string simName = txtSim.Text.Trim().ToLower();
Vector3 position = new Vector3(x, y, z);
if (Client != null && Client.Network.CurrentSim != null)
{
// Check for a local teleport to shortcut the process
if (simName == Client.Network.CurrentSim.Name.ToLower())
{
// Local teleport
Client.Self.RequestTeleport(Client.Network.CurrentSim.Handle, position);
}
else
{
// Cross-sim teleport
bool success = false;
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate(object s, DoWorkEventArgs ea) { success = Client.Self.Teleport(simName, position); };
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs ea)
{
BeginInvoke((MethodInvoker)
delegate()
{
if (!success)
System.Windows.Forms.MessageBox.Show("Teleport failed");
});
};
worker.RunWorkerAsync();
}
}
else
{
// Oops! How did the user click this...
cmdTeleport.Enabled = false;
}
}
}
}
public struct TextureInfo
{
/// <summary>OpenGL Texture ID</summary>
public int ID;
/// <summary>True if this texture has an alpha component</summary>
public bool Alpha;
public TextureInfo(int id, bool alpha)
{
ID = id;
Alpha = alpha;
}
}
public struct HeightmapLookupValue : IComparable<HeightmapLookupValue>
{
public int Index;
public float Value;
public HeightmapLookupValue(int index, float value)
{
Index = index;
Value = value;
}
public int CompareTo(HeightmapLookupValue val)
{
return Value.CompareTo(val.Value);
}
}
public struct RenderablePrim
{
public Primitive Prim;
public FacetedMesh Mesh;
public readonly static RenderablePrim Empty = new RenderablePrim();
}
public struct Camera
{
public Vector3 Position;
public Vector3 FocalPoint;
public double Zoom;
public double Far;
}
public struct NativeMethods
{
[StructLayout(LayoutKind.Sequential)]
public struct Message
{
public IntPtr HWnd;
public uint Msg;
public IntPtr WParam;
public IntPtr LParam;
public uint Time;
public System.Drawing.Point Point;
}
//[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool PeekMessage(out Message msg, IntPtr hWnd, uint messageFilterMin, uint messageFilterMax, uint flags);
}
public static class Math3D
{
// Column-major:
// | 0 4 8 12 |
// | 1 5 9 13 |
// | 2 6 10 14 |
// | 3 7 11 15 |
public static float[] CreateTranslationMatrix(Vector3 v)
{
float[] mat = new float[16];
mat[12] = v.X;
mat[13] = v.Y;
mat[14] = v.Z;
mat[0] = mat[5] = mat[10] = mat[15] = 1;
return mat;
}
public static float[] CreateRotationMatrix(Quaternion q)
{
float[] mat = new float[16];
// Transpose the quaternion (don't ask me why)
q.X = q.X * -1f;
q.Y = q.Y * -1f;
q.Z = q.Z * -1f;
float x2 = q.X + q.X;
float y2 = q.Y + q.Y;
float z2 = q.Z + q.Z;
float xx = q.X * x2;
float xy = q.X * y2;
float xz = q.X * z2;
float yy = q.Y * y2;
float yz = q.Y * z2;
float zz = q.Z * z2;
float wx = q.W * x2;
float wy = q.W * y2;
float wz = q.W * z2;
mat[0] = 1.0f - (yy + zz);
mat[1] = xy - wz;
mat[2] = xz + wy;
mat[3] = 0.0f;
mat[4] = xy + wz;
mat[5] = 1.0f - (xx + zz);
mat[6] = yz - wx;
mat[7] = 0.0f;
mat[8] = xz - wy;
mat[9] = yz + wx;
mat[10] = 1.0f - (xx + yy);
mat[11] = 0.0f;
mat[12] = 0.0f;
mat[13] = 0.0f;
mat[14] = 0.0f;
mat[15] = 1.0f;
return mat;
}
public static float[] CreateScaleMatrix(Vector3 v)
{
float[] mat = new float[16];
mat[0] = v.X;
mat[5] = v.Y;
mat[10] = v.Z;
mat[15] = 1;
return mat;
}
}
}
|
jhs/libopenmetaverse
|
Programs/PrimWorkshop/frmBrowser.cs
|
C#
|
bsd-3-clause
| 75,586 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_SYSTEM_DARK_MODE_DARK_MODE_FEATURE_POD_CONTROLLER_H_
#define ASH_SYSTEM_DARK_MODE_DARK_MODE_FEATURE_POD_CONTROLLER_H_
#include "ash/public/cpp/style/color_mode_observer.h"
#include "ash/system/unified/feature_pod_controller_base.h"
#include "base/macros.h"
namespace ash {
class UnifiedSystemTrayController;
// Controller of a feature pod button that toggles dark mode for ash.
class DarkModeFeaturePodController : public FeaturePodControllerBase,
public ColorModeObserver {
public:
explicit DarkModeFeaturePodController(
UnifiedSystemTrayController* tray_controller);
DarkModeFeaturePodController(const DarkModeFeaturePodController& other) =
delete;
DarkModeFeaturePodController& operator=(
const DarkModeFeaturePodController& other) = delete;
~DarkModeFeaturePodController() override;
// FeaturePodControllerBase:
FeaturePodButton* CreateButton() override;
void OnIconPressed() override;
void OnLabelPressed() override;
SystemTrayItemUmaType GetUmaType() const override;
// ColorModeObserver:
void OnColorModeChanged(bool dark_mode_enabled) override;
private:
void UpdateButton(bool dark_mode_enabled);
UnifiedSystemTrayController* const tray_controller_;
FeaturePodButton* button_ = nullptr;
};
} // namespace ash
#endif // ASH_SYSTEM_DARK_MODE_DARK_MODE_FEATURE_POD_CONTROLLER_H_
|
nwjs/chromium.src
|
ash/system/dark_mode/dark_mode_feature_pod_controller.h
|
C
|
bsd-3-clause
| 1,560 |
<?php
return array(
# definir e gerenciar controllers
'controllers' => array(
'invokables' => array(
'HomeController' => 'Contato\Controller\HomeController',
'ContatosController' => 'Contato\Controller\ContatosController'
),
),
# definir e gerenciar rotas
'router' => array(
'routes' => array(
'home' => array(
'type' => 'Literal',
'options' => array(
'route' => '/',
'defaults' => array(
'controller' => 'HomeController',
'action' => 'index',
),
),
),
# literal para action sobre home
'sobre' => array(
'type' => 'Literal',
'options' => array(
'route' => '/sobre',
'defaults' => array(
'controller' => 'HomeController',
'action' => 'sobre',
),
),
),
'contatos' => array(
'type' => 'Segment',
'options' => array(
'route' => '/contatos[/:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'ContatosController',
'action' => 'index',
),
),
),
),
),
# definir e gerenciar servicos
'service_manager' => array(
'factories' => array(
#'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory',
),
),
# definir e gerenciar layouts, erros, exceptions, doctype base
'view_manager' => array(
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => array(
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'contato/home/index' => __DIR__ . '/../view/contato/home/index.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
),
'template_path_stack' => array(
__DIR__ . '/../view',
),
),
);
|
scastanheira/tutorialzf2
|
module/Contato/config/module.config.php
|
PHP
|
bsd-3-clause
| 2,708 |
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.stickycoding.rokon;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class layout {
public static final int main=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040001;
public static final int hello=0x7f040000;
}
}
|
pjlegato/rokon
|
gen/com/stickycoding/rokon/R.java
|
Java
|
bsd-3-clause
| 621 |
ALTER TABLE feature_checkin_question ADD answer_explanation TEXT NULL;
|
City-Outdoors/City-Outdoors-Web
|
includes/sql/migrations/20130104141500addquestionanswertext.sql
|
SQL
|
bsd-3-clause
| 71 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.tabmodel;
import android.annotation.TargetApi;
import android.os.Build;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.MediumTest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.ApplicationStatus;
import org.chromium.base.test.util.CallbackHelper;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.DisabledTest;
import org.chromium.base.test.util.FlakyTest;
import org.chromium.base.test.util.MinAndroidSdkLevel;
import org.chromium.base.test.util.Restriction;
import org.chromium.base.test.util.RetryOnFailure;
import org.chromium.base.test.util.UrlUtils;
import org.chromium.chrome.browser.ChromeTabbedActivity2;
import org.chromium.chrome.browser.flags.ChromeSwitches;
import org.chromium.chrome.browser.multiwindow.MultiWindowTestHelper;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tab.TabLaunchType;
import org.chromium.chrome.browser.tab.TabSelectionType;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.chrome.test.ChromeTabbedActivityTestRule;
import org.chromium.chrome.test.util.ChromeTabUtils;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.browser.test.util.Criteria;
import org.chromium.content_public.browser.test.util.CriteriaHelper;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
import org.chromium.ui.test.util.UiRestriction;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeoutException;
/**
* Tests undo and restoring of tabs in a {@link TabModel}.
*/
@RunWith(ChromeJUnit4ClassRunner.class)
@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE})
public class UndoTabModelTest {
@Rule
public ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule();
private static final Tab[] EMPTY = new Tab[] { };
private static final String TEST_URL_0 = UrlUtils.encodeHtmlDataUri("<html>test_url_0.</html>");
private static final String TEST_URL_1 = UrlUtils.encodeHtmlDataUri("<html>test_url_1.</html>");
@Before
public void setUp() throws InterruptedException {
mActivityTestRule.startMainActivityOnBlankPage();
}
private void checkState(
final TabModel model, final Tab[] tabsList, final Tab selectedTab,
final Tab[] closingTabs, final Tab[] fullTabsList,
final Tab fullSelectedTab) {
// Keeping these checks on the test thread so the stacks are useful for identifying
// failures.
// Check the selected tab.
Assert.assertEquals("Wrong selected tab", selectedTab, TabModelUtils.getCurrentTab(model));
// Check the list of tabs.
Assert.assertEquals("Incorrect number of tabs", tabsList.length, model.getCount());
for (int i = 0; i < tabsList.length; i++) {
Assert.assertEquals(
"Unexpected tab at " + i, tabsList[i].getId(), model.getTabAt(i).getId());
}
// Check the list of tabs we expect to be closing.
for (int i = 0; i < closingTabs.length; i++) {
int id = closingTabs[i].getId();
Assert.assertTrue("Tab " + id + " not in closing list", model.isClosurePending(id));
}
TabList fullModel = model.getComprehensiveModel();
// Check the comprehensive selected tab.
Assert.assertEquals(
"Wrong selected tab", fullSelectedTab, TabModelUtils.getCurrentTab(fullModel));
// Check the comprehensive list of tabs.
Assert.assertEquals("Incorrect number of tabs", fullTabsList.length, fullModel.getCount());
for (int i = 0; i < fullModel.getCount(); i++) {
int id = fullModel.getTabAt(i).getId();
Assert.assertEquals("Unexpected tab at " + i, fullTabsList[i].getId(), id);
}
}
private void createTabOnUiThread(final ChromeTabCreator tabCreator) {
TestThreadUtils.runOnUiThreadBlocking(() -> {
tabCreator.createNewTab(
new LoadUrlParams("about:blank"), TabLaunchType.FROM_CHROME_UI, null);
});
}
private void selectTabOnUiThread(final TabModel model, final Tab tab) {
TestThreadUtils.runOnUiThreadBlocking(
() -> { model.setIndex(model.indexOf(tab), TabSelectionType.FROM_USER); });
}
private void closeTabOnUiThread(final TabModel model, final Tab tab, final boolean undoable)
throws TimeoutException {
// Check preconditions.
Assert.assertFalse(tab.isClosing());
Assert.assertTrue(tab.isInitialized());
Assert.assertFalse(model.isClosurePending(tab.getId()));
Assert.assertNotNull(TabModelUtils.getTabById(model, tab.getId()));
final CallbackHelper didReceivePendingClosureHelper = new CallbackHelper();
model.addObserver(new TabModelObserver() {
@Override
public void tabPendingClosure(Tab tab) {
didReceivePendingClosureHelper.notifyCalled();
}
});
TestThreadUtils.runOnUiThreadBlocking(() -> {
// Take action.
model.closeTab(tab, true, false, undoable);
});
boolean didUndo = undoable && model.supportsPendingClosures();
// Make sure the TabModel throws a tabPendingClosure callback if necessary.
if (didUndo) didReceivePendingClosureHelper.waitForCallback(0);
// Check post conditions
Assert.assertEquals(didUndo, model.isClosurePending(tab.getId()));
Assert.assertNull(TabModelUtils.getTabById(model, tab.getId()));
Assert.assertTrue(tab.isClosing());
Assert.assertEquals(didUndo, tab.isInitialized());
}
private void closeAllTabsOnUiThread(final TabModel model) {
TestThreadUtils.runOnUiThreadBlocking(() -> { model.closeAllTabs(); });
}
private void moveTabOnUiThread(final TabModel model, final Tab tab, final int newIndex) {
TestThreadUtils.runOnUiThreadBlocking(() -> { model.moveTab(tab.getId(), newIndex); });
}
private void cancelTabClosureOnUiThread(final TabModel model, final Tab tab)
throws TimeoutException {
// Check preconditions.
Assert.assertTrue(tab.isClosing());
Assert.assertTrue(tab.isInitialized());
Assert.assertTrue(model.isClosurePending(tab.getId()));
Assert.assertNull(TabModelUtils.getTabById(model, tab.getId()));
final CallbackHelper didReceiveClosureCancelledHelper = new CallbackHelper();
model.addObserver(new TabModelObserver() {
@Override
public void tabClosureUndone(Tab tab) {
didReceiveClosureCancelledHelper.notifyCalled();
}
});
TestThreadUtils.runOnUiThreadBlocking(() -> {
// Take action.
model.cancelTabClosure(tab.getId());
});
// Make sure the TabModel throws a tabClosureUndone.
didReceiveClosureCancelledHelper.waitForCallback(0);
// Check post conditions.
Assert.assertFalse(model.isClosurePending(tab.getId()));
Assert.assertNotNull(TabModelUtils.getTabById(model, tab.getId()));
Assert.assertFalse(tab.isClosing());
Assert.assertTrue(tab.isInitialized());
}
private void cancelAllTabClosuresOnUiThread(final TabModel model, final Tab[] expectedToClose)
throws TimeoutException {
final CallbackHelper tabClosureUndoneHelper = new CallbackHelper();
for (int i = 0; i < expectedToClose.length; i++) {
Tab tab = expectedToClose[i];
Assert.assertTrue(tab.isClosing());
Assert.assertTrue(tab.isInitialized());
Assert.assertTrue(model.isClosurePending(tab.getId()));
Assert.assertNull(TabModelUtils.getTabById(model, tab.getId()));
// Make sure that this TabModel throws the right events.
model.addObserver(new TabModelObserver() {
@Override
public void tabClosureUndone(Tab currentTab) {
tabClosureUndoneHelper.notifyCalled();
}
});
}
TestThreadUtils.runOnUiThreadBlocking(() -> {
for (int i = 0; i < expectedToClose.length; i++) {
Tab tab = expectedToClose[i];
model.cancelTabClosure(tab.getId());
}
});
tabClosureUndoneHelper.waitForCallback(0, expectedToClose.length);
for (int i = 0; i < expectedToClose.length; i++) {
final Tab tab = expectedToClose[i];
Assert.assertFalse(model.isClosurePending(tab.getId()));
Assert.assertNotNull(TabModelUtils.getTabById(model, tab.getId()));
Assert.assertFalse(tab.isClosing());
Assert.assertTrue(tab.isInitialized());
}
}
private void commitTabClosureOnUiThread(final TabModel model, final Tab tab)
throws TimeoutException {
// Check preconditions.
Assert.assertTrue(tab.isClosing());
Assert.assertTrue(tab.isInitialized());
Assert.assertTrue(model.isClosurePending(tab.getId()));
Assert.assertNull(TabModelUtils.getTabById(model, tab.getId()));
final CallbackHelper didReceiveClosureCommittedHelper = new CallbackHelper();
model.addObserver(new TabModelObserver() {
@Override
public void tabClosureCommitted(Tab tab) {
didReceiveClosureCommittedHelper.notifyCalled();
}
});
TestThreadUtils.runOnUiThreadBlocking(() -> {
// Take action.
model.commitTabClosure(tab.getId());
});
// Make sure the TabModel throws a tabClosureCommitted.
didReceiveClosureCommittedHelper.waitForCallback(0);
// Check post conditions
Assert.assertFalse(model.isClosurePending(tab.getId()));
Assert.assertNull(TabModelUtils.getTabById(model, tab.getId()));
Assert.assertTrue(tab.isClosing());
Assert.assertFalse(tab.isInitialized());
}
private void commitAllTabClosuresOnUiThread(final TabModel model, Tab[] expectedToClose)
throws TimeoutException {
final CallbackHelper tabClosureCommittedHelper = new CallbackHelper();
for (int i = 0; i < expectedToClose.length; i++) {
Tab tab = expectedToClose[i];
Assert.assertTrue(tab.isClosing());
Assert.assertTrue(tab.isInitialized());
Assert.assertTrue(model.isClosurePending(tab.getId()));
// Make sure that this TabModel throws the right events.
model.addObserver(new TabModelObserver() {
@Override
public void tabClosureCommitted(Tab currentTab) {
tabClosureCommittedHelper.notifyCalled();
}
});
}
TestThreadUtils.runOnUiThreadBlocking(() -> { model.commitAllTabClosures(); });
tabClosureCommittedHelper.waitForCallback(0, expectedToClose.length);
for (int i = 0; i < expectedToClose.length; i++) {
final Tab tab = expectedToClose[i];
Assert.assertTrue(tab.isClosing());
Assert.assertFalse(tab.isInitialized());
Assert.assertFalse(model.isClosurePending(tab.getId()));
}
}
private void saveStateOnUiThread(final TabModelSelector selector) {
TestThreadUtils.runOnUiThreadBlocking(
() -> { ((TabModelSelectorImpl) selector).saveState(); });
for (int i = 0; i < selector.getModels().size(); i++) {
TabList tabs = selector.getModels().get(i).getComprehensiveModel();
for (int j = 0; j < tabs.getCount(); j++) {
Assert.assertFalse(tabs.isClosurePending(tabs.getTabAt(j).getId()));
}
}
}
private void openMostRecentlyClosedTabOnUiThread(final TabModelSelector selector) {
TestThreadUtils.runOnUiThreadBlocking(
() -> { selector.getCurrentModel().openMostRecentlyClosedTab(); });
}
// Helper class that notifies after the tab is closed, and a tab restore service entry has been
// created in tab restore service.
private static class TabClosedObserver implements TabModelObserver {
private CallbackHelper mTabClosedCallback;
public TabClosedObserver(CallbackHelper closedCallback) {
mTabClosedCallback = closedCallback;
}
@Override
public void didCloseTab(int tabId, boolean incognito) {
mTabClosedCallback.notifyCalled();
}
}
/**
* Test undo with a single tab with the following actions/expected states:
* Action Model List Close List Comprehensive List
* 1. Initial State [ 0s ] - [ 0s ]
* 2. CloseTab(0, allow undo) - [ 0 ] [ 0s ]
* 3. CancelClose(0) [ 0s ] - [ 0s ]
* 4. CloseTab(0, allow undo) - [ 0 ] [ 0s ]
* 5. CommitClose(0) - - -
* 6. CreateTab(0) [ 0s ] - [ 0s ]
* 7. CloseTab(0, allow undo) - [ 0 ] [ 0s ]
* 8. CommitAllClose - - -
* 9. CreateTab(0) [ 0s ] - [ 0s ]
* 10. CloseTab(0, disallow undo) - - -
*
*/
@Test
@MediumTest
@RetryOnFailure
public void testSingleTab() throws TimeoutException {
TabModel model = mActivityTestRule.getActivity().getTabModelSelector().getModel(false);
ChromeTabCreator tabCreator = mActivityTestRule.getActivity().getTabCreator(false);
Tab tab0 = model.getTabAt(0);
Tab[] fullList = new Tab[] { tab0 };
// 1.
checkState(model, new Tab[] { tab0 }, tab0, EMPTY, fullList, tab0);
// 2.
closeTabOnUiThread(model, tab0, true);
checkState(model, EMPTY, null, new Tab[] { tab0 }, fullList, tab0);
// 3.
cancelTabClosureOnUiThread(model, tab0);
checkState(model, new Tab[] { tab0 }, tab0, EMPTY, fullList, tab0);
// 4.
closeTabOnUiThread(model, tab0, true);
checkState(model, EMPTY, null, new Tab[] { tab0 }, fullList, tab0);
// 5.
commitTabClosureOnUiThread(model, tab0);
fullList = EMPTY;
checkState(model, EMPTY, null, EMPTY, EMPTY, null);
// 6.
createTabOnUiThread(tabCreator);
tab0 = model.getTabAt(0);
fullList = new Tab[] { tab0 };
checkState(model, new Tab[] { tab0 }, tab0, EMPTY, fullList, tab0);
// 7.
closeTabOnUiThread(model, tab0, true);
checkState(model, EMPTY, null, new Tab[] { tab0 }, fullList, tab0);
// 8.
commitAllTabClosuresOnUiThread(model, new Tab[] { tab0 });
fullList = EMPTY;
checkState(model, EMPTY, null, EMPTY, EMPTY, null);
// 9.
createTabOnUiThread(tabCreator);
tab0 = model.getTabAt(0);
fullList = new Tab[] { tab0 };
checkState(model, new Tab[] { tab0 }, tab0, EMPTY, fullList, tab0);
// 10.
closeTabOnUiThread(model, tab0, false);
fullList = EMPTY;
checkState(model, EMPTY, null, EMPTY, fullList, null);
Assert.assertTrue(tab0.isClosing());
Assert.assertFalse(tab0.isInitialized());
}
/**
* Test undo with two tabs with the following actions/expected states:
* Action Model List Close List Comprehensive List
* 1. Initial State [ 0 1s ] - [ 0 1s ]
* 2. CloseTab(0, allow undo) [ 1s ] [ 0 ] [ 0 1s ]
* 3. CancelClose(0) [ 0 1s ] - [ 0 1s ]
* 4. CloseTab(0, allow undo) [ 1s ] [ 0 ] [ 0 1s ]
* 5. CloseTab(1, allow undo) - [ 1 0 ] [ 0s 1 ]
* 6. CancelClose(1) [ 1s ] [ 0 ] [ 0 1s ]
* 7. CancelClose(0) [ 0 1s ] - [ 0 1s ]
* 8. CloseTab(1, allow undo) [ 0s ] [ 1 ] [ 0s 1 ]
* 9. CloseTab(0, allow undo) - [ 0 1 ] [ 0s 1 ]
* 10. CancelClose(1) [ 1s ] [ 0 ] [ 0 1s ]
* 11. CancelClose(0) [ 0 1s ] - [ 0 1s ]
* 12. CloseTab(1, allow undo) [ 0s ] [ 1 ] [ 0s 1 ]
* 13. CloseTab(0, allow undo) - [ 0 1 ] [ 0s 1 ]
* 14. CancelClose(0) [ 0s ] [ 1 ] [ 0s 1 ]
* 15. CloseTab(0, allow undo) - [ 0 1 ] [ 0s 1 ]
* 16. CancelClose(0) [ 0s ] [ 1 ] [ 0s 1 ]
* 17. CancelClose(1) [ 0s 1 ] - [ 0s 1 ]
* 18. CloseTab(0, disallow undo) [ 1s ] - [ 1s ]
* 19. CreateTab(0) [ 1 0s ] - [ 1 0s ]
* 20. CloseTab(0, allow undo) [ 1s ] [ 0 ] [ 1s 0 ]
* 21. CommitClose(0) [ 1s ] - [ 1s ]
* 22. CreateTab(0) [ 1 0s ] - [ 1 0s ]
* 23. CloseTab(0, allow undo) [ 1s ] [ 0 ] [ 1s 0 ]
* 24. CloseTab(1, allow undo) - [ 1 0 ] [ 1s 0 ]
* 25. CommitAllClose - - -
*
*/
@Test
// @MediumTest
// @RetryOnFailure
@DisabledTest(
message = "Flaky on all Android configurations except Swarming. See crbug.com/620014.")
public void
testTwoTabs() throws TimeoutException {
TabModel model = mActivityTestRule.getActivity().getTabModelSelector().getModel(false);
ChromeTabCreator tabCreator = mActivityTestRule.getActivity().getTabCreator(false);
createTabOnUiThread(tabCreator);
Tab tab0 = model.getTabAt(0);
Tab tab1 = model.getTabAt(1);
Tab[] fullList = new Tab[] { tab0, tab1 };
// 1.
checkState(model, new Tab[] { tab0, tab1 }, tab1, EMPTY, fullList, tab1);
// 2.
closeTabOnUiThread(model, tab0, true);
checkState(model, new Tab[] { tab1 }, tab1, new Tab[] { tab0 }, fullList, tab1);
// 3.
cancelTabClosureOnUiThread(model, tab0);
checkState(model, new Tab[] { tab0, tab1 }, tab1, EMPTY, fullList, tab1);
// 4.
closeTabOnUiThread(model, tab0, true);
checkState(model, new Tab[] { tab1 }, tab1, new Tab[] { tab0 }, fullList, tab1);
// 5.
closeTabOnUiThread(model, tab1, true);
checkState(model, EMPTY, null, new Tab[] { tab0, tab1 }, fullList, tab0);
// 6.
cancelTabClosureOnUiThread(model, tab1);
checkState(model, new Tab[] { tab1 }, tab1, new Tab[] { tab0 }, fullList, tab1);
// 7.
cancelTabClosureOnUiThread(model, tab0);
checkState(model, new Tab[] { tab0, tab1 }, tab1, EMPTY, fullList, tab1);
// 8.
closeTabOnUiThread(model, tab1, true);
checkState(model, new Tab[] { tab0 }, tab0, new Tab[] { tab1 }, fullList, tab0);
// 9.
closeTabOnUiThread(model, tab0, true);
checkState(model, EMPTY, null, new Tab[] { tab0, tab1 }, fullList, tab0);
// 10.
cancelTabClosureOnUiThread(model, tab1);
checkState(model, new Tab[] { tab1 }, tab1, new Tab[] { tab0 }, fullList, tab1);
// 11.
cancelTabClosureOnUiThread(model, tab0);
checkState(model, new Tab[] { tab0, tab1 }, tab1, EMPTY, fullList, tab1);
// 12.
closeTabOnUiThread(model, tab1, true);
checkState(model, new Tab[] { tab0 }, tab0, new Tab[] { tab1 }, fullList, tab0);
// 13.
closeTabOnUiThread(model, tab0, true);
checkState(model, EMPTY, null, new Tab[] { tab0, tab1 }, fullList, tab0);
// 14.
cancelTabClosureOnUiThread(model, tab0);
checkState(model, new Tab[] { tab0 }, tab0, new Tab[] { tab1 }, fullList, tab0);
// 15.
closeTabOnUiThread(model, tab0, true);
checkState(model, EMPTY, null, new Tab[] { tab0, tab1 }, fullList, tab0);
// 16.
cancelTabClosureOnUiThread(model, tab0);
checkState(model, new Tab[] { tab0 }, tab0, new Tab[] { tab1 }, fullList, tab0);
// 17.
cancelTabClosureOnUiThread(model, tab1);
checkState(model, new Tab[] { tab0, tab1 }, tab0, EMPTY, fullList, tab0);
// 18.
closeTabOnUiThread(model, tab0, false);
fullList = new Tab[] { tab1 };
checkState(model, new Tab[] { tab1 }, tab1, EMPTY, fullList, tab1);
// 19.
createTabOnUiThread(tabCreator);
tab0 = model.getTabAt(1);
fullList = new Tab[] { tab1, tab0 };
checkState(model, new Tab[] { tab1, tab0 }, tab0, EMPTY, fullList, tab0);
// 20.
closeTabOnUiThread(model, tab0, true);
checkState(model, new Tab[] { tab1 }, tab1, new Tab[] { tab0 }, fullList, tab1);
// 21.
commitTabClosureOnUiThread(model, tab0);
fullList = new Tab[] { tab1 };
checkState(model, new Tab[] { tab1 }, tab1, EMPTY, fullList, tab1);
// 22.
createTabOnUiThread(tabCreator);
tab0 = model.getTabAt(1);
fullList = new Tab[] { tab1, tab0 };
checkState(model, new Tab[] { tab1, tab0 }, tab0, EMPTY, fullList, tab0);
// 23.
closeTabOnUiThread(model, tab0, true);
checkState(model, new Tab[] { tab1 }, tab1, new Tab[] { tab0 }, fullList, tab1);
// 24.
closeTabOnUiThread(model, tab1, true);
checkState(model, EMPTY, null, new Tab[] { tab1, tab0 }, fullList, tab1);
// 25.
commitAllTabClosuresOnUiThread(model, new Tab[] { tab1, tab0 });
checkState(model, EMPTY, null, EMPTY, EMPTY, null);
}
/**
* Test restoring in the same order of closing with the following actions/expected states:
* Action Model List Close List Comprehensive List
* 1. Initial State [ 0 1 2 3s ] - [ 0 1 2 3s ]
* 2. CloseTab(0, allow undo) [ 1 2 3s ] [ 0 ] [ 0 1 2 3s ]
* 3. CloseTab(1, allow undo) [ 2 3s ] [ 1 0 ] [ 0 1 2 3s ]
* 4. CloseTab(2, allow undo) [ 3s ] [ 2 1 0 ] [ 0 1 2 3s ]
* 5. CloseTab(3, allow undo) - [ 3 2 1 0 ] [ 0s 1 2 3 ]
* 6. CancelClose(3) [ 3s ] [ 2 1 0 ] [ 0 1 2 3s ]
* 7. CancelClose(2) [ 2 3s ] [ 1 0 ] [ 0 1 2 3s ]
* 8. CancelClose(1) [ 1 2 3s ] [ 0 ] [ 0 1 2 3s ]
* 9. CancelClose(0) [ 0 1 2 3s ] - [ 0 1 2 3s ]
* 10. SelectTab(3) [ 0 1 2 3s ] - [ 0 1 2 3s ]
* 11. CloseTab(3, allow undo) [ 0 1 2s ] [ 3 ] [ 0 1 2s 3 ]
* 12. CloseTab(2, allow undo) [ 0 1s ] [ 2 3 ] [ 0 1s 2 3 ]
* 13. CloseTab(1, allow undo) [ 0s ] [ 1 2 3 ] [ 0s 1 2 3 ]
* 14. CloseTab(0, allow undo) - [ 0 1 2 3 ] [ 0s 1 2 3 ]
* 15. CancelClose(0) [ 0s ] [ 1 2 3 ] [ 0s 1 2 3 ]
* 16. CancelClose(1) [ 0s 1 ] [ 2 3 ] [ 0s 1 2 3 ]
* 17. CancelClose(2) [ 0s 1 2 ] [ 3 ] [ 0s 1 2 3 ]
* 18. CancelClose(3) [ 0s 1 2 3 ] - [ 0s 1 2 3 ]
* 19. CloseTab(2, allow undo) [ 0s 1 3 ] [ 2 ] [ 0s 1 2 3 ]
* 20. CloseTab(0, allow undo) [ 1s 3 ] [ 0 2 ] [ 0 1s 2 3 ]
* 21. CloseTab(3, allow undo) [ 1s ] [ 3 0 2 ] [ 0 1s 2 3 ]
* 22. CancelClose(3) [ 1s 3 ] [ 0 2 ] [ 0 1s 2 3 ]
* 23. CancelClose(0) [ 0 1s 3 ] [ 2 ] [ 0 1s 2 3 ]
* 24. CancelClose(2) [ 0 1s 2 3 ] - [ 0 1s 2 3 ]
*
*/
@Test
@MediumTest
@RetryOnFailure
public void testInOrderRestore() throws TimeoutException {
TabModel model = mActivityTestRule.getActivity().getTabModelSelector().getModel(false);
ChromeTabCreator tabCreator = mActivityTestRule.getActivity().getTabCreator(false);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
Tab tab0 = model.getTabAt(0);
Tab tab1 = model.getTabAt(1);
Tab tab2 = model.getTabAt(2);
Tab tab3 = model.getTabAt(3);
final Tab[] fullList = new Tab[] { tab0, tab1, tab2, tab3 };
// 1.
checkState(model, new Tab[] { tab0, tab1, tab2, tab3 }, tab3, EMPTY, fullList, tab3);
// 2.
closeTabOnUiThread(model, tab0, true);
checkState(model, new Tab[] { tab1, tab2, tab3 }, tab3, new Tab[] { tab0 },
fullList, tab3);
// 3.
closeTabOnUiThread(model, tab1, true);
checkState(model, new Tab[] { tab2, tab3 }, tab3, new Tab[] { tab1, tab0 },
fullList, tab3);
// 4.
closeTabOnUiThread(model, tab2, true);
checkState(model, new Tab[] { tab3 }, tab3, new Tab[] { tab2, tab1, tab0 },
fullList, tab3);
// 5.
closeTabOnUiThread(model, tab3, true);
checkState(model, EMPTY, null, new Tab[] { tab3, tab2, tab1, tab0 }, fullList, tab0);
// 6.
cancelTabClosureOnUiThread(model, tab3);
checkState(model, new Tab[] { tab3 }, tab3, new Tab[] { tab2, tab1, tab0 },
fullList, tab3);
// 7.
cancelTabClosureOnUiThread(model, tab2);
checkState(model, new Tab[] { tab2, tab3 }, tab3, new Tab[] { tab1, tab0 },
fullList, tab3);
// 8.
cancelTabClosureOnUiThread(model, tab1);
checkState(model, new Tab[] { tab1, tab2, tab3 }, tab3, new Tab[] { tab0 },
fullList, tab3);
// 9.
cancelTabClosureOnUiThread(model, tab0);
checkState(model, new Tab[] { tab0, tab1, tab2, tab3 }, tab3, EMPTY, fullList, tab3);
// 10.
selectTabOnUiThread(model, tab3);
checkState(model, new Tab[] { tab0, tab1, tab2, tab3 }, tab3, EMPTY, fullList, tab3);
// 11.
closeTabOnUiThread(model, tab3, true);
checkState(model, new Tab[] { tab0, tab1, tab2 }, tab2, new Tab[] { tab3 },
fullList, tab2);
// 12.
closeTabOnUiThread(model, tab2, true);
checkState(model, new Tab[] { tab0, tab1 }, tab1, new Tab[] { tab2, tab3 },
fullList, tab1);
// 13.
closeTabOnUiThread(model, tab1, true);
checkState(model, new Tab[] { tab0 }, tab0, new Tab[] { tab1, tab2, tab3 },
fullList, tab0);
// 14.
closeTabOnUiThread(model, tab0, true);
checkState(model, EMPTY, null, new Tab[] { tab0, tab1, tab2, tab3 }, fullList, tab0);
// 15.
cancelTabClosureOnUiThread(model, tab0);
checkState(model, new Tab[] { tab0 }, tab0, new Tab[] { tab1, tab2, tab3 },
fullList, tab0);
// 16.
cancelTabClosureOnUiThread(model, tab1);
checkState(model, new Tab[] { tab0, tab1 }, tab0, new Tab[] { tab2, tab3 },
fullList, tab0);
// 17.
cancelTabClosureOnUiThread(model, tab2);
checkState(model, new Tab[] { tab0, tab1, tab2 }, tab0, new Tab[] { tab3 },
fullList, tab0);
// 18.
cancelTabClosureOnUiThread(model, tab3);
checkState(model, new Tab[] { tab0, tab1, tab2, tab3 }, tab0, EMPTY, fullList, tab0);
// 19.
closeTabOnUiThread(model, tab2, true);
checkState(model, new Tab[] { tab0, tab1, tab3 }, tab0, new Tab[] { tab2 },
fullList, tab0);
// 20.
closeTabOnUiThread(model, tab0, true);
checkState(model, new Tab[] { tab1, tab3 }, tab1, new Tab[] { tab0, tab2 },
fullList, tab1);
// 21.
closeTabOnUiThread(model, tab3, true);
checkState(model, new Tab[] { tab1 }, tab1, new Tab[] { tab3, tab0, tab2 },
fullList, tab1);
// 22.
cancelTabClosureOnUiThread(model, tab3);
checkState(model, new Tab[] { tab1, tab3 }, tab1, new Tab[] { tab0, tab2 },
fullList, tab1);
// 23.
cancelTabClosureOnUiThread(model, tab0);
checkState(model, new Tab[] { tab0, tab1, tab3 }, tab1, new Tab[] { tab2 },
fullList, tab1);
// 24.
cancelTabClosureOnUiThread(model, tab2);
checkState(model, new Tab[] { tab0, tab1, tab2, tab3 }, tab1, EMPTY, fullList, tab1);
}
/**
* Test restoring in the reverse of closing with the following actions/expected states:
* Action Model List Close List Comprehensive List
* 1. Initial State [ 0 1 2 3s ] - [ 0 1 2 3s ]
* 2. CloseTab(0, allow undo) [ 1 2 3s ] [ 0 ] [ 0 1 2 3s ]
* 3. CloseTab(1, allow undo) [ 2 3s ] [ 1 0 ] [ 0 1 2 3s ]
* 4. CloseTab(2, allow undo) [ 3s ] [ 2 1 0 ] [ 0 1 2 3s ]
* 5. CloseTab(3, allow undo) - [ 3 2 1 0 ] [ 0s 1 2 3 ]
* 6. CancelClose(0) [ 0s ] [ 3 2 1 ] [ 0s 1 2 3 ]
* 7. CancelClose(1) [ 0s 1 ] [ 3 2 ] [ 0s 1 2 3 ]
* 8. CancelClose(2) [ 0s 1 2 ] [ 3 ] [ 0s 1 2 3 ]
* 9. CancelClose(3) [ 0s 1 2 3 ] - [ 0s 1 2 3 ]
* 10. CloseTab(3, allow undo) [ 0s 1 2 ] [ 3 ] [ 0s 1 2 3 ]
* 11. CloseTab(2, allow undo) [ 0s 1 ] [ 2 3 ] [ 0s 1 2 3 ]
* 12. CloseTab(1, allow undo) [ 0s ] [ 1 2 3 ] [ 0s 1 2 3 ]
* 13. CloseTab(0, allow undo) - [ 0 1 2 3 ] [ 0s 1 2 3 ]
* 14. CancelClose(3) [ 3s ] [ 0 1 2 ] [ 0 1 2 3s ]
* 15. CancelClose(2) [ 2 3s ] [ 0 1 ] [ 0 1 2 3s ]
* 16. CancelClose(1) [ 1 2 3s ] [ 0 ] [ 0 1 2 3s ]
* 17. CancelClose(0) [ 0 1 2 3s ] - [ 0 1 2 3s ]
* 18. SelectTab(3) [ 0 1 2 3s ] - [ 0 1 2 3s ]
* 19. CloseTab(2, allow undo) [ 0 1 3s ] [ 2 ] [ 0 1 2 3s ]
* 20. CloseTab(0, allow undo) [ 1 3s ] [ 0 2 ] [ 0 1 2 3s ]
* 21. CloseTab(3, allow undo) [ 1s ] [ 3 0 2 ] [ 0 1s 2 3 ]
* 22. CancelClose(2) [ 1s 2 ] [ 3 0 ] [ 0 1s 2 3 ]
* 23. CancelClose(0) [ 0 1s 2 ] [ 3 ] [ 0 1s 2 3 ]
* 24. CancelClose(3) [ 0 1s 2 3 ] - [ 0 1s 2 3 ]
*
*/
@Test
@MediumTest
@Restriction(UiRestriction.RESTRICTION_TYPE_PHONE) // See crbug.com/633607
public void testReverseOrderRestore() throws TimeoutException {
TabModel model = mActivityTestRule.getActivity().getTabModelSelector().getModel(false);
ChromeTabCreator tabCreator = mActivityTestRule.getActivity().getTabCreator(false);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
Tab tab0 = model.getTabAt(0);
Tab tab1 = model.getTabAt(1);
Tab tab2 = model.getTabAt(2);
Tab tab3 = model.getTabAt(3);
Tab[] fullList = new Tab[] { tab0, tab1, tab2, tab3 };
// 1.
checkState(model, new Tab[] { tab0, tab1, tab2, tab3 }, tab3, EMPTY, fullList, tab3);
// 2.
closeTabOnUiThread(model, tab0, true);
checkState(model, new Tab[] { tab1, tab2, tab3 }, tab3, new Tab[] { tab0 },
fullList, tab3);
// 3.
closeTabOnUiThread(model, tab1, true);
checkState(model, new Tab[] { tab2, tab3 }, tab3, new Tab[] { tab1, tab0 },
fullList, tab3);
// 4.
closeTabOnUiThread(model, tab2, true);
checkState(model, new Tab[] { tab3 }, tab3, new Tab[] { tab2, tab1, tab0 },
fullList, tab3);
// 5.
closeTabOnUiThread(model, tab3, true);
checkState(model, EMPTY, null, new Tab[] { tab3, tab2, tab1, tab0 }, fullList, tab0);
// 6.
cancelTabClosureOnUiThread(model, tab0);
checkState(model, new Tab[] { tab0 }, tab0, new Tab[] { tab3, tab2, tab1 },
fullList, tab0);
// 7.
cancelTabClosureOnUiThread(model, tab1);
checkState(model, new Tab[] { tab0, tab1 }, tab0, new Tab[] { tab3, tab2 },
fullList, tab0);
// 8.
cancelTabClosureOnUiThread(model, tab2);
checkState(model, new Tab[] { tab0, tab1, tab2 }, tab0, new Tab[] { tab3 },
fullList, tab0);
// 9.
cancelTabClosureOnUiThread(model, tab3);
checkState(model, new Tab[] { tab0, tab1, tab2, tab3 }, tab0, EMPTY, fullList, tab0);
// 10.
closeTabOnUiThread(model, tab3, true);
checkState(model, new Tab[] { tab0, tab1, tab2 }, tab0, new Tab[] { tab3 },
fullList, tab0);
// 11.
closeTabOnUiThread(model, tab2, true);
checkState(model, new Tab[] { tab0, tab1 }, tab0, new Tab[] { tab2, tab3 },
fullList, tab0);
// 12.
closeTabOnUiThread(model, tab1, true);
checkState(model, new Tab[] { tab0 }, tab0, new Tab[] { tab1, tab2, tab3 },
fullList, tab0);
// 13.
closeTabOnUiThread(model, tab0, true);
checkState(model, EMPTY, null, new Tab[] { tab0, tab1, tab2, tab3 }, fullList, tab0);
// 14.
cancelTabClosureOnUiThread(model, tab3);
checkState(model, new Tab[] { tab3 }, tab3, new Tab[] { tab0, tab1, tab2 },
fullList, tab3);
// 15.
cancelTabClosureOnUiThread(model, tab2);
checkState(model, new Tab[] { tab2, tab3 }, tab3, new Tab[] { tab0, tab1 },
fullList, tab3);
// 16.
cancelTabClosureOnUiThread(model, tab1);
checkState(model, new Tab[] { tab1, tab2, tab3 }, tab3, new Tab[] { tab0 },
fullList, tab3);
// 17.
cancelTabClosureOnUiThread(model, tab0);
checkState(model, new Tab[] { tab0, tab1, tab2, tab3 }, tab3, EMPTY, fullList, tab3);
// 18.
selectTabOnUiThread(model, tab3);
checkState(model, new Tab[] { tab0, tab1, tab2, tab3 }, tab3, EMPTY, fullList, tab3);
// 19.
closeTabOnUiThread(model, tab2, true);
checkState(model, new Tab[] { tab0, tab1, tab3 }, tab3, new Tab[] { tab2 },
fullList, tab3);
// 20.
closeTabOnUiThread(model, tab0, true);
checkState(model, new Tab[] { tab1, tab3 }, tab3, new Tab[] { tab0, tab2 },
fullList, tab3);
// 21.
closeTabOnUiThread(model, tab3, true);
checkState(model, new Tab[] { tab1 }, tab1, new Tab[] { tab3, tab0, tab2 },
fullList, tab1);
// 22.
cancelTabClosureOnUiThread(model, tab2);
checkState(model, new Tab[] { tab1, tab2 }, tab1, new Tab[] { tab3, tab0 },
fullList, tab1);
// 23.
cancelTabClosureOnUiThread(model, tab0);
checkState(model, new Tab[] { tab0, tab1, tab2 }, tab1, new Tab[] { tab3 },
fullList, tab1);
// 24.
cancelTabClosureOnUiThread(model, tab3);
checkState(model, new Tab[] { tab0, tab1, tab2, tab3 }, tab1, EMPTY, fullList, tab1);
}
/**
* Test restoring out of order with the following actions/expected states:
* Action Model List Close List Comprehensive List
* 1. Initial State [ 0 1 2 3s ] - [ 0 1 2 3s ]
* 2. CloseTab(0, allow undo) [ 1 2 3s ] [ 0 ] [ 0 1 2 3s ]
* 3. CloseTab(1, allow undo) [ 2 3s ] [ 1 0 ] [ 0 1 2 3s ]
* 4. CloseTab(2, allow undo) [ 3s ] [ 2 1 0 ] [ 0 1 2 3s ]
* 5. CloseTab(3, allow undo) - [ 3 2 1 0 ] [ 0s 1 2 3 ]
* 6. CancelClose(2) [ 2s ] [ 3 1 0 ] [ 0 1 2s 3 ]
* 7. CancelClose(1) [ 1 2s ] [ 3 0 ] [ 0 1 2s 3 ]
* 8. CancelClose(3) [ 1 2s 3 ] [ 0 ] [ 0 1 2s 3 ]
* 9. CancelClose(0) [ 0 1 2s 3 ] - [ 0 1 2s 3 ]
* 10. CloseTab(1, allow undo) [ 0 2s 3 ] [ 1 ] [ 0 1 2s 3 ]
* 11. CancelClose(1) [ 0 1 2s 3 ] - [ 0 1 2s 3 ]
* 12. CloseTab(3, disallow undo) [ 0 1 2s ] - [ 0 1 2s ]
* 13. CloseTab(1, allow undo) [ 0 2s ] [ 1 ] [ 0 1 2s ]
* 14. CloseTab(0, allow undo) [ 2s ] [ 0 1 ] [ 0 1 2s ]
* 15. CommitClose(0) [ 2s ] [ 1 ] [ 1 2s ]
* 16. CancelClose(1) [ 1 2s ] - [ 1 2s ]
* 17. CloseTab(2, disallow undo) [ 1s ] - [ 1s ]
*
*/
@Test
@MediumTest
@RetryOnFailure
public void testOutOfOrder1() throws TimeoutException {
TabModel model = mActivityTestRule.getActivity().getTabModelSelector().getModel(false);
ChromeTabCreator tabCreator = mActivityTestRule.getActivity().getTabCreator(false);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
Tab tab0 = model.getTabAt(0);
Tab tab1 = model.getTabAt(1);
Tab tab2 = model.getTabAt(2);
Tab tab3 = model.getTabAt(3);
Tab[] fullList = new Tab[] { tab0, tab1, tab2, tab3 };
// 1.
checkState(model, new Tab[] { tab0, tab1, tab2, tab3 }, tab3, EMPTY, fullList, tab3);
// 2.
closeTabOnUiThread(model, tab0, true);
checkState(model, new Tab[] { tab1, tab2, tab3 }, tab3, new Tab[] { tab0 },
fullList, tab3);
// 3.
closeTabOnUiThread(model, tab1, true);
checkState(model, new Tab[] { tab2, tab3 }, tab3, new Tab[] { tab1, tab0 },
fullList, tab3);
// 4.
closeTabOnUiThread(model, tab2, true);
checkState(model, new Tab[] { tab3 }, tab3, new Tab[] { tab2, tab1, tab0 },
fullList, tab3);
// 5.
closeTabOnUiThread(model, tab3, true);
checkState(model, EMPTY, null, new Tab[] { tab3, tab2, tab1, tab0 }, fullList, tab0);
// 6.
cancelTabClosureOnUiThread(model, tab2);
checkState(model, new Tab[] { tab2 }, tab2, new Tab[] { tab3, tab1, tab0 },
fullList, tab2);
// 7.
cancelTabClosureOnUiThread(model, tab1);
checkState(model, new Tab[] { tab1, tab2 }, tab2, new Tab[] { tab3, tab0 },
fullList, tab2);
// 8.
cancelTabClosureOnUiThread(model, tab3);
checkState(model, new Tab[] { tab1, tab2, tab3 }, tab2, new Tab[] { tab0 },
fullList, tab2);
// 9.
cancelTabClosureOnUiThread(model, tab0);
checkState(model, new Tab[] { tab0, tab1, tab2, tab3 }, tab2, EMPTY, fullList, tab2);
// 10.
closeTabOnUiThread(model, tab1, true);
checkState(model, new Tab[] { tab0, tab2, tab3 }, tab2, new Tab[] { tab1 },
fullList, tab2);
// 11.
cancelTabClosureOnUiThread(model, tab1);
checkState(model, new Tab[] { tab0, tab1, tab2, tab3 }, tab2, EMPTY, fullList, tab2);
// 12.
closeTabOnUiThread(model, tab3, false);
fullList = new Tab[] { tab0, tab1, tab2 };
checkState(model, new Tab[] { tab0, tab1, tab2 }, tab2, EMPTY, fullList, tab2);
// 13.
closeTabOnUiThread(model, tab1, true);
checkState(model, new Tab[] { tab0, tab2 }, tab2, new Tab[] { tab1 }, fullList,
tab2);
// 14.
closeTabOnUiThread(model, tab0, true);
checkState(model, new Tab[] { tab2 }, tab2, new Tab[] { tab0, tab1 }, fullList,
tab2);
// 15.
commitTabClosureOnUiThread(model, tab0);
fullList = new Tab[] { tab1, tab2 };
checkState(model, new Tab[] { tab2 }, tab2, new Tab[] { tab1 }, fullList, tab2);
// 16.
cancelTabClosureOnUiThread(model, tab1);
checkState(model, new Tab[] { tab1, tab2 }, tab2, EMPTY, fullList, tab2);
// 17.
closeTabOnUiThread(model, tab2, false);
fullList = new Tab[] { tab1 };
checkState(model, new Tab[] { tab1 }, tab1, EMPTY, fullList, tab1);
}
/**
* Test restoring out of order with the following actions/expected states:
* Action Model List Close List Comprehensive List
* 1. Initial State [ 0 1 2 3s ] - [ 0 1 2 3s ]
* 2. CloseTab(1, allow undo) [ 0 2 3s ] [ 1 ] [ 0 1 2 3s ]
* 3. CloseTab(3, allow undo) [ 0 2s ] [ 3 1 ] [ 0 1 2s 3 ]
* 4. CancelClose(1) [ 0 1 2s ] [ 3 ] [ 0 1 2s 3 ]
* 5. CloseTab(2, allow undo) [ 0 1s ] [ 2 3 ] [ 0 1s 2 3 ]
* 6. CloseTab(0, allow undo) [ 1s ] [ 0 2 3 ] [ 0 1s 2 3 ]
* 7. CommitClose(0) [ 1s ] [ 2 3 ] [ 1s 2 3 ]
* 8. CancelClose(3) [ 1s 3 ] [ 2 ] [ 1s 2 3 ]
* 9. CloseTab(1, allow undo) [ 3s ] [ 1 2 ] [ 1 2 3s ]
* 10. CommitClose(2) [ 3s ] [ 1 ] [ 1 3s ]
* 11. CancelClose(1) [ 1 3s ] - [ 1 3s ]
* 12. CloseTab(3, allow undo) [ 1s ] [ 3 ] [ 1s 3 ]
* 13. CloseTab(1, allow undo) - [ 1 3 ] [ 1s 3 ]
* 14. CommitAll - - -
*
*/
@Test
@MediumTest
@FlakyTest(message = "crbug.com/592969")
public void testOutOfOrder2() throws TimeoutException {
TabModel model = mActivityTestRule.getActivity().getTabModelSelector().getModel(false);
ChromeTabCreator tabCreator = mActivityTestRule.getActivity().getTabCreator(false);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
Tab tab0 = model.getTabAt(0);
Tab tab1 = model.getTabAt(1);
Tab tab2 = model.getTabAt(2);
Tab tab3 = model.getTabAt(3);
Tab[] fullList = new Tab[] { tab0, tab1, tab2, tab3 };
// 1.
checkState(model, new Tab[] { tab0, tab1, tab2, tab3 }, tab3, EMPTY, fullList, tab3);
// 2.
closeTabOnUiThread(model, tab1, true);
checkState(model, new Tab[] { tab0, tab2, tab3 }, tab3, new Tab[] { tab1 },
fullList, tab3);
// 3.
closeTabOnUiThread(model, tab3, true);
checkState(model, new Tab[] { tab0, tab2 }, tab2, new Tab[] { tab3, tab1 },
fullList, tab2);
// 4.
cancelTabClosureOnUiThread(model, tab1);
checkState(model, new Tab[] { tab0, tab1, tab2 }, tab2, new Tab[] { tab3 },
fullList, tab2);
// 5.
closeTabOnUiThread(model, tab2, true);
checkState(model, new Tab[] { tab0, tab1 }, tab1, new Tab[] { tab2, tab3 },
fullList, tab1);
// 6.
closeTabOnUiThread(model, tab0, true);
checkState(model, new Tab[] { tab1 }, tab1, new Tab[] { tab0, tab2, tab3 },
fullList, tab1);
// 7.
commitTabClosureOnUiThread(model, tab0);
fullList = new Tab[] { tab1, tab2, tab3 };
checkState(model, new Tab[] { tab1 }, tab1, new Tab[] { tab2, tab3 }, fullList,
tab1);
// 8.
cancelTabClosureOnUiThread(model, tab3);
checkState(model, new Tab[] { tab1, tab3 }, tab1, new Tab[] { tab2 }, fullList,
tab1);
// 9.
closeTabOnUiThread(model, tab1, true);
checkState(model, new Tab[] { tab3 }, tab3, new Tab[] { tab1, tab2 }, fullList,
tab3);
// 10.
commitTabClosureOnUiThread(model, tab2);
fullList = new Tab[] { tab1, tab3 };
checkState(model, new Tab[] { tab3 }, tab3, new Tab[] { tab1 }, fullList, tab3);
// 11.
cancelTabClosureOnUiThread(model, tab1);
checkState(model, new Tab[] { tab1, tab3 }, tab3, EMPTY, fullList, tab3);
// 12.
closeTabOnUiThread(model, tab3, true);
checkState(model, new Tab[] { tab1 }, tab1, new Tab[] { tab3 }, fullList, tab1);
// 13.
closeTabOnUiThread(model, tab1, true);
checkState(model, EMPTY, null, new Tab[] { tab1, tab3 }, fullList, tab1);
// 14.
commitAllTabClosuresOnUiThread(model, new Tab[] { tab1, tab3 });
checkState(model, EMPTY, null, EMPTY, EMPTY, null);
}
/**
* Test undo {@link TabModel#closeAllTabs()} with the following actions/expected states:
* Action Model List Close List Comprehensive List
* 1. Initial State [ 0 1 2 3s ] - [ 0 1 2 3s ]
* 2. CloseTab(1, allow undo) [ 0 2 3s ] [ 1 ] [ 0 1 2 3s ]
* 3. CloseTab(2, allow undo) [ 0 3s ] [ 2 1 ] [ 0 1 2 3s ]
* 4. CloseAll - [ 0 3 2 1 ] [ 0s 1 2 3 ]
* 5. CancelAllClose [ 0 1 2 3s ] - [ 0 1 2 3s ]
* 6. CloseAll - [ 0 1 2 3 ] [ 0s 1 2 3 ]
* 7. CommitAllClose - - -
* 8. CreateTab(0) [ 0s ] - [ 0s ]
* 9. CloseAll - [ 0 ] [ 0s ]
*
*/
@Test
@MediumTest
@DisabledTest(message = "crbug.com/633607")
public void testCloseAll() throws TimeoutException {
TabModel model = mActivityTestRule.getActivity().getTabModelSelector().getModel(false);
ChromeTabCreator tabCreator = mActivityTestRule.getActivity().getTabCreator(false);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
Tab tab0 = model.getTabAt(0);
Tab tab1 = model.getTabAt(1);
Tab tab2 = model.getTabAt(2);
Tab tab3 = model.getTabAt(3);
Tab[] fullList = new Tab[] { tab0, tab1, tab2, tab3 };
// 1.
checkState(model, fullList, tab3, EMPTY, fullList, tab3);
// 2.
closeTabOnUiThread(model, tab1, true);
checkState(model, new Tab[] { tab0, tab2, tab3 }, tab3, new Tab[] { tab1 }, fullList, tab3);
// 3.
closeTabOnUiThread(model, tab2, true);
checkState(model, new Tab[] { tab0, tab3 }, tab3, new Tab[] { tab1, tab2 }, fullList, tab3);
// 4.
closeAllTabsOnUiThread(model);
checkState(model, EMPTY, null, fullList, fullList, tab0);
// 5.
cancelAllTabClosuresOnUiThread(model, fullList);
checkState(model, fullList, tab0, EMPTY, fullList, tab0);
// 6.
closeAllTabsOnUiThread(model);
checkState(model, EMPTY, null, fullList, fullList, tab0);
// 7.
commitAllTabClosuresOnUiThread(model, fullList);
checkState(model, EMPTY, null, EMPTY, EMPTY, null);
Assert.assertTrue(tab0.isClosing());
Assert.assertTrue(tab1.isClosing());
Assert.assertTrue(tab2.isClosing());
Assert.assertTrue(tab3.isClosing());
Assert.assertFalse(tab0.isInitialized());
Assert.assertFalse(tab1.isInitialized());
Assert.assertFalse(tab2.isInitialized());
Assert.assertFalse(tab3.isInitialized());
// 8.
createTabOnUiThread(tabCreator);
tab0 = model.getTabAt(0);
fullList = new Tab[] { tab0 };
checkState(model, new Tab[] { tab0 }, tab0, EMPTY, fullList, tab0);
// 9.
closeAllTabsOnUiThread(model);
checkState(model, EMPTY, null, fullList, fullList, tab0);
Assert.assertTrue(tab0.isClosing());
Assert.assertTrue(tab0.isInitialized());
}
/**
* Test {@link TabModel#closeTab(Tab)} when not allowing a close commits all pending
* closes:
* Action Model List Close List Comprehensive List
* 1. Initial State [ 0 1 2 3s ] - [ 0 1 2 3s ]
* 2. CloseTab(1, allow undo) [ 0 2 3s ] [ 1 ] [ 0 1 2 3s ]
* 3. CloseTab(2, allow undo) [ 0 3s ] [ 2 1 ] [ 0 1 2 3s ]
* 4. CloseTab(3, disallow undo) [ 0s ] - [ 0s ]
*
*/
@Test
@MediumTest
public void testCloseTab() throws TimeoutException {
TabModel model = mActivityTestRule.getActivity().getTabModelSelector().getModel(false);
ChromeTabCreator tabCreator = mActivityTestRule.getActivity().getTabCreator(false);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
Tab tab0 = model.getTabAt(0);
Tab tab1 = model.getTabAt(1);
Tab tab2 = model.getTabAt(2);
Tab tab3 = model.getTabAt(3);
Tab[] fullList = new Tab[] { tab0, tab1, tab2, tab3 };
// 1.
checkState(model, new Tab[] { tab0, tab1, tab2, tab3 }, tab3, EMPTY, fullList, tab3);
// 2.
closeTabOnUiThread(model, tab1, true);
checkState(model, new Tab[] { tab0, tab2, tab3 }, tab3, EMPTY, fullList, tab3);
// 3.
closeTabOnUiThread(model, tab2, true);
checkState(model, new Tab[] { tab0, tab3 }, tab3, EMPTY, fullList, tab3);
// 4.
closeTabOnUiThread(model, tab3, false);
fullList = new Tab[] { tab0 };
checkState(model, new Tab[] { tab0 }, tab0, EMPTY, fullList, tab0);
Assert.assertTrue(tab1.isClosing());
Assert.assertTrue(tab2.isClosing());
Assert.assertFalse(tab1.isInitialized());
Assert.assertFalse(tab2.isInitialized());
}
/**
* Test {@link TabModel#moveTab(int, int)} commits all pending closes:
* Action Model List Close List Comprehensive List
* 1. Initial State [ 0 1 2 3s ] - [ 0 1 2 3s ]
* 2. CloseTab(1, allow undo) [ 0 2 3s ] [ 1 ] [ 0 1 2 3s ]
* 3. CloseTab(2, allow undo) [ 0 3s ] [ 2 1 ] [ 0 1 2 3s ]
* 4. MoveTab(0, 2) [ 3s 0 ] - [ 3s 0 ]
*
*/
@Test
@MediumTest
@RetryOnFailure
public void testMoveTab() throws TimeoutException {
TabModel model = mActivityTestRule.getActivity().getTabModelSelector().getModel(false);
ChromeTabCreator tabCreator = mActivityTestRule.getActivity().getTabCreator(false);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
Tab tab0 = model.getTabAt(0);
Tab tab1 = model.getTabAt(1);
Tab tab2 = model.getTabAt(2);
Tab tab3 = model.getTabAt(3);
Tab[] fullList = new Tab[] { tab0, tab1, tab2, tab3 };
// 1.
checkState(model, new Tab[] { tab0, tab1, tab2, tab3 }, tab3, EMPTY, fullList, tab3);
// 2.
closeTabOnUiThread(model, tab1, true);
checkState(model, new Tab[] { tab0, tab2, tab3 }, tab3, EMPTY, fullList, tab3);
// 3.
closeTabOnUiThread(model, tab2, true);
checkState(model, new Tab[] { tab0, tab3 }, tab3, EMPTY, fullList, tab3);
// 4.
moveTabOnUiThread(model, tab0, 2);
fullList = new Tab[] { tab3, tab0 };
checkState(model, new Tab[] { tab3, tab0 }, tab3, EMPTY, fullList, tab3);
Assert.assertTrue(tab1.isClosing());
Assert.assertTrue(tab2.isClosing());
Assert.assertFalse(tab1.isInitialized());
Assert.assertFalse(tab1.isInitialized());
}
/**
* Test adding a {@link Tab} to a {@link TabModel} commits all pending closes:
* Action Model List Close List Comprehensive List
* 1. Initial State [ 0 1 2 3s ] - [ 0 1 2 3s ]
* 2. CloseTab(1, allow undo) [ 0 2 3s ] [ 1 ] [ 0 1 2 3s ]
* 3. CloseTab(2, allow undo) [ 0 3s ] [ 2 1 ] [ 0 1 2 3s ]
* 4. CreateTab(4) [ 0 3 4s ] - [ 0 3 4s ]
* 5. CloseTab(0, allow undo) [ 3 4s ] [ 0 ] [ 0 3 4s ]
* 6. CloseTab(3, allow undo) [ 4s ] [ 3 0 ] [ 0 3 4s ]
* 7. CloseTab(4, allow undo) - [ 4 3 0 ] [ 0s 3 4 ]
* 8. CreateTab(5) [ 5s ] - [ 5s ]
*/
//@MediumTest
//@Restriction(UiRestriction.RESTRICTION_TYPE_PHONE) // See crbug.com/633607
// Disabled due to flakiness on linux_android_rel_ng (crbug.com/661429)
@Test
@DisabledTest
public void testAddTab() throws TimeoutException {
TabModel model = mActivityTestRule.getActivity().getTabModelSelector().getModel(false);
ChromeTabCreator tabCreator = mActivityTestRule.getActivity().getTabCreator(false);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
Tab tab0 = model.getTabAt(0);
Tab tab1 = model.getTabAt(1);
Tab tab2 = model.getTabAt(2);
Tab tab3 = model.getTabAt(3);
Tab[] fullList = new Tab[] { tab0, tab1, tab2, tab3 };
// 1.
checkState(model, new Tab[] { tab0, tab1, tab2, tab3 }, tab3, EMPTY, fullList, tab3);
// 2.
closeTabOnUiThread(model, tab1, true);
checkState(model, new Tab[] { tab0, tab2, tab3 }, tab3, EMPTY, fullList, tab3);
// 3.
closeTabOnUiThread(model, tab2, true);
checkState(model, new Tab[] { tab0, tab3 }, tab3, EMPTY, fullList, tab3);
// 4.
createTabOnUiThread(tabCreator);
Tab tab4 = model.getTabAt(2);
fullList = new Tab[] { tab0, tab3, tab4 };
checkState(model, new Tab[] { tab0, tab3, tab4 }, tab4, EMPTY, fullList, tab4);
Assert.assertTrue(tab1.isClosing());
Assert.assertTrue(tab2.isClosing());
Assert.assertFalse(tab1.isInitialized());
Assert.assertFalse(tab2.isInitialized());
// 5.
closeTabOnUiThread(model, tab0, true);
checkState(model, new Tab[] { tab3, tab4 }, tab4, new Tab[] { tab0 }, fullList,
tab4);
// 6.
closeTabOnUiThread(model, tab3, true);
checkState(model, new Tab[] { tab4 }, tab4, new Tab[] { tab3, tab0 }, fullList,
tab4);
// 7.
closeTabOnUiThread(model, tab4, true);
checkState(model, EMPTY, null, new Tab[] { tab4, tab3, tab0 }, fullList, tab0);
// 8.
createTabOnUiThread(tabCreator);
Tab tab5 = model.getTabAt(0);
fullList = new Tab[] { tab5 };
checkState(model, new Tab[] { tab5 }, tab5, EMPTY, fullList, tab5);
Assert.assertTrue(tab0.isClosing());
Assert.assertTrue(tab3.isClosing());
Assert.assertTrue(tab4.isClosing());
Assert.assertFalse(tab0.isInitialized());
Assert.assertFalse(tab3.isInitialized());
Assert.assertFalse(tab4.isInitialized());
}
/**
* Test a {@link TabModel} where undo is not supported:
* Action Model List Close List Comprehensive List
* 1. Initial State [ 0 1 2 3s ] - [ 0 1 2 3s ]
* 2. CloseTab(1, allow undo) [ 0 2 3s ] - [ 0 2 3s ]
* 3. CloseAll - - -
*
*/
@Test
@MediumTest
@RetryOnFailure
@DisabledTest(message = "crbug.com/1042168")
public void testUndoNotSupported() throws TimeoutException {
TabModel model = mActivityTestRule.getActivity().getTabModelSelector().getModel(true);
ChromeTabCreator tabCreator = mActivityTestRule.getActivity().getTabCreator(true);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
createTabOnUiThread(tabCreator);
Tab tab0 = model.getTabAt(0);
Tab tab1 = model.getTabAt(1);
Tab tab2 = model.getTabAt(2);
Tab tab3 = model.getTabAt(3);
Tab[] fullList = new Tab[] { tab0, tab1, tab2, tab3 };
// 1.
checkState(model, new Tab[] { tab0, tab1, tab2, tab3 }, tab3, EMPTY, fullList, tab3);
Assert.assertFalse(model.supportsPendingClosures());
// 2.
closeTabOnUiThread(model, tab1, true);
fullList = new Tab[] { tab0, tab2, tab3 };
checkState(model, new Tab[] { tab0, tab2, tab3 }, tab3, EMPTY, fullList, tab3);
Assert.assertTrue(tab1.isClosing());
Assert.assertFalse(tab1.isInitialized());
// 3.
closeAllTabsOnUiThread(model);
checkState(model, EMPTY, null, EMPTY, EMPTY, null);
Assert.assertTrue(tab0.isClosing());
Assert.assertTrue(tab2.isClosing());
Assert.assertTrue(tab3.isClosing());
Assert.assertFalse(tab0.isInitialized());
Assert.assertFalse(tab2.isInitialized());
Assert.assertFalse(tab3.isInitialized());
}
/**
* Test calling {@link TabModelSelectorImpl#saveState()} commits all pending closures:
* Action Model List Close List Comprehensive List
* 1. Initial State [ 0 1s ] - [ 0 1s ]
* 2. CloseTab(0, allow undo) [ 1s ] [ 0 ] [ 0 1s ]
* 3. SaveState [ 1s ] - [ 1s ]
*/
@Test
@MediumTest
@Restriction(UiRestriction.RESTRICTION_TYPE_PHONE) // See crbug.com/633607
public void testSaveStateCommitsUndos() throws TimeoutException {
TabModelSelector selector = mActivityTestRule.getActivity().getTabModelSelector();
TabModel model = selector.getModel(false);
ChromeTabCreator tabCreator = mActivityTestRule.getActivity().getTabCreator(false);
createTabOnUiThread(tabCreator);
Tab tab0 = model.getTabAt(0);
Tab tab1 = model.getTabAt(1);
Tab[] fullList = new Tab[] { tab0, tab1 };
// 1.
checkState(model, new Tab[] { tab0, tab1 }, tab1, EMPTY, fullList, tab1);
// 2.
closeTabOnUiThread(model, tab0, true);
checkState(model, new Tab[] { tab1 }, tab1, EMPTY, fullList, tab1);
// 3.
saveStateOnUiThread(selector);
fullList = new Tab[] { tab1 };
checkState(model, new Tab[] { tab1 }, tab1, EMPTY, fullList, tab1);
Assert.assertTrue(tab0.isClosing());
Assert.assertFalse(tab0.isInitialized());
}
/**
* Test opening recently closed tabs using the rewound list in Java.
*/
@Test
@MediumTest
@RetryOnFailure
public void testOpenRecentlyClosedTab() throws TimeoutException {
TabModelSelector selector = mActivityTestRule.getActivity().getTabModelSelector();
TabModel model = selector.getModel(false);
ChromeTabCreator tabCreator = mActivityTestRule.getActivity().getTabCreator(false);
createTabOnUiThread(tabCreator);
Tab tab0 = model.getTabAt(0);
Tab tab1 = model.getTabAt(1);
Tab[] allTabs = new Tab[]{tab0, tab1};
closeTabOnUiThread(model, tab1, true);
checkState(model, new Tab[]{tab0}, tab0, new Tab[]{tab1}, allTabs, tab0);
// Ensure tab recovery, and reuse of {@link Tab} objects in Java.
openMostRecentlyClosedTabOnUiThread(selector);
checkState(model, allTabs, tab0, EMPTY, allTabs, tab0);
}
/**
* Test opening recently closed tab using native tab restore service.
*/
@Test
@MediumTest
public void testOpenRecentlyClosedTabNative() throws TimeoutException {
final TabModelSelector selector = mActivityTestRule.getActivity().getTabModelSelector();
final TabModel model = selector.getModel(false);
// Create new tab and wait until it's loaded.
// Native can only successfully recover the tab after a page load has finished and
// it has navigation history.
ChromeTabUtils.fullyLoadUrlInNewTab(InstrumentationRegistry.getInstrumentation(),
mActivityTestRule.getActivity(), TEST_URL_0, false);
// Close the tab, and commit pending closure.
Assert.assertEquals(model.getCount(), 2);
closeTabOnUiThread(model, model.getTabAt(1), false);
Assert.assertEquals(1, model.getCount());
Tab tab0 = model.getTabAt(0);
Tab[] tabs = new Tab[]{tab0};
checkState(model, tabs, tab0, EMPTY, tabs, tab0);
// Recover the page.
openMostRecentlyClosedTabOnUiThread(selector);
Assert.assertEquals(2, model.getCount());
tab0 = model.getTabAt(0);
Tab tab1 = model.getTabAt(1);
tabs = new Tab[]{tab0, tab1};
Assert.assertEquals(TEST_URL_0, tab1.getUrlString());
checkState(model, tabs, tab0, EMPTY, tabs, tab0);
}
/**
* Test opening recently closed tab when we have multiple windows.
* | Action | Result
* 1. Create second window. |
* 2. Open tab in window 1. |
* 3. Open tab in window 2. |
* 4. Close tab in window 1. |
* 5. Close tab in window 2. |
* 6. Restore tab. | Tab restored in window 2.
* 7. Restore tab. | Tab restored in window 1.
*/
@Test
@MediumTest
@MinAndroidSdkLevel(24)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@CommandLineFlags.Add(ChromeSwitches.DISABLE_TAB_MERGING_FOR_TESTING)
public void testOpenRecentlyClosedTabMultiWindow() throws TimeoutException {
final ChromeTabbedActivity2 secondActivity =
MultiWindowTestHelper.createSecondChromeTabbedActivity(
mActivityTestRule.getActivity());
// Wait for the second window to be fully initialized.
CriteriaHelper.pollUiThread(new Criteria() {
@Override
public boolean isSatisfied() {
return secondActivity.getTabModelSelector().isTabStateInitialized();
}
});
// First window context.
final TabModelSelector firstSelector =
mActivityTestRule.getActivity().getTabModelSelector();
final TabModel firstModel = firstSelector.getModel(false);
// Second window context.
final TabModel secondModel = secondActivity.getTabModelSelector().getModel(false);
// Create tabs.
ChromeTabUtils.fullyLoadUrlInNewTab(InstrumentationRegistry.getInstrumentation(),
mActivityTestRule.getActivity(), TEST_URL_0, false);
ChromeTabUtils.fullyLoadUrlInNewTab(
InstrumentationRegistry.getInstrumentation(), secondActivity, TEST_URL_1, false);
Assert.assertEquals("Unexpected number of tabs in first window.", 2, firstModel.getCount());
Assert.assertEquals(
"Unexpected number of tabs in second window.", 2, secondModel.getCount());
// Close one tab in the first window.
closeTabOnUiThread(firstModel, firstModel.getTabAt(1), false);
Assert.assertEquals("Unexpected number of tabs in first window.", 1, firstModel.getCount());
Assert.assertEquals(
"Unexpected number of tabs in second window.", 2, secondModel.getCount());
// Close one tab in the second window.
closeTabOnUiThread(secondModel, secondModel.getTabAt(1), false);
Assert.assertEquals("Unexpected number of tabs in first window.", 1, firstModel.getCount());
Assert.assertEquals(
"Unexpected number of tabs in second window.", 1, secondModel.getCount());
// Restore one tab.
openMostRecentlyClosedTabOnUiThread(firstSelector);
Assert.assertEquals("Unexpected number of tabs in first window.", 1, firstModel.getCount());
Assert.assertEquals(
"Unexpected number of tabs in second window.", 2, secondModel.getCount());
// Restore one more tab.
openMostRecentlyClosedTabOnUiThread(firstSelector);
// Check final states of both windows.
Tab firstModelTab = firstModel.getTabAt(0);
Tab secondModelTab = secondModel.getTabAt(0);
Tab[] firstWindowTabs = new Tab[]{firstModelTab, firstModel.getTabAt(1)};
Tab[] secondWindowTabs = new Tab[]{secondModelTab, secondModel.getTabAt(1)};
checkState(firstModel, firstWindowTabs, firstModelTab, EMPTY, firstWindowTabs,
firstModelTab);
checkState(secondModel, secondWindowTabs, secondModelTab, EMPTY, secondWindowTabs,
secondModelTab);
Assert.assertEquals(TEST_URL_0, firstWindowTabs[1].getUrlString());
Assert.assertEquals(TEST_URL_1, secondWindowTabs[1].getUrlString());
secondActivity.finishAndRemoveTask();
}
/**
* Test restoring closed tab from a closed window.
* | Action | Result
* 1. Create second window. |
* 2. Open tab in window 2. |
* 3. Close tab in window 2. |
* 4. Close second window. |
* 5. Restore tab. | Tab restored in first window.
*/
@Test
@MediumTest
@MinAndroidSdkLevel(24)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@CommandLineFlags.Add(ChromeSwitches.DISABLE_TAB_MERGING_FOR_TESTING)
public void testOpenRecentlyClosedTabMultiWindowFallback() throws TimeoutException {
final ChromeTabbedActivity2 secondActivity =
MultiWindowTestHelper.createSecondChromeTabbedActivity(
mActivityTestRule.getActivity());
// Wait for the second window to be fully initialized.
CriteriaHelper.pollUiThread(new Criteria() {
@Override
public boolean isSatisfied() {
return secondActivity.getTabModelSelector().isTabStateInitialized();
}
});
// First window context.
final TabModelSelector firstSelector =
mActivityTestRule.getActivity().getTabModelSelector();
final TabModel firstModel = firstSelector.getModel(false);
// Second window context.
final TabModel secondModel = secondActivity.getTabModelSelector().getModel(false);
// Create tab on second window.
ChromeTabUtils.fullyLoadUrlInNewTab(
InstrumentationRegistry.getInstrumentation(), secondActivity, TEST_URL_1, false);
Assert.assertEquals("Window 2 should have 2 tab.", 2, secondModel.getCount());
// Close tab in second window, wait until tab restore service history is created.
CallbackHelper closedCallback = new CallbackHelper();
secondModel.addObserver(new TabClosedObserver(closedCallback));
closeTabOnUiThread(secondModel, secondModel.getTabAt(1), false);
closedCallback.waitForCallback(0);
Assert.assertEquals("Window 2 should have 1 tab.", 1, secondModel.getCount());
// Closed the second window. Must wait until it's totally closed.
int numExpectedActivities = ApplicationStatus.getRunningActivities().size() - 1;
secondActivity.finishAndRemoveTask();
CriteriaHelper.pollUiThread(Criteria.equals(numExpectedActivities, new Callable<Integer>() {
@Override
public Integer call() {
return ApplicationStatus.getRunningActivities().size();
}
}));
Assert.assertEquals("Window 1 should have 1 tab.", 1, firstModel.getCount());
// Restore closed tab from second window. It should be created in first window.
openMostRecentlyClosedTabOnUiThread(firstSelector);
Assert.assertEquals("Closed tab in second window should be restored in the first window.",
2, firstModel.getCount());
Tab tab0 = firstModel.getTabAt(0);
Tab tab1 = firstModel.getTabAt(1);
Tab[] firstWindowTabs = new Tab[]{tab0, tab1};
checkState(firstModel, firstWindowTabs, tab0, EMPTY, firstWindowTabs, tab0);
Assert.assertEquals(TEST_URL_1, tab1.getUrlString());
}
}
|
endlessm/chromium-browser
|
chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/UndoTabModelTest.java
|
Java
|
bsd-3-clause
| 70,523 |
;
; Copyright (c) 2010 The VP8 project authors. All Rights Reserved.
;
; Use of this source code is governed by a BSD-style license
; that can be found in the LICENSE file in the root of the source
; tree. An additional intellectual property rights grant can be found
; in the file PATENTS. All contributing project authors may
; be found in the AUTHORS file in the root of the source tree.
;
EXPORT |vp8_short_walsh4x4_neon|
ARM
REQUIRE8
PRESERVE8
AREA ||.text||, CODE, READONLY, ALIGN=2
;void vp8_short_walsh4x4_c(short *input, short *output, int pitch)
|vp8_short_walsh4x4_neon| PROC
vld1.16 {d2}, [r0], r2 ;load input
vld1.16 {d3}, [r0], r2
vld1.16 {d4}, [r0], r2
vld1.16 {d5}, [r0], r2
;First for-loop
;transpose d2, d3, d4, d5. Then, d2=ip[0], d3=ip[1], d4=ip[2], d5=ip[3]
vtrn.32 d2, d4
vtrn.32 d3, d5
vtrn.16 d2, d3
vtrn.16 d4, d5
vadd.s16 d6, d2, d5 ;a1 = ip[0]+ip[3]
vadd.s16 d7, d3, d4 ;b1 = ip[1]+ip[2]
vsub.s16 d8, d3, d4 ;c1 = ip[1]-ip[2]
vsub.s16 d9, d2, d5 ;d1 = ip[0]-ip[3]
vadd.s16 d2, d6, d7 ;op[0] = a1 + b1
vsub.s16 d4, d6, d7 ;op[2] = a1 - b1
vadd.s16 d3, d8, d9 ;op[1] = c1 + d1
vsub.s16 d5, d9, d8 ;op[3] = d1 - c1
;Second for-loop
;transpose d2, d3, d4, d5. Then, d2=ip[0], d3=ip[4], d4=ip[8], d5=ip[12]
vtrn.32 d2, d4
vtrn.32 d3, d5
vtrn.16 d2, d3
vtrn.16 d4, d5
vadd.s16 d6, d2, d5 ;a1 = ip[0]+ip[12]
vadd.s16 d7, d3, d4 ;b1 = ip[4]+ip[8]
vsub.s16 d8, d3, d4 ;c1 = ip[4]-ip[8]
vsub.s16 d9, d2, d5 ;d1 = ip[0]-ip[12]
vadd.s16 d2, d6, d7 ;a2 = a1 + b1;
vsub.s16 d4, d6, d7 ;c2 = a1 - b1;
vadd.s16 d3, d8, d9 ;b2 = c1 + d1;
vsub.s16 d5, d9, d8 ;d2 = d1 - c1;
vcgt.s16 q3, q1, #0
vcgt.s16 q4, q2, #0
vsub.s16 q1, q1, q3
vsub.s16 q2, q2, q4
vshr.s16 q1, q1, #1
vshr.s16 q2, q2, #1
vst1.16 {q1, q2}, [r1]
bx lr
ENDP
END
|
mrchapp/libvpx
|
vp8/encoder/arm/neon/vp8_shortwalsh4x4_neon.asm
|
Assembly
|
bsd-3-clause
| 2,443 |
/*
* This file is part of the Jikes RVM project (http://jikesrvm.org).
*
* This file is licensed to You under the Common Public License (CPL);
* You may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.opensource.org/licenses/cpl1.0.php
*
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership.
*/
package java.lang;
import org.jikesrvm.runtime.Magic;
/**
* Float <==> int bit transfer for Jikes RVM.
*/
final class VMFloat {
static int floatToIntBits(float value) {
// Check for NaN and return canonical NaN value
if (value != value) return 0x7fc00000;
else return Magic.floatAsIntBits(value);
}
static int floatToRawIntBits(float value) {
return Magic.floatAsIntBits(value);
}
static float intBitsToFloat(int bits) {
return Magic.intBitsAsFloat(bits);
}
static String toString(float f) {
return VMDouble.toString((double) f, true);
}
static float parseFloat(String str) {
return (float) VMDouble.parseDouble(str);
}
}
|
ut-osa/laminar
|
jikesrvm-3.0.0/libraryInterface/GNUClasspath/CPL/src/java/lang/VMFloat.java
|
Java
|
bsd-3-clause
| 1,113 |
package org.lielas.micdataloggerstudio.main;
import org.lielas.dataloggerstudio.lib.LoggerRecord;
/**
* Created by Andi on 11.04.2015.
*/
public class LoggerRecordManager {
private LoggerRecord activeLoggerRecord;
private static LoggerRecordManager instance;
public static LoggerRecordManager getInstance(){
if(instance == null){
instance = new LoggerRecordManager();
}
return instance;
}
public LoggerRecordManager(){
activeLoggerRecord = null;
}
public void setActiveLoggerRecord(LoggerRecord lr){
activeLoggerRecord = lr;
}
public LoggerRecord getActiveLoggerRecord(){
return activeLoggerRecord;
}
}
|
anre/LielasDataloggerstudio
|
src/dataloggerstudio/android/micdataloggerstudio/main/LoggerRecordManager.java
|
Java
|
bsd-3-clause
| 714 |
#include <QString>
#include <QtTest>
#include <QCoreApplication>
#include <testlib.h>
#include <QtDataSync/private/changecontroller_p.h>
#include <QtDataSync/private/synchelper_p.h>
#include <QtDataSync/private/defaults_p.h>
//DIRTY HACK: allow access for test
#define private public
#include <QtDataSync/private/exchangeengine_p.h>
#undef private
#include <QtDataSync/private/setup_p.h>
using namespace QtDataSync;
class TestChangeController : public QObject
{
Q_OBJECT
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void testChanges_data();
void testChanges();
void testDeviceChanges();
//last test, to avoid problems
void testChangeTriggers();
void testPassiveTriggers();
private:
LocalStore *store;
ChangeController *controller;
};
void TestChangeController::initTestCase()
{
try {
TestLib::init();
Setup setup;
TestLib::setup(setup);
setup.create();
auto engine = SetupPrivate::engine(DefaultSetup);
store = new LocalStore(DefaultsPrivate::obtainDefaults(DefaultSetup), this);
controller = new ChangeController(DefaultsPrivate::obtainDefaults(DefaultSetup), this);
controller->initialize({
{QStringLiteral("store"), QVariant::fromValue(store)},
{QStringLiteral("emitter"), QVariant::fromValue<QObject*>(reinterpret_cast<QObject*>(engine->emitter()))}, //trick to pass the unexported type to qvariant
});
} catch(QException &e) {
QFAIL(e.what());
}
}
void TestChangeController::cleanupTestCase()
{
controller->finalize();
delete controller;
controller = nullptr;
delete store;
store = nullptr;
Setup::removeSetup(DefaultSetup, true);
}
void TestChangeController::testChanges_data()
{
QTest::addColumn<ObjectKey>("key");
QTest::addColumn<QJsonObject>("data");
QTest::addColumn<bool>("isDelete");
QTest::addColumn<quint64>("version");
QTest::addColumn<bool>("complete");
QTest::newRow("change1") << TestLib::generateKey(42)
<< TestLib::generateDataJson(42)
<< false
<< 1ull
<< false;
QTest::newRow("change2") << TestLib::generateKey(42)
<< TestLib::generateDataJson(42, QStringLiteral("hello world"))
<< false
<< 2ull
<< false;
QTest::newRow("delete3") << TestLib::generateKey(42)
<< QJsonObject()
<< true
<< 3ull
<< false;
QTest::newRow("change4") << TestLib::generateKey(42)
<< TestLib::generateDataJson(42)
<< false
<< 4ull
<< true;
QTest::newRow("delete5") << TestLib::generateKey(42)
<< QJsonObject()
<< true
<< 5ull
<< true;
QTest::newRow("delete0") << TestLib::generateKey(42)
<< QJsonObject()
<< true
<< 0ull
<< true;
QTest::newRow("change1") << TestLib::generateKey(42)
<< TestLib::generateDataJson(42)
<< false
<< 1ull
<< true;
}
void TestChangeController::testChanges()
{
QFETCH(ObjectKey, key);
QFETCH(QJsonObject, data);
QFETCH(bool, isDelete);
QFETCH(quint64, version);
QFETCH(bool, complete);
controller->setUploadingEnabled(false);
QCoreApplication::processEvents();
QSignalSpy activeSpy(controller, &ChangeController::uploadingChanged);
QSignalSpy changeSpy(controller, &ChangeController::uploadChange);
QSignalSpy addedSpy(controller, &ChangeController::progressAdded);
QSignalSpy incrementSpy(controller, &ChangeController::progressIncrement);
QSignalSpy errorSpy(controller, &ChangeController::controllerError);
try {
//trigger the change
if(isDelete)
store->remove(key);
else
store->save(key, data);
//enable changes
controller->setUploadingEnabled(true);
if(!errorSpy.isEmpty())
QFAIL(errorSpy.takeFirst()[0].toString().toUtf8().constData());
if(version == 0) {
QVERIFY(!activeSpy.last()[0].toBool());
QVERIFY(changeSpy.isEmpty());
QVERIFY(errorSpy.isEmpty());
return;
}
QCOMPARE(changeSpy.size(), 1);
QVERIFY(activeSpy.last()[0].toBool());
QCOMPARE(addedSpy.size(), 1);
QCOMPARE(addedSpy.takeFirst()[0].toUInt(), 1u);
auto change = changeSpy.takeFirst();
auto keyHash = change[0].toByteArray();
auto syncData = SyncHelper::extract(change[1].toByteArray());
QCOMPARE(std::get<0>(syncData), isDelete);
QCOMPARE(std::get<1>(syncData), key);
QCOMPARE(std::get<2>(syncData), version);
QCOMPARE(std::get<3>(syncData), data);
if(complete) {
controller->uploadDone(keyHash);
QCOMPARE(store->changeCount(), 0u);
QCOMPARE(incrementSpy.size(), 1);
} else
QVERIFY(incrementSpy.isEmpty());
} catch(QException &e) {
QFAIL(e.what());
}
controller->clearUploads();
}
void TestChangeController::testDeviceChanges()
{
controller->setUploadingEnabled(false);
QCoreApplication::processEvents();
QSignalSpy activeSpy(controller, &ChangeController::uploadingChanged);
QSignalSpy changeSpy(controller, &ChangeController::uploadChange);
QSignalSpy deviceChangeSpy(controller, &ChangeController::uploadDeviceChange);
QSignalSpy addedSpy(controller, &ChangeController::progressAdded);
QSignalSpy incrementSpy(controller, &ChangeController::progressIncrement);
QSignalSpy errorSpy(controller, &ChangeController::controllerError);
try {
auto devId = QUuid::createUuid();
//Create the device changes
store->reset(false);
store->save(TestLib::generateKey(42), TestLib::generateDataJson(42));
store->save(TestLib::generateKey(43), TestLib::generateDataJson(43));
store->remove(TestLib::generateKey(43));
store->save(TestLib::generateKey(44), TestLib::generateDataJson(44));
store->save(TestLib::generateKey(45), TestLib::generateDataJson(45));
store->remove(TestLib::generateKey(45));
store->markUnchanged(TestLib::generateKey(42), 1, false);
store->markUnchanged(TestLib::generateKey(43), 2, false); //fake persistet
store->prepareAccountAdded(devId);
//enable changes
controller->setUploadingEnabled(true);
if(!errorSpy.isEmpty())
QFAIL(errorSpy.takeFirst()[0].toString().toUtf8().constData());
QCOMPARE(changeSpy.size(), 2);
QCOMPARE(deviceChangeSpy.size(), 3);
QCOMPARE(addedSpy.size(), 1);
QCOMPARE(addedSpy.takeFirst()[0].toUInt(), 5u);
QVERIFY(activeSpy.last()[0].toBool());
QCOMPARE(store->changeCount(), 5u);
auto change = changeSpy.takeFirst();
auto keyHash = change[0].toByteArray();
controller->uploadDone(keyHash);
QCOMPARE(changeSpy.size(), 1);
QCOMPARE(deviceChangeSpy.size(), 3);
QCOMPARE(store->changeCount(), 4u);
QCOMPARE(incrementSpy.size(), 1);
change = changeSpy.takeFirst();
keyHash = change[0].toByteArray();
controller->uploadDone(keyHash);
QCOMPARE(changeSpy.size(), 0);
QCOMPARE(deviceChangeSpy.size(), 3);
QCOMPARE(store->changeCount(), 3u);
QCOMPARE(incrementSpy.size(), 2);
change = deviceChangeSpy.takeFirst();
keyHash = change[0].toByteArray();
controller->deviceUploadDone(keyHash, devId);
QCOMPARE(changeSpy.size(), 0);
QCOMPARE(deviceChangeSpy.size(), 2);
QCOMPARE(store->changeCount(), 2u);
QCOMPARE(incrementSpy.size(), 3);
change = deviceChangeSpy.takeFirst();
keyHash = change[0].toByteArray();
controller->deviceUploadDone(keyHash, devId);
QCOMPARE(changeSpy.size(), 0);
QCOMPARE(deviceChangeSpy.size(), 1);
QCOMPARE(store->changeCount(), 1u);
QCOMPARE(incrementSpy.size(), 4);
change = deviceChangeSpy.takeFirst();
keyHash = change[0].toByteArray();
controller->deviceUploadDone(keyHash, devId);
QCOMPARE(changeSpy.size(), 0);
QCOMPARE(deviceChangeSpy.size(), 0);
QCOMPARE(store->changeCount(), 0u);
QCOMPARE(incrementSpy.size(), 5);
QVERIFY(!deviceChangeSpy.wait());
QVERIFY(changeSpy.isEmpty());
QVERIFY(deviceChangeSpy.isEmpty());
store->reset(false);
} catch(QException &e) {
QFAIL(e.what());
}
controller->clearUploads();
}
void TestChangeController::testChangeTriggers()
{
for(auto i = 0; i < 5; i++) { //wait for the engine to init itself
QCoreApplication::processEvents();
QThread::msleep(100);
}
//DIRTY HACK: force the engine pass the local controller to anyone asking
auto engine = SetupPrivate::engine(DefaultSetup);
auto old = engine->_changeController;
engine->_changeController = controller;
//enable changes
controller->setUploadingEnabled(true);
QCoreApplication::processEvents();
QSignalSpy activeSpy(controller, &ChangeController::uploadingChanged);
QSignalSpy changeSpy(controller, &ChangeController::uploadChange);
QSignalSpy addedSpy(controller, &ChangeController::progressAdded);
QSignalSpy incrementSpy(controller, &ChangeController::progressIncrement);
QSignalSpy errorSpy(controller, &ChangeController::controllerError);
try {
//clear
store->reset(false);
QVERIFY(changeSpy.isEmpty());
QVERIFY(errorSpy.isEmpty());
auto key = TestLib::generateKey(10);
auto data = TestLib::generateDataJson(10);
//save data
store->save(key, data);
QVERIFY(changeSpy.wait());
QVERIFY(activeSpy.last()[0].toBool());
QCOMPARE(addedSpy.size(), 1);
QCOMPARE(addedSpy.takeFirst()[0].toUInt(), 1u);
if(!errorSpy.isEmpty())
QFAIL(errorSpy.takeFirst()[0].toString().toUtf8().constData());
QCOMPARE(changeSpy.size(), 1);
auto change = changeSpy.takeFirst();
auto keyHash = change[0].toByteArray();
QCOMPARE(change[1].toByteArray(), SyncHelper::combine(key, 1, data));
controller->uploadDone(keyHash);
QVERIFY(activeSpy.wait());
QVERIFY(!activeSpy.last()[0].toBool());
QVERIFY(changeSpy.isEmpty());
QCOMPARE(incrementSpy.size(), 1);
QVERIFY(errorSpy.isEmpty());
//now a delete
store->remove(key);
QVERIFY(changeSpy.wait());
QVERIFY(activeSpy.last()[0].toBool());
QCOMPARE(addedSpy.size(), 1);
QCOMPARE(addedSpy.takeFirst()[0].toUInt(), 1u);
if(!errorSpy.isEmpty())
QFAIL(errorSpy.takeFirst()[0].toString().toUtf8().constData());
QCOMPARE(changeSpy.size(), 1);
change = changeSpy.takeFirst();
keyHash = change[0].toByteArray();
QCOMPARE(change[1].toByteArray(), SyncHelper::combine(key, 2));
controller->uploadDone(keyHash);
QVERIFY(activeSpy.wait());
QVERIFY(!activeSpy.last()[0].toBool());
QVERIFY(changeSpy.isEmpty());
QVERIFY(errorSpy.isEmpty());
QCOMPARE(incrementSpy.size(), 2);
engine->_changeController = old;
} catch(QException &e) {
engine->_changeController = old;
QFAIL(e.what());
}
}
void TestChangeController::testPassiveTriggers()
{
for(auto i = 0; i < 5; i++) { //wait for the engine to init itself
QCoreApplication::processEvents();
QThread::msleep(100);
}
//DIRTY HACK: force the engine pass the local controller to anyone asking
auto engine = SetupPrivate::engine(DefaultSetup);
auto old = engine->_changeController;
engine->_changeController = controller;
//enable changes
controller->setUploadingEnabled(true);
QCoreApplication::processEvents();
QSignalSpy changeSpy(controller, &ChangeController::uploadChange);
try {
auto nName = QStringLiteral("setup2");
Setup setup;
TestLib::setup(setup);
setup.setRemoteObjectHost(QStringLiteral("threaded:/qtdatasync/default/enginenode"));
QVERIFY(setup.createPassive(nName, 5000));
auto key = TestLib::generateKey(22);
auto data = TestLib::generateDataJson(22);
{
LocalStore second(DefaultsPrivate::obtainDefaults(nName));
second.save(key, data);
QVERIFY(changeSpy.wait());
QCOMPARE(changeSpy.size(), 1);
auto change = changeSpy.takeFirst();
QCOMPARE(change[1].toByteArray(), SyncHelper::combine(key, 1, data));
}
Setup::removeSetup(nName);
engine->_changeController = old;
} catch(QException &e) {
engine->_changeController = old;
QFAIL(e.what());
}
}
QTEST_MAIN(TestChangeController)
#include "tst_changecontroller.moc"
|
Skycoder42/QtDataSync
|
tests/auto/datasync/TestChangeController/tst_changecontroller.cpp
|
C++
|
bsd-3-clause
| 11,600 |
package gore
import (
"io/ioutil"
"os"
"testing"
)
func init() {
if os.Getenv("TEST_REDIS_CLIENT") != "" {
shouldTest = true
}
}
var scriptSet = `
return redis.call('SET', KEYS[1], ARGV[1])
`
var scriptGet = `
return redis.call('GET', KEYS[1])
`
var scriptError = `
return redis.call('ZRANGE', KEYS[1], 0, -1)
`
func TestScript(t *testing.T) {
if !shouldTest {
return
}
conn, err := Dial("localhost:6379")
if err != nil {
t.Fatal(err)
}
defer conn.Close()
s := NewScript()
s.SetBody(scriptSet)
rep, err := s.Execute(conn, 1, "kirisame", "marisa")
if err != nil || !rep.IsOk() {
t.Fatal(err, rep)
}
s.SetBody(scriptGet)
rep, err = s.Execute(conn, 1, "kirisame")
if err != nil {
t.Fatal(err)
}
val, err := rep.String()
if err != nil || val != "marisa" {
t.Fatal(err, val)
}
s.SetBody(scriptError)
rep, err = s.Execute(conn, 1, "kirisame")
if err != nil || !rep.IsError() {
t.Fatal(err, rep)
}
rep, err = NewCommand("FLUSHALL").Run(conn)
if err != nil || !rep.IsOk() {
t.Fatal(err, "not ok")
}
}
func TestScriptMap(t *testing.T) {
err := os.MkdirAll("testscripts", 0755)
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll("testscripts")
err = ioutil.WriteFile("testscripts/set.lua", []byte(scriptSet), 0644)
if err != nil {
t.Fatal(err)
}
err = ioutil.WriteFile("testscripts/get.lua", []byte(scriptGet), 0644)
if err != nil {
t.Fatal(err)
}
err = ioutil.WriteFile("testscripts/error.lua", []byte(scriptError), 0644)
if err != nil {
t.Fatal(err)
}
err = LoadScripts("testscripts", ".*\\.lua")
if err != nil {
t.Fatal(err)
}
if !shouldTest {
return
}
conn, err := Dial("localhost:6379")
if err != nil {
t.Fatal(err)
}
defer conn.Close()
s := GetScript("set.lua")
rep, err := s.Execute(conn, 1, "kirisame", "marisa")
if err != nil || !rep.IsOk() {
t.Fatal(err, rep)
}
s = GetScript("get.lua")
rep, err = s.Execute(conn, 1, "kirisame")
if err != nil {
t.Fatal(err)
}
val, err := rep.String()
if err != nil || val != "marisa" {
t.Fatal(err, val)
}
s = GetScript("error.lua")
rep, err = s.Execute(conn, 1, "kirisame")
if err != nil || !rep.IsError() {
t.Fatal(err, rep)
}
rep, err = NewCommand("FLUSHALL").Run(conn)
if err != nil || !rep.IsOk() {
t.Fatal(err, "not ok")
}
}
|
keimoon/gore
|
script_test.go
|
GO
|
bsd-3-clause
| 2,285 |
<?php
use yii\helpers\Html;
use kartik\grid\GridView;
use yii\widgets\Pjax;
use yii\helpers\Url;
use yii\bootstrap\Modal;
use yii\helpers\Json;
use kartik\widgets\FileInput;
use kartik\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $searchModel backend\modules\permitapp\models\DriversSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'ข้อมูลคนขับรถ';
$this->params['breadcrumbs'][] = $this->title;
/* * ********************************************************
*
* Javascript event handlers
*
* ********************************************************* */
//This handles the clicking of the refresh button on the grid
$this->registerJs(
"$(document).on('click', \"#refresh_ingredients_grid\", function()
{
$.pjax.reload({container:\"#order_ingredient_grid\"});
});"
);
//This handles the change of customer details
$this->registerJs("$('#customerorders-customer_id').on('change',function(){
updateOrderDetails();
});");
//Action on adding an ingredient data: {id: ".$model->id."},
$this->registerJs(
"$(document).on('click', '#add_ingredient_button', function()
{
$.ajax
({
url: '" . yii\helpers\Url::toRoute("/permitapp/drivers/create") . "',
success: function (data, textStatus, jqXHR)
{
$('#activity-modal').modal();
$('.modal-body').html(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log('An error occured!');
alert('Error in ajax request' );
}
});
});"
);
//action on clicking the ingredient percentage amount link in the grid data: {id: ".$model->id."},
$this->registerJs(
"$(document).on('click', \".sap_edit_ingredient_link\", function()
{
var ingredientID = ($(this).attr('ingredientId'));
$.ajax
({
url: '" . yii\helpers\Url::toRoute("customer-order/ajax-update-ingredient") . "',
data: {id: ingredientID},
success: function (data, textStatus, jqXHR)
{
$('#activity-modal').modal();
$('.modal-body').html(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log('An error occured!');
alert('Error in ajax request' );
}
});
});"
);
//action on submiting the ingredient add form
$this->registerJs("
$('body').on('beforeSubmit', 'form#ingredient_add', function () {
var form = $(this);
// return false if form still have some validation errors
if (form.find('.has-error').length) {
return false;
}
// submit form
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
success: function (response)
{
$('#activity-modal').modal('hide');
$.pjax.reload({container:'#order_ingredient_grid'});
}
});
return false;
});
");
//action of deleting an ingredient
$this->registerJs(
"$(document).on('click', '.order_ingredient_delete', function()
{
$.ajax
({
url: '" . yii\helpers\Url::toRoute("customer-orders-ingredients/ajax-delete") . "',
data: {id: $(this).closest('tr').data('key')},
success: function (data, textStatus, jqXHR)
{
var url = '" . yii\helpers\Url::toRoute("customer-order/update") . "&id=" . $model->id . "';
$.pjax.reload({url: url, container:'#order_ingredient_grid'});
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log('An error occured!');
alert('Error in ajax request' );
}
});
});"
);
?>
<div class="drivers-index">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title"><i class="fa fa-bars"></i> <?php // $this->title ?></h3>
<p class="pull-right">
<?= Html::button('ข้อมูลคนขับรถ', ['value' => Url::to('index.php?r=permitapp/drivers/create'), 'class' => 'btn btn-success', 'id' => 'modalButton']) ?>
</p>
</div>
<div class="box-body">
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?php
Modal::begin([
'header' => '<h4>Branches</h4>',
'id' => 'modal',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
<?php Pjax::begin(['id' => 'branchesGrid']); ?>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
[
'attribute' => 'drivers_title',
'format' => 'html',
'value' => function($data) {
switch ($data->drivers_title) {
case 1: return 'นาย';
case 2: return 'นาง';
case 3: return 'นางสาว';
}
},
],
'drivers_name',
'drivers_lastname',
'drivers_passport',
'drivers_licence',
// 'appilcant_id',
// 'car_id',
//'status',
[
'label' => 'Active',
'attribute' => 'status',
'format' => 'html',
'value' => function($model) {
return Html::a(
($model->status == 0 ? '<i class="glyphicon glyphicon-remove"></i> Not Active' : '<i class="glyphicon glyphicon-ok"></i> Active'), '#', ['class' => 'btn btn-block btn-sm' . ($model->status == 0 ? ' btn-default' : ' btn-success')]);
}
],
// 'drivers_licence',
// 'appilcant_id',
// 'car_id',
// 'status',
// 'blacklist_status',
// 'blacklist_date',
// 'comment',
// 'create_at',
// 'create_by',
// 'update_at',
// 'update_by',
[
'class' => 'yii\grid\ActionColumn',
'buttonOptions' => ['class' => 'btn btn-default'],
'template' => '<div class="btn-group btn-group-sm text-center" role="group">{copy} {view} {update} {delete} </div>',
'options' => ['style' => 'width:150px;'],
],
],
]);
?>
<?php Pjax::end(); ?>
</div><!-- /.box-body -->
</div>
</div>
<div>
<?php
Modal::begin([
'id' => 'activity-modal',
// 'header' => '<h4 class="modal-title">Add Product</h4>',
'size' => 'modal-lg',
'options' =>
[
'tabindex' => false,
]
]);
?>
<div id="modal_content">dd</div>
<?php Modal::end(); ?>
</div>
|
aekkapun/dlt-tcplch
|
backend/modules/permitapp/views/drivers/index.php
|
PHP
|
bsd-3-clause
| 7,760 |
<?php
/**
* Main Index Page
*
* The main index page for the RMS pulls all of its logic from the webroot/index page.
*
* @author Russell Toris - [email protected]
* @copyright 2014 Worcester Polytechnic Institute
* @link https://github.com/WPI-RAIL/rms
* @since RMS v 2.0.0
* @version 2.0.2
* @package app
*/
require 'webroot' . DIRECTORY_SEPARATOR . 'index.php';
|
cRhodan/RMIP
|
app/index.php
|
PHP
|
bsd-3-clause
| 378 |
<?php
namespace app\modules\api\controllers;
use yii\web\Controller;
use app\modules\api\models\TbUserinfo;
use yii\helpers\BaseJson;
class DefaultController extends Controller
{
public function actionIndex()
{
return BaseJson::encode(TbUserinfo::find()->all());
}
}
|
ydst22502/php
|
modules/api/controllers/DefaultController.php
|
PHP
|
bsd-3-clause
| 290 |
package com.pengyifan.leetcode;
/**
* Given an array nums, write a function to move all 0's to the end of it while maintaining the
* relative order of the non-zero elements.
* <p>
* For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3,
* 12, 0, 0].
* <p>
* Note:
* <p>
* You must do this in-place without making a copy of the array.
* Minimize the total number of operations.
*/
public class MoveZeroes {
public void moveZeroes(int[] nums) {
int begin = 0;
int i = 0;
while (i < nums.length) {
if (nums[i] == 0) {
i++;
} else {
nums[begin] = nums[i];
begin++;
i++;
}
}
while (begin < nums.length) {
nums[begin] = 0;
begin++;
}
}
}
|
yfpeng/pengyifan-leetcode
|
src/main/java/com/pengyifan/leetcode/MoveZeroes.java
|
Java
|
bsd-3-clause
| 776 |
package io.compgen.ngsutils.vcf.annotate;
import java.util.ArrayList;
import java.util.List;
import io.compgen.common.StringUtils;
import io.compgen.ngsutils.support.stats.FisherExact;
import io.compgen.ngsutils.vcf.VCFAnnotationDef;
import io.compgen.ngsutils.vcf.VCFAttributeException;
import io.compgen.ngsutils.vcf.VCFAttributeValue;
import io.compgen.ngsutils.vcf.VCFAttributes;
import io.compgen.ngsutils.vcf.VCFHeader;
import io.compgen.ngsutils.vcf.VCFParseException;
import io.compgen.ngsutils.vcf.VCFRecord;
public class FisherStrandBias extends AbstractBasicAnnotator {
protected FisherExact fisher = new FisherExact();
public VCFAnnotationDef getAnnotationType() throws VCFAnnotatorException {
try {
return VCFAnnotationDef.format("CG_FSB", "A", "Float", "Sample-based Fisher Strand Bias for alt alleles (Phred-scale)");
} catch (VCFParseException e) {
throw new VCFAnnotatorException(e);
}
}
@Override
public void setHeaderInner(VCFHeader header) throws VCFAnnotatorException {
VCFAnnotationDef sacDef = header.getFormatDef("SAC");
if (sacDef == null || !sacDef.number.equals(".") || !sacDef.type.equals("Integer")) {
throw new VCFAnnotatorException("\"SAC\" FORMAT annotation missing!");
}
header.addFormat(getAnnotationType());
}
// 2019-03-03 - mbreese
// changed this test to return the strand bias of *ONLY* the alt allele.
// the Fisher test is against a theoretical 50%/50% split
@Override
public void annotate(VCFRecord record) throws VCFAnnotatorException {
for (VCFAttributes sampleVals : record.getSampleAttributes()) {
if (sampleVals.contains("SAC")) {
// This should be the strand-level counts for each allele (ref+,ref-,alt1+,alt1-,alt2+,alt2-, etc...)
String sacVal = sampleVals.get("SAC").toString();
String[] spl = sacVal.split(",");
// int refPlus = Integer.parseInt(spl[0]);
// int refMinus = Integer.parseInt(spl[1]);
List<String> fsbOuts = new ArrayList<String>();
for (int i=2; i<spl.length; i+=2) {
int plus = Integer.parseInt(spl[i]);
int minus = Integer.parseInt(spl[i+1]);
int total = plus + minus;
int half = total / 2; // this will round down in cases where total is odd.
fsbOuts.add(""+round(phred(calcFisherStrandBias(half, half, plus, minus)),3));
}
try {
if (fsbOuts.size() == 0) {
sampleVals.put("CG_FSB", VCFAttributeValue.MISSING);
} else {
sampleVals.put("CG_FSB", new VCFAttributeValue(StringUtils.join(",", fsbOuts)));
}
} catch (VCFAttributeException e) {
throw new VCFAnnotatorException(e);
}
}
}
}
public static String round(double val, int places) {
return String.format("%."+places+"f", val);
}
private double phred(double val) {
if (val <= 0.0) {
return 255.0;
} else if (val >= 1.0) {
return 0.0;
} else {
return -10 * Math.log10(val);
}
}
private double calcFisherStrandBias(int refPlus, int refMinus, int plus, int minus) {
return fisher.calcTwoTailedPvalue(refPlus, refMinus, plus, minus);
}
}
|
compgen-io/ngsutilsj
|
src/java/io/compgen/ngsutils/vcf/annotate/FisherStrandBias.java
|
Java
|
bsd-3-clause
| 3,150 |
.sx-widget-element
{
display: none !important;
}
.sx-selected
{
margin-bottom: 0px;
list-style: none;
padding-left: 0;
border: 1px solid #ccc;
border-radius: 5px;
cursor: pointer;
background: white;
min-height: 33px;
line-height: 21px;
}
.sx-selected .sx-close-btn
{
color: black;
font-size: 16px;
opacity: 0.5;
margin-left: 20px;
}
.sx-selected .sx-close-btn:hover
{
opacity: 0.7;
}
.sx-selected li a {
overflow: hidden;
white-space: nowrap;
}
.sx-selected li
{
padding: 5px 10px;
font-size: 14px;
/*font-weight: bold;*/
/*background: white;*/
display: flex;
}
.sx-single-mode .sx-selected-value {
width: 100%;
white-space: nowrap;
overflow: hidden;
}
.sx-select-tree {
padding-top: 10px;
}
.sx-multi-mode .sx-selected li {
display: inline-flex;
padding: 0.05rem 0.25rem 0.05rem 0.25rem;
color: #555;
background: #f5f5f5;
border: 1px solid #ccc;
border-radius: 0.25rem;
margin: 2px;
}
.sx-multi-mode .sx-selected .sx-close-btn {
margin-left: 6px;
}
|
skeeks-cms/cms
|
src/widgets/formInputs/selectTree/assets/src/css/select-tree.css
|
CSS
|
bsd-3-clause
| 1,093 |
rem NOTE: this batch file is to be run in a Visual Studio command prompt
rem Delete old files
del *.obj
del *.ilk
del *.exe
del *.pdb
rem Compile files into .obj files in current directory
cl /I"..\..\testcasesupport" /W3 /MT /GS /RTC1 /bigobj /EHsc /nologo /c main.cpp CWE*.cpp CWE*.c ..\..\testcasesupport\io.c ..\..\testcasesupport\std_thread.c
rem Link all .obj file into a exe
cl /FeCWE758 *.obj /I"..\..\testcasesupport" /W3 /MT /GS /RTC1 /bigobj /EHsc /nologo
|
JianpingZeng/xcc
|
xcc/test/juliet/testcases/CWE758_Undefined_Behavior/CWE758.bat
|
Batchfile
|
bsd-3-clause
| 470 |
//
// ASDisplayNode+Deprecated.h
// AsyncDisplayKit
//
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
#pragma once
#import "ASDisplayNode.h"
@interface ASDisplayNode (Deprecated)
/**
* @abstract The name of this node, which will be displayed in `description`. The default value is nil.
*
* @deprecated Deprecated in version 2.0: Use .debugName instead. This value will display in
* results of the -asciiArtString method (@see ASLayoutElementAsciiArtProtocol).
*/
@property (nullable, nonatomic, copy) NSString *name ASDISPLAYNODE_DEPRECATED_MSG("Use .debugName instead.");
/**
* @abstract Asks the node to measure and return the size that best fits its subnodes.
*
* @param constrainedSize The maximum size the receiver should fit in.
*
* @return A new size that fits the receiver's subviews.
*
* @discussion Though this method does not set the bounds of the view, it does have side effects--caching both the
* constraint and the result.
*
* @warning Subclasses must not override this; it calls -measureWithSizeRange: with zero min size.
* -measureWithSizeRange: caches results from -calculateLayoutThatFits:. Calling this method may
* be expensive if result is not cached.
*
* @see measureWithSizeRange:
* @see [ASDisplayNode(Subclassing) calculateLayoutThatFits:]
*
* @deprecated Deprecated in version 2.0: Use layoutThatFits: with a constrained size of (CGSizeZero, constrainedSize) and call size on the returned ASLayout
*/
- (CGSize)measure:(CGSize)constrainedSize ASDISPLAYNODE_DEPRECATED_MSG("Use layoutThatFits: with a constrained size of (CGSizeZero, constrainedSize) and call size on the returned ASLayout.");
/**
* @abstract Calculate a layout based on given size range.
*
* @param constrainedSize The minimum and maximum sizes the receiver should fit in.
*
* @return An ASLayout instance defining the layout of the receiver and its children.
*
* @deprecated Deprecated in version 2.0: Use ASCalculateRootLayout() or ASCalculateLayout() instead
*/
- (nonnull ASLayout *)measureWithSizeRange:(ASSizeRange)constrainedSize ASDISPLAYNODE_DEPRECATED_MSG("Use layoutThatFits: instead.");
/**
* @abstract Called whenever the visiblity of the node changed.
*
* @discussion Subclasses may use this to monitor when they become visible.
*
* @deprecated @see didEnterVisibleState @see didExitVisibleState
*/
- (void)visibilityDidChange:(BOOL)isVisible ASDISPLAYNODE_REQUIRES_SUPER ASDISPLAYNODE_DEPRECATED_MSG("Use -didEnterVisibleState / -didExitVisibleState instead.");
/**
* @abstract Called whenever the visiblity of the node changed.
*
* @discussion Subclasses may use this to monitor when they become visible.
*
* @deprecated @see didEnterVisibleState @see didExitVisibleState
*/
- (void)visibleStateDidChange:(BOOL)isVisible ASDISPLAYNODE_REQUIRES_SUPER ASDISPLAYNODE_DEPRECATED_MSG("Use -didEnterVisibleState / -didExitVisibleState instead.");
/**
* @abstract Called whenever the the node has entered or exited the display state.
*
* @discussion Subclasses may use this to monitor when a node should be rendering its content.
*
* @note This method can be called from any thread and should therefore be thread safe.
*
* @deprecated @see didEnterDisplayState @see didExitDisplayState
*/
- (void)displayStateDidChange:(BOOL)inDisplayState ASDISPLAYNODE_REQUIRES_SUPER ASDISPLAYNODE_DEPRECATED_MSG("Use -didEnterDisplayState / -didExitDisplayState instead.");
/**
* @abstract Called whenever the the node has entered or left the load state.
*
* @discussion Subclasses may use this to monitor data for a node should be loaded, either from a local or remote source.
*
* @note This method can be called from any thread and should therefore be thread safe.
*
* @deprecated @see didEnterPreloadState @see didExitPreloadState
*/
- (void)loadStateDidChange:(BOOL)inLoadState ASDISPLAYNODE_REQUIRES_SUPER ASDISPLAYNODE_DEPRECATED_MSG("Use -didEnterPreloadState / -didExitPreloadState instead.");
/**
* @abstract Cancels all performing layout transitions. Can be called on any thread.
*
* @deprecated Deprecated in version 2.0: Use cancelLayoutTransition
*/
- (void)cancelLayoutTransitionsInProgress ASDISPLAYNODE_DEPRECATED_MSG("Use -cancelLayoutTransition instead.");
/**
* @abstract A boolean that shows whether the node automatically inserts and removes nodes based on the presence or
* absence of the node and its subnodes is completely determined in its layoutSpecThatFits: method.
*
* @discussion If flag is YES the node no longer require addSubnode: or removeFromSupernode method calls. The presence
* or absence of subnodes is completely determined in its layoutSpecThatFits: method.
*
* @deprecated Deprecated in version 2.0: Use automaticallyManagesSubnodes
*/
@property (nonatomic, assign) BOOL usesImplicitHierarchyManagement ASDISPLAYNODE_DEPRECATED_MSG("Set .automaticallyManagesSubnodes instead.");
@end
|
bimawa/AsyncDisplayKit
|
AsyncDisplayKit/ASDisplayNode+Deprecated.h
|
C
|
bsd-3-clause
| 5,159 |
/*
* Copyright (c) 2011 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/* Outer frame of the dialog. */
body {
-webkit-box-flex: 1;
-webkit-box-orient: vertical;
-webkit-transition: opacity 0.07s linear;
-webkit-user-select: none;
display: -webkit-box;
height: 100%;
margin: 0;
opacity: 0;
padding: 0;
position: absolute;
width: 100%;
}
/* The top title of the dialog. */
.dialog-title {
-webkit-box-sizing: border-box;
-webkit-padding-start: 15px;
background-image: -webkit-linear-gradient(top, #fff,#f6f6f6);
border-bottom: 1px #d6d9e3 solid;
color: #42506c;
font-size: 15px;
font-weight: bold;
height: 32px;
padding-top: 8px;
padding-bottom: 8px;
}
/* Breadcrumbs and things under the title but above the list view. */
.dialog-header {
-webkit-box-orient: horizontal;
-webkit-box-align: center;
display: -webkit-box;
margin: 15px;
margin-bottom: 4px;
}
/* Container for the detail and thumbnail (not implemented yet) list views. */
.dialog-body {
-webkit-box-orient: horizontal;
-webkit-box-flex: 1;
border: 1px #aaa solid;
border-radius: 3px;
display: -webkit-box;
margin: 15px;
margin-top: 0;
}
/* Container for the ok/cancel buttons. */
.dialog-footer {
-webkit-box-orient: horizontal;
display: -webkit-box;
margin: 15px;
margin-top: 0;
}
/* The container for breadcrumb elements. */
.breadcrumbs {
-webkit-box-orient: horizontal;
-webkit-box-flex: 1;
display: -webkit-box;
font-size: 15px;
line-height: 15px;
height: 18px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* A single directory name in the list of path breadcrumbs. */
.breadcrumb-path {
color: #265692;
cursor: pointer;
font-size: 14px;
}
/* The final breadcrumb, representing the current directory. */
.breadcrumb-last {
color: #666;
cursor: inherit;
font-weight: bold;
}
/* The > arrow between breadcrumbs. */
.breadcrumb-spacer {
-webkit-margin-start: 7px;
-webkit-margin-end: 4px;
color: #aaa;
font-size: 12px;
}
button.detail-view {
margin-right: 0;
}
button.thumbnail-view {
margin-left: 0;
}
button.detail-view > img,
button.thumbnail-view > img {
position: relative;
top: 1px;
}
.list-container {
-webkit-box-orient: vertical;
-webkit-box-flex: 1;
display: -webkit-box;
position: relative;
}
/* The cr.ui.Grid representing the detailed file list. */
.thumbnail-grid {
position: absolute;
top: 0;
left: 0;
border: 0;
overflow-y: scroll;
}
/* An item in the thumbnail view. */
.thumbnail-item {
margin-top: 10px;
margin-left: 10px;
width: 120px;
height: 120px;
text-align: center;
}
.thumbnail-item > div.img-container {
-webkit-box-align: center;
-webkit-box-pack: center;
display: -webkit-box;
height: 91px;
margin: 2px;
width: 116px;
}
.thumbnail-item > div.img-container > img {
max-width: 110px;
max-height: 85px;
}
.thumbnail-item > div.text-container {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Text box used for renaming in the detail list. */
.detail-table input.rename {
-webkit-margin-start: -5px;
margin-top: 1px;
position: absolute;
}
/* Text box used for renaming in the thumbnail list. */
.thumbnail-grid input.rename {
-webkit-margin-start: -2px;
position: absolute;
}
/* The cr.ui.Table representing the detailed file list. */
.detail-table {
position: absolute;
top: 0;
left: 0;
border: 0;
}
/* The right-column 'Preview' column container. */
.preview-container {
-webkit-border-start: 1px #aaa solid;
-webkit-box-orient: vertical;
display: -webkit-box;
width: 225px;
}
/* cr.ui.Table has a black focus border by default, which we don't want. */
.detail-table:focus {
border: 0;
}
/* Table splitter element */
.table-header-splitter {
-webkit-border-start: 1px #aaa solid;
background-color: inherit;
height: 20px;
margin-top: 4px;
}
/* Container for a table header. */
.table-header {
-webkit-box-sizing: border-box;
border-bottom: 1px #aaa solid;
background-image: -webkit-linear-gradient(top, #f9f9f9, #e8e8e8);
height: 28px;
}
/* Text label in a table header. */
.table-header-label {
margin-top: 6px;
}
/* First column has no label, so we want the sort indicator to take up the
* whole space.
*/
.table-header-cell:first-child .table-header-sort-image-desc:after,
.table-header-cell:first-child .table-header-sort-image-asc:after {
-webkit-padding-start: 0;
}
/* The first child of a list cell. */
.table-row-cell > * {
-webkit-margin-start: 5px;
-webkit-box-orient: horizontal;
-webkit-box-flex: 1;
display: -webkit-box;
}
/* Column text containers. */
.detail-name, .detail-size, .detail-date {
padding-top: 2px;
}
/* The icon in the name column. */
.detail-icon {
-webkit-margin-end: 3px;
-webkit-margin-start: 3px;
background-image: url(../images/filetype_generic.png);
background-position: center;
background-repeat: no-repeat;
height: 24px;
}
/* Icon for files in the detail list. */
.detail-icon[iconType="audio"] {
background-image: url(../images/filetype_audio.png);
}
.detail-icon[iconType="doc"] {
background-image: url(../images/filetype_doc.png);
}
.detail-icon[iconType="folder"] {
background-image: url(../images/filetype_folder.png);
}
.detail-icon[iconType="html"] {
background-image: url(../images/filetype_html.png);
}
.detail-icon[iconType="image"] {
background-image: url(../images/filetype_image.png);
}
.detail-icon[iconType="pdf"] {
background-image: url(../images/filetype_pdf.png);
}
.detail-icon[iconType="presentation"] {
background-image: url(../images/filetype_presentation.png);
}
.detail-icon[iconType="spreadsheet"] {
background-image: url(../images/filetype_spreadsheet.png);
}
.detail-icon[iconType="text"] {
background-image: url(../images/filetype_text.png);
}
.detail-icon[iconType="video"] {
background-image: url(../images/filetype_video.png);
}
/* The filename text in the preview pane. */
.preview-filename {
-webkit-margin-start: 8px;
color: #666;
font-weight: bold;
margin-top: 10px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* The preview image. */
.preview-img {
margin-top: 10px;
max-height: 300px;
max-width: 190px;
}
.preview-img[src=''] {
visibility: hidden;
}
/* Decoration when multiple images are selected. */
.preview-img.multiple-selected {
-webkit-box-shadow: 5px 5px 0 #aaa;
}
/* Checkboard background to distinguish images with alpha channels. */
.preview-img.transparent-background {
/* ../images/preview-background.png */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAlwSFlzAAAOTQAADiYBwNzaZQAAAAd0SU1FB9sDExUSAaQ/5TMAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAQ0lEQVRYw+3VsQkAMQwDQOfJRt7r9/FQ3ilDuAiBUy84UKFVVX8M0t2TenxxOQAAAAAAAAB7+ueZaQIAAAAAAIC3AQceAAfi8EmRSgAAAABJRU5ErkJggg==);
}
/* The task buttons at the bottom of the preview pane. */
.task-buttons {
padding: 4px;
overflow-y: auto;
}
.task-button {
display: block;
width: 100%;
text-align: left;
}
.task-button > img {
position: relative;
top: 2px;
padding-after: 5px;
padding-right: 5px;
}
/* The selection summary text at the bottom of the preview pane. */
.preview-summary {
border-top: 1px #aaa solid;
color: #666;
font-weight: bold;
overflow: hidden;
padding: 5px;
text-overflow: ellipsis;
white-space: nowrap;
}
.filename-label {
-webkit-box-orient: horizontal;
color: #666;
display: -webkit-box;
font-weight: bold;
padding-top: 4px;
padding-right: 4px;
}
.filename-input {
-webkit-box-orient: horizontal;
-webkit-box-flex: 1;
display: -webkit-box;
}
/* A horizontal spring. */
.horizontal-spacer {
-webkit-box-orient: horizontal;
-webkit-box-flex: 1;
display: -webkit-box;
}
/* A vertical spring. */
.vertical-spacer {
-webkit-box-orient: vertical;
-webkit-box-flex: 1;
display: -webkit-box;
}
|
Crystalnix/house-of-life-chromium
|
chrome/browser/resources/file_manager/css/file_manager.css
|
CSS
|
bsd-3-clause
| 8,075 |
/*
* mpi2.c
*
* Created on: 2011-11-08
* Author: francis
*/
#include <stdio.h>
#include <mpi.h>
#define MSG_SIZE 128
int main(int argc, char **argv)
{
int numprocs, rank, namelen;
MPI_Status status;
char processor_name[MPI_MAX_PROCESSOR_NAME];
char msg0[MSG_SIZE] = "foo";
char msg1[MSG_SIZE] = "bar";
char msg_recv[MSG_SIZE];
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (numprocs != 2) {
printf("Error: number of processors must be equal to 2\n");
MPI_Finalize();
return -1;
}
switch (rank) {
case 0:
MPI_Send(msg0, MSG_SIZE, MPI_CHARACTER, 1, 1, MPI_COMM_WORLD);
MPI_Recv(msg_recv, MSG_SIZE, MPI_CHARACTER, 1, 1, MPI_COMM_WORLD,
&status);
break;
case 1:
MPI_Recv(msg_recv, MSG_SIZE, MPI_CHARACTER, 0, 1, MPI_COMM_WORLD,
&status);
MPI_Send(msg1, MSG_SIZE, MPI_CHARACTER, 0, 1, MPI_COMM_WORLD);
break;
default:
break;
}
MPI_Get_processor_name(processor_name, &namelen);
printf("Process %d on %s out of %d recv=%s\n", rank, processor_name,
numprocs, msg_recv);
MPI_Finalize();
return 0;
}
|
GuillaumeArruda/INF8601
|
inf8601-lab3-2.1.2/examples/mpi2.c
|
C
|
bsd-3-clause
| 1,119 |
<?php
namespace common\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Field;
/**
* FieldSearch represents the model behind the search form about `common\models\Field`.
*/
class FieldSearch extends Field
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'form_id', 'order', 'required', 'create_at'], 'integer'],
[['name', 'desc', 'type', 'default', 'options'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Field::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'form_id' => $this->form_id,
'order' => $this->order,
'required' => $this->required,
'create_at' => $this->create_at,
]);
$query->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'desc', $this->desc])
->andFilterWhere(['like', 'type', $this->type])
->andFilterWhere(['like', 'default', $this->default])
->andFilterWhere(['like', 'options', $this->options]);
return $dataProvider;
}
}
|
fnsoxt/yii2-form-generator
|
common/models/FieldSearch.php
|
PHP
|
bsd-3-clause
| 1,709 |
/**
* Copyright 2017 Jacques Florence
* All rights reserved.
* See License.txt file
*
*/
#ifndef MDP_GOVERNOR_CONFIGURATION_H
#define MDP_GOVERNOR_CONFIGURATION_H
#include <vector>
#include <scheduler/schedulerConfiguration.h>
namespace Mdp
{
class StateSpaceDimension;
}
namespace MdpGov
{
class MdpGovernorConfiguration : public Scheduler::SchedulerConfiguration
{
public:
MdpGovernorConfiguration(std::string file) : Scheduler::SchedulerConfiguration(file){};
virtual Scheduler::FreqGovernor *getFreqGovernorFromFile() override;
virtual std::vector<Mdp::StateSpaceDimension*> getDimensionsFromFile();
};
}
#endif
|
Jacques-Florence/schedSim
|
src/mdpGovernor/mdpGovernorConfiguration.h
|
C
|
bsd-3-clause
| 634 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
this.EXPORTED_SYMBOLS = [
"UserAPI10Client",
];
const {utils: Cu} = Components;
Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://services-common/rest.js");
Cu.import("resource://services-common/utils.js");
Cu.import("resource://services-sync/identity.js");
Cu.import("resource://services-sync/util.js");
/**
* A generic client for the user API 1.0 service.
*
* http://docs.services.mozilla.com/reg/apis.html
*
* Instances are constructed with the base URI of the service.
*/
this.UserAPI10Client = function UserAPI10Client(baseURI) {
this._log = Log.repository.getLogger("Sync.UserAPI");
this._log.level = Log.Level[Svc.Prefs.get("log.logger.userapi")];
this.baseURI = baseURI;
}
UserAPI10Client.prototype = {
USER_CREATE_ERROR_CODES: {
2: "Incorrect or missing captcha.",
4: "User exists.",
6: "JSON parse failure.",
7: "Missing password field.",
9: "Requested password not strong enough.",
12: "No email address on file.",
},
/**
* Determine whether a specified username exists.
*
* Callback receives the following arguments:
*
* (Error) Describes error that occurred or null if request was
* successful.
* (boolean) True if user exists. False if not. null if there was an error.
*/
usernameExists: function usernameExists(username, cb) {
if (typeof(cb) != "function") {
throw new Error("cb must be a function.");
}
let url = this.baseURI + username;
let request = new RESTRequest(url);
request.get(this._onUsername.bind(this, cb, request));
},
/**
* Obtain the Weave (Sync) node for a specified user.
*
* The callback receives the following arguments:
*
* (Error) Describes error that occurred or null if request was successful.
* (string) Username request is for.
* (string) URL of user's node. If null and there is no error, no node could
* be assigned at the time of the request.
*/
getWeaveNode: function getWeaveNode(username, password, cb) {
if (typeof(cb) != "function") {
throw new Error("cb must be a function.");
}
let request = this._getRequest(username, "/node/weave", password);
request.get(this._onWeaveNode.bind(this, cb, request));
},
/**
* Change a password for the specified user.
*
* @param username
* (string) The username whose password to change.
* @param oldPassword
* (string) The old, current password.
* @param newPassword
* (string) The new password to switch to.
*/
changePassword: function changePassword(username, oldPassword, newPassword, cb) {
let request = this._getRequest(username, "/password", oldPassword);
request.onComplete = this._onChangePassword.bind(this, cb, request);
request.post(CommonUtils.encodeUTF8(newPassword));
},
createAccount: function createAccount(email, password, captchaChallenge,
captchaResponse, cb) {
let username = IdentityManager.prototype.usernameFromAccount(email);
let body = JSON.stringify({
"email": email,
"password": Utils.encodeUTF8(password),
"captcha-challenge": captchaChallenge,
"captcha-response": captchaResponse
});
let url = this.baseURI + username;
let request = new RESTRequest(url);
if (this.adminSecret) {
request.setHeader("X-Weave-Secret", this.adminSecret);
}
request.onComplete = this._onCreateAccount.bind(this, cb, request);
request.put(body);
},
_getRequest: function _getRequest(username, path, password=null) {
let url = this.baseURI + username + path;
let request = new RESTRequest(url);
if (password) {
let up = username + ":" + password;
request.setHeader("authorization", "Basic " + btoa(up));
}
return request;
},
_onUsername: function _onUsername(cb, request, error) {
if (error) {
cb(error, null);
return;
}
let body = request.response.body;
if (body == "0") {
cb(null, false);
return;
} else if (body == "1") {
cb(null, true);
return;
} else {
cb(new Error("Unknown response from server: " + body), null);
return;
}
},
_onWeaveNode: function _onWeaveNode(cb, request, error) {
if (error) {
cb.network = true;
cb(error, null);
return;
}
let response = request.response;
if (response.status == 200) {
let body = response.body;
if (body == "null") {
cb(null, null);
return;
}
cb(null, body);
return;
}
let error = new Error("Sync node retrieval failed.");
switch (response.status) {
case 400:
error.denied = true;
break;
case 404:
error.notFound = true;
break;
default:
error.message = "Unexpected response code: " + response.status;
}
cb(error, null);
return;
},
_onChangePassword: function _onChangePassword(cb, request, error) {
this._log.info("Password change response received: " +
request.response.status);
if (error) {
cb(error);
return;
}
let response = request.response;
if (response.status != 200) {
cb(new Error("Password changed failed: " + response.body));
return;
}
cb(null);
},
_onCreateAccount: function _onCreateAccount(cb, request, error) {
let response = request.response;
this._log.info("Create account response: " + response.status + " " +
response.body);
if (error) {
cb(new Error("HTTP transport error."), null);
return;
}
if (response.status == 200) {
cb(null, response.body);
return;
}
let error = new Error("Could not create user.");
error.body = response.body;
cb(error, null);
return;
},
};
Object.freeze(UserAPI10Client.prototype);
|
GaloisInc/hacrypto
|
src/Javascript/Mozilla/old_snapshots/sync/modules/userapi.js
|
JavaScript
|
bsd-3-clause
| 6,161 |
////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Daniel Kollmann
// 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 Daniel Kollmann nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using Brainiac.Design.Properties;
namespace Brainiac.Design.Attributes
{
[AttributeUsage(AttributeTargets.Property)]
public class DesignerFloat : DesignerProperty
{
protected float _min, _max, _steps;
protected string _units;
protected int _precision;
/// <summary>
/// The units the value is represented in.
/// </summary>
public string Units
{
get { return Plugin.GetResourceString(_units); }
}
/// <summary>
/// The minimum value of the property.
/// </summary>
public float Min
{
get { return _min; }
}
/// <summary>
/// The maximum value of the property.
/// </summary>
public float Max
{
get { return _max; }
}
/// <summary>
/// The minimum value added or substracted when changing the property's value.
/// </summary>
public float Steps
{
get { return _steps; }
}
/// <summary>
/// The number of decimal places shown.
/// </summary>
public int Precision
{
get { return _precision; }
}
/// <summary>
/// Creates a new designer attribute for handling a float value.
/// </summary>
/// <param name="displayName">The name shown on the node and in the property editor for the property.</param>
/// <param name="description">The description shown in the property editor for the property.</param>
/// <param name="category">The category shown in the property editor for the property.</param>
/// <param name="displayMode">Defines how the property is visualised in the editor.</param>
/// <param name="displayOrder">Defines the order the properties will be sorted in when shown in the property grid. Lower come first.</param>
/// <param name="flags">Defines the designer flags stored for the property.</param>
/// <param name="min">The minimum value of the property.</param>
/// <param name="max">The maximum value of the property.</param>
/// <param name="steps">The minimum value added or substracted when changing the property's value.</param>
/// <param name="precision">The number of decimal places shown.</param>
/// <param name="units">The units the value is represented in.</param>
public DesignerFloat(string displayName, string description, string category, DisplayMode displayMode, int displayOrder, DesignerFlags flags, float min, float max, float steps, int precision, string units) : base(displayName, description, category, displayMode, displayOrder, flags, new EditorType[] { new EditorType("EditorValue", typeof(DesignerNumberEditor)) })
{
_min= min;
_max= max;
_steps= steps;
_precision= precision;
_units= units;
}
public override string GetDisplayValue(object obj)
{
return string.Format(CultureInfo.InvariantCulture, "{0}", (float)obj);
}
public override string GetExportValue(object obj)
{
return string.Format(CultureInfo.InvariantCulture, "{0}f", (float)obj);
}
public override object FromStringValue(Type type, string str)
{
if(type !=typeof(float))
throw new Exception(Resources.ExceptionDesignerAttributeInvalidType);
float result;
if(float.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out result))
return result;
throw new Exception( string.Format(Resources.ExceptionDesignerAttributeIllegalFloatValue, str) );
}
}
}
|
learno/Brainiac-Designer
|
Brainiac Designer Base/Attributes/DesignerFloat.cs
|
C#
|
bsd-3-clause
| 5,242 |
"""
A very simple Flask app to display the current state of link rot. Currently relies on HTTP Basic access
authentication to protect it.
"""
import configparser
import logging
import hashlib
import MySQLdb
import os
import os.path as osp
from flask import Flask, request, render_template, abort, Response
from werkzeug.exceptions import BadRequest
CONFIG_FILE_LOCATION = os.path.join(os.path.dirname(__file__), 'db_info.conf')
POST_PATH = '/url/new/'
app = Flask(__name__)
def load_db_connection_info_from_parser():
try:
config = configparser.ConfigParser()
config.read(CONFIG_FILE_LOCATION)
return config
except configparser.Error:
abort(500)
@app.route(POST_PATH, methods=['POST'])
def add_new_url():
if request.method == 'POST':
# sanitise incoming json
try:
rot_json_dict = request.get_json()
except BadRequest:
return abort(400)
if rot_json_dict is None:
return abort(422)
try:
if rot_json_dict['short'] and rot_json_dict['stout']:
return abort(418)
except KeyError:
pass
# TODO - pull these from elsewhere in the project. Hardcoding for testing.
if not all([k in rot_json_dict.keys() for k in ['url',
'entity_id',
'entity_type',
'attempts',
'last_code',
'last_stamp',
'last_checker']]):
return abort(422)
url_hash = hashlib.sha512(rot_json_dict['url'].encode('utf-8')).hexdigest()
db, cursor = db_connect()
try:
try:
cursor.execute("INSERT INTO rot (entity_id, type, url, attempts, last_code, last_stamp, last_checker, url_hash) "
"VALUES (%(entity_id)s, %(type)s, %(url)s, %(attempts)s, %(last_code)s, %(last_stamp)s, %(last_checker)s, %(url_hash)s) "
"ON DUPLICATE KEY UPDATE "
"attempts=%(attempts)s, last_code=%(last_code)s, last_stamp=%(last_stamp)s, last_checker=%(last_checker)s;",
{'entity_id': rot_json_dict['entity_id'],
'type': rot_json_dict['entity_type'],
'url': rot_json_dict['url'],
'attempts': rot_json_dict['attempts'],
'last_code': rot_json_dict['last_code'],
'last_stamp': rot_json_dict['last_stamp'],
'last_checker': rot_json_dict['last_checker'],
'url_hash': url_hash})
db.commit()
except:
'''with open(osp.join(osp.dirname(osp.abspath(__file__)), "blah"), "wb") as f: # for debug
f.write(cursor._last_executed)'''
raise
return Response(None, status=202) # Should move across to using an ORM. Should return 201 if created.
finally:
cursor.close()
db.close()
else:
return abort(405)
def db_connect():
db_config = load_db_connection_info_from_parser()
db = MySQLdb.connect(host=db_config['DB']['host'],
user=db_config['DB']['user'],
passwd=db_config['DB']['password'],
db=db_config['DB']['name'])
cursor = db.cursor()
return db, cursor
@app.route('/view/all/')
def dirtily_simple_view():
db, cursor = db_connect()
try:
cursor.execute("SELECT entity_id, type, url, attempts, last_code, last_stamp, last_checker FROM rot;")
sql_results = cursor.fetchall() # Yeah, because that's a good idea Mark
sql_results = [(result[0], result[1], result[2], result[3], result[4], result[5], result[6],) for result in sql_results]
# TODO - limit number of rows returned, and accept GET parameters specifying the number to return AND start id
# TODO - limit number of rows returned, and accept GET parameters specifying the number to return AND start id
finally:
cursor.close()
db.close()
return render_template('simple_all_view.html', sql_results=sql_results)
@app.route('/')
def hello_world():
try:
return 'Hallo.'
except Exception as e:
logging.error(e)
|
IntrepidBrit/dullu
|
web_interface/flask_app.py
|
Python
|
bsd-3-clause
| 4,600 |
/* $NetBSD: ip_rcmd_pxy.c,v 1.1.2.1 1999/12/20 21:02:07 he Exp $ */
/*
* Simple RCMD transparent proxy for in-kernel use. For use with the NAT
* code.
*/
#if SOLARIS && defined(_KERNEL)
extern kmutex_t ipf_rw;
#endif
#define isdigit(x) ((x) >= '0' && (x) <= '9')
#define IPF_RCMD_PROXY
int ippr_rcmd_init __P((void));
int ippr_rcmd_new __P((fr_info_t *, ip_t *, ap_session_t *, nat_t *));
int ippr_rcmd_out __P((fr_info_t *, ip_t *, ap_session_t *, nat_t *));
u_short ipf_rcmd_atoi __P((char *));
int ippr_rcmd_portmsg __P((fr_info_t *, ip_t *, ap_session_t *, nat_t *));
static frentry_t rcmdfr;
/*
* RCMD application proxy initialization.
*/
int ippr_rcmd_init()
{
bzero((char *)&rcmdfr, sizeof(rcmdfr));
rcmdfr.fr_ref = 1;
rcmdfr.fr_flags = FR_INQUE|FR_PASS|FR_QUICK|FR_KEEPSTATE;
return 0;
}
/*
* Setup for a new RCMD proxy.
*/
int ippr_rcmd_new(fin, ip, aps, nat)
fr_info_t *fin;
ip_t *ip;
ap_session_t *aps;
nat_t *nat;
{
tcphdr_t *tcp = (tcphdr_t *)fin->fin_dp;
aps->aps_psiz = sizeof(u_32_t);
KMALLOCS(aps->aps_data, u_32_t *, sizeof(u_32_t));
if (aps->aps_data == NULL)
return -1;
*(u_32_t *)aps->aps_data = 0;
aps->aps_sport = tcp->th_sport;
aps->aps_dport = tcp->th_dport;
return 0;
}
/*
* ipf_rcmd_atoi - implement a simple version of atoi
*/
u_short ipf_rcmd_atoi(ptr)
char *ptr;
{
register char *s = ptr, c;
register u_short i = 0;
while ((c = *s++) && isdigit(c)) {
i *= 10;
i += c - '0';
}
return i;
}
int ippr_rcmd_portmsg(fin, ip, aps, nat)
fr_info_t *fin;
ip_t *ip;
ap_session_t *aps;
nat_t *nat;
{
char portbuf[8], *s;
struct in_addr swip;
u_short sp, dp;
int off, dlen;
tcphdr_t *tcp, tcph, *tcp2 = &tcph;
fr_info_t fi;
nat_t *ipn;
mb_t *m;
#if SOLARIS
mb_t *m1;
#endif
tcp = (tcphdr_t *)fin->fin_dp;
off = (ip->ip_hl << 2) + (tcp->th_off << 2);
m = *(mb_t **)fin->fin_mp;
#if SOLARIS
m = fin->fin_qfm;
dlen = msgdsize(m) - off;
bzero(portbuf, sizeof(portbuf));
copyout_mblk(m, off, MIN(sizeof(portbuf), dlen), portbuf);
#else
dlen = mbufchainlen(m) - off;
bzero(portbuf, sizeof(portbuf));
m_copydata(m, off, MIN(sizeof(portbuf), dlen), portbuf);
#endif
if ((*(u_32_t *)aps->aps_data != 0) &&
(tcp->th_seq != *(u_32_t *)aps->aps_data))
return 0;
portbuf[sizeof(portbuf) - 1] = '\0';
s = portbuf;
sp = ipf_rcmd_atoi(s);
if (!sp)
return 0;
/*
* Add skeleton NAT entry for connection which will come back the
* other way.
*/
sp = htons(sp);
dp = htons(fin->fin_data[1]);
ipn = nat_outlookup(fin->fin_ifp, IPN_TCP, nat->nat_p, nat->nat_inip,
ip->ip_dst, (dp << 16) | sp);
if (ipn == NULL) {
bcopy((char *)fin, (char *)&fi, sizeof(fi));
bzero((char *)tcp2, sizeof(*tcp2));
tcp2->th_win = htons(8192);
tcp2->th_sport = sp;
tcp2->th_dport = 0; /* XXX - don't specify remote port */
fi.fin_data[0] = ntohs(sp);
fi.fin_data[1] = 0;
fi.fin_dp = (char *)tcp2;
swip = ip->ip_src;
ip->ip_src = nat->nat_inip;
ipn = nat_new(nat->nat_ptr, ip, &fi, IPN_TCP|FI_W_DPORT,
NAT_OUTBOUND);
if (ipn != NULL) {
ipn->nat_age = fr_defnatage;
fi.fin_fr = &rcmdfr;
(void) fr_addstate(ip, &fi, FI_W_DPORT);
}
ip->ip_src = swip;
}
return 0;
}
int ippr_rcmd_out(fin, ip, aps, nat)
fr_info_t *fin;
ip_t *ip;
ap_session_t *aps;
nat_t *nat;
{
return ippr_rcmd_portmsg(fin, ip, aps, nat);
}
|
MarginC/kame
|
netbsd/sys/netinet/ip_rcmd_pxy.c
|
C
|
bsd-3-clause
| 3,333 |
{% extends 'is_core/base.html' %}
{% load i18n %}
{% block content %}{% trans 'Welcome' %}{% endblock %}
|
matllubos/django-is-core
|
is_core/templates/is_core/home.html
|
HTML
|
bsd-3-clause
| 106 |
#ifndef LIDX_ICU_UTILS_H
#define LIDX_ICU_UTILS_H
#if !__APPLE__
#include "unicode/utypes.h"
#include "unicode/uloc.h"
#include "unicode/utext.h"
#include "unicode/localpointer.h"
#include "unicode/parseerr.h"
#include "unicode/ubrk.h"
#include "unicode/urep.h"
#include "unicode/utrans.h"
#include "unicode/parseerr.h"
#include "unicode/uenum.h"
#include "unicode/uset.h"
#include "unicode/putil.h"
#include "unicode/uiter.h"
#include "unicode/ustring.h"
#else
#if defined(__CHAR16_TYPE__)
typedef __CHAR16_TYPE__ UChar;
#else
typedef uint16_t UChar;
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
void lidx_init_icu_utils(void);
void lidx_deinit_icu_utils(void);
unsigned int lidx_u_get_length(const UChar * word);
UChar * lidx_from_utf8(const char * word);
char * lidx_to_utf8(const UChar * word);
char * lidx_transliterate(const UChar * text, int length);
#ifdef __cplusplus
}
#endif
#endif
|
dinhviethoa/lidx
|
src/lidx-icu-utils.h
|
C
|
bsd-3-clause
| 908 |
##
# Copyright (c) 2005 Apple Computer, Inc. All rights reserved.
#
# 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.
#
# DRI: Wilfredo Sanchez, [email protected]
##
"""
WebDAV XML base classes.
This module provides XML utilities for use with WebDAV.
See RFC 2518: http://www.ietf.org/rfc/rfc2518.txt (WebDAV)
"""
__all__ = [
"dav_namespace",
"WebDAVElement",
"PCDATAElement",
"WebDAVOneShotElement",
"WebDAVUnknownElement",
"WebDAVEmptyElement",
"WebDAVTextElement",
"WebDAVDateTimeElement",
"DateTimeHeaderElement",
]
import string
import StringIO
import xml.dom.minidom
import datetime
from twisted.python import log
from twisted.web2.http_headers import parseDateTime
from twisted.web2.dav.element.util import PrintXML, decodeXMLName
##
# Base XML elements
##
dav_namespace = "DAV:"
class WebDAVElement (object):
"""
WebDAV XML element. (RFC 2518, section 12)
"""
namespace = dav_namespace # Element namespace (class variable)
name = None # Element name (class variable)
allowed_children = None # Types & count limits on child elements
allowed_attributes = None # Allowed attribute names
hidden = False # Don't list in PROPFIND with <allprop>
protected = False # See RFC 3253 section 1.4.1
unregistered = False # Subclass of factory; doesn't register
def qname(self):
return (self.namespace, self.name)
def sname(self):
return "{%s}%s" % (self.namespace, self.name)
qname = classmethod(qname)
sname = classmethod(sname)
def __init__(self, *children, **attributes):
super(WebDAVElement, self).__init__()
if self.allowed_children is None:
raise NotImplementedError("WebDAVElement subclass %s is not implemented."
% (self.__class__.__name__,))
#
# Validate that children are of acceptable types
#
allowed_children = dict([
(child_type, list(limits))
for child_type, limits
in self.allowed_children.items()
])
my_children = []
for child in children:
if child is None:
continue
if isinstance(child, (str, unicode)):
child = PCDATAElement(child)
assert isinstance(child, (WebDAVElement, PCDATAElement)), "Not an element: %r" % (child,)
for allowed, (min, max) in allowed_children.items():
if type(allowed) == type and isinstance(child, allowed):
qname = allowed
elif child.qname() == allowed:
qname = allowed
else:
continue
if min is not None and min > 0:
min -= 1
if max is not None:
assert max > 0, "Too many children of type %s for %s" % (child.sname(), self.sname())
max -= 1
allowed_children[qname] = (min, max)
my_children.append(child)
break
else:
if not (isinstance(child, PCDATAElement) and child.isWhitespace()):
log.msg("Child of type %s is unexpected and therefore ignored in %s element"
% (child.sname(), self.sname()))
for qname, (min, max) in allowed_children.items():
if min != 0:
raise ValueError("Not enough children of type {%s}%s for %s"
% (qname[0], qname[1], self.sname()))
self.children = tuple(my_children)
#
# Validate that attributes have known names
#
my_attributes = {}
if self.allowed_attributes:
for name in attributes:
if name in self.allowed_attributes:
my_attributes[name] = attributes[name]
else:
log.msg("Attribute %s is unexpected and therefore ignored in %s element"
% (name, self.sname()))
for name, required in self.allowed_attributes.items():
if required and name not in my_attributes:
raise ValueError("Attribute %s is required in %s element"
% (name, self.sname()))
elif not isinstance(self, WebDAVUnknownElement):
if attributes:
log.msg("Attributes %s are unexpected and therefore ignored in %s element"
% (attributes.keys(), self.sname()))
self.attributes = my_attributes
def __str__(self):
return self.sname()
def __repr__(self):
if hasattr(self, "attributes") and hasattr(self, "children"):
return "<%s %r: %r>" % (self.sname(), self.attributes, self.children)
else:
return "<%s>" % (self.sname())
def __eq__(self, other):
if isinstance(other, WebDAVElement):
return (
self.name == other.name and
self.namespace == other.namespace and
self.attributes == other.attributes and
self.children == other.children
)
else:
return NotImplemented
def __ne__(self, other):
return not self.__eq__(other)
def __contains__(self, child):
return child in self.children
def writeXML(self, output):
document = xml.dom.minidom.Document()
self.addToDOM(document, None)
PrintXML(document, stream=output)
def toxml(self):
output = StringIO.StringIO()
self.writeXML(output)
return output.getvalue()
def element(self, document):
element = document.createElementNS(self.namespace, self.name)
if hasattr(self, "attributes"):
for name, value in self.attributes.items():
namespace, name = decodeXMLName(name)
attribute = document.createAttributeNS(namespace, name)
attribute.nodeValue = value
element.setAttributeNodeNS(attribute)
return element
def addToDOM(self, document, parent):
element = self.element(document)
if parent is None:
document.appendChild(element)
else:
parent.appendChild(element)
for child in self.children:
if child:
try:
child.addToDOM(document, element)
except:
log.err("Unable to add child %r of element %s to DOM" % (child, self))
raise
def childrenOfType(self, child_type):
"""
Returns a list of children with the same qname as the given type.
"""
if type(child_type) is tuple:
qname = child_type
else:
qname = child_type.qname()
return [ c for c in self.children if c.qname() == qname ]
def childOfType(self, child_type):
"""
Returns a child of the given type, if any, or None.
Raises ValueError if more than one is found.
"""
found = None
for child in self.childrenOfType(child_type):
if found:
raise ValueError("Multiple %s elements found in %s" % (child_type.sname(), self.toxml()))
found = child
return found
class PCDATAElement (object):
def sname(self): return "#PCDATA"
qname = classmethod(sname)
sname = classmethod(sname)
def __init__(self, data):
super(PCDATAElement, self).__init__()
if data is None:
data = ""
elif type(data) is unicode:
data = data.encode("utf-8")
else:
assert type(data) is str, ("PCDATA must be a string: %r" % (data,))
self.data = data
def __str__(self):
return str(self.data)
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.data)
def __add__(self, other):
if isinstance(other, PCDATAElement):
return self.__class__(self.data + other.data)
else:
return self.__class__(self.data + other)
def __eq__(self, other):
if isinstance(other, PCDATAElement):
return self.data == other.data
elif type(other) in (str, unicode):
return self.data == other
else:
return NotImplemented
def __ne__(self, other):
return not self.__eq__(other)
def isWhitespace(self):
for char in str(self):
if char not in string.whitespace:
return False
return True
def element(self, document):
return document.createTextNode(self.data)
def addToDOM(self, document, parent):
try:
parent.appendChild(self.element(document))
except TypeError:
log.err("Invalid PCDATA: %r" % (self.data,))
raise
class WebDAVOneShotElement (WebDAVElement):
"""
Element with exactly one WebDAVEmptyElement child and no attributes.
"""
__singletons = {}
def __new__(clazz, *children):
child = None
for next in children:
if isinstance(next, WebDAVEmptyElement):
if child is not None:
raise ValueError("%s must have exactly one child, not %r"
% (clazz.__name__, children))
child = next
elif isinstance(next, PCDATAElement):
pass
else:
raise ValueError("%s child is not a WebDAVEmptyElement instance: %s"
% (clazz.__name__, next))
if clazz not in WebDAVOneShotElement.__singletons:
WebDAVOneShotElement.__singletons[clazz] = {
child: WebDAVElement.__new__(clazz, children)
}
elif child not in WebDAVOneShotElement.__singletons[clazz]:
WebDAVOneShotElement.__singletons[clazz][child] = (
WebDAVElement.__new__(clazz, children)
)
return WebDAVOneShotElement.__singletons[clazz][child]
class WebDAVUnknownElement (WebDAVElement):
"""
Placeholder for unknown element tag names.
"""
allowed_children = {
WebDAVElement: (0, None),
PCDATAElement: (0, None),
}
class WebDAVEmptyElement (WebDAVElement):
"""
WebDAV element with no contents.
"""
__singletons = {}
def __new__(clazz, *args, **kwargs):
assert not args
if kwargs:
return WebDAVElement.__new__(clazz, **kwargs)
else:
if clazz not in WebDAVEmptyElement.__singletons:
WebDAVEmptyElement.__singletons[clazz] = (WebDAVElement.__new__(clazz))
return WebDAVEmptyElement.__singletons[clazz]
allowed_children = {}
children = ()
class WebDAVTextElement (WebDAVElement):
"""
WebDAV element containing PCDATA.
"""
def fromString(clazz, string):
if string is None:
return clazz()
elif isinstance(string, (str, unicode)):
return clazz(PCDATAElement(string))
else:
return clazz(PCDATAElement(str(string)))
fromString = classmethod(fromString)
allowed_children = { PCDATAElement: (0, None) }
def __str__(self):
return "".join([c.data for c in self.children])
def __repr__(self):
content = str(self)
if content:
return "<%s: %r>" % (self.sname(), content)
else:
return "<%s>" % (self.sname(),)
def __eq__(self, other):
if isinstance(other, WebDAVTextElement):
return str(self) == str(other)
elif type(other) in (str, unicode):
return str(self) == other
else:
return NotImplemented
class WebDAVDateTimeElement (WebDAVTextElement):
"""
WebDAV date-time element. (RFC 2518, section 23.2)
"""
def fromDate(clazz, date):
"""
date may be a datetime.datetime instance, a POSIX timestamp
(integer value, such as returned by time.time()), or an ISO
8601-formatted (eg. "2005-06-13T16:14:11Z") date/time string.
"""
def isoformat(date):
if date.utcoffset() is None:
return date.isoformat() + "Z"
else:
return date.isoformat()
if type(date) is int:
date = isoformat(datetime.datetime.fromtimestamp(date))
elif type(date) is str:
pass
elif type(date) is unicode:
date = date.encode("utf-8")
elif isinstance(date, datetime.datetime):
date = isoformat(date)
else:
raise ValueError("Unknown date type: %r" % (date,))
return clazz(PCDATAElement(date))
fromDate = classmethod(fromDate)
def __init__(self, *children, **attributes):
super(WebDAVDateTimeElement, self).__init__(*children, **attributes)
self.datetime() # Raise ValueError if the format is wrong
def __eq__(self, other):
if isinstance(other, WebDAVDateTimeElement):
return self.datetime() == other.datetime()
else:
return NotImplemented
def datetime(self):
s = str(self)
if not s:
return None
else:
return parse_date(s)
class DateTimeHeaderElement (WebDAVTextElement):
"""
WebDAV date-time element for elements that substitute for HTTP
headers. (RFC 2068, section 3.3.1)
"""
def fromDate(clazz, date):
"""
date may be a datetime.datetime instance, a POSIX timestamp
(integer value, such as returned by time.time()), or an RFC
2068 Full Date (eg. "Mon, 23 May 2005 04:52:22 GMT") string.
"""
def format(date):
#
# FIXME: strftime() is subject to localization nonsense; we need to
# ensure that we're using the correct localization, or don't use
# strftime().
#
return date.strftime("%a, %d %b %Y %H:%M:%S GMT")
if type(date) is int:
date = format(datetime.datetime.fromtimestamp(date))
elif type(date) is str:
pass
elif type(date) is unicode:
date = date.encode("utf-8")
elif isinstance(date, datetime.datetime):
if date.tzinfo:
raise NotImplementedError("I need to normalize to UTC")
date = format(date)
else:
raise ValueError("Unknown date type: %r" % (date,))
return clazz(PCDATAElement(date))
fromDate = classmethod(fromDate)
def __init__(self, *children, **attributes):
super(DateTimeHeaderElement, self).__init__(*children, **attributes)
self.datetime() # Raise ValueError if the format is wrong
def __eq__(self, other):
if isinstance(other, WebDAVDateTimeElement):
return self.datetime() == other.datetime()
else:
return NotImplemented
def datetime(self):
s = str(self)
if not s:
return None
else:
return parseDateTime(s)
##
# Utilities
##
class FixedOffset (datetime.tzinfo):
"""
Fixed offset in minutes east from UTC.
"""
def __init__(self, offset, name=None):
super(FixedOffset, self).__init__()
self._offset = datetime.timedelta(minutes=offset)
self._name = name
def utcoffset(self, dt): return self._offset
def tzname (self, dt): return self._name
def dst (self, dt): return datetime.timedelta(0)
def parse_date(date):
"""
Parse an ISO 8601 date and return a corresponding datetime.datetime object.
"""
# See http://www.iso.org/iso/en/prods-services/popstds/datesandtime.html
global regex_date
if regex_date is None:
import re
regex_date = re.compile(
"^" +
"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})T" +
"(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})(?:.(?P<subsecond>\d+))*" +
"(?:Z|(?P<offset_sign>\+|-)(?P<offset_hour>\d{2}):(?P<offset_minute>\d{2}))" +
"$"
)
match = regex_date.match(date)
if match is not None:
subsecond = match.group("subsecond")
if subsecond is None:
subsecond = 0
else:
subsecond = int(subsecond)
offset_sign = match.group("offset_sign")
if offset_sign is None:
offset = FixedOffset(0)
else:
offset_hour = int(match.group("offset_hour" ))
offset_minute = int(match.group("offset_minute"))
delta = (offset_hour * 60) + offset_minute
if offset_sign == "+": offset = FixedOffset(0 - delta)
elif offset_sign == "-": offset = FixedOffset(0 + delta)
return datetime.datetime(
int(match.group("year" )),
int(match.group("month" )),
int(match.group("day" )),
int(match.group("hour" )),
int(match.group("minute")),
int(match.group("second")),
subsecond,
offset
)
else:
raise ValueError("Invalid ISO 8601 date format: %r" % (date,))
regex_date = None
|
santisiri/popego
|
envs/ALPHA-POPEGO/lib/python2.5/site-packages/twisted/web2/dav/element/base.py
|
Python
|
bsd-3-clause
| 18,439 |
/*
* Copyright (c) 2012, Yahoo! Inc. All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
var config = {};
// User default config
config.seleniumHost = "";
config.defaultAppHost = "";
config.logLevel = "INFO";
config.browser = "firefox";
config.firefoxVersion = "";
config.parallel = false;
config.baseUrl = "";
// Framework config
config.arrowModuleRoot = global.appRoot + "/";
config.dimensions = config.arrowModuleRoot + "config/dimensions.json";
config.defaultTestHost = config.arrowModuleRoot + "lib/client/testHost.html";
config.defaultAppSeed = "http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js";
config.testSeed = config.arrowModuleRoot + "lib/client/yuitest-seed.js";
config.testRunner = config.arrowModuleRoot + "lib/client/yuitest-runner.js";
config.autolib = config.arrowModuleRoot + "lib/common";
config.descriptorName = "test_descriptor.json";
module.exports = config;
|
proverma/arrow
|
tests/unit/lib/session/testdata/config.js
|
JavaScript
|
bsd-3-clause
| 957 |
/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm/gm.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkColor.h"
#include "include/core/SkMatrix.h"
#include "include/core/SkPaint.h"
#include "include/core/SkPath.h"
#include "include/core/SkPoint.h"
#include "include/core/SkRect.h"
#include "include/core/SkScalar.h"
#include "include/core/SkSize.h"
#include "include/core/SkString.h"
#include "include/core/SkTypes.h"
#include "include/utils/SkRandom.h"
#include "tools/ToolUtils.h"
#include <array>
#include <vector>
namespace skiagm {
static constexpr int kPadSize = 20;
static constexpr int kBoxSize = 100;
static constexpr SkPoint kJitters[] = {{0, 0}, {.5f, .5f}, {2/3.f, 1/3.f}};
// Tests various corners of different angles falling on the same pixel, particularly to ensure
// analytic AA is working properly.
class SharedCornersGM : public GM {
public:
SharedCornersGM() { this->setBGColor(ToolUtils::color_to_565(0xFF1A65D7)); }
protected:
SkString onShortName() override {
return SkString("sharedcorners");
}
SkISize onISize() override {
constexpr int numRows = 3 * 2;
constexpr int numCols = (1 + SK_ARRAY_COUNT(kJitters)) * 2;
return SkISize::Make(numCols * (kBoxSize + kPadSize) + kPadSize,
numRows * (kBoxSize + kPadSize) + kPadSize);
}
void onOnceBeforeDraw() override {
fFillPaint.setColor(SK_ColorWHITE);
fFillPaint.setAntiAlias(true);
fWireFramePaint = fFillPaint;
fWireFramePaint.setStyle(SkPaint::kStroke_Style);
}
void onDraw(SkCanvas* canvas) override {
canvas->translate(kPadSize, kPadSize);
canvas->save();
// Adjacent rects.
this->drawTriangleBoxes(canvas,
{{0, 0}, {40, 0}, {80, 0}, {120, 0},
{0, 20}, {40, 20}, {80, 20}, {120, 20},
{40, 40}, {80, 40},
{40, 60}, {80, 60}},
{{{0, 1, 4}}, {{1, 5, 4}},
{{5, 1, 6}}, {{1, 2, 6}},
{{2, 3, 6}}, {{3, 7, 6}},
{{8, 5, 9}}, {{5, 6, 9}},
{{10, 8, 11}}, {{8, 9, 11}}});
// Obtuse angles.
this->drawTriangleBoxes(canvas,
{{ 0, 0}, {10, 0}, {20, 0},
{ 0, 2}, {20, 2},
{10, 4},
{ 0, 6}, {20, 6},
{ 0, 8}, {10, 8}, {20, 8}},
{{{3, 1, 4}}, {{4, 5, 3}}, {{6, 5, 7}}, {{7, 9, 6}},
{{0, 1, 3}}, {{1, 2, 4}},
{{3, 5, 6}}, {{5, 4, 7}},
{{6, 9, 8}}, {{9, 7, 10}}});
canvas->restore();
canvas->translate((kBoxSize + kPadSize) * 4, 0);
// Right angles.
this->drawTriangleBoxes(canvas,
{{0, 0}, {-1, 0}, {0, -1}, {1, 0}, {0, 1}},
{{{0, 1, 2}}, {{0, 2, 3}}, {{0, 3, 4}}, {{0, 4, 1}}});
// Acute angles.
SkRandom rand;
std::vector<SkPoint> pts;
std::vector<std::array<int, 3>> indices;
SkScalar theta = 0;
pts.push_back({0, 0});
while (theta < 2*SK_ScalarPI) {
pts.push_back({SkScalarCos(theta), SkScalarSin(theta)});
if (pts.size() > 2) {
indices.push_back({{0, (int)pts.size() - 2, (int)pts.size() - 1}});
}
theta += rand.nextRangeF(0, SK_ScalarPI/3);
}
indices.push_back({{0, (int)pts.size() - 1, 1}});
this->drawTriangleBoxes(canvas, pts, indices);
}
void drawTriangleBoxes(SkCanvas* canvas, const std::vector<SkPoint>& points,
const std::vector<std::array<int, 3>>& triangles) {
SkPath path;
path.setFillType(SkPathFillType::kEvenOdd);
path.setIsVolatile(true);
for (const std::array<int, 3>& triangle : triangles) {
path.moveTo(points[triangle[0]]);
path.lineTo(points[triangle[1]]);
path.lineTo(points[triangle[2]]);
path.close();
}
SkScalar scale = kBoxSize / SkTMax(path.getBounds().height(), path.getBounds().width());
path.transform(SkMatrix::MakeScale(scale, scale));
this->drawRow(canvas, path);
canvas->translate(0, kBoxSize + kPadSize);
SkMatrix rot;
rot.setRotate(45, path.getBounds().centerX(), path.getBounds().centerY());
path.transform(rot);
this->drawRow(canvas, path);
canvas->translate(0, kBoxSize + kPadSize);
rot.setRotate(-45 - 69.38111f, path.getBounds().centerX(), path.getBounds().centerY());
path.transform(rot);
this->drawRow(canvas, path);
canvas->translate(0, kBoxSize + kPadSize);
}
void drawRow(SkCanvas* canvas, const SkPath& path) {
SkAutoCanvasRestore acr(canvas, true);
const SkRect& bounds = path.getBounds();
canvas->translate((kBoxSize - bounds.width()) / 2 - bounds.left(),
(kBoxSize - bounds.height()) / 2 - bounds.top());
canvas->drawPath(path, fWireFramePaint);
canvas->translate(kBoxSize + kPadSize, 0);
for (SkPoint jitter : kJitters) {
{
SkAutoCanvasRestore acr(canvas, true);
canvas->translate(jitter.x(), jitter.y());
canvas->drawPath(path, fFillPaint);
}
canvas->translate(kBoxSize + kPadSize, 0);
}
}
SkPaint fWireFramePaint;
SkPaint fFillPaint;
};
DEF_GM(return new SharedCornersGM;)
}
|
HalCanary/skia-hc
|
gm/sharedcorners.cpp
|
C++
|
bsd-3-clause
| 5,681 |
<?php
$code = $_REQUEST['code'];
$info = '';
//echo $code;
if (empty($_REQUEST['state']))
{
echo '未验证的请求。。。 code='.$code ;
//redirect('/w/index.php');
}
else if ($_REQUEST['state'] == 'wb')
{
$url = "/index.php?r=weibo/codetotoken&code=".$code;
$info = 'oauth get code success. ';
//echo "<a href='".$_SERVER['HTTP_HOST'].":/".$url."'>进入新浪微博</a>";
//header("Location: $url");
}
else if ($_REQUEST['state'] == 'tx')
{
//$url = "/w/index.php/Account/tx_auth?".http_build_query($_REQUEST);
$info = 'oauth get code failed.';
//echo "<a href='".$_SERVER['HTTP_HOST'].":/".$url."'>进入腾讯微博</a>";
//header("Location: $url");
}
else
{
$info = 'unknown state when oauth get code: state='.$_REQUEST['state'];
}
?>
<html>
<head>
<!--
<meta http-equiv="refresh" content="1;url=<?php echo $url; ?>">
-->
<?php #echo "<script>location.href='$url';</script>"; ?>
</head>
<body>
<?php echo $info;?>
<br/>
this page will auth go next. if not, <a href="<?php echo $url; ?>">click here go on</a>.
</body>
</html>
|
uxff/yii2-advanced
|
frontend/web/oauthcallback.php
|
PHP
|
bsd-3-clause
| 1,126 |
/**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* 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 NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK 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.
*
* @providesModule Game2048
* @flow
*/
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
} = React;
var Animated = require('Animated');
var GameBoard = require('GameBoard');
var TouchableBounce = require('TouchableBounce');
var BOARD_PADDING = 3;
var CELL_MARGIN = 4;
var CELL_SIZE = 60;
class Cell extends React.Component {
render() {
return <View style={styles.cell} />;
}
}
class Board extends React.Component {
render() {
return (
<View style={styles.board}>
<View style={styles.row}><Cell/><Cell/><Cell/><Cell/></View>
<View style={styles.row}><Cell/><Cell/><Cell/><Cell/></View>
<View style={styles.row}><Cell/><Cell/><Cell/><Cell/></View>
<View style={styles.row}><Cell/><Cell/><Cell/><Cell/></View>
{this.props.children}
</View>
);
}
}
class Tile extends React.Component {
static _getPosition(index): number {
return BOARD_PADDING + (index * (CELL_SIZE + CELL_MARGIN * 2) + CELL_MARGIN);
}
constructor(props: {}) {
super(props);
var tile = this.props.tile;
this.state = {
opacity: new Animated.Value(0),
top: new Animated.Value(Tile._getPosition(tile.toRow())),
left: new Animated.Value(Tile._getPosition(tile.toColumn())),
};
}
calculateOffset(): {top: number; left: number; opacity: number} {
var tile = this.props.tile;
var offset = {
top: this.state.top,
left: this.state.left,
opacity: this.state.opacity,
};
if (tile.isNew()) {
Animated.timing(this.state.opacity, {
duration: 100,
toValue: 1,
}).start();
} else {
Animated.parallel([
Animated.timing(offset.top, {
duration: 100,
toValue: Tile._getPosition(tile.toRow()),
}),
Animated.timing(offset.left, {
duration: 100,
toValue: Tile._getPosition(tile.toColumn()),
}),
]).start();
}
return offset;
}
render() {
var tile = this.props.tile;
var tileStyles = [
styles.tile,
styles['tile' + tile.value],
this.calculateOffset(),
];
var textStyles = [
styles.value,
tile.value > 4 && styles.whiteText,
tile.value > 100 && styles.threeDigits,
tile.value > 1000 && styles.fourDigits,
];
return (
<Animated.View style={tileStyles}>
<Text style={textStyles}>{tile.value}</Text>
</Animated.View>
);
}
}
class GameEndOverlay extends React.Component {
render() {
var board = this.props.board;
if (!board.hasWon() && !board.hasLost()) {
return <View/>;
}
var message = board.hasWon() ?
'Good Job!' : 'Game Over';
return (
<View style={styles.overlay}>
<Text style={styles.overlayMessage}>{message}</Text>
<TouchableBounce onPress={this.props.onRestart} style={styles.tryAgain}>
<Text style={styles.tryAgainText}>Try Again?</Text>
</TouchableBounce>
</View>
);
}
}
class Game2048 extends React.Component {
startX: number;
startY: number;
constructor(props: {}) {
super(props);
this.state = {
board: new GameBoard(),
};
this.startX = 0;
this.startY = 0;
}
restartGame() {
this.setState({board: new GameBoard()});
}
handleTouchStart(event: Object) {
if (this.state.board.hasWon()) {
return;
}
this.startX = event.nativeEvent.pageX;
this.startY = event.nativeEvent.pageY;
}
handleTouchEnd(event: Object) {
if (this.state.board.hasWon()) {
return;
}
var deltaX = event.nativeEvent.pageX - this.startX;
var deltaY = event.nativeEvent.pageY - this.startY;
var direction = -1;
if (Math.abs(deltaX) > 3 * Math.abs(deltaY) && Math.abs(deltaX) > 30) {
direction = deltaX > 0 ? 2 : 0;
} else if (Math.abs(deltaY) > 3 * Math.abs(deltaX) && Math.abs(deltaY) > 30) {
direction = deltaY > 0 ? 3 : 1;
}
if (direction !== -1) {
this.setState({board: this.state.board.move(direction)});
}
}
render() {
var tiles = this.state.board.tiles
.filter((tile) => tile.value)
.map((tile) => <Tile ref={tile.id} key={tile.id} tile={tile} />);
return (
<View
style={styles.container}
onTouchStart={(event) => this.handleTouchStart(event)}
onTouchEnd={(event) => this.handleTouchEnd(event)}>
<Board>
{tiles}
</Board>
<GameEndOverlay board={this.state.board} onRestart={() => this.restartGame()} />
</View>
);
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
board: {
padding: BOARD_PADDING,
backgroundColor: '#bbaaaa',
borderRadius: 5,
},
overlay: {
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
backgroundColor: 'rgba(221, 221, 221, 0.5)',
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
overlayMessage: {
fontSize: 40,
marginBottom: 20,
},
tryAgain: {
backgroundColor: '#887761',
padding: 20,
borderRadius: 5,
},
tryAgainText: {
color: '#ffffff',
fontSize: 20,
fontWeight: '500',
},
cell: {
width: CELL_SIZE,
height: CELL_SIZE,
borderRadius: 5,
backgroundColor: '#ddccbb',
margin: CELL_MARGIN,
},
row: {
flexDirection: 'row',
},
tile: {
position: 'absolute',
width: CELL_SIZE,
height: CELL_SIZE,
backgroundColor: '#ddccbb',
borderRadius: 5,
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
value: {
fontSize: 24,
color: '#776666',
fontFamily: 'Verdana',
fontWeight: '500',
},
tile2: {
backgroundColor: '#eeeeee',
},
tile4: {
backgroundColor: '#eeeecc',
},
tile8: {
backgroundColor: '#ffbb88',
},
tile16: {
backgroundColor: '#ff9966',
},
tile32: {
backgroundColor: '#ff7755',
},
tile64: {
backgroundColor: '#ff5533',
},
tile128: {
backgroundColor: '#eecc77',
},
tile256: {
backgroundColor: '#eecc66',
},
tile512: {
backgroundColor: '#eecc55',
},
tile1024: {
backgroundColor: '#eecc33',
},
tile2048: {
backgroundColor: '#eecc22',
},
whiteText: {
color: '#ffffff',
},
threeDigits: {
fontSize: 20,
},
fourDigits: {
fontSize: 18,
},
});
AppRegistry.registerComponent('Game2048', () => Game2048);
module.exports = Game2048;
|
quyixia/react-native
|
Examples/2048/Game2048.js
|
JavaScript
|
bsd-3-clause
| 7,190 |
#!/bin/bash
#Copyright (c) 2008, Jay Wang
#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 the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
PATH=/bin
echo `pwd` > msys/root
echo "@echo off" > start-msys.bat
echo "set ROOT=`pwd -W`" >> start-msys.bat
echo "set VROOT=`pwd`" >> start-msys.bat
cat start-msys.bat.in >> start-msys.bat
tools/todos.exe start-msys.bat
echo "@echo off" > start-msys-rxvt.bat
echo "set ROOT=`pwd -W`" >> start-msys-rxvt.bat
echo "set VROOT=`pwd`" >> start-msys-rxvt.bat
cat start-msys-rxvt.bat.in >> start-msys-rxvt.bat
tools/todos.exe start-msys-rxvt.bat
echo "@echo off" > start-cmd.bat
echo "set ROOT=`pwd -W`" >> start-cmd.bat
echo "set VROOT=`pwd`" >> start-msys.bat
cat start-cmd.bat.in >> start-cmd.bat
tools/todos.exe start-cmd.bat
echo >> msys/etc/fstab
echo "`pwd -W`/mingw /mingw" >> msys/etc/fstab
|
stu90206/mozbuildtools
|
start-script/set_root2.sh
|
Shell
|
bsd-3-clause
| 2,235 |
#=
Copyright (c) 2015, Intel Corporation
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 Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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("../../src/Sparso.jl")
include("../../src/simple-show.jl")
using Sparso
set_options(SA_ENABLE, SA_VERBOSE, SA_USE_SPMP, SA_REPLACE_CALLS)
function WAXPBY_test(p, beta, r)
p = r + beta * p
end
m = 10
p = repmat([1/m], m)
r = copy(p)
beta = 0.1
@acc WAXPBY_test(p, beta, r)
|
IntelLabs/Sparso
|
test/correctness/call-replacement-test7.jl
|
Julia
|
bsd-3-clause
| 1,794 |
/* eslint-env jest */
import { getEditionData, getPastSixDaysData } from "./api";
import { fetchJSON as mockFetchJSON } from "./util";
jest.mock("./util", () => ({
today: () => "2019-02-12",
fetchJSON: jest.fn(() => Promise.resolve())
}));
describe("api", () => {
let originalConsole;
beforeEach(() => {
originalConsole = global.console;
global.console = { log: () => null };
mockFetchJSON.mockReset();
});
afterEach(() => {
global.console = originalConsole;
});
describe("getEditionData", () => {
it("requests the correct data from the API", async () => {
mockFetchJSON.mockReturnValueOnce(
Promise.resolve({
cpi_updatetext: "9AM UPDATE",
cpi_modules: [],
title: "Times Tuesday 12 February 2019"
})
);
await getEditionData({
edition: "latest",
api: "http://times.api"
});
expect(mockFetchJSON.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
"http://times.api/edition/latest?include=article",
],
]
`);
});
it("returns the correct data", async () => {
mockFetchJSON.mockReturnValueOnce(
Promise.resolve({
cpi_updatetext: "9AM UPDATE",
cpi_modules: [
{ identifier: "abc" },
{ identifier: "def" },
{ identifier: "ghi" }
],
title: "Times Tuesday 12 February 2019"
})
);
expect(await getEditionData({})).toMatchInlineSnapshot(`
Object {
"ids": Array [
"abc",
"def",
"ghi",
],
"title": "Times Tuesday 12 February 2019 (9AM UPDATE)",
}
`);
});
});
describe("getPastSixDaysData", () => {
it("requests the correct data from the APIs", async () => {
mockFetchJSON.mockImplementation(url =>
Promise.resolve(
url.includes("past-six-days")
? [{ editiondate: "2019-02-11" }, { editiondate: "2019-02-12" }]
: {
cpi_updatetext: "9AM UPDATE",
cpi_modules: [],
title: "Times Tuesday 12 February 2019"
}
)
);
await getPastSixDaysData({
api: "http://times.api"
});
expect(mockFetchJSON.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
"http://times.api/past-six-days",
],
Array [
"http://times.api/edition/2019-02-11?include=article",
],
Array [
"http://times.api/edition/2019-02-12?include=article",
],
]
`);
});
it("returns the correct data", async () => {
mockFetchJSON.mockImplementation(url =>
Promise.resolve(
url.includes("past-six-days")
? [{ editiondate: "2019-02-11" }, { editiondate: "2019-02-12" }]
: {
cpi_updatetext: "9AM UPDATE",
cpi_modules: [
{ identifier: "abc" },
{ identifier: "def" },
{ identifier: "ghi" }
],
title: "Times Tuesday 12 February 2019"
}
)
);
expect(await getPastSixDaysData({})).toMatchInlineSnapshot(`
Object {
"ids": Array [
"abc",
"def",
"ghi",
"abc",
"def",
"ghi",
],
"title": "Past six days from 2019-02-12",
}
`);
});
});
});
|
newsuk/times-components
|
lib/cli/edition-checker/src/api.test.js
|
JavaScript
|
bsd-3-clause
| 3,576 |
---------------------------------------------------------------------------------------------------
-- User story: Smoke
-- Use case: DeleteInteractionChoiceSet
-- Item: Happy path
--
-- Requirement summary:
-- [DeleteInteractionChoiceSet] SUCCESS choiceSet removal
--
-- Description:
-- Mobile application sends valid DeleteInteractionChoiceSet request to SDL
-- and interactionChoiceSet with <interactionChoiceSetID> was successfully
-- removed on SDL and HMI for the application.
-- Pre-conditions:
-- a. HMI and SDL are started
-- b. appID is registered and activated on SDL
-- c. appID is currently in Background, Full or Limited HMI level
-- d. Choice set with <interactionChoiceSetID> is created
-- Steps:
-- appID requests DeleteInteractionChoiceSet request with valid parameters
-- Expected:
-- SDL validates parameters of the request
-- SDL checks if VR interface is available on HMI
-- SDL checks if DeleteInteractionChoiceSet is allowed by Policies
-- SDL checks if all parameters are allowed by Policies
-- SDL transfers the VR.DeleteCommand with allowed parameters to HMI
-- SDL receives successful responses to corresponding VR.DeleteCommand from HMI
-- SDL responds with (resultCode: SUCCESS, success:true) to mobile application
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local common = require('test_scripts/Smoke/commonSmoke')
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
--[[ Local Variables ]]
local putFileParams = {
requestParams = {
syncFileName = 'icon.png',
fileType = "GRAPHIC_PNG",
persistentFile = false,
systemFile = false
},
filePath = "files/icon.png"
}
local createRequestParams = {
interactionChoiceSetID = 1001,
choiceSet = {
{
choiceID = 1001,
menuName ="Choice1001",
vrCommands = {
"Choice1001"
},
image = {
value ="icon.png",
imageType ="DYNAMIC"
}
}
}
}
local createResponseVrParams = {
cmdID = createRequestParams.interactionChoiceSetID,
type = "Choice",
vrCommands = createRequestParams.vrCommands
}
local createAllParams = {
requestParams = createRequestParams,
responseVrParams = createResponseVrParams
}
local deleteRequestParams = {
interactionChoiceSetID = createRequestParams.interactionChoiceSetID
}
local deleteResponseVrParams = {
cmdID = createRequestParams.interactionChoiceSetID,
type = "Choice"
}
local deleteAllParams = {
requestParams = deleteRequestParams,
responseVrParams = deleteResponseVrParams
}
--[[ Local Functions ]]
local function createInteractionChoiceSet(pParams)
local cid = common.getMobileSession():SendRPC("CreateInteractionChoiceSet", pParams.requestParams)
pParams.responseVrParams.appID = common.getHMIAppId()
common.getHMIConnection():ExpectRequest("VR.AddCommand", pParams.responseVrParams)
:Do(function(_, data)
common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {})
end)
:ValidIf(function(_, data)
if data.params.grammarID ~= nil then
deleteResponseVrParams.grammarID = data.params.grammarID
return true
else
return false, "grammarID should not be empty"
end
end)
common.getMobileSession():ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
common.getMobileSession():ExpectNotification("OnHashChange")
end
local function deleteInteractionChoiceSet(pParams)
local cid = common.getMobileSession():SendRPC("DeleteInteractionChoiceSet", pParams.requestParams)
pParams.responseVrParams.appID = common.getHMIAppId()
common.getHMIConnection():ExpectRequest("VR.DeleteCommand", pParams.responseVrParams)
:Do(function(_, data)
common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {})
end)
common.getMobileSession():ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
common.getMobileSession():ExpectNotification("OnHashChange")
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Update Preloaded PT", common.updatePreloadedPT)
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("Register App", common.registerApp)
runner.Step("Activate App", common.activateApp)
runner.Step("Upload icon file", common.putFile, { putFileParams })
runner.Step("CreateInteractionChoiceSet", createInteractionChoiceSet, { createAllParams })
runner.Title("Test")
runner.Step("DeleteInteractionChoiceSet Positive Case", deleteInteractionChoiceSet, { deleteAllParams })
runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)
|
smartdevicelink/sdl_atf_test_scripts
|
test_scripts/Smoke/API/009_DeleteInteractionChoiceSet_PositiveCase_SUCCESS.lua
|
Lua
|
bsd-3-clause
| 4,761 |
<?php
namespace App\Views\Helpers;
class FormatHelper {
/**
* SIMPLE DEMO string formatter.
* Format any string template with curly bracket
* replacements: '...{0}...{1}...', given as first param
* with params given as all next arguments
* @param string $template string template with curly brackets replacements: '...{0}...{1}...'
* @param mixed $args.., any arguments converted to string
* @return string
*/
public function Format ($template, $args) {
$arguments = func_get_args();
if (count($arguments) == 0) return '';
if (count($arguments) == 1) return $arguments[0];
$str = array_shift($arguments);
foreach ($arguments as $key => $val)
$str = str_replace('{'.$key.'}', (string)$val, $str);
return $str;
}
}
|
mvccore/project-basic
|
App/Views/Helpers/FormatHelper.php
|
PHP
|
bsd-3-clause
| 756 |
/* GDOME Document Object Model C API for openjs
* $Id: wrappers.h 9311 2009-09-06 07:08:12Z jheusala $
*/
#ifndef OPENJS_EXTENSIONS_CGDOME_WRAPPERS_H
#define OPENJS_EXTENSIONS_CGDOME_WRAPPERS_H 1
#include "../../core/v8.h"
namespace openjs {
namespace extensions {
#include "auto-wrappers.h"
}
}
#endif
|
sendanor/openjs
|
src/openjs/extensions/mod_cgdome/wrappers.h
|
C
|
bsd-3-clause
| 313 |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\Insurance */
$this->title = '车险报价';
$this->params['breadcrumbs'][] = ['label' => 'Insurances', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="insurance-create">
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
|
xiaohaoyong/AcarAdmin
|
views/insurance/create.php
|
PHP
|
bsd-3-clause
| 372 |
<?php
declare(strict_types=1);
namespace LizardsAndPumpkins\DataPool\UrlKeyStore;
use LizardsAndPumpkins\Util\Storage\Clearable;
class InMemoryUrlKeyStore extends IntegrationTestUrlKeyStoreAbstract implements UrlKeyStore, Clearable
{
/**
* @var string[]
*/
private $urlKeys = [];
public function clear(): void
{
$this->urlKeys = [];
}
public function addUrlKeyForVersion(
string $dataVersionString,
string $urlKeyString,
string $contextDataString,
string $urlKeyTypeString
) {
$this->validateParameters($dataVersionString);
$this->urlKeys[$dataVersionString][] = [$urlKeyString, $contextDataString, $urlKeyTypeString];
}
private function validateParameters(string $dataVersionString): void
{
$this->validateDataVersionString($dataVersionString);
}
/**
* @param string $dataVersionString
* @return string[]
*/
public function getForDataVersion(string $dataVersionString) : array
{
$this->validateDataVersionString($dataVersionString);
return $this->urlKeys[$dataVersionString] ?? [];
}
}
|
lizards-and-pumpkins/catalog
|
src/DataPool/UrlKeyStore/InMemoryUrlKeyStore.php
|
PHP
|
bsd-3-clause
| 1,160 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.