text
stringlengths
2
100k
meta
dict
// Boost.Units - A C++ library for zero-overhead dimensional analysis and // unit/quantity manipulation and conversion // // Copyright (C) 2003-2008 Matthias Christian Schabel // Copyright (C) 2007-2008 Steven Watanabe // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_UNIT_SYSTEMS_IMPERIAL_HUNDREDWEIGHT_HPP_INCLUDED #define BOOST_UNIT_SYSTEMS_IMPERIAL_HUNDREDWEIGHT_HPP_INCLUDED #include <boost/units/scaled_base_unit.hpp> #include <boost/units/static_rational.hpp> #include <boost/units/scale.hpp> #include <boost/units/base_units/imperial/pound.hpp> namespace boost { namespace units { namespace imperial { typedef scaled_base_unit<pound_base_unit, scale<112, static_rational<1> > > hundredweight_base_unit; } // namespace imperial template<> struct base_unit_info<imperial::hundredweight_base_unit> { static const char* name() { return("hundredweight"); } static const char* symbol() { return("cwt"); } }; } // namespace units } // namespace boost #endif // BOOST_UNIT_SYSTEMS_IMPERIAL_HUNDREDWEIGHT_HPP_INCLUDED
{ "pile_set_name": "Github" }
/** * @name Uncontrolled data in arithmetic expression * @description Arithmetic operations on uncontrolled data that is not validated can cause * overflows. * @kind path-problem * @problem.severity warning * @precision medium * @id java/uncontrolled-arithmetic * @tags security * external/cwe/cwe-190 * external/cwe/cwe-191 */ import java import semmle.code.java.dataflow.TaintTracking import semmle.code.java.security.SecurityTests import ArithmeticCommon import DataFlow::PathGraph class TaintSource extends DataFlow::ExprNode { TaintSource() { // Either this is an access to a random number generating method of the right kind, ... exists(Method def | def = this.getExpr().(MethodAccess).getMethod() and ( // Some random-number methods are omitted: // `nextDouble` and `nextFloat` are between 0 and 1, // `nextGaussian` is extremely unlikely to hit max values. def.getName() = "nextInt" or def.getName() = "nextLong" ) and def.getNumberOfParameters() = 0 and def.getDeclaringType().hasQualifiedName("java.util", "Random") ) or // ... or this is the array parameter of `nextBytes`, which is filled with random bytes. exists(MethodAccess m, Method def | m.getAnArgument() = this.getExpr() and m.getMethod() = def and def.getName() = "nextBytes" and def.getNumberOfParameters() = 1 and def.getDeclaringType().hasQualifiedName("java.util", "Random") ) } } class ArithmeticUncontrolledOverflowConfig extends TaintTracking::Configuration { ArithmeticUncontrolledOverflowConfig() { this = "ArithmeticUncontrolledOverflowConfig" } override predicate isSource(DataFlow::Node source) { source instanceof TaintSource } override predicate isSink(DataFlow::Node sink) { overflowSink(_, sink.asExpr()) } override predicate isSanitizer(DataFlow::Node n) { overflowBarrier(n) } } class ArithmeticUncontrolledUnderflowConfig extends TaintTracking::Configuration { ArithmeticUncontrolledUnderflowConfig() { this = "ArithmeticUncontrolledUnderflowConfig" } override predicate isSource(DataFlow::Node source) { source instanceof TaintSource } override predicate isSink(DataFlow::Node sink) { underflowSink(_, sink.asExpr()) } override predicate isSanitizer(DataFlow::Node n) { underflowBarrier(n) } } from DataFlow::PathNode source, DataFlow::PathNode sink, ArithExpr exp, string effect where any(ArithmeticUncontrolledOverflowConfig c).hasFlowPath(source, sink) and overflowSink(exp, sink.getNode().asExpr()) and effect = "overflow" or any(ArithmeticUncontrolledUnderflowConfig c).hasFlowPath(source, sink) and underflowSink(exp, sink.getNode().asExpr()) and effect = "underflow" select exp, source, sink, "$@ flows to here and is used in arithmetic, potentially causing an " + effect + ".", source.getNode(), "Uncontrolled value"
{ "pile_set_name": "Github" }
<ion-header> <ion-navbar> <ion-title>Toasts</ion-title> </ion-navbar> </ion-header> <ion-content padding> <button ion-button block (click)="showToast()">Show Toast and Navigate</button> <button ion-button block (click)="showLongToast()">Show Long Toast</button> <button ion-button block (click)="showDismissPageChangeToast()">Show Toast Dismiss Page Change</button> <br /> <button ion-button block (click)="showDismissDurationToast()">Custom (1.5s) Duration</button> <button ion-button block (click)="showToastWithCloseButton('bottom')" class="e2eOpenToast">With closeButtonText</button> <button ion-button block (click)="showToastWithCloseButton('top')">Top With closeButtonText</button> <button ion-button block (click)="showToastWithCloseButton('middle')">Middle With closeButtonText</button> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed lacinia purus ac turpis fermentum, nec accumsan nulla rutrum. Aenean lorem est, luctus id iaculis ac, ultricies quis odio. Aenean imperdiet imperdiet ex et vehicula. Suspendisse vulputate turpis quis ultricies porttitor. Proin malesuada tortor at libero laoreet, eu eleifend enim pulvinar. Nulla facilisi. Fusce sit amet mauris mauris. Mauris consequat libero sed egestas tincidunt. </p> <p> In felis augue, sagittis id dui ac, tempor luctus turpis. Vestibulum nec urna vitae nisl malesuada lacinia ut sit amet orci. Suspendisse sed mauris vitae mauris porttitor pulvinar. Donec quis ante id dui cursus malesuada ut nec magna. Vestibulum venenatis efficitur urna, quis tempus quam. Curabitur id elementum eros, at euismod nisl. Aliquam ultricies imperdiet arcu id consequat. Aliquam erat volutpat. Nam quis laoreet dui. Donec eget neque non leo porta scelerisque. In blandit placerat nibh, ut viverra nisi feugiat a. Pellentesque semper, ligula et tincidunt egestas, urna arcu pellentesque massa, vitae accumsan ligula velit vitae sem. Nulla porta est id ligula viverra, ut placerat quam auctor. Morbi eget efficitur nibh. </p> <p> Aenean viverra commodo enim eget interdum. Donec condimentum tincidunt sollicitudin. Curabitur malesuada est elementum lectus sodales, vitae eleifend massa dignissim. Pellentesque nec diam dapibus purus vulputate pharetra at id nunc. Vivamus dapibus sed turpis in facilisis. Nulla sollicitudin lacus sem, vel fringilla neque accumsan non. Suspendisse non congue turpis, id mattis ex. Nam sit amet diam quis neque convallis aliquet quis et lorem. Donec sit amet libero sit amet nisl mollis vehicula nec id eros. Curabitur rutrum condimentum porta. Donec pellentesque consectetur lacus. Etiam maximus ante vitae varius eleifend. Integer ac justo sem. Morbi iaculis vel urna in tempus. Aenean at rhoncus nulla. </p> </ion-content>
{ "pile_set_name": "Github" }
/* ========================================== Unity Project - A Test Framework for C Copyright (c) 2007-19 Mike Karlesky, Mark VanderVoord, Greg Williams [Released under MIT License. Please refer to license.txt for details] ========================================== */ #ifndef UNITY_INTERNALS_H #define UNITY_INTERNALS_H #ifdef UNITY_INCLUDE_CONFIG_H #include "unity_config.h" #endif #ifndef UNITY_EXCLUDE_SETJMP_H #include <setjmp.h> #endif #ifndef UNITY_EXCLUDE_MATH_H #include <math.h> #endif #ifndef UNITY_EXCLUDE_STDDEF_H #include <stddef.h> #endif #ifdef UNITY_INCLUDE_PRINT_FORMATTED #include <stdarg.h> #endif /* Unity Attempts to Auto-Detect Integer Types * Attempt 1: UINT_MAX, ULONG_MAX in <limits.h>, or default to 32 bits * Attempt 2: UINTPTR_MAX in <stdint.h>, or default to same size as long * The user may override any of these derived constants: * UNITY_INT_WIDTH, UNITY_LONG_WIDTH, UNITY_POINTER_WIDTH */ #ifndef UNITY_EXCLUDE_STDINT_H #include <stdint.h> #endif #ifndef UNITY_EXCLUDE_LIMITS_H #include <limits.h> #endif /*------------------------------------------------------- * Guess Widths If Not Specified *-------------------------------------------------------*/ /* Determine the size of an int, if not already specified. * We cannot use sizeof(int), because it is not yet defined * at this stage in the translation of the C program. * Also sizeof(int) does return the size in addressable units on all platforms, * which may not necessarily be the size in bytes. * Therefore, infer it from UINT_MAX if possible. */ #ifndef UNITY_INT_WIDTH #ifdef UINT_MAX #if (UINT_MAX == 0xFFFF) #define UNITY_INT_WIDTH (16) #elif (UINT_MAX == 0xFFFFFFFF) #define UNITY_INT_WIDTH (32) #elif (UINT_MAX == 0xFFFFFFFFFFFFFFFF) #define UNITY_INT_WIDTH (64) #endif #else /* Set to default */ #define UNITY_INT_WIDTH (32) #endif /* UINT_MAX */ #endif /* Determine the size of a long, if not already specified. */ #ifndef UNITY_LONG_WIDTH #ifdef ULONG_MAX #if (ULONG_MAX == 0xFFFF) #define UNITY_LONG_WIDTH (16) #elif (ULONG_MAX == 0xFFFFFFFF) #define UNITY_LONG_WIDTH (32) #elif (ULONG_MAX == 0xFFFFFFFFFFFFFFFF) #define UNITY_LONG_WIDTH (64) #endif #else /* Set to default */ #define UNITY_LONG_WIDTH (32) #endif /* ULONG_MAX */ #endif /* Determine the size of a pointer, if not already specified. */ #ifndef UNITY_POINTER_WIDTH #ifdef UINTPTR_MAX #if (UINTPTR_MAX <= 0xFFFF) #define UNITY_POINTER_WIDTH (16) #elif (UINTPTR_MAX <= 0xFFFFFFFF) #define UNITY_POINTER_WIDTH (32) #elif (UINTPTR_MAX <= 0xFFFFFFFFFFFFFFFF) #define UNITY_POINTER_WIDTH (64) #endif #else /* Set to default */ #define UNITY_POINTER_WIDTH UNITY_LONG_WIDTH #endif /* UINTPTR_MAX */ #endif /*------------------------------------------------------- * Int Support (Define types based on detected sizes) *-------------------------------------------------------*/ #if (UNITY_INT_WIDTH == 32) typedef unsigned char UNITY_UINT8; typedef unsigned short UNITY_UINT16; typedef unsigned int UNITY_UINT32; typedef signed char UNITY_INT8; typedef signed short UNITY_INT16; typedef signed int UNITY_INT32; #elif (UNITY_INT_WIDTH == 16) typedef unsigned char UNITY_UINT8; typedef unsigned int UNITY_UINT16; typedef unsigned long UNITY_UINT32; typedef signed char UNITY_INT8; typedef signed int UNITY_INT16; typedef signed long UNITY_INT32; #else #error Invalid UNITY_INT_WIDTH specified! (16 or 32 are supported) #endif /*------------------------------------------------------- * 64-bit Support *-------------------------------------------------------*/ /* Auto-detect 64 Bit Support */ #ifndef UNITY_SUPPORT_64 #if UNITY_LONG_WIDTH == 64 || UNITY_POINTER_WIDTH == 64 #define UNITY_SUPPORT_64 #endif #endif /* 64-Bit Support Dependent Configuration */ #ifndef UNITY_SUPPORT_64 /* No 64-bit Support */ typedef UNITY_UINT32 UNITY_UINT; typedef UNITY_INT32 UNITY_INT; #define UNITY_MAX_NIBBLES (8) /* Maximum number of nibbles in a UNITY_(U)INT */ #else /* 64-bit Support */ #if (UNITY_LONG_WIDTH == 32) typedef unsigned long long UNITY_UINT64; typedef signed long long UNITY_INT64; #elif (UNITY_LONG_WIDTH == 64) typedef unsigned long UNITY_UINT64; typedef signed long UNITY_INT64; #else #error Invalid UNITY_LONG_WIDTH specified! (32 or 64 are supported) #endif typedef UNITY_UINT64 UNITY_UINT; typedef UNITY_INT64 UNITY_INT; #define UNITY_MAX_NIBBLES (16) /* Maximum number of nibbles in a UNITY_(U)INT */ #endif /*------------------------------------------------------- * Pointer Support *-------------------------------------------------------*/ #if (UNITY_POINTER_WIDTH == 32) #define UNITY_PTR_TO_INT UNITY_INT32 #define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX32 #elif (UNITY_POINTER_WIDTH == 64) #define UNITY_PTR_TO_INT UNITY_INT64 #define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX64 #elif (UNITY_POINTER_WIDTH == 16) #define UNITY_PTR_TO_INT UNITY_INT16 #define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX16 #else #error Invalid UNITY_POINTER_WIDTH specified! (16, 32 or 64 are supported) #endif #ifndef UNITY_PTR_ATTRIBUTE #define UNITY_PTR_ATTRIBUTE #endif #ifndef UNITY_INTERNAL_PTR #define UNITY_INTERNAL_PTR UNITY_PTR_ATTRIBUTE const void* #endif /*------------------------------------------------------- * Float Support *-------------------------------------------------------*/ #ifdef UNITY_EXCLUDE_FLOAT /* No Floating Point Support */ #ifndef UNITY_EXCLUDE_DOUBLE #define UNITY_EXCLUDE_DOUBLE /* Remove double when excluding float support */ #endif #ifndef UNITY_EXCLUDE_FLOAT_PRINT #define UNITY_EXCLUDE_FLOAT_PRINT #endif #else /* Floating Point Support */ #ifndef UNITY_FLOAT_PRECISION #define UNITY_FLOAT_PRECISION (0.00001f) #endif #ifndef UNITY_FLOAT_TYPE #define UNITY_FLOAT_TYPE float #endif typedef UNITY_FLOAT_TYPE UNITY_FLOAT; /* isinf & isnan macros should be provided by math.h */ #ifndef isinf /* The value of Inf - Inf is NaN */ #define isinf(n) (isnan((n) - (n)) && !isnan(n)) #endif #ifndef isnan /* NaN is the only floating point value that does NOT equal itself. * Therefore if n != n, then it is NaN. */ #define isnan(n) ((n != n) ? 1 : 0) #endif #endif /*------------------------------------------------------- * Double Float Support *-------------------------------------------------------*/ /* unlike float, we DON'T include by default */ #if defined(UNITY_EXCLUDE_DOUBLE) || !defined(UNITY_INCLUDE_DOUBLE) /* No Floating Point Support */ #ifndef UNITY_EXCLUDE_DOUBLE #define UNITY_EXCLUDE_DOUBLE #else #undef UNITY_INCLUDE_DOUBLE #endif #ifndef UNITY_EXCLUDE_FLOAT #ifndef UNITY_DOUBLE_TYPE #define UNITY_DOUBLE_TYPE double #endif typedef UNITY_FLOAT UNITY_DOUBLE; /* For parameter in UnityPrintFloat(UNITY_DOUBLE), which aliases to double or float */ #endif #else /* Double Floating Point Support */ #ifndef UNITY_DOUBLE_PRECISION #define UNITY_DOUBLE_PRECISION (1e-12) #endif #ifndef UNITY_DOUBLE_TYPE #define UNITY_DOUBLE_TYPE double #endif typedef UNITY_DOUBLE_TYPE UNITY_DOUBLE; #endif /*------------------------------------------------------- * Output Method: stdout (DEFAULT) *-------------------------------------------------------*/ #ifndef UNITY_OUTPUT_CHAR /* Default to using putchar, which is defined in stdio.h */ #include <stdio.h> #define UNITY_OUTPUT_CHAR(a) (void)putchar(a) #else /* If defined as something else, make sure we declare it here so it's ready for use */ #ifdef UNITY_OUTPUT_CHAR_HEADER_DECLARATION extern void UNITY_OUTPUT_CHAR_HEADER_DECLARATION; #endif #endif #ifndef UNITY_OUTPUT_FLUSH #ifdef UNITY_USE_FLUSH_STDOUT /* We want to use the stdout flush utility */ #include <stdio.h> #define UNITY_OUTPUT_FLUSH() (void)fflush(stdout) #else /* We've specified nothing, therefore flush should just be ignored */ #define UNITY_OUTPUT_FLUSH() #endif #else /* If defined as something else, make sure we declare it here so it's ready for use */ #ifdef UNITY_OUTPUT_FLUSH_HEADER_DECLARATION extern void UNITY_OUTPUT_FLUSH_HEADER_DECLARATION; #endif #endif #ifndef UNITY_OUTPUT_FLUSH #define UNITY_FLUSH_CALL() #else #define UNITY_FLUSH_CALL() UNITY_OUTPUT_FLUSH() #endif #ifndef UNITY_PRINT_EOL #define UNITY_PRINT_EOL() UNITY_OUTPUT_CHAR('\n') #endif #ifndef UNITY_OUTPUT_START #define UNITY_OUTPUT_START() #endif #ifndef UNITY_OUTPUT_COMPLETE #define UNITY_OUTPUT_COMPLETE() #endif #ifdef UNITY_INCLUDE_EXEC_TIME #if !defined(UNITY_EXEC_TIME_START) && \ !defined(UNITY_EXEC_TIME_STOP) && \ !defined(UNITY_PRINT_EXEC_TIME) && \ !defined(UNITY_TIME_TYPE) /* If none any of these macros are defined then try to provide a default implementation */ #if defined(UNITY_CLOCK_MS) /* This is a simple way to get a default implementation on platforms that support getting a millisecond counter */ #define UNITY_TIME_TYPE UNITY_UINT #define UNITY_EXEC_TIME_START() Unity.CurrentTestStartTime = UNITY_CLOCK_MS() #define UNITY_EXEC_TIME_STOP() Unity.CurrentTestStopTime = UNITY_CLOCK_MS() #define UNITY_PRINT_EXEC_TIME() { \ UNITY_UINT execTimeMs = (Unity.CurrentTestStopTime - Unity.CurrentTestStartTime); \ UnityPrint(" ("); \ UnityPrintNumberUnsigned(execTimeMs); \ UnityPrint(" ms)"); \ } #elif defined(_WIN32) #include <time.h> #define UNITY_TIME_TYPE clock_t #define UNITY_GET_TIME(t) t = (clock_t)((clock() * 1000) / CLOCKS_PER_SEC) #define UNITY_EXEC_TIME_START() UNITY_GET_TIME(Unity.CurrentTestStartTime) #define UNITY_EXEC_TIME_STOP() UNITY_GET_TIME(Unity.CurrentTestStopTime) #define UNITY_PRINT_EXEC_TIME() { \ UNITY_UINT execTimeMs = (Unity.CurrentTestStopTime - Unity.CurrentTestStartTime); \ UnityPrint(" ("); \ UnityPrintNumberUnsigned(execTimeMs); \ UnityPrint(" ms)"); \ } #elif defined(__unix__) #include <time.h> #define UNITY_TIME_TYPE struct timespec #define UNITY_GET_TIME(t) clock_gettime(CLOCK_MONOTONIC, &t) #define UNITY_EXEC_TIME_START() UNITY_GET_TIME(Unity.CurrentTestStartTime) #define UNITY_EXEC_TIME_STOP() UNITY_GET_TIME(Unity.CurrentTestStopTime) #define UNITY_PRINT_EXEC_TIME() { \ UNITY_UINT execTimeMs = ((Unity.CurrentTestStopTime.tv_sec - Unity.CurrentTestStartTime.tv_sec) * 1000L); \ execTimeMs += ((Unity.CurrentTestStopTime.tv_nsec - Unity.CurrentTestStartTime.tv_nsec) / 1000000L); \ UnityPrint(" ("); \ UnityPrintNumberUnsigned(execTimeMs); \ UnityPrint(" ms)"); \ } #endif #endif #endif #ifndef UNITY_EXEC_TIME_START #define UNITY_EXEC_TIME_START() do{}while(0) #endif #ifndef UNITY_EXEC_TIME_STOP #define UNITY_EXEC_TIME_STOP() do{}while(0) #endif #ifndef UNITY_TIME_TYPE #define UNITY_TIME_TYPE UNITY_UINT #endif #ifndef UNITY_PRINT_EXEC_TIME #define UNITY_PRINT_EXEC_TIME() do{}while(0) #endif /*------------------------------------------------------- * Footprint *-------------------------------------------------------*/ #ifndef UNITY_LINE_TYPE #define UNITY_LINE_TYPE UNITY_UINT #endif #ifndef UNITY_COUNTER_TYPE #define UNITY_COUNTER_TYPE UNITY_UINT #endif /*------------------------------------------------------- * Internal Structs Needed *-------------------------------------------------------*/ typedef void (*UnityTestFunction)(void); #define UNITY_DISPLAY_RANGE_INT (0x10) #define UNITY_DISPLAY_RANGE_UINT (0x20) #define UNITY_DISPLAY_RANGE_HEX (0x40) #define UNITY_DISPLAY_RANGE_CHAR (0x80) typedef enum { UNITY_DISPLAY_STYLE_INT = (UNITY_INT_WIDTH / 8) + UNITY_DISPLAY_RANGE_INT, UNITY_DISPLAY_STYLE_INT8 = 1 + UNITY_DISPLAY_RANGE_INT, UNITY_DISPLAY_STYLE_INT16 = 2 + UNITY_DISPLAY_RANGE_INT, UNITY_DISPLAY_STYLE_INT32 = 4 + UNITY_DISPLAY_RANGE_INT, #ifdef UNITY_SUPPORT_64 UNITY_DISPLAY_STYLE_INT64 = 8 + UNITY_DISPLAY_RANGE_INT, #endif UNITY_DISPLAY_STYLE_UINT = (UNITY_INT_WIDTH / 8) + UNITY_DISPLAY_RANGE_UINT, UNITY_DISPLAY_STYLE_UINT8 = 1 + UNITY_DISPLAY_RANGE_UINT, UNITY_DISPLAY_STYLE_UINT16 = 2 + UNITY_DISPLAY_RANGE_UINT, UNITY_DISPLAY_STYLE_UINT32 = 4 + UNITY_DISPLAY_RANGE_UINT, #ifdef UNITY_SUPPORT_64 UNITY_DISPLAY_STYLE_UINT64 = 8 + UNITY_DISPLAY_RANGE_UINT, #endif UNITY_DISPLAY_STYLE_HEX8 = 1 + UNITY_DISPLAY_RANGE_HEX, UNITY_DISPLAY_STYLE_HEX16 = 2 + UNITY_DISPLAY_RANGE_HEX, UNITY_DISPLAY_STYLE_HEX32 = 4 + UNITY_DISPLAY_RANGE_HEX, #ifdef UNITY_SUPPORT_64 UNITY_DISPLAY_STYLE_HEX64 = 8 + UNITY_DISPLAY_RANGE_HEX, #endif UNITY_DISPLAY_STYLE_CHAR = 1 + UNITY_DISPLAY_RANGE_CHAR + UNITY_DISPLAY_RANGE_INT, UNITY_DISPLAY_STYLE_UNKNOWN } UNITY_DISPLAY_STYLE_T; typedef enum { UNITY_WITHIN = 0x0, UNITY_EQUAL_TO = 0x1, UNITY_GREATER_THAN = 0x2, UNITY_GREATER_OR_EQUAL = 0x2 + UNITY_EQUAL_TO, UNITY_SMALLER_THAN = 0x4, UNITY_SMALLER_OR_EQUAL = 0x4 + UNITY_EQUAL_TO, UNITY_UNKNOWN } UNITY_COMPARISON_T; #ifndef UNITY_EXCLUDE_FLOAT typedef enum UNITY_FLOAT_TRAIT { UNITY_FLOAT_IS_NOT_INF = 0, UNITY_FLOAT_IS_INF, UNITY_FLOAT_IS_NOT_NEG_INF, UNITY_FLOAT_IS_NEG_INF, UNITY_FLOAT_IS_NOT_NAN, UNITY_FLOAT_IS_NAN, UNITY_FLOAT_IS_NOT_DET, UNITY_FLOAT_IS_DET, UNITY_FLOAT_INVALID_TRAIT } UNITY_FLOAT_TRAIT_T; #endif typedef enum { UNITY_ARRAY_TO_VAL = 0, UNITY_ARRAY_TO_ARRAY, UNITY_ARRAY_UNKNOWN } UNITY_FLAGS_T; struct UNITY_STORAGE_T { const char* TestFile; const char* CurrentTestName; #ifndef UNITY_EXCLUDE_DETAILS const char* CurrentDetail1; const char* CurrentDetail2; #endif UNITY_LINE_TYPE CurrentTestLineNumber; UNITY_COUNTER_TYPE NumberOfTests; UNITY_COUNTER_TYPE TestFailures; UNITY_COUNTER_TYPE TestIgnores; UNITY_COUNTER_TYPE CurrentTestFailed; UNITY_COUNTER_TYPE CurrentTestIgnored; #ifdef UNITY_INCLUDE_EXEC_TIME UNITY_TIME_TYPE CurrentTestStartTime; UNITY_TIME_TYPE CurrentTestStopTime; #endif #ifndef UNITY_EXCLUDE_SETJMP_H jmp_buf AbortFrame; #endif }; extern struct UNITY_STORAGE_T Unity; /*------------------------------------------------------- * Test Suite Management *-------------------------------------------------------*/ void UnityBegin(const char* filename); int UnityEnd(void); void UnitySetTestFile(const char* filename); void UnityConcludeTest(void); void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int FuncLineNum); /*------------------------------------------------------- * Details Support *-------------------------------------------------------*/ #ifdef UNITY_EXCLUDE_DETAILS #define UNITY_CLR_DETAILS() #define UNITY_SET_DETAIL(d1) #define UNITY_SET_DETAILS(d1,d2) #else #define UNITY_CLR_DETAILS() { Unity.CurrentDetail1 = 0; Unity.CurrentDetail2 = 0; } #define UNITY_SET_DETAIL(d1) { Unity.CurrentDetail1 = (d1); Unity.CurrentDetail2 = 0; } #define UNITY_SET_DETAILS(d1,d2) { Unity.CurrentDetail1 = (d1); Unity.CurrentDetail2 = (d2); } #ifndef UNITY_DETAIL1_NAME #define UNITY_DETAIL1_NAME "Function" #endif #ifndef UNITY_DETAIL2_NAME #define UNITY_DETAIL2_NAME "Argument" #endif #endif /*------------------------------------------------------- * Test Output *-------------------------------------------------------*/ void UnityPrint(const char* string); #ifdef UNITY_INCLUDE_PRINT_FORMATTED void UnityPrintFormatted(const char* format, ...); #endif void UnityPrintLen(const char* string, const UNITY_UINT32 length); void UnityPrintMask(const UNITY_UINT mask, const UNITY_UINT number); void UnityPrintNumberByStyle(const UNITY_INT number, const UNITY_DISPLAY_STYLE_T style); void UnityPrintNumber(const UNITY_INT number_to_print); void UnityPrintNumberUnsigned(const UNITY_UINT number); void UnityPrintNumberHex(const UNITY_UINT number, const char nibbles_to_print); #ifndef UNITY_EXCLUDE_FLOAT_PRINT void UnityPrintFloat(const UNITY_DOUBLE input_number); #endif /*------------------------------------------------------- * Test Assertion Functions *------------------------------------------------------- * Use the macros below this section instead of calling * these directly. The macros have a consistent naming * convention and will pull in file and line information * for you. */ void UnityAssertEqualNumber(const UNITY_INT expected, const UNITY_INT actual, const char* msg, const UNITY_LINE_TYPE lineNumber, const UNITY_DISPLAY_STYLE_T style); void UnityAssertGreaterOrLessOrEqualNumber(const UNITY_INT threshold, const UNITY_INT actual, const UNITY_COMPARISON_T compare, const char *msg, const UNITY_LINE_TYPE lineNumber, const UNITY_DISPLAY_STYLE_T style); void UnityAssertEqualIntArray(UNITY_INTERNAL_PTR expected, UNITY_INTERNAL_PTR actual, const UNITY_UINT32 num_elements, const char* msg, const UNITY_LINE_TYPE lineNumber, const UNITY_DISPLAY_STYLE_T style, const UNITY_FLAGS_T flags); void UnityAssertBits(const UNITY_INT mask, const UNITY_INT expected, const UNITY_INT actual, const char* msg, const UNITY_LINE_TYPE lineNumber); void UnityAssertEqualString(const char* expected, const char* actual, const char* msg, const UNITY_LINE_TYPE lineNumber); void UnityAssertEqualStringLen(const char* expected, const char* actual, const UNITY_UINT32 length, const char* msg, const UNITY_LINE_TYPE lineNumber); void UnityAssertEqualStringArray( UNITY_INTERNAL_PTR expected, const char** actual, const UNITY_UINT32 num_elements, const char* msg, const UNITY_LINE_TYPE lineNumber, const UNITY_FLAGS_T flags); void UnityAssertEqualMemory( UNITY_INTERNAL_PTR expected, UNITY_INTERNAL_PTR actual, const UNITY_UINT32 length, const UNITY_UINT32 num_elements, const char* msg, const UNITY_LINE_TYPE lineNumber, const UNITY_FLAGS_T flags); void UnityAssertNumbersWithin(const UNITY_UINT delta, const UNITY_INT expected, const UNITY_INT actual, const char* msg, const UNITY_LINE_TYPE lineNumber, const UNITY_DISPLAY_STYLE_T style); void UnityAssertNumbersArrayWithin(const UNITY_UINT delta, UNITY_INTERNAL_PTR expected, UNITY_INTERNAL_PTR actual, const UNITY_UINT32 num_elements, const char* msg, const UNITY_LINE_TYPE lineNumber, const UNITY_DISPLAY_STYLE_T style, const UNITY_FLAGS_T flags); void UnityFail(const char* message, const UNITY_LINE_TYPE line); void UnityIgnore(const char* message, const UNITY_LINE_TYPE line); void UnityMessage(const char* message, const UNITY_LINE_TYPE line); #ifndef UNITY_EXCLUDE_FLOAT void UnityAssertFloatsWithin(const UNITY_FLOAT delta, const UNITY_FLOAT expected, const UNITY_FLOAT actual, const char* msg, const UNITY_LINE_TYPE lineNumber); void UnityAssertEqualFloatArray(UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* expected, UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* actual, const UNITY_UINT32 num_elements, const char* msg, const UNITY_LINE_TYPE lineNumber, const UNITY_FLAGS_T flags); void UnityAssertFloatSpecial(const UNITY_FLOAT actual, const char* msg, const UNITY_LINE_TYPE lineNumber, const UNITY_FLOAT_TRAIT_T style); #endif #ifndef UNITY_EXCLUDE_DOUBLE void UnityAssertDoublesWithin(const UNITY_DOUBLE delta, const UNITY_DOUBLE expected, const UNITY_DOUBLE actual, const char* msg, const UNITY_LINE_TYPE lineNumber); void UnityAssertEqualDoubleArray(UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* expected, UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* actual, const UNITY_UINT32 num_elements, const char* msg, const UNITY_LINE_TYPE lineNumber, const UNITY_FLAGS_T flags); void UnityAssertDoubleSpecial(const UNITY_DOUBLE actual, const char* msg, const UNITY_LINE_TYPE lineNumber, const UNITY_FLOAT_TRAIT_T style); #endif /*------------------------------------------------------- * Helpers *-------------------------------------------------------*/ UNITY_INTERNAL_PTR UnityNumToPtr(const UNITY_INT num, const UNITY_UINT8 size); #ifndef UNITY_EXCLUDE_FLOAT UNITY_INTERNAL_PTR UnityFloatToPtr(const float num); #endif #ifndef UNITY_EXCLUDE_DOUBLE UNITY_INTERNAL_PTR UnityDoubleToPtr(const double num); #endif /*------------------------------------------------------- * Error Strings We Might Need *-------------------------------------------------------*/ extern const char UnityStrOk[]; extern const char UnityStrPass[]; extern const char UnityStrFail[]; extern const char UnityStrIgnore[]; extern const char UnityStrErrFloat[]; extern const char UnityStrErrDouble[]; extern const char UnityStrErr64[]; extern const char UnityStrErrShorthand[]; /*------------------------------------------------------- * Test Running Macros *-------------------------------------------------------*/ #ifndef UNITY_EXCLUDE_SETJMP_H #define TEST_PROTECT() (setjmp(Unity.AbortFrame) == 0) #define TEST_ABORT() longjmp(Unity.AbortFrame, 1) #else #define TEST_PROTECT() 1 #define TEST_ABORT() return #endif /* This tricky series of macros gives us an optional line argument to treat it as RUN_TEST(func, num=__LINE__) */ #ifndef RUN_TEST #ifdef __STDC_VERSION__ #if __STDC_VERSION__ >= 199901L #define UNITY_SUPPORT_VARIADIC_MACROS #endif #endif #ifdef UNITY_SUPPORT_VARIADIC_MACROS #define RUN_TEST(...) UnityDefaultTestRun(RUN_TEST_FIRST(__VA_ARGS__), RUN_TEST_SECOND(__VA_ARGS__)) #define RUN_TEST_FIRST(...) RUN_TEST_FIRST_HELPER(__VA_ARGS__, throwaway) #define RUN_TEST_FIRST_HELPER(first, ...) (first), #first #define RUN_TEST_SECOND(...) RUN_TEST_SECOND_HELPER(__VA_ARGS__, __LINE__, throwaway) #define RUN_TEST_SECOND_HELPER(first, second, ...) (second) #endif #endif /* If we can't do the tricky version, we'll just have to require them to always include the line number */ #ifndef RUN_TEST #ifdef CMOCK #define RUN_TEST(func, num) UnityDefaultTestRun(func, #func, num) #else #define RUN_TEST(func) UnityDefaultTestRun(func, #func, __LINE__) #endif #endif #define TEST_LINE_NUM (Unity.CurrentTestLineNumber) #define TEST_IS_IGNORED (Unity.CurrentTestIgnored) #define UNITY_NEW_TEST(a) \ Unity.CurrentTestName = (a); \ Unity.CurrentTestLineNumber = (UNITY_LINE_TYPE)(__LINE__); \ Unity.NumberOfTests++; #ifndef UNITY_BEGIN #define UNITY_BEGIN() UnityBegin(__FILE__) #endif #ifndef UNITY_END #define UNITY_END() UnityEnd() #endif #ifndef UNITY_SHORTHAND_AS_INT #ifndef UNITY_SHORTHAND_AS_MEM #ifndef UNITY_SHORTHAND_AS_NONE #ifndef UNITY_SHORTHAND_AS_RAW #define UNITY_SHORTHAND_AS_OLD #endif #endif #endif #endif /*----------------------------------------------- * Command Line Argument Support *-----------------------------------------------*/ #ifdef UNITY_USE_COMMAND_LINE_ARGS int UnityParseOptions(int argc, char** argv); int UnityTestMatches(void); #endif /*------------------------------------------------------- * Basic Fail and Ignore *-------------------------------------------------------*/ #define UNITY_TEST_FAIL(line, message) UnityFail( (message), (UNITY_LINE_TYPE)(line)) #define UNITY_TEST_IGNORE(line, message) UnityIgnore( (message), (UNITY_LINE_TYPE)(line)) /*------------------------------------------------------- * Test Asserts *-------------------------------------------------------*/ #define UNITY_TEST_ASSERT(condition, line, message) if (condition) {} else {UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), (message));} #define UNITY_TEST_ASSERT_NULL(pointer, line, message) UNITY_TEST_ASSERT(((pointer) == NULL), (UNITY_LINE_TYPE)(line), (message)) #define UNITY_TEST_ASSERT_NOT_NULL(pointer, line, message) UNITY_TEST_ASSERT(((pointer) != NULL), (UNITY_LINE_TYPE)(line), (message)) #define UNITY_TEST_ASSERT_EQUAL_INT(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) #define UNITY_TEST_ASSERT_EQUAL_INT8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) #define UNITY_TEST_ASSERT_EQUAL_INT16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) #define UNITY_TEST_ASSERT_EQUAL_INT32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) #define UNITY_TEST_ASSERT_EQUAL_UINT(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) #define UNITY_TEST_ASSERT_EQUAL_UINT8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) #define UNITY_TEST_ASSERT_EQUAL_UINT16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) #define UNITY_TEST_ASSERT_EQUAL_UINT32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) #define UNITY_TEST_ASSERT_EQUAL_HEX8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) #define UNITY_TEST_ASSERT_EQUAL_HEX16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) #define UNITY_TEST_ASSERT_EQUAL_HEX32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) #define UNITY_TEST_ASSERT_EQUAL_CHAR(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) #define UNITY_TEST_ASSERT_BITS(mask, expected, actual, line, message) UnityAssertBits((UNITY_INT)(mask), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line)) #define UNITY_TEST_ASSERT_GREATER_THAN_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) #define UNITY_TEST_ASSERT_GREATER_THAN_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) #define UNITY_TEST_ASSERT_GREATER_THAN_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) #define UNITY_TEST_ASSERT_GREATER_THAN_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) #define UNITY_TEST_ASSERT_GREATER_THAN_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) #define UNITY_TEST_ASSERT_GREATER_THAN_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) #define UNITY_TEST_ASSERT_GREATER_THAN_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) #define UNITY_TEST_ASSERT_GREATER_THAN_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) #define UNITY_TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) #define UNITY_TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) #define UNITY_TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) #define UNITY_TEST_ASSERT_GREATER_THAN_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) #define UNITY_TEST_ASSERT_SMALLER_THAN_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) #define UNITY_TEST_ASSERT_SMALLER_THAN_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) #define UNITY_TEST_ASSERT_SMALLER_THAN_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) #define UNITY_TEST_ASSERT_SMALLER_THAN_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) #define UNITY_TEST_ASSERT_SMALLER_THAN_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) #define UNITY_TEST_ASSERT_SMALLER_THAN_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) #define UNITY_TEST_ASSERT_SMALLER_THAN_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) #define UNITY_TEST_ASSERT_SMALLER_THAN_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) #define UNITY_TEST_ASSERT_SMALLER_THAN_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) #define UNITY_TEST_ASSERT_SMALLER_THAN_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) #define UNITY_TEST_ASSERT_SMALLER_THAN_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) #define UNITY_TEST_ASSERT_SMALLER_THAN_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 ) (threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16) (threshold), (UNITY_INT)(UNITY_INT16) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32) (threshold), (UNITY_INT)(UNITY_INT32) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 ) (threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) #define UNITY_TEST_ASSERT_INT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin( (delta), (UNITY_INT) (expected), (UNITY_INT) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) #define UNITY_TEST_ASSERT_INT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_INT8 ) (expected), (UNITY_INT)(UNITY_INT8 ) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) #define UNITY_TEST_ASSERT_INT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_INT16) (expected), (UNITY_INT)(UNITY_INT16) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) #define UNITY_TEST_ASSERT_INT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_INT32) (expected), (UNITY_INT)(UNITY_INT32) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) #define UNITY_TEST_ASSERT_UINT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin( (delta), (UNITY_INT) (expected), (UNITY_INT) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) #define UNITY_TEST_ASSERT_UINT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) #define UNITY_TEST_ASSERT_UINT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) #define UNITY_TEST_ASSERT_UINT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) #define UNITY_TEST_ASSERT_HEX8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) #define UNITY_TEST_ASSERT_HEX16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) #define UNITY_TEST_ASSERT_HEX32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) #define UNITY_TEST_ASSERT_CHAR_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_INT8 ) (expected), (UNITY_INT)(UNITY_INT8 ) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) #define UNITY_TEST_ASSERT_INT_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin( (delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT8 )(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin( (delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin( (UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT8 )(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT8 )(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_PTR(expected, actual, line, message) UnityAssertEqualNumber((UNITY_PTR_TO_INT)(expected), (UNITY_PTR_TO_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER) #define UNITY_TEST_ASSERT_EQUAL_STRING(expected, actual, line, message) UnityAssertEqualString((const char*)(expected), (const char*)(actual), (message), (UNITY_LINE_TYPE)(line)) #define UNITY_TEST_ASSERT_EQUAL_STRING_LEN(expected, actual, len, line, message) UnityAssertEqualStringLen((const char*)(expected), (const char*)(actual), (UNITY_UINT32)(len), (message), (UNITY_LINE_TYPE)(line)) #define UNITY_TEST_ASSERT_EQUAL_MEMORY(expected, actual, len, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), 1, (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualStringArray((UNITY_INTERNAL_PTR)(expected), (const char**)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, num_elements, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) (expected), (UNITY_INT_WIDTH / 8)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) (expected), (UNITY_INT_WIDTH / 8)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT16)(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT32)(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_PTR_TO_INT) (expected), (UNITY_POINTER_WIDTH / 8)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements, line, message) UnityAssertEqualStringArray((UNITY_INTERNAL_PTR)(expected), (const char**)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, num_elements, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_EACH_EQUAL_CHAR(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_VAL) #ifdef UNITY_SUPPORT_64 #define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) #define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) #define UNITY_TEST_ASSERT_EQUAL_HEX64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) #define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)(expected), 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT64)(expected), 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)(expected), 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) #define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) #define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) #define UNITY_TEST_ASSERT_GREATER_THAN_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) #define UNITY_TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) #define UNITY_TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) #define UNITY_TEST_ASSERT_SMALLER_THAN_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) #define UNITY_TEST_ASSERT_SMALLER_THAN_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) #define UNITY_TEST_ASSERT_SMALLER_THAN_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) #define UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_ARRAY) #else #define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_EQUAL_HEX64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_GREATER_THAN_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_SMALLER_THAN_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_SMALLER_THAN_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_SMALLER_THAN_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #endif #ifdef UNITY_EXCLUDE_FLOAT #define UNITY_TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) #define UNITY_TEST_ASSERT_EQUAL_FLOAT(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) #define UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) #define UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) #define UNITY_TEST_ASSERT_FLOAT_IS_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) #define UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) #define UNITY_TEST_ASSERT_FLOAT_IS_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) #define UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) #define UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) #define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) #define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) #define UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) #else #define UNITY_TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual, line, message) UnityAssertFloatsWithin((UNITY_FLOAT)(delta), (UNITY_FLOAT)(expected), (UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line)) #define UNITY_TEST_ASSERT_EQUAL_FLOAT(expected, actual, line, message) UNITY_TEST_ASSERT_FLOAT_WITHIN((UNITY_FLOAT)(expected) * (UNITY_FLOAT)UNITY_FLOAT_PRECISION, (UNITY_FLOAT)(expected), (UNITY_FLOAT)(actual), (UNITY_LINE_TYPE)(line), (message)) #define UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualFloatArray((UNITY_FLOAT*)(expected), (UNITY_FLOAT*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements, line, message) UnityAssertEqualFloatArray(UnityFloatToPtr(expected), (UNITY_FLOAT*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_FLOAT_IS_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF) #define UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NEG_INF) #define UNITY_TEST_ASSERT_FLOAT_IS_NAN(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN) #define UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_DET) #define UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_INF) #define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NEG_INF) #define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NAN) #define UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_DET) #endif #ifdef UNITY_EXCLUDE_DOUBLE #define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) #define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) #define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) #define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) #define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) #define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) #define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) #define UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) #define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) #define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) #define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) #define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) #else #define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, message) UnityAssertDoublesWithin((UNITY_DOUBLE)(delta), (UNITY_DOUBLE)(expected), (UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line)) #define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) UNITY_TEST_ASSERT_DOUBLE_WITHIN((UNITY_DOUBLE)(expected) * (UNITY_DOUBLE)UNITY_DOUBLE_PRECISION, (UNITY_DOUBLE)(expected), (UNITY_DOUBLE)(actual), (UNITY_LINE_TYPE)(line), (message)) #define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray((UNITY_DOUBLE*)(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray(UnityDoubleToPtr(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF) #define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NEG_INF) #define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN) #define UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_DET) #define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_INF) #define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NEG_INF) #define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NAN) #define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_DET) #endif /* End of UNITY_INTERNALS_H */ #endif
{ "pile_set_name": "Github" }
// Load modules var Url = require('url'); var Lab = require('lab'); var Hoek = require('hoek'); var Hawk = require('../lib'); // Declare internals var internals = {}; // Test shortcuts var expect = Lab.expect; var before = Lab.before; var after = Lab.after; var describe = Lab.experiment; var it = Lab.test; describe('Hawk', function () { var credentialsFunc = function (id, callback) { var credentials = { id: id, key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', algorithm: (id === '1' ? 'sha1' : 'sha256'), user: 'steve' }; return callback(null, credentials); }; it('should generate an authorization then successfully parse it', function (done) { credentialsFunc('123456', function (err, credentials) { var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); expect(auth).to.exist; Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials) { expect(err).to.not.exist; expect(credentials.user).to.equal('steve'); done(); }); }); }); it('should fail authorization on mismatching host', function (done) { credentialsFunc('123456', function (err, credentials) { var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); expect(auth).to.exist; Hawk.server.authenticateMessage('example1.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials) { expect(err).to.exist; expect(err.message).to.equal('Bad mac'); done(); }); }); }); it('should fail authorization on stale timestamp', function (done) { credentialsFunc('123456', function (err, credentials) { var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); expect(auth).to.exist; Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, { localtimeOffsetMsec: 100000 }, function (err, credentials) { expect(err).to.exist; expect(err.message).to.equal('Stale timestamp'); done(); }); }); }); it('should fail authorization on invalid authorization', function (done) { credentialsFunc('123456', function (err, credentials) { var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); expect(auth).to.exist; delete auth.id; Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials) { expect(err).to.exist; expect(err.message).to.equal('Invalid authorization'); done(); }); }); }); it('should fail authorization on bad hash', function (done) { credentialsFunc('123456', function (err, credentials) { var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); expect(auth).to.exist; Hawk.server.authenticateMessage('example.com', 8080, 'some message1', auth, credentialsFunc, {}, function (err, credentials) { expect(err).to.exist; expect(err.message).to.equal('Bad message hash'); done(); }); }); }); it('should fail authorization on nonce error', function (done) { credentialsFunc('123456', function (err, credentials) { var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); expect(auth).to.exist; Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, { nonceFunc: function (nonce, ts, callback) { callback (new Error('kaboom')); } }, function (err, credentials) { expect(err).to.exist; expect(err.message).to.equal('Invalid nonce'); done(); }); }); }); it('should fail authorization on credentials error', function (done) { credentialsFunc('123456', function (err, credentials) { var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); expect(auth).to.exist; var errFunc = function (id, callback) { callback(new Error('kablooey')); }; Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials) { expect(err).to.exist; expect(err.message).to.equal('kablooey'); done(); }); }); }); it('should fail authorization on missing credentials', function (done) { credentialsFunc('123456', function (err, credentials) { var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); expect(auth).to.exist; var errFunc = function (id, callback) { callback(); }; Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials) { expect(err).to.exist; expect(err.message).to.equal('Unknown credentials'); done(); }); }); }); it('should fail authorization on invalid credentials', function (done) { credentialsFunc('123456', function (err, credentials) { var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); expect(auth).to.exist; var errFunc = function (id, callback) { callback(null, {}); }; Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials) { expect(err).to.exist; expect(err.message).to.equal('Invalid credentials'); done(); }); }); }); it('should fail authorization on invalid credentials algorithm', function (done) { credentialsFunc('123456', function (err, credentials) { var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); expect(auth).to.exist; var errFunc = function (id, callback) { callback(null, { key: '123', algorithm: '456' }); }; Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials) { expect(err).to.exist; expect(err.message).to.equal('Unknown algorithm'); done(); }); }); }); it('should fail on missing host', function (done) { credentialsFunc('123456', function (err, credentials) { var auth = Hawk.client.message(null, 8080, 'some message', { credentials: credentials }); expect(auth).to.not.exist; done(); }); }); it('should fail on missing credentials', function (done) { var auth = Hawk.client.message('example.com', 8080, 'some message', {}); expect(auth).to.not.exist; done(); }); it('should fail on invalid algorithm', function (done) { credentialsFunc('123456', function (err, credentials) { var creds = Hoek.clone(credentials); creds.algorithm = 'blah'; var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: creds }); expect(auth).to.not.exist; done(); }); }); });
{ "pile_set_name": "Github" }
{ "forge_marker": 1, "defaults": { "model": "cube", "textures": { "particle": "ancientwarfare:blocks/structure/orc_totem_front_2", "down": "ancientwarfare:blocks/structure/totem_bottom", "up": "ancientwarfare:blocks/structure/totem_top_2", "north": "ancientwarfare:blocks/structure/orc_totem_front_2", "west": "ancientwarfare:blocks/structure/totem_side_2", "south": "ancientwarfare:blocks/structure/orc_totem_front_2", "east": "ancientwarfare:blocks/structure/totem_side_2" }, "transform": "forge:default-block" }, "variants": { "normal": [{}], "facing": { "north": {}, "south": { "y": 180 }, "west": { "y": 270 }, "east": { "y": 90 } } } }
{ "pile_set_name": "Github" }
var isObject = require('./isObject'); /** `Object#toString` result references. */ var funcTag = '[object Function]', genTag = '[object GeneratorFunction]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8 which returns 'object' for typed array and weak map constructors, // and PhantomJS 1.9 which returns 'function' for `NodeList` instances. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } module.exports = isFunction;
{ "pile_set_name": "Github" }
package com.platform.website.transformer.mr.pv; import com.platform.website.common.KpiType; import com.platform.website.transformer.model.dim.StatsUserDimension; import com.platform.website.transformer.model.value.map.TimeOutputValue; import com.platform.website.transformer.model.value.reduce.MapWritableValue; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.MapWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; /** * 计算website的page view的reduce类 */ public class PageViewReducer extends Reducer<StatsUserDimension, NullWritable, StatsUserDimension, MapWritableValue> { private MapWritableValue mapWritableValue = new MapWritableValue(); private MapWritable map = new MapWritable(); @SuppressWarnings("unused") @Override protected void reduce(StatsUserDimension key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException { int pvCount = 0; for (NullWritable value : values) { // pv++,每一条数据算一个pv,不涉及到去重 pvCount++; } // 填充value this.map.put(new IntWritable(-1), new IntWritable(pvCount)); this.mapWritableValue.setValue(this.map); // 填充kpi this.mapWritableValue.setKpi(KpiType.valueOfName(key.getStatsCommon().getKpi().getKpiName())); // 输出 context.write(key, this.mapWritableValue); } }
{ "pile_set_name": "Github" }
/** * bootstrap.js v3.0.0 by @fat and @mdo * Copyright 2013 Twitter Inc. * http://www.apache.org/licenses/LICENSE-2.0 */ if (!jQuery) { throw new Error("Bootstrap requires jQuery") } /* ======================================================================== * Bootstrap: transition.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#transitions * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd' , 'MozTransition' : 'transitionend' , 'OTransition' : 'oTransitionEnd otransitionend' , 'transition' : 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false, $el = this $(this).one($.support.transition.end, function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() }) }(window.jQuery); /* ======================================================================== * Bootstrap: alert.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#alerts * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.hasClass('alert') ? $this : $this.parent() } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { $parent.trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one($.support.transition.end, removeElement) .emulateTransitionEnd(150) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= var old = $.fn.alert $.fn.alert = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(window.jQuery); /* ======================================================================== * Bootstrap: button.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#buttons * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) } Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state = state + 'Text' if (!data.resetText) $el.data('resetText', $el[val]()) $el[val](data[state] || this.options[state]) // push to event loop to allow forms to submit setTimeout(function () { state == 'loadingText' ? $el.addClass(d).attr(d, d) : $el.removeClass(d).removeAttr(d); }, 0) } Button.prototype.toggle = function () { var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') .prop('checked', !this.$element.hasClass('active')) .trigger('change') if ($input.prop('type') === 'radio') $parent.find('.active').removeClass('active') } this.$element.toggleClass('active') } // BUTTON PLUGIN DEFINITION // ======================== var old = $.fn.button $.fn.button = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document).on('click.bs.button.data-api', '[data-toggle^=button]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') $btn.button('toggle') e.preventDefault() }) }(window.jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#carousel * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = this.sliding = this.interval = this.$active = this.$items = null this.options.pause == 'hover' && this.$element .on('mouseenter', $.proxy(this.pause, this)) .on('mouseleave', $.proxy(this.cycle, this)) } Carousel.DEFAULTS = { interval: 5000 , pause: 'hover' , wrap: true } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getActiveIndex = function () { this.$active = this.$element.find('.item.active') this.$items = this.$active.parent().children() return this.$items.index(this.$active) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getActiveIndex() if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid', function () { that.to(pos) }) if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition.end) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || $active[type]() var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var fallback = type == 'next' ? 'first' : 'last' var that = this if (!$next.length) { if (!this.options.wrap) return $next = this.$element.find('.item')[fallback]() } this.sliding = true isCycling && this.pause() var e = $.Event('slide.bs.carousel', { relatedTarget: $next[0], direction: direction }) if ($next.hasClass('active')) return if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') this.$element.one('slid', function () { var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()]) $nextIndicator && $nextIndicator.addClass('active') }) } if ($.support.transition && this.$element.hasClass('slide')) { this.$element.trigger(e) if (e.isDefaultPrevented()) return $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one($.support.transition.end, function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger('slid') }, 0) }) .emulateTransitionEnd(600) } else { this.$element.trigger(e) if (e.isDefaultPrevented()) return $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger('slid') } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== var old = $.fn.carousel $.fn.carousel = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= $(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { var $this = $(this), href var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false $target.carousel(options) if (slideIndex = $this.attr('data-slide-to')) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() }) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) $carousel.carousel($carousel.data()) }) }) }(window.jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#collapse * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.transitioning = null if (this.options.parent) this.$parent = $(this.options.parent) if (this.options.toggle) this.toggle() } Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var actives = this.$parent && this.$parent.find('> .panel > .in') if (actives && actives.length) { var hasData = actives.data('bs.collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing') [dimension](0) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('in') [dimension]('auto') this.transitioning = 0 this.$element.trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) [dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element [dimension](this.$element[dimension]()) [0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse') .removeClass('in') this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .trigger('hidden.bs.collapse') .removeClass('collapsing') .addClass('collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } // COLLAPSE PLUGIN DEFINITION // ========================== var old = $.fn.collapse $.fn.collapse = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function (e) { var $this = $(this), href var target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 var $target = $(target) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() var parent = $this.attr('data-parent') var $parent = parent && $(parent) if (!data || !data.transitioning) { if ($parent) $parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed') $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed') } $target.collapse(option) }) }(window.jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#dropdowns * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle=dropdown]' var Dropdown = function (element) { var $el = $(element).on('click.bs.dropdown', this.toggle) } Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we we use a backdrop because click events don't delegate $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus) } $parent.trigger(e = $.Event('show.bs.dropdown')) if (e.isDefaultPrevented()) return $parent .toggleClass('open') .trigger('shown.bs.dropdown') $this.focus() } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27)/.test(e.keyCode)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if (!isActive || (isActive && e.keyCode == 27)) { if (e.which == 27) $parent.find(toggle).focus() return $this.click() } var $items = $('[role=menu] li:not(.divider):visible a', $parent) if (!$items.length) return var index = $items.index($items.filter(':focus')) if (e.keyCode == 38 && index > 0) index-- // up if (e.keyCode == 40 && index < $items.length - 1) index++ // down if (!~index) index=0 $items.eq(index).focus() } function clearMenus() { $(backdrop).remove() $(toggle).each(function (e) { var $parent = getParent($(this)) if (!$parent.hasClass('open')) return $parent.trigger(e = $.Event('hide.bs.dropdown')) if (e.isDefaultPrevented()) return $parent.removeClass('open').trigger('hidden.bs.dropdown') }) } function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } // DROPDOWN PLUGIN DEFINITION // ========================== var old = $.fn.dropdown $.fn.dropdown = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('dropdown') if (!data) $this.data('dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api' , toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown) }(window.jQuery); /* ======================================================================== * Bootstrap: modal.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#modals * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$element = $(element) this.$backdrop = this.isShown = null if (this.options.remote) this.$element.load(this.options.remote) } Modal.DEFAULTS = { backdrop: true , keyboard: true , show: true } Modal.prototype.toggle = function (_relatedTarget) { return this[!this.isShown ? 'show' : 'hide'](_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.$element.on('click.dismiss.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) // don't move modals dom position } that.$element.show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$element.find('.modal-dialog') // wait for modal to slide in .one($.support.transition.end, function () { that.$element.focus().trigger(e) }) .emulateTransitionEnd(300) : that.$element.focus().trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .attr('aria-hidden', true) .off('click.dismiss.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one($.support.transition.end, $.proxy(this.hideModal, this)) .emulateTransitionEnd(300) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.focus() } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keyup.dismiss.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.removeBackdrop() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$element.on('click.dismiss.modal', $.proxy(function (e) { if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this) }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (callback) { callback() } } // MODAL PLUGIN DEFINITION // ======================= var old = $.fn.modal $.fn.modal = function (option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 var option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) e.preventDefault() $target .modal(option, this) .one('hide', function () { $this.is(':visible') && $this.focus() }) }) $(document) .on('show.bs.modal', '.modal', function () { $(document.body).addClass('modal-open') }) .on('hidden.bs.modal', '.modal', function () { $(document.body).removeClass('modal-open') }) }(window.jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null this.init('tooltip', element, options) } Tooltip.DEFAULTS = { animation: true , placement: 'top' , selector: false , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>' , trigger: 'hover focus' , title: '' , delay: 0 , html: false , container: false } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focus' var eventOut = trigger == 'hover' ? 'mouseleave' : 'blur' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay , hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.'+ this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) if (e.isDefaultPrevented()) return var $tip = this.tip() this.setContent() if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var $parent = this.$element.parent() var orgPlacement = placement var docScroll = document.documentElement.scrollTop || document.body.scrollTop var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth() var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight() var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' : placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' : placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' : placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) this.$element.trigger('shown.bs.' + this.type) } } Tooltip.prototype.applyPlacement = function(offset, placement) { var replace var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top = offset.top + marginTop offset.left = offset.left + marginLeft $tip .offset(offset) .addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { replace = true offset.top = offset.top + height - actualHeight } if (/bottom|top/.test(placement)) { var delta = 0 if (offset.left < 0) { delta = offset.left * -2 offset.left = 0 $tip.offset(offset) actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight } this.replaceArrow(delta - width + actualWidth, actualWidth, 'left') } else { this.replaceArrow(actualHeight - height, actualHeight, 'top') } if (replace) $tip.offset(offset) } Tooltip.prototype.replaceArrow = function(delta, dimension, position) { this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + "%") : '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function () { var that = this var $tip = this.tip() var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && this.$tip.hasClass('fade') ? $tip .one($.support.transition.end, complete) .emulateTransitionEnd(150) : complete() this.$element.trigger('hidden.bs.' + this.type) return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function () { var el = this.$element[0] return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : { width: el.offsetWidth , height: el.offsetHeight }, this.$element.offset()) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.tip = function () { return this.$tip = this.$tip || $(this.options.template) } Tooltip.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow') } Tooltip.prototype.validate = function () { if (!this.$element[0].parentNode) { this.hide() this.$element = null this.options = null } } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = e ? $(e.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) : this self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } Tooltip.prototype.destroy = function () { this.hide().$element.off('.' + this.type).removeData('bs.' + this.type) } // TOOLTIP PLUGIN DEFINITION // ========================= var old = $.fn.tooltip $.fn.tooltip = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(window.jQuery); /* ======================================================================== * Bootstrap: popover.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#popovers * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function (element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.DEFAULTS = $.extend({} , $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right' , trigger: 'click' , content: '' , template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function () { return Popover.DEFAULTS } Popover.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() } Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function () { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find('.arrow') } Popover.prototype.tip = function () { if (!this.$tip) this.$tip = $(this.options.template) return this.$tip } // POPOVER PLUGIN DEFINITION // ========================= var old = $.fn.popover $.fn.popover = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(window.jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#scrollspy * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { var href var process = $.proxy(this.process, this) this.$element = $(element).is('body') ? $(window) : $(element) this.$body = $('body') this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 || '') + ' .nav li > a' this.offsets = $([]) this.targets = $([]) this.activeTarget = null this.refresh() this.process() } ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.refresh = function () { var offsetMethod = this.$element[0] == window ? 'offset' : 'position' this.offsets = $([]) this.targets = $([]) var self = this var $targets = this.$body .find(this.selector) .map(function () { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#\w/.test(href) && $(href) return ($href && $href.length && [[ $href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight var maxScroll = scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (scrollTop >= maxScroll) { return activeTarget != (i = targets.last()[0]) && this.activate(i) } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate( targets[i] ) } } ScrollSpy.prototype.activate = function (target) { this.activeTarget = target $(this.selector) .parents('.active') .removeClass('active') var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate') } // SCROLLSPY PLUGIN DEFINITION // =========================== var old = $.fn.scrollspy $.fn.scrollspy = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) $spy.scrollspy($spy.data()) }) }) }(window.jQuery); /* ======================================================================== * Bootstrap: tab.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#tabs * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // TAB CLASS DEFINITION // ==================== var Tab = function (element) { this.element = $(element) } Tab.prototype.show = function () { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } if ($this.parent('li').hasClass('active')) return var previous = $ul.find('.active:last a')[0] var e = $.Event('show.bs.tab', { relatedTarget: previous }) $this.trigger(e) if (e.isDefaultPrevented()) return var $target = $(selector) this.activate($this.parent('li'), $ul) this.activate($target, $target.parent(), function () { $this.trigger({ type: 'shown.bs.tab' , relatedTarget: previous }) }) } Tab.prototype.activate = function (element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && $active.hasClass('fade') function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') element.addClass('active') if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu')) { element.closest('li.dropdown').addClass('active') } callback && callback() } transition ? $active .one($.support.transition.end, next) .emulateTransitionEnd(150) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== var old = $.fn.tab $.fn.tab = function ( option ) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function () { $.fn.tab = old return this } // TAB DATA-API // ============ $(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.preventDefault() $(this).tab('show') }) }(window.jQuery); /* ======================================================================== * Bootstrap: affix.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#affix * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // AFFIX CLASS DEFINITION // ====================== var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$window = $(window) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = this.unpin = null this.checkPosition() } Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0 } Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var scrollHeight = $(document).height() var scrollTop = this.$window.scrollTop() var position = this.$element.offset() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top() if (typeof offsetBottom == 'function') offsetBottom = offset.bottom() var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false if (this.affixed === affix) return if (this.unpin) this.$element.css('top', '') this.affixed = affix this.unpin = affix == 'bottom' ? position.top - scrollTop : null this.$element.removeClass(Affix.RESET).addClass('affix' + (affix ? '-' + affix : '')) if (affix == 'bottom') { this.$element.offset({ top: document.body.offsetHeight - offsetBottom - this.$element.height() }) } } // AFFIX PLUGIN DEFINITION // ======================= var old = $.fn.affix $.fn.affix = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function () { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom) data.offset.bottom = data.offsetBottom if (data.offsetTop) data.offset.top = data.offsetTop $spy.affix(data) }) }) }(window.jQuery);
{ "pile_set_name": "Github" }
/* Copyright (C) 2000-2009, 2011 Free Software Foundation, Inc. This file is part of the GNU LIBICONV Library. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "common.h" #include "vim.h" int clip_mch_own_selection(VimClipboard *cbd) { return FALSE; } void clip_mch_lose_selection(VimClipboard *cbd) { } void clip_mch_set_selection(VimClipboard *cbd) { vimtouch_set_clipboard(cbd); } void clip_mch_request_selection(VimClipboard *cbd) { vimtouch_get_clipboard(cbd); }
{ "pile_set_name": "Github" }
define(['d3', 'grouped-bar', 'groupedBarChartDataBuilder'], function(d3, chart, dataBuilder) { 'use strict'; const aTestDataSet = () => new dataBuilder.GroupedBarChartDataBuilder(); const buildDataSet = (dataSetName) => { return aTestDataSet() [dataSetName]() .build(); }; const differentDatesReducer = (acc, d) => { if (acc.indexOf(d.date) === -1) { acc.push(d.date); } return acc; }; describe('Grouped Bar Chart', () => { let groupedBarChart, dataset, containerFixture, f; beforeEach(() => { dataset = buildDataSet('with3Sources'); groupedBarChart = chart() .groupLabel('stack') .nameLabel('date') .valueLabel('views') .grid('full'); // DOM Fixture Setup f = jasmine.getFixtures(); f.fixturesPath = 'base/test/fixtures/'; f.load('testContainer.html'); containerFixture = d3.select('.test-container'); containerFixture.datum(dataset.data).call(groupedBarChart); }); afterEach(() => { containerFixture.remove(); f = jasmine.getFixtures(); f.cleanUp(); f.clearCache(); }); describe('Render', () => { it('should render a chart with minimal requirements', () => { const expected = 1; const actual = containerFixture.select('.grouped-bar').size(); expect(actual).toEqual(expected); }); describe('groups', () => { it('should create a container-group', () => { const expected = 1; const actual = containerFixture.select('g.container-group').size(); expect(actual).toEqual(expected); }); it('should create a chart-group', () => { const expected = 1; const actual = containerFixture.select('g.chart-group').size(); expect(actual).toEqual(expected); }); it('should create a x-axis-group', () => { const expected = 1; const actual = containerFixture.select('g.x-axis-group').size(); expect(actual).toEqual(expected); }); it('should create a y-axis-group', () => { const expected = 1; const actual = containerFixture.select('g.y-axis-group').size(); expect(actual).toEqual(expected); }); it('should create a grid-lines-group', () => { const expected = 1; const actual = containerFixture.select('g.grid-lines-group').size(); expect(actual).toEqual(expected); }); it('should create a metadata-group', () => { const expected = 1; const actual = containerFixture.select('g.metadata-group').size(); expect(actual).toEqual(expected); }); }); describe('grid lines', () => { it('should draw horizontal grid line', () => { const expected = 1; const actual = containerFixture.select('.horizontal-grid-line').size(); expect(actual).toEqual(expected); }); it('should draw vertical grid line', () => { const expected = 1; const actual = containerFixture.select('.vertical-grid-line').size(); expect(actual).toEqual(expected); }); }); describe('axis', () => { it('should draw an X axis', () => { const expected = 1; const actual = containerFixture.select('.x-axis-group .axis.x').size(); expect(actual).toEqual(expected); }); it('should draw an Y axis', () => { const expected = 1; const actual = containerFixture.select('.y-axis-group.axis').size(); expect(actual).toEqual(expected); }); }); it('should render a layer for each data entry group', () => { const actual = containerFixture.selectAll('.layer').size(); const expected = dataset.data.reduce(differentDatesReducer, []).length; expect(actual).toEqual(expected); }); it('should render a bar for each data entry', () => { const actual = containerFixture.selectAll('.bar').size(); const expected = dataset.data.length; expect(actual).toEqual(expected); }); describe('when reloading with a two sources dataset', () => { it('should render in the same svg', () => { const expected = 1; const newDataset = buildDataSet('with2Sources'); let actual; containerFixture.datum(newDataset.data).call(groupedBarChart); actual = containerFixture.selectAll('.grouped-bar').size(); expect(actual).toEqual(expected); }); it('should render four layers', () => { const expected = 4; const newDataset = buildDataSet('with2Sources'); let actual; containerFixture.datum(newDataset.data).call(groupedBarChart); actual = containerFixture.selectAll('.grouped-bar .layer').size(); expect(actual).toEqual(expected); }); it('should render eight bars total', () => { const expected = 8; const newDataset = buildDataSet('with2Sources'); let actual; containerFixture.datum(newDataset.data).call(groupedBarChart); actual = containerFixture.selectAll('.grouped-bar .bar').size(); expect(actual).toEqual(expected); }); }); describe('when grouped bar is animated', () => { it('it renders correct number of layers and bars', () => { const expectedNLayers = 4; const nBarsPerLayer = 3; groupedBarChart.isAnimated(true); containerFixture.datum(dataset.data).call(groupedBarChart); const actualNLayers = containerFixture.selectAll('.chart-group .layer').size(); const actualNBars = containerFixture.selectAll('.chart-group .bar').size(); expect(actualNLayers).toEqual(expectedNLayers); expect(actualNBars).toEqual(expectedNLayers * nBarsPerLayer); }); }); }); describe('API', () => { it('should provide an aspect ratio getter and setter', () => { let previous = groupedBarChart.aspectRatio(), expected = 600, actual; groupedBarChart.aspectRatio(expected); actual = groupedBarChart.aspectRatio(); expect(previous).not.toBe(expected); expect(actual).toBe(expected); }); it('should provide a colorSchema getter and setter', () => { let previous = groupedBarChart.colorSchema(), expected = ['#ffffff', '#fafefc', '#000000'], actual; groupedBarChart.colorSchema(expected); actual = groupedBarChart.colorSchema(); expect(previous).not.toBe(expected); expect(actual).toBe(expected); }); it('should have exportChart defined', () => { expect(groupedBarChart.exportChart).toBeDefined(); }); it('should provide groupLabel getter and setter', () => { let previous = groupedBarChart.groupLabel(), expected = 'testLabel', actual; groupedBarChart.groupLabel(expected); actual = groupedBarChart.groupLabel(); expect(previous).not.toBe(actual); expect(actual).toBe(expected); }); it('should provide grid mode getter and setter', () => { let previous = groupedBarChart.grid(), expected = 'vertical', actual; groupedBarChart.grid(expected); actual = groupedBarChart.grid(); expect(previous).not.toBe(expected); expect(actual).toBe(expected); }); it('should provide height getter and setter', () => { let previous = groupedBarChart.height(), expected = {top: 4, right: 4, bottom: 4, left: 4}, actual; groupedBarChart.height(expected); actual = groupedBarChart.height(); expect(previous).not.toBe(actual); expect(actual).toBe(expected); }); it('should provide horizontal direction getter and setter', () => { let previous = groupedBarChart.isHorizontal(), expected = true, actual; groupedBarChart.isHorizontal(expected); actual = groupedBarChart.isHorizontal(); expect(previous).not.toBe(actual); expect(actual).toBe(expected); }); it('should provide isAnimated getter and setter', () => { let previous = groupedBarChart.isAnimated(), expected = true, actual; groupedBarChart.isAnimated(expected); actual = groupedBarChart.isAnimated(); expect(previous).not.toBe(expected); expect(actual).toBe(expected); }); it('should provide locale getter and setter', () => { let defaultLocale = false, testLocale = 'en-GB', newLocale; groupedBarChart.locale(testLocale); newLocale = groupedBarChart.locale(); expect(defaultLocale).not.toBe(newLocale); expect(newLocale).toBe(testLocale); }) it('should provide loadingState getter and setter', () => { let previous = groupedBarChart.loadingState(), expected = 'test', actual; groupedBarChart.loadingState(expected); actual = groupedBarChart.loadingState(); expect(previous).not.toBe(actual); expect(actual).toBe(expected); }); it('should provide margin getter and setter', () => { let previous = groupedBarChart.margin(), expected = {top: 4, right: 4, bottom: 4, left: 4}, actual; groupedBarChart.margin(expected); actual = groupedBarChart.margin(); expect(previous).not.toBe(actual); expect(actual).toEqual(expected); }); describe('when margins are set partially', function () { it('should override the default values', () => { let previous = groupedBarChart.margin(), expected = { ...previous, top: 10, right: 20 }, actual; groupedBarChart.width(expected); actual = groupedBarChart.width(); expect(previous).not.toBe(actual); expect(actual).toEqual(expected); }) }); it('should provide nameLabel getter and setter', () => { let previous = groupedBarChart.nameLabel(), expected = 'key', actual; groupedBarChart.nameLabel(expected); actual = groupedBarChart.nameLabel(); expect(previous).not.toBe(expected); expect(actual).toBe(expected); }); it('should provide xTicks getter and setter', () => { let previous = groupedBarChart.xTicks(), expected = 4, actual; groupedBarChart.xTicks(expected); actual = groupedBarChart.xTicks(); expect(previous).not.toBe(actual); expect(actual).toBe(expected); }); it('should provide yTicks getter and setter', () => { let previous = groupedBarChart.yTicks(), expected = 4, actual; groupedBarChart.yTicks(expected); actual = groupedBarChart.yTicks(); expect(previous).not.toBe(actual); expect(actual).toBe(expected); }); it('should provide a tooltip threshold getter and setter', () => { let previous = groupedBarChart.tooltipThreshold(), expected = 600, actual; groupedBarChart.tooltipThreshold(expected); actual = groupedBarChart.tooltipThreshold(); expect(previous).not.toBe(expected); expect(actual).toBe(expected); }); it('should provide valueLabel getter and setter', () => { let previous = groupedBarChart.valueLabel(), expected = 'quantity', actual; groupedBarChart.valueLabel(expected); actual = groupedBarChart.valueLabel(); expect(previous).not.toBe(expected); expect(actual).toBe(expected); }); it('should provide valueLabelFormat getter and setter', () => { let previous = groupedBarChart.valueLabelFormat(), expected = 's', actual; groupedBarChart.valueLabelFormat(expected); actual = groupedBarChart.valueLabelFormat(); expect(previous).not.toBe(expected); expect(actual).toBe(expected); }); it('should provide width getter and setter', () => { let previous = groupedBarChart.width(), expected = 40, actual; groupedBarChart.width(expected); actual = groupedBarChart.width(); expect(previous).not.toBe(actual); expect(actual).toBe(expected); }); it('should provide yTickTextOffset getter and setter', () => { let previous = groupedBarChart.yTickTextOffset(), expected = { x: -20, y: -8 }, actual; groupedBarChart.yTickTextOffset(expected); actual = groupedBarChart.yTickTextOffset(); expect(previous).not.toBe(actual); expect(actual).toBe(expected); }); it('should provide yAxisLabel getter and setter', () => { let defaultYAxisLabel = 'Hello', testYAxisLabel = 'World', newYAxisLabel; groupedBarChart.yAxisLabel(testYAxisLabel); newYAxisLabel = groupedBarChart.yAxisLabel(); expect(defaultYAxisLabel).not.toBe(newYAxisLabel); expect(newYAxisLabel).toBe(testYAxisLabel); }); it('should provide yAxisLabelOffset getter and setter', () => { let defaultYAxisLabelOffset = groupedBarChart.yAxisLabelOffset(), testYAxisLabelOffset = -30, newYAxisLabelOffset; groupedBarChart.yAxisLabelOffset(testYAxisLabelOffset); newYAxisLabelOffset = groupedBarChart.yAxisLabelOffset(); expect(defaultYAxisLabelOffset).not.toBe(newYAxisLabelOffset); expect(newYAxisLabelOffset).toBe(testYAxisLabelOffset); }); it('should provide bar padding getter and setter', () => { let previous = groupedBarChart.betweenBarsPadding(), expected = 0.5, actual; groupedBarChart.betweenBarsPadding(expected); actual = groupedBarChart.betweenBarsPadding(); expect(previous).not.toBe(actual); expect(actual).toBe(expected); }); it('should provide bar group padding getter and setter', () => { let previous = groupedBarChart.betweenGroupsPadding(), expected = 0.5, actual; groupedBarChart.betweenGroupsPadding(expected); actual = groupedBarChart.betweenGroupsPadding(); expect(previous).not.toBe(actual); expect(actual).toBe(expected); }); }); describe('Lifecycle', () => { describe('when clicking on a bar', () => { it('should trigger a callback', () => { const chart = containerFixture.select('.grouped-bar'); const callbackSpy = jasmine.createSpy('callback'); const expectedCalls = 1; const expectedArguments = 2; groupedBarChart.on('customClick', callbackSpy); chart.dispatch('click'); expect(callbackSpy.calls.count()).toEqual(expectedCalls); expect(callbackSpy.calls.allArgs()[0].length).toEqual(expectedArguments); }) }); describe('when hovering', () => { it('mouseover should trigger a callback', () => { const chart = containerFixture.selectAll('.grouped-bar'); const callbackSpy = jasmine.createSpy('callback'); const expectedCalls = 1; const expectedArguments = 2; groupedBarChart.on('customMouseOver', callbackSpy); chart.dispatch('mouseover'); expect(callbackSpy.calls.count()).toEqual(expectedCalls); expect(callbackSpy.calls.allArgs()[0].length).toEqual(expectedArguments); }); it('mouseout should trigger a callback', () => { const chart = containerFixture.selectAll('.grouped-bar'); const callbackSpy = jasmine.createSpy('callback'); const expectedCalls = 1; const expectedArguments = 2; groupedBarChart.on('customMouseOut', callbackSpy); chart.dispatch('mouseout'); expect(callbackSpy.calls.count()).toEqual(expectedCalls); expect(callbackSpy.calls.allArgs()[0].length).toEqual(expectedArguments); }); }); }); // TODO-locale: We need to figure out how to clear the default formatting, as this // test is messing up with the rest of tests xdescribe('locale', () => { it('should show the € sign', () => { const customSign = '€'; const customLocale = { 'decimal': ',', 'thousands': '.', 'grouping': [ 3 ], 'currency': [ `${customSign} `, '' ] }; groupedBarChart .valueLabelFormat('$,.2f') .locale(customLocale); containerFixture.datum(dataset.data).call(groupedBarChart); const firstTickSelection = containerFixture.select('.y-axis-group.axis') .select('.tick'); expect(firstTickSelection.text()).toMatch(new RegExp(`${customSign} \\d+\\.?\\d*`)); }); }); }); });
{ "pile_set_name": "Github" }
//The MIT License(MIT) //Copyright(c) 2016 Alberto Rodriguez & LiveCharts Contributors //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. using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media.Animation; using System.Windows.Shapes; using LiveCharts.Charts; using LiveCharts.Definitions.Points; namespace LiveCharts.Wpf.Points { internal class CandlePointView : PointView, IOhlcPointView { public Line HighToLowLine { get; set; } public Rectangle OpenToCloseRectangle { get; set; } public double Open { get; set; } public double High { get; set; } public double Close { get; set; } public double Low { get; set; } public double Width { get; set; } public double Left { get; set; } public double StartReference { get; set; } public override void DrawOrMove(ChartPoint previousDrawn, ChartPoint current, int index, ChartCore chart) { var center = Left + Width / 2; if (IsNew) { HighToLowLine.X1 = center; HighToLowLine.X2 = center; HighToLowLine.Y1 = StartReference; HighToLowLine.Y2 = StartReference; Canvas.SetTop(OpenToCloseRectangle, (Open + Close) / 2); Canvas.SetLeft(OpenToCloseRectangle, Left); OpenToCloseRectangle.Width = Width; OpenToCloseRectangle.Height = 0; } if (DataLabel != null && double.IsNaN(Canvas.GetLeft(DataLabel))) { Canvas.SetTop(DataLabel, current.ChartLocation.Y); Canvas.SetLeft(DataLabel, current.ChartLocation.X); } if (HoverShape != null) { var h = Math.Abs(High - Low); HoverShape.Width = Width; HoverShape.Height = h > 10 ? h : 10; Canvas.SetLeft(HoverShape, Left); Canvas.SetTop(HoverShape, High); } var candleSeries = (CandleSeries)current.SeriesView; if (candleSeries.ColoringRules == null) { if (current.Open <= current.Close) { HighToLowLine.Stroke = candleSeries.IncreaseBrush; OpenToCloseRectangle.Fill = candleSeries.IncreaseBrush; OpenToCloseRectangle.Stroke = candleSeries.IncreaseBrush; } else { HighToLowLine.Stroke = candleSeries.DecreaseBrush; OpenToCloseRectangle.Fill = candleSeries.DecreaseBrush; OpenToCloseRectangle.Stroke = candleSeries.DecreaseBrush; } } else { foreach (var rule in candleSeries.ColoringRules) { if (!rule.Condition(current, previousDrawn)) continue; HighToLowLine.Stroke = rule.Stroke; OpenToCloseRectangle.Fill = rule.Fill; OpenToCloseRectangle.Stroke = rule.Stroke; break; } } if (chart.View.DisableAnimations) { HighToLowLine.Y1 = High; HighToLowLine.Y2 = Low; HighToLowLine.X1 = center; HighToLowLine.X2 = center; OpenToCloseRectangle.Width = Width; OpenToCloseRectangle.Height = Math.Abs(Open - Close); Canvas.SetTop(OpenToCloseRectangle, Math.Min(Open, Close)); Canvas.SetLeft(OpenToCloseRectangle, Left); if (DataLabel != null) { DataLabel.UpdateLayout(); var cx = CorrectXLabel(current.ChartLocation.X - DataLabel.ActualHeight * .5, chart); var cy = CorrectYLabel(current.ChartLocation.Y - DataLabel.ActualWidth * .5, chart); Canvas.SetTop(DataLabel, cy); Canvas.SetLeft(DataLabel, cx); } return; } var animSpeed = chart.View.AnimationsSpeed; if (DataLabel != null) { DataLabel.UpdateLayout(); var cx = CorrectXLabel(current.ChartLocation.X - DataLabel.ActualWidth * .5, chart); var cy = CorrectYLabel(current.ChartLocation.Y - DataLabel.ActualHeight * .5, chart); DataLabel.BeginAnimation(Canvas.LeftProperty, new DoubleAnimation(cx, animSpeed)); DataLabel.BeginAnimation(Canvas.TopProperty, new DoubleAnimation(cy, animSpeed)); } HighToLowLine.BeginAnimation(Line.X1Property, new DoubleAnimation(center, animSpeed)); HighToLowLine.BeginAnimation(Line.X2Property, new DoubleAnimation(center, animSpeed)); HighToLowLine.BeginAnimation(Line.Y1Property, new DoubleAnimation(High, animSpeed)); HighToLowLine.BeginAnimation(Line.Y2Property, new DoubleAnimation(Low, animSpeed)); OpenToCloseRectangle.BeginAnimation(Canvas.LeftProperty, new DoubleAnimation(Left, animSpeed)); OpenToCloseRectangle.BeginAnimation(Canvas.TopProperty, new DoubleAnimation(Math.Min(Open, Close), animSpeed)); OpenToCloseRectangle.BeginAnimation(FrameworkElement.WidthProperty, new DoubleAnimation(Width, animSpeed)); OpenToCloseRectangle.BeginAnimation(FrameworkElement.HeightProperty, new DoubleAnimation(Math.Max(Math.Abs(Open - Close), OpenToCloseRectangle.StrokeThickness), animSpeed)); } public override void RemoveFromView(ChartCore chart) { chart.View.RemoveFromDrawMargin(HoverShape); chart.View.RemoveFromDrawMargin(OpenToCloseRectangle); chart.View.RemoveFromDrawMargin(HighToLowLine); chart.View.RemoveFromDrawMargin(DataLabel); } protected double CorrectXLabel(double desiredPosition, ChartCore chart) { if (desiredPosition + DataLabel.ActualWidth * .5 < -0.1) return -DataLabel.ActualWidth; if (desiredPosition + DataLabel.ActualWidth > chart.DrawMargin.Width) desiredPosition -= desiredPosition + DataLabel.ActualWidth - chart.DrawMargin.Width + 2; if (desiredPosition < 0) desiredPosition = 0; return desiredPosition; } protected double CorrectYLabel(double desiredPosition, ChartCore chart) { //desiredPosition -= Ellipse.ActualHeight * .5 + DataLabel.ActualHeight * .5 + 2; if (desiredPosition + DataLabel.ActualHeight > chart.DrawMargin.Height) desiredPosition -= desiredPosition + DataLabel.ActualHeight - chart.DrawMargin.Height + 2; if (desiredPosition < 0) desiredPosition = 0; return desiredPosition; } } }
{ "pile_set_name": "Github" }
version https://git-lfs.github.com/spec/v1 oid sha256:0e0fbbf70cdf89ae8e948bc39141b8d7132d9cbd622b0d4aa990306883418656 size 13613
{ "pile_set_name": "Github" }
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @subpackage Spreadsheets * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Spreadsheets.php 24594 2012-01-05 21:27:01Z matthew $ */ /** * Zend_Gdata */ require_once('Zend/Gdata.php'); /** * Zend_Gdata_Spreadsheets_SpreadsheetFeed */ require_once('Zend/Gdata/Spreadsheets/SpreadsheetFeed.php'); /** * Zend_Gdata_Spreadsheets_WorksheetFeed */ require_once('Zend/Gdata/Spreadsheets/WorksheetFeed.php'); /** * Zend_Gdata_Spreadsheets_CellFeed */ require_once('Zend/Gdata/Spreadsheets/CellFeed.php'); /** * Zend_Gdata_Spreadsheets_ListFeed */ require_once('Zend/Gdata/Spreadsheets/ListFeed.php'); /** * Zend_Gdata_Spreadsheets_SpreadsheetEntry */ require_once('Zend/Gdata/Spreadsheets/SpreadsheetEntry.php'); /** * Zend_Gdata_Spreadsheets_WorksheetEntry */ require_once('Zend/Gdata/Spreadsheets/WorksheetEntry.php'); /** * Zend_Gdata_Spreadsheets_CellEntry */ require_once('Zend/Gdata/Spreadsheets/CellEntry.php'); /** * Zend_Gdata_Spreadsheets_ListEntry */ require_once('Zend/Gdata/Spreadsheets/ListEntry.php'); /** * Zend_Gdata_Spreadsheets_DocumentQuery */ require_once('Zend/Gdata/Spreadsheets/DocumentQuery.php'); /** * Zend_Gdata_Spreadsheets_ListQuery */ require_once('Zend/Gdata/Spreadsheets/ListQuery.php'); /** * Zend_Gdata_Spreadsheets_CellQuery */ require_once('Zend/Gdata/Spreadsheets/CellQuery.php'); /** * Gdata Spreadsheets * * @link http://code.google.com/apis/gdata/spreadsheets.html * * @category Zend * @package Zend_Gdata * @subpackage Spreadsheets * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Gdata_Spreadsheets extends Zend_Gdata { const SPREADSHEETS_FEED_URI = 'https://spreadsheets.google.com/feeds/spreadsheets'; const SPREADSHEETS_POST_URI = 'https://spreadsheets.google.com/feeds/spreadsheets/private/full'; const WORKSHEETS_FEED_LINK_URI = 'http://schemas.google.com/spreadsheets/2006#worksheetsfeed'; const LIST_FEED_LINK_URI = 'http://schemas.google.com/spreadsheets/2006#listfeed'; const CELL_FEED_LINK_URI = 'http://schemas.google.com/spreadsheets/2006#cellsfeed'; const AUTH_SERVICE_NAME = 'wise'; /** * Namespaces used for Zend_Gdata_Photos * * @var array */ public static $namespaces = array( array('gs', 'http://schemas.google.com/spreadsheets/2006', 1, 0), array( 'gsx', 'http://schemas.google.com/spreadsheets/2006/extended', 1, 0) ); /** * Create Gdata_Spreadsheets object * * @param Zend_Http_Client $client (optional) The HTTP client to use when * when communicating with the Google servers. * @param string $applicationId The identity of the app in the form of Company-AppName-Version */ public function __construct($client = null, $applicationId = 'MyCompany-MyApp-1.0') { $this->registerPackage('Zend_Gdata_Spreadsheets'); $this->registerPackage('Zend_Gdata_Spreadsheets_Extension'); parent::__construct($client, $applicationId); $this->_httpClient->setParameterPost('service', self::AUTH_SERVICE_NAME); $this->_server = 'spreadsheets.google.com'; } /** * Gets a spreadsheet feed. * * @param mixed $location A DocumentQuery or a string URI specifying the feed location. * @return Zend_Gdata_Spreadsheets_SpreadsheetFeed */ public function getSpreadsheetFeed($location = null) { if ($location == null) { $uri = self::SPREADSHEETS_FEED_URI; } else if ($location instanceof Zend_Gdata_Spreadsheets_DocumentQuery) { if ($location->getDocumentType() == null) { $location->setDocumentType('spreadsheets'); } $uri = $location->getQueryUrl(); } else { $uri = $location; } return parent::getFeed($uri, 'Zend_Gdata_Spreadsheets_SpreadsheetFeed'); } /** * Gets a spreadsheet entry. * * @param string $location A DocumentQuery or a URI specifying the entry location. * @return SpreadsheetEntry */ public function getSpreadsheetEntry($location) { if ($location instanceof Zend_Gdata_Spreadsheets_DocumentQuery) { if ($location->getDocumentType() == null) { $location->setDocumentType('spreadsheets'); } $uri = $location->getQueryUrl(); } else { $uri = $location; } return parent::getEntry($uri, 'Zend_Gdata_Spreadsheets_SpreadsheetEntry'); } /** * Gets a worksheet feed. * * @param mixed $location A DocumentQuery, SpreadsheetEntry, or a string URI * @return Zend_Gdata_Spreadsheets_WorksheetFeed The feed of worksheets */ public function getWorksheetFeed($location) { if ($location instanceof Zend_Gdata_Spreadsheets_DocumentQuery) { if ($location->getDocumentType() == null) { $location->setDocumentType('worksheets'); } $uri = $location->getQueryUrl(); } else if ($location instanceof Zend_Gdata_Spreadsheets_SpreadsheetEntry) { $uri = $location->getLink(self::WORKSHEETS_FEED_LINK_URI)->href; } else { $uri = $location; } return parent::getFeed($uri, 'Zend_Gdata_Spreadsheets_WorksheetFeed'); } /** * Gets a worksheet entry. * * @param string $location A DocumentQuery or a URI specifying the entry location. * @return WorksheetEntry */ public function GetWorksheetEntry($location) { if ($location instanceof Zend_Gdata_Spreadsheets_DocumentQuery) { if ($location->getDocumentType() == null) { $location->setDocumentType('worksheets'); } $uri = $location->getQueryUrl(); } else { $uri = $location; } return parent::getEntry($uri, 'Zend_Gdata_Spreadsheets_WorksheetEntry'); } /** * Gets a cell feed. * * @param string $location A CellQuery, WorksheetEntry or a URI specifying the feed location. * @return CellFeed */ public function getCellFeed($location) { if ($location instanceof Zend_Gdata_Spreadsheets_CellQuery) { $uri = $location->getQueryUrl(); } else if ($location instanceof Zend_Gdata_Spreadsheets_WorksheetEntry) { $uri = $location->getLink(self::CELL_FEED_LINK_URI)->href; } else { $uri = $location; } return parent::getFeed($uri, 'Zend_Gdata_Spreadsheets_CellFeed'); } /** * Gets a cell entry. * * @param string $location A CellQuery or a URI specifying the entry location. * @return CellEntry */ public function getCellEntry($location) { if ($location instanceof Zend_Gdata_Spreadsheets_CellQuery) { $uri = $location->getQueryUrl(); } else { $uri = $location; } return parent::getEntry($uri, 'Zend_Gdata_Spreadsheets_CellEntry'); } /** * Gets a list feed. * * @param mixed $location A ListQuery, WorksheetEntry or string URI specifying the feed location. * @return ListFeed */ public function getListFeed($location) { if ($location instanceof Zend_Gdata_Spreadsheets_ListQuery) { $uri = $location->getQueryUrl(); } else if ($location instanceof Zend_Gdata_Spreadsheets_WorksheetEntry) { $uri = $location->getLink(self::LIST_FEED_LINK_URI)->href; } else { $uri = $location; } return parent::getFeed($uri, 'Zend_Gdata_Spreadsheets_ListFeed'); } /** * Gets a list entry. * * @param string $location A ListQuery or a URI specifying the entry location. * @return ListEntry */ public function getListEntry($location) { if ($location instanceof Zend_Gdata_Spreadsheets_ListQuery) { $uri = $location->getQueryUrl(); } else { $uri = $location; } return parent::getEntry($uri, 'Zend_Gdata_Spreadsheets_ListEntry'); } /** * Updates an existing cell. * * @param int $row The row containing the cell to update * @param int $col The column containing the cell to update * @param int $inputValue The new value for the cell * @param string $key The key for the spreadsheet to be updated * @param string $wkshtId (optional) The worksheet to be updated * @return CellEntry The updated cell entry. */ public function updateCell($row, $col, $inputValue, $key, $wkshtId = 'default') { $cell = 'R'.$row.'C'.$col; $query = new Zend_Gdata_Spreadsheets_CellQuery(); $query->setSpreadsheetKey($key); $query->setWorksheetId($wkshtId); $query->setCellId($cell); $entry = $this->getCellEntry($query); $entry->setCell(new Zend_Gdata_Spreadsheets_Extension_Cell(null, $row, $col, $inputValue)); $response = $entry->save(); return $response; } /** * Inserts a new row with provided data. * * @param array $rowData An array of column header to row data * @param string $key The key of the spreadsheet to modify * @param string $wkshtId (optional) The worksheet to modify * @return ListEntry The inserted row */ public function insertRow($rowData, $key, $wkshtId = 'default') { $newEntry = new Zend_Gdata_Spreadsheets_ListEntry(); $newCustomArr = array(); foreach ($rowData as $k => $v) { $newCustom = new Zend_Gdata_Spreadsheets_Extension_Custom(); $newCustom->setText($v)->setColumnName($k); $newEntry->addCustom($newCustom); } $query = new Zend_Gdata_Spreadsheets_ListQuery(); $query->setSpreadsheetKey($key); $query->setWorksheetId($wkshtId); $feed = $this->getListFeed($query); $editLink = $feed->getLink('http://schemas.google.com/g/2005#post'); return $this->insertEntry($newEntry->saveXML(), $editLink->href, 'Zend_Gdata_Spreadsheets_ListEntry'); } /** * Updates an existing row with provided data. * * @param ListEntry $entry The row entry to update * @param array $newRowData An array of column header to row data */ public function updateRow($entry, $newRowData) { $newCustomArr = array(); foreach ($newRowData as $k => $v) { $newCustom = new Zend_Gdata_Spreadsheets_Extension_Custom(); $newCustom->setText($v)->setColumnName($k); $newCustomArr[] = $newCustom; } $entry->setCustom($newCustomArr); return $entry->save(); } /** * Deletes an existing row . * * @param ListEntry $entry The row to delete */ public function deleteRow($entry) { $entry->delete(); } /** * Returns the content of all rows as an associative array * * @param mixed $location A ListQuery or string URI specifying the feed location. * @return array An array of rows. Each element of the array is an associative array of data */ public function getSpreadsheetListFeedContents($location) { $listFeed = $this->getListFeed($location); $listFeed = $this->retrieveAllEntriesForFeed($listFeed); $spreadsheetContents = array(); foreach ($listFeed as $listEntry) { $rowContents = array(); $customArray = $listEntry->getCustom(); foreach ($customArray as $custom) { $rowContents[$custom->getColumnName()] = $custom->getText(); } $spreadsheetContents[] = $rowContents; } return $spreadsheetContents; } /** * Returns the content of all cells as an associative array, indexed * off the cell location (ie 'A1', 'D4', etc). Each element of * the array is an associative array with a 'value' and a 'function'. * Only non-empty cells are returned by default. 'range' is the * value of the 'range' query parameter specified at: * http://code.google.com/apis/spreadsheets/reference.html#cells_Parameters * * @param mixed $location A CellQuery, WorksheetEntry or a URL (w/o query string) specifying the feed location. * @param string $range The range of cells to retrieve * @param boolean $empty Whether to retrieve empty cells * @return array An associative array of cells */ public function getSpreadsheetCellFeedContents($location, $range = null, $empty = false) { $cellQuery = null; if ($location instanceof Zend_Gdata_Spreadsheets_CellQuery) { $cellQuery = $location; } else if ($location instanceof Zend_Gdata_Spreadsheets_WorksheetEntry) { $url = $location->getLink(self::CELL_FEED_LINK_URI)->href; $cellQuery = new Zend_Gdata_Spreadsheets_CellQuery($url); } else { $url = $location; $cellQuery = new Zend_Gdata_Spreadsheets_CellQuery($url); } if ($range != null) { $cellQuery->setRange($range); } $cellQuery->setReturnEmpty($empty); $cellFeed = $this->getCellFeed($cellQuery); $cellFeed = $this->retrieveAllEntriesForFeed($cellFeed); $spreadsheetContents = array(); foreach ($cellFeed as $cellEntry) { $cellContents = array(); $cell = $cellEntry->getCell(); $cellContents['formula'] = $cell->getInputValue(); $cellContents['value'] = $cell->getText(); $spreadsheetContents[$cellEntry->getTitle()->getText()] = $cellContents; } return $spreadsheetContents; } /** * Alias for getSpreadsheetFeed * * @param mixed $location A DocumentQuery or a string URI specifying the feed location. * @return Zend_Gdata_Spreadsheets_SpreadsheetFeed */ public function getSpreadsheets($location = null) { return $this->getSpreadsheetFeed($location = null); } }
{ "pile_set_name": "Github" }
%YAML:1.0 #-------------------------------------------------------------------------------------------- # Camera Parameters. Adjust them! #-------------------------------------------------------------------------------------------- # Camera calibration and distortion parameters (OpenCV) #+++++ Cam0 +++++ Camera.fx: 359.428 Camera.fy: 359.428 Camera.cx: 303.5964 Camera.cy: 92.60785 Camera.k1: 0.0 Camera.k2: 0.0 Camera.p1: 0.0 Camera.p2: 0.0 Camera.k3: 0.000000 # Camera frames per second Camera.fps: 10.0 # Color order of the images (0: BGR, 1: RGB. It is ignored if images are grayscale) Camera.RGB: 0 #T_SC Cam0.T00: 1.0 Cam0.T01: 0.0 Cam0.T02: 0.0 Cam0.T03: 0.0 Cam0.T10: 0.0 Cam0.T11: 1.0 Cam0.T12: 0.0 Cam0.T13: 0.0 Cam0.T20: 0.0 Cam0.T21: 0.0 Cam0.T22: 0.0 Cam0.T23: 1.0 Cam0.T30: 0.0 Cam0.T31: 0.0 Cam0.T32: 0.0 Cam0.T33: 1.0
{ "pile_set_name": "Github" }
version: "3.7" services: dagster-grpc-server: image: ${IMAGE_NAME} hostname: dagster-grpc-server container_name: dagster-grpc-server ports: - "8090:8090" command: [ "dagster", "api", "grpc", "--port", "8090", "--host", "0.0.0.0", "--python-file", "test_pipelines/repo.py", ] networks: - dagster networks: dagster: driver: bridge name: dagster
{ "pile_set_name": "Github" }
Below patch is a squash of following 4 commits borrowed from ayufan's https://github.com/ayufan-rock64/linux-mainline-kernel repo: From cc22206776d61948f6984a4f03d8013eb4f92984 Mon Sep 17 00:00:00 2001 From: Pantelis Antoniou <[email protected]> Date: Wed, 3 Dec 2014 13:23:28 +0200 Subject: [PATCH] OF: DT-Overlay configfs interface This is a port of Pantelis Antoniou's v3 port that makes use of the new upstreamed configfs support for binary attributes. Original commit message: Add a runtime interface to using configfs for generic device tree overlay usage. With it its possible to use device tree overlays without having to use a per-platform overlay manager. Please see Documentation/devicetree/configfs-overlays.txt for more info. Changes since v2: - Removed ifdef CONFIG_OF_OVERLAY (since for now it's required) - Created a documentation entry - Slight rewording in Kconfig Changes since v1: - of_resolve() -> of_resolve_phandles(). Originally-signed-off-by: Pantelis Antoniou <[email protected]> Signed-off-by: Phil Elwell <[email protected]> DT configfs: Fix build errors on other platforms Signed-off-by: Phil Elwell <[email protected]> DT configfs: fix build error There is an error when compiling rpi-4.6.y branch: CC drivers/of/configfs.o drivers/of/configfs.c:291:21: error: initialization from incompatible pointer type [-Werror=incompatible-pointer-types] .default_groups = of_cfs_def_groups, ^ drivers/of/configfs.c:291:21: note: (near initialization for 'of_cfs_subsys.su_group.default_groups.next') The .default_groups is linked list since commit 1ae1602de028acaa42a0f6ff18d19756f8e825c6. This commit uses configfs_add_default_group to fix this problem. Change-Id: Id4903c9725ebc355aadd067bbc32047db622ce61 Signed-off-by: Slawomir Stepien <[email protected]> From 7cfb967c52d374ddcb0fc9194f38d1d5f9d8cdd8 Mon Sep 17 00:00:00 2001 From: popcornmix <[email protected]> Date: Sun, 3 Dec 2017 21:43:03 +0000 Subject: [PATCH] configfs: New of_overlay API From 8637321fabb045fe8617360ef1b058978b0d8457 Mon Sep 17 00:00:00 2001 From: Phil Elwell <[email protected]> Date: Mon, 4 Dec 2017 14:07:40 +0000 Subject: [PATCH] SQUASH: config_fs: of_overlay_apply takes a pointer Signed-off-by: Phil Elwell <[email protected]> From 274dfabb947ca32116a429c582c74aaee6ff1b5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20Trzci=C5=84ski?= <[email protected]> Date: Mon, 14 May 2018 11:28:09 +0200 Subject: [PATCH] ayufan: fix overlayfs to compile on 4.17 kernel Change-Id: I421887697d2ba6e52aba9100100b7664760e2001 diff --git a/Documentation/devicetree/configfs-overlays.txt b/Documentation/devicetree/configfs-overlays.txt new file mode 100644 index 0000000000000..5fa43e0643072 --- /dev/null +++ b/Documentation/devicetree/configfs-overlays.txt @@ -0,0 +1,31 @@ +Howto use the configfs overlay interface. + +A device-tree configfs entry is created in /config/device-tree/overlays +and and it is manipulated using standard file system I/O. +Note that this is a debug level interface, for use by developers and +not necessarily something accessed by normal users due to the +security implications of having direct access to the kernel's device tree. + +* To create an overlay you mkdir the directory: + + # mkdir /config/device-tree/overlays/foo + +* Either you echo the overlay firmware file to the path property file. + + # echo foo.dtbo >/config/device-tree/overlays/foo/path + +* Or you cat the contents of the overlay to the dtbo file + + # cat foo.dtbo >/config/device-tree/overlays/foo/dtbo + +The overlay file will be applied, and devices will be created/destroyed +as required. + +To remove it simply rmdir the directory. + + # rmdir /config/device-tree/overlays/foo + +The rationalle of the dual interface (firmware & direct copy) is that each is +better suited to different use patterns. The firmware interface is what's +intended to be used by hardware managers in the kernel, while the copy interface +make sense for developers (since it avoids problems with namespaces). diff --git a/drivers/of/Kconfig b/drivers/of/Kconfig index 37c2ccbefecdc..d3fc81a40c0e7 100644 --- a/drivers/of/Kconfig +++ b/drivers/of/Kconfig @@ -103,4 +103,11 @@ config OF_OVERLAY config OF_NUMA bool +config OF_CONFIGFS + bool "Device Tree Overlay ConfigFS interface" + select CONFIGFS_FS + select OF_OVERLAY + help + Enable a simple user-space driven DT overlay interface. + endif # OF diff --git a/drivers/of/Makefile b/drivers/of/Makefile index 663a4af0cccd5..b00a95adf5199 100644 --- a/drivers/of/Makefile +++ b/drivers/of/Makefile @@ -1,6 +1,7 @@ # SPDX-License-Identifier: GPL-2.0 obj-y = base.o device.o platform.o property.o obj-$(CONFIG_OF_KOBJ) += kobj.o +obj-$(CONFIG_OF_CONFIGFS) += configfs.o obj-$(CONFIG_OF_DYNAMIC) += dynamic.o obj-$(CONFIG_OF_FLATTREE) += fdt.o obj-$(CONFIG_OF_EARLY_FLATTREE) += fdt_address.o diff --git a/drivers/of/configfs.c b/drivers/of/configfs.c new file mode 100644 index 000000000..5dd509e8f --- /dev/null +++ b/drivers/of/configfs.c @@ -0,0 +1,290 @@ +/* + * Configfs entries for device-tree + * + * Copyright (C) 2013 - Pantelis Antoniou <[email protected]> + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + */ +#include <linux/ctype.h> +#include <linux/cpu.h> +#include <linux/module.h> +#include <linux/of.h> +#include <linux/of_fdt.h> +#include <linux/spinlock.h> +#include <linux/slab.h> +#include <linux/proc_fs.h> +#include <linux/configfs.h> +#include <linux/types.h> +#include <linux/stat.h> +#include <linux/limits.h> +#include <linux/file.h> +#include <linux/vmalloc.h> +#include <linux/firmware.h> +#include <linux/sizes.h> + +#include "of_private.h" + +struct cfs_overlay_item { + struct config_item item; + + char path[PATH_MAX]; + + const struct firmware *fw; + struct device_node *overlay; + int ov_id; + + void *dtbo; + int dtbo_size; +}; + +static int create_overlay(struct cfs_overlay_item *overlay, void *blob, u32 blob_size) +{ + int err; + + err = of_overlay_fdt_apply(blob, blob_size, &overlay->ov_id); + if (err < 0) { + pr_err("%s: Failed to create overlay (err=%d)\n", + __func__, err); + goto out_err; + } + +out_err: + return err; +} + +static inline struct cfs_overlay_item *to_cfs_overlay_item( + struct config_item *item) +{ + return item ? container_of(item, struct cfs_overlay_item, item) : NULL; +} + +static ssize_t cfs_overlay_item_path_show(struct config_item *item, + char *page) +{ + struct cfs_overlay_item *overlay = to_cfs_overlay_item(item); + return sprintf(page, "%s\n", overlay->path); +} + +static ssize_t cfs_overlay_item_path_store(struct config_item *item, + const char *page, size_t count) +{ + struct cfs_overlay_item *overlay = to_cfs_overlay_item(item); + const char *p = page; + char *s; + int err; + + /* if it's set do not allow changes */ + if (overlay->path[0] != '\0' || overlay->dtbo_size > 0) + return -EPERM; + + /* copy to path buffer (and make sure it's always zero terminated */ + count = snprintf(overlay->path, sizeof(overlay->path) - 1, "%s", p); + overlay->path[sizeof(overlay->path) - 1] = '\0'; + + /* strip trailing newlines */ + s = overlay->path + strlen(overlay->path); + while (s > overlay->path && *--s == '\n') + *s = '\0'; + + pr_debug("%s: path is '%s'\n", __func__, overlay->path); + + err = request_firmware(&overlay->fw, overlay->path, NULL); + if (err != 0) + goto out_err; + + err = create_overlay(overlay, (void *)overlay->fw->data, overlay->fw->size); + if (err != 0) + goto out_err; + + return count; + +out_err: + + release_firmware(overlay->fw); + overlay->fw = NULL; + + overlay->path[0] = '\0'; + return err; +} + +static ssize_t cfs_overlay_item_status_show(struct config_item *item, + char *page) +{ + struct cfs_overlay_item *overlay = to_cfs_overlay_item(item); + + return sprintf(page, "%s\n", + overlay->ov_id >= 0 ? "applied" : "unapplied"); +} + +CONFIGFS_ATTR(cfs_overlay_item_, path); +CONFIGFS_ATTR_RO(cfs_overlay_item_, status); + +static struct configfs_attribute *cfs_overlay_attrs[] = { + &cfs_overlay_item_attr_path, + &cfs_overlay_item_attr_status, + NULL, +}; + +ssize_t cfs_overlay_item_dtbo_read(struct config_item *item, + void *buf, size_t max_count) +{ + struct cfs_overlay_item *overlay = to_cfs_overlay_item(item); + + pr_debug("%s: buf=%p max_count=%zu\n", __func__, + buf, max_count); + + if (overlay->dtbo == NULL) + return 0; + + /* copy if buffer provided */ + if (buf != NULL) { + /* the buffer must be large enough */ + if (overlay->dtbo_size > max_count) + return -ENOSPC; + + memcpy(buf, overlay->dtbo, overlay->dtbo_size); + } + + return overlay->dtbo_size; +} + +ssize_t cfs_overlay_item_dtbo_write(struct config_item *item, + const void *buf, size_t count) +{ + struct cfs_overlay_item *overlay = to_cfs_overlay_item(item); + int err; + + /* if it's set do not allow changes */ + if (overlay->path[0] != '\0' || overlay->dtbo_size > 0) + return -EPERM; + + /* copy the contents */ + overlay->dtbo = kmemdup(buf, count, GFP_KERNEL); + if (overlay->dtbo == NULL) + return -ENOMEM; + + overlay->dtbo_size = count; + + err = create_overlay(overlay, overlay->dtbo, overlay->dtbo_size); + if (err != 0) + goto out_err; + + return count; + +out_err: + kfree(overlay->dtbo); + overlay->dtbo = NULL; + overlay->dtbo_size = 0; + + return err; +} + +CONFIGFS_BIN_ATTR(cfs_overlay_item_, dtbo, NULL, SZ_1M); + +static struct configfs_bin_attribute *cfs_overlay_bin_attrs[] = { + &cfs_overlay_item_attr_dtbo, + NULL, +}; + +static void cfs_overlay_release(struct config_item *item) +{ + struct cfs_overlay_item *overlay = to_cfs_overlay_item(item); + + if (overlay->ov_id >= 0) + of_overlay_remove(&overlay->ov_id); + if (overlay->fw) + release_firmware(overlay->fw); + /* kfree with NULL is safe */ + kfree(overlay->dtbo); + kfree(overlay); +} + +static struct configfs_item_operations cfs_overlay_item_ops = { + .release = cfs_overlay_release, +}; + +static struct config_item_type cfs_overlay_type = { + .ct_item_ops = &cfs_overlay_item_ops, + .ct_attrs = cfs_overlay_attrs, + .ct_bin_attrs = cfs_overlay_bin_attrs, + .ct_owner = THIS_MODULE, +}; + +static struct config_item *cfs_overlay_group_make_item( + struct config_group *group, const char *name) +{ + struct cfs_overlay_item *overlay; + + overlay = kzalloc(sizeof(*overlay), GFP_KERNEL); + if (!overlay) + return ERR_PTR(-ENOMEM); + overlay->ov_id = -1; + + config_item_init_type_name(&overlay->item, name, &cfs_overlay_type); + return &overlay->item; +} + +static void cfs_overlay_group_drop_item(struct config_group *group, + struct config_item *item) +{ + struct cfs_overlay_item *overlay = to_cfs_overlay_item(item); + + config_item_put(&overlay->item); +} + +static struct configfs_group_operations overlays_ops = { + .make_item = cfs_overlay_group_make_item, + .drop_item = cfs_overlay_group_drop_item, +}; + +static struct config_item_type overlays_type = { + .ct_group_ops = &overlays_ops, + .ct_owner = THIS_MODULE, +}; + +static struct configfs_group_operations of_cfs_ops = { + /* empty - we don't allow anything to be created */ +}; + +static struct config_item_type of_cfs_type = { + .ct_group_ops = &of_cfs_ops, + .ct_owner = THIS_MODULE, +}; + +struct config_group of_cfs_overlay_group; + +static struct configfs_subsystem of_cfs_subsys = { + .su_group = { + .cg_item = { + .ci_namebuf = "device-tree", + .ci_type = &of_cfs_type, + }, + }, + .su_mutex = __MUTEX_INITIALIZER(of_cfs_subsys.su_mutex), +}; + +static int __init of_cfs_init(void) +{ + int ret; + + pr_info("%s\n", __func__); + + config_group_init(&of_cfs_subsys.su_group); + config_group_init_type_name(&of_cfs_overlay_group, "overlays", + &overlays_type); + configfs_add_default_group(&of_cfs_overlay_group, + &of_cfs_subsys.su_group); + + ret = configfs_register_subsystem(&of_cfs_subsys); + if (ret != 0) { + pr_err("%s: failed to register subsys\n", __func__); + goto out; + } + pr_info("%s: OK\n", __func__); +out: + return ret; +} +late_initcall(of_cfs_init);
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <!--Generated by crowdin.com--> <!-- Copyright (C) 2014-2015 The CyanogenMod Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources> <string name="app_name">CM સેટિંગ્સ અને સંગ્રહ</string> </resources>
{ "pile_set_name": "Github" }
#region License // Copyright (c) 2013, ClearCanvas Inc. // All rights reserved. // http://www.clearcanvas.ca // // This file is part of the ClearCanvas RIS/PACS open source project. // // The ClearCanvas RIS/PACS open source project is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // The ClearCanvas RIS/PACS open source project is distributed in the hope that it // will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General // Public License for more details. // // You should have received a copy of the GNU General Public License along with // the ClearCanvas RIS/PACS open source project. If not, see // <http://www.gnu.org/licenses/>. #endregion using System.Collections.Generic; using System.Drawing; using ClearCanvas.Common; using ClearCanvas.Common.Utilities; using ClearCanvas.Desktop; using ClearCanvas.ImageViewer.Graphics; using ClearCanvas.ImageViewer.Mathematics; namespace ClearCanvas.ImageViewer.InteractiveGraphics { /// <summary> /// This class implements a simple algorithm for determining which cursor on an 8 point compass to show /// for a particular control point in a <see cref="ControlPointsGraphic.ControlPointGroup"/>. The class assumes that the /// purpose of the control points is to stretch the graphic that owns the control points (as will be /// the case with most ROI graphic implementations). /// </summary> [Cloneable(true)] internal class CompassStretchCursorTokenStrategy : StretchCursorTokenStrategy { private enum CompassPoints { NorthEast = 0, SouthEast = 1, SouthWest = 2, NorthWest = 3, North = 4, East = 5, South = 6, West = 7 }; [CloneIgnore] private SortedList<CompassPoints, CursorToken> _stretchIndicatorTokens; public CompassStretchCursorTokenStrategy() { InstallDefaults(); } private IControlPointsGraphic ControlPoints { get { if (base.TargetGraphic is IControlPointsGraphic) return (IControlPointsGraphic) base.TargetGraphic; return null; } } /// <summary> /// Gets the bounding rectangle that contains all the points in the <see cref="ControlPointsGraphic.ControlPointGroup"/>. /// </summary> private RectangleF BoundingRectangle { get { List<PointF> controlPoints = new List<PointF>(); for (int i = 0; i < this.ControlPoints.Count; ++i) controlPoints.Add(this.ControlPoints[i]); return RectangleUtilities.ComputeBoundingRectangle(controlPoints.ToArray()); } } /// <summary> /// Gets or sets the <see cref="CursorToken"/> that corresponds to a particular point on the compass. /// </summary> /// <param name="compassPoint">the compass point.</param> /// <returns>the <see cref="CursorToken"/> that corresponds to the specified point on the compass, or null.</returns> private CursorToken this[CompassPoints compassPoint] { get { if (!_stretchIndicatorTokens.ContainsKey(compassPoint)) return null; return _stretchIndicatorTokens[compassPoint]; } set { if (value != null) { _stretchIndicatorTokens[compassPoint] = value; } else { if (_stretchIndicatorTokens.ContainsKey(compassPoint)) _stretchIndicatorTokens.Remove(compassPoint); } } } /// <summary> /// Installs the default set of system cursors for the compass. /// </summary> private void InstallDefaults() { _stretchIndicatorTokens = new SortedList<CompassPoints, CursorToken>(); _stretchIndicatorTokens[CompassPoints.East] = _stretchIndicatorTokens[CompassPoints.West] = new CursorToken(CursorToken.SystemCursors.SizeWE); _stretchIndicatorTokens[CompassPoints.North] = _stretchIndicatorTokens[CompassPoints.South] = new CursorToken(CursorToken.SystemCursors.SizeNS); _stretchIndicatorTokens[CompassPoints.NorthEast] = _stretchIndicatorTokens[CompassPoints.SouthWest] = new CursorToken(CursorToken.SystemCursors.SizeNESW); _stretchIndicatorTokens[CompassPoints.NorthWest] = _stretchIndicatorTokens[CompassPoints.SouthEast] = new CursorToken(CursorToken.SystemCursors.SizeNWSE); } /// <summary> /// Computes the distance from a point to a compass point on the given rectangle. /// </summary> /// <param name="point">a point whose distance from a compass point on the rectangle is to be determined.</param> /// <param name="compassRectangle">the rectangle from which to determine the compass point position.</param> /// <param name="compassPoint">the point on the compass to find the distance to.</param> /// <returns></returns> private float DistanceToCompassPoint(PointF point, RectangleF compassRectangle, CompassPoints compassPoint) { PointF compassPointPosition = GetCompassPointPosition(compassPoint, compassRectangle); return (float)Vector.Distance(point, compassPointPosition); } /// <summary> /// Computes the position on a given rectangle that corresponds to the given compass point. /// </summary> /// <param name="compassPoint">the compass point whose position on the rectangle is to be determined.</param> /// <param name="rectangle">the rectangle.</param> /// <returns>the point on the rectangle that corresponds to the given compass point.</returns> private PointF GetCompassPointPosition(CompassPoints compassPoint, RectangleF rectangle) { float top = rectangle.Top; float left = rectangle.Left; float right = rectangle.Right; float bottom = rectangle.Bottom; float centreX = left; if (left != right) centreX = rectangle.Left + rectangle.Width / 2F; float centreY = top; if (top != bottom) centreY = rectangle.Top + rectangle.Height / 2F; switch (compassPoint) { case CompassPoints.NorthWest: return new PointF(left, top); case CompassPoints.NorthEast: return new PointF(right, top); case CompassPoints.SouthEast: return new PointF(right, bottom); case CompassPoints.SouthWest: return new PointF(left, bottom); case CompassPoints.North: return new PointF(centreX, top); case CompassPoints.East: return new PointF(right, centreY); case CompassPoints.South: return new PointF(centreX, bottom); default: //CompassPoints.West: return new PointF(left, centreY); } } /// <summary> /// Gets the appropriate <see cref="CursorToken"/> for a given point (in destination coordinates). /// </summary> /// <param name="point">the point (in destination coordinates).</param> /// <returns>a <see cref="CursorToken"/> that is appropriate for the given point, or null.</returns> public override CursorToken GetCursorToken(Point point) { if (_stretchIndicatorTokens.Count == 0) return null; Platform.CheckForNullReference(ControlPoints, "_controlPoints"); int controlPointIndex = ControlPoints.HitTestControlPoint(point); if (controlPointIndex < 0) return null; ControlPoints.CoordinateSystem = CoordinateSystem.Destination; PointF controlPoint = ControlPoints[controlPointIndex]; RectangleF containingRectangle = this.BoundingRectangle; CompassPoints closestCompassPoint = _stretchIndicatorTokens.Keys[0]; float minDistance = DistanceToCompassPoint(controlPoint, containingRectangle, closestCompassPoint); for (int i = 1; i < _stretchIndicatorTokens.Keys.Count; ++i) { CompassPoints compassPoint = _stretchIndicatorTokens.Keys[i]; float distance = DistanceToCompassPoint(controlPoint, containingRectangle, compassPoint); if (distance <= minDistance) { closestCompassPoint = compassPoint; minDistance = distance; } } ControlPoints.ResetCoordinateSystem(); return _stretchIndicatorTokens[closestCompassPoint]; } } }
{ "pile_set_name": "Github" }
var baseGet = require('../internal/baseGet'), toPath = require('../internal/toPath'); /** * The opposite of `_.property`; this method creates a function that returns * the property value at a given path on `object`. * * @static * @memberOf _ * @category Utility * @param {Object} object The object to query. * @returns {Function} Returns the new function. * @example * * var array = [0, 1, 2], * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); * // => [2, 0] */ function propertyOf(object) { return function(path) { return baseGet(object, toPath(path), (path + '')); }; } module.exports = propertyOf;
{ "pile_set_name": "Github" }
var tap = require("tap") , minimatch = require("../") tap.test("brace expansion", function (t) { // [ pattern, [expanded] ] ; [ [ "a{b,c{d,e},{f,g}h}x{y,z}" , [ "abxy" , "abxz" , "acdxy" , "acdxz" , "acexy" , "acexz" , "afhxy" , "afhxz" , "aghxy" , "aghxz" ] ] , [ "a{1..5}b" , [ "a1b" , "a2b" , "a3b" , "a4b" , "a5b" ] ] , [ "a{b}c", ["a{b}c"] ] , [ "a{00..05}b" , [ "a00b" , "a01b" , "a02b" , "a03b" , "a04b" , "a05b" ] ] , [ "z{a,b},c}d", ["za,c}d", "zb,c}d"] ] , [ "z{a,b{,c}d", ["z{a,bd", "z{a,bcd"] ] , [ "a{b{c{d,e}f}g}h", ["a{b{cdf}g}h", "a{b{cef}g}h"] ] , [ "a{b{c{d,e}f{x,y}}g}h", ["a{b{cdfx}g}h", "a{b{cdfy}g}h", "a{b{cefx}g}h", "a{b{cefy}g}h"] ] , [ "a{b{c{d,e}f{x,y{}g}h", ["a{b{cdfxh", "a{b{cdfy{}gh", "a{b{cefxh", "a{b{cefy{}gh"] ] ].forEach(function (tc) { var p = tc[0] , expect = tc[1] t.equivalent(minimatch.braceExpand(p), expect, p) }) console.error("ending") t.end() })
{ "pile_set_name": "Github" }
//===- xray-extract.cpp: XRay Instrumentation Map Extraction --------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // Implementation of the xray-extract.h interface. // // FIXME: Support other XRay-instrumented binary formats other than ELF. // //===----------------------------------------------------------------------===// #include "func-id-helper.h" #include "xray-registry.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Error.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Format.h" #include "llvm/Support/raw_ostream.h" #include "llvm/XRay/InstrumentationMap.h" using namespace llvm; using namespace llvm::xray; using namespace llvm::yaml; // llvm-xray extract // ---------------------------------------------------------------------------- static cl::SubCommand Extract("extract", "Extract instrumentation maps"); static cl::opt<std::string> ExtractInput(cl::Positional, cl::desc("<input file>"), cl::Required, cl::sub(Extract)); static cl::opt<std::string> ExtractOutput("output", cl::value_desc("output file"), cl::init("-"), cl::desc("output file; use '-' for stdout"), cl::sub(Extract)); static cl::alias ExtractOutput2("o", cl::aliasopt(ExtractOutput), cl::desc("Alias for -output"), cl::sub(Extract)); static cl::opt<bool> ExtractSymbolize("symbolize", cl::value_desc("symbolize"), cl::init(false), cl::desc("symbolize functions"), cl::sub(Extract)); static cl::alias ExtractSymbolize2("s", cl::aliasopt(ExtractSymbolize), cl::desc("alias for -symbolize"), cl::sub(Extract)); namespace { void exportAsYAML(const InstrumentationMap &Map, raw_ostream &OS, FuncIdConversionHelper &FH) { // First we translate the sleds into the YAMLXRaySledEntry objects in a deque. std::vector<YAMLXRaySledEntry> YAMLSleds; auto Sleds = Map.sleds(); YAMLSleds.reserve(std::distance(Sleds.begin(), Sleds.end())); for (const auto &Sled : Sleds) { auto FuncId = Map.getFunctionId(Sled.Function); if (!FuncId) return; YAMLSleds.push_back({*FuncId, Sled.Address, Sled.Function, Sled.Kind, Sled.AlwaysInstrument, ExtractSymbolize ? FH.SymbolOrNumber(*FuncId) : ""}); } Output Out(OS, nullptr, 0); Out << YAMLSleds; } } // namespace static CommandRegistration Unused(&Extract, []() -> Error { auto InstrumentationMapOrError = loadInstrumentationMap(ExtractInput); if (!InstrumentationMapOrError) return joinErrors(make_error<StringError>( Twine("Cannot extract instrumentation map from '") + ExtractInput + "'.", std::make_error_code(std::errc::invalid_argument)), InstrumentationMapOrError.takeError()); std::error_code EC; raw_fd_ostream OS(ExtractOutput, EC, sys::fs::OpenFlags::OF_Text); if (EC) return make_error<StringError>( Twine("Cannot open file '") + ExtractOutput + "' for writing.", EC); const auto &FunctionAddresses = InstrumentationMapOrError->getFunctionAddresses(); symbolize::LLVMSymbolizer Symbolizer; llvm::xray::FuncIdConversionHelper FuncIdHelper(ExtractInput, Symbolizer, FunctionAddresses); exportAsYAML(*InstrumentationMapOrError, OS, FuncIdHelper); return Error::success(); });
{ "pile_set_name": "Github" }
<?php /** * Quotes pattern. * * @package A8C\FSE */ $markup = ' <!-- wp:group {"align":"full","style":{"color":{"background":"#f1f1ee","text":"#000000"}}} --> <div class="wp-block-group alignfull has-text-color has-background" style="background-color:#f1f1ee;color:#000000"><div class="wp-block-group__inner-container"><!-- wp:spacer {"height":26} --> <div style="height:26px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:jetpack/layout-grid {"gutterSize":"huge","addGutterEnds":false,"column1DesktopSpan":3,"column1DesktopOffset":1,"column1TabletSpan":3,"column1MobileSpan":4,"column2DesktopSpan":6,"column2DesktopOffset":1,"column2TabletSpan":5,"column2MobileSpan":4,"column3DesktopSpan":2,"column3DesktopOffset":4,"column3TabletSpan":4,"column3TabletOffset":1,"column3MobileSpan":4,"column4DesktopSpan":4,"column4TabletSpan":4,"column4MobileSpan":4,"className":"column1-desktop-grid__span-3 column1-desktop-grid__start-2 column1-desktop-grid__row-1 column2-desktop-grid__span-6 column2-desktop-grid__start-6 column2-desktop-grid__row-1 column1-tablet-grid__span-3 column1-tablet-grid__row-1 column2-tablet-grid__span-5 column2-tablet-grid__start-4 column2-tablet-grid__row-1 column1-mobile-grid__span-4 column1-mobile-grid__row-1 column2-mobile-grid__span-4 column2-mobile-grid__row-2"} --> <div class="wp-block-jetpack-layout-grid alignfull column1-desktop-grid__span-3 column1-desktop-grid__start-2 column1-desktop-grid__row-1 column2-desktop-grid__span-6 column2-desktop-grid__start-6 column2-desktop-grid__row-1 column1-tablet-grid__span-3 column1-tablet-grid__row-1 column2-tablet-grid__span-5 column2-tablet-grid__start-4 column2-tablet-grid__row-1 column1-mobile-grid__span-4 column1-mobile-grid__row-1 column2-mobile-grid__span-4 column2-mobile-grid__row-2 wp-block-jetpack-layout-gutter__nowrap wp-block-jetpack-layout-gutter__huge"><!-- wp:jetpack/layout-grid-column --> <div class="wp-block-jetpack-layout-grid-column wp-block-jetpack-layout-grid__padding-none"><!-- wp:spacer {"height":20} --> <div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:heading {"level":3,"style":{"typography":{"fontSize":28,"lineHeight":"1.3"}}} --> <h3 style="line-height:1.3;font-size:28px"><strong>%1$s</strong></h3> <!-- /wp:heading --></div> <!-- /wp:jetpack/layout-grid-column --> <!-- wp:jetpack/layout-grid-column --> <div class="wp-block-jetpack-layout-grid-column wp-block-jetpack-layout-grid__padding-none"><!-- wp:spacer {"height":24} --> <div style="height:24px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:jetpack/rating-star {"rating":5,"className":"margin-bottom-half"} --> <figure class="wp-block-jetpack-rating-star margin-bottom-half" style="text-align:left"><span>★</span><span>★</span><span>★</span><span>★</span><span>★</span></figure> <!-- /wp:jetpack/rating-star --> <!-- wp:paragraph {"className":"margin-top-half margin-bottom-half"} --> <p class="margin-top-half margin-bottom-half">%2$s</p> <!-- /wp:paragraph --> <!-- wp:paragraph {"className":"margin-top-half","style":{"typography":{"fontSize":16}}} --> <p class="margin-top-half" style="font-size:16px"><strong>Brianna</strong><br>Brighton</p> <!-- /wp:paragraph --> <!-- wp:spacer {"height":30} --> <div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:jetpack/rating-star {"rating":5,"className":"margin-bottom-half"} --> <figure class="wp-block-jetpack-rating-star margin-bottom-half" style="text-align:left"><span>★</span><span>★</span><span>★</span><span>★</span><span>★</span></figure> <!-- /wp:jetpack/rating-star --> <!-- wp:paragraph {"className":"margin-top-half margin-bottom-half"} --> <p class="margin-top-half margin-bottom-half">%3$s</p> <!-- /wp:paragraph --> <!-- wp:paragraph {"className":"margin-top-half","style":{"typography":{"fontSize":16}}} --> <p class="margin-top-half" style="font-size:16px"><strong>Jayla</strong><br>Hove</p> <!-- /wp:paragraph --> <!-- wp:spacer {"height":30} --> <div style="height:30px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:jetpack/rating-star {"rating":5,"className":"margin-bottom-half"} --> <figure class="wp-block-jetpack-rating-star margin-bottom-half" style="text-align:left"><span>★</span><span>★</span><span>★</span><span>★</span><span>★</span></figure> <!-- /wp:jetpack/rating-star --> <!-- wp:paragraph {"className":"margin-top-half margin-bottom-half"} --> <p class="margin-top-half margin-bottom-half">%4$s</p> <!-- /wp:paragraph --> <!-- wp:paragraph {"className":"margin-top-half","style":{"typography":{"fontSize":16}}} --> <p class="margin-top-half" style="font-size:16px"><strong>Ethan</strong><br>Kemp Town</p> <!-- /wp:paragraph --></div> <!-- /wp:jetpack/layout-grid-column --></div> <!-- /wp:jetpack/layout-grid --> <!-- wp:spacer --> <div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --></div></div> <!-- /wp:group --> '; return array( '__file' => 'wp_block', 'title' => esc_html__( 'Quotes', 'full-site-editing' ), 'categories' => array( 'quotes', 'text', 'list' ), 'content' => sprintf( $markup, esc_html__( 'What Our Customers Are Saying', 'full-site-editing' ), esc_html__( 'Reasonably priced good food and drink. The menu favorite that keeps me coming back is the seafood chowder. Really tasty, nice and hot. It&rsquo;s perfect for a chilly winter night! Stuff is always very attentive and helpful. I always enjoy and relax with the calm atmosphere.', 'full-site-editing' ), esc_html__( 'Great food at a great price! Love the seafood plates as well as the salads. Excellent eating experience from walking in the door and being greeted by stuff, seated and drink order taken, was probably 5 minutes. Server was very helpful and friendly. We&rsquo;ll definitely come back!', 'full-site-editing' ), esc_html__( 'The place is awesome with attending staff. Excellent and authentic flavors. Will surely visit this place again. It also is an excellent place to have a business conversation. We really recommend this restaurant.', 'full-site-editing' ) ), 'viewportWidth' => 1280, );
{ "pile_set_name": "Github" }
// run with: // java -cp $ORACLE_HOME/jdbc/lib/ojdbc5.jar:. Client_id import java.sql.*; import oracle.jdbc.OracleConnection; public class Commit2 { public static void main(String[] args) throws InterruptedException { try { // get connection and statement DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:LIN11G", "system","oracle"); Statement stmt = conn.createStatement(); // set metrics for connection (will be sent to server the next rountrip) String[] metrics = new String[OracleConnection.END_TO_END_STATE_INDEX_MAX]; metrics[OracleConnection.END_TO_END_MODULE_INDEX]="Committer"; ((OracleConnection)conn).setEndToEndMetrics(metrics,(short)0); for(int i=1;i<1000000;i++) { ResultSet rs = stmt.executeQuery("UPDATE t SET a=a+1"); //autocommit takes care of this conn.commit(); } Thread.sleep(1000); } catch (SQLException e) { e.printStackTrace(); } } }
{ "pile_set_name": "Github" }
# Copyright 1999-2019 Gentoo Authors # Distributed under the terms of the GNU General Public License v2 EAPI=6 inherit flag-o-matic toolchain-funcs udev versionator MY_PV="$(replace_version_separator 2 -)" DESCRIPTION="Administrative interface for the grsecurity Role Based Access Control system" HOMEPAGE="https://www.grsecurity.net/" SRC_URI="https://dev.gentoo.org/~blueness/hardened-sources/gradm/${PN}-${MY_PV}.tar.gz" LICENSE="GPL-2" SLOT="0" KEYWORDS="~alpha amd64 ~arm ~hppa ~ia64 ~mips ~ppc ~ppc64 ~sparc x86" IUSE="pam" RDEPEND="" DEPEND=" sys-devel/bison sys-devel/flex pam? ( sys-libs/pam )" S=${WORKDIR}/${PN} PATCHES=( "${FILESDIR}"/respect-gentoo-env-r3.patch ) src_prepare() { default sed -i -e "s:/lib/udev:$(get_udevdir):" Makefile || die } src_compile() { local target use pam || target="nopam" emake ${target} CC="$(tc-getCC)" OPT_FLAGS="${CFLAGS}" } src_install() { emake DESTDIR="${D}" install fperms 711 /sbin/gradm } pkg_postinst() { ewarn ewarn "Be sure to set a password with 'gradm -P' before enabling learning mode." ewarn }
{ "pile_set_name": "Github" }
//============================================================================ //ZedGraph Class Library - A Flexible Line Graph/Bar Graph Library in C# //Copyright © 2004 John Champion // //This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //License as published by the Free Software Foundation; either //version 2.1 of the License, or (at your option) any later version. // //This library is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU //Lesser General Public License for more details. // //You should have received a copy of the GNU Lesser General Public //License along with this library; if not, write to the Free Software //Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //============================================================================= using System; using Color = System.Drawing.Color; namespace ZedGraph { /// <summary> /// Class used to get the next color/symbol for GraphPane.AddCurve methods. /// </summary> /// /// <author> Jerry Vos modified by John Champion </author> /// <version> $Revision: 3.4 $ $Date: 2006-06-24 20:26:43 $ </version> public class ColorSymbolRotator { #region Static fields /// <summary> /// The <see cref="Color"/>s <see cref="ColorSymbolRotator"/> /// rotates through. /// </summary> public static readonly Color[] COLORS = new Color[] { Color.Red, Color.Blue, Color.Green, Color.Purple, Color.Cyan, Color.Pink, Color.LightBlue, Color.PaleVioletRed, Color.SeaGreen, Color.Yellow }; /// <summary> /// The <see cref="SymbolType"/>s <see cref="ColorSymbolRotator"/> /// rotates through. /// </summary> public static readonly SymbolType[] SYMBOLS = new SymbolType[] { SymbolType.Circle, SymbolType.Diamond, SymbolType.Plus, SymbolType.Square, SymbolType.Star, SymbolType.Triangle, SymbolType.TriangleDown, SymbolType.XCross, SymbolType.HDash, SymbolType.VDash }; private static ColorSymbolRotator _staticInstance; #endregion #region Fields /// <summary> /// The index of the next color to be used. Note: may be /// > COLORS.Length, it is reset to 0 on the next call if it is. /// </summary> protected int colorIndex = 0; /// <summary> /// The index of the next symbol to be used. Note: may be /// > SYMBOLS.Length, it is reset to 0 on the next call if it is. /// </summary> protected int symbolIndex = 0; #endregion #region Properties /// <summary> /// Retrieves the next color in the rotation Calling this /// method has the side effect of incrementing the color index. /// <seealso cref="NextSymbol"/> /// <seealso cref="NextColorIndex"/> /// </summary> public Color NextColor { get { return COLORS[NextColorIndex]; } } /// <summary> /// Retrieves the index of the next color to be used. Calling this /// method has the side effect of incrementing the color index. /// </summary> public int NextColorIndex { get { if (colorIndex >= COLORS.Length) colorIndex = 0; return colorIndex++; } set { colorIndex = value; } } /// <summary> /// Retrieves the next color in the rotation. Calling this /// method has the side effect of incrementing the symbol index. /// <seealso cref="NextColor"/> /// <seealso cref="NextSymbolIndex"/> /// </summary> public SymbolType NextSymbol { get { return SYMBOLS[NextSymbolIndex]; } } /// <summary> /// Retrieves the index of the next symbol to be used. Calling this /// method has the side effect of incrementing the symbol index. /// </summary> public int NextSymbolIndex { get { if (symbolIndex >= SYMBOLS.Length) symbolIndex = 0; return symbolIndex++; } set { symbolIndex = value; } } /// <summary> /// Retrieves the <see cref="ColorSymbolRotator"/> instance used by the /// static methods. /// <seealso cref="StaticNextColor"/> /// <seealso cref="StaticNextSymbol"/> /// </summary> public static ColorSymbolRotator StaticInstance { get { if (_staticInstance == null) _staticInstance = new ColorSymbolRotator(); return _staticInstance; } } /// <summary> /// Retrieves the next color from this class's static /// <see cref="ColorSymbolRotator"/> instance /// <seealso cref="StaticInstance"/> /// <seealso cref="StaticNextSymbol"/> /// </summary> public static Color StaticNextColor { get { return StaticInstance.NextColor; } } /// <summary> /// Retrieves the next symbol type from this class's static /// <see cref="ColorSymbolRotator"/> instance /// <seealso cref="StaticInstance"/> /// <seealso cref="StaticNextColor"/> /// </summary> public static SymbolType StaticNextSymbol { get { return StaticInstance.NextSymbol; } } #endregion } }
{ "pile_set_name": "Github" }
##### NEW KEYS ##### struct ShapeKey <: Gadfly.GuideElement title::AbstractString labels::Vector{String} pos::Vector visible::Bool end ShapeKey(;title="Shape", labels=String[], pos=[], visible=true) = ShapeKey(title, labels, pos, visible) ShapeKey(v::Nothing) = ShapeKey(visible=false) ShapeKey(title::AbstractString, labels::Vector{String}, pos::Vector) = ShapeKey(title, labels, pos, true) """ Guide.shapekey[(; title="Shape", labels=String[], pos=Float64[])] Guide.shapekey(title, labels, pos) Enable control of the auto-generated shapekey. Set the key `title` and the item `labels`. `pos` overrides [Theme(key_position=)](@ref Gadfly) and can be in either relative (e.g. [0.7w, 0.2h] is the lower right quadrant), absolute (e.g. [0mm, 0mm]), or plot scale (e.g. [0,0]) coordinates. `Guide.shapekey(nothing)` will hide the key. """ const shapekey = ShapeKey function render(guide::ShapeKey, theme::Gadfly.Theme, aes::Gadfly.Aesthetics) (theme.key_position == :none || !guide.visible || isa(aes.shape[1], Function)) && return PositionedGuide[] gpos = guide.pos (theme.key_position == :inside) && isempty(gpos) && (gpos = [0.7w, 0.25h]) # Aesthetics for keys: shape_key_title, shape_label (Function), shape_key_shapes (AbstractDict) nshapes = length(unique(aes.shape)) guide_title = (guide.title≠"Shape" || aes.shape_key_title==nothing) ? guide.title : aes.shape_key_title shape_key_labels = isempty(guide.labels) ? aes.shape_label(1:nshapes) : guide.labels colors = Colorant[] if (aes.shape_key_title !=nothing) && (aes.color_key_title==aes.shape_key_title) colors = collect(keys(aes.color_key_colors)) end shapes = theme.point_shapes[1:nshapes] title_context, title_width = render_key_title2(guide_title, theme) ctxs = render_discrete_key(shape_key_labels, title_context, title_width, theme, shapes=shapes, colors=colors) position, stackable = right_guide_position, true if !isempty(gpos) position, stackable = over_guide_position, false ctxs = [compose(context(), (context(gpos[1],gpos[2]), ctxs[1]))] elseif theme.key_position == :left position = left_guide_position elseif theme.key_position == :top position = top_guide_position elseif theme.key_position == :bottom position = bottom_guide_position end return [PositionedGuide(ctxs, 0, position, stackable)] end function render_discrete_key(labels::Vector{String}, title_ctx::Context, title_width::Measure, theme::Gadfly.Theme; colors=Colorant[], aes_color_label=nothing, shapes=Function[], sizes=Measure[]) n = max(length(colors), length(shapes), length(sizes)) n==0 && (n = length(labels)) isempty(shapes) && (shapes = fill((theme.key_swatch_shape==nothing) ? theme.point_shapes[1] : theme.key_swatch_shape, n)) isempty(colors) && (colors = fill((theme.key_swatch_color==nothing) ? theme.default_color : theme.key_swatch_color, n)) isempty(sizes) && (sizes = fill((theme.key_swatch_size==nothing) ? theme.point_size : theme.key_swatch_size, n)) # only consider layouts with a reasonable number of columns maxcols = theme.key_max_columns < 1 ? 1 : theme.key_max_columns maxcols = min(n, maxcols) extents = text_extents(theme.key_label_font, theme.key_label_font_size, values(labels)...) text_widths, text_heights = first.(extents), last.(extents) ypad = 1.0mm title_height = title_ctx.box.a[2] swatch_size = 2*maximum(sizes) entry_height = max(swatch_size, maximum(text_heights)) + ypad # return a context with a lyout of numcols columns function make_layout(numcols) colrows = Array{Int}(undef, numcols) m = n for i in 1:numcols colrows[i] = ceil(Int, m/(1+numcols-i)) m -= colrows[i] end xpad = 1mm colwidths = Array{Measure}(undef, numcols) m = 0 for (i, nrows) in enumerate(colrows) if m == n colwidths[i] = 0mm else colwidth = maximum(text_widths[m+1:m+nrows]) colwidth += entry_height + xpad colwidths[i] = colwidth m += nrows end end ctxwidth = sum(colwidths) ctxheight = entry_height * colrows[1] + title_height ctxp = ctxpromise() do draw_context yoff = 0.5h - ctxheight/2 outerctx = context() compose!(outerctx, (context(xpad, yoff), title_ctx)) ctx = context(0, yoff+title_height, ctxwidth, ctxheight-title_height, units=UnitBox(0, 0, 1, colrows[1])) m = 0 xpos = 0w for (colwidth, nrows) in zip(colwidths, colrows) x = [0.5cy] clrs = colors[m+1:m+nrows] shps = shapes[m+1:m+nrows] szs = sizes[m+1:m+nrows] swatches_shapes = [f(x, [y-0.5].*cy, [s]) for (y,(f,s)) in enumerate(zip(shps, szs))] sw1 = [(context(), s, fill(c), fillopacity(theme.alphas[1]), stroke(theme.discrete_highlight_color(c))) for (s,c) in zip(swatches_shapes, clrs)] swatches = compose!(context(), linewidth(theme.highlight_width), sw1...) swatch_labels = compose!(context(), text([entry_height+xpad], [0.5:nrows;]*cy, labels[m+1:m+nrows], [hleft], [vcenter]), font(theme.key_label_font), fontsize(theme.key_label_font_size), fill(theme.key_label_color)) col = compose!(context(xpos, 0, colwidth), swatches, swatch_labels) if aes_color_label != nothing classes = [svg_color_class_from_label(aes_color_label([c])[1]) for c in clrs] #class_jscalls = ["data(\"color_class\", \"$(c)\")" for c in classes] compose!(col, svgclass(classes), jscall([""" data(\"color_class\", \"$(c)\") .click(Gadfly.colorkey_swatch_click) """ for c in classes])) end compose!(ctx, col) m += nrows xpos += colwidth end return compose!(outerctx, ctx, # defeat webkit's asinine default drag behavior jscall("drag(function() {}, function() {}, function() {})"), svgclass("guide colorkey")) end return compose!(context(minwidth=max(title_width, ctxwidth), minheight=ctxheight, units=UnitBox()), ctxp) end return map(make_layout, 1:maxcols) end function render_key_title2(title::AbstractString, theme::Gadfly.Theme) title_width, title_height = max_text_extents(theme.key_title_font, theme.key_title_font_size, title) if theme.guide_title_position == :left title_form = text(0.0w, title_height, title, hleft, vbottom) elseif theme.guide_title_position == :center title_form = text(0.5w, title_height, title, hcenter, vbottom) elseif theme.guide_title_position == :right title_form = text(1.0w, title_height, title, hright, vbottom) else error("$(theme.guide_title_position) is not a valid guide title position") end title_padding = 1.5mm title_context = compose!( context(0w, 0h, 1w, title_height + title_padding), title_form, stroke(nothing), font(theme.key_title_font), fontsize(theme.key_title_font_size), fill(theme.key_title_color)) return title_context, title_width end struct SizeKey <: Gadfly.GuideElement title::AbstractString labels::Vector{String} pos::Vector{Compose.MeasureOrNumber} visible::Bool end SizeKey(;title="Size", labels=String[], pos=[], visible=true) = SizeKey(title, labels, pos, visible) SizeKey(v::Nothing) = SizeKey(visible=false) SizeKey(title::AbstractString, labels::Vector{String}, pos::Vector) = SizeKey(title, labels, pos, true) """ Guide.sizekey[(; title="size", labels=String[], pos=[])] Guide.sizekey(title, labels, pos) Enable control of the sizekey. Set the key `title` and the item `labels`. `pos` overrides [Theme(key_position=)](@ref Gadfly) and can be in either relative (e.g. [0.7w, 0.2h] is the lower right quadrant), absolute (e.g. [0mm, 0mm]), or plot scale (e.g. [0,0]) coordinates. Currently `Guide.sizekey` will only work by adding `Scale.size_discrete2` to the plot. `Guide.sizekey(nothing)` will hide the key. """ const sizekey = SizeKey function render(guide::SizeKey, theme::Gadfly.Theme, aes::Gadfly.Aesthetics) (theme.key_position==:none || !guide.visible || aes.size_key_vals===nothing) && return PositionedGuide[] gpos = guide.pos (theme.key_position==:inside) && isempty(gpos) && (gpos = [0.7w, 0.25h]) # Aesthetics for keys: size_key_title, size_label (Function), size_key_vals (AbstractDict) nsizes = length(unique(aes.size)) guide_title = (guide.title≠"Size" || aes.size_key_title===nothing) ? guide.title : aes.size_key_title sizes = collect(keys(aes.size_key_vals)) size_key_labels = isempty(guide.labels) ? aes.size_label(sizes) : guide.labels colors = Colorant[] if (aes.size_key_title≠nothing) && (aes.color_key_title==aes.size_key_title) colors = collect(keys(aes.color_key_colors)) end title_context, title_width = render_key_title2(guide_title, theme) ctxs = render_discrete_key(size_key_labels, title_context, title_width, theme, sizes=sizes, colors=colors) position, stackable = right_guide_position, true if !isempty(gpos) position, stackable = over_guide_position, false ctxs = [compose(context(), (context(gpos[1], gpos[2]), ctxs[1]))] elseif theme.key_position == :left position = left_guide_position elseif theme.key_position == :top position = top_guide_position elseif theme.key_position == :bottom position = bottom_guide_position end return [PositionedGuide(ctxs, 0, position, stackable)] end struct ManualDiscreteKey <: Gadfly.GuideElement title::AbstractString labels::Vector{String} pos::Vector colors::Vector{Colorant} shapes::Vector{Function} sizes::Vector{Measure} visible::Bool end function ManualDiscreteKey(;title="", labels=String[], pos=[], color=Colorant[], shape=Function[], size=Measure[]) CT, ST, SZT = eltype(color), eltype(shape), eltype(size) ncolors, nshapes, nsizes = length(color), length(shape), length(size) n = max(ncolors, nshapes, nsizes) ncolors==1 && (color = repeat(color, n)) nshapes==1 && (shape = repeat(shape, n)) nsizes==1 && (size = repeat(size, n)) theme = Gadfly.current_theme() clrs = CT<:Int ? theme.discrete_colormap(maximum(color))[color] : Gadfly.parse_colorant(color) shps = ST<:Int ? theme.point_shapes[shape] : shape szs = SZT<:Int ? theme.discrete_sizemap(maximum(size))[size] : size cataes = [clrs, shps, szs] notempty = .!isempty.(cataes) if any(notempty) swatches = collect(Tuple, zip(cataes[notempty]...)) !allunique(swatches) && error("Swatches should not be repeated in a manual key") end return ManualDiscreteKey(title, labels, pos, clrs, shps, szs, true) end """ Guide.manual_discrete_key(title::String, labels::Vector{String}; pos=[], color=Colorant[], shape=Function[], size=Measure[]) Manually define a discrete key with the legend `title` and `labels`, and swatch `color`, `shape` and `size`. The swatch aesthetics can be Vectors of specific types (as above), or integer ranges. Integer ranges refer to the order of items in the discrete Theme palettes [Discrete Scales](@ref). Set the key position inside using `pos` (see [`Guide.sizekey`](@ref), [`Guide.shapekey`](@ref)). """ manual_discrete_key(title::AbstractString, labels::Vector{String}; kwargs...) = ManualDiscreteKey(title=title, labels=labels; kwargs...) """ Guide.manual_color_key(title::String, labels::Vector{String}, color::AbstractVector= 1:length(labels); pos=[], shape=Function[], size=Measure[]) Similar to [`Guide.manual_discrete_key`](@ref). `color` can be Ints, or Colors and/or Strings (default is Ints). """ function manual_color_key(title::AbstractString, labels::Vector{String}, color::AbstractVector=1:length(labels); kwargs...) ManualDiscreteKey(title=title, labels=labels, color=color; kwargs...) end function render(guide::ManualDiscreteKey, theme::Gadfly.Theme, aes::Gadfly.Aesthetics) gpos = guide.pos (theme.key_position == :inside) && isempty(gpos) && (gpos = [0.7w, 0.25h]) title_context, title_width = render_key_title2(guide.title, theme) ctxs = render_discrete_key(guide.labels, title_context, title_width, theme, shapes=guide.shapes, colors=guide.colors, sizes=guide.sizes) position, stackable = right_guide_position, true if !isempty(gpos) position, stackable = over_guide_position, false ctxs = [compose(context(), (context(gpos[1],gpos[2]), ctxs[1]))] elseif theme.key_position == :left position = left_guide_position elseif theme.key_position == :top position = top_guide_position elseif theme.key_position == :bottom position = bottom_guide_position end return [PositionedGuide(ctxs, 0, position, stackable)] end
{ "pile_set_name": "Github" }
{ "parent": "create:chromatic_compound", "display": { "icon": { "item": "create:shadow_steel" }, "title": { "translate": "advancement.create.shadow_steel" }, "description": { "translate": "advancement.create.shadow_steel.desc" }, "frame": "goal", "show_toast": true, "announce_to_chat": true, "hidden": false }, "criteria": { "0": { "trigger": "minecraft:inventory_changed", "conditions": { "items": [ { "item": "create:shadow_steel" } ] } } }, "requirements": [ [ "0" ] ] }
{ "pile_set_name": "Github" }
ADD_GEMRB_PLUGIN (STOImporter STOImporter.cpp)
{ "pile_set_name": "Github" }
{ "name": "Xilinx Magnitude_No_L2 L2 Test", "description": [ "Magnitude L2 function example" ], "flow": "vitis", "platform_whitelist": [ "u200", "zcu102", "zcu104" ], "platform_blacklist": [ "u280", "u250", "u50" ], "platform_properties": { "u200": { "host": { "compiler": { "includepaths": [ "$(OPENCV_INCLUDE)" ] }, "linker": { "librarypaths": [ "$(OPENCV_LIB)" ] } } }, "zcu102": { "host": { "compiler": { "includepaths": [ "$(SYSROOT)/usr/include" ], "options": "--sysroot=$(SYSROOT)" }, "linker": { "librarypaths": [ "$(SYSROOT)/usr/lib", "${SYSROOT}/opt/xilinx/xrt/lib" ] } } }, "zcu104": { "host": { "compiler": { "includepaths": [ "$(SYSROOT)/usr/include" ], "options": "--sysroot=$(SYSROOT)" }, "linker": { "librarypaths": [ "$(SYSROOT)/usr/lib", "${SYSROOT}/opt/xilinx/xrt/lib" ] } } } }, "gui": false, "launch": [ { "target": "sw_emu", "cmd_args": "LIB_DIR/data/4k.jpg ", "name": "sw_emu", "ld_library_path": [ "$(OPENCV_LIB)", "$(LD_LIBRARY_PATH)", "$(XILINX_XRT)/lib" ] }, { "target": "hw_emu", "cmd_args": "LIB_DIR/data/128x128.png ", "name": "hw_emu", "ld_library_path": [ "$(OPENCV_LIB)", "$(LD_LIBRARY_PATH)", "$(XILINX_XRT)/lib" ] }, { "target": "hw", "cmd_args": "LIB_DIR/data/4k.jpg ", "name": "hardware_build", "ld_library_path": [ "$(OPENCV_LIB)", "$(LD_LIBRARY_PATH)", "$(XILINX_XRT)/lib" ] } ], "data": [ "LIB_DIR/data/4k.jpg", "LIB_DIR/data/128x128.png" ], "host": { "host_exe": "magnitude", "compiler": { "sources": [ "LIB_DIR/L2/examples/magnitude/xf_magnitude_tb.cpp", "LIB_DIR/ext/xcl2/xcl2.cpp" ], "options": "-O3", "symbols": [ "__SDSVHLS__" ] } }, "v++": { "compiler": { "symbols": [], "clflags": [] } }, "containers": [ { "name": "krnl_magnitude", "accelerators": [ { "name": "magnitude_accel", "location": "LIB_DIR/L2/examples/magnitude/xf_magnitude_accel.cpp" } ] } ], "testinfo": { "disable": false, "jobs": [ { "index": 0, "dependency": [], "env": "", "cmd": "", "max_memory_MB": 32768, "max_time_min": { "vitis_hw_build": 470, "vitis_hw_emu": 470, "vitis_sw_emu": 60, "vitis_hw_run": 30 } } ], "targets": [ "vitis_sw_emu", "vitis_hw_emu", "vitis_hw_build", "vitis_hw_run" ], "category": "full" } }
{ "pile_set_name": "Github" }
// // ======================================================================== // Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // // This program and the accompanying materials are made available under // the terms of the Eclipse Public License 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0 // // This Source Code may also be made available under the following // Secondary Licenses when the conditions for such availability set // forth in the Eclipse Public License, v. 2.0 are satisfied: // the Apache License v2.0 which is available at // https://www.apache.org/licenses/LICENSE-2.0 // // SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 // ======================================================================== // package org.eclipse.jetty.websocket.javax.tests.server.sockets.primitives; import java.io.IOException; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import org.eclipse.jetty.toolchain.test.StackUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @ServerEndpoint("/echo/primitives/byteobject") public class ByteObjectTextSocket { private static final Logger LOG = LoggerFactory.getLogger(ByteObjectTextSocket.class); private Session session; @OnOpen public void onOpen(Session session) { this.session = session; } @OnMessage public void onMessage(Byte b) throws IOException { if (b == null) { session.getAsyncRemote().sendText("Error: Byte is null"); } else { String msg = String.format("0x%02X", b); session.getAsyncRemote().sendText(msg); } } @OnError public void onError(Throwable cause) throws IOException { LOG.warn("Error", cause); session.getBasicRemote().sendText("Exception: " + StackUtils.toString(cause)); } }
{ "pile_set_name": "Github" }
-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDhKPS3wNv6Brxh0nsbsFDZ6M53ZPNr46LqKY4fpU4hoYcVeJCA5 20DAeRJsrmoZ541VsI1KyGhHxhvBDZR0pFgLxCpEttC5ytrL/enUicGvie7hQG1F8 y/u+SRhHwCe6YbytRMvXhOb8ursYWtMxD5Zx5p7kpnscTIkld3dJMcxwIDAQABAoG BAMv1c6g4dYvJKkBaj9YHI1Yhg1W4BqEGtX70YZ/c+CeS0HDso8mA2cjNn+P6mB8q ra+XhZjwFyiCqHl4EVSRL8mEHfCCzblIWX/Lsuaqa5ZXLQt/iifnX+SI9TR0ueObB uWNh/QMpu4o1Jetq2HQ2BvbQxdDn9NdaVNWdz32ANzxAkEA8iQO/Amcraj/9xqlSV DKLBYDWHbou/lMYrgUDB+7Nx67+qFNZ9WGO2DgSI40bG5oZUBzBk7QdoQ7M75fHII 7OwJBAO4MFk3Zw7qHMAKPiGXil5k4t2L7NkKx9lDX+0RT3AbyrWffBdWyQmxPIAYF shxCUHtUdl0zqapMPDJrx8KgU+UCQAa9Oi2JlvK+YWFfPHpt5TKU6kLsDE4vAhE9T lGIEI3YLSMsmhrptnKwn41lZ9AcwosO4CSszOB/jaZDBiKk/UECQQC4a6rX82680s EyKqr8bBkQvqzsxTybXS48IafrnqBmzZnkUBdAIJNvP7nKkJ0VYZbihWQR/tViNx+ n3HJtaTK1AkBzGSTmC6HoYena3KrIevI26PJ1NLxfOl7GbM+asUTGEaGKPghf1HjU 7bvpFmyeeiGeJMyhuk5ycDATc9EJgHXB -----END RSA PRIVATE KEY-----
{ "pile_set_name": "Github" }
// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofInetPktinfo = 0xc sizeofSockExtendedErr = 0x10 sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 sizeofICMPFilter = 0x4 sizeofSockFprog = 0x10 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type inetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpFilter struct { Data uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [6]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.tools.jconsole; import java.awt.*; import java.beans.*; import java.lang.reflect.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.plaf.basic.*; /** * This class is a temporary workaround for bug 4834918: * Win L&F: JInternalFrame should merge with JMenuBar when maximized. * It is not a general solution, but intended for use within the * limited scope of JConsole when running with XP/Vista styles. */ @SuppressWarnings("serial") public class MaximizableInternalFrame extends JInternalFrame { private boolean isXP; private JFrame mainFrame; private JMenuBar mainMenuBar; private String mainTitle; private JComponent titlePane; private Border normalBorder; private PropertyChangeListener pcl; public MaximizableInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable, boolean iconifiable) { super(title, resizable, closable, maximizable, iconifiable); init(); } private void init() { normalBorder = getBorder(); isXP = normalBorder.getClass().getName().endsWith("XPBorder"); if (isXP) { setRootPaneCheckingEnabled(false); titlePane = ((BasicInternalFrameUI)getUI()).getNorthPane(); if (pcl == null) { pcl = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent ev) { String prop = ev.getPropertyName(); if (prop.equals("icon") || prop.equals("maximum") || prop.equals("closed")) { updateFrame(); } } }; addPropertyChangeListener(pcl); } } else if (pcl != null) { removePropertyChangeListener(pcl); pcl = null; } } private void updateFrame() { JFrame mainFrame; if (!isXP || (mainFrame = getMainFrame()) == null) { return; } JMenuBar menuBar = getMainMenuBar(); BasicInternalFrameUI ui = (BasicInternalFrameUI)getUI(); if (isMaximum() && !isIcon() && !isClosed()) { if (ui.getNorthPane() != null) { // Merge title bar into menu bar mainTitle = mainFrame.getTitle(); mainFrame.setTitle(mainTitle + " - " + getTitle()); if (menuBar != null) { // Move buttons to menu bar updateButtonStates(); menuBar.add(Box.createGlue()); for (Component c : titlePane.getComponents()) { if (c instanceof JButton) { menuBar.add(c); } else if (c instanceof JLabel) { // This is the system menu icon menuBar.add(Box.createHorizontalStrut(3), 0); menuBar.add(c, 1); menuBar.add(Box.createHorizontalStrut(3), 2); } } ui.setNorthPane(null); setBorder(null); } } } else { if (ui.getNorthPane() == null) { // Restore title bar mainFrame.setTitle(mainTitle); if (menuBar != null) { // Move buttons back to title bar for (Component c : menuBar.getComponents()) { if (c instanceof JButton || c instanceof JLabel) { titlePane.add(c); } else if (c instanceof Box.Filler) { menuBar.remove(c); } } menuBar.repaint(); updateButtonStates(); ui.setNorthPane(titlePane); setBorder(normalBorder); } } } } public void updateUI() { boolean isMax = (isXP && getBorder() == null); if (isMax) { try { setMaximum(false); } catch (PropertyVetoException ex) { } } super.updateUI(); init(); if (isMax) { try { setMaximum(true); } catch (PropertyVetoException ex) { } } } private JFrame getMainFrame() { if (mainFrame == null) { JDesktopPane desktop = getDesktopPane(); if (desktop != null) { mainFrame = (JFrame)SwingUtilities.getWindowAncestor(desktop); } } return mainFrame; } private JMenuBar getMainMenuBar() { if (mainMenuBar == null) { JFrame mainFrame = getMainFrame(); if (mainFrame != null) { mainMenuBar = mainFrame.getJMenuBar(); if (mainMenuBar != null && !(mainMenuBar.getLayout() instanceof FixedMenuBarLayout)) { mainMenuBar.setLayout(new FixedMenuBarLayout(mainMenuBar, BoxLayout.X_AXIS)); } } } return mainMenuBar; } public void setTitle(String title) { if (isXP && isMaximum()) { if (getMainFrame() != null) { getMainFrame().setTitle(mainTitle + " - " + title); } } super.setTitle(title); } private class FixedMenuBarLayout extends BoxLayout { public FixedMenuBarLayout(Container target, int axis) { super(target, axis); } public void layoutContainer(Container target) { super.layoutContainer(target); for (Component c : target.getComponents()) { if (c instanceof JButton) { int y = (target.getHeight() - c.getHeight()) / 2; c.setLocation(c.getX(), Math.max(2, y)); } } } } // The rest of this class is messy and should not be relied upon. It // uses reflection to access private, undocumented, and unsupported // classes and fields. // // Install icon wrappers to display MDI icons when the buttons // are in the menubar. // // Please note that this will very likely fail in a future version // of Swing, but at least it should fail silently. // private static Object WP_MINBUTTON, WP_RESTOREBUTTON, WP_CLOSEBUTTON, WP_MDIMINBUTTON, WP_MDIRESTOREBUTTON, WP_MDICLOSEBUTTON; static { if (JConsole.IS_WIN) { try { Class<?> Part = Class.forName("com.sun.java.swing.plaf.windows.TMSchema$Part"); if (Part != null) { WP_MINBUTTON = Part.getField("WP_MINBUTTON").get(null); WP_RESTOREBUTTON = Part.getField("WP_RESTOREBUTTON").get(null); WP_CLOSEBUTTON = Part.getField("WP_CLOSEBUTTON").get(null); WP_MDIMINBUTTON = Part.getField("WP_MDIMINBUTTON").get(null); WP_MDIRESTOREBUTTON = Part.getField("WP_MDIRESTOREBUTTON").get(null); WP_MDICLOSEBUTTON = Part.getField("WP_MDICLOSEBUTTON").get(null); } for (String str : new String[] { "maximize", "minimize", "iconify", "close" }) { String key = "InternalFrame." + str + "Icon"; UIManager.put(key, new MDIButtonIcon(UIManager.getIcon(key))); } } catch (ClassNotFoundException ex) { if (JConsole.debug) { ex.printStackTrace(); } } catch (NoSuchFieldException ex) { if (JConsole.debug) { ex.printStackTrace(); } } catch (IllegalAccessException ex) { if (JConsole.debug) { ex.printStackTrace(); } } } } // A wrapper class for the title pane button icons. // This code should really go in the WindowsIconsFactory class. private static class MDIButtonIcon implements Icon { Icon windowsIcon; Field part; MDIButtonIcon(Icon icon) { windowsIcon = icon; if (WP_MINBUTTON != null) { try { part = windowsIcon.getClass().getDeclaredField("part"); part.setAccessible(true); } catch (NoSuchFieldException ex) { if (JConsole.debug) { ex.printStackTrace(); } } } } public void paintIcon(Component c, Graphics g, int x, int y) { if (part != null) { try { Object v = part.get(windowsIcon); if (c.getParent() instanceof JMenuBar) { // Use MDI icons if (v == WP_MINBUTTON) { part.set(windowsIcon, WP_MDIMINBUTTON); } else if (v == WP_RESTOREBUTTON) { part.set(windowsIcon, WP_MDIRESTOREBUTTON); } else if (v == WP_CLOSEBUTTON) { part.set(windowsIcon, WP_MDICLOSEBUTTON); } } else { // Use regular icons if (v == WP_MDIMINBUTTON) { part.set(windowsIcon, WP_MINBUTTON); } else if (v == WP_MDIRESTOREBUTTON) { part.set(windowsIcon, WP_RESTOREBUTTON); } else if (v == WP_MDICLOSEBUTTON) { part.set(windowsIcon, WP_CLOSEBUTTON); } } } catch (IllegalAccessException ex) { if (JConsole.debug) { ex.printStackTrace(); } } } windowsIcon.paintIcon(c, g, x, y); } public int getIconWidth(){ return windowsIcon.getIconWidth(); } public int getIconHeight() { return windowsIcon.getIconHeight(); } } // Use reflection to invoke protected methods in BasicInternalFrameTitlePane private Method setButtonIcons; private Method enableActions; private void updateButtonStates() { try { if (setButtonIcons == null) { Class<? extends JComponent> cls = titlePane.getClass(); Class<?> superCls = cls.getSuperclass(); setButtonIcons = cls.getDeclaredMethod("setButtonIcons"); enableActions = superCls.getDeclaredMethod("enableActions"); setButtonIcons.setAccessible(true); enableActions.setAccessible(true); } setButtonIcons.invoke(titlePane); enableActions.invoke(titlePane); } catch (Exception ex) { if (JConsole.debug) { ex.printStackTrace(); } } } }
{ "pile_set_name": "Github" }
<template> <span> <v-tooltip top color="#000000" max-width="600"> <template v-slot:activator="{ on }"> <v-icon x-small allow-overflow :color="color" dark v-on="on">fas fa-info-circle</v-icon> </template> <span><slot /></span> </v-tooltip> </span> </template> <style lang="scss" scoped> .csTooltip { font-size: 1rem; } </style> <script> export default { props: { text: String, color: { type: String, default: "blue darken-3" } } }; </script>
{ "pile_set_name": "Github" }
/* * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package com.sun.enterprise.v3.services.impl.monitor.stats; import java.util.concurrent.atomic.AtomicLong; import org.glassfish.external.probe.provider.annotations.ProbeListener; import org.glassfish.external.probe.provider.annotations.ProbeParam; import org.glassfish.external.statistics.CountStatistic; import org.glassfish.external.statistics.impl.CountStatisticImpl; import org.glassfish.gmbal.AMXMetadata; import org.glassfish.gmbal.Description; import org.glassfish.gmbal.ManagedAttribute; import org.glassfish.gmbal.ManagedObject; import org.glassfish.grizzly.http.server.filecache.FileCache; /** * File cache statistics * * @author Alexey Stashok */ @AMXMetadata(type="file-cache-mon", group="monitoring") @ManagedObject @Description("File Cache Statistics") public class FileCacheStatsProvider implements StatsProvider { private final String name; protected final CountStatisticImpl hitsCount = new CountStatisticImpl("HitsCount", "count" , "Number of cache lookup hits"); protected final CountStatisticImpl missesCount = new CountStatisticImpl("MissesCount", "count", "Number of cache lookup misses"); protected final CountStatisticImpl infoHitsCount = new CountStatisticImpl("InfoHitsCount", "count", "Number of hits on cached file info"); protected final CountStatisticImpl infoMissesCount = new CountStatisticImpl("InfoMissesCount", "count", "Number of misses on cached file info"); protected final CountStatisticImpl contentHitsCount = new CountStatisticImpl("ContentHitsCount", "count", "Number of hits on cached file content"); protected final CountStatisticImpl contentMissesCount = new CountStatisticImpl("ContentMissesCount", "count", "Number of misses on cached file content"); protected final CountStatisticImpl openCacheEntriesCount = new CountStatisticImpl("OpenCacheEntriesCount", "count", "Number of current open cache entries"); protected final AtomicLong heapSize = new AtomicLong(); protected final AtomicLong mappedMemorySize = new AtomicLong(); protected final AtomicLong maxHeapSize = new AtomicLong(); protected final AtomicLong maxMappedMemorySize = new AtomicLong(); protected volatile FileCache fileCache; public FileCacheStatsProvider(String name) { this.name = name; } @Override public Object getStatsObject() { return fileCache; } @Override public void setStatsObject(Object object) { if (object instanceof FileCache) { fileCache = (FileCache) object; } else { fileCache = null; } } @ManagedAttribute(id = "hits") @Description("Number of cache lookup hits") public CountStatistic getHitsCount() { return hitsCount; } @ManagedAttribute(id = "misses") @Description("Number of cache lookup misses") public CountStatistic getMissesCount() { return missesCount; } @ManagedAttribute(id = "infohits") @Description("Number of hits on cached file info") public CountStatistic getInfoHitsCount() { return infoHitsCount; } @ManagedAttribute(id = "infomisses") @Description("Number of misses on cached file info") public CountStatistic getInfoMissesCount() { return infoMissesCount; } @ManagedAttribute(id = "contenthits") @Description("Number of hits on cached file content") public CountStatistic getContentHitsCount() { return contentHitsCount; } @ManagedAttribute(id = "contentmisses") @Description("Number of misses on cached file content") public CountStatistic getContentMissesCount() { return contentMissesCount; } @ManagedAttribute(id = "opencacheentries") @Description("Number of current open cache entries") public CountStatistic getOpenCacheEntriesCount() { return openCacheEntriesCount; } @ManagedAttribute(id = "heapsize") @Description("Current cache size in bytes") public CountStatistic getHeapSize() { final CountStatisticImpl stats = new CountStatisticImpl("HeapSize", "byte(s)", "Current cache size in bytes"); stats.setCount(heapSize.get()); return stats; } @ManagedAttribute(id = "maxheapsize") @Description("Maximum heap space used for cache") public CountStatistic getMaxHeapSize() { final CountStatisticImpl stats = new CountStatisticImpl("MaxHeapSize", "byte(s)", "Maximum heap space used for cache"); stats.setCount(maxHeapSize.get()); return stats; } @ManagedAttribute(id = "mappedmemorysize") @Description("Size of mapped memory used for caching") public CountStatistic getMappedMemorySize() { final CountStatisticImpl stats = new CountStatisticImpl( "MappedMemorySize", "byte(s)", "Size of mapped memory used for caching"); stats.setCount(mappedMemorySize.get()); return stats; } @ManagedAttribute(id = "maxmappedmemorysize") @Description("Maximum memory map size used for caching") public CountStatistic getMaxMappedMemorySize() { final CountStatisticImpl stats = new CountStatisticImpl( "MaxMappedMemorySize", "byte(s)", "Maximum memory map size used for caching"); stats.setCount(maxMappedMemorySize.get()); return stats; } @ProbeListener("glassfish:kernel:file-cache:countHitEvent") public void countHitEvent(@ProbeParam("fileCacheName") String fileCacheName) { if (name.equals(fileCacheName)) { hitsCount.increment(); } } @ProbeListener("glassfish:kernel:file-cache:countMissEvent") public void countMissEvent(@ProbeParam("fileCacheName") String fileCacheName) { if (name.equals(fileCacheName)) { missesCount.increment(); } } @ProbeListener("glassfish:kernel:file-cache:countInfoHitEvent") public void countInfoHitEvent(@ProbeParam("fileCacheName") String fileCacheName) { if (name.equals(fileCacheName)) { infoHitsCount.increment(); } } @ProbeListener("glassfish:kernel:file-cache:countInfoMissEvent") public void countInfoMissEvent(@ProbeParam("fileCacheName") String fileCacheName) { if (name.equals(fileCacheName)) { infoMissesCount.increment(); } } @ProbeListener("glassfish:kernel:file-cache:countContentHitEvent") public void countContentHitEvent(@ProbeParam("fileCacheName") String fileCacheName) { if (name.equals(fileCacheName)) { contentHitsCount.increment(); } } @ProbeListener("glassfish:kernel:file-cache:countContentMissEvent") public void countContentMissEvent(@ProbeParam("fileCacheName") String fileCacheName) { if (name.equals(fileCacheName)) { contentMissesCount.increment(); } } @ProbeListener("glassfish:kernel:file-cache:incOpenCacheEntriesEvent") public void incOpenCacheEntriesEvent(@ProbeParam("fileCacheName") String fileCacheName) { if (name.equals(fileCacheName)) { openCacheEntriesCount.increment(); } } @ProbeListener("glassfish:kernel:file-cache:decOpenCacheEntriesEvent") public void decOpenCacheEntriesEvent(@ProbeParam("fileCacheName") String fileCacheName) { if (name.equals(fileCacheName)) { openCacheEntriesCount.decrement(); } } @ProbeListener("glassfish:kernel:file-cache:addHeapSizeEvent") public void addHeapSizeEvent(@ProbeParam("fileCacheName") String fileCacheName, @ProbeParam("size") long size) { if (name.equals(fileCacheName)) { final long newSize = heapSize.addAndGet(size); while (true) { final long maxSize = maxHeapSize.get(); if (newSize > maxSize) { if (maxHeapSize.compareAndSet(maxSize, newSize)) { break; } } else { break; } } } } @ProbeListener("glassfish:kernel:file-cache:subHeapSizeEvent") public void subHeapSizeEvent(@ProbeParam("fileCacheName") String fileCacheName, @ProbeParam("size") long size) { if (name.equals(fileCacheName)) { heapSize.addAndGet(-size); } } @ProbeListener("glassfish:kernel:file-cache:addMappedMemorySizeEvent") public void addMappedMemorySizeEvent( @ProbeParam("fileCacheName") String fileCacheName, @ProbeParam("size") long size) { if (name.equals(fileCacheName)) { final long newSize = mappedMemorySize.addAndGet(size); while (true) { final long maxMemSize = maxMappedMemorySize.get(); if (newSize > maxMemSize) { if (maxMappedMemorySize.compareAndSet(maxMemSize, newSize)) { break; } } else { break; } } } } @ProbeListener("glassfish:kernel:file-cache:subMappedMemorySizeEvent") public void subMappedMemorySizeEvent( @ProbeParam("fileCacheName") String fileCacheName, @ProbeParam("size") long size) { if (name.equals(fileCacheName)) { mappedMemorySize.addAndGet(-size); } } }
{ "pile_set_name": "Github" }
Date: Fri, 1 Jun 2001 16:38:17 -0500 (CDT) From: Chris Lattner <[email protected]> To: Vikram S. Adve <[email protected]> Subject: Interesting: GCC passes Take a look at this document (which describes the order of optimizations that GCC performs): http://gcc.gnu.org/onlinedocs/gcc_17.html The rundown is that after RTL generation, the following happens: 1 . [t] jump optimization (jumps to jumps, etc) 2 . [t] Delete unreachable code 3 . Compute live ranges for CSE 4 . [t] Jump threading (jumps to jumps with identical or inverse conditions) 5 . [t] CSE 6 . *** Conversion to SSA 7 . [t] SSA Based DCE 8 . *** Conversion to LLVM 9 . UnSSA 10. GCSE 11. LICM 12. Strength Reduction 13. Loop unrolling 14. [t] CSE 15. [t] DCE 16. Instruction combination, register movement, scheduling... etc. I've marked optimizations with a [t] to indicate things that I believe to be relatively trivial to implement in LLVM itself. The time consuming things to reimplement would be SSA based PRE, Strength reduction & loop unrolling... these would be the major things we would miss out on if we did LLVM creation from tree code [inlining and other high level optimizations are done on the tree representation]. Given the lack of "strong" optimizations that would take a long time to reimplement, I am leaning a bit more towards creating LLVM from the tree code. Especially given that SGI has GPL'd their compiler, including many SSA based optimizations that could be adapted (besides the fact that their code looks MUCH nicer than GCC :) Even if we choose to do LLVM code emission from RTL, we will almost certainly want to move LLVM emission from step 8 down until at least CSE has been rerun... which causes me to wonder if the SSA generation code will still work (due to global variable dependencies and stuff). I assume that it can be made to work, but might be a little more involved than we would like. I'm continuing to look at the Tree -> RTL code. It is pretty gross because they do some of the translation a statement at a time, and some of it a function at a time... I'm not quite clear why and how the distinction is drawn, but it does not appear that there is a wonderful place to attach extra info. Anyways, I'm proceeding with the RTL -> LLVM conversion phase for now. We can talk about this more on Monday. Wouldn't it be nice if there were a obvious decision to be made? :) -Chris
{ "pile_set_name": "Github" }
/* $Id: bkm_a8.c,v 1.22.2.4 2004/01/15 14:02:34 keil Exp $ * * low level stuff for Scitel Quadro (4*S0, passive) * * Author Roland Klabunde * Copyright by Roland Klabunde <[email protected]> * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #include <linux/init.h> #include "hisax.h" #include "isac.h" #include "ipac.h" #include "hscx.h" #include "isdnl1.h" #include <linux/pci.h> #include "bkm_ax.h" #define ATTEMPT_PCI_REMAPPING /* Required for PLX rev 1 */ static const char sct_quadro_revision[] = "$Revision: 1.22.2.4 $"; static const char *sct_quadro_subtypes[] = { "", "#1", "#2", "#3", "#4" }; #define wordout(addr, val) outw(val, addr) #define wordin(addr) inw(addr) static inline u_char readreg(unsigned int ale, unsigned int adr, u_char off) { register u_char ret; wordout(ale, off); ret = wordin(adr) & 0xFF; return (ret); } static inline void readfifo(unsigned int ale, unsigned int adr, u_char off, u_char *data, int size) { int i; wordout(ale, off); for (i = 0; i < size; i++) data[i] = wordin(adr) & 0xFF; } static inline void writereg(unsigned int ale, unsigned int adr, u_char off, u_char data) { wordout(ale, off); wordout(adr, data); } static inline void writefifo(unsigned int ale, unsigned int adr, u_char off, u_char *data, int size) { int i; wordout(ale, off); for (i = 0; i < size; i++) wordout(adr, data[i]); } /* Interface functions */ static u_char ReadISAC(struct IsdnCardState *cs, u_char offset) { return (readreg(cs->hw.ax.base, cs->hw.ax.data_adr, offset | 0x80)); } static void WriteISAC(struct IsdnCardState *cs, u_char offset, u_char value) { writereg(cs->hw.ax.base, cs->hw.ax.data_adr, offset | 0x80, value); } static void ReadISACfifo(struct IsdnCardState *cs, u_char *data, int size) { readfifo(cs->hw.ax.base, cs->hw.ax.data_adr, 0x80, data, size); } static void WriteISACfifo(struct IsdnCardState *cs, u_char *data, int size) { writefifo(cs->hw.ax.base, cs->hw.ax.data_adr, 0x80, data, size); } static u_char ReadHSCX(struct IsdnCardState *cs, int hscx, u_char offset) { return (readreg(cs->hw.ax.base, cs->hw.ax.data_adr, offset + (hscx ? 0x40 : 0))); } static void WriteHSCX(struct IsdnCardState *cs, int hscx, u_char offset, u_char value) { writereg(cs->hw.ax.base, cs->hw.ax.data_adr, offset + (hscx ? 0x40 : 0), value); } /* Set the specific ipac to active */ static void set_ipac_active(struct IsdnCardState *cs, u_int active) { /* set irq mask */ writereg(cs->hw.ax.base, cs->hw.ax.data_adr, IPAC_MASK, active ? 0xc0 : 0xff); } /* * fast interrupt HSCX stuff goes here */ #define READHSCX(cs, nr, reg) readreg(cs->hw.ax.base, \ cs->hw.ax.data_adr, reg + (nr ? 0x40 : 0)) #define WRITEHSCX(cs, nr, reg, data) writereg(cs->hw.ax.base, \ cs->hw.ax.data_adr, reg + (nr ? 0x40 : 0), data) #define READHSCXFIFO(cs, nr, ptr, cnt) readfifo(cs->hw.ax.base, \ cs->hw.ax.data_adr, (nr ? 0x40 : 0), ptr, cnt) #define WRITEHSCXFIFO(cs, nr, ptr, cnt) writefifo(cs->hw.ax.base, \ cs->hw.ax.data_adr, (nr ? 0x40 : 0), ptr, cnt) #include "hscx_irq.c" static irqreturn_t bkm_interrupt_ipac(int intno, void *dev_id) { struct IsdnCardState *cs = dev_id; u_char ista, val, icnt = 5; u_long flags; spin_lock_irqsave(&cs->lock, flags); ista = readreg(cs->hw.ax.base, cs->hw.ax.data_adr, IPAC_ISTA); if (!(ista & 0x3f)) { /* not this IPAC */ spin_unlock_irqrestore(&cs->lock, flags); return IRQ_NONE; } Start_IPAC: if (cs->debug & L1_DEB_IPAC) debugl1(cs, "IPAC ISTA %02X", ista); if (ista & 0x0f) { val = readreg(cs->hw.ax.base, cs->hw.ax.data_adr, HSCX_ISTA + 0x40); if (ista & 0x01) val |= 0x01; if (ista & 0x04) val |= 0x02; if (ista & 0x08) val |= 0x04; if (val) { hscx_int_main(cs, val); } } if (ista & 0x20) { val = 0xfe & readreg(cs->hw.ax.base, cs->hw.ax.data_adr, ISAC_ISTA | 0x80); if (val) { isac_interrupt(cs, val); } } if (ista & 0x10) { val = 0x01; isac_interrupt(cs, val); } ista = readreg(cs->hw.ax.base, cs->hw.ax.data_adr, IPAC_ISTA); if ((ista & 0x3f) && icnt) { icnt--; goto Start_IPAC; } if (!icnt) printk(KERN_WARNING "HiSax: Scitel Quadro (%s) IRQ LOOP\n", sct_quadro_subtypes[cs->subtyp]); writereg(cs->hw.ax.base, cs->hw.ax.data_adr, IPAC_MASK, 0xFF); writereg(cs->hw.ax.base, cs->hw.ax.data_adr, IPAC_MASK, 0xC0); spin_unlock_irqrestore(&cs->lock, flags); return IRQ_HANDLED; } static void release_io_sct_quadro(struct IsdnCardState *cs) { release_region(cs->hw.ax.base & 0xffffffc0, 128); if (cs->subtyp == SCT_1) release_region(cs->hw.ax.plx_adr, 64); } static void enable_bkm_int(struct IsdnCardState *cs, unsigned bEnable) { if (cs->typ == ISDN_CTYPE_SCT_QUADRO) { if (bEnable) wordout(cs->hw.ax.plx_adr + 0x4C, (wordin(cs->hw.ax.plx_adr + 0x4C) | 0x41)); else wordout(cs->hw.ax.plx_adr + 0x4C, (wordin(cs->hw.ax.plx_adr + 0x4C) & ~0x41)); } } static void reset_bkm(struct IsdnCardState *cs) { if (cs->subtyp == SCT_1) { wordout(cs->hw.ax.plx_adr + 0x50, (wordin(cs->hw.ax.plx_adr + 0x50) & ~4)); mdelay(10); /* Remove the soft reset */ wordout(cs->hw.ax.plx_adr + 0x50, (wordin(cs->hw.ax.plx_adr + 0x50) | 4)); mdelay(10); } } static int BKM_card_msg(struct IsdnCardState *cs, int mt, void *arg) { u_long flags; switch (mt) { case CARD_RESET: spin_lock_irqsave(&cs->lock, flags); /* Disable ints */ set_ipac_active(cs, 0); enable_bkm_int(cs, 0); reset_bkm(cs); spin_unlock_irqrestore(&cs->lock, flags); return (0); case CARD_RELEASE: /* Sanity */ spin_lock_irqsave(&cs->lock, flags); set_ipac_active(cs, 0); enable_bkm_int(cs, 0); spin_unlock_irqrestore(&cs->lock, flags); release_io_sct_quadro(cs); return (0); case CARD_INIT: spin_lock_irqsave(&cs->lock, flags); cs->debug |= L1_DEB_IPAC; set_ipac_active(cs, 1); inithscxisac(cs, 3); /* Enable ints */ enable_bkm_int(cs, 1); spin_unlock_irqrestore(&cs->lock, flags); return (0); case CARD_TEST: return (0); } return (0); } static int sct_alloc_io(u_int adr, u_int len) { if (!request_region(adr, len, "scitel")) { printk(KERN_WARNING "HiSax: Scitel port %#x-%#x already in use\n", adr, adr + len); return (1); } return (0); } static struct pci_dev *dev_a8 = NULL; static u16 sub_vendor_id = 0; static u16 sub_sys_id = 0; static u_char pci_bus = 0; static u_char pci_device_fn = 0; static u_char pci_irq = 0; int setup_sct_quadro(struct IsdnCard *card) { struct IsdnCardState *cs = card->cs; char tmp[64]; u_int found = 0; u_int pci_ioaddr1, pci_ioaddr2, pci_ioaddr3, pci_ioaddr4, pci_ioaddr5; strcpy(tmp, sct_quadro_revision); printk(KERN_INFO "HiSax: T-Berkom driver Rev. %s\n", HiSax_getrev(tmp)); if (cs->typ == ISDN_CTYPE_SCT_QUADRO) { cs->subtyp = SCT_1; /* Preset */ } else return (0); /* Identify subtype by para[0] */ if (card->para[0] >= SCT_1 && card->para[0] <= SCT_4) cs->subtyp = card->para[0]; else { printk(KERN_WARNING "HiSax: Scitel Quadro: Invalid " "subcontroller in configuration, default to 1\n"); return (0); } if ((cs->subtyp != SCT_1) && ((sub_sys_id != PCI_DEVICE_ID_BERKOM_SCITEL_QUADRO) || (sub_vendor_id != PCI_VENDOR_ID_BERKOM))) return (0); if (cs->subtyp == SCT_1) { while ((dev_a8 = hisax_find_pci_device(PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_9050, dev_a8))) { sub_vendor_id = dev_a8->subsystem_vendor; sub_sys_id = dev_a8->subsystem_device; if ((sub_sys_id == PCI_DEVICE_ID_BERKOM_SCITEL_QUADRO) && (sub_vendor_id == PCI_VENDOR_ID_BERKOM)) { if (pci_enable_device(dev_a8)) return (0); pci_ioaddr1 = pci_resource_start(dev_a8, 1); pci_irq = dev_a8->irq; pci_bus = dev_a8->bus->number; pci_device_fn = dev_a8->devfn; found = 1; break; } } if (!found) { printk(KERN_WARNING "HiSax: Scitel Quadro (%s): " "Card not found\n", sct_quadro_subtypes[cs->subtyp]); return (0); } #ifdef ATTEMPT_PCI_REMAPPING /* HACK: PLX revision 1 bug: PLX address bit 7 must not be set */ if ((pci_ioaddr1 & 0x80) && (dev_a8->revision == 1)) { printk(KERN_WARNING "HiSax: Scitel Quadro (%s): " "PLX rev 1, remapping required!\n", sct_quadro_subtypes[cs->subtyp]); /* Restart PCI negotiation */ pci_write_config_dword(dev_a8, PCI_BASE_ADDRESS_1, (u_int)-1); /* Move up by 0x80 byte */ pci_ioaddr1 += 0x80; pci_ioaddr1 &= PCI_BASE_ADDRESS_IO_MASK; pci_write_config_dword(dev_a8, PCI_BASE_ADDRESS_1, pci_ioaddr1); dev_a8->resource[1].start = pci_ioaddr1; } #endif /* End HACK */ } if (!pci_irq) { /* IRQ range check ?? */ printk(KERN_WARNING "HiSax: Scitel Quadro (%s): No IRQ\n", sct_quadro_subtypes[cs->subtyp]); return (0); } pci_read_config_dword(dev_a8, PCI_BASE_ADDRESS_1, &pci_ioaddr1); pci_read_config_dword(dev_a8, PCI_BASE_ADDRESS_2, &pci_ioaddr2); pci_read_config_dword(dev_a8, PCI_BASE_ADDRESS_3, &pci_ioaddr3); pci_read_config_dword(dev_a8, PCI_BASE_ADDRESS_4, &pci_ioaddr4); pci_read_config_dword(dev_a8, PCI_BASE_ADDRESS_5, &pci_ioaddr5); if (!pci_ioaddr1 || !pci_ioaddr2 || !pci_ioaddr3 || !pci_ioaddr4 || !pci_ioaddr5) { printk(KERN_WARNING "HiSax: Scitel Quadro (%s): " "No IO base address(es)\n", sct_quadro_subtypes[cs->subtyp]); return (0); } pci_ioaddr1 &= PCI_BASE_ADDRESS_IO_MASK; pci_ioaddr2 &= PCI_BASE_ADDRESS_IO_MASK; pci_ioaddr3 &= PCI_BASE_ADDRESS_IO_MASK; pci_ioaddr4 &= PCI_BASE_ADDRESS_IO_MASK; pci_ioaddr5 &= PCI_BASE_ADDRESS_IO_MASK; /* Take over */ cs->irq = pci_irq; cs->irq_flags |= IRQF_SHARED; /* pci_ioaddr1 is unique to all subdevices */ /* pci_ioaddr2 is for the fourth subdevice only */ /* pci_ioaddr3 is for the third subdevice only */ /* pci_ioaddr4 is for the second subdevice only */ /* pci_ioaddr5 is for the first subdevice only */ cs->hw.ax.plx_adr = pci_ioaddr1; /* Enter all ipac_base addresses */ switch (cs->subtyp) { case 1: cs->hw.ax.base = pci_ioaddr5 + 0x00; if (sct_alloc_io(pci_ioaddr1, 128)) return (0); if (sct_alloc_io(pci_ioaddr5, 64)) return (0); /* disable all IPAC */ writereg(pci_ioaddr5, pci_ioaddr5 + 4, IPAC_MASK, 0xFF); writereg(pci_ioaddr4 + 0x08, pci_ioaddr4 + 0x0c, IPAC_MASK, 0xFF); writereg(pci_ioaddr3 + 0x10, pci_ioaddr3 + 0x14, IPAC_MASK, 0xFF); writereg(pci_ioaddr2 + 0x20, pci_ioaddr2 + 0x24, IPAC_MASK, 0xFF); break; case 2: cs->hw.ax.base = pci_ioaddr4 + 0x08; if (sct_alloc_io(pci_ioaddr4, 64)) return (0); break; case 3: cs->hw.ax.base = pci_ioaddr3 + 0x10; if (sct_alloc_io(pci_ioaddr3, 64)) return (0); break; case 4: cs->hw.ax.base = pci_ioaddr2 + 0x20; if (sct_alloc_io(pci_ioaddr2, 64)) return (0); break; } /* For isac and hscx data path */ cs->hw.ax.data_adr = cs->hw.ax.base + 4; printk(KERN_INFO "HiSax: Scitel Quadro (%s) configured at " "0x%.4lX, 0x%.4lX, 0x%.4lX and IRQ %d\n", sct_quadro_subtypes[cs->subtyp], cs->hw.ax.plx_adr, cs->hw.ax.base, cs->hw.ax.data_adr, cs->irq); test_and_set_bit(HW_IPAC, &cs->HW_Flags); cs->readisac = &ReadISAC; cs->writeisac = &WriteISAC; cs->readisacfifo = &ReadISACfifo; cs->writeisacfifo = &WriteISACfifo; cs->BC_Read_Reg = &ReadHSCX; cs->BC_Write_Reg = &WriteHSCX; cs->BC_Send_Data = &hscx_fill_fifo; cs->cardmsg = &BKM_card_msg; cs->irq_func = &bkm_interrupt_ipac; printk(KERN_INFO "HiSax: Scitel Quadro (%s): IPAC Version %d\n", sct_quadro_subtypes[cs->subtyp], readreg(cs->hw.ax.base, cs->hw.ax.data_adr, IPAC_ID)); return (1); }
{ "pile_set_name": "Github" }
package basexxx import ( "testing" "github.com/stretchr/testify/assert" ) func TestBase62(t *testing.T) { var ui uint64 = 123456 str := Base62(ui) assert.Equal(t, str, "W7E") } func TestBytesToBase62(t *testing.T) { bs := []byte{255, 200, 155, 100, 55, 11, 0, 255, 200} str := BytesToBase62(bs) assert.Equal(t, str, "LxWs8cX6Xt93E") } func TestParseBase62(t *testing.T) { s := "W7E" ui, err := ParseBase62(s) assert.NoError(t, err) assert.Equal(t, ui, uint64(123456)) }
{ "pile_set_name": "Github" }
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): pass def backwards(self, orm): pass models = { } complete_apps = ['main']
{ "pile_set_name": "Github" }
/*! * Bootstrap v3.3.7 (http://getbootstrap.com) * Copyright 2011-2016 Twitter, Inc. * Licensed under the MIT license */ if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery') } +function ($) { 'use strict'; var version = $.fn.jquery.split(' ')[0].split('.') if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 3)) { throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4') } }(jQuery); /* ======================================================================== * Bootstrap: transition.js v3.3.7 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { WebkitTransition : 'webkitTransitionEnd', MozTransition : 'transitionend', OTransition : 'oTransitionEnd otransitionend', transition : 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } return false // explicit for ie8 ( ._.) } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false var $el = this $(this).one('bsTransitionEnd', function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() if (!$.support.transition) return $.event.special.bsTransitionEnd = { bindType: $.support.transition.end, delegateType: $.support.transition.end, handle: function (e) { if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments) } } }) }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.3.7 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.VERSION = '3.3.7' Alert.TRANSITION_DURATION = 150 Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector === '#' ? [] : selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.closest('.alert') } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { // detach from parent, fire event then clean up data $parent.detach().trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one('bsTransitionEnd', removeElement) .emulateTransitionEnd(Alert.TRANSITION_DURATION) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.alert $.fn.alert = Plugin $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.3.7 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) this.isLoading = false } Button.VERSION = '3.3.7' Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state += 'Text' if (data.resetText == null) $el.data('resetText', $el[val]()) // push to event loop to allow forms to submit setTimeout($.proxy(function () { $el[val](data[state] == null ? this.options[state] : data[state]) if (state == 'loadingText') { this.isLoading = true $el.addClass(d).attr(d, d).prop(d, true) } else if (this.isLoading) { this.isLoading = false $el.removeClass(d).removeAttr(d).prop(d, false) } }, this), 0) } Button.prototype.toggle = function () { var changed = true var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') == 'radio') { if ($input.prop('checked')) changed = false $parent.find('.active').removeClass('active') this.$element.addClass('active') } else if ($input.prop('type') == 'checkbox') { if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false this.$element.toggleClass('active') } $input.prop('checked', this.$element.hasClass('active')) if (changed) $input.trigger('change') } else { this.$element.attr('aria-pressed', !this.$element.hasClass('active')) this.$element.toggleClass('active') } } // BUTTON PLUGIN DEFINITION // ======================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } var old = $.fn.button $.fn.button = Plugin $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document) .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) { var $btn = $(e.target).closest('.btn') Plugin.call($btn, 'toggle') if (!($(e.target).is('input[type="radio"], input[type="checkbox"]'))) { // Prevent double click on radios, and the double selections (so cancellation) on checkboxes e.preventDefault() // The target component still receive the focus if ($btn.is('input,button')) $btn.trigger('focus') else $btn.find('input:visible,button:visible').first().trigger('focus') } }) .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) { $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type)) }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.3.7 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = null this.sliding = null this.interval = null this.$active = null this.$items = null this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this)) this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element .on('mouseenter.bs.carousel', $.proxy(this.pause, this)) .on('mouseleave.bs.carousel', $.proxy(this.cycle, this)) } Carousel.VERSION = '3.3.7' Carousel.TRANSITION_DURATION = 600 Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true, keyboard: true } Carousel.prototype.keydown = function (e) { if (/input|textarea/i.test(e.target.tagName)) return switch (e.which) { case 37: this.prev(); break case 39: this.next(); break default: return } e.preventDefault() } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getItemIndex = function (item) { this.$items = item.parent().children('.item') return this.$items.index(item || this.$active) } Carousel.prototype.getItemForDirection = function (direction, active) { var activeIndex = this.getItemIndex(active) var willWrap = (direction == 'prev' && activeIndex === 0) || (direction == 'next' && activeIndex == (this.$items.length - 1)) if (willWrap && !this.options.wrap) return active var delta = direction == 'prev' ? -1 : 1 var itemIndex = (activeIndex + delta) % this.$items.length return this.$items.eq(itemIndex) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active')) if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid" if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos)) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || this.getItemForDirection(type, $active) var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var that = this if ($next.hasClass('active')) return (this.sliding = false) var relatedTarget = $next[0] var slideEvent = $.Event('slide.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) this.$element.trigger(slideEvent) if (slideEvent.isDefaultPrevented()) return this.sliding = true isCycling && this.pause() if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)]) $nextIndicator && $nextIndicator.addClass('active') } var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid" if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one('bsTransitionEnd', function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger(slidEvent) }, 0) }) .emulateTransitionEnd(Carousel.TRANSITION_DURATION) } else { $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger(slidEvent) } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } var old = $.fn.carousel $.fn.carousel = Plugin $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= var clickHandler = function (e) { var href var $this = $(this) var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7 if (!$target.hasClass('carousel')) return var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false Plugin.call($target, options) if (slideIndex) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() } $(document) .on('click.bs.carousel.data-api', '[data-slide]', clickHandler) .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) Plugin.call($carousel, $carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.3.7 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ /* jshint latedef: false */ +function ($) { 'use strict'; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' + '[data-toggle="collapse"][data-target="#' + element.id + '"]') this.transitioning = null if (this.options.parent) { this.$parent = this.getParent() } else { this.addAriaAndCollapsedClass(this.$element, this.$trigger) } if (this.options.toggle) this.toggle() } Collapse.VERSION = '3.3.7' Collapse.TRANSITION_DURATION = 350 Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var activesData var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing') if (actives && actives.length) { activesData = actives.data('bs.collapse') if (activesData && activesData.transitioning) return } var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return if (actives && actives.length) { Plugin.call(actives, 'hide') activesData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing')[dimension](0) .attr('aria-expanded', true) this.$trigger .removeClass('collapsed') .attr('aria-expanded', true) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('collapse in')[dimension]('') this.transitioning = 0 this.$element .trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element[dimension](this.$element[dimension]())[0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse in') .attr('aria-expanded', false) this.$trigger .addClass('collapsed') .attr('aria-expanded', false) this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .removeClass('collapsing') .addClass('collapse') .trigger('hidden.bs.collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } Collapse.prototype.getParent = function () { return $(this.options.parent) .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]') .each($.proxy(function (i, element) { var $element = $(element) this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element) }, this)) .end() } Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) { var isOpen = $element.hasClass('in') $element.attr('aria-expanded', isOpen) $trigger .toggleClass('collapsed', !isOpen) .attr('aria-expanded', isOpen) } function getTargetFromTrigger($trigger) { var href var target = $trigger.attr('data-target') || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7 return $(target) } // COLLAPSE PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.collapse $.fn.collapse = Plugin $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) { var $this = $(this) if (!$this.attr('data-target')) e.preventDefault() var $target = getTargetFromTrigger($this) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() Plugin.call($target, option) }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.3.7 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle="dropdown"]' var Dropdown = function (element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.VERSION = '3.3.7' function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } function clearMenus(e) { if (e && e.which === 3) return $(backdrop).remove() $(toggle).each(function () { var $this = $(this) var $parent = getParent($this) var relatedTarget = { relatedTarget: this } if (!$parent.hasClass('open')) return if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this.attr('aria-expanded', 'false') $parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget)) }) } Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $(document.createElement('div')) .addClass('dropdown-backdrop') .insertAfter($(this)) .on('click', clearMenus) } var relatedTarget = { relatedTarget: this } $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this .trigger('focus') .attr('aria-expanded', 'true') $parent .toggleClass('open') .trigger($.Event('shown.bs.dropdown', relatedTarget)) } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if (!isActive && e.which != 27 || isActive && e.which == 27) { if (e.which == 27) $parent.find(toggle).trigger('focus') return $this.trigger('click') } var desc = ' li:not(.disabled):visible a' var $items = $parent.find('.dropdown-menu' + desc) if (!$items.length) return var index = $items.index(e.target) if (e.which == 38 && index > 0) index-- // up if (e.which == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items.eq(index).trigger('focus') } // DROPDOWN PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.dropdown') if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.dropdown $.fn.dropdown = Plugin $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown) .on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.3.7 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$body = $(document.body) this.$element = $(element) this.$dialog = this.$element.find('.modal-dialog') this.$backdrop = null this.isShown = null this.originalBodyPad = null this.scrollbarWidth = 0 this.ignoreBackdropClick = false if (this.options.remote) { this.$element .find('.modal-content') .load(this.options.remote, $.proxy(function () { this.$element.trigger('loaded.bs.modal') }, this)) } } Modal.VERSION = '3.3.7' Modal.TRANSITION_DURATION = 300 Modal.BACKDROP_TRANSITION_DURATION = 150 Modal.DEFAULTS = { backdrop: true, keyboard: true, show: true } Modal.prototype.toggle = function (_relatedTarget) { return this.isShown ? this.hide() : this.show(_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.checkScrollbar() this.setScrollbar() this.$body.addClass('modal-open') this.escape() this.resize() this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.$dialog.on('mousedown.dismiss.bs.modal', function () { that.$element.one('mouseup.dismiss.bs.modal', function (e) { if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true }) }) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(that.$body) // don't move modals dom position } that.$element .show() .scrollTop(0) that.adjustDialog() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element.addClass('in') that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$dialog // wait for modal to slide in .one('bsTransitionEnd', function () { that.$element.trigger('focus').trigger(e) }) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : that.$element.trigger('focus').trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() this.resize() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .off('click.dismiss.bs.modal') .off('mouseup.dismiss.bs.modal') this.$dialog.off('mousedown.dismiss.bs.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one('bsTransitionEnd', $.proxy(this.hideModal, this)) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (document !== e.target && this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.trigger('focus') } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keydown.dismiss.bs.modal') } } Modal.prototype.resize = function () { if (this.isShown) { $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this)) } else { $(window).off('resize.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.$body.removeClass('modal-open') that.resetAdjustments() that.resetScrollbar() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $(document.createElement('div')) .addClass('modal-backdrop ' + animate) .appendTo(this.$body) this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) { if (this.ignoreBackdropClick) { this.ignoreBackdropClick = false return } if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus() : this.hide() }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one('bsTransitionEnd', callback) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') var callbackRemove = function () { that.removeBackdrop() callback && callback() } $.support.transition && this.$element.hasClass('fade') ? this.$backdrop .one('bsTransitionEnd', callbackRemove) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callbackRemove() } else if (callback) { callback() } } // these following methods are used to handle overflowing modals Modal.prototype.handleUpdate = function () { this.adjustDialog() } Modal.prototype.adjustDialog = function () { var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight this.$element.css({ paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '', paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : '' }) } Modal.prototype.resetAdjustments = function () { this.$element.css({ paddingLeft: '', paddingRight: '' }) } Modal.prototype.checkScrollbar = function () { var fullWindowWidth = window.innerWidth if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8 var documentElementRect = document.documentElement.getBoundingClientRect() fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left) } this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth this.scrollbarWidth = this.measureScrollbar() } Modal.prototype.setScrollbar = function () { var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10) this.originalBodyPad = document.body.style.paddingRight || '' if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth) } Modal.prototype.resetScrollbar = function () { this.$body.css('padding-right', this.originalBodyPad) } Modal.prototype.measureScrollbar = function () { // thx walsh var scrollDiv = document.createElement('div') scrollDiv.className = 'modal-scrollbar-measure' this.$body.append(scrollDiv) var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth this.$body[0].removeChild(scrollDiv) return scrollbarWidth } // MODAL PLUGIN DEFINITION // ======================= function Plugin(option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } var old = $.fn.modal $.fn.modal = Plugin $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7 var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) if ($this.is('a')) e.preventDefault() $target.one('show.bs.modal', function (showEvent) { if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown $target.one('hidden.bs.modal', function () { $this.is(':visible') && $this.trigger('focus') }) }) Plugin.call($target, option, this) }) }(jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.3.7 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = null this.options = null this.enabled = null this.timeout = null this.hoverState = null this.$element = null this.inState = null this.init('tooltip', element, options) } Tooltip.VERSION = '3.3.7' Tooltip.TRANSITION_DURATION = 150 Tooltip.DEFAULTS = { animation: true, placement: 'top', selector: false, template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: 'hover focus', title: '', delay: 0, html: false, container: false, viewport: { selector: 'body', padding: 0 } } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport)) this.inState = { click: false, hover: false, focus: false } if (this.$element[0] instanceof document.constructor && !this.options.selector) { throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!') } var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin' var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay, hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } if (obj instanceof $.Event) { self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true } if (self.tip().hasClass('in') || self.hoverState == 'in') { self.hoverState = 'in' return } clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.isInStateTrue = function () { for (var key in this.inState) { if (this.inState[key]) return true } return false } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } if (obj instanceof $.Event) { self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false } if (self.isInStateTrue()) return clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.' + this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0]) if (e.isDefaultPrevented() || !inDom) return var that = this var $tip = this.tip() var tipId = this.getUID(this.type) this.setContent() $tip.attr('id', tipId) this.$element.attr('aria-describedby', tipId) if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) .data('bs.' + this.type, this) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) this.$element.trigger('inserted.bs.' + this.type) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var orgPlacement = placement var viewportDim = this.getPosition(this.$viewport) placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' : placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' : placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' : placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) var complete = function () { var prevHoverState = that.hoverState that.$element.trigger('shown.bs.' + that.type) that.hoverState = null if (prevHoverState == 'out') that.leave(that) } $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() } } Tooltip.prototype.applyPlacement = function (offset, placement) { var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top += marginTop offset.left += marginLeft // $.fn.offset doesn't round pixel values // so we use setOffset directly with our own function B-0 $.offset.setOffset($tip[0], $.extend({ using: function (props) { $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) } }, offset), 0) $tip.addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { offset.top = offset.top + height - actualHeight } var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight) if (delta.left) offset.left += delta.left else offset.top += delta.top var isVertical = /top|bottom/.test(placement) var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight' $tip.offset(offset) this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical) } Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) { this.arrow() .css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%') .css(isVertical ? 'top' : 'left', '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function (callback) { var that = this var $tip = $(this.$tip) var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() if (that.$element) { // TODO: Check whether guarding this code with this `if` is really necessary. that.$element .removeAttr('aria-describedby') .trigger('hidden.bs.' + that.type) } callback && callback() } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && $tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() this.hoverState = null return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function ($element) { $element = $element || this.$element var el = $element[0] var isBody = el.tagName == 'BODY' var elRect = el.getBoundingClientRect() if (elRect.width == null) { // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093 elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top }) } var isSvg = window.SVGElement && el instanceof window.SVGElement // Avoid using $.offset() on SVGs since it gives incorrect results in jQuery 3. // See https://github.com/twbs/bootstrap/issues/20280 var elOffset = isBody ? { top: 0, left: 0 } : (isSvg ? null : $element.offset()) var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() } var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null return $.extend({}, elRect, scroll, outerDims, elOffset) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) { var delta = { top: 0, left: 0 } if (!this.$viewport) return delta var viewportPadding = this.options.viewport && this.options.viewport.padding || 0 var viewportDimensions = this.getPosition(this.$viewport) if (/right|left/.test(placement)) { var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight if (topEdgeOffset < viewportDimensions.top) { // top overflow delta.top = viewportDimensions.top - topEdgeOffset } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset } } else { var leftEdgeOffset = pos.left - viewportPadding var rightEdgeOffset = pos.left + viewportPadding + actualWidth if (leftEdgeOffset < viewportDimensions.left) { // left overflow delta.left = viewportDimensions.left - leftEdgeOffset } else if (rightEdgeOffset > viewportDimensions.right) { // right overflow delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset } } return delta } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.getUID = function (prefix) { do prefix += ~~(Math.random() * 1000000) while (document.getElementById(prefix)) return prefix } Tooltip.prototype.tip = function () { if (!this.$tip) { this.$tip = $(this.options.template) if (this.$tip.length != 1) { throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!') } } return this.$tip } Tooltip.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')) } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = this if (e) { self = $(e.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(e.currentTarget, this.getDelegateOptions()) $(e.currentTarget).data('bs.' + this.type, self) } } if (e) { self.inState.click = !self.inState.click if (self.isInStateTrue()) self.enter(self) else self.leave(self) } else { self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } } Tooltip.prototype.destroy = function () { var that = this clearTimeout(this.timeout) this.hide(function () { that.$element.off('.' + that.type).removeData('bs.' + that.type) if (that.$tip) { that.$tip.detach() } that.$tip = null that.$arrow = null that.$viewport = null that.$element = null }) } // TOOLTIP PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data && /destroy|hide/.test(option)) return if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tooltip $.fn.tooltip = Plugin $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(jQuery); /* ======================================================================== * Bootstrap: popover.js v3.3.7 * http://getbootstrap.com/javascript/#popovers * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function (element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.VERSION = '3.3.7' Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right', trigger: 'click', content: '', template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function () { return Popover.DEFAULTS } Popover.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text' ](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() } Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function () { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.arrow')) } // POPOVER PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data && /destroy|hide/.test(option)) return if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.popover $.fn.popover = Plugin $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.3.7 * http://getbootstrap.com/javascript/#scrollspy * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { this.$body = $(document.body) this.$scrollElement = $(element).is(document.body) ? $(window) : $(element) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || '') + ' .nav li > a' this.offsets = [] this.targets = [] this.activeTarget = null this.scrollHeight = 0 this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this)) this.refresh() this.process() } ScrollSpy.VERSION = '3.3.7' ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.getScrollHeight = function () { return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight) } ScrollSpy.prototype.refresh = function () { var that = this var offsetMethod = 'offset' var offsetBase = 0 this.offsets = [] this.targets = [] this.scrollHeight = this.getScrollHeight() if (!$.isWindow(this.$scrollElement[0])) { offsetMethod = 'position' offsetBase = this.$scrollElement.scrollTop() } this.$body .find(this.selector) .map(function () { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#./.test(href) && $(href) return ($href && $href.length && $href.is(':visible') && [[$href[offsetMethod]().top + offsetBase, href]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { that.offsets.push(this[0]) that.targets.push(this[1]) }) } ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.getScrollHeight() var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (this.scrollHeight != scrollHeight) { this.refresh() } if (scrollTop >= maxScroll) { return activeTarget != (i = targets[targets.length - 1]) && this.activate(i) } if (activeTarget && scrollTop < offsets[0]) { this.activeTarget = null return this.clear() } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (offsets[i + 1] === undefined || scrollTop < offsets[i + 1]) && this.activate(targets[i]) } } ScrollSpy.prototype.activate = function (target) { this.activeTarget = target this.clear() var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } ScrollSpy.prototype.clear = function () { $(this.selector) .parentsUntil(this.options.target, '.active') .removeClass('active') } // SCROLLSPY PLUGIN DEFINITION // =========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.scrollspy $.fn.scrollspy = Plugin $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load.bs.scrollspy.data-api', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) Plugin.call($spy, $spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.3.7 * http://getbootstrap.com/javascript/#tabs * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TAB CLASS DEFINITION // ==================== var Tab = function (element) { // jscs:disable requireDollarBeforejQueryAssignment this.element = $(element) // jscs:enable requireDollarBeforejQueryAssignment } Tab.VERSION = '3.3.7' Tab.TRANSITION_DURATION = 150 Tab.prototype.show = function () { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.data('target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } if ($this.parent('li').hasClass('active')) return var $previous = $ul.find('.active:last a') var hideEvent = $.Event('hide.bs.tab', { relatedTarget: $this[0] }) var showEvent = $.Event('show.bs.tab', { relatedTarget: $previous[0] }) $previous.trigger(hideEvent) $this.trigger(showEvent) if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return var $target = $(selector) this.activate($this.closest('li'), $ul) this.activate($target, $target.parent(), function () { $previous.trigger({ type: 'hidden.bs.tab', relatedTarget: $this[0] }) $this.trigger({ type: 'shown.bs.tab', relatedTarget: $previous[0] }) }) } Tab.prototype.activate = function (element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length) function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', false) element .addClass('active') .find('[data-toggle="tab"]') .attr('aria-expanded', true) if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu').length) { element .closest('li.dropdown') .addClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', true) } callback && callback() } $active.length && transition ? $active .one('bsTransitionEnd', next) .emulateTransitionEnd(Tab.TRANSITION_DURATION) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tab $.fn.tab = Plugin $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function () { $.fn.tab = old return this } // TAB DATA-API // ============ var clickHandler = function (e) { e.preventDefault() Plugin.call($(this), 'show') } $(document) .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler) .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler) }(jQuery); /* ======================================================================== * Bootstrap: affix.js v3.3.7 * http://getbootstrap.com/javascript/#affix * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // AFFIX CLASS DEFINITION // ====================== var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$target = $(this.options.target) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = null this.unpin = null this.pinnedOffset = null this.checkPosition() } Affix.VERSION = '3.3.7' Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0, target: window } Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) { var scrollTop = this.$target.scrollTop() var position = this.$element.offset() var targetHeight = this.$target.height() if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false if (this.affixed == 'bottom') { if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom' return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom' } var initializing = this.affixed == null var colliderTop = initializing ? scrollTop : position.top var colliderHeight = initializing ? targetHeight : height if (offsetTop != null && scrollTop <= offsetTop) return 'top' if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom' return false } Affix.prototype.getPinnedOffset = function () { if (this.pinnedOffset) return this.pinnedOffset this.$element.removeClass(Affix.RESET).addClass('affix') var scrollTop = this.$target.scrollTop() var position = this.$element.offset() return (this.pinnedOffset = position.top - scrollTop) } Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var height = this.$element.height() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom var scrollHeight = Math.max($(document).height(), $(document.body).height()) if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element) if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element) var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom) if (this.affixed != affix) { if (this.unpin != null) this.$element.css('top', '') var affixType = 'affix' + (affix ? '-' + affix : '') var e = $.Event(affixType + '.bs.affix') this.$element.trigger(e) if (e.isDefaultPrevented()) return this.affixed = affix this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null this.$element .removeClass(Affix.RESET) .addClass(affixType) .trigger(affixType.replace('affix', 'affixed') + '.bs.affix') } if (affix == 'bottom') { this.$element.offset({ top: scrollHeight - height - offsetBottom }) } } // AFFIX PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.affix $.fn.affix = Plugin $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function () { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom if (data.offsetTop != null) data.offset.top = data.offsetTop Plugin.call($spy, data) }) }) }(jQuery);
{ "pile_set_name": "Github" }
use v6; use Test; use lib $?FILE.IO.parent(2).add("packages/Test-Helpers"); use Test::Util; plan 33; # L<S04/Phasers/ENTER "at every block entry time"> # L<S04/Phasers/LEAVE "at every block exit time"> { my $str; my sub foo ($x, $y) { ENTER { $str ~= "(" } LEAVE { $str ~= ")" } $str ~= "$x,$y"; } foo(3,4); is $str, '(3,4)'; foo(-1,2); is $str, '(3,4)(-1,2)'; } # reversed order { my $str; my sub foo ($x, $y) { $str ~= "$x,$y"; LEAVE { $str ~= ")" } ENTER { $str ~= "(" } } foo(7,-8); is $str, '(7,-8)'; foo(5,0); is $str, '(7,-8)(5,0)'; } # multiple ENTER and LEAVE blocks { my $str; { ENTER { $str ~= '[' } LEAVE { $str ~= ']' } $str ~= 21; ENTER { $str ~= '(' } LEAVE { $str ~= ')' } ENTER { $str ~= '{' } LEAVE { $str ~= '}' } } is $str, '[({21})]', 'multiple ENTER/LEAVE worked'; } # L<S04/Phasers/ENTER "repeats on loop blocks"> { my $str; for 1..2 -> $x { $str ~= ','; ENTER { $str ~= "E$x" } LEAVE { $str ~= "L$x " } } is $str, 'E1,L1 E2,L2 ', 'ENTER/LEAVE repeats on loop blocks'; } # L<S04/Phasers/LEAVE "at every block exit time"> # named sub: { my $str; my sub is_even ($x) { return 1 if $x % 2 == 0; return 0; LEAVE { $str ~= $x } } is is_even(3), 0, 'basic sanity check (1)'; is $str, '3', 'LEAVE executed at the 1st explicit return'; is is_even(2), 1, 'basic sanity check (2)'; is $str, '32', 'LEAVE executed at the 2nd explicit return'; } # normal closure: # https://github.com/Raku/old-issue-tracker/issues/4112 #?rakudo skip 'leave NYI RT #124960' { is EVAL(q{ my $a; { leave; $a = 100; LEAVE { $a++ } } $a; }), 1, 'leave triggers LEAVE {}'; } { my $str; try { ENTER { $str ~= '(' } LEAVE { $str ~= ')' } $str ~= 'x'; die 'foo'; } is $str, '(x)', 'die calls LEAVE blocks'; } { my $str; try { LEAVE { $str ~= $! // '<undef>' } die 'foo'; } ok $str ~~ /foo/, '$! set in LEAVE if exception thrown'; } { my $str; { LEAVE { $str ~= (defined($!) ?? 'yes' !! 'no') } try { die 'foo' } $str ~= (defined($!) ?? 'aye' !! 'nay'); } #?rakudo todo 'is this spec? why would LEAVE not see outer $!? fossil?' is $str, 'ayeno', '$! not set in LEAVE if exception not thrown'; } { my $str; try { $str ~= '('; try { ENTER { die 'foo' } $str ~= 'x'; } $str ~= ')'; } is $str, '()', 'die in ENTER caught by try'; } { my $str; try { $str ~= '('; try { LEAVE { die 'foo' } $str ~= 'x'; } $str ~= ')'; } #?rakudo.jvm todo "nigh" is $str, '(x)', 'die in LEAVE caught by try'; } { my $str; try { $str ~= '('; try { ENTER { $str ~= '['; die 'foo' } LEAVE { $str ~= ']' } $str ~= 'x'; } $str ~= ')'; } is $str, '([])', 'die in ENTER calls LEAVE'; } { my $str; try { ENTER { $str ~= '1'; die 'foo' } ENTER { $str ~= '2' } } is $str, '1', 'die aborts ENTER queue'; } # https://github.com/Raku/old-issue-tracker/issues/3363 { my $str; try { LEAVE { $str ~= '1' } LEAVE { $str ~= '2'; die 'foo' } } is $str, '21', 'die doesn\'t abort LEAVE queue'; #?rakudo.jvm todo 'RT #121530' is $!.message, 'foo', 'single exception from LEAVE is rethrown after running LEAVEs'; } # https://github.com/Raku/old-issue-tracker/issues/2785 { my $a = 0; my $b = 0; multi sub rt113548() { $a = 1; LEAVE $b = 2; }; rt113548; ok($a == 1 && $b == 2, "LEAVE fires in a multi sub"); } # https://github.com/Raku/old-issue-tracker/issues/2988 { my $x = 0; for 1..10 { LEAVE { $x++ }; next } is $x, 10, "next triggers LEAVE"; } # https://github.com/Raku/old-issue-tracker/issues/3022 { my $str=''; for 1..2 { ENTER { $str ~= $_ for <foo bar> }; $str ~= $_; } is $str, 'foobar1foobar2', 'can run for loop in phaser in for loop'; } # https://github.com/Raku/old-issue-tracker/issues/3160 { is_run( q[sub foo { LEAVE { say 'OK' }; die 'foobar' }; foo()], { out => "OK\n", err => /foobar/, }, 'LEAVE fires after die in sub' ); } # https://github.com/Raku/old-issue-tracker/issues/2806 { my $rt113950_last = "hello!"; loop { last; LEAVE $rt113950_last ~= " bye!"; } is $rt113950_last, "hello! bye!", '"last" triggers LEAVE phaser in loop'; my $rt113950_next = "hello!"; for ^3 { next; LEAVE $rt113950_next ~= " yay!"; } is $rt113950_next, "hello! yay! yay! yay!", '"next" triggers LEAVE phaser in "for" loop'; } # https://github.com/Raku/old-issue-tracker/issues/2999 { is ENTER { 42 }, 42, 'ENTER works as an r-value (mainline)'; sub enter-test() { ENTER 'SANDMAN' } is enter-test(), 'SANDMAN', 'ENTER works as an r-value (sub)'; } # https://github.com/Raku/old-issue-tracker/issues/4346 { sub doit() { if True { LEAVE 1; return 'ls'; } } is doit(), 'ls', 'return in nested block with LEAVE works'; } { sub foo() { LEAVE die 'wtf'; LEAVE die 'omg'; } throws-like { foo() }, X::PhaserExceptions, exceptions => sub (@ex) { @ex>>.message ~~ <omg wtf> }; } { # https://github.com/rakudo/rakudo/issues/1455 my $res; -> { LEAVE $res := now - ENTER now }(); isa-ok $res, Duration, 'using ENTER inside LEAVE does not crash'; } # https://colabti.org/irclogger/irclogger_log/perl6?date=2019-04-26#l196 # When a block has no local variables, the ENTER phaser would not success- # fully decont a variable out of a surrounding scope. Didn't have a ticket, # was fixed in Rakudo as a side-effect of 541a4f1628. { my $set; # Run at most 20 iterations my @v = ^20; my $i = 0; loop { $set ∪= @v[$i++]; last if $i == @v; # Should be true in the 2nd iteration, but is always (Set) in # a buggy rakudo version. last if ENTER $set<>; } is $set.elems, 2, 'decont in ENTER works without locals'; } # https://github.com/rakudo/rakudo/issues/3411 { my $entered; class A { method a() { ENTER ++$entered; } } A.a; is $entered, 1, 'Did ENTER only run once'; } # vim: expandtab shiftwidth=4
{ "pile_set_name": "Github" }
require('../../modules/es6.regexp.match'); module.exports = require('../../modules/$.wks')('match');
{ "pile_set_name": "Github" }
/* Tags */ #head-tags{ margin-left:1em; margin-top:1em; } #body .tags a.tag-link { display: inline-block; line-height: 2em; font-size: 0.8em; position: relative; margin: 0 16px 8px 0; padding: 0 10px 0 12px; background: #8451a1; -webkit-border-bottom-right-radius: 3px; border-bottom-right-radius: 3px; -webkit-border-top-right-radius: 3px; border-top-right-radius: 3px; -webkit-box-shadow: 0 1px 2px rgba(0,0,0,0.2); box-shadow: 0 1px 2px rgba(0,0,0,0.2); color: #fff; } #body .tags a.tag-link:before { content: ""; position: absolute; top:0; left: -1em; width: 0; height: 0; border-color: transparent #8451a1 transparent transparent; border-style: solid; border-width: 1em 1em 1em 0; } #body .tags a.tag-link:after { content: ""; position: absolute; top: 10px; left: 1px; width: 5px; height: 5px; -webkit-border-radius: 50%; border-radius: 100%; background: #fff; }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?colorPrimary" android:orientation="vertical"> <im.vector.view.VectorCircularImageView android:id="@+id/room_header_avatar" android:layout_width="84dp" android:layout_height="84dp" android:layout_gravity="center_horizontal" android:layout_marginTop="16dp" android:adjustViewBounds="true" android:scaleType="centerCrop" android:transitionName="vector_transition_avatar" tools:src="@tools:sample/avatars" /> <!-- keep singleLine="true" because maxLines="1" truncation is not the expected one.--> <TextView android:id="@+id/action_bar_header_room_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="6dp" android:layout_marginBottom="2dp" android:ellipsize="end" android:gravity="center_horizontal" android:padding="8dp" android:singleLine="true" android:textColor="?vctr_toolbar_primary_text_color" android:textSize="20sp" tools:text="a room name here" /> <TextView android:id="@+id/action_bar_header_room_topic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginStart="44dp" android:layout_marginLeft="44dp" android:layout_marginEnd="44dp" android:layout_marginRight="44dp" android:layout_marginBottom="10dp" android:autoLink="web" android:ellipsize="end" android:gravity="center_horizontal" android:maxLines="3" android:textColor="?vctr_toolbar_primary_text_color" android:textColorLink="?vctr_toolbar_link_text_color" android:textSize="14sp" tools:text="a topic here www.example.org" /> <LinearLayout android:id="@+id/action_bar_header_room_members_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginBottom="10dp"> <ImageView android:id="@+id/action_bar_header_room_members_settings_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:contentDescription="@string/list_members" android:padding="8dp" android:scaleType="center" android:src="@drawable/ic_list_white_24dp" /> <TextView android:id="@+id/action_bar_header_room_members_text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:ellipsize="end" android:padding="8dp" android:textColor="?vctr_toolbar_secondary_text_color" android:textSize="14sp" tools:text="a text" /> <ImageView android:id="@+id/action_bar_header_room_members_invite_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:contentDescription="@string/invite" android:padding="8dp" android:src="@drawable/ic_add_circle_outline_white_24dp" /> </LinearLayout> </LinearLayout>
{ "pile_set_name": "Github" }
/* LanguageTool, a natural language style checker * Copyright (C) 2013 Marcin Miłkowski (www.languagetool.org) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.rules.patterns; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.languagetool.Language; import static org.junit.Assert.fail; /** * Common pattern test routines (usable for Disambiguation rules as well). * * @author Marcin Miłkowski */ public final class PatternTestTools { // These characters should not be present in token values as they split tokens in all languages. private static final Pattern TOKEN_SEPARATOR_PATTERN = Pattern.compile("[ .,:;…!?(){}<>«»\"]"); private static final Pattern TOKEN_SEPARATOR_PATTERN_NO_DOT = Pattern.compile("[ ,:;…!?(){}<>«»\"]"); private static final Pattern PROBABLE_PATTERN = Pattern.compile("(\\\\[dDsSwW])|.*([^*]\\*|[.+?{}()|\\[\\]].*|\\\\d).*"); // Polish POS tags use dots, so do not consider the presence of a dot // as indicating a probable regular expression. private static final Pattern PROBABLE_PATTERN_PL_POS = Pattern.compile("(\\\\[dDsSwW])|.*([^*]\\*|[+?{}()|\\[\\]].*|\\\\d).*"); private static final Pattern CHAR_SET_PATTERN = Pattern.compile("\\[^?([^\\]]+)\\]"); private static final Pattern STRICT_CHAR_SET_PATTERN = Pattern.compile("(\\(\\?-i\\))?.*(?<!\\\\)\\[^?([^\\]]+)\\]"); /* * These strings are not be recognized as a regular expression */ private static final Set<String> NO_REGEXP = new HashSet<>(Arrays.asList( "PRP:LOK+TMP+MOD:DAT+AKK", "AUX:ind+pres+3+p", "PRP:TMP+MOD+CAU:DAT", "PRP:LOK+TMP:DAT" )); private PatternTestTools() { } public static void failIfWhitespaceInToken(List<PatternToken> patternTokens, AbstractPatternRule rule, Language lang) { if (patternTokens != null) { for (PatternToken token : patternTokens) { if (token.getString() != null && token.getString().matches(".*\\s.*")) { fail("Whitespace found in token '" + token.getString() + "' of rule " + rule.getFullId() + " (language " + lang.getShortCodeWithCountryAndVariant() + "): " + "Using whitespace in a token will not work, as text gets split at whitespace. " + "Use a new <token> element instead."); } } } } // TODO: probably this would be more useful for exceptions // instead of adding next methods to PatternRule // we can probably validate using XSD and specify regexes straight there public static void warnIfRegexpSyntaxNotKosher(List<PatternToken> patternTokens, String ruleId, String ruleSubId, Language lang) { if (patternTokens == null) { // for <regexp> return; } int i = 0; for (PatternToken pToken : patternTokens) { i++; if (pToken.isReferenceElement()) { continue; } // Check whether token value is consistent with regexp="..." warnIfElementNotKosher( pToken.getString(), pToken.isRegularExpression(), pToken.isCaseSensitive(), pToken.getNegation(), pToken.isInflected(), false, // not a POS lang, ruleId + "[" + ruleSubId + "]", i); // Check postag="..." is consistent with postag_regexp="..." warnIfElementNotKosher( pToken.getPOStag() == null ? "" : pToken.getPOStag(), pToken.isPOStagRegularExpression(), pToken.isCaseSensitive(), pToken.getPOSNegation(), false, true, // a POS. lang, ruleId + "[" + ruleSubId + "] (POS tag)", i); List<PatternToken> exceptionPatternTokens = new ArrayList<>(); if (pToken.getExceptionList() != null) { for (PatternToken exception: pToken.getExceptionList()) { // Detect useless exception or missing skip="...". I.e. things like this: // <token postag="..."><exception scope="next">foo</exception</token> // We now allow scope="next" without skip="..." if (exception.hasNextException()) continue; // if (exception.hasNextException() && pToken.getSkipNext() == 0) { // warn("The " + lang + " rule: " // + ruleId + "[" + ruleSubId + "]" // + " (exception in token [" + i + "])" // + " has no skip=\"...\" and yet contains scope=\"next\"" // + " so the exception never applies." // + " Did you forget skip=\"...\"?"); // } // Detect exception that can't possibly be matched. if ( !pToken.getString().isEmpty() && !exception.getString().isEmpty() && !pToken.getNegation() && !pToken.isInflected() && !exception.getNegation() && !exception.isInflected() && pToken.getSkipNext() == 0 && pToken.isCaseSensitive() == exception.isCaseSensitive()) { if (exception.isRegularExpression()) { if (pToken.isRegularExpression()) { // Both exception and token are regexp. In that case, we only // check sanity when exception regexp is a simple disjunction as // in this example: // <token regexp="yes">...some arbitrary regexp... // <exception regexp="yes">foo|bar|xxx</exception> // </token> // All the words foo, bar, xxx should match the token regexp, or else they // are useless. if (exception.getString().indexOf('|') >= 0) { String[] alt = exception.getString().split("\\|"); for (String part : alt) { if (exception.getString().indexOf('(') >= 0) { break; } if (part.matches("[^.*?{}\\[\\]]+")) { if (!part.matches("(?i)" + pToken.getString())) { warn("The " + lang + " rule: " + ruleId + "[" + ruleSubId + "]" + " has exception regexp [" + exception.getString() + "] which contains disjunction part [" + part + "] which seems useless since it does not match " + "the regexp of token word [" + i + "] " + "[" + pToken.getString() + "], or did you forget skip=\"...\" or scope=\"previous\"?"); } } } } } else { // It does not make sense to to have a regexp exception // with a token which is not a regexp!? // Example <token>foo<exception regexp="xxx|yyy"/></token> warn("The " + lang + " rule: " + ruleId + "[" + ruleSubId + "]" + " has exception regexp [" + exception.getString() + "] in token word [" + i +"] [" + pToken.getString() + "] which seems useless, or " + "did you forget skip=\"...\" or scope=\"previous\"?"); } } else { if (pToken.isRegularExpression()) { // An exception that cannot match a token regexp is useless. // Example: <token regexp="yes">foo|bar<exception>xxx</exception></token> // Here exception word xxx cannot possibly match the regexp "foo|bar". if (!exception.getString().matches( (exception.isCaseSensitive() ? "" : "(?i)") + pToken.getString())) { warn("The " + lang + " rule: " + ruleId + "[" + ruleSubId + "] has exception word [" + exception.getString() + "] which cannot match the " + "regexp token [" + i + "] [" + pToken.getString() + "] so exception seems useless, " + "or did you forget skip=\"...\" or scope=\"previous\"?"); } } else { // An exception that cannot match a token string is useless, // Example: <token>foo<exception>bar</exception></token> warn("The " + lang + " rule: " + ruleId + "[" + ruleSubId + "] has exception word [" + exception.getString() + "] in token word [" + i + "] [" + pToken.getString() + "] which seems useless, " + "or did you forget skip=\"...\" or scope=\"previous\"?"); } } } // Check whether exception value is consistent with regexp="..." // Don't check string "." since it is sometimes used as a regexp // and sometimes used as non regexp. if (!exception.getString().equals(".")) { warnIfElementNotKosher( exception.getString(), exception.isRegularExpression(), exception.isCaseSensitive(), exception.getNegation(), exception.isInflected(), false, // not a POS lang, ruleId + "[" + ruleSubId+ "] (exception in token [" + i + "])", i); } // Check postag="..." of exception is consistent with postag_regexp="..." warnIfElementNotKosher( exception.getPOStag() == null ? "" : exception.getPOStag(), exception.isPOStagRegularExpression(), exception.isCaseSensitive(), exception.getPOSNegation(), false, true, // a POS lang, ruleId + "[" + ruleSubId + "] (exception in POS tag of token [" + i + "])", i); // Search for duplicate exceptions (which are useless). // Since there are 2 nested loops on the list of exceptions, // this has thus a O(n^2) complexity, where n is the number // of exceptions in a token. But n is small and it is also // for testing only so that's OK. for (PatternToken otherException: exceptionPatternTokens) { if (equalException(exception, otherException)) { warn("The " + lang + " rule: " + ruleId + "[" + ruleSubId + "]" + " in token [" + i + "]" + " contains duplicate exceptions with" + " string=[" + exception.getString() + "]" + " POS tag=[" + exception.getPOStag() + "]" + " negate=[" + exception.getNegation() + "]" + " POS negate=[" + exception.getPOSNegation() + "]"); break; } } exceptionPatternTokens.add(exception); } } } } /** * Predicate to check whether two exceptions are identical or whether * one exception always implies the other. * * Example #1, useless identical exceptions: * <exception>xx</exception><exception>xx</exception> * * Example #2, first exception implies the second exception: * <exception>xx</exception><exception postag="A">xx</exception> */ private static boolean equalException(PatternToken exception1, PatternToken exception2) { String string1 = exception1.getString() == null ? "" : exception1.getString(); String string2 = exception2.getString() == null ? "" : exception2.getString(); if (!exception1.isCaseSensitive() || !exception2.isCaseSensitive()) { // String comparison is done case insensitive if one or both strings // are case insensitive, because the case insensitive one would imply // the case sensitive one. string1 = string1.toLowerCase(); string2 = string2.toLowerCase(); } if (!string1.isEmpty() && !string2.isEmpty()) { if (!string1.equals(string2)) { return false; } } String posTag1 = exception1.getPOStag() == null ? "" : exception1.getPOStag(); String posTag2 = exception2.getPOStag() == null ? "" : exception2.getPOStag(); if (!posTag1.isEmpty() && !posTag2.isEmpty()) { if (!posTag1.equals(posTag2)) { return false; } } if ( string1.isEmpty() != string2.isEmpty() && posTag1.isEmpty() != posTag2.isEmpty()) { return false; } // We should not need to check for: // - isCaseSensitive() since an exception without isCaseSensitive // imply the one with isCaseSensitive. // - isInflected() since an exception with inflected="yes" // implies the one without inflected="yes" if they have // identical strings. // without inflected="yes". // - isRegularExpression() since a given string is either // a regexp or not. return exception1.getNegation() == exception2.getNegation() && exception1.getPOSNegation() == exception2.getPOSNegation() && exception1.hasNextException() == exception2.hasNextException() && exception1.hasPreviousException() == exception2.hasPreviousException(); } private static void warnIfElementNotKosher( String stringValue, boolean isRegularExpression, boolean isCaseSensitive, boolean isNegated, boolean isInflected, boolean isPos, Language lang, String ruleId, int tokenIndex) { // Check that the string value does not contain token separator. if (!isPos && !isRegularExpression && stringValue.length() > 1) { // Example: <token>foo bar</token> can't be valid because // token value contains a space which is a token separator. // Ukrainian dictionary contains some abbreviations with dot Pattern tokenSeparatorPattern = lang.getShortCode().equals("uk") ? TOKEN_SEPARATOR_PATTERN_NO_DOT : TOKEN_SEPARATOR_PATTERN; if (tokenSeparatorPattern.matcher(stringValue).find()) { warn("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains " + "\"" + stringValue + "\" that contains token separators, so can't possibly be matched."); } } // Use a different regexp to check for probable regexp in Polish POS tags // since Polish uses dot '.' in POS tags. So a dot does not indicate that // it's a probable regexp for Polish POS tags. Pattern regexPattern = (isPos && lang.getShortCode().equals("pl")) || (!isPos && lang.getShortCode().equals("uk")) ? PROBABLE_PATTERN_PL_POS // Polish POS tag or Ukrainian token : PROBABLE_PATTERN; // other usual cases if (!isRegularExpression && stringValue.length() > 1 && regexPattern.matcher(stringValue).find() && !NO_REGEXP.contains(stringValue)) { warn("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains " + "\"" + stringValue + "\" that is not marked as regular expression but probably is one."); } if (isRegularExpression && stringValue.isEmpty()) { warn("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains an empty string " + "\"" + stringValue + "\" that is marked as regular expression."); } else if (isRegularExpression && stringValue.length() > 1 && !regexPattern.matcher(stringValue).find()) { warn("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains " + "\"" + stringValue + "\" that is marked as regular expression but probably is not one."); } if (isNegated && stringValue.isEmpty()) { warn("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], marked as negated but is " + "empty so the negation is useless. Did you mix up " + "negate=\"yes\" and negate_pos=\"yes\"?"); } if (isInflected && stringValue.isEmpty()) { warn("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains " + "\"" + stringValue + "\" that is marked as inflected but is empty, so the attribute is redundant."); } if (isRegularExpression && ".*".equals(stringValue)) { warn("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], marked as regular expression contains " + "regular expression \".*\" which is useless: " + "(use an empty string without regexp=\"yes\" such as <token/>)"); } if (isRegularExpression) { Matcher matcher = CHAR_SET_PATTERN.matcher(stringValue); if (matcher.find()) { Matcher strictMatcher = STRICT_CHAR_SET_PATTERN.matcher(stringValue); // for performance reasons, only now use the strict pattern if (strictMatcher.find()) { // Remove things like \p{Punct} which are irrelevant here. String s = strictMatcher.group(2).replaceAll("\\\\p\\{[^}]*\\}", ""); // case sensitive if pattern contains (?-i). if (s.indexOf('|') >= 0) { if (!(s.indexOf('|') >= 1 && s.charAt(s.indexOf('|') -1) == '\\')){ //don't warn if it's escaped warn("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains | (pipe) in " + "regexp bracket expression [" + strictMatcher.group(2) + "] which is unlikely to be correct."); } } /* Disabled case insensitive check for now: it gives several errors * in German which are minor and debatable whether it adds value. boolean caseSensitive = matcher.group(1) != null || isCaseSensitive; if (!caseSensitive) { s = s.toLowerCase(); } */ char[] sorted = s.toCharArray(); // Sort characters in string, so finding duplicate characters can be done by // looking for identical adjacent characters. Arrays.sort(sorted); for (int i = 1; i < sorted.length; ++i) { char c = sorted[i]; if ("&\\-|".indexOf(c) < 0 && sorted[i - 1] == c) { warn("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains " + "regexp part [" + strictMatcher.group(2) + "] which contains duplicated char [" + c + "]."); break; } } } } if (stringValue.contains("|")) { if (stringValue.contains("||") || stringValue.charAt(0) == '|' || stringValue.charAt(stringValue.length() - 1) == '|') { // Empty disjunctions in regular expression are most likely not intended. warn("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains empty " + "disjunction | within " + "\"" + stringValue + "\"."); } String[] groups = stringValue.split("[)(]"); for (String group : groups) { String[] alt = group.split("\\|"); Set<String> partSet = new HashSet<>(); Set<String> partSetNoCase = new HashSet<>(); boolean hasSingleChar = false; boolean hasSingleDot = false; for (String part : alt) { if (part.length() == 1) { // If all alternatives in disjunction have one char, then // a dot . (any char) does not make sense since it would match // other characters. if (part.equals(".")) { hasSingleDot = true; } else { hasSingleChar = true; } } String partNoCase = isCaseSensitive ? part : part.toLowerCase(); if (partSetNoCase.contains(partNoCase)) { if (partSet.contains(part)) { // Duplicate disjunction parts "foo|foo". warn("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains " + "duplicated disjunction part (" + part + ") within " + "\"" + stringValue + "\"."); } else { // Duplicate disjunction parts "Foo|foo" since element ignores case. warn("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains duplicated " + "non case sensitive disjunction part (" + part + ") within " + "\"" + stringValue + "\". Did you " + "forget case_sensitive=\"yes\"?"); } } partSetNoCase.add(partNoCase); partSet.add(part); } if (hasSingleDot && hasSingleChar) { // This finds errors like this <token regexp="yes">.|;|:</token> // which should be <token regexp="yes">\.|;|:</token> or // even better <token regexp="yes">[.;:]</token> warn("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains a single dot (matching any char) " + "so other single char disjunctions are useless within " + "\"" + stringValue + "\". Did you forget forget a backslash before the dot?"); } } } } } private static void warn(String s) { System.err.println("*** WARNING: " + s); } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2019, Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ //! //! \file decode_packet_id.h //! \brief Defines the utils interface for decode packet id. //! \details Defines the utils interface to declare the unique decode packet id //! among decoders. //! #ifndef __DECODE_PACKET_ID_H__ #define __DECODE_PACKET_ID_H__ #include "decode_unique_id.h" namespace decode { #define DeclareDecodePacketId(name) DeclareDecodeUniqueId(Packet, name) #define DecodePacketId(scope, name) GetDecodeUniqueId(scope, Packet, name) } #endif
{ "pile_set_name": "Github" }
gcr.io/google_containers/kube-controller-manager-amd64:v1.10.3-beta.0
{ "pile_set_name": "Github" }
# Context: A semiprime is a product of two prime # numbers, not necessarily distinct. # Squares of prime numbers are also semiprimes. # Problem: Find the numbers which are semiprimes, # within a given range. For e.g. 1 to 100. def isSemiprime(num): # start with the smallest prime prime = 2 # initialize counter to 0 count = 0 # Design of while loop: # 1. if count exceeds 2, it is not a semiprime, e.g. 30 = 2*3*5 # 2. when the number becomes 1, we have found the second prime while count < 3 and num != 1: # if the number is divisible by current prime, # increment count, else move to new prime if not (num % prime): num = num / prime count = count + 1 else: prime = prime + 1 # if count is two, given number is a semiprime return count == 2 for i in range(1, 100): if isSemiprime(i): print(i, end=" ") # Result: 4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 # 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95
{ "pile_set_name": "Github" }
angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": { "0": "AM", "1": "PM" }, "DAY": { "0": "dimanche", "1": "lundi", "2": "mardi", "3": "mercredi", "4": "jeudi", "5": "vendredi", "6": "samedi" }, "MONTH": { "0": "janvier", "1": "f\u00e9vrier", "2": "mars", "3": "avril", "4": "mai", "5": "juin", "6": "juillet", "7": "ao\u00fbt", "8": "septembre", "9": "octobre", "10": "novembre", "11": "d\u00e9cembre" }, "SHORTDAY": { "0": "dim.", "1": "lun.", "2": "mar.", "3": "mer.", "4": "jeu.", "5": "ven.", "6": "sam." }, "SHORTMONTH": { "0": "janv.", "1": "f\u00e9vr.", "2": "mars", "3": "avr.", "4": "mai", "5": "juin", "6": "juil.", "7": "ao\u00fbt", "8": "sept.", "9": "oct.", "10": "nov.", "11": "d\u00e9c." }, "fullDate": "EEEE d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y HH:mm:ss", "mediumDate": "d MMM y", "mediumTime": "HH:mm:ss", "short": "dd/MM/yy HH:mm", "shortDate": "dd/MM/yy", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u20ac", "DECIMAL_SEP": ",", "GROUP_SEP": "\u00a0", "PATTERNS": { "0": { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, "1": { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "(", "negSuf": "\u00a0\u00a4)", "posPre": "", "posSuf": "\u00a0\u00a4" } } }, "id": "fr-gf", "pluralCat": function (n) { if (n >= 0 && n <= 2 && n != 2) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
{ "pile_set_name": "Github" }
pathlib==1.0.1 scandir==1.6 h5py==2.7.1 Keras==2.1.2 opencv-python==3.3.0.10 tensorflow-gpu==1.4.0 scikit-image dlib face_recognition tqdm
{ "pile_set_name": "Github" }
owner = MAN controller = MAN add_core = MAN add_core = CHC add_core = CHI infra = 6 infra = 6 infra = 6 infra = 6 infra = 6
{ "pile_set_name": "Github" }
discard """ cmd: "nim c --gc:arc --exceptions:goto $file" outputsub: "Error: unhandled exception: Problem [OSError]" exitcode: "1" """ raise newException(OSError, "Problem")
{ "pile_set_name": "Github" }
// This is brl/bseg/sdet/sdet_gauss_fit.cxx #include <iostream> #include <fstream> #include <cmath> #include <utility> #include "sdet_gauss_fit.h" //: // \file #ifdef _MSC_VER # include "vcl_msvc_warnings.h" #endif #include "vgl/vgl_point_3d.h" #include "vnl/vnl_math.h" #include <vsol/vsol_point_2d.h> // for dereferencing ps_list[j] // for new matrix operations #include "vnl/vnl_matrix_fixed.h" #include "vnl/vnl_inverse.h" #include <vnl/algo/vnl_levenberg_marquardt.h> #define JIL_DIAGNOSTICS // ----------------------------------------------------------------- // constructor sdet_adjust_lsqr:: sdet_adjust_lsqr( std::vector<vgl_point_3d<double> > img_pts, unsigned int num_unknowns, unsigned int num_residuals, int n_peaks) : vnl_least_squares_function(num_unknowns, num_residuals, vnl_least_squares_function::no_gradient) , img_pts_(std::move(img_pts)) , num_pixels_(img_pts_.size()) , n_peaks_(n_peaks) { } // ----------------------------------------------------------------- // MAIN method: function "f" to calculate errors // The virtual least-squares cost function - // calculates the fit of pixels to 2-d gaussian curve // The 1 + n+peaks*6 unknowns to fit: // [0] plane = zero plane (floor) of gaussian distributions, same for all peaks // Each peak has the following 6 parameters // [1] peak = peak value of gaussian distribution // [2] x_bar = x location (in pixels) of peak // [3] y_bar = y location (in pixels) of peak // And the 2x2 covariance matrix (the 2 off-diagonals are equal) // [4] var_x = variance in x direction [0,0] // [5] var_y = variance in y direction [1,1] // [6] covar = off-diagonal covariance values [0,1] = [1,0] // The fit_error residual vector elements are mis-fit errors for each image point // (NOTE: the errors are set to the absolute values (not squares) of the differences) void sdet_adjust_lsqr::f( vnl_vector<double> const& unknowns, vnl_vector<double> & fit_error) { // set the parameters of the 2-d Gaussian from "unknowns" and // calculate the pixel point predictions using these values vnl_vector<double> fit_value(num_pixels_); // the gaussian predictions of image intensity vnl_vector<double> sum(num_pixels_); // the sum of gaussians from all peaks // zero out all sums for (unsigned i=0; i < num_pixels_; ++i) { sum[i] = 0.0; } // Multiple peaks complicate this calculation, as the contribution of all the // peaks must be added together to get the predicted value at a pixel // Loop through the peaks to add up predicted value for each pixel for (int j=0; j < n_peaks_; ++j) { vnl_matrix_fixed<double,2,2> V; V(0,0) = unknowns[6*j+4]; // the x variance V(0,1) = unknowns[6*j+6]; // the covariance (equal) V(1,0) = unknowns[6*j+6]; // the covariance (equal) V(1,1) = unknowns[6*j+5]; // the y variance vnl_matrix_fixed<double,2,2> Vinv = vnl_inverse(V); for (unsigned i=0; i < img_pts_.size(); ++i) { double peak_delta = unknowns[6*j+1] - unknowns[0]; //predicted height of peak above bkgd vnl_matrix_fixed<double,2,1> D; // the pixel's xi-xbari matrix D(0,0) = img_pts_[i].x() - unknowns[6*j+2]; // pixel x loc - peak x loc D(1,0) = img_pts_[i].y() - unknowns[6*j+3]; // pixel y loc - peak y loc vnl_matrix_fixed<double,1,2> Dtrans = D.transpose(); // the xi-xbari matrix transpose double exponent = ((-1.0 * Dtrans * Vinv * D)(0,0))/2.0; // exponent of e //value of gaussian at x,y, a matrix operation double gaussian = peak_delta * std::exp(exponent); // add up value of summed components of multiple peaks at eacy image point sum[i] += gaussian; } } // finally, add "floor" value to sum for (unsigned i=0; i < img_pts_.size(); ++i) fit_value[i] = sum[i] + unknowns[0]; // add value of pixel above "floor" #if 0 // Debug: print out values for this step std::cout << "plane(" << unknowns[0] << "), peak(" << unknowns[1] << "),\n" << "x(" << unknowns[2] << "), y(" << unknowns[3] << ")\n" << "var x(" << unknowns[4] << "), var y(" << unknowns[5] << ")\n" << "covar(" << unknowns[6] << ')' << std::endl; #endif // calculate the fit_error values of the current fit for (unsigned i = 0; i < img_pts_.size(); ++i) { double e = (fit_value[i] - img_pts_[i].z()); fit_error[i] = std::fabs(e); #if 0 // Debug: print out values of fit error for each point std::cout << "fiterror[" << i << ']' << fit_error[i] << std::endl; #endif } } // ------------------------------------------------------------------------- // Initialize the process static bool init(std::vector<vgl_point_3d<double> > img_pts, std::vector<double>& peak, double& plane, std::vector<double>& ux, std::vector<double>& uy, std::vector<double>& sxx, std::vector<double>& syy, std::vector<double>& sxy, std::vector<vsol_point_2d_sptr> ps_list, int n_peaks, double xmin, double ymin) { //find the smallest intensity value in polygon plane = 65000.; for (auto & img_pt : img_pts) { if ( img_pt.z() < plane ) plane = img_pt.z(); } // With multiple peaks, finding the largest is more complex, // Let's assume that the largest value around each peak will occur near the // selected position. So let's just look in that local area for a couple pixels. for (int j=0; j < n_peaks; ++j) { peak.push_back(0.0); // create vector elements for this peak ux.push_back(0.0); uy.push_back(0.0); sxx.push_back(0.0); syy.push_back(0.0); sxy.push_back(0.0); double xf = ps_list[j]->x() - xmin; // "picked" values of x & y for this peak double yf = ps_list[j]->y() - ymin; for (auto & img_pt : img_pts) { double dx = img_pt.x() - xf; double dy = img_pt.y() - yf; // is this point within 2 pixels of selected peak's "picked" location?? if (dx >= -2. && dx <= 2. && dy >= -2. && dy <= 2.) if ( img_pt.z() > peak[j] ) { peak[j] = img_pt.z(); ux[j] = img_pt.x(); // these are our rough guesses uy[j] = img_pt.y(); } } // Compute various moments of the "Gaussian" distribution // For multiple peaks, the moments become much more difficult to calculate. // Let's see if a simplifying assumption can be used and still converge. This // assumption will be that the highest pixel value around the peak will be a // good starting point for the peak and x,y values. We will assume the variances // will be about half a pixel with covariance = 0. (see above and below) #if 0 // Original code, now commented out double sum = 0.0; ux = 0.0; uy = 0.0; for (unsigned i=0; i<img_pts.size(); ++i) { vgl_point_3d<double>& p = img_pts[i]; double w = p.z()-plane; sum += w; double x = p.x(), y = p.y(); ux += w*x; uy += w*y; sxx[j] += x*x*w; syy[j] += y*y*w; sxy[j] += x*y*w; } if (sum<=0) return false; ux /= sum; uy /= sum; sxx[j] = 0; syy[j] = 0; sxy[j] = 0; for (unsigned i=0; i<img_pts.size(); ++i) { vgl_point_3d<double>& p = img_pts[i]; double w = p.z()-plane; double x = p.x(), y = p.y(); sxx[j] += (x-ux)*(x-ux)*w; syy[j] += (y-uy)*(y-uy)*w; sxy[j] += (x-ux)*(y-uy)*w; } sxx[j] /= sum; syy[j] /= sum; sxy[j] /= sum; #else // more rough guesses sxx[j] = 0.5; syy[j] = 0.5; sxy[j] = 0.0; #endif // 0 } // end of for j loop return true; } // ------------------------------------------------------------ //: Adjust the parameters of the 2d gaussian // Returns adjusted fit parameters vnl_vector<double> sdet_gauss_fit::adjust( const std::vector<vgl_point_3d<double> >& img_pts, std::vector<vsol_point_2d_sptr> ps_list, int n_peaks, std::ofstream& outfile, double xmin, double ymin) { unsigned num_pixels = img_pts.size(); unsigned num_unknowns = 6*n_peaks + 1; // zero level + (6 * number of peaks) unsigned num_residuals = num_pixels; // Do some calculations to find reasonable values to start with // We want to be able to draw a polygon on the image and fit only the // pixels in that polygon. So here the pixels and their x,y location // in the image are stored in a std::vector<vgl_point_3d<double> img_pnts double plane; std::vector<double> peak; std::vector<double> ux; std::vector<double> uy; std::vector<double> sxx; std::vector<double> syy; std::vector<double> sxy; if (!init(img_pts, peak, plane, ux, uy, sxx, syy, sxy, std::move(ps_list), n_peaks, xmin, ymin)) { outfile << "ERROR!! sdet_gauss_fit::adjust(), Cannot init()" << std::endl; std::cerr << "ERROR!! sdet_gauss_fit::adjust(), Cannot init()\n"; } for (int i=0; i < n_peaks; ++i) { #if 0 outfile << "Init values:\n-----------------------------------------------\n Peak " << i+1 << "\n -------------------------\nplane= " << plane << std::endl << "peak=" << peak[i] << ", ux=" << ux[i] << ", uy=" << uy[i] << ", sxx=" << sxx[i] << ", syy=" << syy[i] << ", sxy=" << sxy[i] << std::endl; outfile.flush(); #endif std::cout << "Init values:\n-----------------------------------------------\n Peak " << i+1 << "\n -------------------------\nplane= " << plane << std::endl << "peak=" << peak[i] << ", ux=" << ux[i] << ", uy=" << uy[i] << ", sxx=" << sxx[i] << ", syy=" << syy[i] << ", sxy=" << sxy[i] << std::endl; } // Initialize the least squares function sdet_adjust_lsqr lsf(img_pts, num_unknowns, num_residuals, n_peaks); // -------- // Create the Levenberg Marquardt minimizer vnl_levenberg_marquardt levmarq(lsf); #ifdef JIL_DIAGNOSTICS levmarq.set_verbose(true); levmarq.set_trace(true); #endif //Use the default values - Leaving these calls for potential future need #if 0 // Set the x-tolerance. When the length of the steps taken in X (variables) // are no longer than this, the minimization terminates. levmarq.set_x_tolerance(1e-10); // Set the epsilon-function. This is the step length for FD Jacobian. levmarq.set_epsilon_function(1); // Set the f-tolerance. When the successive RMS errors are less than this, // minimization terminates. levmarq.set_f_tolerance(1e-15); #endif // Set the maximum number of iterations levmarq.set_max_function_evals(1000); // Create an INITIAL values of parameters with which to start vnl_vector<double> unknowns(num_unknowns); unknowns[0] = plane; for (int i=0; i < n_peaks; ++i) { unknowns[1+6*i] = peak[i]; unknowns[2+6*i] = ux[i]; unknowns[3+6*i] = uy[i]; unknowns[4+6*i] = sxx[i]; unknowns[5+6*i] = syy[i]; unknowns[6+6*i] = sxy[i]; outfile << "max pixel for peak " << i+1 << " = " << peak[i] << std::endl; } std::cout << "\nStarting Levenberg-Marquardt minimizer, may take a few seconds per iteration" << std::endl; // Minimize the error and get best correspondence vertices and translations levmarq.minimize(unknowns); // Summarize the results levmarq.diagnose_outcome(); #if 0 outfile << "Min error of " << levmarq.get_end_error() << " at the following local minima :" << std::endl; #endif std::cout << "Min error of " << levmarq.get_end_error() << " at the following local minima :" << std::endl; // print out parameter fit results #if 0 outfile << " -----------------------------\nFitted parameters:\n------------" << std::endl; #endif std::cout << " -----------------------------\nFitted parameters:\n------------" << std::endl; for (unsigned i=0; i<num_unknowns; ++i) { #if 0 outfile << "unknowns[" << i << "]= " << unknowns[i] << std::endl; if (i%6==4||i%6==5) std::cout << " sd = " << std::sqrt(unknowns[i]) << std::endl; #endif std::cout << "unknowns[" << i << "]= " << unknowns[i] << std::endl; if (i%6==4||i%6==5) std::cout << " sd = " << std::sqrt(unknowns[i]) << std::endl; if ((i % 6) == 0) { #if 0 outfile << "------------" << std::endl; #endif std::cout << "------------" << std::endl; } } outfile.flush(); std::cout.flush(); return unknowns; } // ------------------------------------------------------- // Calculate the parameters for the ellipse // Argument is fitted 2-d gaussian parameters, returns ellipse angle and parameters vnl_vector<double> sdet_gauss_fit::calculate_ellipse( vnl_vector<double> result, float x, float y, int i, int n_peaks, std::ofstream& outfile) { // First check to be sure n_peaks agrees with the length of result vnl_vector<double> params(3*n_peaks); const double pi = vnl_math::pi; double theta = 0.0; // angle from x axis to ellipse major axis double a = 0.0; // ellipse major axis std deviation double b = 0.0; // ellipse minor axis std deviation double sxx = result[6*i+4]; // copy result data into local variables double syy = result[6*i+5]; double sxy = result[6*i+6]; // take care of special cases where sxy = 0 or sxx = syy // First calculate the appropriate booleans about relationship of s(nn) bool xxgtyy = (sxx > syy); bool xxeqyy = (std::fabs(sxx - syy) < 0.0001); bool xygt0 = (sxy > 0.0001); bool xyeq0 = (std::fabs(sxy) < 0.0001); // Case 7 if (xyeq0 && xxeqyy) theta = 0.0; // 0 degrees, along x axis // Case 2 else if (xxeqyy && xygt0) theta = pi/4.0; // 45 degrees, diagonal // Case 3 else if (xxeqyy && !xygt0) theta = 3.0*pi/4.0; // 135 degrees, diagonal // the other normal cases else { theta = 0.5 * std::atan(2.0 * sxy/(sxx - syy)); // Case 1 if (xxgtyy && xygt0) {} // theta is correct // Case 4 else if (xxgtyy && !xygt0) theta = theta + pi; // theta + 180 degrees // Case 5&6 else if (!xxgtyy) theta = theta + pi/2.0; // theta + 90 degrees } double angle = theta*180./pi; // now calculate the one sigma length of the major and minor axis double sqrt2 = std::sqrt(2.0); double factor = std::sqrt(sxx*sxx + syy*syy + 4.0*sxy*sxy - 2.0*sxx*syy); a = std::sqrt(sxx + syy + factor)/sqrt2; b = std::sqrt(sxx + syy - factor)/sqrt2; // print out and write results to a file too outfile << "--------------------\nresults for peak " << i+1 << std::endl; std::cout << "--------------------\nresults for peak " << i+1 << std::endl; double bkgd = result[0]; double peak = result[6*i+1]; double d_peak = peak - bkgd; outfile << "bkgd= " << bkgd << ", peak= " << peak << ", d_peak= " << d_peak << std::endl << "x= " << x << ", y= " << y << std::endl; std::cout << "bkgd= " << bkgd << ", peak= " << peak << ", d_peak= " << d_peak << std::endl << "x= " << x << ", y= " << y << std::endl; #if 0 outfile << "sxx= " << sxx << ", syy= " << syy << ", sxy= " << sxy << ", factor= " << factor << std::endl; std::cout << "sxx= " << sxx << ", syy= " << syy << ", sxy= " << sxy << ", factor= " << factor << std::endl << "sin(theta)= " << std::sin(theta) << ", cos(theta)= " << std::cos(theta) << std::endl; #endif outfile << "theta= " << theta << ", angle= " << angle << ", a= " << a << ", b= " << b << std::endl; std::cout << "theta= " << theta << ", angle= " << angle << ", a= " << a << ", b= " << b << std::endl; outfile.flush(); std::cout.flush(); params[0] = theta; params[1] = a; params[2] = b; return params; }
{ "pile_set_name": "Github" }
feature done blob mark :1 data 10 keepme v1 reset refs/heads/branchO commit refs/heads/branchO mark :2 author Full Name <[email protected]> 2000000000 +0100 committer Full Name <[email protected]> 2000000000 +0100 data 2 A M 100644 :1 moduleA/keepme blob mark :3 data 10 keepme v2 commit refs/heads/branchO mark :4 author Full Name <[email protected]> 2000050000 +0100 committer Full Name <[email protected]> 2000050000 +0100 data 2 G from :2 M 100644 :3 moduleA/keepme commit refs/heads/branchI mark :5 author Full Name <[email protected]> 2000070000 +0100 committer Full Name <[email protected]> 2000070000 +0100 data 29 I: Merge commit 'D' into 'H' from :4 merge :2 commit refs/heads/branchO mark :6 author Full Name <[email protected]> 2000080000 +0100 committer Full Name <[email protected]> 2000080000 +0100 data 29 J: Merge commit 'H' into 'D' from :2 merge :4 blob mark :7 data 10 keepme v3 commit refs/heads/branchO mark :8 author Full Name <[email protected]> 2000092000 +0100 committer Full Name <[email protected]> 2000092000 +0100 data 2 L from :6 M 100644 :7 moduleA/keepme blob mark :9 data 10 keepme v4 commit refs/heads/master mark :10 author Full Name <[email protected]> 3000000000 +0100 committer Full Name <[email protected]> 3000000000 +0100 data 2 Q from :8 M 100644 :9 moduleA/keepme blob mark :11 data 10 keepme v5 commit refs/heads/master mark :12 author Full Name <[email protected]> 3000030000 +0100 committer Full Name <[email protected]> 3000030000 +0100 data 2 T from :10 M 100644 :11 moduleA/keepme blob mark :13 data 10 keepme v6 commit refs/heads/master mark :14 author Full Name <[email protected]> 3000060000 +0100 committer Full Name <[email protected]> 3000060000 +0100 data 2 W from :12 M 100644 :13 moduleA/keepme done
{ "pile_set_name": "Github" }
# This test is like sto_using_select, except that we test access via a # hash index. setup { CREATE TABLE sto1 (c int NOT NULL); INSERT INTO sto1 SELECT generate_series(1, 1000); CREATE INDEX idx_sto1 ON sto1 USING HASH (c); } setup { VACUUM ANALYZE sto1; } teardown { DROP TABLE sto1; } session "s1" setup { BEGIN ISOLATION LEVEL REPEATABLE READ; } step "noseq" { SET enable_seqscan = false; } step "s1f1" { SELECT c FROM sto1 where c = 1000; } step "s1f2" { SELECT c FROM sto1 where c = 1001; } teardown { ROLLBACK; } session "s2" step "s2sleep" { SELECT setting, pg_sleep(6) FROM pg_settings WHERE name = 'old_snapshot_threshold'; } step "s2u" { UPDATE sto1 SET c = 1001 WHERE c = 1000; } permutation "noseq" "s1f1" "s2sleep" "s2u" "s1f2"
{ "pile_set_name": "Github" }
/* * Scilab ( http://www.scilab.org/ ) - This file is part of Scilab * Copyright (C) 2010-2011 - DIGITEO - Allan CORNET * * Copyright (C) 2012 - 2016 - Scilab Enterprises * * This file is hereby licensed under the terms of the GNU GPL v2.0, * pursuant to article 5.3.4 of the CeCILL v.2.1. * This file was originally licensed under the terms of the CeCILL v2.1, * and continues to be available under such terms. * For more information, see the COPYING file which you should have received * along with this program. * */ /*--------------------------------------------------------------------------*/ #if defined(__linux__) #define _GNU_SOURCE /* Bug 5673 fix: avoid dependency on GLIBC_2.7 */ #endif /*--------------------------------------------------------------------------*/ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "sci_malloc.h" #include "fscanfMat.h" #include "charEncoding.h" #include "BOOL.h" #include "localization.h" #include "Scierror.h" #include "os_string.h" #include "freeArrayOfString.h" #include "mgetl.h" #include "mopen.h" #include "mclose.h" #include "numericconstants_interface.h" /*--------------------------------------------------------------------------*/ #define EOL "\n" #define NanString "Nan" #define InfString "Inf" #define NegInfString "-Inf" /*--------------------------------------------------------------------------*/ #if _MSC_VER #define READ_ONLY_TEXT_MODE L"rt" #else #define READ_ONLY_TEXT_MODE L"r" #endif /*--------------------------------------------------------------------------*/ #define NB_FORMAT_SUPPORTED 7 static char *supportedFormat[NB_FORMAT_SUPPORTED] = {"lf", "lg", "d", "i", "e", "f", "g"}; /*--------------------------------------------------------------------------*/ static BOOL itCanBeMatrixLine(char *line, char *format, char *separator); static int getNbColumnsInLine(char *line, char *format, char *separator); static int getNumbersColumnsInLines(char **lines, int sizelines, int nbLinesText, char *format, char *separator); static int getNumbersLinesOfText(char **lines, int sizelines, char *format, char *separator); static char **splitLine(char *str, char *sep, int *toks, char meta); static double *getDoubleValuesFromLines(char **lines, int sizelines, int nbLinesText, char *format, char *separator, int m, int n); static double *getDoubleValuesInLine(char *line, char *format, char *separator, int nbColumnsMax); static BOOL checkFscanfMatFormat(char *format); static char *getCleanedFormat(char *format); static BOOL isOnlyBlankLine(const char *line); static char **removeEmptyLinesAtTheEnd(char **lines, int *sizelines); static BOOL isValidLineWithOnlyOneNumber(char *line); static char ** removeTextLinesAtTheEnd(char **lines, int *sizelines, char *format, char *separator); /*--------------------------------------------------------------------------*/ fscanfMatResult *fscanfMat(char *filename, char *format, char *separator) { int fd = 0; int f_swap = 0; double res = 0.0; int errMOPEN = MOPEN_INVALID_STATUS; int i = 0; int nbLinesTextDetected = 0; int nbColumns = 0; int nbRows = 0; fscanfMatResult *resultFscanfMat = NULL; wchar_t **pwstLines = NULL; char **lines = NULL; int nblines = 0; double *dValues = NULL; wchar_t* filenameW = NULL; if ((filename == NULL) || (format == NULL) || (separator == NULL)) { return NULL; } if (!checkFscanfMatFormat(format)) { resultFscanfMat = (fscanfMatResult*)(MALLOC(sizeof(fscanfMatResult))); if (resultFscanfMat) { resultFscanfMat->err = FSCANFMAT_FORMAT_ERROR; resultFscanfMat->m = 0; resultFscanfMat->n = 0; resultFscanfMat->sizeText = 0; resultFscanfMat->text = NULL; resultFscanfMat->values = NULL; } return resultFscanfMat; } filenameW = to_wide_string(filename); errMOPEN = mopen(filenameW, READ_ONLY_TEXT_MODE, f_swap, &fd); FREE(filenameW); if (errMOPEN != MOPEN_NO_ERROR) { resultFscanfMat = (fscanfMatResult*)(MALLOC(sizeof(fscanfMatResult))); if (resultFscanfMat) { resultFscanfMat->err = FSCANFMAT_MOPEN_ERROR; resultFscanfMat->m = 0; resultFscanfMat->n = 0; resultFscanfMat->sizeText = 0; resultFscanfMat->text = NULL; resultFscanfMat->values = NULL; } return resultFscanfMat; } nblines = mgetl(fd, -1, &pwstLines); mclose(fd); if (nblines < 0) { resultFscanfMat = (fscanfMatResult*)(MALLOC(sizeof(fscanfMatResult))); if (resultFscanfMat) { resultFscanfMat->err = FSCANFMAT_READLINES_ERROR; resultFscanfMat->m = 0; resultFscanfMat->n = 0; resultFscanfMat->sizeText = 0; resultFscanfMat->text = NULL; resultFscanfMat->values = NULL; } freeArrayOfWideString(pwstLines, nblines); return resultFscanfMat; } lines = (char**)MALLOC(sizeof(char*) * nblines); for (i = 0; i < nblines; i++) { lines[i] = wide_string_to_UTF8(pwstLines[i]); } freeArrayOfWideString(pwstLines, nblines); lines = removeEmptyLinesAtTheEnd(lines, &nblines); lines = removeTextLinesAtTheEnd(lines, &nblines, format, separator); nbLinesTextDetected = getNumbersLinesOfText(lines, nblines, format, separator); nbRows = nblines - nbLinesTextDetected; nbColumns = getNumbersColumnsInLines(lines, nblines, nbLinesTextDetected, format, separator); dValues = getDoubleValuesFromLines(lines, nblines, nbLinesTextDetected, format, separator, nbColumns, nbRows); if (dValues) { resultFscanfMat = (fscanfMatResult*)(MALLOC(sizeof(fscanfMatResult))); if (resultFscanfMat) { if (nbLinesTextDetected > 0) { if (lines) { for (i = nbLinesTextDetected; i < nblines; i++) { if (lines[i]) { FREE(lines[i]); lines[i] = NULL; } } } resultFscanfMat->text = lines; } else { freeArrayOfString(lines, nblines); resultFscanfMat->text = NULL; } resultFscanfMat->sizeText = nbLinesTextDetected; resultFscanfMat->m = nbRows; resultFscanfMat->n = nbColumns; resultFscanfMat->values = dValues; resultFscanfMat->err = FSCANFMAT_NO_ERROR; } else { FREE(dValues); freeArrayOfString(lines, nblines); } } else { freeArrayOfString(lines, nblines); if (nbColumns == 0 || nbRows == 0) { resultFscanfMat = (fscanfMatResult*)(MALLOC(sizeof(fscanfMatResult))); if (resultFscanfMat) { resultFscanfMat->err = FSCANFMAT_READLINES_ERROR; resultFscanfMat->m = 0; resultFscanfMat->n = 0; resultFscanfMat->sizeText = 0; resultFscanfMat->text = NULL; resultFscanfMat->values = NULL; } } } return resultFscanfMat; } /*--------------------------------------------------------------------------*/ void freeFscanfMatResult(fscanfMatResult *resultStruct) { if (resultStruct) { if (resultStruct->text) { freeArrayOfString(resultStruct->text, resultStruct->sizeText); resultStruct->text = NULL; } if (resultStruct->values) { FREE(resultStruct->values); resultStruct->values = NULL; } resultStruct->err = FSCANFMAT_ERROR; resultStruct->m = 0; resultStruct->n = 0; resultStruct->sizeText = 0; FREE(resultStruct); resultStruct = NULL; } } /*--------------------------------------------------------------------------*/ static BOOL itCanBeMatrixLine(char *line, char *format, char *separator) { if (line) { int ierr = 0; double dValue = 0.; ierr = sscanf(line, format, &dValue); if ((ierr == EOF) || (ierr == 0)) { char *str = os_strdup(line); if (str) { ierr = sscanf(line, "%4s", str); if ((ierr != 0) && (ierr != EOF)) { if ((strncmp(str, NanString, (int)strlen(NanString)) == 0) || (strncmp(str, NegInfString, (int)strlen(NegInfString)) == 0) || (strncmp(str, InfString, (int)strlen(InfString)) == 0)) { FREE(str); str = NULL; return TRUE; } } FREE(str); str = NULL; } } else { return TRUE; } } return FALSE; } /*--------------------------------------------------------------------------*/ static int getNumbersLinesOfText(char **lines, int sizelines, char *format, char *separator) { int numberOfLines = 0; if (lines) { int i = 0; for (i = 0; i < sizelines; i++) { if (!itCanBeMatrixLine(lines[i], format, separator)) { numberOfLines++; } else { return numberOfLines; } } } return numberOfLines; } /*--------------------------------------------------------------------------*/ static int getNumbersColumnsInLines(char **lines, int sizelines, int nbLinesText, char *format, char *separator) { int previousNbColumns = 0; int NbColumns = 0; BOOL firstLine = TRUE; if (lines) { int i = 0; int firstLinesMatrix = nbLinesText; for (i = firstLinesMatrix; i < sizelines; i++) { NbColumns = getNbColumnsInLine(lines[i], format, separator); if (firstLine) { previousNbColumns = NbColumns; firstLine = FALSE; } else { if (previousNbColumns != NbColumns) { return 0; } } } } return NbColumns; } /*--------------------------------------------------------------------------*/ static int getNbColumnsInLine(char *line, char *format, char *separator) { int nbColums = 0; if (line && format && separator) { int i = 0; int nbTokens = 0; char **splittedStr = splitLine(line, separator, &nbTokens, 0); if (nbTokens == 0) { freeArrayOfString(splittedStr, nbTokens); return nbColums; } if (splittedStr) { for (i = 0; i < nbTokens; i++) { double dValue = 0.; int ierr = sscanf(splittedStr[i], format, &dValue); if ((ierr != 0) && (ierr != EOF)) { nbColums++; } else { char *str = os_strdup(splittedStr[i]); strcpy(str, ""); ierr = sscanf(splittedStr[i], "%4s", str); if ((ierr != 0) && (ierr != EOF)) { if ( (strcmp(str, NanString) == 0) || (strcmp(str, NegInfString) == 0) || (strcmp(str, InfString) == 0) ) { nbColums++; } else { freeArrayOfString(splittedStr, nbTokens); /* bug 6889 */ if (nbColums) { nbColums--; } FREE(str); str = NULL; return nbColums; } } else { FREE(str); str = NULL; freeArrayOfString(splittedStr, nbTokens); return nbColums; } FREE(str); str = NULL; } } freeArrayOfString(splittedStr, nbTokens); } } return nbColums; } /*--------------------------------------------------------------------------*/ static char **splitLine(char *str, char *sep, int *toks, char meta) { char **retstr = NULL; char *idx = NULL; char *end = NULL; char *sep_end = NULL; char *sep_idx = NULL; int len = 0; int curr_str = 0; char last_char = 0xFF; *toks = 0; if ((sep == NULL) || (str == NULL)) { return NULL; } sep_end = sep + strlen(sep); end = str + strlen(str); sep_idx = sep; idx = str; if (strstr(str, sep) == NULL) { if ((int)strlen(str) > 0) { if (isValidLineWithOnlyOneNumber(str)) { retstr = (char **) MALLOC(sizeof(char *)); if (retstr) { retstr[0] = os_strdup(str); *toks = 1; } } } return retstr; } retstr = (char **) MALLOC((sizeof(char *) * (int)strlen(str))); if (retstr == NULL) { *toks = 0; return NULL; } while (idx < end) { while (sep_idx < sep_end) { if ((*idx == *sep_idx) && (last_char != meta)) { if (len > 0) { if (curr_str < (int)strlen(str)) { retstr[curr_str] = (char *) MALLOC((sizeof(char) * len) + 1); if (retstr[curr_str] == NULL) { freeArrayOfString(retstr, curr_str); *toks = 0; return NULL; } memcpy(retstr[curr_str], (idx - len), len); retstr[curr_str][len] = 0; len = 0; curr_str++; last_char = *idx; idx++; } if (curr_str >= (int)strlen(str)) { *toks = curr_str + 1; return retstr; } } else { last_char = *idx; idx++; sep_idx = sep; len = 0; } } else { sep_idx++; } } sep_idx = sep; len++; last_char = *idx; idx++; } if (len > 0) { retstr[curr_str] = (char *) MALLOC((sizeof(char) * len) + 1); if (retstr[curr_str] == NULL) { *toks = 0; FREE(retstr); return NULL; } memcpy(retstr[curr_str], (idx - len), len); retstr[curr_str][len] = 0; *toks = curr_str + 1; } return retstr; } /*--------------------------------------------------------------------------*/ static double *getDoubleValuesFromLines(char **lines, int sizelines, int nbLinesText, char *format, char *separator, int m, int n) { double *dValues = NULL; if (m == 0 || n == 0) { return NULL; } dValues = (double*) MALLOC(sizeof(double) * (m * n)); if (dValues) { int i = 0; int firstLinesMatrix = nbLinesText; for (i = firstLinesMatrix; i < sizelines; i++) { double *dValsTmp = getDoubleValuesInLine(lines[i], format, separator, m); if (dValsTmp) { int j = 0; for (j = 0; j < m; j++) { dValues[(i - firstLinesMatrix) + n * j] = dValsTmp[j]; } FREE(dValsTmp); dValsTmp = NULL; } } } return dValues; } /*--------------------------------------------------------------------------*/ static double *getDoubleValuesInLine(char *line, char *format, char *separator, int nbColumnsMax) { double *dValues = NULL; if (line && format && separator) { int nbTokens = 0; char **splittedStr = splitLine(line, separator, &nbTokens, 0); if (splittedStr) { int i = 0; dValues = (double*)MALLOC(sizeof(double) * nbColumnsMax); for (i = 0; i < nbColumnsMax; i++) { int ierr = 0; double dValue = 0.; char *cleanedFormat = getCleanedFormat(format); int iLen = (int)strlen(cleanedFormat); switch (cleanedFormat[iLen - 1]) { case 'e' : case 'g' : case 'f' : { if (cleanedFormat[iLen - 2] == 'l') { double tmp = 0.; ierr = sscanf(splittedStr[i], cleanedFormat, &tmp); dValue = tmp; } else { float tmp = 0.; ierr = sscanf(splittedStr[i], cleanedFormat, &tmp); dValue = tmp; } break; } case 'd' : case 'i' : { int tmp = 0; ierr = sscanf(splittedStr[i], cleanedFormat, &tmp); dValue = tmp; break; } } FREE(cleanedFormat); if ((ierr != 0) && (ierr != EOF)) { dValues[i] = dValue; } else { char *str = os_strdup(line); strcpy(str, ""); ierr = sscanf(splittedStr[i], "%4s", str); if ((ierr != 0) && (ierr != EOF)) { if ( (strcmp(str, NanString) == 0) || (strcmp(str, NegInfString) == 0) || (strcmp(str, InfString) == 0) ) { if (strcmp(str, NanString) == 0) { dValues[i] = nc_nan(); } if (strcmp(str, NegInfString) == 0) { dValues[i] = nc_neginf(); } if (strcmp(str, InfString) == 0) { dValues[i] = nc_inf(); } } else { freeArrayOfString(splittedStr, nbTokens); FREE(dValues); dValues = NULL; FREE(str); str = NULL; return NULL; } } else { freeArrayOfString(splittedStr, nbTokens); FREE(dValues); dValues = NULL; FREE(str); str = NULL; return NULL; } FREE(str); str = NULL; } } freeArrayOfString(splittedStr, nbTokens); } } return dValues; } /*--------------------------------------------------------------------------*/ static BOOL checkFscanfMatFormat(char *format) { if (format) { char *tokenPercent1 = strchr(format, '%'); char *tokenPercent2 = strrchr(format, '%'); if ((tokenPercent2 && tokenPercent1) && (tokenPercent1 == tokenPercent2)) { char *cleanedFormat = getCleanedFormat(format); if (cleanedFormat) { FREE(cleanedFormat); cleanedFormat = NULL; return TRUE; } } } return FALSE; } /*--------------------------------------------------------------------------*/ static char *getCleanedFormat(char *format) { char *cleanedFormat = NULL; if (format) { char *percent = strchr(format, '%'); if (percent) { int i = 0; for (i = 0; i < NB_FORMAT_SUPPORTED; i++) { char *token = strstr(percent, supportedFormat[i]); if (token) { int nbcharacters = (int)(strlen(percent) - strlen(token)); cleanedFormat = os_strdup(percent); cleanedFormat[nbcharacters] = 0; if ( (nbcharacters - 1 > 0) && (isdigit(cleanedFormat[nbcharacters - 1]) || (cleanedFormat[nbcharacters - 1]) == '.') || (cleanedFormat[nbcharacters - 1]) == '%') { strcat(cleanedFormat, supportedFormat[i]); return cleanedFormat; } else { FREE(cleanedFormat); cleanedFormat = NULL; } } } } } return cleanedFormat; } /*--------------------------------------------------------------------------*/ static char **removeEmptyLinesAtTheEnd(char **lines, int *sizelines) { int i = 0; int nbLinesToRemove = 0; if (lines) { for (i = *sizelines - 1; i >= 0; i--) { if (lines[i]) { if ( (strcmp(lines[i], "") == 0) || (isOnlyBlankLine(lines[i])) ) { FREE(lines[i]); lines[i] = NULL; nbLinesToRemove++; } else { break; } } } if (nbLinesToRemove > 0) { lines = (char**)REALLOC(lines, sizeof(char*) * (*sizelines - nbLinesToRemove)); *sizelines = *sizelines - nbLinesToRemove; } } else { *sizelines = 0; } return lines; } /*--------------------------------------------------------------------------*/ static BOOL isValidLineWithOnlyOneNumber(char *line) { if (line) { char *pEnd = NULL; strtod(line, &pEnd); if ((pEnd) && ((int)strlen(pEnd) == 0)) { return TRUE; } else { if ((strncmp(line, NanString, (int)strlen(NanString)) == 0) || (strncmp(line, NegInfString, (int)strlen(NegInfString)) == 0) || (strncmp(line, InfString, (int)strlen(InfString)) == 0)) { return TRUE; } } } return FALSE; } /*--------------------------------------------------------------------------*/ static BOOL isOnlyBlankLine(const char *line) { if (line) { int i = 0; for (i = 0; i < (int) strlen(line); i++) { if (line[i] != ' ') { return FALSE; } } } return TRUE; } /*--------------------------------------------------------------------------*/ static char ** removeTextLinesAtTheEnd(char **lines, int *sizelines, char *format, char *separator) { char **linesReturned = NULL; int i = 0; int nbLinesToRemove = 0; for (i = *sizelines - 1; i > 0; i--) { if (itCanBeMatrixLine(lines[i], format, separator) == FALSE) { nbLinesToRemove++; FREE(lines[i]); lines[i] = NULL; } else { break; } } if (nbLinesToRemove > 0) { //must free last lines. *sizelines = *sizelines - nbLinesToRemove; linesReturned = lines; } else { linesReturned = lines; } return linesReturned; } /*--------------------------------------------------------------------------*/
{ "pile_set_name": "Github" }
//Stock Basics 01 - https://www.youtube.com/watch?v=CcJP8TX7CVc //Stock Basics 02 - https://www.youtube.com/watch?v=Pi6FXIYvTkk //Sample file: http://bit.ly/taq-sample display "Don't run this, copy paste it" exit(); t: read_from_path('taq/taq20141030.table') //t: open_table('taq/taq20141030.table') //All tickers select unique(sym) from t //How many trades involved AAPL? select count(*) from t where sym='AAPL' //Value of the average trade (money changing hands) select avg(price * vol) as value from t //Value of the average trade for each symbol select avg(price * vol) as value from t group by sym //Closing price for AAPL select last price from t where sym = 'AAPL' //All closes for the day closes: select last price from t group by sym //All opens for the day opens: select first price from t group by sym //All average trade prices for the day (unweighted) select avg price from t group by sym //Average price for AAPL (unweighted) select avg price from t where sym='AAPL' //Volume-weighted average price for AAPL select sum(price*vol)/sum(vol) from t where sym='AAPL' //All volume-weighted average prices for the day select sum(price*vol)/sum(vol) from t group by sym //================================================================== //Build a stats table stats: select first(price) as open, last(price) as close, last(price) - first(price) as change, sum(price*vol)/sum(vol) as vwap from t group by sym //Which stock gained the most in price over the day? diffs: closes.price - opens.price; select from closes where diffs = max(diffs) max diffs select from stats where change = max(change) //Which stock lost the most? select from stats where change = min(change) //BRK A which is also one of the most valuable //Which stock lost the most as a percentage of open? select from stats where (change/open) = min(change/open) //Which stock gained the most as a percentage of open? select from stats where (change/open) = max(change/open) //Growth as percentage for all stocks select sym, change/open as growth from stats select (last(price)-first(price))/first(price) as growth from t group by sym //Which stocks gained over the day? select from stats where change > 0 //Which stocks closed higher than their VWAP? closes.price > stats.vwap better: select from closes where closes.price > stats.vwap closes.sym[which closes.price > stats.vwap] better.sym select from stats where close > vwap //Which stock had the highest volume (most shares traded)? select from (select sum(vol) from t group by sym) where vol = max(vol) //Which stock caused the most money to change hands? select from (select floor sum(vol*price) as value from t group by sym) where value = max(value)
{ "pile_set_name": "Github" }
// Flexible Nav jQuery library. // ================================ // **Flexible Nav** is a small **jQuery** library // which add a smart navigation bar on the right of the page. // It improves a web page **navigation** and helps // to **visualize** different sections // of a document, an article,.. any web page. // // Nav links are **distributed proportionally** to the page sections. // See how **your scrollbar *"weds"* these links** :) // // - - - // // You can easily use it on any website with the *Bookmarklet*. // // **Save this bookmark** by drag and dropping it in your bar... // // <a class="bookmark" title="Flexible Nav bookmarklet" href="javascript:(function(){window.flexibleNavBase='http://gre.github.io/flexible-nav/lib/';var a=document.getElementsByTagName('head')[0],b=document.createElement('script');b.type='text/javascript';b.src=flexibleNavBase+'bookmarklet.min.js';a.appendChild(b);})(); void 0" target="_blank">FlexibleNav bookmarklet</a> // // ...and **click on it in any website**! // // - - - // // **This page is a 3-in-one document!** // // * First, it explains goals and possible usages of the library. // * Second, it presents **a library usage** // _(see this flexible box right panel?)_. // * Third, it shows the **annotated JS code** _(thanks to docco)_ // // Download // -------- // You can also use it in your websites. // // <a class="download" target="_blank" href="https://github.com/gre/flexible-nav">Download or fork me on github</a> // // Usages // ----- // // #### Generation and Flexibility #### // // The library can generate for you the nav sidebar content // providing elements to display in navigation. // // By default, it uses `h1` to `h3` elements to retrieve and locate // the different sections of a document but you can override these // elements selector. // // You have usually two kind of selected elements to use: // // * **Select a title**. The link will take the title as text. // * **Select any container** and add a **`data-navtext` attribute** // to define the title you want. // // Example: `<div id="demo" data-navtext="Demo of the game">...` // // * **Simple usage used in this page** // // var nav = new FlexibleNavMaker().make().prependTo('body'); // new FlexibleNav(nav); // // * **Selecting element you want** // // new FlexibleNavMaker(".navtitle"); // // Using this code bellow, all nodes having this `navtitle` class // will appear in the flexible nav panel. // // #### Flexibility only #### // // You can also create your own nav links to have more controls of used links. // Conventionnally, you need to use // a `<nav />` element with a `flexible-nav` class and `<a href="#myidtarget" />` kind of elements for links. // // * **Add flexibility to an existing nav** // // new FlexibleNav($('#myNav')); // // *(replace myNav by you nav id)* // /*! * Flexible Nav - 2011 - by @greweb * http://www.apache.org/licenses/LICENSE-2.0 */ // The code // ======== // (function($){ "use strict"; // **Utilities functions** // // Generate an unique number identifier var _uuid = 0; var uuid = function(){ return ++_uuid; }; // Template for creating a nav element with links. // // * `links` : an Array of *{ href, text }* var tmplNav = function(links) { var nav = $('<nav class="flexible-nav"><ul></ul></nav>'); var lis = $.map(links, function(link){ return $('<li><a href="'+link.href+'">'+link.text+'</a></li>')[0]; }); nav.find('ul').append(lis); return nav; } // Retrieve a node pointed by an a element `aEl` hash href. var targetForLink = function(aEl) { var href = $(aEl).attr('href'); if(href.substring(0,1) == '#') { var target = $(href); return target.size() ? target : null; } return null; } // FlexibleNavMaker // ------------------------ // Dynamically create a nav. // // * `selector` (optional) : selector for all nodes to add in nav. // using `h1, h2, h3` if not setted. window.FlexibleNavMaker = function(selector) { var self = this; self.nodes = $(selector || 'h1,h2,h3'); // ### .make() ### // An instance of FlexibleNavMaker contains only a `make` method // which create the nav element with nodes matching `selector`. self.make = function() { var links = self.nodes.map(function(){ var node = $(this); // Find the id or create a unique one var id = node.attr('id'); if(!id) { while(!id) { id = 'n'+( uuid() ); if($('#'+id).size()>0) id = null; } node.attr('id', id); } // The text link is the `data-navtext` attribute or the node text. var text = node.attr('data-navtext') || node.text(); return { href: '#'+id, text: text }; }); return tmplNav(links); } } // FlexibleNav // ----------- // Make a nav element "flexible". // // * `nav` : a nav DOM element window.FlexibleNav = function(nav) { var self = this; self.nav = $(nav); // Init links adding some classes. // // Set the target node name class. // Example: class `tnn-h1` self.updateClasses = function() { self.nav.find('a').each(function(){ var node = $(this); var target = targetForLink(node); if(target) { node.addClass('tnn-'+target[0].nodeName.toLowerCase()); } }); } // ### .update() ### self.update = function() { var documentHeight = $(document).height(); var windowHeight = $(window).height(); // Transform links into array of visible target `top` position and link `node`. var links = self.nav.find('a').map(function(){ var node = $(this); var target = targetForLink(node); if(target==null || !target.is(':visible')) return null; return { top: target.offset().top, node: node }; }); // Update nav link positions. $.each(links, function(i, link) { link.node.css('top', (100*link.top/documentHeight)+'%'); }); // Update current section. var scrollTop = $(document).scrollTop(); var closest = null; $.each(links, function(i, link){ link.node.removeClass('current'); if(closest==null || (link.top <= scrollTop+10 && link.top > closest.top)) closest = link; }); closest && closest.node.addClass('current'); } // ### Init ### // Bind scroll event and init nav. $(window).scroll(function(){ self.update(); }); self.updateClasses(); self.update(); } }(jQuery));
{ "pile_set_name": "Github" }
/*************************************************************************** ** ** ** Polyphone, a soundfont editor ** ** Copyright (C) 2013-2019 Davy Triponney ** ** ** ** This program is free software: you can redistribute it and/or modify ** ** it under the terms of the GNU General Public License as published by ** ** the Free Software Foundation, either version 3 of the License, or ** ** (at your option) any later version. ** ** ** ** This program is distributed in the hope that it will be useful, ** ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** ** GNU General Public License for more details. ** ** ** ** You should have received a copy of the GNU General Public License ** ** along with this program. If not, see http://www.gnu.org/licenses/. ** ** ** **************************************************************************** ** Author: Davy Triponney ** ** Website/Contact: https://www.polyphone-soundfonts.com ** ** Date: 01.01.2013 ** ***************************************************************************/ #ifndef DETAILSMANAGER_H #define DETAILSMANAGER_H #include <QObject> #include <QMutex> #include <QMap> class SoundfontDetails; class UrlReaderJson; class DetailsManager: public QObject { Q_OBJECT public: // Singleton: get the instance of the object and finally kill it static DetailsManager * getInstance(); static void kill(); // Ask for details. The signal "detailsReady" will be then emitted void askForSoundfontDetails(int id, bool forceReload); // Get the details of a soundfont SoundfontDetails * getDetails(int id); signals: // Emitted when soundfont details are ready void detailsReady(int id); // Emitted when it was not possible to get the details void detailsFailed(int id, QString error); private slots: void downloadCompleted(QString error); private: DetailsManager(); ~DetailsManager(); void run(); static DetailsManager * s_instance; QMap<int, SoundfontDetails *> _soundfontDetails; // Classified by ID UrlReaderJson * _urlReaderDetails; int _currentReaderDetailId; QList<int> _stack; QMutex _mutex; }; #endif // DETAILSMANAGER_H
{ "pile_set_name": "Github" }
div p { margin-bottom: 0 !important; text-align: center !important; width: 100%; }
{ "pile_set_name": "Github" }
package org.jboss.resteasy.test.providers.jackson2.jsonfilter.resource; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; /** * @author <a href="mailto:[email protected]">Jim Ma</a> * */ @Path("/products") public class Jackson2Resource { @GET @Produces("application/json") @Path("{id}") public Jackson2Product getProduct(@PathParam("id") int id) { return new Jackson2Product(id, "Iphone"); } }
{ "pile_set_name": "Github" }
// Code generated by smithy-go-codegen DO NOT EDIT. package migrationhub import ( "context" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/retry" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" smithy "github.com/awslabs/smithy-go" "github.com/awslabs/smithy-go/middleware" smithyhttp "github.com/awslabs/smithy-go/transport/http" ) // Registers a new migration task which represents a server, database, etc., being // migrated to AWS by a migration tool. This API is a prerequisite to calling the // NotifyMigrationTaskState API as the migration tool must first register the // migration task with Migration Hub. func (c *Client) ImportMigrationTask(ctx context.Context, params *ImportMigrationTaskInput, optFns ...func(*Options)) (*ImportMigrationTaskOutput, error) { stack := middleware.NewStack("ImportMigrationTask", smithyhttp.NewStackRequest) options := c.options.Copy() for _, fn := range optFns { fn(&options) } addawsAwsjson11_serdeOpImportMigrationTaskMiddlewares(stack) awsmiddleware.AddRequestInvocationIDMiddleware(stack) smithyhttp.AddContentLengthMiddleware(stack) AddResolveEndpointMiddleware(stack, options) v4.AddComputePayloadSHA256Middleware(stack) retry.AddRetryMiddlewares(stack, options) addHTTPSignerV4Middleware(stack, options) awsmiddleware.AddAttemptClockSkewMiddleware(stack) addClientUserAgent(stack) smithyhttp.AddErrorCloseResponseBodyMiddleware(stack) smithyhttp.AddCloseResponseBodyMiddleware(stack) addOpImportMigrationTaskValidationMiddleware(stack) stack.Initialize.Add(newServiceMetadataMiddleware_opImportMigrationTask(options.Region), middleware.Before) addRequestIDRetrieverMiddleware(stack) addResponseErrorMiddleware(stack) for _, fn := range options.APIOptions { if err := fn(stack); err != nil { return nil, err } } handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) result, metadata, err := handler.Handle(ctx, params) if err != nil { return nil, &smithy.OperationError{ ServiceID: ServiceID, OperationName: "ImportMigrationTask", Err: err, } } out := result.(*ImportMigrationTaskOutput) out.ResultMetadata = metadata return out, nil } type ImportMigrationTaskInput struct { // Unique identifier that references the migration task. Do not store personal data // in this field. MigrationTaskName *string // The name of the ProgressUpdateStream. > ProgressUpdateStream *string // Optional boolean flag to indicate whether any effect should take place. Used to // test if the caller has permission to make the call. DryRun *bool } type ImportMigrationTaskOutput struct { // Metadata pertaining to the operation's result. ResultMetadata middleware.Metadata } func addawsAwsjson11_serdeOpImportMigrationTaskMiddlewares(stack *middleware.Stack) { stack.Serialize.Add(&awsAwsjson11_serializeOpImportMigrationTask{}, middleware.After) stack.Deserialize.Add(&awsAwsjson11_deserializeOpImportMigrationTask{}, middleware.After) } func newServiceMetadataMiddleware_opImportMigrationTask(region string) awsmiddleware.RegisterServiceMetadata { return awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "mgh", OperationName: "ImportMigrationTask", } }
{ "pile_set_name": "Github" }
// /** @file // Fat Package Localized Strings and Content. // // Copyright (c) 2013, Intel Corporation. All rights reserved.<BR> // // 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 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. // // Additional terms: In addition to the forgoing, redistribution and use // of the code is conditioned upon the FAT 32 File System Driver and all // derivative works thereof being used for and designed only to read // and/or write to a file system that is directly managed by an // Extensible Firmware Interface (EFI) implementation or by an emulator // of an EFI implementation. // // **/ #string STR_PROPERTIES_PACKAGE_NAME #language en-US "Fat package"
{ "pile_set_name": "Github" }
# Overview This section will cover the prerequisites you need to start developing with the starter project. The guide assumes a Unix-like environment; deviations for Windows users will be called out with inline note blocks. # Prerequisites Aside from mobile platform-specific SDKs, [Node.js](https://nodejs.org/dist) 4.4.x is the only external prerequisite. While any version of 4.4.x or higher should work, I've specifically tested and verified with version [4.4.0](https://nodejs.org/dist/v4.4.0/). Windows users can download the installer from the link above. For Mac OS, I recommend installing Node using [Node Version Manager](https://github.com/creationix/nvm). ## iOS Specific If you are developing for iOS, you need XCode 7. I've specifically tested with version 7.3. * [Current Version](https://developer.apple.com/xcode/download/) * [Previous Versions](https://developer.apple.com/downloads/) You'll probably also want two additional Node packages globally, which will allow you to run your application on the iOS simulator as well as on a physical device directly from the command line: $ npm install -g ios-sim $ npm install -g ios-deploy ## Android Specific If you are developing for Android, you need the the Android SDK and the Java Development SDK. I've tested with the following versions of the Android SDK: * Android SDK ([installer](http://developer.android.com/sdk/index.html#Other)) * Android SDK Tools - 24.4.0 * Android SDK Platform-tools - 23.0.1 * Android SDK Build-tools - 23.0.1 * Android 5.1.1 - API 22 * [JDK](http://www.oracle.com/technetwork/java/javase/downloads/index.html) 1.7 * [Android Studio](http://developer.android.com/sdk/index.html) - 1.4 (optional) !!! note "Note for Windows users" You can check whether you've installed these prerequisites properly by typing each the following commands into a command prompt and ensuring they can execute: `android`, `java --version`, `javac --version`, `ant --version`. ## Other Dependencies All other dependencies are installed in the project directory via `npm`. To use them **you must add `./node_modules/.bin` to your path**. Using the dependencies directly from the project directory reduces dependency hell with globally installed modules and ensures all development is done using the exact same versions of the modules. !!! warning "Attention" Do not skip this step; you need to add `./node_modules/.bin` to your path. If you try to install all the required depdencies globally, you are much more likely to run into issues. !!! note "Note for Windows users" Windows users should note that the path `.\node_modules\.bin` should be appended via the System > Environment Variables GUI, and should restart the command prompt instance for the changes to take effect. ## IDEs and Text Editors This project is platform and IDE agnostic. You can use any IDE or text editor. I recommend using the free and lightweight [Visual Studio Code](https://code.visualstudio.com) editor, as it has superb support for TypeScript. Development and debugging can be done in Chrome using its built-in Developer Tools window. !!! note "Note for Windows users" This version of the starter project is made to work with any IDE. Although I have put together an [alternate version](https://github.com/Justin-Credible/Ionic-TypeScript-MDHA-Starter) that supports Visual Studio 2015, I still highly recommend using this version. The VS2015 Cordova wrapper ("Tools for Apache Cordova" project template) can sometimes be a bit of a black box, in my opinion, which makes it harder to work with. # Environment Setup To begin, edit your path, clone the repository, install the node packages, and initialize the development environment. $ PATH=$PATH:./node_modules/.bin $ git clone https://github.com/Justin-Credible/Ionic-TypeScript-Starter.git $ cd Ionic-TypeScript-Starter $ npm install $ gulp init !!! warning "Attention" If you receive any errors while running `gulp init`, please double-check to ensure you've added `./node_modules/bin` to your path and that this path takes precedence over the globally installed node modules path. `gulp init` sets up the Cordova platform and plugins, obtains libraries, and compiles code. See [Gulp Tasks](gulp-tasks.md) for details. Your environment should now be ready for development!
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <Filter Include="源文件"> <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> </Filter> <Filter Include="头文件"> <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> <Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions> </Filter> <Filter Include="资源文件"> <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions> </Filter> </ItemGroup> <ItemGroup> <ClInclude Include="png.h"> <Filter>头文件</Filter> </ClInclude> <ClInclude Include="pngconf.h"> <Filter>头文件</Filter> </ClInclude> <ClInclude Include="pngfile.h"> <Filter>头文件</Filter> </ClInclude> <ClInclude Include="pnglibconf.h"> <Filter>头文件</Filter> </ClInclude> <ClInclude Include="zconf.h"> <Filter>头文件</Filter> </ClInclude> <ClInclude Include="zlib.h"> <Filter>头文件</Filter> </ClInclude> <ClInclude Include="as-util.h"> <Filter>头文件</Filter> </ClInclude> <ClInclude Include="decode_lz.h"> <Filter>头文件</Filter> </ClInclude> </ItemGroup> <ItemGroup> <Library Include="libpngd.lib"> <Filter>资源文件</Filter> </Library> <Library Include="zlibd.lib"> <Filter>资源文件</Filter> </Library> </ItemGroup> <ItemGroup> <ClCompile Include="exiar.cpp"> <Filter>源文件</Filter> </ClCompile> <ClCompile Include="decode_lz.c"> <Filter>源文件</Filter> </ClCompile> <ClCompile Include="pngfile.cpp"> <Filter>源文件</Filter> </ClCompile> </ItemGroup> </Project>
{ "pile_set_name": "Github" }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; function Context(indented, column, type, info, align, prev) { this.indented = indented; this.column = column; this.type = type; this.info = info; this.align = align; this.prev = prev; } function pushContext(state, col, type, info) { var indent = state.indented; if (state.context && state.context.type == "statement" && type != "statement") indent = state.context.indented; return state.context = new Context(indent, col, type, info, null, state.context); } function popContext(state) { var t = state.context.type; if (t == ")" || t == "]" || t == "}") state.indented = state.context.indented; return state.context = state.context.prev; } function typeBefore(stream, state, pos) { if (state.prevToken == "variable" || state.prevToken == "variable-3") return true; if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, pos))) return true; if (state.typeAtEndOfLine && stream.column() == stream.indentation()) return true; } function isTopScope(context) { for (;;) { if (!context || context.type == "top") return true; if (context.type == "}" && context.prev.info != "namespace") return false; context = context.prev; } } CodeMirror.defineMode("clike", function(config, parserConfig) { var indentUnit = config.indentUnit, statementIndentUnit = parserConfig.statementIndentUnit || indentUnit, dontAlignCalls = parserConfig.dontAlignCalls, keywords = parserConfig.keywords || {}, types = parserConfig.types || {}, builtin = parserConfig.builtin || {}, blockKeywords = parserConfig.blockKeywords || {}, defKeywords = parserConfig.defKeywords || {}, atoms = parserConfig.atoms || {}, hooks = parserConfig.hooks || {}, multiLineStrings = parserConfig.multiLineStrings, indentStatements = parserConfig.indentStatements !== false, indentSwitch = parserConfig.indentSwitch !== false, namespaceSeparator = parserConfig.namespaceSeparator, isPunctuationChar = parserConfig.isPunctuationChar || /[\[\]{}\(\),;\:\.]/, numberStart = parserConfig.numberStart || /[\d\.]/, number = parserConfig.number || /^(?:0x[a-f\d]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(u|ll?|l|f)?/i, isOperatorChar = parserConfig.isOperatorChar || /[+\-*&%=<>!?|\/]/; var curPunc, isDefKeyword; function tokenBase(stream, state) { var ch = stream.next(); if (hooks[ch]) { var result = hooks[ch](stream, state); if (result !== false) return result; } if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } if (isPunctuationChar.test(ch)) { curPunc = ch; return null; } if (numberStart.test(ch)) { stream.backUp(1) if (stream.match(number)) return "number" stream.next() } if (ch == "/") { if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } if (stream.eat("/")) { stream.skipToEnd(); return "comment"; } } if (isOperatorChar.test(ch)) { while (!stream.match(/^\/[\/*]/, false) && stream.eat(isOperatorChar)) {} return "operator"; } stream.eatWhile(/[\w\$_\xa1-\uffff]/); if (namespaceSeparator) while (stream.match(namespaceSeparator)) stream.eatWhile(/[\w\$_\xa1-\uffff]/); var cur = stream.current(); if (contains(keywords, cur)) { if (contains(blockKeywords, cur)) curPunc = "newstatement"; if (contains(defKeywords, cur)) isDefKeyword = true; return "keyword"; } if (contains(types, cur)) return "variable-3"; if (contains(builtin, cur)) { if (contains(blockKeywords, cur)) curPunc = "newstatement"; return "builtin"; } if (contains(atoms, cur)) return "atom"; return "variable"; } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped) {end = true; break;} escaped = !escaped && next == "\\"; } if (end || !(escaped || multiLineStrings)) state.tokenize = null; return "string"; }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = null; break; } maybeEnd = (ch == "*"); } return "comment"; } function maybeEOL(stream, state) { if (parserConfig.typeFirstDefinitions && stream.eol() && isTopScope(state.context)) state.typeAtEndOfLine = typeBefore(stream, state, stream.pos) } // Interface return { startState: function(basecolumn) { return { tokenize: null, context: new Context((basecolumn || 0) - indentUnit, 0, "top", null, false), indented: 0, startOfLine: true, prevToken: null }; }, token: function(stream, state) { var ctx = state.context; if (stream.sol()) { if (ctx.align == null) ctx.align = false; state.indented = stream.indentation(); state.startOfLine = true; } if (stream.eatSpace()) { maybeEOL(stream, state); return null; } curPunc = isDefKeyword = null; var style = (state.tokenize || tokenBase)(stream, state); if (style == "comment" || style == "meta") return style; if (ctx.align == null) ctx.align = true; if (curPunc == ";" || curPunc == ":" || (curPunc == "," && stream.match(/^\s*(?:\/\/.*)?$/, false))) while (state.context.type == "statement") popContext(state); else if (curPunc == "{") pushContext(state, stream.column(), "}"); else if (curPunc == "[") pushContext(state, stream.column(), "]"); else if (curPunc == "(") pushContext(state, stream.column(), ")"); else if (curPunc == "}") { while (ctx.type == "statement") ctx = popContext(state); if (ctx.type == "}") ctx = popContext(state); while (ctx.type == "statement") ctx = popContext(state); } else if (curPunc == ctx.type) popContext(state); else if (indentStatements && (((ctx.type == "}" || ctx.type == "top") && curPunc != ";") || (ctx.type == "statement" && curPunc == "newstatement"))) { pushContext(state, stream.column(), "statement", stream.current()); } if (style == "variable" && ((state.prevToken == "def" || (parserConfig.typeFirstDefinitions && typeBefore(stream, state, stream.start) && isTopScope(state.context) && stream.match(/^\s*\(/, false))))) style = "def"; if (hooks.token) { var result = hooks.token(stream, state, style); if (result !== undefined) style = result; } if (style == "def" && parserConfig.styleDefs === false) style = "variable"; state.startOfLine = false; state.prevToken = isDefKeyword ? "def" : style || curPunc; maybeEOL(stream, state); return style; }, indent: function(state, textAfter) { if (state.tokenize != tokenBase && state.tokenize != null || state.typeAtEndOfLine) return CodeMirror.Pass; var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev; if (parserConfig.dontIndentStatements) while (ctx.type == "statement" && parserConfig.dontIndentStatements.test(ctx.info)) ctx = ctx.prev if (hooks.indent) { var hook = hooks.indent(state, ctx, textAfter); if (typeof hook == "number") return hook } var closing = firstChar == ctx.type; var switchBlock = ctx.prev && ctx.prev.info == "switch"; if (parserConfig.allmanIndentation && /[{(]/.test(firstChar)) { while (ctx.type != "top" && ctx.type != "}") ctx = ctx.prev return ctx.indented } if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit); if (ctx.align && (!dontAlignCalls || ctx.type != ")")) return ctx.column + (closing ? 0 : 1); if (ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit; return ctx.indented + (closing ? 0 : indentUnit) + (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0); }, electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/, blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: "//", fold: "brace" }; }); function words(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } function contains(words, word) { if (typeof words === "function") { return words(word); } else { return words.propertyIsEnumerable(word); } } var cKeywords = "auto if break case register continue return default do sizeof " + "static else struct switch extern typedef union for goto while enum const volatile"; var cTypes = "int long char short double float unsigned signed void size_t ptrdiff_t"; function cppHook(stream, state) { if (!state.startOfLine) return false for (var ch, next = null; ch = stream.peek();) { if (ch == "\\" && stream.match(/^.$/)) { next = cppHook break } else if (ch == "/" && stream.match(/^\/[\/\*]/, false)) { break } stream.next() } state.tokenize = next return "meta" } function pointerHook(_stream, state) { if (state.prevToken == "variable-3") return "variable-3"; return false; } function cpp14Literal(stream) { stream.eatWhile(/[\w\.']/); return "number"; } function cpp11StringHook(stream, state) { stream.backUp(1); // Raw strings. if (stream.match(/(R|u8R|uR|UR|LR)/)) { var match = stream.match(/"([^\s\\()]{0,16})\(/); if (!match) { return false; } state.cpp11RawStringDelim = match[1]; state.tokenize = tokenRawString; return tokenRawString(stream, state); } // Unicode strings/chars. if (stream.match(/(u8|u|U|L)/)) { if (stream.match(/["']/, /* eat */ false)) { return "string"; } return false; } // Ignore this hook. stream.next(); return false; } function cppLooksLikeConstructor(word) { var lastTwo = /(\w+)::(\w+)$/.exec(word); return lastTwo && lastTwo[1] == lastTwo[2]; } // C#-style strings where "" escapes a quote. function tokenAtString(stream, state) { var next; while ((next = stream.next()) != null) { if (next == '"' && !stream.eat('"')) { state.tokenize = null; break; } } return "string"; } // C++11 raw string literal is <prefix>"<delim>( anything )<delim>", where // <delim> can be a string up to 16 characters long. function tokenRawString(stream, state) { // Escape characters that have special regex meanings. var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&'); var match = stream.match(new RegExp(".*?\\)" + delim + '"')); if (match) state.tokenize = null; else stream.skipToEnd(); return "string"; } function def(mimes, mode) { if (typeof mimes == "string") mimes = [mimes]; var words = []; function add(obj) { if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop)) words.push(prop); } add(mode.keywords); add(mode.types); add(mode.builtin); add(mode.atoms); if (words.length) { mode.helperType = mimes[0]; CodeMirror.registerHelper("hintWords", mimes[0], words); } for (var i = 0; i < mimes.length; ++i) CodeMirror.defineMIME(mimes[i], mode); } def(["text/x-csrc", "text/x-c", "text/x-chdr"], { name: "clike", keywords: words(cKeywords), types: words(cTypes + " bool _Complex _Bool float_t double_t intptr_t intmax_t " + "int8_t int16_t int32_t int64_t uintptr_t uintmax_t uint8_t uint16_t " + "uint32_t uint64_t"), blockKeywords: words("case do else for if switch while struct"), defKeywords: words("struct"), typeFirstDefinitions: true, atoms: words("null true false"), hooks: {"#": cppHook, "*": pointerHook}, modeProps: {fold: ["brace", "include"]} }); def(["text/x-c++src", "text/x-c++hdr"], { name: "clike", keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try explicit new " + "static_cast typeid catch operator template typename class friend private " + "this using const_cast inline public throw virtual delete mutable protected " + "alignas alignof constexpr decltype nullptr noexcept thread_local final " + "static_assert override"), types: words(cTypes + " bool wchar_t"), blockKeywords: words("catch class do else finally for if struct switch try while"), defKeywords: words("class namespace struct enum union"), typeFirstDefinitions: true, atoms: words("true false null"), dontIndentStatements: /^template$/, hooks: { "#": cppHook, "*": pointerHook, "u": cpp11StringHook, "U": cpp11StringHook, "L": cpp11StringHook, "R": cpp11StringHook, "0": cpp14Literal, "1": cpp14Literal, "2": cpp14Literal, "3": cpp14Literal, "4": cpp14Literal, "5": cpp14Literal, "6": cpp14Literal, "7": cpp14Literal, "8": cpp14Literal, "9": cpp14Literal, token: function(stream, state, style) { if (style == "variable" && stream.peek() == "(" && (state.prevToken == ";" || state.prevToken == null || state.prevToken == "}") && cppLooksLikeConstructor(stream.current())) return "def"; } }, namespaceSeparator: "::", modeProps: {fold: ["brace", "include"]} }); def("text/x-java", { name: "clike", keywords: words("abstract assert break case catch class const continue default " + "do else enum extends final finally float for goto if implements import " + "instanceof interface native new package private protected public " + "return static strictfp super switch synchronized this throw throws transient " + "try volatile while @interface"), types: words("byte short int long float double boolean char void Boolean Byte Character Double Float " + "Integer Long Number Object Short String StringBuffer StringBuilder Void"), blockKeywords: words("catch class do else finally for if switch try while"), defKeywords: words("class interface package enum @interface"), typeFirstDefinitions: true, atoms: words("true false null"), number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, hooks: { "@": function(stream) { // Don't match the @interface keyword. if (stream.match('interface', false)) return false; stream.eatWhile(/[\w\$_]/); return "meta"; } }, modeProps: {fold: ["brace", "import"]} }); def("text/x-csharp", { name: "clike", keywords: words("abstract as async await base break case catch checked class const continue" + " default delegate do else enum event explicit extern finally fixed for" + " foreach goto if implicit in interface internal is lock namespace new" + " operator out override params private protected public readonly ref return sealed" + " sizeof stackalloc static struct switch this throw try typeof unchecked" + " unsafe using virtual void volatile while add alias ascending descending dynamic from get" + " global group into join let orderby partial remove select set value var yield"), types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" + " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" + " UInt64 bool byte char decimal double short int long object" + " sbyte float string ushort uint ulong"), blockKeywords: words("catch class do else finally for foreach if struct switch try while"), defKeywords: words("class interface namespace struct var"), typeFirstDefinitions: true, atoms: words("true false null"), hooks: { "@": function(stream, state) { if (stream.eat('"')) { state.tokenize = tokenAtString; return tokenAtString(stream, state); } stream.eatWhile(/[\w\$_]/); return "meta"; } } }); function tokenTripleString(stream, state) { var escaped = false; while (!stream.eol()) { if (!escaped && stream.match('"""')) { state.tokenize = null; break; } escaped = stream.next() == "\\" && !escaped; } return "string"; } def("text/x-scala", { name: "clike", keywords: words( /* scala */ "abstract case catch class def do else extends final finally for forSome if " + "implicit import lazy match new null object override package private protected return " + "sealed super this throw trait try type val var while with yield _ " + /* package scala */ "assert assume require print println printf readLine readBoolean readByte readShort " + "readChar readInt readLong readFloat readDouble" ), types: words( "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " + "Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable " + "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " + "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " + "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector " + /* package java.lang */ "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void" ), multiLineStrings: true, blockKeywords: words("catch class do else finally for forSome if match switch try while"), defKeywords: words("class def object package trait type val var"), atoms: words("true false null"), indentStatements: false, indentSwitch: false, isOperatorChar: /[+\-*&%=<>!?|\/#:@]/, hooks: { "@": function(stream) { stream.eatWhile(/[\w\$_]/); return "meta"; }, '"': function(stream, state) { if (!stream.match('""')) return false; state.tokenize = tokenTripleString; return state.tokenize(stream, state); }, "'": function(stream) { stream.eatWhile(/[\w\$_\xa1-\uffff]/); return "atom"; }, "=": function(stream, state) { var cx = state.context if (cx.type == "}" && cx.align && stream.eat(">")) { state.context = new Context(cx.indented, cx.column, cx.type, cx.info, null, cx.prev) return "operator" } else { return false } } }, modeProps: {closeBrackets: {triples: '"'}} }); function tokenKotlinString(tripleString){ return function (stream, state) { var escaped = false, next, end = false; while (!stream.eol()) { if (!tripleString && !escaped && stream.match('"') ) {end = true; break;} if (tripleString && stream.match('"""')) {end = true; break;} next = stream.next(); if(!escaped && next == "$" && stream.match('{')) stream.skipTo("}"); escaped = !escaped && next == "\\" && !tripleString; } if (end || !tripleString) state.tokenize = null; return "string"; } } def("text/x-kotlin", { name: "clike", keywords: words( /*keywords*/ "package as typealias class interface this super val " + "var fun for is in This throw return " + "break continue object if else while do try when !in !is as? " + /*soft keywords*/ "file import where by get set abstract enum open inner override private public internal " + "protected catch finally out final vararg reified dynamic companion constructor init " + "sealed field property receiver param sparam lateinit data inline noinline tailrec " + "external annotation crossinline const operator infix" ), types: words( /* package java.lang */ "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void" ), intendSwitch: false, indentStatements: false, multiLineStrings: true, blockKeywords: words("catch class do else finally for if where try while enum"), defKeywords: words("class val var object package interface fun"), atoms: words("true false null this"), hooks: { '"': function(stream, state) { state.tokenize = tokenKotlinString(stream.match('""')); return state.tokenize(stream, state); } }, modeProps: {closeBrackets: {triples: '"'}} }); def(["x-shader/x-vertex", "x-shader/x-fragment"], { name: "clike", keywords: words("sampler1D sampler2D sampler3D samplerCube " + "sampler1DShadow sampler2DShadow " + "const attribute uniform varying " + "break continue discard return " + "for while do if else struct " + "in out inout"), types: words("float int bool void " + "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " + "mat2 mat3 mat4"), blockKeywords: words("for while do if else struct"), builtin: words("radians degrees sin cos tan asin acos atan " + "pow exp log exp2 sqrt inversesqrt " + "abs sign floor ceil fract mod min max clamp mix step smoothstep " + "length distance dot cross normalize ftransform faceforward " + "reflect refract matrixCompMult " + "lessThan lessThanEqual greaterThan greaterThanEqual " + "equal notEqual any all not " + "texture1D texture1DProj texture1DLod texture1DProjLod " + "texture2D texture2DProj texture2DLod texture2DProjLod " + "texture3D texture3DProj texture3DLod texture3DProjLod " + "textureCube textureCubeLod " + "shadow1D shadow2D shadow1DProj shadow2DProj " + "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " + "dFdx dFdy fwidth " + "noise1 noise2 noise3 noise4"), atoms: words("true false " + "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " + "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " + "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " + "gl_FogCoord gl_PointCoord " + "gl_Position gl_PointSize gl_ClipVertex " + "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " + "gl_TexCoord gl_FogFragCoord " + "gl_FragCoord gl_FrontFacing " + "gl_FragData gl_FragDepth " + "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " + "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " + "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " + "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " + "gl_ProjectionMatrixInverseTranspose " + "gl_ModelViewProjectionMatrixInverseTranspose " + "gl_TextureMatrixInverseTranspose " + "gl_NormalScale gl_DepthRange gl_ClipPlane " + "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " + "gl_FrontLightModelProduct gl_BackLightModelProduct " + "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " + "gl_FogParameters " + "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " + "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " + "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " + "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " + "gl_MaxDrawBuffers"), indentSwitch: false, hooks: {"#": cppHook}, modeProps: {fold: ["brace", "include"]} }); def("text/x-nesc", { name: "clike", keywords: words(cKeywords + "as atomic async call command component components configuration event generic " + "implementation includes interface module new norace nx_struct nx_union post provides " + "signal task uses abstract extends"), types: words(cTypes), blockKeywords: words("case do else for if switch while struct"), atoms: words("null true false"), hooks: {"#": cppHook}, modeProps: {fold: ["brace", "include"]} }); def("text/x-objectivec", { name: "clike", keywords: words(cKeywords + "inline restrict _Bool _Complex _Imaginary BOOL Class bycopy byref id IMP in " + "inout nil oneway out Protocol SEL self super atomic nonatomic retain copy readwrite readonly"), types: words(cTypes), atoms: words("YES NO NULL NILL ON OFF true false"), hooks: { "@": function(stream) { stream.eatWhile(/[\w\$]/); return "keyword"; }, "#": cppHook, indent: function(_state, ctx, textAfter) { if (ctx.type == "statement" && /^@\w/.test(textAfter)) return ctx.indented } }, modeProps: {fold: "brace"} }); def("text/x-squirrel", { name: "clike", keywords: words("base break clone continue const default delete enum extends function in class" + " foreach local resume return this throw typeof yield constructor instanceof static"), types: words(cTypes), blockKeywords: words("case catch class else for foreach if switch try while"), defKeywords: words("function local class"), typeFirstDefinitions: true, atoms: words("true false null"), hooks: {"#": cppHook}, modeProps: {fold: ["brace", "include"]} }); // Ceylon Strings need to deal with interpolation var stringTokenizer = null; function tokenCeylonString(type) { return function(stream, state) { var escaped = false, next, end = false; while (!stream.eol()) { if (!escaped && stream.match('"') && (type == "single" || stream.match('""'))) { end = true; break; } if (!escaped && stream.match('``')) { stringTokenizer = tokenCeylonString(type); end = true; break; } next = stream.next(); escaped = type == "single" && !escaped && next == "\\"; } if (end) state.tokenize = null; return "string"; } } def("text/x-ceylon", { name: "clike", keywords: words("abstracts alias assembly assert assign break case catch class continue dynamic else" + " exists extends finally for function given if import in interface is let module new" + " nonempty object of out outer package return satisfies super switch then this throw" + " try value void while"), types: function(word) { // In Ceylon all identifiers that start with an uppercase are types var first = word.charAt(0); return (first === first.toUpperCase() && first !== first.toLowerCase()); }, blockKeywords: words("case catch class dynamic else finally for function if interface module new object switch try while"), defKeywords: words("class dynamic function interface module object package value"), builtin: words("abstract actual aliased annotation by default deprecated doc final formal late license" + " native optional sealed see serializable shared suppressWarnings tagged throws variable"), isPunctuationChar: /[\[\]{}\(\),;\:\.`]/, isOperatorChar: /[+\-*&%=<>!?|^~:\/]/, numberStart: /[\d#$]/, number: /^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i, multiLineStrings: true, typeFirstDefinitions: true, atoms: words("true false null larger smaller equal empty finished"), indentSwitch: false, styleDefs: false, hooks: { "@": function(stream) { stream.eatWhile(/[\w\$_]/); return "meta"; }, '"': function(stream, state) { state.tokenize = tokenCeylonString(stream.match('""') ? "triple" : "single"); return state.tokenize(stream, state); }, '`': function(stream, state) { if (!stringTokenizer || !stream.match('`')) return false; state.tokenize = stringTokenizer; stringTokenizer = null; return state.tokenize(stream, state); }, "'": function(stream) { stream.eatWhile(/[\w\$_\xa1-\uffff]/); return "atom"; }, token: function(_stream, state, style) { if ((style == "variable" || style == "variable-3") && state.prevToken == ".") { return "variable-2"; } } }, modeProps: { fold: ["brace", "import"], closeBrackets: {triples: '"'} } }); });
{ "pile_set_name": "Github" }
{ "name": "select2", "title": "Select2", "description": "Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.", "keywords": [ "select", "autocomplete", "typeahead", "dropdown", "multiselect", "tag", "tagging" ], "version": "4.0.3", "author": { "name": "Kevin Brown", "url": "https://github.com/kevin-brown" }, "licenses": [ { "type": "MIT", "url": "http://opensource.org/licenses/MIT" } ], "bugs": "https://github.com/select2/select2/issues", "homepage": "https://select2.github.io", "docs": "https://select2.github.io", "download": "https://github.com/select2/select2/releases", "dependencies": { "jquery": ">=1.7.2" } }
{ "pile_set_name": "Github" }
! @@name: copyprivate.4f ! @@type: F-fixed ! @@compilable: yes ! @@linkable: no ! @@expect: success SUBROUTINE S(N) INTEGER N REAL, DIMENSION(:), ALLOCATABLE :: A REAL, DIMENSION(:), POINTER :: B ALLOCATE (A(N)) !$OMP SINGLE ALLOCATE (B(N)) READ (11) A,B !$OMP END SINGLE COPYPRIVATE(A,B) ! Variable A is private and is ! assigned the same value in each thread ! Variable B is shared !$OMP BARRIER !$OMP SINGLE DEALLOCATE (B) !$OMP END SINGLE NOWAIT END SUBROUTINE S
{ "pile_set_name": "Github" }
#pragma checksum "C:\Users\rmt01\Dropbox\WindowsBox\Kodning\Fusk\Injector\C++\Xenos-master\BlackBone\App1\App.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "A57A6474CE005A5AD1777F980C75F16B" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace App1 { #if !DISABLE_XAML_GENERATED_MAIN /// <summary> /// Program class /// </summary> public static class Program { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] static void Main(string[] args) { global::Windows.UI.Xaml.Application.Start((p) => new App()); } } #endif partial class App : global::Windows.UI.Xaml.Application { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] private bool _contentLoaded; /// <summary> /// InitializeComponent() /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public void InitializeComponent() { if (_contentLoaded) return; _contentLoaded = true; #if DEBUG && !DISABLE_XAML_GENERATED_BINDING_DEBUG_OUTPUT DebugSettings.BindingFailed += (sender, args) => { global::System.Diagnostics.Debug.WriteLine(args.Message); }; #endif #if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION UnhandledException += (sender, e) => { if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break(); }; #endif } } }
{ "pile_set_name": "Github" }
using RGB.NET.Core; using SkiaSharp; namespace Artemis.Core { public static class RgbRectangleExtensions { public static SKRect ToSKRect(this Rectangle rectangle, double scale) { return SKRect.Create( (rectangle.Location.X * scale).RoundToInt(), (rectangle.Location.Y * scale).RoundToInt(), (rectangle.Size.Width * scale).RoundToInt(), (rectangle.Size.Height * scale).RoundToInt() ); } } }
{ "pile_set_name": "Github" }
package com.huruwo.serialporthelper; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; /** * @author: liuwan * @date: 2018-05-28 * @action: */ public class SpAdapter extends BaseAdapter { String[] datas; Context mContext; public SpAdapter(Context context) { this.mContext = context; } public void setDatas(String[] datas) { this.datas = datas; notifyDataSetChanged(); } @Override public int getCount() { return datas == null ? 0 : datas.length; } @Override public Object getItem(int position) { return datas == null ? null : datas[position]; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHodler hodler = null; if (convertView == null) { hodler = new ViewHodler(); convertView = LayoutInflater.from(mContext).inflate(R.layout.item_layout, null); hodler.mTextView = (TextView) convertView; convertView.setTag(hodler); } else { hodler = (ViewHodler) convertView.getTag(); } hodler.mTextView.setText(datas[position]); return convertView; } private static class ViewHodler { TextView mTextView; } }
{ "pile_set_name": "Github" }
@charset "UTF-8"; @import "lib/global"; /* Card */ .pui-card { color: #666; display: block; position: relative; text-align: left; margin-bottom: 15px; margin-bottom: 1.5rem; p:last-child { margin-bottom: 0; } } .pui-card-head, .pui-card-title, .pui-card-foot { position: relative; padding: 6px 15px; padding: 0.6rem 1.5rem; > h1, > strong { margin: 0; font-size: 16px; font-size: 1.6rem; small { padding-left: 4px; padding-left: 0.4rem; } } } .pui-card-head { } .pui-card-foot { } .pui-card-box { padding: 15px; padding: 1.5rem; overflow: auto; position: relative; color: $default-text-color; > h1 { font-size: 22px; font-size: 2.2rem; } } .pui-card-head + .pui-card-box { padding-top: 5px; } .pui-card-default { background: #fff; border: 1px solid $default-border-color; } .pui-card-simple { .pui-card-box { padding: 5px 15px; padding: 0.5rem 1.5rem; } } .pui-card-unbordered { border: none; .pui-card-title, .pui-card-head { padding-top: 0; } .pui-card-foot { padding-bottom: 0; } .pui-card-head, .pui-card-title, .pui-card-foot, .pui-card-box { padding-left: 0; padding-right: 0; } } .pui-card-badge { display: inline-block; padding: 0 5px; background: #fff; font-size: 10px; font-size: 1rem; font-weight: 700; line-height: 14px; color: #fff; text-align: center; vertical-align: middle; text-transform: none; border: 1px solid #ddd; @include border-radius(2px); } .pui-card-head-bg, .pui-card-title-bg, .pui-card-foot-bg { background: #fafafa; } .pui-card-title-left-border { margin-left: -16px; margin-left: -1.6rem; > h1, > strong { padding: 0; border-left: 4px solid $primary-color; padding-left: 12px; padding-left: 1.2rem; } } .pui-card-title-underline { padding-top: 4px; padding-top: 0.4rem; padding-bottom: 5px; padding-bottom: 0.5rem; border-bottom: 1px solid #ddd; } .pui-card-foot-topline { border-top: 1px solid #ddd; } .pui-card-title-right { float: right; color: #ccc; padding-top: 4px; padding-top: 0.4rem; a { color: #ccc; html.no-touch &:hover, &.hover { color: #007CFF; } } html.no-touch .pui-badge:hover, .pui-badge.hover { color: #fff; } html.no-touch .pui-badge-default:hover, .pui-badge-default.hover { color: #ccc; } } $bg-color : ""; $text-color: ""; $border-color: ""; @each $name, $color in $ui-colors { @if $name == error { $bg-color: #FFE8E3; $border-color: #F7D1CB; $text-color: $color; }@else if $name == warning { $bg-color: #FCF5E8; $border-color: #FAE5C4; $text-color: $color; } @else { $text-color: $color; $border-color: lighten($color, 28%); $bg-color: lighten($color, 38%); } .pui-card-#{$name} { border-color: $border-color; .pui-card-head, .pui-card-title, .pui-card-foot { color: $text-color; border-color: $border-color; background-color: $bg-color; small, span, a { color: $text-color; } } } } .pui-card-radius { @include border-radius(4px); } .pui-card-square { @include border-radius(none); } .pui-card-group { .pui-card { margin-bottom: 8px; margin-bottom: 0.8rem; } .pui-card-head, .pui-card-title, .pui-card-foot { background: #fafafa; } } .pui-card-padding-none { .pui-card-head, .pui-card-title, .pui-card-box, .pui-card-foot { padding-left: 0; padding-right: 0; } } .pui-card-box.pui-card-box-underline { border: none; border-bottom: 1px solid #ddd; margin-bottom: -5px; margin-bottom: -0.5rem; } .pui-card-shadow { @include box-shadow(0 0 4px rgba(0, 0, 0, 0.2)); html.no-touch &:hover, &.hover, &.pui-hover { @include box-shadow(0 0 6px rgba(0, 0, 0, 0.25)); } } .pui-row .pui-card:last-child { margin-bottom: 0; } .pui-card-image { overflow: auto; border: none; box-shadow: 0 0 5px rgba(0, 0, 0, .2); } .pui-card-head-bg { position: relative; padding: 0; > h1 { color: #fff; position: absolute; left: 1.5rem; bottom: 1.5rem; margin: 0; font-size: 2.2rem; > small { color: #fff; } } } .pui-card-head-img { width: 100%; height: auto; margin: 0 0 -0.6rem; } .pui-card-radius .pui-card-head-img { @include border-top-left-radius(4px); @include border-top-right-radius(4px); } .pui-card-column { @include flexbox(); @include flex-direction(row); } .pui-card-column > .pui-card-box { @include flex(1); } .pui-card-left, .pui-card-right { position: relative; > p { margin-bottom: 0; } > h1 { color: #fff; position: absolute; left: 1.5rem; bottom: 1.5rem; margin: 0; font-size: 2.2rem; line-height: 1.4; text-align: left; -webkit-text-shadow: 0 1px 1px rgba(0, 0, 0, .5); text-shadow: 0 1px 1px rgba(0, 0, 0, .5); > small { color: #fff; display: block; margin: 0; } } } .pui-card-right > h1 { text-align: right; } .pui-card-box-left { float: left; margin-right: 2rem; } .pui-card-box-right { float: right; margin-left: 2rem; } @media (max-width: 360px) { .pui-card-column { @include flex-direction(column); > .pui-card-left { height: auto; } } }
{ "pile_set_name": "Github" }
/* (c) 2014 - 2015 Open Source Geospatial Foundation - all rights reserved * (c) 2001 - 2013 OpenPlans * This code is licensed under the GPL 2.0 license, available at the root * application directory. */ package org.geoserver.importer.bdb; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.apache.commons.io.FileUtils; import org.geoserver.importer.CountingVisitor; import org.geoserver.importer.Directory; import org.geoserver.importer.ImportContext; import org.geoserver.importer.Importer; import org.geoserver.importer.ImporterInfoDAO; import org.geoserver.importer.ImporterTestSupport; import org.geoserver.importer.RemoteData; import org.geoserver.importer.SearchingVisitor; import org.geoserver.importer.bdb.BDBImportStore.BindingType; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class BDBImportStoreTest extends ImporterTestSupport { @Parameters(name = "{0}") public static Collection<Object[]> data() { List<Object[]> result = new ArrayList<>(); result.add(new Object[] {"serial", BindingType.SERIAL}); result.add(new Object[] {"xstream", BindingType.XSTREAM}); return result; } BDBImportStore store; File dbRoot; private BindingType bindingType; public BDBImportStoreTest(String name, BindingType bindingType) { this.bindingType = bindingType; } // The test has been written assuming the importer uses a memory store while a separate, test // managed store is used to run checks... keeping it that way, wasted enough time trying to // make it just run with the importer one @BeforeClass public static void setupMemoryStore() { System.setProperty(Importer.IMPORTER_STORE_KEY, "memory"); } @AfterClass public static void clearMemoryStore() { System.clearProperty(Importer.IMPORTER_STORE_KEY); } @Before public void setupStoreField() throws Exception { store = new BDBImportStore(importer); store.setBinding(bindingType); store.init(); dbRoot = new File(importer.getImportRoot(), "bdb"); } // in order to test this, run once, then change the serialVersionUID of ImportContext2 @Test public void testSerialVersionUIDChange() throws Exception { Importer imp = new Importer(null, new ImporterInfoDAO()) { @Override public File getImportRoot() { File root = new File("target"); root.mkdirs(); return root; } }; ImportContext ctx = new ImportContext2(); ctx.setState(ImportContext.State.PENDING); ctx.setUser("fooboo"); BDBImportStore store = new BDBImportStore(imp); try { store.init(); store.add(ctx); Iterator<ImportContext> iterator = store.iterator(); while (iterator.hasNext()) { ctx = iterator.next(); assertEquals("fooboo", ctx.getUser()); } store.add(ctx); } finally { store.destroy(); } } public static class ImportContext2 extends ImportContext { private static final long serialVersionUID = 12345; } @Test public void testAdd() throws Exception { File dir = unpack("shape/archsites_epsg_prj.zip"); ImportContext context = importer.createContext(new Directory(dir)); assertEquals(1, context.getTasks().size()); for (int i = 0; i < context.getTasks().size(); i++) { assertNotNull(context.getTasks().get(i).getStore()); assertNotNull(context.getTasks().get(i).getStore().getCatalog()); } // @todo commented these out as importer.createContext adds to the store // assertNull(context.getId()); CountingVisitor cv = new CountingVisitor(); // store.query(cv); // assertEquals(0, cv.getCount()); store.add(context); assertNotNull(context.getId()); assertNotNull(context.getTasks().get(0).getLayer()); ImportContext context2 = store.get(context.getId()); assertNotNull(context2); assertEquals(context.getId(), context2.getId()); store.query(cv); assertEquals(1, cv.getCount()); SearchingVisitor sv = new SearchingVisitor(context.getId()); store.query(sv); assertTrue(sv.isFound()); importer.reattach(context2); // ensure various transient bits are set correctly on deserialization assertEquals(1, context2.getTasks().size()); for (int i = 0; i < context2.getTasks().size(); i++) { assertNotNull(context2.getTasks().get(i).getStore()); assertNotNull(context2.getTasks().get(i).getStore().getCatalog()); } assertNotNull(context2.getTasks().get(0).getLayer()); } @Test public void testSaveRemoteData() throws Exception { ImportContext context = importer.registerContext(null); RemoteData data = new RemoteData("ftp://geoserver.org"); data.setUsername("geoserver"); data.setPassword("gisIsCool"); context.setData(data); store.add(context); assertNotNull(context.getId()); ImportContext context2 = store.get(context.getId()); assertEquals(data, context2.getData()); } @Test public void testSave() throws Exception { testAdd(); ImportContext context = store.get(0); assertNotNull(context); assertEquals(ImportContext.State.PENDING, context.getState()); context.setState(ImportContext.State.COMPLETE); ImportContext context2 = store.get(0); assertNotNull(context2); assertEquals(ImportContext.State.PENDING, context2.getState()); store.save(context); context2 = store.get(0); assertNotNull(context2); assertEquals(ImportContext.State.COMPLETE, context2.getState()); } @Test public void testDatabaseRecovery() throws Exception {} @Test public void testIDManagement() throws Exception { // verify base - first one is zero ImportContext zero = new ImportContext(); store.add(zero); assertEquals(Long.valueOf(0), zero.getId()); // try for zero again (less than current case - client out of sync) Long advanceId = store.advanceId(0L); assertEquals(Long.valueOf(1), advanceId); // and again for current (equals current case - normal mode) advanceId = store.advanceId(2L); assertEquals(Long.valueOf(2), advanceId); // now jump ahead (client advances case - server out of sync) advanceId = store.advanceId(666L); assertEquals(Long.valueOf(666), advanceId); // the next created import should be one higher ImportContext dumby = new ImportContext(); store.add(dumby); assertEquals(Long.valueOf(667), dumby.getId()); } @After public void destroyStore() throws Exception { store.destroy(); // clean up the databse FileUtils.deleteDirectory(dbRoot); } }
{ "pile_set_name": "Github" }
<!--index.wxml--> <view class="topBar"> 我的团队 </view> <view class="teamBox"> <view wx:for="{{teamArray}}" wx:key="team"> <view class="teamInfo"> <view class="teamName">{{item.name}}</view> <view class="teamMember"> <view class="members">{{item.members}}</view> <view class="memberNum">{{item.members.length}}个成员</view> <image class="right_arrow" src="../../i/right.png"></image> </view> </view> </view> </view>
{ "pile_set_name": "Github" }
// ImagePanel .@{prefix}-imagepanel { overflow: auto; background: black; } .@{prefix}-imagepanel img { position: absolute; } .@{prefix}-imagetool.@{prefix}-btn .@{prefix}-ico { display: block; width: 20px; height: 20px; text-align: center; line-height: 20px; font-size: 20px; padding: 5px; }
{ "pile_set_name": "Github" }
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "perception_evaluator_manager", srcs = ["evaluator_manager.cc"], hdrs = ["evaluator_manager.h"], deps = [ "//modules/common/configs:vehicle_config_helper", "//modules/prediction/common:feature_output", "//modules/prediction/common:semantic_map", "//modules/prediction/container/obstacles:obstacles_container", "//modules/prediction/evaluator", "//modules/prediction/evaluator/vehicle:semantic_lstm_evaluator", ], ) cpplint()
{ "pile_set_name": "Github" }
# assert-plus Changelog ## 1.0.0 - *BREAKING* assert.number (and derivatives) now accept Infinity as valid input - Add assert.finite check. Previous assert.number callers should use this if they expect Infinity inputs to throw. ## 0.2.0 - Fix `assert.object(null)` so it throws - Fix optional/arrayOf exports for non-type-of asserts - Add optiona/arrayOf exports for Stream/Date/Regex/uuid - Add basic unit test coverage
{ "pile_set_name": "Github" }
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import gym import argparse import ns3gym __author__ = "Piotr Gawlowicz" __copyright__ = "Copyright (c) 2018, Technische Universität Berlin" __version__ = "0.1.0" __email__ = "[email protected]" env = gym.make('ns3-v0') env.reset() ob_space = env.observation_space ac_space = env.action_space print("Observation space: ", ob_space, ob_space.dtype) print("Action space: ", ac_space, ac_space.dtype) stepIdx = 0 try: obs = env.reset() print("Step: ", stepIdx) print("---obs: ", obs) while True: stepIdx += 1 action = env.action_space.sample() print("---action: ", action) obs, reward, done, info = env.step(action) print("Step: ", stepIdx) print("---obs, reward, done, info: ", obs, reward, done, info) if done: break except KeyboardInterrupt: print("Ctrl-C -> Exit") finally: env.close() print("Done")
{ "pile_set_name": "Github" }
/********************************************************************************/ /* Projeto: Biblioteca ZeusMDFe */ /* Biblioteca C# para emissão de Manifesto Eletrônico Fiscal de Documentos */ /* (https://mdfe-portal.sefaz.rs.gov.br/ */ /* */ /* Direitos Autorais Reservados (c) 2014 Adenilton Batista da Silva */ /* Zeusdev Tecnologia LTDA ME */ /* */ /* Você pode obter a última versão desse arquivo no GitHub */ /* localizado em https://github.com/adeniltonbs/Zeus.Net.NFe.NFCe */ /* */ /* */ /* Esta biblioteca é software livre; você pode redistribuí-la e/ou modificá-la */ /* sob os termos da Licença Pública Geral Menor do GNU conforme publicada pela */ /* Free Software Foundation; tanto a versão 2.1 da Licença, ou (a seu critério) */ /* qualquer versão posterior. */ /* */ /* Esta biblioteca é distribuída na expectativa de que seja útil, porém, SEM */ /* NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU */ /* ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral Menor*/ /* do GNU para mais detalhes. (Arquivo LICENÇA.TXT ou LICENSE.TXT) */ /* */ /* Você deve ter recebido uma cópia da Licença Pública Geral Menor do GNU junto*/ /* com esta biblioteca; se não, escreva para a Free Software Foundation, Inc., */ /* no endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. */ /* Você também pode obter uma copia da licença em: */ /* http://www.opensource.org/licenses/lgpl-license.php */ /* */ /* Zeusdev Tecnologia LTDA ME - [email protected] */ /* http://www.zeusautomacao.com.br/ */ /* Rua Comendador Francisco josé da Cunha, 111 - Itabaiana - SE - 49500-000 */ /********************************************************************************/ using System; using System.Xml.Serialization; namespace MDFe.Classes.Informacoes { [Serializable] public class MDFeInfEmbComb { /// <summary> /// 2 - Código da embarcação do comboio /// </summary> [XmlElement(ElementName = "cEmbComb")] public string CEmbComb { get; set; } public string xBalsa { get; set; } } }
{ "pile_set_name": "Github" }
<!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"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>CMSIS DSP Software Library: Data Fields</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javaScript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body onload='searchBox.OnSelectItem(0);'> <!-- Generated by Doxygen 1.7.2 --> <script type="text/javascript"><!-- var searchBox = new SearchBox("searchBox", "search",false,'Search'); --></script> <div class="navigation" id="top"> <div class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li id="searchli"> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li class="current"><a href="globals.html"><span>Globals</span></a></li> </ul> </div> <div class="tabs2"> <ul class="tablist"> <li class="current"><a href="globals.html"><span>All</span></a></li> <li><a href="globals_func.html"><span>Functions</span></a></li> <li><a href="globals_vars.html"><span>Variables</span></a></li> <li><a href="globals_type.html"><span>Typedefs</span></a></li> <li><a href="globals_enum.html"><span>Enumerations</span></a></li> <li><a href="globals_eval.html"><span>Enumerator</span></a></li> <li><a href="globals_defs.html"><span>Defines</span></a></li> </ul> </div> <div class="tabs3"> <ul class="tablist"> <li><a href="globals.html#index__"><span>_</span></a></li> <li><a href="globals_0x61.html#index_a"><span>a</span></a></li> <li><a href="globals_0x62.html#index_b"><span>b</span></a></li> <li><a href="globals_0x63.html#index_c"><span>c</span></a></li> <li><a href="globals_0x64.html#index_d"><span>d</span></a></li> <li><a href="globals_0x65.html#index_e"><span>e</span></a></li> <li><a href="globals_0x66.html#index_f"><span>f</span></a></li> <li><a href="globals_0x67.html#index_g"><span>g</span></a></li> <li><a href="globals_0x69.html#index_i"><span>i</span></a></li> <li><a href="globals_0x6c.html#index_l"><span>l</span></a></li> <li><a href="globals_0x6d.html#index_m"><span>m</span></a></li> <li><a href="globals_0x6e.html#index_n"><span>n</span></a></li> <li><a href="globals_0x6f.html#index_o"><span>o</span></a></li> <li><a href="globals_0x70.html#index_p"><span>p</span></a></li> <li><a href="globals_0x71.html#index_q"><span>q</span></a></li> <li><a href="globals_0x72.html#index_r"><span>r</span></a></li> <li><a href="globals_0x73.html#index_s"><span>s</span></a></li> <li><a href="globals_0x74.html#index_t"><span>t</span></a></li> <li><a href="globals_0x75.html#index_u"><span>u</span></a></li> <li><a href="globals_0x76.html#index_v"><span>v</span></a></li> <li class="current"><a href="globals_0x77.html#index_w"><span>w</span></a></li> <li><a href="globals_0x78.html#index_x"><span>x</span></a></li> </ul> </div> </div> <div class="contents"> Here is a list of all functions, variables, defines, enums, and typedefs with links to the files they belong to: <h3><a class="anchor" id="index_w"></a>- w -</h3><ul> <li>Weights_128 : <a class="el" href="group___d_c_t4___i_d_c_t4.html#gad00f29d896d64d6da7afbbb9d3e182a4">arm_dct4_init_f32.c</a> </li> <li>Weights_2048 : <a class="el" href="group___d_c_t4___i_d_c_t4.html#gac3a2a00b3106dfcb5e0a582f50c65692">arm_dct4_init_f32.c</a> </li> <li>Weights_512 : <a class="el" href="group___d_c_t4___i_d_c_t4.html#gaeb67b0be5b3c2139d660e02cedeed908">arm_dct4_init_f32.c</a> </li> <li>WeightsQ15_128 : <a class="el" href="group___d_c_t4___i_d_c_t4.html#ga8e8f0253c5a4337bd90968838db6164d">arm_dct4_init_q15.c</a> </li> <li>WeightsQ15_2048 : <a class="el" href="group___d_c_t4___i_d_c_t4.html#gab858d2072b29f338b5dabf5cde9aaf66">arm_dct4_init_q15.c</a> </li> <li>WeightsQ15_512 : <a class="el" href="group___d_c_t4___i_d_c_t4.html#ga0492a1e2539ffb9d5276a357dab9dca1">arm_dct4_init_q15.c</a> </li> <li>WeightsQ31_128 : <a class="el" href="group___d_c_t4___i_d_c_t4.html#ga02d7024538a87214296b01d83ba36b02">arm_dct4_init_q31.c</a> </li> <li>WeightsQ31_2048 : <a class="el" href="group___d_c_t4___i_d_c_t4.html#ga725b65c25a02b3cad329e18bb832f65e">arm_dct4_init_q31.c</a> </li> <li>WeightsQ31_512 : <a class="el" href="group___d_c_t4___i_d_c_t4.html#ga31a8217a96f7d3171921e98398f31596">arm_dct4_init_q31.c</a> </li> <li>wire1 : <a class="el" href="arm__signal__converge__example__f32_8c.html#a16e759789fbc05f878863f009066c8ea">arm_signal_converge_example_f32.c</a> , <a class="el" href="arm__variance__example__f32_8c.html#acc43b372d92d5027b9f9cac782c8b3c7">arm_variance_example_f32.c</a> </li> <li>wire2 : <a class="el" href="arm__variance__example__f32_8c.html#a41a9afab5be5ccd2e6f618b83102f0d1">arm_variance_example_f32.c</a> , <a class="el" href="arm__signal__converge__example__f32_8c.html#a4e370163c81ae2b72cc655a6b79e4c6a">arm_signal_converge_example_f32.c</a> </li> <li>wire3 : <a class="el" href="arm__signal__converge__example__f32_8c.html#a7e2cceadf6ec7f0aa0f698a680fa3a4b">arm_signal_converge_example_f32.c</a> , <a class="el" href="arm__variance__example__f32_8c.html#af61f43ad332a2322e43ced590b6d9768">arm_variance_example_f32.c</a> </li> </ul> </div> <!--- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark">&#160;</span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark">&#160;</span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark">&#160;</span>Defines</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <hr class="footer"/><address class="footer"><small>Generated on Fri Jul 15 2011 13:16:23 for CMSIS DSP Software Library by&#160; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.2 </small></address> </body> </html>
{ "pile_set_name": "Github" }
// Copyright 2014 The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package prometheus import ( "bytes" "fmt" "io/ioutil" "os" "path/filepath" "runtime" "sort" "strings" "sync" "unicode/utf8" "github.com/cespare/xxhash/v2" "github.com/golang/protobuf/proto" "github.com/prometheus/common/expfmt" dto "github.com/prometheus/client_model/go" "github.com/prometheus/client_golang/prometheus/internal" ) const ( // Capacity for the channel to collect metrics and descriptors. capMetricChan = 1000 capDescChan = 10 ) // DefaultRegisterer and DefaultGatherer are the implementations of the // Registerer and Gatherer interface a number of convenience functions in this // package act on. Initially, both variables point to the same Registry, which // has a process collector (currently on Linux only, see NewProcessCollector) // and a Go collector (see NewGoCollector, in particular the note about // stop-the-world implication with Go versions older than 1.9) already // registered. This approach to keep default instances as global state mirrors // the approach of other packages in the Go standard library. Note that there // are caveats. Change the variables with caution and only if you understand the // consequences. Users who want to avoid global state altogether should not use // the convenience functions and act on custom instances instead. var ( defaultRegistry = NewRegistry() DefaultRegisterer Registerer = defaultRegistry DefaultGatherer Gatherer = defaultRegistry ) func init() { MustRegister(NewProcessCollector(ProcessCollectorOpts{})) MustRegister(NewGoCollector()) } // NewRegistry creates a new vanilla Registry without any Collectors // pre-registered. func NewRegistry() *Registry { return &Registry{ collectorsByID: map[uint64]Collector{}, descIDs: map[uint64]struct{}{}, dimHashesByName: map[string]uint64{}, } } // NewPedanticRegistry returns a registry that checks during collection if each // collected Metric is consistent with its reported Desc, and if the Desc has // actually been registered with the registry. Unchecked Collectors (those whose // Describe method does not yield any descriptors) are excluded from the check. // // Usually, a Registry will be happy as long as the union of all collected // Metrics is consistent and valid even if some metrics are not consistent with // their own Desc or a Desc provided by their registered Collector. Well-behaved // Collectors and Metrics will only provide consistent Descs. This Registry is // useful to test the implementation of Collectors and Metrics. func NewPedanticRegistry() *Registry { r := NewRegistry() r.pedanticChecksEnabled = true return r } // Registerer is the interface for the part of a registry in charge of // registering and unregistering. Users of custom registries should use // Registerer as type for registration purposes (rather than the Registry type // directly). In that way, they are free to use custom Registerer implementation // (e.g. for testing purposes). type Registerer interface { // Register registers a new Collector to be included in metrics // collection. It returns an error if the descriptors provided by the // Collector are invalid or if they — in combination with descriptors of // already registered Collectors — do not fulfill the consistency and // uniqueness criteria described in the documentation of metric.Desc. // // If the provided Collector is equal to a Collector already registered // (which includes the case of re-registering the same Collector), the // returned error is an instance of AlreadyRegisteredError, which // contains the previously registered Collector. // // A Collector whose Describe method does not yield any Desc is treated // as unchecked. Registration will always succeed. No check for // re-registering (see previous paragraph) is performed. Thus, the // caller is responsible for not double-registering the same unchecked // Collector, and for providing a Collector that will not cause // inconsistent metrics on collection. (This would lead to scrape // errors.) Register(Collector) error // MustRegister works like Register but registers any number of // Collectors and panics upon the first registration that causes an // error. MustRegister(...Collector) // Unregister unregisters the Collector that equals the Collector passed // in as an argument. (Two Collectors are considered equal if their // Describe method yields the same set of descriptors.) The function // returns whether a Collector was unregistered. Note that an unchecked // Collector cannot be unregistered (as its Describe method does not // yield any descriptor). // // Note that even after unregistering, it will not be possible to // register a new Collector that is inconsistent with the unregistered // Collector, e.g. a Collector collecting metrics with the same name but // a different help string. The rationale here is that the same registry // instance must only collect consistent metrics throughout its // lifetime. Unregister(Collector) bool } // Gatherer is the interface for the part of a registry in charge of gathering // the collected metrics into a number of MetricFamilies. The Gatherer interface // comes with the same general implication as described for the Registerer // interface. type Gatherer interface { // Gather calls the Collect method of the registered Collectors and then // gathers the collected metrics into a lexicographically sorted slice // of uniquely named MetricFamily protobufs. Gather ensures that the // returned slice is valid and self-consistent so that it can be used // for valid exposition. As an exception to the strict consistency // requirements described for metric.Desc, Gather will tolerate // different sets of label names for metrics of the same metric family. // // Even if an error occurs, Gather attempts to gather as many metrics as // possible. Hence, if a non-nil error is returned, the returned // MetricFamily slice could be nil (in case of a fatal error that // prevented any meaningful metric collection) or contain a number of // MetricFamily protobufs, some of which might be incomplete, and some // might be missing altogether. The returned error (which might be a // MultiError) explains the details. Note that this is mostly useful for // debugging purposes. If the gathered protobufs are to be used for // exposition in actual monitoring, it is almost always better to not // expose an incomplete result and instead disregard the returned // MetricFamily protobufs in case the returned error is non-nil. Gather() ([]*dto.MetricFamily, error) } // Register registers the provided Collector with the DefaultRegisterer. // // Register is a shortcut for DefaultRegisterer.Register(c). See there for more // details. func Register(c Collector) error { return DefaultRegisterer.Register(c) } // MustRegister registers the provided Collectors with the DefaultRegisterer and // panics if any error occurs. // // MustRegister is a shortcut for DefaultRegisterer.MustRegister(cs...). See // there for more details. func MustRegister(cs ...Collector) { DefaultRegisterer.MustRegister(cs...) } // Unregister removes the registration of the provided Collector from the // DefaultRegisterer. // // Unregister is a shortcut for DefaultRegisterer.Unregister(c). See there for // more details. func Unregister(c Collector) bool { return DefaultRegisterer.Unregister(c) } // GathererFunc turns a function into a Gatherer. type GathererFunc func() ([]*dto.MetricFamily, error) // Gather implements Gatherer. func (gf GathererFunc) Gather() ([]*dto.MetricFamily, error) { return gf() } // AlreadyRegisteredError is returned by the Register method if the Collector to // be registered has already been registered before, or a different Collector // that collects the same metrics has been registered before. Registration fails // in that case, but you can detect from the kind of error what has // happened. The error contains fields for the existing Collector and the // (rejected) new Collector that equals the existing one. This can be used to // find out if an equal Collector has been registered before and switch over to // using the old one, as demonstrated in the example. type AlreadyRegisteredError struct { ExistingCollector, NewCollector Collector } func (err AlreadyRegisteredError) Error() string { return "duplicate metrics collector registration attempted" } // MultiError is a slice of errors implementing the error interface. It is used // by a Gatherer to report multiple errors during MetricFamily gathering. type MultiError []error func (errs MultiError) Error() string { if len(errs) == 0 { return "" } buf := &bytes.Buffer{} fmt.Fprintf(buf, "%d error(s) occurred:", len(errs)) for _, err := range errs { fmt.Fprintf(buf, "\n* %s", err) } return buf.String() } // Append appends the provided error if it is not nil. func (errs *MultiError) Append(err error) { if err != nil { *errs = append(*errs, err) } } // MaybeUnwrap returns nil if len(errs) is 0. It returns the first and only // contained error as error if len(errs is 1). In all other cases, it returns // the MultiError directly. This is helpful for returning a MultiError in a way // that only uses the MultiError if needed. func (errs MultiError) MaybeUnwrap() error { switch len(errs) { case 0: return nil case 1: return errs[0] default: return errs } } // Registry registers Prometheus collectors, collects their metrics, and gathers // them into MetricFamilies for exposition. It implements both Registerer and // Gatherer. The zero value is not usable. Create instances with NewRegistry or // NewPedanticRegistry. type Registry struct { mtx sync.RWMutex collectorsByID map[uint64]Collector // ID is a hash of the descIDs. descIDs map[uint64]struct{} dimHashesByName map[string]uint64 uncheckedCollectors []Collector pedanticChecksEnabled bool } // Register implements Registerer. func (r *Registry) Register(c Collector) error { var ( descChan = make(chan *Desc, capDescChan) newDescIDs = map[uint64]struct{}{} newDimHashesByName = map[string]uint64{} collectorID uint64 // All desc IDs XOR'd together. duplicateDescErr error ) go func() { c.Describe(descChan) close(descChan) }() r.mtx.Lock() defer func() { // Drain channel in case of premature return to not leak a goroutine. for range descChan { } r.mtx.Unlock() }() // Conduct various tests... for desc := range descChan { // Is the descriptor valid at all? if desc.err != nil { return fmt.Errorf("descriptor %s is invalid: %s", desc, desc.err) } // Is the descID unique? // (In other words: Is the fqName + constLabel combination unique?) if _, exists := r.descIDs[desc.id]; exists { duplicateDescErr = fmt.Errorf("descriptor %s already exists with the same fully-qualified name and const label values", desc) } // If it is not a duplicate desc in this collector, XOR it to // the collectorID. (We allow duplicate descs within the same // collector, but their existence must be a no-op.) if _, exists := newDescIDs[desc.id]; !exists { newDescIDs[desc.id] = struct{}{} collectorID ^= desc.id } // Are all the label names and the help string consistent with // previous descriptors of the same name? // First check existing descriptors... if dimHash, exists := r.dimHashesByName[desc.fqName]; exists { if dimHash != desc.dimHash { return fmt.Errorf("a previously registered descriptor with the same fully-qualified name as %s has different label names or a different help string", desc) } } else { // ...then check the new descriptors already seen. if dimHash, exists := newDimHashesByName[desc.fqName]; exists { if dimHash != desc.dimHash { return fmt.Errorf("descriptors reported by collector have inconsistent label names or help strings for the same fully-qualified name, offender is %s", desc) } } else { newDimHashesByName[desc.fqName] = desc.dimHash } } } // A Collector yielding no Desc at all is considered unchecked. if len(newDescIDs) == 0 { r.uncheckedCollectors = append(r.uncheckedCollectors, c) return nil } if existing, exists := r.collectorsByID[collectorID]; exists { switch e := existing.(type) { case *wrappingCollector: return AlreadyRegisteredError{ ExistingCollector: e.unwrapRecursively(), NewCollector: c, } default: return AlreadyRegisteredError{ ExistingCollector: e, NewCollector: c, } } } // If the collectorID is new, but at least one of the descs existed // before, we are in trouble. if duplicateDescErr != nil { return duplicateDescErr } // Only after all tests have passed, actually register. r.collectorsByID[collectorID] = c for hash := range newDescIDs { r.descIDs[hash] = struct{}{} } for name, dimHash := range newDimHashesByName { r.dimHashesByName[name] = dimHash } return nil } // Unregister implements Registerer. func (r *Registry) Unregister(c Collector) bool { var ( descChan = make(chan *Desc, capDescChan) descIDs = map[uint64]struct{}{} collectorID uint64 // All desc IDs XOR'd together. ) go func() { c.Describe(descChan) close(descChan) }() for desc := range descChan { if _, exists := descIDs[desc.id]; !exists { collectorID ^= desc.id descIDs[desc.id] = struct{}{} } } r.mtx.RLock() if _, exists := r.collectorsByID[collectorID]; !exists { r.mtx.RUnlock() return false } r.mtx.RUnlock() r.mtx.Lock() defer r.mtx.Unlock() delete(r.collectorsByID, collectorID) for id := range descIDs { delete(r.descIDs, id) } // dimHashesByName is left untouched as those must be consistent // throughout the lifetime of a program. return true } // MustRegister implements Registerer. func (r *Registry) MustRegister(cs ...Collector) { for _, c := range cs { if err := r.Register(c); err != nil { panic(err) } } } // Gather implements Gatherer. func (r *Registry) Gather() ([]*dto.MetricFamily, error) { var ( checkedMetricChan = make(chan Metric, capMetricChan) uncheckedMetricChan = make(chan Metric, capMetricChan) metricHashes = map[uint64]struct{}{} wg sync.WaitGroup errs MultiError // The collected errors to return in the end. registeredDescIDs map[uint64]struct{} // Only used for pedantic checks ) r.mtx.RLock() goroutineBudget := len(r.collectorsByID) + len(r.uncheckedCollectors) metricFamiliesByName := make(map[string]*dto.MetricFamily, len(r.dimHashesByName)) checkedCollectors := make(chan Collector, len(r.collectorsByID)) uncheckedCollectors := make(chan Collector, len(r.uncheckedCollectors)) for _, collector := range r.collectorsByID { checkedCollectors <- collector } for _, collector := range r.uncheckedCollectors { uncheckedCollectors <- collector } // In case pedantic checks are enabled, we have to copy the map before // giving up the RLock. if r.pedanticChecksEnabled { registeredDescIDs = make(map[uint64]struct{}, len(r.descIDs)) for id := range r.descIDs { registeredDescIDs[id] = struct{}{} } } r.mtx.RUnlock() wg.Add(goroutineBudget) collectWorker := func() { for { select { case collector := <-checkedCollectors: collector.Collect(checkedMetricChan) case collector := <-uncheckedCollectors: collector.Collect(uncheckedMetricChan) default: return } wg.Done() } } // Start the first worker now to make sure at least one is running. go collectWorker() goroutineBudget-- // Close checkedMetricChan and uncheckedMetricChan once all collectors // are collected. go func() { wg.Wait() close(checkedMetricChan) close(uncheckedMetricChan) }() // Drain checkedMetricChan and uncheckedMetricChan in case of premature return. defer func() { if checkedMetricChan != nil { for range checkedMetricChan { } } if uncheckedMetricChan != nil { for range uncheckedMetricChan { } } }() // Copy the channel references so we can nil them out later to remove // them from the select statements below. cmc := checkedMetricChan umc := uncheckedMetricChan for { select { case metric, ok := <-cmc: if !ok { cmc = nil break } errs.Append(processMetric( metric, metricFamiliesByName, metricHashes, registeredDescIDs, )) case metric, ok := <-umc: if !ok { umc = nil break } errs.Append(processMetric( metric, metricFamiliesByName, metricHashes, nil, )) default: if goroutineBudget <= 0 || len(checkedCollectors)+len(uncheckedCollectors) == 0 { // All collectors are already being worked on or // we have already as many goroutines started as // there are collectors. Do the same as above, // just without the default. select { case metric, ok := <-cmc: if !ok { cmc = nil break } errs.Append(processMetric( metric, metricFamiliesByName, metricHashes, registeredDescIDs, )) case metric, ok := <-umc: if !ok { umc = nil break } errs.Append(processMetric( metric, metricFamiliesByName, metricHashes, nil, )) } break } // Start more workers. go collectWorker() goroutineBudget-- runtime.Gosched() } // Once both checkedMetricChan and uncheckdMetricChan are closed // and drained, the contraption above will nil out cmc and umc, // and then we can leave the collect loop here. if cmc == nil && umc == nil { break } } return internal.NormalizeMetricFamilies(metricFamiliesByName), errs.MaybeUnwrap() } // WriteToTextfile calls Gather on the provided Gatherer, encodes the result in the // Prometheus text format, and writes it to a temporary file. Upon success, the // temporary file is renamed to the provided filename. // // This is intended for use with the textfile collector of the node exporter. // Note that the node exporter expects the filename to be suffixed with ".prom". func WriteToTextfile(filename string, g Gatherer) error { tmp, err := ioutil.TempFile(filepath.Dir(filename), filepath.Base(filename)) if err != nil { return err } defer os.Remove(tmp.Name()) mfs, err := g.Gather() if err != nil { return err } for _, mf := range mfs { if _, err := expfmt.MetricFamilyToText(tmp, mf); err != nil { return err } } if err := tmp.Close(); err != nil { return err } if err := os.Chmod(tmp.Name(), 0644); err != nil { return err } return os.Rename(tmp.Name(), filename) } // processMetric is an internal helper method only used by the Gather method. func processMetric( metric Metric, metricFamiliesByName map[string]*dto.MetricFamily, metricHashes map[uint64]struct{}, registeredDescIDs map[uint64]struct{}, ) error { desc := metric.Desc() // Wrapped metrics collected by an unchecked Collector can have an // invalid Desc. if desc.err != nil { return desc.err } dtoMetric := &dto.Metric{} if err := metric.Write(dtoMetric); err != nil { return fmt.Errorf("error collecting metric %v: %s", desc, err) } metricFamily, ok := metricFamiliesByName[desc.fqName] if ok { // Existing name. if metricFamily.GetHelp() != desc.help { return fmt.Errorf( "collected metric %s %s has help %q but should have %q", desc.fqName, dtoMetric, desc.help, metricFamily.GetHelp(), ) } // TODO(beorn7): Simplify switch once Desc has type. switch metricFamily.GetType() { case dto.MetricType_COUNTER: if dtoMetric.Counter == nil { return fmt.Errorf( "collected metric %s %s should be a Counter", desc.fqName, dtoMetric, ) } case dto.MetricType_GAUGE: if dtoMetric.Gauge == nil { return fmt.Errorf( "collected metric %s %s should be a Gauge", desc.fqName, dtoMetric, ) } case dto.MetricType_SUMMARY: if dtoMetric.Summary == nil { return fmt.Errorf( "collected metric %s %s should be a Summary", desc.fqName, dtoMetric, ) } case dto.MetricType_UNTYPED: if dtoMetric.Untyped == nil { return fmt.Errorf( "collected metric %s %s should be Untyped", desc.fqName, dtoMetric, ) } case dto.MetricType_HISTOGRAM: if dtoMetric.Histogram == nil { return fmt.Errorf( "collected metric %s %s should be a Histogram", desc.fqName, dtoMetric, ) } default: panic("encountered MetricFamily with invalid type") } } else { // New name. metricFamily = &dto.MetricFamily{} metricFamily.Name = proto.String(desc.fqName) metricFamily.Help = proto.String(desc.help) // TODO(beorn7): Simplify switch once Desc has type. switch { case dtoMetric.Gauge != nil: metricFamily.Type = dto.MetricType_GAUGE.Enum() case dtoMetric.Counter != nil: metricFamily.Type = dto.MetricType_COUNTER.Enum() case dtoMetric.Summary != nil: metricFamily.Type = dto.MetricType_SUMMARY.Enum() case dtoMetric.Untyped != nil: metricFamily.Type = dto.MetricType_UNTYPED.Enum() case dtoMetric.Histogram != nil: metricFamily.Type = dto.MetricType_HISTOGRAM.Enum() default: return fmt.Errorf("empty metric collected: %s", dtoMetric) } if err := checkSuffixCollisions(metricFamily, metricFamiliesByName); err != nil { return err } metricFamiliesByName[desc.fqName] = metricFamily } if err := checkMetricConsistency(metricFamily, dtoMetric, metricHashes); err != nil { return err } if registeredDescIDs != nil { // Is the desc registered at all? if _, exist := registeredDescIDs[desc.id]; !exist { return fmt.Errorf( "collected metric %s %s with unregistered descriptor %s", metricFamily.GetName(), dtoMetric, desc, ) } if err := checkDescConsistency(metricFamily, dtoMetric, desc); err != nil { return err } } metricFamily.Metric = append(metricFamily.Metric, dtoMetric) return nil } // Gatherers is a slice of Gatherer instances that implements the Gatherer // interface itself. Its Gather method calls Gather on all Gatherers in the // slice in order and returns the merged results. Errors returned from the // Gather calls are all returned in a flattened MultiError. Duplicate and // inconsistent Metrics are skipped (first occurrence in slice order wins) and // reported in the returned error. // // Gatherers can be used to merge the Gather results from multiple // Registries. It also provides a way to directly inject existing MetricFamily // protobufs into the gathering by creating a custom Gatherer with a Gather // method that simply returns the existing MetricFamily protobufs. Note that no // registration is involved (in contrast to Collector registration), so // obviously registration-time checks cannot happen. Any inconsistencies between // the gathered MetricFamilies are reported as errors by the Gather method, and // inconsistent Metrics are dropped. Invalid parts of the MetricFamilies // (e.g. syntactically invalid metric or label names) will go undetected. type Gatherers []Gatherer // Gather implements Gatherer. func (gs Gatherers) Gather() ([]*dto.MetricFamily, error) { var ( metricFamiliesByName = map[string]*dto.MetricFamily{} metricHashes = map[uint64]struct{}{} errs MultiError // The collected errors to return in the end. ) for i, g := range gs { mfs, err := g.Gather() if err != nil { if multiErr, ok := err.(MultiError); ok { for _, err := range multiErr { errs = append(errs, fmt.Errorf("[from Gatherer #%d] %s", i+1, err)) } } else { errs = append(errs, fmt.Errorf("[from Gatherer #%d] %s", i+1, err)) } } for _, mf := range mfs { existingMF, exists := metricFamiliesByName[mf.GetName()] if exists { if existingMF.GetHelp() != mf.GetHelp() { errs = append(errs, fmt.Errorf( "gathered metric family %s has help %q but should have %q", mf.GetName(), mf.GetHelp(), existingMF.GetHelp(), )) continue } if existingMF.GetType() != mf.GetType() { errs = append(errs, fmt.Errorf( "gathered metric family %s has type %s but should have %s", mf.GetName(), mf.GetType(), existingMF.GetType(), )) continue } } else { existingMF = &dto.MetricFamily{} existingMF.Name = mf.Name existingMF.Help = mf.Help existingMF.Type = mf.Type if err := checkSuffixCollisions(existingMF, metricFamiliesByName); err != nil { errs = append(errs, err) continue } metricFamiliesByName[mf.GetName()] = existingMF } for _, m := range mf.Metric { if err := checkMetricConsistency(existingMF, m, metricHashes); err != nil { errs = append(errs, err) continue } existingMF.Metric = append(existingMF.Metric, m) } } } return internal.NormalizeMetricFamilies(metricFamiliesByName), errs.MaybeUnwrap() } // checkSuffixCollisions checks for collisions with the “magic” suffixes the // Prometheus text format and the internal metric representation of the // Prometheus server add while flattening Summaries and Histograms. func checkSuffixCollisions(mf *dto.MetricFamily, mfs map[string]*dto.MetricFamily) error { var ( newName = mf.GetName() newType = mf.GetType() newNameWithoutSuffix = "" ) switch { case strings.HasSuffix(newName, "_count"): newNameWithoutSuffix = newName[:len(newName)-6] case strings.HasSuffix(newName, "_sum"): newNameWithoutSuffix = newName[:len(newName)-4] case strings.HasSuffix(newName, "_bucket"): newNameWithoutSuffix = newName[:len(newName)-7] } if newNameWithoutSuffix != "" { if existingMF, ok := mfs[newNameWithoutSuffix]; ok { switch existingMF.GetType() { case dto.MetricType_SUMMARY: if !strings.HasSuffix(newName, "_bucket") { return fmt.Errorf( "collected metric named %q collides with previously collected summary named %q", newName, newNameWithoutSuffix, ) } case dto.MetricType_HISTOGRAM: return fmt.Errorf( "collected metric named %q collides with previously collected histogram named %q", newName, newNameWithoutSuffix, ) } } } if newType == dto.MetricType_SUMMARY || newType == dto.MetricType_HISTOGRAM { if _, ok := mfs[newName+"_count"]; ok { return fmt.Errorf( "collected histogram or summary named %q collides with previously collected metric named %q", newName, newName+"_count", ) } if _, ok := mfs[newName+"_sum"]; ok { return fmt.Errorf( "collected histogram or summary named %q collides with previously collected metric named %q", newName, newName+"_sum", ) } } if newType == dto.MetricType_HISTOGRAM { if _, ok := mfs[newName+"_bucket"]; ok { return fmt.Errorf( "collected histogram named %q collides with previously collected metric named %q", newName, newName+"_bucket", ) } } return nil } // checkMetricConsistency checks if the provided Metric is consistent with the // provided MetricFamily. It also hashes the Metric labels and the MetricFamily // name. If the resulting hash is already in the provided metricHashes, an error // is returned. If not, it is added to metricHashes. func checkMetricConsistency( metricFamily *dto.MetricFamily, dtoMetric *dto.Metric, metricHashes map[uint64]struct{}, ) error { name := metricFamily.GetName() // Type consistency with metric family. if metricFamily.GetType() == dto.MetricType_GAUGE && dtoMetric.Gauge == nil || metricFamily.GetType() == dto.MetricType_COUNTER && dtoMetric.Counter == nil || metricFamily.GetType() == dto.MetricType_SUMMARY && dtoMetric.Summary == nil || metricFamily.GetType() == dto.MetricType_HISTOGRAM && dtoMetric.Histogram == nil || metricFamily.GetType() == dto.MetricType_UNTYPED && dtoMetric.Untyped == nil { return fmt.Errorf( "collected metric %q { %s} is not a %s", name, dtoMetric, metricFamily.GetType(), ) } previousLabelName := "" for _, labelPair := range dtoMetric.GetLabel() { labelName := labelPair.GetName() if labelName == previousLabelName { return fmt.Errorf( "collected metric %q { %s} has two or more labels with the same name: %s", name, dtoMetric, labelName, ) } if !checkLabelName(labelName) { return fmt.Errorf( "collected metric %q { %s} has a label with an invalid name: %s", name, dtoMetric, labelName, ) } if dtoMetric.Summary != nil && labelName == quantileLabel { return fmt.Errorf( "collected metric %q { %s} must not have an explicit %q label", name, dtoMetric, quantileLabel, ) } if !utf8.ValidString(labelPair.GetValue()) { return fmt.Errorf( "collected metric %q { %s} has a label named %q whose value is not utf8: %#v", name, dtoMetric, labelName, labelPair.GetValue()) } previousLabelName = labelName } // Is the metric unique (i.e. no other metric with the same name and the same labels)? h := xxhash.New() h.WriteString(name) h.Write(separatorByteSlice) // Make sure label pairs are sorted. We depend on it for the consistency // check. if !sort.IsSorted(labelPairSorter(dtoMetric.Label)) { // We cannot sort dtoMetric.Label in place as it is immutable by contract. copiedLabels := make([]*dto.LabelPair, len(dtoMetric.Label)) copy(copiedLabels, dtoMetric.Label) sort.Sort(labelPairSorter(copiedLabels)) dtoMetric.Label = copiedLabels } for _, lp := range dtoMetric.Label { h.WriteString(lp.GetName()) h.Write(separatorByteSlice) h.WriteString(lp.GetValue()) h.Write(separatorByteSlice) } hSum := h.Sum64() if _, exists := metricHashes[hSum]; exists { return fmt.Errorf( "collected metric %q { %s} was collected before with the same name and label values", name, dtoMetric, ) } metricHashes[hSum] = struct{}{} return nil } func checkDescConsistency( metricFamily *dto.MetricFamily, dtoMetric *dto.Metric, desc *Desc, ) error { // Desc help consistency with metric family help. if metricFamily.GetHelp() != desc.help { return fmt.Errorf( "collected metric %s %s has help %q but should have %q", metricFamily.GetName(), dtoMetric, metricFamily.GetHelp(), desc.help, ) } // Is the desc consistent with the content of the metric? lpsFromDesc := make([]*dto.LabelPair, len(desc.constLabelPairs), len(dtoMetric.Label)) copy(lpsFromDesc, desc.constLabelPairs) for _, l := range desc.variableLabels { lpsFromDesc = append(lpsFromDesc, &dto.LabelPair{ Name: proto.String(l), }) } if len(lpsFromDesc) != len(dtoMetric.Label) { return fmt.Errorf( "labels in collected metric %s %s are inconsistent with descriptor %s", metricFamily.GetName(), dtoMetric, desc, ) } sort.Sort(labelPairSorter(lpsFromDesc)) for i, lpFromDesc := range lpsFromDesc { lpFromMetric := dtoMetric.Label[i] if lpFromDesc.GetName() != lpFromMetric.GetName() || lpFromDesc.Value != nil && lpFromDesc.GetValue() != lpFromMetric.GetValue() { return fmt.Errorf( "labels in collected metric %s %s are inconsistent with descriptor %s", metricFamily.GetName(), dtoMetric, desc, ) } } return nil }
{ "pile_set_name": "Github" }
/** * Module dependencies. */ var utils = require('./utils'); /** * Initialization middleware, exposing the * request and response to eachother, as well * as defaulting the X-Powered-By header field. * * @param {Function} app * @return {Function} * @api private */ exports.init = function(app){ return function expressInit(req, res, next){ req.app = res.app = app; if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); req.res = res; res.req = req; req.next = next; req.__proto__ = app.request; res.__proto__ = app.response; res.locals = res.locals || utils.locals(res); next(); } };
{ "pile_set_name": "Github" }
// license:LGPL-2.1+ // copyright-holders:Michael Zapf /**************************************************************************** Horizon Ramdisk See horizon.c for documentation Michael Zapf February 2012 *****************************************************************************/ #ifndef MAME_BUS_TI99_PEB_HORIZON_H #define MAME_BUS_TI99_PEB_HORIZON_H #pragma once #include "peribox.h" #include "machine/ram.h" namespace bus { namespace ti99 { namespace peb { class horizon_ramdisk_device : public device_t, public device_ti99_peribox_card_interface, public device_nvram_interface { public: horizon_ramdisk_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock); void readz(offs_t offset, uint8_t *value) override; void write(offs_t offset, uint8_t data) override; void crureadz(offs_t offset, uint8_t *value) override; void cruwrite(offs_t offset, uint8_t data) override; DECLARE_INPUT_CHANGED_MEMBER( hs_changed ); protected: void device_start() override; void device_reset() override; virtual void device_add_mconfig(machine_config &config) override; virtual ioport_constructor device_input_ports() const override; void nvram_default() override; void nvram_read(emu_file &file) override; void nvram_write(emu_file &file) override; private: void setbit(int& page, int pattern, bool set); required_device<ram_device> m_ram; required_device<ram_device> m_nvram; required_device<ram_device> m_ros; int m_page; int m_cru_horizon; int m_cru_phoenix; bool m_timode; bool m_32k_installed; bool m_split_mode; bool m_rambo_mode; bool m_hideswitch; bool m_use_rambo; bool m_genmod_fix; }; } } } // end namespace bus::ti99::peb DECLARE_DEVICE_TYPE_NS(TI99_HORIZON, bus::ti99::peb, horizon_ramdisk_device) #endif // MAME_BUS_TI99_PEB_HORIZON_H
{ "pile_set_name": "Github" }
[files] basehome:modules/demo/demo-config.xml|etc/demo-config.xml
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title></title> <link rel="Stylesheet" href="../css/analysis.css" /> <script type="text/javascript"> function init() { if (window.location.hash) { var parentDiv, nodes, i, helpInfo, helpId, helpInfoArr, helpEnvFilter, envContent, hideEnvClass, hideNodes; helpInfo = window.location.hash.substring(1); if(helpInfo.indexOf("-")) { helpInfoArr = helpInfo.split("-"); helpId = helpInfoArr[0]; helpEnvFilter = helpInfoArr[1]; } else { helpId = helpInfo; } parentDiv = document.getElementById("topics"); nodes = parentDiv.children; hideEnvClass = (helpEnvFilter === "OnlineOnly"? "PortalOnly": "OnlineOnly"); if(document.getElementsByClassName) { hideNodes = document.getElementsByClassName(hideEnvClass); } else { hideNodes = document.querySelectorAll(hideEnvClass); } for(i=0; i < nodes.length; i++) { if(nodes[i].id !== helpId) { nodes[i].style.display ="none"; } } for(i=0; i < hideNodes.length; i++) { hideNodes[i].style.display ="none"; } } } </script> </head> <body onload="init()"> <div id="topics"> <div id="toolDescription" class="smallsize"> <h2>Stabilirea rețelei cu costuri optime de deplasare</h2><p/> <h2><img src="../images/GUID-097BDD6E-0AD8-44F2-BB70-C5395F4B1AF4-web.png" alt="Ilustrarea instrumentului Stabilirea rețelei cu costuri optime de deplasare"></h2> <hr/> <p>Acest instrument calculează rețeaua cu costuri optime dintr-un set de regiuni de introducere. </p> <p>Un exemplu de utilizare a acestui instrument este găsirea celei mai bune rețele pentru vehiculele de urgență. </p> <p>Dacă se bifează <b>Utilizare extindere curentă hartă</b>, vor fi analizate numai acele locaţii din stratul tematic de intrare care sunt vizibile &icirc;n extinderea curentă a hărţii. Dacă nu se bifează, toate locaţiile din stratul tematic de intrare vor fi analizate, chiar dacă se află &icirc;n afara extinderii curente a hărţii. </p> </div> <!--Parameter divs for each param--> <div id="inputRegionsRasterOrFeatures"> <div><h2>Alegeți rasterul sau stratul tematic al locației pentru a stabili traseele de deplasare dintre</h2></div> <hr/> <div> <p>Regiunile de intrare care vor fi conectate de rețea cu cele mai mici costuri. </p> <p>Regiunile pot fi definite fie de către un serviciu de imagini sau un serviciu de obiecte spaţiale. </p> <p>Pentru serviciul de imagini, regiunile sunt definite de grupuri de celule apropiate (adiacente) de aceeași valoare. Fiecare regiune trebuie să primească un număr unic. Celulele care nu fac parte din nicio regiune trebuie să fie NoData. Tipul rasterului trebuie să fie un număr &icirc;ntreg, iar valorile pot fi pozitive sau negative. </p> <p>Pentru serviciul de obiecte spaţiale, intrarea poate fi un punct, o linie sau un poligon. </p> </div> </div> <div id="inputCostRaster"> <div><h2>Alegeţi stratul tematic raster cu costuri de deplasare</h2></div> <hr/> <div> <p>Un raster care definește impedanța sau costul deplasării planimetrice prin fiecare celulă. </p> <p>Valoarea din fiecare amplasare a celulei reprezintă distanța cost-pe-unitate pentru deplasarea prin celulă. Fiecare valoare de localizare a celulei este &icirc;nmulțită cu rezoluției celulei &icirc;n timp ce se compensează deplasarea pe diagonală pentru a obține costul total al deplasării prin celulă. </p> <p>Valorile rasterului de cost poate fi un număr &icirc;ntreg sau o virgulă mobilă, dar nu pot fi negative sau zero (nu puteți avea un cost negativ sau zero). </p> </div> </div> <div id="outputOptimumNetworkName"> <div><h2>Numele stratului tematic poliliniar al traseelor optime rezultante</h2></div> <hr/> <div> <p>Acesta este numele stratului tematic ce va fi creat &icirc;n <b>Resursele mele</b> şi va fi adăugat pe hartă. Numele implicit se bazează pe numele instrumentului şi numele stratului tematic de intrare. Dacă stratul tematic rezultat există deja, vi se va solicita să furnizaţi un alt nume. </p> <p>Puteți specifica numele folderului &icirc;n <b>Resursele mele</b> unde se va salva rezultatul folosind caseta drop-down <b>Salvați rezultatele &icirc;n</b>. </p> </div> </div> <div id="outputNeighborNetworkName"> <div><h2>Numele stratului tematic poliliniar al traseelor apropiate rezultante</h2></div> <hr/> <div> <p>Acesta este numele stratului tematic ce va fi creat &icirc;n <b>Resursele mele</b> şi va fi adăugat pe hartă. Numele implicit se bazează pe numele instrumentului şi numele stratului tematic de intrare. Dacă stratul tematic rezultat există deja, vi se va solicita să furnizaţi un alt nume. </p> <p>Puteți specifica numele folderului &icirc;n <b>Resursele mele</b> unde se va salva rezultatul folosind caseta drop-down <b>Salvați rezultatele &icirc;n</b>. </p> </div> </div> </div> </html>
{ "pile_set_name": "Github" }
//===- TargetFrameLoweringImpl.cpp - Implement target frame interface ------==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implements the layout of a stack frame on the target machine. // //===----------------------------------------------------------------------===// #include "llvm/ADT/BitVector.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/IR/Attributes.h" #include "llvm/IR/CallingConv.h" #include "llvm/IR/Function.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/Support/Compiler.h" #include "llvm/Target/TargetFrameLowering.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Target/TargetSubtargetInfo.h" using namespace llvm; TargetFrameLowering::~TargetFrameLowering() = default; /// The default implementation just looks at attribute "no-frame-pointer-elim". bool TargetFrameLowering::noFramePointerElim(const MachineFunction &MF) const { auto Attr = MF.getFunction()->getFnAttribute("no-frame-pointer-elim"); return Attr.getValueAsString() == "true"; } /// Returns the displacement from the frame register to the stack /// frame of the specified index, along with the frame register used /// (in output arg FrameReg). This is the default implementation which /// is overridden for some targets. int TargetFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI, unsigned &FrameReg) const { const MachineFrameInfo &MFI = MF.getFrameInfo(); const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); // By default, assume all frame indices are referenced via whatever // getFrameRegister() says. The target can override this if it's doing // something different. FrameReg = RI->getFrameRegister(MF); return MFI.getObjectOffset(FI) + MFI.getStackSize() - getOffsetOfLocalArea() + MFI.getOffsetAdjustment(); } bool TargetFrameLowering::needsFrameIndexResolution( const MachineFunction &MF) const { return MF.getFrameInfo().hasStackObjects(); } void TargetFrameLowering::determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS) const { const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); // Resize before the early returns. Some backends expect that // SavedRegs.size() == TRI.getNumRegs() after this call even if there are no // saved registers. SavedRegs.resize(TRI.getNumRegs()); // When interprocedural register allocation is enabled caller saved registers // are preferred over callee saved registers. if (MF.getTarget().Options.EnableIPRA && isSafeForNoCSROpt(MF.getFunction())) return; // Get the callee saved register list... const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs(); // Early exit if there are no callee saved registers. if (!CSRegs || CSRegs[0] == 0) return; // In Naked functions we aren't going to save any registers. if (MF.getFunction()->hasFnAttribute(Attribute::Naked)) return; // Functions which call __builtin_unwind_init get all their registers saved. bool CallsUnwindInit = MF.callsUnwindInit(); const MachineRegisterInfo &MRI = MF.getRegInfo(); for (unsigned i = 0; CSRegs[i]; ++i) { unsigned Reg = CSRegs[i]; if (CallsUnwindInit || MRI.isPhysRegModified(Reg)) SavedRegs.set(Reg); } } unsigned TargetFrameLowering::getStackAlignmentSkew( const MachineFunction &MF) const { // When HHVM function is called, the stack is skewed as the return address // is removed from the stack before we enter the function. if (LLVM_UNLIKELY(MF.getFunction()->getCallingConv() == CallingConv::HHVM)) return MF.getTarget().getPointerSize(); return 0; }
{ "pile_set_name": "Github" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Assets { using System; public class AssetManagerException : Exception { public AssetManagerException(string message) : base(message) { } } }
{ "pile_set_name": "Github" }
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu_buffer * refcounted data buffer API */ #ifndef AVUTIL_BUFFER_H #define AVUTIL_BUFFER_H #include <stdint.h> /** * @defgroup lavu_buffer AVBuffer * @ingroup lavu_data * * @{ * AVBuffer is an API for reference-counted data buffers. * * There are two core objects in this API -- AVBuffer and AVBufferRef. AVBuffer * represents the data buffer itself; it is opaque and not meant to be accessed * by the caller directly, but only through AVBufferRef. However, the caller may * e.g. compare two AVBuffer pointers to check whether two different references * are describing the same data buffer. AVBufferRef represents a single * reference to an AVBuffer and it is the object that may be manipulated by the * caller directly. * * There are two functions provided for creating a new AVBuffer with a single * reference -- av_buffer_alloc() to just allocate a new buffer, and * av_buffer_create() to wrap an existing array in an AVBuffer. From an existing * reference, additional references may be created with av_buffer_ref(). * Use av_buffer_unref() to free a reference (this will automatically free the * data once all the references are freed). * * The convention throughout this API and the rest of FFmpeg is such that the * buffer is considered writable if there exists only one reference to it (and * it has not been marked as read-only). The av_buffer_is_writable() function is * provided to check whether this is true and av_buffer_make_writable() will * automatically create a new writable buffer when necessary. * Of course nothing prevents the calling code from violating this convention, * however that is safe only when all the existing references are under its * control. * * @note Referencing and unreferencing the buffers is thread-safe and thus * may be done from multiple threads simultaneously without any need for * additional locking. * * @note Two different references to the same buffer can point to different * parts of the buffer (i.e. their AVBufferRef.data will not be equal). */ /** * A reference counted buffer type. It is opaque and is meant to be used through * references (AVBufferRef). */ typedef struct AVBuffer AVBuffer; /** * A reference to a data buffer. * * The size of this struct is not a part of the public ABI and it is not meant * to be allocated directly. */ typedef struct AVBufferRef { AVBuffer *buffer; /** * The data buffer. It is considered writable if and only if * this is the only reference to the buffer, in which case * av_buffer_is_writable() returns 1. */ uint8_t *data; /** * Size of data in bytes. */ int size; } AVBufferRef; /** * Allocate an AVBuffer of the given size using av_malloc(). * * @return an AVBufferRef of given size or NULL when out of memory */ AVBufferRef *av_buffer_alloc(int size); /** * Same as av_buffer_alloc(), except the returned buffer will be initialized * to zero. */ AVBufferRef *av_buffer_allocz(int size); /** * Always treat the buffer as read-only, even when it has only one * reference. */ #define AV_BUFFER_FLAG_READONLY (1 << 0) /** * Create an AVBuffer from an existing array. * * If this function is successful, data is owned by the AVBuffer. The caller may * only access data through the returned AVBufferRef and references derived from * it. * If this function fails, data is left untouched. * @param data data array * @param size size of data in bytes * @param free a callback for freeing this buffer's data * @param opaque parameter to be got for processing or passed to free * @param flags a combination of AV_BUFFER_FLAG_* * * @return an AVBufferRef referring to data on success, NULL on failure. */ AVBufferRef *av_buffer_create(uint8_t *data, int size, void (*free)(void *opaque, uint8_t *data), void *opaque, int flags); /** * Default free callback, which calls av_free() on the buffer data. * This function is meant to be passed to av_buffer_create(), not called * directly. */ void av_buffer_default_free(void *opaque, uint8_t *data); /** * Create a new reference to an AVBuffer. * * @return a new AVBufferRef referring to the same AVBuffer as buf or NULL on * failure. */ AVBufferRef *av_buffer_ref(AVBufferRef *buf); /** * Free a given reference and automatically free the buffer if there are no more * references to it. * * @param buf the reference to be freed. The pointer is set to NULL on return. */ void av_buffer_unref(AVBufferRef **buf); /** * @return 1 if the caller may write to the data referred to by buf (which is * true if and only if buf is the only reference to the underlying AVBuffer). * Return 0 otherwise. * A positive answer is valid until av_buffer_ref() is called on buf. */ int av_buffer_is_writable(const AVBufferRef *buf); /** * @return the opaque parameter set by av_buffer_create. */ void *av_buffer_get_opaque(const AVBufferRef *buf); int av_buffer_get_ref_count(const AVBufferRef *buf); /** * Create a writable reference from a given buffer reference, avoiding data copy * if possible. * * @param buf buffer reference to make writable. On success, buf is either left * untouched, or it is unreferenced and a new writable AVBufferRef is * written in its place. On failure, buf is left untouched. * @return 0 on success, a negative AVERROR on failure. */ int av_buffer_make_writable(AVBufferRef **buf); /** * Reallocate a given buffer. * * @param buf a buffer reference to reallocate. On success, buf will be * unreferenced and a new reference with the required size will be * written in its place. On failure buf will be left untouched. *buf * may be NULL, then a new buffer is allocated. * @param size required new buffer size. * @return 0 on success, a negative AVERROR on failure. * * @note the buffer is actually reallocated with av_realloc() only if it was * initially allocated through av_buffer_realloc(NULL) and there is only one * reference to it (i.e. the one passed to this function). In all other cases * a new buffer is allocated and the data is copied. */ int av_buffer_realloc(AVBufferRef **buf, int size); /** * @} */ /** * @defgroup lavu_bufferpool AVBufferPool * @ingroup lavu_data * * @{ * AVBufferPool is an API for a lock-free thread-safe pool of AVBuffers. * * Frequently allocating and freeing large buffers may be slow. AVBufferPool is * meant to solve this in cases when the caller needs a set of buffers of the * same size (the most obvious use case being buffers for raw video or audio * frames). * * At the beginning, the user must call av_buffer_pool_init() to create the * buffer pool. Then whenever a buffer is needed, call av_buffer_pool_get() to * get a reference to a new buffer, similar to av_buffer_alloc(). This new * reference works in all aspects the same way as the one created by * av_buffer_alloc(). However, when the last reference to this buffer is * unreferenced, it is returned to the pool instead of being freed and will be * reused for subsequent av_buffer_pool_get() calls. * * When the caller is done with the pool and no longer needs to allocate any new * buffers, av_buffer_pool_uninit() must be called to mark the pool as freeable. * Once all the buffers are released, it will automatically be freed. * * Allocating and releasing buffers with this API is thread-safe as long as * either the default alloc callback is used, or the user-supplied one is * thread-safe. */ /** * The buffer pool. This structure is opaque and not meant to be accessed * directly. It is allocated with av_buffer_pool_init() and freed with * av_buffer_pool_uninit(). */ typedef struct AVBufferPool AVBufferPool; /** * Allocate and initialize a buffer pool. * * @param size size of each buffer in this pool * @param alloc a function that will be used to allocate new buffers when the * pool is empty. May be NULL, then the default allocator will be used * (av_buffer_alloc()). * @return newly created buffer pool on success, NULL on error. */ AVBufferPool *av_buffer_pool_init(int size, AVBufferRef* (*alloc)(int size)); /** * Mark the pool as being available for freeing. It will actually be freed only * once all the allocated buffers associated with the pool are released. Thus it * is safe to call this function while some of the allocated buffers are still * in use. * * @param pool pointer to the pool to be freed. It will be set to NULL. * @see av_buffer_pool_can_uninit() */ void av_buffer_pool_uninit(AVBufferPool **pool); /** * Allocate a new AVBuffer, reusing an old buffer from the pool when available. * This function may be called simultaneously from multiple threads. * * @return a reference to the new buffer on success, NULL on error. */ AVBufferRef *av_buffer_pool_get(AVBufferPool *pool); /** * @} */ #endif /* AVUTIL_BUFFER_H */
{ "pile_set_name": "Github" }
<Product Revision="5" xmlns="https://github.com/OpenZWave/open-zwave"> <MetaData> <MetaDataItem name="OzwInfoPage">http://www.openzwave.com/device-database/0208:0008:0201</MetaDataItem> <MetaDataItem name="ProductPic">images/hank/hkzw-dws01.png</MetaDataItem> <MetaDataItem id="0008" name="ZWProductPage" type="0201">https://products.z-wavealliance.org/products/2775/</MetaDataItem> <MetaDataItem name="ProductManual">https://Products.Z-WaveAlliance.org/ProductManual/File?folder=&amp;filename=Manuals/2844/DoorWindowSensorEngineeringSpecification.pdf</MetaDataItem> <MetaDataItem name="InclusionDescription">1. Insert the AAA battery. 2. Set the Z-Wave network main controller into learning mode. 3. Triple or single short press the Z-button. 4. If the add for inclusion is successful, the LED will blink less than 5 seconds and then keep on 3 seconds. Otherwise, the LED will blink 5 seconds and then turn off, in which case you need to repeat the process from step 2. </MetaDataItem> <MetaDataItem name="ResetDescription">1. Insert the AAA battery. 2. Pressing and holding the Z button for more than 20 seconds, 3. Led will keep on until the Z-Button is released, and it will reset to factory default when the button is released. Using this procedure only in the event that the network primary controller is missing or otherwise inoperable. </MetaDataItem> <MetaDataItem id="0008" name="Identifier" type="0201">HKZW-DWS01</MetaDataItem> <MetaDataItem name="Description">Door/Window Sensor is a wireless reed sensor powered by AAA battery. It is used for detecting the opening or closing of doors, windows. It can communicate with an associated Z-Wave device, such as Siren, Smart Switch, etc.</MetaDataItem> <MetaDataItem name="ExclusionDescription">1. Insert the AAA battery. 2. Set the Z-Wave network main controller into learning mode. 3. Triple clicking the Z-button. 4. If the remove for exclusion, the LED will turn off within 1 second. Otherwise, the LED will blink 5 seconds and then turn off, in which case you need to repeat the process from step 2. </MetaDataItem> <MetaDataItem id="0008" name="FrequencyName" type="0201">U.S. / Canada / Mexico</MetaDataItem> <MetaDataItem name="Name">Door/Window Sensor</MetaDataItem> <ChangeLog> <Entry author="Justin Hammond - [email protected]" date="24 May 2019" revision="2">Initial Metadata Import from Z-Wave Alliance Database - https://products.z-wavealliance.org/products/1892/xml</Entry> <Entry author="Justin Hammond - [email protected]" date="24 May 2019" revision="3">Updated Metadata Import from Z-Wave Alliance Database - https://products.z-wavealliance.org/products/1896/xml</Entry> <Entry author="Justin Hammond - [email protected]" date="02 Jun 2019" revision="4">Updated Metadata Import from Z-Wave Alliance Database - https://products.z-wavealliance.org/products/2775/xml</Entry> <Entry author="Justin Hammond - [email protected]" date="02 Jun 2019" revision="5">Updated Metadata Import from Z-Wave Alliance Database - https://products.z-wavealliance.org/products/2844/xml</Entry> </ChangeLog> <MetaDataItem id="0008" name="ZWProductPage" type="0200">https://products.z-wavealliance.org/products/2844/</MetaDataItem> <MetaDataItem id="0008" name="Identifier" type="0200">HKZW-DWS01</MetaDataItem> <MetaDataItem id="0008" name="FrequencyName" type="0200">CEPT (Europe)</MetaDataItem> </MetaData> <!-- Hank HKZW-DWS01 Door/Window Sensor http://products.z-wavealliance.org/products/1896 http://products.z-wavealliance.org/ProductManual/File?folder=&filename=Manuals/1896/HKZW-DWS01_Product%20Manual%20.pdf --> <!-- Configuration --> <CommandClass id="112"> <Value genre="config" index="14" instance="1" label="BASIC SET command" max="1" min="0" size="1" type="list" value="0"> <Help>Enable/Disable BASIC SET command</Help> <Item label="Disabled" value="0"/> <Item label="Enabled" value="1"/> </Value> <Value genre="config" index="15" instance="1" label="Value of the BASIC SET" max="1" min="0" size="1" type="list" value="0"> <Help> Send BASIC SET VALUE = 255 to nodes associated with group 2 when door/window is opened. Send BASIC SET VALUE = 0 to nodes associated with group 2 when door/window is closed.</Help> <Item label="255" value="0"/> <Item label="0" value="1"/> </Value> <Value genre="config" index="32" instance="1" label="Level of low battery" max="50" min="10" size="1" type="byte" units="%" value="10"> <Help>The value here defines the low battery</Help> </Value> </CommandClass> <!-- Association Groups --> <CommandClass id="133"> <Associations num_groups="2"> <Group index="1" label="Lifeline" max_associations="5"/> <Group index="2" label="BASIC SET command" max_associations="5"/> </Associations> </CommandClass> </Product>
{ "pile_set_name": "Github" }
package Paws::EC2::DeleteTransitGatewayVpcAttachmentResult; use Moose; has TransitGatewayVpcAttachment => (is => 'ro', isa => 'Paws::EC2::TransitGatewayVpcAttachment', request_name => 'transitGatewayVpcAttachment', traits => ['NameInRequest',]); has _request_id => (is => 'ro', isa => 'Str'); 1; ### main pod documentation begin ### =head1 NAME Paws::EC2::DeleteTransitGatewayVpcAttachmentResult =head1 ATTRIBUTES =head2 TransitGatewayVpcAttachment => L<Paws::EC2::TransitGatewayVpcAttachment> Information about the deleted VPC attachment. =head2 _request_id => Str =cut
{ "pile_set_name": "Github" }
{ "instance_id": "mymachine", "service_conf_dir": "example/nerve_services", "max_repeated_report_failures": 10, "statsd": { "host": "localhost", "port": 8125 }, "services": { "your_http_service": { "host": "1.2.3.4", "port": 3000, "reporter_type": "zookeeper", "zk_hosts": ["localhost:2181"], "zk_path": "/nerve/services/your_http_service/services", "check_interval": 2, "checks": [ { "type": "http", "uri": "/health", "timeout": 0.2, "rise": 3, "fall": 2 } ] }, "your_tcp_service": { "host": "1.2.3.4", "port": 6379, "reporter_type": "zookeeper", "zk_hosts": ["localhost:2181"], "zk_path": "/nerve/services/your_tcp_service/services", "check_interval": 2, "checks": [ { "type": "tcp", "timeout": 0.2, "rise": 3, "fall": 2 } ] }, "rabbitmq_service": { "host": "1.2.3.4", "port": 5672, "reporter_type": "zookeeper", "zk_hosts": ["localhost:2181"], "zk_path": "/nerve/services/your_rabbitmq_service/services", "check_interval": 2, "checks": [ { "type": "rabbitmq", "username": "guest", "password": "guest" } ] } } }
{ "pile_set_name": "Github" }
# config file generated automatically by calling # ./local/nist_eval/create_new_language_configs.FLP.sh --language "203-lao" --corpus "/export/babel/data" --indus "/export/babel/data/scoring/IndusDB" # include common settings for fullLP systems. . conf/common.fullLP || exit 1; #speech corpora files location train_data_dir=/export/babel/data/203-lao/release-current/conversational/training train_data_list=./conf/lists/203-lao/train.FullLP.list train_nj=32 #Radical reduced DEV corpora files location dev2h_data_dir=/export/babel/data/203-lao/release-current/conversational/dev dev2h_data_list=./conf/lists/203-lao/dev.list dev2h_rttm_file=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.mitllfa3.rttm dev2h_ecf_file=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.scoring.ecf.xml dev2h_stm_file=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.stm dev2h_kwlists=( [kwlist]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.annot.kwlist.xml [kwlist2]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.annot.kwlist2.xml [kwlist3]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.annot.kwlist3.xml [kwlist4]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.annot.kwlist4.xml ) # dev2h_kwlists dev2h_nj=16 dev2h_subset_ecf=true #Official DEV corpora files location dev10h_data_dir=/export/babel/data/203-lao/release-current/conversational/dev dev10h_data_list=./conf/lists/203-lao/dev.list dev10h_rttm_file=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.mitllfa3.rttm dev10h_ecf_file=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.scoring.ecf.xml dev10h_stm_file=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.stm dev10h_kwlists=( [kwlist]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.annot.kwlist.xml [kwlist2]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.annot.kwlist2.xml [kwlist3]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.annot.kwlist3.xml [kwlist4]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.annot.kwlist4.xml ) # dev10h_kwlists dev10h_nj=32 #Official EVAL period evaluation data files eval_data_dir=/export/babel/data/203-lao/release-current/conversational/eval eval_data_list=./conf/lists/203-lao/eval.list eval_ecf_file=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-eval.ecf.xml eval_kwlists=( [kwlist]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.annot.kwlist.xml [kwlist2]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.annot.kwlist2.xml [kwlist3]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.annot.kwlist3.xml [kwlist4]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.annot.kwlist4.xml ) # eval_kwlists eval_nj=32 #Official post-EVAL period data files evalpart1_data_dir=/export/babel/data/203-lao/release-current/conversational/eval evalpart1_data_list=./conf/lists/203-lao/evalpart1.list evalpart1_rttm_file=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-evalpart1/IARPA-babel203b-v3.1a_conv-evalpart1.mitllfa3.rttm evalpart1_ecf_file=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-evalpart1/IARPA-babel203b-v3.1a_conv-evalpart1.scoring.ecf.xml evalpart1_stm_file=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-evalpart1/IARPA-babel203b-v3.1a_conv-evalpart1.stm evalpart1_kwlists=( [kwlist]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-evalpart1/IARPA-babel203b-v3.1a_conv-evalpart1.annot.kwlist.xml [kwlist2]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-evalpart1/IARPA-babel203b-v3.1a_conv-evalpart1.annot.kwlist2.xml [kwlist3]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-evalpart1/IARPA-babel203b-v3.1a_conv-evalpart1.annot.kwlist3.xml [kwlist4]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-evalpart1/IARPA-babel203b-v3.1a_conv-evalpart1.annot.kwlist4.xml ) # evalpart1_kwlists evalpart1_nj=32 #Shadow data files shadow_data_dir=( /export/babel/data/203-lao/release-current/conversational/dev /export/babel/data/203-lao/release-current/conversational/eval ) # shadow_data_dir shadow_data_list=( ./conf/lists/203-lao/dev.list ./conf/lists/203-lao/eval.list ) # shadow_data_dir shadow_ecf_file=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.scoring.ecf.xml shadow_rttm_file=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.mitllfa3.rttm shadow_stm_file=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.stm shadow_kwlists=( [kwlist]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.annot.kwlist.xml [kwlist2]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.annot.kwlist2.xml [kwlist3]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.annot.kwlist3.xml [kwlist4]=/export/babel/data/scoring/IndusDB/IARPA-babel203b-v3.1a_conv-dev/IARPA-babel203b-v3.1a_conv-dev.annot.kwlist4.xml ) # shadow_kwlists shadow_nj=32 #Unsupervised training set file (./conf/lists/203-lao/untranscribed-training.list) not found. lexicon_file=/export/babel/data/203-lao/release-current/conversational/reference_materials/lexicon.txt lexiconFlags="--romanized --oov <unk>"
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>CodeRay output</title> <style type="text/css"> .CodeRay .line-numbers a { text-decoration: inherit; color: inherit; } body { background-color: white; padding: 0; margin: 0; } .CodeRay { background-color: hsl(0,0%,95%); border: 1px solid silver; color: black; } .CodeRay pre { margin: 0px; } span.CodeRay { white-space: pre; border: 0px; padding: 2px; } table.CodeRay { border-collapse: collapse; width: 100%; padding: 2px; } table.CodeRay td { padding: 2px 4px; vertical-align: top; } .CodeRay .line-numbers { background-color: hsl(180,65%,90%); color: gray; text-align: right; -webkit-user-select: none; -moz-user-select: none; user-select: none; } .CodeRay .line-numbers a { background-color: hsl(180,65%,90%) !important; color: gray !important; text-decoration: none !important; } .CodeRay .line-numbers pre { word-break: normal; } .CodeRay .line-numbers a:target { color: blue !important; } .CodeRay .line-numbers .highlighted { color: red !important; } .CodeRay .line-numbers .highlighted a { color: red !important; } .CodeRay span.line-numbers { padding: 0px 4px; } .CodeRay .line { display: block; float: left; width: 100%; } .CodeRay .code { width: 100%; } .CodeRay .debug { color: white !important; background: blue !important; } .CodeRay .annotation { color:#007 } .CodeRay .attribute-name { color:#b48 } .CodeRay .attribute-value { color:#700 } .CodeRay .binary { color:#549 } .CodeRay .binary .char { color:#325 } .CodeRay .binary .delimiter { color:#325 } .CodeRay .char { color:#D20 } .CodeRay .char .content { color:#D20 } .CodeRay .char .delimiter { color:#710 } .CodeRay .class { color:#B06; font-weight:bold } .CodeRay .class-variable { color:#369 } .CodeRay .color { color:#0A0 } .CodeRay .comment { color:#777 } .CodeRay .comment .char { color:#444 } .CodeRay .comment .delimiter { color:#444 } .CodeRay .constant { color:#036; font-weight:bold } .CodeRay .decorator { color:#B0B } .CodeRay .definition { color:#099; font-weight:bold } .CodeRay .delimiter { color:black } .CodeRay .directive { color:#088; font-weight:bold } .CodeRay .docstring { color:#D42; } .CodeRay .doctype { color:#34b } .CodeRay .done { text-decoration: line-through; color: gray } .CodeRay .entity { color:#800; font-weight:bold } .CodeRay .error { color:#F00; background-color:#FAA } .CodeRay .escape { color:#666 } .CodeRay .exception { color:#C00; font-weight:bold } .CodeRay .float { color:#60E } .CodeRay .function { color:#06B; font-weight:bold } .CodeRay .function .delimiter { color:#024; font-weight:bold } .CodeRay .global-variable { color:#d70 } .CodeRay .hex { color:#02b } .CodeRay .id { color:#33D; font-weight:bold } .CodeRay .include { color:#B44; font-weight:bold } .CodeRay .inline { background-color: hsla(0,0%,0%,0.07); color: black } .CodeRay .inline-delimiter { font-weight: bold; color: #666 } .CodeRay .instance-variable { color:#33B } .CodeRay .integer { color:#00D } .CodeRay .imaginary { color:#f00 } .CodeRay .important { color:#D00 } .CodeRay .key { color: #606 } .CodeRay .key .char { color: #60f } .CodeRay .key .delimiter { color: #404 } .CodeRay .keyword { color:#080; font-weight:bold } .CodeRay .label { color:#970; font-weight:bold } .CodeRay .local-variable { color:#950 } .CodeRay .map .content { color:#808 } .CodeRay .map .delimiter { color:#40A} .CodeRay .map { background-color:hsla(200,100%,50%,0.06); } .CodeRay .namespace { color:#707; font-weight:bold } .CodeRay .octal { color:#40E } .CodeRay .operator { } .CodeRay .predefined { color:#369; font-weight:bold } .CodeRay .predefined-constant { color:#069 } .CodeRay .predefined-type { color:#0a8; font-weight:bold } .CodeRay .preprocessor { color:#579 } .CodeRay .pseudo-class { color:#00C; font-weight:bold } .CodeRay .regexp { background-color:hsla(300,100%,50%,0.06); } .CodeRay .regexp .content { color:#808 } .CodeRay .regexp .delimiter { color:#404 } .CodeRay .regexp .modifier { color:#C2C } .CodeRay .reserved { color:#080; font-weight:bold } .CodeRay .shell { background-color:hsla(120,100%,50%,0.06); } .CodeRay .shell .content { color:#2B2 } .CodeRay .shell .delimiter { color:#161 } .CodeRay .string { background-color:hsla(0,100%,50%,0.05); } .CodeRay .string .char { color: #b0b } .CodeRay .string .content { color: #D20 } .CodeRay .string .delimiter { color: #710 } .CodeRay .string .modifier { color: #E40 } .CodeRay .symbol { color:#A60 } .CodeRay .symbol .content { color:#A60 } .CodeRay .symbol .delimiter { color:#740 } .CodeRay .tag { color:#070; font-weight:bold } .CodeRay .type { color:#339; font-weight:bold } .CodeRay .value { color: #088 } .CodeRay .variable { color:#037 } .CodeRay .insert { background: hsla(120,100%,50%,0.12) } .CodeRay .delete { background: hsla(0,100%,50%,0.12) } .CodeRay .change { color: #bbf; background: #007 } .CodeRay .head { color: #f8f; background: #505 } .CodeRay .head .filename { color: white; } .CodeRay .delete .eyecatcher { background-color: hsla(0,100%,50%,0.2); border: 1px solid hsla(0,100%,45%,0.5); margin: -1px; border-bottom: none; border-top-left-radius: 5px; border-top-right-radius: 5px; } .CodeRay .insert .eyecatcher { background-color: hsla(120,100%,50%,0.2); border: 1px solid hsla(120,100%,25%,0.5); margin: -1px; border-top: none; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; } .CodeRay .insert .insert { color: #0c0; background:transparent; font-weight:bold } .CodeRay .delete .delete { color: #c00; background:transparent; font-weight:bold } .CodeRay .change .change { color: #88f } .CodeRay .head .head { color: #f4f } .CodeRay { border: none; } </style> </head> <body> <table class="CodeRay"><tr> <td class="line-numbers"><pre><a href="#n1" name="n1">1</a> <a href="#n2" name="n2">2</a> <a href="#n3" name="n3">3</a> <a href="#n4" name="n4">4</a> <a href="#n5" name="n5">5</a> <a href="#n6" name="n6">6</a> <a href="#n7" name="n7">7</a> <a href="#n8" name="n8">8</a> <a href="#n9" name="n9">9</a> <strong><a href="#n10" name="n10">10</a></strong> <a href="#n11" name="n11">11</a> <a href="#n12" name="n12">12</a> <a href="#n13" name="n13">13</a> <a href="#n14" name="n14">14</a> <a href="#n15" name="n15">15</a> </pre></td> <td class="code"><pre><span class="comment">/* DreemGL is a collaboration between Teeming Society &amp; Samsung Electronics, sponsored by Samsung and others. Copyright 2015-2016 Teeming Society. Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an &quot;AS IS&quot; BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.*/</span> define.<span class="reserved">class</span>(<span class="string"><span class="delimiter">'</span><span class="content">../webgl/texturewebgl</span><span class="delimiter">'</span></span>, <span class="keyword">function</span>(require){ <span class="comment">//internal</span> <span class="comment">// copy base class static methods</span> <span class="keyword">var</span> parent = Object.getPrototypeOf(<span class="local-variable">this</span>) <span class="keyword">for</span>(<span class="keyword">var</span> key <span class="keyword">in</span> parent.constructor) <span class="local-variable">this</span>.constructor[key] = parent.constructor[key] }) </pre></td> </tr></table> </body> </html>
{ "pile_set_name": "Github" }
/////////////////////////////////////////////////////////////////////////////////// /// OpenGL Mathematics (glm.g-truc.net) /// /// Copyright (c) 2005 - 2012 G-Truc Creation (www.g-truc.net) /// 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. /// /// @ref core /// @file glm/core/intrinsic_vector_relational.inl /// @date 2009-06-09 / 2011-06-15 /// @author Christophe Riccio /////////////////////////////////////////////////////////////////////////////////// // //// lessThan //template <typename valType> //GLM_FUNC_QUALIFIER typename detail::tvec2<valType>::bool_type lessThan //( // detail::tvec2<valType> const & x, // detail::tvec2<valType> const & y //) //{ // GLM_STATIC_ASSERT( // detail::type<valType>::is_float || // detail::type<valType>::is_int || // detail::type<valType>::is_uint); // // return typename detail::tvec2<bool>::bool_type(x.x < y.x, x.y < y.y); //} // //template <typename valType> //GLM_FUNC_QUALIFIER typename detail::tvec3<valType>::bool_type lessThan //( // detail::tvec3<valType> const & x, // detail::tvec3<valType> const & y //) //{ // GLM_STATIC_ASSERT( // detail::type<valType>::is_float || // detail::type<valType>::is_int || // detail::type<valType>::is_uint); // // return typename detail::tvec3<bool>::bool_type(x.x < y.x, x.y < y.y, x.z < y.z); //} // //template <typename valType> //GLM_FUNC_QUALIFIER typename detail::tvec4<valType>::bool_type lessThan //( // detail::tvec4<valType> const & x, // detail::tvec4<valType> const & y //) //{ // GLM_STATIC_ASSERT( // detail::type<valType>::is_float || // detail::type<valType>::is_int || // detail::type<valType>::is_uint); // // return typename detail::tvec4<bool>::bool_type(x.x < y.x, x.y < y.y, x.z < y.z, x.w < y.w); //} // //// lessThanEqual //template <typename valType> //GLM_FUNC_QUALIFIER typename detail::tvec2<valType>::bool_type lessThanEqual //( // detail::tvec2<valType> const & x, // detail::tvec2<valType> const & y //) //{ // GLM_STATIC_ASSERT( // detail::type<valType>::is_float || // detail::type<valType>::is_int || // detail::type<valType>::is_uint); // // return typename detail::tvec2<bool>::bool_type(x.x <= y.x, x.y <= y.y); //} // //template <typename valType> //GLM_FUNC_QUALIFIER typename detail::tvec3<valType>::bool_type lessThanEqual //( // detail::tvec3<valType> const & x, // detail::tvec3<valType> const & y //) //{ // GLM_STATIC_ASSERT( // detail::type<valType>::is_float || // detail::type<valType>::is_int || // detail::type<valType>::is_uint); // // return typename detail::tvec3<bool>::bool_type(x.x <= y.x, x.y <= y.y, x.z <= y.z); //} // //template <typename valType> //GLM_FUNC_QUALIFIER typename detail::tvec4<valType>::bool_type lessThanEqual //( // detail::tvec4<valType> const & x, // detail::tvec4<valType> const & y //) //{ // GLM_STATIC_ASSERT( // detail::type<valType>::is_float || // detail::type<valType>::is_int || // detail::type<valType>::is_uint); // // return typename detail::tvec4<bool>::bool_type(x.x <= y.x, x.y <= y.y, x.z <= y.z, x.w <= y.w); //} // //// greaterThan //template <typename valType> //GLM_FUNC_QUALIFIER typename detail::tvec2<valType>::bool_type greaterThan //( // detail::tvec2<valType> const & x, // detail::tvec2<valType> const & y //) //{ // GLM_STATIC_ASSERT( // detail::type<valType>::is_float || // detail::type<valType>::is_int || // detail::type<valType>::is_uint); // // return typename detail::tvec2<bool>::bool_type(x.x > y.x, x.y > y.y); //} // //template <typename valType> //GLM_FUNC_QUALIFIER typename detail::tvec3<valType>::bool_type greaterThan //( // detail::tvec3<valType> const & x, // detail::tvec3<valType> const & y //) //{ // GLM_STATIC_ASSERT( // detail::type<valType>::is_float || // detail::type<valType>::is_int || // detail::type<valType>::is_uint); // // return typename detail::tvec3<bool>::bool_type(x.x > y.x, x.y > y.y, x.z > y.z); //} // //template <typename valType> //GLM_FUNC_QUALIFIER typename detail::tvec4<valType>::bool_type greaterThan //( // detail::tvec4<valType> const & x, // detail::tvec4<valType> const & y //) //{ // GLM_STATIC_ASSERT( // detail::type<valType>::is_float || // detail::type<valType>::is_int || // detail::type<valType>::is_uint); // // return typename detail::tvec4<bool>::bool_type(x.x > y.x, x.y > y.y, x.z > y.z, x.w > y.w); //} // //// greaterThanEqual //template <typename valType> //GLM_FUNC_QUALIFIER typename detail::tvec2<valType>::bool_type greaterThanEqual //( // detail::tvec2<valType> const & x, // detail::tvec2<valType> const & y //) //{ // GLM_STATIC_ASSERT( // detail::type<valType>::is_float || // detail::type<valType>::is_int || // detail::type<valType>::is_uint); // // return typename detail::tvec2<bool>::bool_type(x.x >= y.x, x.y >= y.y); //} // //template <typename valType> //GLM_FUNC_QUALIFIER typename detail::tvec3<valType>::bool_type greaterThanEqual //( // detail::tvec3<valType> const & x, // detail::tvec3<valType> const & y //) //{ // GLM_STATIC_ASSERT( // detail::type<valType>::is_float || // detail::type<valType>::is_int || // detail::type<valType>::is_uint); // // return typename detail::tvec3<bool>::bool_type(x.x >= y.x, x.y >= y.y, x.z >= y.z); //} // //template <typename valType> //GLM_FUNC_QUALIFIER typename detail::tvec4<valType>::bool_type greaterThanEqual //( // detail::tvec4<valType> const & x, // detail::tvec4<valType> const & y //) //{ // GLM_STATIC_ASSERT( // detail::type<valType>::is_float || // detail::type<valType>::is_int || // detail::type<valType>::is_uint); // // return typename detail::tvec4<bool>::bool_type(x.x >= y.x, x.y >= y.y, x.z >= y.z, x.w >= y.w); //} // //// equal //template <typename valType> //GLM_FUNC_QUALIFIER typename detail::tvec2<valType>::bool_type equal //( // detail::tvec2<valType> const & x, // detail::tvec2<valType> const & y //) //{ // GLM_STATIC_ASSERT( // detail::type<valType>::is_float || // detail::type<valType>::is_int || // detail::type<valType>::is_uint || // detail::type<valType>::is_bool); // // return typename detail::tvec2<valType>::bool_type(x.x == y.x, x.y == y.y); //} // //template <typename valType> //GLM_FUNC_QUALIFIER typename detail::tvec3<valType>::bool_type equal //( // detail::tvec3<valType> const & x, // detail::tvec3<valType> const & y //) //{ // GLM_STATIC_ASSERT( // detail::type<valType>::is_float || // detail::type<valType>::is_int || // detail::type<valType>::is_uint || // detail::type<valType>::is_bool); // // return typename detail::tvec3<valType>::bool_type(x.x == y.x, x.y == y.y, x.z == y.z); //} // //template <typename valType> //GLM_FUNC_QUALIFIER typename detail::tvec4<valType>::bool_type equal //( // detail::tvec4<valType> const & x, // detail::tvec4<valType> const & y //) //{ // GLM_STATIC_ASSERT( // detail::type<valType>::is_float || // detail::type<valType>::is_int || // detail::type<valType>::is_uint || // detail::type<valType>::is_bool); // // return typename detail::tvec4<valType>::bool_type(x.x == y.x, x.y == y.y, x.z == y.z, x.w == y.w); //} // //// notEqual //template <typename valType> //GLM_FUNC_QUALIFIER typename detail::tvec2<valType>::bool_type notEqual //( // detail::tvec2<valType> const & x, // detail::tvec2<valType> const & y //) //{ // GLM_STATIC_ASSERT( // detail::type<valType>::is_float || // detail::type<valType>::is_int || // detail::type<valType>::is_uint || // detail::type<valType>::is_bool); // // return typename detail::tvec2<valType>::bool_type(x.x != y.x, x.y != y.y); //} // //template <typename valType> //GLM_FUNC_QUALIFIER typename detail::tvec3<valType>::bool_type notEqual //( // detail::tvec3<valType> const & x, // detail::tvec3<valType> const & y //) //{ // GLM_STATIC_ASSERT( // detail::type<valType>::is_float || // detail::type<valType>::is_int || // detail::type<valType>::is_uint || // detail::type<valType>::is_bool); // // return typename detail::tvec3<valType>::bool_type(x.x != y.x, x.y != y.y, x.z != y.z); //} // //template <typename valType> //GLM_FUNC_QUALIFIER typename detail::tvec4<valType>::bool_type notEqual //( // detail::tvec4<valType> const & x, // detail::tvec4<valType> const & y //) //{ // GLM_STATIC_ASSERT( // detail::type<valType>::is_float || // detail::type<valType>::is_int || // detail::type<valType>::is_uint || // detail::type<valType>::is_bool); // // return typename detail::tvec4<valType>::bool_type(x.x != y.x, x.y != y.y, x.z != y.z, x.w != y.w); //} // //// any //GLM_FUNC_QUALIFIER bool any(detail::tvec2<bool> const & x) //{ // return x.x || x.y; //} // //GLM_FUNC_QUALIFIER bool any(detail::tvec3<bool> const & x) //{ // return x.x || x.y || x.z; //} // //GLM_FUNC_QUALIFIER bool any(detail::tvec4<bool> const & x) //{ // return x.x || x.y || x.z || x.w; //} // //// all //GLM_FUNC_QUALIFIER bool all(const detail::tvec2<bool>& x) //{ // return x.x && x.y; //} // //GLM_FUNC_QUALIFIER bool all(const detail::tvec3<bool>& x) //{ // return x.x && x.y && x.z; //} // //GLM_FUNC_QUALIFIER bool all(const detail::tvec4<bool>& x) //{ // return x.x && x.y && x.z && x.w; //} // //// not //GLM_FUNC_QUALIFIER detail::tvec2<bool>::bool_type not_ //( // detail::tvec2<bool> const & v //) //{ // return detail::tvec2<bool>::bool_type(!v.x, !v.y); //} // //GLM_FUNC_QUALIFIER detail::tvec3<bool>::bool_type not_ //( // detail::tvec3<bool> const & v //) //{ // return detail::tvec3<bool>::bool_type(!v.x, !v.y, !v.z); //} // //GLM_FUNC_QUALIFIER detail::tvec4<bool>::bool_type not_ //( // detail::tvec4<bool> const & v //) //{ // return detail::tvec4<bool>::bool_type(!v.x, !v.y, !v.z, !v.w); //}
{ "pile_set_name": "Github" }
// 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. #ifndef NET_HTTP_BIDIRECTIONAL_STREAM_IMPL_H_ #define NET_HTTP_BIDIRECTIONAL_STREAM_IMPL_H_ #include <stdint.h> #include <memory> #include <vector> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "net/base/load_timing_info.h" #include "net/base/net_export.h" #include "net/socket/next_proto.h" namespace base { class Timer; } // namespace base namespace net { class IOBuffer; class NetLogWithSource; class SpdyHeaderBlock; struct BidirectionalStreamRequestInfo; // Exposes an interface to do HTTP/2 bidirectional streaming. // Note that only one ReadData or SendData should be in flight until the // operation completes synchronously or asynchronously. // BidirectionalStreamImpl once created by HttpStreamFactoryImpl should be owned // by BidirectionalStream. class NET_EXPORT_PRIVATE BidirectionalStreamImpl { public: // Delegate to handle BidirectionalStreamImpl events. class NET_EXPORT_PRIVATE Delegate { public: Delegate(); // Called when the stream is ready for reading and writing. // The delegate may call BidirectionalStreamImpl::ReadData to start reading, // call BidirectionalStreamImpl::SendData to send data, // or call BidirectionalStreamImpl::Cancel to cancel the stream. // The delegate should not call BidirectionalStreamImpl::Cancel // during this callback. // |request_headers_sent| if true, request headers have been sent. If false, // SendRequestHeaders() needs to be explicitly called. virtual void OnStreamReady(bool request_headers_sent) = 0; // Called when response headers are received. // This is called at most once for the lifetime of a stream. // The delegate may call BidirectionalStreamImpl::ReadData to start // reading, call BidirectionalStreamImpl::SendData to send data, // or call BidirectionalStreamImpl::Cancel to cancel the stream. virtual void OnHeadersReceived(const SpdyHeaderBlock& response_headers) = 0; // Called when read is completed asynchronously. |bytes_read| specifies how // much data is available. // The delegate may call BidirectionalStreamImpl::ReadData to continue // reading, call BidirectionalStreamImpl::SendData to send data, // or call BidirectionalStreamImpl::Cancel to cancel the stream. virtual void OnDataRead(int bytes_read) = 0; // Called when the entire buffer passed through SendData is sent. // The delegate may call BidirectionalStreamImpl::ReadData to continue // reading, or call BidirectionalStreamImpl::SendData to send data. // The delegate should not call BidirectionalStreamImpl::Cancel // during this callback. virtual void OnDataSent() = 0; // Called when trailers are received. This is called as soon as trailers // are received, which can happen before a read completes. // The delegate is able to continue reading if there is no pending read and // EOF has not been received, or to send data if there is no pending send. virtual void OnTrailersReceived(const SpdyHeaderBlock& trailers) = 0; // Called when an error occurred. Do not call into the stream after this // point. No other delegate functions will be called after this. virtual void OnFailed(int status) = 0; protected: virtual ~Delegate(); private: DISALLOW_COPY_AND_ASSIGN(Delegate); }; BidirectionalStreamImpl(); // |this| should not be destroyed during Delegate::OnHeadersSent or // Delegate::OnDataSent. virtual ~BidirectionalStreamImpl(); // Starts the BidirectionalStreamImpl and sends request headers. // |send_request_headers_automatically| if true, request headers will be sent // automatically when stream is negotiated. If false, request headers will be // sent only when SendRequestHeaders() is invoked or with next // SendData/SendvData. virtual void Start(const BidirectionalStreamRequestInfo* request_info, const NetLogWithSource& net_log, bool send_request_headers_automatically, BidirectionalStreamImpl::Delegate* delegate, std::unique_ptr<base::Timer> timer) = 0; // Sends request headers to server. // When |send_request_headers_automatically_| is // false and OnStreamReady() is invoked with request_headers_sent = false, // headers will be combined with next SendData/SendvData unless this // method is called first, in which case headers will be sent separately // without delay. // (This method cannot be called when |send_request_headers_automatically_| is // true nor when OnStreamReady() is invoked with request_headers_sent = true, // since headers have been sent by the stream when stream is negotiated // successfully.) virtual void SendRequestHeaders() = 0; // Reads at most |buf_len| bytes into |buf|. Returns the number of bytes read, // ERR_IO_PENDING if the read is to be completed asynchronously, or an error // code if any error occurred. If returns 0, there is no more data to read. // This should not be called before Delegate::OnHeadersReceived is invoked, // and should not be called again unless it returns with number greater than // 0 or until Delegate::OnDataRead is invoked. virtual int ReadData(IOBuffer* buf, int buf_len) = 0; // Sends data. This should not be called be called before // Delegate::OnHeadersSent is invoked, and should not be called again until // Delegate::OnDataSent is invoked. If |end_stream| is true, the DATA frame // will have an END_STREAM flag. virtual void SendData(const scoped_refptr<IOBuffer>& data, int length, bool end_stream) = 0; virtual void SendvData(const std::vector<scoped_refptr<IOBuffer>>& buffers, const std::vector<int>& lengths, bool end_stream) = 0; // Returns the protocol used by this stream. If stream has not been // established, return kProtoUnknown. virtual NextProto GetProtocol() const = 0; // Total number of bytes received over the network of SPDY data, headers, and // push_promise frames associated with this stream, including the size of // frame headers, after SSL decryption and not including proxy overhead. virtual int64_t GetTotalReceivedBytes() const = 0; // Total number of bytes sent over the network of SPDY frames associated with // this stream, including the size of frame headers, before SSL encryption and // not including proxy overhead. Note that some SPDY frames such as pings are // not associated with any stream, and are not included in this value. virtual int64_t GetTotalSentBytes() const = 0; // Populates the connection establishment part of |load_timing_info|, and // socket reuse info. Return true if LoadTimingInfo is obtained successfully // and false otherwise. virtual bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const = 0; private: DISALLOW_COPY_AND_ASSIGN(BidirectionalStreamImpl); }; } // namespace net #endif // NET_HTTP_BIDIRECTIONAL_STREAM_IMPL_H_
{ "pile_set_name": "Github" }
$(function () { var hlCode = document.querySelectorAll('pre code.cs'), i, l, hlLength = hlCode.length, mapperRegex = /\bMapper\b/g, typeRegex = /(new<\/span>\W+|class<\/span> <span class="hljs-title">|public<\/span>\W+|: <span class="hljs-title">|&lt;)([A-Z][^& \(\[\]]+)( |{|\(|\[\]&gt;|&gt;)/g, genericTypeRegex = /(I{0,1}Dictionary|IEnumerable|IReadOnlyCollection|I{0,1}Collection|I{0,1}List)&lt;/g, observer = new MutationObserver(function (mutations) { for (i = 0, l = mutations.length; i < l; ++i) { var mutation = mutations[i]; if (mutation.attributeName === 'class') { var innerHTML = mutation.target.innerHTML .replace(mapperRegex, '<span class="hljs-type">Mapper</span>') .replace(typeRegex, '$1<span class="hljs-type">$2</span>$3') .replace(genericTypeRegex, '<span class="hljs-type">$1</span>&lt;'); mutation.target.innerHTML = innerHTML; } } }), config = { attributes: true }; for (i = 0; i < hlLength; ++i) { observer.observe(hlCode[i], config); } });
{ "pile_set_name": "Github" }
/// Credit BinaryX /// Sourced from - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/page-2#post-1945602 /// Updated by ddreaper - removed dependency on a custom ScrollRect script. Now implements drag interfaces and standard Scroll Rect. using System; using UnityEngine.EventSystems; namespace UnityEngine.UI.Extensions { [RequireComponent(typeof(ScrollRect))] [AddComponentMenu("Layout/Extensions/Horizontal Scroll Snap")] public class HorizontalScrollSnap : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler { private Transform _screensContainer; private int _screens = 1; private bool _fastSwipeTimer = false; private int _fastSwipeCounter = 0; private int _fastSwipeTarget = 30; private System.Collections.Generic.List<Vector3> _positions; private ScrollRect _scroll_rect; private Vector3 _lerp_target; private bool _lerp; [Tooltip("The gameobject that contains toggles which suggest pagination. (optional)")] public GameObject Pagination; [Tooltip("Button to go to the next page. (optional)")] public GameObject NextButton; [Tooltip("Button to go to the previous page. (optional)")] public GameObject PrevButton; [Tooltip("Transition speed between pages. (optional)")] public float transitionSpeed = 7.5f; public Boolean UseFastSwipe = true; public int FastSwipeThreshold = 100; private bool _startDrag = true; private Vector3 _startPosition = new Vector3(); [Tooltip("The currently active page")] [SerializeField] private int _currentScreen; [Tooltip("The screen / page to start the control on")] public int StartingScreen = 1; [Tooltip("The distance between two pages, by default 3 times the height of the control")] public int PageStep = 0; private GameObject removedGo = null; public int CurrentPage { get { return _currentScreen; } } private Action onPageChanged; /// <summary> /// 滑动结束时,页面变化的回调 /// </summary> /// <param name="callBack"></param> public void RegisterOnScrollEnd(Action callBack) { this.onPageChanged = callBack; } // Use this for initialization void Awake() { _scroll_rect = gameObject.GetComponent<ScrollRect>(); if (_scroll_rect.horizontalScrollbar || _scroll_rect.verticalScrollbar) { Debug.LogWarning("Warning, using scrollbors with the Scroll Snap controls is not advised as it causes unpredictable results"); } _screensContainer = _scroll_rect.content; if (PageStep == 0) { PageStep = (int)_scroll_rect.GetComponent<RectTransform>().rect.width * 1; } DistributePages(); _lerp = false; _currentScreen = StartingScreen; _scroll_rect.horizontalNormalizedPosition = (float)(_currentScreen - 1) / (float)(_screens - 1); ChangeBulletsInfo(_currentScreen); if (NextButton) NextButton.GetComponent<Button>().onClick.AddListener(() => { NextScreen(); }); if (PrevButton) PrevButton.GetComponent<Button>().onClick.AddListener(() => { PreviousScreen(); }); } void Update() { if (_lerp) { _screensContainer.localPosition = Vector3.Lerp(_screensContainer.localPosition, _lerp_target, transitionSpeed * Time.deltaTime); if (Vector3.Distance(_screensContainer.localPosition, _lerp_target) < 0.005f) { _lerp = false; } //change the info bullets at the bottom of the screen. Just for visual effect if (Vector3.Distance(_screensContainer.localPosition, _lerp_target) < 10f) { ChangeBulletsInfo(CurrentScreen()); } } if (_fastSwipeTimer) { _fastSwipeCounter++; } } private bool fastSwipe = false; //to determine if a fast swipe was performed //Function for switching screens with buttons public void NextScreen() { if (_currentScreen < _screens - 1) { _currentScreen++; _lerp = true; _lerp_target = _positions[_currentScreen]; ChangeBulletsInfo(_currentScreen); } } //Function for switching screens with buttons public void PreviousScreen() { if (_currentScreen > 0) { _currentScreen--; _lerp = true; _lerp_target = _positions[_currentScreen]; ChangeBulletsInfo(_currentScreen); } } //Function for switching to a specific screen public void GoToScreen(int screenIndex) { if (screenIndex < _screens && screenIndex >= 0) { _lerp = true; _lerp_target = _positions[screenIndex]; ChangeBulletsInfo(screenIndex); } } //Because the CurrentScreen function is not so reliable, these are the functions used for swipes private void NextScreenCommand() { if (_currentScreen < _screens - 1) { _lerp = true; _lerp_target = _positions[_currentScreen + 1]; ChangeBulletsInfo(_currentScreen + 1); } } //Because the CurrentScreen function is not so reliable, these are the functions used for swipes private void PrevScreenCommand() { if (_currentScreen > 0) { _lerp = true; _lerp_target = _positions[_currentScreen - 1]; ChangeBulletsInfo(_currentScreen - 1); } } //find the closest registered point to the releasing point private Vector3 FindClosestFrom(Vector3 start, System.Collections.Generic.List<Vector3> positions) { Vector3 closest = Vector3.zero; float distance = Mathf.Infinity; foreach (Vector3 position in _positions) { if (Vector3.Distance(start, position) < distance) { distance = Vector3.Distance(start, position); closest = position; } } return closest; } //returns the current screen that the is seeing public int CurrentScreen() { var pos = FindClosestFrom(_screensContainer.localPosition, _positions); return _currentScreen = GetPageforPosition(pos); } //changes the bullets on the bottom of the page - pagination private void ChangeBulletsInfo(int currentScreen) { if (Pagination) for (int i = 0; i < Pagination.transform.childCount; i++) { Pagination.transform.GetChild(i).GetComponent<Toggle>().isOn = (currentScreen == i) ? true : false; } if (onPageChanged != null ) { onPageChanged(); } } //used for changing between screen resolutions private void DistributePages() { int _offset = 0; int _dimension = 0; Vector2 panelDimensions = gameObject.GetComponent<RectTransform>().sizeDelta; int currentXPosition = 0; int inactiveGmo = 0; for (int i = 0; i < _screensContainer.transform.childCount; i++) { GameObject temp = _screensContainer.transform.GetChild(i).gameObject; if (temp.activeSelf) { RectTransform child = temp.GetComponent<RectTransform>(); currentXPosition = _offset + (i - inactiveGmo) * PageStep; child.sizeDelta = new Vector2(panelDimensions.x, panelDimensions.y); child.anchoredPosition = new Vector2(currentXPosition, 0f); } else { inactiveGmo++; } } _dimension = currentXPosition + _offset * -1; _screensContainer.GetComponent<RectTransform>().offsetMax = new Vector2(_dimension, 0f); _screens = _screensContainer.childCount - inactiveGmo; _positions = new System.Collections.Generic.List<Vector3>(); if (_screens > 0) { for (float i = 0; i < _screens; ++i) { _scroll_rect.horizontalNormalizedPosition = (float)i / (float)(_screens - 1); _positions.Add(_screensContainer.localPosition); } } } int GetPageforPosition(Vector3 pos) { for (int i = 0; i < _positions.Count; i++) { if (_positions[i] == pos) { return i; } } return 0; } void OnValidate() { var childCount = gameObject.GetComponent<ScrollRect>().content.ActivedChildCount(); if (StartingScreen > childCount) { StartingScreen = childCount; } if (StartingScreen < 1) { StartingScreen = 1; } } /// <summary> /// Add a new child to this Scroll Snap and recalculate it's children /// </summary> /// <param name="GO">GameObject to add to the ScrollSnap</param> public void AddChild(GameObject GO) { if (_scroll_rect == null) { return; } _scroll_rect.horizontalNormalizedPosition = 0; GO.transform.SetParent(_screensContainer, false); GO.transform.SetAsLastSibling(); DistributePages(); _scroll_rect.horizontalNormalizedPosition = (float)(_currentScreen) / (float)(_screens - 1); } /// <summary> /// Remove a new child to this Scroll Snap and recalculate it's children /// *Note, this is an index address (0-x) /// </summary> /// <param name="index"></param> /// <param name="ChildRemoved"></param> public GameObject RemoveChild(int index) { removedGo = null; RemoveChild(index, out removedGo); return removedGo; } /// <summary> /// Remove a new child to this Scroll Snap and recalculate it's children /// *Note, this is an index address (0-x) /// </summary> /// <param name="index"></param> /// <param name="ChildRemoved"></param> public void RemoveChild(int index, out GameObject ChildRemoved) { ChildRemoved = null; if (index < 0 || index > _screensContainer.childCount) { return; } _scroll_rect.horizontalNormalizedPosition = 0; var children = _screensContainer.transform; int i = 0; foreach (Transform child in children) { if (i == index) { child.SetParent(null); ChildRemoved = child.gameObject; break; } i++; } DistributePages(); if (_currentScreen > _screens - 1) { _currentScreen = Mathf.Max(0, _screens - 1); } _scroll_rect.horizontalNormalizedPosition = (float)(_currentScreen) / (float)(_screens - 1); } #region Interfaces public void OnBeginDrag(PointerEventData eventData) { _startPosition = _screensContainer.localPosition; _fastSwipeCounter = 0; _fastSwipeTimer = true; _currentScreen = CurrentScreen(); } public void OnEndDrag(PointerEventData eventData) { _startDrag = true; if (_scroll_rect.horizontal) { if (UseFastSwipe) { fastSwipe = false; _fastSwipeTimer = false; if (_fastSwipeCounter <= _fastSwipeTarget) { if (Math.Abs(_startPosition.x - _screensContainer.localPosition.x) > FastSwipeThreshold) { fastSwipe = true; } } if (fastSwipe) { if (_startPosition.x - _screensContainer.localPosition.x > 0) { NextScreenCommand(); } else { PrevScreenCommand(); } } else { _lerp = true; _lerp_target = FindClosestFrom(_screensContainer.localPosition, _positions); _currentScreen = GetPageforPosition(_lerp_target); } } else { _lerp = true; _lerp_target = FindClosestFrom(_screensContainer.localPosition, _positions); _currentScreen = GetPageforPosition(_lerp_target); } } } public void OnDrag(PointerEventData eventData) { _lerp = false; if (_startDrag) { OnBeginDrag(eventData); _startDrag = false; } } #endregion } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2019 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.eclipse.ditto.services.models.signalenrichment; import java.time.Duration; import java.util.Objects; import javax.annotation.concurrent.Immutable; import org.eclipse.ditto.services.utils.config.ConfigWithFallback; import com.typesafe.config.Config; /** * Default implementation of {@link SignalEnrichmentFacadeByRoundTripConfig}. */ @Immutable public final class DefaultSignalEnrichmentFacadeByRoundTripConfig implements SignalEnrichmentFacadeByRoundTripConfig { private final Duration askTimeout; private DefaultSignalEnrichmentFacadeByRoundTripConfig(final ConfigWithFallback configWithFallback) { this.askTimeout = configWithFallback.getDuration( SignalEnrichmentFacadeByRoundTripConfigValue.ASK_TIMEOUT.getConfigPath()); } /** * Returns an instance of {@code DefaultConnectionEnrichmentConfig} based on the settings of the specified Config. * * @param config is supposed to provide the settings of the provider specific config at {@value #CONFIG_PATH}. * @return the instance. * @throws org.eclipse.ditto.services.utils.config.DittoConfigError if {@code config} is invalid. */ public static DefaultSignalEnrichmentFacadeByRoundTripConfig of(final Config config) { return new DefaultSignalEnrichmentFacadeByRoundTripConfig(ConfigWithFallback.newInstance(config, SignalEnrichmentFacadeByRoundTripConfigValue.values())); } @Override public Duration getAskTimeout() { return askTimeout; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final DefaultSignalEnrichmentFacadeByRoundTripConfig that = (DefaultSignalEnrichmentFacadeByRoundTripConfig) o; return Objects.equals(askTimeout, that.askTimeout); } @Override public int hashCode() { return Objects.hash(askTimeout); } @Override public String toString() { return getClass().getSimpleName() + " [" + "askTimeout=" + askTimeout + "]"; } }
{ "pile_set_name": "Github" }
#-- encoding: UTF-8 #-- copyright # OpenProject is an open source project management software. # Copyright (C) 2012-2020 the OpenProject GmbH # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3. # # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: # Copyright (C) 2006-2017 Jean-Philippe Lang # Copyright (C) 2010-2013 the ChiliProject Team # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # See docs/COPYRIGHT.rdoc for more details. #++ def parse_password_rules(str) str.sub(', and ', ', ').split(', ') end Given /^passwords must contain ([0-9]+) of ([a-z, ]+) characters$/ do |minimum_rules, rules| rules = parse_password_rules(rules) Setting.password_active_rules = rules Setting.password_min_adhered_rules = minimum_rules.to_i end Given /^passwords have a minimum length of ([0-9]+) characters$/ do |minimum_length| Setting.password_min_length = minimum_length end Given /^users are not allowed to reuse the last ([0-9]+) passwords$/ do |count| Setting.password_count_former_banned = count end def fill_change_password(old_password, new_password, confirmation = new_password) # use find and set with id to prevent ambiguous match I get with fill_in find('#password').set(old_password) fill_in('new_password', with: new_password) fill_in('new_password_confirmation', with: confirmation) click_link_or_button 'Save' @new_password = new_password end def change_password(old_password, new_password) visit '/my/password' fill_change_password(old_password, new_password) end Given /^I try to change my password from "([^\"]+)" to "([^\"]+)"$/ do |old, new| change_password(old, new) end When /^I try to set my new password to "(.+)"$/ do |password| visit '/my/password' change_password('adminADMIN!', password) end When /^I fill out the change password form$/ do fill_change_password('adminADMIN!', 'adminADMIN!New') end When /^I fill out the change password form with a wrong old password$/ do fill_change_password('wrong', 'adminADMIN!New') end When /^I fill out the change password form with a wrong password confirmation$/ do fill_change_password('adminADMIN!', 'adminADMIN!New', 'wrong') end Then /^the password change should succeed$/ do find('.notice').should have_content('success') end Then /^I should be able to login using the new password$/ do visit('/logout') login(@user.login, @new_password) end Then /^the password and confirmation fields should be empty$/ do find('#user_password').value.should be_empty find('#user_password_confirmation').value.should be_empty end Then /^the password and confirmation fields should be disabled$/ do find('#user_password').should be_disabled find('#user_password_confirmation').should be_disabled end Then /^the force password change field should be checked$/ do find('#user_force_password_change').should be_checked end Then /^the force password change field should be disabled$/ do find('#user_force_password_change').should be_disabled end Given /^I try to log in with user "([^"]*)"$/ do |login| step 'I go to the logout page' login(login, @new_password || 'adminADMIN!') end Given /^I try to log in with user "([^"]*)" and a wrong password$/ do |login| step 'I go to the logout page' login(login, 'Wrong password') end Given /^I try to log in with user "([^"]*)" and the password sent via email$/ do |login| step 'I go to the logout page' login(login, assigned_password_from_last_email) end When /^I activate the ([a-z, ]+) password rules$/ do |rules| rules = parse_password_rules(rules) # ensure checkboxes are loaded, 'all' doesn't wait should have_selector(:xpath, "//input[@id='settings_password_active_rules_' and @value='#{rules.first}']") all(:xpath, "//input[@id='settings_password_active_rules_']").each do |checkbox| checkbox.set(false) end rules.each do |rule| find(:xpath, "//input[@id='settings_password_active_rules_' and @value='#{rule}']").set(true) end end def set_user_attribute(login, attribute, value) user = User.find_by login: login user.send((attribute.to_s + '=').to_sym, value) user.save end Given /^the user "(.+)" is(not |) forced to change his password$/ do |login, disable| set_user_attribute(login, :force_password_change, disable != 'not ') end Given /^I use the first existing token to request a password reset$/ do token = Token::Recovery.first visit account_lost_password_path(token: token.value) end
{ "pile_set_name": "Github" }