text
stringlengths
2
100k
meta
dict
# # Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com) # # Distributed under the Boost Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # lib socket ; # SOLARIS lib nsl ; # SOLARIS lib ws2_32 ; # NT lib mswsock ; # NT lib ipv6 ; # HPUX lib network ; # HAIKU project : requirements <library>/boost/system//boost_system <library>/boost/chrono//boost_chrono <library>/boost/thread//boost_thread <define>BOOST_ALL_NO_LIB=1 <threading>multi <target-os>solaris:<library>socket <target-os>solaris:<library>nsl <target-os>windows:<define>_WIN32_WINNT=0x0501 <target-os>windows,<toolset>gcc:<library>ws2_32 <target-os>windows,<toolset>gcc:<library>mswsock <target-os>windows,<toolset>gcc-cygwin:<define>__USE_W32_SOCKETS <target-os>hpux,<toolset>gcc:<define>_XOPEN_SOURCE_EXTENDED <target-os>hpux:<library>ipv6 <target-os>haiku:<library>network ; exe chat_server : chat_server.cpp ; exe chat_client : chat_client.cpp ; exe posix_chat_client : posix_chat_client.cpp ;
{ "pile_set_name": "Github" }
import Foundation struct ObfuscableFilesFilter { let isObfuscable: (URL) -> Bool } extension ObfuscableFilesFilter { func and(_ other: ObfuscableFilesFilter) -> ObfuscableFilesFilter { return ObfuscableFilesFilter { url in self.isObfuscable(url) && other.isObfuscable(url) } } func negate() -> ObfuscableFilesFilter { return ObfuscableFilesFilter { !self.isObfuscable($0) } } func or(_ other: ObfuscableFilesFilter) -> ObfuscableFilesFilter { return ObfuscableFilesFilter { url in self.isObfuscable(url) || other.isObfuscable(url) } } /// Filter that does not match any files static func none() -> ObfuscableFilesFilter { return ObfuscableFilesFilter { _ in false } } static func defaultObfuscableFilesFilter() -> ObfuscableFilesFilter { // > Swift apps no longer include dynamically linked libraries // > for the Swift standard library and Swift SDK overlays in // > build variants for devices running iOS 12.2, watchOS 5.2, // > and tvOS 12.2. // -- https://developer.apple.com/documentation/xcode_release_notes/xcode_10_2_beta_release_notes/swift_5_release_notes_for_xcode_10_2_beta return skipSwiftLibrary() } static func skipSwiftLibrary() -> ObfuscableFilesFilter { return ObfuscableFilesFilter { url in !url.lastPathComponent.starts(with: "libswift") } } static func only(file: URL) -> ObfuscableFilesFilter { return ObfuscableFilesFilter { url in url == file } } static func onlyFiles(in obfuscableDirectory: URL) -> ObfuscableFilesFilter { return ObfuscableFilesFilter { url in obfuscableDirectory.standardizedFileURL.contains(url.standardizedFileURL) } } static func isFramework(framework: String) -> ObfuscableFilesFilter { let frameworkComponent = framework + ".framework" return ObfuscableFilesFilter { url in url.pathComponents.contains(frameworkComponent) } } static func skipFramework(framework: String) -> ObfuscableFilesFilter { return isFramework(framework: framework).negate() } static func skipAllFrameworks() -> ObfuscableFilesFilter { return ObfuscableFilesFilter { url in !url.pathComponents.contains("Frameworks") } } }
{ "pile_set_name": "Github" }
# Verify that after CHANGE MASTER, replication (I/O thread and SQL # thread) restart from where SQL thread left, not from where # I/O thread left (some old bug fixed in 4.0.17) source include/master-slave.inc; connection master; # Make SQL slave thread advance a bit create table t1(n int); sync_slave_with_master; select * from t1; # Now stop it and make I/O slave thread be ahead stop slave sql_thread; connection master; insert into t1 values(1); insert into t1 values(2); save_master_pos; let $slave_param= Read_Master_Log_Pos; let $slave_param_value= query_get_value(SHOW MASTER STATUS, Position, 1); connection slave; source include/wait_for_slave_param.inc; source include/stop_slave.inc; let $read_pos= query_get_value(SHOW SLAVE STATUS, Read_Master_Log_Pos, 1); let $exec_pos= query_get_value(SHOW SLAVE STATUS, Exec_Master_Log_Pos, 1); if ($read_pos == $exec_pos) { source include/show_rpl_debug_info.inc; echo 'Read_Master_Log_Pos: $read_pos' == 'Exec_Master_Log_Pos: $exec_pos'; die Failed because Read_Master_Log_Pos is equal to Exec_Master_Log_Pos; } change master to master_user='root'; let $read_pos= query_get_value(SHOW SLAVE STATUS, Read_Master_Log_Pos, 1); let $exec_pos= query_get_value(SHOW SLAVE STATUS, Exec_Master_Log_Pos, 1); if ($read_pos != $exec_pos) { source include/show_rpl_debug_info.inc; echo 'Read_Master_Log_Pos: $read_pos' <> 'Exec_Master_Log_Pos: $exec_pos'; die Failed because Read_Master_Log_Pos is not equal to Exec_Master_Log_Pos; } start slave; sync_with_master; select * from t1; connection master; drop table t1; sync_slave_with_master; # End of 4.1 tests # # BUG#12190 CHANGE MASTER has differ path requiremts on MASTER_LOG_FILE and RELAY_LOG_FILE # if ($bug_59037_is_fixed == 'true') { --source include/rpl_reset.inc connection master; create table t1 (a int); insert into t1 values (1); flush logs; insert into t1 values (2); # Note: the master positon saved by this will also be used by the # 'sync_with_master' below. sync_slave_with_master; # Check if the table t1 and t2 are identical on master and slave; let $diff_tables= master:t1,slave:t1 source include/diff_tables.inc; connection slave; source include/stop_slave.inc; delete from t1 where a=2; # start replication from the second insert, after fix of BUG#12190, # relay_log_file does not use absolute path, only the filename is # required # # Note: the follow change master will automatically reset # relay_log_purge to false, save the old value to restore let $relay_log_purge= `select @@global.relay_log_purge`; CHANGE MASTER TO relay_log_file='slave-relay-bin.000005', relay_log_pos=4; start slave sql_thread; source include/wait_for_slave_sql_to_start.inc; # Sync to the same position saved by the 'sync_slave_with_master' above. sync_with_master; # Check if the table t1 and t2 are identical on master and slave; let $diff_tables= master:t1,slave:t1 source include/diff_tables.inc; # clean up connection slave; start slave io_thread; source include/wait_for_slave_io_to_start.inc; eval set global relay_log_purge=$relay_log_purge; connection master; drop table t1; } --source include/rpl_end.inc
{ "pile_set_name": "Github" }
/* * QEMU I/O channel test helpers * * Copyright (c) 2015 Red Hat, Inc. * * 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 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, see <http://www.gnu.org/licenses/>. * */ #include "io/channel.h" #ifndef TEST_IO_CHANNEL_HELPERS #define TEST_IO_CHANNEL_HELPERS typedef struct QIOChannelTest QIOChannelTest; QIOChannelTest *qio_channel_test_new(void); void qio_channel_test_run_threads(QIOChannelTest *test, bool blocking, QIOChannel *src, QIOChannel *dst); void qio_channel_test_run_writer(QIOChannelTest *test, QIOChannel *src); void qio_channel_test_run_reader(QIOChannelTest *test, QIOChannel *dst); void qio_channel_test_validate(QIOChannelTest *test); #endif /* TEST_IO_CHANNEL_HELPERS */
{ "pile_set_name": "Github" }
/* ----------------------------------------------------------------------- ffi.c - (c) 2011 Anthony Green (c) 2008 Red Hat, Inc. (c) 2006 Free Software Foundation, Inc. (c) 2003-2004 Randolph Chung <[email protected]> HPPA Foreign Function Interface HP-UX PA ABI support Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ``Software''), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- */ #include <ffi.h> #include <ffi_common.h> #include <stdlib.h> #include <stdio.h> #define ROUND_UP(v, a) (((size_t)(v) + (a) - 1) & ~((a) - 1)) #define MIN_STACK_SIZE 64 #define FIRST_ARG_SLOT 9 #define DEBUG_LEVEL 0 #define fldw(addr, fpreg) \ __asm__ volatile ("fldw 0(%0), %%" #fpreg "L" : : "r"(addr) : #fpreg) #define fstw(fpreg, addr) \ __asm__ volatile ("fstw %%" #fpreg "L, 0(%0)" : : "r"(addr)) #define fldd(addr, fpreg) \ __asm__ volatile ("fldd 0(%0), %%" #fpreg : : "r"(addr) : #fpreg) #define fstd(fpreg, addr) \ __asm__ volatile ("fstd %%" #fpreg "L, 0(%0)" : : "r"(addr)) #define debug(lvl, x...) do { if (lvl <= DEBUG_LEVEL) { printf(x); } } while (0) static inline int ffi_struct_type(ffi_type *t) { size_t sz = t->size; /* Small structure results are passed in registers, larger ones are passed by pointer. Note that small structures of size 2, 4 and 8 differ from the corresponding integer types in that they have different alignment requirements. */ if (sz <= 1) return FFI_TYPE_UINT8; else if (sz == 2) return FFI_TYPE_SMALL_STRUCT2; else if (sz == 3) return FFI_TYPE_SMALL_STRUCT3; else if (sz == 4) return FFI_TYPE_SMALL_STRUCT4; else if (sz == 5) return FFI_TYPE_SMALL_STRUCT5; else if (sz == 6) return FFI_TYPE_SMALL_STRUCT6; else if (sz == 7) return FFI_TYPE_SMALL_STRUCT7; else if (sz <= 8) return FFI_TYPE_SMALL_STRUCT8; else return FFI_TYPE_STRUCT; /* else, we pass it by pointer. */ } /* PA has a downward growing stack, which looks like this: Offset [ Variable args ] SP = (4*(n+9)) arg word N ... SP-52 arg word 4 [ Fixed args ] SP-48 arg word 3 SP-44 arg word 2 SP-40 arg word 1 SP-36 arg word 0 [ Frame marker ] ... SP-20 RP SP-4 previous SP The first four argument words on the stack are reserved for use by the callee. Instead, the general and floating registers replace the first four argument slots. Non FP arguments are passed solely in the general registers. FP arguments are passed in both general and floating registers when using libffi. Non-FP 32-bit args are passed in gr26, gr25, gr24 and gr23. Non-FP 64-bit args are passed in register pairs, starting on an odd numbered register (i.e. r25+r26 and r23+r24). FP 32-bit arguments are passed in fr4L, fr5L, fr6L and fr7L. FP 64-bit arguments are passed in fr5 and fr7. The registers are allocated in the same manner as stack slots. This allows the callee to save its arguments on the stack if necessary: arg word 3 -> gr23 or fr7L arg word 2 -> gr24 or fr6L or fr7R arg word 1 -> gr25 or fr5L arg word 0 -> gr26 or fr4L or fr5R Note that fr4R and fr6R are never used for arguments (i.e., doubles are not passed in fr4 or fr6). The rest of the arguments are passed on the stack starting at SP-52, but 64-bit arguments need to be aligned to an 8-byte boundary This means we can have holes either in the register allocation, or in the stack. */ /* ffi_prep_args is called by the assembly routine once stack space has been allocated for the function's arguments The following code will put everything into the stack frame (which was allocated by the asm routine), and on return the asm routine will load the arguments that should be passed by register into the appropriate registers NOTE: We load floating point args in this function... that means we assume gcc will not mess with fp regs in here. */ void ffi_prep_args_pa32(UINT32 *stack, extended_cif *ecif, unsigned bytes) { register unsigned int i; register ffi_type **p_arg; register void **p_argv; unsigned int slot = FIRST_ARG_SLOT; char *dest_cpy; size_t len; debug(1, "%s: stack = %p, ecif = %p, bytes = %u\n", __FUNCTION__, stack, ecif, bytes); p_arg = ecif->cif->arg_types; p_argv = ecif->avalue; for (i = 0; i < ecif->cif->nargs; i++) { int type = (*p_arg)->type; switch (type) { case FFI_TYPE_SINT8: *(SINT32 *)(stack - slot) = *(SINT8 *)(*p_argv); break; case FFI_TYPE_UINT8: *(UINT32 *)(stack - slot) = *(UINT8 *)(*p_argv); break; case FFI_TYPE_SINT16: *(SINT32 *)(stack - slot) = *(SINT16 *)(*p_argv); break; case FFI_TYPE_UINT16: *(UINT32 *)(stack - slot) = *(UINT16 *)(*p_argv); break; case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: case FFI_TYPE_POINTER: debug(3, "Storing UINT32 %u in slot %u\n", *(UINT32 *)(*p_argv), slot); *(UINT32 *)(stack - slot) = *(UINT32 *)(*p_argv); break; case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: /* Align slot for 64-bit type. */ slot += (slot & 1) ? 1 : 2; *(UINT64 *)(stack - slot) = *(UINT64 *)(*p_argv); break; case FFI_TYPE_FLOAT: /* First 4 args go in fr4L - fr7L. */ debug(3, "Storing UINT32(float) in slot %u\n", slot); *(UINT32 *)(stack - slot) = *(UINT32 *)(*p_argv); switch (slot - FIRST_ARG_SLOT) { /* First 4 args go in fr4L - fr7L. */ case 0: fldw(stack - slot, fr4); break; case 1: fldw(stack - slot, fr5); break; case 2: fldw(stack - slot, fr6); break; case 3: fldw(stack - slot, fr7); break; } break; case FFI_TYPE_DOUBLE: /* Align slot for 64-bit type. */ slot += (slot & 1) ? 1 : 2; debug(3, "Storing UINT64(double) at slot %u\n", slot); *(UINT64 *)(stack - slot) = *(UINT64 *)(*p_argv); switch (slot - FIRST_ARG_SLOT) { /* First 2 args go in fr5, fr7. */ case 1: fldd(stack - slot, fr5); break; case 3: fldd(stack - slot, fr7); break; } break; #ifdef PA_HPUX case FFI_TYPE_LONGDOUBLE: /* Long doubles are passed in the same manner as structures larger than 8 bytes. */ *(UINT32 *)(stack - slot) = (UINT32)(*p_argv); break; #endif case FFI_TYPE_STRUCT: /* Structs smaller or equal than 4 bytes are passed in one register. Structs smaller or equal 8 bytes are passed in two registers. Larger structures are passed by pointer. */ len = (*p_arg)->size; if (len <= 4) { dest_cpy = (char *)(stack - slot) + 4 - len; memcpy(dest_cpy, (char *)*p_argv, len); } else if (len <= 8) { slot += (slot & 1) ? 1 : 2; dest_cpy = (char *)(stack - slot) + 8 - len; memcpy(dest_cpy, (char *)*p_argv, len); } else *(UINT32 *)(stack - slot) = (UINT32)(*p_argv); break; default: FFI_ASSERT(0); } slot++; p_arg++; p_argv++; } /* Make sure we didn't mess up and scribble on the stack. */ { unsigned int n; debug(5, "Stack setup:\n"); for (n = 0; n < (bytes + 3) / 4; n++) { if ((n%4) == 0) { debug(5, "\n%08x: ", (unsigned int)(stack - n)); } debug(5, "%08x ", *(stack - n)); } debug(5, "\n"); } FFI_ASSERT(slot * 4 <= bytes); return; } static void ffi_size_stack_pa32(ffi_cif *cif) { ffi_type **ptr; int i; int z = 0; /* # stack slots */ for (ptr = cif->arg_types, i = 0; i < cif->nargs; ptr++, i++) { int type = (*ptr)->type; switch (type) { case FFI_TYPE_DOUBLE: case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: z += 2 + (z & 1); /* must start on even regs, so we may waste one */ break; #ifdef PA_HPUX case FFI_TYPE_LONGDOUBLE: #endif case FFI_TYPE_STRUCT: z += 1; /* pass by ptr, callee will copy */ break; default: /* <= 32-bit values */ z++; } } /* We can fit up to 6 args in the default 64-byte stack frame, if we need more, we need more stack. */ if (z <= 6) cif->bytes = MIN_STACK_SIZE; /* min stack size */ else cif->bytes = 64 + ROUND_UP((z - 6) * sizeof(UINT32), MIN_STACK_SIZE); debug(3, "Calculated stack size is %u bytes\n", cif->bytes); } /* Perform machine dependent cif processing. */ ffi_status ffi_prep_cif_machdep(ffi_cif *cif) { /* Set the return type flag */ switch (cif->rtype->type) { case FFI_TYPE_VOID: case FFI_TYPE_FLOAT: case FFI_TYPE_DOUBLE: cif->flags = (unsigned) cif->rtype->type; break; #ifdef PA_HPUX case FFI_TYPE_LONGDOUBLE: /* Long doubles are treated like a structure. */ cif->flags = FFI_TYPE_STRUCT; break; #endif case FFI_TYPE_STRUCT: /* For the return type we have to check the size of the structures. If the size is smaller or equal 4 bytes, the result is given back in one register. If the size is smaller or equal 8 bytes than we return the result in two registers. But if the size is bigger than 8 bytes, we work with pointers. */ cif->flags = ffi_struct_type(cif->rtype); break; case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: cif->flags = FFI_TYPE_UINT64; break; default: cif->flags = FFI_TYPE_INT; break; } /* Lucky us, because of the unique PA ABI we get to do our own stack sizing. */ switch (cif->abi) { case FFI_PA32: ffi_size_stack_pa32(cif); break; default: FFI_ASSERT(0); break; } return FFI_OK; } extern void ffi_call_pa32(void (*)(UINT32 *, extended_cif *, unsigned), extended_cif *, unsigned, unsigned, unsigned *, void (*fn)(void)); void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) { extended_cif ecif; ecif.cif = cif; ecif.avalue = avalue; /* If the return value is a struct and we don't have a return value address then we need to make one. */ if (rvalue == NULL #ifdef PA_HPUX && (cif->rtype->type == FFI_TYPE_STRUCT || cif->rtype->type == FFI_TYPE_LONGDOUBLE)) #else && cif->rtype->type == FFI_TYPE_STRUCT) #endif { ecif.rvalue = alloca(cif->rtype->size); } else ecif.rvalue = rvalue; switch (cif->abi) { case FFI_PA32: debug(3, "Calling ffi_call_pa32: ecif=%p, bytes=%u, flags=%u, rvalue=%p, fn=%p\n", &ecif, cif->bytes, cif->flags, ecif.rvalue, (void *)fn); ffi_call_pa32(ffi_prep_args_pa32, &ecif, cif->bytes, cif->flags, ecif.rvalue, fn); break; default: FFI_ASSERT(0); break; } } #if FFI_CLOSURES /* This is more-or-less an inverse of ffi_call -- we have arguments on the stack, and we need to fill them into a cif structure and invoke the user function. This really ought to be in asm to make sure the compiler doesn't do things we don't expect. */ ffi_status ffi_closure_inner_pa32(ffi_closure *closure, UINT32 *stack) { ffi_cif *cif; void **avalue; void *rvalue; UINT32 ret[2]; /* function can return up to 64-bits in registers */ ffi_type **p_arg; char *tmp; int i, avn; unsigned int slot = FIRST_ARG_SLOT; register UINT32 r28 asm("r28"); cif = closure->cif; /* If returning via structure, callee will write to our pointer. */ if (cif->flags == FFI_TYPE_STRUCT) rvalue = (void *)r28; else rvalue = &ret[0]; avalue = (void **)alloca(cif->nargs * FFI_SIZEOF_ARG); avn = cif->nargs; p_arg = cif->arg_types; for (i = 0; i < avn; i++) { int type = (*p_arg)->type; switch (type) { case FFI_TYPE_SINT8: case FFI_TYPE_UINT8: case FFI_TYPE_SINT16: case FFI_TYPE_UINT16: case FFI_TYPE_SINT32: case FFI_TYPE_UINT32: case FFI_TYPE_POINTER: avalue[i] = (char *)(stack - slot) + sizeof(UINT32) - (*p_arg)->size; break; case FFI_TYPE_SINT64: case FFI_TYPE_UINT64: slot += (slot & 1) ? 1 : 2; avalue[i] = (void *)(stack - slot); break; case FFI_TYPE_FLOAT: #ifdef PA_LINUX /* The closure call is indirect. In Linux, floating point arguments in indirect calls with a prototype are passed in the floating point registers instead of the general registers. So, we need to replace what was previously stored in the current slot with the value in the corresponding floating point register. */ switch (slot - FIRST_ARG_SLOT) { case 0: fstw(fr4, (void *)(stack - slot)); break; case 1: fstw(fr5, (void *)(stack - slot)); break; case 2: fstw(fr6, (void *)(stack - slot)); break; case 3: fstw(fr7, (void *)(stack - slot)); break; } #endif avalue[i] = (void *)(stack - slot); break; case FFI_TYPE_DOUBLE: slot += (slot & 1) ? 1 : 2; #ifdef PA_LINUX /* See previous comment for FFI_TYPE_FLOAT. */ switch (slot - FIRST_ARG_SLOT) { case 1: fstd(fr5, (void *)(stack - slot)); break; case 3: fstd(fr7, (void *)(stack - slot)); break; } #endif avalue[i] = (void *)(stack - slot); break; #ifdef PA_HPUX case FFI_TYPE_LONGDOUBLE: /* Long doubles are treated like a big structure. */ avalue[i] = (void *) *(stack - slot); break; #endif case FFI_TYPE_STRUCT: /* Structs smaller or equal than 4 bytes are passed in one register. Structs smaller or equal 8 bytes are passed in two registers. Larger structures are passed by pointer. */ if((*p_arg)->size <= 4) { avalue[i] = (void *)(stack - slot) + sizeof(UINT32) - (*p_arg)->size; } else if ((*p_arg)->size <= 8) { slot += (slot & 1) ? 1 : 2; avalue[i] = (void *)(stack - slot) + sizeof(UINT64) - (*p_arg)->size; } else avalue[i] = (void *) *(stack - slot); break; default: FFI_ASSERT(0); } slot++; p_arg++; } /* Invoke the closure. */ (closure->fun) (cif, rvalue, avalue, closure->user_data); debug(3, "after calling function, ret[0] = %08x, ret[1] = %08x\n", ret[0], ret[1]); /* Store the result using the lower 2 bytes of the flags. */ switch (cif->flags) { case FFI_TYPE_UINT8: *(stack - FIRST_ARG_SLOT) = (UINT8)(ret[0] >> 24); break; case FFI_TYPE_SINT8: *(stack - FIRST_ARG_SLOT) = (SINT8)(ret[0] >> 24); break; case FFI_TYPE_UINT16: *(stack - FIRST_ARG_SLOT) = (UINT16)(ret[0] >> 16); break; case FFI_TYPE_SINT16: *(stack - FIRST_ARG_SLOT) = (SINT16)(ret[0] >> 16); break; case FFI_TYPE_INT: case FFI_TYPE_SINT32: case FFI_TYPE_UINT32: *(stack - FIRST_ARG_SLOT) = ret[0]; break; case FFI_TYPE_SINT64: case FFI_TYPE_UINT64: *(stack - FIRST_ARG_SLOT) = ret[0]; *(stack - FIRST_ARG_SLOT - 1) = ret[1]; break; case FFI_TYPE_DOUBLE: fldd(rvalue, fr4); break; case FFI_TYPE_FLOAT: fldw(rvalue, fr4); break; case FFI_TYPE_STRUCT: /* Don't need a return value, done by caller. */ break; case FFI_TYPE_SMALL_STRUCT2: case FFI_TYPE_SMALL_STRUCT3: case FFI_TYPE_SMALL_STRUCT4: tmp = (void*)(stack - FIRST_ARG_SLOT); tmp += 4 - cif->rtype->size; memcpy((void*)tmp, &ret[0], cif->rtype->size); break; case FFI_TYPE_SMALL_STRUCT5: case FFI_TYPE_SMALL_STRUCT6: case FFI_TYPE_SMALL_STRUCT7: case FFI_TYPE_SMALL_STRUCT8: { unsigned int ret2[2]; int off; /* Right justify ret[0] and ret[1] */ switch (cif->flags) { case FFI_TYPE_SMALL_STRUCT5: off = 3; break; case FFI_TYPE_SMALL_STRUCT6: off = 2; break; case FFI_TYPE_SMALL_STRUCT7: off = 1; break; default: off = 0; break; } memset (ret2, 0, sizeof (ret2)); memcpy ((char *)ret2 + off, ret, 8 - off); *(stack - FIRST_ARG_SLOT) = ret2[0]; *(stack - FIRST_ARG_SLOT - 1) = ret2[1]; } break; case FFI_TYPE_POINTER: case FFI_TYPE_VOID: break; default: debug(0, "assert with cif->flags: %d\n",cif->flags); FFI_ASSERT(0); break; } return FFI_OK; } /* Fill in a closure to refer to the specified fun and user_data. cif specifies the argument and result types for fun. The cif must already be prep'ed. */ extern void ffi_closure_pa32(void); ffi_status ffi_prep_closure_loc (ffi_closure* closure, ffi_cif* cif, void (*fun)(ffi_cif*,void*,void**,void*), void *user_data, void *codeloc) { UINT32 *tramp = (UINT32 *)(closure->tramp); #ifdef PA_HPUX UINT32 *tmp; #endif if (cif->abi != FFI_PA32) return FFI_BAD_ABI; /* Make a small trampoline that will branch to our handler function. Use PC-relative addressing. */ #ifdef PA_LINUX tramp[0] = 0xeaa00000; /* b,l .+8,%r21 ; %r21 <- pc+8 */ tramp[1] = 0xd6a01c1e; /* depi 0,31,2,%r21 ; mask priv bits */ tramp[2] = 0x4aa10028; /* ldw 20(%r21),%r1 ; load plabel */ tramp[3] = 0x36b53ff1; /* ldo -8(%r21),%r21 ; get closure addr */ tramp[4] = 0x0c201096; /* ldw 0(%r1),%r22 ; address of handler */ tramp[5] = 0xeac0c000; /* bv%r0(%r22) ; branch to handler */ tramp[6] = 0x0c281093; /* ldw 4(%r1),%r19 ; GP of handler */ tramp[7] = ((UINT32)(ffi_closure_pa32) & ~2); /* Flush d/icache -- have to flush up 2 two lines because of alignment. */ __asm__ volatile( "fdc 0(%0)\n\t" "fdc %1(%0)\n\t" "fic 0(%%sr4, %0)\n\t" "fic %1(%%sr4, %0)\n\t" "sync\n\t" "nop\n\t" "nop\n\t" "nop\n\t" "nop\n\t" "nop\n\t" "nop\n\t" "nop\n" : : "r"((unsigned long)tramp & ~31), "r"(32 /* stride */) : "memory"); #endif #ifdef PA_HPUX tramp[0] = 0xeaa00000; /* b,l .+8,%r21 ; %r21 <- pc+8 */ tramp[1] = 0xd6a01c1e; /* depi 0,31,2,%r21 ; mask priv bits */ tramp[2] = 0x4aa10038; /* ldw 28(%r21),%r1 ; load plabel */ tramp[3] = 0x36b53ff1; /* ldo -8(%r21),%r21 ; get closure addr */ tramp[4] = 0x0c201096; /* ldw 0(%r1),%r22 ; address of handler */ tramp[5] = 0x02c010b4; /* ldsid (%r22),%r20 ; load space id */ tramp[6] = 0x00141820; /* mtsp %r20,%sr0 ; into %sr0 */ tramp[7] = 0xe2c00000; /* be 0(%sr0,%r22) ; branch to handler */ tramp[8] = 0x0c281093; /* ldw 4(%r1),%r19 ; GP of handler */ tramp[9] = ((UINT32)(ffi_closure_pa32) & ~2); /* Flush d/icache -- have to flush three lines because of alignment. */ __asm__ volatile( "copy %1,%0\n\t" "fdc,m %2(%0)\n\t" "fdc,m %2(%0)\n\t" "fdc,m %2(%0)\n\t" "ldsid (%1),%0\n\t" "mtsp %0,%%sr0\n\t" "copy %1,%0\n\t" "fic,m %2(%%sr0,%0)\n\t" "fic,m %2(%%sr0,%0)\n\t" "fic,m %2(%%sr0,%0)\n\t" "sync\n\t" "nop\n\t" "nop\n\t" "nop\n\t" "nop\n\t" "nop\n\t" "nop\n\t" "nop\n" : "=&r" ((unsigned long)tmp) : "r" ((unsigned long)tramp & ~31), "r" (32/* stride */) : "memory"); #endif closure->cif = cif; closure->user_data = user_data; closure->fun = fun; return FFI_OK; } #endif
{ "pile_set_name": "Github" }
/* This is a compiled file, you should be editing the file in the templates directory */ .pace { -webkit-pointer-events: none; pointer-events: none; -webkit-user-select: none; -moz-user-select: none; user-select: none; } .pace .pace-activity { display: block; position: fixed; z-index: 2000; top: 0; right: 0; width: 300px; height: 300px; background: #2299dd; -webkit-transition: -webkit-transform 0.3s; transition: transform 0.3s; -webkit-transform: translateX(100%) translateY(-100%) rotate(45deg); transform: translateX(100%) translateY(-100%) rotate(45deg); pointer-events: none; } .pace.pace-active .pace-activity { -webkit-transform: translateX(50%) translateY(-50%) rotate(45deg); transform: translateX(50%) translateY(-50%) rotate(45deg); } .pace .pace-activity::before, .pace .pace-activity::after { -moz-box-sizing: border-box; box-sizing: border-box; position: absolute; bottom: 30px; left: 50%; display: block; border: 5px solid #fff; border-radius: 50%; content: ''; } .pace .pace-activity::before { margin-left: -40px; width: 80px; height: 80px; border-right-color: rgba(0, 0, 0, .2); border-left-color: rgba(0, 0, 0, .2); -webkit-animation: pace-theme-corner-indicator-spin 3s linear infinite; animation: pace-theme-corner-indicator-spin 3s linear infinite; } .pace .pace-activity::after { bottom: 50px; margin-left: -20px; width: 40px; height: 40px; border-top-color: rgba(0, 0, 0, .2); border-bottom-color: rgba(0, 0, 0, .2); -webkit-animation: pace-theme-corner-indicator-spin 1s linear infinite; animation: pace-theme-corner-indicator-spin 1s linear infinite; } @-webkit-keyframes pace-theme-corner-indicator-spin { 0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(359deg); } } @keyframes pace-theme-corner-indicator-spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(359deg); } }
{ "pile_set_name": "Github" }
0 1 15.479 15.0995 16.0434
{ "pile_set_name": "Github" }
#!/bin/sh set -e . ../scripts/run-test run_test MemHandlerTest fail "" tests/MemHandlerTest
{ "pile_set_name": "Github" }
[android-components](../../index.md) / [mozilla.components.concept.engine.permission](../index.md) / [PermissionRequest](index.md) / [reject](./reject.md) # reject `abstract fun reject(): `[`Unit`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html) [(source)](https://github.com/mozilla-mobile/android-components/blob/master/components/concept/engine/src/main/java/mozilla/components/concept/engine/permission/PermissionRequest.kt#L49) Rejects the requested permissions.
{ "pile_set_name": "Github" }
/* * Copyright (C) 2009, Willow Garage, Inc. * * 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 names of Stanford University or Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL 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. */ #ifndef ROSCPP_SERVICE_HANDLE_H #define ROSCPP_SERVICE_HANDLE_H #include "ros/forwards.h" #include "common.h" namespace ros { /** * \brief Manages an service advertisement. * * A ServiceServer should always be created through a call to NodeHandle::advertiseService(), or copied from * one that was. Once all copies of a specific * ServiceServer go out of scope, the service associated with it will be unadvertised and the service callback * will stop being called. */ class ROSCPP_DECL ServiceServer { public: ServiceServer() {} ServiceServer(const ServiceServer& rhs); ~ServiceServer(); ServiceServer& operator=(const ServiceServer& other) = default; /** * \brief Unadvertise the service associated with this ServiceServer * * This method usually does not need to be explicitly called, as automatic shutdown happens when * all copies of this ServiceServer go out of scope * * This method overrides the automatic reference counted unadvertise, and immediately * unadvertises the service associated with this ServiceServer */ void shutdown(); std::string getService() const; operator void*() const { return (impl_ && impl_->isValid()) ? (void*)1 : (void*)0; } bool operator<(const ServiceServer& rhs) const { return impl_ < rhs.impl_; } bool operator==(const ServiceServer& rhs) const { return impl_ == rhs.impl_; } bool operator!=(const ServiceServer& rhs) const { return impl_ != rhs.impl_; } private: ServiceServer(const std::string& service, const NodeHandle& node_handle); class Impl { public: Impl(); ~Impl(); void unadvertise(); bool isValid() const; std::string service_; NodeHandlePtr node_handle_; bool unadvertised_; }; typedef boost::shared_ptr<Impl> ImplPtr; typedef boost::weak_ptr<Impl> ImplWPtr; ImplPtr impl_; friend class NodeHandle; friend class NodeHandleBackingCollection; }; typedef std::vector<ServiceServer> V_ServiceServer; } #endif // ROSCPP_SERVICE_HANDLE_H
{ "pile_set_name": "Github" }
package client import ( "fmt" "net/url" "strconv" "github.com/docker/docker/api/types/swarm" "golang.org/x/net/context" ) // SwarmUpdate updates the swarm. func (cli *Client) SwarmUpdate(ctx context.Context, version swarm.Version, swarm swarm.Spec, flags swarm.UpdateFlags) error { query := url.Values{} query.Set("version", strconv.FormatUint(version.Index, 10)) query.Set("rotateWorkerToken", fmt.Sprintf("%v", flags.RotateWorkerToken)) query.Set("rotateManagerToken", fmt.Sprintf("%v", flags.RotateManagerToken)) query.Set("rotateManagerUnlockKey", fmt.Sprintf("%v", flags.RotateManagerUnlockKey)) resp, err := cli.post(ctx, "/swarm/update", query, swarm, nil) ensureReaderClosed(resp) return err }
{ "pile_set_name": "Github" }
/* Copyright IBM Corp. 2017 All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package cluster import ( "bytes" "crypto/tls" "crypto/x509" "encoding/hex" "encoding/json" "encoding/pem" "fmt" "math/rand" "sync" "sync/atomic" "time" "github.com/hyperledger/fabric-config/protolator" "github.com/hyperledger/fabric-protos-go/common" "github.com/hyperledger/fabric/bccsp" "github.com/hyperledger/fabric/common/channelconfig" "github.com/hyperledger/fabric/common/configtx" "github.com/hyperledger/fabric/common/flogging" "github.com/hyperledger/fabric/common/policies" "github.com/hyperledger/fabric/common/util" "github.com/hyperledger/fabric/internal/pkg/comm" "github.com/hyperledger/fabric/protoutil" "github.com/pkg/errors" "google.golang.org/grpc" ) // ConnByCertMap maps certificates represented as strings // to gRPC connections type ConnByCertMap map[string]*grpc.ClientConn // Lookup looks up a certificate and returns the connection that was mapped // to the certificate, and whether it was found or not func (cbc ConnByCertMap) Lookup(cert []byte) (*grpc.ClientConn, bool) { conn, ok := cbc[string(cert)] return conn, ok } // Put associates the given connection to the certificate func (cbc ConnByCertMap) Put(cert []byte, conn *grpc.ClientConn) { cbc[string(cert)] = conn } // Remove removes the connection that is associated to the given certificate func (cbc ConnByCertMap) Remove(cert []byte) { delete(cbc, string(cert)) } // Size returns the size of the connections by certificate mapping func (cbc ConnByCertMap) Size() int { return len(cbc) } // CertificateComparator returns whether some relation holds for two given certificates type CertificateComparator func([]byte, []byte) bool // MemberMapping defines NetworkMembers by their ID // and enables to lookup stubs by a certificate type MemberMapping struct { id2stub map[uint64]*Stub SamePublicKey CertificateComparator } // Foreach applies the given function on all stubs in the mapping func (mp *MemberMapping) Foreach(f func(id uint64, stub *Stub)) { for id, stub := range mp.id2stub { f(id, stub) } } // Put inserts the given stub to the MemberMapping func (mp *MemberMapping) Put(stub *Stub) { mp.id2stub[stub.ID] = stub } // Remove removes the stub with the given ID from the MemberMapping func (mp *MemberMapping) Remove(ID uint64) { delete(mp.id2stub, ID) } // ByID retrieves the Stub with the given ID from the MemberMapping func (mp MemberMapping) ByID(ID uint64) *Stub { return mp.id2stub[ID] } // LookupByClientCert retrieves a Stub with the given client certificate func (mp MemberMapping) LookupByClientCert(cert []byte) *Stub { for _, stub := range mp.id2stub { if mp.SamePublicKey(stub.ClientTLSCert, cert) { return stub } } return nil } // ServerCertificates returns a set of the server certificates // represented as strings func (mp MemberMapping) ServerCertificates() StringSet { res := make(StringSet) for _, member := range mp.id2stub { res[string(member.ServerTLSCert)] = struct{}{} } return res } // StringSet is a set of strings type StringSet map[string]struct{} // union adds the elements of the given set to the StringSet func (ss StringSet) union(set StringSet) { for k := range set { ss[k] = struct{}{} } } // subtract removes all elements in the given set from the StringSet func (ss StringSet) subtract(set StringSet) { for k := range set { delete(ss, k) } } // PredicateDialer creates gRPC connections // that are only established if the given predicate // is fulfilled type PredicateDialer struct { lock sync.RWMutex Config comm.ClientConfig } func (dialer *PredicateDialer) UpdateRootCAs(serverRootCAs [][]byte) { dialer.lock.Lock() defer dialer.lock.Unlock() dialer.Config.SecOpts.ServerRootCAs = serverRootCAs } // Dial creates a new gRPC connection that can only be established, if the remote node's // certificate chain satisfy verifyFunc func (dialer *PredicateDialer) Dial(address string, verifyFunc RemoteVerifier) (*grpc.ClientConn, error) { dialer.lock.RLock() cfg := dialer.Config.Clone() dialer.lock.RUnlock() cfg.SecOpts.VerifyCertificate = verifyFunc client, err := comm.NewGRPCClient(cfg) if err != nil { return nil, errors.WithStack(err) } return client.NewConnection(address, func(tlsConfig *tls.Config) { // We need to dynamically overwrite the TLS root CAs, // as they may be updated. dialer.lock.RLock() serverRootCAs := dialer.Config.Clone().SecOpts.ServerRootCAs dialer.lock.RUnlock() tlsConfig.RootCAs = x509.NewCertPool() for _, pem := range serverRootCAs { tlsConfig.RootCAs.AppendCertsFromPEM(pem) } }) } // DERtoPEM returns a PEM representation of the DER // encoded certificate func DERtoPEM(der []byte) string { return string(pem.EncodeToMemory(&pem.Block{ Type: "CERTIFICATE", Bytes: der, })) } // StandardDialer wraps an ClientConfig, and provides // a means to connect according to given EndpointCriteria. type StandardDialer struct { Config comm.ClientConfig } // Dial dials an address according to the given EndpointCriteria func (dialer *StandardDialer) Dial(endpointCriteria EndpointCriteria) (*grpc.ClientConn, error) { cfg := dialer.Config.Clone() cfg.SecOpts.ServerRootCAs = endpointCriteria.TLSRootCAs client, err := comm.NewGRPCClient(cfg) if err != nil { return nil, errors.Wrap(err, "failed creating gRPC client") } return client.NewConnection(endpointCriteria.Endpoint) } //go:generate mockery -dir . -name BlockVerifier -case underscore -output ./mocks/ // BlockVerifier verifies block signatures. type BlockVerifier interface { // VerifyBlockSignature verifies a signature of a block. // It has an optional argument of a configuration envelope // which would make the block verification to use validation rules // based on the given configuration in the ConfigEnvelope. // If the config envelope passed is nil, then the validation rules used // are the ones that were applied at commit of previous blocks. VerifyBlockSignature(sd []*protoutil.SignedData, config *common.ConfigEnvelope) error } // BlockSequenceVerifier verifies that the given consecutive sequence // of blocks is valid. type BlockSequenceVerifier func(blocks []*common.Block, channel string) error // Dialer creates a gRPC connection to a remote address type Dialer interface { Dial(endpointCriteria EndpointCriteria) (*grpc.ClientConn, error) } // VerifyBlocks verifies the given consecutive sequence of blocks is valid, // and returns nil if it's valid, else an error. func VerifyBlocks(blockBuff []*common.Block, signatureVerifier BlockVerifier) error { if len(blockBuff) == 0 { return errors.New("buffer is empty") } // First, we verify that the block hash in every block is: // Equal to the hash in the header // Equal to the previous hash in the succeeding block for i := range blockBuff { if err := VerifyBlockHash(i, blockBuff); err != nil { return err } } var config *common.ConfigEnvelope var isLastBlockConfigBlock bool // Verify all configuration blocks that are found inside the block batch, // with the configuration that was committed (nil) or with one that is picked up // during iteration over the block batch. for _, block := range blockBuff { configFromBlock, err := ConfigFromBlock(block) if err == errNotAConfig { isLastBlockConfigBlock = false continue } if err != nil { return err } // The block is a configuration block, so verify it if err := VerifyBlockSignature(block, signatureVerifier, config); err != nil { return err } config = configFromBlock isLastBlockConfigBlock = true } // Verify the last block's signature lastBlock := blockBuff[len(blockBuff)-1] // If last block is a config block, we verified it using the policy of the previous block, so it's valid. if isLastBlockConfigBlock { return nil } return VerifyBlockSignature(lastBlock, signatureVerifier, config) } var errNotAConfig = errors.New("not a config block") // ConfigFromBlock returns a ConfigEnvelope if exists, or a *NotAConfigBlock error. // It may also return some other error in case parsing failed. func ConfigFromBlock(block *common.Block) (*common.ConfigEnvelope, error) { if block == nil || block.Data == nil || len(block.Data.Data) == 0 { return nil, errors.New("empty block") } txn := block.Data.Data[0] env, err := protoutil.GetEnvelopeFromBlock(txn) if err != nil { return nil, errors.WithStack(err) } payload, err := protoutil.UnmarshalPayload(env.Payload) if err != nil { return nil, errors.WithStack(err) } if block.Header.Number == 0 { configEnvelope, err := configtx.UnmarshalConfigEnvelope(payload.Data) if err != nil { return nil, errors.Wrap(err, "invalid config envelope") } return configEnvelope, nil } if payload.Header == nil { return nil, errors.New("nil header in payload") } chdr, err := protoutil.UnmarshalChannelHeader(payload.Header.ChannelHeader) if err != nil { return nil, errors.WithStack(err) } if common.HeaderType(chdr.Type) != common.HeaderType_CONFIG { return nil, errNotAConfig } configEnvelope, err := configtx.UnmarshalConfigEnvelope(payload.Data) if err != nil { return nil, errors.Wrap(err, "invalid config envelope") } return configEnvelope, nil } // VerifyBlockHash verifies the hash chain of the block with the given index // among the blocks of the given block buffer. func VerifyBlockHash(indexInBuffer int, blockBuff []*common.Block) error { if len(blockBuff) <= indexInBuffer { return errors.Errorf("index %d out of bounds (total %d blocks)", indexInBuffer, len(blockBuff)) } block := blockBuff[indexInBuffer] if block.Header == nil { return errors.New("missing block header") } seq := block.Header.Number dataHash := protoutil.BlockDataHash(block.Data) // Verify data hash matches the hash in the header if !bytes.Equal(dataHash, block.Header.DataHash) { computedHash := hex.EncodeToString(dataHash) claimedHash := hex.EncodeToString(block.Header.DataHash) return errors.Errorf("computed hash of block (%d) (%s) doesn't match claimed hash (%s)", seq, computedHash, claimedHash) } // We have a previous block in the buffer, ensure current block's previous hash matches the previous one. if indexInBuffer > 0 { prevBlock := blockBuff[indexInBuffer-1] currSeq := block.Header.Number if prevBlock.Header == nil { return errors.New("previous block header is nil") } prevSeq := prevBlock.Header.Number if prevSeq+1 != currSeq { return errors.Errorf("sequences %d and %d were received consecutively", prevSeq, currSeq) } if !bytes.Equal(block.Header.PreviousHash, protoutil.BlockHeaderHash(prevBlock.Header)) { claimedPrevHash := hex.EncodeToString(block.Header.PreviousHash) actualPrevHash := hex.EncodeToString(protoutil.BlockHeaderHash(prevBlock.Header)) return errors.Errorf("block [%d]'s hash (%s) mismatches block [%d]'s prev block hash (%s)", prevSeq, actualPrevHash, currSeq, claimedPrevHash) } } return nil } // SignatureSetFromBlock creates a signature set out of a block. func SignatureSetFromBlock(block *common.Block) ([]*protoutil.SignedData, error) { if block.Metadata == nil || len(block.Metadata.Metadata) <= int(common.BlockMetadataIndex_SIGNATURES) { return nil, errors.New("no metadata in block") } metadata, err := protoutil.GetMetadataFromBlock(block, common.BlockMetadataIndex_SIGNATURES) if err != nil { return nil, errors.Errorf("failed unmarshaling medatata for signatures: %v", err) } var signatureSet []*protoutil.SignedData for _, metadataSignature := range metadata.Signatures { sigHdr, err := protoutil.UnmarshalSignatureHeader(metadataSignature.SignatureHeader) if err != nil { return nil, errors.Errorf("failed unmarshaling signature header for block with id %d: %v", block.Header.Number, err) } signatureSet = append(signatureSet, &protoutil.SignedData{ Identity: sigHdr.Creator, Data: util.ConcatenateBytes(metadata.Value, metadataSignature.SignatureHeader, protoutil.BlockHeaderBytes(block.Header)), Signature: metadataSignature.Signature, }, ) } return signatureSet, nil } // VerifyBlockSignature verifies the signature on the block with the given BlockVerifier and the given config. func VerifyBlockSignature(block *common.Block, verifier BlockVerifier, config *common.ConfigEnvelope) error { signatureSet, err := SignatureSetFromBlock(block) if err != nil { return err } return verifier.VerifyBlockSignature(signatureSet, config) } // EndpointCriteria defines criteria of how to connect to a remote orderer node. type EndpointCriteria struct { Endpoint string // Endpoint of the form host:port TLSRootCAs [][]byte // PEM encoded TLS root CA certificates } // String returns a string representation of this EndpointCriteria func (ep EndpointCriteria) String() string { var formattedCAs []interface{} for _, rawCAFile := range ep.TLSRootCAs { var bl *pem.Block pemContent := rawCAFile for { bl, pemContent = pem.Decode(pemContent) if bl == nil { break } cert, err := x509.ParseCertificate(bl.Bytes) if err != nil { break } issuedBy := cert.Issuer.String() if cert.Issuer.String() == cert.Subject.String() { issuedBy = "self" } info := make(map[string]interface{}) info["Expired"] = time.Now().After(cert.NotAfter) info["Subject"] = cert.Subject.String() info["Issuer"] = issuedBy formattedCAs = append(formattedCAs, info) } } formattedEndpointCriteria := make(map[string]interface{}) formattedEndpointCriteria["Endpoint"] = ep.Endpoint formattedEndpointCriteria["CAs"] = formattedCAs rawJSON, err := json.Marshal(formattedEndpointCriteria) if err != nil { return fmt.Sprintf("{\"Endpoint\": \"%s\"}", ep.Endpoint) } return string(rawJSON) } // EndpointconfigFromConfigBlock retrieves TLS CA certificates and endpoints // from a config block. func EndpointconfigFromConfigBlock(block *common.Block, bccsp bccsp.BCCSP) ([]EndpointCriteria, error) { if block == nil { return nil, errors.New("nil block") } envelopeConfig, err := protoutil.ExtractEnvelope(block, 0) if err != nil { return nil, err } bundle, err := channelconfig.NewBundleFromEnvelope(envelopeConfig, bccsp) if err != nil { return nil, errors.Wrap(err, "failed extracting bundle from envelope") } msps, err := bundle.MSPManager().GetMSPs() if err != nil { return nil, errors.Wrap(err, "failed obtaining MSPs from MSPManager") } ordererConfig, ok := bundle.OrdererConfig() if !ok { return nil, errors.New("failed obtaining orderer config from bundle") } mspIDsToCACerts := make(map[string][][]byte) var aggregatedTLSCerts [][]byte for _, org := range ordererConfig.Organizations() { // Validate that every orderer org has a corresponding MSP instance in the MSP Manager. msp, exists := msps[org.MSPID()] if !exists { return nil, errors.Errorf("no MSP found for MSP with ID of %s", org.MSPID()) } // Build a per org mapping of the TLS CA certs for this org, // and aggregate all TLS CA certs into aggregatedTLSCerts to be used later on. var caCerts [][]byte caCerts = append(caCerts, msp.GetTLSIntermediateCerts()...) caCerts = append(caCerts, msp.GetTLSRootCerts()...) mspIDsToCACerts[org.MSPID()] = caCerts aggregatedTLSCerts = append(aggregatedTLSCerts, caCerts...) } endpointsPerOrg := perOrgEndpoints(ordererConfig, mspIDsToCACerts) if len(endpointsPerOrg) > 0 { return endpointsPerOrg, nil } return globalEndpointsFromConfig(aggregatedTLSCerts, bundle), nil } func perOrgEndpoints(ordererConfig channelconfig.Orderer, mspIDsToCerts map[string][][]byte) []EndpointCriteria { var endpointsPerOrg []EndpointCriteria for _, org := range ordererConfig.Organizations() { for _, endpoint := range org.Endpoints() { endpointsPerOrg = append(endpointsPerOrg, EndpointCriteria{ TLSRootCAs: mspIDsToCerts[org.MSPID()], Endpoint: endpoint, }) } } return endpointsPerOrg } func globalEndpointsFromConfig(aggregatedTLSCerts [][]byte, bundle *channelconfig.Bundle) []EndpointCriteria { var globalEndpoints []EndpointCriteria for _, endpoint := range bundle.ChannelConfig().OrdererAddresses() { globalEndpoints = append(globalEndpoints, EndpointCriteria{ Endpoint: endpoint, TLSRootCAs: aggregatedTLSCerts, }) } return globalEndpoints } //go:generate mockery -dir . -name VerifierFactory -case underscore -output ./mocks/ // VerifierFactory creates BlockVerifiers. type VerifierFactory interface { // VerifierFromConfig creates a BlockVerifier from the given configuration. VerifierFromConfig(configuration *common.ConfigEnvelope, channel string) (BlockVerifier, error) } // VerificationRegistry registers verifiers and retrieves them. type VerificationRegistry struct { LoadVerifier func(chain string) BlockVerifier Logger *flogging.FabricLogger VerifierFactory VerifierFactory VerifiersByChannel map[string]BlockVerifier } // RegisterVerifier adds a verifier into the registry if applicable. func (vr *VerificationRegistry) RegisterVerifier(chain string) { if _, exists := vr.VerifiersByChannel[chain]; exists { vr.Logger.Debugf("No need to register verifier for chain %s", chain) return } v := vr.LoadVerifier(chain) if v == nil { vr.Logger.Errorf("Failed loading verifier for chain %s", chain) return } vr.VerifiersByChannel[chain] = v vr.Logger.Infof("Registered verifier for chain %s", chain) } // RetrieveVerifier returns a BlockVerifier for the given channel, or nil if not found. func (vr *VerificationRegistry) RetrieveVerifier(channel string) BlockVerifier { verifier, exists := vr.VerifiersByChannel[channel] if exists { return verifier } vr.Logger.Errorf("No verifier for channel %s exists", channel) return nil } // BlockCommitted notifies the VerificationRegistry upon a block commit, which may // trigger a registration of a verifier out of the block in case the block is a config block. func (vr *VerificationRegistry) BlockCommitted(block *common.Block, channel string) { conf, err := ConfigFromBlock(block) // The block doesn't contain a config block, but is a valid block if err == errNotAConfig { vr.Logger.Debugf("Committed block [%d] for channel %s that is not a config block", block.Header.Number, channel) return } // The block isn't a valid block if err != nil { vr.Logger.Errorf("Failed parsing block of channel %s: %v, content: %s", channel, err, BlockToString(block)) return } // The block contains a config block verifier, err := vr.VerifierFactory.VerifierFromConfig(conf, channel) if err != nil { vr.Logger.Errorf("Failed creating a verifier from a config block for channel %s: %v, content: %s", channel, err, BlockToString(block)) return } vr.VerifiersByChannel[channel] = verifier vr.Logger.Debugf("Committed config block [%d] for channel %s", block.Header.Number, channel) } // BlockToString returns a string representation of this block. func BlockToString(block *common.Block) string { buff := &bytes.Buffer{} protolator.DeepMarshalJSON(buff, block) return buff.String() } // BlockCommitFunc signals a block commit. type BlockCommitFunc func(block *common.Block, channel string) // LedgerInterceptor intercepts block commits. type LedgerInterceptor struct { Channel string InterceptBlockCommit BlockCommitFunc LedgerWriter } // Append commits a block into the ledger, and also fires the configured callback. func (interceptor *LedgerInterceptor) Append(block *common.Block) error { defer interceptor.InterceptBlockCommit(block, interceptor.Channel) return interceptor.LedgerWriter.Append(block) } // BlockVerifierAssembler creates a BlockVerifier out of a config envelope type BlockVerifierAssembler struct { Logger *flogging.FabricLogger BCCSP bccsp.BCCSP } // VerifierFromConfig creates a BlockVerifier from the given configuration. func (bva *BlockVerifierAssembler) VerifierFromConfig(configuration *common.ConfigEnvelope, channel string) (BlockVerifier, error) { bundle, err := channelconfig.NewBundle(channel, configuration.Config, bva.BCCSP) if err != nil { return nil, errors.Wrap(err, "failed extracting bundle from envelope") } policyMgr := bundle.PolicyManager() return &BlockValidationPolicyVerifier{ Logger: bva.Logger, PolicyMgr: policyMgr, Channel: channel, BCCSP: bva.BCCSP, }, nil } // BlockValidationPolicyVerifier verifies signatures based on the block validation policy. type BlockValidationPolicyVerifier struct { Logger *flogging.FabricLogger Channel string PolicyMgr policies.Manager BCCSP bccsp.BCCSP } // VerifyBlockSignature verifies the signed data associated to a block, optionally with the given config envelope. func (bv *BlockValidationPolicyVerifier) VerifyBlockSignature(sd []*protoutil.SignedData, envelope *common.ConfigEnvelope) error { policyMgr := bv.PolicyMgr // If the envelope passed isn't nil, we should use a different policy manager. if envelope != nil { bundle, err := channelconfig.NewBundle(bv.Channel, envelope.Config, bv.BCCSP) if err != nil { buff := &bytes.Buffer{} protolator.DeepMarshalJSON(buff, envelope.Config) bv.Logger.Errorf("Failed creating a new bundle for channel %s, Config content is: %s", bv.Channel, buff.String()) return err } bv.Logger.Infof("Initializing new PolicyManager for channel %s", bv.Channel) policyMgr = bundle.PolicyManager() } policy, exists := policyMgr.GetPolicy(policies.BlockValidation) if !exists { return errors.Errorf("policy %s wasn't found", policies.BlockValidation) } return policy.EvaluateSignedData(sd) } //go:generate mockery -dir . -name BlockRetriever -case underscore -output ./mocks/ // BlockRetriever retrieves blocks type BlockRetriever interface { // Block returns a block with the given number, // or nil if such a block doesn't exist. Block(number uint64) *common.Block } // LastConfigBlock returns the last config block relative to the given block. func LastConfigBlock(block *common.Block, blockRetriever BlockRetriever) (*common.Block, error) { if block == nil { return nil, errors.New("nil block") } if blockRetriever == nil { return nil, errors.New("nil blockRetriever") } lastConfigBlockNum, err := protoutil.GetLastConfigIndexFromBlock(block) if err != nil { return nil, err } lastConfigBlock := blockRetriever.Block(lastConfigBlockNum) if lastConfigBlock == nil { return nil, errors.Errorf("unable to retrieve last config block [%d]", lastConfigBlockNum) } return lastConfigBlock, nil } // StreamCountReporter reports the number of streams currently connected to this node type StreamCountReporter struct { Metrics *Metrics count uint32 } func (scr *StreamCountReporter) Increment() { count := atomic.AddUint32(&scr.count, 1) scr.Metrics.reportStreamCount(count) } func (scr *StreamCountReporter) Decrement() { count := atomic.AddUint32(&scr.count, ^uint32(0)) scr.Metrics.reportStreamCount(count) } type certificateExpirationCheck struct { minimumExpirationWarningInterval time.Duration expiresAt time.Time expirationWarningThreshold time.Duration lastWarning time.Time nodeName string endpoint string alert func(string, ...interface{}) } func (exp *certificateExpirationCheck) checkExpiration(currentTime time.Time, channel string) { timeLeft := exp.expiresAt.Sub(currentTime) if timeLeft > exp.expirationWarningThreshold { return } timeSinceLastWarning := currentTime.Sub(exp.lastWarning) if timeSinceLastWarning < exp.minimumExpirationWarningInterval { return } exp.alert("Certificate of %s from %s for channel %s expires in less than %v", exp.nodeName, exp.endpoint, channel, timeLeft) exp.lastWarning = currentTime } // CachePublicKeyComparisons creates CertificateComparator that caches invocations based on input arguments. // The given CertificateComparator must be a stateless function. func CachePublicKeyComparisons(f CertificateComparator) CertificateComparator { m := &ComparisonMemoizer{ MaxEntries: 4096, F: f, } return m.Compare } // ComparisonMemoizer speeds up comparison computations by caching past invocations of a stateless function type ComparisonMemoizer struct { // Configuration F func(a, b []byte) bool MaxEntries uint16 // Internal state cache map[arguments]bool lock sync.RWMutex once sync.Once rand *rand.Rand } type arguments struct { a, b string } // Size returns the number of computations the ComparisonMemoizer currently caches. func (cm *ComparisonMemoizer) Size() int { cm.lock.RLock() defer cm.lock.RUnlock() return len(cm.cache) } // Compare compares the given two byte slices. // It may return previous computations for the given two arguments, // otherwise it will compute the function F and cache the result. func (cm *ComparisonMemoizer) Compare(a, b []byte) bool { cm.once.Do(cm.setup) key := arguments{ a: string(a), b: string(b), } cm.lock.RLock() result, exists := cm.cache[key] cm.lock.RUnlock() if exists { return result } result = cm.F(a, b) cm.lock.Lock() defer cm.lock.Unlock() cm.shrinkIfNeeded() cm.cache[key] = result return result } func (cm *ComparisonMemoizer) shrinkIfNeeded() { for { currentSize := uint16(len(cm.cache)) if currentSize < cm.MaxEntries { return } cm.shrink() } } func (cm *ComparisonMemoizer) shrink() { // Shrink the cache by 25% by removing every fourth element (on average) for key := range cm.cache { if cm.rand.Int()%4 != 0 { continue } delete(cm.cache, key) } } func (cm *ComparisonMemoizer) setup() { cm.lock.Lock() defer cm.lock.Unlock() cm.rand = rand.New(rand.NewSource(time.Now().UnixNano())) cm.cache = make(map[arguments]bool) }
{ "pile_set_name": "Github" }
// +build go1.8 package pq import ( "context" "database/sql" "testing" "time" ) func TestMultipleSimpleQuery(t *testing.T) { db := openTestConn(t) defer db.Close() rows, err := db.Query("select 1; set time zone default; select 2; select 3") if err != nil { t.Fatal(err) } defer rows.Close() var i int for rows.Next() { if err := rows.Scan(&i); err != nil { t.Fatal(err) } if i != 1 { t.Fatalf("expected 1, got %d", i) } } if !rows.NextResultSet() { t.Fatal("expected more result sets", rows.Err()) } for rows.Next() { if err := rows.Scan(&i); err != nil { t.Fatal(err) } if i != 2 { t.Fatalf("expected 2, got %d", i) } } // Make sure that if we ignore a result we can still query. rows, err = db.Query("select 4; select 5") if err != nil { t.Fatal(err) } defer rows.Close() for rows.Next() { if err := rows.Scan(&i); err != nil { t.Fatal(err) } if i != 4 { t.Fatalf("expected 4, got %d", i) } } if !rows.NextResultSet() { t.Fatal("expected more result sets", rows.Err()) } for rows.Next() { if err := rows.Scan(&i); err != nil { t.Fatal(err) } if i != 5 { t.Fatalf("expected 5, got %d", i) } } if rows.NextResultSet() { t.Fatal("unexpected result set") } } const contextRaceIterations = 100 func TestContextCancelExec(t *testing.T) { db := openTestConn(t) defer db.Close() ctx, cancel := context.WithCancel(context.Background()) // Delay execution for just a bit until db.ExecContext has begun. defer time.AfterFunc(time.Millisecond*10, cancel).Stop() // Not canceled until after the exec has started. if _, err := db.ExecContext(ctx, "select pg_sleep(1)"); err == nil { t.Fatal("expected error") } else if err.Error() != "pq: canceling statement due to user request" { t.Fatalf("unexpected error: %s", err) } // Context is already canceled, so error should come before execution. if _, err := db.ExecContext(ctx, "select pg_sleep(1)"); err == nil { t.Fatal("expected error") } else if err.Error() != "context canceled" { t.Fatalf("unexpected error: %s", err) } for i := 0; i < contextRaceIterations; i++ { func() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() if _, err := db.ExecContext(ctx, "select 1"); err != nil { t.Fatal(err) } }() if _, err := db.Exec("select 1"); err != nil { t.Fatal(err) } } } func TestContextCancelQuery(t *testing.T) { db := openTestConn(t) defer db.Close() ctx, cancel := context.WithCancel(context.Background()) // Delay execution for just a bit until db.QueryContext has begun. defer time.AfterFunc(time.Millisecond*10, cancel).Stop() // Not canceled until after the exec has started. if _, err := db.QueryContext(ctx, "select pg_sleep(1)"); err == nil { t.Fatal("expected error") } else if err.Error() != "pq: canceling statement due to user request" { t.Fatalf("unexpected error: %s", err) } // Context is already canceled, so error should come before execution. if _, err := db.QueryContext(ctx, "select pg_sleep(1)"); err == nil { t.Fatal("expected error") } else if err.Error() != "context canceled" { t.Fatalf("unexpected error: %s", err) } for i := 0; i < contextRaceIterations; i++ { func() { ctx, cancel := context.WithCancel(context.Background()) rows, err := db.QueryContext(ctx, "select 1") cancel() if err != nil { t.Fatal(err) } else if err := rows.Close(); err != nil { t.Fatal(err) } }() if rows, err := db.Query("select 1"); err != nil { t.Fatal(err) } else if err := rows.Close(); err != nil { t.Fatal(err) } } } func TestContextCancelBegin(t *testing.T) { db := openTestConn(t) defer db.Close() ctx, cancel := context.WithCancel(context.Background()) tx, err := db.BeginTx(ctx, nil) if err != nil { t.Fatal(err) } // Delay execution for just a bit until tx.Exec has begun. defer time.AfterFunc(time.Millisecond*10, cancel).Stop() // Not canceled until after the exec has started. if _, err := tx.Exec("select pg_sleep(1)"); err == nil { t.Fatal("expected error") } else if err.Error() != "pq: canceling statement due to user request" { t.Fatalf("unexpected error: %s", err) } // Transaction is canceled, so expect an error. if _, err := tx.Query("select pg_sleep(1)"); err == nil { t.Fatal("expected error") } else if err != sql.ErrTxDone { t.Fatalf("unexpected error: %s", err) } // Context is canceled, so cannot begin a transaction. if _, err := db.BeginTx(ctx, nil); err == nil { t.Fatal("expected error") } else if err.Error() != "context canceled" { t.Fatalf("unexpected error: %s", err) } for i := 0; i < contextRaceIterations; i++ { func() { ctx, cancel := context.WithCancel(context.Background()) tx, err := db.BeginTx(ctx, nil) cancel() if err != nil { t.Fatal(err) } else if err := tx.Rollback(); err != nil && err != sql.ErrTxDone { t.Fatal(err) } }() if tx, err := db.Begin(); err != nil { t.Fatal(err) } else if err := tx.Rollback(); err != nil { t.Fatal(err) } } }
{ "pile_set_name": "Github" }
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables __all__ = ['Vault'] class Vault(pulumi.CustomResource): def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, kms_key_arn: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None, __name__=None, __opts__=None): """ Provides an AWS Backup vault resource. ## Example Usage ```python import pulumi import pulumi_aws as aws example = aws.backup.Vault("example", kms_key_arn=aws_kms_key["example"]["arn"]) ``` :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] kms_key_arn: The server-side encryption key that is used to protect your backups. :param pulumi.Input[str] name: Name of the backup vault to create. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Metadata that you can assign to help organize the resources that you create. """ if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['kms_key_arn'] = kms_key_arn __props__['name'] = name __props__['tags'] = tags __props__['arn'] = None __props__['recovery_points'] = None super(Vault, __self__).__init__( 'aws:backup/vault:Vault', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, arn: Optional[pulumi.Input[str]] = None, kms_key_arn: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, recovery_points: Optional[pulumi.Input[int]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None) -> 'Vault': """ Get an existing Vault resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] arn: The ARN of the vault. :param pulumi.Input[str] kms_key_arn: The server-side encryption key that is used to protect your backups. :param pulumi.Input[str] name: Name of the backup vault to create. :param pulumi.Input[int] recovery_points: The number of recovery points that are stored in a backup vault. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Metadata that you can assign to help organize the resources that you create. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() __props__["arn"] = arn __props__["kms_key_arn"] = kms_key_arn __props__["name"] = name __props__["recovery_points"] = recovery_points __props__["tags"] = tags return Vault(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter def arn(self) -> pulumi.Output[str]: """ The ARN of the vault. """ return pulumi.get(self, "arn") @property @pulumi.getter(name="kmsKeyArn") def kms_key_arn(self) -> pulumi.Output[str]: """ The server-side encryption key that is used to protect your backups. """ return pulumi.get(self, "kms_key_arn") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ Name of the backup vault to create. """ return pulumi.get(self, "name") @property @pulumi.getter(name="recoveryPoints") def recovery_points(self) -> pulumi.Output[int]: """ The number of recovery points that are stored in a backup vault. """ return pulumi.get(self, "recovery_points") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]: """ Metadata that you can assign to help organize the resources that you create. """ return pulumi.get(self, "tags") def translate_output_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop def translate_input_property(self, prop): return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
{ "pile_set_name": "Github" }
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo package cpu func getisar0() uint64 func getisar1() uint64 func getpfr0() uint64
{ "pile_set_name": "Github" }
use strict; use warnings; # New HTML templates our @Templates = ( { Queue => '0', Name => 'Autoreply in HTML', # loc Description => 'HTML Autoresponse template', # loc Content => q[Subject: AutoReply: {$Ticket->Subject} Content-Type: text/html <p>Greetings,</p> <p>This message has been automatically generated in response to the creation of a trouble ticket regarding <b>{$Ticket->Subject()}</b>, a summary of which appears below.</p> <p>There is no need to reply to this message right now. Your ticket has been assigned an ID of <b>{$Ticket->SubjectTag}</b>.</p> <p>Please include the string <b>{$Ticket->SubjectTag}</b> in the subject line of all future correspondence about this issue. To do so, you may reply to this message.</p> <p>Thank you,<br/> {$Ticket->QueueObj->CorrespondAddress()}</p> <hr/> {$Transaction->Content(Type => 'text/html')} ], }, { Queue => '0', Name => 'Transaction in HTML', # loc Description => 'HTML transaction template', # loc Content => 'RT-Attach-Message: yes Content-Type: text/html <b>{$Transaction->CreatedAsString}: Request <a href="{RT->Config->Get("WebURL")}Ticket/Display.html?id={$Ticket->id}">{$Ticket->id}</a> was acted upon by {$Transaction->CreatorObj->Name}.</b> <br> <table border="0"> <tr><td align="right"><b>Transaction:</b></td><td>{$Transaction->Description}</td></tr> <tr><td align="right"><b>Queue:</b></td><td>{$Ticket->QueueObj->Name}</td></tr> <tr><td align="right"><b>Subject:</b></td><td>{$Transaction->Subject || $Ticket->Subject || "(No subject given)"} </td></tr> <tr><td align="right"><b>Owner:</b></td><td>{$Ticket->OwnerObj->Name}</td></tr> <tr><td align="right"><b>Requestors:</b></td><td>{$Ticket->RequestorAddresses}</td></tr> <tr><td align="right"><b>Status:</b></td><td>{$Ticket->Status}</td></tr> <tr><td align="right"><b>Ticket URL:</b></td><td><a href="{RT->Config->Get("WebURL")}Ticket/Display.html?id={$Ticket->id}">{RT->Config->Get("WebURL")}Ticket/Display.html?id={$Ticket->id}</a></td></tr> </table> <br/> <br/> {$Transaction->Content( Type => "text/html")} ' }, { Queue => '0', Name => 'Admin Correspondence in HTML', # loc Description => 'HTML admin correspondence template', # loc Content => 'RT-Attach-Message: yes Content-Type: text/html Ticket URL: <a href="{RT->Config->Get("WebURL")}Ticket/Display.html?id={$Ticket->id}">{RT->Config->Get("WebURL")}Ticket/Display.html?id={$Ticket->id}</a> <br /> <br /> {$Transaction->Content(Type => "text/html");} ' }, { Queue => '0', Name => 'Correspondence in HTML', # loc Description => 'HTML correspondence template', # loc Content => 'RT-Attach-Message: yes Content-Type: text/html {$Transaction->Content( Type => "text/html")} ' }, { Queue => '0', Name => 'Admin Comment in HTML', # loc Description => 'HTML admin comment template', # loc Content => 'Subject: [Comment] {my $s=($Transaction->Subject||$Ticket->Subject); $s =~ s/\\[Comment\\]\\s*//g; $s =~ s/^Re:\\s*//i; $s;} RT-Attach-Message: yes Content-Type: text/html <p>This is a comment about <a href="{RT->Config->Get("WebURL")}Ticket/Display.html?id={$Ticket->id}">ticket {$Ticket->id}</a>. It is not sent to the Requestor(s):</p> {$Transaction->Content(Type => "text/html")} ' }, { Queue => '0', Name => 'Status Change in HTML', # loc Description => 'HTML Ticket status changed', # loc Content => 'Subject: Status Changed to: {$Transaction->NewValue} Content-Type: text/html <a href="{RT->Config->Get("WebURL")}Ticket/Display.html?id={$Ticket->id}">{RT->Config->Get("WebURL")}Ticket/Display.html?id={$Ticket->id}</a> <br/> <br/> {$Transaction->Content(Type => "text/html")} ' }, { Queue => '0', Name => 'Resolved in HTML', # loc Description => 'HTML Ticket Resolved', # loc Content => 'Subject: Resolved: {$Ticket->Subject} Content-Type: text/html <p>According to our records, your request has been resolved. If you have any further questions or concerns, please respond to this message.</p> ' }, { Queue => '___Approvals', Name => "New Pending Approval in HTML", # loc Description => "Notify Owners and AdminCcs of new items pending their approval", # loc Content => 'Subject: New Pending Approval: {$Ticket->Subject} Content-Type: text/html <p>Greetings,</p> <p>There is a new item pending your approval: <b>{$Ticket->Subject()}</b>, a summary of which appears below.</p> <p>Please <a href="{RT->Config->Get(\'WebURL\')}Approvals/Display.html?id={$Ticket->id}">approve or reject this ticket</a>, or visit the <a href="{RT->Config->Get(\'WebURL\')}Approvals/">approvals overview</a> to batch-process all your pending approvals.</p> <hr /> {$Transaction->Content()} ' }, { Queue => '___Approvals', Name => "Approval Passed in HTML", # loc Description => "Notify Requestor of their ticket has been approved by some approver", # loc Content => 'Subject: Ticket Approved: {$Ticket->Subject} Content-Type: text/html <p>Greetings,</p> <p>Your ticket has been approved by <b>{ eval { $Approver->Name } }</b>. Other approvals may be pending.</p> <p>Approver\'s notes:</p> <blockquote>{ $Notes }</blockquote> ' }, { Queue => '___Approvals', Name => "All Approvals Passed in HTML", # loc Description => "Notify Requestor of their ticket has been approved by all approvers", # loc Content => 'Subject: Ticket Approved: {$Ticket->Subject} Content-Type: text/html <p>Greetings,</p> <p>Your ticket has been approved by <b>{ eval { $Approver->Name } }</b>. Its Owner may now start to act on it.</p> <p>Approver\'s notes:</p> <blockquote>{ $Notes }</blockquote> ' }, { Queue => '___Approvals', Name => "Approval Rejected in HTML", # loc Description => "Notify Owner of their rejected ticket", # loc Content => 'Subject: Ticket Rejected: {$Ticket->Subject} Content-Type: text/html <p>Greetings,</p> <p>Your ticket has been rejected by <b>{ eval { $Approver->Name } }</b>.</p> <p>Approver\'s notes:</p> <blockquote>{ $Notes }</blockquote> ' }, { Queue => '___Approvals', Name => "Approval Ready for Owner in HTML", # loc Description => "Notify Owner of their ticket has been approved and is ready to be acted on", # loc Content => 'Subject: Ticket Approved: {$Ticket->Subject} Content-Type: text/html <p>Greetings,</p> <p>The ticket has been approved, you may now start to act on it.</p> ' }, );
{ "pile_set_name": "Github" }
======================================== GLib ======================================== .. contents:: 目錄 Memory Allocation ======================================== GLib 的 `Memory Allocation <https://developer.gnome.org/glib/unstable/glib-Memory-Allocation.html>`_ 相關處理都在 ``glib/gmem.h`` 和 ``glib/gmem.c`` , 大部分都是基於 C stdlib 的包裝, 多加些檢查和提供更方便的介面。 GLib 以前支援使用非系統的 allocator, 但是現在已經移除, 只會使用系統提供的 allocator。 以 malloc 為範例; * malloc - 直接分配特定大小的記憶體 * `g_malloc <https://github.com/GNOME/glib/blob/8a96fca3908609407f59c8f5be8de982a76114c1/glib/gmem.c#L93>`_ - 基於 malloc 多加了 log 和失敗檢查 * `g_malloc_n <https://github.com/GNOME/glib/blob/8a96fca3908609407f59c8f5be8de982a76114c1/glib/gmem.c#L331>`_ - 基於 g_malloc,參數包裝成「幾塊」和「每塊大小」 - 檢查 overflow * `_G_NEW <https://github.com/GNOME/glib/blob/8a96fca3908609407f59c8f5be8de982a76114c1/glib/gmem.h#L257>`_ - 基於 g_malloc_n,參數包裝成「型別」、「數量」、「使用的 allocator 名稱」 - ``_G_NEW`` 有另外優化的版本,如果可以在編譯時確定不會 overflow 的話就省去 ``_n`` 系列的函式呼叫 * `g_new <https://github.com/GNOME/glib/blob/8a96fca3908609407f59c8f5be8de982a76114c1/glib/gmem.h#L280>`_ - 基於 _G_NEW,參數包裝成「型別」、「數量」 .. code-block:: c // 使用 DATA_TYPE *mem = g_new(DATA_TYPE, COUNT); gint *newkey = g_new(gint, 1); guint **mema = g_new(guint*, n); char **foo = g_new(char*, 1); GSourceCallback* new_callback = g_new(GSourceCallback, 1); // g_new #define g_new(struct_type, n_structs) _G_NEW (struct_type, n_structs, malloc) // _G_NEW #define _G_NEW(struct_type, n_structs, func) ((struct_type *) g_##func##_n ((n_structs), sizeof (struct_type))) // g_malloc_n gpointer g_malloc_n (gsize n_blocks, gsize n_block_bytes) { if (SIZE_OVERFLOWS (n_blocks, n_block_bytes)) { g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes", G_STRLOC, n_blocks, n_block_bytes); } return g_malloc (n_blocks * n_block_bytes); } // g_malloc gpointer g_malloc (gsize n_bytes) { if (G_LIKELY (n_bytes)) { gpointer mem; mem = malloc (n_bytes); TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 0)); if (mem) return mem; g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes", G_STRLOC, n_bytes); } TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 0, 0)); return NULL; } // malloc // 系統 libc 實做 I/O ======================================== 參考 ======================================== * `GLib Reference Manual <https://developer.gnome.org/glib/unstable/>`_ * `Hackfests in the GNOME-related world <https://wiki.gnome.org/Hackfests>`_ * `Events - GNOME Wiki! <https://wiki.gnome.org/Events>`_ * `Planet GNOME <http://planet.gnome.org/>`_
{ "pile_set_name": "Github" }
#region License // ==================================================== // Project Porcupine Copyright(C) 2016 Team Porcupine // This program comes with ABSOLUTELY NO WARRANTY; This is free software, // and you are welcome to redistribute it under certain conditions; See // file LICENSE, which is part of this source code package, for details. // ==================================================== #endregion using System; using System.Collections; using System.IO; using System.Xml; using ICSharpCode.SharpZipLib.Zip; using UnityEngine; namespace ProjectPorcupine.Localization { /* , , / \/ \ (/ //_ \_ .-._ \|| . \ \ '-._ _,:__.-"/---\_ \ ______/___ '. .--------------------'~-'--.)__( , )\ \ `'--.___ _\ / | Here ,' \)|\ `\| /_.-' _\ \ _:,_ Be Dragons " || ( .'__ _.' \'-/,`-~` |/ '. ___.> /=,| Abandon hope all ye who enter | / .-'/_ ) '---------------------------------' )' ( /(/ \\ " '==' */ /// <summary> /// This class makes sure that your localization is up to date. It does that by comparing latest know commit hash /// (which is stored in Application.streamingAssetsPath/Localization/curr.ver) to the latest hash available through /// GitHub. If the hashes don't match or curr.ver doesn't exist a new zip containing /// localization will be downloaded from GitHub repo. Then, the zip is stored in the memory and waits for /// Application.streamingAssetsPath/Localization to be cleaned. When It's empty the zip gets unpacked and saved /// to hard drive using ICSharpCode.SharpZipLib.Zip library. Every GitHub zip download has a folder with /// *ProjectName*-*BranchName* so all of it's content needs to be moved to Application.streamingAssetsPath/Localization. /// After that the folder get's deleted and new curr.ver file is created containing latest hash. /// GitHub's branch name corresponds to World.current.gameVersion, so that the changes in localization /// for version 0.2 won't affect users who haven't updated yet from version 0.1. /// </summary> public static class LocalizationDownloader { // TODO: Change this to the official repo before PR. private static readonly string LocalizationRepositoryZipLocation = "https://github.com/QuiZr/ProjectPorcupineLocalization/archive/" + GameController.GameVersion + ".zip"; // TODO: Change this to the official repo before PR. private static readonly string LastCommitGithubApiLocation = "https://api.github.com/repos/QuiZr/ProjectPorcupineLocalization/commits/" + GameController.GameVersion; private static readonly string LocalizationFolderPath = Path.Combine(Application.streamingAssetsPath, "Localization"); // Object for downloading localization data from web. private static WWW www; /// <summary> /// Check if there are any new updates for localization. TODO: Add a choice for a user to not update it right now. /// </summary> public static IEnumerator CheckIfCurrentLocalizationIsUpToDate(Action onLocalizationDownloadedCallback) { string currentLocalizationVersion = GetLocalizationVersionFromConfig(); // Check the latest localization version through the GitHub API. WWW versionChecker = new WWW(LastCommitGithubApiLocation); // yield until API response is downloaded yield return versionChecker; if (string.IsNullOrEmpty(versionChecker.error) == false) { // This could be a thing when for example user has no internet connection. UnityDebugger.Debugger.LogError("LocalizationDownloader", "Error while checking for localization updates. Are you sure that you're connected to the internet?"); UnityDebugger.Debugger.LogError("LocalizationDownloader", versionChecker.error); yield break; } // Let's try to filter that response and get the latest hash from it. // There is a possibility that the versionChecker.text will be corrupted // (i.e. when you pull the Ethernet plug while downloading so thats why // a little try-catch block is there. string latestCommitHash = string.Empty; try { latestCommitHash = GetHashOfLastCommitFromAPIResponse(versionChecker.text); } catch (Exception e) { UnityDebugger.Debugger.LogError("LocalizationDownloader", e.Message); } if (latestCommitHash != currentLocalizationVersion) { // There are still some updates available. We should probably notify // user about it and offer him an option to download it right now. // For now... Let's just force it >.> Beginners task! UnityDebugger.Debugger.Log("LocalizationDownloader", "There is an update for localization files!"); yield return DownloadLocalizationFromWeb(onLocalizationDownloadedCallback); // Because config.xml exists in the new downloaded localization, we have to add the version element to it. try { string configPath = Path.Combine(LocalizationFolderPath, "config.xml"); XmlDocument document = new XmlDocument(); document.Load(configPath); XmlNode node = document.SelectSingleNode("//config"); XmlElement versionElement = document.CreateElement("version"); versionElement.SetAttribute("hash", latestCommitHash); node.InsertBefore(versionElement, document.SelectSingleNode("//languages")); document.Save(configPath); } catch (Exception e) { // Not a big deal: // Next time the LocalizationDownloader will force an update. UnityDebugger.Debugger.LogWarning("LocalizationDownloader", "Writing version in config.xml file failed: " + e.Message); throw; } } } // For now Unity's implementation of .net WebClient will do just fine, // especially that it doesn't have problems with downloading from https. private static IEnumerator DownloadLocalizationFromWeb(Action onLocalizationDownloadedCallback) { // If there were some files downloading previously (maybe user tried to download the newest // language pack and mashed a download button?) just cancel them and start a new one. if (www != null) { www.Dispose(); } UnityDebugger.Debugger.Log("LocalizationDownloader", "Localization files download has started"); www = new WWW(LocalizationRepositoryZipLocation); // Wait for www to download current localization files. yield return www; UnityDebugger.Debugger.Log("LocalizationDownloader", "Localization files download has finished!"); // Almost like a callback call OnDownloadLocalizationComplete(onLocalizationDownloadedCallback); } /// <summary> /// Callback for DownloadLocalizationFromWeb. /// It replaces current content of localizationFolderPath with fresh, downloaded one. /// </summary> private static void OnDownloadLocalizationComplete(Action onLocalizationDownloadedCallback) { if (www.isDone == false) { // This should never happen. UnityDebugger.Debugger.LogError("LocalizationDownloader", "OnDownloadLocalizationComplete got called before www finished downloading."); www.Dispose(); return; } if (string.IsNullOrEmpty(www.error) == false) { // This could be a thing when for example user has no internet connection. UnityDebugger.Debugger.LogError("LocalizationDownloader", "Error while downloading localizations files."); UnityDebugger.Debugger.LogError("LocalizationDownloader", www.error); return; } // Clean the Localization folder and return it's info. DirectoryInfo localizationFolderInfo = ClearLocalizationDirectory(); // Turn's out that System.IO.Compression.GZipStream is not working in unity: // http://forum.unity3d.com/threads/cant-use-gzipstream-from-c-behaviours.33973/ // So I need to use some sort of 3rd party solution. // Convert array of downloaded bytes to stream. using (ZipInputStream zipReadStream = new ZipInputStream(new MemoryStream(www.bytes))) { // Unpack zip to the hard drive. ZipEntry theEntry; // While there are still files inside zip archive. while ((theEntry = zipReadStream.GetNextEntry()) != null) { string directoryName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); // If there was a subfolder in zip (which there probably is) create one. if (string.IsNullOrEmpty(directoryName) == false) { string directoryFullPath = Path.Combine(LocalizationFolderPath, directoryName); if (Directory.Exists(directoryFullPath) == false) { Directory.CreateDirectory(directoryFullPath); } } // Read files from stream to files on HDD. // 2048 buffer should be plenty. if (string.IsNullOrEmpty(fileName) == false && !fileName.StartsWith("en_US.lang")) { string fullFilePath = Path.Combine(LocalizationFolderPath, theEntry.Name); using (FileStream fileWriter = File.Create(fullFilePath)) { int size = 2048; byte[] fdata = new byte[2048]; while (true) { size = zipReadStream.Read(fdata, 0, fdata.Length); if (size > 0) { fileWriter.Write(fdata, 0, size); } else { break; } } } } } } // At this point we should have an subfolder in Application.streamingAssetsPath/Localization // called ProjectPorcupineLocalization-*branch name*. Now we need to move all files from that directory // to Application.streamingAssetsPath/Localization. FileInfo[] fileInfo = localizationFolderInfo.GetFiles(); foreach (FileInfo file in fileInfo) { if (file.Name != "en_US.lang" && file.Name != "en_US.lang.meta") { UnityDebugger.Debugger.LogError("LocalizationDownloader", "There should only be en_US.lang and en_US.lang.meta. Instead there is: " + file.Name); } } DirectoryInfo[] dirInfo = localizationFolderInfo.GetDirectories(); if (dirInfo.Length > 1) { UnityDebugger.Debugger.LogError("LocalizationDownloader", "There should be only one directory"); } // Move files from ProjectPorcupineLocalization-*branch name* to Application.streamingAssetsPath/Localization. string[] filesToMove = Directory.GetFiles(dirInfo[0].FullName); foreach (string file in filesToMove) { string fileName = Path.GetFileName(file); string destFile = Path.Combine(LocalizationFolderPath, fileName); File.Copy(file, destFile, true); File.Delete(file); } // Remove ProjectPorcupineLocalization-*branch name* Directory.Delete(dirInfo[0].FullName); UnityDebugger.Debugger.Log("LocalizationDownloader", "New localization files successfully downloaded!"); onLocalizationDownloadedCallback(); } private static DirectoryInfo ClearLocalizationDirectory() { DirectoryInfo localizationFolderInfo = new DirectoryInfo(LocalizationFolderPath); foreach (FileInfo file in localizationFolderInfo.GetFiles()) { // If there are files without that extension then: // a) someone made a change to localization system and didn't update this // b) We are in a wrong directory, so let's hope we didn't delete anything important. if (file.Extension != ".lang" && file.Extension != ".meta" && file.Extension != ".ver" && file.Extension != ".md" && file.Name != "config.xml") { UnityDebugger.Debugger.LogError("LocalizationDownloader", "SOMETHING WENT HORRIBLY WRONG AT DOWNLOADING LOCALIZATION!"); throw new Exception("SOMETHING WENT HORRIBLY WRONG AT DOWNLOADING LOCALIZATION!"); } if (file.Name != "en_US.lang" && file.Name != "en_US.lang.meta") { file.Delete(); } } foreach (DirectoryInfo dir in localizationFolderInfo.GetDirectories()) { dir.Delete(); } return localizationFolderInfo; } /// <summary> /// Reads Application.streamingAssetsPath/Localization/config.xml making sure that Localization folder exists. /// </summary> private static string GetLocalizationVersionFromConfig() { string localizationConfigFilePath = Path.Combine(LocalizationFolderPath, "config.xml"); string currentLocalizationVersion = null; try { XmlReader reader = XmlReader.Create(localizationConfigFilePath); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "version") { if (reader.HasAttributes) { currentLocalizationVersion = reader.GetAttribute("hash"); break; } } } reader.Close(); } catch (FileNotFoundException) { // It's fine - we will create that file later. UnityDebugger.Debugger.Log("LocalizationDownloader", localizationConfigFilePath + " file not found, forcing an update."); } catch (DirectoryNotFoundException) { // This is probably first launch of the game. UnityDebugger.Debugger.Log("LocalizationDownloader", LocalizationFolderPath + " folder not found, creating..."); try { Directory.CreateDirectory(LocalizationFolderPath); } catch (Exception e) { // If any exception happen here then we don't have a Localization folder in place // so we can just throw - we won't do anything good here. throw e; } } catch (Exception e) { // i.e. UnauthorizedAccessException, NotSupportedException or UnauthorizedAccessException. // Those should never happen and if they do something is really fucked up so we should // probably start a fire, call 911 or at least throw an exception. throw e; } return currentLocalizationVersion; } /// <summary> /// This is a really wonky way of parsing JSON. I didn't want to include something like /// Json.NET library purely for this functionality but if we will be using it somewhere else /// this need to change. DO NOT TOUCH and this will be fine. /// </summary> /// <param name="githubApiResponse">GitHub API response.</param> /// <returns></returns> private static string GetHashOfLastCommitFromAPIResponse(string githubApiResponse) { if (string.IsNullOrEmpty(githubApiResponse)) { throw new ArgumentNullException("githubApiResponse"); } string hashSearchPattern = "sha\":\""; // Index of the first char of hash. int index = githubApiResponse.IndexOf(hashSearchPattern); if (index == -1) { // Either the response was damaged or GitHub API returned an error. throw new Exception("Error at parsing JSON - sha\":\" not found."); } // hashSearchPattern length index += 6; // + 1 for that while loop first run. if (index + 1 >= githubApiResponse.Length - 1) { // Either the response was damaged or GitHub API returned an error. throw new Exception("Error at parsing JSON - githubApiResponse too short."); } char currentChar = githubApiResponse[index]; // Hash of the commit. string hash = string.Empty; // Get the commit hash do { hash += currentChar; index++; currentChar = githubApiResponse[index]; // Check if this is the end of the commit string. if (index + 1 == githubApiResponse.Length - 1) { // Either the response was damaged or GitHub API returned an error. throw new Exception("Error at parsing JSON - hash closing tag not found."); } } while (currentChar != '\"'); return hash; } } }
{ "pile_set_name": "Github" }
```scratch crwdns8484:0[1]crwdnd8484:0[1]crwdne8484:0 ```
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <UIKit/UIButton.h> @class UIColor, UIView; @interface HUQuickControlCircleButton : UIButton { UIColor *_selectedColor; UIView *_backgroundView; UIColor *_standardBackgroundColor; } - (void).cxx_destruct; @property(retain, nonatomic) UIColor *standardBackgroundColor; // @synthesize standardBackgroundColor=_standardBackgroundColor; @property(retain, nonatomic) UIView *backgroundView; // @synthesize backgroundView=_backgroundView; @property(retain, nonatomic) UIColor *selectedColor; // @synthesize selectedColor=_selectedColor; - (void)layoutSubviews; - (void)_controlStateChanged; - (void)_adjustTitleColor; - (void)setHighlighted:(BOOL)arg1; - (void)setEnabled:(BOOL)arg1; @property(nonatomic) double fontSize; - (id)initWithFrame:(struct CGRect)arg1; @end
{ "pile_set_name": "Github" }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Bentley Systems, Incorporated. All rights reserved. * See LICENSE.md in the project root for license terms and full copyright notice. *--------------------------------------------------------------------------------------------*/ import { expect } from "chai"; import * as faker from "faker"; import * as sinon from "sinon"; import * as moq from "typemoq"; import { Id64String } from "@bentley/bentleyjs-core"; import { IModelRpcProps, RpcInterface, RpcInterfaceDefinition, RpcManager } from "@bentley/imodeljs-common"; import { ContentRequestOptions, DescriptorJSON, DistinctValuesRpcRequestOptions, HierarchyRequestOptions, KeySet, KeySetJSON, Paged, PartialHierarchyModificationJSON, PresentationError, PresentationRpcInterface, PresentationRpcRequestOptions, PresentationRpcResponse, PresentationStatus, RpcRequestsHandler, SelectionInfo, SelectionScopeRequestOptions, } from "../presentation-common"; import { FieldDescriptorType } from "../presentation-common/content/Fields"; import { ItemJSON } from "../presentation-common/content/Item"; import { InstanceKeyJSON } from "../presentation-common/EC"; import { NodeKey, NodeKeyJSON } from "../presentation-common/hierarchy/Key"; import { ContentDescriptorRequestOptions, DisplayLabelRequestOptions, DisplayLabelsRequestOptions, DistinctValuesRequestOptions, ExtendedContentRequestOptions, ExtendedHierarchyRequestOptions, PresentationDataCompareOptions, } from "../presentation-common/PresentationManagerOptions"; import { ContentDescriptorRpcRequestOptions, DisplayLabelRpcRequestOptions, DisplayLabelsRpcRequestOptions, ExtendedContentRpcRequestOptions, ExtendedHierarchyRpcRequestOptions, PresentationDataCompareRpcOptions, } from "../presentation-common/PresentationRpcInterface"; import { createRandomDescriptorJSON, createRandomECInstanceKeyJSON, createRandomECInstancesNodeJSON, createRandomECInstancesNodeKeyJSON, createRandomLabelDefinitionJSON, createRandomNodePathElementJSON, createRandomSelectionScope, } from "./_helpers/random"; describe("RpcRequestsHandler", () => { let clientId: string; let defaultRpcHandlerOptions: { imodel: IModelRpcProps }; const token: IModelRpcProps = { key: "test", iModelId: "test", contextId: "test" }; const successResponse = async <TResult>(result: TResult): PresentationRpcResponse<TResult> => ({ statusCode: PresentationStatus.Success, result }); const errorResponse = async (statusCode: PresentationStatus, errorMessage?: string): PresentationRpcResponse => ({ statusCode, errorMessage, result: undefined }); beforeEach(() => { clientId = faker.random.uuid(); defaultRpcHandlerOptions = { imodel: token }; }); describe("construction", () => { let handler: RpcRequestsHandler; afterEach(() => { if (handler) handler.dispose(); }); it("uses client id specified through props", () => { handler = new RpcRequestsHandler({ clientId }); expect(handler.clientId).to.eq(clientId); }); it("creates a client if not specified through props", () => { handler = new RpcRequestsHandler(); expect(handler.clientId).to.not.be.empty; }); }); describe("request", () => { let handler: RpcRequestsHandler; beforeEach(() => { handler = new RpcRequestsHandler(); }); afterEach(() => { handler.dispose(); }); describe("when request succeeds", () => { it("returns result of the request", async () => { const result = faker.random.number(); const actualResult = await handler.request(undefined, async () => successResponse(result), defaultRpcHandlerOptions); expect(actualResult).to.eq(result); }); }); describe("when request throws unknown exception", () => { it("re-throws exception when request throws unknown exception", async () => { const func = async () => { throw new Error("test"); }; await expect(handler.request(undefined, func, defaultRpcHandlerOptions)).to.eventually.be.rejectedWith(Error); }); }); describe("when request returns an unexpected status", () => { it("throws an exception", async () => { const func = async () => errorResponse(PresentationStatus.Error); await expect(handler.request(undefined, func, defaultRpcHandlerOptions)).to.eventually.be.rejectedWith(PresentationError); }); }); describe("when request returns a status of BackendTimeout", () => { it("returns PresentationError", async () => { const func = async () => errorResponse(PresentationStatus.BackendTimeout); await expect(handler.request(undefined, func, defaultRpcHandlerOptions)).to.eventually.be.rejectedWith(PresentationError).and.has.property("errorNumber", 65543); }); it("calls request handler 10 times", async () => { const requestHandlerStub = sinon.stub(); requestHandlerStub.returns(Promise.resolve(errorResponse(PresentationStatus.BackendTimeout))); const requestHandlerSpy = sinon.spy(() => requestHandlerStub()); await expect(handler.request(undefined, requestHandlerSpy, defaultRpcHandlerOptions)).to.eventually.be.rejectedWith(PresentationError); expect(requestHandlerSpy.callCount).to.be.equal(10); }); }); }); describe("requests forwarding to PresentationRpcInterface", () => { let handler: RpcRequestsHandler; let rpcInterfaceMock: moq.IMock<PresentationRpcInterface>; let defaultGetClientForInterfaceImpl: <T extends RpcInterface>(def: RpcInterfaceDefinition<T>) => T; before(() => { rpcInterfaceMock = moq.Mock.ofType<PresentationRpcInterface>(); defaultGetClientForInterfaceImpl = RpcManager.getClientForInterface; RpcManager.getClientForInterface = (() => rpcInterfaceMock.object) as any; }); after(() => { RpcManager.getClientForInterface = defaultGetClientForInterfaceImpl; }); beforeEach(() => { handler = new RpcRequestsHandler({ clientId }); rpcInterfaceMock.reset(); }); afterEach(() => { handler.dispose(); }); it("forwards getNodesCount call for root nodes", async () => { const handlerOptions: ExtendedHierarchyRequestOptions<IModelRpcProps, NodeKeyJSON> = { imodel: token, rulesetOrId: faker.random.word(), }; const rpcOptions: ExtendedHierarchyRpcRequestOptions = { clientId, rulesetOrId: handlerOptions.rulesetOrId, }; const result = faker.random.number(); rpcInterfaceMock .setup(async (x) => x.getNodesCount(token, rpcOptions)) .returns(async () => successResponse(result)).verifiable(); expect(await handler.getNodesCount(handlerOptions)).to.eq(result); rpcInterfaceMock.verifyAll(); }); it("forwards getNodesCount call for child nodes", async () => { const handlerOptions: ExtendedHierarchyRequestOptions<IModelRpcProps, NodeKeyJSON> = { imodel: token, rulesetOrId: faker.random.word(), parentKey: createRandomECInstancesNodeKeyJSON(), }; const rpcOptions: PresentationRpcRequestOptions<ExtendedHierarchyRequestOptions<any, NodeKeyJSON>> = { clientId, rulesetOrId: handlerOptions.rulesetOrId, parentKey: handlerOptions.parentKey, }; const result = faker.random.number(); rpcInterfaceMock .setup(async (x) => x.getNodesCount(token, rpcOptions)) .returns(async () => successResponse(result)).verifiable(); expect(await handler.getNodesCount(handlerOptions)).to.eq(result); rpcInterfaceMock.verifyAll(); }); it("forwards getPagedNodes call", async () => { const handlerOptions: Paged<ExtendedHierarchyRequestOptions<IModelRpcProps, NodeKeyJSON>> = { imodel: token, rulesetOrId: faker.random.word(), paging: { start: 1, size: 2 }, parentKey: createRandomECInstancesNodeKeyJSON(), }; const rpcOptions: PresentationRpcRequestOptions<Paged<ExtendedHierarchyRequestOptions<any, NodeKeyJSON>>> = { clientId, rulesetOrId: handlerOptions.rulesetOrId, paging: { start: 1, size: 2 }, parentKey: NodeKey.fromJSON(handlerOptions.parentKey!), }; const result = { items: [createRandomECInstancesNodeJSON()], total: 1 }; rpcInterfaceMock .setup(async (x) => x.getPagedNodes(token, rpcOptions)) .returns(async () => successResponse(result)).verifiable(); expect(await handler.getPagedNodes(handlerOptions)).to.eq(result); rpcInterfaceMock.verifyAll(); }); it("forwards getFilteredNodePaths call", async () => { const handlerOptions: HierarchyRequestOptions<IModelRpcProps> = { imodel: token, rulesetOrId: faker.random.word(), }; const rpcOptions: PresentationRpcRequestOptions<HierarchyRequestOptions<any>> = { clientId, rulesetOrId: handlerOptions.rulesetOrId, }; const filter = faker.random.word(); const result = [createRandomNodePathElementJSON()]; rpcInterfaceMock .setup(async (x) => x.getFilteredNodePaths(token, rpcOptions, filter)) .returns(async () => successResponse(result)).verifiable(); expect(await handler.getFilteredNodePaths(handlerOptions, filter)).to.eq(result); rpcInterfaceMock.verifyAll(); }); it("forwards getNodePaths call", async () => { const handlerOptions: HierarchyRequestOptions<IModelRpcProps> = { imodel: token, rulesetOrId: faker.random.word(), }; const rpcOptions: PresentationRpcRequestOptions<HierarchyRequestOptions<any>> = { clientId, rulesetOrId: handlerOptions.rulesetOrId, }; const paths = [[createRandomECInstanceKeyJSON()]]; const markedIndex = faker.random.number(); const result = [createRandomNodePathElementJSON()]; rpcInterfaceMock .setup(async (x) => x.getNodePaths(token, rpcOptions, paths, markedIndex)) .returns(async () => successResponse(result)).verifiable(); expect(await handler.getNodePaths(handlerOptions, paths, markedIndex)).to.eq(result); rpcInterfaceMock.verifyAll(); }); it("forwards loadHierarchy call", async () => { const handlerOptions: HierarchyRequestOptions<IModelRpcProps> = { imodel: token, rulesetOrId: faker.random.word(), }; const rpcOptions: PresentationRpcRequestOptions<HierarchyRequestOptions<any>> = { clientId, rulesetOrId: handlerOptions.rulesetOrId, }; rpcInterfaceMock .setup(async (x) => x.loadHierarchy(token, rpcOptions)) .returns(async () => successResponse(undefined)).verifiable(); await handler.loadHierarchy(handlerOptions); rpcInterfaceMock.verifyAll(); }); it("forwards getContentDescriptor call", async () => { const displayType = faker.random.word(); const keys = new KeySet().toJSON(); const selectionInfo: SelectionInfo = { providerName: faker.random.word() }; const handlerOptions: ContentDescriptorRequestOptions<IModelRpcProps, KeySetJSON> = { imodel: token, rulesetOrId: faker.random.word(), displayType, keys, selection: selectionInfo, }; const rpcOptions: ContentDescriptorRpcRequestOptions = { clientId, rulesetOrId: handlerOptions.rulesetOrId, displayType, keys, selection: selectionInfo, }; const result = createRandomDescriptorJSON(); rpcInterfaceMock.setup(async (x) => x.getContentDescriptor(token, rpcOptions)).returns(async () => successResponse(result)).verifiable(); expect(await handler.getContentDescriptor(handlerOptions)).to.eq(result); rpcInterfaceMock.verifyAll(); }); it("forwards getContentSetSize call", async () => { const descriptor = createRandomDescriptorJSON(); const keys = new KeySet().toJSON(); const result = faker.random.number(); const handlerOptions: ExtendedContentRequestOptions<IModelRpcProps, DescriptorJSON, KeySetJSON> = { imodel: token, rulesetOrId: faker.random.word(), descriptor, keys, }; const rpcOptions: ExtendedContentRpcRequestOptions = { clientId, rulesetOrId: handlerOptions.rulesetOrId, descriptor, keys, }; rpcInterfaceMock.setup(async (x) => x.getContentSetSize(token, rpcOptions)).returns(async () => successResponse(result)).verifiable(); expect(await handler.getContentSetSize(handlerOptions)).to.eq(result); rpcInterfaceMock.verifyAll(); }); it("forwards getPagedContent call", async () => { const descriptor = createRandomDescriptorJSON(); const keys = new KeySet().toJSON(); const result = { descriptor: createRandomDescriptorJSON(), contentSet: { total: 123, items: new Array<ItemJSON>(), }, }; const handlerOptions: Paged<ExtendedContentRequestOptions<IModelRpcProps, DescriptorJSON, KeySetJSON>> = { imodel: token, rulesetOrId: faker.random.word(), descriptor, keys, paging: { start: 1, size: 2 }, }; const rpcOptions: Paged<ExtendedContentRpcRequestOptions> = { clientId, rulesetOrId: handlerOptions.rulesetOrId, descriptor, keys, paging: { start: 1, size: 2 }, }; rpcInterfaceMock.setup(async (x) => x.getPagedContent(token, rpcOptions)).returns(async () => successResponse(result)).verifiable(); expect(await handler.getPagedContent(handlerOptions)).to.eq(result); rpcInterfaceMock.verifyAll(); }); it("forwards getPagedContentSet call", async () => { const descriptor = createRandomDescriptorJSON(); const keys = new KeySet().toJSON(); const result = { total: 123, items: new Array<ItemJSON>(), }; const handlerOptions: Paged<ExtendedContentRequestOptions<IModelRpcProps, DescriptorJSON, KeySetJSON>> = { imodel: token, rulesetOrId: faker.random.word(), descriptor, keys, paging: { start: 1, size: 2 }, }; const rpcOptions: Paged<ExtendedContentRpcRequestOptions> = { clientId, rulesetOrId: handlerOptions.rulesetOrId, descriptor, keys, paging: { start: 1, size: 2 }, }; rpcInterfaceMock.setup(async (x) => x.getPagedContentSet(token, rpcOptions)).returns(async () => successResponse(result)).verifiable(); expect(await handler.getPagedContentSet(handlerOptions)).to.eq(result); rpcInterfaceMock.verifyAll(); }); it("forwards getDistinctValues call", async () => { const handlerOptions: ContentRequestOptions<IModelRpcProps> = { imodel: token, rulesetOrId: faker.random.word(), }; const rpcOptions: PresentationRpcRequestOptions<ContentRequestOptions<any>> = { clientId, rulesetOrId: handlerOptions.rulesetOrId, }; const descriptor = createRandomDescriptorJSON(); const keys = new KeySet().toJSON(); const fieldName = faker.random.word(); const maxItems = faker.random.number(); const result = [faker.random.word()]; rpcInterfaceMock.setup(async (x) => x.getDistinctValues(token, rpcOptions, descriptor, keys, fieldName, maxItems)).returns(async () => successResponse(result)).verifiable(); expect(await handler.getDistinctValues(handlerOptions, descriptor, keys, fieldName, maxItems)).to.eq(result); rpcInterfaceMock.verifyAll(); }); it("forwards getPagedDistinctValues call", async () => { const handlerOptions: DistinctValuesRequestOptions<IModelRpcProps, DescriptorJSON, KeySetJSON> = { imodel: token, rulesetOrId: faker.random.word(), descriptor: createRandomDescriptorJSON(), keys: new KeySet().toJSON(), fieldDescriptor: { type: FieldDescriptorType.Name, fieldName: "test", }, }; const rpcOptions: DistinctValuesRpcRequestOptions = { clientId, rulesetOrId: handlerOptions.rulesetOrId, descriptor: handlerOptions.descriptor, keys: new KeySet().toJSON(), fieldDescriptor: { type: FieldDescriptorType.Name, fieldName: "test", }, }; const result = { total: 2, items: [{ displayValue: "1", groupedRawValues: [1.1, 1.2], }, { displayValue: "2", groupedRawValues: [2], }], }; rpcInterfaceMock.setup(async (x) => x.getPagedDistinctValues(token, rpcOptions)).returns(async () => successResponse(result)).verifiable(); expect(await handler.getPagedDistinctValues(handlerOptions)).to.eq(result); rpcInterfaceMock.verifyAll(); }); it("forwards getDisplayLabelDefinition call", async () => { const key = createRandomECInstanceKeyJSON(); const handlerOptions: DisplayLabelRequestOptions<IModelRpcProps, InstanceKeyJSON> = { imodel: token, key, }; const rpcOptions: DisplayLabelRpcRequestOptions = { clientId, key, }; const result = createRandomLabelDefinitionJSON(); rpcInterfaceMock.setup(async (x) => x.getDisplayLabelDefinition(token, rpcOptions)).returns(async () => successResponse(result)).verifiable(); expect(await handler.getDisplayLabelDefinition(handlerOptions)).to.deep.eq(result); rpcInterfaceMock.verifyAll(); }); it("forwards getPagedDisplayLabelDefinitions call", async () => { const keys = [createRandomECInstanceKeyJSON(), createRandomECInstanceKeyJSON()]; const handlerOptions: DisplayLabelsRequestOptions<IModelRpcProps, InstanceKeyJSON> = { imodel: token, keys, }; const rpcOptions: DisplayLabelsRpcRequestOptions = { clientId, keys, }; const result = { total: 2, items: [createRandomLabelDefinitionJSON(), createRandomLabelDefinitionJSON()], }; rpcInterfaceMock.setup(async (x) => x.getPagedDisplayLabelDefinitions(token, rpcOptions)).returns(async () => successResponse(result)).verifiable(); expect(await handler.getPagedDisplayLabelDefinitions(handlerOptions)).to.deep.eq(result); rpcInterfaceMock.verifyAll(); }); it("forwards getSelectionScopes call", async () => { const handlerOptions: SelectionScopeRequestOptions<IModelRpcProps> = { imodel: token, }; const rpcOptions: PresentationRpcRequestOptions<SelectionScopeRequestOptions<any>> = { clientId, }; const result = [createRandomSelectionScope()]; rpcInterfaceMock.setup(async (x) => x.getSelectionScopes(token, rpcOptions)).returns(async () => successResponse(result)).verifiable(); expect(await handler.getSelectionScopes(handlerOptions)).to.eq(result); rpcInterfaceMock.verifyAll(); }); it("forwards computeSelection call", async () => { const handlerOptions: SelectionScopeRequestOptions<IModelRpcProps> = { imodel: token, }; const rpcOptions: PresentationRpcRequestOptions<SelectionScopeRequestOptions<any>> = { clientId, }; const ids = new Array<Id64String>(); const scopeId = faker.random.uuid(); const result = new KeySet().toJSON(); rpcInterfaceMock.setup(async (x) => x.computeSelection(token, rpcOptions, ids, scopeId)).returns(async () => successResponse(result)).verifiable(); expect(await handler.computeSelection(handlerOptions, ids, scopeId)).to.eq(result); rpcInterfaceMock.verifyAll(); }); it("forwards compareHierarchies call", async () => { const handlerOptions: PresentationDataCompareOptions<IModelRpcProps, NodeKeyJSON> = { imodel: token, prev: { rulesetOrId: "test1", }, rulesetOrId: "test2", expandedNodeKeys: [createRandomECInstancesNodeKeyJSON()], }; const rpcOptions: PresentationDataCompareRpcOptions = { clientId, prev: { rulesetOrId: "test1", }, rulesetOrId: "test2", expandedNodeKeys: [...handlerOptions.expandedNodeKeys!], }; const result = new Array<PartialHierarchyModificationJSON>(); rpcInterfaceMock.setup(async (x) => x.compareHierarchies(token, rpcOptions)).returns(async () => successResponse(result)).verifiable(); expect(await handler.compareHierarchies(handlerOptions)).to.eq(result); rpcInterfaceMock.verifyAll(); }); }); });
{ "pile_set_name": "Github" }
/* @generated */ digraph cfg { "main.fad58de7366495db4650cfefac2fcd61_1" [label="1: Start main\nFormals: \nLocals: honda:Car* \n " color=yellow style=filled] "main.fad58de7366495db4650cfefac2fcd61_1" -> "main.fad58de7366495db4650cfefac2fcd61_6" ; "main.fad58de7366495db4650cfefac2fcd61_2" [label="2: Exit main \n " color=yellow style=filled] "main.fad58de7366495db4650cfefac2fcd61_3" [label="3: Return Stmt \n *&return:int=0 [line 14, column 3]\n " shape="box"] "main.fad58de7366495db4650cfefac2fcd61_3" -> "main.fad58de7366495db4650cfefac2fcd61_2" ; "main.fad58de7366495db4650cfefac2fcd61_4" [label="4: Call _fun_NSLog \n n$0=_fun_NSString.stringWithUTF8String:(\"%d\":char* const ) [line 13, column 9]\n n$1=*&honda:Car* [line 13, column 16]\n n$2=_fun_Car.running(n$1:Car*) [line 13, column 22]\n n$3=_fun_NSLog(n$0:objc_object*,n$2:int) [line 13, column 3]\n " shape="box"] "main.fad58de7366495db4650cfefac2fcd61_4" -> "main.fad58de7366495db4650cfefac2fcd61_3" ; "main.fad58de7366495db4650cfefac2fcd61_5" [label="5: Message Call: setRunning: \n n$4=*&honda:Car* [line 12, column 3]\n n$5=_fun_Car.setRunning:(n$4:Car*,1:_Bool) [line 12, column 9]\n " shape="box"] "main.fad58de7366495db4650cfefac2fcd61_5" -> "main.fad58de7366495db4650cfefac2fcd61_4" ; "main.fad58de7366495db4650cfefac2fcd61_6" [label="6: DeclStmt \n VARIABLE_DECLARED(honda:Car*); [line 11, column 3]\n n$6=_fun___objc_alloc_no_fail(sizeof(t=Car):unsigned long) [line 11, column 17]\n n$7=_fun_NSObject.init(n$6:Car*) virtual [line 11, column 16]\n *&honda:Car*=n$7 [line 11, column 3]\n " shape="box"] "main.fad58de7366495db4650cfefac2fcd61_6" -> "main.fad58de7366495db4650cfefac2fcd61_5" ; }
{ "pile_set_name": "Github" }
console.log('WebComponents2')
{ "pile_set_name": "Github" }
#list of ScriptEngineFactory's in this package #org.red5.server.script.rhino.RhinoScriptEngineFactory #javascript com.sun.script.jruby.JRubyScriptEngineFactory com.sun.script.jython.JythonScriptEngineFactory com.sun.script.groovy.GroovyScriptEngineFactory
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <AppleLDAP/NSObject-Protocol.h> @protocol OS_ldap_connection <NSObject> @end
{ "pile_set_name": "Github" }
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License");; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <list> #include "pybind11/pybind11.h" namespace py = pybind11; class MemoryCheckerTestHelper { public: void ListPushBack(int x) { list_.push_back(x); } private: std::list<int> list_; }; PYBIND11_MODULE(_memory_checker_test_helper, m) { py::class_<MemoryCheckerTestHelper>(m, "MemoryCheckerTestHelper") .def(py::init()) .def("list_push_back", &MemoryCheckerTestHelper::ListPushBack); };
{ "pile_set_name": "Github" }
## Version 8.0 beta This new major release is quite a big overhaul bringing both new features and some backwards incompatible changes. However, chances are that the majority of users won't be affected by the latter: the basic scenario described in the README is left intact. Here's what did change in an incompatible way: - We're now prefixing all classes located in [CSS classes reference][cr] with `hljs-`, by default, because some class names would collide with other people's stylesheets. If you were using an older version, you might still want the previous behavior, but still want to upgrade. To suppress this new behavior, you would initialize like so: ```html <script type="text/javascript"> hljs.configure({classPrefix: ''}); hljs.initHighlightingOnLoad(); </script> ``` - `tabReplace` and `useBR` that were used in different places are also unified into the global options object and are to be set using `configure(options)`. This function is documented in our [API docs][]. Also note that these parameters are gone from `highlightBlock` and `fixMarkup` which are now also rely on `configure`. - We removed public-facing (though undocumented) object `hljs.LANGUAGES` which was used to register languages with the library in favor of two new methods: `registerLanguage` and `getLanguage`. Both are documented in our [API docs][]. - Result returned from `highlight` and `highlightAuto` no longer contains two separate attributes contributing to relevance score, `relevance` and `keyword_count`. They are now unified in `relevance`. Another technically compatible change that nonetheless might need attention: - The structure of the NPM package was refactored, so if you had installed it locally, you'll have to update your paths. The usual `require('highlight.js')` works as before. This is contributed by [Dmitry Smolin][]. New features: - Languages now can be recognized by multiple names like "js" for JavaScript or "html" for, well, HTML (which earlier insisted on calling it "xml"). These aliases can be specified in the class attribute of the code container in your HTML as well as in various API calls. For now there are only a few very common aliases but we'll expand it in the future. All of them are listed in the [class reference][]. - Language detection can now be restricted to a subset of languages relevant in a given context — a web page or even a single highlighting call. This is especially useful for node.js build that includes all the known languages. Another example is a StackOverflow-style site where users specify languages as tags rather than in the markdown-formatted code snippets. This is documented in the [API reference][] (see methods `highlightAuto` and `configure`). - Language definition syntax streamlined with [variants][] and [beginKeywords][]. New languages and styles: - *Oxygene* by [Carlo Kok][] - *Mathematica* by [Daniel Kvasnička][] - *Autohotkey* by [Seongwon Lee][] - *Atelier* family of styles in 10 variants by [Bram de Haan][] - *Paraíso* styles by [Jan T. Sott][] Miscelleanous improvements: - Highlighting `=>` prompts in Clojure. - [Jeremy Hull][] fixed a lot of styles for consistency. - Finally, highlighting PHP and HTML [mixed in peculiar ways][php-html]. - Objective C and C# now properly highlight titles in method definition. - Big overhaul of relevance counting for a number of languages. Please do report bugs about mis-detection of non-trivial code snippets! [cr]: http://highlightjs.readthedocs.org/en/latest/css-classes-reference.html [api docs]: http://highlightjs.readthedocs.org/en/latest/api.html [variants]: https://groups.google.com/d/topic/highlightjs/VoGC9-1p5vk/discussion [beginKeywords]: https://github.com/isagalaev/highlight.js/commit/6c7fdea002eb3949577a85b3f7930137c7c3038d [php-html]: https://twitter.com/highlightjs/status/408890903017689088 [Carlo Kok]: https://github.com/carlokok [Bram de Haan]: https://github.com/atelierbram [Daniel Kvasnička]: https://github.com/dkvasnicka [Dmitry Smolin]: https://github.com/dimsmol [Jeremy Hull]: https://github.com/sourrust [Seongwon Lee]: https://github.com/dlimpid [Jan T. Sott]: https://github.com/idleberg ## Version 7.5 A catch-up release dealing with some of the accumulated contributions. This one is probably will be the last before the 8.0 which will be slightly backwards incompatible regarding some advanced use-cases. One outstanding change in this version is the addition of 6 languages to the [hosted script][d]: Markdown, ObjectiveC, CoffeeScript, Apache, Nginx and Makefile. It now weighs about 6K more but we're going to keep it under 30K. New languages: - OCaml by [Mehdi Dogguy][mehdid] and [Nicolas Braud-Santoni][nbraud] - [LiveCode Server][lcs] by [Ralf Bitter][revig] - Scilab by [Sylvestre Ledru][sylvestre] - basic support for Makefile by [Ivan Sagalaev][isagalaev] Improvements: - Ruby's got support for characters like `?A`, `?1`, `?\012` etc. and `%r{..}` regexps. - Clojure now allows a function call in the beginning of s-expressions `(($filter "myCount") (arr 1 2 3 4 5))`. - Haskell's got new keywords and now recognizes more things like pragmas, preprocessors, modules, containers, FFIs etc. Thanks to [Zena Treep][treep] for the implementation and to [Jeremy Hull][sourrust] for guiding it. - Miscelleanous fixes in PHP, Brainfuck, SCSS, Asciidoc, CMake, Python and F#. [mehdid]: https://github.com/mehdid [nbraud]: https://github.com/nbraud [revig]: https://github.com/revig [lcs]: http://livecode.com/developers/guides/server/ [sylvestre]: https://github.com/sylvestre [isagalaev]: https://github.com/isagalaev [treep]: https://github.com/treep [sourrust]: https://github.com/sourrust [d]: http://highlightjs.org/download/ ## New core developers The latest long period of almost complete inactivity in the project coincided with growing interest to it led to a decision that now seems completely obvious: we need more core developers. So without further ado let me welcome to the core team two long-time contributors: [Jeremy Hull][] and [Oleg Efimov][]. Hope now we'll be able to work through stuff faster! P.S. The historical commit is [here][1] for the record. [Jeremy Hull]: https://github.com/sourrust [Oleg Efimov]: https://github.com/sannis [1]: https://github.com/isagalaev/highlight.js/commit/f3056941bda56d2b72276b97bc0dd5f230f2473f ## Version 7.4 This long overdue version is a snapshot of the current source tree with all the changes that happened during the past year. Sorry for taking so long! Along with the changes in code highlight.js has finally got its new home at <http://highlightjs.org/>, moving from its craddle on Software Maniacs which it outgrew a long time ago. Be sure to report any bugs about the site to <mailto:[email protected]>. On to what's new… New languages: - Handlebars templates by [Robin Ward][] - Oracle Rules Language by [Jason Jacobson][] - F# by [Joans Follesø][] - AsciiDoc and Haml by [Dan Allen][] - Lasso by [Eric Knibbe][] - SCSS by [Kurt Emch][] - VB.NET by [Poren Chiang][] - Mizar by [Kelley van Evert][] [Robin Ward]: https://github.com/eviltrout [Jason Jacobson]: https://github.com/jayce7 [Joans Follesø]: https://github.com/follesoe [Dan Allen]: https://github.com/mojavelinux [Eric Knibbe]: https://github.com/EricFromCanada [Kurt Emch]: https://github.com/kemch [Poren Chiang]: https://github.com/rschiang [Kelley van Evert]: https://github.com/kelleyvanevert New style themes: - Monokai Sublime by [noformnocontent][] - Railscasts by [Damien White][] - Obsidian by [Alexander Marenin][] - Docco by [Simon Madine][] - Mono Blue by [Ivan Sagalaev][] (uses a single color hue for everything) - Foundation by [Dan Allen][] [noformnocontent]: http://nn.mit-license.org/ [Damien White]: https://github.com/visoft [Alexander Marenin]: https://github.com/ioncreature [Simon Madine]: https://github.com/thingsinjars [Ivan Sagalaev]: https://github.com/isagalaev Other notable changes: - Corrected many corner cases in CSS. - Dropped Python 2 version of the build tool. - Implemented building for the AMD format. - Updated Rust keywords (thanks to [Dmitry Medvinsky][]). - Literal regexes can now be used in language definitions. - CoffeeScript highlighting is now significantly more robust and rich due to input from [Cédric Néhémie][]. [Dmitry Medvinsky]: https://github.com/dmedvinsky [Cédric Néhémie]: https://github.com/abe33 ## Version 7.3 - Since this version highlight.js no longer works in IE version 8 and older. It's made it possible to reduce the library size and dramatically improve code readability and made it easier to maintain. Time to go forward! - New languages: AppleScript (by [Nathan Grigg][ng] and [Dr. Drang][dd]) and Brainfuck (by [Evgeny Stepanischev][bolk]). - Improvements to existing languages: - interpreter prompt in Python (`>>>` and `...`) - @-properties and classes in CoffeeScript - E4X in JavaScript (by [Oleg Efimov][oe]) - new keywords in Perl (by [Kirk Kimmel][kk]) - big Ruby syntax update (by [Vasily Polovnyov][vast]) - small fixes in Bash - Also Oleg Efimov did a great job of moving all the docs for language and style developers and contributors from the old wiki under the source code in the "docs" directory. Now these docs are nicely presented at <http://highlightjs.readthedocs.org/>. [ng]: https://github.com/nathan11g [dd]: https://github.com/drdrang [bolk]: https://github.com/bolknote [oe]: https://github.com/Sannis [kk]: https://github.com/kimmel [vast]: https://github.com/vast ## Version 7.2 A regular bug-fix release without any significant new features. Enjoy! ## Version 7.1 A Summer crop: - [Marc Fornos][mf] made the definition for Clojure along with the matching style Rainbow (which, of course, works for other languages too). - CoffeeScript support continues to improve getting support for regular expressions. - Yoshihide Jimbo ported to highlight.js [five Tomorrow styles][tm] from the [project by Chris Kempson][tm0]. - Thanks to [Casey Duncun][cd] the library can now be built in the popular [AMD format][amd]. - And last but not least, we've got a fair number of correctness and consistency fixes, including a pretty significant refactoring of Ruby. [mf]: https://github.com/mfornos [tm]: http://jmblog.github.com/color-themes-for-highlightjs/ [tm0]: https://github.com/ChrisKempson/Tomorrow-Theme [cd]: https://github.com/caseman [amd]: http://requirejs.org/docs/whyamd.html ## Version 7.0 The reason for the new major version update is a global change of keyword syntax which resulted in the library getting smaller once again. For example, the hosted build is 2K less than at the previous version while supporting two new languages. Notable changes: - The library now works not only in a browser but also with [node.js][]. It is installable with `npm install highlight.js`. [API][] docs are available on our wiki. - The new unique feature (apparently) among syntax highlighters is highlighting *HTTP* headers and an arbitrary language in the request body. The most useful languages here are *XML* and *JSON* both of which highlight.js does support. Here's [the detailed post][p] about the feature. - Two new style themes: a dark "south" *[Pojoaque][]* by Jason Tate and an emulation of*XCode* IDE by [Angel Olloqui][ao]. - Three new languages: *D* by [Aleksandar Ružičić][ar], *R* by [Joe Cheng][jc] and *GLSL* by [Sergey Tikhomirov][st]. - *Nginx* syntax has become a million times smaller and more universal thanks to remaking it in a more generic manner that doesn't require listing all the directives in the known universe. - Function titles are now highlighted in *PHP*. - *Haskell* and *VHDL* were significantly reworked to be more rich and correct by their respective maintainers [Jeremy Hull][sr] and [Igor Kalnitsky][ik]. And last but not least, many bugs have been fixed around correctness and language detection. Overall highlight.js currently supports 51 languages and 20 style themes. [node.js]: http://nodejs.org/ [api]: http://softwaremaniacs.org/wiki/doku.php/highlight.js:api [p]: http://softwaremaniacs.org/blog/2012/05/10/http-and-json-in-highlight-js/en/ [pojoaque]: http://web-cms-designs.com/ftopict-10-pojoaque-style-for-highlight-js-code-highlighter.html [ao]: https://github.com/angelolloqui [ar]: https://github.com/raleksandar [jc]: https://github.com/jcheng5 [st]: https://github.com/tikhomirov [sr]: https://github.com/sourrust [ik]: https://github.com/ikalnitsky ## Version 6.2 A lot of things happened in highlight.js since the last version! We've got nine new contributors, the discussion group came alive, and the main branch on GitHub now counts more than 350 followers. Here are most significant results coming from all this activity: - 5 (five!) new languages: Rust, ActionScript, CoffeeScript, MatLab and experimental support for markdown. Thanks go to [Andrey Vlasovskikh][av], [Alexander Myadzel][am], [Dmytrii Nagirniak][dn], [Oleg Efimov][oe], [Denis Bardadym][db] and [John Crepezzi][jc]. - 2 new style themes: Monokai by [Luigi Maselli][lm] and stylistic imitation of another well-known highlighter Google Code Prettify by [Aahan Krish][ak]. - A vast number of [correctness fixes and code refactorings][log], mostly made by [Oleg Efimov][oe] and [Evgeny Stepanischev][es]. [av]: https://github.com/vlasovskikh [am]: https://github.com/myadzel [dn]: https://github.com/dnagir [oe]: https://github.com/Sannis [db]: https://github.com/btd [jc]: https://github.com/seejohnrun [lm]: http://grigio.org/ [ak]: https://github.com/geekpanth3r [es]: https://github.com/bolknote [log]: https://github.com/isagalaev/highlight.js/commits/ ## Version 6.1 — Solarized [Jeremy Hull][jh] has implemented my dream feature — a port of [Solarized][] style theme famous for being based on the intricate color theory to achieve correct contrast and color perception. It is now available for highlight.js in both variants — light and dark. This version also adds a new original style Arta. Its author pumbur maintains a [heavily modified fork of highlight.js][pb] on GitHub. [jh]: https://github.com/sourrust [solarized]: http://ethanschoonover.com/solarized [pb]: https://github.com/pumbur/highlight.js ## Version 6.0 New major version of the highlighter has been built on a significantly refactored syntax. Due to this it's even smaller than the previous one while supporting more languages! New languages are: - Haskell by [Jeremy Hull][sourrust] - Erlang in two varieties — module and REPL — made collectively by [Nikolay Zakharov][desh], [Dmitry Kovega][arhibot] and [Sergey Ignatov][ignatov] - Objective C by [Valerii Hiora][vhbit] - Vala by [Antono Vasiljev][antono] - Go by [Stephan Kountso][steplg] [sourrust]: https://github.com/sourrust [desh]: http://desh.su/ [arhibot]: https://github.com/arhibot [ignatov]: https://github.com/ignatov [vhbit]: https://github.com/vhbit [antono]: https://github.com/antono [steplg]: https://github.com/steplg Also this version is marginally faster and fixes a number of small long-standing bugs. Developer overview of the new language syntax is available in a [blog post about recent beta release][beta]. [beta]: http://softwaremaniacs.org/blog/2011/04/25/highlight-js-60-beta/en/ P.S. New version is not yet available on a Yandex' CDN, so for now you have to download [your own copy][d]. [d]: /soft/highlight/en/download/ ## Version 5.14 Fixed bugs in HTML/XML detection and relevance introduced in previous refactoring. Also test.html now shows the second best result of language detection by relevance. ## Version 5.13 Past weekend began with a couple of simple additions for existing languages but ended up in a big code refactoring bringing along nice improvements for language developers. ### For users - Description of C++ has got new keywords from the upcoming [C++ 0x][] standard. - Description of HTML has got new tags from [HTML 5][]. - CSS-styles have been unified to use consistent padding and also have lost pop-outs with names of detected languages. - [Igor Kalnitsky][ik] has sent two new language descriptions: CMake и VHDL. This makes total number of languages supported by highlight.js to reach 35. Bug fixes: - Custom classes on `<pre>` tags are not being overridden anymore - More correct highlighting of code blocks inside non-`<pre>` containers: highlighter now doesn't insist on replacing them with its own container and just replaces the contents. - Small fixes in browser compatibility and heuristics. [c++ 0x]: http://ru.wikipedia.org/wiki/C%2B%2B0x [html 5]: http://en.wikipedia.org/wiki/HTML5 [ik]: http://kalnitsky.org.ua/ ### For developers The most significant change is the ability to include language submodes right under `contains` instead of defining explicit named submodes in the main array: contains: [ 'string', 'number', {begin: '\\n', end: hljs.IMMEDIATE_RE} ] This is useful for auxiliary modes needed only in one place to define parsing. Note that such modes often don't have `className` and hence won't generate a separate `<span>` in the resulting markup. This is similar in effect to `noMarkup: true`. All existing languages have been refactored accordingly. Test file test.html has at last become a real test. Now it not only puts the detected language name under the code snippet but also tests if it matches the expected one. Test summary is displayed right above all language snippets. ## CDN Fine people at [Yandex][] agreed to host highlight.js on their big fast servers. [Link up][l]! [yandex]: http://yandex.com/ [l]: http://softwaremaniacs.org/soft/highlight/en/download/ ## Version 5.10 — "Paris". Though I'm on a vacation in Paris, I decided to release a new version with a couple of small fixes: - Tomas Vitvar discovered that TAB replacement doesn't always work when used with custom markup in code - SQL parsing is even more rigid now and doesn't step over SmallTalk in tests ## Version 5.9 A long-awaited version is finally released. New languages: - Andrew Fedorov made a definition for Lua - a long-time highlight.js contributor [Peter Leonov][pl] made a definition for Nginx config - [Vladimir Moskva][vm] made a definition for TeX [pl]: http://kung-fu-tzu.ru/ [vm]: http://fulc.ru/ Fixes for existing languages: - [Loren Segal][ls] reworked the Ruby definition and added highlighting for [YARD][] inline documentation - the definition of SQL has become more solid and now it shouldn't be overly greedy when it comes to language detection [ls]: http://gnuu.org/ [yard]: http://yardoc.org/ The highlighter has become more usable as a library allowing to do highlighting from initialization code of JS frameworks and in ajax methods (see. readme.eng.txt). Also this version drops support for the [WordPress][wp] plugin. Everyone is welcome to [pick up its maintenance][p] if needed. [wp]: http://wordpress.org/ [p]: http://bazaar.launchpad.net/~isagalaev/+junk/highlight/annotate/342/src/wp_highlight.js.php ## Version 5.8 - Jan Berkel has contributed a definition for Scala. +1 to hotness! - All CSS-styles are rewritten to work only inside `<pre>` tags to avoid conflicts with host site styles. ## Version 5.7. Fixed escaping of quotes in VBScript strings. ## Version 5.5 This version brings a small change: now .ini-files allow digits, underscores and square brackets in key names. ## Version 5.4 Fixed small but upsetting bug in the packer which caused incorrect highlighting of explicitly specified languages. Thanks to Andrew Fedorov for precise diagnostics! ## Version 5.3 The version to fulfil old promises. The most significant change is that highlight.js now preserves custom user markup in code along with its own highlighting markup. This means that now it's possible to use, say, links in code. Thanks to [Vladimir Dolzhenko][vd] for the [initial proposal][1] and for making a proof-of-concept patch. Also in this version: - [Vasily Polovnyov][vp] has sent a GitHub-like style and has implemented support for CSS @-rules and Ruby symbols. - Yura Zaripov has sent two styles: Brown Paper and School Book. - Oleg Volchkov has sent a definition for [Parser 3][p3]. [1]: http://softwaremaniacs.org/forum/highlightjs/6612/ [p3]: http://www.parser.ru/ [vp]: http://vasily.polovnyov.ru/ [vd]: http://dolzhenko.blogspot.com/ ## Version 5.2 - at last it's possible to replace indentation TABs with something sensible (e.g. 2 or 4 spaces) - new keywords and built-ins for 1C by Sergey Baranov - a couple of small fixes to Apache highlighting ## Version 5.1 This is one of those nice version consisting entirely of new and shiny contributions! - [Vladimir Ermakov][vooon] created highlighting for AVR Assembler - [Ruslan Keba][rukeba] created highlighting for Apache config file. Also his original visual style for it is now available for all highlight.js languages under the name "Magula". - [Shuen-Huei Guan][drake] (aka Drake) sent new keywords for RenderMan languages. Also thanks go to [Konstantin Evdokimenko][ke] for his advice on the matter. [vooon]: http://vehq.ru/about/ [rukeba]: http://rukeba.com/ [drake]: http://drakeguan.org/ [ke]: http://k-evdokimenko.moikrug.ru/ ## Version 5.0 The main change in the new major version of highlight.js is a mechanism for packing several languages along with the library itself into a single compressed file. Now sites using several languages will load considerably faster because the library won't dynamically include additional files while loading. Also this version fixes a long-standing bug with Javascript highlighting that couldn't distinguish between regular expressions and division operations. And as usually there were a couple of minor correctness fixes. Great thanks to all contributors! Keep using highlight.js. ## Version 4.3 This version comes with two contributions from [Jason Diamond][jd]: - language definition for C# (yes! it was a long-missed thing!) - Visual Studio-like highlighting style Plus there are a couple of minor bug fixes for parsing HTML and XML attributes. [jd]: http://jason.diamond.name/weblog/ ## Version 4.2 The biggest news is highlighting for Lisp, courtesy of Vasily Polovnyov. It's somewhat experimental meaning that for highlighting "keywords" it doesn't use any pre-defined set of a Lisp dialect. Instead it tries to highlight first word in parentheses wherever it makes sense. I'd like to ask people programming in Lisp to confirm if it's a good idea and send feedback to [the forum][f]. Other changes: - Smalltalk was excluded from DEFAULT_LANGUAGES to save traffic - [Vladimir Epifanov][voldmar] has implemented javascript style switcher for test.html - comments now allowed inside Ruby function definition - [MEL][] language from [Shuen-Huei Guan][drake] - whitespace now allowed between `<pre>` and `<code>` - better auto-detection of C++ and PHP - HTML allows embedded VBScript (`<% .. %>`) [f]: http://softwaremaniacs.org/forum/highlightjs/ [voldmar]: http://voldmar.ya.ru/ [mel]: http://en.wikipedia.org/wiki/Maya_Embedded_Language [drake]: http://drakeguan.org/ ## Version 4.1 Languages: - Bash from Vah - DOS bat-files from Alexander Makarov (Sam) - Diff files from Vasily Polovnyov - Ini files from myself though initial idea was from Sam Styles: - Zenburn from Vladimir Epifanov, this is an imitation of a [well-known theme for Vim][zenburn]. - Ascetic from myself, as a realization of ideals of non-flashy highlighting: just one color in only three gradations :-) In other news. [One small bug][bug] was fixed, built-in keywords were added for Python and C++ which improved auto-detection for the latter (it was shame that [my wife's blog][alenacpp] had issues with it from time to time). And lastly thanks go to Sam for getting rid of my stylistic comments in code that were getting in the way of [JSMin][]. [zenburn]: http://en.wikipedia.org/wiki/Zenburn [alenacpp]: http://alenacpp.blogspot.com/ [bug]: http://softwaremaniacs.org/forum/viewtopic.php?id=1823 [jsmin]: http://code.google.com/p/jsmin-php/ ## Version 4.0 New major version is a result of vast refactoring and of many contributions. Visible new features: - Highlighting of embedded languages. Currently is implemented highlighting of Javascript and CSS inside HTML. - Bundled 5 ready-made style themes! Invisible new features: - Highlight.js no longer pollutes global namespace. Only one object and one function for backward compatibility. - Performance is further increased by about 15%. Changing of a major version number caused by a new format of language definition files. If you use some third-party language files they should be updated. ## Version 3.5 A very nice version in my opinion fixing a number of small bugs and slightly increased speed in a couple of corner cases. Thanks to everybody who reports bugs in he [forum][f] and by email! There is also a new language — XML. A custom XML formerly was detected as HTML and didn't highlight custom tags. In this version I tried to make custom XML to be detected and highlighted by its own rules. Which by the way include such things as CDATA sections and processing instructions (`<? ... ?>`). [f]: http://softwaremaniacs.org/forum/viewforum.php?id=6 ## Version 3.3 [Vladimir Gubarkov][xonix] has provided an interesting and useful addition. File export.html contains a little program that shows and allows to copy and paste an HTML code generated by the highlighter for any code snippet. This can be useful in situations when one can't use the script itself on a site. [xonix]: http://xonixx.blogspot.com/ ## Version 3.2 consists completely of contributions: - Vladimir Gubarkov has described SmallTalk - Yuri Ivanov has described 1C - Peter Leonov has packaged the highlighter as a Firefox extension - Vladimir Ermakov has compiled a mod for phpBB Many thanks to you all! ## Version 3.1 Three new languages are available: Django templates, SQL and Axapta. The latter two are sent by [Dmitri Roudakov][1]. However I've almost entirely rewrote an SQL definition but I'd never started it be it from the ground up :-) The engine itself has got a long awaited feature of grouping keywords ("keyword", "built-in function", "literal"). No more hacks! [1]: http://roudakov.ru/ ## Version 3.0 It is major mainly because now highlight.js has grown large and has become modular. Now when you pass it a list of languages to highlight it will dynamically load into a browser only those languages. Also: - Konstantin Evdokimenko of [RibKit][] project has created a highlighting for RenderMan Shading Language and RenderMan Interface Bytestream. Yay for more languages! - Heuristics for C++ and HTML got better. - I've implemented (at last) a correct handling of backslash escapes in C-like languages. There is also a small backwards incompatible change in the new version. The function initHighlighting that was used to initialize highlighting instead of initHighlightingOnLoad a long time ago no longer works. If you by chance still use it — replace it with the new one. [RibKit]: http://ribkit.sourceforge.net/ ## Version 2.9 Highlight.js is a parser, not just a couple of regular expressions. That said I'm glad to announce that in the new version 2.9 has support for: - in-string substitutions for Ruby -- `#{...}` - strings from from numeric symbol codes (like #XX) for Delphi ## Version 2.8 A maintenance release with more tuned heuristics. Fully backwards compatible. ## Version 2.7 - Nikita Ledyaev presents highlighting for VBScript, yay! - A couple of bugs with escaping in strings were fixed thanks to Mickle - Ongoing tuning of heuristics Fixed bugs were rather unpleasant so I encourage everyone to upgrade! ## Version 2.4 - Peter Leonov provides another improved highlighting for Perl - Javascript gets a new kind of keywords — "literals". These are the words "true", "false" and "null" Also highlight.js homepage now lists sites that use the library. Feel free to add your site by [dropping me a message][mail] until I find the time to build a submit form. [mail]: mailto:[email protected] ## Version 2.3 This version fixes IE breakage in previous version. My apologies to all who have already downloaded that one! ## Version 2.2 - added highlighting for Javascript - at last fixed parsing of Delphi's escaped apostrophes in strings - in Ruby fixed highlighting of keywords 'def' and 'class', same for 'sub' in Perl ## Version 2.0 - Ruby support by [Anton Kovalyov][ak] - speed increased by orders of magnitude due to new way of parsing - this same way allows now correct highlighting of keywords in some tricky places (like keyword "End" at the end of Delphi classes) [ak]: http://anton.kovalyov.net/ ## Version 1.0 Version 1.0 of javascript syntax highlighter is released! It's the first version available with English description. Feel free to post your comments and question to [highlight.js forum][forum]. And don't be afraid if you find there some fancy Cyrillic letters -- it's for Russian users too :-) [forum]: http://softwaremaniacs.org/forum/viewforum.php?id=6
{ "pile_set_name": "Github" }
import subprocess from jadi import component from aj.plugins.services.api import ServiceManager, Service @component(ServiceManager) class SystemdServiceManager(ServiceManager): id = 'systemd' name = 'systemd' @classmethod def __verify__(cls): return subprocess.call(['which', 'systemctl']) == 0 def __init__(self, context): pass def list(self, units=None): if not units: units = [x.split()[0] for x in subprocess.check_output(['systemctl', 'list-unit-files', '--no-legend', '--no-pager', '-la']).decode().splitlines() if x] units = [x for x in units if x.endswith('.service') and '@' not in x] units = list(set(units)) cmd = ['systemctl', 'show', '-o', 'json', '--full', '--all'] + units used_names = set() unit = {} for l in subprocess.check_output(cmd).decode().splitlines() + [None]: if not l: if len(unit) > 0: svc = Service(self) svc.id = unit['Id'] svc.name, type = svc.id.rsplit('.', 1) svc.name = svc.name.replace('\\x2d', '\x2d') svc.running = unit['SubState'] == 'running' svc.state = 'running' if svc.running else 'stopped' if svc.name not in used_names: yield svc used_names.add(svc.name) unit = {} elif '=' in l: k, v = l.split('=', 1) unit[k] = v def get_service(self, _id): for s in self.list(units=[_id]): return s def start(self, _id): subprocess.check_call(['systemctl', 'start', _id], close_fds=True) def stop(self, _id): subprocess.check_call(['systemctl', 'stop', _id], close_fds=True) def restart(self, _id): subprocess.check_call(['systemctl', 'restart', _id], close_fds=True)
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> <Title>EAStdC</title> <link type="text/css" rel="stylesheet" href="UTFDoc.css"> <meta name="author" content="Paul Pedriana"> </head> <body bgcolor="#FFFFFF"> <h1>EAStdC</h1> <p>EAStdC is a package which implements a number of basic library facilities that are similar to those in the standard C library. This does not mean that its functionality is identical to the C standard library. It is an evolution and convergence of the rwstdc and UTFFoundation packages. </p> <p>The fundamental design characteristics of EAStdC are:</p> <ul> <li>The package has minimal dependencies: EABase and EAAssert.</li> <li>It consists of simple standalone functions and classes.</li> <li>Memory is not allocated by any of the functions or classes, excepts possibly under pathological conditions.</li> <li>There is no thread-safety. All thread safety must be coordinated at a higher level by the user. </li> <li>It does not implement localization functionality. Localization functionality is left to specialized libraries for that purpose.</li> <li>With few exceptions, both char8_t and char16_t string functionality are supported equivalently.</li> </ul> <h3> Should you use EAStdC functions that overlap with Standard C library functions?</h3> <p>A primary purpose of EAStdC is to provide a portable implementation of basic utility functions, many of which correspond the standard C library functions. Specifically: </p> <ul> <li> Provide a standardizes portable header file to #include. </li> <ul> <li> e.g. C libraries don&rsquo;t use the same name for headers, such as malloc.h, sys/types.h, memory.h, etc. </li> </ul> <li> Provide standardized function names. </li> <ul> <li> e.g. EAStdC has Vsnprintf, as opposed to VC++ having _vsnprintf but GCC having vsnprintf. </li> </ul> <li> Provide standardized function implementations. </li> <ul> <li> e.g. Sprintf/Scanf work the same in EAStdC, unlike most C libraries. </li> </ul> <li> Provide faster versions. </li> <ul> <li> e.g. Faster strlen, memcpy, special fast memcpy versions. EAStdC sprintf is much faster than stdc. </li> </ul> <li> Provide versions that don&rsquo;t exist in compiler-provided libraries. </li> <ul> <li> e.g. EAStdC has vsnprintf, whereas some C libraries don&rsquo;t. </li> </ul> <li> Lower memory requirements. </li> <ul> <li> Some stdc functions tend to bring in a lot of object code, often because of their locale requirements. </li> </ul> <li> Provides consistent standardized encoding. </li> <ul> <li> EAStdC uses UTF8 for char8_t and UCS2 for char16_t, whereas C libraries aren&rsquo;t consistent. wchar_t could be 8, 16, or 32 bit (we&rsquo;ve seen each of these). </li> </ul> <li> Provide auxiliary or &ldquo;better&rdquo; versions of functions. </li> <ul> <li> e.g. EAStdC&rsquo;s Random, DateTime. </li> </ul> <li> EAStdC has additional functionality that doesn&rsquo;t directly match something from the Standard C library. </li> <ul> <li> e.g. Stopwatch, Hash, FixedPoint. </li> </ul> </ul> <p> Primary downsides to EAStdC: </p> <ul> <li> It doesn&rsquo;t have localization support. You can&rsquo;t call setlocale() with it and have it change how it interprets &ldquo;.&rdquo; And &ldquo;,&rdquo; in numbers. You need to use the EALocale or EAText package for that, though EALocale and EAText do a better job than stdc does. </li> <li> EAStdC might have bugs that haven&rsquo;t been eradicated, while most stdc implementations are pretty good. </li> <li> Stdc has better documentation, though the EAStdC functions that are stdc equivalents usually have the same specification. </li> </ul> <p> In the case of overlap between stdc and EAStdC, I think the policy of what to use depends on your team conventions and your project requirements. Some notes: </p> <ul> <li> If you want to guarantee portability then you&rsquo;re better off using EAStdC. </li> <li> Some functions (e.g. strlen and memcpy) are basic enough that the stdc versions are usually fine. </li> <ul> <li> Except EAStdC&rsquo;s Strlen is faster than most stdc versions, and a surprising number of memcpy implementations for uncommon platforms are slow. </li> </ul> <li> If you think your code will need to build outside our codebase then maybe you should try to stick with stdc. </li> </ul> <hr> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> </body> </html>
{ "pile_set_name": "Github" }
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" android:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. Copyright (c) 2007 Sun Microsystems Inc. All Rights Reserved The contents of this file are subject to the terms of the Common Development and Distribution License (the License). You may not use this file except in compliance with the License. You can obtain a copy of the License at https://opensso.dev.java.net/public/CDDLv1.0.html or opensso/legal/CDDLv1.0.txt See the License for the specific language governing permission and limitations under the License. When distributing Covered Code, include this CDDL Header Notice in each file and include the License file at opensso/legal/CDDLv1.0.txt. If applicable, add the following below the CDDL Header, with the fields enclosed by brackets [] replaced by your own identifying information: "Portions Copyrighted [year] [name of copyright owner]" $Id: amPasswordReset.xml,v 1.3 2009/01/13 06:50:17 mahesh_prasad_r Exp $ Portions Copyrighted 2013-2015 ForgeRock AS. --> <!DOCTYPE ServicesConfiguration PUBLIC "=//iPlanet//Service Management Services (SMS) 1.0 DTD//EN" "jar://com/sun/identity/sm/sms.dtd"> <ServicesConfiguration> <Service name="iPlanetAMPasswordResetService" version="1.0"> <Schema serviceHierarchy="/DSAMEConfig/iPlanetAMPasswordResetService" i18nFileName="amPasswordReset" i18nKey="iplanet-am-password-reset-service-description" resourceName="passwordreset" revisionNumber="20"> <Organization> <AttributeSchema name="RequiredValueValidator" type="validator" syntax="string"> <DefaultValues> <Value>com.sun.identity.sm.RequiredValueValidator</Value> </DefaultValues> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-userValidate" type="single" syntax="string" any="required|display" validator="RequiredValueValidator" resourceName="userAttribute" i18nKey="p101"> <DefaultValues> <Value>uid</Value> </DefaultValues> </AttributeSchema> <AttributeSchema name="openam-am-password-reset-invalidchar-regex" type="single" syntax="string" any="display" i18nKey="p121" resourceName="invalidCharacterRegex"> <DefaultValues> <Value>[\*\(\)_%\W]</Value> </DefaultValues> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-question" type="list" syntax="string" any="required|display" validator="RequiredValueValidator" resourceName="question" i18nKey="p102"> <DefaultValues> <Value>favourite-restaurant</Value> </DefaultValues> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-searchFilter" type="single" syntax="string" any="display" resourceName="searchFilter" i18nKey="p103"> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-baseDN" type="single" syntax="string" any="display" resourceName="baseDN" i18nKey="p104"> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-bindDN" type="single" syntax="string" any="required|display" validator="RequiredValueValidator" resourceName="bindDN" i18nKey="p105"> <DefaultValues> <Value>&#x00A0;</Value> </DefaultValues> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-bindPasswd" type="single" syntax="password" any="required|display" validator="RequiredValueValidator" resourceName="bindPassword" i18nKey="p106"> <DefaultValues> <Value>&#x00A0;</Value> </DefaultValues> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-option" type="single" syntax="string" any="required|display" validator="RequiredValueValidator" resourceName="resetCreatorClass" i18nKey="p107"> <DefaultValues> <Value>com.sun.identity.password.plugins.RandomPasswordGenerator</Value> </DefaultValues> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-notification" type="single" syntax="string" any="required|display" validator="RequiredValueValidator" resourceName="notificationClass" i18nKey="p108"> <DefaultValues> <Value>com.sun.identity.password.plugins.EmailPassword</Value> </DefaultValues> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-enabled" type="single" syntax="boolean" any="required|display" validator="RequiredValueValidator" resourceName="enabled" i18nKey="p109"> <DefaultValues> <Value>true</Value> </DefaultValues> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-user-personal-question" type="single" syntax="boolean" any="required|display" validator="RequiredValueValidator" resourceName="personalQuestion" i18nKey="p110"> <DefaultValues> <Value>false</Value> </DefaultValues> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-max-num-of-questions" type="single" syntax="number_range" rangeStart="1" rangeEnd="5" any="required|display" validator="RequiredValueValidator" resourceName="maximumNumberQuestions" i18nKey="p111"> <DefaultValues> <Value>1</Value> </DefaultValues> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-force-reset" type="single" syntax="boolean" any="display" resourceName="forceResetOnNextLogin" i18nKey="p111.1"> <DefaultValues> <Value>false</Value> </DefaultValues> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-failure-lockout-mode" type="single" syntax="boolean" resourceName="failureLockout" i18nKey="p112"> <DefaultValues> <Value>false</Value> </DefaultValues> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-failure-count" type="single" syntax="number_range" rangeStart="0" rangeEnd="2147483647" i18nKey="p113" resourceName="failureCount"> <DefaultValues> <Value>5</Value> </DefaultValues> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-failure-duration" type="single" syntax="number_range" rangeStart="1" rangeEnd="2147483647" i18nKey="p114" resourceName="failureDuration"> <DefaultValues> <Value>300</Value> </DefaultValues> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-lockout-email-address" type="single" syntax="string" i18nKey="p115" resourceName="lockoutEmail"> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-lockout-warn-user" type="single" syntax="number_range" rangeStart="0" rangeEnd="2147483647" i18nKey="p116" resourceName="warnUserBeforeLockout"> <DefaultValues> <Value>4</Value> </DefaultValues> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-lockout-duration" type="single" syntax="number_range" rangeStart="0" rangeEnd="2147483647" i18nKey="p117" resourceName="lockoutDuration"> <DefaultValues> <Value>0</Value> </DefaultValues> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-lockout-attribute-name" type="single" syntax="string" i18nKey="p118" resourceName="lockoutAttributeName"> </AttributeSchema> <AttributeSchema name="iplanet-am-password-reset-lockout-attribute-value" type="single" syntax="string" i18nKey="p119" resourceName="lockoutAttributeValue"> </AttributeSchema> <AttributeSchema name="openam-password-reset-mail-attribute-name" type="single" syntax="string" i18nKey="p120" resourceName="emailAttribute"> <DefaultValues> <Value>mail</Value> </DefaultValues> </AttributeSchema> </Organization> </Schema> </Service> </ServicesConfiguration>
{ "pile_set_name": "Github" }
{ "images": [ { "filename": "Icon-Small.png", "size": "29x29", "scale": "1x", "idiom": "iphone" }, { "filename": "[email protected]", "size": "29x29", "scale": "2x", "idiom": "iphone" }, { "filename": "[email protected]", "size": "29x29", "scale": "3x", "idiom": "iphone" }, { "filename": "[email protected]", "size": "40x40", "scale": "2x", "idiom": "iphone" }, { "filename": "[email protected]", "size": "40x40", "scale": "3x", "idiom": "iphone" }, { "filename": "Icon.png", "size": "57x57", "scale": "1x", "idiom": "iphone" }, { "filename": "[email protected]", "size": "57x57", "scale": "2x", "idiom": "iphone" }, { "filename": "[email protected]", "size": "60x60", "scale": "2x", "idiom": "iphone" }, { "filename": "[email protected]", "size": "60x60", "scale": "3x", "idiom": "iphone" }, { "filename": "Icon-Small.png", "size": "29x29", "scale": "1x", "idiom": "ipad" }, { "filename": "[email protected]", "size": "29x29", "scale": "2x", "idiom": "ipad" }, { "filename": "Icon-Spotlight-40.png", "size": "40x40", "scale": "1x", "idiom": "ipad" }, { "filename": "[email protected]", "size": "40x40", "scale": "2x", "idiom": "ipad" }, { "filename": "Icon-Small-50.png", "size": "50x50", "scale": "1x", "idiom": "ipad" }, { "filename": "[email protected]", "size": "50x50", "scale": "2x", "idiom": "ipad" }, { "filename": "Icon-72.png", "size": "72x72", "scale": "1x", "idiom": "ipad" }, { "filename": "[email protected]", "size": "72x72", "scale": "2x", "idiom": "ipad" }, { "filename": "Icon-76.png", "size": "76x76", "scale": "1x", "idiom": "ipad" }, { "filename": "[email protected]", "size": "76x76", "scale": "2x", "idiom": "ipad" }, { "filename": "[email protected]", "size": "120x120", "scale": "1x", "idiom": "car" } ], "info": { "version": 1, "author": "xcode" }, "properties": { "pre-rendered": true } }
{ "pile_set_name": "Github" }
using System; using System.Windows; using HunterPie.Core.Jobs; namespace HunterPie.GUI.Widgets.ClassWidget.Parts { /// <summary> /// Interaction logic for BowControl.xaml /// </summary> public partial class BowControl : ClassControl { Bow Context; public int MaxChargeLevel { get => (int)GetValue(MaxChargeLevelProperty); set => SetValue(MaxChargeLevelProperty, value); } public static readonly DependencyProperty MaxChargeLevelProperty = DependencyProperty.Register("MaxChargeLevel", typeof(int), typeof(BowControl)); public int ChargeLevel { get => (int)GetValue(ChargeLevelProperty); set => SetValue(ChargeLevelProperty, value); } public static readonly DependencyProperty ChargeLevelProperty = DependencyProperty.Register("ChargeLevel", typeof(int), typeof(BowControl)); public float ChargeProgress { get => (float)GetValue(ChargeProgressProperty); set => SetValue(ChargeProgressProperty, value); } public static readonly DependencyProperty ChargeProgressProperty = DependencyProperty.Register("ChargeProgress", typeof(float), typeof(BowControl)); public BowControl() => InitializeComponent(); private void UpdateInformation() { var dummyArgs = new BowEventArgs(Context); OnChargeProgressUpdate(this, dummyArgs); OnChargeLevelChange(this, dummyArgs); OnChargeLevelMaxUpdate(this, dummyArgs); OnSafijiivaCounterUpdate(this, new JobEventArgs(Context)); OnWeaponSheathStateChange(this, new JobEventArgs(Context)); } public void SetContext(Bow ctx) { Context = ctx; HookEvents(); } private void HookEvents() { Context.OnChargeProgressUpdate += OnChargeProgressUpdate; Context.OnChargeLevelChange += OnChargeLevelChange; Context.OnChargeLevelMaxUpdate += OnChargeLevelMaxUpdate; Context.OnSafijiivaCounterUpdate += OnSafijiivaCounterUpdate; Context.OnWeaponSheathStateChange += OnWeaponSheathStateChange; } public override void UnhookEvents() { Context.OnChargeProgressUpdate -= OnChargeProgressUpdate; Context.OnChargeLevelChange -= OnChargeLevelChange; Context.OnChargeLevelMaxUpdate -= OnChargeLevelMaxUpdate; Context.OnSafijiivaCounterUpdate -= OnSafijiivaCounterUpdate; Context.OnWeaponSheathStateChange -= OnWeaponSheathStateChange; Context = null; } private void OnWeaponSheathStateChange(object source, JobEventArgs args) { Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Render, new Action(() => { IsWeaponSheathed = args.IsWeaponSheathed; })); } private void OnSafijiivaCounterUpdate(object source, JobEventArgs args) { Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Render, new Action(() => { HasSafiBuff = args.SafijiivaRegenCounter != -1; SafiCounter = args.SafijiivaMaxHits - args.SafijiivaRegenCounter; })); } private void OnChargeLevelMaxUpdate(object source, BowEventArgs args) { Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Render, new Action(() => { MaxChargeLevel = args.MaxChargeLevel + 1; })); } private void OnChargeLevelChange(object source, BowEventArgs args) { Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Render, new Action(() => { ChargeLevel = args.ChargeLevel + 1; })); } private void OnChargeProgressUpdate(object source, BowEventArgs args) { Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Render, new Action(() => { ChargeProgress = Math.Floor(args.ChargeProgress) >= args.MaxChargeLevel ? 1 : args.ChargeProgress % 1; })); } private void BControl_Loaded(object sender, RoutedEventArgs e) => UpdateInformation(); } }
{ "pile_set_name": "Github" }
// +build example // // Do not build by default. package main import ( "gobot.io/x/gobot" "gobot.io/x/gobot/drivers/gpio" "gobot.io/x/gobot/platforms/intel-iot/edison" "gobot.io/x/gobot/api" ) func main() { master := gobot.NewMaster() api.NewAPI(master).Start() e := edison.NewAdaptor() button := gpio.NewButtonDriver(e, "2") led := gpio.NewLedDriver(e, "4") work := func() { button.On(gpio.ButtonPush, func(data interface{}) { led.On() }) button.On(gpio.ButtonRelease, func(data interface{}) { led.Off() }) } robot := gobot.NewRobot("buttonBot", []gobot.Connection{e}, []gobot.Device{led, button}, work, ) master.AddRobot(robot) master.Start() }
{ "pile_set_name": "Github" }
"""Plot functions for the profiling report.""" import copy from typing import Optional, Union import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt from matplotlib.colors import LinearSegmentedColormap from matplotlib.patches import Patch from matplotlib.ticker import FuncFormatter from pandas_profiling.config import config from pandas_profiling.utils.common import convert_timestamp_to_datetime from pandas_profiling.visualisation.context import manage_matplotlib_context from pandas_profiling.visualisation.utils import plot_360_n0sc0pe def _plot_histogram( series: np.ndarray, bins: Union[int, np.ndarray], figsize: tuple = (6, 4), date=False, ): """Plot an histogram from the data and return the AxesSubplot object. Args: series: The data to plot figsize: The size of the figure (width, height) in inches, default (6,4) bins: number of bins (int for equal size, ndarray for variable size) Returns: The histogram plot. """ fig = plt.figure(figsize=figsize) plot = fig.add_subplot(111) plot.set_ylabel("Frequency") # we have precomputed the histograms... diff = np.diff(bins) plot.bar( bins[:-1] + diff / 2, # type: ignore series, diff, facecolor=config["html"]["style"]["primary_color"].get(str), ) if date: def format_fn(tick_val, tick_pos): return convert_timestamp_to_datetime(tick_val).strftime("%Y-%m-%d %H:%M:%S") plot.xaxis.set_major_formatter(FuncFormatter(format_fn)) if not config["plot"]["histogram"]["x_axis_labels"].get(bool): plot.set_xticklabels([]) return plot @manage_matplotlib_context() def histogram(series: np.ndarray, bins: Union[int, np.ndarray], date=False) -> str: """Plot an histogram of the data. Args: series: The data to plot. bins: number of bins (int for equal size, ndarray for variable size) Returns: The resulting histogram encoded as a string. """ plot = _plot_histogram(series, bins, date=date) plot.xaxis.set_tick_params(rotation=90 if date else 45) plot.figure.tight_layout() return plot_360_n0sc0pe(plt) @manage_matplotlib_context() def mini_histogram(series: np.ndarray, bins: Union[int, np.ndarray], date=False) -> str: """Plot a small (mini) histogram of the data. Args: series: The data to plot. bins: number of bins (int for equal size, ndarray for variable size) Returns: The resulting mini histogram encoded as a string. """ plot = _plot_histogram(series, bins, figsize=(3, 2.25), date=date) plot.axes.get_yaxis().set_visible(False) plot.set_facecolor("w") for tick in plot.xaxis.get_major_ticks(): tick.label1.set_fontsize(6 if date else 8) plot.xaxis.set_tick_params(rotation=90 if date else 45) plot.figure.tight_layout() return plot_360_n0sc0pe(plt) def get_cmap_half(cmap): """Get the upper half of the color map Args: cmap: the color map Returns: A new color map based on the upper half of another color map References: https://stackoverflow.com/a/24746399/470433 """ # Evaluate an existing colormap from 0.5 (midpoint) to 1 (upper end) colors = cmap(np.linspace(0.5, 1, cmap.N // 2)) # Create a new colormap from those colors return LinearSegmentedColormap.from_list("cmap_half", colors) def get_correlation_font_size(n_labels) -> Optional[int]: """Dynamic label font sizes in correlation plots Args: n_labels: the number of labels Returns: A font size or None for the default font size """ if n_labels > 100: font_size = 4 elif n_labels > 80: font_size = 5 elif n_labels > 50: font_size = 6 elif n_labels > 40: font_size = 8 else: return None return font_size @manage_matplotlib_context() def correlation_matrix(data: pd.DataFrame, vmin: int = -1) -> str: """Plot image of a matrix correlation. Args: data: The matrix correlation to plot. vmin: Minimum value of value range. Returns: The resulting correlation matrix encoded as a string. """ fig_cor, axes_cor = plt.subplots() cmap_name = config["plot"]["correlation"]["cmap"].get(str) cmap_bad = config["plot"]["correlation"]["bad"].get(str) cmap = plt.get_cmap(cmap_name) if vmin == 0: cmap = get_cmap_half(cmap) cmap = copy.copy(cmap) cmap.set_bad(cmap_bad) labels = data.columns matrix_image = axes_cor.imshow( data, vmin=vmin, vmax=1, interpolation="nearest", cmap=cmap ) plt.colorbar(matrix_image) if data.isnull().values.any(): legend_elements = [Patch(facecolor=cmap(np.nan), label="invalid\ncoefficient")] plt.legend( handles=legend_elements, loc="upper right", handleheight=2.5, ) axes_cor.set_xticks(np.arange(0, data.shape[0], float(data.shape[0]) / len(labels))) axes_cor.set_yticks(np.arange(0, data.shape[1], float(data.shape[1]) / len(labels))) font_size = get_correlation_font_size(len(labels)) axes_cor.set_xticklabels(labels, rotation=90, fontsize=font_size) axes_cor.set_yticklabels(labels, fontsize=font_size) plt.subplots_adjust(bottom=0.2) return plot_360_n0sc0pe(plt) @manage_matplotlib_context() def scatter_complex(series: pd.Series) -> str: """Scatter plot (or hexbin plot) from a series of complex values Examples: >>> complex_series = pd.Series([complex(1, 3), complex(3, 1)]) >>> scatter_complex(complex_series) Args: series: the Series Returns: A string containing (a reference to) the image """ plt.ylabel("Imaginary") plt.xlabel("Real") color = config["html"]["style"]["primary_color"].get(str) scatter_threshold = config["plot"]["scatter_threshold"].get(int) if len(series) > scatter_threshold: cmap = sns.light_palette(color, as_cmap=True) plt.hexbin(series.real, series.imag, cmap=cmap) else: plt.scatter(series.real, series.imag, color=color) return plot_360_n0sc0pe(plt) @manage_matplotlib_context() def scatter_series(series, x_label="Width", y_label="Height") -> str: """Scatter plot (or hexbin plot) from one series of sequences with length 2 Examples: >>> scatter_series(file_sizes, "Width", "Height") Args: series: the Series x_label: the label on the x-axis y_label: the label on the y-axis Returns: A string containing (a reference to) the image """ plt.xlabel(x_label) plt.ylabel(y_label) color = config["html"]["style"]["primary_color"].get(str) scatter_threshold = config["plot"]["scatter_threshold"].get(int) if len(series) > scatter_threshold: cmap = sns.light_palette(color, as_cmap=True) plt.hexbin(*zip(*series.tolist()), cmap=cmap) else: plt.scatter(*zip(*series.tolist()), color=color) return plot_360_n0sc0pe(plt) @manage_matplotlib_context() def scatter_pairwise(series1, series2, x_label, y_label) -> str: """Scatter plot (or hexbin plot) from two series Examples: >>> widths = pd.Series([800, 1024]) >>> heights = pd.Series([600, 768]) >>> scatter_series(widths, heights, "Width", "Height") Args: series1: the series corresponding to the x-axis series2: the series corresponding to the y-axis x_label: the label on the x-axis y_label: the label on the y-axis Returns: A string containing (a reference to) the image """ plt.xlabel(x_label) plt.ylabel(y_label) color = config["html"]["style"]["primary_color"].get(str) scatter_threshold = config["plot"]["scatter_threshold"].get(int) indices = (series1.notna()) & (series2.notna()) if len(series1) > scatter_threshold: cmap = sns.light_palette(color, as_cmap=True) plt.hexbin(series1[indices], series2[indices], gridsize=15, cmap=cmap) else: plt.scatter(series1[indices], series2[indices], color=color) return plot_360_n0sc0pe(plt) @manage_matplotlib_context() def pie_plot(data, legend_kws=None): if legend_kws is None: legend_kws = {} def func(pct, allvals): absolute = int(pct / 100.0 * np.sum(allvals)) return "{:.1f}%\n({:d})".format(pct, absolute) wedges, _, _ = plt.pie( data, autopct=lambda pct: func(pct, data), textprops=dict(color="w") ) plt.legend(wedges, data.index.values, **legend_kws) return plot_360_n0sc0pe(plt)
{ "pile_set_name": "Github" }
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24.0" android:viewportHeight="24.0"> <path android:fillColor="#FF000000" android:pathData="M20,4L4,4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L22,6c0,-1.1 -0.9,-2 -2,-2zM20,8l-8,5 -8,-5L4,6l8,5 8,-5v2z"/> </vector>
{ "pile_set_name": "Github" }
import {GraphQLObjectType} from 'graphql' import {GQLContext} from '../graphql' import ReflectPrompt from './ReflectPrompt' import StandardMutationError from './StandardMutationError' const MoveReflectTemplatePromptPayload = new GraphQLObjectType<any, GQLContext>({ name: 'MoveReflectTemplatePromptPayload', fields: () => ({ error: { type: StandardMutationError }, prompt: { type: ReflectPrompt, resolve: ({promptId}, _args, {dataLoader}) => { if (!promptId) return null return dataLoader.get('reflectPrompts').load(promptId) } } }) }) export default MoveReflectTemplatePromptPayload
{ "pile_set_name": "Github" }
// // ServersDataSource.m // // Copyright (C) 2013 IRCCloud, Ltd. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #import "ServersDataSource.h" #import "BuffersDataSource.h" #import "ChannelsDataSource.h" #import "UsersDataSource.h" #import "EventsDataSource.h" @implementation Server -(id)init { self = [super init]; if(self) { self->_MODE_OPER = @"Y"; self->_MODE_OWNER = @"q"; self->_MODE_ADMIN = @"a"; self->_MODE_OP = @"o"; self->_MODE_HALFOP = @"h"; self->_MODE_VOICED = @"v"; self->_ignore = [[Ignore alloc] init]; } return self; } -(NSComparisonResult)compare:(Server *)aServer { if(aServer.order > _order) return NSOrderedAscending; else if(aServer.order < _order) return NSOrderedDescending; else if(aServer.cid > _cid) return NSOrderedAscending; else if(aServer.cid < _cid) return NSOrderedDescending; else return NSOrderedSame; } -(NSString *)description { return [NSString stringWithFormat:@"{cid: %i, name: %@, hostname: %@, port: %i}", _cid, _name, _hostname, _port]; } -(void)encodeWithCoder:(NSCoder *)aCoder { encodeInt(self->_cid); encodeObject(self->_name); encodeObject(self->_hostname); encodeInt(self->_port); encodeObject(self->_nick); encodeObject(self->_status); encodeInt(self->_ssl); encodeObject(self->_realname); encodeObject(self->_join_commands); encodeObject(self->_fail_info); encodeObject(self->_away); encodeObject(self->_usermask); encodeObject(self->_mode); encodeObject(self->_isupport); encodeObject(self->_ignores); encodeObject(self->_CHANTYPES); encodeObject(self->_PREFIX); encodeInt(self->_order); encodeObject(self->_MODE_OPER); encodeObject(self->_MODE_OWNER); encodeObject(self->_MODE_ADMIN); encodeObject(self->_MODE_OP); encodeObject(self->_MODE_HALFOP); encodeObject(self->_MODE_VOICED); encodeObject(self->_ircserver); encodeInt(self->_orgId); encodeObject(self->_avatar); encodeInt(self->_avatars_supported); } -(id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; if(self) { decodeInt(self->_cid); decodeObject(self->_name); decodeObject(self->_hostname); decodeInt(self->_port); decodeObject(self->_nick); decodeObject(self->_status); decodeInt(self->_ssl); decodeObject(self->_realname); decodeObject(self->_join_commands); decodeObject(self->_fail_info); decodeObject(self->_away); decodeObject(self->_usermask); decodeObject(self->_mode); decodeObject(self->_isupport); self->_isupport = self->_isupport.mutableCopy; decodeObject(self->_ignores); decodeObject(self->_CHANTYPES); decodeObject(self->_PREFIX); decodeInt(self->_order); decodeObject(self->_MODE_OPER); decodeObject(self->_MODE_OWNER); decodeObject(self->_MODE_ADMIN); decodeObject(self->_MODE_OP); decodeObject(self->_MODE_HALFOP); decodeObject(self->_MODE_VOICED); decodeObject(self->_ircserver); decodeInt(self->_orgId); decodeObject(self->_avatar); decodeInt(self->_avatars_supported); self->_ignore = [[Ignore alloc] init]; [self->_ignore setIgnores:self->_ignores]; } return self; } -(NSArray *)ignores { return _ignores; } -(void)setIgnores:(NSArray *)ignores { self->_ignores = ignores; [self->_ignore setIgnores:self->_ignores]; } -(BOOL)isSlack { return _slack || [self->_hostname hasSuffix:@".slack.com"] || [self->_ircserver hasSuffix:@".slack.com"]; } -(NSString *)slackBaseURL { NSString *host = self->_hostname; if(![host hasSuffix:@".slack.com"]) host = self->_ircserver; if([host hasSuffix:@".slack.com"]) return [NSString stringWithFormat:@"https://%@", host]; return nil; } -(BOOL)clientTagDeny:(NSString *)tagName { if([[self->_isupport objectForKey:@"CLIENTTAGDENY"] isKindOfClass:[NSString class]]) { BOOL denied = NO; NSArray *tags = [[self->_isupport objectForKey:@""] componentsSeparatedByString:@","]; for(NSString *tag in tags) { if([tag isEqualToString:@"*"] || [tag isEqualToString:tagName]) denied = YES; if([tag isEqualToString:[NSString stringWithFormat:@"~%@", tagName]]) denied = NO; } return denied; } return NO; } @end @implementation ServersDataSource +(ServersDataSource *)sharedInstance { static ServersDataSource *sharedInstance; @synchronized(self) { if(!sharedInstance) sharedInstance = [[ServersDataSource alloc] init]; return sharedInstance; } return nil; } -(id)init { self = [super init]; if(self) { [NSKeyedArchiver setClassName:@"IRCCloud.Server" forClass:Server.class]; [NSKeyedUnarchiver setClass:Server.class forClassName:@"IRCCloud.Server"]; if([[[NSUserDefaults standardUserDefaults] objectForKey:@"cacheVersion"] isEqualToString:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]) { NSString *cacheFile = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"servers"]; @try { self->_servers = [[NSKeyedUnarchiver unarchiveObjectWithFile:cacheFile] mutableCopy]; } @catch(NSException *e) { [[NSFileManager defaultManager] removeItemAtPath:cacheFile error:nil]; [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"cacheVersion"]; [[BuffersDataSource sharedInstance] clear]; [[ChannelsDataSource sharedInstance] clear]; [[EventsDataSource sharedInstance] clear]; [[UsersDataSource sharedInstance] clear]; } } if(!_servers) self->_servers = [[NSMutableArray alloc] init]; } return self; } -(void)serialize { NSString *cacheFile = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"servers"]; NSArray *servers; @synchronized(self->_servers) { servers = [self->_servers copy]; } @synchronized(self) { @try { [NSKeyedArchiver archiveRootObject:servers toFile:cacheFile]; [[NSURL fileURLWithPath:cacheFile] setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:NULL]; } @catch (NSException *exception) { [[NSFileManager defaultManager] removeItemAtPath:cacheFile error:nil]; } } } -(void)clear { @synchronized(self->_servers) { [self->_servers removeAllObjects]; } } -(void)addServer:(Server *)server { @synchronized(self->_servers) { [self->_servers addObject:server]; } } -(NSArray *)getServers { @synchronized(self->_servers) { return [self->_servers sortedArrayUsingSelector:@selector(compare:)]; } } -(Server *)getServer:(int)cid { NSArray *copy; @synchronized(self->_servers) { copy = self->_servers.copy; } for(Server *server in copy) { if(server.cid == cid) return server; } return nil; } -(Server *)getServer:(NSString *)hostname port:(int)port { NSArray *copy; @synchronized(self->_servers) { copy = self->_servers.copy; } for(Server *server in copy) { if([server.hostname isEqualToString:hostname] && (port == -1 || server.port == port)) return server; } return nil; } -(Server *)getServer:(NSString *)hostname SSL:(BOOL)ssl { NSArray *copy; @synchronized(self->_servers) { copy = self->_servers.copy; } for(Server *server in copy) { if([server.hostname isEqualToString:hostname] && ((ssl == YES && server.ssl > 0) || (ssl == NO && server.ssl == 0))) return server; } return nil; } -(void)removeServer:(int)cid { @synchronized(self->_servers) { Server *server = [self getServer:cid]; if(server) [self->_servers removeObject:server]; } } -(void)removeAllDataForServer:(int)cid { Server *server = [self getServer:cid]; if(server) { for(Buffer *b in [[BuffersDataSource sharedInstance] getBuffersForServer:cid]) { [[BuffersDataSource sharedInstance] removeAllDataForBuffer:b.bid]; } @synchronized(self->_servers) { [self->_servers removeObject:server]; } } } -(NSUInteger)count { @synchronized(self->_servers) { return _servers.count; } } -(void)updateNick:(NSString *)nick server:(int)cid { Server *server = [self getServer:cid]; if(server) server.nick = nick; } -(void)updateStatus:(NSString *)status failInfo:(NSDictionary *)failInfo server:(int)cid { Server *server = [self getServer:cid]; if(server) { server.status = status; server.fail_info = failInfo; } } -(void)updateAway:(NSString *)away server:(int)cid { Server *server = [self getServer:cid]; if(server) server.away = away; } -(void)updateUsermask:(NSString *)usermask server:(int)cid { Server *server = [self getServer:cid]; if(server) server.usermask = usermask; } -(void)updateMode:(NSString *)mode server:(int)cid { Server *server = [self getServer:cid]; if(server) server.mode = mode; } -(void)updateIsupport:(NSDictionary *)isupport server:(int)cid { Server *server = [self getServer:cid]; if(server) { if([isupport isKindOfClass:[NSDictionary class]]) { NSMutableDictionary *d = [[NSMutableDictionary alloc] initWithDictionary:server.isupport]; [d addEntriesFromDictionary:isupport]; server.isupport = d; } else { server.isupport = [[NSMutableDictionary alloc] init]; } if([[server.isupport objectForKey:@"PREFIX"] isKindOfClass:[NSDictionary class]]) server.PREFIX = [server.isupport objectForKey:@"PREFIX"]; else server.PREFIX = nil; if([[server.isupport objectForKey:@"CHANTYPES"] isKindOfClass:[NSString class]]) server.CHANTYPES = [server.isupport objectForKey:@"CHANTYPES"]; else server.CHANTYPES = nil; for(Buffer *b in [[BuffersDataSource sharedInstance] getBuffersForServer:cid]) { b.chantypes = server.CHANTYPES; } server.blocksTyping = [server clientTagDeny:@"typing"] && [server clientTagDeny:@"draft/typing"]; server.blocksReplies = [server clientTagDeny:@"draft/reply"]; server.blocksReactions = server.blocksReplies || [server clientTagDeny:@"draft/react"]; server.blocksEdits = [server clientTagDeny:@"draft/edit"] || [server clientTagDeny:@"draft/edit-text"]; server.blocksDeletes = [server clientTagDeny:@"draft/delete"]; } } -(void)updateIgnores:(NSArray *)ignores server:(int)cid { Server *server = [self getServer:cid]; if(server) server.ignores = ignores; } -(void)updateUserModes:(NSString *)modes server:(int)cid { if([modes isKindOfClass:[NSString class]] && modes.length) { Server *server = [self getServer:cid]; if(server) { if([[modes.lowercaseString substringToIndex:1] isEqualToString:[server.isupport objectForKey:@"OWNER"]]) { server.MODE_OWNER = [modes substringToIndex:1]; if([server.MODE_OWNER.lowercaseString isEqualToString:server.MODE_OPER.lowercaseString]) server.MODE_OPER = @""; } } } } @end
{ "pile_set_name": "Github" }
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a5e90258-e031-4e3a-9a27-3ad25ef2f18d")]
{ "pile_set_name": "Github" }
--- order: 4 zh-CN: title: disable状态 en-US: title: Disable status --- ```jsx import { NumberInput } from 'zent'; ReactDOM.render( <div> <NumberInput value={3} disabled /> <NumberInput value={3} disabled showStepper /> <NumberInput value={3} disabled showCounter/> </div> , mountNode ); ```
{ "pile_set_name": "Github" }
package multithreads.waitAndNotify; import java.util.LinkedList; import java.util.Queue; public class TaskQueue { Queue<String> queue = new LinkedList<>(); public synchronized void addTask(String s) { // 如何让等待的线程被重新唤醒,然后从wait()方法返回?答案是在相同的锁对象上调用notify()方法 this.queue.add(s); // this.notify(); this.notifyAll(); } public synchronized String getTask() { while (queue.isEmpty()) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } return queue.remove(); } }
{ "pile_set_name": "Github" }
.tundra .dijitTitlePaneTitle { background: #cccccc; background:#fff url("images/titleBar.png") repeat-x bottom left; border:1px solid #bfbfbf; padding:3px 4px; } .tundra .dijitTitlePaneTitleHover { background: #f8fafd url("images/accordionItemHover.gif") bottom repeat-x; } .tundra .dijitTitlePane .dijitArrowNode { background-image: url('images/spriteArrows.png'); background-repeat: no-repeat; background-position: 0px 0px; height: 7px; width: 7px; } .dj_ie6 .tundra .dijitTitlePane .dijitArrowNode { background-image: url('images/spriteArrows.gif'); } .tundra .dijitTitlePane .dijitClosed .dijitArrowNode { background-position: -14px 0px; } .tundra .dijitTitlePaneContentOuter { background: #ffffff; border:1px solid #bfbfbf; border-top: 0px; } .tundra .dijitTitlePaneContentInner { padding:10px; } .tundra .dijitTitlePaneTextNode { margin-left: 4px; margin-right: 4px; }
{ "pile_set_name": "Github" }
Quick instructions for testing your mozart installation. From <build-dir>/share/test: make boot-all - Builds all tests with the compiler in <build-dir> make boot-check - Runs all tests (except dp) with the emulator in <build-dir> You can also run oztest and ozbench with the oz from your path/OZ_HOME. Run oztest -h ozbench -h for lots of options.
{ "pile_set_name": "Github" }
### xargo宣布进入maintenance 模式 [issues](https://github.com/japaric/xargo/issues/193) 意味着作者不会在添加新的功能或者是修改Bug,但是开放PR,因为作者坚持这是个临时解决方案。作用要专注于开发 ARM Cortex-M (不清楚是什么项目) --- ### 探讨Rust和它在数据科学的立场 [rust and its stance in data science](https://medium.com/@e_net4/rust-and-its-stance-in-data-science-76d2c5ad2363) 结论: 看好Rust --- ### Future by Example [future by example](http://paulkernfeld.com/2018/01/20/future-by-example.html) --- ### 给Rust新人:从命令行开始使用Rust [rust on command line](http://asquera.de/blog/2018-01-20/getting-started-with-rust-on-the-command-line/) --- ### RFC PR: Add `Option::replace` to the core library [RFC](https://github.com/rust-lang/rfcs/pull/2296) 这个RFC有意思 --- ### 另一篇Wasm和Javascript的性能分析文 [floyd steinberg dithering](https://www.polaris64.net/blog/programming/2018/rust-webassembly-javascript-floyd-steinberg-dithering-performance) --- ### pest发布了1.0版本 [pest](https://github.com/pest-parser/pest) 又一个解析器? --- ### 用Rust控制Sonos音箱 [sonos.rs](https://github.com/w4/sonos.rs) --- ### 使用Rust演示几个图像算法 [evolving line art](https://gkbrk.com/2018/01/evolving-line-art/)
{ "pile_set_name": "Github" }
/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkValidatingReadBuffer_DEFINED #define SkValidatingReadBuffer_DEFINED #include "SkRefCnt.h" #include "SkBitmapHeap.h" #include "SkReadBuffer.h" #include "SkWriteBuffer.h" #include "SkPath.h" #include "SkPicture.h" #include "SkReader32.h" class SkBitmap; class SkValidatingReadBuffer : public SkReadBuffer { public: SkValidatingReadBuffer(const void* data, size_t size); virtual ~SkValidatingReadBuffer(); virtual const void* skip(size_t size) SK_OVERRIDE; // primitives virtual bool readBool() SK_OVERRIDE; virtual SkColor readColor() SK_OVERRIDE; virtual SkFixed readFixed() SK_OVERRIDE; virtual int32_t readInt() SK_OVERRIDE; virtual SkScalar readScalar() SK_OVERRIDE; virtual uint32_t readUInt() SK_OVERRIDE; virtual int32_t read32() SK_OVERRIDE; // strings -- the caller is responsible for freeing the string contents virtual void readString(SkString* string) SK_OVERRIDE; virtual void* readEncodedString(size_t* length, SkPaint::TextEncoding encoding) SK_OVERRIDE; // common data structures virtual SkFlattenable* readFlattenable(SkFlattenable::Type type) SK_OVERRIDE; virtual void skipFlattenable() SK_OVERRIDE; virtual void readPoint(SkPoint* point) SK_OVERRIDE; virtual void readMatrix(SkMatrix* matrix) SK_OVERRIDE; virtual void readIRect(SkIRect* rect) SK_OVERRIDE; virtual void readRect(SkRect* rect) SK_OVERRIDE; virtual void readRegion(SkRegion* region) SK_OVERRIDE; virtual void readPath(SkPath* path) SK_OVERRIDE; // binary data and arrays virtual bool readByteArray(void* value, size_t size) SK_OVERRIDE; virtual bool readColorArray(SkColor* colors, size_t size) SK_OVERRIDE; virtual bool readIntArray(int32_t* values, size_t size) SK_OVERRIDE; virtual bool readPointArray(SkPoint* points, size_t size) SK_OVERRIDE; virtual bool readScalarArray(SkScalar* values, size_t size) SK_OVERRIDE; // helpers to get info about arrays and binary data virtual uint32_t getArrayCount() SK_OVERRIDE; // TODO: Implement this (securely) when needed virtual SkTypeface* readTypeface() SK_OVERRIDE; virtual bool validate(bool isValid) SK_OVERRIDE; virtual bool isValid() const SK_OVERRIDE; virtual bool validateAvailable(size_t size) SK_OVERRIDE; private: bool readArray(void* value, size_t size, size_t elementSize); void setMemory(const void* data, size_t size); static bool IsPtrAlign4(const void* ptr) { return SkIsAlign4((uintptr_t)ptr); } bool fError; typedef SkReadBuffer INHERITED; }; #endif // SkValidatingReadBuffer_DEFINED
{ "pile_set_name": "Github" }
@import '~less/global-variables'; /** * Editor */ // Our own customizations .tr-editor { border: 0; background: transparent; box-shadow: none; height: auto; resize: none; margin: 0; padding: 0; cursor: text; min-height: 100px; &:hover { background: fade(@brand-primary, 10%); } &:focus { background: transparent; outline: none; border: 0; } } /* * Bootstrap theme for Medium-editor * Adapted from https://raw.githubusercontent.com/daviferreira/medium-editor/master/src/sass/themes/bootstrap.scss * * When updating: * - Copypaste that sass here * - Remove Variables from the beginning (they're kept at ./public/less/variables.less) * - Replace $ -> @ * - Replace: * rgba(@medium_editor_placeholder_color, .8) * With: * rgba(red(@medium_editor_placeholder_color), green(@medium_editor_placeholder_color), blue(@medium_editor_placeholder_color), .8) * - Fix indentation to be 2 spaces instead of 4 */ .medium-toolbar-arrow-under:after { top: @medium_editor_button_size; border-color: @medium_editor_bgcolor transparent transparent transparent; } .medium-toolbar-arrow-over:before { border-color: transparent transparent @medium_editor_bgcolor transparent; } .medium-editor-toolbar { border: 1px solid @medium_editor_border_color; background-color: @medium_editor_bgcolor; border-radius: @medium_editor_border_radius; li { button { min-width: @medium_editor_button_size; height: @medium_editor_button_size; line-height: @medium_editor_button_size; border: none; border-right: 1px solid @medium_editor_border_color; background-color: transparent; color: @medium_editor_link_color; padding: 0 5px; font-size: 20px; box-sizing: border-box; transition: background-color 0.2s ease-in, color 0.2s ease-in; &:hover { background-color: @medium_editor_hover_color; color: @medium_editor_button_active_text_color; } } .medium-editor-button-first { border-top-left-radius: @medium_editor_border_radius; border-bottom-left-radius: @medium_editor_border_radius; } .medium-editor-button-last { border-right: none; border-top-right-radius: @medium_editor_border_radius; border-bottom-right-radius: @medium_editor_border_radius; } .medium-editor-button-active { background-color: @medium_editor_hover_color; color: @medium_editor_button_active_text_color; } } } .medium-editor-toolbar-form { background: @medium_editor_bgcolor; color: #fff; border-radius: @medium_editor_border_radius; .medium-editor-toolbar-input { height: @medium_editor_button_size; background: @medium_editor_bgcolor; color: @medium_editor_link_color; margin: 0; padding: 0 5px; line-height: @medium_editor_button_size; &::-webkit-input-placeholder { color: @medium_editor_link_color; color: rgba( red(@medium_editor_link_color), green(@medium_editor_link_color), blue(@medium_editor_link_color), 0.8 ); } &:-moz-placeholder { /* Firefox 18- */ color: @medium_editor_placeholder_color; color: rgba( red(@medium_editor_link_color), green(@medium_editor_link_color), blue(@medium_editor_link_color), 0.8 ); } &::-moz-placeholder { /* Firefox 19+ */ color: @medium_editor_placeholder_color; color: rgba( red(@medium_editor_link_color), green(@medium_editor_link_color), blue(@medium_editor_link_color), 0.8 ); } &:-ms-input-placeholder { color: @medium_editor_placeholder_color; color: rgba( red(@medium_editor_link_color), green(@medium_editor_link_color), blue(@medium_editor_link_color), 0.8 ); } } a { color: @medium_editor_link_color; margin: 0; line-height: 55px; padding: 0 10px; &:hover { text-decoration: none; background-color: @medium_editor_hover_color; color: @medium_editor_button_active_text_color; } } } .medium-editor-toolbar-anchor-preview { background: @medium_editor_bgcolor; color: @medium_editor_link_color; border-radius: @medium_editor_border_radius; } .tr-editor.ng-empty, .medium-editor-placeholder:after { color: @medium_editor_placeholder_color; }
{ "pile_set_name": "Github" }
// 答题 class Solution { // leetcode 20. 有效的括号 isValid (s) { /** * @param {string} s * @return {boolean} */ var isValid = function(s) { let stack = []; // 以遍历的方式进行匹配操作 for (let i = 0; i < s.length; i++) { // 是否是正括号 switch (s[i]) { case '{' : case '[' : case '(' : stack.push(s[i]); break; default: break; } // 是否是反括号 switch (s[i]) { case '}' : if (stack.length === 0 || stack.pop() !== '{') { console.log("valid error. not parentheses. in"); return false; } break; case ']' : if (stack.length === 0 || stack.pop() !== '[') { console.log("valid error. not parentheses. in"); return false; } break; case ')' : if (stack.length === 0 || stack.pop() !== '(') { console.log("valid error. not parentheses. in"); return false; } break; default: break; } } // 是否全部匹配成功 if (stack.length === 0) { return true; } else { console.log("valid error. not parentheses. out"); return false; } } return isValid(s); } // leetcode 203. 移除链表元素 removeElements (head, val) { /** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @param {number} val * @return {ListNode} */ var removeElements = function(head, val) { // 对头步进行特殊处理 while(head !== null && head.val === val) { head = head.next; } // 处理后的头部如果为null 那直接返回 if (head === null) { return null; } // 因为头部已经做了特殊处理, head即不为null 并且 head.val不等于null // 那么可以直接从 head的下一个节点开始判断。 let prev = head; while(prev.next !== null) { if (prev.next.val === val) { let delNode = prev.next; prev.next = delNode.next; delNode = null; } else { prev = prev.next; } } return head; }; var removeElements = function(head, val) { if (head === null) { return null; } let dummyHead = new ListNode(0); dummyHead.next = head; let cur = dummyHead; while (cur.next !== null) { if (cur.next.val === val) { cur.next = cur.next.next; } else { cur = cur.next; } } return dummyHead.next; }; // 递归求解三种方式 var removeElements = function(head, val) { // 解决最基本的问题 if (head === null) { return null; } // 第一种解决方式 // let node = removeElements(head.next, val); // if (head.val === val) { // head = node; // } else { // head.next = node; // } // return head; // 第二种解决方式 // if (head.val === val) { // head = removeElements(head.next, val); // } else { // head.next = removeElements(head.next, val); // } // return head; // 第三种方式 head.next = removeElements(head.next, val); if (head.val === val) { return head.next; } else { return head; } } // 尾递归的方式 失败 没有到达那个程度 // var removeElements = function(head, val, node = null) { // if (head === null) { // return node; // } // return removeElements(head.next, val , node = head); // } // 深入理解递归过程 var removeElements = function(head, val, depth = 0) { // 首次输出 开始调用函数 let depthString = generateDepathString(depth); let info = depthString + "Call: remove " + val + " in " + head; show(info); if (head === null) { // 第二次输出 解决最基本的问题时 info = depthString + "Return :" + head; show(info); return null; } let result = removeElements(head.next, val, depth + 1); // 第三次输出 将原问题分解为小问题 info = depthString + "After: remove " + val + " :" + result; show(info); let ret = null; if (head.val === val) { ret = result; } else { head.next = result; ret = head; } // 第四次输出 求出小问题的解 info = depthString + "Return :" + ret; show(info); return ret; } // 辅助函数 生成递归深度字符串 function generateDepathString (depth) { let arrInfo = ``; for (var i = 0; i < depth; i++) { arrInfo += `-- `;// -- 表示深度,--相同则代表在同一递归深度 } return arrInfo; } // 辅助函数 输出内容 到页面和控制台上 function show (content) { document.body.innerHTML += `${content}<br /><br />`; console.log(content); } return removeElements(head, val); } }
{ "pile_set_name": "Github" }
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its level order traversal as: [ [3], [9,20], [15,7] ]
{ "pile_set_name": "Github" }
# 如何写好的技术简历? - [是时候更新一下你的简历了](https://zhuanlan.zhihu.com/p/89522100)
{ "pile_set_name": "Github" }
#!/usr/bin/env bash # vim:noet:sts=4:ts=4:sw=4:tw=120 #======================================================================================================================= # (c) 2014 Clemens Lang, neverpanic.de # See https://neverpanic.de/blog/2014/03/19/downloading-google-web-fonts-for-local-hosting/ for details. # # With modifications by # - Chris Jung, campino2k.de, and # - Robert, github.com/rotx. # # Changelog: # Version 1.1, 2014-06-21 # - Remove colons and spaces from file names for Windows compatibility # - Add check for Bash version, 4.x is required # - Correctly handle fonts without a local PostScript name # - Change format('ttf') to format('truetype') in CSS output # - Add license header and comments # - Added sed extended regex flag detection # Version 1.0, 2014-03-19 # # License: # Copyright (c) 2014, Clemens Lang # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the # following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following # disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the # following disclaimer in the documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #======================================================================================================================= #======================================================================================================================= # Place this script in the directory where you want the font files to be downloaded and a font.css file using the fonts # to be created. Adjust the list of fonts in the $families variable below with the names of the Google fonts you want to # use. If you like, you can adjust the $css variable to write the generated CSS to a different file. Not that this file # will be created and overwritten if it exists. #======================================================================================================================= declare -a families families+=('Open+Sans:400') families+=('Open+Sans:600') # Adjust this is you want the created file to have a different name. Note that this file will be overwritten! css="font.css" url="http://fonts.googleapis.com/css?family=Open+Sans:400,600" #======================================================================================================================= # No user-serviceable parts below this line. If you just want to use this script, you can stop reading here. # # If you made modifications you'd like to see merged into this script, please mail me a patch to 'cl' at 'clang' dot # 'name' or leave a comment at https://neverpanic.de/blog/2014/03/19/downloading-google-web-fonts-for-local-hosting/. #======================================================================================================================= # Ensure the bash version is new enough. If it isn't error out with a helpful error message rather than crashing later. # if [ ${BASH_VERSINFO[0]} -lt 4 ]; then # echo "Error: This script needs Bash 4.x to run." >&2 # exit 1 # fi # Check whether sed is GNU or BSD sed, or rather, which parameter enables extended regex support. Note that GNU sed does # have -E as an undocumented compatibility option on some systems. if [ "$(echo "test" | sed -E 's/([st]+)$/xx\1/' 2>/dev/null)" == "texxst" ]; then ESED="sed -E" elif [ "$(echo "test" | sed -r 's/([st]+)$/xx\1/' 2>/dev/null)" == "texxst" ]; then ESED="sed -r" else echo "Error: $(which sed) seems to lack extended regex support with -E or -r." >&2 exit 2 fi # Store the useragents we're going to use to trick Google's servers into serving us the correct CSS file. declare -A useragent useragent[eot]='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)' useragent[woff]='Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0' useragent[svg]='Mozilla/4.0 (iPad; CPU OS 4_0_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/4.1 Mobile/9A405 Safari/7534.48.3' useragent[ttf]='Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.54.16 (KHTML, like Gecko) Version/5.1.4 Safari/534.54.16' # Clear the output file >"$css" # Loop over the fonts, and download them one-by-one for family in "${families[@]}"; do echo -n "Downloading ${family}... " printf "@font-face {\n" >>"$css" # Extract name, Windows-safe filename, font style and font weight from the font family name fontname=$(echo "$family" | awk -F : '{print $1}') fontnameescaped=$(echo "$family" | $ESED 's/( |:)/_/g') fontstyle=$(echo "$family" | awk -F : '{print $2}') fontweight=$(echo "$fontstyle" | $ESED 's/italic$//g') printf "\tfont-family: '%s';\n" "$fontname" >>"$css" # $fontstyle could be bolditalic, bold, italic, normal, or nothing. case "$fontstyle" in *italic) printf "\tfont-style: italic;\n" >>"$css" ;; *) printf "\tfont-style: normal;\n" >>"$css" ;; esac # Either bold, a number, or empty. If empty, default to "normal". printf "\tfont-weight: %s;\n" "${fontweight:-normal}" >>"$css" printf "\tsrc:\n" >>"$css" # Determine the local names for the given fonts so we can use a locally-installed font if available. local_name=$(curl -sf --get --data-urlencode "family=$family" "$url" | grep -E "src:" | $ESED "s/^.*src: local\\('([^']+)'\\),.*$/\\1/g") local_postscript_name=$(curl -sf --get --data-urlencode "family=$family" "$url" | grep -E "src:" | $ESED "s/^.*, local\\('([^']+)'\\),.*$/\\1/g") # Some fonts don't have a local PostScript name. printf "\t\tlocal('%s'),\n" "$local_name" >>"$css" if [ -n "$local_postscript_name" ]; then printf "\t\tlocal('%s'),\n" "$local_postscript_name" >>"$css" fi # For each font format, download the font file and print the corresponding CSS statements. for uakey in eot woff ttf svg; do echo -n "$uakey " # Download Google's CSS and throw some regex at it to find the font's URL if [ "$uakey" != "svg" ]; then pattern="http:\\/\\/[^\\)]+\\.$uakey" else pattern="http:\\/\\/[^\\)]+" fi file=$(curl -sf -A "${useragent[$uakey]}" --get --data-urlencode "family=$family" "$url" | grep -Eo "$pattern" | sort -u) printf "\t\t/* from %s */\n" "$file" >>"$css" if [ "$uakey" == "svg" ]; then # SVG fonts need the font after a hash symbol, so extract the correct name from Google's CSS svgname=$(echo "$file" | $ESED 's/^[^#]+#(.*)$/\1/g') fi # Actually download the font file curl -sfL "$file" -o "${fontnameescaped}.$uakey" # Generate the CSS statements required to include the downloaded file. case "$uakey" in eot) printf "\t\turl('%s?#iefix') format('embedded-opentype'),\n" "${fontnameescaped}.$uakey" >>"$css" ;; woff) printf "\t\turl('%s') format('woff'),\n" "${fontnameescaped}.$uakey" >>"$css" ;; ttf) printf "\t\turl('%s') format('truetype'),\n" "${fontnameescaped}.$uakey" >>"$css" ;; svg) printf "\t\turl('%s#%s') format('svg');\n" "${fontnameescaped}.${uakey}" "$svgname" >>"$css" ;; esac done printf "}\n" >>"$css" echo done
{ "pile_set_name": "Github" }
# Flambe The Flambe command-line tool. Visit [getflambe.com] for install instructions. [getflambe.com]: http://getflambe.com
{ "pile_set_name": "Github" }
/*============================================================================= Copyright (c) 2014-2015 Kohei Takahashi 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 FUSION_AS_VECTOR_11052014_1801 #define FUSION_AS_VECTOR_11052014_1801 #include <boost/fusion/support/config.hpp> #include <boost/fusion/container/vector/detail/config.hpp> /////////////////////////////////////////////////////////////////////////////// // Without variadics, we will use the PP version /////////////////////////////////////////////////////////////////////////////// #if !defined(BOOST_FUSION_HAS_VARIADIC_VECTOR) # include <boost/fusion/container/vector/detail/cpp03/as_vector.hpp> #else /////////////////////////////////////////////////////////////////////////////// // C++11 interface /////////////////////////////////////////////////////////////////////////////// #include <boost/fusion/support/detail/index_sequence.hpp> #include <boost/fusion/container/vector/vector.hpp> #include <boost/fusion/iterator/value_of.hpp> #include <boost/fusion/iterator/deref.hpp> #include <boost/fusion/iterator/advance.hpp> #include <cstddef> namespace boost { namespace fusion { namespace detail { BOOST_FUSION_BARRIER_BEGIN template <typename Indices> struct as_vector_impl; template <std::size_t ...Indices> struct as_vector_impl<index_sequence<Indices...> > { template <typename Iterator> struct apply { typedef vector< typename result_of::value_of< typename result_of::advance_c<Iterator, Indices>::type >::type... > type; }; template <typename Iterator> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static typename apply<Iterator>::type call(Iterator i) { typedef typename apply<Iterator>::type result; return result(*advance_c<Indices>(i)...); } }; template <int size> struct as_vector : as_vector_impl<typename make_index_sequence<size>::type> {}; BOOST_FUSION_BARRIER_END }}} #endif #endif
{ "pile_set_name": "Github" }
source "http://rubygems.org" # Specify your gem's dependencies in mini_record.gemspec gem 'rake' gem 'minitest' # Test database adapters with "rake test DB=mysql2" gem 'sqlite3' gem 'pg' gem 'mysql' gem 'mysql2' # Uncomment to test older versions, then "bundle update" # gem 'activerecord', '<= 3.2' # gem 'activerecord', '~> 4.0.0' # gem 'activerecord', '~> 4.1.0' gem 'activerecord', '>= 4.2.0' group :test do gem 'foreigner', '>= 1.4.2' end gemspec
{ "pile_set_name": "Github" }
package timestampmap import ( "sync" "whapp-irc/whapp" ) // A Map contains the last timestamp per chat ID. type Map struct { mutex sync.RWMutex m map[string]int64 } // New contains a new Map. func New() *Map { return &Map{ m: make(map[string]int64), } } // Get returns the value attachted to the given chat ID. func (tm *Map) Get(id whapp.ID) (val int64, found bool) { tm.mutex.RLock() defer tm.mutex.RUnlock() val, found = tm.m[id.String()] return val, found } // Set sets the timestamp for the given chat ID. func (tm *Map) Set(id whapp.ID, val int64) { tm.mutex.Lock() defer tm.mutex.Unlock() tm.m[id.String()] = val } // GetCopy returns a copy of the internal map. func (tm *Map) GetCopy() map[string]int64 { res := make(map[string]int64) tm.mutex.RLock() for k, v := range tm.m { res[k] = v } tm.mutex.RUnlock() return res } // Swap swaps the internal map for the given one. func (tm *Map) Swap(m map[string]int64) { tm.mutex.Lock() defer tm.mutex.Unlock() tm.m = m } // Length returns the amount of timestamps stored in the map. func (tm *Map) Length() int { tm.mutex.RLock() defer tm.mutex.RUnlock() return len(tm.m) }
{ "pile_set_name": "Github" }
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import mnist_inference import os BATCH_SIZE = 100 LEARNING_RATE_BASE = 0.8 LEARNING_RATE_DECAY = 0.99 REGULARIZATION_RATE = 0.0001 TRAINING_STEPS = 30000 MOVING_AVERAGE_DECAY = 0.99 MODEL_SAVE_PATH="MNIST_model/" MODEL_NAME="mnist_model" def train(mnist): x = tf.placeholder(tf.float32, [None, mnist_inference.INPUT_NODE], name='x-input') y_ = tf.placeholder(tf.float32, [None, mnist_inference.OUTPUT_NODE], name='y-input') regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE) y = mnist_inference.inference(x, regularizer) global_step = tf.Variable(0, trainable=False) variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step) variables_averages_op = variable_averages.apply(tf.trainable_variables()) cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, 1)) cross_entropy_mean = tf.reduce_mean(cross_entropy) loss = cross_entropy_mean + tf.add_n(tf.get_collection('losses')) learning_rate = tf.train.exponential_decay( LEARNING_RATE_BASE, global_step, mnist.train.num_examples / BATCH_SIZE, LEARNING_RATE_DECAY, staircase=True) train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step) with tf.control_dependencies([train_step, variables_averages_op]): train_op = tf.no_op(name='train') saver = tf.train.Saver() with tf.Session() as sess: tf.global_variables_initializer().run() for i in range(TRAINING_STEPS): xs, ys = mnist.train.next_batch(BATCH_SIZE) _, loss_value, step = sess.run([train_op, loss, global_step], feed_dict={x: xs, y_: ys}) if i % 1000 == 0: print("After %d training step(s), loss on training batch is %g." % (step, loss_value)) saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME), global_step=global_step) def main(argv=None): mnist = input_data.read_data_sets("../../../datasets/MNIST_data", one_hot=True) train(mnist) if __name__ == '__main__': tf.app.run()
{ "pile_set_name": "Github" }
// stdafx.cpp : source file that includes just the standard includes // TestBsonCodec.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
{ "pile_set_name": "Github" }
# IfElseStmtsMustUseBraces **Category:** `pmd`<br/> **Rule Key:** `pmd:IfElseStmtsMustUseBraces`<br/> > :warning: This rule is **deprecated** in favour of [S00121](https://rules.sonarsource.com/java/RSPEC-121). ----- <p> Avoid using if..else statements without using curly braces. </p>
{ "pile_set_name": "Github" }
-----BEGIN CERTIFICATE----- MIIDwDCCAqigAwIBAgIHBHL9Tb37ezANBgkqhkiG9w0BAQsFADCBnjELMAkGA1UE BhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExEjAQBgNVBAcMCUxvcyBHYXRvczEU MBIGA1UECgwLTmV0ZmxpeCBJbmMxLTArBgNVBAsMJFBsYXRmb3JtIFNlY3VyaXR5 ICgxMjUyMzMyMDgwMDEzNjYxKTEhMB8GA1UEAwwYSW50ZXJtZWRpYXRlIENBIGZv ciAxNDc3MB4XDTIwMDcxNDAzMjExMVoXDTIxMDcxNDAzMDk0NFowgY8xCzAJBgNV BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRIwEAYDVQQHDAlMb3MgR2F0b3Mx FDASBgNVBAoMC05ldGZsaXggSW5jMS0wKwYDVQQLDCRQbGF0Zm9ybSBTZWN1cml0 eSAoMTI1MjMzMjE2MzQxMjI3OCkxEjAQBgNVBAMMCTEyNy4wLjAuMTCCASIwDQYJ KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMVE7hmmF25LC4sEx717goF/MhqWxSI8 g901dqRt9v9rgzWnEffm44teR6jBBq0Vx6AcJ8xISHI/JXVljWqzj5SqxnRGUFrU UD5Ji5R9y7gSICZNzMgyw+2kbaJU0BT5kIoHkaibStrBPxC+andqhv51DwW0HoAa LOususGHlo072hZYoEVNbN3ThfjksyoNuOZK3Bf/zqYXW4CtY1Pd0/Hagu5LFVsl R7/k+vBsuPWUgO2kNOx3NIEg63coN36okMUeUUx2GalT+TvC72fFZHSabBxb4tJ2 0CpNhvK9h6Fd5CRuXQDdexsOqWtUS4Tn85HJ7NEI3DgMNjq1DjsgvPUCAwEAAaMQ MA4wDAYDVR0TAQH/BAIwADANBgkqhkiG9w0BAQsFAAOCAQEAhtHoDQGAxwG4Bw7V km6mSDZZrq+6bUQNjGi2Xx85kWc2mciJj+Degk8czrr/Zw4+woL2zy5zWqr0Coxx 9ASJZxOdlG8uJi0Vczx2WCSy/YY9b3fjqGimlcPXb+1NO8R3T47AXmClJseSPbeH YL38CKgT0Se6pX42U7WjnGEp4/tbkFdQY2T4uZ2267HEg7y2dN3nbleLULESeamT 52dh/IQvHI5ooY1dceEESqQmT+vUZN1YbWsJ/4FhsvNNRyA3cFTCLwy7y6z5xRTQ B/voMNUnwZ9S8MigRAMlcc9wWKCq9qSdrg9z2ncm3oSgFQU2AQCRcvhSsqrzsSY6 SaLmhw== -----END CERTIFICATE-----
{ "pile_set_name": "Github" }
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file linearIntegrator.cxx * @author charles * @date 2000-08-02 */ #include "linearIntegrator.h" #include "config_physics.h" #include "physicalNode.h" #include "forceNode.h" ConfigVariableDouble LinearIntegrator::_max_linear_dt ("default_max_linear_dt", 1.0f / 30.0f); /** * constructor */ LinearIntegrator:: LinearIntegrator() { } /** * destructor */ LinearIntegrator:: ~LinearIntegrator() { } /** * parent integration routine, hands off to child virtual. */ void LinearIntegrator:: integrate(Physical *physical, LinearForceVector &forces, PN_stdfloat dt) { /* <-- darren, 2000.10.06 // cap dt so physics don't go flying off on lags if (dt > _max_linear_dt) dt = _max_linear_dt; */ PhysicsObject::Vector::const_iterator current_object_iter; current_object_iter = physical->get_object_vector().begin(); for (; current_object_iter != physical->get_object_vector().end(); ++current_object_iter) { PhysicsObject *current_object = *current_object_iter; // bail out if this object doesn't exist or doesn't want to be processed. if (current_object == nullptr) { continue; } // set the object's last position to its current position before we move // it current_object->set_last_position(current_object->get_position()); } child_integrate(physical, forces, dt); } /** * Write a string representation of this instance to <out>. */ void LinearIntegrator:: output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"LinearIntegrator"; #endif //] NDEBUG } /** * Write a string representation of this instance to <out>. */ void LinearIntegrator:: write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"LinearIntegrator:\n"; out.width(indent+2); out<<""; out<<"_max_linear_dt "<<_max_linear_dt<<" (class static)\n"; BaseIntegrator::write(out, indent+2); #endif //] NDEBUG }
{ "pile_set_name": "Github" }
<style type="text/css"> foo-bar2 { } </style> <foo-<caret>bar2></foo-bar2>
{ "pile_set_name": "Github" }
// Created on: 1993-05-07 // Created by: Jean Yves LEBEY // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #include <TopOpeBRep_ShapeIntersector2d.ixx> #include <Standard_ProgramError.hxx> #include <Standard_NotImplemented.hxx> #include <TopAbs.hxx> #include <Bnd_Box.hxx> #include <TopOpeBRepTool_box.hxx> #ifdef OCCT_DEBUG extern Standard_Boolean TopOpeBRep_GettraceSI(); extern Standard_Boolean TopOpeBRep_GetcontextFFOR(); #endif //======================================================================= //function : TopOpeBRep_ShapeIntersector2d //purpose : //======================================================================= TopOpeBRep_ShapeIntersector2d::TopOpeBRep_ShapeIntersector2d() { Reset(); myHBoxTool = FBOX_GetHBoxTool(); myFaceScanner.ChangeBoxSort().SetHBoxTool(myHBoxTool); myEdgeScanner.ChangeBoxSort().SetHBoxTool(myHBoxTool); } //======================================================================= //function : Reset //purpose : //======================================================================= void TopOpeBRep_ShapeIntersector2d::Reset() { myIntersectionDone = Standard_False; myFFDone = Standard_False; myEEFFDone = Standard_False; myFFInit = Standard_False; myEEFFInit = Standard_False; } //======================================================================= //function : Init //purpose : //======================================================================= void TopOpeBRep_ShapeIntersector2d::Init (const TopoDS_Shape& S1, const TopoDS_Shape& S2) { Reset(); myShape1 = S1; myShape2 = S2; myHBoxTool->Clear(); } //======================================================================= //function : SetIntersectionDone //purpose : //======================================================================= void TopOpeBRep_ShapeIntersector2d::SetIntersectionDone() { myIntersectionDone = (myFFDone || myEEFFDone); } //======================================================================= //function : CurrentGeomShape //purpose : //======================================================================= const TopoDS_Shape& TopOpeBRep_ShapeIntersector2d::CurrentGeomShape (const Standard_Integer Index) const { if ( myIntersectionDone ) { if (myFFDone) { if ( Index == 1 ) return myFaceScanner.Current(); else if ( Index == 2 ) return myFaceExplorer.Current(); } else if (myEEFFDone) { if ( Index == 1 ) return myEdgeScanner.Current(); else if ( Index == 2 ) return myEdgeExplorer.Current(); } } Standard_ProgramError::Raise("CurrentGeomShape : no intersection 2d"); TopoDS_Shape* bid = new TopoDS_Shape(); return *bid; } //======================================================================= //function : InitIntersection //purpose : //======================================================================= void TopOpeBRep_ShapeIntersector2d::InitIntersection (const TopoDS_Shape& S1, const TopoDS_Shape& S2) { Init(S1,S2); InitFFIntersection(); } //======================================================================= //function : MoreIntersection //purpose : //======================================================================= Standard_Boolean TopOpeBRep_ShapeIntersector2d::MoreIntersection() const { Standard_Boolean res = myIntersectionDone; #ifdef OCCT_DEBUG if (TopOpeBRep_GettraceSI() && res) { if ( myFFDone ) cout<<"FF : "; else if ( myEEFFDone ) cout<<" EE : "; DumpCurrent(1); DumpCurrent(2); } #endif return res; } //======================================================================= //function : DumpCurrent //purpose : //======================================================================= #ifdef OCCT_DEBUG void TopOpeBRep_ShapeIntersector2d::DumpCurrent(const Standard_Integer K) const { if ( myFFDone ) { if ( K == 1 ) myFaceScanner.DumpCurrent(cout); else if ( K == 2 ) myFaceExplorer.DumpCurrent(cout); } else if ( myEEFFDone ) { if ( K == 1 ) myEdgeScanner.DumpCurrent(cout); else if ( K == 2 ) myEdgeExplorer.DumpCurrent(cout); } #else void TopOpeBRep_ShapeIntersector2d::DumpCurrent(const Standard_Integer) const { #endif } //======================================================================= //function : Index //purpose : //======================================================================= #ifdef OCCT_DEBUG Standard_Integer TopOpeBRep_ShapeIntersector2d::Index (const Standard_Integer K)const { Standard_Integer i = 0; if ( myFFDone ) { if ( K == 1 ) i = myFaceScanner.Index(); else if ( K == 2 ) i = myFaceExplorer.Index(); } else if ( myEEFFDone ) { if ( K == 1 ) i = myEdgeScanner.Index(); else if ( K == 2 ) i = myEdgeExplorer.Index(); } return i; } #else Standard_Integer TopOpeBRep_ShapeIntersector2d::Index (const Standard_Integer)const { return 0;} #endif //======================================================================= //function : NextIntersection //purpose : //======================================================================= void TopOpeBRep_ShapeIntersector2d::NextIntersection() { myIntersectionDone = Standard_False; if (myFFDone) { // precedant etat du More() : 2 faces myFFDone = Standard_False; InitEEFFIntersection(); FindEEFFIntersection(); if ( !myIntersectionDone ) { NextFFCouple(); FindFFIntersection(); } } else if ( myEEFFDone ) { NextEEFFCouple(); FindEEFFIntersection(); if ( !myIntersectionDone ) { NextFFCouple(); FindFFIntersection(); } } if ( !myIntersectionDone ) { InitFFIntersection(); } } // ======== // FFFFFFFF // ======== //======================================================================= //function : InitFFIntersection //purpose : //======================================================================= void TopOpeBRep_ShapeIntersector2d::InitFFIntersection() { if ( !myFFInit) { TopAbs_ShapeEnum tscann = TopAbs_FACE; TopAbs_ShapeEnum texplo = TopAbs_FACE; myFaceScanner.Clear(); myFaceScanner.AddBoxesMakeCOB(myShape1,tscann); myFaceExplorer.Init(myShape2,texplo); myFaceScanner.Init(myFaceExplorer); FindFFIntersection(); } myFFInit = Standard_True; } //======================================================================= //function : FindFFIntersection //purpose : //======================================================================= void TopOpeBRep_ShapeIntersector2d::FindFFIntersection() { myFFDone = Standard_False; // myFFSameDomain = Standard_False; if ( MoreFFCouple() ) { // The two candidate intersecting GeomShapes GS1,GS2 and their types t1,t2 const TopoDS_Shape& GS1 = myFaceScanner.Current(); const TopoDS_Shape& GS2 = myFaceExplorer.Current(); #ifdef OCCT_DEBUG if (TopOpeBRep_GettraceSI()) { cout<<"?? FF : "; myFaceScanner.DumpCurrent(cout); myFaceExplorer.DumpCurrent(cout); cout<<endl; } #endif const TopOpeBRepTool_BoxSort& BS = myFaceScanner.BoxSort(); BS.Box(GS1); BS.Box(GS2); myFFDone = Standard_True; } SetIntersectionDone(); } //======================================================================= //function : MoreFFCouple //purpose : //======================================================================= Standard_Boolean TopOpeBRep_ShapeIntersector2d::MoreFFCouple() const { Standard_Boolean more1 = myFaceScanner.More(); Standard_Boolean more2 = myFaceExplorer.More(); return (more1 && more2); } //======================================================================= //function : NextFFCouple //purpose : //======================================================================= void TopOpeBRep_ShapeIntersector2d::NextFFCouple() { myFaceScanner.Next(); Standard_Boolean b1,b2; b1 = (!myFaceScanner.More()); b2 = (myFaceExplorer.More()); while ( b1 && b2 ) { myFaceExplorer.Next(); myFaceScanner.Init(myFaceExplorer); b1 = (!myFaceScanner.More()); b2 = (myFaceExplorer.More()); } } // ======== // EEFFEEFF // ======== //======================================================================= //function : InitEEFFIntersection //purpose : //======================================================================= void TopOpeBRep_ShapeIntersector2d::InitEEFFIntersection() { // prepare exploration of the edges of the two current SameDomain faces TopoDS_Shape face1 = myFaceScanner.Current(); // -26-08-96 TopoDS_Shape face2 = myFaceExplorer.Current(); // -26-08-96 #ifdef OCCT_DEBUG if (TopOpeBRep_GetcontextFFOR()) { face1.Orientation(TopAbs_FORWARD); //-05/07 face2.Orientation(TopAbs_FORWARD); //-05/07 cout<<"ctx : InitEEFFIntersection : faces FORWARD"<<endl; } #endif myEEIntersector.SetFaces(face1,face2); TopAbs_ShapeEnum tscann = TopAbs_EDGE; TopAbs_ShapeEnum texplo = TopAbs_EDGE; myEdgeScanner.Clear(); myEdgeScanner.AddBoxesMakeCOB(face1,tscann); myEdgeExplorer.Init(face2,texplo); myEdgeScanner.Init(myEdgeExplorer); myEEFFInit = Standard_True; } //======================================================================= //function : FindEEFFIntersection //purpose : //======================================================================= void TopOpeBRep_ShapeIntersector2d::FindEEFFIntersection() { myEEFFDone = Standard_False; while ( MoreEEFFCouple() ) { const TopoDS_Shape& GS1 = myEdgeScanner.Current(); const TopoDS_Shape& GS2 = myEdgeExplorer.Current(); myEEIntersector.Perform(GS1,GS2); #ifdef OCCT_DEBUG if (TopOpeBRep_GettraceSI() && myEEIntersector.IsEmpty()) { cout<<" EE : "; myEdgeScanner.DumpCurrent(cout); myEdgeExplorer.DumpCurrent(cout); cout<<"(EE of FF SameDomain)"; cout<<" : EMPTY INTERSECTION"; cout<<endl; } #endif myEEFFDone = ! (myEEIntersector.IsEmpty()); if (myEEFFDone) break; else NextEEFFCouple(); } SetIntersectionDone(); } //======================================================================= //function : MoreEEFFCouple //purpose : //======================================================================= Standard_Boolean TopOpeBRep_ShapeIntersector2d::MoreEEFFCouple() const { Standard_Boolean more1 = myEdgeScanner.More(); Standard_Boolean more2 = myEdgeExplorer.More(); return (more1 && more2); } //======================================================================= //function : NextEEFFCouple //purpose : //======================================================================= void TopOpeBRep_ShapeIntersector2d::NextEEFFCouple() { myEdgeScanner.Next(); while ( ! myEdgeScanner.More() && myEdgeExplorer.More() ) { myEdgeExplorer.Next(); myEdgeScanner.Init(myEdgeExplorer); } } //======================================================================= //function : Shape //purpose : //======================================================================= const TopoDS_Shape& TopOpeBRep_ShapeIntersector2d::Shape ( const Standard_Integer Index )const { if ( Index == 1 ) return myShape1; else if ( Index == 2 ) return myShape2; Standard_ProgramError::Raise("ShapeIntersector : no shape"); TopoDS_Shape* bid = new TopoDS_Shape(); return *bid; } //======================================================================= //function : ChangeEdgesIntersector //purpose : //======================================================================= TopOpeBRep_EdgesIntersector& TopOpeBRep_ShapeIntersector2d::ChangeEdgesIntersector() { return myEEIntersector; }
{ "pile_set_name": "Github" }
/** @file package.h Package containing metadata, data, and/or files. * * @authors Copyright (c) 2014-2017 Jaakko Keränen <[email protected]> * * @par License * LGPL: http://www.gnu.org/licenses/lgpl.html * * <small>This program 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 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 Lesser * General Public License for more details. You should have received a copy of * the GNU Lesser General Public License along with this program; if not, see: * http://www.gnu.org/licenses</small> */ #ifndef LIBDENG2_PACKAGE_H #define LIBDENG2_PACKAGE_H #include "../String" #include "../File" #include "../FileIndex" #include "../Version" #include "../IObject" #include <QSet> namespace de { class Package; /** * Container package with metadata, data, and/or files. * @ingroup fs * * A @em package is a collection of files packaged into a single unit (possibly using an * Archive). Examples of packages are add-on packages (in various formats, e.g., PK3/ZIP * archive or the Snowberry add-on bundle), savegames, custom maps, and demos. * * An instance of Package represents a package that is currently loaded. Note that * the package's metadata namespace is owned by the file that contains the package; * Package only consists of state that is relevant while the package is loaded (i.e., * in active use). */ class DENG2_PUBLIC Package : public IObject { public: /// Package's source is missing or inaccessible. @ingroup errors DENG2_ERROR(SourceError); /// Package fails validation. @ingroup errors DENG2_ERROR(ValidationError); /// Checked metadata does not describe a package. @ingroup errors DENG2_SUB_ERROR(ValidationError, NotPackageError); /// Package is missing some required metadata. @ingroup errors DENG2_SUB_ERROR(ValidationError, IncompleteMetadataError); typedef QSet<String> Assets; /** * Utility for accessing asset metadata. @ingroup fs */ class DENG2_PUBLIC Asset : public RecordAccessor { public: Asset(Record const &rec); Asset(Record const *rec); /** * Retrieves the value of a variable and resolves it to an absolute path in * relation to the asset. * * @param varName Variable name in the package asset metadata. * * @return Absolute path. * * @see ScriptedInfo::absolutePathInContext() */ String absolutePath(String const &varName) const; }; public: /** * Creates a package whose data comes from a file. The file's metadata is used * as the package's metadata namespace. * * @param file File or folder containing the package's contents. */ Package(File const &file); virtual ~Package(); /** * Returns the ".pack" file of the Package. In practice, this may be a ZIP folder, an * regular folder, or a link to a DataBundle. You should use sourceFile() to access * the file in which the package's contents are actually stored. * * @return Package file. */ File const &file() const; /** * Returns the original source file of the package, where the package's contents are * being sourced from. This is usually the file referenced by the "path" member in * the package metadata. */ File const &sourceFile() const; bool sourceFileExists() const; /** * Returns the package's root folder. */ Folder const &root() const; /** * Returns the unique package identifier. This is the file name of the package * without any file extension. */ String identifier() const; /** * Version of the loaded package. The version can be specified either in the * file name (following an underscore) or in the metadata. */ Version version() const; /** * Composes a list of assets contained in the package. * * @return Assets declared in the package metadata. */ Assets assets() const; /** * Executes a script function in the metadata of the package. * * @param name Name of the function to call. * * @return @c true, if the function exists and was called. @c false, if the * function was not found. */ bool executeFunction(String const &name); void setOrder(int ordinal); int order() const; void findPartialPath(String const &path, FileIndex::FoundFiles &found) const; /** * Called by PackageLoader after the package has been marked as loaded. */ virtual void didLoad(); /** * Called by PackageLoader immediately before the package is marked as unloaded. */ virtual void aboutToUnload(); // Implements IObject. Record &objectNamespace(); Record const &objectNamespace() const; public: /** * Parse the embedded metadata found in a package file. * * @param packageFile File containing a package. */ static void parseMetadata(File &packageFile); /** * Checks that all the metadata seems legit. An IncompleteMetadataError or * another exception is thrown if the package is not deemed valid. * * @param packageInfo Metadata to validate. */ static void validateMetadata(Record const &packageInfo); static Record &initializeMetadata(File &packageFile, String const &id = String()); static Record const &metadata(File const &packageFile); static QStringList tags(File const &packageFile); static bool matchTags(File const &packageFile, String const &tagRegExp); static QStringList tags(String const& tagsString); static StringList requires(File const &packageFile); static void addRequiredPackage(File &packageFile, String const &id); static bool hasOptionalContent(String const &packageId); static bool hasOptionalContent(File const &packageFile); /** * Splits a string containing a package identifier and version. The * expected format of the string is `{packageId}_{version}`. * * @param identifier_version Identifier and version. * * @return The split components. */ static std::pair<String, Version> split(String const &identifier_version); static String splitToHumanReadable(String const &identifier_version); static bool equals(String const &id1, String const &id2); static String identifierForFile(File const &file); static String versionedIdentifierForFile(File const &file); static Version versionForFile(File const &file); /** * Locates the file that represents the package where @a file is in. * * @param file File. * * @return Containing package, or nullptr if the file is not inside a package. */ static File const *containerOfFile(File const &file); static String identifierForContainerOfFile(File const &file); /** * Finds the package that contains @a file and returns its modification time. * If the file doesn't appear to be inside a package, returns the file's * modification time. * * @param file File. * * @return Modification time of file or package. */ static Time containerOfFileModifiedAt(File const &file); static String const VAR_PACKAGE; static String const VAR_PACKAGE_ID; static String const VAR_PACKAGE_ALIAS; static String const VAR_PACKAGE_TITLE; static String const VAR_ID; static String const VAR_TITLE; static String const VAR_VERSION; private: DENG2_PRIVATE(d) }; } // namespace de #endif // LIBDENG2_PACKAGE_H
{ "pile_set_name": "Github" }
// Copyright © 2011, Université catholique de Louvain // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifndef MOZART_MODPROPERTY_H #define MOZART_MODPROPERTY_H #include "../mozartcore.hh" #ifndef MOZART_GENERATOR namespace mozart { namespace builtins { ///////////////////// // Property module // ///////////////////// class ModProperty: public Module { public: ModProperty(): Module("Property") {} class RegisterValue: public Builtin<RegisterValue> { public: RegisterValue(): Builtin("registerValue") {} static void call(VM vm, In property, In value) { auto propertyAtom = getArgument<atom_t>(vm, property); vm->getPropertyRegistry().registerValueProp( vm, propertyAtom.contents(), value); } }; class RegisterConstant: public Builtin<RegisterConstant> { public: RegisterConstant(): Builtin("registerConstant") {} static void call(VM vm, In property, In value) { auto propertyAtom = getArgument<atom_t>(vm, property); vm->getPropertyRegistry().registerConstantProp( vm, propertyAtom.contents(), value); } }; class Get: public Builtin<Get> { public: Get(): Builtin("get") {} static void call(VM vm, In property, Out result, Out found) { if (vm->getPropertyRegistry().get(vm, property, result)) { found = build(vm, true); } else { result = build(vm, unit); found = build(vm, false); } } }; class Put: public Builtin<Put> { public: Put(): Builtin("put") {} static void call(VM vm, In property, In value, Out found) { found = build(vm, vm->getPropertyRegistry().put(vm, property, value)); } }; }; } } #endif // MOZART_GENERATOR #endif // MOZART_MODPROPERTY_H
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <objc/NSObject.h> #import <ModelIO/MDLTransformComponent-Protocol.h> @class NSString; @interface MDLTransform : NSObject <MDLTransformComponent> { // Error parsing type: {MDLAffineTransform="_keyedTranslation"{vector<std::__1::pair<double, float __attribute__((ext_vector_type(3)))>, std::__1::allocator<std::__1::pair<double, float __attribute__((ext_vector_type(3)))> > >="__begin_"^{pair<double, float __attribute__((ext_vector_type(3)))>}"__end_"^{pair<double, float __attribute__((ext_vector_type(3)))>}"__end_cap_"{__compressed_pair<std::__1::pair<double, float __attribute__((ext_vector_type(3)))> *, std::__1::allocator<std::__1::pair<double, float __attribute__((ext_vector_type(3)))> > >="__first_"^{pair<double, float __attribute__((ext_vector_type(3)))>}}}"_keyedRotation"{vector<std::__1::pair<double, float __attribute__((ext_vector_type(3)))>, std::__1::allocator<std::__1::pair<double, float __attribute__((ext_vector_type(3)))> > >="__begin_"^{pair<double, float __attribute__((ext_vector_type(3)))>}"__end_"^{pair<double, float __attribute__((ext_vector_type(3)))>}"__end_cap_"{__compressed_pair<std::__1::pair<double, float __attribute__((ext_vector_type(3)))> *, std::__1::allocator<std::__1::pair<double, float __attribute__((ext_vector_type(3)))> > >="__first_"^{pair<double, float __attribute__((ext_vector_type(3)))>}}}"_keyedShear"{vector<std::__1::pair<double, float __attribute__((ext_vector_type(3)))>, std::__1::allocator<std::__1::pair<double, float __attribute__((ext_vector_type(3)))> > >="__begin_"^{pair<double, float __attribute__((ext_vector_type(3)))>}"__end_"^{pair<double, float __attribute__((ext_vector_type(3)))>}"__end_cap_"{__compressed_pair<std::__1::pair<double, float __attribute__((ext_vector_type(3)))> *, std::__1::allocator<std::__1::pair<double, float __attribute__((ext_vector_type(3)))> > >="__first_"^{pair<double, float __attribute__((ext_vector_type(3)))>}}}"_keyedScale"{vector<std::__1::pair<double, float __attribute__((ext_vector_type(3)))>, std::__1::allocator<std::__1::pair<double, float __attribute__((ext_vector_type(3)))> > >="__begin_"^{pair<double, float __attribute__((ext_vector_type(3)))>}"__end_"^{pair<double, float __attribute__((ext_vector_type(3)))>}"__end_cap_"{__compressed_pair<std::__1::pair<double, float __attribute__((ext_vector_type(3)))> *, std::__1::allocator<std::__1::pair<double, float __attribute__((ext_vector_type(3)))> > >="__first_"^{pair<double, float __attribute__((ext_vector_type(3)))>}}}"_startTime"d"_greatestTime"d"_identity"B"_evaluationTime"d"_transform"{float4x4="columns"[4]}"_invTransform"{float4x4="columns"[4]}"_jacobiRotation"{float4x4="columns"[4]}"_invJacobiRotation"{float4x4="columns"[4]}}, name: _transform double _minTime; double _maxTime; } + // Error parsing type: {?=[4]}32@0:8@16d24, name: globalTransformWithObject:atTime: + // Error parsing type: {?=[4]}32@0:8@16d24, name: localTransformWithObject:atTime: - (id).cxx_construct; - (void).cxx_destruct; - // Error parsing type: {?=[4]}24@0:8d16, name: rotationMatrixAtTime: - // Error parsing type: {?=[4]}24@0:8d16, name: localTransformAtTime: - // Error parsing type: v80@0:8{?=[4]}16, name: setLocalTransform: - // Error parsing type: v88@0:8{?=[4]}16d80, name: setLocalTransform:forTime: - // Error parsing type: @80@0:8{?=[4]}16, name: initWithMatrix: - (id)initWithTransformComponent:(id)arg1; - (void)setIdentity; - (id)initWithIdentity; - (id)init; - (void)setTranslation:(double)arg1 forTime: /* Error: Ran out of types for this method. */; - (void)setScale:(double)arg1 forTime: /* Error: Ran out of types for this method. */; - (void)setShear:(double)arg1 forTime: /* Error: Ran out of types for this method. */; - (void)setRotation:(double)arg1 forTime: /* Error: Ran out of types for this method. */; - // Error parsing type: 24@0:8d16, name: rotationAtTime: - // Error parsing type: 24@0:8d16, name: translationAtTime: - // Error parsing type: 24@0:8d16, name: shearAtTime: - // Error parsing type: 24@0:8d16, name: scaleAtTime: // Error parsing type for property rotation: // Property attributes: T,N // Error parsing type for property scale: // Property attributes: T,N // Error parsing type for property shear: // Property attributes: T,N // Error parsing type for property translation: // Property attributes: T,N // Error parsing type for property matrix: // Property attributes: T{?=[4]},N @property(readonly, nonatomic) double maximumTime; @property(readonly, nonatomic) double minimumTime; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
{ "pile_set_name": "Github" }
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphhopper.isochrone.algorithm; import org.locationtech.jts.triangulate.quadedge.Vertex; import java.util.Objects; public class QuadEdgeAsReadableQuadEdge implements ReadableQuadEdge { private final org.locationtech.jts.triangulate.quadedge.QuadEdge delegate; QuadEdgeAsReadableQuadEdge(org.locationtech.jts.triangulate.quadedge.QuadEdge startEdge) { if (startEdge == null) throw new NullPointerException(); this.delegate = startEdge; } public ReadableQuadEdge getPrimary() { return new QuadEdgeAsReadableQuadEdge(delegate.getPrimary()); } public Vertex orig() { return delegate.orig(); } public Vertex dest() { return delegate.dest(); } public ReadableQuadEdge oNext() { return new QuadEdgeAsReadableQuadEdge(delegate.oNext()); } public ReadableQuadEdge oPrev() { return new QuadEdgeAsReadableQuadEdge(delegate.oPrev()); } public ReadableQuadEdge dPrev() { return new QuadEdgeAsReadableQuadEdge(delegate.dPrev()); } public ReadableQuadEdge dNext() { return new QuadEdgeAsReadableQuadEdge(delegate.dNext()); } @Override public ReadableQuadEdge lNext() { return new QuadEdgeAsReadableQuadEdge(delegate.lNext()); } @Override public ReadableQuadEdge sym() { return new QuadEdgeAsReadableQuadEdge(delegate.sym()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; QuadEdgeAsReadableQuadEdge that = (QuadEdgeAsReadableQuadEdge) o; return Objects.equals(delegate, that.delegate); } @Override public int hashCode() { return Objects.hash(delegate); } }
{ "pile_set_name": "Github" }
future==0.16.0 lxml==4.1.1
{ "pile_set_name": "Github" }
#!/bin/bash set -eou pipefail source ../scripts/variables.sh echo "Frontend service address: $(fdfrontend)" echo "Inventory service address: $(fdinventory)" echo "Product service address: $(fdproduct)" ##### # The backend pool for the frontend service in AKS ##### echo "Creating backend pool for frontend service $(fdfrontend)" az network front-door backend-pool create \ -g $(rg) \ --front-door-name $(fdname) \ -n "FrontendBackendPool" \ --load-balancing "loadbalancing1" \ --probe "probe1" \ --address $(fdfrontend) echo "Creating routing rule for frontend service" az network front-door routing-rule create \ -g $(rg) \ --front-door-name $(fdname) \ -n "FrontendServiceRoutingRule" \ --frontend-endpoints "DefaultFrontendEndpoint" \ --backend-pool "FrontendBackendPool" ##### # The backend pool for the inventory service in AKS ##### echo "Creating backend pool or inventory service $(fdinventory)" az network front-door backend-pool create \ -g $(rg) \ --front-door-name $(fdname) \ -n "InventoryBackendPool" \ --load-balancing "loadbalancing1" \ --probe "probe1" \ --address $(fdinventory) echo "Creating routing rule for inventory service $(fdinventory)" az network front-door routing-rule create \ -g $(rg) \ --front-door-name $(fdname) \ -n "InventoryRoutingRule" \ --frontend-endpoints "DefaultInventoryEndpoint" \ --backend-pool "InventoryBackendPool" ##### # The backend pool for the product service in AKS ##### echo "Creating backend pool for product service $(fdproduct)" az network front-door backend-pool create \ -g $(rg) \ --front-door-name $(fdname) \ -n "ProductBackendPool" \ --load-balancing "loadbalancing1" \ --probe "probe1" \ --address $(fdproduct) echo "Creating routing rule for product service" az network front-door routing-rule create \ -g $(rg) \ --front-door-name $(fdname) \ -n "ProductRoutingRule" \ --frontend-endpoints "DefaultProductEndpoint" \ --backend-pool "ProductBackendPool"
{ "pile_set_name": "Github" }
/* (Copyright) 2018, Winton Wang <[email protected]> ctpwrapper is free software: you can redistribute it and/or modify it under the terms of the GNU LGPLv3 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 ctpwrapper. If not, see <http://www.gnu.org/licenses/>. */ #ifndef CTRADERAPI_H #define CTRADERAPI_H #include "Python.h" #include "pythread.h" #include "ThostFtdcTraderApi.h" static inline int TraderSpi_OnFrontConnected(PyObject *); static inline int TraderSpi_OnFrontDisconnected(PyObject *, int); static inline int TraderSpi_OnHeartBeatWarning(PyObject *, int); static inline int TraderSpi_OnRspAuthenticate(PyObject *, CThostFtdcRspAuthenticateField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspUserLogin(PyObject *, CThostFtdcRspUserLoginField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspUserLogout(PyObject *, CThostFtdcUserLogoutField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspUserPasswordUpdate(PyObject *, CThostFtdcUserPasswordUpdateField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspTradingAccountPasswordUpdate(PyObject *, CThostFtdcTradingAccountPasswordUpdateField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspOrderInsert(PyObject *, CThostFtdcInputOrderField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspParkedOrderInsert(PyObject *, CThostFtdcParkedOrderField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspParkedOrderAction(PyObject *, CThostFtdcParkedOrderActionField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspOrderAction(PyObject *, CThostFtdcInputOrderActionField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQueryMaxOrderVolume(PyObject *, CThostFtdcQueryMaxOrderVolumeField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspSettlementInfoConfirm(PyObject *, CThostFtdcSettlementInfoConfirmField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspRemoveParkedOrder(PyObject *, CThostFtdcRemoveParkedOrderField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspRemoveParkedOrderAction(PyObject *, CThostFtdcRemoveParkedOrderActionField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspExecOrderInsert(PyObject *, CThostFtdcInputExecOrderField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspExecOrderAction(PyObject *, CThostFtdcInputExecOrderActionField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspForQuoteInsert(PyObject *, CThostFtdcInputForQuoteField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQuoteInsert(PyObject *, CThostFtdcInputQuoteField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQuoteAction(PyObject *, CThostFtdcInputQuoteActionField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspCombActionInsert(PyObject *, CThostFtdcInputCombActionField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryOrder(PyObject *, CThostFtdcOrderField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryTrade(PyObject *, CThostFtdcTradeField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryInvestorPosition(PyObject *, CThostFtdcInvestorPositionField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryTradingAccount(PyObject *, CThostFtdcTradingAccountField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryInvestor(PyObject *, CThostFtdcInvestorField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryTradingCode(PyObject *, CThostFtdcTradingCodeField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryInstrumentMarginRate(PyObject *, CThostFtdcInstrumentMarginRateField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryInstrumentCommissionRate(PyObject *, CThostFtdcInstrumentCommissionRateField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryExchange(PyObject *, CThostFtdcExchangeField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryProduct(PyObject *, CThostFtdcProductField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryInstrument(PyObject *, CThostFtdcInstrumentField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryDepthMarketData(PyObject *, CThostFtdcDepthMarketDataField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQrySettlementInfo(PyObject *, CThostFtdcSettlementInfoField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryTransferBank(PyObject *, CThostFtdcTransferBankField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryInvestorPositionDetail(PyObject *, CThostFtdcInvestorPositionDetailField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryNotice(PyObject *, CThostFtdcNoticeField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQrySettlementInfoConfirm(PyObject *, CThostFtdcSettlementInfoConfirmField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryInvestorPositionCombineDetail(PyObject *, CThostFtdcInvestorPositionCombineDetailField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryCFMMCTradingAccountKey(PyObject *, CThostFtdcCFMMCTradingAccountKeyField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryEWarrantOffset(PyObject *, CThostFtdcEWarrantOffsetField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryInvestorProductGroupMargin(PyObject *, CThostFtdcInvestorProductGroupMarginField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryExchangeMarginRate(PyObject *, CThostFtdcExchangeMarginRateField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryExchangeMarginRateAdjust(PyObject *, CThostFtdcExchangeMarginRateAdjustField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryExchangeRate(PyObject *, CThostFtdcExchangeRateField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQrySecAgentACIDMap(PyObject *, CThostFtdcSecAgentACIDMapField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryProductExchRate(PyObject *, CThostFtdcProductExchRateField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryOptionInstrTradeCost(PyObject *, CThostFtdcOptionInstrTradeCostField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryOptionInstrCommRate(PyObject *, CThostFtdcOptionInstrCommRateField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryExecOrder(PyObject *, CThostFtdcExecOrderField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryForQuote(PyObject *, CThostFtdcForQuoteField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryQuote(PyObject *, CThostFtdcQuoteField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryCombInstrumentGuard(PyObject *, CThostFtdcCombInstrumentGuardField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryCombAction(PyObject *, CThostFtdcCombActionField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryTransferSerial(PyObject *, CThostFtdcTransferSerialField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryAccountregister(PyObject *, CThostFtdcAccountregisterField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspError(PyObject *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRtnOrder(PyObject *, CThostFtdcOrderField *); static inline int TraderSpi_OnRtnTrade(PyObject *, CThostFtdcTradeField *); static inline int TraderSpi_OnErrRtnOrderInsert(PyObject *, CThostFtdcInputOrderField *, CThostFtdcRspInfoField *); static inline int TraderSpi_OnErrRtnOrderAction(PyObject *, CThostFtdcOrderActionField *, CThostFtdcRspInfoField *); static inline int TraderSpi_OnRtnInstrumentStatus(PyObject *, CThostFtdcInstrumentStatusField *); static inline int TraderSpi_OnRtnTradingNotice(PyObject *, CThostFtdcTradingNoticeInfoField *); static inline int TraderSpi_OnRtnErrorConditionalOrder(PyObject *, CThostFtdcErrorConditionalOrderField *); static inline int TraderSpi_OnRtnExecOrder(PyObject *, CThostFtdcExecOrderField *); static inline int TraderSpi_OnErrRtnExecOrderInsert(PyObject *, CThostFtdcInputExecOrderField *, CThostFtdcRspInfoField *); static inline int TraderSpi_OnErrRtnExecOrderAction(PyObject *, CThostFtdcExecOrderActionField *, CThostFtdcRspInfoField *); static inline int TraderSpi_OnErrRtnForQuoteInsert(PyObject *, CThostFtdcInputForQuoteField *, CThostFtdcRspInfoField *); static inline int TraderSpi_OnRtnQuote(PyObject *, CThostFtdcQuoteField *); static inline int TraderSpi_OnErrRtnQuoteInsert(PyObject *, CThostFtdcInputQuoteField *, CThostFtdcRspInfoField *); static inline int TraderSpi_OnErrRtnQuoteAction(PyObject *, CThostFtdcQuoteActionField *, CThostFtdcRspInfoField *); static inline int TraderSpi_OnRtnForQuoteRsp(PyObject *, CThostFtdcForQuoteRspField *); static inline int TraderSpi_OnRtnCFMMCTradingAccountToken(PyObject *, CThostFtdcCFMMCTradingAccountTokenField *); static inline int TraderSpi_OnRtnCombAction(PyObject *, CThostFtdcCombActionField *); static inline int TraderSpi_OnErrRtnCombActionInsert(PyObject *, CThostFtdcInputCombActionField *, CThostFtdcRspInfoField *); static inline int TraderSpi_OnRspQryContractBank(PyObject *, CThostFtdcContractBankField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryParkedOrder(PyObject *, CThostFtdcParkedOrderField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryParkedOrderAction(PyObject *, CThostFtdcParkedOrderActionField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryTradingNotice(PyObject *, CThostFtdcTradingNoticeField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryBrokerTradingParams(PyObject *, CThostFtdcBrokerTradingParamsField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryBrokerTradingAlgos(PyObject *, CThostFtdcBrokerTradingAlgosField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQueryCFMMCTradingAccountToken(PyObject *, CThostFtdcQueryCFMMCTradingAccountTokenField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRtnFromBankToFutureByBank(PyObject *, CThostFtdcRspTransferField *); static inline int TraderSpi_OnRtnFromFutureToBankByBank(PyObject *, CThostFtdcRspTransferField *); static inline int TraderSpi_OnRtnRepealFromBankToFutureByBank(PyObject *, CThostFtdcRspRepealField *); static inline int TraderSpi_OnRtnRepealFromFutureToBankByBank(PyObject *, CThostFtdcRspRepealField *); static inline int TraderSpi_OnRtnFromBankToFutureByFuture(PyObject *, CThostFtdcRspTransferField *); static inline int TraderSpi_OnRtnFromFutureToBankByFuture(PyObject *, CThostFtdcRspTransferField *); static inline int TraderSpi_OnRtnRepealFromBankToFutureByFutureManual(PyObject *, CThostFtdcRspRepealField *); static inline int TraderSpi_OnRtnRepealFromFutureToBankByFutureManual(PyObject *, CThostFtdcRspRepealField *); static inline int TraderSpi_OnRtnQueryBankBalanceByFuture(PyObject *, CThostFtdcNotifyQueryAccountField *); static inline int TraderSpi_OnErrRtnBankToFutureByFuture(PyObject *, CThostFtdcReqTransferField *, CThostFtdcRspInfoField *); static inline int TraderSpi_OnErrRtnFutureToBankByFuture(PyObject *, CThostFtdcReqTransferField *, CThostFtdcRspInfoField *); static inline int TraderSpi_OnErrRtnRepealBankToFutureByFutureManual(PyObject *, CThostFtdcReqRepealField *, CThostFtdcRspInfoField *); static inline int TraderSpi_OnErrRtnRepealFutureToBankByFutureManual(PyObject *, CThostFtdcReqRepealField *, CThostFtdcRspInfoField *); static inline int TraderSpi_OnErrRtnQueryBankBalanceByFuture(PyObject *, CThostFtdcReqQueryAccountField *, CThostFtdcRspInfoField *); static inline int TraderSpi_OnRtnRepealFromBankToFutureByFuture(PyObject *, CThostFtdcRspRepealField *); static inline int TraderSpi_OnRtnRepealFromFutureToBankByFuture(PyObject *, CThostFtdcRspRepealField *); static inline int TraderSpi_OnRspFromBankToFutureByFuture(PyObject *, CThostFtdcReqTransferField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspFromFutureToBankByFuture(PyObject *, CThostFtdcReqTransferField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQueryBankAccountMoneyByFuture(PyObject *, CThostFtdcReqQueryAccountField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRtnOpenAccountByBank(PyObject *, CThostFtdcOpenAccountField *); static inline int TraderSpi_OnRtnCancelAccountByBank(PyObject *, CThostFtdcCancelAccountField *); static inline int TraderSpi_OnRtnChangeAccountByBank(PyObject *, CThostFtdcChangeAccountField *); static inline int TraderSpi_OnErrRtnBatchOrderAction(PyObject *, CThostFtdcBatchOrderActionField *, CThostFtdcRspInfoField *); static inline int TraderSpi_OnRtnBulletin(PyObject *, CThostFtdcBulletinField *); static inline int TraderSpi_OnRspQryInstrumentOrderCommRate(PyObject *, CThostFtdcInstrumentOrderCommRateField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryMMOptionInstrCommRate(PyObject *, CThostFtdcMMOptionInstrCommRateField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspBatchOrderAction(PyObject *, CThostFtdcInputBatchOrderActionField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryMMInstrumentCommissionRate(PyObject *, CThostFtdcMMInstrumentCommissionRateField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryProductGroup(PyObject *, CThostFtdcProductGroupField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspOptionSelfCloseInsert(PyObject *, CThostFtdcInputOptionSelfCloseField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspOptionSelfCloseAction(PyObject *, CThostFtdcInputOptionSelfCloseActionField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQrySecAgentTradingAccount(PyObject *, CThostFtdcTradingAccountField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQrySecAgentCheckMode(PyObject *, CThostFtdcSecAgentCheckModeField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryOptionSelfClose(PyObject *, CThostFtdcOptionSelfCloseField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRspQryInvestUnit(PyObject *, CThostFtdcInvestUnitField *, CThostFtdcRspInfoField *, int, bool); static inline int TraderSpi_OnRtnOptionSelfClose(PyObject *, CThostFtdcOptionSelfCloseField *); static inline int TraderSpi_OnErrRtnOptionSelfCloseInsert(PyObject *, CThostFtdcInputOptionSelfCloseField *, CThostFtdcRspInfoField *); static inline int TraderSpi_OnErrRtnOptionSelfCloseAction(PyObject *, CThostFtdcOptionSelfCloseActionField *, CThostFtdcRspInfoField *); static inline int TraderSpi_OnRspQrySecAgentTradeInfo(PyObject *, CThostFtdcSecAgentTradeInfoField *, CThostFtdcRspInfoField *, int, bool); ///查询用户当前支持的认证模式的回复 static inline int TraderSpi_OnRspUserAuthMethod(PyObject *, CThostFtdcRspUserAuthMethodField *, CThostFtdcRspInfoField *, int, bool); ///获取图形验证码请求的回复 static inline int TraderSpi_OnRspGenUserCaptcha(PyObject *, CThostFtdcRspGenUserCaptchaField *, CThostFtdcRspInfoField *, int, bool); ///获取短信验证码请求的回复 static inline int TraderSpi_OnRspGenUserText(PyObject *, CThostFtdcRspGenUserTextField *, CThostFtdcRspInfoField *, int, bool); #define Python_GIL(func) \ do { \ PyGILState_STATE gil_state = PyGILState_Ensure(); \ if ((func) == -1) PyErr_Print(); \ PyGILState_Release(gil_state); \ } while (false) class CTraderSpi : public CThostFtdcTraderSpi { public: CTraderSpi(PyObject *obj) : self(obj) {}; virtual ~CTraderSpi() {}; ///当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。 virtual void OnFrontConnected() { Python_GIL(TraderSpi_OnFrontConnected(self)); }; ///当客户端与交易后台通信连接断开时,该方法被调用。当发生这个情况后,API会自动重新连接,客户端可不做处理。 ///@param nReason 错误原因 /// 0x1001 网络读失败 /// 0x1002 网络写失败 /// 0x2001 接收心跳超时 /// 0x2002 发送心跳失败 /// 0x2003 收到错误报文 virtual void OnFrontDisconnected(int nReason) { Python_GIL(TraderSpi_OnFrontDisconnected(self, nReason)); }; ///心跳超时警告。当长时间未收到报文时,该方法被调用。 ///@param nTimeLapse 距离上次接收报文的时间 virtual void OnHeartBeatWarning(int nTimeLapse) { Python_GIL(TraderSpi_OnHeartBeatWarning(self, nTimeLapse)); }; ///客户端认证响应 virtual void OnRspAuthenticate(CThostFtdcRspAuthenticateField *pRspAuthenticateField, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspAuthenticate(self, pRspAuthenticateField, pRspInfo, nRequestID, bIsLast)); }; ///登录请求响应 virtual void OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspUserLogin(self, pRspUserLogin, pRspInfo, nRequestID, bIsLast)); }; ///登出请求响应 virtual void OnRspUserLogout(CThostFtdcUserLogoutField *pUserLogout, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspUserLogout(self, pUserLogout, pRspInfo, nRequestID, bIsLast)); }; ///用户口令更新请求响应 virtual void OnRspUserPasswordUpdate(CThostFtdcUserPasswordUpdateField *pUserPasswordUpdate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspUserPasswordUpdate(self, pUserPasswordUpdate, pRspInfo, nRequestID, bIsLast)); }; ///资金账户口令更新请求响应 virtual void OnRspTradingAccountPasswordUpdate(CThostFtdcTradingAccountPasswordUpdateField *pTradingAccountPasswordUpdate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspTradingAccountPasswordUpdate(self, pTradingAccountPasswordUpdate, pRspInfo, nRequestID, bIsLast)); }; ///报单录入请求响应 virtual void OnRspOrderInsert(CThostFtdcInputOrderField *pInputOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspOrderInsert(self, pInputOrder, pRspInfo, nRequestID, bIsLast)); }; ///预埋单录入请求响应 virtual void OnRspParkedOrderInsert(CThostFtdcParkedOrderField *pParkedOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspParkedOrderInsert(self, pParkedOrder, pRspInfo, nRequestID, bIsLast)); }; ///预埋撤单录入请求响应 virtual void OnRspParkedOrderAction(CThostFtdcParkedOrderActionField *pParkedOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspParkedOrderAction(self, pParkedOrderAction, pRspInfo, nRequestID, bIsLast)); }; ///报单操作请求响应 virtual void OnRspOrderAction(CThostFtdcInputOrderActionField *pInputOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspOrderAction(self, pInputOrderAction, pRspInfo, nRequestID, bIsLast)); }; ///查询最大报单数量响应 virtual void OnRspQueryMaxOrderVolume(CThostFtdcQueryMaxOrderVolumeField *pQueryMaxOrderVolume, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQueryMaxOrderVolume(self, pQueryMaxOrderVolume, pRspInfo, nRequestID, bIsLast)); }; ///投资者结算结果确认响应 virtual void OnRspSettlementInfoConfirm(CThostFtdcSettlementInfoConfirmField *pSettlementInfoConfirm, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspSettlementInfoConfirm(self, pSettlementInfoConfirm, pRspInfo, nRequestID, bIsLast)); }; ///删除预埋单响应 virtual void OnRspRemoveParkedOrder(CThostFtdcRemoveParkedOrderField *pRemoveParkedOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspRemoveParkedOrder(self, pRemoveParkedOrder, pRspInfo, nRequestID, bIsLast)); }; ///删除预埋撤单响应 virtual void OnRspRemoveParkedOrderAction(CThostFtdcRemoveParkedOrderActionField *pRemoveParkedOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspRemoveParkedOrderAction(self, pRemoveParkedOrderAction, pRspInfo, nRequestID, bIsLast)); }; ///执行宣告录入请求响应 virtual void OnRspExecOrderInsert(CThostFtdcInputExecOrderField *pInputExecOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspExecOrderInsert(self, pInputExecOrder, pRspInfo, nRequestID, bIsLast)); }; ///执行宣告操作请求响应 virtual void OnRspExecOrderAction(CThostFtdcInputExecOrderActionField *pInputExecOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspExecOrderAction(self, pInputExecOrderAction, pRspInfo, nRequestID, bIsLast)); }; ///询价录入请求响应 virtual void OnRspForQuoteInsert(CThostFtdcInputForQuoteField *pInputForQuote, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspForQuoteInsert(self, pInputForQuote, pRspInfo, nRequestID, bIsLast)); }; ///报价录入请求响应 virtual void OnRspQuoteInsert(CThostFtdcInputQuoteField *pInputQuote, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQuoteInsert(self, pInputQuote, pRspInfo, nRequestID, bIsLast)); }; ///报价操作请求响应 virtual void OnRspQuoteAction(CThostFtdcInputQuoteActionField *pInputQuoteAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQuoteAction(self, pInputQuoteAction, pRspInfo, nRequestID, bIsLast)); }; ///批量报单操作请求响应 virtual void OnRspBatchOrderAction(CThostFtdcInputBatchOrderActionField *pInputBatchOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspBatchOrderAction(self, pInputBatchOrderAction, pRspInfo, nRequestID, bIsLast)); }; ///期权自对冲录入请求响应 virtual void OnRspOptionSelfCloseInsert(CThostFtdcInputOptionSelfCloseField *pInputOptionSelfClose, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspOptionSelfCloseInsert(self, pInputOptionSelfClose, pRspInfo, nRequestID, bIsLast)); }; ///期权自对冲操作请求响应 virtual void OnRspOptionSelfCloseAction(CThostFtdcInputOptionSelfCloseActionField *pInputOptionSelfCloseAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspOptionSelfCloseAction(self, pInputOptionSelfCloseAction, pRspInfo, nRequestID, bIsLast)); }; ///申请组合录入请求响应 virtual void OnRspCombActionInsert(CThostFtdcInputCombActionField *pInputCombAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspCombActionInsert(self, pInputCombAction, pRspInfo, nRequestID, bIsLast)); }; ///请求查询报单响应 virtual void OnRspQryOrder(CThostFtdcOrderField *pOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryOrder(self, pOrder, pRspInfo, nRequestID, bIsLast)); }; ///请求查询成交响应 virtual void OnRspQryTrade(CThostFtdcTradeField *pTrade, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryTrade(self, pTrade, pRspInfo, nRequestID, bIsLast)); }; ///请求查询投资者持仓响应 virtual void OnRspQryInvestorPosition(CThostFtdcInvestorPositionField *pInvestorPosition, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryInvestorPosition(self, pInvestorPosition, pRspInfo, nRequestID, bIsLast)); }; ///请求查询资金账户响应 virtual void OnRspQryTradingAccount(CThostFtdcTradingAccountField *pTradingAccount, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryTradingAccount(self, pTradingAccount, pRspInfo, nRequestID, bIsLast)); }; ///请求查询投资者响应 virtual void OnRspQryInvestor(CThostFtdcInvestorField *pInvestor, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryInvestor(self, pInvestor, pRspInfo, nRequestID, bIsLast)); }; ///请求查询交易编码响应 virtual void OnRspQryTradingCode(CThostFtdcTradingCodeField *pTradingCode, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryTradingCode(self, pTradingCode, pRspInfo, nRequestID, bIsLast)); }; ///请求查询合约保证金率响应 virtual void OnRspQryInstrumentMarginRate(CThostFtdcInstrumentMarginRateField *pInstrumentMarginRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryInstrumentMarginRate(self, pInstrumentMarginRate, pRspInfo, nRequestID, bIsLast)); }; ///请求查询合约手续费率响应 virtual void OnRspQryInstrumentCommissionRate(CThostFtdcInstrumentCommissionRateField *pInstrumentCommissionRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryInstrumentCommissionRate(self, pInstrumentCommissionRate, pRspInfo, nRequestID, bIsLast)); }; ///请求查询交易所响应 virtual void OnRspQryExchange(CThostFtdcExchangeField *pExchange, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryExchange(self, pExchange, pRspInfo, nRequestID, bIsLast)); }; ///请求查询产品响应 virtual void OnRspQryProduct(CThostFtdcProductField *pProduct, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryProduct(self, pProduct, pRspInfo, nRequestID, bIsLast)); }; ///请求查询合约响应 virtual void OnRspQryInstrument(CThostFtdcInstrumentField *pInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryInstrument(self, pInstrument, pRspInfo, nRequestID, bIsLast)); }; ///请求查询行情响应 virtual void OnRspQryDepthMarketData(CThostFtdcDepthMarketDataField *pDepthMarketData, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryDepthMarketData(self, pDepthMarketData, pRspInfo, nRequestID, bIsLast)); }; ///请求查询投资者结算结果响应 virtual void OnRspQrySettlementInfo(CThostFtdcSettlementInfoField *pSettlementInfo, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQrySettlementInfo(self, pSettlementInfo, pRspInfo, nRequestID, bIsLast)); }; ///请求查询转帐银行响应 virtual void OnRspQryTransferBank(CThostFtdcTransferBankField *pTransferBank, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryTransferBank(self, pTransferBank, pRspInfo, nRequestID, bIsLast)); }; ///请求查询投资者持仓明细响应 virtual void OnRspQryInvestorPositionDetail(CThostFtdcInvestorPositionDetailField *pInvestorPositionDetail, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryInvestorPositionDetail(self, pInvestorPositionDetail, pRspInfo, nRequestID, bIsLast)); }; ///请求查询客户通知响应 virtual void OnRspQryNotice(CThostFtdcNoticeField *pNotice, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryNotice(self, pNotice, pRspInfo, nRequestID, bIsLast)); }; ///请求查询结算信息确认响应 virtual void OnRspQrySettlementInfoConfirm(CThostFtdcSettlementInfoConfirmField *pSettlementInfoConfirm, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQrySettlementInfoConfirm(self, pSettlementInfoConfirm, pRspInfo, nRequestID, bIsLast)); }; ///请求查询投资者持仓明细响应 virtual void OnRspQryInvestorPositionCombineDetail(CThostFtdcInvestorPositionCombineDetailField *pInvestorPositionCombineDetail, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryInvestorPositionCombineDetail(self, pInvestorPositionCombineDetail, pRspInfo, nRequestID, bIsLast)); }; ///查询保证金监管系统经纪公司资金账户密钥响应 virtual void OnRspQryCFMMCTradingAccountKey(CThostFtdcCFMMCTradingAccountKeyField *pCFMMCTradingAccountKey, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryCFMMCTradingAccountKey(self, pCFMMCTradingAccountKey, pRspInfo, nRequestID, bIsLast)); }; ///请求查询仓单折抵信息响应 virtual void OnRspQryEWarrantOffset(CThostFtdcEWarrantOffsetField *pEWarrantOffset, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryEWarrantOffset(self, pEWarrantOffset, pRspInfo, nRequestID, bIsLast)); }; ///请求查询投资者品种/跨品种保证金响应 virtual void OnRspQryInvestorProductGroupMargin(CThostFtdcInvestorProductGroupMarginField *pInvestorProductGroupMargin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryInvestorProductGroupMargin(self, pInvestorProductGroupMargin, pRspInfo, nRequestID, bIsLast)); }; ///请求查询交易所保证金率响应 virtual void OnRspQryExchangeMarginRate(CThostFtdcExchangeMarginRateField *pExchangeMarginRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryExchangeMarginRate(self, pExchangeMarginRate, pRspInfo, nRequestID, bIsLast)); }; ///请求查询交易所调整保证金率响应 virtual void OnRspQryExchangeMarginRateAdjust(CThostFtdcExchangeMarginRateAdjustField *pExchangeMarginRateAdjust, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryExchangeMarginRateAdjust(self, pExchangeMarginRateAdjust, pRspInfo, nRequestID, bIsLast)); }; ///请求查询汇率响应 virtual void OnRspQryExchangeRate(CThostFtdcExchangeRateField *pExchangeRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryExchangeRate(self, pExchangeRate, pRspInfo, nRequestID, bIsLast)); }; ///请求查询二级代理操作员银期权限响应 virtual void OnRspQrySecAgentACIDMap(CThostFtdcSecAgentACIDMapField *pSecAgentACIDMap, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQrySecAgentACIDMap(self, pSecAgentACIDMap, pRspInfo, nRequestID, bIsLast)); }; ///请求查询产品报价汇率 virtual void OnRspQryProductExchRate(CThostFtdcProductExchRateField *pProductExchRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryProductExchRate(self, pProductExchRate, pRspInfo, nRequestID, bIsLast)); }; ///请求查询产品组 virtual void OnRspQryProductGroup(CThostFtdcProductGroupField *pProductGroup, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryProductGroup(self, pProductGroup, pRspInfo, nRequestID, bIsLast)); }; ///请求查询做市商合约手续费率响应 virtual void OnRspQryMMInstrumentCommissionRate(CThostFtdcMMInstrumentCommissionRateField *pMMInstrumentCommissionRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryMMInstrumentCommissionRate(self, pMMInstrumentCommissionRate, pRspInfo, nRequestID, bIsLast)); }; ///请求查询做市商期权合约手续费响应 virtual void OnRspQryMMOptionInstrCommRate(CThostFtdcMMOptionInstrCommRateField *pMMOptionInstrCommRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryMMOptionInstrCommRate(self, pMMOptionInstrCommRate, pRspInfo, nRequestID, bIsLast)); }; ///请求查询报单手续费响应 virtual void OnRspQryInstrumentOrderCommRate(CThostFtdcInstrumentOrderCommRateField *pInstrumentOrderCommRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryInstrumentOrderCommRate(self, pInstrumentOrderCommRate, pRspInfo, nRequestID, bIsLast)); }; ///请求查询资金账户响应 virtual void OnRspQrySecAgentTradingAccount(CThostFtdcTradingAccountField *pTradingAccount, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQrySecAgentTradingAccount(self, pTradingAccount, pRspInfo, nRequestID, bIsLast)); }; ///请求查询二级代理商资金校验模式响应 virtual void OnRspQrySecAgentCheckMode(CThostFtdcSecAgentCheckModeField *pSecAgentCheckMode, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQrySecAgentCheckMode(self, pSecAgentCheckMode, pRspInfo, nRequestID, bIsLast)); }; ///请求查询期权交易成本响应 virtual void OnRspQryOptionInstrTradeCost(CThostFtdcOptionInstrTradeCostField *pOptionInstrTradeCost, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryOptionInstrTradeCost(self, pOptionInstrTradeCost, pRspInfo, nRequestID, bIsLast)); }; ///请求查询期权合约手续费响应 virtual void OnRspQryOptionInstrCommRate(CThostFtdcOptionInstrCommRateField *pOptionInstrCommRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryOptionInstrCommRate(self, pOptionInstrCommRate, pRspInfo, nRequestID, bIsLast)); }; ///请求查询执行宣告响应 virtual void OnRspQryExecOrder(CThostFtdcExecOrderField *pExecOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryExecOrder(self, pExecOrder, pRspInfo, nRequestID, bIsLast)); }; ///请求查询询价响应 virtual void OnRspQryForQuote(CThostFtdcForQuoteField *pForQuote, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryForQuote(self, pForQuote, pRspInfo, nRequestID, bIsLast)); }; ///请求查询报价响应 virtual void OnRspQryQuote(CThostFtdcQuoteField *pQuote, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryQuote(self, pQuote, pRspInfo, nRequestID, bIsLast)); }; ///请求查询期权自对冲响应 virtual void OnRspQryOptionSelfClose(CThostFtdcOptionSelfCloseField *pOptionSelfClose, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryOptionSelfClose(self, pOptionSelfClose, pRspInfo, nRequestID, bIsLast)); }; ///请求查询投资单元响应 virtual void OnRspQryInvestUnit(CThostFtdcInvestUnitField *pInvestUnit, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryInvestUnit(self, pInvestUnit, pRspInfo, nRequestID, bIsLast)); }; ///请求查询组合合约安全系数响应 virtual void OnRspQryCombInstrumentGuard(CThostFtdcCombInstrumentGuardField *pCombInstrumentGuard, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryCombInstrumentGuard(self, pCombInstrumentGuard, pRspInfo, nRequestID, bIsLast)); }; ///请求查询申请组合响应 virtual void OnRspQryCombAction(CThostFtdcCombActionField *pCombAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryCombAction(self, pCombAction, pRspInfo, nRequestID, bIsLast)); }; ///请求查询转帐流水响应 virtual void OnRspQryTransferSerial(CThostFtdcTransferSerialField *pTransferSerial, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryTransferSerial(self, pTransferSerial, pRspInfo, nRequestID, bIsLast)); }; ///请求查询银期签约关系响应 virtual void OnRspQryAccountregister(CThostFtdcAccountregisterField *pAccountregister, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryAccountregister(self, pAccountregister, pRspInfo, nRequestID, bIsLast)); }; ///错误应答 virtual void OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspError(self, pRspInfo, nRequestID, bIsLast)); }; ///报单通知 virtual void OnRtnOrder(CThostFtdcOrderField *pOrder) { Python_GIL(TraderSpi_OnRtnOrder(self, pOrder)); }; ///成交通知 virtual void OnRtnTrade(CThostFtdcTradeField *pTrade) { Python_GIL(TraderSpi_OnRtnTrade(self, pTrade)); }; ///报单录入错误回报 virtual void OnErrRtnOrderInsert(CThostFtdcInputOrderField *pInputOrder, CThostFtdcRspInfoField *pRspInfo) { Python_GIL(TraderSpi_OnErrRtnOrderInsert(self, pInputOrder, pRspInfo)); }; ///报单操作错误回报 virtual void OnErrRtnOrderAction(CThostFtdcOrderActionField *pOrderAction, CThostFtdcRspInfoField *pRspInfo) { Python_GIL(TraderSpi_OnErrRtnOrderAction(self, pOrderAction, pRspInfo)); }; ///合约交易状态通知 virtual void OnRtnInstrumentStatus(CThostFtdcInstrumentStatusField *pInstrumentStatus) { Python_GIL(TraderSpi_OnRtnInstrumentStatus(self, pInstrumentStatus)); }; ///交易所公告通知 virtual void OnRtnBulletin(CThostFtdcBulletinField *pBulletin) { Python_GIL(TraderSpi_OnRtnBulletin(self, pBulletin)); }; ///交易通知 virtual void OnRtnTradingNotice(CThostFtdcTradingNoticeInfoField *pTradingNoticeInfo) { Python_GIL(TraderSpi_OnRtnTradingNotice(self, pTradingNoticeInfo)); }; ///提示条件单校验错误 virtual void OnRtnErrorConditionalOrder(CThostFtdcErrorConditionalOrderField *pErrorConditionalOrder) { Python_GIL(TraderSpi_OnRtnErrorConditionalOrder(self, pErrorConditionalOrder)); }; ///执行宣告通知 virtual void OnRtnExecOrder(CThostFtdcExecOrderField *pExecOrder) { Python_GIL(TraderSpi_OnRtnExecOrder(self, pExecOrder)); }; ///执行宣告录入错误回报 virtual void OnErrRtnExecOrderInsert(CThostFtdcInputExecOrderField *pInputExecOrder, CThostFtdcRspInfoField *pRspInfo) { Python_GIL(TraderSpi_OnErrRtnExecOrderInsert(self, pInputExecOrder, pRspInfo)); }; ///执行宣告操作错误回报 virtual void OnErrRtnExecOrderAction(CThostFtdcExecOrderActionField *pExecOrderAction, CThostFtdcRspInfoField *pRspInfo) { Python_GIL(TraderSpi_OnErrRtnExecOrderAction(self, pExecOrderAction, pRspInfo)); }; ///询价录入错误回报 virtual void OnErrRtnForQuoteInsert(CThostFtdcInputForQuoteField *pInputForQuote, CThostFtdcRspInfoField *pRspInfo) { Python_GIL(TraderSpi_OnErrRtnForQuoteInsert(self, pInputForQuote, pRspInfo)); }; ///报价通知 virtual void OnRtnQuote(CThostFtdcQuoteField *pQuote) { Python_GIL(TraderSpi_OnRtnQuote(self, pQuote)); }; ///报价录入错误回报 virtual void OnErrRtnQuoteInsert(CThostFtdcInputQuoteField *pInputQuote, CThostFtdcRspInfoField *pRspInfo) { Python_GIL(TraderSpi_OnErrRtnQuoteInsert(self, pInputQuote, pRspInfo)); }; ///报价操作错误回报 virtual void OnErrRtnQuoteAction(CThostFtdcQuoteActionField *pQuoteAction, CThostFtdcRspInfoField *pRspInfo) { Python_GIL(TraderSpi_OnErrRtnQuoteAction(self, pQuoteAction, pRspInfo)); }; ///询价通知 virtual void OnRtnForQuoteRsp(CThostFtdcForQuoteRspField *pForQuoteRsp) { Python_GIL(TraderSpi_OnRtnForQuoteRsp(self, pForQuoteRsp)); }; ///保证金监控中心用户令牌 virtual void OnRtnCFMMCTradingAccountToken(CThostFtdcCFMMCTradingAccountTokenField *pCFMMCTradingAccountToken) { Python_GIL(TraderSpi_OnRtnCFMMCTradingAccountToken(self, pCFMMCTradingAccountToken)); }; ///批量报单操作错误回报 virtual void OnErrRtnBatchOrderAction(CThostFtdcBatchOrderActionField *pBatchOrderAction, CThostFtdcRspInfoField *pRspInfo) { Python_GIL(TraderSpi_OnErrRtnBatchOrderAction(self, pBatchOrderAction, pRspInfo)); }; ///期权自对冲通知 virtual void OnRtnOptionSelfClose(CThostFtdcOptionSelfCloseField *pOptionSelfClose) { Python_GIL(TraderSpi_OnRtnOptionSelfClose(self, pOptionSelfClose)); }; ///期权自对冲录入错误回报 virtual void OnErrRtnOptionSelfCloseInsert(CThostFtdcInputOptionSelfCloseField *pInputOptionSelfClose, CThostFtdcRspInfoField *pRspInfo) { Python_GIL(TraderSpi_OnErrRtnOptionSelfCloseInsert(self, pInputOptionSelfClose, pRspInfo)); }; ///期权自对冲操作错误回报 virtual void OnErrRtnOptionSelfCloseAction(CThostFtdcOptionSelfCloseActionField *pOptionSelfCloseAction, CThostFtdcRspInfoField *pRspInfo) { Python_GIL(TraderSpi_OnErrRtnOptionSelfCloseAction(self, pOptionSelfCloseAction, pRspInfo)); }; ///申请组合通知 virtual void OnRtnCombAction(CThostFtdcCombActionField *pCombAction) { Python_GIL(TraderSpi_OnRtnCombAction(self, pCombAction)); }; ///申请组合录入错误回报 virtual void OnErrRtnCombActionInsert(CThostFtdcInputCombActionField *pInputCombAction, CThostFtdcRspInfoField *pRspInfo) { Python_GIL(TraderSpi_OnErrRtnCombActionInsert(self, pInputCombAction, pRspInfo)); }; ///请求查询签约银行响应 virtual void OnRspQryContractBank(CThostFtdcContractBankField *pContractBank, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryContractBank(self, pContractBank, pRspInfo, nRequestID, bIsLast)); }; ///请求查询预埋单响应 virtual void OnRspQryParkedOrder(CThostFtdcParkedOrderField *pParkedOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryParkedOrder(self, pParkedOrder, pRspInfo, nRequestID, bIsLast)); }; ///请求查询预埋撤单响应 virtual void OnRspQryParkedOrderAction(CThostFtdcParkedOrderActionField *pParkedOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryParkedOrderAction(self, pParkedOrderAction, pRspInfo, nRequestID, bIsLast)); }; ///请求查询交易通知响应 virtual void OnRspQryTradingNotice(CThostFtdcTradingNoticeField *pTradingNotice, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryTradingNotice(self, pTradingNotice, pRspInfo, nRequestID, bIsLast)); }; ///请求查询经纪公司交易参数响应 virtual void OnRspQryBrokerTradingParams(CThostFtdcBrokerTradingParamsField *pBrokerTradingParams, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryBrokerTradingParams(self, pBrokerTradingParams, pRspInfo, nRequestID, bIsLast)); }; ///请求查询经纪公司交易算法响应 virtual void OnRspQryBrokerTradingAlgos(CThostFtdcBrokerTradingAlgosField *pBrokerTradingAlgos, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQryBrokerTradingAlgos(self, pBrokerTradingAlgos, pRspInfo, nRequestID, bIsLast)); }; ///请求查询监控中心用户令牌 virtual void OnRspQueryCFMMCTradingAccountToken(CThostFtdcQueryCFMMCTradingAccountTokenField *pQueryCFMMCTradingAccountToken, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQueryCFMMCTradingAccountToken(self, pQueryCFMMCTradingAccountToken, pRspInfo, nRequestID, bIsLast)); }; ///银行发起银行资金转期货通知 virtual void OnRtnFromBankToFutureByBank(CThostFtdcRspTransferField *pRspTransfer) { Python_GIL(TraderSpi_OnRtnFromBankToFutureByBank(self, pRspTransfer)); }; ///银行发起期货资金转银行通知 virtual void OnRtnFromFutureToBankByBank(CThostFtdcRspTransferField *pRspTransfer) { Python_GIL(TraderSpi_OnRtnFromFutureToBankByBank(self, pRspTransfer)); }; ///银行发起冲正银行转期货通知 virtual void OnRtnRepealFromBankToFutureByBank(CThostFtdcRspRepealField *pRspRepeal) { Python_GIL(TraderSpi_OnRtnRepealFromBankToFutureByBank(self, pRspRepeal)); }; ///银行发起冲正期货转银行通知 virtual void OnRtnRepealFromFutureToBankByBank(CThostFtdcRspRepealField *pRspRepeal) { Python_GIL(TraderSpi_OnRtnRepealFromFutureToBankByBank(self, pRspRepeal)); }; ///期货发起银行资金转期货通知 virtual void OnRtnFromBankToFutureByFuture(CThostFtdcRspTransferField *pRspTransfer) { Python_GIL(TraderSpi_OnRtnFromBankToFutureByFuture(self, pRspTransfer)); }; ///期货发起期货资金转银行通知 virtual void OnRtnFromFutureToBankByFuture(CThostFtdcRspTransferField *pRspTransfer) { Python_GIL(TraderSpi_OnRtnFromFutureToBankByFuture(self, pRspTransfer)); }; ///系统运行时期货端手工发起冲正银行转期货请求,银行处理完毕后报盘发回的通知 virtual void OnRtnRepealFromBankToFutureByFutureManual(CThostFtdcRspRepealField *pRspRepeal) { Python_GIL(TraderSpi_OnRtnRepealFromBankToFutureByFutureManual(self, pRspRepeal)); }; ///系统运行时期货端手工发起冲正期货转银行请求,银行处理完毕后报盘发回的通知 virtual void OnRtnRepealFromFutureToBankByFutureManual(CThostFtdcRspRepealField *pRspRepeal) { Python_GIL(TraderSpi_OnRtnRepealFromFutureToBankByFutureManual(self, pRspRepeal)); }; ///期货发起查询银行余额通知 virtual void OnRtnQueryBankBalanceByFuture(CThostFtdcNotifyQueryAccountField *pNotifyQueryAccount) { Python_GIL(TraderSpi_OnRtnQueryBankBalanceByFuture(self, pNotifyQueryAccount)); }; ///期货发起银行资金转期货错误回报 virtual void OnErrRtnBankToFutureByFuture(CThostFtdcReqTransferField *pReqTransfer, CThostFtdcRspInfoField *pRspInfo) { Python_GIL(TraderSpi_OnErrRtnBankToFutureByFuture(self, pReqTransfer, pRspInfo)); }; ///期货发起期货资金转银行错误回报 virtual void OnErrRtnFutureToBankByFuture(CThostFtdcReqTransferField *pReqTransfer, CThostFtdcRspInfoField *pRspInfo) { Python_GIL(TraderSpi_OnErrRtnFutureToBankByFuture(self, pReqTransfer, pRspInfo)); }; ///系统运行时期货端手工发起冲正银行转期货错误回报 virtual void OnErrRtnRepealBankToFutureByFutureManual(CThostFtdcReqRepealField *pReqRepeal, CThostFtdcRspInfoField *pRspInfo) { Python_GIL(TraderSpi_OnErrRtnRepealBankToFutureByFutureManual(self, pReqRepeal, pRspInfo)); }; ///系统运行时期货端手工发起冲正期货转银行错误回报 virtual void OnErrRtnRepealFutureToBankByFutureManual(CThostFtdcReqRepealField *pReqRepeal, CThostFtdcRspInfoField *pRspInfo) { Python_GIL(TraderSpi_OnErrRtnRepealFutureToBankByFutureManual(self, pReqRepeal, pRspInfo)); }; ///期货发起查询银行余额错误回报 virtual void OnErrRtnQueryBankBalanceByFuture(CThostFtdcReqQueryAccountField *pReqQueryAccount, CThostFtdcRspInfoField *pRspInfo) { Python_GIL(TraderSpi_OnErrRtnQueryBankBalanceByFuture(self, pReqQueryAccount, pRspInfo)); }; ///期货发起冲正银行转期货请求,银行处理完毕后报盘发回的通知 virtual void OnRtnRepealFromBankToFutureByFuture(CThostFtdcRspRepealField *pRspRepeal) { Python_GIL(TraderSpi_OnRtnRepealFromBankToFutureByFuture(self, pRspRepeal)); }; ///期货发起冲正期货转银行请求,银行处理完毕后报盘发回的通知 virtual void OnRtnRepealFromFutureToBankByFuture(CThostFtdcRspRepealField *pRspRepeal) { Python_GIL(TraderSpi_OnRtnRepealFromFutureToBankByFuture(self, pRspRepeal)); }; ///期货发起银行资金转期货应答 virtual void OnRspFromBankToFutureByFuture(CThostFtdcReqTransferField *pReqTransfer, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspFromBankToFutureByFuture(self, pReqTransfer, pRspInfo, nRequestID, bIsLast)); }; ///期货发起期货资金转银行应答 virtual void OnRspFromFutureToBankByFuture(CThostFtdcReqTransferField *pReqTransfer, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspFromFutureToBankByFuture(self, pReqTransfer, pRspInfo, nRequestID, bIsLast)); }; ///期货发起查询银行余额应答 virtual void OnRspQueryBankAccountMoneyByFuture(CThostFtdcReqQueryAccountField *pReqQueryAccount, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQueryBankAccountMoneyByFuture(self, pReqQueryAccount, pRspInfo, nRequestID, bIsLast)); }; ///银行发起银期开户通知 virtual void OnRtnOpenAccountByBank(CThostFtdcOpenAccountField *pOpenAccount) { Python_GIL(TraderSpi_OnRtnOpenAccountByBank(self, pOpenAccount)); }; ///银行发起银期销户通知 virtual void OnRtnCancelAccountByBank(CThostFtdcCancelAccountField *pCancelAccount) { Python_GIL(TraderSpi_OnRtnCancelAccountByBank(self, pCancelAccount)); }; ///银行发起变更银行账号通知 virtual void OnRtnChangeAccountByBank(CThostFtdcChangeAccountField *pChangeAccount) { Python_GIL(TraderSpi_OnRtnChangeAccountByBank(self, pChangeAccount)); }; ///请求查询二级代理商信息响应 virtual void OnRspQrySecAgentTradeInfo(CThostFtdcSecAgentTradeInfoField *pSecAgentTradeInfo, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspQrySecAgentTradeInfo(self, pSecAgentTradeInfo, pRspInfo, nRequestID, bIsLast)); }; ///查询用户当前支持的认证模式的回复 virtual void OnRspUserAuthMethod(CThostFtdcRspUserAuthMethodField *pRspUserAuthMethod, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspUserAuthMethod(self, pRspUserAuthMethod, pRspInfo, nRequestID, bIsLast)); }; ///获取图形验证码请求的回复 virtual void OnRspGenUserCaptcha(CThostFtdcRspGenUserCaptchaField *pRspGenUserCaptcha, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspGenUserCaptcha(self, pRspGenUserCaptcha, pRspInfo, nRequestID, bIsLast)); }; ///获取短信验证码请求的回复 virtual void OnRspGenUserText(CThostFtdcRspGenUserTextField *pRspGenUserText, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { Python_GIL(TraderSpi_OnRspGenUserText(self, pRspGenUserText, pRspInfo, nRequestID, bIsLast)); }; private: PyObject *self; }; #endif /* CTRADERAPI_H */
{ "pile_set_name": "Github" }
%verify "executed" /* * Long integer shift, 2addr version. vA is 64-bit value/result, vB is * 32-bit shift distance. */ /* ushr-long/2addr vA, vB */ mov r3, rINST, lsr #12 @ r3<- B ubfx r9, rINST, #8, #4 @ r9<- A GET_VREG(r2, r3) @ r2<- vB add r9, rFP, r9, lsl #2 @ r9<- &fp[A] and r2, r2, #63 @ r2<- r2 & 0x3f ldmia r9, {r0-r1} @ r0/r1<- vAA/vAA+1 mov r0, r0, lsr r2 @ r0<- r2 >> r2 rsb r3, r2, #32 @ r3<- 32 - r2 orr r0, r0, r1, asl r3 @ r0<- r0 | (r1 << (32-r2)) subs ip, r2, #32 @ ip<- r2 - 32 FETCH_ADVANCE_INST(1) @ advance rPC, load rINST movpl r0, r1, lsr ip @ if r2 >= 32, r0<-r1 >>> (r2-32) mov r1, r1, lsr r2 @ r1<- r1 >>> r2 b .L${opcode}_finish %break .L${opcode}_finish: GET_INST_OPCODE(ip) @ extract opcode from rINST stmia r9, {r0-r1} @ vAA/vAA+1<- r0/r1 GOTO_OPCODE(ip) @ jump to next instruction
{ "pile_set_name": "Github" }
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Copyright (c) 2006 Dan Marsden 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) ==============================================================================*/ #if !defined (BOOST_FUSION_PAIR_TIE_20060812_2058) #define BOOST_FUSION_PAIR_TIE_20060812_2058 #include <boost/fusion/support/config.hpp> #include <boost/type_traits/is_const.hpp> #include <boost/utility/enable_if.hpp> namespace boost { namespace fusion { template<typename Key, typename T> struct pair; namespace result_of { template<typename Key, typename T> struct pair_tie { typedef fusion::pair<Key, T&> type; }; } template<typename Key, typename T> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED typename disable_if<is_const<T>, typename result_of::pair_tie<Key, T>::type>::type pair_tie(T& t) { return typename result_of::pair_tie<Key, T>::type(t); } template<typename Key, typename T> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED typename result_of::pair_tie<Key, T const>::type pair_tie(T const& t) { return typename result_of::pair_tie<Key, T const>::type(t); } }} #endif
{ "pile_set_name": "Github" }
// Copyright 2017 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Flags: --allow-natives-syntax function foo(o) { return o[0]; }; %PrepareFunctionForOptimization(foo); assertEquals(undefined, foo({})); Array.prototype[0] = 0; assertEquals(undefined, foo({})); %OptimizeFunctionOnNextCall(foo); assertEquals(undefined, foo({}));
{ "pile_set_name": "Github" }
{ "jest": { "rootDir": "./", "transform": { "^.+\\.(ts|js)$": "<rootDir>/TypescriptPreprocessor.js" }, "testRegex": "/__tests__/.*\\.(ts|tsx|js)$", "testEnvironment": "node", "moduleFileExtensions": [ "ts", "tsx", "js" ] }, "dependencies": { "typescript": "^1.8.10" } }
{ "pile_set_name": "Github" }
" Vim syntax file " Language: ldap.conf(5) configuration file. " Previous Maintainer: Nikolai Weibull <[email protected]> " Latest Revision: 2006-12-11 if exists("b:current_syntax") finish endif let s:cpo_save = &cpo set cpo&vim syn keyword ldapconfTodo contained TODO FIXME XXX NOTE syn region ldapconfComment display oneline start='^\s*#' end='$' \ contains=ldapconfTodo, \ @Spell syn match ldapconfBegin display '^' \ nextgroup=ldapconfOption, \ ldapconfDeprOption, \ ldapconfComment syn case ignore syn keyword ldapconfOption contained URI \ nextgroup=ldapconfURI \ skipwhite syn keyword ldapconfOption contained \ BASE \ BINDDN \ nextgroup=ldapconfDNAttrType \ skipwhite syn keyword ldapconfDeprOption contained \ HOST \ nextgroup=ldapconfHost \ skipwhite syn keyword ldapconfDeprOption contained \ PORT \ nextgroup=ldapconfPort \ skipwhite syn keyword ldapconfOption contained \ REFERRALS \ nextgroup=ldapconfBoolean \ skipwhite syn keyword ldapconfOption contained \ SIZELIMIT \ TIMELIMIT \ nextgroup=ldapconfInteger \ skipwhite syn keyword ldapconfOption contained \ DEREF \ nextgroup=ldapconfDerefWhen \ skipwhite syn keyword ldapconfOption contained \ SASL_MECH \ nextgroup=ldapconfSASLMechanism \ skipwhite syn keyword ldapconfOption contained \ SASL_REALM \ nextgroup=ldapconfSASLRealm \ skipwhite syn keyword ldapconfOption contained \ SASL_AUTHCID \ SASL_AUTHZID \ nextgroup=ldapconfSASLAuthID \ skipwhite syn keyword ldapconfOption contained \ SASL_SECPROPS \ nextgroup=ldapconfSASLSecProps \ skipwhite syn keyword ldapconfOption contained \ TLS_CACERT \ TLS_CERT \ TLS_KEY \ TLS_RANDFILE \ nextgroup=ldapconfFilename \ skipwhite syn keyword ldapconfOption contained \ TLS_CACERTDIR \ nextgroup=ldapconfPath \ skipwhite syn keyword ldapconfOption contained \ TLS_CIPHER_SUITE \ nextgroup=@ldapconfTLSCipher \ skipwhite syn keyword ldapconfOption contained \ TLS_REQCERT \ nextgroup=ldapconfTLSCertCheck \ skipwhite syn keyword ldapconfOption contained \ TLS_CRLCHECK \ nextgroup=ldapconfTLSCRLCheck \ skipwhite syn case match syn match ldapconfURI contained display \ 'ldaps\=://[^[:space:]:]\+\%(:\d\+\)\=' \ nextgroup=ldapconfURI \ skipwhite " LDAP Distinguished Names are defined in Section 3 of RFC 2253: " http://www.ietf.org/rfc/rfc2253.txt. syn match ldapconfDNAttrType contained display \ '\a[a-zA-Z0-9-]\+\|\d\+\%(\.\d\+\)*' \ nextgroup=ldapconfDNAttrTypeEq syn match ldapconfDNAttrTypeEq contained display \ '=' \ nextgroup=ldapconfDNAttrValue syn match ldapconfDNAttrValue contained display \ '\%([^,=+<>#;\\"]\|\\\%([,=+<>#;\\"]\|\x\x\)\)*\|#\%(\x\x\)\+\|"\%([^\\"]\|\\\%([,=+<>#;\\"]\|\x\x\)\)*"' \ nextgroup=ldapconfDNSeparator syn match ldapconfDNSeparator contained display \ '[+,]' \ nextgroup=ldapconfDNAttrType syn match ldapconfHost contained display \ '[^[:space:]:]\+\%(:\d\+\)\=' \ nextgroup=ldapconfHost \ skipwhite syn match ldapconfPort contained display \ '\d\+' syn keyword ldapconfBoolean contained \ on \ true \ yes \ off \ false \ no syn match ldapconfInteger contained display \ '\d\+' syn keyword ldapconfDerefWhen contained \ never \ searching \ finding \ always " Taken from http://www.iana.org/assignments/sasl-mechanisms. syn keyword ldapconfSASLMechanism contained \ KERBEROS_V4 \ GSSAPI \ SKEY \ EXTERNAL \ ANONYMOUS \ OTP \ PLAIN \ SECURID \ NTLM \ NMAS_LOGIN \ NMAS_AUTHEN \ KERBEROS_V5 syn match ldapconfSASLMechanism contained display \ 'CRAM-MD5\|GSS-SPNEGO\|DIGEST-MD5\|9798-[UM]-\%(RSA-SHA1-ENC\|\%(EC\)\=DSA-SHA1\)\|NMAS-SAMBA-AUTH' " TODO: I have been unable to find a definition for a SASL realm, " authentication identity, and proxy authorization identity. syn match ldapconfSASLRealm contained display \ '\S\+' syn match ldapconfSASLAuthID contained display \ '\S\+' syn keyword ldapconfSASLSecProps contained \ none \ noplain \ noactive \ nodict \ noanonymous \ forwardsec \ passcred \ nextgroup=ldapconfSASLSecPSep syn keyword ldapconfSASLSecProps contained \ minssf \ maxssf \ maxbufsize \ nextgroup=ldapconfSASLSecPEq syn match ldapconfSASLSecPEq contained display \ '=' \ nextgroup=ldapconfSASLSecFactor syn match ldapconfSASLSecFactor contained display \ '\d\+' \ nextgroup=ldapconfSASLSecPSep syn match ldapconfSASLSecPSep contained display \ ',' \ nextgroup=ldapconfSASLSecProps syn match ldapconfFilename contained display \ '.\+' syn match ldapconfPath contained display \ '.\+' " Defined in openssl-ciphers(1). " TODO: Should we include the stuff under CIPHER SUITE NAMES? syn cluster ldapconfTLSCipher contains=ldapconfTLSCipherOp, \ ldapconfTLSCipherName, \ ldapconfTLSCipherSort syn match ldapconfTLSCipherOp contained display \ '[+!-]' \ nextgroup=ldapconfTLSCipherName syn keyword ldapconfTLSCipherName contained \ DEFAULT \ COMPLEMENTOFDEFAULT \ ALL \ COMPLEMENTOFALL \ HIGH \ MEDIUM \ LOW \ EXP \ EXPORT \ EXPORT40 \ EXPORT56 \ eNULL \ NULL \ aNULL \ kRSA \ RSA \ kEDH \ kDHr \ kDHd \ aRSA \ aDSS \ DSS \ aDH \ kFZA \ aFZA \ eFZA \ FZA \ TLSv1 \ SSLv3 \ SSLv2 \ DH \ ADH \ AES \ 3DES \ DES \ RC4 \ RC2 \ IDEA \ MD5 \ SHA1 \ SHA \ Camellia \ nextgroup=ldapconfTLSCipherSep syn match ldapconfTLSCipherSort contained display \ '@STRENGTH' \ nextgroup=ldapconfTLSCipherSep syn match ldapconfTLSCipherSep contained display \ '[:, ]' \ nextgroup=@ldapconfTLSCipher syn keyword ldapconfTLSCertCheck contained \ never \ allow \ try \ demand \ hard syn keyword ldapconfTLSCRLCheck contained \ none \ peer \ all hi def link ldapconfTodo Todo hi def link ldapconfComment Comment hi def link ldapconfOption Keyword hi def link ldapconfDeprOption Error hi def link ldapconfString String hi def link ldapconfURI ldapconfString hi def link ldapconfDNAttrType Identifier hi def link ldapconfOperator Operator hi def link ldapconfEq ldapconfOperator hi def link ldapconfDNAttrTypeEq ldapconfEq hi def link ldapconfValue ldapconfString hi def link ldapconfDNAttrValue ldapconfValue hi def link ldapconfSeparator ldapconfOperator hi def link ldapconfDNSeparator ldapconfSeparator hi def link ldapconfHost ldapconfURI hi def link ldapconfNumber Number hi def link ldapconfPort ldapconfNumber hi def link ldapconfBoolean Boolean hi def link ldapconfInteger ldapconfNumber hi def link ldapconfType Type hi def link ldapconfDerefWhen ldapconfType hi def link ldapconfDefine Define hi def link ldapconfSASLMechanism ldapconfDefine hi def link ldapconfSASLRealm ldapconfURI hi def link ldapconfSASLAuthID ldapconfValue hi def link ldapconfSASLSecProps ldapconfType hi def link ldapconfSASLSecPEq ldapconfEq hi def link ldapconfSASLSecFactor ldapconfNumber hi def link ldapconfSASLSecPSep ldapconfSeparator hi def link ldapconfFilename ldapconfString hi def link ldapconfPath ldapconfFilename hi def link ldapconfTLSCipherOp ldapconfOperator hi def link ldapconfTLSCipherName ldapconfDefine hi def link ldapconfSpecial Special hi def link ldapconfTLSCipherSort ldapconfSpecial hi def link ldapconfTLSCipherSep ldapconfSeparator hi def link ldapconfTLSCertCheck ldapconfType hi def link ldapconfTLSCRLCheck ldapconfType let b:current_syntax = "ldapconf" let &cpo = s:cpo_save unlet s:cpo_save
{ "pile_set_name": "Github" }
import { Key, Path, pathToRegexp } from './path-to-regex'; import { MatchOptions, MatchResults } from '../global/interfaces'; import { valueEqual } from './location-utils'; interface CompileOptions { end: boolean; strict: boolean; } let cacheCount = 0; const patternCache: {[key: string]: any } = {}; const cacheLimit = 10000; // Memoized function for creating the path match regex const compilePath = (pattern: Path, options: CompileOptions): { re: RegExp, keys: Key[]} => { const cacheKey = `${options.end}${options.strict}`; const cache = patternCache[cacheKey] || (patternCache[cacheKey] = {}); const cachePattern = JSON.stringify(pattern); if (cache[cachePattern]) { return cache[cachePattern]; } const keys: Key[] = []; const re = pathToRegexp(pattern, keys, options); const compiledPattern = { re, keys }; if (cacheCount < cacheLimit) { cache[cachePattern] = compiledPattern; cacheCount += 1; } return compiledPattern; } /** * Public API for matching a URL pathname to a path pattern. */ export const matchPath = (pathname: string, options: MatchOptions = {}): null | MatchResults => { if (typeof options === 'string') { options = { path: options }; } const { path = '/', exact = false, strict = false } = options; const { re, keys } = compilePath(path, { end: exact, strict }); const match = re.exec(pathname); if (!match) { return null; } const [ url, ...values ] = match; const isExact = pathname === url; if (exact && !isExact) { return null; } return <MatchResults>{ path, // the path pattern used to match url: path === '/' && url === '' ? '/' : url, // the matched portion of the URL isExact, // whether or not we matched exactly params: keys.reduce((memo, key: Key, index) => { memo[key.name] = values[index]; return memo; }, {} as {[key: string]: string}) }; } export const matchesAreEqual = (a: MatchResults | null, b: MatchResults | null) => { if (a == null && b == null) { return true; } if (b == null) { return false; } return a && b && a.path === b.path && a.url === b.url && valueEqual(a.params, b.params); }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2008-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cometd.server; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.cometd.server.http.JSONPTransport; import org.cometd.server.http.JSONTransport; import org.junit.Test; public class BayeuxServerCreationTest { @Test public void testCreationWithoutOptions() throws Exception { BayeuxServerImpl bayeuxServer = new BayeuxServerImpl(); bayeuxServer.start(); Set<String> knownTransports = bayeuxServer.getKnownTransportNames(); assertEquals(2, knownTransports.size()); assertTrue(knownTransports.contains(JSONTransport.NAME)); assertTrue(knownTransports.contains(JSONPTransport.NAME)); assertEquals(knownTransports, new HashSet<>(bayeuxServer.getAllowedTransports())); } @Test public void testCreationWithOptions() throws Exception { BayeuxServerImpl bayeuxServer = new BayeuxServerImpl(); Map<String, String> options = new HashMap<>(); String timeoutKey = "timeout"; String timeoutValue = "10007"; options.put(timeoutKey, timeoutValue); String longPollingTimeoutKey = "long-polling.timeout"; String longPollingTimeoutValue = "11047"; options.put(longPollingTimeoutKey, longPollingTimeoutValue); String websocketTimeoutKey = "ws.timeout"; String websocketTimeoutValue = "12041"; options.put(websocketTimeoutKey, websocketTimeoutValue); String jsonTimeoutKey = "long-polling.json.timeout"; String jsonTimeoutValue = "13003"; options.put(jsonTimeoutKey, jsonTimeoutValue); String jsonpTimeoutKey = "long-polling.jsonp.timeout"; String jsonpTimeoutValue = "14009"; options.put(jsonpTimeoutKey, jsonpTimeoutValue); for (Map.Entry<String, String> entry : options.entrySet()) { bayeuxServer.setOption(entry.getKey(), entry.getValue()); } bayeuxServer.start(); assertEquals(timeoutValue, bayeuxServer.getOption(timeoutKey)); assertEquals(jsonTimeoutValue, bayeuxServer.getTransport(JSONTransport.NAME).getOption(timeoutKey)); assertEquals(jsonpTimeoutValue, bayeuxServer.getTransport(JSONPTransport.NAME).getOption(timeoutKey)); } @Test public void testCreationWithTransports() throws Exception { BayeuxServerImpl bayeuxServer = new BayeuxServerImpl(); JSONTransport jsonTransport = new JSONTransport(bayeuxServer); long timeout = 13003L; jsonTransport.setTimeout(timeout); bayeuxServer.setTransports(jsonTransport); bayeuxServer.setAllowedTransports(JSONTransport.NAME); bayeuxServer.start(); assertEquals(1, bayeuxServer.getAllowedTransports().size()); assertEquals(1, bayeuxServer.getKnownTransportNames().size()); assertEquals(JSONTransport.NAME, bayeuxServer.getAllowedTransports().get(0)); assertEquals(JSONTransport.NAME, bayeuxServer.getKnownTransportNames().iterator().next()); assertEquals(timeout, bayeuxServer.getTransport(JSONTransport.NAME).getTimeout()); } }
{ "pile_set_name": "Github" }
--[[ Unit Test for EmbedNet model Copyright 2016 Xiang Zhang --]] local Model = require('model') local sys = require('sys') -- A Logic Named Joe local joe = {} function joe.main() if joe.init then print('Initializing testing environment') joe:init() end for name, func in pairs(joe) do if type(name) == 'string' and type(func) == 'function' and name:match('[%g]+Test') then print('\nExecuting '..name) func(joe) end end end function joe:init() local config = dofile('config.lua') config.model.embedding = config.variation['large'].embedding config.model.temporal = config.variation['large'].temporal local model = Model(config.model) print('Embedding model:') print(model.embedding) print('Temporal model:') print(model.temporal) self.config = config self.model = model end function joe:modelTest() local model = self.model local params, grads = model:getParameters() grads:zero() print('Number of elements in parameters and gradients: '.. params:nElement()..', '..grads:nElement()) print('Creating input') local input = torch.rand(2, 512):mul(65537):ceil() print(input:size()) print('Forward propagating') sys.tic() local output = model:forward(input) sys.toc(true) print(output:size()) print('Creating output gradients') local grad_output = torch.rand(output:size()) print(grad_output:size()) print('Backward propagating') sys.tic() local grad_input = model:backward(input, grad_output) sys.toc(true) print(grad_input:size()) end function joe:modeTest() local model = self.model print('Setting model to train') model:setModeTrain() for i, m in ipairs(model.temporal.modules) do if torch.type(m) == 'nn.Dropout' then print(i, torch.type(m), m.train) end end print('Setting model to test') model:setModeTest() for i, m in ipairs(model.temporal.modules) do if torch.type(m) == 'nn.Dropout' then print(i, torch.type(m), m.train) end end print('Setting model to train') model:setModeTrain() for i, m in ipairs(model.temporal.modules) do if torch.type(m) == 'nn.Dropout' then print(i, torch.type(m), m.train) end end print('Setting model to test') model:setModeTest() for i, m in ipairs(model.temporal.modules) do if torch.type(m) == 'nn.Dropout' then print(i, torch.type(m), m.train) end end end function joe:saveTest() local model = self.model print('Saving to /tmp/model.t7b') model:save('/tmp/model.t7b') print('Loading from /tmp/model.t7b') local config = self.config config.model.file = '/tmp/model.t7b' local loaded = Model(config.model) print('Embedding model') print(loaded.embedding) print('Temporal model') print(loaded.temporal) config.model.file = nil end joe.main() return joe
{ "pile_set_name": "Github" }
'use strict'; var net = require('net'); var tls = require('tls'); var http = require('http'); var https = require('https'); var events = require('events'); var assert = require('assert'); var util = require('util'); exports.httpOverHttp = httpOverHttp; exports.httpsOverHttp = httpsOverHttp; exports.httpOverHttps = httpOverHttps; exports.httpsOverHttps = httpsOverHttps; function httpOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; return agent; } function httpsOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; agent.createSocket = createSecureSocket; return agent; } function httpOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; return agent; } function httpsOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; agent.createSocket = createSecureSocket; return agent; } function TunnelingAgent(options) { var self = this; self.options = options || {}; self.proxyOptions = self.options.proxy || {}; self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; self.requests = []; self.sockets = []; self.on('free', function onFree(socket, host, port) { for (var i = 0, len = self.requests.length; i < len; ++i) { var pending = self.requests[i]; if (pending.host === host && pending.port === port) { // Detect the request to connect same origin server, // reuse the connection. self.requests.splice(i, 1); pending.request.onSocket(socket); return; } } socket.destroy(); self.removeSocket(socket); }); } util.inherits(TunnelingAgent, events.EventEmitter); TunnelingAgent.prototype.addRequest = function addRequest(req, host, port) { var self = this; if (self.sockets.length >= this.maxSockets) { // We are over limit so we'll add it to the queue. self.requests.push({host: host, port: port, request: req}); return; } // If we are under maxSockets create a new one. self.createSocket({host: host, port: port, request: req}, function(socket) { socket.on('free', onFree); socket.on('close', onCloseOrRemove); socket.on('agentRemove', onCloseOrRemove); req.onSocket(socket); function onFree() { self.emit('free', socket, host, port); } function onCloseOrRemove(err) { self.removeSocket(); socket.removeListener('free', onFree); socket.removeListener('close', onCloseOrRemove); socket.removeListener('agentRemove', onCloseOrRemove); } }); }; TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { var self = this; var placeholder = {}; self.sockets.push(placeholder); var connectOptions = mergeOptions({}, self.proxyOptions, { method: 'CONNECT', path: options.host + ':' + options.port, agent: false }); if (connectOptions.proxyAuth) { connectOptions.headers = connectOptions.headers || {}; connectOptions.headers['Proxy-Authorization'] = 'Basic ' + new Buffer(connectOptions.proxyAuth).toString('base64'); } debug('making CONNECT request'); var connectReq = self.request(connectOptions); connectReq.useChunkedEncodingByDefault = false; // for v0.6 connectReq.once('response', onResponse); // for v0.6 connectReq.once('upgrade', onUpgrade); // for v0.6 connectReq.once('connect', onConnect); // for v0.7 or later connectReq.once('error', onError); connectReq.end(); function onResponse(res) { // Very hacky. This is necessary to avoid http-parser leaks. res.upgrade = true; } function onUpgrade(res, socket, head) { // Hacky. process.nextTick(function() { onConnect(res, socket, head); }); } function onConnect(res, socket, head) { connectReq.removeAllListeners(); socket.removeAllListeners(); if (res.statusCode === 200) { assert.equal(head.length, 0); debug('tunneling connection has established'); self.sockets[self.sockets.indexOf(placeholder)] = socket; cb(socket); } else { debug('tunneling socket could not be established, statusCode=%d', res.statusCode); var error = new Error('tunneling socket could not be established, ' + 'sutatusCode=' + res.statusCode); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); } } function onError(cause) { connectReq.removeAllListeners(); debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack); var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); } }; TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { var pos = this.sockets.indexOf(socket) if (pos === -1) { return; } this.sockets.splice(pos, 1); var pending = this.requests.shift(); if (pending) { // If we have pending requests and a socket gets closed a new one // needs to be created to take over in the pool for the one that closed. this.createSocket(pending, function(socket) { pending.request.onSocket(socket); }); } }; function createSecureSocket(options, cb) { var self = this; TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { // 0 is dummy port for v0.6 var secureSocket = tls.connect(0, mergeOptions({}, self.options, { socket: socket })); cb(secureSocket); }); } function mergeOptions(target) { for (var i = 1, len = arguments.length; i < len; ++i) { var overrides = arguments[i]; if (typeof overrides === 'object') { var keys = Object.keys(overrides); for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { var k = keys[j]; if (overrides[k] !== undefined) { target[k] = overrides[k]; } } } } return target; } var debug; if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { debug = function() { var args = Array.prototype.slice.call(arguments); if (typeof args[0] === 'string') { args[0] = 'TUNNEL: ' + args[0]; } else { args.unshift('TUNNEL:'); } console.error.apply(console, args); } } else { debug = function() {}; } exports.debug = debug; // for test
{ "pile_set_name": "Github" }
{ config, lib, pkgs, ... }: with lib; let cfg = config.hardware; in { imports = [ (mkRenamedOptionModule [ "networking" "enableRT73Firmware" ] [ "hardware" "enableRedistributableFirmware" ]) (mkRenamedOptionModule [ "networking" "enableIntel3945ABGFirmware" ] [ "hardware" "enableRedistributableFirmware" ]) (mkRenamedOptionModule [ "networking" "enableIntel2100BGFirmware" ] [ "hardware" "enableRedistributableFirmware" ]) (mkRenamedOptionModule [ "networking" "enableRalinkFirmware" ] [ "hardware" "enableRedistributableFirmware" ]) (mkRenamedOptionModule [ "networking" "enableRTL8192cFirmware" ] [ "hardware" "enableRedistributableFirmware" ]) ]; ###### interface options = { hardware.enableAllFirmware = mkOption { default = false; type = types.bool; description = '' Turn on this option if you want to enable all the firmware. ''; }; hardware.enableRedistributableFirmware = mkOption { default = false; type = types.bool; description = '' Turn on this option if you want to enable all the firmware with a license allowing redistribution. (i.e. free firmware and <literal>firmware-linux-nonfree</literal>) ''; }; }; ###### implementation config = mkMerge [ (mkIf (cfg.enableAllFirmware || cfg.enableRedistributableFirmware) { hardware.firmware = with pkgs; [ firmwareLinuxNonfree intel2200BGFirmware rtl8192su-firmware rt5677-firmware rtl8723bs-firmware rtlwifi_new-firmware zd1211fw alsa-firmware sof-firmware openelec-dvb-firmware ] ++ optional (pkgs.stdenv.hostPlatform.isAarch32 || pkgs.stdenv.hostPlatform.isAarch64) raspberrypiWirelessFirmware ++ optionals (versionOlder config.boot.kernelPackages.kernel.version "4.13") [ rtl8723bs-firmware ]; }) (mkIf cfg.enableAllFirmware { assertions = [{ assertion = !cfg.enableAllFirmware || (config.nixpkgs.config.allowUnfree or false); message = '' the list of hardware.enableAllFirmware contains non-redistributable licensed firmware files. This requires nixpkgs.config.allowUnfree to be true. An alternative is to use the hardware.enableRedistributableFirmware option. ''; }]; hardware.firmware = with pkgs; [ broadcom-bt-firmware b43Firmware_5_1_138 b43Firmware_6_30_163_46 b43FirmwareCutter ] ++ optional (pkgs.stdenv.hostPlatform.isi686 || pkgs.stdenv.hostPlatform.isx86_64) facetimehd-firmware; }) ]; }
{ "pile_set_name": "Github" }
/* * Robotic Research Group (RRG) * State University of Piauí (UESPI), Brazil - Piauí - Teresina * * Fuzzy.cpp * * Author: AJ Alves <[email protected]> * Co authors: Dr. Ricardo Lira <[email protected]> * Msc. Marvin Lemos <[email protected]> * Douglas S. Kridi <[email protected]> * Kannya Leal <[email protected]> */ #include "Fuzzy.h" // CONTRUCTORS Fuzzy::Fuzzy() { // Initializing pointers with NULL // FuzzyInput this->fuzzyInputs = NULL; // FuzzyOutput this->fuzzyOutputs = NULL; // FuzzyRule this->fuzzyRules = NULL; } // DESTRUCTOR Fuzzy::~Fuzzy() { this->cleanFuzzyInputs(this->fuzzyInputs); this->cleanFuzzyOutputs(this->fuzzyOutputs); this->cleanFuzzyRules(this->fuzzyRules); } // PUBLIC METHODS // Method to include a new FuzzyInput into Fuzzy bool Fuzzy::addFuzzyInput(FuzzyInput *fuzzyInput) { // auxiliary variable to handle the operation fuzzyInputArray *newOne; // allocating in memory if ((newOne = (fuzzyInputArray *)malloc(sizeof(fuzzyInputArray))) == NULL) { // return false if in out of memory return false; } // building the object newOne->fuzzyInput = fuzzyInput; newOne->next = NULL; // if it is the first FuzzyInput, set it as the head if (this->fuzzyInputs == NULL) { this->fuzzyInputs = newOne; } else { // auxiliary variable to handle the operation fuzzyInputArray *aux = this->fuzzyInputs; // find the last element of the array while (aux != NULL) { if (aux->next == NULL) { // make the ralations between them aux->next = newOne; return true; } aux = aux->next; } } return true; } // Method to include a new FuzzyOutput into Fuzzy bool Fuzzy::addFuzzyOutput(FuzzyOutput *fuzzyOutput) { // auxiliary variable to handle the operation fuzzyOutputArray *newOne; // allocating in memory if ((newOne = (fuzzyOutputArray *)malloc(sizeof(fuzzyOutputArray))) == NULL) { // return false if in out of memory return false; } // building the object newOne->fuzzyOutput = fuzzyOutput; newOne->next = NULL; // sorting the fuzzyOutput fuzzyOutput->order(); // if it is the first FuzzyOutput, set it as the head if (this->fuzzyOutputs == NULL) { this->fuzzyOutputs = newOne; } else { // auxiliary variable to handle the operation fuzzyOutputArray *aux = this->fuzzyOutputs; // find the last element of the array while (aux != NULL) { if (aux->next == NULL) { // make the ralations between them aux->next = newOne; return true; } aux = aux->next; } } return true; } // Method to include a new FuzzyRule into Fuzzy bool Fuzzy::addFuzzyRule(FuzzyRule *fuzzyRule) { // auxiliary variable to handle the operation fuzzyRuleArray *newOne; // allocating in memory if ((newOne = (fuzzyRuleArray *)malloc(sizeof(fuzzyRuleArray))) == NULL) { // return false if in out of memory return false; } // building the object newOne->fuzzyRule = fuzzyRule; newOne->next = NULL; // if it is the first FuzzyOutput, set it as the head if (this->fuzzyRules == NULL) { this->fuzzyRules = newOne; } else { // auxiliary variable to handle the operation fuzzyRuleArray *aux = this->fuzzyRules; // find the last element of the array while (aux != NULL) { if (aux->next == NULL) { // make the ralations between them aux->next = newOne; return true; } aux = aux->next; } } return true; } // Method to set a crisp value to one FuzzyInput bool Fuzzy::setInput(int fuzzyInputIndex, float crispValue) { // auxiliary variable to handle the operation fuzzyInputArray *aux; // instantiate with the first element from array aux = this->fuzzyInputs; // while not in the end of the array, iterate while (aux != NULL) { // if the FuzzyInput index match with the desired if (aux->fuzzyInput->getIndex() == fuzzyInputIndex) { // set crisp value for this FuzzyInput and return true aux->fuzzyInput->setCrispInput(crispValue); return true; } aux = aux->next; } // if no FuzzyInput was found, return false return false; } // Method to start the calculate of the result bool Fuzzy::fuzzify() { // auxiliary variable to handle the operation fuzzyInputArray *fuzzyInputAux; fuzzyOutputArray *fuzzyOutputAux; fuzzyRuleArray *fuzzyRuleAux; // to reset the data of all FuzzyInput and FuzzyOutput objects // instantiate with first element of the array fuzzyInputAux = this->fuzzyInputs; // while not in the end of the array, iterate while (fuzzyInputAux != NULL) { // for each FuzzyInput, reset its data fuzzyInputAux->fuzzyInput->resetFuzzySets(); fuzzyInputAux = fuzzyInputAux->next; } // instantiate with first element of the array fuzzyOutputAux = this->fuzzyOutputs; // while not in the end of the array, iterate while (fuzzyOutputAux != NULL) { // for each FuzzyOutput, reset its data fuzzyOutputAux->fuzzyOutput->resetFuzzySets(); fuzzyOutputAux = fuzzyOutputAux->next; } // to calculate the pertinence of all FuzzyInput objects // instantiate with first element of the array fuzzyInputAux = this->fuzzyInputs; // while not in the end of the array, iterate while (fuzzyInputAux != NULL) { // for each FuzzyInput, calculate its pertinence fuzzyInputAux->fuzzyInput->calculateFuzzySetPertinences(); fuzzyInputAux = fuzzyInputAux->next; } // to evaluate which rules were triggered // instantiate with first element of the array fuzzyRuleAux = this->fuzzyRules; // while not in the end of the array, iterate while (fuzzyRuleAux != NULL) { // for each FuzzyRule, evaluate its expressions fuzzyRuleAux->fuzzyRule->evaluateExpression(); fuzzyRuleAux = fuzzyRuleAux->next; } // to truncate the output sets // instantiate with first element of the array fuzzyOutputAux = this->fuzzyOutputs; // while not in the end of the array, iterate while (fuzzyOutputAux != NULL) { // for each FuzzyOutput, truncate the result fuzzyOutputAux->fuzzyOutput->truncate(); fuzzyOutputAux = fuzzyOutputAux->next; } return true; } // Method to verify if one specific FuzzyRule was triggered bool Fuzzy::isFiredRule(int fuzzyRuleIndex) { // auxiliary variable to handle the operation fuzzyRuleArray *aux; // instantiate with first element of the array aux = this->fuzzyRules; // while not in the end of the array, iterate while (aux != NULL) { // if the FuzzyRule index match with the desired if (aux->fuzzyRule->getIndex() == fuzzyRuleIndex) { // return the calculated result return aux->fuzzyRule->isFired(); } aux = aux->next; } // if no FuzzyRule was found, return false return false; } // Method to retrieve the result of the process for one specific FuzzyOutput float Fuzzy::defuzzify(int fuzzyOutputIndex) { // auxiliary variable to handle the operation fuzzyOutputArray *aux; // instantiate with first element of the array aux = this->fuzzyOutputs; // while not in the end of the array, iterate while (aux != NULL) { // if the FuzzyOutput index match with the desired if (aux->fuzzyOutput->getIndex() == fuzzyOutputIndex) { // return the calculated result return aux->fuzzyOutput->getCrispOutput(); } aux = aux->next; } return 0; } // PRIVATE METHODS // Method to recursively clean all FuzzyInput from memory void Fuzzy::cleanFuzzyInputs(fuzzyInputArray *aux) { if (aux != NULL) { this->cleanFuzzyInputs(aux->next); // emptying allocated memory free(aux); } } // Method to recursively clean all FuzzyOutput from memory void Fuzzy::cleanFuzzyOutputs(fuzzyOutputArray *aux) { if (aux != NULL) { this->cleanFuzzyOutputs(aux->next); // emptying allocated memory free(aux); } } // Method to recursively clean all FuzzyRule from memory void Fuzzy::cleanFuzzyRules(fuzzyRuleArray *aux) { if (aux != NULL) { this->cleanFuzzyRules(aux->next); // emptying allocated memory free(aux); } }
{ "pile_set_name": "Github" }
#pragma once INT APIENTRY BITMAP_GetObject(SURFACE * bmp, INT count, LPVOID buffer); HBITMAP FASTCALL BITMAP_CopyBitmap (HBITMAP hBitmap); BOOL NTAPI GreSetBitmapOwner( _In_ HBITMAP hbmp, _In_ ULONG ulOwner); HBITMAP NTAPI GreCreateBitmap( _In_ ULONG nWidth, _In_ ULONG nHeight, _In_ ULONG cPlanes, _In_ ULONG cBitsPixel, _In_opt_ PVOID pvBits); HBITMAP NTAPI GreCreateBitmapEx( _In_ ULONG nWidth, _In_ ULONG nHeight, _In_ ULONG cjWidthBytes, _In_ ULONG iFormat, _In_ USHORT fjBitmap, _In_ ULONG cjSizeImage, _In_opt_ PVOID pvBits, _In_ FLONG flags); HBITMAP NTAPI GreCreateDIBitmapInternal( IN HDC hDc, IN INT cx, IN INT cy, IN DWORD fInit, IN OPTIONAL LPBYTE pjInit, IN OPTIONAL PBITMAPINFO pbmi, IN DWORD iUsage, IN FLONG fl, IN UINT cjMaxBits, IN HANDLE hcmXform); BOOL NTAPI UnsafeSetBitmapBits( _Inout_ PSURFACE psurf, _In_ ULONG cjBits, _In_ const VOID *pvBits); BOOL NTAPI GreGetBitmapDimension( _In_ HBITMAP hBitmap, _Out_ LPSIZE psizDim);
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: db45ebb17de411646b06393269da2e79 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> </root>
{ "pile_set_name": "Github" }
#!/usr/bin/env ruby -W # encoding: utf-8 require 'set' commit_range = ENV['TRAVIS_COMMIT_RANGE'] || 'master' puts "#{File.basename($0)}: commit range #{commit_range}" invalid_files = {} comment_block = false last_file = nil last_lines = nil changed_lines = `git diff #{commit_range} -- *.[mh]`.lines changed_lines.each do |line| case line when /^\+\+\+ [^\/]+\/(.*)$/ last_file = $1 when /^@@ ([-+]\d*,\d*) ([-+]\d*,\d*) @@/ last_lines = [$1, $2] when /^\+ / if not comment_block invalid_files[last_file] ||= {} invalid_files[last_file][last_lines] ||= [] invalid_files[last_file][last_lines] << line unless comment_block end when /^\+\s*?\/\*\*/ comment_block = true when /^\+\s*?\*\*\// then comment_block = false end end if invalid_files.empty? puts "All indent correct!" exit 0 end puts "The following files have incorrect indent:" invalid_files.each do |file, lines| puts "• #{file}:" lines.each do |line_no, line_data| puts "around #{line_no[0]}..#{line_no[1]}:" line_data.each do |line| puts line end end end
{ "pile_set_name": "Github" }
/** * @ngdoc factory * @name core.factory:trNativeAppBridge * @description * Service for communicating with Native Trustroots mobile app */ angular.module('core').factory('trNativeAppBridge', trNativeAppBridgeFactory); /* @ngInject */ function trNativeAppBridgeFactory( $q, $rootScope, $log, $window, $timeout, $location, ) { const service = { activate: activate, getAppInfo: getAppInfo, isNativeMobileApp: isNativeMobileApp, signalUnAuthenticated: signalUnAuthenticated, signalAuthenticated: signalAuthenticated, }; return service; /** * Tells if the site is wrapped inside native mobile app * * @returns {Boolea} */ function isNativeMobileApp() { return !!$window.isNativeMobileApp; } /** * Activate event listener listening for mobile app wrapping the site in * WebView signaling us it's ready. * * @returns {Promise} */ function activate() { return $q(function (resolve) { logToNativeApp('trNativeAppBridgeFactory activate'); // eslint-disable-next-line angular/document-service document.addEventListener('message', function (event) { // event = event.originalEvent || event; if (event && event.data === 'trMobileAppInit' && !isNativeMobileApp()) { // document.removeEventListener('message'); bootstrapBridge(); resolve($window.trMobileApp || { res: 'No data' }); } }); }); } /** * When mobile app wrapping the site in WebView signals us it's ready, * attempt to bootstrap app bridge. */ function bootstrapBridge() { logToNativeApp('Bootstrap native app bridge initialised'); // Not in native mobile, stop here if (!$window.trMobileApp || !angular.isObject($window.trMobileApp)) { logToNativeApp('Bootstrap native app bridge: not a mobile app'); return; } // Signal Native app it can stop polling us with `trMobileAppInit` message postMessageToApp('trNativeAppBridgeInitialized'); // Look in the DOM for new urls after each state change $rootScope.$on('$stateChangeSuccess', renderOutgoingUrls); logToNativeApp('Bootstrap native app bridge done'); } /** * Hooks onto all outgoing urls and instead of letting them open in current * browser instance (i.e. React Native WebView), sends a custom event to * the app, which then in turn handles opening the URL in the phone. */ function renderOutgoingUrls() { logToNativeApp('Render outbound urls'); const elementPattern = [ 'a[href^="http://"]', ',', // And 'a[href^="https://"]', ',', // And 'a[href^="mailto://"]', ',', // And 'a[href^="tel://"]', ',', // And 'a[href^="tel://"]', // Not: ':not(.tr-app-urlified)', ':not(a[href^="' + $location.protocol() + '://' + $location.host() + '"])', ':not(a[ui-sref])', ].join(''); // $timetout makes sure we have DOM rendered by Angular $timeout(function () { angular.element(elementPattern).each(function () { angular .element(this) .addClass('tr-app-urlified') .click(function (e) { const url = angular.element(this).attr('href'); if (url) { e.preventDefault(); postMessageToApp('openUrl', { url: url, }); } }); }); }); } /** * Read device & app info, should be something like: * ``` * { * "version": "0.2.0", * "expoVersion": "1.20.0", * "deviceName": "E39", * "deviceYearClass": 2012, * "os": "android" * } * ``` * * @return {Object} */ function getAppInfo() { return $window.trMobileApp || {}; } /** * Send "unAuthenticated" signal to mobile app */ function signalUnAuthenticated() { if (!isNativeMobileApp()) { return; } postMessageToApp('unAuthenticated'); } /** * Send "authenticated" signal to mobile app */ function signalAuthenticated() { if (!isNativeMobileApp()) { return; } postMessageToApp('authenticated'); } /** * Send log info signal to native app so that we know there what underlaying app is doing */ function logToNativeApp(str) { $log.log(str); postMessageToApp('log', { log: '[WebView]: ' + str }); } /** * Uses `window.postMessage()` to signal a messages to the native app * * At native app this page is wrapped in React Native WebView. * * Value in postMessage has to be string. */ function postMessageToApp(action, data) { if ( !isNativeMobileApp() || !action || !angular.isString(action) || !angular.isFunction($window.postMessage) ) { return; } data = data && angular.isObject(data) ? data : {}; const message = angular.extend( { action: action, }, data, ); // Note that `angular.toJson()` won't handle Date objects nicely on Safari // https://docs.angularjs.org/api/ng/function/angular.toJson $window.postMessage(angular.toJson(message)); } }
{ "pile_set_name": "Github" }
/* Original style from softwaremaniacs.org (c) Ivan Sagalaev <[email protected]> */ .hljs { display: block; padding: 0.5em; background: white; color: black; } .hljs-string, .hljs-tag .hljs-value, .hljs-filter .hljs-argument, .hljs-addition, .hljs-change, .apache .hljs-tag, .apache .hljs-cbracket, .nginx .hljs-built_in, .tex .hljs-formula { color: #888; } .hljs-comment, .hljs-template_comment, .hljs-shebang, .hljs-doctype, .hljs-pi, .hljs-javadoc, .hljs-deletion, .apache .hljs-sqbracket { color: #CCC; } .hljs-keyword, .hljs-tag .hljs-title, .ini .hljs-title, .lisp .hljs-title, .clojure .hljs-title, .http .hljs-title, .nginx .hljs-title, .css .hljs-tag, .hljs-winutils, .hljs-flow, .apache .hljs-tag, .tex .hljs-command, .hljs-request, .hljs-status { font-weight: bold; }
{ "pile_set_name": "Github" }
var tape = require('tape') var through = require('through2') var stream = require('stream') var shift = require('./') tape('shifts next', function (t) { var passthrough = through() passthrough.write('hello') passthrough.write('world') t.same(shift(passthrough), Buffer('hello')) t.same(shift(passthrough), Buffer('world')) t.end() }) tape('shifts next with core', function (t) { var passthrough = stream.PassThrough() passthrough.write('hello') passthrough.write('world') t.same(shift(passthrough), Buffer('hello')) t.same(shift(passthrough), Buffer('world')) t.end() }) tape('shifts next with object mode', function (t) { var passthrough = through({objectMode: true}) passthrough.write({hello: 1}) passthrough.write({world: 1}) t.same(shift(passthrough), {hello: 1}) t.same(shift(passthrough), {world: 1}) t.end() }) tape('shifts next with object mode with core', function (t) { var passthrough = stream.PassThrough({objectMode: true}) passthrough.write({hello: 1}) passthrough.write({world: 1}) t.same(shift(passthrough), {hello: 1}) t.same(shift(passthrough), {world: 1}) t.end() })
{ "pile_set_name": "Github" }
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.tutorialproject" android:versionCode="1" android:versionName="1.0"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="22" /> <application android:name=".MainApplication" android:allowBackup="true" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation|screenSize" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" /> </application> </manifest>
{ "pile_set_name": "Github" }
desc: Test that UUIDs work tests: - cd: r.uuid() ot: uuid() - cd: r.expr(r.uuid()) ot: uuid() - cd: r.type_of(r.uuid()) ot: 'STRING' - cd: r.uuid().ne(r.uuid()) ot: true - cd: r.uuid('magic') ot: ('97dd10a5-4fc4-554f-86c5-0d2c2e3d5330') - cd: r.uuid('magic').eq(r.uuid('magic')) ot: true - cd: r.uuid('magic').ne(r.uuid('beans')) ot: true - py: r.expr([1,2,3,4,5,6,7,8,9,10]).map(lambda u:r.uuid()).distinct().count() js: r([1,2,3,4,5,6,7,8,9,10]).map(function(u) {return r.uuid();}).distinct().count() rb: r.expr([1,2,3,4,5,6,7,8,9,10]).map {|u| r.uuid()}.distinct().count() ot: 10
{ "pile_set_name": "Github" }
fooking is distributed gateway server.It transfers client's requests to backend and send responses back with fpm protocol. Just like Nginx, as building a http server with nginx and fastcgi server(e.g fpm, etc..), you can create a socket server with fooking. # features 1 gateway server adding dynamicly. 2 unique sessionid for each client. 3 group broadcast(like redis's pub/sub). 4 server status monitor. 5 clients event notify(onconnect and onclose). 6 all language supported(php, python, etc...). 7 custom message protocol by lua. 8 backend connection keepalive. # client protocol client protocol is the protocol use in clients to fooking, default build up with 4 bytes header in bigend and body, But you can custom protocol with lua(reference script.lua). # backend protocol backend protocol is the protocol use in fooking to backends, you can use any luanguage with support fastcgi. this protocol is simply, reference: http://www.fastcgi.com/drupal/node/6?q=node/22 # getting started this example is chat room, source code in example/chat * Step 1(download and compile) git clone https://github.com/scgywx/fooking.git cd {$FOOKING_PATH} make * Step 2(start fooking router server) cd src ./fooking ../router.lua * Step 3(start fooking gateway server) ./fooking ../config.lua * Step 4(start fastcgi server, e.g php-fpm) service php-fpm start(if it was started please skip this step) * Step 5(test) modify websocket server host and port in example/chat/index.html(search 'ws://') open index.html in your browser and starting chat # arch ![image](http://static.oschina.net/uploads/space/2014/1209/222447_G7Ft_140911.jpg)
{ "pile_set_name": "Github" }
var isArray = require('./isArray'); /** * Casts `value` as an array if it's not one. * * @static * @memberOf _ * @since 4.4.0 * @category Lang * @param {*} value The value to inspect. * @returns {Array} Returns the cast array. * @example * * _.castArray(1); * // => [1] * * _.castArray({ 'a': 1 }); * // => [{ 'a': 1 }] * * _.castArray('abc'); * // => ['abc'] * * _.castArray(null); * // => [null] * * _.castArray(undefined); * // => [undefined] * * _.castArray(); * // => [] * * var array = [1, 2, 3]; * console.log(_.castArray(array) === array); * // => true */ function castArray() { if (!arguments.length) { return []; } var value = arguments[0]; return isArray(value) ? value : [value]; } module.exports = castArray;
{ "pile_set_name": "Github" }
# Overview Turbo is developed for web site that based on [tornado](http://tornado.readthedocs.org/en/stable/) and [mongodb](https://www.mongodb.org/) to build rapidly and easily to scale up and maintain. Turbo has support for: - Easily scale up and maintain - Rapid development for RESTFul api and web site - Django or flask style application structure - Easily customizing - Simple ORM for mongodb - Logger - Session In addtion to the above, turbo has a command line utility `turbo-admin` for fast build application structure. ## Demo ```sh git clone https://github.com/wecatch/app-turbo.git cd app-turbo/demos/helloword/app-server python main.py ``` Open your brower and visit [http://localhost:8888](http://localhost:8888) ## Install First be sure you have `MongoDB` and `redis` installed. ```sh pip install turbo ``` Install the latest ```sh git clone https://github.com/wecatch/app-turbo.git cd app-turbo python setup.py install ``` ## Hello, world ```bash turbo-admin startproject my_turbo_app cd my_turbo_app cd app-server python main.py ``` Open your broswer and visite [http://localhost:8888](http://localhost:8888) Server start on port 8888 default, you can change this `python main.py --port=8890`
{ "pile_set_name": "Github" }
<?php /** * The main site settings page */ return array( /** * Settings page title * * @type string */ 'title' => 'Site Settings', /** * The edit fields array * * @type array */ 'edit_fields' => array( 'site_name' => array( 'title' => 'Site Name', 'type' => 'text', 'limit' => 50, ), 'page_cache_lifetime' => array( 'title' => 'Page Cache Lifetime (in minutes)', 'type' => 'number', ), 'logo' => array( 'title' => 'Image (200 x 150)', 'type' => 'image', 'naming' => 'random', 'location' => public_path(), 'size_limit' => 2, 'sizes' => array( array(200, 150, 'crop', public_path() . '/resize/', 100), ) ), ), /** * The validation rules for the form, based on the Laravel validation class * * @type array */ 'rules' => array( 'site_name' => 'required|max:50', 'page_cache_lifetime' => 'required|integer', 'logo' => 'required', ), /** * This is run prior to saving the JSON form data * * @type function * @param array $data * * @return string (on error) / void (otherwise) */ 'before_save' => function(&$data) { $data['site_name'] = $data['site_name'] . ' - The Blurst Site Ever'; }, /** * The permission option is an authentication check that lets you define a closure that should return true if the current user * is allowed to view this settings page. Any "falsey" response will result in a 404. * * @type closure */ 'permission'=> function() { return true; //return Auth::user()->hasRole('developer'); }, /** * This is where you can define the settings page's custom actions */ 'actions' => array( //Ordering an item up 'clear_page_cache' => array( 'title' => 'Clear Page Cache', 'messages' => array( 'active' => 'Clearing cache...', 'success' => 'Page Cache Cleared', 'error' => 'There was an error while clearing the page cache', ), //the settings data is passed to the closure and saved if a truthy response is returned 'action' => function(&$data) { Cache::forget('pages'); return true; } ), ), );
{ "pile_set_name": "Github" }
namespace $ASSEMBLYNAME${ using System; using System.Collections.Generic; using System.ComponentModel; using DevExpress.Persistent.Base; using DevExpress.Persistent.Validation; using DevExpress.Xpo; using Xpand.Persistent.Base.PersistentMetaData; using Xpand.Persistent.BaseImpl.PersistentMetaData.PersistentAttributeInfos; using System.Linq; $TYPEATTRIBUTES$ public class $CLASSNAME$:$BASECLASSNAME${ public $CLASSNAME$(Session session):base(session){} public override void AfterConstruction() { base.AfterConstruction(); } protected override void OnSaving() { base.OnSaving(); } protected override void OnChanged(string propertyName, object oldValue, object newValue) { base.OnChanged(propertyName,oldValue, newValue); } $INJECTCODE$ } }
{ "pile_set_name": "Github" }
#!/bin/bash if [[ $(nodetool status | grep $POD_IP) == *"UN"* ]]; then if [[ $DEBUG ]]; then echo "UN"; fi exit 0; else if [[ $DEBUG ]]; then echo "Not Up"; fi exit 1; fi
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <Body> <Title>湖北二广高速路大客车翻覆34人受伤</Title> <ReportTime type="absTime">2011-10-13 14:31:05</ReportTime> <Content> <Paragraph> <Sentence> <Event eid="e1" type="thoughtevent"> <Participant sid="s1">中新网</Participant> <Location lid="l1">荆门</Location> <Time tid="t1" type="relTime">10月13日</Time> <Denoter did="d1" type="statement">电</Denoter> </Event>(吴奇勇) <Event eid="e2"> <Time tid="t2" type="relTime">13日凌晨3时40分许</Time>, <Location lid="l2">二广高速1738公里+800米处湖北省荆门市沙洋县纪山镇付场村路段</Location>,一辆北京开往湖南张家界的车号为“湘G01572” <Object sid="s2">大客车</Object>发生 <Denoter did="d2" type="emergency">车祸</Denoter> </Event>, <Event eid="e3"> <Object sid="s3">客车</Object> <Denoter did="d3" type="action">翻覆</Denoter>到 <Location lid="l3">高速护栏下</Location> </Event>, <Event eid="e4">导致 <Participant sid="s4">34人</Participant> <Denoter did="d4" type="stateChange">受伤</Denoter> </Event>, <Event eid="e5"> <Denoter did="d5" type="statement">重伤</Denoter>有 <Participant sid="s5">8人</Participant> </Event>, <Event eid="e6">其中 <Denoter did="d6" type="statement">危重</Denoter> <Participant sid="s6">2人</Participant> </Event>。 </Sentence> </Paragraph>    <Paragraph> <Sentence> <Event eid="e7" type="thoughtEvent">据参加现场救助的 <Participant sid="s7">湖北省沙洋县宣传部副部长段红蕾</Participant> <Denoter did="d7" type="statement">介绍</Denoter> </Event>, <Event eid="e8">接到 <Denoter did="d8" type="action">报警</Denoter>后 </Event>, <Event eid="e9">事发地湖北 <Participant sid="s9">荆门市副市长周松青</Participant>和 <Participant sid="s9">沙洋县委书记梁早阳</Participant>等第一时间 <Denoter did="d9" type="movement">赶到</Denoter> <Location lid="l9" type="destination">现场</Location> </Event> <Event eid="e10">组织 <Participant sid="s10">当地公安、消防、卫生等部门</Participant>紧急 <Denoter did="d10" type="action">施救</Denoter> </Event>。 <Event eid="e11">34名伤者中除 <Participant oid="o11">两人</Participant> <Denoter did="d11" type="action">送往</Denoter> <Location lid="l11" type="destination">荆门市石化医院</Location>外 </Event>, <Event eid="e12"> <Participant oid="o12,o13">其他全部</Participant>就近 <Denoter did="d12" type="movement">送往</Denoter>湖北省荆州市多家医院 </Event> <Event eid="e13"> <Denoter did="d13" type="operation">救治</Denoter> </Event>。 </Sentence> <Sentence> <Event eid="e14">34名伤者中有 <Denoter did="d14" type="stateChange">重伤</Denoter> <Participant sid="s14">8人</Participant> </Event>, <Event eid="e15">其中 <Denoter did="d15" type="stateChange">危重</Denoter> <Participant sid="s15">2人</Participant> </Event>。 </Sentence> </Paragraph>    <Paragraph> <Sentence> <Event eid="e16" type="thoughtEvent">据现场施救的 <Participant sid="s16">湖北高警总队三支队支队长韩</Participant> <Denoter did="d16" type="statement">介绍</Denoter> </Event>, <Event eid="e17">经初步 <Denoter did="d17" type="action">调查</Denoter> </Event>,“湘G01572”大客车为湖南省张家界汽运公司第二直属分公司车辆。 <Event eid="e18"> <Time tid="t18" type="relTime">事发时</Time>由 <Location lid="l18" type="origin">北京</Location> <Denoter did="d18" type="movement">开往</Denoter> <Location lid="l18" type="destination">张家界</Location> </Event>。 </Sentence> <Sentence> <Event eid="e19"> <Time tid="t19" type="relTime">当时</Time> <Object sid="s19,s20,s21">大客车</Object>向左 <Denoter did="d19" type="movement">过</Denoter> <Location lid="l19">中央隔离带</Location> </Event>, <Event eid="e20">再 <Denoter did="d20" type="action">冲开</Denoter> <Object oid="o20">对向车道护栏</Object> </Event>, <Event eid="e21"> <Denoter did="d21" type="action">翻覆</Denoter>到 <Location lid="l21">护坡下</Location> </Event>。 </Sentence> <Sentence> <Event eid="e22"> <Object sid="s22">客车</Object> <Time tid="t22" type="relTime">事发时</Time> <Denoter did="d22" type="action">载客</Denoter> <Participant oid="o22">49人</Participant> </Event>。 </Sentence> </Paragraph>    <Paragraph> <Sentence> <Event eid="e23">截止记者 <Time tid="t23" type="relTime">发稿时</Time>, <Participant oid="o23,o24">伤员</Participant>已经全部 <Denoter did="d23" type="movement">送往</Denoter>医院 </Event> <Event eid="e24"> <Denoter did="d24" type="operation">治疗</Denoter> </Event>, <Event eid="e25"> <Participant sid="s25">高警</Participant>和 <Participant sid="s25">路政人员</Participant>仍在 <Denoter did="d25" type="action">清理</Denoter> <Location lid="l25">现场</Location> </Event>, <Event eid="e26"> <Location lid="l26">二广高速事发地段</Location> <Denoter did="d26" type="action">通行</Denoter>未受影响 </Event>。 </Sentence> <Sentence> <Event eid="e27"> <Object oid="o27">事故原因</Object>还在进一步 <Denoter did="d27" type="action">调查</Denoter> 中 </Event>。 </Sentence> </Paragraph> </Content> <eRelation relType="Thoughtcontent" thoughtevent_eid="e1" thoughtcontent_eids="e2-e27"/> <eRelation relType="Causal" cause_eid="e3" effect_eid="e4"/> <eRelation relType="Causal" cause_eid="e3" effect_eid="e5"/> <eRelation relType="Causal" cause_eid="e3" effect_eid="e6"/> <eRelation relType="Thoughtcontent" thoughtevent_eid="e7" thoughtcontent_eids="e8-e15"/> <eRelation relType="Follow" bevent_eid="e8" aevent_eid="e9"/> <eRelation relType="Follow" bevent_eid="e9" aevent_eid="e10"/> <eRelation relType="Accompany" accompanya_eid="e11" accompanyb_eid="e12"/> <eRelation relType="Follow" bevent_eid="e12" aevent_eid="e13"/> <eRelation relType="Thoughtcontent" thoughtevent_eid="e16" thoughtcontent_eids="e17-e22"/> <eRelation relType="Follow" bevent_eid="e18" aevent_eid="e19"/> <eRelation relType="Follow" bevent_eid="e19" aevent_eid="e20"/> <eRelation relType="Follow" bevent_eid="e20" aevent_eid="e21"/> <eRelation relType="Follow" bevent_eid="e23" aevent_eid="e24"/> <eRelation relType="Follow" bevent_eid="e24" aevent_eid="e25"/> </Body>
{ "pile_set_name": "Github" }
using System; namespace NetCoreStack.WebSockets { [Flags] public enum WebSocketCommands : byte { Connect = 1, DataSend = 2, Handshake = 4, All = 7 } }
{ "pile_set_name": "Github" }
#include <map> #include "D3dDdi/Adapter.h" #include "D3dDdi/AdapterFuncs.h" #include "D3dDdi/DeviceCallbacks.h" #include "D3dDdi/DeviceFuncs.h" namespace { HRESULT APIENTRY closeAdapter(HANDLE hAdapter) { HRESULT result = D3dDdi::AdapterFuncs::s_origVtablePtr->pfnCloseAdapter(hAdapter); if (SUCCEEDED(result)) { D3dDdi::Adapter::remove(hAdapter); } return result; } HRESULT APIENTRY createDevice(HANDLE hAdapter, D3DDDIARG_CREATEDEVICE* pCreateData) { D3dDdi::DeviceCallbacks::hookVtable(pCreateData->pCallbacks); HRESULT result = D3dDdi::AdapterFuncs::s_origVtablePtr->pfnCreateDevice(hAdapter, pCreateData); if (SUCCEEDED(result)) { D3dDdi::DeviceFuncs::hookVtable( D3dDdi::Adapter::get(hAdapter).getModule(), pCreateData->pDeviceFuncs); D3dDdi::DeviceFuncs::onCreateDevice(hAdapter, pCreateData->hDevice); } return result; } HRESULT APIENTRY getCaps(HANDLE hAdapter, const D3DDDIARG_GETCAPS* pData) { HRESULT result = D3dDdi::AdapterFuncs::s_origVtablePtr->pfnGetCaps(hAdapter, pData); if (SUCCEEDED(result) && D3DDDICAPS_DDRAW == pData->Type) { static_cast<DDRAW_CAPS*>(pData->pData)->FxCaps = DDRAW_FXCAPS_BLTMIRRORLEFTRIGHT | DDRAW_FXCAPS_BLTMIRRORUPDOWN; } return result; } } namespace D3dDdi { void AdapterFuncs::onOpenAdapter(HANDLE adapter, HMODULE module) { Adapter::add(adapter, module); } void AdapterFuncs::setCompatVtable(D3DDDI_ADAPTERFUNCS& vtable) { vtable.pfnCloseAdapter = &closeAdapter; vtable.pfnCreateDevice = &createDevice; vtable.pfnGetCaps = &getCaps; } }
{ "pile_set_name": "Github" }
# This file configures AppVeyor (http://www.appveyor.com), # a Windows-based CI service similar to Travis. # Identifier for this run version: "{build}" # Clone the repo into this path, which conforms to the standard # Go workspace structure. clone_folder: c:\gopath\src\cloud.google.com\go environment: GOPATH: c:\gopath GCLOUD_TESTS_GOLANG_PROJECT_ID: dulcet-port-762 GCLOUD_TESTS_GOLANG_KEY: c:\gopath\src\cloud.google.com\go\key.json KEYFILE_CONTENTS: secure: IvRbDAhM2PIQqzVkjzJ4FjizUvoQ+c3vG/qhJQG+HlZ/L5KEkqLu+x6WjLrExrNMyGku4znB2jmbTrUW3Ob4sGG+R5vvqeQ3YMHCVIkw5CxY+/bUDkW5RZWsVbuCnNa/vKsWmCP+/sZW6ICe29yKJ2ZOb6QaauI4s9R6j+cqBbU9pumMGYFRb0Rw3uUU7DKmVFCy+NjTENZIlDP9rmjANgAzigowJJEb2Tg9sLlQKmQeKiBSRN8lKc5Nq60a+fIzHGKvql4eIitDDDpOpyHv15/Xr1BzFw2yDoiR4X1lng0u7q0X9RgX4VIYa6gT16NXBEmQgbuX8gh7SfPMp9RhiZD9sVUaV+yogEabYpyPnmUURo0hXwkctKaBkQlEmKvjHwF5dvbg8+yqGhwtjAgFNimXG3INrwQsfQsZskkQWanutbJf9xy50GyWWFZZdi0uT4oXP/b5P7aklPXKXsvrJKBh7RjEaqBrhi86IJwOjBspvoR4l2WmcQyxb2xzQS1pjbBJFQfYJJ8+JgsstTL8PBO9d4ybJC0li1Om1qnWxkaewvPxxuoHJ9LpRKof19yRYWBmhTXb2tTASKG/zslvl4fgG4DmQBS93WC7dsiGOhAraGw2eCTgd0lYZOhk1FjWl9TS80aktXxzH/7nTvem5ohm+eDl6O0wnTL4KXjQVNSQ1PyLn4lGRJ5MNGzBTRFWIr2API2rca4Fysyfh/UdmazPGlNbY9JPGqb9+F04QzLfqm+Zz/cHy59E7lOSMBlUI4KD6d6ZNNKNRH+/g9i+fSiyiXKugTfda8KBnWGyPwprxuWGYaiQUGUYOwJY5R6x5c4mjImAB310V+Wo33UbWFJiwxEDsiCNqW1meVkBzt2er26vh4qbgCUIQ3iM3gFPfHgy+QxkmIhic7Q1HYacQElt8AAP41M7cCKWCuZidegP37MBB//mjjiNt047ZSQEvB4tqsX/OvfbByVef+cbtVw9T0yjHvmCdPW1XrhyrCCgclu6oYYdbmc5D7BBDRbjjMWGv6YvceAbfGf6ukdB5PuV+TGEN/FoQ1QTRA6Aqf+3fLMg4mS4oyTfw5xyYNbv3qoyLPrp+BnxI53WB9p0hfMg4n9FD6NntBxjDq+Q3Lk/bjC/Y4MaRWdzbMzF9a0lgGfcw9DURlK5p7uGJC9vg34feNoQprxVEZRQ01cHLeob6eGkYm4HxSRx8JY39Mh+9wzJo+k/aIvFleNC3e35NOrkXr6wb5e42n2DwBdPqdNolTLtLFRglAL1LTpp27UjvjieWJAKfoDTR5CKl01sZqt0wPdLLcvsMj6CiPFmccUIOYeZMe86kLBD61Qa5F1EwkgO3Om2qSjW96FzL4skRc+BmU5RrHlAFSldR1wpUgtkUMv9vH5Cy+UJdcvpZ8KbmhZ2PsjF7ddJ1ve9RAw3cP325AyIMwZ77Ef1mgTM0NJze6eSW1qKlEsgt1FADPyeUu1NQTA2H2dueMPGlArWTSUgyWR9AdfpqouT7eg0JWI5w+yUZZC+/rPglYbt84oLmYpwuli0z8FyEQRPIc3EtkfWIv/yYgDr2TZ0N2KvGfpi/MAUWgxI1gleC2uKgEOEtuJthd3XZjF2NoE7IBqjQOINybcJOjyeB5vRLDY1FLuxYzdg1y1etkV4XQig/vje install: # Info for debugging. - echo %PATH% - go version - go env - go get -v -d -t ./... # Provide a build script, or AppVeyor will call msbuild. build_script: - go install -v ./... - echo %KEYFILE_CONTENTS% > %GCLOUD_TESTS_GOLANG_KEY% test_script: - go test -v ./...
{ "pile_set_name": "Github" }
debug synnet tech tech Username PASSWORD adm (none) <br> ANYCOM <br> ILMI admin (none) n/a PASSWORD adminttd adminttd admin comcomcom admin admin operator (none) security security 3comcso RIP000 tech (none) admin synnet (none) admin root (none) monitor monitor manager manager
{ "pile_set_name": "Github" }
using Microsoft.Extensions.Localization; using OrchardCore.Users.Services; using OrchardCore.Workflows.Services; namespace OrchardCore.Users.Workflows.Activities { public class UserEnabledEvent : UserEvent { public UserEnabledEvent(IUserService userService, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer<UserEnabledEvent> localizer) : base(userService, scriptEvaluator, localizer) { } public override string Name => nameof(UserEnabledEvent); public override LocalizedString DisplayText => S["User Enabled Event"]; } }
{ "pile_set_name": "Github" }