code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php use yii\bootstrap\Html; /** * @var $this \yii\web\View * @var $content string */ ?> <?php $this->beginContent('@app/views/layouts/base.php') ?> <div class="wrap"> <?= $this->render('//shared/admin_panel') ?> <?= $this->render('//shared/header') ?> <a class="logo" href="/"> <?php echo Html::img("@web/files/img/logo.png") ?> </a> <?= $this->render('//shared/menu') ?> <?php if (isset($this->blocks['topBanner'])) { echo $this->blocks['topBanner']; } ?> <div class="container"><?= $content ?></div> </div> <footer class="footer"> <div class="container"> <p class="pull-left">&copy; Vetoni <?= date('Y') ?></p> <p class="pull-right"><?= Yii::powered() ?></p> </div> </footer> <?php $this->endContent() ?>
vetoni/toko
views/layouts/main.php
PHP
bsd-3-clause
874
<h1 id="title_header"></h1> <div id="calendar" class="{{ css_classes }}"> </div>
arbitrahj/django-bootstrap-calendar
dj_calendar/templates/dj_calendar/partial/calendar.html
HTML
bsd-3-clause
82
package com.github.paulp.optional import scala.collection._ import mutable.HashSet case class Options( options: Map[String, String], args: List[String], rawArgs: List[String] ) case class ArgInfo(short: Char, long: String, isSwitch: Boolean, help: String) object Options { private val ShortOption = """-(\w)""".r private val ShortSquashedOption = """-([^-\s]\w+)""".r private val LongOption = """--([-\w]+)""".r private val OptionTerminator = "--" private val True = "true"; /** * Take a list of string arguments and parse them into options. * Currently the dumbest option parser in the entire world, but * oh well. */ def parse(mainArgs: scala.collection.immutable.Map [String, MainArg], argInfos: HashSet[ArgInfo], args: String*): Options = { import mutable._; val optionsStack = new ArrayStack[String]; val options = new OpenHashMap[String, String]; val arguments = new ArrayBuffer[String]; def addSwitch(c: Char) = options(c.toString) = True def isSwitch(c: Char) = argInfos exists { case ArgInfo(`c`, _, true, _) => true case _ => false } def addOption(name: String) = { if (mainArgs.isDefinedAt(name) && mainArgs(name).isBoolean) { options(name) = True; } else if (optionsStack.isEmpty) { options(name) = True; } else { val next = optionsStack.pop; next match { case ShortOption(_) | ShortSquashedOption(_) | LongOption(_) | OptionTerminator => optionsStack.push(next); options(name) = True; case x => options(name) = x; } } } optionsStack ++= args.reverse; while(!optionsStack.isEmpty){ optionsStack.pop match { case ShortSquashedOption(xs) => xs foreach addSwitch case ShortOption(name) => val c = name(0) if (isSwitch(c)) addSwitch(c) else addOption(name) // Treat hyphens as if they were underscores, so we can have --switches-like-this as well as --switches_like_this case LongOption(name) => addOption (name.replaceAll ("-", "_")); case OptionTerminator => optionsStack.drain(arguments += _); case x => arguments += x; } } Options(options, arguments.toList, args.toList) } }
ornicar/optional
src/main/scala/options.scala
Scala
bsd-3-clause
2,389
/*- * Copyright (c) 2001-2008, by Cisco Systems, Inc. All rights reserved. * Copyright (c) 2008-2012, by Randall Stewart. All rights reserved. * Copyright (c) 2008-2012, by Michael Tuexen. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * a) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * b) 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. * * c) Neither the name of Cisco Systems, 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. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #ifndef _NETINET_SCTP_CONSTANTS_H_ #define _NETINET_SCTP_CONSTANTS_H_ /* IANA assigned port number for SCTP over UDP encapsulation */ #define SCTP_OVER_UDP_TUNNELING_PORT 9899 /* Number of packets to get before sack sent by default */ #define SCTP_DEFAULT_SACK_FREQ 2 /* Address limit - This variable is calculated * based on an 65535 byte max ip packet. We take out 100 bytes * for the cookie, 40 bytes for a v6 header and 32 * bytes for the init structure. A second init structure * for the init-ack and then finally a third one for the * imbedded init. This yeilds 100+40+(3 * 32) = 236 bytes. * This leaves 65299 bytes for addresses. We throw out the 299 bytes. * Now whatever we send in the INIT() we need to allow to get back in the * INIT-ACK plus all the values from INIT and INIT-ACK * listed in the cookie. Plus we need some overhead for * maybe copied parameters in the COOKIE. If we * allow 1080 addresses, and each side has 1080 V6 addresses * that will be 21600 bytes. In the INIT-ACK we will * see the INIT-ACK 21600 + 43200 in the cookie. This leaves * about 500 bytes slack for misc things in the cookie. */ #define SCTP_ADDRESS_LIMIT 1080 /* We need at least 2k of space for us, inits * larger than that lets abort. */ #define SCTP_LARGEST_INIT_ACCEPTED (65535 - 2048) /* Number of addresses where we just skip the counting */ #define SCTP_COUNT_LIMIT 40 #define SCTP_ZERO_COPY_TICK_DELAY (((100 * hz) + 999) / 1000) #define SCTP_ZERO_COPY_SENDQ_TICK_DELAY (((100 * hz) + 999) / 1000) /* Number of ticks to delay before running * iterator on an address change. */ #define SCTP_ADDRESS_TICK_DELAY 2 #define SCTP_VERSION_STRING "KAME-BSD 1.1" /* #define SCTP_AUDITING_ENABLED 1 used for debug/auditing */ #define SCTP_AUDIT_SIZE 256 #define SCTP_KTRHEAD_NAME "sctp_iterator" #define SCTP_KTHREAD_PAGES 0 #define SCTP_MCORE_NAME "sctp_core_worker" /* If you support Multi-VRF how big to * make the initial array of VRF's to. */ #define SCTP_DEFAULT_VRF_SIZE 4 /* constants for rto calc */ #define sctp_align_safe_nocopy 0 #define sctp_align_unsafe_makecopy 1 /* JRS - Values defined for the HTCP algorithm */ #define ALPHA_BASE (1<<7) /* 1.0 with shift << 7 */ #define BETA_MIN (1<<6) /* 0.5 with shift << 7 */ #define BETA_MAX 102 /* 0.8 with shift << 7 */ /* Places that CWND log can happen from */ #define SCTP_CWND_LOG_FROM_FR 1 #define SCTP_CWND_LOG_FROM_RTX 2 #define SCTP_CWND_LOG_FROM_BRST 3 #define SCTP_CWND_LOG_FROM_SS 4 #define SCTP_CWND_LOG_FROM_CA 5 #define SCTP_CWND_LOG_FROM_SAT 6 #define SCTP_BLOCK_LOG_INTO_BLK 7 #define SCTP_BLOCK_LOG_OUTOF_BLK 8 #define SCTP_BLOCK_LOG_CHECK 9 #define SCTP_STR_LOG_FROM_INTO_STRD 10 #define SCTP_STR_LOG_FROM_IMMED_DEL 11 #define SCTP_STR_LOG_FROM_INSERT_HD 12 #define SCTP_STR_LOG_FROM_INSERT_MD 13 #define SCTP_STR_LOG_FROM_INSERT_TL 14 #define SCTP_STR_LOG_FROM_MARK_TSN 15 #define SCTP_STR_LOG_FROM_EXPRS_DEL 16 #define SCTP_FR_LOG_BIGGEST_TSNS 17 #define SCTP_FR_LOG_STRIKE_TEST 18 #define SCTP_FR_LOG_STRIKE_CHUNK 19 #define SCTP_FR_T3_TIMEOUT 20 #define SCTP_MAP_PREPARE_SLIDE 21 #define SCTP_MAP_SLIDE_FROM 22 #define SCTP_MAP_SLIDE_RESULT 23 #define SCTP_MAP_SLIDE_CLEARED 24 #define SCTP_MAP_SLIDE_NONE 25 #define SCTP_FR_T3_MARK_TIME 26 #define SCTP_FR_T3_MARKED 27 #define SCTP_FR_T3_STOPPED 28 #define SCTP_FR_MARKED 30 #define SCTP_CWND_LOG_NOADV_SS 31 #define SCTP_CWND_LOG_NOADV_CA 32 #define SCTP_MAX_BURST_APPLIED 33 #define SCTP_MAX_IFP_APPLIED 34 #define SCTP_MAX_BURST_ERROR_STOP 35 #define SCTP_INCREASE_PEER_RWND 36 #define SCTP_DECREASE_PEER_RWND 37 #define SCTP_SET_PEER_RWND_VIA_SACK 38 #define SCTP_LOG_MBCNT_INCREASE 39 #define SCTP_LOG_MBCNT_DECREASE 40 #define SCTP_LOG_MBCNT_CHKSET 41 #define SCTP_LOG_NEW_SACK 42 #define SCTP_LOG_TSN_ACKED 43 #define SCTP_LOG_TSN_REVOKED 44 #define SCTP_LOG_LOCK_TCB 45 #define SCTP_LOG_LOCK_INP 46 #define SCTP_LOG_LOCK_SOCK 47 #define SCTP_LOG_LOCK_SOCKBUF_R 48 #define SCTP_LOG_LOCK_SOCKBUF_S 49 #define SCTP_LOG_LOCK_CREATE 50 #define SCTP_LOG_INITIAL_RTT 51 #define SCTP_LOG_RTTVAR 52 #define SCTP_LOG_SBALLOC 53 #define SCTP_LOG_SBFREE 54 #define SCTP_LOG_SBRESULT 55 #define SCTP_FR_DUPED 56 #define SCTP_FR_MARKED_EARLY 57 #define SCTP_FR_CWND_REPORT 58 #define SCTP_FR_CWND_REPORT_START 59 #define SCTP_FR_CWND_REPORT_STOP 60 #define SCTP_CWND_LOG_FROM_SEND 61 #define SCTP_CWND_INITIALIZATION 62 #define SCTP_CWND_LOG_FROM_T3 63 #define SCTP_CWND_LOG_FROM_SACK 64 #define SCTP_CWND_LOG_NO_CUMACK 65 #define SCTP_CWND_LOG_FROM_RESEND 66 #define SCTP_FR_LOG_CHECK_STRIKE 67 #define SCTP_SEND_NOW_COMPLETES 68 #define SCTP_CWND_LOG_FILL_OUTQ_CALLED 69 #define SCTP_CWND_LOG_FILL_OUTQ_FILLS 70 #define SCTP_LOG_FREE_SENT 71 #define SCTP_NAGLE_APPLIED 72 #define SCTP_NAGLE_SKIPPED 73 #define SCTP_WAKESND_FROM_SACK 74 #define SCTP_WAKESND_FROM_FWDTSN 75 #define SCTP_NOWAKE_FROM_SACK 76 #define SCTP_CWNDLOG_PRESEND 77 #define SCTP_CWNDLOG_ENDSEND 78 #define SCTP_AT_END_OF_SACK 79 #define SCTP_REASON_FOR_SC 80 #define SCTP_BLOCK_LOG_INTO_BLKA 81 #define SCTP_ENTER_USER_RECV 82 #define SCTP_USER_RECV_SACKS 83 #define SCTP_SORECV_BLOCKSA 84 #define SCTP_SORECV_BLOCKSB 85 #define SCTP_SORECV_DONE 86 #define SCTP_SACK_RWND_UPDATE 87 #define SCTP_SORECV_ENTER 88 #define SCTP_SORECV_ENTERPL 89 #define SCTP_MBUF_INPUT 90 #define SCTP_MBUF_IALLOC 91 #define SCTP_MBUF_IFREE 92 #define SCTP_MBUF_ICOPY 93 #define SCTP_MBUF_SPLIT 94 #define SCTP_SORCV_FREECTL 95 #define SCTP_SORCV_DOESCPY 96 #define SCTP_SORCV_DOESLCK 97 #define SCTP_SORCV_DOESADJ 98 #define SCTP_SORCV_BOTWHILE 99 #define SCTP_SORCV_PASSBF 100 #define SCTP_SORCV_ADJD 101 #define SCTP_UNKNOWN_MAX 102 #define SCTP_RANDY_STUFF 103 #define SCTP_RANDY_STUFF1 104 #define SCTP_STRMOUT_LOG_ASSIGN 105 #define SCTP_STRMOUT_LOG_SEND 106 #define SCTP_FLIGHT_LOG_DOWN_CA 107 #define SCTP_FLIGHT_LOG_UP 108 #define SCTP_FLIGHT_LOG_DOWN_GAP 109 #define SCTP_FLIGHT_LOG_DOWN_RSND 110 #define SCTP_FLIGHT_LOG_UP_RSND 111 #define SCTP_FLIGHT_LOG_DOWN_RSND_TO 112 #define SCTP_FLIGHT_LOG_DOWN_WP 113 #define SCTP_FLIGHT_LOG_UP_REVOKE 114 #define SCTP_FLIGHT_LOG_DOWN_PDRP 115 #define SCTP_FLIGHT_LOG_DOWN_PMTU 116 #define SCTP_SACK_LOG_NORMAL 117 #define SCTP_SACK_LOG_EXPRESS 118 #define SCTP_MAP_TSN_ENTERS 119 #define SCTP_THRESHOLD_CLEAR 120 #define SCTP_THRESHOLD_INCR 121 #define SCTP_FLIGHT_LOG_DWN_WP_FWD 122 #define SCTP_FWD_TSN_CHECK 123 #define SCTP_LOG_MAX_TYPES 124 /* * To turn on various logging, you must first enable 'options KTR' and * you might want to bump the entires 'options KTR_ENTRIES=80000'. * To get something to log you define one of the logging defines. * (see LINT). * * This gets the compile in place, but you still need to turn the * logging flag on too in the sysctl (see in sctp.h). */ #define SCTP_LOG_EVENT_UNKNOWN 0 #define SCTP_LOG_EVENT_CWND 1 #define SCTP_LOG_EVENT_BLOCK 2 #define SCTP_LOG_EVENT_STRM 3 #define SCTP_LOG_EVENT_FR 4 #define SCTP_LOG_EVENT_MAP 5 #define SCTP_LOG_EVENT_MAXBURST 6 #define SCTP_LOG_EVENT_RWND 7 #define SCTP_LOG_EVENT_MBCNT 8 #define SCTP_LOG_EVENT_SACK 9 #define SCTP_LOG_LOCK_EVENT 10 #define SCTP_LOG_EVENT_RTT 11 #define SCTP_LOG_EVENT_SB 12 #define SCTP_LOG_EVENT_NAGLE 13 #define SCTP_LOG_EVENT_WAKE 14 #define SCTP_LOG_MISC_EVENT 15 #define SCTP_LOG_EVENT_CLOSE 16 #define SCTP_LOG_EVENT_MBUF 17 #define SCTP_LOG_CHUNK_PROC 18 #define SCTP_LOG_ERROR_RET 19 #define SCTP_LOG_MAX_EVENT 20 #define SCTP_LOCK_UNKNOWN 2 /* number of associations by default for zone allocation */ #define SCTP_MAX_NUM_OF_ASOC 40000 /* how many addresses per assoc remote and local */ #define SCTP_SCALE_FOR_ADDR 2 /* default MULTIPLE_ASCONF mode enable(1)/disable(0) value (sysctl) */ #define SCTP_DEFAULT_MULTIPLE_ASCONFS 0 /* * Theshold for rwnd updates, we have to read (sb_hiwat >> * SCTP_RWND_HIWAT_SHIFT) before we will look to see if we need to send a * window update sack. When we look, we compare the last rwnd we sent vs the * current rwnd. It too must be greater than this value. Using 3 divdes the * hiwat by 8, so for 200k rwnd we need to read 24k. For a 64k rwnd we need * to read 8k. This seems about right.. I hope :-D.. we do set a * min of a MTU on it so if the rwnd is real small we will insist * on a full MTU of 1500 bytes. */ #define SCTP_RWND_HIWAT_SHIFT 3 /* How much of the rwnd must the * message be taking up to start partial delivery. * We calculate this by shifing the hi_water (recv_win) * left the following .. set to 1, when a message holds * 1/2 the rwnd. If we set it to 2 when a message holds * 1/4 the rwnd...etc.. */ #define SCTP_PARTIAL_DELIVERY_SHIFT 1 /* * default HMAC for cookies, etc... use one of the AUTH HMAC id's * SCTP_HMAC is the HMAC_ID to use * SCTP_SIGNATURE_SIZE is the digest length */ #define SCTP_HMAC SCTP_AUTH_HMAC_ID_SHA1 #define SCTP_SIGNATURE_SIZE SCTP_AUTH_DIGEST_LEN_SHA1 #define SCTP_SIGNATURE_ALOC_SIZE SCTP_SIGNATURE_SIZE /* * the SCTP protocol signature this includes the version number encoded in * the last 4 bits of the signature. */ #define PROTO_SIGNATURE_A 0x30000000 #define SCTP_VERSION_NUMBER 0x3 #define MAX_TSN 0xffffffff /* how many executions every N tick's */ #define SCTP_ITERATOR_MAX_AT_ONCE 20 /* number of clock ticks between iterator executions */ #define SCTP_ITERATOR_TICKS 1 /* * option: If you comment out the following you will receive the old behavior * of obeying cwnd for the fast retransmit algorithm. With this defined a FR * happens right away with-out waiting for the flightsize to drop below the * cwnd value (which is reduced by the FR to 1/2 the inflight packets). */ #define SCTP_IGNORE_CWND_ON_FR 1 /* * Adds implementors guide behavior to only use newest highest update in SACK * gap ack's to figure out if you need to stroke a chunk for FR. */ #define SCTP_NO_FR_UNLESS_SEGMENT_SMALLER 1 /* default max I can burst out after a fast retransmit, 0 disables it */ #define SCTP_DEF_MAX_BURST 4 #define SCTP_DEF_HBMAX_BURST 4 #define SCTP_DEF_FRMAX_BURST 4 /* RTO calculation flag to say if it * is safe to determine local lan or not. */ #define SCTP_RTT_FROM_NON_DATA 0 #define SCTP_RTT_FROM_DATA 1 /* IP hdr (20/40) + 12+2+2 (enet) + sctp common 12 */ #define SCTP_FIRST_MBUF_RESV 68 /* Packet transmit states in the sent field */ #define SCTP_DATAGRAM_UNSENT 0 #define SCTP_DATAGRAM_SENT 1 #define SCTP_DATAGRAM_RESEND1 2 /* not used (in code, but may * hit this value) */ #define SCTP_DATAGRAM_RESEND2 3 /* not used (in code, but may * hit this value) */ #define SCTP_DATAGRAM_RESEND 4 #define SCTP_DATAGRAM_ACKED 10010 #define SCTP_DATAGRAM_MARKED 20010 #define SCTP_FORWARD_TSN_SKIP 30010 #define SCTP_DATAGRAM_NR_ACKED 40010 /* chunk output send from locations */ #define SCTP_OUTPUT_FROM_USR_SEND 0 #define SCTP_OUTPUT_FROM_T3 1 #define SCTP_OUTPUT_FROM_INPUT_ERROR 2 #define SCTP_OUTPUT_FROM_CONTROL_PROC 3 #define SCTP_OUTPUT_FROM_SACK_TMR 4 #define SCTP_OUTPUT_FROM_SHUT_TMR 5 #define SCTP_OUTPUT_FROM_HB_TMR 6 #define SCTP_OUTPUT_FROM_SHUT_ACK_TMR 7 #define SCTP_OUTPUT_FROM_ASCONF_TMR 8 #define SCTP_OUTPUT_FROM_STRRST_TMR 9 #define SCTP_OUTPUT_FROM_AUTOCLOSE_TMR 10 #define SCTP_OUTPUT_FROM_EARLY_FR_TMR 11 #define SCTP_OUTPUT_FROM_STRRST_REQ 12 #define SCTP_OUTPUT_FROM_USR_RCVD 13 #define SCTP_OUTPUT_FROM_COOKIE_ACK 14 #define SCTP_OUTPUT_FROM_DRAIN 15 #define SCTP_OUTPUT_FROM_CLOSING 16 #define SCTP_OUTPUT_FROM_SOCKOPT 17 /* SCTP chunk types are moved sctp.h for application (NAT, FW) use */ /* align to 32-bit sizes */ #define SCTP_SIZE32(x) ((((x) + 3) >> 2) << 2) #define IS_SCTP_CONTROL(a) ((a)->chunk_type != SCTP_DATA) #define IS_SCTP_DATA(a) ((a)->chunk_type == SCTP_DATA) /* SCTP parameter types */ /*************0x0000 series*************/ #define SCTP_HEARTBEAT_INFO 0x0001 #define SCTP_IPV4_ADDRESS 0x0005 #define SCTP_IPV6_ADDRESS 0x0006 #define SCTP_STATE_COOKIE 0x0007 #define SCTP_UNRECOG_PARAM 0x0008 #define SCTP_COOKIE_PRESERVE 0x0009 #define SCTP_HOSTNAME_ADDRESS 0x000b #define SCTP_SUPPORTED_ADDRTYPE 0x000c /* draft-ietf-stewart-tsvwg-strreset-xxx */ #define SCTP_STR_RESET_OUT_REQUEST 0x000d #define SCTP_STR_RESET_IN_REQUEST 0x000e #define SCTP_STR_RESET_TSN_REQUEST 0x000f #define SCTP_STR_RESET_RESPONSE 0x0010 #define SCTP_STR_RESET_ADD_OUT_STREAMS 0x0011 #define SCTP_STR_RESET_ADD_IN_STREAMS 0x0012 #define SCTP_MAX_RESET_PARAMS 2 #define SCTP_STREAM_RESET_TSN_DELTA 0x1000 /*************0x4000 series*************/ /*************0x8000 series*************/ #define SCTP_ECN_CAPABLE 0x8000 /* draft-ietf-tsvwg-auth-xxx */ #define SCTP_RANDOM 0x8002 #define SCTP_CHUNK_LIST 0x8003 #define SCTP_HMAC_LIST 0x8004 /* * draft-ietf-tsvwg-addip-sctp-xx param=0x8008 len=0xNNNN Byte | Byte | Byte * | Byte Byte | Byte ... * * Where each byte is a chunk type extension supported. For example, to support * all chunks one would have (in hex): * * 80 01 00 09 C0 C1 80 81 82 00 00 00 * * Has the parameter. C0 = PR-SCTP (RFC3758) C1, 80 = ASCONF (addip draft) 81 * = Packet Drop 82 = Stream Reset 83 = Authentication */ #define SCTP_SUPPORTED_CHUNK_EXT 0x8008 /*************0xC000 series*************/ #define SCTP_PRSCTP_SUPPORTED 0xc000 /* draft-ietf-tsvwg-addip-sctp */ #define SCTP_ADD_IP_ADDRESS 0xc001 #define SCTP_DEL_IP_ADDRESS 0xc002 #define SCTP_ERROR_CAUSE_IND 0xc003 #define SCTP_SET_PRIM_ADDR 0xc004 #define SCTP_SUCCESS_REPORT 0xc005 #define SCTP_ULP_ADAPTATION 0xc006 /* behave-nat-draft */ #define SCTP_HAS_NAT_SUPPORT 0xc007 #define SCTP_NAT_VTAGS 0xc008 /* bits for TOS field */ #define SCTP_ECT0_BIT 0x02 #define SCTP_ECT1_BIT 0x01 #define SCTP_CE_BITS 0x03 /* below turns off above */ #define SCTP_FLEXIBLE_ADDRESS 0x20 #define SCTP_NO_HEARTBEAT 0x40 /* mask to get sticky */ #define SCTP_STICKY_OPTIONS_MASK 0x0c /* * SCTP states for internal state machine XXX (should match "user" values) */ #define SCTP_STATE_EMPTY 0x0000 #define SCTP_STATE_INUSE 0x0001 #define SCTP_STATE_COOKIE_WAIT 0x0002 #define SCTP_STATE_COOKIE_ECHOED 0x0004 #define SCTP_STATE_OPEN 0x0008 #define SCTP_STATE_SHUTDOWN_SENT 0x0010 #define SCTP_STATE_SHUTDOWN_RECEIVED 0x0020 #define SCTP_STATE_SHUTDOWN_ACK_SENT 0x0040 #define SCTP_STATE_SHUTDOWN_PENDING 0x0080 #define SCTP_STATE_CLOSED_SOCKET 0x0100 #define SCTP_STATE_ABOUT_TO_BE_FREED 0x0200 #define SCTP_STATE_PARTIAL_MSG_LEFT 0x0400 #define SCTP_STATE_WAS_ABORTED 0x0800 #define SCTP_STATE_IN_ACCEPT_QUEUE 0x1000 #define SCTP_STATE_MASK 0x007f #define SCTP_GET_STATE(asoc) ((asoc)->state & SCTP_STATE_MASK) #define SCTP_SET_STATE(asoc, newstate) ((asoc)->state = ((asoc)->state & ~SCTP_STATE_MASK) | newstate) #define SCTP_CLEAR_SUBSTATE(asoc, substate) ((asoc)->state &= ~substate) #define SCTP_ADD_SUBSTATE(asoc, substate) ((asoc)->state |= substate) /* SCTP reachability state for each address */ #define SCTP_ADDR_REACHABLE 0x001 #define SCTP_ADDR_NO_PMTUD 0x002 #define SCTP_ADDR_NOHB 0x004 #define SCTP_ADDR_BEING_DELETED 0x008 #define SCTP_ADDR_NOT_IN_ASSOC 0x010 #define SCTP_ADDR_OUT_OF_SCOPE 0x080 #define SCTP_ADDR_UNCONFIRMED 0x200 #define SCTP_ADDR_REQ_PRIMARY 0x400 /* JRS 5/13/07 - Added potentially failed state for CMT PF */ #define SCTP_ADDR_PF 0x800 /* bound address types (e.g. valid address types to allow) */ #define SCTP_BOUND_V6 0x01 #define SCTP_BOUND_V4 0x02 /* * what is the default number of mbufs in a chain I allow before switching to * a cluster */ #define SCTP_DEFAULT_MBUFS_IN_CHAIN 5 /* How long a cookie lives in milli-seconds */ #define SCTP_DEFAULT_COOKIE_LIFE 60000 /* Maximum the mapping array will grow to (TSN mapping array) */ #define SCTP_MAPPING_ARRAY 512 /* size of the inital malloc on the mapping array */ #define SCTP_INITIAL_MAPPING_ARRAY 16 /* how much we grow the mapping array each call */ #define SCTP_MAPPING_ARRAY_INCR 32 /* * Here we define the timer types used by the implementation as arguments in * the set/get timer type calls. */ #define SCTP_TIMER_INIT 0 #define SCTP_TIMER_RECV 1 #define SCTP_TIMER_SEND 2 #define SCTP_TIMER_HEARTBEAT 3 #define SCTP_TIMER_PMTU 4 #define SCTP_TIMER_MAXSHUTDOWN 5 #define SCTP_TIMER_SIGNATURE 6 /* * number of timer types in the base SCTP structure used in the set/get and * has the base default. */ #define SCTP_NUM_TMRS 7 /* timer types */ #define SCTP_TIMER_TYPE_NONE 0 #define SCTP_TIMER_TYPE_SEND 1 #define SCTP_TIMER_TYPE_INIT 2 #define SCTP_TIMER_TYPE_RECV 3 #define SCTP_TIMER_TYPE_SHUTDOWN 4 #define SCTP_TIMER_TYPE_HEARTBEAT 5 #define SCTP_TIMER_TYPE_COOKIE 6 #define SCTP_TIMER_TYPE_NEWCOOKIE 7 #define SCTP_TIMER_TYPE_PATHMTURAISE 8 #define SCTP_TIMER_TYPE_SHUTDOWNACK 9 #define SCTP_TIMER_TYPE_ASCONF 10 #define SCTP_TIMER_TYPE_SHUTDOWNGUARD 11 #define SCTP_TIMER_TYPE_AUTOCLOSE 12 #define SCTP_TIMER_TYPE_EVENTWAKE 13 #define SCTP_TIMER_TYPE_STRRESET 14 #define SCTP_TIMER_TYPE_INPKILL 15 #define SCTP_TIMER_TYPE_ASOCKILL 16 #define SCTP_TIMER_TYPE_ADDR_WQ 17 #define SCTP_TIMER_TYPE_ZERO_COPY 18 #define SCTP_TIMER_TYPE_ZCOPY_SENDQ 19 #define SCTP_TIMER_TYPE_PRIM_DELETED 20 /* add new timers here - and increment LAST */ #define SCTP_TIMER_TYPE_LAST 21 #define SCTP_IS_TIMER_TYPE_VALID(t) (((t) > SCTP_TIMER_TYPE_NONE) && \ ((t) < SCTP_TIMER_TYPE_LAST)) /* max number of TSN's dup'd that I will hold */ #define SCTP_MAX_DUP_TSNS 20 /* * Here we define the types used when setting the retry amounts. */ /* How many drop re-attempts we make on INIT/COOKIE-ECHO */ #define SCTP_RETRY_DROPPED_THRESH 4 /* * Maxmium number of chunks a single association can have on it. Note that * this is a squishy number since the count can run over this if the user * sends a large message down .. the fragmented chunks don't count until * AFTER the message is on queue.. it would be the next send that blocks * things. This number will get tuned up at boot in the sctp_init and use the * number of clusters as a base. This way high bandwidth environments will * not get impacted by the lower bandwidth sending a bunch of 1 byte chunks */ #define SCTP_ASOC_MAX_CHUNKS_ON_QUEUE 512 /* The conversion from time to ticks and vice versa is done by rounding * upwards. This way we can test in the code the time to be positive and * know that this corresponds to a positive number of ticks. */ #define MSEC_TO_TICKS(x) ((hz == 1000) ? x : ((((x) * hz) + 999) / 1000)) #define TICKS_TO_MSEC(x) ((hz == 1000) ? x : ((((x) * 1000) + (hz - 1)) / hz)) #define SEC_TO_TICKS(x) ((x) * hz) #define TICKS_TO_SEC(x) (((x) + (hz - 1)) / hz) /* * Basically the minimum amount of time before I do a early FR. Making this * value to low will cause duplicate retransmissions. */ #define SCTP_MINFR_MSEC_TIMER 250 /* The floor this value is allowed to fall to when starting a timer. */ #define SCTP_MINFR_MSEC_FLOOR 20 /* init timer def = 1 sec */ #define SCTP_INIT_SEC 1 /* send timer def = 1 seconds */ #define SCTP_SEND_SEC 1 /* recv timer def = 200ms */ #define SCTP_RECV_MSEC 200 /* 30 seconds + RTO (in ms) */ #define SCTP_HB_DEFAULT_MSEC 30000 /* Max time I will wait for Shutdown to complete */ #define SCTP_DEF_MAX_SHUTDOWN_SEC 180 /* * This is how long a secret lives, NOT how long a cookie lives how many * ticks the current secret will live. */ #define SCTP_DEFAULT_SECRET_LIFE_SEC 3600 #define SCTP_RTO_UPPER_BOUND (60000) /* 60 sec in ms */ #define SCTP_RTO_LOWER_BOUND (1000) /* 1 sec is ms */ #define SCTP_RTO_INITIAL (3000) /* 3 sec in ms */ #define SCTP_INP_KILL_TIMEOUT 20/* number of ms to retry kill of inpcb */ #define SCTP_ASOC_KILL_TIMEOUT 10 /* number of ms to retry kill of inpcb */ #define SCTP_DEF_MAX_INIT 8 #define SCTP_DEF_MAX_SEND 10 #define SCTP_DEF_MAX_PATH_RTX 5 #define SCTP_DEF_PATH_PF_THRESHOLD SCTP_DEF_MAX_PATH_RTX #define SCTP_DEF_PMTU_RAISE_SEC 600 /* 10 min between raise attempts */ /* How many streams I request initally by default */ #define SCTP_OSTREAM_INITIAL 10 #define SCTP_ISTREAM_INITIAL 2048 /* * How many smallest_mtu's need to increase before a window update sack is * sent (should be a power of 2). */ /* Send window update (incr * this > hiwat). Should be a power of 2 */ #define SCTP_MINIMAL_RWND (4096) /* minimal rwnd */ #define SCTP_ADDRMAX 16 /* SCTP DEBUG Switch parameters */ #define SCTP_DEBUG_TIMER1 0x00000001 #define SCTP_DEBUG_TIMER2 0x00000002 /* unused */ #define SCTP_DEBUG_TIMER3 0x00000004 /* unused */ #define SCTP_DEBUG_TIMER4 0x00000008 #define SCTP_DEBUG_OUTPUT1 0x00000010 #define SCTP_DEBUG_OUTPUT2 0x00000020 #define SCTP_DEBUG_OUTPUT3 0x00000040 #define SCTP_DEBUG_OUTPUT4 0x00000080 #define SCTP_DEBUG_UTIL1 0x00000100 #define SCTP_DEBUG_UTIL2 0x00000200 /* unused */ #define SCTP_DEBUG_AUTH1 0x00000400 #define SCTP_DEBUG_AUTH2 0x00000800 /* unused */ #define SCTP_DEBUG_INPUT1 0x00001000 #define SCTP_DEBUG_INPUT2 0x00002000 #define SCTP_DEBUG_INPUT3 0x00004000 #define SCTP_DEBUG_INPUT4 0x00008000 /* unused */ #define SCTP_DEBUG_ASCONF1 0x00010000 #define SCTP_DEBUG_ASCONF2 0x00020000 #define SCTP_DEBUG_OUTPUT5 0x00040000 /* unused */ #define SCTP_DEBUG_XXX 0x00080000 /* unused */ #define SCTP_DEBUG_PCB1 0x00100000 #define SCTP_DEBUG_PCB2 0x00200000 /* unused */ #define SCTP_DEBUG_PCB3 0x00400000 #define SCTP_DEBUG_PCB4 0x00800000 #define SCTP_DEBUG_INDATA1 0x01000000 #define SCTP_DEBUG_INDATA2 0x02000000 /* unused */ #define SCTP_DEBUG_INDATA3 0x04000000 /* unused */ #define SCTP_DEBUG_CRCOFFLOAD 0x08000000 /* unused */ #define SCTP_DEBUG_USRREQ1 0x10000000 /* unused */ #define SCTP_DEBUG_USRREQ2 0x20000000 /* unused */ #define SCTP_DEBUG_PEEL1 0x40000000 #define SCTP_DEBUG_XXXXX 0x80000000 /* unused */ #define SCTP_DEBUG_ALL 0x7ff3ffff #define SCTP_DEBUG_NOISY 0x00040000 /* What sender needs to see to avoid SWS or we consider peers rwnd 0 */ #define SCTP_SWS_SENDER_DEF 1420 /* * SWS is scaled to the sb_hiwat of the socket. A value of 2 is hiwat/4, 1 * would be hiwat/2 etc. */ /* What receiver needs to see in sockbuf or we tell peer its 1 */ #define SCTP_SWS_RECEIVER_DEF 3000 #define SCTP_INITIAL_CWND 4380 #define SCTP_DEFAULT_MTU 1500 /* emergency default MTU */ /* amount peer is obligated to have in rwnd or I will abort */ #define SCTP_MIN_RWND 1500 #define SCTP_DEFAULT_MAXSEGMENT 65535 #define SCTP_CHUNK_BUFFER_SIZE 512 #define SCTP_PARAM_BUFFER_SIZE 512 /* small chunk store for looking at chunk_list in auth */ #define SCTP_SMALL_CHUNK_STORE 260 #define SCTP_HOW_MANY_SECRETS 2 /* how many secrets I keep */ #define SCTP_NUMBER_OF_SECRETS 8 /* or 8 * 4 = 32 octets */ #define SCTP_SECRET_SIZE 32 /* number of octets in a 256 bits */ /* * SCTP upper layer notifications */ #define SCTP_NOTIFY_ASSOC_UP 1 #define SCTP_NOTIFY_ASSOC_DOWN 2 #define SCTP_NOTIFY_INTERFACE_DOWN 3 #define SCTP_NOTIFY_INTERFACE_UP 4 #define SCTP_NOTIFY_SENT_DG_FAIL 5 #define SCTP_NOTIFY_UNSENT_DG_FAIL 6 #define SCTP_NOTIFY_SPECIAL_SP_FAIL 7 #define SCTP_NOTIFY_ASSOC_LOC_ABORTED 8 #define SCTP_NOTIFY_ASSOC_REM_ABORTED 9 #define SCTP_NOTIFY_ASSOC_RESTART 10 #define SCTP_NOTIFY_PEER_SHUTDOWN 11 #define SCTP_NOTIFY_ASCONF_ADD_IP 12 #define SCTP_NOTIFY_ASCONF_DELETE_IP 13 #define SCTP_NOTIFY_ASCONF_SET_PRIMARY 14 #define SCTP_NOTIFY_PARTIAL_DELVIERY_INDICATION 15 #define SCTP_NOTIFY_INTERFACE_CONFIRMED 16 #define SCTP_NOTIFY_STR_RESET_RECV 17 #define SCTP_NOTIFY_STR_RESET_SEND 18 #define SCTP_NOTIFY_STR_RESET_FAILED_OUT 19 #define SCTP_NOTIFY_STR_RESET_FAILED_IN 20 #define SCTP_NOTIFY_STR_RESET_DENIED_OUT 21 #define SCTP_NOTIFY_STR_RESET_DENIED_IN 22 #define SCTP_NOTIFY_AUTH_NEW_KEY 23 #define SCTP_NOTIFY_AUTH_FREE_KEY 24 #define SCTP_NOTIFY_NO_PEER_AUTH 25 #define SCTP_NOTIFY_SENDER_DRY 26 #define SCTP_NOTIFY_REMOTE_ERROR 27 /* This is the value for messages that are NOT completely * copied down where we will start to split the message. * So, with our default, we split only if the piece we * want to take will fill up a full MTU (assuming * a 1500 byte MTU). */ #define SCTP_DEFAULT_SPLIT_POINT_MIN 2904 /* Maximum length of diagnostic information in error causes */ #define SCTP_DIAG_INFO_LEN 64 /* ABORT CODES and other tell-tale location * codes are generated by adding the below * to the instance id. */ /* File defines */ #define SCTP_FROM_SCTP_INPUT 0x10000000 #define SCTP_FROM_SCTP_PCB 0x20000000 #define SCTP_FROM_SCTP_INDATA 0x30000000 #define SCTP_FROM_SCTP_TIMER 0x40000000 #define SCTP_FROM_SCTP_USRREQ 0x50000000 #define SCTP_FROM_SCTPUTIL 0x60000000 #define SCTP_FROM_SCTP6_USRREQ 0x70000000 #define SCTP_FROM_SCTP_ASCONF 0x80000000 #define SCTP_FROM_SCTP_OUTPUT 0x90000000 #define SCTP_FROM_SCTP_PEELOFF 0xa0000000 #define SCTP_FROM_SCTP_PANDA 0xb0000000 #define SCTP_FROM_SCTP_SYSCTL 0xc0000000 #define SCTP_FROM_SCTP_CC_FUNCTIONS 0xd0000000 /* Location ID's */ #define SCTP_LOC_1 0x00000001 #define SCTP_LOC_2 0x00000002 #define SCTP_LOC_3 0x00000003 #define SCTP_LOC_4 0x00000004 #define SCTP_LOC_5 0x00000005 #define SCTP_LOC_6 0x00000006 #define SCTP_LOC_7 0x00000007 #define SCTP_LOC_8 0x00000008 #define SCTP_LOC_9 0x00000009 #define SCTP_LOC_10 0x0000000a #define SCTP_LOC_11 0x0000000b #define SCTP_LOC_12 0x0000000c #define SCTP_LOC_13 0x0000000d #define SCTP_LOC_14 0x0000000e #define SCTP_LOC_15 0x0000000f #define SCTP_LOC_16 0x00000010 #define SCTP_LOC_17 0x00000011 #define SCTP_LOC_18 0x00000012 #define SCTP_LOC_19 0x00000013 #define SCTP_LOC_20 0x00000014 #define SCTP_LOC_21 0x00000015 #define SCTP_LOC_22 0x00000016 #define SCTP_LOC_23 0x00000017 #define SCTP_LOC_24 0x00000018 #define SCTP_LOC_25 0x00000019 #define SCTP_LOC_26 0x0000001a #define SCTP_LOC_27 0x0000001b #define SCTP_LOC_28 0x0000001c #define SCTP_LOC_29 0x0000001d #define SCTP_LOC_30 0x0000001e #define SCTP_LOC_31 0x0000001f #define SCTP_LOC_32 0x00000020 #define SCTP_LOC_33 0x00000021 #define SCTP_LOC_34 0x00000022 #define SCTP_LOC_35 0x00000023 /* Free assoc codes */ #define SCTP_NORMAL_PROC 0 #define SCTP_PCBFREE_NOFORCE 1 #define SCTP_PCBFREE_FORCE 2 /* From codes for adding addresses */ #define SCTP_ADDR_IS_CONFIRMED 8 #define SCTP_ADDR_DYNAMIC_ADDED 6 #define SCTP_IN_COOKIE_PROC 100 #define SCTP_ALLOC_ASOC 1 #define SCTP_LOAD_ADDR_2 2 #define SCTP_LOAD_ADDR_3 3 #define SCTP_LOAD_ADDR_4 4 #define SCTP_LOAD_ADDR_5 5 #define SCTP_DONOT_SETSCOPE 0 #define SCTP_DO_SETSCOPE 1 /* This value determines the default for when * we try to add more on the send queue., if * there is room. This prevents us from cycling * into the copy_resume routine to often if * we have not got enough space to add a decent * enough size message. Note that if we have enough * space to complete the message copy we will always * add to the message, no matter what the size. Its * only when we reach the point that we have some left * to add, there is only room for part of it that we * will use this threshold. Its also a sysctl. */ #define SCTP_DEFAULT_ADD_MORE 1452 #ifndef SCTP_PCBHASHSIZE /* default number of association hash buckets in each endpoint */ #define SCTP_PCBHASHSIZE 256 #endif #ifndef SCTP_TCBHASHSIZE #define SCTP_TCBHASHSIZE 1024 #endif #ifndef SCTP_CHUNKQUEUE_SCALE #define SCTP_CHUNKQUEUE_SCALE 10 #endif /* clock variance is 1 ms */ #define SCTP_CLOCK_GRANULARITY 1 #define IP_HDR_SIZE 40 /* we use the size of a IP6 header here this * detracts a small amount for ipv4 but it * simplifies the ipv6 addition */ /* Argument magic number for sctp_inpcb_free() */ /* third argument */ #define SCTP_CALLED_DIRECTLY_NOCMPSET 0 #define SCTP_CALLED_AFTER_CMPSET_OFCLOSE 1 #define SCTP_CALLED_FROM_INPKILL_TIMER 2 /* second argument */ #define SCTP_FREE_SHOULD_USE_ABORT 1 #define SCTP_FREE_SHOULD_USE_GRACEFUL_CLOSE 0 #ifndef IPPROTO_SCTP #define IPPROTO_SCTP 132 /* the Official IANA number :-) */ #endif /* !IPPROTO_SCTP */ #define SCTP_MAX_DATA_BUNDLING 256 /* modular comparison */ /* See RFC 1982 for details. */ #define SCTP_SSN_GT(a, b) (((a < b) && ((uint16_t)(b - a) > (1U<<15))) || \ ((a > b) && ((uint16_t)(a - b) < (1U<<15)))) #define SCTP_SSN_GE(a, b) (SCTP_SSN_GT(a, b) || (a == b)) #define SCTP_TSN_GT(a, b) (((a < b) && ((uint32_t)(b - a) > (1U<<31))) || \ ((a > b) && ((uint32_t)(a - b) < (1U<<31)))) #define SCTP_TSN_GE(a, b) (SCTP_TSN_GT(a, b) || (a == b)) /* Mapping array manipulation routines */ #define SCTP_IS_TSN_PRESENT(arry, gap) ((arry[(gap >> 3)] >> (gap & 0x07)) & 0x01) #define SCTP_SET_TSN_PRESENT(arry, gap) (arry[(gap >> 3)] |= (0x01 << ((gap & 0x07)))) #define SCTP_UNSET_TSN_PRESENT(arry, gap) (arry[(gap >> 3)] &= ((~(0x01 << ((gap & 0x07)))) & 0xff)) #define SCTP_CALC_TSN_TO_GAP(gap, tsn, mapping_tsn) do { \ if (tsn >= mapping_tsn) { \ gap = tsn - mapping_tsn; \ } else { \ gap = (MAX_TSN - mapping_tsn) + tsn + 1; \ } \ } while (0) #define SCTP_RETRAN_DONE -1 #define SCTP_RETRAN_EXIT -2 /* * This value defines the number of vtag block time wait entry's per list * element. Each entry will take 2 4 byte ints (and of course the overhead * of the next pointer as well). Using 15 as an example will yield * ((8 * * 15) + 8) or 128 bytes of overhead for each timewait block that gets * initialized. Increasing it to 31 would yeild 256 bytes per block. */ #define SCTP_NUMBER_IN_VTAG_BLOCK 15 /* * If we use the STACK option, we have an array of this size head pointers. * This array is mod'd the with the size to find which bucket and then all * entries must be searched to see if the tag is in timed wait. If so we * reject it. */ #define SCTP_STACK_VTAG_HASH_SIZE 32 /* * Number of seconds of time wait for a vtag. */ #define SCTP_TIME_WAIT 60 /* How many micro seconds is the cutoff from * local lan type rtt's */ /* * We allow 900us for the rtt. */ #define SCTP_LOCAL_LAN_RTT 900 #define SCTP_LAN_UNKNOWN 0 #define SCTP_LAN_LOCAL 1 #define SCTP_LAN_INTERNET 2 #define SCTP_SEND_BUFFER_SPLITTING 0x00000001 #define SCTP_RECV_BUFFER_SPLITTING 0x00000002 /* The system retains a cache of free chunks such to * cut down on calls the memory allocation system. There * is a per association limit of free items and a overall * system limit. If either one gets hit then the resource * stops being cached. */ #define SCTP_DEF_ASOC_RESC_LIMIT 10 #define SCTP_DEF_SYSTEM_RESC_LIMIT 1000 /*- * defines for socket lock states. * Used by __APPLE__ and SCTP_SO_LOCK_TESTING */ #define SCTP_SO_LOCKED 1 #define SCTP_SO_NOT_LOCKED 0 #define SCTP_HOLDS_LOCK 1 #define SCTP_NOT_LOCKED 0 /*- * For address locks, do we hold the lock? */ #define SCTP_ADDR_LOCKED 1 #define SCTP_ADDR_NOT_LOCKED 0 #define IN4_ISPRIVATE_ADDRESS(a) \ ((((uint8_t *)&(a)->s_addr)[0] == 10) || \ ((((uint8_t *)&(a)->s_addr)[0] == 172) && \ (((uint8_t *)&(a)->s_addr)[1] >= 16) && \ (((uint8_t *)&(a)->s_addr)[1] <= 32)) || \ ((((uint8_t *)&(a)->s_addr)[0] == 192) && \ (((uint8_t *)&(a)->s_addr)[1] == 168))) #define IN4_ISLOOPBACK_ADDRESS(a) \ ((((uint8_t *)&(a)->s_addr)[0] == 127) && \ (((uint8_t *)&(a)->s_addr)[1] == 0) && \ (((uint8_t *)&(a)->s_addr)[2] == 0) && \ (((uint8_t *)&(a)->s_addr)[3] == 1)) #define IN4_ISLINKLOCAL_ADDRESS(a) \ ((((uint8_t *)&(a)->s_addr)[0] == 169) && \ (((uint8_t *)&(a)->s_addr)[1] == 254)) #if defined(_KERNEL) #define SCTP_GETTIME_TIMEVAL(x) (getmicrouptime(x)) #define SCTP_GETPTIME_TIMEVAL(x) (microuptime(x)) #endif #if defined(_KERNEL) || defined(__Userspace__) #define sctp_sowwakeup(inp, so) \ do { \ if (inp->sctp_flags & SCTP_PCB_FLAGS_DONT_WAKE) { \ inp->sctp_flags |= SCTP_PCB_FLAGS_WAKEOUTPUT; \ } else { \ sowwakeup(so); \ } \ } while (0) #define sctp_sowwakeup_locked(inp, so) \ do { \ if (inp->sctp_flags & SCTP_PCB_FLAGS_DONT_WAKE) { \ SOCKBUF_UNLOCK(&((so)->so_snd)); \ inp->sctp_flags |= SCTP_PCB_FLAGS_WAKEOUTPUT; \ } else { \ sowwakeup_locked(so); \ } \ } while (0) #define sctp_sorwakeup(inp, so) \ do { \ if (inp->sctp_flags & SCTP_PCB_FLAGS_DONT_WAKE) { \ inp->sctp_flags |= SCTP_PCB_FLAGS_WAKEINPUT; \ } else { \ sorwakeup(so); \ } \ } while (0) #define sctp_sorwakeup_locked(inp, so) \ do { \ if (inp->sctp_flags & SCTP_PCB_FLAGS_DONT_WAKE) { \ inp->sctp_flags |= SCTP_PCB_FLAGS_WAKEINPUT; \ SOCKBUF_UNLOCK(&((so)->so_rcv)); \ } else { \ sorwakeup_locked(so); \ } \ } while (0) #endif /* _KERNEL || __Userspace__ */ #endif
jrobhoward/SCADAbase
sys/netinet/sctp_constants.h
C
bsd-3-clause
35,554
{% load applicationcontent_tags i18n %} {% include "base/widget/_base_begin.html" %} <div id="{{ widget.fe_identifier }}" class="{{ widget.render_base_classes }}" {% if widget.enter_effect_style != 'disabled' %}data-aos="{{ widget.enter_effect_style }}"{% endif %}{% if widget.enter_effect_duration %}data-aos-duration="{{ widget.enter_effect_duration }}"{% endif %} {% if widget.enter_effect_delay %}data-aos-delay="{{ widget.enter_effect_delay }}"{% endif %} {% if widget.enter_effect_offset %}data-aos-offset="{{ widget.enter_effect_offset }}"{% endif %} data-aos-once="{% if widget.enter_effect_iteration == 0 %}false{% elif widget.enter_effect_iteration == 1 %}true{% endif %}"> <div class="jumbotron {{ widget.render_content_classes }}"> {% if request.frontend_editing %} <div class="widget-tools"> {% include "base/widget/_edit.html" %} </div> {% endif %} {% block title %} {% if widget.label %} <a id="{{ widget.label|slugify }}"></a> <h2 class="widget-title"><span>{{ widget.label }}</span></h2> {% endif %} {% endblock %} {% block content %}{% endblock %} </div> </div> {% include "base/widget/_base_end.html" %}
django-leonardo/django-leonardo
leonardo/module/web/templates/base/widget/jumbotron.html
HTML
bsd-3-clause
1,180
<?php /*========================================================================= MIDAS Server Copyright (c) Kitware SAS. 20 rue de la Villette. All rights reserved. 69328 Lyon, FRANCE. See Copyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ /** Assetstore Model Base*/ abstract class AssetstoreModelBase extends AppModel { /** Constructor*/ public function __construct() { parent::__construct(); $this->_name = 'assetstore'; $this->_key = 'assetstore_id'; $this->_mainData = array( 'assetstore_id' => array('type' => MIDAS_DATA), 'name' => array('type' => MIDAS_DATA), 'itemrevision_id' => array('type' => MIDAS_DATA), 'path' => array('type' => MIDAS_DATA), 'type' => array('type' => MIDAS_DATA), 'bitstreams' => array('type' => MIDAS_ONE_TO_MANY, 'model' => 'Bitstream', 'parent_column' => 'assetstore_id', 'child_column' => 'assetstore_id'), ); $this->initialize(); // required } // end __construct() /** Abstract functions */ abstract function getAll(); /** save an assetsore*/ public function save($dao) { parent::save($dao); } /** delete an assetstore (and all the items in it)*/ public function delete($dao) { if(!$dao instanceof AssetstoreDao) { throw new Zend_Exception("Error param."); } $bitreams = $dao->getBitstreams(); $items = array(); foreach($bitreams as $key => $bitstream) { $revision = $bitstream->getItemrevision(); if(empty($revision)) { continue; } $item = $revision->getItem(); if(empty($item)) { continue; } $items[$item->getKey()] = $item; } $modelLoader = new MIDAS_ModelLoader(); $item_model = $modelLoader->loadModel('Item'); foreach($items as $item) { $item_model->delete($item); } parent::delete($dao); }// delete } // end class AssetstoreModelBase
mgrauer/midas3score
core/models/base/AssetstoreModelBase.php
PHP
bsd-3-clause
2,220
package eu.monnetproject.util; import java.util.*; /** * Utility function to syntactically sugar properties for OSGi. * This allows you to create a property map as follows * <code>Props.prop("key1","value1")</code><br/> * <code> .prop("key2","value2")</code> */ public final class Props { public static PropsMap prop(String key, Object value) { PropsMap pm = new PropsMap(); pm.put(key,value); return pm; } public static class PropsMap extends Hashtable<String,Object> { public PropsMap prop(String key, Object value) { put(key,value); return this; } } }
monnetproject/coal
nlp.sim/src/main/java/eu/monnetproject/util/Props.java
Java
bsd-3-clause
590
#!/usr/bin/env python import sys from os.path import * import os from pyflann import * from copy import copy from numpy import * from numpy.random import * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level="warning") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """ Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """ seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main()
piskvorky/flann
test/test_nn_autotune.py
Python
bsd-3-clause
2,411
# -*- coding: utf-8 -*- from collections import OrderedDict import locale from optparse import make_option from verify.management.commands import VerifyBaseCommand from verify.models import * from verify.politici_models import * from django.db.models import Q, Count __author__ = 'guglielmo' class Command(VerifyBaseCommand): """ Report delle statistiche di genere complessive, a livello nazionale, per tutti gli organi di tutte le istituzioni. Può limitarsi a una o più istituzioni, se si passa un elenco di institution_id """ args = '<institution_id institution_id ...>' help = "Check that all locations have only male components (list locations with female components)." option_list = VerifyBaseCommand.option_list def execute_verification(self, *args, **options): self.csv_headers = ["ISTITUZIONE", "INCARICO", "N_DONNE", "N_UOMINI", "N_TOTALI", "PERC_DONNE", "PERC_UOMINI"] institutions = OpInstitution.objects.using('politici').all() if args: institutions = institutions.filter(id__in=args) self.logger.info( "Verification {0} launched with institutions limited to {1}".format( self.__class__.__module__, ",".join(institutions.values_list('id', flat=True)) ) ) else: self.logger.info( "Verification {0} launched for all institutions".format( self.__class__.__module__ ) ) self.ok_locs = [] self.ko_locs = [] for institution in institutions: charge_types_ids = OpInstitutionCharge.objects.using('politici').\ filter(date_end__isnull=True, content__deleted_at__isnull=True).\ filter(institution=institution).\ values_list('charge_type', flat=True).\ distinct() charge_types = OpChargeType.objects.using('politici').\ filter(id__in=charge_types_ids) for charge_type in charge_types: self.logger.info( "Counting {0} in {1}".format( charge_type.name, institution.name ) ) qs = OpInstitutionCharge.objects.using('politici').\ filter(date_end__isnull=True, content__deleted_at__isnull=True).\ filter(institution=institution, charge_type=charge_type) n_tot = qs.count() n_fem = qs.filter(politician__sex__iexact='f').count() n_mal = n_tot - n_fem merged = [institution.name, charge_type.name, n_fem, n_mal, n_tot,] merged.append(locale.format("%.2f",100. * n_fem / float(n_tot) )) merged.append(locale.format("%.2f",100. * n_mal / float(n_tot) )) self.ko_locs.append(merged) outcome = Verification.OUTCOME.failed self.logger.info( "Report for {0} institutions generated.".format( len(self.ko_locs) ) ) return outcome
openpolis/op-verify
project/verify/management/commands/generi_in_istituzioni.py
Python
bsd-3-clause
3,219
#ifndef __KIDS_CONFIG_H_ #define __KIDS_CONFIG_H_ #include <cstdio> #include <cstring> #include <string> #include <vector> #define NLIMIT_NORMAL 0 #define NLIMIT_NETWORKSTORE 1 #define NLIMIT_PUBSUB 2 struct LimitConfig { int hard_limit_bytes; int soft_limit_bytes; int soft_limit_seconds; }; struct StoreConfig { ~StoreConfig() { for (std::vector<StoreConfig*>::iterator it = stores.begin(); it != stores.end(); ++it) { delete *it; } } std::string type; std::string buffer_type; std::string socket; std::string host; std::string port; std::string path; std::string name; std::string rotate; std::string success; std::string topic; std::vector<StoreConfig*> stores; }; struct KidsConfig { KidsConfig() : store(NULL) { memset(nlimit, 0, sizeof(nlimit)); } ~KidsConfig() { delete store; } std::string listen_socket; std::string listen_host; std::string listen_port; std::string log_level; std::string log_file; std::string max_clients; std::string worker_threads; std::string ignore_case; LimitConfig nlimit[3]; StoreConfig *store; }; struct Token { Token() {} Token(int tid, char *s, char *e) { id = tid; while (s < e) { value.push_back(*s); s++; } } int id; std::string value; }; struct KeyValue { KeyValue(std::string k, std::vector<std::string>* v) :key(k), value(*v) {} std::string key; std::vector<std::string> value; }; struct ParseContext { ParseContext() : line(0), success(true), conf(NULL) {} ~ParseContext() { delete conf; } int line; bool success; char error[1025]; KidsConfig *conf; }; ParseContext *ParseConfigFile(const std::string& filename); ParseContext *ParseConfig(std::string str); #endif // __KIDS_CONFIG_H_
akkakks/kids
src/conf.h
C
bsd-3-clause
1,770
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008-2016. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; import edu.wpi.first.wpilibj.hal.FRCNetComm.tResourceType; import edu.wpi.first.wpilibj.hal.HAL; import edu.wpi.first.wpilibj.hal.HAL; /** * Handle input from standard Joysticks connected to the Driver Station. This class handles standard * input that comes from the Driver Station. Each time a value is requested the most recent value is * returned. There is a single class instance for each joystick and the mapping of ports to hardware * buttons depends on the code in the driver station. */ public class Joystick extends GenericHID { static final byte kDefaultXAxis = 0; static final byte kDefaultYAxis = 1; static final byte kDefaultZAxis = 2; static final byte kDefaultTwistAxis = 2; static final byte kDefaultThrottleAxis = 3; static final int kDefaultTriggerButton = 1; static final int kDefaultTopButton = 2; /** * Represents an analog axis on a joystick. */ public enum AxisType { kX(0), kY(1), kZ(2), kTwist(3), kThrottle(4), kNumAxis(5); @SuppressWarnings("MemberName") public final int value; private AxisType(int value) { this.value = value; } } /** * Represents a digital button on the JoyStick. */ public enum ButtonType { kTrigger(0), kTop(1), kNumButton(2); @SuppressWarnings("MemberName") public final int value; private ButtonType(int value) { this.value = value; } } /** * Represents a rumble output on the JoyStick. */ public enum RumbleType { kLeftRumble, kRightRumble } private final DriverStation m_ds; private final int m_port; private final byte[] m_axes; private final byte[] m_buttons; private int m_outputs; private short m_leftRumble; private short m_rightRumble; /** * Construct an instance of a joystick. The joystick index is the usb port on the drivers * station. * * @param port The port on the driver station that the joystick is plugged into. */ public Joystick(final int port) { this(port, AxisType.kNumAxis.value, ButtonType.kNumButton.value); m_axes[AxisType.kX.value] = kDefaultXAxis; m_axes[AxisType.kY.value] = kDefaultYAxis; m_axes[AxisType.kZ.value] = kDefaultZAxis; m_axes[AxisType.kTwist.value] = kDefaultTwistAxis; m_axes[AxisType.kThrottle.value] = kDefaultThrottleAxis; m_buttons[ButtonType.kTrigger.value] = kDefaultTriggerButton; m_buttons[ButtonType.kTop.value] = kDefaultTopButton; HAL.report(tResourceType.kResourceType_Joystick, port); } /** * Protected version of the constructor to be called by sub-classes. * * <p>This constructor allows the subclass to configure the number of constants for axes and * buttons. * * @param port The port on the driver station that the joystick is plugged into. * @param numAxisTypes The number of axis types in the enum. * @param numButtonTypes The number of button types in the enum. */ protected Joystick(int port, int numAxisTypes, int numButtonTypes) { m_ds = DriverStation.getInstance(); m_axes = new byte[numAxisTypes]; m_buttons = new byte[numButtonTypes]; m_port = port; } /** * Get the X value of the joystick. This depends on the mapping of the joystick connected to the * current port. * * @param hand Unused * @return The X value of the joystick. */ public double getX(Hand hand) { return getRawAxis(m_axes[AxisType.kX.value]); } /** * Get the Y value of the joystick. This depends on the mapping of the joystick connected to the * current port. * * @param hand Unused * @return The Y value of the joystick. */ public double getY(Hand hand) { return getRawAxis(m_axes[AxisType.kY.value]); } /** * Get the Z value of the joystick. This depends on the mapping of the joystick connected to the * current port. * * @param hand Unused * @return The Z value of the joystick. */ public double getZ(Hand hand) { return getRawAxis(m_axes[AxisType.kZ.value]); } /** * Get the twist value of the current joystick. This depends on the mapping of the joystick * connected to the current port. * * @return The Twist value of the joystick. */ public double getTwist() { return getRawAxis(m_axes[AxisType.kTwist.value]); } /** * Get the throttle value of the current joystick. This depends on the mapping of the joystick * connected to the current port. * * @return The Throttle value of the joystick. */ public double getThrottle() { return getRawAxis(m_axes[AxisType.kThrottle.value]); } /** * Get the value of the axis. * * @param axis The axis to read, starting at 0. * @return The value of the axis. */ public double getRawAxis(final int axis) { return m_ds.getStickAxis(m_port, axis); } /** * For the current joystick, return the axis determined by the argument. * * <p>This is for cases where the joystick axis is returned programatically, otherwise one of the * previous functions would be preferable (for example getX()). * * @param axis The axis to read. * @return The value of the axis. */ public double getAxis(final AxisType axis) { switch (axis) { case kX: return getX(); case kY: return getY(); case kZ: return getZ(); case kTwist: return getTwist(); case kThrottle: return getThrottle(); default: return 0.0; } } /** * For the current joystick, return the number of axis. */ public int getAxisCount() { return m_ds.getStickAxisCount(m_port); } /** * Read the state of the trigger on the joystick. * * <p>Look up which button has been assigned to the trigger and read its state. * * @param hand This parameter is ignored for the Joystick class and is only here to complete the * GenericHID interface. * @return The state of the trigger. */ public boolean getTrigger(Hand hand) { return getRawButton(m_buttons[ButtonType.kTrigger.value]); } /** * Read the state of the top button on the joystick. * * <p>Look up which button has been assigned to the top and read its state. * * @param hand This parameter is ignored for the Joystick class and is only here to complete the * GenericHID interface. * @return The state of the top button. */ public boolean getTop(Hand hand) { return getRawButton(m_buttons[ButtonType.kTop.value]); } /** * This is not supported for the Joystick. This method is only here to complete the GenericHID * interface. * * @param hand This parameter is ignored for the Joystick class and is only here to complete the * GenericHID interface. * @return The state of the bumper (always false) */ public boolean getBumper(Hand hand) { return false; } /** * Get the button value (starting at button 1). * * <p>The appropriate button is returned as a boolean value. * * @param button The button number to be read (starting at 1). * @return The state of the button. */ public boolean getRawButton(final int button) { return m_ds.getStickButton(m_port, (byte) button); } /** * For the current joystick, return the number of buttons. */ public int getButtonCount() { return m_ds.getStickButtonCount(m_port); } /** * Get the angle in degrees of a POV on the joystick. * * <p>The POV angles start at 0 in the up direction, and increase clockwise (eg right is 90, * upper-left is 315). * * @param pov The index of the POV to read (starting at 0) * @return the angle of the POV in degrees, or -1 if the POV is not pressed. */ public int getPOV(int pov) { return m_ds.getStickPOV(m_port, pov); } /** * For the current joystick, return the number of POVs. */ public int getPOVCount() { return m_ds.getStickPOVCount(m_port); } /** * Get buttons based on an enumerated type. * * <p>The button type will be looked up in the list of buttons and then read. * * @param button The type of button to read. * @return The state of the button. */ public boolean getButton(ButtonType button) { switch (button) { case kTrigger: return getTrigger(); case kTop: return getTop(); default: return false; } } /** * Get the magnitude of the direction vector formed by the joystick's current position relative to * its origin. * * @return The magnitude of the direction vector */ public double getMagnitude() { return Math.sqrt(Math.pow(getX(), 2) + Math.pow(getY(), 2)); } /** * Get the direction of the vector formed by the joystick and its origin in radians. * * @return The direction of the vector in radians */ public double getDirectionRadians() { return Math.atan2(getX(), -getY()); } /** * Get the direction of the vector formed by the joystick and its origin in degrees. * * <p>Uses acos(-1) to represent Pi due to absence of readily accessable Pi constant in C++ * * @return The direction of the vector in degrees */ public double getDirectionDegrees() { return Math.toDegrees(getDirectionRadians()); } /** * Get the channel currently associated with the specified axis. * * @param axis The axis to look up the channel for. * @return The channel fr the axis. */ public int getAxisChannel(AxisType axis) { return m_axes[axis.value]; } /** * Set the channel associated with a specified axis. * * @param axis The axis to set the channel for. * @param channel The channel to set the axis to. */ public void setAxisChannel(AxisType axis, int channel) { m_axes[axis.value] = (byte) channel; } /** * Get the value of isXbox for the current joystick. * * @return A boolean that is true if the controller is an xbox controller. */ public boolean getIsXbox() { return m_ds.getJoystickIsXbox(m_port); } /** * Get the HID type of the current joystick. * * @return The HID type value of the current joystick. */ public int getType() { return m_ds.getJoystickType(m_port); } /** * Get the name of the current joystick. * * @return The name of the current joystick. */ public String getName() { return m_ds.getJoystickName(m_port); } /** * Get the port number of the joystick. * * @return The port number of the joystick. */ public int getPort() { return m_port; } /** * Get the axis type of a joystick axis. * * @return the axis type of a joystick axis. */ public int getAxisType(int axis) { return m_ds.getJoystickAxisType(m_port, axis); } /** * Set the rumble output for the joystick. The DS currently supports 2 rumble values, left rumble * and right rumble. * * @param type Which rumble value to set * @param value The normalized value (0 to 1) to set the rumble to */ public void setRumble(RumbleType type, float value) { if (value < 0) { value = 0; } else if (value > 1) { value = 1; } if (type == RumbleType.kLeftRumble) { m_leftRumble = (short) (value * 65535); } else { m_rightRumble = (short) (value * 65535); } HAL.setJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, m_rightRumble); } /** * Set a single HID output value for the joystick. * * @param outputNumber The index of the output to set (1-32) * @param value The value to set the output to */ public void setOutput(int outputNumber, boolean value) { m_outputs = (m_outputs & ~(1 << (outputNumber - 1))) | ((value ? 1 : 0) << (outputNumber - 1)); HAL.setJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, m_rightRumble); } /** * Set all HID output values for the joystick. * * @param value The 32 bit output value (1 bit for each output) */ public void setOutputs(int value) { m_outputs = value; HAL.setJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, m_rightRumble); } }
PeterMitrano/allwpilib
wpilibj/src/athena/java/edu/wpi/first/wpilibj/Joystick.java
Java
bsd-3-clause
12,635
package sdp func (s Session) appendAttributes(attrs Attributes) Session { for _, v := range attrs { if v.Value == blank { s = s.AddFlag(v.Key) } else { s = s.AddAttribute(v.Key, v.Value) } } return s } // Append encodes message to Session and returns result. // // See RFC 4566 Section 5. func (m *Message) Append(s Session) Session { s = s.AddVersion(m.Version) s = s.AddOrigin(m.Origin) s = s.AddSessionName(m.Name) if len(m.Info) > 0 { s = s.AddSessionInfo(m.Info) } if len(m.URI) > 0 { s = s.AddURI(m.URI) } if len(m.Email) > 0 { s = s.AddEmail(m.Email) } if len(m.Phone) > 0 { s = s.AddPhone(m.Phone) } if !m.Connection.Blank() { s = s.AddConnectionData(m.Connection) } for t, v := range m.Bandwidths { s = s.AddBandwidth(t, v) } // One or more time descriptions ("t=" and "r=" lines) for _, t := range m.Timing { s = s.AddTiming(t.Start, t.End) if len(t.Offsets) > 0 { s = s.AddRepeatTimesCompact(t.Repeat, t.Active, t.Offsets...) } } if len(m.TZAdjustments) > 0 { s = s.AddTimeZones(m.TZAdjustments...) } if !m.Encryption.Blank() { s = s.AddEncryption(m.Encryption) } s = s.appendAttributes(m.Attributes) for i := range m.Medias { s = s.AddMediaDescription(m.Medias[i].Description) if len(m.Medias[i].Title) > 0 { s = s.AddSessionInfo(m.Medias[i].Title) } if !m.Medias[i].Connection.Blank() { s = s.AddConnectionData(m.Medias[i].Connection) } for t, v := range m.Medias[i].Bandwidths { s = s.AddBandwidth(t, v) } if !m.Medias[i].Encryption.Blank() { s = s.AddEncryption(m.Medias[i].Encryption) } s = s.appendAttributes(m.Medias[i].Attributes) } return s }
ernado/sdp
encoder.go
GO
bsd-3-clause
1,664
<?php if(!class_exists('AbstractQueuedJob')) return; /** * A Job for running a external link check for published pages * */ class CheckLinksJob extends AbstractQueuedJob implements QueuedJob { public function getTitle() { return _t('CheckLinksJob.TITLE', 'Checking for broken links'); } public function getJobType() { return QueuedJob::QUEUED; } public function getSignature() { return md5(get_class($this)); } /** * Check an individual page */ public function process() { $task = CheckLinksTask::create(); $track = $task->runLinksCheck(1); $this->currentStep = $track->CompletedPages; $this->totalSteps = $track->TotalPages; $this->isComplete = $track->Status === 'Completed'; } }
blpraveen/silverstripe-brokenlinks
code/jobs/CheckLinksJob.php
PHP
bsd-3-clause
722
// Copyright 2010-2016, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google 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 MOZC_WIN32_BASE_OMAHA_UTIL_H_ #define MOZC_WIN32_BASE_OMAHA_UTIL_H_ // Omaha is the code name of Google Update, which is not used in // OSS version of Mozc. #if !defined(GOOGLE_JAPANESE_INPUT_BUILD) #error OmahaUtil must be used with Google Japanese Input, not OSS Mozc #endif // !GOOGLE_JAPANESE_INPUT_BUILD #include <windows.h> #include <string> #include "base/port.h" namespace mozc { namespace win32 { // TODO(yukawa): Add unit test for this class. class OmahaUtil { public: // Writes the channel name specified by |value| for Omaha. // Returns true if the operation completed successfully. static bool WriteChannel(const wstring &value); // Reads the channel name for Omaha. // Returns an empty string if there is no entry or fails to retrieve the // channel name. static wstring ReadChannel(); // Clears the registry entry to specify error message for Omaha. // Returns true if the operation completed successfully. static bool ClearOmahaError(); // Writes the registry entry for Omaha to show some error messages. // Returns true if the operation completed successfully. static bool WriteOmahaError(const wstring &ui_message, const wstring &header); // Clears the registry entry for the channel name. // Returns true if the operation completed successfully. static bool ClearChannel(); private: DISALLOW_COPY_AND_ASSIGN(OmahaUtil); }; } // namespace win32 } // namespace mozc #endif // MOZC_WIN32_BASE_OMAHA_UTIL_H_
kbc-developers/Mozc
src/win32/base/omaha_util.h
C
bsd-3-clause
3,042
#!/usr/bin/env python from distutils.core import setup setup(name='django-modeltranslation', version='0.4.0-alpha1', description='Translates Django models using a registration approach.', long_description='The modeltranslation application can be used to ' 'translate dynamic content of existing models to an ' 'arbitrary number of languages without having to ' 'change the original model classes. It uses a ' 'registration approach (comparable to Django\'s admin ' 'app) to be able to add translations to existing or ' 'new projects and is fully integrated into the Django ' 'admin backend.', author='Peter Eschler', author_email='[email protected]', maintainer='Dirk Eschler', maintainer_email='[email protected]', url='http://code.google.com/p/django-modeltranslation/', packages=['modeltranslation', 'modeltranslation.management', 'modeltranslation.management.commands'], package_data={'modeltranslation': ['static/modeltranslation/css/*.css', 'static/modeltranslation/js/*.js']}, include_package_data = True, requires=['django(>=1.0)'], download_url='http://django-modeltranslation.googlecode.com/files/django-modeltranslation-0.4.0-alpha1.tar.gz', classifiers=['Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License'], license='New BSD')
google-code-export/django-modeltranslation
setup.py
Python
bsd-3-clause
1,631
<div class="row"> <div class="col-xs-12"> <div class="box"> <?= \yii\grid\GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ 'idadvert', [ 'label' => 'title', 'value' => 'title', ], 'user.email', 'price', 'created_at:datetime', [ 'class' => 'yii\grid\ActionColumn', 'template' => '{view} {delete}', 'buttons' => [ 'view' => function ($url, $model, $key) { return \yii\helpers\Html::a("<span class=\"glyphicon glyphicon-eye-open\"></span>", Yii::$app->params['baseUrl']. "/view-advert/".$key, ['target' => '_blank']); } ], ] ], ]) ?> </div> </div> </div>
lastfocus/lol-project
backend/views/advert/index.php
PHP
bsd-3-clause
1,090
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>DHAIR2: PatientAssociate Class Reference</title> <link href="../../doxygen.css" rel="stylesheet" type="text/css"> <link href="../../tabs.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.5.6 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="../../index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="../../namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="../../annotated.html"><span>Classes</span></a></li> <li> <form action="../../search.php" method="get"> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td><label>&nbsp;<u>S</u>earch&nbsp;for&nbsp;</label></td> <td><input type="text" name="query" value="" size="20" accesskey="s"/></td> </tr> </table> </form> </li> </ul> </div> <div class="tabs"> <ul> <li><a href="../../annotated.html"><span>Class&nbsp;List</span></a></li> <li><a href="../../hierarchy.html"><span>Class&nbsp;Hierarchy</span></a></li> <li><a href="../../functions.html"><span>Class&nbsp;Members</span></a></li> </ul> </div> </div> <div class="contents"> <h1>PatientAssociate Class Reference</h1><!-- doxytag: class="PatientAssociate" --><!-- doxytag: inherits="AppModel" --><div class="dynheader"> Inheritance diagram for PatientAssociate:</div> <div class="dynsection"> <p><center><img src="../../de/d63/classPatientAssociate.png" usemap="#PatientAssociate_map" border="0" alt=""></center> <map name="PatientAssociate_map"> </map> </div> <p> <a href="../../d5/d8a/classPatientAssociate-members.html">List of all members.</a><table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> <tr><td colspan="2"><br><h2>Public Member Functions</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="3163fd014a399c0dccb94d3d7cae6932"></a><!-- doxytag: member="PatientAssociate::countForPatientJournal" ref="3163fd014a399c0dccb94d3d7cae6932" args="($patient_id)" --> &nbsp;</td><td class="memItemRight" valign="bottom"><b>countForPatientJournal</b> ($patient_id)</td></tr> <tr><td colspan="2"><br><h2>Public Attributes</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="821f8762aba39015c29fed74ff3e7a7f"></a><!-- doxytag: member="PatientAssociate::$name" ref="821f8762aba39015c29fed74ff3e7a7f" args="" --> &nbsp;</td><td class="memItemRight" valign="bottom"><b>$name</b> = &quot;PatientAssociate&quot;</td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="1b477ef9589643785b5f6a7c7f3f394d"></a><!-- doxytag: member="PatientAssociate::$useTable" ref="1b477ef9589643785b5f6a7c7f3f394d" args="" --> &nbsp;</td><td class="memItemRight" valign="bottom"><b>$useTable</b> = &quot;patients_associates&quot;</td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="78b87fcff6874c80559dce177d1bb35d"></a><!-- doxytag: member="PatientAssociate::$primaryKey" ref="78b87fcff6874c80559dce177d1bb35d" args="" --> &nbsp;</td><td class="memItemRight" valign="bottom"><b>$primaryKey</b> = &quot;id&quot;</td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="6a54b69164de94dc59049ad7460aacca"></a><!-- doxytag: member="PatientAssociate::$belongsTo" ref="6a54b69164de94dc59049ad7460aacca" args="" --> &nbsp;</td><td class="memItemRight" valign="bottom"><b>$belongsTo</b> = array(&quot;Patient&quot;, &quot;<a class="el" href="../../d1/d41/classAssociate.html">Associate</a>&quot;)</td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">&nbsp;</td><td class="memItemRight" valign="bottom"><b>$hasAndBelongsToMany</b></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="66a8e0acf7290babaf0a38825346adea"></a><!-- doxytag: member="PatientAssociate::$validate" ref="66a8e0acf7290babaf0a38825346adea" args="" --> &nbsp;</td><td class="memItemRight" valign="bottom"><b>$validate</b></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="0ca548fc0bc60b7022c1d70038ccc9d0"></a><!-- doxytag: member="PatientAssociate::$count" ref="0ca548fc0bc60b7022c1d70038ccc9d0" args="" --> return&nbsp;</td><td class="memItemRight" valign="bottom"><b>$count</b></td></tr> </table> <hr><a name="_details"></a><h2>Detailed Description</h2> Copyright 2013 University of Washington, School of Nursing. <a href="http://opensource.org/licenses/BSD-3-Clause">http://opensource.org/licenses/BSD-3-Clause</a> <hr><h2>Member Data Documentation</h2> <a class="anchor" name="b323350ddab8b46be3e6d56e4b8df364"></a><!-- doxytag: member="PatientAssociate::$hasAndBelongsToMany" ref="b323350ddab8b46be3e6d56e4b8df364" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">PatientAssociate::$hasAndBelongsToMany </td> </tr> </table> </div> <div class="memdoc"> <p> <b>Initial value:</b><div class="fragment"><pre class="fragment"> array(<span class="stringliteral">"Subscale"</span> =&gt; array(<span class="stringliteral">'className'</span> =&gt; <span class="stringliteral">"Subscale"</span>, <span class="stringliteral">'joinTable'</span> =&gt; <span class="stringliteral">"patients_associates_subscales"</span>, <span class="stringliteral">'foreignKey'</span> =&gt; <span class="stringliteral">"patient_associate_id"</span>, <span class="stringliteral">"dependent"</span> =&gt; <span class="keyword">true</span>, <span class="stringliteral">'associationForeignKey'</span> =&gt; <span class="stringliteral">'subscale_id'</span> )) </pre></div> </div> </div><p> <hr>The documentation for this class was generated from the following file:<ul> <li>/var/lib/jenkins/jobs/CPRO doc auto-generation - GitHub Repo/workspace/app/Model/PatientAssociate.php</ul> </div> <hr size="1"><address style="text-align: right;"><small>Generated on Mon Dec 23 10:49:47 2013 for DHAIR2 by&nbsp; <a href="http://www.doxygen.org/index.html"> <img src="../../doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.6 </small></address> </body> </html>
uwcirg/cpro
app/docs/phpdocs/html/de/d63/classPatientAssociate.html
HTML
bsd-3-clause
6,546
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Border Properties</title> <style type="text/css"> <!-- .style1 { font-family: Arial; font-size: 10pt; } --> </style> </head> <BODY> <P class=style1><IMG height=270 src="screenshots/Border Properties Dialog.jpg" width=363></P> <P class=style1>Border properties dialog defines borders of the balloons (both static and dynamic). This doesn't apply to other items. </P> </BODY> </html>
visla/PDFReporter
Help/PDF Reports Template Editor_Border Properties.html
HTML
bsd-3-clause
641
#include "stdfx.h" //#include "tfxparam.h" #include "trop.h" //=================================================================== class PremultiplyFx : public TStandardRasterFx { FX_PLUGIN_DECLARATION(PremultiplyFx) TRasterFxPort m_input; public: PremultiplyFx() { addInputPort("Source", m_input); } ~PremultiplyFx(){}; bool doGetBBox(double frame, TRectD &bBox, const TRenderSettings &info) { if (m_input.isConnected()) return m_input->doGetBBox(frame, bBox, info); else { bBox = TRectD(); return false; } } void doCompute(TTile &tile, double frame, const TRenderSettings &ri); bool canHandle(const TRenderSettings &info, double frame) { return true; } }; //------------------------------------------------------------------------------ void PremultiplyFx::doCompute(TTile &tile, double frame, const TRenderSettings &ri) { if (!m_input.isConnected()) return; m_input->compute(tile, frame, ri); TRop::premultiply(tile.getRaster()); } FX_PLUGIN_IDENTIFIER(PremultiplyFx, "premultiplyFx");
walkerka/opentoonz
toonz/sources/stdfx/premultiplyfx.cpp
C++
bsd-3-clause
1,082
/* $NetBSD: proc.h,v 1.8 1996/11/25 22:09:11 gwr Exp $ */ /* * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. * * from: proc.h 8.1 (Berkeley) 6/10/93 */ /* * Machine-dependent part of the proc structure for sun3. */ struct mdproc { int *md_regs; /* registers on current frame */ int md_flags; /* machine-dependent flags */ }; /* md_flags */ #define MDP_FPUSED 0x0001 /* floating point coprocessor used */ #define MDP_STACKADJ 0x0002 /* frame SP adjusted, might have to undo when system call returns ERESTART. */ #define MDP_HPUXTRACE 0x0004 /* being traced by HP-UX process */
MarginC/kame
netbsd/sys/arch/sun3/include/proc.h
C
bsd-3-clause
2,379
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/components/phonehub/multidevice_setup_state_updater.h" #include "ash/components/phonehub/pref_names.h" #include "ash/components/phonehub/util/histogram_util.h" #include "base/callback_helpers.h" #include "chromeos/components/multidevice/logging/logging.h" #include "chromeos/services/multidevice_setup/public/cpp/prefs.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" namespace chromeos { namespace phonehub { namespace { using multidevice_setup::mojom::Feature; using multidevice_setup::mojom::FeatureState; using multidevice_setup::mojom::HostStatus; } // namespace // static void MultideviceSetupStateUpdater::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterBooleanPref(prefs::kIsAwaitingVerifiedHost, false); } MultideviceSetupStateUpdater::MultideviceSetupStateUpdater( PrefService* pref_service, multidevice_setup::MultiDeviceSetupClient* multidevice_setup_client, NotificationAccessManager* notification_access_manager) : pref_service_(pref_service), multidevice_setup_client_(multidevice_setup_client), notification_access_manager_(notification_access_manager) { multidevice_setup_client_->AddObserver(this); notification_access_manager_->AddObserver(this); } MultideviceSetupStateUpdater::~MultideviceSetupStateUpdater() { multidevice_setup_client_->RemoveObserver(this); notification_access_manager_->RemoveObserver(this); } void MultideviceSetupStateUpdater::OnNotificationAccessChanged() { switch (notification_access_manager_->GetAccessStatus()) { case NotificationAccessManager::AccessStatus::kAccessGranted: if (IsWaitingForAccessToInitiallyEnableNotifications()) { PA_LOG(INFO) << "Enabling PhoneHubNotifications for the first time now " << "that access has been granted by the phone."; multidevice_setup_client_->SetFeatureEnabledState( Feature::kPhoneHubNotifications, /*enabled=*/true, /*auth_token=*/absl::nullopt, base::DoNothing()); } break; case NotificationAccessManager::AccessStatus::kAvailableButNotGranted: FALLTHROUGH; case NotificationAccessManager::AccessStatus::kProhibited: // Disable kPhoneHubNotifications if notification access has been revoked // by the phone. PA_LOG(INFO) << "Disabling PhoneHubNotifications feature."; multidevice_setup_client_->SetFeatureEnabledState( Feature::kPhoneHubNotifications, /*enabled=*/false, /*auth_token=*/absl::nullopt, base::DoNothing()); break; } } void MultideviceSetupStateUpdater::OnHostStatusChanged( const multidevice_setup::MultiDeviceSetupClient::HostStatusWithDevice& host_device_with_status) { EnablePhoneHubIfAwaitingVerifiedHost(); } void MultideviceSetupStateUpdater::OnFeatureStatesChanged( const multidevice_setup::MultiDeviceSetupClient::FeatureStatesMap& feature_state_map) { EnablePhoneHubIfAwaitingVerifiedHost(); } bool MultideviceSetupStateUpdater:: IsWaitingForAccessToInitiallyEnableNotifications() const { // If the Phone Hub notifications feature has never been explicitly set, we // should enable it after // 1. the top-level Phone Hub feature is enabled, and // 2. the phone has granted access. // We do *not* want disrupt the feature state if it was already explicitly set // by the user. return multidevice_setup::IsDefaultFeatureEnabledValue( Feature::kPhoneHubNotifications, pref_service_) && multidevice_setup_client_->GetFeatureState(Feature::kPhoneHub) == FeatureState::kEnabledByUser; } void MultideviceSetupStateUpdater::EnablePhoneHubIfAwaitingVerifiedHost() { bool is_awaiting_verified_host = pref_service_->GetBoolean(prefs::kIsAwaitingVerifiedHost); const HostStatus host_status = multidevice_setup_client_->GetHostStatus().first; const FeatureState feature_state = multidevice_setup_client_->GetFeatureState(Feature::kPhoneHub); // Enable the PhoneHub feature if the phone is verified and there was an // intent to enable the feature. We also ensure that the feature is currently // disabled and not in state like kNotSupportedByPhone or kProhibitedByPolicy. if (is_awaiting_verified_host && host_status == HostStatus::kHostVerified && feature_state == FeatureState::kDisabledByUser) { multidevice_setup_client_->SetFeatureEnabledState( Feature::kPhoneHub, /*enabled=*/true, /*auth_token=*/absl::nullopt, base::DoNothing()); util::LogFeatureOptInEntryPoint(util::OptInEntryPoint::kSetupFlow); } UpdateIsAwaitingVerifiedHost(); } void MultideviceSetupStateUpdater::UpdateIsAwaitingVerifiedHost() { // Wait to enable Phone Hub until after host phone is verified. The intent to // enable Phone Hub must be persisted in the event that this class is // destroyed before the phone is verified. const HostStatus host_status = multidevice_setup_client_->GetHostStatus().first; if (host_status == HostStatus::kHostSetLocallyButWaitingForBackendConfirmation) { pref_service_->SetBoolean(prefs::kIsAwaitingVerifiedHost, true); return; } // The intent to enable Phone Hub after host verification was fulfilled. // Note: We don't want to reset the pref if, say, the host status is // kNoEligibleHosts; that might just be a transient state seen during // start-up, for instance. It is true that we don't want to enable Phone Hub // if the user explicitly disabled it in settings, however, that can only // occur after the host becomes verified and we first enable Phone Hub. const bool is_awaiting_verified_host = pref_service_->GetBoolean(prefs::kIsAwaitingVerifiedHost); const FeatureState feature_state = multidevice_setup_client_->GetFeatureState(Feature::kPhoneHub); if (is_awaiting_verified_host && host_status == HostStatus::kHostVerified && feature_state == FeatureState::kEnabledByUser) { pref_service_->SetBoolean(prefs::kIsAwaitingVerifiedHost, false); return; } } } // namespace phonehub } // namespace chromeos
scheib/chromium
ash/components/phonehub/multidevice_setup_state_updater.cc
C++
bsd-3-clause
6,304
/* * jQuery File Upload Plugin JS Example 8.9.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /* global $, window */ $(function () { 'use strict'; // Initialize the jQuery File Upload widget: $('#fileupload').fileupload({ // Uncomment the following to send cross-domain cookies: //xhrFields: {withCredentials: true}, url: root_url + '/media/upload' }); // Enable iframe cross-domain access via redirect option: $('#fileupload').fileupload( 'option', 'redirect', window.location.href.replace( /\/[^\/]*$/, '/cors/result.html?%s' ) ); if (window.location.hostname === 'blueimp.github.io') { // Demo settings: $('#fileupload').fileupload('option', { url: '//jquery-file-upload.appspot.com/', // Enable image resizing, except for Android and Opera, // which actually support image resizing, but fail to // send Blob objects via XHR requests: disableImageResize: /Android(?!.*Chrome)|Opera/ .test(window.navigator.userAgent), maxFileSize: 5000000, acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i }); // Upload server status check for browsers with CORS support: if ($.support.cors) { $.ajax({ url: '//jquery-file-upload.appspot.com/', type: 'HEAD' }).fail(function () { $('<div class="alert alert-danger"/>') .text('Upload server currently unavailable - ' + new Date()) .appendTo('#fileupload'); }); } } else { // Load existing files: $('#fileupload').addClass('fileupload-processing'); $.ajax({ // Uncomment the following to send cross-domain cookies: //xhrFields: {withCredentials: true}, url: $('#fileupload').fileupload('option', 'url'), dataType: 'json', context: $('#fileupload')[0] }).always(function () { $(this).removeClass('fileupload-processing'); }).done(function (result) { $(this).fileupload('option', 'done') .call(this, $.Event('done'), {result: result}); }); } /////////////////////////////////////////////// });
vohoanglong07/yii_basic
web/js/fileupload/main.js
JavaScript
bsd-3-clause
2,550
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/media/images/favicon.ico" /> <title>DataTables example</title> <style type="text/css" title="currentStyle"> @import "../../media/css/demo_page.css"; @import "../../media/css/demo_table.css"; </style> <script type="text/javascript" language="javascript" src="../../media/js/jquery.js"></script> <script type="text/javascript" language="javascript" src="../../media/js/jquery.dataTables.js"></script> <script type="text/javascript" charset="utf-8"> $(document).ready(function() { $('#example').dataTable( { "processing": true, "serverSide": true, "ajax": { "url": "scripts/post.php", "type": "POST" } } ); } ); </script> </head> <body id="dt_example"> <div id="container"> <div class="full_width big"> DataTables server-side processing with POST example </div> <h1>Preamble</h1> <p>The default HTTP method that DataTables uses to get data from the server-side if GET, however, there are times when you may wish to use POST. This is very easy using the sServerMethod initialisation parameter, which is simply set to the HTTP method that you want to use - the default is 'GET' and this example shows 'POST' being used.</p> <h1>Live example</h1> <div id="dynamic"> <table cellpadding="0" cellspacing="0" border="0" class="display" id="example"> <thead> <tr> <th width="20%">Rendering engine</th> <th width="25%">Browser</th> <th width="25%">Platform(s)</th> <th width="15%">Engine version</th> <th width="15%">CSS grade</th> </tr> </thead> <tbody> <tr> <td colspan="5" class="dataTables_empty">Loading data from server</td> </tr> </tbody> <tfoot> <tr> <th>Rendering engine</th> <th>Browser</th> <th>Platform(s)</th> <th>Engine version</th> <th>CSS grade</th> </tr> </tfoot> </table> </div> <div class="spacer"></div> <h1>Initialisation code</h1> <pre class="brush: js;">$(document).ready(function() { $('#example').dataTable( { "bProcessing": true, "bServerSide": true, "sAjaxSource": "scripts/post.php", "sServerMethod": "POST" } ); } );</pre> <style type="text/css"> @import "../examples_support/syntax/css/shCore.css"; </style> <script type="text/javascript" language="javascript" src="../examples_support/syntax/js/shCore.js"></script> <h1>Server response</h1> <p>The code below shows the latest JSON data that has been returned from the server in response to the Ajax request made by DataTables. This will update as further requests are made.</p> <pre id="latest_xhr" class="brush: js;"></pre> <h1>Other examples</h1> <div class="demo_links"> <h2>Basic initialisation</h2> <ul> <li><a href="../basic_init/zero_config.html">Zero configuration</a></li> <li><a href="../basic_init/filter_only.html">Feature enablement</a></li> <li><a href="../basic_init/table_sorting.html">Sorting data</a></li> <li><a href="../basic_init/multi_col_sort.html">Multi-column sorting</a></li> <li><a href="../basic_init/multiple_tables.html">Multiple tables</a></li> <li><a href="../basic_init/hidden_columns.html">Hidden columns</a></li> <li><a href="../basic_init/complex_header.html">Complex headers - grouping with colspan</a></li> <li><a href="../basic_init/dom.html">DOM positioning</a></li> <li><a href="../basic_init/flexible_width.html">Flexible table width</a></li> <li><a href="../basic_init/state_save.html">State saving</a></li> <li><a href="../basic_init/alt_pagination.html">Alternative pagination styles</a></li> <li>Scrolling: <br> <a href="../basic_init/scroll_x.html">Horizontal</a> / <a href="../basic_init/scroll_y.html">Vertical</a> / <a href="../basic_init/scroll_xy.html">Both</a> / <a href="../basic_init/scroll_y_theme.html">Themed</a> / <a href="../basic_init/scroll_y_infinite.html">Infinite</a> </li> <li><a href="../basic_init/language.html">Change language information (internationalisation)</a></li> <li><a href="../basic_init/themes.html">ThemeRoller themes (Smoothness)</a></li> </ul> <h2>Advanced initialisation</h2> <ul> <li>Events: <br> <a href="../advanced_init/events_live.html">Live events</a> / <a href="../advanced_init/events_pre_init.html">Pre-init</a> / <a href="../advanced_init/events_post_init.html">Post-init</a> </li> <li><a href="../advanced_init/column_render.html">Column rendering</a></li> <li><a href="../advanced_init/html_sort.html">Sorting without HTML tags</a></li> <li><a href="../advanced_init/dom_multiple_elements.html">Multiple table controls (sDom)</a></li> <li><a href="../advanced_init/length_menu.html">Defining length menu options</a></li> <li><a href="../advanced_init/complex_header.html">Complex headers and hidden columns</a></li> <li><a href="../advanced_init/dom_toolbar.html">Custom toolbar (element) around table</a></li> <li><a href="../advanced_init/highlight.html">Row highlighting with CSS</a></li> <li><a href="../advanced_init/row_grouping.html">Row grouping</a></li> <li><a href="../advanced_init/row_callback.html">Row callback</a></li> <li><a href="../advanced_init/footer_callback.html">Footer callback</a></li> <li><a href="../advanced_init/sorting_control.html">Control sorting direction of columns</a></li> <li><a href="../advanced_init/language_file.html">Change language information from a file (internationalisation)</a></li> <li><a href="../advanced_init/defaults.html">Setting defaults</a></li> <li><a href="../advanced_init/localstorage.html">State saving with localStorage</a></li> <li><a href="../advanced_init/dt_events.html">Custom events</a></li> </ul> <h2>API</h2> <ul> <li><a href="../api/add_row.html">Dynamically add a new row</a></li> <li><a href="../api/multi_filter.html">Individual column filtering (using "input" elements)</a></li> <li><a href="../api/multi_filter_select.html">Individual column filtering (using "select" elements)</a></li> <li><a href="../api/highlight.html">Highlight rows and columns</a></li> <li><a href="../api/row_details.html">Show and hide details about a particular record</a></li> <li><a href="../api/select_row.html">User selectable rows (multiple rows)</a></li> <li><a href="../api/select_single_row.html">User selectable rows (single row) and delete rows</a></li> <li><a href="../api/editable.html">Editable rows (with jEditable)</a></li> <li><a href="../api/form.html">Submit form with elements in table</a></li> <li><a href="../api/counter_column.html">Index column (static number column)</a></li> <li><a href="../api/show_hide.html">Show and hide columns dynamically</a></li> <li><a href="../api/api_in_init.html">API function use in initialisation object (callback)</a></li> <li><a href="../api/tabs_and_scrolling.html">DataTables scrolling and tabs</a></li> <li><a href="../api/regex.html">Regular expression filtering</a></li> </ul> </div> <div class="demo_links"> <h2>Data sources</h2> <ul> <li><a href="../data_sources/dom.html">DOM</a></li> <li><a href="../data_sources/js_array.html">Javascript array</a></li> <li><a href="../data_sources/ajax.html">Ajax source</a></li> <li><a href="../data_sources/server_side.html">Server side processing</a></li> </ul> <h2>Server-side processing</h2> <ul> <li><a href="../server_side/server_side.html">Obtain server-side data</a></li> <li><a href="../server_side/custom_vars.html">Add extra HTTP variables</a></li> <li><a href="../server_side/post.html">Use HTTP POST</a></li> <li><a href="../server_side/ids.html">Automatic addition of IDs and classes to rows</a></li> <li><a href="../server_side/object_data.html">Reading table data from objects</a></li> <li><a href="../server_side/row_details.html">Show and hide details about a particular record</a></li> <li><a href="../server_side/select_rows.html">User selectable rows (multiple rows)</a></li> <li><a href="../server_side/jsonp.html">JSONP for a cross domain data source</a></li> <li><a href="../server_side/editable.html">jEditable integration with DataTables</a></li> <li><a href="../server_side/defer_loading.html">Deferred loading of Ajax data</a></li> <li><a href="../server_side/pipeline.html">Pipelining data (reduce Ajax calls for paging)</a></li> </ul> <h2>Ajax data source</h2> <ul> <li><a href="../ajax/ajax.html">Ajax sourced data (array of arrays)</a></li> <li><a href="../ajax/objects.html">Ajax sourced data (array of objects)</a></li> <li><a href="../ajax/defer_render.html">Deferred DOM creation for extra speed</a></li> <li><a href="../ajax/null_data_source.html">Empty data source columns</a></li> <li><a href="../ajax/custom_data_property.html">Use a data source other than aaData (the default)</a></li> <li><a href="../ajax/objects_subarrays.html">Read column data from sub-arrays</a></li> <li><a href="../ajax/deep.html">Read column data from deeply nested properties</a></li> </ul> <h2>Plug-ins</h2> <ul> <li><a href="../plug-ins/plugin_api.html">Add custom API functions</a></li> <li><a href="../plug-ins/sorting_plugin.html">Sorting and automatic type detection</a></li> <li><a href="../plug-ins/sorting_sType.html">Sorting without automatic type detection</a></li> <li><a href="../plug-ins/paging_plugin.html">Custom pagination controls</a></li> <li><a href="../plug-ins/range_filtering.html">Range filtering / custom filtering</a></li> <li><a href="../plug-ins/dom_sort.html">Live DOM sorting</a></li> <li><a href="../plug-ins/html_sort.html">Automatic HTML type detection</a></li> </ul> </div> <div id="footer" class="clear" style="text-align:center;"> <p> Please refer to the <a href="http://www.datatables.net/usage">DataTables documentation</a> for full information about its API properties and methods.<br> Additionally, there are a wide range of <a href="http://www.datatables.net/extras">extras</a> and <a href="http://www.datatables.net/plug-ins">plug-ins</a> which extend the capabilities of DataTables. </p> <span style="font-size:10px;"> DataTables designed and created by <a href="http://www.sprymedia.co.uk">Allan Jardine</a> &copy; 2007-2011<br> DataTables is dual licensed under the <a href="http://www.datatables.net/license_gpl2">GPL v2 license</a> or a <a href="http://www.datatables.net/license_bsd">BSD (3-point) license</a>. </span> </div> </div> </body> </html>
Khan/DataTables
examples/server_side/post.html
HTML
bsd-3-clause
11,018
module Spree module Admin class AuthorsController < ResourceController def index params[:q] ||= {} params[:q][:deleted_at_null] ||= "1" @search = @authors.ransack(params[:q]) @authors = @search.result.page(params[:page]).per(Spree::Config[:admin_products_per_page]) @authors = @authors.includes(:user_detail) end def update author_info = Spree::UserDetail.find_or_create_by(user_id: params[:id]) result = author_info.update_attributes(author_params[:user_detail]) if result flash[:success] = flash_message_for(@author, :successfully_updated) respond_with(@author) do |format| format.html { redirect_to admin_authors_path } format.json { render layout: false, status: :updated } end else invoke_callbacks(:update, :fails) respond_with(@author) end end protected def collection page = params[:page].to_i > 0 ? params[:page].to_i : 1 per_page = params[:per_page].to_i > 0 ? params[:per_page].to_i : 20 Spree::User.authors.page(page).per(per_page) end private def author_params params.require(:author).permit(:id, { user_detail: [:nickname, :website_url, :bio_info] }) end end end end
mehadesai/spree-multi-blogs
app/controllers/spree/admin/authors_controller.rb
Ruby
bsd-3-clause
1,361
/* * Copyright (c) 2006, 2006, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /* * ceil(x) * Return x rounded toward -inf to integral value * Method: * Bit twiddling. * Exception: * Inexact flag raised if x not equal to ceil(x). */ #include "fdlibm.h" #ifdef __STDC__ static const double huge = 1.0e300; #else static double huge = 1.0e300; #endif #ifdef __STDC__ double ceil(double x) #else double ceil(x) double x; #endif { int i0,i1,j0; unsigned i,j; i0 = __HI(x); i1 = __LO(x); j0 = ((i0>>20)&0x7ff)-0x3ff; if(j0<20) { if(j0<0) { /* raise inexact if x != 0 */ if(huge+x>0.0) {/* return 0*sign(x) if |x|<1 */ if(i0<0) {i0=0x80000000;i1=0;} else if((i0|i1)!=0) { i0=0x3ff00000;i1=0;} } } else { i = (0x000fffff)>>j0; if(((i0&i)|i1)==0) return x; /* x is integral */ if(huge+x>0.0) { /* raise inexact flag */ if(i0>0) i0 += (0x00100000)>>j0; i0 &= (~i); i1=0; } } } else if (j0>51) { if(j0==0x400) return x+x; /* inf or NaN */ else return x; /* x is integral */ } else { i = ((unsigned)(0xffffffff))>>(j0-20); if((i1&i)==0) return x; /* x is integral */ if(huge+x>0.0) { /* raise inexact flag */ if(i0>0) { if(j0==20) i0+=1; else { j = i1 + (1<<(52-j0)); if(j<i1) i0+=1; /* got a carry */ i1 = j; } } i1 &= (~i); } } __HI(x) = i0; __LO(x) = i1; return x; }
SnakeDoc/GuestVM
guestvm~guestvm/com.oracle.max.ve.native/fdlibm/s_ceil.c
C
bsd-3-clause
1,481
.aui-base { }
giros/alloy-ui
build/aui-base/assets/aui-base-core.css
CSS
bsd-3-clause
13
/* * CDDL HEADER START * * 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 usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Portions Copyright (c) 2008-2009 Stacey Son <[email protected]> * * $FreeBSD$ * */ /* * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include "opt_kdtrace.h" #include <sys/cdefs.h> #include <sys/param.h> #include <sys/systm.h> #include <sys/conf.h> #include <sys/kernel.h> #include <sys/limits.h> #include <sys/lock.h> #include <sys/linker.h> #include <sys/module.h> #include <sys/mutex.h> #include <sys/dtrace.h> #include <sys/lockstat.h> #if defined(__i386__) || defined(__amd64__) || \ defined(__mips__) || defined(__powerpc__) #define LOCKSTAT_AFRAMES 1 #else #error "architecture not supported" #endif static d_open_t lockstat_open; static void lockstat_provide(void *, dtrace_probedesc_t *); static void lockstat_destroy(void *, dtrace_id_t, void *); static void lockstat_enable(void *, dtrace_id_t, void *); static void lockstat_disable(void *, dtrace_id_t, void *); static void lockstat_load(void *); static int lockstat_unload(void); typedef struct lockstat_probe { char *lsp_func; char *lsp_name; int lsp_probe; dtrace_id_t lsp_id; #ifdef __FreeBSD__ int lsp_frame; #endif } lockstat_probe_t; #ifdef __FreeBSD__ lockstat_probe_t lockstat_probes[] = { /* Spin Locks */ { LS_MTX_SPIN_LOCK, LSS_ACQUIRE, LS_MTX_SPIN_LOCK_ACQUIRE, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_MTX_SPIN_LOCK, LSS_SPIN, LS_MTX_SPIN_LOCK_SPIN, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_MTX_SPIN_UNLOCK, LSS_RELEASE, LS_MTX_SPIN_UNLOCK_RELEASE, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, /* Adaptive Locks */ { LS_MTX_LOCK, LSA_ACQUIRE, LS_MTX_LOCK_ACQUIRE, DTRACE_IDNONE, (LOCKSTAT_AFRAMES + 1) }, { LS_MTX_LOCK, LSA_BLOCK, LS_MTX_LOCK_BLOCK, DTRACE_IDNONE, (LOCKSTAT_AFRAMES + 1) }, { LS_MTX_LOCK, LSA_SPIN, LS_MTX_LOCK_SPIN, DTRACE_IDNONE, (LOCKSTAT_AFRAMES + 1) }, { LS_MTX_UNLOCK, LSA_RELEASE, LS_MTX_UNLOCK_RELEASE, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_MTX_TRYLOCK, LSA_ACQUIRE, LS_MTX_TRYLOCK_ACQUIRE, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, /* Reader/Writer Locks */ { LS_RW_RLOCK, LSR_ACQUIRE, LS_RW_RLOCK_ACQUIRE, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_RW_RLOCK, LSR_BLOCK, LS_RW_RLOCK_BLOCK, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_RW_RLOCK, LSR_SPIN, LS_RW_RLOCK_SPIN, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_RW_RUNLOCK, LSR_RELEASE, LS_RW_RUNLOCK_RELEASE, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_RW_WLOCK, LSR_ACQUIRE, LS_RW_WLOCK_ACQUIRE, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_RW_WLOCK, LSR_BLOCK, LS_RW_WLOCK_BLOCK, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_RW_WLOCK, LSR_SPIN, LS_RW_WLOCK_SPIN, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_RW_WUNLOCK, LSR_RELEASE, LS_RW_WUNLOCK_RELEASE, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_RW_TRYUPGRADE, LSR_UPGRADE, LS_RW_TRYUPGRADE_UPGRADE, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_RW_DOWNGRADE, LSR_DOWNGRADE, LS_RW_DOWNGRADE_DOWNGRADE, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, /* Shared/Exclusive Locks */ { LS_SX_SLOCK, LSX_ACQUIRE, LS_SX_SLOCK_ACQUIRE, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_SX_SLOCK, LSX_BLOCK, LS_SX_SLOCK_BLOCK, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_SX_SLOCK, LSX_SPIN, LS_SX_SLOCK_SPIN, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_SX_SUNLOCK, LSX_RELEASE, LS_SX_SUNLOCK_RELEASE, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_SX_XLOCK, LSX_ACQUIRE, LS_SX_XLOCK_ACQUIRE, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_SX_XLOCK, LSX_BLOCK, LS_SX_XLOCK_BLOCK, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_SX_XLOCK, LSX_SPIN, LS_SX_XLOCK_SPIN, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_SX_XUNLOCK, LSX_RELEASE, LS_SX_XUNLOCK_RELEASE, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_SX_TRYUPGRADE, LSX_UPGRADE, LS_SX_TRYUPGRADE_UPGRADE, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { LS_SX_DOWNGRADE, LSX_DOWNGRADE, LS_SX_DOWNGRADE_DOWNGRADE, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, /* Thread Locks */ { LS_THREAD_LOCK, LST_SPIN, LS_THREAD_LOCK_SPIN, DTRACE_IDNONE, LOCKSTAT_AFRAMES }, { NULL } }; #else #error "OS not supported" #endif static struct cdevsw lockstat_cdevsw = { .d_version = D_VERSION, .d_open = lockstat_open, .d_name = "lockstat", }; static struct cdev *lockstat_cdev; static dtrace_provider_id_t lockstat_id; /*ARGSUSED*/ static void lockstat_enable(void *arg, dtrace_id_t id, void *parg) { lockstat_probe_t *probe = parg; ASSERT(!lockstat_probemap[probe->lsp_probe]); lockstat_enabled++; lockstat_probemap[probe->lsp_probe] = id; #ifdef DOODAD membar_producer(); #endif lockstat_probe_func = dtrace_probe; #ifdef DOODAD membar_producer(); lockstat_hot_patch(); membar_producer(); #endif } /*ARGSUSED*/ static void lockstat_disable(void *arg, dtrace_id_t id, void *parg) { lockstat_probe_t *probe = parg; int i; ASSERT(lockstat_probemap[probe->lsp_probe]); lockstat_enabled--; lockstat_probemap[probe->lsp_probe] = 0; #ifdef DOODAD lockstat_hot_patch(); membar_producer(); #endif /* * See if we have any probes left enabled. */ for (i = 0; i < LS_NPROBES; i++) { if (lockstat_probemap[i]) { /* * This probe is still enabled. We don't need to deal * with waiting for all threads to be out of the * lockstat critical sections; just return. */ return; } } } /*ARGSUSED*/ static int lockstat_open(struct cdev *dev __unused, int oflags __unused, int devtype __unused, struct thread *td __unused) { return (0); } /*ARGSUSED*/ static void lockstat_provide(void *arg, dtrace_probedesc_t *desc) { int i = 0; for (i = 0; lockstat_probes[i].lsp_func != NULL; i++) { lockstat_probe_t *probe = &lockstat_probes[i]; if (dtrace_probe_lookup(lockstat_id, "kernel", probe->lsp_func, probe->lsp_name) != 0) continue; ASSERT(!probe->lsp_id); #ifdef __FreeBSD__ probe->lsp_id = dtrace_probe_create(lockstat_id, "kernel", probe->lsp_func, probe->lsp_name, probe->lsp_frame, probe); #else probe->lsp_id = dtrace_probe_create(lockstat_id, "kernel", probe->lsp_func, probe->lsp_name, LOCKSTAT_AFRAMES, probe); #endif } } /*ARGSUSED*/ static void lockstat_destroy(void *arg, dtrace_id_t id, void *parg) { lockstat_probe_t *probe = parg; ASSERT(!lockstat_probemap[probe->lsp_probe]); probe->lsp_id = 0; } static dtrace_pattr_t lockstat_attr = { { DTRACE_STABILITY_EVOLVING, DTRACE_STABILITY_EVOLVING, DTRACE_CLASS_COMMON }, { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN }, { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN }, { DTRACE_STABILITY_EVOLVING, DTRACE_STABILITY_EVOLVING, DTRACE_CLASS_COMMON }, { DTRACE_STABILITY_EVOLVING, DTRACE_STABILITY_EVOLVING, DTRACE_CLASS_COMMON }, }; static dtrace_pops_t lockstat_pops = { lockstat_provide, NULL, lockstat_enable, lockstat_disable, NULL, NULL, NULL, NULL, NULL, lockstat_destroy }; static void lockstat_load(void *dummy) { /* Create the /dev/dtrace/lockstat entry. */ lockstat_cdev = make_dev(&lockstat_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600, "dtrace/lockstat"); if (dtrace_register("lockstat", &lockstat_attr, DTRACE_PRIV_USER, NULL, &lockstat_pops, NULL, &lockstat_id) != 0) return; } static int lockstat_unload() { int error = 0; if ((error = dtrace_unregister(lockstat_id)) != 0) return (error); destroy_dev(lockstat_cdev); return (error); } /* ARGSUSED */ static int lockstat_modevent(module_t mod __unused, int type, void *data __unused) { int error = 0; switch (type) { case MOD_LOAD: break; case MOD_UNLOAD: break; case MOD_SHUTDOWN: break; default: error = EOPNOTSUPP; break; } return (error); } SYSINIT(lockstat_load, SI_SUB_DTRACE_PROVIDER, SI_ORDER_ANY, lockstat_load, NULL); SYSUNINIT(lockstat_unload, SI_SUB_DTRACE_PROVIDER, SI_ORDER_ANY, lockstat_unload, NULL); DEV_MODULE(lockstat, lockstat_modevent, NULL); MODULE_VERSION(lockstat, 1); MODULE_DEPEND(lockstat, dtrace, 1, 1, 1); MODULE_DEPEND(lockstat, opensolaris, 1, 1, 1);
jrobhoward/SCADAbase
sys/cddl/dev/lockstat/lockstat.c
C
bsd-3-clause
8,829
<?php namespace xp\runtime; /** * Wrap code passed in from the command line. * * @see https://wiki.php.net/rfc/group_use_declarations * @test xp://net.xp_framework.unittest.runtime.CodeTest */ class Code { private $fragment, $imports; /** * Creates a new code instance * * @param string $input */ public function __construct($input) { // Shebang if (0 === strncmp($input, '#!', 2)) { $input= substr($input, strcspn($input, "\n") + 1); } // PHP open tags if (0 === strncmp($input, '<?', 2)) { $input= substr($input, strcspn($input, "\r\n\t =") + 1); } $this->fragment= trim($input, "\r\n\t ;").';'; $this->imports= []; while (0 === strncmp($this->fragment, 'use ', 4)) { $delim= strpos($this->fragment, ';'); foreach ($this->importsIn(substr($this->fragment, 4, $delim - 4)) as $import) { $this->imports[]= $import; } $this->fragment= ltrim(substr($this->fragment, $delim + 1), ' '); } } /** @return string */ public function fragment() { return $this->fragment; } /** @return string */ public function expression() { return strstr($this->fragment, 'return ') || strstr($this->fragment, 'return;') ? $this->fragment : 'return '.$this->fragment ; } /** @return string[] */ public function imports() { return $this->imports; } /** @return string */ public function head() { return empty($this->imports) ? '' : 'use '.implode(', ', $this->imports).';'; } /** * Returns types used inside a `use ...` directive. * * @param string $use * @return string[] */ private function importsIn($use) { $name= strrpos($use, '\\') + 1; $used= []; if ('{' === $use{$name}) { $namespace= substr($use, 0, $name); foreach (explode(',', substr($use, $name + 1, -1)) as $type) { $used[]= $namespace.trim($type); } } else { foreach (explode(',', $use) as $type) { $used[]= trim($type); } } return $used; } }
johannes85/core
src/main/php/xp/runtime/Code.class.php
PHP
bsd-3-clause
2,041
#!/usr/bin/python # Copyright (c) 2009, Purdue University # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright notice, this # list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # Neither the name of the Purdue University nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Test for Credential cache library.""" __copyright__ = 'Copyright (C) 2009, Purdue University' __license__ = 'BSD' __version__ = '#TRUNK#' import unittest import os import roster_core from roster_server import credentials CONFIG_FILE = 'test_data/roster.conf' # Example in test_data SCHEMA_FILE = '../roster-core/data/database_schema.sql' DATA_FILE = 'test_data/test_data.sql' class TestCredentialsLibrary(unittest.TestCase): def setUp(self): self.config_instance = roster_core.Config(file_name=CONFIG_FILE) self.cred_instance = credentials.CredCache(self.config_instance, u'sharrell') db_instance = self.config_instance.GetDb() db_instance.CreateRosterDatabase() data = open(DATA_FILE, 'r').read() db_instance.StartTransaction() db_instance.cursor.execute(data) db_instance.EndTransaction() db_instance.close() self.core_instance = roster_core.Core(u'sharrell', self.config_instance) def is_valid_uuid (self, uuid): """ TAKEN FROM THE BLUEZ MODULE is_valid_uuid (uuid) -> bool returns True if uuid is a valid 128-bit UUID. valid UUIDs are always strings taking one of the following forms: XXXX XXXXXXXX XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX where each X is a hexadecimal digit (case insensitive) """ try: if len (uuid) == 4: if int (uuid, 16) < 0: return False elif len (uuid) == 8: if int (uuid, 16) < 0: return False elif len (uuid) == 36: pieces = uuid.split ("-") if len (pieces) != 5 or \ len (pieces[0]) != 8 or \ len (pieces[1]) != 4 or \ len (pieces[2]) != 4 or \ len (pieces[3]) != 4 or \ len (pieces[4]) != 12: return False [ int (p, 16) for p in pieces ] else: return False except ValueError: return False except TypeError: return False return True def testCredentials(self): self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test')) cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test', self.core_instance) self.assertEqual(self.cred_instance.CheckCredential(cred_string, u'sharrell', self.core_instance), u'') self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell', self.core_instance), None) if( __name__ == '__main__' ): unittest.main()
stephenlienharrell/roster-dns-management
test/credentials_test.py
Python
bsd-3-clause
4,275
#!/usr/bin/env python import sys import hyperdex.client from hyperdex.client import LessEqual, GreaterEqual, Range, Regex, LengthEquals, LengthLessEqual, LengthGreaterEqual c = hyperdex.client.Client(sys.argv[1], int(sys.argv[2])) def to_objectset(xs): return set([frozenset(x.items()) for x in xs]) assert c.put('kv', 'k', {}) == True assert c.get('kv', 'k') == {'v': {}} assert c.put('kv', 'k', {'v': {1: 3.14, 2: 0.25, 3: 1.0}}) == True assert c.get('kv', 'k') == {'v': {1: 3.14, 2: 0.25, 3: 1.0}} assert c.put('kv', 'k', {'v': {}}) == True assert c.get('kv', 'k') == {'v': {}}
hyc/HyperDex
test/python/DataTypeMapIntFloat.py
Python
bsd-3-clause
585
<?php namespace yiicms\components\core; # Websun template parser, version 0.1.80 # http://webew.ru/articles/3609.webew /* 0.1.80 - allowed_extensions option implemented 0.1.71 - replaced too new array declaration [] with array() - keeping PHP 5.3 compatibility 0.1.70 - added :^N and :^i 0.1.60 - __construct() accepts an array as of now (wrapping function accepts distinct variables still) - "no_global_variables" setting implemented 0.1.55 - fixed misbehavior of functions' args parsing when dealing with comma inside of double quotes like @function(*var*, "string,string") По поводу массивов в JSON-нотации в качестве скалярных величин: // 1. Как *var* вытащить из json_decode? // Сначала *var* => json_encode(*var*, 1) // (это будет голый массив данных; не-data-свойства потеряются) // 2. Как указывать кодировку (json_decode только в UTF-8), // $WEBSUN_CHARSET? // 2а) Как вообще избавиться от %u0441 вместо кириллицы? // возможно только для UTF-8 или избирательно 1251, // т.к. нужно ловить буквы и делать им кодирование в %uXXXX // Всё это будет очень долго, особенно если это проводить // для каждой переменной // (хотя там можно поставить костыль на [ и { - // если не встретили в начале, то обрабатываем как обычно) 0.1.54 - $WEBSUN_ALLOWED_CALLBACKS instead of $WEBSUN_VISIBLES 0.1.53 - list of visible functions as a global variable for all versions (for a while - see v. 0.1.51) 0.1.53(beta) - added trim() at the beginning get_var_or_string() 0.1.52(beta) - using is_numeric() when parsing ifs (opposite to v.0.1.17) 0.1.51(beta) - list of visible functions added (draft) prior to PHP 5.6 - as a global array variable PHP 5.6 and higher - as a namespace 0.1.50 - fixed default paths handling (see __construct() ) 0.1.49 - added preg_quote() in parse_cycle() for searching array's name 0.1.48 - $ can be used in templates_root direcory path (^ makes no sense, because it means templates_root path itself) 0.1.47 - called back the possibility of spaces before variables, because it makes parsing of cycles harder: instead of [*|&..]array: we must catch [*|&..]\s*array, which (according to one of the tests) works ~10% slower; simple (non-cycle) variables and constants (literally how it is described in comment to previous version) can still work - this unofficial possibility will be left 0.1.46 - spaces can be like {?* a = b *}, {?* a > b *} (especially convenient when using constants: {?*a = =CONST*}) 0.1.45 - now spaces can be around &, | and variable names in ifs 0.1.44 - loosen parse_cycle() regexp to accept arrays with non-alphanumeric keys (for example, it may occur handy to use some non-latin string as a key), now {%* anything here *} is accepted. Note: except of dots in "anything", which are still interpreted as key separators. 0.1.43 - some fixes in profiling: parse_template's time is not added to total instead of this, total time is calculated as a time of highest level parse_template run Note: profiling by itself may increase total run time up to 60% 0.1.42 - loosen regexp at check_if_condition_part() from [$=]?[\w.\^]*+ to [^*=<>]*+ now any variable name can be used in ifs, not just alphanumeric; such loose behaviour looks more flexible and parallels var_value() algorithm (which can interpret any variable name except of with dots) 0.1.41 - fixed find_and_parse_cycle(): "array_name:" prefixed with & is also catched (required for ifs like {?*array:key1&array:key2*}) 0.1.40 - fixed error in check_if_condition_part() (pattern) 0.1.39 - fixed error in check_if_condition_part() (forgotten vars like array^COUNT>1 etc.) 0.1.38 - fixed error in if alternatives (see 0.1.37) introduced check_if_condition_part() method added possibility of "AND", not just "OR" in if alternatives: {?*var_1="one"|var_2="two"*} it is OR {*var_1="one"|var_2="two"*?} {?*var_1="one"&var_2="two"*} it is AND {*var_1="one"&var_2="two"*?} Fixed profiling! Now any profiling information is passed to the higher level - otherwise (as it previously was) each object instance (i.e. each call of nested template or module) produced it's own and private timesheet. 0.1.37 - fixes in var_value(): parsing of | (if alternatives) now goes before parsing of strings ("..") so things like {?*var_1="one"|var_2="two"*} ... {*var_1="one"|var_2="two"*?} are possible (but things like {?*var="one|two"*} are not) 0.1.36 - correct string literals parsing - var_value() fix (important when passed to module) 0.1.35 - two literals comparison is accepted in if's now (previously only variable was allowed at the left) Needed to do so because of :^KEY parsing - those are converted to literals BEFORE ifs are processed Substituted ("[^"*][\w.:$|\^]*+) subpattern with the ("[^"*]+"|[\w.:$|\^]*+) one 0.1.34 - fixed surpassing variables to child templates (now {* + *var1|var2* | *tpl1|tpl2* *} works) 0.1.33 - fixed parse_if (now {?*var1|var2*}..{*var1|var2*?} works) 0.1.32 - fixed getting template name from variable (now variable can be like {*var1|var2|"string"*} as everywhere else) 0.1.31 - fixed /r/n deletion from the end of the pattern 0.1.30 - fixed parse_cycle() function: regexp now catches {* *%array:subarray* | ... *} (previously missed it) 0.1.29 - fixed a misprint 0.1.28 - A bunch of little fixes. Added profiling mode (experimental for a while so not recommended to use hardly). Regexp for ifs speeded up by substituting loose [^<>=]* with strict [\w.:$\^]*+ (boosted the usecase about 100 times) In parse_cycle - also ([\w$.]*) instead of ([-\w$.]*) (don't remember, what "-" was for). Constants are now handled in var_value (with all other stuff like ^COUNT etc.) instead of in get_var_or_string(). 0.1.27 - "alt" version is main now added {* + *some* | >{*var*} *} - templates right inside of the var 0.1.26 - fixed some things with $matches dealing in parsee_if 0.1.25 - version suffix changed "beta" (b) to "alternative" (alt) 0.1.25 - fixed replacement of array:foo - Now it is more strict and occurs if only symbols *=<>| precede array:foo ( =<> - for {*array:foo_1>array:foo_2*}, | - for {*array:foo_1|array:foo_2*}, * - for just {*array:foo*} ) 0.1.24 - (beta) rewriting regexps with no named subpatterns for compatibility with old PHP versions (PCRE documentation is unclear and issues like new PHP and no support of named subpatterns occur) EXCEPT pattern for addvars method 0.1.23 - fixed ^KEY parsing a little (removed preg_quote and fixed regexp) 0.1.22 - now not only *array:foo* (and *array:^KEY*) is caught, but array:foo and array:^KEY as well Needed it because otherwise if clauses like {*array:a|array:b*} are not parsed. This required substitution of str_replace with with preg_replace which had no visible affect on perfomance. 0.1.21 - fixed some in var_value() (substr sometimes returns FALSE not empty string) everything is mb* now 0.1.20 - fixed trimming \r\n at the end of the template 0.1.19 - websun_parse_template_path() fixed to set current templates directory to the one of template specified 0.1.18 - KEY added 0.1.17 - fixed some in var_value() теперь по умолчанию корневой каталог шаблона - тот, в котором выполняется вызвавший функцию скрипт добавлены ^COUNT (0.1.13) добавлены if'ы: {*var_1|var_2|"строка"|1234(число)*} в if'ах добавлено сравнение с переменными: {?*a>b*}..{*a>b?*} {?*a>"строка"*}..{*a>"строка"*?} {?*a>3*}..{*a>3*?} */ class websun { public $vars; public $templates_root_dir; // templates_root_dir указывать без закрывающего слэша! public $templates_current_dir; public $TIMES; public $no_global_vars; private $profiling; private $predecessor; // объект шаблонизатора верхнего уровня, из которого делался вызов текущего function __construct($options) { // $options - ассоциативный массив с ключами: // - data - данные // - templates_root - корневой каталог шаблонизатора // - predecessor - объект-родитель (из которого вызывается дочерний) // - allowed_extensions - список разрешенных расширений шаблонов (по умолчанию: *.tpl, *.html, *.css, *.js) // - no_global_vars - разрешать ли использовать в шаблонах переменные глобальной области видимости // - profiling - включать ли измерения скорости (пока не до конца отлажено) $this->vars = $options['data']; if (isset($options['templates_root']) AND $options['templates_root']) // корневой каталог шаблонов { $this->templates_root_dir = $this->template_real_path($options['templates_root']); } else { // если не указан, то принимается каталог файла, в котором вызван websun // С 0.50 - НЕ getcwd()! Т.к. текущий каталог - тот, откуда он запускается, // $this->templates_root_dir = getcwd(); foreach (debug_backtrace() as $trace) { if (preg_match('/^websun_parse_template/', $trace['function'])) { $this->templates_root_dir = dirname($trace['file']); break; } } if (!$this->templates_root_dir) { foreach (debug_backtrace() as $trace) { if ($trace['class'] == 'websun') { $this->templates_root_dir = dirname($trace['file']); break; } } } } $this->templates_current_dir = $this->templates_root_dir . '/'; $this->predecessor = (isset($options['predecessor']) ? $options['predecessor'] : false); $this->allowed_extensions = (isset($options['allowed_extensions'])) ? $options['allowed_extensions'] : ['tpl', 'html', 'css', 'js']; $this->no_global_vars = (isset($options['no_global_vars']) ? $options['no_global_vars'] : false); $this->profiling = (isset($options['profiling']) ? $options['profiling'] : false); } function parse_template($template) { if ($this->profiling) { $start = microtime(1); } $template = preg_replace('/ \\/\* (.*?) \*\\/ /sx', '', $template); /**ПЕРЕПИСАТЬ ПО JEFFREY FRIEDL'У !!!**/ $template = str_replace('\\\\', "\x01", $template); // убираем двойные слэши $template = str_replace('\*', "\x02", $template); // и экранированные звездочки // С 0.1.51 отключили // $template = preg_replace_callback( // дописывающие модули // '/ // {\* // &(\w+) // (?P<args>\([^*]*\))? // \*} // /x', // array($this, 'addvars'), // $template // ); $template = $this->find_and_parse_cycle($template); $template = $this->find_and_parse_if($template); $template = preg_replace_callback( // переменные, шаблоны и модули '/ {\* (.*?) \*} /x', /* подумать о том, чтобы вместо (.*?) использовать жадное, но более строгое ( (?: [^*]*+ | \*(?!}) )+ ) */ [$this, 'parse_vars_templates_functions'], $template ); $template = str_replace("\x01", '\\\\', $template); // возвращаем двойные слэши обратно $template = str_replace("\x02", '*', $template); // а звездочки - уже без экранирования if ($this->profiling AND !$this->predecessor) { $this->TIMES['_TOTAL'] = round(microtime(1) - $start, 4) . " s"; // ksort($this->TIMES); echo '<pre>' . print_r($this->TIMES, 1) . '</pre>'; } return $template; } // // дописывание массива переменных из шаблона // // (хак для Бурцева) // 0.1.51 - убрали; все равно Бурцев не пользуется // function addvars($matches) { // // if ($this->profiling) // // // $start = microtime(1); // // // // $module_name = 'module_'.$matches[1]; // // # ДОБАВИТЬ КЛАССЫ ПОТОМ // // $args = (isset($matches['args'])) // // // ? explode(',', mb_substr($matches['args'], 1, -1) ) // убираем скобки // // // : array(); // // $this->vars = array_merge( // // // $this->vars, // // // call_user_func_array($module_name, $args) // // // ); // call_user_func_array быстрее, чем call_user_func // // // // if ($this->profiling) // // // $this->write_time(__FUNCTION__, $start, microtime(1)); // // // // return TRUE; // } function var_value($string) { if ($this->profiling) { $start = microtime(1); } if (mb_substr($string, 0, 1) == '=') { # константа $C = mb_substr($string, 1); $out = (defined($C)) ? constant($C) : ''; } // можно делать if'ы: // {*var_1|var_2|"строка"|134*} // сработает первая часть, которая TRUE elseif (mb_strpos($string, '|') !== false) { $f = __FUNCTION__; foreach (explode('|', $string) as $str) { // останавливаемся при первом же TRUE if ($val = $this->$f($str)) { break; } } $out = $val; } elseif ( # скалярная величина mb_substr($string, 0, 1) == '"' AND mb_substr($string, -1) == '"' ) { $out = mb_substr($string, 1, -1); } elseif (is_numeric($string)) { $out = $string; } else { if (mb_substr($string, 0, 1) == '$') { // глобальная переменная if (!$this->no_global_vars) { $string = mb_substr($string, 1); $value = $GLOBALS; } else { $value = ''; } } else { $value = $this->vars; } // допустимы выражения типа {*var^COUNT*} // (вернет count($var)) ) if (mb_substr($string, -6) == '^COUNT') { $string = mb_substr($string, 0, -6); $return_mode = 'count'; } else { $return_mode = false; } // default $rawkeys = explode('.', $string); $keys = []; foreach ($rawkeys as $v) { if ($v !== '') { $keys[] = $v; } } // array_filter() использовать не получается, // т.к. числовой индекс 0 она тоже считает за FALSE и убирает // поэтому нужно сравнение с учетом типа // пустая строка указывает на корневой массив foreach ($keys as $k) { if (is_array($value) AND isset($value[$k])) { $value = $value[$k]; } elseif (is_object($value)) { try { $value = $value->$k; } catch (\Exception $e) { $value = null; break; } } else { $value = null; break; } } // в зависимости от $return_mode действуем по-разному: $out = (!$return_mode) // возвращаем значение переменной (обычный случай) ? $value // возвращаем число элементов в массиве : (is_array($value) ? count($value) : false); } if ($this->profiling) { $this->write_time(__FUNCTION__, $start, microtime(1)); } return $out; } function find_and_parse_cycle($template) { if ($this->profiling) { $start = microtime(1); } // пришлось делать специальную функцию, чтобы реализовать рекурсию $out = preg_replace_callback( '/ {%\* ([^*]*) \*} (.*?) {\* \1 \*%} /sx', [$this, 'parse_cycle'], $template ); if ($this->profiling) { $this->write_time(__FUNCTION__, $start, microtime(1)); } return $out; } function parse_cycle($matches) { if ($this->profiling) { $start = microtime(1); } $array_name = $matches[1]; $array = $this->var_value($array_name); $array_name_quoted = preg_quote($array_name); if (!is_array($array)) { return false; } $parsed = ''; $dot = ($array_name != '' AND $array_name != '$') ? '.' : ''; $i = 0; $n = 1; foreach ($array as $key => $value) { $parsed .= preg_replace( [// массив поиска "/(?<=[*=<>|&%])\s*$array_name_quoted\:\^KEY\b/", "/(?<=[*=<>|&%])\s*$array_name_quoted\:\^i\b/", "/(?<=[*=<>|&%])\s*$array_name_quoted\:\^N\b/", "/(?<=[*=<>|&%])\s*$array_name_quoted\:/" ], [// массив замены '"' . $key . '"', // preg_quote для ключей нельзя, '"' . $i . '"', '"' . $n . '"', $array_name . $dot . $key . '.' // т.к. в них бывает удобно ], // хранить некоторые данные, $matches[2] // а preg_quote слишком многое экранирует ); $i++; $n++; } $parsed = $this->find_and_parse_cycle($parsed); if ($this->profiling) { $this->write_time(__FUNCTION__, $start, microtime(1)); } return $parsed; } function find_and_parse_if($template) { if ($this->profiling) { $start = microtime(1); } $out = preg_replace_callback( '/ { (\?\!?) \*([^*]*)\* } # открывающее условие (.*?) # тело if {\*\2\* \1} # закрывающее условие /sx', [$this, 'parse_if'], $template ); if ($this->profiling) { $this->write_time(__FUNCTION__, $start, microtime(1)); } return $out; } function parse_if($matches) { // 1 - ? или ?! // 2 - тело условия // 3 - тело if if ($this->profiling) { $start = microtime(1); } $final_check = false; $separator = (strpos($matches[2], '&')) ? '&' // "AND" : '|'; // "OR" $parts = explode($separator, $matches[2]); $parts = array_map('trim', $parts); // убираем пробелы по краям $checks = []; foreach ($parts as $p) { $checks[] = $this->check_if_condition_part($p); } if ($separator == '|') // режим "OR" { $final_check = in_array(true, $checks); } else // режим "AND" { $final_check = !in_array(false, $checks); } $result = ($matches[1] == '?') ? $final_check : !$final_check; $parsed_if = ($result) ? $this->find_and_parse_if($matches[3]) : ''; if ($this->profiling) { $this->write_time(__FUNCTION__, $start, microtime(1)); } return $parsed_if; } function check_if_condition_part($str) { if ($this->profiling) { $start = microtime(1); } preg_match( '/^ ( "[^"*]+" # строковый литерал | # или [^*<>=]*+ # имя переменной ) (?: # если есть сравнение с чем-то: ([=<>]) # знак сравнения \s* (.*) # то, с чем сравнивают )? $ /x', $str, $matches ); $left = $this->var_value(trim($matches[1])); if (!isset($matches[2])) { $check = ($left == true); } else { $right = (isset($matches[3])) ? $this->var_value($matches[3]) : false; switch ($matches[2]) { case '=': $check = ($left == $right); break; case '>': $check = ($left > $right); break; case '<': $check = ($left < $right); break; default: $check = ($left == true); } } if ($this->profiling) { $this->write_time(__FUNCTION__, $start, microtime(1)); } return $check; } function parse_vars_templates_functions($matches) { if ($this->profiling) { $start = microtime(1); } // тут обрабатываем сразу всё - и переменные, и шаблоны, и модули $work = $matches[1]; $work = trim($work); // убираем пробелы по краям if (mb_substr($work, 0, 1) == '@') { // модуль {* @name(arg1,arg2) | template *} $p = '/ ^ ([^(|]++) # 1 - имя модуля (?: \( ([^)]*+) \) \s* )? # 2 - аргументы (?: \| \s* (.*+) )? # 3 - это уже до конца $ # (именно .*+, а не .++) /x'; if (preg_match($p, mb_substr($work, 1), $m)) { $function_name = $this->get_var_or_string($m[1]); // С версии 0.1.51 - проверяем по специальному списку // if (PHP_VERSION_ID / 100 > 506) { // это включим позже, получим PHP 5.6 // $list = - тут ссылка на константу из namespace // else global $WEBSUN_ALLOWED_CALLBACKS; $list = $WEBSUN_ALLOWED_CALLBACKS; // } if ($list and in_array($function_name, $list)) { $allowed = true; } else { $allowed = false; trigger_error("<b>$function_name()</b> is not in the list of allowed callbacks.", E_USER_WARNING); } if ($allowed) { $args = []; if (isset($m[2])) { preg_match_all('/[^",]+|"[^"]*"/', $m[2], $tmp); if ($tmp) { // от промежутков между аргументами и запятыми останутся пробелы; их надо убрать $tmp = array_filter(array_map('trim', $tmp[0])); $args = array_map([$this, 'get_var_or_string'], $tmp); } unset($tmp); } $subvars = call_user_func_array($function_name, $args); // print_r(array_map( array($this, 'get_var_or_string'), explode(',', $m[2]) )); exit; if (isset($m[3])) // передали указание на шаблон { $html = $this->call_template($m[3], $subvars); } else { $html = $subvars; } // шаблон не указан => модуль возвращает строку } else { $html = ''; } } else { $html = ''; } // вызов модуля сделан некорректно } elseif (mb_substr($work, 0, 1) == '+') { // шаблон - {* +*vars_var*|*tpl_var* *} // переменная как шаблон - {* +*var* | >*template_inside* *} $html = ''; $parts = preg_split( '/(?<=[\*\s])\|(?=[\*\s])/', // вертикальная черта mb_substr($work, 1) // должна ловиться только как разделитель // между переменной и шаблоном, но не должна ловиться // как разделитель внутри нотации переменой или шаблона // (например, {* + *var1|$GLOBAL* | *tpl1|tpl2* *} ); $parts = array_map('trim', $parts); // убираем пробелы по краям if (!isset($parts[1])) { // если нет разделителя (|) - значит, // передали только имя шаблона +template $html = $this->call_template($parts[0], $this->vars); } else { $varname_string = mb_substr($parts[0], 1, -1); // убираем звездочки // {* +*vars* | шаблон *} - простая передача переменной шаблону // {* +*?vars* | шаблон *} - подключение шаблона только в случае, если vars == TRUE // {* +*%vars* | шаблон *} - подключение шаблона не для самого vars, а для каждого его дочернего элемента $indicator = mb_substr($varname_string, 0, 1); if ($indicator == '?') { if ($subvars = $this->var_value(mb_substr($varname_string, 1))) // 0.1.27 $html = $this->parse_child_template($tplname, $subvars); { $html = $this->call_template($parts[1], $subvars); } } elseif ($indicator == '%') { if ($subvars = $this->var_value(mb_substr($varname_string, 1))) { foreach ($subvars as $row) { // 0.1.27 $html .= $this->parse_child_template($tplname, $row); $html .= $this->call_template($parts[1], $row); } } } else { $subvars = $this->var_value($varname_string); // 0.1.27 $html = $this->parse_child_template($tplname, $subvars); $html = $this->call_template($parts[1], $subvars); } } } else { $html = $this->var_value($work); } // переменная (+ константы - тут же) if ($this->profiling) { $this->write_time(__FUNCTION__, $start, microtime(1)); } return $html; } function call_template($template_notation, $vars) { if ($this->profiling) { $start = microtime(1); } // $template_notation - либо путь к шаблону, // либо переменная, содержащая путь к шаблону, // либо шаблон прямо в переменной - если >*var* $c = __CLASS__; // нужен объект этого же класса - делаем $subobject = new $c([ 'data' => $vars, 'templates_root' => $this->templates_root_dir, 'predecessor' => $this, 'no_global_vars' => $this->no_global_vars, 'profiling' => $this->profiling, ]); $template_notation = trim($template_notation); if (mb_substr($template_notation, 0, 1) == '>') { // шаблон прямо в переменной $v = mb_substr($template_notation, 1); $subtemplate = $this->get_var_or_string($v); $subobject->templates_current_dir = $this->templates_current_dir; } else { $path = $this->get_var_or_string($template_notation); $subobject->templates_current_dir = pathinfo($this->template_real_path($path), PATHINFO_DIRNAME) . '/'; $subtemplate = $this->get_template($path); } $result = $subobject->parse_template($subtemplate); if ($this->profiling) { $this->write_time(__FUNCTION__, $start, microtime(1)); } return $result; } function get_var_or_string($str) { // используется, в основном, // для получения имён шаблонов и модулей $str = trim($str); if ($this->profiling) { $start = microtime(1); } if (mb_substr($str, 0, 1) == '*' AND mb_substr($str, -1) == '*') { $out = $this->var_value(mb_substr($str, 1, -1)); } // если вокруг есть звездочки - значит, перменная else // нет звездочек - значит, обычная строка-литерал { $out = (mb_substr($str, 0, 1) == '"' AND mb_substr($str, -1) == '"') // строка ? mb_substr($str, 1, -1) : $str; } if ($this->profiling) { $this->write_time(__FUNCTION__, $start, microtime(1)); } return $out; } function get_template($tpl) { if ($this->profiling) { $start = microtime(1); } if (!$tpl) { return false; } $tpl_real_path = $this->template_real_path($tpl); $ext = pathinfo($tpl_real_path, PATHINFO_EXTENSION); if (!in_array($ext, $this->allowed_extensions)) { trigger_error( "Template's <b>$tpl_real_path</b> extension is not in the allowed list (" . implode(", ", $this->allowed_extensions) . "). Check <b>allowed_extensions</b> option.", E_USER_WARNING ); return ''; } // return rtrim(file_get_contents($tpl_real_path), "\r\n"); // (убираем перенос строки, присутствующий в конце любого файла) $out = preg_replace( '/\r?\n$/', '', file_get_contents($tpl_real_path) ); if ($this->profiling) { $this->write_time(__FUNCTION__, $start, microtime(1)); } return $out; } function template_real_path($tpl) { // функция определяет реальный путь к шаблону в файловой системе // первый символ пути к шаблону определяет тип пути // если в начале адреса есть / - интерпретируем как абсолютный путь ФС // если второй символ пути - двоеточие (путь вида C:/ - Windows) - // также интепретируем как абсолютный путь ФС // если есть ^ - отталкиваемся от $templates_root_dir // если $ - от $_SERVER[DOCUMENT_ROOT] // во всех остальных случаях отталкиваемся от каталога текущего шаблона - templates_current_dir if ($this->profiling) { $start = microtime(1); } $dir_indicator = mb_substr($tpl, 0, 1); $adjust_tpl_path = true; if ($dir_indicator == '^') { $dir = $this->templates_root_dir; } elseif ($dir_indicator == '$') { $dir = $_SERVER['DOCUMENT_ROOT']; } elseif ($dir_indicator == '/') { $dir = ''; $adjust_tpl_path = false; } // абсолютный путь для ФС else { if (mb_substr($tpl, 1, 1) == ':') // Windows - указан абсолютный путь - вида С:/... { $dir = ''; } else { $dir = $this->templates_current_dir; } $adjust_tpl_path = false; // в обоих случаях строку к пути менять не надо } if ($adjust_tpl_path) { $tpl = mb_substr($tpl, 1); } $tpl_real_path = $dir . $tpl; if ($this->profiling) { $this->write_time(__FUNCTION__, $start, microtime(1)); } return $tpl_real_path; } function write_time($method, $start, $end) { //echo ($this->predecessor) . '<br>'; if (!$this->predecessor) { $time = &$this->TIMES; } else { $time = &$this->predecessor->TIMES; } if (!isset($time[$method])) { $time[$method] = [ 'n' => 0, 'last' => 0, 'total' => 0, 'avg' => 0 ]; } $time[$method]['n'] += 1; $time[$method]['last'] = round($end - $start, 4); $time[$method]['total'] += $time[$method]['last']; $time[$method]['avg'] = round($time[$method]['total'] / $time[$method]['n'], 4); } } function websun_parse_template_path( $data, $template_path, $templates_root_dir = false, $no_global_vars = false // $profiling = FALSE - пока убрали ) { // функция-обёртка для быстрого вызова класса // принимает шаблон в виде пути к нему $W = new websun([ 'data' => $data, 'templates_root' => $templates_root_dir, 'no_global_vars' => $no_global_vars ]); $tpl = $W->get_template($template_path); $W->templates_current_dir = pathinfo($W->template_real_path($template_path), PATHINFO_DIRNAME) . '/'; $string = $W->parse_template($tpl); return $string; } function websun_parse_template( $data, $template_code, $templates_root_dir = false, $no_global_vars = false // profiling пока убрали ) { // функция-обёртка для быстрого вызова класса // принимает шаблон непосредственно в виде кода $W = new websun([ 'data' => $data, 'templates_root' => $templates_root_dir, 'no_global_vars' => $no_global_vars ]); $string = $W->parse_template($template_code); return $string; } ?>
muratymt/yiicms
components/core/websun.php
PHP
bsd-3-clause
37,601
/* Since the td elements are the ones that actually get colored, don't bother with the row itself. */ .HighlightMe td { background-color: hsl(36, 100%, 75%) !important; } /* Turn the transparent boxes white */ .HighlightMe .notstarted { background-color: white; }
rsesek/cr-buildbot-highlight
src/highlight-me.css
CSS
bsd-3-clause
271
/*! * speedt * Copyright(c) 2015 speedt <[email protected]> * BSD 3 Licensed */ 'use strict'; var utils = require('speedt-utils'); var Service = function(app){ var self = this; // TODO self.serverId = app.getServerId(); self.connCount = 0; self.loginedCount = 0; self.logined = {}; }; module.exports = Service; var proto = Service.prototype; proto.increaseConnectionCount = function(){ return ++this.connCount; }; proto.decreaseConnectionCount = function(uid){ var self = this; // TODO var result = [--self.connCount]; // TODO if(uid) result.push(removeLoginedUser.call(self, uid)); return result; }; proto.replaceLoginedUser = function(uid, info){ var self = this; // TODO var user = self.logined[uid]; if(user) return updateUserInfo.call(self, user, info); // TODO self.loginedCount++; // TODO info.uid = uid; self.logined[uid] = info; }; var updateUserInfo = function(user, info){ var self = this; // TODO for(var p in info){ if(info.hasOwnProperty(p) && typeof 'function' !== info[p]){ self.logined[user.uid][p] = info[p]; } // END } // END }; var removeLoginedUser = function(uid){ var self = this; // TODO if(!self.logined[uid]) return; // TODO delete self.logined[uid]; // TODO return --self.loginedCount; }; proto.getStatisticsInfo = function(){ var self = this; return { serverId: self.serverId, connCount: self.connCount, loginedCount: self.loginedCount, logined: self.logined }; };
3203317/st
server/lib/common/services/connectionService.js
JavaScript
bsd-3-clause
1,457
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // GCC 5 does not evaluate static assertions dependent on a template parameter. // UNSUPPORTED: gcc-5 // UNSUPPORTED: c++98, c++03 // <string> // Test that hash specializations for <string> require "char_traits<_CharT>" not just any "_Trait". #include <string> template <class _CharT> struct trait // copied from <__string> { typedef _CharT char_type; typedef int int_type; typedef std::streamoff off_type; typedef std::streampos pos_type; typedef std::mbstate_t state_type; static inline void assign(char_type& __c1, const char_type& __c2) { __c1 = __c2; } static inline bool eq(char_type __c1, char_type __c2) { return __c1 == __c2; } static inline bool lt(char_type __c1, char_type __c2) { return __c1 < __c2; } static int compare(const char_type* __s1, const char_type* __s2, size_t __n); static size_t length(const char_type* __s); static const char_type* find(const char_type* __s, size_t __n, const char_type& __a); static char_type* move(char_type* __s1, const char_type* __s2, size_t __n); static char_type* copy(char_type* __s1, const char_type* __s2, size_t __n); static char_type* assign(char_type* __s, size_t __n, char_type __a); static inline int_type not_eof(int_type __c) { return eq_int_type(__c, eof()) ? ~eof() : __c; } static inline char_type to_char_type(int_type __c) { return char_type(__c); } static inline int_type to_int_type(char_type __c) { return int_type(__c); } static inline bool eq_int_type(int_type __c1, int_type __c2) { return __c1 == __c2; } static inline int_type eof() { return int_type(EOF); } }; template <class CharT> void test() { typedef std::basic_string<CharT, trait<CharT> > str_t; std::hash<str_t> h; // expected-error-re 4 {{{{call to implicitly-deleted default constructor of 'std::hash<str_t>'|implicit instantiation of undefined template}} {{.+}}}}}} (void)h; } int main(int, char**) { test<char>(); test<wchar_t>(); test<char16_t>(); test<char32_t>(); return 0; }
endlessm/chromium-browser
third_party/llvm/libcxx/test/std/strings/basic.string.hash/char_type_hash.fail.cpp
C++
bsd-3-clause
2,504
/*========================================================================= Program: Advanced Normalization Tools Module: $RCSfile: itkANTSImageRegistrationOptimizer.h,v $ Language: C++ Date: $Date: 2009/04/22 01:00:17 $ Version: $Revision: 1.44 $ Copyright (c) ConsortiumOfANTS. All rights reserved. See accompanying COPYING.txt or http://sourceforge.net/projects/advants/files/ANTS/ANTSCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __itkANTSImageRegistrationOptimizer_h #define __itkANTSImageRegistrationOptimizer_h #include "itkObject.h" #include "itkObjectFactory.h" #include "itkVectorGaussianInterpolateImageFunction.h" #include "antsCommandLineParser.h" #include "itkShiftScaleImageFilter.h" #include "itkMinimumMaximumImageFilter.h" #include "itkImage.h" #include "itkMacro.h" #include "ReadWriteImage.h" #include "itkCenteredEuler3DTransform.h" #include "itkQuaternionRigidTransform.h" #include "itkANTSAffine3DTransform.h" #include "itkANTSCenteredAffine2DTransform.h" #include "itkCenteredTransformInitializer.h" #include "itkTransformFileReader.h" #include "itkTransformFileWriter.h" #include "itkFiniteDifferenceFunction.h" #include "itkFixedArray.h" #include "itkANTSSimilarityMetric.h" #include "itkVectorExpandImageFilter.h" //#include "itkNeighbohoodAlgorithm.h" #include "itkPDEDeformableRegistrationFilter.h" #include "itkWarpImageFilter.h" #include "itkWarpImageMultiTransformFilter.h" #include "itkDeformationFieldFromMultiTransformFilter.h" #include "itkWarpImageWAffineFilter.h" #include "itkPointSet.h" #include "itkVector.h" #include "itkBSplineScatteredDataPointSetToImageFilter.h" #include "itkGeneralToBSplineDeformationFieldFilter.h" #include "ANTS_affine_registration2.h" #include "itkVectorFieldGradientImageFunction.h" #include "itkBSplineInterpolateImageFunction.h" namespace itk { template<unsigned int TDimension = 3, class TReal = float> class ITK_EXPORT ANTSImageRegistrationOptimizer : public Object { public: /** Standard class typedefs. */ typedef ANTSImageRegistrationOptimizer Self; typedef Object Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ itkNewMacro( Self ); /** Run-time type information (and related methods). */ itkTypeMacro( ANTSImageRegistrationOptimizer, Object ); itkStaticConstMacro( Dimension, unsigned int, TDimension ); itkStaticConstMacro( ImageDimension, unsigned int, TDimension ); typedef TReal RealType; typedef Image<RealType, itkGetStaticConstMacro( Dimension )> ImageType; typedef typename ImageType::Pointer ImagePointer; typedef itk::MatrixOffsetTransformBase< double, ImageDimension, ImageDimension > TransformType; /** Point Types for landmarks and labeled point-sets */ typedef itk::ANTSLabeledPointSet<Dimension> LabeledPointSetType; typedef typename LabeledPointSetType::Pointer LabeledPointSetPointer; typedef typename LabeledPointSetType::PointSetType PointSetType; typedef typename PointSetType::Pointer PointSetPointer; typedef typename PointSetType::PointType PointType; typedef typename PointSetType::PixelType PointDataType; typedef typename ImageType::PointType ImagePointType; typedef itk::MatrixOffsetTransformBase<double, TDimension, TDimension> AffineTransformType; typedef typename AffineTransformType::Pointer AffineTransformPointer; typedef OptAffine<AffineTransformPointer, ImagePointer> OptAffineType; typedef itk::Vector<float,ImageDimension> VectorType; typedef itk::Image<VectorType,ImageDimension> DeformationFieldType; typedef typename DeformationFieldType::Pointer DeformationFieldPointer; typedef itk::Image<VectorType,ImageDimension+1> TimeVaryingVelocityFieldType; typedef typename TimeVaryingVelocityFieldType::Pointer TimeVaryingVelocityFieldPointer; typedef itk::VectorLinearInterpolateImageFunction<TimeVaryingVelocityFieldType,float> VelocityFieldInterpolatorType; typedef itk::VectorGaussianInterpolateImageFunction<TimeVaryingVelocityFieldType,float> VelocityFieldInterpolatorType2; typedef typename DeformationFieldType::IndexType IndexType; typedef ants::CommandLineParser ParserType; typedef typename ParserType::OptionType OptionType; typedef GeneralToBSplineDeformationFieldFilter<DeformationFieldType> BSplineFilterType; typedef FixedArray<RealType, itkGetStaticConstMacro( ImageDimension )> ArrayType; /** Typedefs for similarity metrics */ typedef ANTSSimilarityMetric <itkGetStaticConstMacro( Dimension ), float> SimilarityMetricType; typedef typename SimilarityMetricType::Pointer SimilarityMetricPointer; typedef std::vector<SimilarityMetricPointer> SimilarityMetricListType; /** FiniteDifferenceFunction type. */ typedef FiniteDifferenceFunction<DeformationFieldType> FiniteDifferenceFunctionType; typedef typename FiniteDifferenceFunctionType::TimeStepType TimeStepType; typedef typename FiniteDifferenceFunctionType::Pointer FiniteDifferenceFunctionPointer; typedef AvantsPDEDeformableRegistrationFunction<ImageType,ImageType, DeformationFieldType> MetricBaseType; typedef typename MetricBaseType::Pointer MetricBaseTypePointer; /* Jacobian and other calculations */ typedef itk::VectorFieldGradientImageFunction<DeformationFieldType> JacobianFunctionType; /** Set functions */ void SetAffineTransform(AffineTransformPointer A) {this->m_AffineTransform=A;} void SetDeformationField(DeformationFieldPointer A) {this->m_DeformationField=A;} void SetInverseDeformationField(DeformationFieldPointer A) {this->m_InverseDeformationField=A;} void SetMaskImage( ImagePointer m) { this->m_MaskImage=m; } void SetFixedImageAffineTransform(AffineTransformPointer A) {this->m_FixedImageAffineTransform=A;} AffineTransformPointer GetFixedImageAffineTransform() {return this->m_FixedImageAffineTransform;} /** Get functions */ AffineTransformPointer GetAffineTransform() {return this->m_AffineTransform;} DeformationFieldPointer GetDeformationField( ) {return this->m_DeformationField;} DeformationFieldPointer GetInverseDeformationField() {return this->m_InverseDeformationField;} /** Initialize all parameters */ void SetNumberOfLevels(unsigned int i) {this->m_NumberOfLevels=i;} void SetParser( typename ParserType::Pointer P ) {this->m_Parser=P;} /** Basic operations */ DeformationFieldPointer CopyDeformationField( DeformationFieldPointer input ); std::string localANTSGetFilePrefix(const char *str){ std::string filename = str; std::string::size_type pos = filename.rfind( "." ); std::string filepre = std::string( filename, 0, pos ); if ( pos != std::string::npos ){ std::string extension = std::string( filename, pos, filename.length()-1); if (extension==std::string(".gz")){ pos = filepre.rfind( "." ); extension = std::string( filepre, pos, filepre.length()-1 ); } // if (extension==".txt") return AFFINE_FILE; // else return DEFORMATION_FILE; } // else{ // return INVALID_FILE; //} return filepre; } void SmoothDeformationField(DeformationFieldPointer field, bool TrueEqualsGradElseTotal ) { typename ParserType::OptionType::Pointer regularizationOption = this->m_Parser->GetOption( "regularization" ); if ( ( regularizationOption->GetValue() ).find( "DMFFD" ) != std::string::npos ) { if( ( !TrueEqualsGradElseTotal && this->m_TotalSmoothingparam == 0.0 ) || ( TrueEqualsGradElseTotal && this->m_GradSmoothingparam == 0.0 ) ) { return; } ArrayType meshSize; unsigned int splineOrder = this->m_BSplineFieldOrder; float bsplineKernelVariance = static_cast<float>( splineOrder + 1 ) / 12.0; unsigned int numberOfLevels = 1; if( TrueEqualsGradElseTotal ) { if( this->m_GradSmoothingparam < 0.0 ) { meshSize = this->m_GradSmoothingMeshSize; for( unsigned int d = 0; d < ImageDimension; d++ ) { meshSize[d] *= static_cast<unsigned int>( vcl_pow( 2.0, static_cast<int>( this->m_CurrentLevel ) ) ); } } else { float spanLength = vcl_sqrt( this->m_GradSmoothingparam / bsplineKernelVariance ); for( unsigned int d = 0; d < ImageDimension; d++ ) { meshSize[d] = static_cast<unsigned int>( field->GetLargestPossibleRegion().GetSize()[d] / spanLength + 0.5 ); } } this->SmoothDeformationFieldBSpline( field, meshSize, splineOrder, numberOfLevels ); } else { if( this->m_TotalSmoothingparam < 0.0 ) { meshSize = this->m_TotalSmoothingMeshSize; for( unsigned int d = 0; d < ImageDimension; d++ ) { meshSize[d] *= static_cast<unsigned int>( vcl_pow( 2.0, static_cast<int>( this->m_CurrentLevel ) ) ); } } else { float spanLength = vcl_sqrt( this->m_TotalSmoothingparam / bsplineKernelVariance ); for( unsigned int d = 0; d < ImageDimension; d++ ) { meshSize[d] = static_cast<unsigned int>( field->GetLargestPossibleRegion().GetSize()[d] / spanLength + 0.5 ); } } RealType maxMagnitude = 0.0; ImageRegionIterator<DeformationFieldType> It( field, field->GetLargestPossibleRegion() ); for( It.GoToBegin(); !It.IsAtEnd(); ++It ) { RealType magnitude = ( It.Get() ).GetNorm(); if( magnitude > maxMagnitude ) { maxMagnitude = magnitude; } } this->SmoothDeformationFieldBSpline( field, meshSize, splineOrder, numberOfLevels ); if( maxMagnitude > 0.0 ) { for( It.GoToBegin(); !It.IsAtEnd(); ++It ) { It.Set( It.Get() / maxMagnitude ); } } } } else // Gaussian { float sig=0; if (TrueEqualsGradElseTotal) sig=this->m_GradSmoothingparam; else sig=this->m_TotalSmoothingparam; this->SmoothDeformationFieldGauss(field,sig); } } void SmoothDeformationFieldGauss(DeformationFieldPointer field = NULL, float sig=0.0, bool useparamimage=false, unsigned int lodim=ImageDimension); // float = smoothingparam, int = maxdim to smooth void SmoothVelocityGauss(TimeVaryingVelocityFieldPointer field,float,unsigned int); void SmoothDeformationFieldBSpline(DeformationFieldPointer field, ArrayType meshSize, unsigned int splineorder, unsigned int numberoflevels ); DeformationFieldPointer ComputeUpdateFieldAlternatingMin(DeformationFieldPointer fixedwarp, DeformationFieldPointer movingwarp, PointSetPointer fpoints=NULL, PointSetPointer wpoints=NULL,DeformationFieldPointer updateFieldInv=NULL, bool updateenergy=true); DeformationFieldPointer ComputeUpdateField(DeformationFieldPointer fixedwarp, DeformationFieldPointer movingwarp, PointSetPointer fpoints=NULL, PointSetPointer wpoints=NULL,DeformationFieldPointer updateFieldInv=NULL, bool updateenergy=true); TimeVaryingVelocityFieldPointer ExpandVelocity( ) { float expandFactors[ImageDimension+1]; expandFactors[ImageDimension]=1; m_Debug=false; for( int idim = 0; idim < ImageDimension; idim++ ) { expandFactors[idim] = (float)this->m_CurrentDomainSize[idim]/(float) this->m_TimeVaryingVelocity->GetLargestPossibleRegion().GetSize()[idim]; if( expandFactors[idim] < 1 ) expandFactors[idim] = 1; if (this->m_Debug) std::cout << " ExpFac " << expandFactors[idim] << " curdsz " << this->m_CurrentDomainSize[idim] << std::endl; } VectorType pad; pad.Fill(0); typedef VectorExpandImageFilter<TimeVaryingVelocityFieldType, TimeVaryingVelocityFieldType> ExpanderType; typename ExpanderType::Pointer m_FieldExpander = ExpanderType::New(); m_FieldExpander->SetInput(this->m_TimeVaryingVelocity); m_FieldExpander->SetExpandFactors( expandFactors ); m_FieldExpander->SetEdgePaddingValue( pad ); m_FieldExpander->UpdateLargestPossibleRegion(); return m_FieldExpander->GetOutput(); } DeformationFieldPointer ExpandField(DeformationFieldPointer field, typename ImageType::SpacingType targetSpacing) { // this->m_Debug=true; float expandFactors[ImageDimension]; for( int idim = 0; idim < ImageDimension; idim++ ) { expandFactors[idim] = (float)this->m_CurrentDomainSize[idim]/(float)field->GetLargestPossibleRegion().GetSize()[idim]; if( expandFactors[idim] < 1 ) expandFactors[idim] = 1; // if (this->m_Debug) std::cout << " ExpFac " << expandFactors[idim] << " curdsz " << this->m_CurrentDomainSize[idim] << std::endl; } VectorType pad; pad.Fill(0); typedef VectorExpandImageFilter<DeformationFieldType, DeformationFieldType> ExpanderType; typename ExpanderType::Pointer m_FieldExpander = ExpanderType::New(); m_FieldExpander->SetInput(field); m_FieldExpander->SetExpandFactors( expandFactors ); // use default m_FieldExpander->SetEdgePaddingValue( pad ); m_FieldExpander->UpdateLargestPossibleRegion(); typename DeformationFieldType::Pointer fieldout=m_FieldExpander->GetOutput(); fieldout->SetSpacing(targetSpacing); fieldout->SetOrigin(field->GetOrigin()); if (this->m_Debug) std::cout << " Field size " << fieldout->GetLargestPossibleRegion().GetSize() << std::endl; //this->m_Debug=false; return fieldout; } ImagePointer GetVectorComponent(DeformationFieldPointer field, unsigned int index) { // Initialize the Moving to the displacement field typedef DeformationFieldType FieldType; typename ImageType::Pointer sfield=ImageType::New(); sfield->SetSpacing( field->GetSpacing() ); sfield->SetOrigin( field->GetOrigin() ); sfield->SetDirection( field->GetDirection() ); sfield->SetLargestPossibleRegion(field->GetLargestPossibleRegion() ); sfield->SetRequestedRegion(field->GetRequestedRegion() ); sfield->SetBufferedRegion( field->GetBufferedRegion() ); sfield->Allocate(); typedef itk::ImageRegionIteratorWithIndex<FieldType> Iterator; Iterator vfIter( field, field->GetLargestPossibleRegion() ); for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter) { VectorType v1=vfIter.Get(); sfield->SetPixel(vfIter.GetIndex(),v1[index]); } return sfield; } ImagePointer SubsampleImage( ImagePointer, RealType , typename ImageType::PointType outputOrigin, typename ImageType::DirectionType outputDirection, AffineTransformPointer aff = NULL); DeformationFieldPointer SubsampleField( DeformationFieldPointer field, typename ImageType::SizeType targetSize, typename ImageType::SpacingType targetSpacing ) { std::cout << "FIXME -- NOT DONE CORRECTLY " << std::endl; std::cout << "FIXME -- NOT DONE CORRECTLY " << std::endl; std::cout << "FIXME -- NOT DONE CORRECTLY " << std::endl; std::cout << "FIXME -- NOT DONE CORRECTLY " << std::endl; std::cout << " SUBSAM FIELD SUBSAM FIELD SUBSAM FIELD " << std::endl; typename DeformationFieldType::Pointer sfield=DeformationFieldType::New(); for (unsigned int i=0; i < ImageDimension; i++) { typename ImageType::Pointer precomp=this->GetVectorComponent(field,i); typename ImageType::Pointer comp=this->SubsampleImage(precomp,targetSize,targetSpacing); if ( i==0 ) { sfield->SetSpacing( comp->GetSpacing() ); sfield->SetOrigin( comp->GetOrigin() ); sfield->SetDirection( comp->GetDirection() ); sfield->SetLargestPossibleRegion(comp->GetLargestPossibleRegion() ); sfield->SetRequestedRegion(comp->GetRequestedRegion() ); sfield->SetBufferedRegion( comp->GetBufferedRegion() ); sfield->Allocate(); } typedef itk::ImageRegionIteratorWithIndex<DeformationFieldType> Iterator; typedef typename DeformationFieldType::PixelType VectorType; VectorType v1; VectorType zero; zero.Fill(0.0); Iterator vfIter( sfield, sfield->GetLargestPossibleRegion() ); for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter) { v1=vfIter.Get(); v1[i]=comp->GetPixel(vfIter.GetIndex()); vfIter.Set(v1); } } return sfield; } PointSetPointer WarpMultiTransform(ImagePointer referenceimage, ImagePointer movingImage, PointSetPointer movingpoints, AffineTransformPointer aff , DeformationFieldPointer totalField, bool doinverse , AffineTransformPointer fixedaff ) { if (!movingpoints) { std::cout << " NULL POINTS " << std::endl; return NULL; } AffineTransformPointer affinverse=NULL; if (aff) { affinverse=AffineTransformType::New(); aff->GetInverse(affinverse); } AffineTransformPointer fixedaffinverse=NULL; if (fixedaff) { fixedaffinverse=AffineTransformType::New(); fixedaff->GetInverse(fixedaffinverse); } typedef itk::WarpImageMultiTransformFilter<ImageType,ImageType, DeformationFieldType, TransformType> WarperType; typename WarperType::Pointer warper = WarperType::New(); warper->SetInput(movingImage); warper->SetEdgePaddingValue( 0); warper->SetSmoothScale(1); if (!doinverse) { if (totalField) warper->PushBackDeformationFieldTransform(totalField); if (fixedaff) warper->PushBackAffineTransform(fixedaff); else if (aff) warper->PushBackAffineTransform(aff); } else { if (aff) warper->PushBackAffineTransform( affinverse ); else if (fixedaff) warper->PushBackAffineTransform(fixedaffinverse); if (totalField) warper->PushBackDeformationFieldTransform(totalField); } warper->SetOutputOrigin(referenceimage->GetOrigin()); typename ImageType::SizeType size=referenceimage->GetLargestPossibleRegion().GetSize(); if (totalField) size=totalField->GetLargestPossibleRegion().GetSize(); warper->SetOutputSize(size); typename ImageType::SpacingType spacing=referenceimage->GetSpacing(); if (totalField) spacing=totalField->GetSpacing(); warper->SetOutputSpacing(spacing); warper->SetOutputDirection(referenceimage->GetDirection()); totalField->SetOrigin(referenceimage->GetOrigin() ); totalField->SetDirection(referenceimage->GetDirection() ); // warper->Update(); // std::cout << " updated in point warp " << std::endl; PointSetPointer outputMesh = PointSetType::New(); unsigned long count = 0; unsigned long sz1 = movingpoints->GetNumberOfPoints(); if (this->m_Debug) std::cout << " BEFORE # points " << sz1 << std::endl; for (unsigned long ii=0; ii<sz1; ii++) { PointType point,wpoint; PointDataType label=0; movingpoints->GetPoint(ii,&point); movingpoints->GetPointData(ii,&label); // convert pointtype to imagepointtype ImagePointType pt,wpt; for (unsigned int jj=0; jj<ImageDimension; jj++) pt[jj]=point[jj]; bool bisinside = warper->MultiTransformSinglePoint(pt,wpt); if (bisinside) { for (unsigned int jj=0; jj<ImageDimension; jj++) wpoint[jj]=wpt[jj]; outputMesh->SetPointData( count, label ); outputMesh->SetPoint( count, wpoint ); // if (ii % 100 == 0) std::cout << " pt " << pt << " wpt " << wpt << std::endl; count++; } } if (this->m_Debug) std::cout << " AFTER # points " << count << std::endl; // if (count != sz1 ) std::cout << " WARNING: POINTS ARE MAPPING OUT OF IMAGE DOMAIN " << 1.0 - (float) count/(float)(sz1+1) << std::endl; return outputMesh; } ImagePointer WarpMultiTransform( ImagePointer referenceimage, ImagePointer movingImage, AffineTransformPointer aff , DeformationFieldPointer totalField, bool doinverse , AffineTransformPointer fixedaff ) { typedef typename ImageType::DirectionType DirectionType; DirectionType rdirection=referenceimage->GetDirection(); DirectionType mdirection=movingImage->GetDirection(); AffineTransformPointer affinverse=NULL; if (aff) { affinverse=AffineTransformType::New(); aff->GetInverse(affinverse); } AffineTransformPointer fixedaffinverse=NULL; if (fixedaff) { fixedaffinverse=AffineTransformType::New(); fixedaff->GetInverse(fixedaffinverse); } DirectionType iddir; iddir.Fill(0); for (unsigned int i=0;i<ImageDimension;i++) iddir[i][i]=1; typedef itk::LinearInterpolateImageFunction<ImageType,double> InterpolatorType1; typedef itk::NearestNeighborInterpolateImageFunction<ImageType,double> InterpolatorType2; typedef itk::BSplineInterpolateImageFunction<ImageType,double> InterpolatorType3; typename InterpolatorType1::Pointer interp1 = InterpolatorType1::New(); typename InterpolatorType2::Pointer interpnn = InterpolatorType2::New(); typename InterpolatorType3::Pointer interpcu = InterpolatorType3::New(); this->m_UseMulti=true; if (!this->m_UseMulti){ ImagePointer wmimage = this->SubsampleImage(movingImage , this->m_ScaleFactor , movingImage->GetOrigin() , movingImage->GetDirection() , aff ); typedef itk::WarpImageFilter<ImageType,ImageType, DeformationFieldType> WarperType; typename WarperType::Pointer warper; warper = WarperType::New(); warper->SetInput( wmimage); warper->SetDeformationField(totalField); warper->SetOutputSpacing(totalField->GetSpacing()); warper->SetOutputOrigin(totalField->GetOrigin()); warper->SetInterpolator(interp1); if (this->m_UseNN) warper->SetInterpolator(interpnn); if (this->m_UseBSplineInterpolation) warper->SetInterpolator(interpcu); // warper->SetOutputSize(this->m_CurrentDomainSize); // warper->SetEdgePaddingValue( 0 ); warper->Update(); return warper->GetOutput(); } typedef itk::WarpImageMultiTransformFilter<ImageType,ImageType, DeformationFieldType, TransformType> WarperType; typename WarperType::Pointer warper = WarperType::New(); warper->SetInput(movingImage); warper->SetEdgePaddingValue( 0); warper->SetSmoothScale(1); warper->SetInterpolator(interp1); if (this->m_UseNN) warper->SetInterpolator(interpnn); if (!doinverse) { if (totalField) warper->PushBackDeformationFieldTransform(totalField); if (fixedaff) warper->PushBackAffineTransform(fixedaff); else if (aff) warper->PushBackAffineTransform(aff); } else { if (aff) warper->PushBackAffineTransform( affinverse ); else if (fixedaff) warper->PushBackAffineTransform(fixedaffinverse); if (totalField) warper->PushBackDeformationFieldTransform(totalField); } warper->SetOutputOrigin(referenceimage->GetOrigin()); typename ImageType::SizeType size=referenceimage->GetLargestPossibleRegion().GetSize(); if (totalField) size=totalField->GetLargestPossibleRegion().GetSize(); warper->SetOutputSize(size); typename ImageType::SpacingType spacing=referenceimage->GetSpacing(); if (totalField) spacing=totalField->GetSpacing(); warper->SetOutputSpacing(spacing); warper->SetOutputDirection(referenceimage->GetDirection()); totalField->SetOrigin(referenceimage->GetOrigin() ); totalField->SetDirection(referenceimage->GetDirection() ); warper->Update(); if (this->m_Debug){ std::cout << " updated ok -- warped image output size " << warper->GetOutput()->GetLargestPossibleRegion().GetSize() << " requested size " << totalField->GetLargestPossibleRegion().GetSize() << std::endl; } typename ImageType::Pointer outimg=warper->GetOutput(); return outimg; } ImagePointer SmoothImageToScale(ImagePointer image , float scalingFactor ) { typename ImageType::SpacingType inputSpacing = image->GetSpacing(); typename ImageType::RegionType::SizeType inputSize = image->GetRequestedRegion().GetSize(); typename ImageType::SpacingType outputSpacing; typename ImageType::RegionType::SizeType outputSize; RealType minimumSpacing = inputSpacing.GetVnlVector().min_value(); // RealType maximumSpacing = inputSpacing.GetVnlVector().max_value(); for ( unsigned int d = 0; d < Dimension; d++ ) { RealType scaling = vnl_math_min( scalingFactor * minimumSpacing / inputSpacing[d], static_cast<RealType>( inputSize[d] ) / 32.0 ); outputSpacing[d] = inputSpacing[d] * scaling; outputSize[d] = static_cast<unsigned long>( inputSpacing[d] * static_cast<RealType>( inputSize[d] ) / outputSpacing[d] + 0.5 ); typedef RecursiveGaussianImageFilter<ImageType, ImageType> GaussianFilterType; typename GaussianFilterType::Pointer smoother = GaussianFilterType::New(); smoother->SetInputImage( image ); smoother->SetDirection( d ); smoother->SetNormalizeAcrossScale( false ); float sig = (outputSpacing[d]/inputSpacing[d]-1.0)*0.2;///(float)ImageDimension; smoother->SetSigma(sig ); if ( smoother->GetSigma() > 0.0 ) { smoother->Update(); image = smoother->GetOutput(); } } image=this->NormalizeImage(image); return image; } typename ANTSImageRegistrationOptimizer<TDimension, TReal>::DeformationFieldPointer IntegrateConstantVelocity(DeformationFieldPointer totalField, unsigned int ntimesteps, float timeweight); /** Base optimization functions */ // AffineTransformPointer AffineOptimization(AffineTransformPointer &aff_init, OptAffine &affine_opt); // {return NULL;} AffineTransformPointer AffineOptimization(OptAffineType &affine_opt); // {return NULL;} std::string GetTransformationModel( ) { return this->m_TransformationModel; } void SetTransformationModel( std::string s) { this->m_TransformationModel=s; std::cout << " Requested Transformation Model: " << this->m_TransformationModel << " : Using " << std::endl; if ( this->m_TransformationModel == std::string("Elast") ) { std::cout << "Elastic model for transformation. " << std::endl; } else if ( this->m_TransformationModel == std::string("SyN") ) { std::cout << "SyN diffeomorphic model for transformation. " << std::endl; } else if ( this->m_TransformationModel == std::string("GreedyExp") ) { std::cout << "Greedy Exp Diff model for transformation. Similar to Diffeomorphic Demons. Params same as Exp model. " << std::endl; this->m_TransformationModel=std::string("GreedyExp"); } else { std::cout << "Exp Diff model for transformation. " << std::endl; this->m_TransformationModel=std::string("Exp"); } } void SetUpParameters() { /** Univariate Deformable Mapping */ // set up parameters for deformation restriction std::string temp=this->m_Parser->GetOption( "Restrict-Deformation" )->GetValue(); this->m_RestrictDeformation = this->m_Parser->template ConvertVector<float>(temp); if ( this->m_RestrictDeformation.size() != ImageDimension ) { std::cout <<" You input a vector of size : " << this->m_RestrictDeformation.size() << " for --Restrict-Deformation. The vector length does not match the image dimension. Ignoring. " << std::endl; for (unsigned int jj=0; jj<this->m_RestrictDeformation.size(); jj++ ) this->m_RestrictDeformation[jj]=0; } // set up max iterations per level temp=this->m_Parser->GetOption( "number-of-iterations" )->GetValue(); this->m_Iterations = this->m_Parser->template ConvertVector<unsigned int>(temp); this->SetNumberOfLevels(this->m_Iterations.size()); this->m_UseROI=false; if ( typename OptionType::Pointer option = this->m_Parser->GetOption( "roi" ) ) { temp=this->m_Parser->GetOption( "roi" )->GetValue(); this->m_RoiNumbers = this->m_Parser->template ConvertVector<float>(temp); if ( temp.length() > 3 ) this->m_UseROI=true; } typename ParserType::OptionType::Pointer oOption = this->m_Parser->GetOption( "output-naming" ); this->m_OutputNamingConvention=oOption->GetValue(); typename ParserType::OptionType::Pointer thicknessOption = this->m_Parser->GetOption( "geodesic" ); if( thicknessOption->GetValue() == "true" || thicknessOption->GetValue() == "1" ) { this->m_ComputeThickness=1; this->m_SyNFullTime=2; }// asymm forces else if( thicknessOption->GetValue() == "2" ) { this->m_ComputeThickness=1; this->m_SyNFullTime=1; } // symmetric forces else this->m_ComputeThickness=0; // not full time varying stuff /** * Get transformation model and associated parameters */ typename ParserType::OptionType::Pointer transformOption = this->m_Parser->GetOption( "transformation-model" ); this->SetTransformationModel( transformOption->GetValue() ); if ( transformOption->GetNumberOfParameters() >= 1 ) { std::string parameter = transformOption->GetParameter( 0, 0 ); float temp=this->m_Parser->template Convert<float>( parameter ); this->m_Gradstep = temp; this->m_GradstepAltered = temp; } else { this->m_Gradstep=0.5; this->m_GradstepAltered=0.5; } if ( transformOption->GetNumberOfParameters() >= 2 ) { std::string parameter = transformOption->GetParameter( 0, 1 ); this->m_NTimeSteps = this->m_Parser->template Convert<unsigned int>( parameter ); } else this->m_NTimeSteps=1; if ( transformOption->GetNumberOfParameters() >= 3 ) { std::string parameter = transformOption->GetParameter( 0, 2 ); this->m_DeltaTime = this->m_Parser->template Convert<float>( parameter ); if (this->m_DeltaTime > 1) this->m_DeltaTime=1; if (this->m_DeltaTime <= 0) this->m_DeltaTime=0.001; std::cout <<" set DT " << this->m_DeltaTime << std::endl; this->m_SyNType=1; } else this->m_DeltaTime=0.1; // if ( transformOption->GetNumberOfParameters() >= 3 ) // { // std::string parameter = transformOption->GetParameter( 0, 2 ); // this->m_SymmetryType // = this->m_Parser->template Convert<unsigned int>( parameter ); // } /** * Get regularization and associated parameters */ this->m_GradSmoothingparam = -1; this->m_TotalSmoothingparam = -1; this->m_GradSmoothingMeshSize.Fill( 0 ); this->m_TotalSmoothingMeshSize.Fill( 0 ); typename ParserType::OptionType::Pointer regularizationOption = this->m_Parser->GetOption( "regularization" ); if( regularizationOption->GetValue() == "Gauss" ) { if ( regularizationOption->GetNumberOfParameters() >= 1 ) { std::string parameter = regularizationOption->GetParameter( 0, 0 ); this->m_GradSmoothingparam = this->m_Parser->template Convert<float>( parameter ); } else this->m_GradSmoothingparam=3; if ( regularizationOption->GetNumberOfParameters() >= 2 ) { std::string parameter = regularizationOption->GetParameter( 0, 1 ); this->m_TotalSmoothingparam = this->m_Parser->template Convert<float>( parameter ); } else this->m_TotalSmoothingparam=0.5; if ( regularizationOption->GetNumberOfParameters() >= 3 ) { std::string parameter = regularizationOption->GetParameter( 0, 2 ); this->m_GaussianTruncation = this->m_Parser->template Convert<float>( parameter ); } else this->m_GaussianTruncation = 256; std::cout <<" Grad Step " << this->m_Gradstep << " total-smoothing " << this->m_TotalSmoothingparam << " gradient-smoothing " << this->m_GradSmoothingparam << std::endl; } else if( ( regularizationOption->GetValue() ).find( "DMFFD" ) != std::string::npos ) { if ( regularizationOption->GetNumberOfParameters() >= 1 ) { std::string parameter = regularizationOption->GetParameter( 0, 0 ); if( parameter.find( "x" ) != std::string::npos ) { std::vector<unsigned int> gradMeshSize = this->m_Parser->template ConvertVector<unsigned int>( parameter ); for( unsigned int d = 0; d < ImageDimension; d++ ) { this->m_GradSmoothingMeshSize[d] = gradMeshSize[d]; } } else { this->m_GradSmoothingparam = this->m_Parser->template Convert<float>( parameter ); } } else { this->m_GradSmoothingparam = 3.0; } if ( regularizationOption->GetNumberOfParameters() >= 2 ) { std::string parameter = regularizationOption->GetParameter( 0, 1 ); if( parameter.find( "x" ) != std::string::npos ) { std::vector<unsigned int> totalMeshSize = this->m_Parser->template ConvertVector<unsigned int>( parameter ); for( unsigned int d = 0; d < ImageDimension; d++ ) { this->m_TotalSmoothingMeshSize[d] = totalMeshSize[d]; } } else { this->m_TotalSmoothingparam = this->m_Parser->template Convert<float>( parameter ); } } else { this->m_TotalSmoothingparam=0.5; } if ( regularizationOption->GetNumberOfParameters() >= 3 ) { std::string parameter = regularizationOption->GetParameter( 0, 2 ); this->m_BSplineFieldOrder = this->m_Parser->template Convert<unsigned int>( parameter ); } else this->m_BSplineFieldOrder = 3; std::cout <<" Grad Step " << this->m_Gradstep << " total-smoothing " << this->m_TotalSmoothingparam << " gradient-smoothing " << this->m_GradSmoothingparam << " bspline-field-order " << this->m_BSplineFieldOrder << std::endl; } else { this->m_GradSmoothingparam=3; this->m_TotalSmoothingparam=0.5; std::cout <<" Default Regularization is Gaussian smoothing with : " << this->m_GradSmoothingparam << " & " << this->m_TotalSmoothingparam << std::endl; // itkExceptionMacro( "Invalid regularization: " << regularizationOption->GetValue() ); } } void ComputeMultiResolutionParameters(ImagePointer fixedImage ) { VectorType zero; zero.Fill(0); /** Compute scale factors */ this->m_FullDomainSpacing = fixedImage->GetSpacing(); this->m_FullDomainSize = fixedImage->GetRequestedRegion().GetSize(); this->m_CurrentDomainSpacing = fixedImage->GetSpacing(); this->m_CurrentDomainSize = fixedImage->GetRequestedRegion().GetSize(); this->m_CurrentDomainDirection=fixedImage->GetDirection(); this->m_FullDomainOrigin.Fill(0); this->m_CurrentDomainOrigin.Fill(0); /** alter the input size based on information gained from the ROI information - if available */ if (this->m_UseROI) { for (unsigned int ii=0; ii<ImageDimension; ii++) { this->m_FullDomainSize[ii]= (typename ImageType::SizeType::SizeValueType) this->m_RoiNumbers[ii+ImageDimension]; this->m_FullDomainOrigin[ii]=this->m_RoiNumbers[ii]; } std::cout << " ROI #s : size " << this->m_FullDomainSize << " orig " << this->m_FullDomainOrigin << std::endl; } RealType minimumSpacing = this->m_FullDomainSpacing.GetVnlVector().min_value(); // RealType maximumSpacing = this->m_FullDomainSpacing.GetVnlVector().max_value(); for ( unsigned int d = 0; d < Dimension; d++ ) { RealType scaling = vnl_math_min( this->m_ScaleFactor * minimumSpacing / this->m_FullDomainSpacing[d], static_cast<RealType>( this->m_FullDomainSize[d] ) / 32.0 ); if (scaling < 1) scaling=1; this->m_CurrentDomainSpacing[d] = this->m_FullDomainSpacing[d] * scaling; this->m_CurrentDomainSize[d] = static_cast<unsigned long>( this->m_FullDomainSpacing[d] *static_cast<RealType>( this->m_FullDomainSize[d] ) / this->m_CurrentDomainSpacing[d] + 0.5 ); this->m_CurrentDomainOrigin[d] = static_cast<unsigned long>( this->m_FullDomainSpacing[d] *static_cast<RealType>( this->m_FullDomainOrigin[d] ) / this->m_CurrentDomainSpacing[d] + 0.5 ); } // this->m_Debug=true; if (this->m_Debug) std::cout << " outsize " << this->m_CurrentDomainSize << " curspc " << this->m_CurrentDomainSpacing << " fullspc " << this->m_FullDomainSpacing << " fullsz " << this->m_FullDomainSize << std::endl; // this->m_Debug=false; if (!this->m_DeformationField) {/*FIXME -- need initial deformation strategy */ this->m_DeformationField=DeformationFieldType::New(); this->m_DeformationField->SetSpacing( this->m_CurrentDomainSpacing); this->m_DeformationField->SetOrigin( fixedImage->GetOrigin() ); this->m_DeformationField->SetDirection( fixedImage->GetDirection() ); typename ImageType::RegionType region; region.SetSize( this->m_CurrentDomainSize); this->m_DeformationField->SetLargestPossibleRegion(region); this->m_DeformationField->SetRequestedRegion(region); this->m_DeformationField->SetBufferedRegion(region); this->m_DeformationField->Allocate(); this->m_DeformationField->FillBuffer(zero); std::cout << " allocated def field " << this->m_DeformationField->GetDirection() << std::endl; //exit(0); } else { this->m_DeformationField=this->ExpandField(this->m_DeformationField,this->m_CurrentDomainSpacing); if ( this->m_TimeVaryingVelocity ) this->ExpandVelocity(); } } ImagePointer NormalizeImage( ImagePointer image) { typedef itk::MinimumMaximumImageFilter<ImageType> MinMaxFilterType; typename MinMaxFilterType::Pointer minMaxFilter = MinMaxFilterType::New(); minMaxFilter->SetInput( image ); minMaxFilter->Update(); double min = minMaxFilter->GetMinimum(); double shift = -1.0 * static_cast<double>( min ); double scale = static_cast<double>( minMaxFilter->GetMaximum() ); scale += shift; scale = 1.0 / scale; typedef itk::ShiftScaleImageFilter<ImageType,ImageType> FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetInput( image ); filter->SetShift( shift ); filter->SetScale( scale ); filter->Update(); return filter->GetOutput(); } void DeformableOptimization() { DeformationFieldPointer updateField = NULL; this->SetUpParameters(); typename ImageType::SpacingType spacing; VectorType zero; zero.Fill(0); std::cout << " setting N-TimeSteps = " << this->m_NTimeSteps << " trunc " << this->m_GaussianTruncation << std::endl; unsigned int maxits=0; for ( unsigned int currentLevel = 0; currentLevel < this->m_NumberOfLevels; currentLevel++ ) if ( this->m_Iterations[currentLevel] > maxits) maxits=this->m_Iterations[currentLevel]; if (maxits == 0) { this->m_DeformationField=NULL; this->m_InverseDeformationField=NULL; // this->ComputeMultiResolutionParameters(this->m_SimilarityMetrics[0]->GetFixedImage()); return; } /* this is a hack to force univariate mappings in the future, we will re-cast this framework s.t. multivariate images can be used */ unsigned int numberOfMetrics=this->m_SimilarityMetrics.size(); for ( unsigned int metricCount = 1; metricCount < numberOfMetrics; metricCount++) { this->m_SimilarityMetrics[metricCount]->GetFixedImage( )->SetOrigin( this->m_SimilarityMetrics[0]->GetFixedImage()->GetOrigin()); this->m_SimilarityMetrics[metricCount]->GetFixedImage( )->SetDirection( this->m_SimilarityMetrics[0]->GetFixedImage()->GetDirection()); this->m_SimilarityMetrics[metricCount]->GetMovingImage( )->SetOrigin( this->m_SimilarityMetrics[0]->GetMovingImage()->GetOrigin()); this->m_SimilarityMetrics[metricCount]->GetMovingImage( )->SetDirection( this->m_SimilarityMetrics[0]->GetMovingImage()->GetDirection()); } /* here, we assign all point set pointers to any single non-null point-set pointer */ for (unsigned int metricCount=0; metricCount < numberOfMetrics; metricCount++) { for (unsigned int metricCount2=0; metricCount2 < numberOfMetrics; metricCount2++) { if (this->m_SimilarityMetrics[metricCount]->GetFixedPointSet()) this->m_SimilarityMetrics[metricCount2]->SetFixedPointSet(this->m_SimilarityMetrics[metricCount]->GetFixedPointSet()); if (this->m_SimilarityMetrics[metricCount]->GetMovingPointSet()) this->m_SimilarityMetrics[metricCount2]->SetMovingPointSet(this->m_SimilarityMetrics[metricCount]->GetMovingPointSet()); } } this->m_SmoothFixedImages.resize(numberOfMetrics,NULL); this->m_SmoothMovingImages.resize(numberOfMetrics,NULL); for ( unsigned int currentLevel = 0; currentLevel < this->m_NumberOfLevels; currentLevel++ ) { this->m_CurrentLevel = currentLevel; typedef Vector<float,1> ProfilePointDataType; typedef Image<ProfilePointDataType, 1> CurveType; typedef PointSet<ProfilePointDataType, 1> EnergyProfileType; typedef typename EnergyProfileType::PointType ProfilePointType; std::vector<EnergyProfileType::Pointer> energyProfiles; energyProfiles.resize( numberOfMetrics ); for( unsigned int qq = 0; qq < numberOfMetrics; qq++ ) { energyProfiles[qq] = EnergyProfileType::New(); energyProfiles[qq]->Initialize(); } ImagePointer fixedImage; ImagePointer movingImage; this->m_GradstepAltered=this->m_Gradstep; this->m_ScaleFactor = pow( 2.0, (int)static_cast<RealType>( this->m_NumberOfLevels-currentLevel-1 ) ); std::cout << " this->m_ScaleFactor " << this->m_ScaleFactor << " nlev " << this->m_NumberOfLevels << " curl " << currentLevel << std::endl; /** FIXME -- here we assume the metrics all have the same image */ fixedImage = this->m_SimilarityMetrics[0]->GetFixedImage(); movingImage = this->m_SimilarityMetrics[0]->GetMovingImage(); spacing=fixedImage->GetSpacing(); this->ComputeMultiResolutionParameters(fixedImage); std::cout << " Its at this level " << this->m_Iterations[currentLevel] << std::endl; /* generate smoothed images for all metrics */ for ( unsigned int metricCount=0; metricCount < numberOfMetrics; metricCount++) { this->m_SmoothFixedImages[metricCount] = this->SmoothImageToScale(this->m_SimilarityMetrics[metricCount]->GetFixedImage(), this->m_ScaleFactor); this->m_SmoothMovingImages[metricCount] = this->SmoothImageToScale(this->m_SimilarityMetrics[metricCount]->GetMovingImage(), this->m_ScaleFactor); } fixedImage=this->m_SmoothFixedImages[0]; movingImage=this->m_SmoothMovingImages[0]; unsigned int nmet=this->m_SimilarityMetrics.size(); this->m_LastEnergy.resize(nmet,1.e12); this->m_Energy.resize(nmet,1.e9); this->m_EnergyBad.resize(nmet,0); bool converged=false; this->m_CurrentIteration=0; if (this->GetTransformationModel() != std::string("SyN")) this->m_FixedImageAffineTransform=NULL; while (!converged) { for (unsigned int metricCount=0; metricCount < numberOfMetrics; metricCount++) this->m_SimilarityMetrics[metricCount]->GetMetric()->SetIterations(this->m_CurrentIteration); if ( this->GetTransformationModel() == std::string("Elast")) { if (this->m_Iterations[currentLevel] > 0) this->ElasticRegistrationUpdate(fixedImage, movingImage); } else if (this->GetTransformationModel() == std::string("SyN")) { if ( currentLevel > 0 ) { this->m_SyNF=this->ExpandField(this->m_SyNF,this->m_CurrentDomainSpacing); this->m_SyNFInv=this->ExpandField(this->m_SyNFInv,this->m_CurrentDomainSpacing); this->m_SyNM=this->ExpandField(this->m_SyNM,this->m_CurrentDomainSpacing); this->m_SyNMInv=this->ExpandField(this->m_SyNMInv,this->m_CurrentDomainSpacing); } if(this->m_Iterations[currentLevel] > 0) { if (this->m_SyNType && this->m_ComputeThickness ) this->DiReCTUpdate(fixedImage, movingImage, this->m_SimilarityMetrics[0]->GetFixedPointSet(), this->m_SimilarityMetrics[0]->GetMovingPointSet() ); else if (this->m_SyNType) this->SyNTVRegistrationUpdate(fixedImage, movingImage, this->m_SimilarityMetrics[0]->GetFixedPointSet(), this->m_SimilarityMetrics[0]->GetMovingPointSet() ); else this->SyNRegistrationUpdate(fixedImage, movingImage, this->m_SimilarityMetrics[0]->GetFixedPointSet(), this->m_SimilarityMetrics[0]->GetMovingPointSet() ); } else if (this->m_SyNType) this->UpdateTimeVaryingVelocityFieldWithSyNFandSyNM( ); // this->CopyOrAddToVelocityField( this->m_SyNF, 0 , false); } else if (this->GetTransformationModel() == std::string("Exp")) { if(this->m_Iterations[currentLevel] > 0) { this->DiffeomorphicExpRegistrationUpdate(fixedImage, movingImage,this->m_SimilarityMetrics[0]->GetFixedPointSet(), this->m_SimilarityMetrics[0]->GetMovingPointSet() ); } } else if (this->GetTransformationModel() == std::string("GreedyExp")) { if(this->m_Iterations[currentLevel] > 0) { this->GreedyExpRegistrationUpdate(fixedImage, movingImage,this->m_SimilarityMetrics[0]->GetFixedPointSet(), this->m_SimilarityMetrics[0]->GetMovingPointSet() ); } } this->m_CurrentIteration++; /** * This is where we track the energy profile to check for convergence. */ for( unsigned int qq = 0; qq < numberOfMetrics; qq++ ) { ProfilePointType point; point[0] = this->m_CurrentIteration-1; ProfilePointDataType energy; energy[0] = this->m_Energy[qq]; energyProfiles[qq]->SetPoint( this->m_CurrentIteration-1, point ); energyProfiles[qq]->SetPointData( this->m_CurrentIteration-1, energy ); } /** * If there are a sufficent number of iterations, fit a quadratic * single B-spline span to the number of energy profile points * in the first metric. To test convergence, evaluate the derivative * at the end of the profile to determine if >= 0. To change to a * window of the energy profile, simply change the origin (assuming that * the desired window will start at the user-specified origin and * end at the current iteration). */ unsigned int domtar=12; if( this->m_CurrentIteration > domtar ) { typedef BSplineScatteredDataPointSetToImageFilter <EnergyProfileType, CurveType> BSplinerType; typename BSplinerType::Pointer bspliner = BSplinerType::New(); typename CurveType::PointType origin; unsigned int domainorigin=0; unsigned int domainsize=this->m_CurrentIteration - domainorigin; if ( this->m_CurrentIteration > domtar ) { domainsize=domtar; domainorigin=this->m_CurrentIteration-domainsize; } origin.Fill( domainorigin ); typename CurveType::SizeType size; size.Fill( domainsize ); typename CurveType::SpacingType spacing; spacing.Fill( 1 ); typename EnergyProfileType::Pointer energyProfileWindow = EnergyProfileType::New(); energyProfileWindow->Initialize(); unsigned int windowBegin = static_cast<unsigned int>( origin[0] ); float totale=0; for( unsigned int qq = windowBegin; qq < this->m_CurrentIteration; qq++ ) { ProfilePointType point; point[0] = qq; ProfilePointDataType energy; energy.Fill( 0 ); energyProfiles[0]->GetPointData( qq, &energy ); totale+=energy[0]; energyProfileWindow->SetPoint( qq-windowBegin, point ); energyProfileWindow->SetPointData( qq-windowBegin, energy ); } // std::cout <<" totale " << totale << std::endl; if (totale > 0) totale*=(-1.0); for( unsigned int qq = windowBegin; qq < this->m_CurrentIteration; qq++ ) { ProfilePointDataType energy; energy.Fill(0); energyProfiles[0]->GetPointData( qq, &energy ); energyProfileWindow->SetPointData( qq-windowBegin, energy/totale); } bspliner->SetInput( energyProfileWindow ); bspliner->SetOrigin( origin ); bspliner->SetSpacing( spacing ); bspliner->SetSize( size ); bspliner->SetNumberOfLevels( 1 ); unsigned int order=1; bspliner->SetSplineOrder( order ); typename BSplinerType::ArrayType ncps; ncps.Fill( order+1); // single span, order = 2 bspliner->SetNumberOfControlPoints( ncps ); bspliner->Update(); ProfilePointType endPoint; endPoint[0] = static_cast<float>( this->m_CurrentIteration-domainsize*0.5 ); typename BSplinerType::GradientType gradient; gradient.Fill(0); bspliner->EvaluateGradientAtPoint( endPoint, gradient ); this->m_ESlope=gradient[0][0] ; if ( this->m_ESlope < 0.0001 && this->m_CurrentIteration > domtar) converged=true; std::cout << " E-Slope " << this->m_ESlope;//<< std::endl; } for ( unsigned int qq=0; qq < this->m_Energy.size(); qq++ ) { if ( qq==0 ) std::cout << " iteration " << this->m_CurrentIteration; std::cout << " energy " << qq << " : " << this->m_Energy[qq];// << " Last " << this->m_LastEnergy[qq]; if (this->m_LastEnergy[qq] < this->m_Energy[qq]) { this->m_EnergyBad[qq]++; } } unsigned int numbade=0; for (unsigned int qq=0; qq<this->m_Energy.size(); qq++) if (this->m_CurrentIteration <= 1) this->m_EnergyBad[qq] = 0; else if ( this->m_EnergyBad[qq] > 1 ) numbade += this->m_EnergyBad[qq]; //if ( this->m_EnergyBad[0] > 2) // { // this->m_GradstepAltered*=0.8; // std::cout <<" reducing gradstep " << this->m_GradstepAltered; // this->m_EnergyBad[this->m_Energy.size()-1]=0; // } std::cout << std::endl; if (this->m_CurrentIteration >= this->m_Iterations[currentLevel] )converged = true; // || this->m_EnergyBad[0] >= 6 ) // if ( converged && this->m_CurrentIteration >= this->m_Iterations[currentLevel] ) std::cout <<" tired convergence: reached max iterations " << std::endl; else if (converged) { std::cout << " Converged due to oscillation in optimization "; for (unsigned int qq=0; qq<this->m_Energy.size(); qq++) std::cout<< " metric " << qq << " bad " << this->m_EnergyBad[qq] << " " ; std::cout <<std::endl; } } } if ( this->GetTransformationModel() == std::string("SyN")) { // float timestep=1.0/(float)this->m_NTimeSteps; // unsigned int nts=this->m_NTimeSteps; if (this->m_SyNType) { // this->m_SyNFInv = this->IntegrateConstantVelocity(this->m_SyNF, nts, timestep*(-1.)); // this->m_SyNMInv = this->IntegrateConstantVelocity(this->m_SyNM, nts, timestep*(-1.)); // this->m_SyNF= this->IntegrateConstantVelocity(this->m_SyNF, nts, timestep); // this->m_SyNM= this->IntegrateConstantVelocity(this->m_SyNM, // nts, timestep); // DeformationFieldPointer fdiffmap = this->IntegrateVelocity(0,0.5); // this->m_SyNFInv = this->IntegrateVelocity(0.5,0); // DeformationFieldPointer mdiffmap = this->IntegrateVelocity(0.5,1); // this->m_SyNMInv = this->IntegrateVelocity(1,0.5); // this->m_SyNM=this->CopyDeformationField(mdiffmap); // this->m_SyNF=this->CopyDeformationField(fdiffmap); this->m_DeformationField = this->IntegrateVelocity(0,1); // ImagePointer wmimage= this->WarpMultiTransform( this->m_SmoothFixedImages[0],this->m_SmoothMovingImages[0], this->m_AffineTransform, this->m_DeformationField, false , this->m_ScaleFactor ); this->m_InverseDeformationField=this->IntegrateVelocity(1,0); } else { this->m_InverseDeformationField=this->CopyDeformationField( this->m_SyNM); this->ComposeDiffs(this->m_SyNF,this->m_SyNMInv,this->m_DeformationField,1); this->ComposeDiffs(this->m_SyNM,this->m_SyNFInv,this->m_InverseDeformationField,1); } } else if (this->GetTransformationModel() == std::string("Exp")) { DeformationFieldPointer diffmap = this->IntegrateConstantVelocity( this->m_DeformationField, (unsigned int)this->m_NTimeSteps , 1 ); // 1.0/ (float)this->m_NTimeSteps); DeformationFieldPointer invdiffmap = this->IntegrateConstantVelocity(this->m_DeformationField,(unsigned int) this->m_NTimeSteps, -1 ); // -1.0/(float)this->m_NTimeSteps); this->m_InverseDeformationField=invdiffmap; this->m_DeformationField=diffmap; AffineTransformPointer invaff =NULL; if (this->m_AffineTransform) { invaff=AffineTransformType::New(); this->m_AffineTransform->GetInverse(invaff); if (this->m_Debug) std::cout << " ??????invaff " << this->m_AffineTransform << std::endl << std::endl; if (this->m_Debug) std::cout << " invaff?????? " << invaff << std::endl << std::endl; } } else if (this->GetTransformationModel() == std::string("GreedyExp")) { DeformationFieldPointer diffmap = this->m_DeformationField; this->m_InverseDeformationField=NULL; this->m_DeformationField=diffmap; AffineTransformPointer invaff =NULL; if (this->m_AffineTransform) { invaff=AffineTransformType::New(); this->m_AffineTransform->GetInverse(invaff); if (this->m_Debug) std::cout << " ??????invaff " << this->m_AffineTransform << std::endl << std::endl; if (this->m_Debug) std::cout << " invaff?????? " << invaff << std::endl << std::endl; } } this->m_DeformationField->SetOrigin( this->m_SimilarityMetrics[0]->GetFixedImage()->GetOrigin() ); this->m_DeformationField->SetDirection( this->m_SimilarityMetrics[0]->GetFixedImage()->GetDirection() ); if (this->m_InverseDeformationField) { this->m_InverseDeformationField->SetOrigin( this->m_SimilarityMetrics[0]->GetFixedImage()->GetOrigin() ); this->m_InverseDeformationField->SetDirection( this->m_SimilarityMetrics[0]->GetFixedImage()->GetDirection() ); } if ( this->m_TimeVaryingVelocity ) { std::string outname=localANTSGetFilePrefix(this->m_OutputNamingConvention.c_str())+std::string("velocity.mhd"); typename itk::ImageFileWriter<TimeVaryingVelocityFieldType>::Pointer writer = itk::ImageFileWriter<TimeVaryingVelocityFieldType>::New(); writer->SetFileName(outname.c_str()); writer->SetInput( this->m_TimeVaryingVelocity); writer->UpdateLargestPossibleRegion(); // writer->Write(); std::cout << " write tv field " << outname << std::endl; // WriteImage<TimeVaryingVelocityFieldType>( this->m_TimeVaryingVelocity , outname.c_str()); } } void DiffeomorphicExpRegistrationUpdate(ImagePointer fixedImage, ImagePointer movingImage,PointSetPointer fpoints=NULL, PointSetPointer mpoints=NULL); void GreedyExpRegistrationUpdate(ImagePointer fixedImage, ImagePointer movingImage,PointSetPointer fpoints=NULL, PointSetPointer mpoints=NULL); void SyNRegistrationUpdate(ImagePointer fixedImage, ImagePointer movingImage, PointSetPointer fpoints=NULL, PointSetPointer mpoints=NULL); void SyNExpRegistrationUpdate(ImagePointer fixedImage, ImagePointer movingImage, PointSetPointer fpoints=NULL, PointSetPointer mpoints=NULL); void SyNTVRegistrationUpdate(ImagePointer fixedImage, ImagePointer movingImage, PointSetPointer fpoints=NULL, PointSetPointer mpoints=NULL); void DiReCTUpdate(ImagePointer fixedImage, ImagePointer movingImage, PointSetPointer fpoints=NULL, PointSetPointer mpoints=NULL); /** allows one to copy or add a field to a time index within the velocity * field */ void UpdateTimeVaryingVelocityFieldWithSyNFandSyNM( ); void CopyOrAddToVelocityField( TimeVaryingVelocityFieldPointer velocity, DeformationFieldPointer update1, DeformationFieldPointer update2 , float timept); //void CopyOrAddToVelocityField( DeformationFieldPointer update, unsigned int timeindex, bool CopyIsTrueOtherwiseAdd); void ElasticRegistrationUpdate(ImagePointer fixedImage, ImagePointer movingImage) { typename ImageType::SpacingType spacing; VectorType zero; zero.Fill(0); DeformationFieldPointer updateField; updateField=this->ComputeUpdateField(this->m_DeformationField,NULL,NULL,NULL,NULL); typedef ImageRegionIteratorWithIndex<DeformationFieldType> Iterator; Iterator dIter(this->m_DeformationField,this->m_DeformationField->GetLargestPossibleRegion() ); for( dIter.GoToBegin(); !dIter.IsAtEnd(); ++dIter ) { typename ImageType::IndexType index=dIter.GetIndex(); VectorType vec=updateField->GetPixel(index); dIter.Set(dIter.Get()+vec*this->m_Gradstep); } if (this->m_Debug) { std::cout << " updated elast " << " up-sz " << updateField->GetLargestPossibleRegion() << std::endl; std::cout << " t-sz " << this->m_DeformationField->GetLargestPossibleRegion() << std::endl; } this->SmoothDeformationField(this->m_DeformationField, false); return; } ImagePointer WarpImageBackward( ImagePointer image, DeformationFieldPointer field ) { typedef WarpImageFilter<ImageType,ImageType, DeformationFieldType> WarperType; typename WarperType::Pointer warper = WarperType::New(); typedef NearestNeighborInterpolateImageFunction<ImageType,double> InterpolatorType; warper->SetInput(image); warper->SetDeformationField( field ); warper->SetEdgePaddingValue( 0); warper->SetOutputSpacing(field->GetSpacing() ); warper->SetOutputOrigin( field->GetOrigin() ); warper->Update(); return warper->GetOutput(); } void ComposeDiffs(DeformationFieldPointer fieldtowarpby, DeformationFieldPointer field, DeformationFieldPointer fieldout, float sign); void SetSimilarityMetrics( SimilarityMetricListType S ) {this->m_SimilarityMetrics=S;} void SetFixedPointSet( PointSetPointer p ) { this->m_FixedPointSet=p; } void SetMovingPointSet( PointSetPointer p ) { this->m_MovingPointSet=p; } void SetDeltaTime( float t) {this->m_DeltaTime=t; } float InvertField(DeformationFieldPointer field, DeformationFieldPointer inverseField, float weight=1.0, float toler=0.1, int maxiter=20, bool print = false) { float mytoler=toler; unsigned int mymaxiter=maxiter; typename ParserType::OptionType::Pointer thicknessOption = this->m_Parser->GetOption( "go-faster" ); if( thicknessOption->GetValue() == "true" || thicknessOption->GetValue() == "1" ) { mytoler=0.5; maxiter=12; } VectorType zero; zero.Fill(0); // if (this->GetElapsedIterations() < 2 ) maxiter=10; ImagePointer floatImage = ImageType::New(); floatImage->SetLargestPossibleRegion( field->GetLargestPossibleRegion() ); floatImage->SetBufferedRegion( field->GetLargestPossibleRegion().GetSize() ); floatImage->SetSpacing(field->GetSpacing()); floatImage->SetOrigin(field->GetOrigin()); floatImage->SetDirection(field->GetDirection()); floatImage->Allocate(); typedef typename DeformationFieldType::PixelType VectorType; typedef typename DeformationFieldType::IndexType IndexType; typedef typename VectorType::ValueType ScalarType; typedef ImageRegionIteratorWithIndex<DeformationFieldType> Iterator; DeformationFieldPointer lagrangianInitCond=DeformationFieldType::New(); lagrangianInitCond->SetSpacing( field->GetSpacing() ); lagrangianInitCond->SetOrigin( field->GetOrigin() ); lagrangianInitCond->SetDirection( field->GetDirection() ); lagrangianInitCond->SetLargestPossibleRegion( field->GetLargestPossibleRegion() ); lagrangianInitCond->SetRequestedRegion(field->GetRequestedRegion() ); lagrangianInitCond->SetBufferedRegion( field->GetLargestPossibleRegion() ); lagrangianInitCond->Allocate(); DeformationFieldPointer eulerianInitCond=DeformationFieldType::New(); eulerianInitCond->SetSpacing( field->GetSpacing() ); eulerianInitCond->SetOrigin( field->GetOrigin() ); eulerianInitCond->SetDirection( field->GetDirection() ); eulerianInitCond->SetLargestPossibleRegion( field->GetLargestPossibleRegion() ); eulerianInitCond->SetRequestedRegion(field->GetRequestedRegion() ); eulerianInitCond->SetBufferedRegion( field->GetLargestPossibleRegion() ); eulerianInitCond->Allocate(); typedef typename DeformationFieldType::SizeType SizeType; SizeType size=field->GetLargestPossibleRegion().GetSize(); typename ImageType::SpacingType spacing = field->GetSpacing(); float subpix=0.0; unsigned long npix=1; for (int j=0; j<ImageDimension; j++) // only use in-plane spacing { npix*=field->GetLargestPossibleRegion().GetSize()[j]; } subpix=pow((float)ImageDimension,(float)ImageDimension)*0.5; float max=0; Iterator iter( field, field->GetLargestPossibleRegion() ); for( iter.GoToBegin(); !iter.IsAtEnd(); ++iter ) { IndexType index=iter.GetIndex(); VectorType vec1=iter.Get(); VectorType newvec=vec1*weight; lagrangianInitCond->SetPixel(index,newvec); float mag=0; for (unsigned int jj=0; jj<ImageDimension; jj++) mag+=newvec[jj]*newvec[jj]; mag=sqrt(mag); if (mag > max) max=mag; } eulerianInitCond->FillBuffer(zero); float scale=(1.)/max; if (scale > 1.) scale=1.0; // float initscale=scale; Iterator vfIter( inverseField, inverseField->GetLargestPossibleRegion() ); // int num=10; // for (int its=0; its<num; its++) float difmag=10.0; unsigned int ct=0; float denergy=10; float denergy2=10; float laste=1.e9; float meandif=1.e8; // int badct=0; // while (difmag > subpix && meandif > subpix*0.1 && badct < 2 )//&& ct < 20 && denergy > 0) // float length=0.0; float stepl=2.; float lastdifmag=0; float epsilon = (float)size[0]/256; if (epsilon > 1) epsilon = 1; while ( difmag > mytoler && ct < mymaxiter && meandif > 0.001) { denergy=laste-difmag;//meandif; denergy2=laste-meandif; laste=difmag;//meandif; meandif=0.0; //this field says what position the eulerian field should contain in the E domain this->ComposeDiffs(inverseField,lagrangianInitCond, eulerianInitCond, 1); difmag=0.0; for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter ) { IndexType index=vfIter.GetIndex(); VectorType update=eulerianInitCond->GetPixel(index); float mag=0; for (int j=0; j<ImageDimension;j++) { update[j]*=(-1.0); mag+=(update[j]/spacing[j])*(update[j]/spacing[j]); } mag=sqrt(mag); meandif+=mag; if (mag > difmag) {difmag=mag; } // if (mag < 1.e-2) update.Fill(0); eulerianInitCond->SetPixel(index,update); floatImage->SetPixel(index,mag); } meandif/=(float)npix; if (ct == 0) epsilon = 0.75; else epsilon=0.5; stepl=difmag*epsilon; for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter ) { float val = floatImage->GetPixel(vfIter.GetIndex()); VectorType update=eulerianInitCond->GetPixel(vfIter.GetIndex()); if (val > stepl) update = update * (stepl/val); VectorType upd=vfIter.Get()+update * (epsilon); vfIter.Set(upd); } ct++; lastdifmag=difmag; } // std::cout <<" difmag " << difmag << ": its " << ct << std::endl; return difmag; } void SetUseNearestNeighborInterpolation( bool useNN) { this->m_UseNN=useNN; } void SetUseBSplineInterpolation( bool useNN) { this->m_UseBSplineInterpolation=useNN; } protected: DeformationFieldPointer IntegrateVelocity(float,float); DeformationFieldPointer IntegrateLandmarkSetVelocity(float,float, PointSetPointer movingpoints, ImagePointer referenceimage ); VectorType IntegratePointVelocity(float starttimein, float finishtimein , IndexType startPoint); ImagePointer MakeSubImage( ImagePointer bigimage) { typedef itk::ImageRegionIteratorWithIndex<ImageType> Iterator; ImagePointer varimage=ImageType::New(); typename ImageType::RegionType region; typename ImageType::SizeType size=bigimage->GetLargestPossibleRegion().GetSize(); region.SetSize( this->m_CurrentDomainSize); typename ImageType::IndexType index; index.Fill(0); region.SetIndex(index); varimage->SetRegions( region ); varimage->SetSpacing(this->m_CurrentDomainSpacing); varimage->SetOrigin(bigimage->GetOrigin()); varimage->SetDirection(bigimage->GetDirection()); varimage->Allocate(); varimage->FillBuffer(0); typename ImageType::IndexType cornerind; cornerind.Fill(0); for (unsigned int ii=0; ii<ImageDimension; ii++) { float diff =(float)this->m_CurrentDomainOrigin[ii]-(float)this->m_CurrentDomainSize[ii]/2; if (diff < 0) diff=0; cornerind[ii]=(unsigned long) diff; } // std::cout << " corner index " << cornerind << std::endl; Iterator vfIter2( bigimage, bigimage->GetLargestPossibleRegion() ); for( vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 ) { typename ImageType::IndexType origindex=vfIter2.GetIndex(); typename ImageType::IndexType index=vfIter2.GetIndex(); bool oktosample=true; for (unsigned int ii=0; ii<ImageDimension; ii++) { float centerbasedcoord = (origindex[ii]-this->m_CurrentDomainOrigin[ii]); // float diff = // index[ii]=origindex[ii]-cornerind[ii]; if ( fabs(centerbasedcoord) > (this->m_CurrentDomainSize[ii]/2-1)) oktosample=false; } if (oktosample) { // std::cout << " index " << index << " origindex " << origindex << " ok? " << oktosample << std::endl; varimage->SetPixel(index,bigimage->GetPixel(origindex)); } } //std::cout << " sizes " << varimage->GetLargestPossibleRegion().GetSize() << " bigimage " << bigimage->GetLargestPossibleRegion().GetSize() << std::endl; return varimage; } float MeasureDeformation(DeformationFieldPointer field, int option=0) { typedef typename DeformationFieldType::PixelType VectorType; typedef typename DeformationFieldType::IndexType IndexType; typedef typename DeformationFieldType::SizeType SizeType; typedef typename VectorType::ValueType ScalarType; typedef ImageRegionIteratorWithIndex<DeformationFieldType> Iterator; // all we have to do here is add the local field to the global field. Iterator vfIter( field, field->GetLargestPossibleRegion() ); SizeType size=field->GetLargestPossibleRegion().GetSize(); unsigned long ct=1; double totalmag=0; float maxstep=0; // this->m_EuclideanNorm=0; typename ImageType::SpacingType myspacing = field->GetSpacing(); for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter ) { IndexType index=vfIter.GetIndex(); IndexType rindex=vfIter.GetIndex(); IndexType lindex=vfIter.GetIndex(); VectorType update=vfIter.Get(); float mag=0.0; float stepl=0.0; for (int i=0;i<ImageDimension;i++) { rindex=index; lindex=index; if ((int)index[i]< (int)(size[i]-2)) rindex[i]=rindex[i]+1; if (index[i]>2) lindex[i]=lindex[i]-1; VectorType rupdate=field->GetPixel(rindex); VectorType lupdate=field->GetPixel(lindex); VectorType dif=rupdate-lupdate; for (int tt=0; tt<ImageDimension; tt++) { stepl+=update[tt]*update[tt]/(myspacing[tt]*myspacing[tt]); mag+=dif[tt]*dif[tt]/(myspacing[tt]*myspacing[tt]); } } stepl=sqrt(stepl); mag=sqrt(mag); if (stepl > maxstep) maxstep=stepl; ct++; totalmag+=mag; // this->m_EuclideanNorm+=stepl; } //this->m_EuclideanNorm/=ct; //this->m_ElasticPathLength = totalmag/ct; //this->m_LinftyNorm = maxstep; // std::cout << " Elast path length " << this->m_ElasticPathLength << " L inf norm " << this->m_LinftyNorm << std::endl; //if (this->m_ElasticPathLength >= this->m_ArcLengthGoal) // if (maxstep >= this->m_ArcLengthGoal) { // this->StopRegistration(); // scale the field to the right length // float scale=this->m_ArcLengthGoal/this->m_ElasticPathLength; // for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter )vfIter.Set(vfIter.Get()*scale); } //if (this->m_LinftyNorm <= 0) this->m_LinftyNorm=1; //if (this->m_ElasticPathLength <= 0) this->m_ElasticPathLength=0; //if (this->m_EuclideanNorm <= 0) this->m_EuclideanNorm=0; //if (option==0) return this->m_ElasticPathLength; //else if (option==2) return this->m_EuclideanNorm; // else return maxstep; } ANTSImageRegistrationOptimizer(); virtual ~ANTSImageRegistrationOptimizer() {} void PrintSelf( std::ostream& os, Indent indent ) const; private: ANTSImageRegistrationOptimizer( const Self& ); //purposely not implemented void operator=( const Self& ); //purposely not implemented typename VelocityFieldInterpolatorType::Pointer m_VelocityFieldInterpolator; typename ImageType::SizeType m_CurrentDomainSize; typename ImageType::PointType m_CurrentDomainOrigin; typename ImageType::SpacingType m_CurrentDomainSpacing; typename ImageType::DirectionType m_CurrentDomainDirection; typename ImageType::SizeType m_FullDomainSize; typename ImageType::PointType m_FullDomainOrigin; typename ImageType::SpacingType m_FullDomainSpacing; AffineTransformPointer m_AffineTransform; AffineTransformPointer m_FixedImageAffineTransform; DeformationFieldPointer m_DeformationField; DeformationFieldPointer m_InverseDeformationField; std::vector<float> m_GradientDescentParameters; std::vector<float> m_MetricScalarWeights; std::vector<ImagePointer> m_SmoothFixedImages; std::vector<ImagePointer> m_SmoothMovingImages; bool m_Debug; unsigned int m_NumberOfLevels; typename ParserType::Pointer m_Parser; SimilarityMetricListType m_SimilarityMetrics; ImagePointer m_MaskImage; float m_ScaleFactor; bool m_UseMulti; bool m_UseROI; bool m_UseNN; bool m_UseBSplineInterpolation; unsigned int m_CurrentIteration; unsigned int m_CurrentLevel; std::string m_TransformationModel; std::string m_OutputNamingConvention; PointSetPointer m_FixedPointSet; PointSetPointer m_MovingPointSet; std::vector<unsigned int> m_Iterations; std::vector<float> m_RestrictDeformation; std::vector<float> m_RoiNumbers; float m_GradSmoothingparam; float m_TotalSmoothingparam; float m_Gradstep; float m_GradstepAltered; float m_NTimeSteps; float m_GaussianTruncation; float m_DeltaTime; float m_ESlope; /** energy stuff */ std::vector<float> m_Energy; std::vector<float> m_LastEnergy; std::vector<unsigned int> m_EnergyBad; /** for SyN only */ DeformationFieldPointer m_SyNF; DeformationFieldPointer m_SyNFInv; DeformationFieldPointer m_SyNM; DeformationFieldPointer m_SyNMInv; TimeVaryingVelocityFieldPointer m_TimeVaryingVelocity; TimeVaryingVelocityFieldPointer m_LastTimeVaryingVelocity; TimeVaryingVelocityFieldPointer m_LastTimeVaryingUpdate; unsigned int m_SyNType; /** for BSpline stuff */ unsigned int m_BSplineFieldOrder; ArrayType m_GradSmoothingMeshSize; ArrayType m_TotalSmoothingMeshSize; /** For thickness calculation */ ImagePointer m_HitImage; ImagePointer m_ThickImage; unsigned int m_ComputeThickness; unsigned int m_SyNFullTime; }; } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkANTSImageRegistrationOptimizer.cxx" #endif #endif
vfonov/mincANTS
ImageRegistration/itkANTSImageRegistrationOptimizer.h
C
bsd-3-clause
74,622
#!/bin/bash # AUTHOR: Léo Perrin <[email protected]> # Time-stamp: <2013-04-16 22:35:22 leo> # Append a pdf to the end of another. if (( $# < 1 )) then echo "Usage:" echo " concat-pdf.sh 1.pdf 2.pdf" echo "Creates a pdf called 1-2.pdf made of the concatenation of the"\ "content of 1.pdf and 2.pdf" echo "" echo " concat-pdf.sh pdf-to-append.pdf" echo "Prompts for a pdf file and appends pdf-to-append.pdf at the end"\ "of it. The result is stored in a new file." elif (( $# < 2 )) then main_pdf=$(zenity --text="The file "$1" will appended to:" \ --file-selection --file-filter="*.pdf" --filename=$(pwd)/) out=$(sed "s/\.[^\.]*//" <<< $main_pdf)-$(sed "s/\.[^\.]*//" <<< $1).pdf pdftk $main_pdf $1 cat output $out else out=$(sed "s/\.[^\.]*//" <<< $1)-$(sed "s/\.[^\.]*//" <<< $2).pdf pdftk $1 $2 cat output $out fi
picarresursix/my-nautilus-actions
images/concat-pdf.sh
Shell
bsd-3-clause
914
# intelengine ## Introduction intelengine aims to be an information gathering and exploitation architecture, it is based on the use of transforms, that convert one data type into another. For instance, a simple transform would be obtaining a list of domains from an IP address or a location history from a twitter nickname. ## Main goals The main goals of intelengine can be summarized in: * Simplicity * Modularity * Scalability * RESTful * Programming language agnostic ## Architecture intelengine consists in a client-server architecture. **intelsrv**, the server component, is an HTTP server that exposes a REST API, that allows the communication between server and clients. The mission of intelsrv is handling execution flows and distribute tasks between the different intelworker present in the architecture. Besides that, it also taskes care of error handling, concurrency and caching **intelworker**, the worker component is responsible for executing the commands issued by clients and transmit their results back to intelsrv. intelworker is designed to be programming language agnostic, so commands can be coded using any language that can read from STDIN and write to STDOUT. Finally, the **client** can be any program able to interact with the intelsrv's REST API. It is important to note that the communication between the different instances of intelserver and intelworker is carried out via a message broker using the amqp protocol. ``` +--------+ http +------------+ amqp +--------+ amqp +---------------+ | client |----+---->| intelsrv_1 |----+---->| BROKER |----+---->| intelworker_1 | +--------+ | +------------+ | +--------+ | +---------------+ | +------------+ | | +---------------+ +---->| intelsrv_2 |----+ +---->| intelworker_2 | | +------------+ | | +---------------+ | +------------+ | | +---------------+ +---->| intelsrv_n |----+ +---->| intelworker_m | +------------+ +---------------+ ``` ## Commands Commands live with intelworker and are splitted in two parts: * **Definition file** (cmd file) * **Implementation** (standalone executable) The command **definition file** is a JSON file that defines how the command is called. It must include the following information: * **Description**: Description of the command functionality * **Path**: Path of the executable that will be called when the command is executed * **Args**: Arguments passed to the executable when it is called * **Input**: Type of the input data * **Output**: Type of the output data * **Parameters**: Structure describing the type of the accepted parameters * **Group**: Command category The following snippet shows a dummy cmd file: ```json { "Description": "echo request's body", "Cmd": "cat", "Args": [], "Input": "", "Output": "", "Parameters": "", "Group": "debug" } ``` Also, the definition files must have the extension ".cmd", being the name of the command the name of the file without this extension. The command's **implementation** is an standalone executable that implements the command's functionality. By convention, it must wait for JSON input via STDIN and write its output in JSON format to STDOUT. Also, it must exit with the return value 0 when the execution finished correctly, or any other value on error. The input of the command is the body of the POST request sent to the intelsrv's path "/cmd/exec/\<cmdname\>". When the users makes this request, an unique ID will be generated and returned in the response. This way it is possible to retrieve the result of the command sending a GET request to "/cmd/result/\<uuid\>", being the output of the command returned to the client in the response body. If the command exited with error, this error will be returned in the "Error" field within the JSON response. Commands must take care of the input and output types specified in their definition file. Also, input and output must be treated as arrays of those types. For instance, if the input type is "IP", the command should expect an array of IPs as input. Due to these design principles, commands can be implemented in any programming language that can read from STDIN and write to STDOUT. ## Transforms vs Commands The word **command** was chosen rather than **transform**, because a transform can be considered as a particular class of command. It's important to take into account that intelengine is not only aimed at being used for data gathering but also for exploitation, crawlering, etc. ## intelsrv's routes The following routes are configured by default: * **GET /cmd/list**: List supported commands * **POST /cmd/exec/\<cmdname\>**: Execute the command \<cmdname\> * **GET /cmd/result/\<uuid\>**: Retrieve the result of the command linked to the UUID \<uuid\>
jroimartin/intelengine
README.md
Markdown
bsd-3-clause
5,004
module Watir module RowContainer # Returns a row in the table # * index - the index of the row def [](index) assert_exists TableRow.new(self, :ole_object, @o.rows.item(index)) end def strings assert_exists rows_memo = [] @o.rows.each do |row| cells_memo = [] row.cells.each do |cell| cells_memo << TableCell.new(self, :ole_object, cell).text end rows_memo << cells_memo end rows_memo end end # This class is used for dealing with tables. # Normally a user would not need to create this object as it is returned by the Watir::Container#table method # # many of the methods available to this object are inherited from the Element class # class Table < NonControlElement include RowContainer # override the highlight method, as if the tables rows are set to have a background color, # this will override the table background color, and the normal flash method won't work def highlight(set_or_clear) if set_or_clear == :set begin @original_border = @o.border.to_i if @o.border.to_i==1 @o.border = 2 else @o.border = 1 end rescue @original_border = nil end else begin @o.border= @original_border unless @original_border == nil @original_border = nil rescue # we could be here for a number of reasons... ensure @original_border = nil end end super end # this method is used to populate the properties in the to_s method def table_string_creator n = [] n << "rows:".ljust(TO_S_SIZE) + self.row_count.to_s n << "cols:".ljust(TO_S_SIZE) + self.column_count.to_s return n end private :table_string_creator # returns the properties of the object in a string # raises an ObjectNotFound exception if the object cannot be found def to_s assert_exists r = string_creator r += table_string_creator return r.join("\n") end # iterates through the rows in the table. Yields a TableRow object def each assert_exists @o.rows.each do |row| yield TableRow.new(self, :ole_object, row) end end # Returns the number of rows inside the table, including rows in nested tables. def row_count assert_exists rows.length end # This method returns the number of columns in a row of the table. # Raises an UnknownObjectException if the table doesn't exist. # * index - the index of the row def column_count(index=0) assert_exists row[index].cells.length end # Returns an array containing all the text values in the specified column # Raises an UnknownCellException if the specified column does not exist in every # Raises an UnknownObjectException if the table doesn't exist. # row of the table # * columnnumber - column index to extract values from def column_values(columnnumber) return (0..row_count - 1).collect {|i| self[i][columnnumber].text} end # Returns an array containing all the text values in the specified row # Raises an UnknownObjectException if the table doesn't exist. # * rownumber - row index to extract values from def row_values(rownumber) return (0..column_count(rownumber) - 1).collect {|i| self[rownumber][i].text} end def hashes assert_exists headers = [] @o.rows.item(0).cells.each do |cell| headers << TableCell.new(self, :ole_object, cell).text end rows_memo = [] i = 0 @o.rows.each do |row| next if row.uniqueID == @o.rows.item(0).uniqueID cells_memo = {} cells = row.cells raise "row at index #{i} has #{cells.length} cells, expected #{headers.length}" if cells.length < headers.length j = 0 cells.each do |cell| cells_memo[headers[j]] = TableCell.new(self, :ole_object, cell).text j += 1 end rows_memo << cells_memo i += 1 end rows_memo end end class TableSection < NonControlElement include RowContainer Watir::Container.module_eval do def tbody(how={}, what=nil) how = {how => what} if what TableSection.new(self, how.merge(:tag_name => "tbody"), nil) end def tbodys(how={}, what=nil) how = {how => what} if what TableSectionCollection.new(self, how.merge(:tag_name => "tbody"), nil) end def thead(how={}, what=nil) how = {how => what} if what TableSection.new(self, how.merge(:tag_name => "thead"), nil) end def theads(how={}, what=nil) how = {how => what} if what TableSectionCollection.new(self, how.merge(:tag_name => "thead"), nil) end def tfoot(how={}, what=nil) how = {how => what} if what TableSection.new(self, how.merge(:tag_name => "tfoot"), nil) end def tfoots(how={}, what=nil) how = {how => what} if what TableSectionCollection.new(self, how.merge(:tag_name => "tfoot"), nil) end end end class TableRow < NonControlElement TAG = "TR" # this method iterates through each of the cells in the row. Yields a TableCell object def each locate cells.each {|cell| yield cell} end # Returns an element from the row as a TableCell object def [](index) assert_exists if cells.length <= index raise UnknownCellException, "Unable to locate a cell at index #{index}" end return cells[index] end # defaults all missing methods to the array of elements, to be able to # use the row as an array # def method_missing(aSymbol, *args) # return @o.send(aSymbol, *args) # end def column_count locate cells.length end Watir::Container.module_eval do def row(how={}, what=nil) TableRow.new(self, how, what) end alias_method :tr, :row def rows(how={}, what=nil) TableRows.new(self, how, what) end alias_method :trs, :rows end end # this class is a table cell - when called via the Table object class TableCell < NonControlElement TAGS = ["TH", "TD"] alias to_s text def colspan locate @o.colSpan end Watir::Container.module_eval do def cell(how={}, what=nil) TableCell.new(self, how, what) end alias_method :td, :cell def cells(how={}, what=nil) TableCells.new(self, how, what) end alias_method :tds, :cells end end end
jarib/watir
watir/lib/watir/table.rb
Ruby
bsd-3-clause
6,849
<?php namespace PragmaRX\Health\Checkers; use GuzzleHttp\Client as Guzzle; use Illuminate\Support\Str; use PragmaRX\Health\Support\LocallyProtected; use PragmaRX\Health\Support\Result; class ServerVars extends Base { protected $response; protected $errors; /** * Check resource. * * @return Result */ public function check() { $this->requestServerVars(); collect($this->target->config['vars'])->each(function ($var) { $this->checkVar($var); }); return blank($this->errors) ? $this->makeHealthyResult() : $this->makeResult(false, sprintf($this->target->resource->errorMessage, implode('; ', $this->errors))); } public function requestServerVars() { $url = $this->makeUrl(); $bearer = (new LocallyProtected())->protect($this->target->config['cache_timeout'] ?? 60); $guzze = new Guzzle($this->getAuthorization()); $response = $guzze->request('GET', $url, [ 'headers' => ['API-Token' => $bearer], ]); if (($code = $response->getStatusCode()) !== 200) { throw new \Exception("Request to {$url} returned a status code {$code}"); } $this->response = json_decode((string) $response->getBody(), true); } public function checkVar($var) { if (blank($this->response[$var['name']] ?? null)) { if ($var['mandatory']) { $this->errors[] = "{$var['name']} is empty"; } return; } $got = $this->response[$var['name']]; $expected = $var['value']; if (! $this->compare($var, $expected, $got)) { $this->errors[] = "{$var['name']}: expected '{$expected}' but got '{$got}'"; } } public function compare($var, $expected, $got) { $operator = $var['operator'] ?? 'equals'; $strict = $var['strict'] ?? true; if ($operator === 'equals') { return $strict ? $expected === $got : $expected == $got; } if ($operator === 'contains') { return Str::contains($got, $expected); } throw new \Exception("Operator '$operator' is not supported."); } public function makeUrl() { $url = route($this->target->config['route']); if ($queryString = $this->target->config['query_string']) { $url .= "?$queryString"; } return $url; } public function getAuthorization() { if (blank($auth = $this->target->config['auth'] ?? null)) { return []; } return ['auth' => [$auth['username'], $auth['password']]]; } }
antonioribeiro/health
src/Checkers/ServerVars.php
PHP
bsd-3-clause
2,717
<aside class="main-sidebar"> <section class="sidebar"> <?= dmstr\widgets\Menu::widget( [ 'options' => ['class' => 'sidebar-menu'], 'items' => [ ['label' => 'Menu', 'options' => ['class' => 'header']], ['label' => 'Home', 'icon' => 'fa fa-area-chart', 'url' => ['/site/index']], ['label' => 'Login', 'url' => ['site/login'], 'visible' => Yii::$app->user->isGuest], [ 'label' => 'Lesson', 'icon' => 'fa fa-book', 'url' => '#', 'items' => [ ['label' => 'Index', 'icon' => 'fa fa-th-list', 'url' => ['/lesson/index'],], ['label' => 'Create', 'icon' => 'fa fa-edit', 'url' => ['/lesson/create'],], ], ], [ 'label' => 'App User', 'icon' => 'fa fa-group', 'url' => '#', 'items' => [ ['label' => 'Points', 'icon' => 'fa fa-dollar', 'url' => ['/user-earned-point/index'],], ['label' => 'Score', 'icon' => 'fa fa-graduation-cap', 'url' => ['/user-score/index'],], ], ], ], ] ) ?> </section> </aside>
mehdihasan/new_english
admin/layouts/left.php
PHP
bsd-3-clause
1,482
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/optimization_guide/optimization_guide_web_contents_observer.h" #include "chrome/browser/optimization_guide/chrome_hints_manager.h" #include "chrome/browser/optimization_guide/optimization_guide_keyed_service.h" #include "chrome/browser/optimization_guide/optimization_guide_keyed_service_factory.h" #include "chrome/browser/prefetch/no_state_prefetch/no_state_prefetch_manager_factory.h" #include "chrome/browser/profiles/profile.h" #include "components/no_state_prefetch/browser/no_state_prefetch_manager.h" #include "components/optimization_guide/core/hints_fetcher.h" #include "components/optimization_guide/core/hints_processing_util.h" #include "components/optimization_guide/core/optimization_guide_enums.h" #include "components/optimization_guide/core/optimization_guide_features.h" #include "components/optimization_guide/proto/hints.pb.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents.h" namespace { bool IsValidOptimizationGuideNavigation( content::NavigationHandle* navigation_handle) { if (!navigation_handle->IsInPrimaryMainFrame()) return false; if (!navigation_handle->GetURL().SchemeIsHTTPOrHTTPS()) return false; // Now check if this is a NSP navigation. NSP is not a valid navigation. prerender::NoStatePrefetchManager* no_state_prefetch_manager = prerender::NoStatePrefetchManagerFactory::GetForBrowserContext( navigation_handle->GetWebContents()->GetBrowserContext()); if (!no_state_prefetch_manager) { // Not a NSP navigation if there is no NSP manager. return true; } return !(no_state_prefetch_manager->IsWebContentsPrerendering( navigation_handle->GetWebContents())); } } // namespace OptimizationGuideWebContentsObserver::OptimizationGuideWebContentsObserver( content::WebContents* web_contents) : content::WebContentsObserver(web_contents) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); optimization_guide_keyed_service_ = OptimizationGuideKeyedServiceFactory::GetForProfile( Profile::FromBrowserContext(web_contents->GetBrowserContext())); } OptimizationGuideWebContentsObserver::~OptimizationGuideWebContentsObserver() = default; OptimizationGuideNavigationData* OptimizationGuideWebContentsObserver:: GetOrCreateOptimizationGuideNavigationData( content::NavigationHandle* navigation_handle) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_EQ(web_contents(), navigation_handle->GetWebContents()); NavigationHandleData* navigation_handle_data = NavigationHandleData::GetOrCreateForNavigationHandle(*navigation_handle); OptimizationGuideNavigationData* navigation_data = navigation_handle_data->GetOptimizationGuideNavigationData(); if (!navigation_data) { // We do not have one already - create one. navigation_handle_data->SetOptimizationGuideNavigationData( std::make_unique<OptimizationGuideNavigationData>( navigation_handle->GetNavigationId(), navigation_handle->NavigationStart())); navigation_data = navigation_handle_data->GetOptimizationGuideNavigationData(); } DCHECK(navigation_data); return navigation_data; } void OptimizationGuideWebContentsObserver::DidStartNavigation( content::NavigationHandle* navigation_handle) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!IsValidOptimizationGuideNavigation(navigation_handle)) return; if (!optimization_guide_keyed_service_) return; OptimizationGuideNavigationData* navigation_data = GetOrCreateOptimizationGuideNavigationData(navigation_handle); navigation_data->set_navigation_url(navigation_handle->GetURL()); optimization_guide_keyed_service_->OnNavigationStartOrRedirect( navigation_data); } void OptimizationGuideWebContentsObserver::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!IsValidOptimizationGuideNavigation(navigation_handle)) return; if (!optimization_guide_keyed_service_) return; OptimizationGuideNavigationData* navigation_data = GetOrCreateOptimizationGuideNavigationData(navigation_handle); navigation_data->set_navigation_url(navigation_handle->GetURL()); optimization_guide_keyed_service_->OnNavigationStartOrRedirect( navigation_data); } void OptimizationGuideWebContentsObserver::DidFinishNavigation( content::NavigationHandle* navigation_handle) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!IsValidOptimizationGuideNavigation(navigation_handle)) return; // Note that a lot of Navigations (same document, non-committed, etc.) might // not have navigation data associated with them, but we reduce likelihood of // future leaks by always trying to remove the data. NavigationHandleData* navigation_handle_data = NavigationHandleData::GetForNavigationHandle(*navigation_handle); if (!navigation_handle_data) return; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce( &OptimizationGuideWebContentsObserver::NotifyNavigationFinish, weak_factory_.GetWeakPtr(), navigation_handle_data->TakeOptimizationGuideNavigationData(), navigation_handle->GetRedirectChain())); } void OptimizationGuideWebContentsObserver::PostFetchHintsUsingManager( content::RenderFrameHost* render_frame_host) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!render_frame_host->GetLastCommittedURL().SchemeIsHTTPOrHTTPS()) return; if (!optimization_guide_keyed_service_) return; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce( &OptimizationGuideWebContentsObserver::FetchHintsUsingManager, weak_factory_.GetWeakPtr(), optimization_guide_keyed_service_->GetHintsManager(), web_contents()->GetPrimaryPage().GetWeakPtr())); } void OptimizationGuideWebContentsObserver::FetchHintsUsingManager( optimization_guide::ChromeHintsManager* hints_manager, base::WeakPtr<content::Page> page) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(hints_manager); if (!page) return; PageData& page_data = GetPageData(*page); page_data.set_sent_batched_hints_request(); hints_manager->FetchHintsForURLs( page_data.GetHintsTargetUrls(), optimization_guide::proto::CONTEXT_BATCH_UPDATE_GOOGLE_SRP); } void OptimizationGuideWebContentsObserver::NotifyNavigationFinish( std::unique_ptr<OptimizationGuideNavigationData> navigation_data, const std::vector<GURL>& navigation_redirect_chain) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (optimization_guide_keyed_service_) { optimization_guide_keyed_service_->OnNavigationFinish( navigation_redirect_chain); } // We keep the navigation data in the PageData around to keep track of events // happening for the navigation that can happen after commit, such as a fetch // for the navigation successfully completing (which is not guaranteed to come // back before commit, if at all). PageData& page_data = GetPageData(web_contents()->GetPrimaryPage()); page_data.SetNavigationData(std::move(navigation_data)); } void OptimizationGuideWebContentsObserver::FlushLastNavigationData() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); PageData& page_data = GetPageData(web_contents()->GetPrimaryPage()); page_data.SetNavigationData(nullptr); } void OptimizationGuideWebContentsObserver::AddURLsToBatchFetchBasedOnPrediction( std::vector<GURL> urls, content::WebContents* web_contents) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!this->web_contents()) return; DCHECK_EQ(this->web_contents(), web_contents); PageData& page_data = GetPageData(web_contents->GetPrimaryPage()); if (page_data.is_sent_batched_hints_request()) return; page_data.InsertHintTargetUrls(urls); PostFetchHintsUsingManager(web_contents->GetMainFrame()); } OptimizationGuideWebContentsObserver::PageData& OptimizationGuideWebContentsObserver::GetPageData(content::Page& page) { return *PageData::GetOrCreateForPage(page); } OptimizationGuideWebContentsObserver::PageData::PageData(content::Page& page) : PageUserData(page) {} OptimizationGuideWebContentsObserver::PageData::~PageData() = default; void OptimizationGuideWebContentsObserver::PageData::InsertHintTargetUrls( const std::vector<GURL>& urls) { DCHECK(!sent_batched_hints_request_); for (const GURL& url : urls) hints_target_urls_.insert(url); } std::vector<GURL> OptimizationGuideWebContentsObserver::PageData::GetHintsTargetUrls() { std::vector<GURL> target_urls = std::move(hints_target_urls_.vector()); hints_target_urls_.clear(); return target_urls; } OptimizationGuideWebContentsObserver::NavigationHandleData:: NavigationHandleData(content::NavigationHandle&) {} OptimizationGuideWebContentsObserver::NavigationHandleData:: ~NavigationHandleData() = default; PAGE_USER_DATA_KEY_IMPL(OptimizationGuideWebContentsObserver::PageData); NAVIGATION_HANDLE_USER_DATA_KEY_IMPL( OptimizationGuideWebContentsObserver::NavigationHandleData); WEB_CONTENTS_USER_DATA_KEY_IMPL(OptimizationGuideWebContentsObserver);
nwjs/chromium.src
chrome/browser/optimization_guide/optimization_guide_web_contents_observer.cc
C++
bsd-3-clause
9,522
// GLFW Engine. // ----------------------------------------------------------------------------- // Copyright (C) 2011, ZEUS project (See authors) // // This program is open source and distributed under the New BSD License. See // license for more detail. // ----------------------------------------------------------------------------- #include <Core/GLFWEngine.h> #include <Devices/GLFWKeyboard.h> #include <Devices/GLFWMouse.h> #include <Display/Camera.h> #include <Display/GLFWWindow.h> #include <Math/Vector.h> #include <GL/glfw.h> #include <stdlib.h> using namespace ZEUS::Display; using namespace ZEUS::Devices; using namespace ZEUS::Math; namespace ZEUS { namespace Core { GLFWEngine::GLFWEngine() : IEngine() { if (!glfwInit()) exit(EXIT_FAILURE); Vector<2, unsigned int> res(800, 600); window = new Display::GLFWWindow(res); IKeyboard::Add<GLFWKeyboard>(); IMouse::Add<GLFWMouse>(); } GLFWEngine::~GLFWEngine(){ glfwTerminate(); } GLFWEngine* GLFWEngine::CreateEngine(){ GLFWEngine* tmp = new GLFWEngine(); engine = tmp; return tmp; } void GLFWEngine::Initialize(){ glfwSetTime(0.0); } double GLFWEngine::GetImplTime(){ return glfwGetTime(); } } }
papaboo/The-ZEUS-Project
extensions/GLFW/Core/GLFWEngine.cpp
C++
bsd-3-clause
1,427
/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <folly/Conv.h> #include <folly/Foreach.h> #include <folly/wangle/acceptor/ConnectionManager.h> #include <folly/io/Cursor.h> #include <folly/io/async/EventBase.h> #include <folly/io/async/EventBaseManager.h> #include <folly/io/async/TimeoutManager.h> #include <gtest/gtest.h> #include <proxygen/lib/http/codec/test/MockHTTPCodec.h> #include <proxygen/lib/http/codec/test/TestUtils.h> #include <proxygen/lib/http/session/HTTPDirectResponseHandler.h> #include <proxygen/lib/http/session/HTTPDownstreamSession.h> #include <proxygen/lib/http/session/HTTPSession.h> #include <proxygen/lib/http/session/test/HTTPSessionMocks.h> #include <proxygen/lib/http/session/test/HTTPSessionTest.h> #include <proxygen/lib/http/session/test/MockByteEventTracker.h> #include <proxygen/lib/http/session/test/TestUtils.h> #include <proxygen/lib/test/TestAsyncTransport.h> #include <string> #include <strstream> #include <folly/io/async/test/MockAsyncTransport.h> #include <vector> using namespace folly::wangle; using namespace folly; using namespace proxygen; using namespace std; using namespace testing; struct HTTP1xCodecPair { typedef HTTP1xCodec Codec; static const int version = 1; }; struct HTTP2CodecPair { typedef HTTP2Codec Codec; static const int version = 2; }; struct SPDY2CodecPair { typedef SPDYCodec Codec; static const SPDYVersion version = SPDYVersion::SPDY2; }; struct SPDY3CodecPair { typedef SPDYCodec Codec; static const SPDYVersion version = SPDYVersion::SPDY3; }; struct SPDY3_1CodecPair { typedef SPDYCodec Codec; static const SPDYVersion version = SPDYVersion::SPDY3_1; }; template <typename C> class HTTPDownstreamTest : public testing::Test { public: explicit HTTPDownstreamTest(uint32_t sessionWindowSize = spdy::kInitialWindow) : eventBase_(), transport_(new TestAsyncTransport(&eventBase_)), transactionTimeouts_(makeTimeoutSet(&eventBase_)) { EXPECT_CALL(mockController_, attachSession(_)); httpSession_ = new HTTPDownstreamSession( transactionTimeouts_.get(), std::move(AsyncTransportWrapper::UniquePtr(transport_)), localAddr, peerAddr, &mockController_, std::move(makeServerCodec<typename C::Codec>( C::version)), mockTransportInfo /* no stats for now */); httpSession_->setFlowControl(spdy::kInitialWindow, spdy::kInitialWindow, sessionWindowSize); httpSession_->startNow(); } void SetUp() { folly::EventBaseManager::get()->clearEventBase(); HTTPSession::setPendingWriteMax(65536); } void addSingleByteReads(const char* data, std::chrono::milliseconds delay={}) { for (const char* p = data; *p != '\0'; ++p) { transport_->addReadEvent(p, 1, delay); } } void testPriorities(HTTPCodec& clientCodec, uint32_t numPriorities); void testChunks(bool trailers); void parseOutput(HTTPCodec& clientCodec) { IOBufQueue stream(IOBufQueue::cacheChainLength()); auto writeEvents = transport_->getWriteEvents(); for (auto event: *writeEvents) { auto vec = event->getIoVec(); for (size_t i = 0; i < event->getCount(); i++) { unique_ptr<IOBuf> buf( std::move(IOBuf::wrapBuffer(vec[i].iov_base, vec[i].iov_len))); stream.append(std::move(buf)); uint32_t consumed = clientCodec.onIngress(*stream.front()); stream.split(consumed); } } EXPECT_EQ(stream.chainLength(), 0); } protected: EventBase eventBase_; TestAsyncTransport* transport_; // invalid once httpSession_ is destroyed AsyncTimeoutSet::UniquePtr transactionTimeouts_; StrictMock<MockController> mockController_; HTTPDownstreamSession* httpSession_; }; // Uses TestAsyncTransport typedef HTTPDownstreamTest<HTTP1xCodecPair> HTTPDownstreamSessionTest; typedef HTTPDownstreamTest<SPDY2CodecPair> SPDY2DownstreamSessionTest; typedef HTTPDownstreamTest<SPDY3CodecPair> SPDY3DownstreamSessionTest; TEST_F(HTTPDownstreamSessionTest, immediate_eof) { // Send EOF without any request data EXPECT_CALL(mockController_, getRequestHandler(_, _)).Times(0); EXPECT_CALL(mockController_, detachSession(_)); transport_->addReadEOF(std::chrono::milliseconds(0)); transport_->startReadEvents(); eventBase_.loop(); } TEST_F(HTTPDownstreamSessionTest, http_1_0_no_headers) { MockHTTPHandler* handler = new MockHTTPHandler(); InSequence dummy; EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(handler)); EXPECT_CALL(*handler, setTransaction(_)) .WillOnce(SaveArg<0>(&handler->txn_)); EXPECT_CALL(*handler, onHeadersComplete(_)) .WillOnce(Invoke([&] (std::shared_ptr<HTTPMessage> msg) { EXPECT_FALSE(msg->getIsChunked()); EXPECT_FALSE(msg->getIsUpgraded()); EXPECT_EQ("/", msg->getURL()); EXPECT_EQ("/", msg->getPath()); EXPECT_EQ("", msg->getQueryString()); EXPECT_EQ(1, msg->getHTTPVersion().first); EXPECT_EQ(0, msg->getHTTPVersion().second); })); EXPECT_CALL(*handler, onEOM()) .WillOnce(InvokeWithoutArgs(handler, &MockHTTPHandler::terminate)); EXPECT_CALL(*handler, detachTransaction()) .WillOnce(InvokeWithoutArgs([&] { delete handler; })); EXPECT_CALL(mockController_, detachSession(_)); transport_->addReadEvent("GET / HTTP/1.0\r\n\r\n", std::chrono::milliseconds(0)); transport_->startReadEvents(); eventBase_.loop(); } TEST_F(HTTPDownstreamSessionTest, http_1_0_no_headers_eof) { MockHTTPHandler* handler = new MockHTTPHandler(); InSequence dummy; EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(handler)); EXPECT_CALL(*handler, setTransaction(_)) .WillOnce(SaveArg<0>(&handler->txn_)); EXPECT_CALL(*handler, onHeadersComplete(_)) .WillOnce(Invoke([&] (std::shared_ptr<HTTPMessage> msg) { EXPECT_FALSE(msg->getIsChunked()); EXPECT_FALSE(msg->getIsUpgraded()); EXPECT_EQ("http://example.com/foo?bar", msg->getURL()); EXPECT_EQ("/foo", msg->getPath()); EXPECT_EQ("bar", msg->getQueryString()); EXPECT_EQ(1, msg->getHTTPVersion().first); EXPECT_EQ(0, msg->getHTTPVersion().second); })); EXPECT_CALL(*handler, onEOM()) .WillOnce(InvokeWithoutArgs(handler, &MockHTTPHandler::terminate)); EXPECT_CALL(*handler, detachTransaction()) .WillOnce(InvokeWithoutArgs([&] { delete handler; })); EXPECT_CALL(mockController_, detachSession(_)); transport_->addReadEvent("GET http://example.com/foo?bar HTTP/1.0\r\n\r\n", std::chrono::milliseconds(0)); transport_->addReadEOF(std::chrono::milliseconds(0)); transport_->startReadEvents(); eventBase_.loop(); } TEST_F(HTTPDownstreamSessionTest, single_bytes) { MockHTTPHandler* handler = new MockHTTPHandler(); InSequence dummy; EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(handler)); EXPECT_CALL(*handler, setTransaction(_)) .WillOnce(SaveArg<0>(&handler->txn_)); EXPECT_CALL(*handler, onHeadersComplete(_)) .WillOnce(Invoke([&] (std::shared_ptr<HTTPMessage> msg) { const HTTPHeaders& hdrs = msg->getHeaders(); EXPECT_EQ(2, hdrs.size()); EXPECT_TRUE(hdrs.exists("host")); EXPECT_TRUE(hdrs.exists("connection")); EXPECT_FALSE(msg->getIsChunked()); EXPECT_FALSE(msg->getIsUpgraded()); EXPECT_EQ("/somepath.php?param=foo", msg->getURL()); EXPECT_EQ("/somepath.php", msg->getPath()); EXPECT_EQ("param=foo", msg->getQueryString()); EXPECT_EQ(1, msg->getHTTPVersion().first); EXPECT_EQ(1, msg->getHTTPVersion().second); })); EXPECT_CALL(*handler, onEOM()) .WillOnce(InvokeWithoutArgs(handler, &MockHTTPHandler::terminate)); EXPECT_CALL(*handler, detachTransaction()) .WillOnce(InvokeWithoutArgs([&] { delete handler; })); EXPECT_CALL(mockController_, detachSession(_)); addSingleByteReads("GET /somepath.php?param=foo HTTP/1.1\r\n" "Host: example.com\r\n" "Connection: close\r\n" "\r\n"); transport_->addReadEOF(std::chrono::milliseconds(0)); transport_->startReadEvents(); eventBase_.loop(); } TEST_F(HTTPDownstreamSessionTest, single_bytes_with_body) { MockHTTPHandler* handler = new MockHTTPHandler(); InSequence dummy; EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(handler)); EXPECT_CALL(*handler, setTransaction(_)) .WillOnce(SaveArg<0>(&handler->txn_)); EXPECT_CALL(*handler, onHeadersComplete(_)) .WillOnce(Invoke([&] (std::shared_ptr<HTTPMessage> msg) { const HTTPHeaders& hdrs = msg->getHeaders(); EXPECT_EQ(3, hdrs.size()); EXPECT_TRUE(hdrs.exists("host")); EXPECT_TRUE(hdrs.exists("content-length")); EXPECT_TRUE(hdrs.exists("myheader")); EXPECT_FALSE(msg->getIsChunked()); EXPECT_FALSE(msg->getIsUpgraded()); EXPECT_EQ("/somepath.php?param=foo", msg->getURL()); EXPECT_EQ("/somepath.php", msg->getPath()); EXPECT_EQ("param=foo", msg->getQueryString()); EXPECT_EQ(1, msg->getHTTPVersion().first); EXPECT_EQ(1, msg->getHTTPVersion().second); })); EXPECT_CALL(*handler, onBody(_)) .WillOnce(ExpectString("1")) .WillOnce(ExpectString("2")) .WillOnce(ExpectString("3")) .WillOnce(ExpectString("4")) .WillOnce(ExpectString("5")); EXPECT_CALL(*handler, onEOM()) .WillOnce(InvokeWithoutArgs(handler, &MockHTTPHandler::terminate)); EXPECT_CALL(*handler, detachTransaction()) .WillOnce(InvokeWithoutArgs([&] { delete handler; })); EXPECT_CALL(mockController_, detachSession(_)); addSingleByteReads("POST /somepath.php?param=foo HTTP/1.1\r\n" "Host: example.com\r\n" "MyHeader: FooBar\r\n" "Content-Length: 5\r\n" "\r\n" "12345"); transport_->addReadEOF(std::chrono::milliseconds(0)); transport_->startReadEvents(); eventBase_.loop(); } TEST_F(HTTPDownstreamSessionTest, split_body) { MockHTTPHandler* handler = new MockHTTPHandler(); InSequence dummy; EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(handler)); EXPECT_CALL(*handler, setTransaction(_)) .WillOnce(SaveArg<0>(&handler->txn_)); EXPECT_CALL(*handler, onHeadersComplete(_)) .WillOnce(Invoke([&] (std::shared_ptr<HTTPMessage> msg) { const HTTPHeaders& hdrs = msg->getHeaders(); EXPECT_EQ(2, hdrs.size()); })); EXPECT_CALL(*handler, onBody(_)) .WillOnce(ExpectString("12345")) .WillOnce(ExpectString("abcde")); EXPECT_CALL(*handler, onEOM()) .WillOnce(InvokeWithoutArgs(handler, &MockHTTPHandler::terminate)); EXPECT_CALL(*handler, detachTransaction()) .WillOnce(InvokeWithoutArgs([&] { delete handler; })); EXPECT_CALL(mockController_, detachSession(_)); transport_->addReadEvent("POST / HTTP/1.1\r\n" "Host: example.com\r\n" "Content-Length: 10\r\n" "\r\n" "12345", std::chrono::milliseconds(0)); transport_->addReadEvent("abcde", std::chrono::milliseconds(5)); transport_->addReadEOF(std::chrono::milliseconds(0)); transport_->startReadEvents(); eventBase_.loop(); } TEST_F(HTTPDownstreamSessionTest, post_chunked) { MockHTTPHandler* handler = new MockHTTPHandler(); InSequence dummy; EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(handler)); EXPECT_CALL(*handler, setTransaction(_)) .WillOnce(SaveArg<0>(&handler->txn_)); EXPECT_CALL(*handler, onHeadersComplete(_)) .WillOnce(Invoke([&] (std::shared_ptr<HTTPMessage> msg) { const HTTPHeaders& hdrs = msg->getHeaders(); EXPECT_EQ(3, hdrs.size()); EXPECT_TRUE(hdrs.exists("host")); EXPECT_TRUE(hdrs.exists("content-type")); EXPECT_TRUE(hdrs.exists("transfer-encoding")); EXPECT_TRUE(msg->getIsChunked()); EXPECT_FALSE(msg->getIsUpgraded()); EXPECT_EQ("http://example.com/cgi-bin/foo.aspx?abc&def", msg->getURL()); EXPECT_EQ("/cgi-bin/foo.aspx", msg->getPath()); EXPECT_EQ("abc&def", msg->getQueryString()); EXPECT_EQ(1, msg->getHTTPVersion().first); EXPECT_EQ(1, msg->getHTTPVersion().second); })); EXPECT_CALL(*handler, onChunkHeader(3)); EXPECT_CALL(*handler, onBody(_)) .WillOnce(ExpectString("bar")); EXPECT_CALL(*handler, onChunkComplete()); EXPECT_CALL(*handler, onChunkHeader(0x22)); EXPECT_CALL(*handler, onBody(_)) .WillOnce(ExpectString("0123456789abcdef\nfedcba9876543210\n")); EXPECT_CALL(*handler, onChunkComplete()); EXPECT_CALL(*handler, onChunkHeader(3)); EXPECT_CALL(*handler, onBody(_)) .WillOnce(ExpectString("foo")); EXPECT_CALL(*handler, onChunkComplete()); EXPECT_CALL(*handler, onEOM()) .WillOnce(InvokeWithoutArgs(handler, &MockHTTPHandler::terminate)); EXPECT_CALL(*handler, detachTransaction()) .WillOnce(InvokeWithoutArgs([&] { delete handler; })); EXPECT_CALL(mockController_, detachSession(_)); transport_->addReadEvent("POST http://example.com/cgi-bin/foo.aspx?abc&def " "HTTP/1.1\r\n" "Host: example.com\r\n" "Content-Type: text/pla", std::chrono::milliseconds(0)); transport_->addReadEvent("in; charset=utf-8\r\n" "Transfer-encoding: chunked\r\n" "\r", std::chrono::milliseconds(2)); transport_->addReadEvent("\n" "3\r\n" "bar\r\n" "22\r\n" "0123456789abcdef\n" "fedcba9876543210\n" "\r\n" "3\r", std::chrono::milliseconds(3)); transport_->addReadEvent("\n" "foo\r\n" "0\r\n\r\n", std::chrono::milliseconds(1)); transport_->startReadEvents(); eventBase_.loop(); } TEST_F(HTTPDownstreamSessionTest, multi_message) { MockHTTPHandler* handler1 = new MockHTTPHandler(); MockHTTPHandler* handler2 = new MockHTTPHandler(); EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(handler1)) .WillOnce(Return(handler2)); InSequence dummy; EXPECT_CALL(*handler1, setTransaction(_)) .WillOnce(SaveArg<0>(&handler1->txn_)); EXPECT_CALL(*handler1, onHeadersComplete(_)); EXPECT_CALL(*handler1, onBody(_)) .WillOnce(ExpectString("foo")) .WillOnce(ExpectString("bar9876")); EXPECT_CALL(*handler1, onEOM()) .WillOnce(InvokeWithoutArgs(handler1, &MockHTTPHandler::sendReply)); EXPECT_CALL(*handler1, detachTransaction()) .WillOnce(InvokeWithoutArgs([&] { delete handler1; })); EXPECT_CALL(*handler2, setTransaction(_)) .WillOnce(SaveArg<0>(&handler2->txn_)); EXPECT_CALL(*handler2, onHeadersComplete(_)); EXPECT_CALL(*handler2, onChunkHeader(0xa)); EXPECT_CALL(*handler2, onBody(_)) .WillOnce(ExpectString("some ")) .WillOnce(ExpectString("data\n")); EXPECT_CALL(*handler2, onChunkComplete()); EXPECT_CALL(*handler2, onEOM()) .WillOnce(InvokeWithoutArgs(handler2, &MockHTTPHandler::terminate)); EXPECT_CALL(*handler2, detachTransaction()) .WillOnce(InvokeWithoutArgs([&] { delete handler2; })); EXPECT_CALL(mockController_, detachSession(_)); transport_->addReadEvent("POST / HTTP/1.1\r\n" "Host: example.com\r\n" "Content-Length: 10\r\n" "\r\n" "foo", std::chrono::milliseconds(0)); transport_->addReadEvent("bar9876" "POST /foo HTTP/1.1\r\n" "Host: exa", std::chrono::milliseconds(2)); transport_->addReadEvent("mple.com\r\n" "Connection: close\r\n" "Trans", std::chrono::milliseconds(0)); transport_->addReadEvent("fer-encoding: chunked\r\n" "\r\n", std::chrono::milliseconds(2)); transport_->addReadEvent("a\r\nsome ", std::chrono::milliseconds(0)); transport_->addReadEvent("data\n\r\n0\r\n\r\n", std::chrono::milliseconds(2)); transport_->addReadEOF(std::chrono::milliseconds(0)); transport_->startReadEvents(); eventBase_.loop(); } TEST_F(HTTPDownstreamSessionTest, connect) { StrictMock<MockHTTPHandler> handler; InSequence dummy; EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handler)); EXPECT_CALL(handler, setTransaction(_)) .WillOnce(SaveArg<0>(&handler.txn_)); // Send HTTP 200 OK to accept the CONNECT request EXPECT_CALL(handler, onHeadersComplete(_)) .WillOnce(Invoke([&handler] (std::shared_ptr<HTTPMessage> msg) { handler.sendHeaders(200, 100); })); EXPECT_CALL(handler, onUpgrade(_)); // Data should be received using onBody EXPECT_CALL(handler, onBody(_)) .WillOnce(ExpectString("12345")) .WillOnce(ExpectString("abcde")); EXPECT_CALL(handler, onEOM()) .WillOnce(InvokeWithoutArgs(&handler, &MockHTTPHandler::terminate)); EXPECT_CALL(handler, detachTransaction()); EXPECT_CALL(mockController_, detachSession(_)); transport_->addReadEvent("CONNECT test HTTP/1.1\r\n" "\r\n" "12345", std::chrono::milliseconds(0)); transport_->addReadEvent("abcde", std::chrono::milliseconds(5)); transport_->addReadEOF(std::chrono::milliseconds(0)); transport_->startReadEvents(); eventBase_.loop(); } TEST_F(HTTPDownstreamSessionTest, connect_rejected) { StrictMock<MockHTTPHandler> handler; InSequence dummy; EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handler)); EXPECT_CALL(handler, setTransaction(_)) .WillOnce(SaveArg<0>(&handler.txn_)); // Send HTTP 400 to reject the CONNECT request EXPECT_CALL(handler, onHeadersComplete(_)) .WillOnce(Invoke([&handler] (std::shared_ptr<HTTPMessage> msg) { handler.sendReplyCode(400); })); EXPECT_CALL(handler, onEOM()) .WillOnce(InvokeWithoutArgs(&handler, &MockHTTPHandler::terminate)); EXPECT_CALL(handler, detachTransaction()); EXPECT_CALL(mockController_, detachSession(_)); transport_->addReadEvent("CONNECT test HTTP/1.1\r\n" "\r\n" "12345", std::chrono::milliseconds(0)); transport_->addReadEvent("abcde", std::chrono::milliseconds(5)); transport_->addReadEOF(std::chrono::milliseconds(0)); transport_->startReadEvents(); eventBase_.loop(); } TEST_F(HTTPDownstreamSessionTest, http_upgrade) { StrictMock<MockHTTPHandler> handler; InSequence dummy; EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handler)); EXPECT_CALL(handler, setTransaction(_)) .WillOnce(SaveArg<0>(&handler.txn_)); // Send HTTP 101 Switching Protocls to accept the upgrade request EXPECT_CALL(handler, onHeadersComplete(_)) .WillOnce(Invoke([&handler] (std::shared_ptr<HTTPMessage> msg) { handler.sendHeaders(101, 100); })); // Send the response in the new protocol after upgrade EXPECT_CALL(handler, onUpgrade(_)) .WillOnce(Invoke([&handler] (UpgradeProtocol protocol) { handler.sendReplyCode(100); })); EXPECT_CALL(handler, onEOM()) .WillOnce(InvokeWithoutArgs(&handler, &MockHTTPHandler::terminate)); EXPECT_CALL(handler, detachTransaction()); EXPECT_CALL(mockController_, detachSession(_)); transport_->addReadEvent("GET /upgrade HTTP/1.1\r\n" "Upgrade: TEST/1.0\r\n" "Connection: upgrade\r\n" "\r\n", std::chrono::milliseconds(0)); transport_->addReadEOF(std::chrono::milliseconds(0)); transport_->startReadEvents(); eventBase_.loop(); } TEST(HTTPDownstreamTest, parse_error_no_txn) { // 1) Get a parse error on SYN_STREAM for streamID == 1 // 2) Expect that the codec should be asked to generate an abort on // streamID==1 EventBase evb; // Setup the controller and its expecations. NiceMock<MockController> mockController; // Setup the codec, its callbacks, and its expectations. auto codec = makeDownstreamParallelCodec(); HTTPCodec::Callback* codecCallback = nullptr; EXPECT_CALL(*codec, setCallback(_)) .WillRepeatedly(SaveArg<0>(&codecCallback)); // Expect egress abort for streamID == 1 EXPECT_CALL(*codec, generateRstStream(_, 1, _)); // Setup transport bool transportGood = true; auto transport = newMockTransport(&evb); EXPECT_CALL(*transport, good()) .WillRepeatedly(ReturnPointee(&transportGood)); EXPECT_CALL(*transport, closeNow()) .WillRepeatedly(Assign(&transportGood, false)); EXPECT_CALL(*transport, writeChain(_, _, _)) .WillRepeatedly(Invoke([&] (folly::AsyncTransportWrapper::WriteCallback* callback, const shared_ptr<IOBuf> iob, WriteFlags flags) { callback->writeSuccess(); })); // Create the downstream session, thus initializing codecCallback auto transactionTimeouts = makeInternalTimeoutSet(&evb); auto session = new HTTPDownstreamSession( transactionTimeouts.get(), AsyncTransportWrapper::UniquePtr(transport), localAddr, peerAddr, &mockController, std::move(codec), mockTransportInfo); session->startNow(); HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS, "foo"); ex.setProxygenError(kErrorParseHeader); ex.setCodecStatusCode(ErrorCode::REFUSED_STREAM); codecCallback->onError(HTTPCodec::StreamID(1), ex, true); // cleanup session->shutdownTransportWithReset(kErrorConnectionReset); evb.loop(); } TEST(HTTPDownstreamTest, byte_events_drained) { // Test that byte events are drained before socket is closed EventBase evb; NiceMock<MockController> mockController; auto codec = makeDownstreamParallelCodec(); auto byteEventTracker = new MockByteEventTracker(nullptr); auto transport = newMockTransport(&evb); auto transactionTimeouts = makeInternalTimeoutSet(&evb); // Create the downstream session auto session = new HTTPDownstreamSession( transactionTimeouts.get(), AsyncTransportWrapper::UniquePtr(transport), localAddr, peerAddr, &mockController, std::move(codec), mockTransportInfo); session->setByteEventTracker( std::unique_ptr<ByteEventTracker>(byteEventTracker)); InSequence dummy; session->startNow(); // Byte events should be drained first EXPECT_CALL(*byteEventTracker, drainByteEvents()) .Times(1); EXPECT_CALL(*transport, closeWithReset()) .Times(AtLeast(1)); // Close the socket session->shutdownTransportWithReset(kErrorConnectionReset); evb.loop(); } TEST_F(HTTPDownstreamSessionTest, trailers) { testChunks(true); } TEST_F(HTTPDownstreamSessionTest, explicit_chunks) { testChunks(false); } template <class C> void HTTPDownstreamTest<C>::testChunks(bool trailers) { StrictMock<MockHTTPHandler> handler; InSequence dummy; EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handler)); EXPECT_CALL(handler, setTransaction(_)) .WillOnce(SaveArg<0>(&handler.txn_)); EXPECT_CALL(handler, onHeadersComplete(_)); EXPECT_CALL(handler, onEOM()) .WillOnce(InvokeWithoutArgs([&handler, trailers] () { handler.sendChunkedReplyWithBody(200, 100, 17, trailers); })); EXPECT_CALL(handler, detachTransaction()); transport_->addReadEvent("GET / HTTP/1.1\r\n" "\r\n", std::chrono::milliseconds(0)); transport_->addReadEOF(std::chrono::milliseconds(0)); transport_->startReadEvents(); HTTPSession::DestructorGuard g(httpSession_); eventBase_.loop(); HTTP1xCodec clientCodec(TransportDirection::UPSTREAM); NiceMock<MockHTTPCodecCallback> callbacks; EXPECT_CALL(callbacks, onMessageBegin(1, _)) .Times(1); EXPECT_CALL(callbacks, onHeadersComplete(1, _)) .Times(1); for (int i = 0; i < 6; i++) { EXPECT_CALL(callbacks, onChunkHeader(1, _)); EXPECT_CALL(callbacks, onBody(1, _)); EXPECT_CALL(callbacks, onChunkComplete(1)); } if (trailers) { EXPECT_CALL(callbacks, onTrailersComplete(1, _)); } EXPECT_CALL(callbacks, onMessageComplete(1, _)); clientCodec.setCallback(&callbacks); parseOutput(clientCodec); EXPECT_CALL(mockController_, detachSession(_)); } TEST_F(HTTPDownstreamSessionTest, http_drain) { StrictMock<MockHTTPHandler> handler1; StrictMock<MockHTTPHandler> handler2; InSequence dummy; EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handler1)); EXPECT_CALL(handler1, setTransaction(_)) .WillOnce(SaveArg<0>(&handler1.txn_)); EXPECT_CALL(handler1, onHeadersComplete(_)) .WillOnce(Invoke([this, &handler1] (std::shared_ptr<HTTPMessage> msg) { handler1.sendHeaders(200, 100); httpSession_->notifyPendingShutdown(); })); EXPECT_CALL(handler1, onEOM()) .WillOnce(InvokeWithoutArgs([&handler1] { handler1.sendBody(100); handler1.txn_->sendEOM(); })); EXPECT_CALL(handler1, detachTransaction()); EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handler2)); EXPECT_CALL(handler2, setTransaction(_)) .WillOnce(SaveArg<0>(&handler2.txn_)); EXPECT_CALL(handler2, onHeadersComplete(_)) .WillOnce(Invoke([this, &handler2] (std::shared_ptr<HTTPMessage> msg) { handler2.sendHeaders(200, 100); })); EXPECT_CALL(handler2, onEOM()) .WillOnce(InvokeWithoutArgs([&handler2] { handler2.sendBody(100); handler2.txn_->sendEOM(); })); EXPECT_CALL(handler2, detachTransaction()); EXPECT_CALL(mockController_, detachSession(_)); transport_->addReadEvent("GET / HTTP/1.1\r\n" "\r\n", std::chrono::milliseconds(0)); transport_->addReadEvent("GET / HTTP/1.1\r\n" "\r\n", std::chrono::milliseconds(0)); transport_->startReadEvents(); eventBase_.loop(); } // 1) receive full request // 2) notify pending shutdown // 3) wait for session read timeout -> should be ignored // 4) response completed TEST_F(HTTPDownstreamSessionTest, http_drain_long_running) { StrictMock<MockHTTPHandler> handler; InSequence enforceSequence; EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handler)); // txn1, as soon as headers go out, mark set code shouldShutdown=true EXPECT_CALL(handler, setTransaction(_)) .WillOnce(SaveArg<0>(&handler.txn_)); EXPECT_CALL(handler, onHeadersComplete(_)) .WillOnce(Invoke([this, &handler] (std::shared_ptr<HTTPMessage> msg) { httpSession_->notifyPendingShutdown(); eventBase_.tryRunAfterDelay([this] { // simulate read timeout httpSession_->timeoutExpired(); }, 100); eventBase_.tryRunAfterDelay([&handler] { handler.sendReplyWithBody(200, 100); }, 200); })); EXPECT_CALL(handler, onEOM()); EXPECT_CALL(handler, detachTransaction()); EXPECT_CALL(mockController_, detachSession(_)); transport_->addReadEvent("GET / HTTP/1.1\r\n" "\r\n", std::chrono::milliseconds(0)); transport_->startReadEvents(); eventBase_.loop(); } TEST_F(HTTPDownstreamSessionTest, early_abort) { MockHTTPHandler* handler = new MockHTTPHandler(); InSequence dummy; EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(handler)); EXPECT_CALL(*handler, setTransaction(_)) .WillOnce(Invoke([&] (HTTPTransaction* txn) { handler->txn_ = txn; handler->txn_->sendAbort(); })); EXPECT_CALL(*handler, onHeadersComplete(_)) .Times(0); EXPECT_CALL(*handler, detachTransaction()) .WillOnce(InvokeWithoutArgs([&] { delete handler; })); EXPECT_CALL(mockController_, detachSession(_)); addSingleByteReads("GET /somepath.php?param=foo HTTP/1.1\r\n" "Host: example.com\r\n" "Connection: close\r\n" "\r\n"); transport_->addReadEOF(std::chrono::milliseconds(0)); transport_->startReadEvents(); eventBase_.loop(); } TEST_F(SPDY3DownstreamSessionTest, http_paused_buffered) { IOBufQueue requests{IOBufQueue::cacheChainLength()}; IOBufQueue rst{IOBufQueue::cacheChainLength()}; HTTPMessage req = getGetRequest(); MockHTTPHandler handler1; MockHTTPHandler handler2; SPDYCodec clientCodec(TransportDirection::UPSTREAM, SPDYVersion::SPDY3); auto streamID = HTTPCodec::StreamID(1); clientCodec.generateConnectionPreface(requests); clientCodec.generateHeader(requests, streamID, req); clientCodec.generateEOM(requests, streamID); clientCodec.generateRstStream(rst, streamID, ErrorCode::CANCEL); streamID += 2; clientCodec.generateHeader(requests, streamID, req); clientCodec.generateEOM(requests, streamID); EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handler1)) .WillOnce(Return(&handler2)); EXPECT_CALL(mockController_, detachSession(_)); InSequence handlerSequence; EXPECT_CALL(handler1, setTransaction(_)) .WillOnce(Invoke([&handler1] (HTTPTransaction* txn) { handler1.txn_ = txn; })); EXPECT_CALL(handler1, onHeadersComplete(_)); EXPECT_CALL(handler1, onEOM()) .WillOnce(InvokeWithoutArgs([&handler1, this] { transport_->pauseWrites(); handler1.sendHeaders(200, 65536 * 2); handler1.sendBody(65536 * 2); })); EXPECT_CALL(handler1, onEgressPaused()); EXPECT_CALL(handler2, setTransaction(_)) .WillOnce(Invoke([&handler2] (HTTPTransaction* txn) { handler2.txn_ = txn; })); EXPECT_CALL(handler2, onEgressPaused()); EXPECT_CALL(handler2, onHeadersComplete(_)); EXPECT_CALL(handler2, onEOM()); EXPECT_CALL(handler1, onError(_)) .WillOnce(Invoke([&] (const HTTPException& ex) { ASSERT_EQ(ex.getProxygenError(), kErrorStreamAbort); eventBase_.runInLoop([this] { transport_->resumeWrites(); }); })); EXPECT_CALL(handler1, detachTransaction()); EXPECT_CALL(handler2, onEgressResumed()) .WillOnce(Invoke([&] () { handler2.sendReplyWithBody(200, 32768); })); EXPECT_CALL(handler2, detachTransaction()); transport_->addReadEvent(requests, std::chrono::milliseconds(10)); transport_->addReadEvent(rst, std::chrono::milliseconds(10)); transport_->addReadEOF(std::chrono::milliseconds(50)); transport_->startReadEvents(); eventBase_.loop(); } TEST_F(HTTPDownstreamSessionTest, http_writes_draining_timeout) { IOBufQueue requests{IOBufQueue::cacheChainLength()}; HTTPMessage req = getGetRequest(); MockHTTPHandler handler1; HTTP1xCodec clientCodec(TransportDirection::UPSTREAM); auto streamID = HTTPCodec::StreamID(0); clientCodec.generateConnectionPreface(requests); clientCodec.generateHeader(requests, streamID, req); clientCodec.generateEOM(requests, streamID); clientCodec.generateHeader(requests, streamID, req); EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handler1)); EXPECT_CALL(mockController_, detachSession(_)); InSequence handlerSequence; EXPECT_CALL(handler1, setTransaction(_)) .WillOnce(Invoke([&handler1] (HTTPTransaction* txn) { handler1.txn_ = txn; })); EXPECT_CALL(handler1, onHeadersComplete(_)); EXPECT_CALL(handler1, onEOM()) .WillOnce(InvokeWithoutArgs([&handler1, this] { transport_->pauseWrites(); handler1.sendHeaders(200, 1000); })); EXPECT_CALL(handler1, onError(_)) .WillOnce(Invoke([&] (const HTTPException& ex) { ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout); ASSERT_EQ( folly::to<std::string>("WriteTimeout on transaction id: ", handler1.txn_->getID()), std::string(ex.what())); handler1.txn_->sendAbort(); })); EXPECT_CALL(handler1, detachTransaction()); transport_->addReadEvent(requests, std::chrono::milliseconds(10)); transport_->startReadEvents(); eventBase_.loop(); } TEST_F(HTTPDownstreamSessionTest, http_rate_limit_normal) { // The rate-limiting code grabs the event base from the EventBaseManager, // so we need to set it. folly::EventBaseManager::get()->setEventBase(&eventBase_, false); // Create a request IOBufQueue requests{IOBufQueue::cacheChainLength()}; HTTPMessage req = getGetRequest(); MockHTTPHandler handler1; HTTP1xCodec clientCodec(TransportDirection::UPSTREAM); auto streamID = HTTPCodec::StreamID(0); clientCodec.generateConnectionPreface(requests); clientCodec.generateHeader(requests, streamID, req); clientCodec.generateEOM(requests, streamID); // The controller should return the handler when asked EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillRepeatedly(Return(&handler1)); // Set a low rate-limit on the transaction EXPECT_CALL(handler1, setTransaction(_)) .WillOnce(Invoke([&handler1] (HTTPTransaction* txn) { uint32_t rateLimit_kbps = 640; txn->setEgressRateLimit(rateLimit_kbps * 1024); handler1.txn_ = txn; })); // Send a somewhat big response that we know will get rate-limited InSequence handlerSequence; EXPECT_CALL(handler1, onHeadersComplete(_)); EXPECT_CALL(handler1, onEOM()) .WillOnce(InvokeWithoutArgs([&handler1, this] { // At 640kbps, this should take slightly over 800ms uint32_t rspLengthBytes = 100000; handler1.sendHeaders(200, rspLengthBytes); handler1.sendBody(rspLengthBytes); handler1.txn_->sendEOM(); })); EXPECT_CALL(handler1, detachTransaction()); transport_->addReadEvent(requests, std::chrono::milliseconds(10)); transport_->startReadEvents(); // Keep the session around even after the event base loop completes so we can // read the counters on a valid object. HTTPSession::DestructorGuard g(httpSession_); eventBase_.loop(); proxygen::TimePoint timeFirstWrite = transport_->getWriteEvents()->front()->getTime(); proxygen::TimePoint timeLastWrite = transport_->getWriteEvents()->back()->getTime(); int64_t writeDuration = (int64_t)millisecondsBetween(timeLastWrite, timeFirstWrite).count(); EXPECT_GT(writeDuration, 800); } TEST_F(SPDY3DownstreamSessionTest, spdy_rate_limit_normal) { // The rate-limiting code grabs the event base from the EventBaseManager, // so we need to set it. folly::EventBaseManager::get()->setEventBase(&eventBase_, false); IOBufQueue requests{IOBufQueue::cacheChainLength()}; HTTPMessage req = getGetRequest(); MockHTTPHandler handler1; SPDYCodec clientCodec(TransportDirection::UPSTREAM, SPDYVersion::SPDY3); auto streamID = HTTPCodec::StreamID(1); clientCodec.generateConnectionPreface(requests); clientCodec.getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE, 100000); clientCodec.generateSettings(requests); clientCodec.generateHeader(requests, streamID, req); clientCodec.generateEOM(requests, streamID); EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillRepeatedly(Return(&handler1)); EXPECT_CALL(mockController_, detachSession(_)); InSequence handlerSequence; EXPECT_CALL(handler1, setTransaction(_)) .WillOnce(Invoke([&handler1] (HTTPTransaction* txn) { uint32_t rateLimit_kbps = 640; txn->setEgressRateLimit(rateLimit_kbps * 1024); handler1.txn_ = txn; })); EXPECT_CALL(handler1, onHeadersComplete(_)); EXPECT_CALL(handler1, onEOM()) .WillOnce(InvokeWithoutArgs([&handler1, this] { // At 640kbps, this should take slightly over 800ms uint32_t rspLengthBytes = 100000; handler1.sendHeaders(200, rspLengthBytes); handler1.sendBody(rspLengthBytes); handler1.txn_->sendEOM(); })); EXPECT_CALL(handler1, detachTransaction()); transport_->addReadEvent(requests, std::chrono::milliseconds(10)); transport_->addReadEOF(std::chrono::milliseconds(50)); transport_->startReadEvents(); // Keep the session around even after the event base loop completes so we can // read the counters on a valid object. HTTPSession::DestructorGuard g(httpSession_); eventBase_.loop(); proxygen::TimePoint timeFirstWrite = transport_->getWriteEvents()->front()->getTime(); proxygen::TimePoint timeLastWrite = transport_->getWriteEvents()->back()->getTime(); int64_t writeDuration = (int64_t)millisecondsBetween(timeLastWrite, timeFirstWrite).count(); EXPECT_GT(writeDuration, 800); } /** * This test will reset the connection while the server is waiting around * to send more bytes (so as to keep under the rate limit). */ TEST_F(SPDY3DownstreamSessionTest, spdy_rate_limit_rst) { // The rate-limiting code grabs the event base from the EventBaseManager, // so we need to set it. folly::EventBaseManager::get()->setEventBase(&eventBase_, false); IOBufQueue requests{IOBufQueue::cacheChainLength()}; IOBufQueue rst{IOBufQueue::cacheChainLength()}; HTTPMessage req = getGetRequest(); MockHTTPHandler handler1; SPDYCodec clientCodec(TransportDirection::UPSTREAM, SPDYVersion::SPDY3); auto streamID = HTTPCodec::StreamID(1); clientCodec.generateConnectionPreface(requests); clientCodec.getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE, 100000); clientCodec.generateSettings(requests); clientCodec.generateHeader(requests, streamID, req); clientCodec.generateEOM(requests, streamID); clientCodec.generateRstStream(rst, streamID, ErrorCode::CANCEL); EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillRepeatedly(Return(&handler1)); EXPECT_CALL(mockController_, detachSession(_)); InSequence handlerSequence; EXPECT_CALL(handler1, setTransaction(_)) .WillOnce(Invoke([&handler1] (HTTPTransaction* txn) { uint32_t rateLimit_kbps = 640; txn->setEgressRateLimit(rateLimit_kbps * 1024); handler1.txn_ = txn; })); EXPECT_CALL(handler1, onHeadersComplete(_)); EXPECT_CALL(handler1, onEOM()) .WillOnce(InvokeWithoutArgs([&handler1, this] { uint32_t rspLengthBytes = 100000; handler1.sendHeaders(200, rspLengthBytes); handler1.sendBody(rspLengthBytes); handler1.txn_->sendEOM(); })); EXPECT_CALL(handler1, onError(_)); EXPECT_CALL(handler1, detachTransaction()); transport_->addReadEvent(requests, std::chrono::milliseconds(10)); transport_->addReadEvent(rst, std::chrono::milliseconds(10)); transport_->addReadEOF(std::chrono::milliseconds(50)); transport_->startReadEvents(); eventBase_.loop(); } // Send a 1.0 request, egress the EOM with the last body chunk on a paused // socket, and let it timeout. shutdownTransportWithReset will result in a call // to removeTransaction with writesDraining_=true TEST_F(HTTPDownstreamSessionTest, write_timeout) { IOBufQueue requests{IOBufQueue::cacheChainLength()}; MockHTTPHandler handler1; HTTPMessage req = getGetRequest(); req.setHTTPVersion(1, 0); HTTP1xCodec clientCodec(TransportDirection::UPSTREAM); auto streamID = HTTPCodec::StreamID(0); clientCodec.generateConnectionPreface(requests); clientCodec.generateHeader(requests, streamID, req); clientCodec.generateEOM(requests, streamID); EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handler1)); InSequence handlerSequence; EXPECT_CALL(handler1, setTransaction(_)) .WillOnce(Invoke([&handler1] (HTTPTransaction* txn) { handler1.txn_ = txn; })); EXPECT_CALL(handler1, onHeadersComplete(_)); EXPECT_CALL(handler1, onEOM()) .WillOnce(InvokeWithoutArgs([&handler1, this] { handler1.sendHeaders(200, 100); eventBase_.tryRunAfterDelay([&handler1, this] { transport_->pauseWrites(); handler1.sendBody(100); handler1.txn_->sendEOM(); }, 50); })); EXPECT_CALL(handler1, onError(_)) .WillOnce(Invoke([&] (const HTTPException& ex) { ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout); ASSERT_EQ( folly::to<std::string>("WriteTimeout on transaction id: ", handler1.txn_->getID()), std::string(ex.what())); })); EXPECT_CALL(handler1, detachTransaction()); EXPECT_CALL(mockController_, detachSession(_)); transport_->addReadEvent(requests, std::chrono::milliseconds(0)); transport_->startReadEvents(); eventBase_.loop(); } // Send an abort from the write timeout path while pipelining TEST_F(HTTPDownstreamSessionTest, write_timeout_pipeline) { IOBufQueue requests{IOBufQueue::cacheChainLength()}; MockHTTPHandler handler1; HTTPMessage req = getGetRequest(); HTTP1xCodec clientCodec(TransportDirection::UPSTREAM); const char* buf = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n" "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"; EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handler1)); InSequence handlerSequence; EXPECT_CALL(handler1, setTransaction(_)) .WillOnce(Invoke([&handler1] (HTTPTransaction* txn) { handler1.txn_ = txn; })); EXPECT_CALL(handler1, onHeadersComplete(_)); EXPECT_CALL(handler1, onEOM()) .WillOnce(InvokeWithoutArgs([&handler1, this] { handler1.sendHeaders(200, 100); eventBase_.tryRunAfterDelay([&handler1, this] { transport_->pauseWrites(); handler1.sendBody(100); handler1.txn_->sendEOM(); }, 50); })); EXPECT_CALL(handler1, onError(_)) .WillOnce(Invoke([&] (const HTTPException& ex) { ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout); ASSERT_EQ( folly::to<std::string>("WriteTimeout on transaction id: ", handler1.txn_->getID()), std::string(ex.what())); handler1.txn_->sendAbort(); })); EXPECT_CALL(handler1, detachTransaction()); EXPECT_CALL(mockController_, detachSession(_)); transport_->addReadEvent(buf, std::chrono::milliseconds(0)); transport_->startReadEvents(); eventBase_.loop(); } TEST_F(HTTPDownstreamSessionTest, body_packetization) { IOBufQueue requests{IOBufQueue::cacheChainLength()}; MockHTTPHandler handler1; HTTPMessage req = getGetRequest(); req.setHTTPVersion(1, 0); req.setWantsKeepalive(false); HTTP1xCodec clientCodec(TransportDirection::UPSTREAM); auto streamID = HTTPCodec::StreamID(0); clientCodec.generateConnectionPreface(requests); clientCodec.generateHeader(requests, streamID, req); clientCodec.generateEOM(requests, streamID); EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handler1)); InSequence handlerSequence; EXPECT_CALL(handler1, setTransaction(_)) .WillOnce(Invoke([&handler1] (HTTPTransaction* txn) { handler1.txn_ = txn; })); EXPECT_CALL(handler1, onHeadersComplete(_)); EXPECT_CALL(handler1, onEOM()) .WillOnce(InvokeWithoutArgs([&handler1, this] { handler1.sendReplyWithBody(200, 32768); })); EXPECT_CALL(handler1, detachTransaction()); EXPECT_CALL(mockController_, detachSession(_)); transport_->addReadEvent(requests, std::chrono::milliseconds(0)); transport_->startReadEvents(); // Keep the session around even after the event base loop completes so we can // read the counters on a valid object. HTTPSession::DestructorGuard g(httpSession_); eventBase_.loop(); EXPECT_EQ(transport_->getWriteEvents()->size(), 1); } TEST_F(HTTPDownstreamSessionTest, http_malformed_pkt1) { // Create a HTTP connection and keep sending just '\n' to the HTTP1xCodec. std::string data(90000, '\n'); EXPECT_CALL(mockController_, detachSession(_)); transport_->addReadEvent(data.c_str(), data.length(), std::chrono::milliseconds(0)); transport_->addReadEOF(std::chrono::milliseconds(0)); transport_->startReadEvents(); eventBase_.loop(); } TEST_F(HTTPDownstreamSessionTest, big_explcit_chunk_write) { // even when the handler does a massive write, the transport only gets small // writes IOBufQueue requests{IOBufQueue::cacheChainLength()}; HTTPMessage req = getGetRequest(); HTTP1xCodec clientCodec(TransportDirection::UPSTREAM); auto streamID = HTTPCodec::StreamID(0); clientCodec.generateConnectionPreface(requests); clientCodec.generateHeader(requests, streamID, req); clientCodec.generateEOM(requests, streamID); MockHTTPHandler handler; EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handler)); EXPECT_CALL(handler, setTransaction(_)) .WillOnce(Invoke([&handler] (HTTPTransaction* txn) { handler.txn_ = txn; })); EXPECT_CALL(handler, onHeadersComplete(_)) .WillOnce(Invoke([&handler] (std::shared_ptr<HTTPMessage> msg) { handler.sendHeaders(200, 100, false); size_t len = 16 * 1024 * 1024; handler.txn_->sendChunkHeader(len); auto chunk = makeBuf(len); handler.txn_->sendBody(std::move(chunk)); handler.txn_->sendChunkTerminator(); handler.txn_->sendEOM(); })); EXPECT_CALL(handler, detachTransaction()); EXPECT_CALL(mockController_, detachSession(_)); transport_->addReadEvent(requests, std::chrono::milliseconds(0)); transport_->startReadEvents(); // Keep the session around even after the event base loop completes so we can // read the counters on a valid object. HTTPSession::DestructorGuard g(httpSession_); eventBase_.loop(); EXPECT_GT(transport_->getWriteEvents()->size(), 250); } TEST_F(SPDY2DownstreamSessionTest, spdy_prio) { SPDYCodec clientCodec(TransportDirection::UPSTREAM, SPDYVersion::SPDY2); testPriorities(clientCodec, 4); } TEST_F(SPDY3DownstreamSessionTest, spdy_prio) { SPDYCodec clientCodec(TransportDirection::UPSTREAM, SPDYVersion::SPDY3); testPriorities(clientCodec, 8); } template <class C> void HTTPDownstreamTest<C>::testPriorities( HTTPCodec& clientCodec, uint32_t numPriorities) { IOBufQueue requests{IOBufQueue::cacheChainLength()}; uint32_t iterations = 10; uint32_t maxPriority = numPriorities - 1; HTTPMessage req = getGetRequest(); auto streamID = HTTPCodec::StreamID(1); clientCodec.generateConnectionPreface(requests); for (int pri = numPriorities - 1; pri >= 0; pri--) { req.setPriority(pri * (8 / numPriorities)); for (uint32_t i = 0; i < iterations; i++) { clientCodec.generateHeader(requests, streamID, req); clientCodec.generateEOM(requests, streamID); MockHTTPHandler* handler = new MockHTTPHandler(); InSequence handlerSequence; EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(handler)); EXPECT_CALL(*handler, setTransaction(_)) .WillOnce(Invoke([handler] (HTTPTransaction* txn) { handler->txn_ = txn; })); EXPECT_CALL(*handler, onHeadersComplete(_)); EXPECT_CALL(*handler, onEOM()) .WillOnce(InvokeWithoutArgs([handler] { handler->sendReplyWithBody(200, 1000); })); EXPECT_CALL(*handler, detachTransaction()) .WillOnce(InvokeWithoutArgs([handler] { delete handler; })); streamID += 2; } } unique_ptr<IOBuf> head = requests.move(); head->coalesce(); transport_->addReadEvent(head->data(), head->length(), std::chrono::milliseconds(0)); transport_->startReadEvents(); eventBase_.loop(); NiceMock<MockHTTPCodecCallback> callbacks; std::list<HTTPCodec::StreamID> streams; EXPECT_CALL(callbacks, onMessageBegin(_, _)) .Times(iterations * numPriorities); EXPECT_CALL(callbacks, onHeadersComplete(_, _)) .Times(iterations * numPriorities); // body is variable and hence ignored EXPECT_CALL(callbacks, onMessageComplete(_, _)) .Times(iterations * numPriorities) .WillRepeatedly(Invoke([&] (HTTPCodec::StreamID stream, bool upgrade) { streams.push_back(stream); })); clientCodec.setCallback(&callbacks); parseOutput(clientCodec); // transactions finish in priority order (higher streamIDs first) EXPECT_EQ(streams.size(), iterations * numPriorities); auto txn = streams.begin(); for (int band = maxPriority; band >= 0; band--) { auto upperID = iterations * 2 * (band + 1); auto lowerID = iterations * 2 * band; for (uint32_t i = 0; i < iterations; i++) { EXPECT_LE(lowerID, (uint32_t)*txn); EXPECT_GE(upperID, (uint32_t)*txn); ++txn; } } } // Verifies that the read timeout is not running when no ingress is expected/ // required to proceed TEST_F(SPDY3DownstreamSessionTest, spdy_timeout) { IOBufQueue requests{IOBufQueue::cacheChainLength()}; HTTPMessage req = getGetRequest(); SPDYCodec clientCodec(TransportDirection::UPSTREAM, SPDYVersion::SPDY3); clientCodec.generateConnectionPreface(requests); for (auto streamID = HTTPCodec::StreamID(1); streamID <= 3; streamID += 2) { clientCodec.generateHeader(requests, streamID, req); clientCodec.generateEOM(requests, streamID); } MockHTTPHandler* handler1 = new StrictMock<MockHTTPHandler>(); MockHTTPHandler* handler2 = new StrictMock<MockHTTPHandler>(); HTTPSession::setPendingWriteMax(512); EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(handler1)) .WillOnce(Return(handler2)); InSequence handlerSequence; EXPECT_CALL(*handler1, setTransaction(_)) .WillOnce(Invoke([handler1] (HTTPTransaction* txn) { handler1->txn_ = txn; })); EXPECT_CALL(*handler1, onHeadersComplete(_)) .WillOnce(InvokeWithoutArgs([this] { transport_->pauseWrites(); })); EXPECT_CALL(*handler1, onEOM()) .WillOnce(InvokeWithoutArgs([handler1] { handler1->sendHeaders(200, 1000); handler1->sendBody(1000); })); EXPECT_CALL(*handler1, onEgressPaused()); EXPECT_CALL(*handler2, setTransaction(_)) .WillOnce(Invoke([handler2] (HTTPTransaction* txn) { handler2->txn_ = txn; })); EXPECT_CALL(*handler2, onEgressPaused()); EXPECT_CALL(*handler2, onHeadersComplete(_)); EXPECT_CALL(*handler2, onEOM()) .WillOnce(InvokeWithoutArgs([handler2, this] { // This transaction should start egress paused. We've received the // EOM, so the timeout shouldn't be running delay 400ms and resume // writes, this keeps txn1 from getting a write timeout eventBase_.tryRunAfterDelay([this] { transport_->resumeWrites(); }, 400); })); EXPECT_CALL(*handler1, onEgressResumed()) .WillOnce(InvokeWithoutArgs([handler1] { handler1->txn_->sendEOM(); })); EXPECT_CALL(*handler2, onEgressResumed()) .WillOnce(InvokeWithoutArgs([handler2, this] { // delay an additional 200ms. The total 600ms delay shouldn't fire // onTimeout eventBase_.tryRunAfterDelay([handler2] { handler2->sendReplyWithBody(200, 400); }, 200 ); })); EXPECT_CALL(*handler1, detachTransaction()) .WillOnce(InvokeWithoutArgs([handler1] { delete handler1; })); EXPECT_CALL(*handler2, detachTransaction()) .WillOnce(InvokeWithoutArgs([handler2] { delete handler2; })); transport_->addReadEvent(requests, std::chrono::milliseconds(10)); transport_->startReadEvents(); eventBase_.loop(); } // Verifies that the read timer is running while a transaction is blocked // on a window update TEST_F(SPDY3DownstreamSessionTest, spdy_timeout_win) { IOBufQueue requests{IOBufQueue::cacheChainLength()}; HTTPMessage req = getGetRequest(); SPDYCodec clientCodec(TransportDirection::UPSTREAM, SPDYVersion::SPDY3); auto streamID = HTTPCodec::StreamID(1); clientCodec.generateConnectionPreface(requests); clientCodec.getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE, 500); clientCodec.generateSettings(requests); clientCodec.generateHeader(requests, streamID, req, 0, false, nullptr); clientCodec.generateEOM(requests, streamID); StrictMock<MockHTTPHandler> handler; EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handler)); InSequence handlerSequence; EXPECT_CALL(handler, setTransaction(_)) .WillOnce(Invoke([&] (HTTPTransaction* txn) { handler.txn_ = txn; })); EXPECT_CALL(handler, onHeadersComplete(_)); EXPECT_CALL(handler, onEOM()) .WillOnce(InvokeWithoutArgs([&] { handler.sendReplyWithBody(200, 1000); })); EXPECT_CALL(handler, onEgressPaused()); EXPECT_CALL(handler, onError(_)) .WillOnce(Invoke([&] (const HTTPException& ex) { ASSERT_EQ(ex.getProxygenError(), kErrorTimeout); ASSERT_EQ( folly::to<std::string>("ingress timeout, streamID=", streamID), std::string(ex.what())); handler.terminate(); })); EXPECT_CALL(handler, detachTransaction()); transport_->addReadEvent(requests, std::chrono::milliseconds(10)); transport_->startReadEvents(); eventBase_.loop(); } TYPED_TEST_CASE_P(HTTPDownstreamTest); TYPED_TEST_P(HTTPDownstreamTest, testWritesDraining) { IOBufQueue requests{IOBufQueue::cacheChainLength()}; HTTPMessage req = getGetRequest(); auto clientCodec = makeClientCodec<typename TypeParam::Codec>(TypeParam::version); auto badCodec = makeServerCodec<typename TypeParam::Codec>(TypeParam::version); auto streamID = HTTPCodec::StreamID(1); clientCodec->generateConnectionPreface(requests); clientCodec->generateHeader(requests, streamID, req); clientCodec->generateEOM(requests, streamID); streamID += 1; badCodec->generateHeader(requests, streamID, req, 1); MockHTTPHandler handler1; EXPECT_CALL(this->mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handler1)); EXPECT_CALL(this->mockController_, detachSession(_)); InSequence handlerSequence; EXPECT_CALL(handler1, setTransaction(_)) .WillOnce(Invoke([&handler1] (HTTPTransaction* txn) { handler1.txn_ = txn; })); EXPECT_CALL(handler1, onHeadersComplete(_)); EXPECT_CALL(handler1, onEOM()); EXPECT_CALL(handler1, onError(_)) .WillOnce(Invoke([&] (const HTTPException& ex) { ASSERT_EQ(ex.getProxygenError(), kErrorEOF); ASSERT_EQ("Shutdown transport: EOF", std::string(ex.what())); })); EXPECT_CALL(handler1, detachTransaction()); this->transport_->addReadEvent(requests, std::chrono::milliseconds(10)); this->transport_->startReadEvents(); this->eventBase_.loop(); } TYPED_TEST_P(HTTPDownstreamTest, testBodySizeLimit) { IOBufQueue requests{IOBufQueue::cacheChainLength()}; HTTPMessage req = getGetRequest(); auto clientCodec = makeClientCodec<typename TypeParam::Codec>(TypeParam::version); auto streamID = HTTPCodec::StreamID(1); clientCodec->generateConnectionPreface(requests); clientCodec->generateHeader(requests, streamID, req); clientCodec->generateEOM(requests, streamID); streamID += 2; clientCodec->generateHeader(requests, streamID, req, 0); clientCodec->generateEOM(requests, streamID); MockHTTPHandler handler1; MockHTTPHandler handler2; EXPECT_CALL(this->mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handler1)) .WillOnce(Return(&handler2)); InSequence handlerSequence; EXPECT_CALL(handler1, setTransaction(_)) .WillOnce(Invoke([&handler1] (HTTPTransaction* txn) { handler1.txn_ = txn; })); EXPECT_CALL(handler1, onHeadersComplete(_)); EXPECT_CALL(handler1, onEOM()); EXPECT_CALL(handler2, setTransaction(_)) .WillOnce(Invoke([&handler2] (HTTPTransaction* txn) { handler2.txn_ = txn; })); EXPECT_CALL(handler2, onHeadersComplete(_)); EXPECT_CALL(handler2, onEOM()) .WillOnce(InvokeWithoutArgs([&] { handler1.sendReplyWithBody(200, 5000); handler2.sendReplyWithBody(200, 5000); })); EXPECT_CALL(handler1, detachTransaction()); EXPECT_CALL(handler2, detachTransaction()); this->transport_->addReadEvent(requests, std::chrono::milliseconds(10)); this->transport_->startReadEvents(); this->eventBase_.loop(); NiceMock<MockHTTPCodecCallback> callbacks; std::list<HTTPCodec::StreamID> streams; EXPECT_CALL(callbacks, onMessageBegin(1, _)); EXPECT_CALL(callbacks, onHeadersComplete(1, _)); EXPECT_CALL(callbacks, onMessageBegin(3, _)); EXPECT_CALL(callbacks, onHeadersComplete(3, _)); EXPECT_CALL(callbacks, onBody(1, _)); EXPECT_CALL(callbacks, onBody(3, _)); EXPECT_CALL(callbacks, onBody(1, _)); EXPECT_CALL(callbacks, onMessageComplete(1, _)); EXPECT_CALL(callbacks, onBody(3, _)); EXPECT_CALL(callbacks, onMessageComplete(3, _)); clientCodec->setCallback(&callbacks); this->parseOutput(*clientCodec); } TYPED_TEST_P(HTTPDownstreamTest, testUniformPauseState) { HTTPSession::setPendingWriteMax(12000); IOBufQueue requests{IOBufQueue::cacheChainLength()}; HTTPMessage req = getGetRequest(); req.setPriority(1); auto clientCodec = makeClientCodec<typename TypeParam::Codec>(TypeParam::version); auto streamID = HTTPCodec::StreamID(1); clientCodec->generateConnectionPreface(requests); clientCodec->getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE, 1000000); clientCodec->generateSettings(requests); clientCodec->generateWindowUpdate(requests, 0, 1000000); clientCodec->generateHeader(requests, streamID, req); clientCodec->generateEOM(requests, streamID); streamID += 2; clientCodec->generateHeader(requests, streamID, req, 0); clientCodec->generateEOM(requests, streamID); StrictMock<MockHTTPHandler> handler1; StrictMock<MockHTTPHandler> handler2; EXPECT_CALL(this->mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handler1)) .WillOnce(Return(&handler2)); InSequence handlerSequence; EXPECT_CALL(handler1, setTransaction(_)) .WillOnce(Invoke([&handler1] (HTTPTransaction* txn) { handler1.txn_ = txn; })); EXPECT_CALL(handler1, onHeadersComplete(_)); EXPECT_CALL(handler1, onEOM()); EXPECT_CALL(handler2, setTransaction(_)) .WillOnce(Invoke([&handler2] (HTTPTransaction* txn) { handler2.txn_ = txn; })); EXPECT_CALL(handler2, onHeadersComplete(_)); EXPECT_CALL(handler2, onEOM()) .WillOnce(InvokeWithoutArgs([&] { handler1.sendHeaders(200, 24000); // triggers pause of all txns this->transport_->pauseWrites(); handler1.txn_->sendBody(std::move(makeBuf(12000))); this->eventBase_.runAfterDelay([this] { this->transport_->resumeWrites(); }, 50); })); EXPECT_CALL(handler1, onEgressPaused()); EXPECT_CALL(handler2, onEgressPaused()); EXPECT_CALL(handler1, onEgressResumed()) .WillOnce(InvokeWithoutArgs([&] { // resume does not trigger another pause, handler1.txn_->sendBody(std::move(makeBuf(12000))); })); EXPECT_CALL(handler2, onEgressResumed()) .WillOnce(InvokeWithoutArgs([&] { handler2.sendHeaders(200, 12000); handler2.txn_->sendBody(std::move(makeBuf(12000))); this->transport_->pauseWrites(); this->eventBase_.runAfterDelay([this] { this->transport_->resumeWrites(); }, 50); })); EXPECT_CALL(handler1, onEgressPaused()); EXPECT_CALL(handler2, onEgressPaused()); EXPECT_CALL(handler1, onEgressResumed()); EXPECT_CALL(handler2, onEgressResumed()) .WillOnce(InvokeWithoutArgs([&] { handler1.txn_->sendEOM(); handler2.txn_->sendEOM(); })); EXPECT_CALL(handler1, detachTransaction()); EXPECT_CALL(handler2, detachTransaction()); this->transport_->addReadEvent(requests, std::chrono::milliseconds(10)); this->transport_->startReadEvents(); this->eventBase_.loop(); } // Set max streams=1 // send two spdy requests a few ms apart. // Block writes // generate a complete response for txn=1 before parsing txn=3 // HTTPSession should allow the txn=3 to be served rather than refusing it TEST_F(SPDY3DownstreamSessionTest, spdy_max_concurrent_streams) { IOBufQueue requests{IOBufQueue::cacheChainLength()}; StrictMock<MockHTTPHandler> handler1; StrictMock<MockHTTPHandler> handler2; HTTPMessage req = getGetRequest(); req.setHTTPVersion(1, 0); req.setWantsKeepalive(false); SPDYCodec clientCodec(TransportDirection::UPSTREAM, SPDYVersion::SPDY3); auto streamID = HTTPCodec::StreamID(1); clientCodec.generateConnectionPreface(requests); clientCodec.generateHeader(requests, streamID, req); clientCodec.generateEOM(requests, streamID); streamID += 2; clientCodec.generateHeader(requests, streamID, req); clientCodec.generateEOM(requests, streamID); httpSession_->getCodecFilterChain()->getEgressSettings()->setSetting( SettingsId::MAX_CONCURRENT_STREAMS, 1); EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handler1)) .WillOnce(Return(&handler2)); InSequence handlerSequence; EXPECT_CALL(handler1, setTransaction(_)) .WillOnce(Invoke([&handler1] (HTTPTransaction* txn) { handler1.txn_ = txn; })); EXPECT_CALL(handler1, onHeadersComplete(_)); EXPECT_CALL(handler1, onEOM()) .WillOnce(InvokeWithoutArgs([&handler1, this] { transport_->pauseWrites(); handler1.sendReplyWithBody(200, 100); })); EXPECT_CALL(handler2, setTransaction(_)) .WillOnce(Invoke([&handler2] (HTTPTransaction* txn) { handler2.txn_ = txn; })); EXPECT_CALL(handler2, onHeadersComplete(_)); EXPECT_CALL(handler2, onEOM()) .WillOnce(InvokeWithoutArgs([&handler2, this] { handler2.sendReplyWithBody(200, 100); eventBase_.runInLoop([this] { transport_->resumeWrites(); }); })); EXPECT_CALL(handler1, detachTransaction()); EXPECT_CALL(handler2, detachTransaction()); EXPECT_CALL(mockController_, detachSession(_)); transport_->addReadEvent(requests, std::chrono::milliseconds(10)); transport_->startReadEvents(); transport_->addReadEOF(std::chrono::milliseconds(10)); eventBase_.loop(); } REGISTER_TYPED_TEST_CASE_P(HTTPDownstreamTest, testWritesDraining, testBodySizeLimit, testUniformPauseState); typedef ::testing::Types<SPDY2CodecPair, SPDY3CodecPair, SPDY3_1CodecPair, HTTP2CodecPair> ParallelCodecs; INSTANTIATE_TYPED_TEST_CASE_P(ParallelCodecs, HTTPDownstreamTest, ParallelCodecs); class SPDY31DownstreamTest : public HTTPDownstreamTest<SPDY3_1CodecPair> { public: SPDY31DownstreamTest() : HTTPDownstreamTest<SPDY3_1CodecPair>(2 * spdy::kInitialWindow) {} }; TEST_F(SPDY31DownstreamTest, testSessionFlowControl) { eventBase_.loopOnce(); NiceMock<MockHTTPCodecCallback> callbacks; SPDYCodec clientCodec(TransportDirection::UPSTREAM, SPDYVersion::SPDY3_1); InSequence sequence; EXPECT_CALL(callbacks, onSettings(_)); EXPECT_CALL(callbacks, onWindowUpdate(0, spdy::kInitialWindow)); clientCodec.setCallback(&callbacks); parseOutput(clientCodec); } TEST_F(SPDY3DownstreamSessionTest, new_txn_egress_paused) { // Send 1 request with prio=0 // Have egress pause while sending the first response // Send a second request with prio=1 // -- the new txn should start egress paused // Finish the body and eom both responses // Unpause egress // The first txn should complete first std::array<StrictMock<MockHTTPHandler>, 2> handlers; IOBufQueue requests{IOBufQueue::cacheChainLength()}; HTTPMessage req = getGetRequest(); SPDYCodec clientCodec(TransportDirection::UPSTREAM, SPDYVersion::SPDY3); auto streamID = HTTPCodec::StreamID(1); clientCodec.generateConnectionPreface(requests); req.setPriority(0); clientCodec.generateHeader(requests, streamID, req, 0, nullptr); clientCodec.generateEOM(requests, streamID); streamID += 2; req.setPriority(1); clientCodec.generateHeader(requests, streamID, req, 0, nullptr); clientCodec.generateEOM(requests, streamID); EXPECT_CALL(mockController_, getRequestHandler(_, _)) .WillOnce(Return(&handlers[0])) .WillOnce(Return(&handlers[1])); HTTPSession::setPendingWriteMax(200); // lower the per session buffer limit { InSequence handlerSequence; EXPECT_CALL(handlers[0], setTransaction(_)) .WillOnce(Invoke([&handlers] (HTTPTransaction* txn) { handlers[0].txn_ = txn; })); EXPECT_CALL(handlers[0], onHeadersComplete(_)); EXPECT_CALL(handlers[0], onEOM()) .WillOnce(Invoke([this, &handlers] { this->transport_->pauseWrites(); handlers[0].sendHeaders(200, 1000); handlers[0].sendBody(100); // headers + 100 bytes - over the limit })); EXPECT_CALL(handlers[0], onEgressPaused()) .WillOnce(InvokeWithoutArgs([] { LOG(INFO) << "paused 1"; })); EXPECT_CALL(handlers[1], setTransaction(_)) .WillOnce(Invoke([&handlers] (HTTPTransaction* txn) { handlers[1].txn_ = txn; })); EXPECT_CALL(handlers[1], onEgressPaused()); // starts paused EXPECT_CALL(handlers[1], onHeadersComplete(_)); EXPECT_CALL(handlers[1], onEOM()) .WillOnce(InvokeWithoutArgs([&handlers, this] { // Technically shouldn't send while handler is egress // paused, but meh. handlers[0].sendBody(900); handlers[0].txn_->sendEOM(); handlers[1].sendReplyWithBody(200, 1000); eventBase_.runInLoop([this] { transport_->resumeWrites(); }); })); EXPECT_CALL(handlers[0], detachTransaction()); EXPECT_CALL(handlers[1], detachTransaction()); } transport_->addReadEvent(requests, std::chrono::milliseconds(10)); transport_->startReadEvents(); transport_->addReadEOF(std::chrono::milliseconds(10)); HTTPSession::DestructorGuard g(httpSession_); eventBase_.loop(); NiceMock<MockHTTPCodecCallback> callbacks; std::list<HTTPCodec::StreamID> streams; EXPECT_CALL(callbacks, onMessageBegin(_, _)) .Times(2); EXPECT_CALL(callbacks, onHeadersComplete(_, _)) .Times(2); // body is variable and hence ignored; EXPECT_CALL(callbacks, onMessageComplete(_, _)) .WillRepeatedly(Invoke([&] (HTTPCodec::StreamID stream, bool upgrade) { streams.push_back(stream); })); clientCodec.setCallback(&callbacks); parseOutput(clientCodec); EXPECT_CALL(mockController_, detachSession(_)); }
luxuan/proxygen
proxygen/lib/http/session/test/HTTPDownstreamSessionTest.cpp
C++
bsd-3-clause
67,684
#include "farversion.hpp" #define PLUGIN_BUILD 37 #define PLUGIN_DESC L"File names case conversion for Far Manager" #define PLUGIN_NAME L"FileCase" #define PLUGIN_FILENAME L"FileCase.dll" #define PLUGIN_AUTHOR FARCOMPANYNAME #define PLUGIN_VERSION MAKEFARVERSION(FARMANAGERVERSION_MAJOR,FARMANAGERVERSION_MINOR,FARMANAGERVERSION_REVISION,PLUGIN_BUILD,VS_RELEASE)
data-man/FarAS
plugins/filecase/version.hpp
C++
bsd-3-clause
364
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/renderer_host/pepper/device_id_fetcher.h" #include "base/file_util.h" #include "base/prefs/pref_service.h" #include "base/strings/string_number_conversions.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #if defined(OS_CHROMEOS) #include "chromeos/cryptohome/cryptohome_library.h" #endif #include "components/user_prefs/pref_registry_syncable.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_ppapi_host.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" #include "crypto/encryptor.h" #include "crypto/random.h" #include "crypto/sha2.h" #if defined(ENABLE_RLZ) #include "rlz/lib/machine_id.h" #endif using content::BrowserPpapiHost; using content::BrowserThread; using content::RenderProcessHost; namespace chrome { namespace { const char kDRMIdentifierFile[] = "Pepper DRM ID.0"; const uint32_t kSaltLength = 32; void GetMachineIDAsync(const DeviceIDFetcher::IDCallback& callback) { std::string result; #if defined(OS_WIN) && defined(ENABLE_RLZ) rlz_lib::GetMachineId(&result); #elif defined(OS_CHROMEOS) result = chromeos::CryptohomeLibrary::Get()->GetSystemSalt(); if (result.empty()) { // cryptohome must not be running; re-request after a delay. const int64 kRequestSystemSaltDelayMs = 500; base::MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&GetMachineIDAsync, callback), base::TimeDelta::FromMilliseconds(kRequestSystemSaltDelayMs)); return; } #else // Not implemented for other platforms. NOTREACHED(); #endif callback.Run(result); } } // namespace DeviceIDFetcher::DeviceIDFetcher(int render_process_id) : in_progress_(false), render_process_id_(render_process_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); } DeviceIDFetcher::~DeviceIDFetcher() { } bool DeviceIDFetcher::Start(const IDCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (in_progress_) return false; in_progress_ = true; callback_ = callback; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&DeviceIDFetcher::CheckPrefsOnUIThread, this)); return true; } // static void DeviceIDFetcher::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* prefs) { prefs->RegisterBooleanPref(prefs::kEnableDRM, true, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); prefs->RegisterStringPref( prefs::kDRMSalt, "", user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); } // static base::FilePath DeviceIDFetcher::GetLegacyDeviceIDPath( const base::FilePath& profile_path) { return profile_path.AppendASCII(kDRMIdentifierFile); } void DeviceIDFetcher::CheckPrefsOnUIThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); Profile* profile = NULL; RenderProcessHost* render_process_host = RenderProcessHost::FromID(render_process_id_); if (render_process_host && render_process_host->GetBrowserContext()) { profile = Profile::FromBrowserContext( render_process_host->GetBrowserContext()); } if (!profile || profile->IsOffTheRecord() || !profile->GetPrefs()->GetBoolean(prefs::kEnableDRM)) { RunCallbackOnIOThread(std::string()); return; } // Check if the salt pref is set. If it isn't, set it. std::string salt = profile->GetPrefs()->GetString(prefs::kDRMSalt); if (salt.empty()) { uint8_t salt_bytes[kSaltLength]; crypto::RandBytes(salt_bytes, arraysize(salt_bytes)); // Since it will be stored in a string pref, convert it to hex. salt = base::HexEncode(salt_bytes, arraysize(salt_bytes)); profile->GetPrefs()->SetString(prefs::kDRMSalt, salt); } #if defined(OS_CHROMEOS) // Try the legacy path first for ChromeOS. We pass the new salt in as well // in case the legacy id doesn't exist. BrowserThread::PostBlockingPoolTask( FROM_HERE, base::Bind(&DeviceIDFetcher::LegacyComputeOnBlockingPool, this, profile->GetPath(), salt)); #else // Get the machine ID and call ComputeOnUIThread with salt + machine_id. GetMachineIDAsync(base::Bind(&DeviceIDFetcher::ComputeOnUIThread, this, salt)); #endif } void DeviceIDFetcher::ComputeOnUIThread(const std::string& salt, const std::string& machine_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (machine_id.empty()) { LOG(ERROR) << "Empty machine id"; RunCallbackOnIOThread(std::string()); return; } // Build the identifier as follows: // SHA256(machine-id||service||SHA256(machine-id||service||salt)) std::vector<uint8> salt_bytes; if (!base::HexStringToBytes(salt, &salt_bytes)) salt_bytes.clear(); if (salt_bytes.size() != kSaltLength) { LOG(ERROR) << "Unexpected salt bytes length: " << salt_bytes.size(); RunCallbackOnIOThread(std::string()); return; } char id_buf[256 / 8]; // 256-bits for SHA256 std::string input = machine_id; input.append(kDRMIdentifierFile); input.append(salt_bytes.begin(), salt_bytes.end()); crypto::SHA256HashString(input, &id_buf, sizeof(id_buf)); std::string id = StringToLowerASCII( base::HexEncode(reinterpret_cast<const void*>(id_buf), sizeof(id_buf))); input = machine_id; input.append(kDRMIdentifierFile); input.append(id); crypto::SHA256HashString(input, &id_buf, sizeof(id_buf)); id = StringToLowerASCII(base::HexEncode( reinterpret_cast<const void*>(id_buf), sizeof(id_buf))); RunCallbackOnIOThread(id); } // TODO(raymes): This is temporary code to migrate ChromeOS devices to the new // scheme for generating device IDs. Delete this once we are sure most ChromeOS // devices have been migrated. void DeviceIDFetcher::LegacyComputeOnBlockingPool( const base::FilePath& profile_path, const std::string& salt) { std::string id; // First check if the legacy device ID file exists on ChromeOS. If it does, we // should just return that. base::FilePath id_path = GetLegacyDeviceIDPath(profile_path); if (base::PathExists(id_path)) { if (base::ReadFileToString(id_path, &id) && !id.empty()) { RunCallbackOnIOThread(id); return; } } // If we didn't find an ID, get the machine ID and call the new code path to // generate an ID. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&GetMachineIDAsync, base::Bind(&DeviceIDFetcher::ComputeOnUIThread, this, salt))); } void DeviceIDFetcher::RunCallbackOnIOThread(const std::string& id) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&DeviceIDFetcher::RunCallbackOnIOThread, this, id)); return; } in_progress_ = false; callback_.Run(id); } } // namespace chrome
mogoweb/chromium-crosswalk
chrome/browser/renderer_host/pepper/device_id_fetcher.cc
C++
bsd-3-clause
7,226
exports.dbname = "lrdata"; exports.dbuser = "lrdata"; exports.dbpassword = "test"; exports.lfmApiKey = 'c0db7c8bfb98655ab25aa2e959fdcc68'; exports.lfmApiSecret = 'aff4890d7cb9492bc72250abbeffc3e1'; exports.tagAgeBeforeRefresh = 14; // In days exports.tagFetchFrequency = 1000; // In milliseconds
alnorth/listening-room-add-ons-site
config.js
JavaScript
bsd-3-clause
298
""" Room Typeclasses for the TutorialWorld. This defines special types of Rooms available in the tutorial. To keep everything in one place we define them together with the custom commands needed to control them. Those commands could also have been in a separate module (e.g. if they could have been re-used elsewhere.) """ from __future__ import print_function import random from evennia import TICKER_HANDLER from evennia import CmdSet, Command, DefaultRoom from evennia import utils, create_object, search_object from evennia import syscmdkeys, default_cmds from evennia.contrib.tutorial_world.objects import LightSource # the system error-handling module is defined in the settings. We load the # given setting here using utils.object_from_module. This way we can use # it regardless of if we change settings later. from django.conf import settings _SEARCH_AT_RESULT = utils.object_from_module(settings.SEARCH_AT_RESULT) # ------------------------------------------------------------- # # Tutorial room - parent room class # # This room is the parent of all rooms in the tutorial. # It defines a tutorial command on itself (available to # all those who are in a tutorial room). # # ------------------------------------------------------------- # # Special command available in all tutorial rooms class CmdTutorial(Command): """ Get help during the tutorial Usage: tutorial [obj] This command allows you to get behind-the-scenes info about an object or the current location. """ key = "tutorial" aliases = ["tut"] locks = "cmd:all()" help_category = "TutorialWorld" def func(self): """ All we do is to scan the current location for an Attribute called `tutorial_info` and display that. """ caller = self.caller if not self.args: target = self.obj # this is the room the command is defined on else: target = caller.search(self.args.strip()) if not target: return helptext = target.db.tutorial_info if helptext: caller.msg("|G%s|n" % helptext) else: caller.msg("|RSorry, there is no tutorial help available here.|n") # for the @detail command we inherit from MuxCommand, since # we want to make use of MuxCommand's pre-parsing of '=' in the # argument. class CmdTutorialSetDetail(default_cmds.MuxCommand): """ sets a detail on a room Usage: @detail <key> = <description> @detail <key>;<alias>;... = description Example: @detail walls = The walls are covered in ... @detail castle;ruin;tower = The distant ruin ... This sets a "detail" on the object this command is defined on (TutorialRoom for this tutorial). This detail can be accessed with the TutorialRoomLook command sitting on TutorialRoom objects (details are set as a simple dictionary on the room). This is a Builder command. We custom parse the key for the ;-separator in order to create multiple aliases to the detail all at once. """ key = "@detail" locks = "cmd:perm(Builder)" help_category = "TutorialWorld" def func(self): """ All this does is to check if the object has the set_detail method and uses it. """ if not self.args or not self.rhs: self.caller.msg("Usage: @detail key = description") return if not hasattr(self.obj, "set_detail"): self.caller.msg("Details cannot be set on %s." % self.obj) return for key in self.lhs.split(";"): # loop over all aliases, if any (if not, this will just be # the one key to loop over) self.obj.set_detail(key, self.rhs) self.caller.msg("Detail set: '%s': '%s'" % (self.lhs, self.rhs)) class CmdTutorialLook(default_cmds.CmdLook): """ looks at the room and on details Usage: look <obj> look <room detail> look *<account> Observes your location, details at your location or objects in your vicinity. Tutorial: This is a child of the default Look command, that also allows us to look at "details" in the room. These details are things to examine and offers some extra description without actually having to be actual database objects. It uses the return_detail() hook on TutorialRooms for this. """ # we don't need to specify key/locks etc, this is already # set by the parent. help_category = "TutorialWorld" def func(self): """ Handle the looking. This is a copy of the default look code except for adding in the details. """ caller = self.caller args = self.args if args: # we use quiet=True to turn off automatic error reporting. # This tells search that we want to handle error messages # ourself. This also means the search function will always # return a list (with 0, 1 or more elements) rather than # result/None. looking_at_obj = caller.search(args, # note: excludes room/room aliases candidates=caller.location.contents + caller.contents, use_nicks=True, quiet=True) if len(looking_at_obj) != 1: # no target found or more than one target found (multimatch) # look for a detail that may match detail = self.obj.return_detail(args) if detail: self.caller.msg(detail) return else: # no detail found, delegate our result to the normal # error message handler. _SEARCH_AT_RESULT(None, caller, args, looking_at_obj) return else: # we found a match, extract it from the list and carry on # normally with the look handling. looking_at_obj = looking_at_obj[0] else: looking_at_obj = caller.location if not looking_at_obj: caller.msg("You have no location to look at!") return if not hasattr(looking_at_obj, 'return_appearance'): # this is likely due to us having an account instead looking_at_obj = looking_at_obj.character if not looking_at_obj.access(caller, "view"): caller.msg("Could not find '%s'." % args) return # get object's appearance caller.msg(looking_at_obj.return_appearance(caller)) # the object's at_desc() method. looking_at_obj.at_desc(looker=caller) return class TutorialRoomCmdSet(CmdSet): """ Implements the simple tutorial cmdset. This will overload the look command in the default CharacterCmdSet since it has a higher priority (ChracterCmdSet has prio 0) """ key = "tutorial_cmdset" priority = 1 def at_cmdset_creation(self): """add the tutorial-room commands""" self.add(CmdTutorial()) self.add(CmdTutorialSetDetail()) self.add(CmdTutorialLook()) class TutorialRoom(DefaultRoom): """ This is the base room type for all rooms in the tutorial world. It defines a cmdset on itself for reading tutorial info about the location. """ def at_object_creation(self): """Called when room is first created""" self.db.tutorial_info = "This is a tutorial room. It allows you to use the 'tutorial' command." self.cmdset.add_default(TutorialRoomCmdSet) def at_object_receive(self, new_arrival, source_location): """ When an object enter a tutorial room we tell other objects in the room about it by trying to call a hook on them. The Mob object uses this to cheaply get notified of enemies without having to constantly scan for them. Args: new_arrival (Object): the object that just entered this room. source_location (Object): the previous location of new_arrival. """ if new_arrival.has_account and not new_arrival.is_superuser: # this is a character for obj in self.contents_get(exclude=new_arrival): if hasattr(obj, "at_new_arrival"): obj.at_new_arrival(new_arrival) def return_detail(self, detailkey): """ This looks for an Attribute "obj_details" and possibly returns the value of it. Args: detailkey (str): The detail being looked at. This is case-insensitive. """ details = self.db.details if details: return details.get(detailkey.lower(), None) def set_detail(self, detailkey, description): """ This sets a new detail, using an Attribute "details". Args: detailkey (str): The detail identifier to add (for aliases you need to add multiple keys to the same description). Case-insensitive. description (str): The text to return when looking at the given detailkey. """ if self.db.details: self.db.details[detailkey.lower()] = description else: self.db.details = {detailkey.lower(): description} # ------------------------------------------------------------- # # Weather room - room with a ticker # # ------------------------------------------------------------- # These are rainy weather strings WEATHER_STRINGS = ( "The rain coming down from the iron-grey sky intensifies.", "A gust of wind throws the rain right in your face. Despite your cloak you shiver.", "The rainfall eases a bit and the sky momentarily brightens.", "For a moment it looks like the rain is slowing, then it begins anew with renewed force.", "The rain pummels you with large, heavy drops. You hear the rumble of thunder in the distance.", "The wind is picking up, howling around you, throwing water droplets in your face. It's cold.", "Bright fingers of lightning flash over the sky, moments later followed by a deafening rumble.", "It rains so hard you can hardly see your hand in front of you. You'll soon be drenched to the bone.", "Lightning strikes in several thundering bolts, striking the trees in the forest to your west.", "You hear the distant howl of what sounds like some sort of dog or wolf.", "Large clouds rush across the sky, throwing their load of rain over the world.") class WeatherRoom(TutorialRoom): """ This should probably better be called a rainy room... This sets up an outdoor room typeclass. At irregular intervals, the effects of weather will show in the room. Outdoor rooms should inherit from this. """ def at_object_creation(self): """ Called when object is first created. We set up a ticker to update this room regularly. Note that we could in principle also use a Script to manage the ticking of the room; the TickerHandler works fine for simple things like this though. """ super(WeatherRoom, self).at_object_creation() # subscribe ourselves to a ticker to repeatedly call the hook # "update_weather" on this object. The interval is randomized # so as to not have all weather rooms update at the same time. self.db.interval = random.randint(50, 70) TICKER_HANDLER.add(interval=self.db.interval, callback=self.update_weather, idstring="tutorial") # this is parsed by the 'tutorial' command on TutorialRooms. self.db.tutorial_info = \ "This room has a Script running that has it echo a weather-related message at irregular intervals." def update_weather(self, *args, **kwargs): """ Called by the tickerhandler at regular intervals. Even so, we only update 20% of the time, picking a random weather message when we do. The tickerhandler requires that this hook accepts any arguments and keyword arguments (hence the *args, **kwargs even though we don't actually use them in this example) """ if random.random() < 0.2: # only update 20 % of the time self.msg_contents("|w%s|n" % random.choice(WEATHER_STRINGS)) SUPERUSER_WARNING = "\nWARNING: You are playing as a superuser ({name}). Use the {quell} command to\n" \ "play without superuser privileges (many functions and puzzles ignore the \n" \ "presence of a superuser, making this mode useful for exploring things behind \n" \ "the scenes later).\n" \ # ------------------------------------------------------------ # # Intro Room - unique room # # This room marks the start of the tutorial. It sets up properties on # the player char that is needed for the tutorial. # # ------------------------------------------------------------- class IntroRoom(TutorialRoom): """ Intro room properties to customize: char_health - integer > 0 (default 20) """ def at_object_creation(self): """ Called when the room is first created. """ super(IntroRoom, self).at_object_creation() self.db.tutorial_info = "The first room of the tutorial. " \ "This assigns the health Attribute to "\ "the account." def at_object_receive(self, character, source_location): """ Assign properties on characters """ # setup character for the tutorial health = self.db.char_health or 20 if character.has_account: character.db.health = health character.db.health_max = health if character.is_superuser: string = "-" * 78 + SUPERUSER_WARNING + "-" * 78 character.msg("|r%s|n" % string.format(name=character.key, quell="|w@quell|r")) # ------------------------------------------------------------- # # Bridge - unique room # # Defines a special west-eastward "bridge"-room, a large room that takes # several steps to cross. It is complete with custom commands and a # chance of falling off the bridge. This room has no regular exits, # instead the exitings are handled by custom commands set on the account # upon first entering the room. # # Since one can enter the bridge room from both ends, it is # divided into five steps: # westroom <- 0 1 2 3 4 -> eastroom # # ------------------------------------------------------------- class CmdEast(Command): """ Go eastwards across the bridge. Tutorial info: This command relies on the caller having two Attributes (assigned by the room when entering): - east_exit: a unique name or dbref to the room to go to when exiting east. - west_exit: a unique name or dbref to the room to go to when exiting west. The room must also have the following Attributes - tutorial_bridge_posistion: the current position on on the bridge, 0 - 4. """ key = "east" aliases = ["e"] locks = "cmd:all()" help_category = "TutorialWorld" def func(self): """move one step eastwards""" caller = self.caller bridge_step = min(5, caller.db.tutorial_bridge_position + 1) if bridge_step > 4: # we have reached the far east end of the bridge. # Move to the east room. eexit = search_object(self.obj.db.east_exit) if eexit: caller.move_to(eexit[0]) else: caller.msg("No east exit was found for this room. Contact an admin.") return caller.db.tutorial_bridge_position = bridge_step # since we are really in one room, we have to notify others # in the room when we move. caller.location.msg_contents("%s steps eastwards across the bridge." % caller.name, exclude=caller) caller.execute_cmd("look") # go back across the bridge class CmdWest(Command): """ Go westwards across the bridge. Tutorial info: This command relies on the caller having two Attributes (assigned by the room when entering): - east_exit: a unique name or dbref to the room to go to when exiting east. - west_exit: a unique name or dbref to the room to go to when exiting west. The room must also have the following property: - tutorial_bridge_posistion: the current position on on the bridge, 0 - 4. """ key = "west" aliases = ["w"] locks = "cmd:all()" help_category = "TutorialWorld" def func(self): """move one step westwards""" caller = self.caller bridge_step = max(-1, caller.db.tutorial_bridge_position - 1) if bridge_step < 0: # we have reached the far west end of the bridge. # Move to the west room. wexit = search_object(self.obj.db.west_exit) if wexit: caller.move_to(wexit[0]) else: caller.msg("No west exit was found for this room. Contact an admin.") return caller.db.tutorial_bridge_position = bridge_step # since we are really in one room, we have to notify others # in the room when we move. caller.location.msg_contents("%s steps westwards across the bridge." % caller.name, exclude=caller) caller.execute_cmd("look") BRIDGE_POS_MESSAGES = ("You are standing |wvery close to the the bridge's western foundation|n." " If you go west you will be back on solid ground ...", "The bridge slopes precariously where it extends eastwards" " towards the lowest point - the center point of the hang bridge.", "You are |whalfways|n out on the unstable bridge.", "The bridge slopes precariously where it extends westwards" " towards the lowest point - the center point of the hang bridge.", "You are standing |wvery close to the bridge's eastern foundation|n." " If you go east you will be back on solid ground ...") BRIDGE_MOODS = ("The bridge sways in the wind.", "The hanging bridge creaks dangerously.", "You clasp the ropes firmly as the bridge sways and creaks under you.", "From the castle you hear a distant howling sound, like that of a large dog or other beast.", "The bridge creaks under your feet. Those planks does not seem very sturdy.", "Far below you the ocean roars and throws its waves against the cliff," " as if trying its best to reach you.", "Parts of the bridge come loose behind you, falling into the chasm far below!", "A gust of wind causes the bridge to sway precariously.", "Under your feet a plank comes loose, tumbling down. For a moment you dangle over the abyss ...", "The section of rope you hold onto crumble in your hands," " parts of it breaking apart. You sway trying to regain balance.") FALL_MESSAGE = "Suddenly the plank you stand on gives way under your feet! You fall!" \ "\nYou try to grab hold of an adjoining plank, but all you manage to do is to " \ "divert your fall westwards, towards the cliff face. This is going to hurt ... " \ "\n ... The world goes dark ...\n\n" class CmdLookBridge(Command): """ looks around at the bridge. Tutorial info: This command assumes that the room has an Attribute "fall_exit", a unique name or dbref to the place they end upp if they fall off the bridge. """ key = 'look' aliases = ["l"] locks = "cmd:all()" help_category = "TutorialWorld" def func(self): """Looking around, including a chance to fall.""" caller = self.caller bridge_position = self.caller.db.tutorial_bridge_position # this command is defined on the room, so we get it through self.obj location = self.obj # randomize the look-echo message = "|c%s|n\n%s\n%s" % (location.key, BRIDGE_POS_MESSAGES[bridge_position], random.choice(BRIDGE_MOODS)) chars = [obj for obj in self.obj.contents_get(exclude=caller) if obj.has_account] if chars: # we create the You see: message manually here message += "\n You see: %s" % ", ".join("|c%s|n" % char.key for char in chars) self.caller.msg(message) # there is a chance that we fall if we are on the western or central # part of the bridge. if bridge_position < 3 and random.random() < 0.05 and not self.caller.is_superuser: # we fall 5% of time. fall_exit = search_object(self.obj.db.fall_exit) if fall_exit: self.caller.msg("|r%s|n" % FALL_MESSAGE) self.caller.move_to(fall_exit[0], quiet=True) # inform others on the bridge self.obj.msg_contents("A plank gives way under %s's feet and " "they fall from the bridge!" % self.caller.key) # custom help command class CmdBridgeHelp(Command): """ Overwritten help command while on the bridge. """ key = "help" aliases = ["h", "?"] locks = "cmd:all()" help_category = "Tutorial world" def func(self): """Implements the command.""" string = "You are trying hard not to fall off the bridge ..." \ "\n\nWhat you can do is trying to cross the bridge |weast|n" \ " or try to get back to the mainland |wwest|n)." self.caller.msg(string) class BridgeCmdSet(CmdSet): """This groups the bridge commands. We will store it on the room.""" key = "Bridge commands" priority = 1 # this gives it precedence over the normal look/help commands. def at_cmdset_creation(self): """Called at first cmdset creation""" self.add(CmdTutorial()) self.add(CmdEast()) self.add(CmdWest()) self.add(CmdLookBridge()) self.add(CmdBridgeHelp()) BRIDGE_WEATHER = ( "The rain intensifies, making the planks of the bridge even more slippery.", "A gust of wind throws the rain right in your face.", "The rainfall eases a bit and the sky momentarily brightens.", "The bridge shakes under the thunder of a closeby thunder strike.", "The rain pummels you with large, heavy drops. You hear the distinct howl of a large hound in the distance.", "The wind is picking up, howling around you and causing the bridge to sway from side to side.", "Some sort of large bird sweeps by overhead, giving off an eery screech. Soon it has disappeared in the gloom.", "The bridge sways from side to side in the wind.", "Below you a particularly large wave crashes into the rocks.", "From the ruin you hear a distant, otherwordly howl. Or maybe it was just the wind.") class BridgeRoom(WeatherRoom): """ The bridge room implements an unsafe bridge. It also enters the player into a state where they get new commands so as to try to cross the bridge. We want this to result in the account getting a special set of commands related to crossing the bridge. The result is that it will take several steps to cross it, despite it being represented by only a single room. We divide the bridge into steps: self.db.west_exit - - | - - self.db.east_exit 0 1 2 3 4 The position is handled by a variable stored on the character when entering and giving special move commands will increase/decrease the counter until the bridge is crossed. We also has self.db.fall_exit, which points to a gathering location to end up if we happen to fall off the bridge (used by the CmdLookBridge command). """ def at_object_creation(self): """Setups the room""" # this will start the weather room's ticker and tell # it to call update_weather regularly. super(BridgeRoom, self).at_object_creation() # this identifies the exits from the room (should be the command # needed to leave through that exit). These are defaults, but you # could of course also change them after the room has been created. self.db.west_exit = "cliff" self.db.east_exit = "gate" self.db.fall_exit = "cliffledge" # add the cmdset on the room. self.cmdset.add_default(BridgeCmdSet) # since the default Character's at_look() will access the room's # return_description (this skips the cmdset) when # first entering it, we need to explicitly turn off the room # as a normal view target - once inside, our own look will # handle all return messages. self.locks.add("view:false()") def update_weather(self, *args, **kwargs): """ This is called at irregular intervals and makes the passage over the bridge a little more interesting. """ if random.random() < 80: # send a message most of the time self.msg_contents("|w%s|n" % random.choice(BRIDGE_WEATHER)) def at_object_receive(self, character, source_location): """ This hook is called by the engine whenever the player is moved into this room. """ if character.has_account: # we only run this if the entered object is indeed a player object. # check so our east/west exits are correctly defined. wexit = search_object(self.db.west_exit) eexit = search_object(self.db.east_exit) fexit = search_object(self.db.fall_exit) if not (wexit and eexit and fexit): character.msg("The bridge's exits are not properly configured. " "Contact an admin. Forcing west-end placement.") character.db.tutorial_bridge_position = 0 return if source_location == eexit[0]: # we assume we enter from the same room we will exit to character.db.tutorial_bridge_position = 4 else: # if not from the east, then from the west! character.db.tutorial_bridge_position = 0 character.execute_cmd("look") def at_object_leave(self, character, target_location): """ This is triggered when the player leaves the bridge room. """ if character.has_account: # clean up the position attribute del character.db.tutorial_bridge_position # ------------------------------------------------------------------------------- # # Dark Room - a room with states # # This room limits the movemenets of its denizens unless they carry an active # LightSource object (LightSource is defined in # tutorialworld.objects.LightSource) # # ------------------------------------------------------------------------------- DARK_MESSAGES = ("It is pitch black. You are likely to be eaten by a grue.", "It's pitch black. You fumble around but cannot find anything.", "You don't see a thing. You feel around, managing to bump your fingers hard against something. Ouch!", "You don't see a thing! Blindly grasping the air around you, you find nothing.", "It's totally dark here. You almost stumble over some un-evenness in the ground.", "You are completely blind. For a moment you think you hear someone breathing nearby ... " "\n ... surely you must be mistaken.", "Blind, you think you find some sort of object on the ground, but it turns out to be just a stone.", "Blind, you bump into a wall. The wall seems to be covered with some sort of vegetation," " but its too damp to burn.", "You can't see anything, but the air is damp. It feels like you are far underground.") ALREADY_LIGHTSOURCE = "You don't want to stumble around in blindness anymore. You already " \ "found what you need. Let's get light already!" FOUND_LIGHTSOURCE = "Your fingers bump against a splinter of wood in a corner." \ " It smells of resin and seems dry enough to burn! " \ "You pick it up, holding it firmly. Now you just need to" \ " |wlight|n it using the flint and steel you carry with you." class CmdLookDark(Command): """ Look around in darkness Usage: look Look around in the darkness, trying to find something. """ key = "look" aliases = ["l", 'feel', 'search', 'feel around', 'fiddle'] locks = "cmd:all()" help_category = "TutorialWorld" def func(self): """ Implement the command. This works both as a look and a search command; there is a random chance of eventually finding a light source. """ caller = self.caller if random.random() < 0.8: # we don't find anything caller.msg(random.choice(DARK_MESSAGES)) else: # we could have found something! if any(obj for obj in caller.contents if utils.inherits_from(obj, LightSource)): # we already carry a LightSource object. caller.msg(ALREADY_LIGHTSOURCE) else: # don't have a light source, create a new one. create_object(LightSource, key="splinter", location=caller) caller.msg(FOUND_LIGHTSOURCE) class CmdDarkHelp(Command): """ Help command for the dark state. """ key = "help" locks = "cmd:all()" help_category = "TutorialWorld" def func(self): """ Replace the the help command with a not-so-useful help """ string = "Can't help you until you find some light! Try looking/feeling around for something to burn. " \ "You shouldn't give up even if you don't find anything right away." self.caller.msg(string) class CmdDarkNoMatch(Command): """ This is a system command. Commands with special keys are used to override special sitations in the game. The CMD_NOMATCH is used when the given command is not found in the current command set (it replaces Evennia's default behavior or offering command suggestions) """ key = syscmdkeys.CMD_NOMATCH locks = "cmd:all()" def func(self): """Implements the command.""" self.caller.msg("Until you find some light, there's not much you can do. Try feeling around.") class DarkCmdSet(CmdSet): """ Groups the commands of the dark room together. We also import the default say command here so that players can still talk in the darkness. We give the cmdset the mergetype "Replace" to make sure it completely replaces whichever command set it is merged onto (usually the default cmdset) """ key = "darkroom_cmdset" mergetype = "Replace" priority = 2 def at_cmdset_creation(self): """populate the cmdset.""" self.add(CmdTutorial()) self.add(CmdLookDark()) self.add(CmdDarkHelp()) self.add(CmdDarkNoMatch()) self.add(default_cmds.CmdSay) class DarkRoom(TutorialRoom): """ A dark room. This tries to start the DarkState script on all objects entering. The script is responsible for making sure it is valid (that is, that there is no light source shining in the room). The is_lit Attribute is used to define if the room is currently lit or not, so as to properly echo state changes. Since this room (in the tutorial) is meant as a sort of catch-all, we also make sure to heal characters ending up here, since they may have been beaten up by the ghostly apparition at this point. """ def at_object_creation(self): """ Called when object is first created. """ super(DarkRoom, self).at_object_creation() self.db.tutorial_info = "This is a room with custom command sets on itself." # the room starts dark. self.db.is_lit = False self.cmdset.add(DarkCmdSet, permanent=True) def at_init(self): """ Called when room is first recached (such as after a reload) """ self.check_light_state() def _carries_light(self, obj): """ Checks if the given object carries anything that gives light. Note that we do NOT look for a specific LightSource typeclass, but for the Attribute is_giving_light - this makes it easy to later add other types of light-giving items. We also accept if there is a light-giving object in the room overall (like if a splinter was dropped in the room) """ return obj.is_superuser or obj.db.is_giving_light or any(o for o in obj.contents if o.db.is_giving_light) def _heal(self, character): """ Heal a character. """ health = character.db.health_max or 20 character.db.health = health def check_light_state(self, exclude=None): """ This method checks if there are any light sources in the room. If there isn't it makes sure to add the dark cmdset to all characters in the room. It is called whenever characters enter the room and also by the Light sources when they turn on. Args: exclude (Object): An object to not include in the light check. """ if any(self._carries_light(obj) for obj in self.contents if obj != exclude): self.locks.add("view:all()") self.cmdset.remove(DarkCmdSet) self.db.is_lit = True for char in (obj for obj in self.contents if obj.has_account): # this won't do anything if it is already removed char.msg("The room is lit up.") else: # noone is carrying light - darken the room self.db.is_lit = False self.locks.add("view:false()") self.cmdset.add(DarkCmdSet, permanent=True) for char in (obj for obj in self.contents if obj.has_account): if char.is_superuser: char.msg("You are Superuser, so you are not affected by the dark state.") else: # put players in darkness char.msg("The room is completely dark.") def at_object_receive(self, obj, source_location): """ Called when an object enters the room. """ if obj.has_account: # a puppeted object, that is, a Character self._heal(obj) # in case the new guy carries light with them self.check_light_state() def at_object_leave(self, obj, target_location): """ In case people leave with the light, we make sure to clear the DarkCmdSet if necessary. This also works if they are teleported away. """ # since this hook is called while the object is still in the room, # we exclude it from the light check, to ignore any light sources # it may be carrying. self.check_light_state(exclude=obj) # ------------------------------------------------------------- # # Teleport room - puzzles solution # # This is a sort of puzzle room that requires a certain # attribute on the entering character to be the same as # an attribute of the room. If not, the character will # be teleported away to a target location. This is used # by the Obelisk - grave chamber puzzle, where one must # have looked at the obelisk to get an attribute set on # oneself, and then pick the grave chamber with the # matching imagery for this attribute. # # ------------------------------------------------------------- class TeleportRoom(TutorialRoom): """ Teleporter - puzzle room. Important attributes (set at creation): puzzle_key - which attr to look for on character puzzle_value - what char.db.puzzle_key must be set to success_teleport_to - where to teleport in case if success success_teleport_msg - message to echo while teleporting to success failure_teleport_to - where to teleport to in case of failure failure_teleport_msg - message to echo while teleporting to failure """ def at_object_creation(self): """Called at first creation""" super(TeleportRoom, self).at_object_creation() # what character.db.puzzle_clue must be set to, to avoid teleportation. self.db.puzzle_value = 1 # target of successful teleportation. Can be a dbref or a # unique room name. self.db.success_teleport_msg = "You are successful!" self.db.success_teleport_to = "treasure room" # the target of the failure teleportation. self.db.failure_teleport_msg = "You fail!" self.db.failure_teleport_to = "dark cell" def at_object_receive(self, character, source_location): """ This hook is called by the engine whenever the player is moved into this room. """ if not character.has_account: # only act on player characters. return # determine if the puzzle is a success or not is_success = str(character.db.puzzle_clue) == str(self.db.puzzle_value) teleport_to = self.db.success_teleport_to if is_success else self.db.failure_teleport_to # note that this returns a list results = search_object(teleport_to) if not results or len(results) > 1: # we cannot move anywhere since no valid target was found. character.msg("no valid teleport target for %s was found." % teleport_to) return if character.is_superuser: # superusers don't get teleported character.msg("Superuser block: You would have been teleported to %s." % results[0]) return # perform the teleport if is_success: character.msg(self.db.success_teleport_msg) else: character.msg(self.db.failure_teleport_msg) # teleport quietly to the new place character.move_to(results[0], quiet=True, move_hooks=False) # we have to call this manually since we turn off move_hooks # - this is necessary to make the target dark room aware of an # already carried light. results[0].at_object_receive(character, self) # ------------------------------------------------------------- # # Outro room - unique exit room # # Cleans up the character from all tutorial-related properties. # # ------------------------------------------------------------- class OutroRoom(TutorialRoom): """ Outro room. Called when exiting the tutorial, cleans the character of tutorial-related attributes. """ def at_object_creation(self): """ Called when the room is first created. """ super(OutroRoom, self).at_object_creation() self.db.tutorial_info = "The last room of the tutorial. " \ "This cleans up all temporary Attributes " \ "the tutorial may have assigned to the "\ "character." def at_object_receive(self, character, source_location): """ Do cleanup. """ if character.has_account: del character.db.health_max del character.db.health del character.db.last_climbed del character.db.puzzle_clue del character.db.combat_parry_mode del character.db.tutorial_bridge_position for obj in character.contents: if obj.typeclass_path.startswith("evennia.contrib.tutorial_world"): obj.delete() character.tags.clear(category="tutorial_world")
feend78/evennia
evennia/contrib/tutorial_world/rooms.py
Python
bsd-3-clause
40,655
<?php namespace asdfstudio\admin\helpers; use Yii; use asdfstudio\admin\Module; use asdfstudio\admin\base\Admin; use yii\db\ActiveRecord; class AdminHelper { /** * @param string $entity Admin class name or Id * @return Admin|null */ public static function getEntity($entity) { /* @var Module $module */ $module = Yii::$app->controller->module; if (isset($module->entities[$entity])) { return $module->entities[$entity]; } elseif (isset($module->entitiesClasses[$entity])) { return static::getEntity($module->entitiesClasses[$entity]); } return null; } /** * Return value of nested attribute. * * ```php * // e.g. $post is Post model. We need to get a name of owmer. Owner is related model. * * AdminHelper::resolveAttribute('owner.username', $post); // it returns username from owner attribute * ``` * * @param string $attribute * @param ActiveRecord $model * @return string */ public static function resolveAttribute($attribute, $model) { $path = explode('.', $attribute); $attr = $model; foreach ($path as $a) { $attr = $attr->{$a}; } return $attr; } }
Tecnoready/yii2-admin-module
helpers/AdminHelper.php
PHP
bsd-3-clause
1,294
#include <core/Runtime.h> #include <stdlib.h> #include <math.h> int runtime_f32_mul(Stack stack) { Value* operand1 = NULL; Value* operand2 = NULL; pop_Value(stack, &operand2); pop_Value(stack, &operand1); if(isnan(operand1->value.f32) || isnan(operand2->value.f32)) { push_Value(stack, new_f32Value(nanf(""))); } else if(isinf(operand1->value.f32) || isinf(operand2->value.f32)) { if(operand1->value.f32 == 0 || operand2->value.f32 == 0) { push_Value(stack, new_f32Value(nanf(""))); } else if(signbit(operand1->value.f32) ^ signbit(operand2->value.f32)) { push_Value(stack, new_f32Value(-strtof("INF", NULL))); } else { push_Value(stack, new_f32Value(strtof("INF", NULL))); } } else if(operand1->value.f32 == 0 && operand2->value.f32 == 0) { if(signbit(operand1->value.f32) ^ signbit(operand2->value.f32)) { push_Value(stack, new_f32Value(-0.0f)); } else { push_Value(stack, new_f32Value(+0.0f)); } } else { push_Value(stack, new_f32Value(operand1->value.f32 * operand2->value.f32)); } free_Value(operand1); free_Value(operand2); return 0; }
LuisHsu/WasmVM
src/lib/core/runtime/f32_mul.c
C
bsd-3-clause
1,224
package tools; /* * Extremely Compiler Collection * Copyright (c) 2015-2020, Jianping Zeng. * * 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 java.io.PrintStream; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * This owns the files read by a parser, handles include stacks, * and handles diagnostic wrangling. * * @author Jianping Zeng * @version 0.4 */ public final class SourceMgr { public enum DiagKind { DK_Error, DK_Warning, DK_Remark, DK_Note } private DiagKind getDiagKindByName(String name) { switch (name) { case "error": return DiagKind.DK_Error; case "warning": return DiagKind.DK_Warning; case "remark": return DiagKind.DK_Remark; case "note": return DiagKind.DK_Note; default: Util.assertion("Unknown diagnostic kind!"); return null; } } public static class SMLoc { private MemoryBuffer buffer; private int startPos; @Override public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; if (getClass() != obj.getClass()) return false; SMLoc loc = (SMLoc) obj; return loc.buffer.equals(buffer) && startPos == loc.startPos; } public static SMLoc get(MemoryBuffer buf, int start) { SMLoc loc = new SMLoc(); loc.buffer = buf; loc.startPos = start; return loc; } public static SMLoc get(MemoryBuffer buf) { SMLoc loc = new SMLoc(); loc.buffer = buf; loc.startPos = buf.getBufferStart(); return loc; } public boolean isValid() { return buffer != null; } public int getPointer() { return startPos; } } static class SrcBuffer { MemoryBuffer buffer; /** * This is the location of the parent include, or * null if it is in the top level. */ SMLoc includeLoc; } private static class LineNoCache { int lastQueryBufferID; MemoryBuffer lastQuery; int lineNoOfQuery; } /** * This is all of the buffers that we are reading from. */ private ArrayList<SrcBuffer> buffers = new ArrayList<>(); /** * This is the list of directories we should search for * include files in. */ private LinkedList<String> includeDirs; /** * This s cache for line number queries. */ private LineNoCache lineNoCache; public void setIncludeDirs(List<String> dirs) { includeDirs = new LinkedList<>(dirs); } public SrcBuffer getBufferInfo(int i) { Util.assertion(i >= 0 && i < buffers.size(), "Invalid buffer ID!"); return buffers.get(i); } public MemoryBuffer getMemoryBuffer(int i) { Util.assertion(i >= 0 && i < buffers.size(), "Invalid buffer ID!"); return buffers.get(i).buffer; } public SMLoc getParentIncludeLoc(int i) { Util.assertion(i >= 0 && i < buffers.size(), "Invalid buffer ID!"); return buffers.get(i).includeLoc; } public int addNewSourceBuffer(MemoryBuffer buf, SMLoc includeLoc) { SrcBuffer buffer = new SrcBuffer(); buffer.buffer = buf; buffer.includeLoc = includeLoc; buffers.add(buffer); return buffers.size() - 1; } /** * Search for a file with the specified name in the current directory or * in one of the {@linkplain #includeDirs}. If no such file found, this return * ~0, otherwise it returns the buffer ID of the stacked file. * * @param filename * @param includeLoc * @return */ public int addIncludeFile(String filename, SMLoc includeLoc) { MemoryBuffer newBuf = MemoryBuffer.getFile(filename); for (int i = 0, e = includeDirs.size(); i < e && newBuf == null; i++) { String incFile = includeDirs.get(i) + "/" + filename; newBuf = MemoryBuffer.getFile(incFile); } if (newBuf == null) return ~0; return addNewSourceBuffer(newBuf, includeLoc); } /** * Return the ID of the buffer containing the specified location, return -1 * if not found. * * @param loc * @return */ public int findBufferContainingLoc(SMLoc loc) { for (int i = 0, e = buffers.size(); i < e; i++) { MemoryBuffer buf = buffers.get(i).buffer; if (buf.contains(loc.buffer)) return i; } return ~0; } /** * Find the line number for the specified location in the specified file. * * @param loc * @param bufferID * @return */ public int findLineNumber(SMLoc loc, int bufferID) { if (bufferID == -1) bufferID = findBufferContainingLoc(loc); Util.assertion(bufferID != -1, "Invalid location!"); int lineNo = 1; MemoryBuffer buf = getBufferInfo(bufferID).buffer; if (lineNoCache != null) { if (lineNoCache.lastQueryBufferID == bufferID && lineNoCache.lastQuery.getCharBuffer().equals(buf.getCharBuffer()) && lineNoCache.lastQuery.getBufferStart() <= buf.getBufferStart()) { buf = lineNoCache.lastQuery; lineNo = lineNoCache.lineNoOfQuery; } } for (; !SMLoc.get(buf).equals(loc); buf.advance()) { if (buf.getCurChar() == '\n') ++lineNo; } if (lineNoCache == null) lineNoCache = new LineNoCache(); lineNoCache.lastQueryBufferID = bufferID; lineNoCache.lastQuery = buf; lineNoCache.lineNoOfQuery = lineNo; return lineNo; } public int findLineNumber(SMLoc loc) { return findLineNumber(loc, -1); } /** * Emit a message about the specified location with the specified string. * This method is deprecated, you should use {@linkplain Error#printMessage(SMLoc, String, DiagKind)} instead. * * @param loc * @param msg * @param type If not null, it specified the kind of message to be emitted (e.g. "error") * which is prefixed to the message. */ @Deprecated public void printMessage(SMLoc loc, String msg, String type) { Error.printMessage(loc, msg, getDiagKindByName(type)); } /** * Return an SMDiagnostic at the specified location with the specified string. * * @param loc * @param msg * @param kind If not null, it specified the kind of message to be emitted (e.g. "error") * which is prefixed to the message. * @return */ public SMDiagnostic getMessage(SMLoc loc, String msg, DiagKind kind) { int curBuf = findBufferContainingLoc(loc); Util.assertion(curBuf != -1, "Invalid or unspecified location!"); MemoryBuffer curMB = getBufferInfo(curBuf).buffer; Util.assertion(curMB.getCharBuffer() == loc.buffer.getCharBuffer()); int columnStart = loc.getPointer(); while (columnStart >= curMB.getBufferStart() && curMB.getCharAt(columnStart) != '\n' && curMB.getCharAt(columnStart) != '\r') --columnStart; int columnEnd = loc.getPointer(); while (columnEnd < curMB.length() && curMB.getCharAt(columnEnd) != '\n' && curMB.getCharAt(columnEnd) != '\r') ++columnEnd; String printedMsg = ""; switch (kind) { case DK_Error: printedMsg = "error: "; break; case DK_Remark: printedMsg = "remark: "; break; case DK_Note: printedMsg = "note: "; break; case DK_Warning: printedMsg = "warning: "; break; } printedMsg += msg; return new SMDiagnostic(curMB.getBufferIdentifier(), findLineNumber(loc, curBuf), curMB.getBufferStart() - columnStart, printedMsg, curMB.getSubString(columnStart, columnEnd)); } private void printIncludeStack(SMLoc includeLoc, PrintStream os) { // Top stack. if (includeLoc.buffer == null) return; int curBuf = findBufferContainingLoc(includeLoc); Util.assertion(curBuf != -1, "Invalid or unspecified location!"); printIncludeStack(getBufferInfo(curBuf).includeLoc, os); os.printf("Included from %s:%d:\n", getBufferInfo(curBuf).buffer.getBufferIdentifier(), findLineNumber(includeLoc, curBuf)); } }
JianpingZeng/xcc
xcc/java/tools/SourceMgr.java
Java
bsd-3-clause
8,511
package com.logicalpractice.collections; import static org.junit.Assert.*; import static org.hamcrest.Matchers.* ; import org.junit.Test; public class ExpressionTest { @Test public void script1() throws Exception { Person billy = new Person("Billy", "Smith"); Expression<Person,String> testObject = new Expression<Person,String>(){{ each(Person.class).getFirstName(); }}; String result = testObject.apply(billy); assertThat(result, equalTo("Billy")); } }
tempredirect/lps-collections
src/test/java/com/logicalpractice/collections/ExpressionTest.java
Java
bsd-3-clause
534
<?php declare(strict_types=1); namespace LizardsAndPumpkins\Context\Country; use LizardsAndPumpkins\Context\ContextPartBuilder; class IntegrationTestContextCountry implements ContextPartBuilder { private $defaultCountryCode = 'DE'; /** * @param mixed[] $inputDataSet * @return string */ public function getValue(array $inputDataSet) : string { if (isset($inputDataSet[Country::CONTEXT_CODE])) { return (string) $inputDataSet[Country::CONTEXT_CODE]; } return $this->defaultCountryCode; } public function getCode() : string { return Country::CONTEXT_CODE; } }
lizards-and-pumpkins/catalog
tests/Integration/Util/Context/Country/IntegrationTestContextCountry.php
PHP
bsd-3-clause
660
Backend ======= stack build managemytime to run the server, just invoke the executable (it's inside .stack-work) or stack exec managemytime-exe it ships with a builtin self-signed certificate for localhost to run the integration tests, you'll want unencrypted http, which you can select with the "test" argument stack exec managemytime-exe test stack test managemytime:functional-tests Don't store any important data in the sqlite.db created by default in the project directory since it will be erased by the testrunner To create a "production" build (with a proper tls certificate, encrypted inside `tls.yml`) ansible-playbook --ask-vault-pass build.yml Frontend ======== Install the flow type checker: opam install flowtype Install bower and jstransform: npm install -g bower jstransform Typecheck javascript: flow check frontend/src/ Parse js and strip signatures: jstransform --strip-types --es6module --watch frontend/src frontend/scripts Install the frontend dependencies (you'll have to symlink them manually): bower install
berdario/managemytime
README.md
Markdown
bsd-3-clause
1,091
const initialState = { country: 'es', language: 'es-ES' } const settings = (state = initialState, action) => { switch (action.type) { default: return state } } export default settings
emoriarty/podcaster
src/reducers/settings.js
JavaScript
bsd-3-clause
200
<?php // This is the configuration for yiic console application. // Any writable CConsoleApplication properties can be configured here. return array( 'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..', 'name'=>'My Console Application', // autoloading model and component classes 'import'=>array( 'application.models.*', 'application.components.*', ), // preloading 'log' component 'preload'=>array('log'), // application components 'components'=>array( // database settings are configured in database.php 'db'=>require(dirname(__FILE__).'/database.php'), 'log'=>array( 'class'=>'CLogRouter', 'routes'=>array( array( 'class'=>'CFileLogRoute', 'levels'=>'error, warning', ), ), ), ), );
stiflerbox/yii1-segmentation
testdrive/protected/config/console.php
PHP
bsd-3-clause
766
#based on SilkJS Makefile ARCH := $(shell getconf LONG_BIT) COREMQ= mqdb.o OBJ= HMQ = include/lru_cache/lru_cache.h include/lru_cache/scoped_mutex.h fstools.cc CORECL= client.o OBJ= V8DIR= ./v8-read-only V8LIB_64 := $(V8DIR)/out/x64.release/obj.target/tools/gyp V8LIB_32 := $(V8DIR)/out/ia32.release/obj.target/tools/gyp V8LIB_DIR := $(V8LIB_$(ARCH)) V8VERSION_64 := x64.release V8VERSION_32 := ia32.release V8VERSION := $(V8VERSION_$(ARCH)) V8= $(V8LIB_DIR)/libv8_base.a $(V8LIB_DIR)/libv8_snapshot.a CFLAGS = -O6 -fomit-frame-pointer -fdata-sections -ffunction-sections -fno-strict-aliasing -fno-rtti -fno-exceptions -fvisibility=hidden -Wall -W -Wno-unused-parameter -Wnon-virtual-dtor -m$(ARCH) -O3 -fomit-frame-pointer -fdata-sections -ffunction-sections -ansi -fno-strict-aliasing -fexceptions all: mqdb client mqdb2 tasksink taskvent taskvs asclient %.o: %.cpp Makefile g++ $(CFLAGS) -c -I./include -I$(V8DIR)/include -g -o $*.o $*.cpp mqdb: $(V8) $(COREMQ) $(OBJ) $(HMQ) Makefile g++ $(CFLAGS) -I./include -I$(V8DIR)/include -o mqdb mqdb.cpp -L$(V8LIB_DIR)/ -L./leveldb/ -lv8_base -lv8_snapshot -lmm -lpthread -lzmq -lleveldb #-lgd client: $(V8) $(CORECL) $(OBJ) Makefile g++ $(CFLAGS) -o client $(CORECL) $(OBJ) -L$(V8LIB_DIR)/ -lmm -lpthread -lzmq $(V8): cd $(V8DIR) && make dependencies && GYP_GENERATORS=make make $(V8VERSION) update: cd $(V8DIR) && svn update && make dependencies && GYP_GENERATORS=make make $(V8VERSION) git pull
PawelMarc/MQDB
Makefile
Makefile
bsd-3-clause
1,468
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Justin Madsen // ============================================================================= // // model a single track chain system, as part of a tracked vehicle. // TODO: read in subsystem data w/ JSON input files // // ============================================================================= #include <cstdio> #include <sstream> #include "subsys/trackSystem/TrackSystem.h" namespace chrono { // ----------------------------------------------------------------------------- // Static variables // idler, right side const ChVector<> TrackSystem::m_idlerPos(-2.1904, -0.1443, 0.2447); // relative to local csys const ChQuaternion<> TrackSystem::m_idlerRot(QUNIT); // drive gear, right side const ChVector<> TrackSystem::m_gearPos(1.7741, -0.0099, 0.2447); // relative to local csys const ChQuaternion<> TrackSystem::m_gearRot(QUNIT); // suspension const int TrackSystem::m_numSuspensions = 5; TrackSystem::TrackSystem(const std::string& name, int track_idx, const double idler_preload) : m_track_idx(track_idx), m_name(name), m_idler_preload(idler_preload) { // FILE* fp = fopen(filename.c_str(), "r"); // char readBuffer[65536]; // fclose(fp); Create(track_idx); } // Create: 1) load/set the subsystem data, resize vectors 2) BuildSubsystems() // TODO: replace hard-coded junk with JSON input files for each subsystem void TrackSystem::Create(int track_idx) { /* // read idler info assert(d.HasMember("Idler")); m_idlerMass = d["Idler"]["Mass"].GetDouble(); m_idlerPos = loadVector(d["Idler"]["Location"]); m_idlerInertia = loadVector(d["Idler"]["Inertia"]); m_idlerRadius = d["Spindle"]["Radius"].GetDouble(); m_idlerWidth = d["Spindle"]["Width"].GetDouble(); m_idler_K = d["Idler"]["SpringK"].GetDouble(); m_idler_C = d["Idler"]["SpringC"].GetDouble(); */ /* // Read Drive Gear data assert(d.HasMember("Drive Gear")); assert(d["Drive Gear"].IsObject()); m_gearMass = d["Drive Gear"]["Mass"].GetDouble(); m_gearPos = loadVector(d["Drive Gear"]["Location"]); m_gearInertia = loadVector(d["Drive Gear"]["Inertia"]); m_gearRadius = d["Drive Gear"]["Radius"].GetDouble(); m_gearWidth = d["Drive Gear"]["Width"].GetDouble(); // Read Suspension data assert(d.HasMember("Suspension")); assert(d["Suspension"].IsObject()); assert(d["Suspension"]["Location"].IsArray() ); m_suspensionFilename = d["Suspension"]["Input File"].GetString(); m_NumSuspensions = d["Suspension"]["Location"].Size(); */ m_suspensions.resize(m_numSuspensions); m_suspensionLocs.resize(m_numSuspensions); // hard-code positions relative to trackSystem csys. Start w/ one nearest sprocket m_suspensionLocs[0] = ChVector<>(1.3336, 0, 0); m_suspensionLocs[1] = ChVector<>(0.6668, 0, 0); // trackSystem c-sys aligned with middle suspension subsystem arm/chassis revolute constraint position m_suspensionLocs[2] = ChVector<>(0, 0, 0); m_suspensionLocs[3] = ChVector<>(-0.6682, 0, 0); m_suspensionLocs[4] = ChVector<>(-1.3368, 0, 0); /* for(int j = 0; j < m_numSuspensions; j++) { m_suspensionLocs[j] = loadVector(d["Suspension"]["Locaiton"][j]); } // Read Track Chain data assert(d.HasMember("Track Chain")); assert(d["Track Chain"].IsObject()); m_trackChainFilename = d["Track Chain"]["Input File"].GetString() */ // create the various subsystems, from the hardcoded static variables in each subsystem class BuildSubsystems(); } void TrackSystem::BuildSubsystems() { std::stringstream gearName; gearName << "drive gear " << m_track_idx; // build one of each of the following subsystems. VisualizationType and CollisionType defaults are PRIMITIVES m_driveGear = ChSharedPtr<DriveGear>(new DriveGear(gearName.str(), VisualizationType::Mesh, // CollisionType::Primitives) ); // VisualizationType::Primitives, CollisionType::CallbackFunction)); std::stringstream idlerName; idlerName << "idler " << m_track_idx; m_idler = ChSharedPtr<IdlerSimple>(new IdlerSimple(idlerName.str(), VisualizationType::Mesh, CollisionType::Primitives)); std::stringstream chainname; chainname << "chain " << m_track_idx; m_chain = ChSharedPtr<TrackChain>(new TrackChain(chainname.str(), // VisualizationType::Primitives, VisualizationType::CompoundPrimitives, CollisionType::Primitives)); // CollisionType::CompoundPrimitives) ); // build suspension/road wheel subsystems for (int i = 0; i < m_numSuspensions; i++) { std::stringstream susp_name; susp_name << "suspension " << i << ", chain " << m_track_idx; m_suspensions[i] = ChSharedPtr<TorsionArmSuspension>( new TorsionArmSuspension(susp_name.str(), VisualizationType::Primitives, CollisionType::Primitives, 0, i )); } } void TrackSystem::Initialize(ChSharedPtr<ChBodyAuxRef> chassis, const ChVector<>& local_pos, ChTrackVehicle* vehicle, double pin_damping) { m_local_pos = local_pos; m_gearPosRel = m_gearPos; m_idlerPosRel = m_idlerPos; // if we're on the left side of the vehicle, switch lateral z-axis on all relative positions if (m_local_pos.z < 0) { m_gearPosRel.z *= -1; m_idlerPosRel.z *= -1; } // Create list of the center location of the rolling elements and their clearance. // Clearance is a sphere shaped envelope at each center location, where it can // be guaranteed that the track chain geometry will not penetrate the sphere. std::vector<ChVector<> > rolling_elem_locs; // w.r.t. chassis ref. frame std::vector<double> clearance; // 1 per rolling elem std::vector<ChVector<> > rolling_elem_spin_axis; /// w.r.t. abs. frame // initialize 1 of each of the following subsystems. // will use the chassis ref frame to do the transforms, since the TrackSystem // local ref. frame has same rot (just difference in position) // NOTE: move drive Gear Init() AFTER the chain of shoes is created, since // need the list of shoes to be passed in to create custom collision w/ gear // HOWEVER, still add the info to the rolling element lists passed into TrackChain Init(). // drive sprocket is First added to the lists passed into TrackChain Init() rolling_elem_locs.push_back(m_local_pos + Get_gearPosRel()); clearance.push_back(m_driveGear->GetRadius()); rolling_elem_spin_axis.push_back(m_driveGear->GetBody()->GetRot().GetZaxis()); // initialize the torsion arm suspension subsystems for (int s_idx = 0; s_idx < m_suspensionLocs.size(); s_idx++) { m_suspensions[s_idx]->Initialize(chassis, chassis->GetFrame_REF_to_abs(), ChCoordsys<>(m_local_pos + m_suspensionLocs[s_idx], QUNIT)); // add to the lists passed into the track chain, find location of each wheel center w.r.t. chassis coords. rolling_elem_locs.push_back(m_local_pos + m_suspensionLocs[s_idx] + m_suspensions[s_idx]->GetWheelPosRel()); clearance.push_back(m_suspensions[s_idx]->GetWheelRadius()); rolling_elem_spin_axis.push_back(m_suspensions[s_idx]->GetWheelBody()->GetRot().GetZaxis()); } // last control point: the idler body m_idler->Initialize(chassis, chassis->GetFrame_REF_to_abs(), ChCoordsys<>(m_local_pos + Get_idlerPosRel(), Q_from_AngAxis(CH_C_PI, VECT_Z)), m_idler_preload); // add to the lists passed into the track chain Init() rolling_elem_locs.push_back(m_local_pos + Get_idlerPosRel()); clearance.push_back(m_idler->GetRadius()); rolling_elem_spin_axis.push_back(m_idler->GetBody()->GetRot().GetZaxis()); // After all rolling elements have been initialized, now able to setup the TrackChain. // Assumed that start_pos is between idler and gear control points, e.g., on the top // of the track chain. ChVector<> start_pos = (rolling_elem_locs.front() + rolling_elem_locs.back()) / 2.0; start_pos.y += (clearance.front() + clearance.back()) / 2.0; // Assumption: start_pos should lie close to where the actual track chain would // pass between the idler and driveGears. // MUST be on the top part of the chain so the chain wrap rotation direction can be assumed. m_chain->Initialize(chassis, chassis->GetFrame_REF_to_abs(), rolling_elem_locs, clearance, rolling_elem_spin_axis, start_pos); // add some initial damping to the inter-shoe pin joints if (pin_damping > 0) m_chain->Set_pin_friction(pin_damping); // chain of shoes available for gear init m_driveGear->Initialize(chassis, chassis->GetFrame_REF_to_abs(), ChCoordsys<>(m_local_pos + Get_gearPosRel(), QUNIT), m_chain->GetShoeBody(), vehicle); } const ChVector<> TrackSystem::Get_idler_spring_react() { return m_idler->m_shock->Get_react_force(); } } // end namespace chrono
jcmadsen/chrono
src/demos/trackVehicle/subsys/trackSystem/TrackSystem.cpp
C++
bsd-3-clause
9,871
# eXist Book Example Code [![Build Status](https://travis-ci.org/eXist-book/book-code.png?branch=master)](https://travis-ci.org/eXist-book/book-code) [![Java 7](https://img.shields.io/badge/java-7-blue.svg)](http://java.oracle.com) [![License](https://img.shields.io/badge/license-BSD%203-blue.svg)](http://www.opensource.org/licenses/BSD-3-Clause) This repository contains all (except the [Using eXist 101 chapter](https://github.com/eXist-book/using-exist-101)) of the code and examples discussed in the [eXist book](http://shop.oreilly.com/product/0636920026525.do) published by O'Reilly. This version contains code compatible with eXist-db 2.1 which was the latest version at the time the book was authored. Versions for eXist-db [3.0.RC1](https://github.com/eXist-book/book-code/tree/eXist-3.0.RC1), [3.0](https://github.com/eXist-book/book-code/tree/eXist-3.0), and [4.0.0](https://github.com/eXist-book/book-code/tree/eXist-4.0.0) are also available. The repository has the following layout: * [chapters/](https://github.com/eXist-book/book-code/tree/master/chapters) Under this folder each chapter of the book that has example code is represented. * [xml-examples-xar/](https://github.com/eXist-book/book-code/tree/master/xml-examples-xar) These are the files needed to build an EXPath Package XAR from other files distributed in the chapters folders. In particular the content of the XAR package is assembled using the the `fileSet`s set out in the assembly [xml-examples-xar/expath-pkg.assembly.xml](https://github.com/eXist-book/book-code/blob/master/xml-examples-xar/expath-pkg.assembly.xml) All other files are related to the Maven build process. Building ======== The EXPath Package XAR and the Java projects are all built using Apache Maven. You will need to have Git and at least Maven 3.1.1 installed. Git can be downloaded and installed from http://git-scm.com and you can download and install Maven from http://maven.apache.org. Once you have Maven installed you can simply run the following from your Unix/Linux/Mac terminal or Windows command prompt: ```bash git clone https://github.com/eXist-book/book-code.git cd book-code mvn clean install ``` You should then find the EXPath PKG XAR located at `xml-examples-xar/target/exist-book.xar`. The Java projects artifacts will be located within the `target` sub-folders of each Java project respectively.
eXist-book/book-code
README.md
Markdown
bsd-3-clause
2,391
<?php // uncomment the following to define a path alias // Yii::setPathOfAlias('local','path/to/local-folder'); // This is the main Web application configuration. Any writable // CWebApplication properties can be configured here. return array( 'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..', 'name'=>'Plataforma LAEL', 'language'=>'es', 'sourceLanguage'=>'en', 'charset'=>'utf-8', 'theme'=>'classic', // preloading 'log' component 'preload'=>array('log'), // autoloading model and component classes 'import'=>array( 'application.models.*', 'application.components.*', ), 'modules'=>array( // uncomment the following to enable the Gii tool /* 'gii'=>array( 'class'=>'system.gii.GiiModule', 'password'=>'Enter Your Password Here', // If removed, Gii defaults to localhost only. Edit carefully to taste. 'ipFilters'=>array('127.0.0.1','::1'), ), */ ), // application components 'components'=>array( 'user'=>array( // enable cookie-based authentication 'allowAutoLogin'=>true, ), // uncomment the following to enable URLs in path-format /* 'urlManager'=>array( 'urlFormat'=>'path', 'rules'=>array( '<controller:\w+>/<id:\d+>'=>'<controller>/view', '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>', '<controller:\w+>/<action:\w+>'=>'<controller>/<action>', ), ), */ 'db'=>array( 'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db', ), // uncomment the following to use a MySQL database /* 'db'=>array( 'connectionString' => 'mysql:host=localhost;dbname=testdrive', 'emulatePrepare' => true, 'username' => 'root', 'password' => '', 'charset' => 'utf8', ), */ 'errorHandler'=>array( // use 'site/error' action to display errors 'errorAction'=>'site/error', ), 'log'=>array( 'class'=>'CLogRouter', 'routes'=>array( array( 'class'=>'CFileLogRoute', 'levels'=>'error, warning', ), // uncomment the following to show log messages on web pages /* array( 'class'=>'CWebLogRoute', ), */ ), ), ), // application-level parameters that can be accessed // using Yii::app()->params['paramName'] 'params'=>array( // this is used in contact page 'adminEmail'=>'[email protected]', ), );
phghost/plataformaeducativalael-1
protected/config/main.php
PHP
bsd-3-clause
2,340
# $FreeBSD: releng/9.3/sys/modules/drm2/radeonkmsfw/R300_cp/Makefile 254885 2013-08-25 19:37:15Z dumbbell $ KMOD= radeonkmsfw_R300_cp IMG= R300_cp .include <bsd.kmod.mk>
dcui/FreeBSD-9.3_kernel
sys/modules/drm2/radeonkmsfw/R300_cp/Makefile
Makefile
bsd-3-clause
172
/** Copyright (c) 2014, Nathan Carver All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @file Code to run the TEETH Smart Toothbrush Holder on Intel Edison board. * * Code is maintained at https://github.com/ncarver/TEETH-IotToothbrushHolder. * * All code and modules are defined in this file, main.js. * * @author Nathan Carver * @copyright Nathan Carver 2014 * @version 0.0.1 */ /* * Required libraries * * You will need these libraries to interface with the services and hardware. */ var MRAA = require('mraa'); //require MRAA for communicating with hardware pins var LCD = require('jsupm_i2clcd'); //require LCD libraries for signaling the LCD screen var LED = require('jsupm_grove'); //require SEEED Grove library for photoresister var BUZZ = require("jsupm_buzzer"); //require SEEED Grove library for buzzer var MAILER = require('nodemailer'); //require for sending emails over SMTP var NET = require('net'); //require for sending cloud data to Edison service on TCP /** * Change the constants properties to customize the operation of the TEETH Smart Toothbrush Timer * @global */ var constants = { 'LOG_LEVEL': 3, //Change this value to limit loggin output: 0-none, 1-err, 2-warn, 3-info, 4-debug, 5-all 'USE_SOUND': true, 'PINS': { //Change these values to match the pins on your Edison build 'brushSwitch': [8, 4], //digital pins monitoring switches for toothbrushes 'buzzer': 3, //digital pin for signaling the buzzer 'roomLightSensor': 0, //analog pin for getting room light readings from photoresister on 10K external pullup 'roomLightThreshold' : 80 //value that indicates that room is dark }, 'MAIL': { //Change these values based on documentation at nodemailer to use your SMTP account 'service': 'Gmail', //Account service name, ex. "Gmail" 'user': '[email protected]', //user name to login to your service 'pass': 'pass****', //password to login to your service 'from': 'TEETH <[email protected]>', //appears in the "From:" section of your emails 'brushTo': ['[email protected]', '[email protected]'], //email value for each toothbrush 'subject': 'Great job on TEETH!', //appears as the subject of your emails 'body': 'You met the goal today. Way to go!' //the body text of your emails }, 'METRICS': { //Change these values to match the custom components of your Intel Cloud Analytics 'brushComponent': ['brush1', 'brush2'] //component value for each toothbrush }, 'SCREEN_MSG': { //Messages that appear on the LCD screen during the timer prep and countdown 'ready': '...get ready', //message to display during start of prep time 'set': '.....get set', //message to display last five seconds of prep time 'countdown': 'Countdown:', //message to display during countdown 'percent25': '...almost there!', //message to display 25% of the way through countdown 'percent50': 'good...halfway ', //message to display 50% of the way through countdown 'percent75': 'you\'re doing it ', //message to display 75% of the way through countdown 'finish': 'GREAT JOB!', //message to display at the end of countdown 'brushName': ['Nathan', 'Sarah'] //name to display during countdwon, one value for each toothbrush }, 'TIME': { //Time focused constants for timer, buzzer sounds 'brushPreptime': [10, 30], //seconds of prep time for each toothbrush 'brushGoaltime': [30, 120], //seconds of countdown time for each toothbrush 'buzzDuration': 20, //milliseconds of buzzer time for start and stop sounds 'buzzInterval': 150 //milliseconds between buzzer sounds for start and stop signals }, 'COLOR': { //Colors to use on the LCD screen 'off': [ 0, 0, 0], //black - use when LCD is off 'ready': [100, 100, 100], //light grey - use during prep time 'percent0': [255, 68, 29], //red - use at start of countdown 'percent25': [232, 114, 12], //brown - use when countdown is 25% finished 'percent50': [255, 179, 0], //orange - use when countdown is 50% finished 'percent75': [232, 211, 12], //yellow - use when countdown is 75% finished 'finish': [ 89, 132, 13], //green - use when countdown is finished 'colorFadeDuration': 1000, //milliseconds to fade to new color during countdown mode 'fadeSteps': 100 //number of fading steps to take during colorFadeDuration } }; /** * These values hold the setTimeout and setInterval handles so they can be cleared as part of a timer interuption * @global */ var timers = { 'fadeColor': null, //timer fading the color on the LCD screen 'buzzerPlay': null, //timer playing the buzzer sounds 'buzzerWait': null, //timer waiting in between buzzer sounds 'prepCountdown': null, //timer for the main prep time 'startCountdown': null, //timer for the last five seconds of prep time 'countdown': null, //timer for the main countdown 'lightsOut': null //timer lookin for "lights out" interuption }; /** * Creates a new Logger object and the helper methods used to send messages to console. * Highest level of logging, ERR (1), only outputs errors during code execution. * Lowest level DEBUG (4) outputs all logging messages. * * @see constants.LOG_LEVEL Use the constant constants.LOG_LEVEL to adjust the level of output. * @class */ var Logger = function () { this.ERR = 1; this.WARN = 2; this.INFO = 3; this.DEBUG = 4; /** * @private */ var logLevels = ['', 'err', 'warn', 'info', 'debug']; /** * @param {string} msg message to send to logger * @param {int} level log level for this message * @public */ this.it = function (msg, level) { if (constants.LOG_LEVEL >= level || level === undefined) { console.log('%s - %s: %s', new Date(), logLevels[level], msg); } }; /* * @param {string} msg message to send to logger at log level ERR (1) * @public */ this.err = function (msg) { this.it(msg, this.ERR); }; /* * @param {string} msg message to send to logger at log level WARN (2) * @public */ this.warn = function (msg) { this.it(msg, this.WARN); }; /* * @param {string} msg message to send to logger at log level INFO (3) * @public */ this.info = function (msg) { this.it(msg, this.INFO); }; /* * @param {string} msg message to send to logger at log level DEBUG (4) * @public */ this.debug = function (msg) { this.it(msg, this.DEBUG); }; }; /** * Creates a new Sensors object to monitor the hardware connected to the Edison * @requires mraa:Gpio * @requires mraa:Aio * @param {Logger} log object for logging output * @see constants.PINS Use the constant constants.PINS to identify the hardware connections * @class */ var Sensors = function (log) { log.info('instatiate Sensors'); /** * @private */ var i; /** * the array of switches associated with each toothbrush are initialized * as INPUT pins during instatiation. * @public */ this.brushSwitch = []; for (i = 0; i < constants.PINS.brushSwitch.length; i = i + 1) { this.brushSwitch[i] = new MRAA.Gpio(constants.PINS.brushSwitch[i]); this.brushSwitch[i].dir(MRAA.DIR_IN); } /** * the analog pin for monitoring the phototransister is initialized * during instatiation. Expected that this photo cell will have a 10K * external pulldown resistor. * @public */ // this.roomLightSensor = new MRAA.Aio(constants.PINS.roomLightSensor); }; /** * Creates a new Buzzer object to play a sound on the buzzer connected to the Edison * @requires jsupm_buzzer:Buzzer * @param {Logger} log object for logging output * @see constants.TIME Use the properties of constants.TIME to adjust the buzzer sounds * @class */ var Buzzer = function (log) { log.info('instatiate Buzzer'); var buzzer = new BUZZ.Buzzer(constants.PINS.buzzer); /** * play calls the playSound method of the low-level buzzer class for a simple tone value * @private */ function play(buzzingTime) { log.debug('(buzzer.play for ' + buzzingTime + ')'); if (!constants.USE_SOUND) { return; } buzzer.playSound(BUZZ.DO, 5000); timers.buzzerPlay = setTimeout(function () { buzzer.playSound(BUZZ.DO, 0); }, buzzingTime); } /** * plays the standard sound for the buzz duration, then waits, and plays again * expected to be called at the beginning of the countdown * @public */ this.playStartSound = function () { log.info('buzzer.playStartSound'); play(constants.TIME.buzzDuration); timers.buzzerWait = setTimeout(function () { play(constants.TIME.buzzDuration); }, constants.TIME.buzzInterval); }; /** * plays the standard sound for the buzz duration, then waits, and plays again * expected to be called at the end of the countdown * @public */ this.playStopSound = function () { log.info('buzzer.playStopSound'); play(constants.TIME.buzzDuration); timers.buzzerWait = setTimeout(function () { play(constants.TIME.buzzDuration); }, constants.TIME.buzzInterval); }; }; /** * Creates a new Screen object to display messages and colors RGB LCD connected to the Edison over I2C * @requires jsupm_i2clcd:Jhd1313m1 * @param {Logger} log object for logging output * @see constants.COLOR Use the properties of constants.COLOR to adjust the screen background colors * @see constants.SCREEN_MSG Use the properties of constants.SCREEN_MSG to change the messages displayed on screen * @class */ var Screen = function (log) { log.info('instatiate Screen'); /** * Instance variables to connect to LCD screen and manage the color fading * @private */ var lcd = new LCD.Jhd1313m1(6, 0x3E, 0x62), //standard I2C bus interval = constants.COLOR.colorFadeDuration / constants.COLOR.fadeSteps, lastColor = constants.COLOR.off, steps = constants.COLOR.fadeSteps; /** * getRemainingSteps identifies how many more steps are needed before fade is finished * @returns {int} number of steps remaining * @private */ function getRemainingSteps() { log.debug('(screen.getRemainingSteps)'); return steps; } /** * setRemainingSteps sets how many more steps are needed before fade is finished * @params {int} remainingSteps new number of steps remaining * @private */ function setRemainingSteps(remainingSteps) { log.debug('(screen.setRemainingSteps: ' + remainingSteps + ')'); steps = remainingSteps; } /** * setScreen color calls low-level methods to set RGB values of screen background * also sets the instance variable "lastColor" to help with fade control * @param {array} colorArray array of decimal color values in Red Green Blue order [r,g,b] * @private */ function setScreenColor(colorArray) { log.debug('(screen.setScreenColor to ' + colorArray + ')'); lcd.setColor(colorArray[0], colorArray[1], colorArray[2]); lastColor = colorArray; } /** * Inner method called by timeouts to fade background color from current color to the * updated color passed RGB color array * @private */ function _fadeColor(colorArray) { log.debug('(screen._fadeColor: ' + colorArray + ')'); var step = getRemainingSteps(); if (step > 0) { var diffRed = colorArray[0] - lastColor[0], diffGrn = colorArray[1] - lastColor[1], diffBlu = colorArray[2] - lastColor[2], stepRed = parseInt(diffRed / step, 10), stepGrn = parseInt(diffGrn / step, 10), stepBlu = parseInt(diffBlu / step, 10), nextRed = lastColor[0] + stepRed, nextGrn = lastColor[1] + stepGrn, nextBlu = lastColor[2] + stepBlu; setScreenColor([nextRed, nextGrn, nextBlu]); setRemainingSteps(step - 1); timers.fadeColor = setTimeout(function () { _fadeColor(colorArray); }, interval); } } /** * Starts a timout sequence to slowy change the LCD RGB screen background from its current * color to the one passed in the parameters. The speed and number of steps used for fading * are controlled by the constants. * * @param {array} colorArray a 3-member array of decimal numbers describing the color to display * on the screen background: [r,g,b] * @public */ this.fadeColor = function (colorArray) { log.info('screen.fadeColor: ' + colorArray); setRemainingSteps(constants.COLOR.fadeSteps); _fadeColor(colorArray); }; /** * Helper method combines clearing the screen of all text content and returning the cursor * position back to the top left. * @public */ this.reset = function () { log.info('screen.reset'); lcd.clear(); lcd.setCursor(0, 0); }; /** * Helper method combines reseting the screen and returning the screen color to "off" * @public */ this.resetAndTurnOff = function () { log.info('screen.resetAndTurnOff'); this.reset(); setScreenColor(constants.COLOR.off); }; /** * Turns the screen on and displays the "ready" message defined in constants for the given toothbrush * * @param {int} componentIndex identifies the toothbrush by it's array index * @public */ this.displayReady = function (componentIndex) { log.info('screen.displayReady for ' + componentIndex); lcd.clear(); setScreenColor(constants.COLOR.ready); this.write(constants.SCREEN_MSG.brushName[componentIndex], 0, 0); this.write(constants.SCREEN_MSG.ready, 1, 0); }; /** * Changes the "ready" message to the "set" message defined in constants for the given toothbrush * * @param {int} componentIndex identifies the toothbrush by it's array index * @public */ this.displaySet = function (componentIndex) { log.info('screen.displaySet for ' + componentIndex); this.write(constants.SCREEN_MSG.set, 1, 0); }; /** * Helper message combines writing the given message to the screen at (optional) given coordinates * * @param {string} msg the string to ouput to the screen * @param {int} col (optional) 0-indexed column number to set the cursor * @param {int} row (optional) 0-indexed row number to set the cursor * @public */ this.write = function (msg, col, row) { //log.info('screen.write msg ' + msg); var i; if (!(col === undefined || row === undefined)) { lcd.setCursor(col, row); for (i = 0; i < 10000000; i = i + 1) { //wait for slow LCD } } lcd.write(msg); }; //initialize the LCD screen during instatiation this.resetAndTurnOff(); }; /** * Creates a new Mailer object to send mail over SMTP * @requires nodemailer * @param {Logger} log object for logging output * @see constants.MAIL Use the properties of constants.MAIL to configure your SMTP service * @class */ var Mailer = function (log) { log.info('instatiate Mailer'); /** * Instance options taken from constants.MAIL are used by createTransport to authenticate SMTP * @private */ var mailOptions = { from: constants.MAIL.from, // sender address to: constants.MAIL.brushTo[0], // list of receivers subject: constants.MAIL.subject, // Subject line text: constants.MAIL.body, // plaintext body html: constants.MAIL.body // html body }, transporter = MAILER.createTransport({ service: constants.MAIL.service, auth: { user: constants.MAIL.user, pass: constants.MAIL.pass } }); /** * Sends the message defined in constants.MAIL for the given toothbrush. * Errors are sent to the log Logger object. * @param {int} componentIndex identifies the toothbrush by it's array index in constants * @public */ this.sendCongratsEmail = function (componentIndex) { log.info('mailer.sendCongratsEmail for ' + componentIndex); mailOptions.to = constants.MAIL.brushTo[componentIndex]; transporter.sendMail(mailOptions, function (error, info) { if (error) { log.err('mail error ' + error + '.'); } else { log.info('mail sent.'); } }); }; }; /** * Creates a new Metrics object to connect to Intel Cloud Analytics over TCP * @requires net:socket * @param {Logger} log object for logging output * @class */ var Metrics = function (log) { log.info('instatiate metrics'); /** * instance objects and options to connect over TCP to Edison iot-agent * @private */ var client = new NET.Socket(), options = { host : 'localhost', //use the Intel analytics client running locally on the Edison port : 7070 //on default TCP port }; /** * sendObservation concatenates the string expected by cloud analytics based on the parameter values * @param {string} name custom component name registered with Intel analytics * @param {float} value data value to send to cloud * @private */ function sendObservation(name, value) { log.debug('(metrics.sendObservation for ' + name + ', ' + value + ')'); var msg = JSON.stringify({ n: name, v: value }), sentMsg = msg.length + "#" + msg; //syntax for Intel analytics client.write(sentMsg); } /** * Method combines the activity of connecting to the Edision service and then sending data to the cloud * @param {int} itemIndex array index of component names registered with Intel analytics * @param {float} timeValue data value to send to cloud, expecting fractional number of seconds * @public */ this.addDataToCloud = function (itemIndex, timeValue) { log.info('metrics.addDataToCloud for ' + itemIndex + ', ' + timeValue); client.on('error', function () { log.err('Could not connect to cloud'); }); client.connect(options.port, options.host, function () { sendObservation(constants.METRICS.brushComponent[itemIndex], timeValue); }); }; }; /** * Creates a new Teeth object to manage the countdown timer * @param {Logger} log object for logging output * @param {Sensors} sensor object for listening to hardware sensors * @param {Buzzer} buzzer object for controlling the sounds * @param {Screen} screen object for display on the RGB LCD screen * @param {Mailer} mailer object for sending email * @param {Metrics} metrics object for sending data to cloud * @see constants.TIME Use the properties of constants.TIME to adjust the length of the countdown * @class */ var Teeth = function (log, sensors, buzzer, lcdScreen, mailer, metrics) { log.info('instatiate teeth'); /** * flags to make sure fadeColor only called once for each color * @private */ var fades = [], currentComponent = -1, timeSpent = 0; /** * clearAllTimers loops through all timers in constants to clear them and set to null * @private */ function clearAllTimers() { log.debug('(teeth.clearAllTimers)'); var key, timer; for (key in timers) { if (timers.hasOwnProperty(key)) { timer = timers[key]; if (timer !== null) { clearTimeout(timer); timer = null; } } } fades = []; currentComponent = -1; } /** * finishCountdown clears the screen, plays the stop sound, and starts the waiting process again * @param {int} componentIndex array index number of the toothbrush that is finishing the countdown * @private */ function finishCountdown(componentIndex) { log.debug('(teeth.finishCountdown for ' + componentIndex + ')'); clearAllTimers(); lcdScreen.reset(); buzzer.playStopSound(); mailer.sendCongratsEmail(componentIndex); lcdScreen.write(constants.SCREEN_MSG.finish); metrics.addDataToCloud(componentIndex, constants.TIME.brushGoaltime[componentIndex]); setTimeout(function () { lcdScreen.resetAndTurnOff(); wait(); }, 1000); } /** * countdown generates messages and colors to the screen during the countdown, * called continuously until time is over * @param {int} componentIndex array index number of the toothbrush that is in the middle of the countdown * @param {int} timeRemaining the amount of time remaining in seconds before the countdown is over * @private */ function countdown(componentIndex, timeRemaining) { log.debug('(teeth.countdown for ' + componentIndex + ': ' + timeRemaining + ')'); var originalValue = constants.TIME.brushGoaltime[componentIndex]; timeSpent = originalValue - timeRemaining; if (timeRemaining > 0) { lcdScreen.write(constants.SCREEN_MSG.countdown + timeRemaining + ' ', 0, 0); if (timeRemaining <= (0.25 * originalValue)) { lcdScreen.write(constants.SCREEN_MSG.percent25, 1, 0); if (fades[constants.COLOR.percent25] !== 1) { lcdScreen.fadeColor(constants.COLOR.percent25); fades[constants.COLOR.percent25] = 1; } } else if (timeRemaining <= (0.5 * originalValue)) { lcdScreen.write(constants.SCREEN_MSG.percent50, 1, 0); if (fades[constants.COLOR.percent50] !== 1) { lcdScreen.fadeColor(constants.COLOR.percent50); fades[constants.COLOR.percent50] = 1; } } else if (timeRemaining <= (0.75 * originalValue)) { lcdScreen.write(constants.SCREEN_MSG.percent75, 1, 0); if (fades[constants.COLOR.percent75] !== 1) { lcdScreen.fadeColor(constants.COLOR.percent75); fades[constants.COLOR.percent75] = 1; } } timers.countdown = setTimeout(function () { countdown(componentIndex, timeRemaining - 1); }, 1000); } else { finishCountdown(componentIndex); } } /** * startCountdown plays the sound and begins the first call to countdown * @param {int} componentIndex array index number of the toothbrush that is starting the countdown * @private */ function startCountdown(componentIndex) { log.info('(teeth.startCountdown for ' + componentIndex + ')'); buzzer.playStartSound(); lcdScreen.reset(); currentComponent = componentIndex; countdown(componentIndex, constants.TIME.brushGoaltime[componentIndex]); } /** * prepCountdown prepares the screen and waits for real countdown to begin, displays * an additional warning with five seconds to go * @param {int} componentIndex array index number of the toothbrush that is starting the countdown * @private */ function prepCountdown(componentIndex) { log.debug('(teeth.prepCountdown for ' + componentIndex + ')'); lcdScreen.displayReady(componentIndex); var prepTime = constants.TIME.brushPreptime[componentIndex]; timers.prepCountdown = setTimeout(function () { log.debug('setTimeout: prepCountdown'); lcdScreen.displaySet(componentIndex); }, (prepTime - 5) * 1000); timers.startCountdown = setTimeout(function () { log.debug('setTimeout: startCountdown'); startCountdown(componentIndex); }, prepTime * 1000); } /** * watchForLightsOut polls the photoresistor to see if the room is dark, then stops all activity * @private */ function watchForLightsOut() { //do not log.debug >> called every 50ms return; var val = sensors.roomLightSensor.read(); if (val < constants.PINS.roomLightThreshold) { log.info('Trigger for lights out: Stop Timer (early) then wait 5 seconds to start again'); if (currentComponent >= 0) { metrics.addDataToCloud(currentComponent, timeSpent); } clearAllTimers(); lcdScreen.resetAndTurnOff(); setTimeout(wait, 5000); } } /** * wait is the main entry to this class, it polls the switches regularly to see if it should start the countdown * @private */ function wait() { //do not log.debug >> called every 100ms var i, val; for (i = 0; i < sensors.brushSwitch.length; i = i + 1) { val = sensors.brushSwitch[i].read(); if (val === 0) { //0 for NO (normally open switch), 1 for NC (normally closed) log.info('Trigger for toothbrush ' + i + ': Start Timer'); prepCountdown(i); timers.lightsOut = setInterval(watchForLightsOut, 50); break; } } if (i >= sensors.brushSwitch.length) { setTimeout(wait, 100); } } /** * Entry point to Teeth, the start command initiates the Smart Toothbrush Holder and begins the process of waiting for a countdown * @public */ this.start = function () { log.info('Teeth.start waiting for toothbrush events'); wait(); }; }; /* Create instance objects of the classes needed by TEETH */ var log = new Logger(), sensors = new Sensors(log), buzzer = new Buzzer(log), lcdScreen = new Screen(log), mailer = new Mailer(log), metrics = new Metrics(log), teeth = new Teeth(log, sensors, buzzer, lcdScreen, mailer, metrics); /* Get the code running by invoking the start method of the Teeth controller */ teeth.start();
ncarver/TEETH
main.js
JavaScript
bsd-3-clause
28,665
<?php use app\core\helpers\Html; use app\core\helpers\Url; $this->title = '权限管理 在此页面添加名修改权限项注释'; $this->params['breadcrumbs'][] = $this->title; ?> <style type="text/css"> .nopad{padding-left: 0} .panel-default>.panel-heading{ padding: 10px 15px; background-color: #f5f5f5; border-color: #ddd; } </style> <div class="page-content"> <!-- /section:settings.box --> <div class="page-content-area"> <div class="page-header"> <h1> <small> <a data-loading-text="数据更新中, 请稍后..." href="<?=Url::toRoute('sync')?>" class="btn btn-danger auth-sync">权限初始化</a> </small> <?= $this->render('@app/modules/sys/views/admin/layout/_nav.php') ?> </h1> </div><!-- /.page-header --> <div class="row"> <div class="col-md-12"> <?php foreach ($classes as $key => $value):?> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <?=$key;?> </h4> </div> <div class="panel-body"> <?php foreach ($value as $ke => $val):?> <dl class="col-md-12 col-sm-12 nopad"> <dt><?php echo $ke;?> </dt> <?php foreach ($val as $k => $v):?> <dd class="col-md-3 nopad"> <span class="lbl "> <?php echo $k?> <input value="<?= $v['title']?>" class="action_des input-small form-control" key="<?=$v['name']?>" /> </span> </dd> <?php endforeach;?> </dl> <hr/> <?php endforeach;?> </div> </div> <?php endforeach;?> </div> </div><!-- /.row --> </div><!-- /.page-content-area --> </div><!-- /.page-content --> <?php $this->beginBlock('auth') ?> $(function(){ $('.auth-sync').click(function(e){ e.preventDefault(); var btn = $(this).button('loading'); $.get($(this).attr('href'),null,function(xhr){ if (xhr.status) { location.reload(); }; btn.button('reset'); },'json'); }); $('.action_des').change(function(e){ e.preventDefault(); var url = "<?=Url::toRoute('title')?>"; var csrf = $('meta[name=csrf-token]').attr('content'); var data = {name:$(this).attr('key'), title:$(this).val(), _csrf:csrf}; $.post(url, data, function(xhr){ if (!xhr.status) { alert(xhr.info); }; },'json'); }); }) <?php $this->endBlock() ?> <?php $this->registerJs($this->blocks['auth'], \yii\web\View::POS_END); ?>
cboy868/lion2
modules/sys/views/admin/auth-permission/index.php
PHP
bsd-3-clause
3,238
<!doctype html> <html> <head> <meta charset="utf-8"> <title>System\Browser\assets\scripts\Flash.js 源码</title> <link href="../../assets/styles/prettify.css" type="text/css" rel="stylesheet" /> <script src="../../assets/scripts/prettify.js" type="text/javascript"></script> <style type="text/css">.highlight { display: block; background-color: #ddd; }</style> </head> <body onload="setTimeout('prettyPrint()', 0);var node = document.getElementById(location.hash.replace(/#/, ''));if(node)node.className = 'highlight';"><pre class="prettyprint lang-js">//=========================================== // Swf swiff.js A //=========================================== using(&quot;System.Controls.Control&quot;); namespace(&quot;.Swiff&quot;, JPlus.Control.extend({ options: { id: null, height: 1, width: 1, container: null, properties: {}, params: { quality: 'high', allowScriptAccess: 'always', wMode: 'window', swLiveConnect: true }, callBacks: {}, vars: {} }, constructor: function (path, options) { this.instance = 'Swiff_' + String.uniqueID(); this.setOptions(options); options = this.options; var id = this.id = options.id || this.instance; var container = document.id(options.container); Swiff.CallBacks[this.instance] = {}; var params = options.params, vars = options.vars, callBacks = options.callBacks; var properties = Object.append({ height: options.height, width: options.width }, options.properties); var self = this; for (var callBack in callBacks) { Swiff.CallBacks[this.instance][callBack] = (function (option) { return function () { return option.apply(self.object, arguments); }; })(callBacks[callBack]); vars[callBack] = 'Swiff.CallBacks.' + this.instance + '.' + callBack; } params.flashVars = Object.toQueryString(vars); if (Browser.ie) { properties.classid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'; params.movie = path; } else { properties.type = 'application/x-shockwave-flash'; } properties.data = path; var build = '&lt;object id=&quot;' + id + '&quot;'; for (var property in properties) build += ' ' + property + '=&quot;' + properties[property] + '&quot;'; build += '&gt;'; for (var param in params) { if (params[param]) build += '&lt;param name=&quot;' + param + '&quot; value=&quot;' + params[param] + '&quot; /&gt;'; } build += '&lt;/object&gt;'; this.object = ((container) ? container.empty() : new Element('div')).set('html', build).firstChild; }, remote: function () { return Swiff.remote.apply(Swiff, [this.node || this].append(arguments)); } })); Swiff.CallBacks = {}; Swiff.remote = function (obj, fn) { var rs = obj.CallFunction('&lt;invoke name=&quot;' + fn + '&quot; returntype=&quot;javascript&quot;&gt;' + __flash__argumentsToXML(arguments, 2) + '&lt;/invoke&gt;'); return eval(rs); };</pre> </body> </html>
jplusui/jplusui.github.com
resources/cookbooks/jplusui-full-api/data/source/System/Browser/assets/scripts/Flash.js.html
HTML
bsd-3-clause
3,002
define(['App', 'jquery', 'underscore', 'backbone', 'hbs!template/subreddit-picker-item', 'view/basem-view'], function(App, $, _, Backbone, SRPitemTmpl, BaseView) { return BaseView.extend({ template: SRPitemTmpl, events: { 'click .add': 'subscribe', 'click .remove': 'unsubscribe' }, initialize: function(data) { this.model = data.model; }, subscribe: function(e) { e.preventDefault() e.stopPropagation() var target = this.$(e.currentTarget) target.removeClass('add').addClass('remove').html('unsubscribe') var params = { action: 'sub', sr: this.model.get('name'), sr_name: this.model.get('name'), uh: $.cookie('modhash') }; console.log(params) this.api("api/subscribe", 'POST', params, function(data) { console.log("subscribe done", data) //edit the window and cookie App.trigger('header:refreshSubreddits') }); }, unsubscribe: function(e) { e.preventDefault() e.stopPropagation() var target = this.$(e.currentTarget) target.removeClass('remove').addClass('add').html('subscribe') var params = { action: 'unsub', sr: this.model.get('name'), uh: $.cookie('modhash') }; console.log(params) this.api("api/subscribe", 'POST', params, function(data) { console.log("unsubscribe done", data) App.trigger('header:refreshSubreddits') }); } }); });
BenjaminAdams/RedditJS
public/js/app/view/subreddit-picker-item-view.js
JavaScript
bsd-3-clause
1,957
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\helpers; use Yii; use yii\base\InvalidParamException; use yii\db\ActiveRecordInterface; use yii\validators\StringValidator; use yii\web\Request; use yii\base\Model; /** * BaseHtml provides concrete implementation for [[Html]]. * * Do not use BaseHtml. Use [[Html]] instead. * * @author Qiang Xue <[email protected]> * @since 2.0 */ class BaseHtml { /** * @var array list of void elements (element name => 1) * @see http://www.w3.org/TR/html-markup/syntax.html#void-element */ public static $voidElements = [ 'area' => 1, 'base' => 1, 'br' => 1, 'col' => 1, 'command' => 1, 'embed' => 1, 'hr' => 1, 'img' => 1, 'input' => 1, 'keygen' => 1, 'link' => 1, 'meta' => 1, 'param' => 1, 'source' => 1, 'track' => 1, 'wbr' => 1, ]; /** * @var array the preferred order of attributes in a tag. This mainly affects the order of the attributes * that are rendered by [[renderTagAttributes()]]. */ public static $attributeOrder = [ 'type', 'id', 'class', 'name', 'value', 'href', 'src', 'action', 'method', 'selected', 'checked', 'readonly', 'disabled', 'multiple', 'size', 'maxlength', 'width', 'height', 'rows', 'cols', 'alt', 'title', 'rel', 'media', ]; /** * @var array list of tag attributes that should be specially handled when their values are of array type. * In particular, if the value of the `data` attribute is `['name' => 'xyz', 'age' => 13]`, two attributes * will be generated instead of one: `data-name="xyz" data-age="13"`. * @since 2.0.3 */ public static $dataAttributes = ['data', 'data-ng', 'ng']; /** * Encodes special characters into HTML entities. * The [[\yii\base\Application::charset|application charset]] will be used for encoding. * @param string $content the content to be encoded * @param boolean $doubleEncode whether to encode HTML entities in `$content`. If false, * HTML entities in `$content` will not be further encoded. * @return string the encoded content * @see decode() * @see http://www.php.net/manual/en/function.htmlspecialchars.php */ public static function encode($content, $doubleEncode = true) { return htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, Yii::$app ? Yii::$app->charset : 'UTF-8', $doubleEncode); } /** * Decodes special HTML entities back to the corresponding characters. * This is the opposite of [[encode()]]. * @param string $content the content to be decoded * @return string the decoded content * @see encode() * @see http://www.php.net/manual/en/function.htmlspecialchars-decode.php */ public static function decode($content) { return htmlspecialchars_decode($content, ENT_QUOTES); } /** * Generates a complete HTML tag. * @param string $name the tag name * @param string $content the content to be enclosed between the start and end tags. It will not be HTML-encoded. * If this is coming from end users, you should consider [[encode()]] it to prevent XSS attacks. * @param array $options the HTML tag attributes (HTML options) in terms of name-value pairs. * These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * * For example when using `['class' => 'my-class', 'target' => '_blank', 'value' => null]` it will result in the * html attributes rendered like this: `class="my-class" target="_blank"`. * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated HTML tag * @see beginTag() * @see endTag() */ public static function tag($name, $content = '', $options = []) { $html = "<$name" . static::renderTagAttributes($options) . '>'; return isset(static::$voidElements[strtolower($name)]) ? $html : "$html$content</$name>"; } /** * Generates a start tag. * @param string $name the tag name * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated start tag * @see endTag() * @see tag() */ public static function beginTag($name, $options = []) { return "<$name" . static::renderTagAttributes($options) . '>'; } /** * Generates an end tag. * @param string $name the tag name * @return string the generated end tag * @see beginTag() * @see tag() */ public static function endTag($name) { return "</$name>"; } /** * Generates a style tag. * @param string $content the style content * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated style tag */ public static function style($content, $options = []) { return static::tag('style', $content, $options); } /** * Generates a script tag. * @param string $content the script content * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated script tag */ public static function script($content, $options = []) { return static::tag('script', $content, $options); } /** * Generates a link tag that refers to an external CSS file. * @param array|string $url the URL of the external CSS file. This parameter will be processed by [[Url::to()]]. * @param array $options the tag options in terms of name-value pairs. The following option is specially handled: * * - condition: specifies the conditional comments for IE, e.g., `lt IE 9`. When this is specified, * the generated `link` tag will be enclosed within the conditional comments. This is mainly useful * for supporting old versions of IE browsers. * - noscript: if set to true, `link` tag will be wrapped into `<noscript>` tags. * * The rest of the options will be rendered as the attributes of the resulting link tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated link tag * @see Url::to() */ public static function cssFile($url, $options = []) { if (!isset($options['rel'])) { $options['rel'] = 'stylesheet'; } $options['href'] = Url::to($url); if (isset($options['condition'])) { $condition = $options['condition']; unset($options['condition']); return self::wrapIntoCondition(static::tag('link', '', $options), $condition); } elseif (isset($options['noscript']) && $options['noscript'] === true) { unset($options['noscript']); return "<noscript>" . static::tag('link', '', $options) . "</noscript>"; } else { return static::tag('link', '', $options); } } /** * Generates a script tag that refers to an external JavaScript file. * @param string $url the URL of the external JavaScript file. This parameter will be processed by [[Url::to()]]. * @param array $options the tag options in terms of name-value pairs. The following option is specially handled: * * - condition: specifies the conditional comments for IE, e.g., `lt IE 9`. When this is specified, * the generated `script` tag will be enclosed within the conditional comments. This is mainly useful * for supporting old versions of IE browsers. * * The rest of the options will be rendered as the attributes of the resulting script tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated script tag * @see Url::to() */ public static function jsFile($url, $options = []) { $options['src'] = Url::to($url); if (isset($options['condition'])) { $condition = $options['condition']; unset($options['condition']); return self::wrapIntoCondition(static::tag('script', '', $options), $condition); } else { return static::tag('script', '', $options); } } /** * Wraps given content into conditional comments for IE, e.g., `lt IE 9`. * @param string $content raw HTML content. * @param string $condition condition string. * @return string generated HTML. */ private static function wrapIntoCondition($content, $condition) { if (strpos($condition, '!IE') !== false) { return "<!--[if $condition]><!-->\n" . $content . "\n<!--<![endif]-->"; } return "<!--[if $condition]>\n" . $content . "\n<![endif]-->"; } /** * Generates the meta tags containing CSRF token information. * @return string the generated meta tags * @see Request::enableCsrfValidation */ public static function csrfMetaTags() { $request = Yii::$app->getRequest(); if ($request instanceof Request && $request->enableCsrfValidation) { return static::tag('meta', '', ['name' => 'csrf-param', 'content' => $request->csrfParam]) . "\n " . static::tag('meta', '', ['name' => 'csrf-token', 'content' => $request->getCsrfToken()]) . "\n"; } else { return ''; } } /** * Generates a form start tag. * @param array|string $action the form action URL. This parameter will be processed by [[Url::to()]]. * @param string $method the form submission method, such as "post", "get", "put", "delete" (case-insensitive). * Since most browsers only support "post" and "get", if other methods are given, they will * be simulated using "post", and a hidden input will be added which contains the actual method type. * See [[\yii\web\Request::methodParam]] for more details. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated form start tag. * @see endForm() */ public static function beginForm($action = '', $method = 'post', $options = []) { $action = Url::to($action); $hiddenInputs = []; $request = Yii::$app->getRequest(); if ($request instanceof Request) { if (strcasecmp($method, 'get') && strcasecmp($method, 'post')) { // simulate PUT, DELETE, etc. via POST $hiddenInputs[] = static::hiddenInput($request->methodParam, $method); $method = 'post'; } if ($request->enableCsrfValidation && !strcasecmp($method, 'post')) { $hiddenInputs[] = static::hiddenInput($request->csrfParam, $request->getCsrfToken()); } } if (!strcasecmp($method, 'get') && ($pos = strpos($action, '?')) !== false) { // query parameters in the action are ignored for GET method // we use hidden fields to add them back foreach (explode('&', substr($action, $pos + 1)) as $pair) { if (($pos1 = strpos($pair, '=')) !== false) { $hiddenInputs[] = static::hiddenInput( urldecode(substr($pair, 0, $pos1)), urldecode(substr($pair, $pos1 + 1)) ); } else { $hiddenInputs[] = static::hiddenInput(urldecode($pair), ''); } } $action = substr($action, 0, $pos); } $options['action'] = $action; $options['method'] = $method; $form = static::beginTag('form', $options); if (!empty($hiddenInputs)) { $form .= "\n" . implode("\n", $hiddenInputs); } return $form; } /** * Generates a form end tag. * @return string the generated tag * @see beginForm() */ public static function endForm() { return '</form>'; } /** * Generates a hyperlink tag. * @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code * such as an image tag. If this is coming from end users, you should consider [[encode()]] * it to prevent XSS attacks. * @param array|string|null $url the URL for the hyperlink tag. This parameter will be processed by [[Url::to()]] * and will be used for the "href" attribute of the tag. If this parameter is null, the "href" attribute * will not be generated. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated hyperlink * @see \yii\helpers\Url::to() */ public static function a($text, $url = null, $options = []) { if ($url !== null) { $options['href'] = Url::to($url); } return static::tag('a', $text, $options); } /** * Generates a mailto hyperlink. * @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code * such as an image tag. If this is coming from end users, you should consider [[encode()]] * it to prevent XSS attacks. * @param string $email email address. If this is null, the first parameter (link body) will be treated * as the email address and used. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated mailto link */ public static function mailto($text, $email = null, $options = []) { $options['href'] = 'mailto:' . ($email === null ? $text : $email); return static::tag('a', $text, $options); } /** * Generates an image tag. * @param array|string $src the image URL. This parameter will be processed by [[Url::to()]]. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated image tag */ public static function img($src, $options = []) { $options['src'] = Url::to($src); if (!isset($options['alt'])) { $options['alt'] = ''; } return static::tag('img', '', $options); } /** * Generates a label tag. * @param string $content label text. It will NOT be HTML-encoded. Therefore you can pass in HTML code * such as an image tag. If this is is coming from end users, you should [[encode()]] * it to prevent XSS attacks. * @param string $for the ID of the HTML element that this label is associated with. * If this is null, the "for" attribute will not be generated. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated label tag */ public static function label($content, $for = null, $options = []) { $options['for'] = $for; return static::tag('label', $content, $options); } /** * Generates a button tag. * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded. * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users, * you should consider [[encode()]] it to prevent XSS attacks. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated button tag */ public static function button($content = 'Button', $options = []) { if (!isset($options['type'])) { $options['type'] = 'button'; } return static::tag('button', $content, $options); } /** * Generates a submit button tag. * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded. * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users, * you should consider [[encode()]] it to prevent XSS attacks. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated submit button tag */ public static function submitButton($content = 'Submit', $options = []) { $options['type'] = 'submit'; return static::button($content, $options); } /** * Generates a reset button tag. * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded. * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users, * you should consider [[encode()]] it to prevent XSS attacks. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated reset button tag */ public static function resetButton($content = 'Reset', $options = []) { $options['type'] = 'reset'; return static::button($content, $options); } /** * Generates an input type of the given type. * @param string $type the type attribute. * @param string $name the name attribute. If it is null, the name attribute will not be generated. * @param string $value the value attribute. If it is null, the value attribute will not be generated. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated input tag */ public static function input($type, $name = null, $value = null, $options = []) { if (!isset($options['type'])) { $options['type'] = $type; } $options['name'] = $name; $options['value'] = $value === null ? null : (string) $value; return static::tag('input', '', $options); } /** * Generates an input button. * @param string $label the value attribute. If it is null, the value attribute will not be generated. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated button tag */ public static function buttonInput($label = 'Button', $options = []) { $options['type'] = 'button'; $options['value'] = $label; return static::tag('input', '', $options); } /** * Generates a submit input button. * @param string $label the value attribute. If it is null, the value attribute will not be generated. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated button tag */ public static function submitInput($label = 'Submit', $options = []) { $options['type'] = 'submit'; $options['value'] = $label; return static::tag('input', '', $options); } /** * Generates a reset input button. * @param string $label the value attribute. If it is null, the value attribute will not be generated. * @param array $options the attributes of the button tag. The values will be HTML-encoded using [[encode()]]. * Attributes whose value is null will be ignored and not put in the tag returned. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated button tag */ public static function resetInput($label = 'Reset', $options = []) { $options['type'] = 'reset'; $options['value'] = $label; return static::tag('input', '', $options); } /** * Generates a text input field. * @param string $name the name attribute. * @param string $value the value attribute. If it is null, the value attribute will not be generated. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated text input tag */ public static function textInput($name, $value = null, $options = []) { return static::input('text', $name, $value, $options); } /** * Generates a hidden input field. * @param string $name the name attribute. * @param string $value the value attribute. If it is null, the value attribute will not be generated. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated hidden input tag */ public static function hiddenInput($name, $value = null, $options = []) { return static::input('hidden', $name, $value, $options); } /** * Generates a password input field. * @param string $name the name attribute. * @param string $value the value attribute. If it is null, the value attribute will not be generated. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated password input tag */ public static function passwordInput($name, $value = null, $options = []) { return static::input('password', $name, $value, $options); } /** * Generates a file input field. * To use a file input field, you should set the enclosing form's "enctype" attribute to * be "multipart/form-data". After the form is submitted, the uploaded file information * can be obtained via $_FILES[$name] (see PHP documentation). * @param string $name the name attribute. * @param string $value the value attribute. If it is null, the value attribute will not be generated. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated file input tag */ public static function fileInput($name, $value = null, $options = []) { return static::input('file', $name, $value, $options); } /** * Generates a text area input. * @param string $name the input name * @param string $value the input value. Note that it will be encoded using [[encode()]]. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated text area tag */ public static function textarea($name, $value = '', $options = []) { $options['name'] = $name; return static::tag('textarea', static::encode($value), $options); } /** * Generates a radio button input. * @param string $name the name attribute. * @param boolean $checked whether the radio button should be checked. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - uncheck: string, the value associated with the uncheck state of the radio button. When this attribute * is present, a hidden input will be generated so that if the radio button is not checked and is submitted, * the value of this attribute will still be submitted to the server via the hidden input. * - label: string, a label displayed next to the radio button. It will NOT be HTML-encoded. Therefore you can pass * in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks. * When this option is specified, the radio button will be enclosed by a label tag. * - labelOptions: array, the HTML attributes for the label tag. Do not set this option unless you set the "label" option. * * The rest of the options will be rendered as the attributes of the resulting radio button tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated radio button tag */ public static function radio($name, $checked = false, $options = []) { $options['checked'] = (bool) $checked; $value = array_key_exists('value', $options) ? $options['value'] : '1'; if (isset($options['uncheck'])) { // add a hidden field so that if the radio button is not selected, it still submits a value $hidden = static::hiddenInput($name, $options['uncheck']); unset($options['uncheck']); } else { $hidden = ''; } if (isset($options['label'])) { $label = $options['label']; $labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : []; unset($options['label'], $options['labelOptions']); $content = static::label(static::input('radio', $name, $value, $options) . ' ' . $label, null, $labelOptions); return $hidden . $content; } else { return $hidden . static::input('radio', $name, $value, $options); } } /** * Generates a checkbox input. * @param string $name the name attribute. * @param boolean $checked whether the checkbox should be checked. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - uncheck: string, the value associated with the uncheck state of the checkbox. When this attribute * is present, a hidden input will be generated so that if the checkbox is not checked and is submitted, * the value of this attribute will still be submitted to the server via the hidden input. * - label: string, a label displayed next to the checkbox. It will NOT be HTML-encoded. Therefore you can pass * in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks. * When this option is specified, the checkbox will be enclosed by a label tag. * - labelOptions: array, the HTML attributes for the label tag. Do not set this option unless you set the "label" option. * * The rest of the options will be rendered as the attributes of the resulting checkbox tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated checkbox tag */ public static function checkbox($name, $checked = false, $options = []) { $options['checked'] = (bool) $checked; $value = array_key_exists('value', $options) ? $options['value'] : '1'; if (isset($options['uncheck'])) { // add a hidden field so that if the checkbox is not selected, it still submits a value $hidden = static::hiddenInput($name, $options['uncheck']); unset($options['uncheck']); } else { $hidden = ''; } if (isset($options['label'])) { $label = $options['label']; $labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : []; unset($options['label'], $options['labelOptions']); $content = static::label(static::input('checkbox', $name, $value, $options) . ' ' . $label, null, $labelOptions); return $hidden . $content; } else { return $hidden . static::input('checkbox', $name, $value, $options); } } /** * Generates a drop-down list. * @param string $name the input name * @param string $selection the selected value * @param array $items the option data items. The array keys are option values, and the array values * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too). * For each sub-array, an option group will be generated whose label is the key associated with the sub-array. * If you have a list of data models, you may convert them into the format described above using * [[\yii\helpers\ArrayHelper::map()]]. * * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in * the labels will also be HTML-encoded. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - prompt: string, a prompt text to be displayed as the first option; * - options: array, the attributes for the select option tags. The array keys must be valid option values, * and the array values are the extra attributes for the corresponding option tags. For example, * * ~~~ * [ * 'value1' => ['disabled' => true], * 'value2' => ['label' => 'value 2'], * ]; * ~~~ * * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options', * except that the array keys represent the optgroup labels specified in $items. * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character. * Defaults to false. * - encode: bool, whether to encode option prompt and option value characters. * Defaults to `true`. This option is available since 2.0.3. * * The rest of the options will be rendered as the attributes of the resulting tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated drop-down list tag */ public static function dropDownList($name, $selection = null, $items = [], $options = []) { if (!empty($options['multiple'])) { return static::listBox($name, $selection, $items, $options); } $options['name'] = $name; unset($options['unselect']); $selectOptions = static::renderSelectOptions($selection, $items, $options); return static::tag('select', "\n" . $selectOptions . "\n", $options); } /** * Generates a list box. * @param string $name the input name * @param string|array $selection the selected value(s) * @param array $items the option data items. The array keys are option values, and the array values * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too). * For each sub-array, an option group will be generated whose label is the key associated with the sub-array. * If you have a list of data models, you may convert them into the format described above using * [[\yii\helpers\ArrayHelper::map()]]. * * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in * the labels will also be HTML-encoded. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - prompt: string, a prompt text to be displayed as the first option; * - options: array, the attributes for the select option tags. The array keys must be valid option values, * and the array values are the extra attributes for the corresponding option tags. For example, * * ~~~ * [ * 'value1' => ['disabled' => true], * 'value2' => ['label' => 'value 2'], * ]; * ~~~ * * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options', * except that the array keys represent the optgroup labels specified in $items. * - unselect: string, the value that will be submitted when no option is selected. * When this attribute is set, a hidden field will be generated so that if no option is selected in multiple * mode, we can still obtain the posted unselect value. * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character. * Defaults to false. * - encode: bool, whether to encode option prompt and option value characters. * Defaults to `true`. This option is available since 2.0.3. * * The rest of the options will be rendered as the attributes of the resulting tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated list box tag */ public static function listBox($name, $selection = null, $items = [], $options = []) { if (!array_key_exists('size', $options)) { $options['size'] = 4; } if (!empty($options['multiple']) && !empty($name) && substr_compare($name, '[]', -2, 2)) { $name .= '[]'; } $options['name'] = $name; if (isset($options['unselect'])) { // add a hidden field so that if the list box has no option being selected, it still submits a value if (!empty($name) && substr_compare($name, '[]', -2, 2) === 0) { $name = substr($name, 0, -2); } $hidden = static::hiddenInput($name, $options['unselect']); unset($options['unselect']); } else { $hidden = ''; } $selectOptions = static::renderSelectOptions($selection, $items, $options); return $hidden . static::tag('select', "\n" . $selectOptions . "\n", $options); } /** * Generates a list of checkboxes. * A checkbox list allows multiple selection, like [[listBox()]]. * As a result, the corresponding submitted value is an array. * @param string $name the name attribute of each checkbox. * @param string|array $selection the selected value(s). * @param array $items the data item used to generate the checkboxes. * The array keys are the checkbox values, while the array values are the corresponding labels. * @param array $options options (name => config) for the checkbox list container tag. * The following options are specially handled: * * - tag: string, the tag name of the container element. * - unselect: string, the value that should be submitted when none of the checkboxes is selected. * By setting this option, a hidden input will be generated. * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true. * This option is ignored if `item` option is set. * - separator: string, the HTML code that separates items. * - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]]. * - item: callable, a callback that can be used to customize the generation of the HTML code * corresponding to a single item in $items. The signature of this callback must be: * * ~~~ * function ($index, $label, $name, $checked, $value) * ~~~ * * where $index is the zero-based index of the checkbox in the whole list; $label * is the label for the checkbox; and $name, $value and $checked represent the name, * value and the checked status of the checkbox input, respectively. * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated checkbox list */ public static function checkboxList($name, $selection = null, $items = [], $options = []) { if (substr($name, -2) !== '[]') { $name .= '[]'; } $formatter = isset($options['item']) ? $options['item'] : null; $itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : []; $encode = !isset($options['encode']) || $options['encode']; $lines = []; $index = 0; foreach ($items as $value => $label) { $checked = $selection !== null && (!is_array($selection) && !strcmp($value, $selection) || is_array($selection) && in_array($value, $selection)); if ($formatter !== null) { $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value); } else { $lines[] = static::checkbox($name, $checked, array_merge($itemOptions, [ 'value' => $value, 'label' => $encode ? static::encode($label) : $label, ])); } $index++; } if (isset($options['unselect'])) { // add a hidden field so that if the list box has no option being selected, it still submits a value $name2 = substr($name, -2) === '[]' ? substr($name, 0, -2) : $name; $hidden = static::hiddenInput($name2, $options['unselect']); } else { $hidden = ''; } $separator = isset($options['separator']) ? $options['separator'] : "\n"; $tag = isset($options['tag']) ? $options['tag'] : 'div'; unset($options['tag'], $options['unselect'], $options['encode'], $options['separator'], $options['item'], $options['itemOptions']); return $hidden . static::tag($tag, implode($separator, $lines), $options); } /** * Generates a list of radio buttons. * A radio button list is like a checkbox list, except that it only allows single selection. * @param string $name the name attribute of each radio button. * @param string|array $selection the selected value(s). * @param array $items the data item used to generate the radio buttons. * The array keys are the radio button values, while the array values are the corresponding labels. * @param array $options options (name => config) for the radio button list container tag. * The following options are specially handled: * * - tag: string, the tag name of the container element. * - unselect: string, the value that should be submitted when none of the radio buttons is selected. * By setting this option, a hidden input will be generated. * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true. * This option is ignored if `item` option is set. * - separator: string, the HTML code that separates items. * - itemOptions: array, the options for generating the radio button tag using [[radio()]]. * - item: callable, a callback that can be used to customize the generation of the HTML code * corresponding to a single item in $items. The signature of this callback must be: * * ~~~ * function ($index, $label, $name, $checked, $value) * ~~~ * * where $index is the zero-based index of the radio button in the whole list; $label * is the label for the radio button; and $name, $value and $checked represent the name, * value and the checked status of the radio button input, respectively. * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated radio button list */ public static function radioList($name, $selection = null, $items = [], $options = []) { $encode = !isset($options['encode']) || $options['encode']; $formatter = isset($options['item']) ? $options['item'] : null; $itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : []; $lines = []; $index = 0; foreach ($items as $value => $label) { $checked = $selection !== null && (!is_array($selection) && !strcmp($value, $selection) || is_array($selection) && in_array($value, $selection)); if ($formatter !== null) { $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value); } else { $lines[] = static::radio($name, $checked, array_merge($itemOptions, [ 'value' => $value, 'label' => $encode ? static::encode($label) : $label, ])); } $index++; } $separator = isset($options['separator']) ? $options['separator'] : "\n"; if (isset($options['unselect'])) { // add a hidden field so that if the list box has no option being selected, it still submits a value $hidden = static::hiddenInput($name, $options['unselect']); } else { $hidden = ''; } $tag = isset($options['tag']) ? $options['tag'] : 'div'; unset($options['tag'], $options['unselect'], $options['encode'], $options['separator'], $options['item'], $options['itemOptions']); return $hidden . static::tag($tag, implode($separator, $lines), $options); } /** * Generates an unordered list. * @param array|\Traversable $items the items for generating the list. Each item generates a single list item. * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true. * @param array $options options (name => config) for the radio button list. The following options are supported: * * - encode: boolean, whether to HTML-encode the items. Defaults to true. * This option is ignored if the `item` option is specified. * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified. * - item: callable, a callback that is used to generate each individual list item. * The signature of this callback must be: * * ~~~ * function ($item, $index) * ~~~ * * where $index is the array key corresponding to `$item` in `$items`. The callback should return * the whole list item tag. * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated unordered list. An empty list tag will be returned if `$items` is empty. */ public static function ul($items, $options = []) { $tag = isset($options['tag']) ? $options['tag'] : 'ul'; $encode = !isset($options['encode']) || $options['encode']; $formatter = isset($options['item']) ? $options['item'] : null; $itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : []; unset($options['tag'], $options['encode'], $options['item'], $options['itemOptions']); if (empty($items)) { return static::tag($tag, '', $options); } $results = []; foreach ($items as $index => $item) { if ($formatter !== null) { $results[] = call_user_func($formatter, $item, $index); } else { $results[] = static::tag('li', $encode ? static::encode($item) : $item, $itemOptions); } } return static::tag($tag, "\n" . implode("\n", $results) . "\n", $options); } /** * Generates an ordered list. * @param array|\Traversable $items the items for generating the list. Each item generates a single list item. * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true. * @param array $options options (name => config) for the radio button list. The following options are supported: * * - encode: boolean, whether to HTML-encode the items. Defaults to true. * This option is ignored if the `item` option is specified. * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified. * - item: callable, a callback that is used to generate each individual list item. * The signature of this callback must be: * * ~~~ * function ($item, $index) * ~~~ * * where $index is the array key corresponding to `$item` in `$items`. The callback should return * the whole list item tag. * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated ordered list. An empty string is returned if `$items` is empty. */ public static function ol($items, $options = []) { $options['tag'] = 'ol'; return static::ul($items, $options); } /** * Generates a label tag for the given model attribute. * The label text is the label associated with the attribute, obtained via [[Model::getAttributeLabel()]]. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * The following options are specially handled: * * - label: this specifies the label to be displayed. Note that this will NOT be [[encode()|encoded]]. * If this is not set, [[Model::getAttributeLabel()]] will be called to get the label for display * (after encoding). * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated label tag */ public static function activeLabel($model, $attribute, $options = []) { $for = array_key_exists('for', $options) ? $options['for'] : static::getInputId($model, $attribute); $attribute = static::getAttributeName($attribute); $label = isset($options['label']) ? $options['label'] : static::encode($model->getAttributeLabel($attribute)); unset($options['label'], $options['for']); return static::label($label, $for, $options); } /** * Generates a hint tag for the given model attribute. * The hint text is the hint associated with the attribute, obtained via [[Model::getAttributeHint()]]. * If no hint content can be obtained, method will return an empty string. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * The following options are specially handled: * * - hint: this specifies the hint to be displayed. Note that this will NOT be [[encode()|encoded]]. * If this is not set, [[Model::getAttributeHint()]] will be called to get the hint for display * (without encoding). * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated hint tag * @since 2.0.4 */ public static function activeHint($model, $attribute, $options = []) { $attribute = static::getAttributeName($attribute); $hint = isset($options['hint']) ? $options['hint'] : $model->getAttributeHint($attribute); if (empty($hint)) { return ''; } $tag = ArrayHelper::remove($options, 'tag', 'div'); unset($options['hint']); return static::tag($tag, $hint, $options); } /** * Generates a summary of the validation errors. * If there is no validation error, an empty error summary markup will still be generated, but it will be hidden. * @param Model|Model[] $models the model(s) whose validation errors are to be displayed * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - header: string, the header HTML for the error summary. If not set, a default prompt string will be used. * - footer: string, the footer HTML for the error summary. * - encode: boolean, if set to false then the error messages won't be encoded. * * The rest of the options will be rendered as the attributes of the container tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * @return string the generated error summary */ public static function errorSummary($models, $options = []) { $header = isset($options['header']) ? $options['header'] : '<p>' . Yii::t('yii', 'Please fix the following errors:') . '</p>'; $footer = isset($options['footer']) ? $options['footer'] : ''; $encode = !isset($options['encode']) || $options['encode'] !== false; unset($options['header'], $options['footer'], $options['encode']); $lines = []; if (!is_array($models)) { $models = [$models]; } foreach ($models as $model) { /* @var $model Model */ foreach ($model->getFirstErrors() as $error) { $lines[] = $encode ? Html::encode($error) : $error; } } if (empty($lines)) { // still render the placeholder for client-side validation use $content = "<ul></ul>"; $options['style'] = isset($options['style']) ? rtrim($options['style'], ';') . '; display:none' : 'display:none'; } else { $content = "<ul><li>" . implode("</li>\n<li>", $lines) . "</li></ul>"; } return Html::tag('div', $header . $content . $footer, $options); } /** * Generates a tag that contains the first validation error of the specified model attribute. * Note that even if there is no validation error, this method will still return an empty error tag. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. The values will be HTML-encoded * using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * * The following options are specially handled: * * - tag: this specifies the tag name. If not set, "div" will be used. * - encode: boolean, if set to false then the error message won't be encoded. * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated label tag */ public static function error($model, $attribute, $options = []) { $attribute = static::getAttributeName($attribute); $error = $model->getFirstError($attribute); $tag = isset($options['tag']) ? $options['tag'] : 'div'; $encode = !isset($options['encode']) || $options['encode'] !== false; unset($options['tag'], $options['encode']); return Html::tag($tag, $encode ? Html::encode($error) : $error, $options); } /** * Generates an input tag for the given model attribute. * This method will generate the "name" and "value" tag attributes automatically for the model attribute * unless they are explicitly specified in `$options`. * @param string $type the input type (e.g. 'text', 'password') * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated input tag */ public static function activeInput($type, $model, $attribute, $options = []) { $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute); $value = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute); if (!array_key_exists('id', $options)) { $options['id'] = static::getInputId($model, $attribute); } return static::input($type, $name, $value, $options); } /** * If `maxlength` option is set true and the model attribute is validated by a string validator, * the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]]. * @param Model $model the model object * @param string $attribute the attribute name or expression. * @param array $options the tag options in terms of name-value pairs. */ private static function normalizeMaxLength($model, $attribute, &$options) { if (isset($options['maxlength']) && $options['maxlength'] === true) { unset($options['maxlength']); $attrName = static::getAttributeName($attribute); foreach ($model->getActiveValidators($attrName) as $validator) { if ($validator instanceof StringValidator && $validator->max !== null) { $options['maxlength'] = $validator->max; break; } } } } /** * Generates a text input tag for the given model attribute. * This method will generate the "name" and "value" tag attributes automatically for the model attribute * unless they are explicitly specified in `$options`. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * The following special options are recognized: * * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated * by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]]. * This is available since version 2.0.3. * * @return string the generated input tag */ public static function activeTextInput($model, $attribute, $options = []) { self::normalizeMaxLength($model, $attribute, $options); return static::activeInput('text', $model, $attribute, $options); } /** * Generates a hidden input tag for the given model attribute. * This method will generate the "name" and "value" tag attributes automatically for the model attribute * unless they are explicitly specified in `$options`. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated input tag */ public static function activeHiddenInput($model, $attribute, $options = []) { return static::activeInput('hidden', $model, $attribute, $options); } /** * Generates a password input tag for the given model attribute. * This method will generate the "name" and "value" tag attributes automatically for the model attribute * unless they are explicitly specified in `$options`. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * The following special options are recognized: * * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated * by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]]. * This option is available since version 2.0.6. * * @return string the generated input tag */ public static function activePasswordInput($model, $attribute, $options = []) { self::normalizeMaxLength($model, $attribute, $options); return static::activeInput('password', $model, $attribute, $options); } /** * Generates a file input tag for the given model attribute. * This method will generate the "name" and "value" tag attributes automatically for the model attribute * unless they are explicitly specified in `$options`. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * @return string the generated input tag */ public static function activeFileInput($model, $attribute, $options = []) { // add a hidden field so that if a model only has a file field, we can // still use isset($_POST[$modelClass]) to detect if the input is submitted return static::activeHiddenInput($model, $attribute, ['id' => null, 'value' => '']) . static::activeInput('file', $model, $attribute, $options); } /** * Generates a textarea tag for the given model attribute. * The model attribute value will be used as the content in the textarea. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * The following special options are recognized: * * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated * by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]]. * This option is available since version 2.0.6. * * @return string the generated textarea tag */ public static function activeTextarea($model, $attribute, $options = []) { $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute); if (isset($options['value'])) { $value = $options['value']; unset($options['value']); } else { $value = static::getAttributeValue($model, $attribute); } if (!array_key_exists('id', $options)) { $options['id'] = static::getInputId($model, $attribute); } self::normalizeMaxLength($model, $attribute, $options); return static::textarea($name, $value, $options); } /** * Generates a radio button tag together with a label for the given model attribute. * This method will generate the "checked" tag attribute according to the model attribute value. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - uncheck: string, the value associated with the uncheck state of the radio button. If not set, * it will take the default value '0'. This method will render a hidden input so that if the radio button * is not checked and is submitted, the value of this attribute will still be submitted to the server * via the hidden input. If you do not want any hidden input, you should explicitly set this option as null. * - label: string, a label displayed next to the radio button. It will NOT be HTML-encoded. Therefore you can pass * in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks. * The radio button will be enclosed by the label tag. Note that if you do not specify this option, a default label * will be used based on the attribute label declaration in the model. If you do not want any label, you should * explicitly set this option as null. * - labelOptions: array, the HTML attributes for the label tag. This is only used when the "label" option is specified. * * The rest of the options will be rendered as the attributes of the resulting tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated radio button tag */ public static function activeRadio($model, $attribute, $options = []) { $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute); $value = static::getAttributeValue($model, $attribute); if (!array_key_exists('value', $options)) { $options['value'] = '1'; } if (!array_key_exists('uncheck', $options)) { $options['uncheck'] = '0'; } if (!array_key_exists('label', $options)) { $options['label'] = static::encode($model->getAttributeLabel(static::getAttributeName($attribute))); } $checked = "$value" === "{$options['value']}"; if (!array_key_exists('id', $options)) { $options['id'] = static::getInputId($model, $attribute); } return static::radio($name, $checked, $options); } /** * Generates a checkbox tag together with a label for the given model attribute. * This method will generate the "checked" tag attribute according to the model attribute value. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - uncheck: string, the value associated with the uncheck state of the radio button. If not set, * it will take the default value '0'. This method will render a hidden input so that if the radio button * is not checked and is submitted, the value of this attribute will still be submitted to the server * via the hidden input. If you do not want any hidden input, you should explicitly set this option as null. * - label: string, a label displayed next to the checkbox. It will NOT be HTML-encoded. Therefore you can pass * in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks. * The checkbox will be enclosed by the label tag. Note that if you do not specify this option, a default label * will be used based on the attribute label declaration in the model. If you do not want any label, you should * explicitly set this option as null. * - labelOptions: array, the HTML attributes for the label tag. This is only used when the "label" option is specified. * * The rest of the options will be rendered as the attributes of the resulting tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated checkbox tag */ public static function activeCheckbox($model, $attribute, $options = []) { $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute); $value = static::getAttributeValue($model, $attribute); if (!array_key_exists('value', $options)) { $options['value'] = '1'; } if (!array_key_exists('uncheck', $options)) { $options['uncheck'] = '0'; } if (!array_key_exists('label', $options)) { $options['label'] = static::encode($model->getAttributeLabel(static::getAttributeName($attribute))); } $checked = "$value" === "{$options['value']}"; if (!array_key_exists('id', $options)) { $options['id'] = static::getInputId($model, $attribute); } return static::checkbox($name, $checked, $options); } /** * Generates a drop-down list for the given model attribute. * The selection of the drop-down list is taken from the value of the model attribute. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $items the option data items. The array keys are option values, and the array values * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too). * For each sub-array, an option group will be generated whose label is the key associated with the sub-array. * If you have a list of data models, you may convert them into the format described above using * [[\yii\helpers\ArrayHelper::map()]]. * * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in * the labels will also be HTML-encoded. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - prompt: string, a prompt text to be displayed as the first option; * - options: array, the attributes for the select option tags. The array keys must be valid option values, * and the array values are the extra attributes for the corresponding option tags. For example, * * ~~~ * [ * 'value1' => ['disabled' => true], * 'value2' => ['label' => 'value 2'], * ]; * ~~~ * * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options', * except that the array keys represent the optgroup labels specified in $items. * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character. * Defaults to false. * - encode: bool, whether to encode option prompt and option value characters. * Defaults to `true`. This option is available since 2.0.3. * * The rest of the options will be rendered as the attributes of the resulting tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated drop-down list tag */ public static function activeDropDownList($model, $attribute, $items, $options = []) { if (empty($options['multiple'])) { return static::activeListInput('dropDownList', $model, $attribute, $items, $options); } else { return static::activeListBox($model, $attribute, $items, $options); } } /** * Generates a list box. * The selection of the list box is taken from the value of the model attribute. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $items the option data items. The array keys are option values, and the array values * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too). * For each sub-array, an option group will be generated whose label is the key associated with the sub-array. * If you have a list of data models, you may convert them into the format described above using * [[\yii\helpers\ArrayHelper::map()]]. * * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in * the labels will also be HTML-encoded. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - prompt: string, a prompt text to be displayed as the first option; * - options: array, the attributes for the select option tags. The array keys must be valid option values, * and the array values are the extra attributes for the corresponding option tags. For example, * * ~~~ * [ * 'value1' => ['disabled' => true], * 'value2' => ['label' => 'value 2'], * ]; * ~~~ * * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options', * except that the array keys represent the optgroup labels specified in $items. * - unselect: string, the value that will be submitted when no option is selected. * When this attribute is set, a hidden field will be generated so that if no option is selected in multiple * mode, we can still obtain the posted unselect value. * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character. * Defaults to false. * - encode: bool, whether to encode option prompt and option value characters. * Defaults to `true`. This option is available since 2.0.3. * * The rest of the options will be rendered as the attributes of the resulting tag. The values will * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated list box tag */ public static function activeListBox($model, $attribute, $items, $options = []) { return static::activeListInput('listBox', $model, $attribute, $items, $options); } /** * Generates a list of checkboxes. * A checkbox list allows multiple selection, like [[listBox()]]. * As a result, the corresponding submitted value is an array. * The selection of the checkbox list is taken from the value of the model attribute. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $items the data item used to generate the checkboxes. * The array keys are the checkbox values, and the array values are the corresponding labels. * Note that the labels will NOT be HTML-encoded, while the values will. * @param array $options options (name => config) for the checkbox list container tag. * The following options are specially handled: * * - tag: string, the tag name of the container element. * - unselect: string, the value that should be submitted when none of the checkboxes is selected. * You may set this option to be null to prevent default value submission. * If this option is not set, an empty string will be submitted. * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true. * This option is ignored if `item` option is set. * - separator: string, the HTML code that separates items. * - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]]. * - item: callable, a callback that can be used to customize the generation of the HTML code * corresponding to a single item in $items. The signature of this callback must be: * * ~~~ * function ($index, $label, $name, $checked, $value) * ~~~ * * where $index is the zero-based index of the checkbox in the whole list; $label * is the label for the checkbox; and $name, $value and $checked represent the name, * value and the checked status of the checkbox input. * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated checkbox list */ public static function activeCheckboxList($model, $attribute, $items, $options = []) { return static::activeListInput('checkboxList', $model, $attribute, $items, $options); } /** * Generates a list of radio buttons. * A radio button list is like a checkbox list, except that it only allows single selection. * The selection of the radio buttons is taken from the value of the model attribute. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $items the data item used to generate the radio buttons. * The array keys are the radio values, and the array values are the corresponding labels. * Note that the labels will NOT be HTML-encoded, while the values will. * @param array $options options (name => config) for the radio button list container tag. * The following options are specially handled: * * - tag: string, the tag name of the container element. * - unselect: string, the value that should be submitted when none of the radio buttons is selected. * You may set this option to be null to prevent default value submission. * If this option is not set, an empty string will be submitted. * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true. * This option is ignored if `item` option is set. * - separator: string, the HTML code that separates items. * - itemOptions: array, the options for generating the radio button tag using [[radio()]]. * - item: callable, a callback that can be used to customize the generation of the HTML code * corresponding to a single item in $items. The signature of this callback must be: * * ~~~ * function ($index, $label, $name, $checked, $value) * ~~~ * * where $index is the zero-based index of the radio button in the whole list; $label * is the label for the radio button; and $name, $value and $checked represent the name, * value and the checked status of the radio button input. * * See [[renderTagAttributes()]] for details on how attributes are being rendered. * * @return string the generated radio button list */ public static function activeRadioList($model, $attribute, $items, $options = []) { return static::activeListInput('radioList', $model, $attribute, $items, $options); } /** * Generates a list of input fields. * This method is mainly called by [[activeListBox()]], [[activeRadioList()]] and [[activeCheckBoxList()]]. * @param string $type the input type. This can be 'listBox', 'radioList', or 'checkBoxList'. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format * about attribute expression. * @param array $items the data item used to generate the input fields. * The array keys are the input values, and the array values are the corresponding labels. * Note that the labels will NOT be HTML-encoded, while the values will. * @param array $options options (name => config) for the input list. The supported special options * depend on the input type specified by `$type`. * @return string the generated input list */ protected static function activeListInput($type, $model, $attribute, $items, $options = []) { $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute); $selection = static::getAttributeValue($model, $attribute); if (!array_key_exists('unselect', $options)) { $options['unselect'] = ''; } if (!array_key_exists('id', $options)) { $options['id'] = static::getInputId($model, $attribute); } return static::$type($name, $selection, $items, $options); } /** * Renders the option tags that can be used by [[dropDownList()]] and [[listBox()]]. * @param string|array $selection the selected value(s). This can be either a string for single selection * or an array for multiple selections. * @param array $items the option data items. The array keys are option values, and the array values * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too). * For each sub-array, an option group will be generated whose label is the key associated with the sub-array. * If you have a list of data models, you may convert them into the format described above using * [[\yii\helpers\ArrayHelper::map()]]. * * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in * the labels will also be HTML-encoded. * @param array $tagOptions the $options parameter that is passed to the [[dropDownList()]] or [[listBox()]] call. * This method will take out these elements, if any: "prompt", "options" and "groups". See more details * in [[dropDownList()]] for the explanation of these elements. * * @return string the generated list options */ public static function renderSelectOptions($selection, $items, &$tagOptions = []) { $lines = []; $encodeSpaces = ArrayHelper::remove($tagOptions, 'encodeSpaces', false); $encode = ArrayHelper::remove($tagOptions, 'encode', true); if (isset($tagOptions['prompt'])) { $prompt = $encode ? static::encode($tagOptions['prompt']) : $tagOptions['prompt']; if ($encodeSpaces) { $prompt = str_replace(' ', '&nbsp;', $prompt); } $lines[] = static::tag('option', $prompt, ['value' => '']); } $options = isset($tagOptions['options']) ? $tagOptions['options'] : []; $groups = isset($tagOptions['groups']) ? $tagOptions['groups'] : []; unset($tagOptions['prompt'], $tagOptions['options'], $tagOptions['groups']); $options['encodeSpaces'] = ArrayHelper::getValue($options, 'encodeSpaces', $encodeSpaces); $options['encode'] = ArrayHelper::getValue($options, 'encode', $encode); foreach ($items as $key => $value) { if (is_array($value)) { $groupAttrs = isset($groups[$key]) ? $groups[$key] : []; if (!isset($groupAttrs['label'])) { $groupAttrs['label'] = $key; } $attrs = ['options' => $options, 'groups' => $groups, 'encodeSpaces' => $encodeSpaces, 'encode' => $encode]; $content = static::renderSelectOptions($selection, $value, $attrs); $lines[] = static::tag('optgroup', "\n" . $content . "\n", $groupAttrs); } else { $attrs = isset($options[$key]) ? $options[$key] : []; $attrs['value'] = (string) $key; $attrs['selected'] = $selection !== null && (!is_array($selection) && !strcmp($key, $selection) || is_array($selection) && in_array($key, $selection)); $text = $encode ? static::encode($value) : $value; if ($encodeSpaces) { $text = str_replace(' ', '&nbsp;', $text); } $lines[] = static::tag('option', $text, $attrs); } } return implode("\n", $lines); } /** * Renders the HTML tag attributes. * * Attributes whose values are of boolean type will be treated as * [boolean attributes](http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes). * * Attributes whose values are null will not be rendered. * * The values of attributes will be HTML-encoded using [[encode()]]. * * The "data" attribute is specially handled when it is receiving an array value. In this case, * the array will be "expanded" and a list data attributes will be rendered. For example, * if `'data' => ['id' => 1, 'name' => 'yii']`, then this will be rendered: * `data-id="1" data-name="yii"`. * Additionally `'data' => ['params' => ['id' => 1, 'name' => 'yii'], 'status' => 'ok']` will be rendered as: * `data-params='{"id":1,"name":"yii"}' data-status="ok"`. * * @param array $attributes attributes to be rendered. The attribute values will be HTML-encoded using [[encode()]]. * @return string the rendering result. If the attributes are not empty, they will be rendered * into a string with a leading white space (so that it can be directly appended to the tag name * in a tag. If there is no attribute, an empty string will be returned. */ public static function renderTagAttributes($attributes) { if (count($attributes) > 1) { $sorted = []; foreach (static::$attributeOrder as $name) { if (isset($attributes[$name])) { $sorted[$name] = $attributes[$name]; } } $attributes = array_merge($sorted, $attributes); } $html = ''; foreach ($attributes as $name => $value) { if (is_bool($value)) { if ($value) { $html .= " $name"; } } elseif (is_array($value)) { if (in_array($name, static::$dataAttributes)) { foreach ($value as $n => $v) { if (is_array($v)) { $html .= " $name-$n='" . Json::htmlEncode($v) . "'"; } else { $html .= " $name-$n=\"" . static::encode($v) . '"'; } } } elseif ($name === 'class') { if (empty($value)) { continue; } $html .= " $name=\"" . static::encode(implode(' ', $value)) . '"'; } elseif ($name === 'style') { if (empty($value)) { continue; } $html .= " $name=\"" . static::encode(static::cssStyleFromArray($value)) . '"'; } else { $html .= " $name='" . Json::htmlEncode($value) . "'"; } } elseif ($value !== null) { $html .= " $name=\"" . static::encode($value) . '"'; } } return $html; } /** * Adds a CSS class (or several classes) to the specified options. * If the CSS class is already in the options, it will not be added again. * If class specification at given options is an array, and some class placed there with the named (string) key, * overriding of such key will have no effect. For example: * * ~~~php * $options = ['class' => ['persistent' => 'initial']]; * Html::addCssClass($options, ['persistent' => 'override']); * var_dump($options['class']); // outputs: array('persistent' => 'initial'); * ~~~ * * @param array $options the options to be modified. * @param string|array $class the CSS class(es) to be added */ public static function addCssClass(&$options, $class) { if (isset($options['class'])) { if (is_array($options['class'])) { $options['class'] = self::mergeCssClasses($options['class'], (array) $class); } else { $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY); $options['class'] = implode(' ', self::mergeCssClasses($classes, (array) $class)); } } else { $options['class'] = $class; } } /** * Merges already existing CSS classes with new one. * This method provides the priority for named existing classes over additional. * @param array $existingClasses already existing CSS classes. * @param array $additionalClasses CSS classes to be added. * @return array merge result. */ private static function mergeCssClasses(array $existingClasses, array $additionalClasses) { foreach ($additionalClasses as $key => $class) { if (is_int($key) && !in_array($class, $existingClasses)) { $existingClasses[] = $class; } elseif (!isset($existingClasses[$key])) { $existingClasses[$key] = $class; } } return array_unique($existingClasses); } /** * Removes a CSS class from the specified options. * @param array $options the options to be modified. * @param string|array $class the CSS class(es) to be removed */ public static function removeCssClass(&$options, $class) { if (isset($options['class'])) { if (is_array($options['class'])) { $classes = array_diff($options['class'], (array) $class); if (empty($classes)) { unset($options['class']); } else { $options['class'] = $classes; } } else { $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY); $classes = array_diff($classes, (array) $class); if (empty($classes)) { unset($options['class']); } else { $options['class'] = implode(' ', $classes); } } } } /** * Adds the specified CSS style to the HTML options. * * If the options already contain a `style` element, the new style will be merged * with the existing one. If a CSS property exists in both the new and the old styles, * the old one may be overwritten if `$overwrite` is true. * * For example, * * ```php * Html::addCssStyle($options, 'width: 100px; height: 200px'); * ``` * * @param array $options the HTML options to be modified. * @param string|array $style the new style string (e.g. `'width: 100px; height: 200px'`) or * array (e.g. `['width' => '100px', 'height' => '200px']`). * @param boolean $overwrite whether to overwrite existing CSS properties if the new style * contain them too. * @see removeCssStyle() * @see cssStyleFromArray() * @see cssStyleToArray() */ public static function addCssStyle(&$options, $style, $overwrite = true) { if (!empty($options['style'])) { $oldStyle = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']); $newStyle = is_array($style) ? $style : static::cssStyleToArray($style); if (!$overwrite) { foreach ($newStyle as $property => $value) { if (isset($oldStyle[$property])) { unset($newStyle[$property]); } } } $style = array_merge($oldStyle, $newStyle); } $options['style'] = is_array($style) ? static::cssStyleFromArray($style) : $style; } /** * Removes the specified CSS style from the HTML options. * * For example, * * ```php * Html::removeCssStyle($options, ['width', 'height']); * ``` * * @param array $options the HTML options to be modified. * @param string|array $properties the CSS properties to be removed. You may use a string * if you are removing a single property. * @see addCssStyle() */ public static function removeCssStyle(&$options, $properties) { if (!empty($options['style'])) { $style = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']); foreach ((array) $properties as $property) { unset($style[$property]); } $options['style'] = static::cssStyleFromArray($style); } } /** * Converts a CSS style array into a string representation. * * For example, * * ```php * print_r(Html::cssStyleFromArray(['width' => '100px', 'height' => '200px'])); * // will display: 'width: 100px; height: 200px;' * ``` * * @param array $style the CSS style array. The array keys are the CSS property names, * and the array values are the corresponding CSS property values. * @return string the CSS style string. If the CSS style is empty, a null will be returned. */ public static function cssStyleFromArray(array $style) { $result = ''; foreach ($style as $name => $value) { $result .= "$name: $value; "; } // return null if empty to avoid rendering the "style" attribute return $result === '' ? null : rtrim($result); } /** * Converts a CSS style string into an array representation. * * The array keys are the CSS property names, and the array values * are the corresponding CSS property values. * * For example, * * ```php * print_r(Html::cssStyleToArray('width: 100px; height: 200px;')); * // will display: ['width' => '100px', 'height' => '200px'] * ``` * * @param string $style the CSS style string * @return array the array representation of the CSS style */ public static function cssStyleToArray($style) { $result = []; foreach (explode(';', $style) as $property) { $property = explode(':', $property); if (count($property) > 1) { $result[trim($property[0])] = trim($property[1]); } } return $result; } /** * Returns the real attribute name from the given attribute expression. * * An attribute expression is an attribute name prefixed and/or suffixed with array indexes. * It is mainly used in tabular data input and/or input of array type. Below are some examples: * * - `[0]content` is used in tabular data input to represent the "content" attribute * for the first model in tabular input; * - `dates[0]` represents the first array element of the "dates" attribute; * - `[0]dates[0]` represents the first array element of the "dates" attribute * for the first model in tabular input. * * If `$attribute` has neither prefix nor suffix, it will be returned back without change. * @param string $attribute the attribute name or expression * @return string the attribute name without prefix and suffix. * @throws InvalidParamException if the attribute name contains non-word characters. */ public static function getAttributeName($attribute) { if (preg_match('/(^|.*\])([\w\.]+)(\[.*|$)/', $attribute, $matches)) { return $matches[2]; } else { throw new InvalidParamException('Attribute name must contain word characters only.'); } } /** * Returns the value of the specified attribute name or expression. * * For an attribute expression like `[0]dates[0]`, this method will return the value of `$model->dates[0]`. * See [[getAttributeName()]] for more details about attribute expression. * * If an attribute value is an instance of [[ActiveRecordInterface]] or an array of such instances, * the primary value(s) of the AR instance(s) will be returned instead. * * @param Model $model the model object * @param string $attribute the attribute name or expression * @return string|array the corresponding attribute value * @throws InvalidParamException if the attribute name contains non-word characters. */ public static function getAttributeValue($model, $attribute) { if (!preg_match('/(^|.*\])([\w\.]+)(\[.*|$)/', $attribute, $matches)) { throw new InvalidParamException('Attribute name must contain word characters only.'); } $attribute = $matches[2]; $value = $model->$attribute; if ($matches[3] !== '') { foreach (explode('][', trim($matches[3], '[]')) as $id) { if ((is_array($value) || $value instanceof \ArrayAccess) && isset($value[$id])) { $value = $value[$id]; } else { return null; } } } // https://github.com/yiisoft/yii2/issues/1457 if (is_array($value)) { foreach ($value as $i => $v) { if ($v instanceof ActiveRecordInterface) { $v = $v->getPrimaryKey(false); $value[$i] = is_array($v) ? json_encode($v) : $v; } } } elseif ($value instanceof ActiveRecordInterface) { $value = $value->getPrimaryKey(false); return is_array($value) ? json_encode($value) : $value; } return $value; } /** * Generates an appropriate input name for the specified attribute name or expression. * * This method generates a name that can be used as the input name to collect user input * for the specified attribute. The name is generated according to the [[Model::formName|form name]] * of the model and the given attribute name. For example, if the form name of the `Post` model * is `Post`, then the input name generated for the `content` attribute would be `Post[content]`. * * See [[getAttributeName()]] for explanation of attribute expression. * * @param Model $model the model object * @param string $attribute the attribute name or expression * @return string the generated input name * @throws InvalidParamException if the attribute name contains non-word characters. */ public static function getInputName($model, $attribute) { $formName = $model->formName(); if (!preg_match('/(^|.*\])([\w\.]+)(\[.*|$)/', $attribute, $matches)) { throw new InvalidParamException('Attribute name must contain word characters only.'); } $prefix = $matches[1]; $attribute = $matches[2]; $suffix = $matches[3]; if ($formName === '' && $prefix === '') { return $attribute . $suffix; } elseif ($formName !== '') { return $formName . $prefix . "[$attribute]" . $suffix; } else { throw new InvalidParamException(get_class($model) . '::formName() cannot be empty for tabular inputs.'); } } /** * Generates an appropriate input ID for the specified attribute name or expression. * * This method converts the result [[getInputName()]] into a valid input ID. * For example, if [[getInputName()]] returns `Post[content]`, this method will return `post-content`. * @param Model $model the model object * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for explanation of attribute expression. * @return string the generated input ID * @throws InvalidParamException if the attribute name contains non-word characters. */ public static function getInputId($model, $attribute) { $name = strtolower(static::getInputName($model, $attribute)); return str_replace(['[]', '][', '[', ']', ' ', '.'], ['', '-', '-', '', '-', '-'], $name); } /** * Escapes regular expression to use in JavaScript * @param string $regexp the regular expression to be escaped. * @return string the escaped result. * @since 2.0.6 */ public static function escapeJsRegularExpression($regexp) { $pattern = preg_replace('/\\\\x\{?([0-9a-fA-F]+)\}?/', '\u$1', $regexp); $deliminator = substr($pattern, 0, 1); $pos = strrpos($pattern, $deliminator, 1); $flag = substr($pattern, $pos + 1); if ($deliminator !== '/') { $pattern = '/' . str_replace('/', '\\/', substr($pattern, 1, $pos - 1)) . '/'; } else { $pattern = substr($pattern, 0, $pos + 1); } if (!empty($flag)) { $pattern .= preg_replace('/[^igm]/', '', $flag); } return $pattern; } }
mcgrogan91/yii2
framework/helpers/BaseHtml.php
PHP
bsd-3-clause
103,758
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>statsmodels.base.model.GenericLikelihoodModelResults.remove_data &#8212; statsmodels v0.10.0 documentation</title> <link rel="stylesheet" href="../../_static/nature.css" type="text/css" /> <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../../_static/graphviz.css" /> <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script> <script type="text/javascript" src="../../_static/jquery.js"></script> <script type="text/javascript" src="../../_static/underscore.js"></script> <script type="text/javascript" src="../../_static/doctools.js"></script> <script type="text/javascript" src="../../_static/language_data.js"></script> <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="shortcut icon" href="../../_static/statsmodels_hybi_favico.ico"/> <link rel="author" title="About these documents" href="../../about.html" /> <link rel="index" title="Index" href="../../genindex.html" /> <link rel="search" title="Search" href="../../search.html" /> <link rel="next" title="statsmodels.base.model.GenericLikelihoodModelResults.save" href="statsmodels.base.model.GenericLikelihoodModelResults.save.html" /> <link rel="prev" title="statsmodels.base.model.GenericLikelihoodModelResults.pvalues" href="statsmodels.base.model.GenericLikelihoodModelResults.pvalues.html" /> <link rel="stylesheet" href="../../_static/examples.css" type="text/css" /> <link rel="stylesheet" href="../../_static/facebox.css" type="text/css" /> <script type="text/javascript" src="../../_static/scripts.js"> </script> <script type="text/javascript" src="../../_static/facebox.js"> </script> <script type="text/javascript"> $.facebox.settings.closeImage = "../../_static/closelabel.png" $.facebox.settings.loadingImage = "../../_static/loading.gif" </script> <script> $(document).ready(function() { $.getJSON("../../../versions.json", function(versions) { var dropdown = document.createElement("div"); dropdown.className = "dropdown"; var button = document.createElement("button"); button.className = "dropbtn"; button.innerHTML = "Other Versions"; var content = document.createElement("div"); content.className = "dropdown-content"; dropdown.appendChild(button); dropdown.appendChild(content); $(".header").prepend(dropdown); for (var i = 0; i < versions.length; i++) { if (versions[i].substring(0, 1) == "v") { versions[i] = [versions[i], versions[i].substring(1)]; } else { versions[i] = [versions[i], versions[i]]; }; }; for (var i = 0; i < versions.length; i++) { var a = document.createElement("a"); a.innerHTML = versions[i][1]; a.href = "../../../" + versions[i][0] + "/index.html"; a.title = versions[i][1]; $(".dropdown-content").append(a); }; }); }); </script> </head><body> <div class="headerwrap"> <div class = "header"> <a href = "../../index.html"> <img src="../../_static/statsmodels_hybi_banner.png" alt="Logo" style="padding-left: 15px"/></a> </div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="statsmodels.base.model.GenericLikelihoodModelResults.save.html" title="statsmodels.base.model.GenericLikelihoodModelResults.save" accesskey="N">next</a> |</li> <li class="right" > <a href="statsmodels.base.model.GenericLikelihoodModelResults.pvalues.html" title="statsmodels.base.model.GenericLikelihoodModelResults.pvalues" accesskey="P">previous</a> |</li> <li><a href ="../../install.html">Install</a></li> &nbsp;|&nbsp; <li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> &nbsp;|&nbsp; <li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> &nbsp;|&nbsp; <li><a href="../index.html">Develop</a></li> &nbsp;|&nbsp; <li><a href="../../examples/index.html">Examples</a></li> &nbsp;|&nbsp; <li><a href="../../faq.html">FAQ</a></li> &nbsp;|&nbsp; <li class="nav-item nav-item-1"><a href="../index.html" >Developer Page</a> |</li> <li class="nav-item nav-item-2"><a href="../internal.html" >Internal Classes</a> |</li> <li class="nav-item nav-item-3"><a href="statsmodels.base.model.GenericLikelihoodModelResults.html" accesskey="U">statsmodels.base.model.GenericLikelihoodModelResults</a> |</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="statsmodels-base-model-genericlikelihoodmodelresults-remove-data"> <h1>statsmodels.base.model.GenericLikelihoodModelResults.remove_data<a class="headerlink" href="#statsmodels-base-model-genericlikelihoodmodelresults-remove-data" title="Permalink to this headline">¶</a></h1> <p>method</p> <dl class="method"> <dt id="statsmodels.base.model.GenericLikelihoodModelResults.remove_data"> <code class="sig-prename descclassname">GenericLikelihoodModelResults.</code><code class="sig-name descname">remove_data</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.base.model.GenericLikelihoodModelResults.remove_data" title="Permalink to this definition">¶</a></dt> <dd><p>remove data arrays, all nobs arrays from result and model</p> <p>This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance.</p> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None.</p> </div> <p>Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible.</p> <p>The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove_data.</p> <p>The attributes to remove are named in:</p> <dl class="simple"> <dt>model._data_attr<span class="classifier">arrays attached to both the model instance</span></dt><dd><p>and the results instance with the same attribute name.</p> </dd> <dt>result.data_in_cache<span class="classifier">arrays that may exist as values in</span></dt><dd><p>result._cache (TODO : should privatize name)</p> </dd> <dt>result._data_attr_model<span class="classifier">arrays attached to the model</span></dt><dd><p>instance but not to the results instance</p> </dd> </dl> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="statsmodels.base.model.GenericLikelihoodModelResults.pvalues.html" title="previous chapter">statsmodels.base.model.GenericLikelihoodModelResults.pvalues</a></p> <h4>Next topic</h4> <p class="topless"><a href="statsmodels.base.model.GenericLikelihoodModelResults.save.html" title="next chapter">statsmodels.base.model.GenericLikelihoodModelResults.save</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../../_sources/dev/generated/statsmodels.base.model.GenericLikelihoodModelResults.remove_data.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3 id="searchlabel">Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../../search.html" method="get"> <input type="text" name="q" aria-labelledby="searchlabel" /> <input type="submit" value="Go" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.1.2. </div> </body> </html>
statsmodels/statsmodels.github.io
v0.10.0/dev/generated/statsmodels.base.model.GenericLikelihoodModelResults.remove_data.html
HTML
bsd-3-clause
9,140
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% load staticfiles %} <link rel="stylesheet" href="{% static 'css/foundation.css' %}" /> </head> <body> <div class="row"> <div class="panel"> <h2> You have successfully logged out </h2> <p> You can <a href="/pta/">login</a> again and access the PTA application</p> </div> </div> </body> </html>
cptdanko/ptaApp
pta/templates/pta/logout.html
HTML
bsd-3-clause
420
/* Copyright (C) 2013-2014 by Kristina Simpson <[email protected]> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgement in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include "CanvasOGL.hpp" #include "ShadersOpenGL.hpp" #include "TextureOpenGL.hpp" namespace KRE { namespace { CanvasPtr& get_instance() { static CanvasPtr res = CanvasPtr(new CanvasOGL()); return res; } } CanvasOGL::CanvasOGL() { handleDimensionsChanged(); } CanvasOGL::~CanvasOGL() { } void CanvasOGL::handleDimensionsChanged() { mvp_ = glm::ortho(0.0f, float(width()), float(height()), 0.0f); } void CanvasOGL::blitTexture(const TexturePtr& tex, const rect& src, float rotation, const rect& dst, const Color& color) const { auto texture = std::dynamic_pointer_cast<OpenGLTexture>(tex); ASSERT_LOG(texture != NULL, "Texture passed in was not of expected type."); const float tx1 = float(src.x()) / texture->width(); const float ty1 = float(src.y()) / texture->height(); const float tx2 = src.w() == 0 ? 1.0f : float(src.x2()) / texture->width(); const float ty2 = src.h() == 0 ? 1.0f : float(src.y2()) / texture->height(); const float uv_coords[] = { tx1, ty1, tx2, ty1, tx1, ty2, tx2, ty2, }; const float vx1 = float(dst.x()); const float vy1 = float(dst.y()); const float vx2 = float(dst.x2()); const float vy2 = float(dst.y2()); const float vtx_coords[] = { vx1, vy1, vx2, vy1, vx1, vy2, vx2, vy2, }; glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3((vx1+vx2)/2.0f,(vy1+vy2)/2.0f,0.0f)) * glm::rotate(glm::mat4(1.0f), rotation, glm::vec3(0.0f,0.0f,1.0f)) * glm::translate(glm::mat4(1.0f), glm::vec3(-(vx1+vx2)/2.0f,-(vy1+vy2)/2.0f,0.0f)); glm::mat4 mvp = mvp_ * model * getModelMatrix(); auto shader = OpenGL::ShaderProgram::defaultSystemShader(); shader->makeActive(); texture->bind(); shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(mvp)); if(color != KRE::Color::colorWhite()) { shader->setUniformValue(shader->getColorUniform(), (color*getColor()).asFloatVector()); } else { shader->setUniformValue(shader->getColorUniform(), getColor().asFloatVector()); } shader->setUniformValue(shader->getTexMapUniform(), 0); // XXX the following line are only temporary, obviously. //shader->SetUniformValue(shader->GetUniformIterator("discard"), 0); glEnableVertexAttribArray(shader->getVertexAttribute()->second.location); glVertexAttribPointer(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords); glEnableVertexAttribArray(shader->getTexcoordAttribute()->second.location); glVertexAttribPointer(shader->getTexcoordAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, uv_coords); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableVertexAttribArray(shader->getTexcoordAttribute()->second.location); glDisableVertexAttribArray(shader->getVertexAttribute()->second.location); } void CanvasOGL::blitTexture(const TexturePtr& tex, const std::vector<vertex_texcoord>& vtc, float rotation, const Color& color) { ASSERT_LOG(false, "XXX CanvasOGL::blitTexture()"); } void CanvasOGL::blitTexture(const MaterialPtr& mat, float rotation, const rect& dst, const Color& color) const { ASSERT_LOG(mat != NULL, "Material was null"); const float vx1 = float(dst.x()); const float vy1 = float(dst.y()); const float vx2 = float(dst.x2()); const float vy2 = float(dst.y2()); const float vtx_coords[] = { vx1, vy1, vx2, vy1, vx1, vy2, vx2, vy2, }; glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3((vx1+vx2)/2.0f,(vy1+vy2)/2.0f,0.0f)) * glm::rotate(glm::mat4(1.0f), rotation, glm::vec3(0.0f,0.0f,1.0f)) * glm::translate(glm::mat4(1.0f), glm::vec3(-(vx1+vy1)/2.0f,-(vy1+vy1)/2.0f,0.0f)); glm::mat4 mvp = mvp_ * model * getModelMatrix(); auto shader = OpenGL::ShaderProgram::defaultSystemShader(); shader->makeActive(); shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(mvp)); //if(color != KRE::Color::colorWhite()) { shader->setUniformValue(shader->getColorUniform(), color.asFloatVector()); //} shader->setUniformValue(shader->getTexMapUniform(), 0); mat->apply(); for(auto it = mat->getTexture().begin(); it != mat->getTexture().end(); ++it) { auto texture = std::dynamic_pointer_cast<OpenGLTexture>(*it); ASSERT_LOG(texture != NULL, "Texture passed in was not of expected type."); auto uv_coords = mat->getNormalisedTextureCoords(it); texture->bind(); // XXX the following line are only temporary, obviously. //shader->SetUniformValue(shader->GetUniformIterator("discard"), 0); glEnableVertexAttribArray(shader->getVertexAttribute()->second.location); glVertexAttribPointer(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords); glEnableVertexAttribArray(shader->getTexcoordAttribute()->second.location); glVertexAttribPointer(shader->getTexcoordAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, &uv_coords); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableVertexAttribArray(shader->getTexcoordAttribute()->second.location); glDisableVertexAttribArray(shader->getVertexAttribute()->second.location); } mat->unapply(); } void CanvasOGL::blitTexture(const MaterialPtr& mat, const rect& src, float rotation, const rect& dst, const Color& color) const { ASSERT_LOG(mat != NULL, "Material was null"); const float vx1 = float(dst.x()); const float vy1 = float(dst.y()); const float vx2 = float(dst.x2()); const float vy2 = float(dst.y2()); const float vtx_coords[] = { vx1, vy1, vx2, vy1, vx1, vy2, vx2, vy2, }; glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3((vx1+vx2)/2.0f,(vy1+vy2)/2.0f,0.0f)) * glm::rotate(glm::mat4(1.0f), rotation, glm::vec3(0.0f,0.0f,1.0f)) * glm::translate(glm::mat4(1.0f), glm::vec3(-(vx1+vy1)/2.0f,-(vy1+vy1)/2.0f,0.0f)); glm::mat4 mvp = mvp_ * model * getModelMatrix(); auto shader = OpenGL::ShaderProgram::defaultSystemShader(); shader->makeActive(); shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(mvp)); //if(color) { shader->setUniformValue(shader->getColorUniform(), color.asFloatVector()); //} shader->setUniformValue(shader->getTexMapUniform(), 0); mat->apply(); for(auto it = mat->getTexture().begin(); it != mat->getTexture().end(); ++it) { auto texture = std::dynamic_pointer_cast<OpenGLTexture>(*it); ASSERT_LOG(texture != NULL, "Texture passed in was not of expected type."); const float tx1 = float(src.x()) / texture->width(); const float ty1 = float(src.y()) / texture->height(); const float tx2 = src.w() == 0 ? 1.0f : float(src.x2()) / texture->width(); const float ty2 = src.h() == 0 ? 1.0f : float(src.y2()) / texture->height(); const float uv_coords[] = { tx1, ty1, tx2, ty1, tx1, ty2, tx2, ty2, }; texture->bind(); // XXX the following line are only temporary, obviously. //shader->SetUniformValue(shader->GetUniformIterator("discard"), 0); glEnableVertexAttribArray(shader->getVertexAttribute()->second.location); glVertexAttribPointer(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords); glEnableVertexAttribArray(shader->getTexcoordAttribute()->second.location); glVertexAttribPointer(shader->getTexcoordAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, &uv_coords); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableVertexAttribArray(shader->getTexcoordAttribute()->second.location); glDisableVertexAttribArray(shader->getVertexAttribute()->second.location); } mat->unapply(); } void CanvasOGL::drawSolidRect(const rect& r, const Color& fill_color, const Color& stroke_color, float rotation) const { rectf vtx = r.as_type<float>(); const float vtx_coords[] = { vtx.x1(), vtx.y1(), vtx.x2(), vtx.y1(), vtx.x1(), vtx.y2(), vtx.x2(), vtx.y2(), }; glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3(vtx.mid_x(),vtx.mid_y(),0.0f)) * glm::rotate(glm::mat4(1.0f), rotation, glm::vec3(0.0f,0.0f,1.0f)) * glm::translate(glm::mat4(1.0f), glm::vec3(-vtx.mid_x(),-vtx.mid_y(),0.0f)); glm::mat4 mvp = mvp_ * model * getModelMatrix(); static OpenGL::ShaderProgramPtr shader = OpenGL::ShaderProgram::factory("simple"); shader->makeActive(); shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(mvp)); // Draw a filled rect shader->setUniformValue(shader->getColorUniform(), fill_color.asFloatVector()); glEnableVertexAttribArray(shader->getVertexAttribute()->second.location); glVertexAttribPointer(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // Draw stroke if stroke_color is specified. // XXX I think there is an easier way of doing this, with modern GL const float vtx_coords_line[] = { vtx.x1(), vtx.y1(), vtx.x2(), vtx.y1(), vtx.x2(), vtx.y2(), vtx.x1(), vtx.y2(), vtx.x1(), vtx.y1(), }; shader->setUniformValue(shader->getColorUniform(), stroke_color.asFloatVector()); glEnableVertexAttribArray(shader->getVertexAttribute()->second.location); glVertexAttribPointer(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords_line); // XXX this may not be right. glDrawArrays(GL_LINE_STRIP, 0, 5); } void CanvasOGL::drawSolidRect(const rect& r, const Color& fill_color, float rotate) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidRect()"); } void CanvasOGL::drawHollowRect(const rect& r, const Color& stroke_color, float rotate) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawHollowRect()"); } void CanvasOGL::drawLine(const point& p1, const point& p2, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawLine()"); } void CanvasOGL::drawLines(const std::vector<glm::vec2>& varray, float line_width, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawLines()"); } void CanvasOGL::drawLines(const std::vector<glm::vec2>& varray, float line_width, const std::vector<glm::u8vec4>& carray) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawLines()"); } void CanvasOGL::drawLineStrip(const std::vector<glm::vec2>& points, float line_width, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawLineStrip()"); } void CanvasOGL::drawLineLoop(const std::vector<glm::vec2>& varray, float line_width, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawLineLoop()"); } void CanvasOGL::drawLine(const pointf& p1, const pointf& p2, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawLine()"); } void CanvasOGL::drawPolygon(const std::vector<glm::vec2>& points, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawPolygon()"); } void CanvasOGL::drawSolidCircle(const point& centre, double radius, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidCircle()"); } void CanvasOGL::drawSolidCircle(const point& centre, double radius, const std::vector<uint8_t>& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidCircle()"); } void CanvasOGL::drawHollowCircle(const point& centre, double radius, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawHollowCircle()"); } void CanvasOGL::drawSolidCircle(const pointf& centre, double radius, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidCircle()"); } void CanvasOGL::drawSolidCircle(const pointf& centre, double radius, const std::vector<uint8_t>& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidCircle()"); } void CanvasOGL::drawHollowCircle(const pointf& centre, double radius, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawHollowCircle()"); } void CanvasOGL::drawPoints(const std::vector<glm::vec2>& points, float radius, const Color& color) const { ASSERT_LOG(false, "XXX write function CanvasOGL::drawPoints()"); } CanvasPtr CanvasOGL::getInstance() { return get_instance(); } }
sweetkristas/swiftly
src/kre/CanvasOGL.cpp
C++
bsd-3-clause
13,121
// Copyright 2016 Keybase Inc. All rights reserved. // Use of this source code is governed by a BSD // license that can be found in the LICENSE file. package libkey import ( "context" "github.com/keybase/client/go/kbfs/idutil" "github.com/keybase/client/go/kbfs/kbfscrypto" "github.com/keybase/client/go/kbfs/kbfsmd" "github.com/keybase/client/go/protocol/keybase1" ) // KeyOpsConfig is a config object containing the outside helper // instances needed by KeyOps. type KeyOpsConfig interface { KeyServer() KeyServer KBPKI() idutil.KBPKI } // KeyOpsStandard implements the KeyOps interface and relays get/put // requests for server-side key halves from/to the key server. type KeyOpsStandard struct { config KeyOpsConfig } // NewKeyOpsStandard creates a new KeyOpsStandard instance. func NewKeyOpsStandard(config KeyOpsConfig) *KeyOpsStandard { return &KeyOpsStandard{config} } // Test that KeyOps standard fully implements the KeyOps interface. var _ KeyOps = (*KeyOpsStandard)(nil) // GetTLFCryptKeyServerHalf is an implementation of the KeyOps interface. func (k *KeyOpsStandard) GetTLFCryptKeyServerHalf( ctx context.Context, serverHalfID kbfscrypto.TLFCryptKeyServerHalfID, key kbfscrypto.CryptPublicKey) (kbfscrypto.TLFCryptKeyServerHalf, error) { // get the key half from the server serverHalf, err := k.config.KeyServer().GetTLFCryptKeyServerHalf( ctx, serverHalfID, key) if err != nil { return kbfscrypto.TLFCryptKeyServerHalf{}, err } // get current uid and deviceKID session, err := k.config.KBPKI().GetCurrentSession(ctx) if err != nil { return kbfscrypto.TLFCryptKeyServerHalf{}, err } // verify we got the expected key err = kbfscrypto.VerifyTLFCryptKeyServerHalfID( serverHalfID, session.UID, key, serverHalf) if err != nil { return kbfscrypto.TLFCryptKeyServerHalf{}, err } return serverHalf, nil } // PutTLFCryptKeyServerHalves is an implementation of the KeyOps interface. func (k *KeyOpsStandard) PutTLFCryptKeyServerHalves( ctx context.Context, keyServerHalves kbfsmd.UserDeviceKeyServerHalves) error { // upload the keys return k.config.KeyServer().PutTLFCryptKeyServerHalves(ctx, keyServerHalves) } // DeleteTLFCryptKeyServerHalf is an implementation of the KeyOps interface. func (k *KeyOpsStandard) DeleteTLFCryptKeyServerHalf( ctx context.Context, uid keybase1.UID, key kbfscrypto.CryptPublicKey, serverHalfID kbfscrypto.TLFCryptKeyServerHalfID) error { return k.config.KeyServer().DeleteTLFCryptKeyServerHalf( ctx, uid, key, serverHalfID) }
keybase/client
go/kbfs/libkey/key_ops.go
GO
bsd-3-clause
2,520
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DataExplorer.Domain.Columns; using DataExplorer.Domain.Layouts; namespace DataExplorer.Domain.Maps.SizeMaps { public class SizeMapFactory : ISizeMapFactory { public SizeMap Create(Column column, double targetMin, double targetMax, SortOrder sortOrder) { if (column.DataType == typeof(Boolean)) return new BooleanToSizeMap(targetMin, targetMax, sortOrder); if (column.DataType == typeof(DateTime)) return new DateTimeToSizeMap( (DateTime)column.Min, (DateTime)column.Max, targetMin, targetMax, sortOrder); if (column.DataType == typeof(Double)) return new FloatToSizeMap( (double)column.Min, (double)column.Max, targetMin, targetMax, sortOrder); if (column.DataType == typeof(Int32)) return new IntegerToSizeMap( (int)column.Min, (int)column.Max, targetMin, targetMax, sortOrder); if (column.DataType == typeof(String)) return new StringToSizeMap( column.Values.Cast<string>().ToList(), targetMin, targetMax, sortOrder); throw new ArgumentException("Column data type is not valid data type for an axis map."); } } }
dataexplorer/dataexplorer
Domain/Maps/SizeMaps/SizeMapFactory.cs
C#
bsd-3-clause
1,714
package com.btr.proxy.search.desktop.gnome; import java.io.File; import java.io.IOException; import java.net.ProxySelector; import java.util.Properties; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import com.btr.proxy.search.ProxySearchStrategy; import com.btr.proxy.selector.direct.NoProxySelector; import com.btr.proxy.selector.fixed.FixedProxySelector; import com.btr.proxy.selector.misc.ProtocolDispatchSelector; import com.btr.proxy.selector.whitelist.ProxyBypassListSelector; import com.btr.proxy.util.EmptyXMLResolver; import com.btr.proxy.util.Logger; import com.btr.proxy.util.PlatformUtil; import com.btr.proxy.util.ProxyException; import com.btr.proxy.util.ProxyUtil; import com.btr.proxy.util.Logger.LogLevel; /***************************************************************************** * Loads the Gnome proxy settings from the Gnome GConf settings. * <p> * The following settings are extracted from the configuration that is stored * in <i>.gconf</i> folder found in the user's home directory: * </p> * <ul> * <li><i>/system/http_proxy/use_http_proxy</i> -> bool used only by gnome-vfs </li> * <li><i>/system/http_proxy/host</i> -> string "my-proxy.example.com" without "http://"</li> * <li><i>/system/http_proxy/port</i> -> int</li> * <li><i>/system/http_proxy/use_authentication</i> -> bool</li> * <li><i>/system/http_proxy/authentication_user</i> -> string</li> * <li><i>/system/http_proxy/authentication_password</i> -> string</li> * <li><i>/system/http_proxy/ignore_hosts</i> -> list-of-string</li> * <li><i>/system/proxy/mode</i> -> string THIS IS THE CANONICAL KEY; SEE BELOW</li> * <li><i>/system/proxy/secure_host</i> -> string "proxy-for-https.example.com"</li> * <li><i>/system/proxy/secure_port</i> -> int</li> * <li><i>/system/proxy/ftp_host</i> -> string "proxy-for-ftp.example.com"</li> * <li><i>/system/proxy/ftp_port</i> -> int</li> * <li><i>/system/proxy/socks_host</i> -> string "proxy-for-socks.example.com"</li> * <li><i>/system/proxy/socks_port</i> -> int</li> * <li><i>/system/proxy/autoconfig_url</i> -> string "http://proxy-autoconfig.example.com"</li> * </ul> * <i>/system/proxy/mode</i> can be either:<br/> * "none" -> No proxy is used<br/> * "manual" -> The user's configuration values are used (/system/http_proxy/{host,port,etc.})<br/> * "auto" -> The "/system/proxy/autoconfig_url" key is used <br/> * <p> * GNOME Proxy_configuration settings are explained * <a href="http://en.opensuse.org/GNOME/Proxy_configuration">here</a> in detail * </p> * @author Bernd Rosstauscher ([email protected]) Copyright 2009 ****************************************************************************/ public class GnomeProxySearchStrategy implements ProxySearchStrategy { /************************************************************************* * ProxySelector * @see java.net.ProxySelector#ProxySelector() ************************************************************************/ public GnomeProxySearchStrategy() { super(); } /************************************************************************* * Loads the proxy settings and initializes a proxy selector for the Gnome * proxy settings. * @return a configured ProxySelector, null if none is found. * @throws ProxyException on file reading error. ************************************************************************/ public ProxySelector getProxySelector() throws ProxyException { Logger.log(getClass(), LogLevel.TRACE, "Detecting Gnome proxy settings"); Properties settings = readSettings(); String type = settings.getProperty("/system/proxy/mode"); ProxySelector result = null; if (type == null) { String useProxy = settings.getProperty("/system/http_proxy/use_http_proxy"); if (useProxy == null) { return null; } type = Boolean.parseBoolean(useProxy)?"manual":"none"; } if ("none".equals(type)) { Logger.log(getClass(), LogLevel.TRACE, "Gnome uses no proxy"); result = NoProxySelector.getInstance(); } if ("manual".equals(type)) { Logger.log(getClass(), LogLevel.TRACE, "Gnome uses manual proxy settings"); result = setupFixedProxySelector(settings); } if ("auto".equals(type)) { String pacScriptUrl = settings.getProperty("/system/proxy/autoconfig_url", ""); Logger.log(getClass(), LogLevel.TRACE, "Gnome uses autodetect script {0}", pacScriptUrl); result = ProxyUtil.buildPacSelectorForUrl(pacScriptUrl); } // Wrap into white-list filter? String noProxyList = settings.getProperty("/system/http_proxy/ignore_hosts", null); if (result != null && noProxyList != null && noProxyList.trim().length() > 0) { Logger.log(getClass(), LogLevel.TRACE, "Gnome uses proxy bypass list: {0}", noProxyList); result = new ProxyBypassListSelector(noProxyList, result); } return result; } /************************************************************************* * Load the proxy settings from the gconf settings XML file. * @return the loaded settings stored in a properties object. * @throws ProxyException on processing error. ************************************************************************/ public Properties readSettings() throws ProxyException { Properties settings = new Properties(); try { parseSettings("/system/proxy/", settings); parseSettings("/system/http_proxy/", settings); } catch (IOException e) { Logger.log(getClass(), LogLevel.ERROR, "Gnome settings file error.", e); throw new ProxyException(e); } return settings; } /************************************************************************* * Finds the Gnome GConf settings file. * @param context the gconf context to parse. * @return a file or null if does not exist. ************************************************************************/ private File findSettingsFile(String context) { // Normally we should inspect /etc/gconf/<version>/path to find out where the actual file is. // But for normal systems this is always stored in .gconf folder in the user's home directory. File userDir = new File(PlatformUtil.getUserHomeDir()); // Build directory path for context StringBuilder path = new StringBuilder(); String[] parts = context.split("/"); for (String part : parts) { path.append(part); path.append(File.separator); } File settingsFile = new File(userDir, ".gconf"+File.separator+path.toString()+"%gconf.xml"); if (!settingsFile.exists()) { Logger.log(getClass(), LogLevel.WARNING, "Gnome settings: {0} not found.", settingsFile); return null; } return settingsFile; } /************************************************************************* * Parse the fixed proxy settings and build an ProxySelector for this a * chained configuration. * @param settings the proxy settings to evaluate. ************************************************************************/ private ProxySelector setupFixedProxySelector(Properties settings) { if (!hasProxySettings(settings)) { return null; } ProtocolDispatchSelector ps = new ProtocolDispatchSelector(); installHttpSelector(settings, ps); if (useForAllProtocols(settings)) { ps.setFallbackSelector(ps.getSelector("http")); } else { installSecureSelector(settings, ps); installFtpSelector(settings, ps); installSocksSelector(settings, ps); } return ps; } /************************************************************************* * Check if the http proxy should also be used for all other protocols. * @param settings to inspect. * @return true if only one proxy is configured else false. ************************************************************************/ private boolean useForAllProtocols(Properties settings) { return Boolean.parseBoolean( settings.getProperty("/system/http_proxy/use_same_proxy", "false")); } /************************************************************************* * Checks if we have Proxy configuration settings in the properties. * @param settings to inspect. * @return true if we have found Proxy settings. ************************************************************************/ private boolean hasProxySettings(Properties settings) { String proxyHost = settings.getProperty("/system/http_proxy/host", null); return proxyHost != null && proxyHost.length() > 0; } /************************************************************************* * Install a http proxy from the given settings. * @param settings to inspect * @param ps the dispatch selector to configure. * @throws NumberFormatException ************************************************************************/ private void installHttpSelector(Properties settings, ProtocolDispatchSelector ps) throws NumberFormatException { String proxyHost = settings.getProperty("/system/http_proxy/host", null); int proxyPort = Integer.parseInt(settings.getProperty("/system/http_proxy/port", "0").trim()); if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) { Logger.log(getClass(), LogLevel.TRACE, "Gnome http proxy is {0}:{1}", proxyHost, proxyPort); ps.setSelector("http", new FixedProxySelector(proxyHost.trim(), proxyPort)); } } /************************************************************************* * Install a socks proxy from the given settings. * @param settings to inspect * @param ps the dispatch selector to configure. * @throws NumberFormatException ************************************************************************/ private void installSocksSelector(Properties settings, ProtocolDispatchSelector ps) throws NumberFormatException { String proxyHost = settings.getProperty("/system/proxy/socks_host", null); int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/socks_port", "0").trim()); if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) { Logger.log(getClass(), LogLevel.TRACE, "Gnome socks proxy is {0}:{1}", proxyHost, proxyPort); ps.setSelector("socks", new FixedProxySelector(proxyHost.trim(), proxyPort)); } } /************************************************************************* * @param settings * @param ps * @throws NumberFormatException ************************************************************************/ private void installFtpSelector(Properties settings, ProtocolDispatchSelector ps) throws NumberFormatException { String proxyHost = settings.getProperty("/system/proxy/ftp_host", null); int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/ftp_port", "0").trim()); if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) { Logger.log(getClass(), LogLevel.TRACE, "Gnome ftp proxy is {0}:{1}", proxyHost, proxyPort); ps.setSelector("ftp", new FixedProxySelector(proxyHost.trim(), proxyPort)); } } /************************************************************************* * @param settings * @param ps * @throws NumberFormatException ************************************************************************/ private void installSecureSelector(Properties settings, ProtocolDispatchSelector ps) throws NumberFormatException { String proxyHost = settings.getProperty("/system/proxy/secure_host", null); int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/secure_port", "0").trim()); if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) { Logger.log(getClass(), LogLevel.TRACE, "Gnome secure proxy is {0}:{1}", proxyHost, proxyPort); ps.setSelector("https", new FixedProxySelector(proxyHost.trim(), proxyPort)); ps.setSelector("sftp", new FixedProxySelector(proxyHost.trim(), proxyPort)); } } /************************************************************************* * Parse the settings file and extract all network.proxy.* settings from it. * @param context the gconf context to parse. * @param settings the settings object to fill. * @return the parsed properties. * @throws IOException on read error. ************************************************************************/ private Properties parseSettings(String context, Properties settings) throws IOException { // Read settings from file File settingsFile = findSettingsFile(context); if (settingsFile == null) { return settings; } try { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); documentBuilder.setEntityResolver(new EmptyXMLResolver()); Document doc = documentBuilder.parse(settingsFile); Element root = doc.getDocumentElement(); Node entry = root.getFirstChild(); while (entry != null) { if ("entry".equals(entry.getNodeName()) && entry instanceof Element) { String entryName = ((Element)entry).getAttribute("name"); settings.setProperty(context+entryName, getEntryValue((Element) entry)); } entry = entry.getNextSibling(); } } catch (SAXException e) { Logger.log(getClass(), LogLevel.ERROR, "Gnome settings parse error", e); throw new IOException(e.getMessage()); } catch (ParserConfigurationException e) { Logger.log(getClass(), LogLevel.ERROR, "Gnome settings parse error", e); throw new IOException(e.getMessage()); } return settings; } /************************************************************************* * Parse an entry value from a given entry node. * @param entry the XML node to inspect. * @return the value, null if it has no value. ************************************************************************/ private String getEntryValue(Element entry) { String type = entry.getAttribute("type"); if ("int".equals(type) || "bool".equals(type)) { return entry.getAttribute("value"); } if ("string".equals(type)) { NodeList list = entry.getElementsByTagName("stringvalue"); if (list.getLength() > 0) { return list.item(0).getTextContent(); } } if ("list".equals(type)) { StringBuilder result = new StringBuilder(); NodeList list = entry.getElementsByTagName("li"); // Build comma separated list of items for (int i = 0; i < list.getLength(); i++) { if (result.length() > 0) { result.append(","); } result.append(getEntryValue((Element) list.item(i))); } return result.toString(); } return null; } }
brsanthu/proxy-vole
src/main/java/com/btr/proxy/search/desktop/gnome/GnomeProxySearchStrategy.java
Java
bsd-3-clause
14,860
/* * Copyright (C) 2014 The Async HBase Authors. All rights reserved. * This file is part of Async HBase. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the StumbleUpon nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.hbase.async; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mock; import java.nio.charset.Charset; import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.hbase.async.HBaseClient.ZKClient; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.socket.SocketChannel; import org.jboss.netty.channel.socket.SocketChannelConfig; import org.jboss.netty.channel.socket.nio.NioClientBossPool; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioWorkerPool; import org.jboss.netty.util.HashedWheelTimer; import org.jboss.netty.util.Timeout; import org.jboss.netty.util.TimerTask; import org.junit.Before; import org.junit.Ignore; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.reflect.Whitebox; import com.stumbleupon.async.Deferred; @PrepareForTest({ HBaseClient.class, RegionClient.class, HBaseRpc.class, GetRequest.class, RegionInfo.class, NioClientSocketChannelFactory.class, Executors.class, HashedWheelTimer.class, NioClientBossPool.class, NioWorkerPool.class }) @Ignore // ignore for test runners public class BaseTestHBaseClient { protected static final Charset CHARSET = Charset.forName("ASCII"); protected static final byte[] COMMA = { ',' }; protected static final byte[] TIMESTAMP = "1234567890".getBytes(); protected static final byte[] INFO = getStatic("INFO"); protected static final byte[] REGIONINFO = getStatic("REGIONINFO"); protected static final byte[] SERVER = getStatic("SERVER"); protected static final byte[] TABLE = { 't', 'a', 'b', 'l', 'e' }; protected static final byte[] KEY = { 'k', 'e', 'y' }; protected static final byte[] KEY2 = { 'k', 'e', 'y', '2' }; protected static final byte[] FAMILY = { 'f' }; protected static final byte[] QUALIFIER = { 'q', 'u', 'a', 'l' }; protected static final byte[] VALUE = { 'v', 'a', 'l', 'u', 'e' }; protected static final byte[] EMPTY_ARRAY = new byte[0]; protected static final KeyValue KV = new KeyValue(KEY, FAMILY, QUALIFIER, VALUE); protected static final RegionInfo meta = mkregion(".META.", ".META.,,1234567890"); protected static final RegionInfo region = mkregion("table", "table,,1234567890"); protected static final int RS_PORT = 50511; protected static final String ROOT_IP = "192.168.0.1"; protected static final String META_IP = "192.168.0.2"; protected static final String REGION_CLIENT_IP = "192.168.0.3"; protected static String MOCK_RS_CLIENT_NAME = "Mock RegionClient"; protected static String MOCK_ROOT_CLIENT_NAME = "Mock RootClient"; protected static String MOCK_META_CLIENT_NAME = "Mock MetaClient"; protected HBaseClient client = null; /** Extracted from {@link #client}. */ protected ConcurrentSkipListMap<byte[], RegionInfo> regions_cache; /** Extracted from {@link #client}. */ protected ConcurrentHashMap<RegionInfo, RegionClient> region2client; /** Extracted from {@link #client}. */ protected ConcurrentHashMap<RegionClient, ArrayList<RegionInfo>> client2regions; /** Extracted from {@link #client}. */ protected ConcurrentSkipListMap<byte[], ArrayList<HBaseRpc>> got_nsre; /** Extracted from {@link #client}. */ protected HashMap<String, RegionClient> ip2client; /** Extracted from {@link #client}. */ protected Counter num_nsre_rpcs; /** Fake client supposedly connected to -ROOT-. */ protected RegionClient rootclient; /** Fake client supposedly connected to .META.. */ protected RegionClient metaclient; /** Fake client supposedly connected to our fake test table. */ protected RegionClient regionclient; /** Each new region client is dumped here */ protected List<RegionClient> region_clients = new ArrayList<RegionClient>(); /** Fake Zookeeper client */ protected ZKClient zkclient; /** Fake channel factory */ protected NioClientSocketChannelFactory channel_factory; /** Fake channel returned from the factory */ protected SocketChannel chan; /** Fake timer for testing */ protected FakeTimer timer; @Before public void before() throws Exception { region_clients.clear(); rootclient = mock(RegionClient.class); when(rootclient.toString()).thenReturn(MOCK_ROOT_CLIENT_NAME); metaclient = mock(RegionClient.class); when(metaclient.toString()).thenReturn(MOCK_META_CLIENT_NAME); regionclient = mock(RegionClient.class); when(regionclient.toString()).thenReturn(MOCK_RS_CLIENT_NAME); zkclient = mock(ZKClient.class); channel_factory = mock(NioClientSocketChannelFactory.class); chan = mock(SocketChannel.class); timer = new FakeTimer(); when(zkclient.getDeferredRoot()).thenReturn(new Deferred<Object>()); PowerMockito.mockStatic(Executors.class); PowerMockito.when(Executors.defaultThreadFactory()) .thenReturn(mock(ThreadFactory.class)); PowerMockito.when(Executors.newCachedThreadPool()) .thenReturn(mock(ExecutorService.class)); PowerMockito.whenNew(NioClientSocketChannelFactory.class).withAnyArguments() .thenReturn(channel_factory); PowerMockito.whenNew(HashedWheelTimer.class).withAnyArguments() .thenReturn(timer); PowerMockito.whenNew(NioClientBossPool.class).withAnyArguments() .thenReturn(mock(NioClientBossPool.class)); PowerMockito.whenNew(NioWorkerPool.class).withAnyArguments() .thenReturn(mock(NioWorkerPool.class)); client = PowerMockito.spy(new HBaseClient("test-quorum-spec")); Whitebox.setInternalState(client, "zkclient", zkclient); Whitebox.setInternalState(client, "rootregion", rootclient); Whitebox.setInternalState(client, "jitter_percent", 0); regions_cache = Whitebox.getInternalState(client, "regions_cache"); region2client = Whitebox.getInternalState(client, "region2client"); client2regions = Whitebox.getInternalState(client, "client2regions"); got_nsre = Whitebox.getInternalState(client, "got_nsre"); ip2client = Whitebox.getInternalState(client, "ip2client"); injectRegionInCache(meta, metaclient, META_IP + ":" + RS_PORT); injectRegionInCache(region, regionclient, REGION_CLIENT_IP + ":" + RS_PORT); when(channel_factory.newChannel(any(ChannelPipeline.class))) .thenReturn(chan); when(chan.getConfig()).thenReturn(mock(SocketChannelConfig.class)); when(rootclient.toString()).thenReturn("Mock RootClient"); PowerMockito.doAnswer(new Answer<RegionClient>(){ @Override public RegionClient answer(InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final String endpoint = (String)args[0] + ":" + (Integer)args[1]; final RegionClient rc = mock(RegionClient.class); when(rc.getRemoteAddress()).thenReturn(endpoint); client2regions.put(rc, new ArrayList<RegionInfo>()); region_clients.add(rc); return rc; } }).when(client, "newClient", anyString(), anyInt()); } /** * Injects an entry in the local caches of the client. */ protected void injectRegionInCache(final RegionInfo region, final RegionClient client, final String ip) { regions_cache.put(region.name(), region); region2client.put(region, client); ArrayList<RegionInfo> regions = client2regions.get(client); if (regions == null) { regions = new ArrayList<RegionInfo>(1); client2regions.put(client, regions); } regions.add(region); ip2client.put(ip, client); } // ----------------- // // Helper functions. // // ----------------- // protected void clearCaches(){ regions_cache.clear(); region2client.clear(); client2regions.clear(); } protected static <T> T getStatic(final String fieldname) { return Whitebox.getInternalState(HBaseClient.class, fieldname); } /** * Creates a fake {@code .META.} row. * The row contains a single entry for all keys of {@link #TABLE}. */ protected static ArrayList<KeyValue> metaRow() { return metaRow(HBaseClient.EMPTY_ARRAY, HBaseClient.EMPTY_ARRAY); } /** * Creates a fake {@code .META.} row. * The row contains a single entry for {@link #TABLE}. * @param start_key The start key of the region in this entry. * @param stop_key The stop key of the region in this entry. */ protected static ArrayList<KeyValue> metaRow(final byte[] start_key, final byte[] stop_key) { final ArrayList<KeyValue> row = new ArrayList<KeyValue>(2); row.add(metaRegionInfo(start_key, stop_key, false, false, TABLE)); row.add(new KeyValue(region.name(), INFO, SERVER, "localhost:54321".getBytes())); return row; } protected static KeyValue metaRegionInfo( final byte[] start_key, final byte[] stop_key, final boolean offline, final boolean splitting, final byte[] table) { final byte[] name = concat(table, COMMA, start_key, COMMA, TIMESTAMP); final byte is_splitting = (byte) (splitting ? 1 : 0); final byte[] regioninfo = concat( new byte[] { 0, // version (byte) stop_key.length, // vint: stop key length }, stop_key, offline ? new byte[] { 1 } : new byte[] { 0 }, // boolean: offline Bytes.fromLong(name.hashCode()), // long: region ID (make it random) new byte[] { (byte) name.length }, // vint: region name length name, // region name new byte[] { is_splitting, // boolean: splitting (byte) start_key.length, // vint: start key length }, start_key ); return new KeyValue(region.name(), INFO, REGIONINFO, regioninfo); } protected static RegionInfo mkregion(final String table, final String name) { return new RegionInfo(table.getBytes(), name.getBytes(), HBaseClient.EMPTY_ARRAY); } protected static byte[] anyBytes() { return any(byte[].class); } /** Concatenates byte arrays together. */ protected static byte[] concat(final byte[]... arrays) { int len = 0; for (final byte[] array : arrays) { len += array.length; } final byte[] result = new byte[len]; len = 0; for (final byte[] array : arrays) { System.arraycopy(array, 0, result, len, array.length); len += array.length; } return result; } /** Creates a new Deferred that's already called back. */ protected static <T> Answer<Deferred<T>> newDeferred(final T result) { return new Answer<Deferred<T>>() { public Deferred<T> answer(final InvocationOnMock invocation) { return Deferred.fromResult(result); } }; } /** * A fake {@link Timer} implementation that fires up tasks immediately. * Tasks are called immediately from the current thread and a history of the * various tasks is logged. */ static final class FakeTimer extends HashedWheelTimer { final List<Map.Entry<TimerTask, Long>> tasks = new ArrayList<Map.Entry<TimerTask, Long>>(); final ArrayList<Timeout> timeouts = new ArrayList<Timeout>(); boolean run = true; @Override public Timeout newTimeout(final TimerTask task, final long delay, final TimeUnit unit) { try { tasks.add(new AbstractMap.SimpleEntry<TimerTask, Long>(task, delay)); if (run) { task.run(null); // Argument never used in this code base. } final Timeout timeout = mock(Timeout.class); timeouts.add(timeout); return timeout; // Return value never used in this code base. } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Timer task failed: " + task, e); } } @Override public Set<Timeout> stop() { run = false; return new HashSet<Timeout>(timeouts); } } /** * A fake {@link org.jboss.netty.util.Timer} implementation. * Instead of executing the task it will store that task in a internal state * and provides a function to start the execution of the stored task. * This implementation thus allows the flexibility of simulating the * things that will be going on during the time out period of a TimerTask. * This was mainly return to simulate the timeout period for * alreadyNSREdRegion test, where the region will be in the NSREd mode only * during this timeout period, which was difficult to simulate using the * above {@link FakeTimer} implementation, as we don't get back the control * during the timeout period * * Here it will hold at most two Tasks. We have two tasks here because when * one is being executed, it may call for newTimeOut for another task. */ static final class FakeTaskTimer extends HashedWheelTimer { protected TimerTask newPausedTask = null; protected TimerTask pausedTask = null; @Override public synchronized Timeout newTimeout(final TimerTask task, final long delay, final TimeUnit unit) { if (pausedTask == null) { pausedTask = task; } else if (newPausedTask == null) { newPausedTask = task; } else { throw new IllegalStateException("Cannot Pause Two Timer Tasks"); } return null; } @Override public Set<Timeout> stop() { return null; } public boolean continuePausedTask() { if (pausedTask == null) { return false; } try { if (newPausedTask != null) { throw new IllegalStateException("Cannot be in this state"); } pausedTask.run(null); // Argument never used in this code base pausedTask = newPausedTask; newPausedTask = null; return true; } catch (Exception e) { throw new RuntimeException("Timer task failed: " + pausedTask, e); } } } /** * Generate and return a mocked HBase RPC for testing purposes with a valid * Deferred that can be called on execution. * @param deferred A deferred to watch for results * @return The RPC to pass through unit tests. */ protected HBaseRpc getMockHBaseRpc(final Deferred<Object> deferred) { final HBaseRpc rpc = mock(HBaseRpc.class); rpc.attempt = 0; when(rpc.getDeferred()).thenReturn(deferred); when(rpc.toString()).thenReturn("MockRPC"); PowerMockito.doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { if (deferred != null) { deferred.callback(invocation.getArguments()[0]); } else { System.out.println("Deferred was null!!"); } return null; } }).when(rpc).callback(Object.class); return rpc; } }
manolama/asynchbase
test/BaseTestHBaseClient.java
Java
bsd-3-clause
17,282
#include "gb_thread.hpp" #include "z80.hpp" #include "memory.hpp" #include "rom.hpp" #include "cart_rom_only.hpp" #include "cart_mbc1.hpp" #include "cart_mbc5.hpp" #include "internal_ram.hpp" #include "video.hpp" #include "timer.hpp" #include "joypad.hpp" #include "sound.hpp" #include "debug.hpp" #include "assert.hpp" #include <cstdlib> #include <vector> #include <fstream> #include <memory> #include <chrono> namespace { class stop_exception {}; std::unique_ptr<gb::memory_mapping> init_cartridge(gb::rom rom) { switch (rom.cartridge()) { case 0x00: // ROM only (could have little RAM) return std::make_unique<gb::cart_rom_only>(std::move(rom)); case 0x01: // MBC1 case 0x02: // MBC1+RAM case 0x03: // MBC1+RAM+BATTERY return std::make_unique<gb::cart_mbc1>(std::move(rom)); case 0x19: // MBC5 case 0x1A: // MBC5+RAM case 0x1B: // MBC5+RAM+BATTERY return std::make_unique<gb::cart_mbc5>(std::move(rom)); default: throw gb::unsupported_rom_exception("Unknown cartridge type"); } } std::unique_ptr<gb::z80_cpu> init_cpu(gb::memory_mapping &cart, gb::internal_ram &internal_ram, gb::video &video, gb::timer &timer, gb::joypad &joypad, gb::sound &sound) { // Make Memory gb::memory_map memory; memory.add_mapping(&cart); memory.add_mapping(&internal_ram); memory.add_mapping(&video); memory.add_mapping(&timer); memory.add_mapping(&joypad); memory.add_mapping(&sound); memory.write8(0xff05, 0x00); memory.write8(0xff06, 0x00); memory.write8(0xff07, 0x00); memory.write8(0xff10, 0x80); memory.write8(0xff11, 0xbf); memory.write8(0xff12, 0xf3); memory.write8(0xff14, 0xbf); memory.write8(0xff16, 0x3f); memory.write8(0xff17, 0x00); memory.write8(0xff19, 0xbf); memory.write8(0xff1a, 0x7f); memory.write8(0xff1b, 0xff); memory.write8(0xff1c, 0x9f); memory.write8(0xff1e, 0xbf); memory.write8(0xff20, 0xff); memory.write8(0xff21, 0x00); memory.write8(0xff22, 0x00); memory.write8(0xff23, 0xbf); memory.write8(0xff24, 0x77); memory.write8(0xff25, 0xf3); memory.write8(0xff26, 0xf1); memory.write8(0xff40, 0x91); memory.write8(0xff42, 0x00); memory.write8(0xff43, 0x00); memory.write8(0xff45, 0x00); memory.write8(0xff47, 0xfc); memory.write8(0xff48, 0xff); memory.write8(0xff49, 0xff); memory.write8(0xff4a, 0x00); memory.write8(0xff4b, 0x00); memory.write8(0xffff, 0x00); // Register file gb::register_file registers; registers.write8<gb::register8::a>(0x11); registers.write8<gb::register8::f>(0xb0); registers.write16<gb::register16::bc>(0x0013); registers.write16<gb::register16::de>(0x00d8); registers.write16<gb::register16::hl>(0x014d); registers.write16<gb::register16::sp>(0xfffe); registers.write16<gb::register16::pc>(0x0100); // Make Cpu return std::make_unique<gb::z80_cpu>(std::move(memory), std::move(registers)); } } gb::gb_hardware::gb_hardware(rom arg_rom) : cartridge(init_cartridge(std::move(arg_rom))), cpu(init_cpu(*cartridge, internal_ram, video, timer, joypad, sound)) { } #define HEAVY_DEBUG 0 gb::cputime gb::gb_hardware::tick() { const auto time_fde = cpu->fetch_decode_execute(); #if HEAVY_DEBUG switch (cpu->current_opcode()->extra_bytes) { case 0: debug(cpu->current_opcode()->mnemonic); break; case 1: debug(cpu->current_opcode()->mnemonic, " $=", static_cast<int>(cpu->value8())); break; case 2: debug(cpu->current_opcode()->mnemonic, " $=", static_cast<int>(cpu->value16())); break; default: ASSERT_UNREACHABLE(); } #endif timer.tick(*cpu, time_fde); const auto time_r = cpu->read(); timer.tick(*cpu, time_r); const auto time_w = cpu->write(); timer.tick(*cpu, time_w); const auto time = time_fde + time_r + time_w; video.tick(*cpu, time); #if HEAVY_DEBUG cpu->registers().debug_print(); #endif return time; } gb::gb_thread::gb_thread() : _running(false) { } gb::gb_thread::~gb_thread() { post_stop(); join(); } void gb::gb_thread::start(gb::rom rom) { ASSERT(!_running); _gb = std::make_unique<gb_hardware>(std::move(rom)); _thread = std::thread(&gb_thread::run, this); _running = true; } void gb::gb_thread::join() { if (_running) { _thread.join(); } } void gb::gb_thread::post_stop() { command fn([](){ throw stop_exception(); }); std::lock_guard<std::mutex> lock(_mutex); _command_queue.emplace_back(std::move(fn)); } std::future<gb::video::raw_image> gb::gb_thread::post_get_image() { // TODO use capture by move (Visual Studio 2015/C++14) auto promise = std::make_shared<std::promise<video::raw_image>>(); auto future = promise->get_future(); command fn([this, promise]() { promise->set_value(_gb->video.image()); }); std::lock_guard<std::mutex> lock(_mutex); _command_queue.emplace_back(std::move(fn)); return future; } void gb::gb_thread::post_key_down(gb::key key) { command fn([this, key]() { _gb->joypad.down(key); }); std::lock_guard<std::mutex> lock(_mutex); _command_queue.emplace_back(std::move(fn)); } void gb::gb_thread::post_key_up(gb::key key) { command fn([this, key]() { _gb->joypad.up(key); }); std::lock_guard<std::mutex> lock(_mutex); _command_queue.emplace_back(std::move(fn)); } void gb::gb_thread::run() { using namespace std::chrono; using clock = steady_clock; static_assert(clock::is_steady, "clock not steady"); static_assert(std::ratio_less_equal<clock::period, std::ratio_multiply<std::ratio<100>, std::nano>>::value, "clock too inaccurate (period > 100ns)"); if (ASSERT_ENABLED) debug("WARNING: asserts are enabled!"); debug("====================================================="); // Let's go :) std::vector<command> current_commands; cputime gb_time(0); auto real_time_start = clock::now(); cputime performance_gb_time(0); nanoseconds performance_sleep_time(0); auto performance_start = clock::now(); try { while (true) { // Command stream { std::lock_guard<std::mutex> lock(_mutex); if (!_command_queue.empty()) { std::swap(current_commands, _command_queue); } } if (!current_commands.empty()) { for (const auto &command : current_commands) { command(); } current_commands.clear(); } // Simulation itself const auto time = _gb->tick(); // Time bookkeeping gb_time += time; const auto real_time = clock::now() - real_time_start; const auto drift = duration_cast<nanoseconds>(gb_time) - real_time; if (drift > milliseconds(5)) { // Simulation is too fast const auto sleep_start = clock::now(); std::this_thread::sleep_for(drift); performance_sleep_time += (clock::now() - sleep_start); const auto new_current_time = clock::now(); const auto new_real_time = new_current_time - real_time_start; const auto new_drift = gb_time - duration_cast<cputime>(new_real_time); gb_time = new_drift; real_time_start = new_current_time; } else if (drift < milliseconds(-100)) { // Simulation is too slow (reset counter to avoid an endless accumulation of negaitve time) // This is a resync-attempt in case of a spike and avoids underflow gb_time = cputime(0); real_time_start = clock::now(); } // Performance-o-meter performance_gb_time += time; const auto performance_now = clock::now(); const auto performance_real_time = performance_now - performance_start; if (performance_real_time > seconds(10)) { const auto accuracy = duration_cast<milliseconds>(performance_gb_time - performance_real_time).count(); const double speed = static_cast<double>(duration_cast<nanoseconds>(performance_gb_time).count()) / static_cast<double>(duration_cast<nanoseconds>(performance_real_time - performance_sleep_time).count()) * 100.0; debug("PERF: simulation drift in the last 10 s was ", accuracy, " ms"); debug("PERF: simulation speed in the last 10 s was ", speed, " % of required speed"); if (speed < 110.0) { debug("PERF WARNING: simulation speed is too low (< 110 %)"); } performance_sleep_time = seconds(0); performance_gb_time = cputime(0); performance_start = performance_now; } } } catch (const stop_exception &) { // this might be ugly but it works well :) } }
kaini/gameboy
gameboy_lib/gb_thread.cpp
C++
bsd-3-clause
8,162
# Verified-BPF Initial tinkering with a BPF metalanguage and implementation formally verified in Coq.
mmcco/Verified-BPF
README.md
Markdown
bsd-3-clause
103
//M*////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ /****************************************************************************************\ * Very fast SAD-based (Sum-of-Absolute-Diffrences) stereo correspondence algorithm. * * Contributed by Kurt Konolige * \****************************************************************************************/ #include "precomp.hpp" #include <stdio.h> #include <limits> #include "opencl_kernels_calib3d.hpp" namespace cv { struct StereoBMParams { StereoBMParams(int _numDisparities=64, int _SADWindowSize=21) { preFilterType = StereoBM::PREFILTER_XSOBEL; preFilterSize = 9; preFilterCap = 31; SADWindowSize = _SADWindowSize; minDisparity = 0; numDisparities = _numDisparities > 0 ? _numDisparities : 64; textureThreshold = 10; uniquenessRatio = 15; speckleRange = speckleWindowSize = 0; roi1 = roi2 = Rect(0,0,0,0); disp12MaxDiff = -1; dispType = CV_16S; } int preFilterType; int preFilterSize; int preFilterCap; int SADWindowSize; int minDisparity; int numDisparities; int textureThreshold; int uniquenessRatio; int speckleRange; int speckleWindowSize; Rect roi1, roi2; int disp12MaxDiff; int dispType; }; static bool ocl_prefilter_norm(InputArray _input, OutputArray _output, int winsize, int prefilterCap) { ocl::Kernel k("prefilter_norm", ocl::calib3d::stereobm_oclsrc, cv::format("-D WSZ=%d", winsize)); if(k.empty()) return false; int scale_g = winsize*winsize/8, scale_s = (1024 + scale_g)/(scale_g*2); scale_g *= scale_s; UMat input = _input.getUMat(), output; _output.create(input.size(), input.type()); output = _output.getUMat(); size_t globalThreads[3] = { input.cols, input.rows, 1 }; k.args(ocl::KernelArg::PtrReadOnly(input), ocl::KernelArg::PtrWriteOnly(output), input.rows, input.cols, prefilterCap, scale_g, scale_s); return k.run(2, globalThreads, NULL, false); } static void prefilterNorm( const Mat& src, Mat& dst, int winsize, int ftzero, uchar* buf ) { int x, y, wsz2 = winsize/2; int* vsum = (int*)alignPtr(buf + (wsz2 + 1)*sizeof(vsum[0]), 32); int scale_g = winsize*winsize/8, scale_s = (1024 + scale_g)/(scale_g*2); const int OFS = 256*5, TABSZ = OFS*2 + 256; uchar tab[TABSZ]; const uchar* sptr = src.ptr(); int srcstep = (int)src.step; Size size = src.size(); scale_g *= scale_s; for( x = 0; x < TABSZ; x++ ) tab[x] = (uchar)(x - OFS < -ftzero ? 0 : x - OFS > ftzero ? ftzero*2 : x - OFS + ftzero); for( x = 0; x < size.width; x++ ) vsum[x] = (ushort)(sptr[x]*(wsz2 + 2)); for( y = 1; y < wsz2; y++ ) { for( x = 0; x < size.width; x++ ) vsum[x] = (ushort)(vsum[x] + sptr[srcstep*y + x]); } for( y = 0; y < size.height; y++ ) { const uchar* top = sptr + srcstep*MAX(y-wsz2-1,0); const uchar* bottom = sptr + srcstep*MIN(y+wsz2,size.height-1); const uchar* prev = sptr + srcstep*MAX(y-1,0); const uchar* curr = sptr + srcstep*y; const uchar* next = sptr + srcstep*MIN(y+1,size.height-1); uchar* dptr = dst.ptr<uchar>(y); for( x = 0; x < size.width; x++ ) vsum[x] = (ushort)(vsum[x] + bottom[x] - top[x]); for( x = 0; x <= wsz2; x++ ) { vsum[-x-1] = vsum[0]; vsum[size.width+x] = vsum[size.width-1]; } int sum = vsum[0]*(wsz2 + 1); for( x = 1; x <= wsz2; x++ ) sum += vsum[x]; int val = ((curr[0]*5 + curr[1] + prev[0] + next[0])*scale_g - sum*scale_s) >> 10; dptr[0] = tab[val + OFS]; for( x = 1; x < size.width-1; x++ ) { sum += vsum[x+wsz2] - vsum[x-wsz2-1]; val = ((curr[x]*4 + curr[x-1] + curr[x+1] + prev[x] + next[x])*scale_g - sum*scale_s) >> 10; dptr[x] = tab[val + OFS]; } sum += vsum[x+wsz2] - vsum[x-wsz2-1]; val = ((curr[x]*5 + curr[x-1] + prev[x] + next[x])*scale_g - sum*scale_s) >> 10; dptr[x] = tab[val + OFS]; } } static bool ocl_prefilter_xsobel(InputArray _input, OutputArray _output, int prefilterCap) { ocl::Kernel k("prefilter_xsobel", ocl::calib3d::stereobm_oclsrc); if(k.empty()) return false; UMat input = _input.getUMat(), output; _output.create(input.size(), input.type()); output = _output.getUMat(); size_t globalThreads[3] = { input.cols, input.rows, 1 }; k.args(ocl::KernelArg::PtrReadOnly(input), ocl::KernelArg::PtrWriteOnly(output), input.rows, input.cols, prefilterCap); return k.run(2, globalThreads, NULL, false); } static void prefilterXSobel( const Mat& src, Mat& dst, int ftzero ) { int x, y; const int OFS = 256*4, TABSZ = OFS*2 + 256; uchar tab[TABSZ]; Size size = src.size(); for( x = 0; x < TABSZ; x++ ) tab[x] = (uchar)(x - OFS < -ftzero ? 0 : x - OFS > ftzero ? ftzero*2 : x - OFS + ftzero); uchar val0 = tab[0 + OFS]; #if CV_SSE2 volatile bool useSIMD = checkHardwareSupport(CV_CPU_SSE2); #endif for( y = 0; y < size.height-1; y += 2 ) { const uchar* srow1 = src.ptr<uchar>(y); const uchar* srow0 = y > 0 ? srow1 - src.step : size.height > 1 ? srow1 + src.step : srow1; const uchar* srow2 = y < size.height-1 ? srow1 + src.step : size.height > 1 ? srow1 - src.step : srow1; const uchar* srow3 = y < size.height-2 ? srow1 + src.step*2 : srow1; uchar* dptr0 = dst.ptr<uchar>(y); uchar* dptr1 = dptr0 + dst.step; dptr0[0] = dptr0[size.width-1] = dptr1[0] = dptr1[size.width-1] = val0; x = 1; #if CV_SSE2 if( useSIMD ) { __m128i z = _mm_setzero_si128(), ftz = _mm_set1_epi16((short)ftzero), ftz2 = _mm_set1_epi8(cv::saturate_cast<uchar>(ftzero*2)); for( ; x <= size.width-9; x += 8 ) { __m128i c0 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow0 + x - 1)), z); __m128i c1 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow1 + x - 1)), z); __m128i d0 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow0 + x + 1)), z); __m128i d1 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow1 + x + 1)), z); d0 = _mm_sub_epi16(d0, c0); d1 = _mm_sub_epi16(d1, c1); __m128i c2 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow2 + x - 1)), z); __m128i c3 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow3 + x - 1)), z); __m128i d2 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow2 + x + 1)), z); __m128i d3 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow3 + x + 1)), z); d2 = _mm_sub_epi16(d2, c2); d3 = _mm_sub_epi16(d3, c3); __m128i v0 = _mm_add_epi16(d0, _mm_add_epi16(d2, _mm_add_epi16(d1, d1))); __m128i v1 = _mm_add_epi16(d1, _mm_add_epi16(d3, _mm_add_epi16(d2, d2))); v0 = _mm_packus_epi16(_mm_add_epi16(v0, ftz), _mm_add_epi16(v1, ftz)); v0 = _mm_min_epu8(v0, ftz2); _mm_storel_epi64((__m128i*)(dptr0 + x), v0); _mm_storel_epi64((__m128i*)(dptr1 + x), _mm_unpackhi_epi64(v0, v0)); } } #endif for( ; x < size.width-1; x++ ) { int d0 = srow0[x+1] - srow0[x-1], d1 = srow1[x+1] - srow1[x-1], d2 = srow2[x+1] - srow2[x-1], d3 = srow3[x+1] - srow3[x-1]; int v0 = tab[d0 + d1*2 + d2 + OFS]; int v1 = tab[d1 + d2*2 + d3 + OFS]; dptr0[x] = (uchar)v0; dptr1[x] = (uchar)v1; } } for( ; y < size.height; y++ ) { uchar* dptr = dst.ptr<uchar>(y); for( x = 0; x < size.width; x++ ) dptr[x] = val0; } } static const int DISPARITY_SHIFT = 4; #if CV_SSE2 static void findStereoCorrespondenceBM_SSE2( const Mat& left, const Mat& right, Mat& disp, Mat& cost, StereoBMParams& state, uchar* buf, int _dy0, int _dy1 ) { const int ALIGN = 16; int x, y, d; int wsz = state.SADWindowSize, wsz2 = wsz/2; int dy0 = MIN(_dy0, wsz2+1), dy1 = MIN(_dy1, wsz2+1); int ndisp = state.numDisparities; int mindisp = state.minDisparity; int lofs = MAX(ndisp - 1 + mindisp, 0); int rofs = -MIN(ndisp - 1 + mindisp, 0); int width = left.cols, height = left.rows; int width1 = width - rofs - ndisp + 1; int ftzero = state.preFilterCap; int textureThreshold = state.textureThreshold; int uniquenessRatio = state.uniquenessRatio; short FILTERED = (short)((mindisp - 1) << DISPARITY_SHIFT); ushort *sad, *hsad0, *hsad, *hsad_sub; int *htext; uchar *cbuf0, *cbuf; const uchar* lptr0 = left.ptr() + lofs; const uchar* rptr0 = right.ptr() + rofs; const uchar *lptr, *lptr_sub, *rptr; short* dptr = disp.ptr<short>(); int sstep = (int)left.step; int dstep = (int)(disp.step/sizeof(dptr[0])); int cstep = (height + dy0 + dy1)*ndisp; short costbuf = 0; int coststep = cost.data ? (int)(cost.step/sizeof(costbuf)) : 0; const int TABSZ = 256; uchar tab[TABSZ]; const __m128i d0_8 = _mm_setr_epi16(0,1,2,3,4,5,6,7), dd_8 = _mm_set1_epi16(8); sad = (ushort*)alignPtr(buf + sizeof(sad[0]), ALIGN); hsad0 = (ushort*)alignPtr(sad + ndisp + 1 + dy0*ndisp, ALIGN); htext = (int*)alignPtr((int*)(hsad0 + (height+dy1)*ndisp) + wsz2 + 2, ALIGN); cbuf0 = (uchar*)alignPtr((uchar*)(htext + height + wsz2 + 2) + dy0*ndisp, ALIGN); for( x = 0; x < TABSZ; x++ ) tab[x] = (uchar)std::abs(x - ftzero); // initialize buffers memset( hsad0 - dy0*ndisp, 0, (height + dy0 + dy1)*ndisp*sizeof(hsad0[0]) ); memset( htext - wsz2 - 1, 0, (height + wsz + 1)*sizeof(htext[0]) ); for( x = -wsz2-1; x < wsz2; x++ ) { hsad = hsad0 - dy0*ndisp; cbuf = cbuf0 + (x + wsz2 + 1)*cstep - dy0*ndisp; lptr = lptr0 + MIN(MAX(x, -lofs), width-lofs-1) - dy0*sstep; rptr = rptr0 + MIN(MAX(x, -rofs), width-rofs-1) - dy0*sstep; for( y = -dy0; y < height + dy1; y++, hsad += ndisp, cbuf += ndisp, lptr += sstep, rptr += sstep ) { int lval = lptr[0]; __m128i lv = _mm_set1_epi8((char)lval), z = _mm_setzero_si128(); for( d = 0; d < ndisp; d += 16 ) { __m128i rv = _mm_loadu_si128((const __m128i*)(rptr + d)); __m128i hsad_l = _mm_load_si128((__m128i*)(hsad + d)); __m128i hsad_h = _mm_load_si128((__m128i*)(hsad + d + 8)); __m128i diff = _mm_adds_epu8(_mm_subs_epu8(lv, rv), _mm_subs_epu8(rv, lv)); _mm_store_si128((__m128i*)(cbuf + d), diff); hsad_l = _mm_add_epi16(hsad_l, _mm_unpacklo_epi8(diff,z)); hsad_h = _mm_add_epi16(hsad_h, _mm_unpackhi_epi8(diff,z)); _mm_store_si128((__m128i*)(hsad + d), hsad_l); _mm_store_si128((__m128i*)(hsad + d + 8), hsad_h); } htext[y] += tab[lval]; } } // initialize the left and right borders of the disparity map for( y = 0; y < height; y++ ) { for( x = 0; x < lofs; x++ ) dptr[y*dstep + x] = FILTERED; for( x = lofs + width1; x < width; x++ ) dptr[y*dstep + x] = FILTERED; } dptr += lofs; for( x = 0; x < width1; x++, dptr++ ) { short* costptr = cost.data ? cost.ptr<short>() + lofs + x : &costbuf; int x0 = x - wsz2 - 1, x1 = x + wsz2; const uchar* cbuf_sub = cbuf0 + ((x0 + wsz2 + 1) % (wsz + 1))*cstep - dy0*ndisp; cbuf = cbuf0 + ((x1 + wsz2 + 1) % (wsz + 1))*cstep - dy0*ndisp; hsad = hsad0 - dy0*ndisp; lptr_sub = lptr0 + MIN(MAX(x0, -lofs), width-1-lofs) - dy0*sstep; lptr = lptr0 + MIN(MAX(x1, -lofs), width-1-lofs) - dy0*sstep; rptr = rptr0 + MIN(MAX(x1, -rofs), width-1-rofs) - dy0*sstep; for( y = -dy0; y < height + dy1; y++, cbuf += ndisp, cbuf_sub += ndisp, hsad += ndisp, lptr += sstep, lptr_sub += sstep, rptr += sstep ) { int lval = lptr[0]; __m128i lv = _mm_set1_epi8((char)lval), z = _mm_setzero_si128(); for( d = 0; d < ndisp; d += 16 ) { __m128i rv = _mm_loadu_si128((const __m128i*)(rptr + d)); __m128i hsad_l = _mm_load_si128((__m128i*)(hsad + d)); __m128i hsad_h = _mm_load_si128((__m128i*)(hsad + d + 8)); __m128i cbs = _mm_load_si128((const __m128i*)(cbuf_sub + d)); __m128i diff = _mm_adds_epu8(_mm_subs_epu8(lv, rv), _mm_subs_epu8(rv, lv)); __m128i diff_h = _mm_sub_epi16(_mm_unpackhi_epi8(diff, z), _mm_unpackhi_epi8(cbs, z)); _mm_store_si128((__m128i*)(cbuf + d), diff); diff = _mm_sub_epi16(_mm_unpacklo_epi8(diff, z), _mm_unpacklo_epi8(cbs, z)); hsad_h = _mm_add_epi16(hsad_h, diff_h); hsad_l = _mm_add_epi16(hsad_l, diff); _mm_store_si128((__m128i*)(hsad + d), hsad_l); _mm_store_si128((__m128i*)(hsad + d + 8), hsad_h); } htext[y] += tab[lval] - tab[lptr_sub[0]]; } // fill borders for( y = dy1; y <= wsz2; y++ ) htext[height+y] = htext[height+dy1-1]; for( y = -wsz2-1; y < -dy0; y++ ) htext[y] = htext[-dy0]; // initialize sums for( d = 0; d < ndisp; d++ ) sad[d] = (ushort)(hsad0[d-ndisp*dy0]*(wsz2 + 2 - dy0)); hsad = hsad0 + (1 - dy0)*ndisp; for( y = 1 - dy0; y < wsz2; y++, hsad += ndisp ) for( d = 0; d < ndisp; d += 16 ) { __m128i s0 = _mm_load_si128((__m128i*)(sad + d)); __m128i s1 = _mm_load_si128((__m128i*)(sad + d + 8)); __m128i t0 = _mm_load_si128((__m128i*)(hsad + d)); __m128i t1 = _mm_load_si128((__m128i*)(hsad + d + 8)); s0 = _mm_add_epi16(s0, t0); s1 = _mm_add_epi16(s1, t1); _mm_store_si128((__m128i*)(sad + d), s0); _mm_store_si128((__m128i*)(sad + d + 8), s1); } int tsum = 0; for( y = -wsz2-1; y < wsz2; y++ ) tsum += htext[y]; // finally, start the real processing for( y = 0; y < height; y++ ) { int minsad = INT_MAX, mind = -1; hsad = hsad0 + MIN(y + wsz2, height+dy1-1)*ndisp; hsad_sub = hsad0 + MAX(y - wsz2 - 1, -dy0)*ndisp; __m128i minsad8 = _mm_set1_epi16(SHRT_MAX); __m128i mind8 = _mm_set1_epi16(0), d8 = d0_8, mask; for( d = 0; d < ndisp; d += 16 ) { __m128i u0 = _mm_load_si128((__m128i*)(hsad_sub + d)); __m128i u1 = _mm_load_si128((__m128i*)(hsad + d)); __m128i v0 = _mm_load_si128((__m128i*)(hsad_sub + d + 8)); __m128i v1 = _mm_load_si128((__m128i*)(hsad + d + 8)); __m128i usad8 = _mm_load_si128((__m128i*)(sad + d)); __m128i vsad8 = _mm_load_si128((__m128i*)(sad + d + 8)); u1 = _mm_sub_epi16(u1, u0); v1 = _mm_sub_epi16(v1, v0); usad8 = _mm_add_epi16(usad8, u1); vsad8 = _mm_add_epi16(vsad8, v1); mask = _mm_cmpgt_epi16(minsad8, usad8); minsad8 = _mm_min_epi16(minsad8, usad8); mind8 = _mm_max_epi16(mind8, _mm_and_si128(mask, d8)); _mm_store_si128((__m128i*)(sad + d), usad8); _mm_store_si128((__m128i*)(sad + d + 8), vsad8); mask = _mm_cmpgt_epi16(minsad8, vsad8); minsad8 = _mm_min_epi16(minsad8, vsad8); d8 = _mm_add_epi16(d8, dd_8); mind8 = _mm_max_epi16(mind8, _mm_and_si128(mask, d8)); d8 = _mm_add_epi16(d8, dd_8); } tsum += htext[y + wsz2] - htext[y - wsz2 - 1]; if( tsum < textureThreshold ) { dptr[y*dstep] = FILTERED; continue; } ushort CV_DECL_ALIGNED(16) minsad_buf[8], mind_buf[8]; _mm_store_si128((__m128i*)minsad_buf, minsad8); _mm_store_si128((__m128i*)mind_buf, mind8); for( d = 0; d < 8; d++ ) if(minsad > (int)minsad_buf[d] || (minsad == (int)minsad_buf[d] && mind > mind_buf[d])) { minsad = minsad_buf[d]; mind = mind_buf[d]; } if( uniquenessRatio > 0 ) { int thresh = minsad + (minsad * uniquenessRatio/100); __m128i thresh8 = _mm_set1_epi16((short)(thresh + 1)); __m128i d1 = _mm_set1_epi16((short)(mind-1)), d2 = _mm_set1_epi16((short)(mind+1)); __m128i dd_16 = _mm_add_epi16(dd_8, dd_8); d8 = _mm_sub_epi16(d0_8, dd_16); for( d = 0; d < ndisp; d += 16 ) { __m128i usad8 = _mm_load_si128((__m128i*)(sad + d)); __m128i vsad8 = _mm_load_si128((__m128i*)(sad + d + 8)); mask = _mm_cmpgt_epi16( thresh8, _mm_min_epi16(usad8,vsad8)); d8 = _mm_add_epi16(d8, dd_16); if( !_mm_movemask_epi8(mask) ) continue; mask = _mm_cmpgt_epi16( thresh8, usad8); mask = _mm_and_si128(mask, _mm_or_si128(_mm_cmpgt_epi16(d1,d8), _mm_cmpgt_epi16(d8,d2))); if( _mm_movemask_epi8(mask) ) break; __m128i t8 = _mm_add_epi16(d8, dd_8); mask = _mm_cmpgt_epi16( thresh8, vsad8); mask = _mm_and_si128(mask, _mm_or_si128(_mm_cmpgt_epi16(d1,t8), _mm_cmpgt_epi16(t8,d2))); if( _mm_movemask_epi8(mask) ) break; } if( d < ndisp ) { dptr[y*dstep] = FILTERED; continue; } } if( 0 < mind && mind < ndisp - 1 ) { int p = sad[mind+1], n = sad[mind-1]; d = p + n - 2*sad[mind] + std::abs(p - n); dptr[y*dstep] = (short)(((ndisp - mind - 1 + mindisp)*256 + (d != 0 ? (p-n)*256/d : 0) + 15) >> 4); } else dptr[y*dstep] = (short)((ndisp - mind - 1 + mindisp)*16); costptr[y*coststep] = sad[mind]; } } } #endif static void findStereoCorrespondenceBM( const Mat& left, const Mat& right, Mat& disp, Mat& cost, const StereoBMParams& state, uchar* buf, int _dy0, int _dy1 ) { const int ALIGN = 16; int x, y, d; int wsz = state.SADWindowSize, wsz2 = wsz/2; int dy0 = MIN(_dy0, wsz2+1), dy1 = MIN(_dy1, wsz2+1); int ndisp = state.numDisparities; int mindisp = state.minDisparity; int lofs = MAX(ndisp - 1 + mindisp, 0); int rofs = -MIN(ndisp - 1 + mindisp, 0); int width = left.cols, height = left.rows; int width1 = width - rofs - ndisp + 1; int ftzero = state.preFilterCap; int textureThreshold = state.textureThreshold; int uniquenessRatio = state.uniquenessRatio; short FILTERED = (short)((mindisp - 1) << DISPARITY_SHIFT); int *sad, *hsad0, *hsad, *hsad_sub, *htext; uchar *cbuf0, *cbuf; const uchar* lptr0 = left.ptr() + lofs; const uchar* rptr0 = right.ptr() + rofs; const uchar *lptr, *lptr_sub, *rptr; short* dptr = disp.ptr<short>(); int sstep = (int)left.step; int dstep = (int)(disp.step/sizeof(dptr[0])); int cstep = (height+dy0+dy1)*ndisp; int costbuf = 0; int coststep = cost.data ? (int)(cost.step/sizeof(costbuf)) : 0; const int TABSZ = 256; uchar tab[TABSZ]; sad = (int*)alignPtr(buf + sizeof(sad[0]), ALIGN); hsad0 = (int*)alignPtr(sad + ndisp + 1 + dy0*ndisp, ALIGN); htext = (int*)alignPtr((int*)(hsad0 + (height+dy1)*ndisp) + wsz2 + 2, ALIGN); cbuf0 = (uchar*)alignPtr((uchar*)(htext + height + wsz2 + 2) + dy0*ndisp, ALIGN); for( x = 0; x < TABSZ; x++ ) tab[x] = (uchar)std::abs(x - ftzero); // initialize buffers memset( hsad0 - dy0*ndisp, 0, (height + dy0 + dy1)*ndisp*sizeof(hsad0[0]) ); memset( htext - wsz2 - 1, 0, (height + wsz + 1)*sizeof(htext[0]) ); for( x = -wsz2-1; x < wsz2; x++ ) { hsad = hsad0 - dy0*ndisp; cbuf = cbuf0 + (x + wsz2 + 1)*cstep - dy0*ndisp; lptr = lptr0 + std::min(std::max(x, -lofs), width-lofs-1) - dy0*sstep; rptr = rptr0 + std::min(std::max(x, -rofs), width-rofs-1) - dy0*sstep; for( y = -dy0; y < height + dy1; y++, hsad += ndisp, cbuf += ndisp, lptr += sstep, rptr += sstep ) { int lval = lptr[0]; for( d = 0; d < ndisp; d++ ) { int diff = std::abs(lval - rptr[d]); cbuf[d] = (uchar)diff; hsad[d] = (int)(hsad[d] + diff); } htext[y] += tab[lval]; } } // initialize the left and right borders of the disparity map for( y = 0; y < height; y++ ) { for( x = 0; x < lofs; x++ ) dptr[y*dstep + x] = FILTERED; for( x = lofs + width1; x < width; x++ ) dptr[y*dstep + x] = FILTERED; } dptr += lofs; for( x = 0; x < width1; x++, dptr++ ) { int* costptr = cost.data ? cost.ptr<int>() + lofs + x : &costbuf; int x0 = x - wsz2 - 1, x1 = x + wsz2; const uchar* cbuf_sub = cbuf0 + ((x0 + wsz2 + 1) % (wsz + 1))*cstep - dy0*ndisp; cbuf = cbuf0 + ((x1 + wsz2 + 1) % (wsz + 1))*cstep - dy0*ndisp; hsad = hsad0 - dy0*ndisp; lptr_sub = lptr0 + MIN(MAX(x0, -lofs), width-1-lofs) - dy0*sstep; lptr = lptr0 + MIN(MAX(x1, -lofs), width-1-lofs) - dy0*sstep; rptr = rptr0 + MIN(MAX(x1, -rofs), width-1-rofs) - dy0*sstep; for( y = -dy0; y < height + dy1; y++, cbuf += ndisp, cbuf_sub += ndisp, hsad += ndisp, lptr += sstep, lptr_sub += sstep, rptr += sstep ) { int lval = lptr[0]; for( d = 0; d < ndisp; d++ ) { int diff = std::abs(lval - rptr[d]); cbuf[d] = (uchar)diff; hsad[d] = hsad[d] + diff - cbuf_sub[d]; } htext[y] += tab[lval] - tab[lptr_sub[0]]; } // fill borders for( y = dy1; y <= wsz2; y++ ) htext[height+y] = htext[height+dy1-1]; for( y = -wsz2-1; y < -dy0; y++ ) htext[y] = htext[-dy0]; // initialize sums for( d = 0; d < ndisp; d++ ) sad[d] = (int)(hsad0[d-ndisp*dy0]*(wsz2 + 2 - dy0)); hsad = hsad0 + (1 - dy0)*ndisp; for( y = 1 - dy0; y < wsz2; y++, hsad += ndisp ) for( d = 0; d < ndisp; d++ ) sad[d] = (int)(sad[d] + hsad[d]); int tsum = 0; for( y = -wsz2-1; y < wsz2; y++ ) tsum += htext[y]; // finally, start the real processing for( y = 0; y < height; y++ ) { int minsad = INT_MAX, mind = -1; hsad = hsad0 + MIN(y + wsz2, height+dy1-1)*ndisp; hsad_sub = hsad0 + MAX(y - wsz2 - 1, -dy0)*ndisp; for( d = 0; d < ndisp; d++ ) { int currsad = sad[d] + hsad[d] - hsad_sub[d]; sad[d] = currsad; if( currsad < minsad ) { minsad = currsad; mind = d; } } tsum += htext[y + wsz2] - htext[y - wsz2 - 1]; if( tsum < textureThreshold ) { dptr[y*dstep] = FILTERED; continue; } if( uniquenessRatio > 0 ) { int thresh = minsad + (minsad * uniquenessRatio/100); for( d = 0; d < ndisp; d++ ) { if( (d < mind-1 || d > mind+1) && sad[d] <= thresh) break; } if( d < ndisp ) { dptr[y*dstep] = FILTERED; continue; } } { sad[-1] = sad[1]; sad[ndisp] = sad[ndisp-2]; int p = sad[mind+1], n = sad[mind-1]; d = p + n - 2*sad[mind] + std::abs(p - n); dptr[y*dstep] = (short)(((ndisp - mind - 1 + mindisp)*256 + (d != 0 ? (p-n)*256/d : 0) + 15) >> 4); costptr[y*coststep] = sad[mind]; } } } } static bool ocl_prefiltering(InputArray left0, InputArray right0, OutputArray left, OutputArray right, StereoBMParams* state) { if( state->preFilterType == StereoBM::PREFILTER_NORMALIZED_RESPONSE ) { if(!ocl_prefilter_norm( left0, left, state->preFilterSize, state->preFilterCap)) return false; if(!ocl_prefilter_norm( right0, right, state->preFilterSize, state->preFilterCap)) return false; } else { if(!ocl_prefilter_xsobel( left0, left, state->preFilterCap )) return false; if(!ocl_prefilter_xsobel( right0, right, state->preFilterCap)) return false; } return true; } struct PrefilterInvoker : public ParallelLoopBody { PrefilterInvoker(const Mat& left0, const Mat& right0, Mat& left, Mat& right, uchar* buf0, uchar* buf1, StereoBMParams* _state) { imgs0[0] = &left0; imgs0[1] = &right0; imgs[0] = &left; imgs[1] = &right; buf[0] = buf0; buf[1] = buf1; state = _state; } void operator()( const Range& range ) const { for( int i = range.start; i < range.end; i++ ) { if( state->preFilterType == StereoBM::PREFILTER_NORMALIZED_RESPONSE ) prefilterNorm( *imgs0[i], *imgs[i], state->preFilterSize, state->preFilterCap, buf[i] ); else prefilterXSobel( *imgs0[i], *imgs[i], state->preFilterCap ); } } const Mat* imgs0[2]; Mat* imgs[2]; uchar* buf[2]; StereoBMParams* state; }; static bool ocl_stereobm( InputArray _left, InputArray _right, OutputArray _disp, StereoBMParams* state) { int ndisp = state->numDisparities; int mindisp = state->minDisparity; int wsz = state->SADWindowSize; int wsz2 = wsz/2; ocl::Device devDef = ocl::Device::getDefault(); int sizeX = devDef.isIntel() ? 32 : std::max(11, 27 - devDef.maxComputeUnits()), sizeY = sizeX - 1, N = ndisp * 2; cv::String opt = cv::format("-D DEFINE_KERNEL_STEREOBM -D MIN_DISP=%d -D NUM_DISP=%d" " -D BLOCK_SIZE_X=%d -D BLOCK_SIZE_Y=%d -D WSZ=%d", mindisp, ndisp, sizeX, sizeY, wsz); ocl::Kernel k("stereoBM", ocl::calib3d::stereobm_oclsrc, opt); if(k.empty()) return false; UMat left = _left.getUMat(), right = _right.getUMat(); int cols = left.cols, rows = left.rows; _disp.create(_left.size(), CV_16S); _disp.setTo((mindisp - 1) << 4); Rect roi = Rect(Point(wsz2 + mindisp + ndisp - 1, wsz2), Point(cols-wsz2-mindisp, rows-wsz2) ); UMat disp = (_disp.getUMat())(roi); int globalX = (disp.cols + sizeX - 1) / sizeX, globalY = (disp.rows + sizeY - 1) / sizeY; size_t globalThreads[3] = {N, globalX, globalY}; size_t localThreads[3] = {N, 1, 1}; int idx = 0; idx = k.set(idx, ocl::KernelArg::PtrReadOnly(left)); idx = k.set(idx, ocl::KernelArg::PtrReadOnly(right)); idx = k.set(idx, ocl::KernelArg::WriteOnlyNoSize(disp)); idx = k.set(idx, rows); idx = k.set(idx, cols); idx = k.set(idx, state->textureThreshold); idx = k.set(idx, state->uniquenessRatio); return k.run(3, globalThreads, localThreads, false); } struct FindStereoCorrespInvoker : public ParallelLoopBody { FindStereoCorrespInvoker( const Mat& _left, const Mat& _right, Mat& _disp, StereoBMParams* _state, int _nstripes, size_t _stripeBufSize, bool _useShorts, Rect _validDisparityRect, Mat& _slidingSumBuf, Mat& _cost ) { left = &_left; right = &_right; disp = &_disp; state = _state; nstripes = _nstripes; stripeBufSize = _stripeBufSize; useShorts = _useShorts; validDisparityRect = _validDisparityRect; slidingSumBuf = &_slidingSumBuf; cost = &_cost; } void operator()( const Range& range ) const { int cols = left->cols, rows = left->rows; int _row0 = std::min(cvRound(range.start * rows / nstripes), rows); int _row1 = std::min(cvRound(range.end * rows / nstripes), rows); uchar *ptr = slidingSumBuf->ptr() + range.start * stripeBufSize; int FILTERED = (state->minDisparity - 1)*16; Rect roi = validDisparityRect & Rect(0, _row0, cols, _row1 - _row0); if( roi.height == 0 ) return; int row0 = roi.y; int row1 = roi.y + roi.height; Mat part; if( row0 > _row0 ) { part = disp->rowRange(_row0, row0); part = Scalar::all(FILTERED); } if( _row1 > row1 ) { part = disp->rowRange(row1, _row1); part = Scalar::all(FILTERED); } Mat left_i = left->rowRange(row0, row1); Mat right_i = right->rowRange(row0, row1); Mat disp_i = disp->rowRange(row0, row1); Mat cost_i = state->disp12MaxDiff >= 0 ? cost->rowRange(row0, row1) : Mat(); #if CV_SSE2 if( useShorts ) findStereoCorrespondenceBM_SSE2( left_i, right_i, disp_i, cost_i, *state, ptr, row0, rows - row1 ); else #endif findStereoCorrespondenceBM( left_i, right_i, disp_i, cost_i, *state, ptr, row0, rows - row1 ); if( state->disp12MaxDiff >= 0 ) validateDisparity( disp_i, cost_i, state->minDisparity, state->numDisparities, state->disp12MaxDiff ); if( roi.x > 0 ) { part = disp_i.colRange(0, roi.x); part = Scalar::all(FILTERED); } if( roi.x + roi.width < cols ) { part = disp_i.colRange(roi.x + roi.width, cols); part = Scalar::all(FILTERED); } } protected: const Mat *left, *right; Mat* disp, *slidingSumBuf, *cost; StereoBMParams *state; int nstripes; size_t stripeBufSize; bool useShorts; Rect validDisparityRect; }; class StereoBMImpl : public StereoBM { public: StereoBMImpl() { params = StereoBMParams(); } StereoBMImpl( int _numDisparities, int _SADWindowSize ) { params = StereoBMParams(_numDisparities, _SADWindowSize); } void compute( InputArray leftarr, InputArray rightarr, OutputArray disparr ) { int dtype = disparr.fixedType() ? disparr.type() : params.dispType; Size leftsize = leftarr.size(); if (leftarr.size() != rightarr.size()) CV_Error( Error::StsUnmatchedSizes, "All the images must have the same size" ); if (leftarr.type() != CV_8UC1 || rightarr.type() != CV_8UC1) CV_Error( Error::StsUnsupportedFormat, "Both input images must have CV_8UC1" ); if (dtype != CV_16SC1 && dtype != CV_32FC1) CV_Error( Error::StsUnsupportedFormat, "Disparity image must have CV_16SC1 or CV_32FC1 format" ); if( params.preFilterType != PREFILTER_NORMALIZED_RESPONSE && params.preFilterType != PREFILTER_XSOBEL ) CV_Error( Error::StsOutOfRange, "preFilterType must be = CV_STEREO_BM_NORMALIZED_RESPONSE" ); if( params.preFilterSize < 5 || params.preFilterSize > 255 || params.preFilterSize % 2 == 0 ) CV_Error( Error::StsOutOfRange, "preFilterSize must be odd and be within 5..255" ); if( params.preFilterCap < 1 || params.preFilterCap > 63 ) CV_Error( Error::StsOutOfRange, "preFilterCap must be within 1..63" ); if( params.SADWindowSize < 5 || params.SADWindowSize > 255 || params.SADWindowSize % 2 == 0 || params.SADWindowSize >= std::min(leftsize.width, leftsize.height) ) CV_Error( Error::StsOutOfRange, "SADWindowSize must be odd, be within 5..255 and be not larger than image width or height" ); if( params.numDisparities <= 0 || params.numDisparities % 16 != 0 ) CV_Error( Error::StsOutOfRange, "numDisparities must be positive and divisble by 16" ); if( params.textureThreshold < 0 ) CV_Error( Error::StsOutOfRange, "texture threshold must be non-negative" ); if( params.uniquenessRatio < 0 ) CV_Error( Error::StsOutOfRange, "uniqueness ratio must be non-negative" ); int FILTERED = (params.minDisparity - 1) << DISPARITY_SHIFT; if(ocl::useOpenCL() && disparr.isUMat() && params.textureThreshold == 0) { UMat left, right; if(ocl_prefiltering(leftarr, rightarr, left, right, &params)) { if(ocl_stereobm(left, right, disparr, &params)) { if( params.speckleRange >= 0 && params.speckleWindowSize > 0 ) filterSpeckles(disparr.getMat(), FILTERED, params.speckleWindowSize, params.speckleRange, slidingSumBuf); if (dtype == CV_32F) disparr.getUMat().convertTo(disparr, CV_32FC1, 1./(1 << DISPARITY_SHIFT), 0); CV_IMPL_ADD(CV_IMPL_OCL); return; } } } Mat left0 = leftarr.getMat(), right0 = rightarr.getMat(); disparr.create(left0.size(), dtype); Mat disp0 = disparr.getMat(); preFilteredImg0.create( left0.size(), CV_8U ); preFilteredImg1.create( left0.size(), CV_8U ); cost.create( left0.size(), CV_16S ); Mat left = preFilteredImg0, right = preFilteredImg1; int mindisp = params.minDisparity; int ndisp = params.numDisparities; int width = left0.cols; int height = left0.rows; int lofs = std::max(ndisp - 1 + mindisp, 0); int rofs = -std::min(ndisp - 1 + mindisp, 0); int width1 = width - rofs - ndisp + 1; if( lofs >= width || rofs >= width || width1 < 1 ) { disp0 = Scalar::all( FILTERED * ( disp0.type() < CV_32F ? 1 : 1./(1 << DISPARITY_SHIFT) ) ); return; } Mat disp = disp0; if( dtype == CV_32F ) { dispbuf.create(disp0.size(), CV_16S); disp = dispbuf; } int wsz = params.SADWindowSize; int bufSize0 = (int)((ndisp + 2)*sizeof(int)); bufSize0 += (int)((height+wsz+2)*ndisp*sizeof(int)); bufSize0 += (int)((height + wsz + 2)*sizeof(int)); bufSize0 += (int)((height+wsz+2)*ndisp*(wsz+2)*sizeof(uchar) + 256); int bufSize1 = (int)((width + params.preFilterSize + 2) * sizeof(int) + 256); int bufSize2 = 0; if( params.speckleRange >= 0 && params.speckleWindowSize > 0 ) bufSize2 = width*height*(sizeof(Point_<short>) + sizeof(int) + sizeof(uchar)); #if CV_SSE2 bool useShorts = params.preFilterCap <= 31 && params.SADWindowSize <= 21 && checkHardwareSupport(CV_CPU_SSE2); #else const bool useShorts = false; #endif const double SAD_overhead_coeff = 10.0; double N0 = 8000000 / (useShorts ? 1 : 4); // approx tbb's min number instructions reasonable for one thread double maxStripeSize = std::min(std::max(N0 / (width * ndisp), (wsz-1) * SAD_overhead_coeff), (double)height); int nstripes = cvCeil(height / maxStripeSize); int bufSize = std::max(bufSize0 * nstripes, std::max(bufSize1 * 2, bufSize2)); if( slidingSumBuf.cols < bufSize ) slidingSumBuf.create( 1, bufSize, CV_8U ); uchar *_buf = slidingSumBuf.ptr(); parallel_for_(Range(0, 2), PrefilterInvoker(left0, right0, left, right, _buf, _buf + bufSize1, &params), 1); Rect validDisparityRect(0, 0, width, height), R1 = params.roi1, R2 = params.roi2; validDisparityRect = getValidDisparityROI(R1.area() > 0 ? Rect(0, 0, width, height) : validDisparityRect, R2.area() > 0 ? Rect(0, 0, width, height) : validDisparityRect, params.minDisparity, params.numDisparities, params.SADWindowSize); parallel_for_(Range(0, nstripes), FindStereoCorrespInvoker(left, right, disp, &params, nstripes, bufSize0, useShorts, validDisparityRect, slidingSumBuf, cost)); if( params.speckleRange >= 0 && params.speckleWindowSize > 0 ) filterSpeckles(disp, FILTERED, params.speckleWindowSize, params.speckleRange, slidingSumBuf); if (disp0.data != disp.data) disp.convertTo(disp0, disp0.type(), 1./(1 << DISPARITY_SHIFT), 0); } AlgorithmInfo* info() const { return 0; } int getMinDisparity() const { return params.minDisparity; } void setMinDisparity(int minDisparity) { params.minDisparity = minDisparity; } int getNumDisparities() const { return params.numDisparities; } void setNumDisparities(int numDisparities) { params.numDisparities = numDisparities; } int getBlockSize() const { return params.SADWindowSize; } void setBlockSize(int blockSize) { params.SADWindowSize = blockSize; } int getSpeckleWindowSize() const { return params.speckleWindowSize; } void setSpeckleWindowSize(int speckleWindowSize) { params.speckleWindowSize = speckleWindowSize; } int getSpeckleRange() const { return params.speckleRange; } void setSpeckleRange(int speckleRange) { params.speckleRange = speckleRange; } int getDisp12MaxDiff() const { return params.disp12MaxDiff; } void setDisp12MaxDiff(int disp12MaxDiff) { params.disp12MaxDiff = disp12MaxDiff; } int getPreFilterType() const { return params.preFilterType; } void setPreFilterType(int preFilterType) { params.preFilterType = preFilterType; } int getPreFilterSize() const { return params.preFilterSize; } void setPreFilterSize(int preFilterSize) { params.preFilterSize = preFilterSize; } int getPreFilterCap() const { return params.preFilterCap; } void setPreFilterCap(int preFilterCap) { params.preFilterCap = preFilterCap; } int getTextureThreshold() const { return params.textureThreshold; } void setTextureThreshold(int textureThreshold) { params.textureThreshold = textureThreshold; } int getUniquenessRatio() const { return params.uniquenessRatio; } void setUniquenessRatio(int uniquenessRatio) { params.uniquenessRatio = uniquenessRatio; } int getSmallerBlockSize() const { return 0; } void setSmallerBlockSize(int) {} Rect getROI1() const { return params.roi1; } void setROI1(Rect roi1) { params.roi1 = roi1; } Rect getROI2() const { return params.roi2; } void setROI2(Rect roi2) { params.roi2 = roi2; } void write(FileStorage& fs) const { fs << "name" << name_ << "minDisparity" << params.minDisparity << "numDisparities" << params.numDisparities << "blockSize" << params.SADWindowSize << "speckleWindowSize" << params.speckleWindowSize << "speckleRange" << params.speckleRange << "disp12MaxDiff" << params.disp12MaxDiff << "preFilterType" << params.preFilterType << "preFilterSize" << params.preFilterSize << "preFilterCap" << params.preFilterCap << "textureThreshold" << params.textureThreshold << "uniquenessRatio" << params.uniquenessRatio; } void read(const FileNode& fn) { FileNode n = fn["name"]; CV_Assert( n.isString() && String(n) == name_ ); params.minDisparity = (int)fn["minDisparity"]; params.numDisparities = (int)fn["numDisparities"]; params.SADWindowSize = (int)fn["blockSize"]; params.speckleWindowSize = (int)fn["speckleWindowSize"]; params.speckleRange = (int)fn["speckleRange"]; params.disp12MaxDiff = (int)fn["disp12MaxDiff"]; params.preFilterType = (int)fn["preFilterType"]; params.preFilterSize = (int)fn["preFilterSize"]; params.preFilterCap = (int)fn["preFilterCap"]; params.textureThreshold = (int)fn["textureThreshold"]; params.uniquenessRatio = (int)fn["uniquenessRatio"]; params.roi1 = params.roi2 = Rect(); } StereoBMParams params; Mat preFilteredImg0, preFilteredImg1, cost, dispbuf; Mat slidingSumBuf; static const char* name_; }; const char* StereoBMImpl::name_ = "StereoMatcher.BM"; Ptr<StereoBM> StereoBM::create(int _numDisparities, int _SADWindowSize) { return makePtr<StereoBMImpl>(_numDisparities, _SADWindowSize); } } /* End of file. */
apavlenko/opencv
modules/calib3d/src/stereobm.cpp
C++
bsd-3-clause
43,834
"use strict"; var mapnik = require('../'); var assert = require('assert'); var path = require('path'); mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'geojson.input')); describe('mapnik.Geometry ', function() { it('should throw with invalid usage', function() { // geometry cannot be created directly for now assert.throws(function() { mapnik.Geometry(); }); }); it('should access a geometry from a feature', function() { var feature = new mapnik.Feature(1); var point = { "type": "MultiPoint", "coordinates": [[0,0],[1,1]] }; var input = { type: "Feature", properties: {}, geometry: point }; var f = new mapnik.Feature.fromJSON(JSON.stringify(input)); var geom = f.geometry(); assert.equal(geom.type(),mapnik.Geometry.MultiPoint); assert.deepEqual(JSON.parse(geom.toJSONSync()),point); var expected_wkb = new Buffer('0104000000020000000101000000000000000000000000000000000000000101000000000000000000f03f000000000000f03f', 'hex'); assert.deepEqual(geom.toWKB(),expected_wkb); }); it('should fail on toJSON due to bad parameters', function() { var feature = new mapnik.Feature(1); var point = { "type": "MultiPoint", "coordinates": [[0,0],[1,1]] }; var input = { type: "Feature", properties: {}, geometry: point }; var f = new mapnik.Feature.fromJSON(JSON.stringify(input)); var geom = f.geometry(); assert.equal(geom.type(),mapnik.Geometry.MultiPoint); assert.throws(function() { geom.toJSONSync(null); }); assert.throws(function() { geom.toJSONSync({transform:null}); }); assert.throws(function() { geom.toJSONSync({transform:{}}); }); assert.throws(function() { geom.toJSON(null, function(err,json) {}); }); assert.throws(function() { geom.toJSON({transform:null}, function(err, json) {}); }); assert.throws(function() { geom.toJSON({transform:{}}, function(err, json) {}); }); }); it('should throw if we attempt to create a Feature from a geojson geometry (rather than geojson feature)', function() { var geometry = { type: 'Point', coordinates: [ 7.415119300000001, 43.730364300000005 ] }; // starts throwing, as expected, at Mapnik v3.0.9 (https://github.com/mapnik/node-mapnik/issues/560) if (mapnik.versions.mapnik_number >= 300009) { assert.throws(function() { var transformed = mapnik.Feature.fromJSON(JSON.stringify(geometry)); }); } }); it('should throw from empty geometry from toWKB', function() { var s = new mapnik.Feature(1); assert.throws(function() { var geom = s.geometry().toWKB(); }); }); });
langateam/node-mapnik
test/geometry.test.js
JavaScript
bsd-3-clause
2,955
<?php use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $model frontend\models\ManagerTrain */ $this->title = $model->id; $this->params['breadcrumbs'][] = ['label' => 'Manager Trains', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="manager-train-view"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?> <?= Html::a('Delete', ['delete', 'id' => $model->id], [ 'class' => 'btn btn-danger', 'data' => [ 'confirm' => 'Are you sure you want to delete this item?', 'method' => 'post', ], ]) ?> </p> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'id', 'rangkaian_fasiliti_awam', 'cat_id', 'location', 'state_id', 'district_id', 'mukim_id', 'sub_base_id', 'cluster_id', 'kampung_id', 'alamat', 'poskod', 'nama_pengurus', 'ic', 'jantina', 'no_fon', 'date_enter', 'enter_by', ], ]) ?> </div>
development2016/kds-dev
frontend/views/manager-train/view.php
PHP
bsd-3-clause
1,317
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2012-, Open Perception, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) 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. * * $Id: correspondence_estimation_backprojection.hpp 7230 2012-09-21 06:31:19Z rusu $ * */ #ifndef PCL_REGISTRATION_IMPL_CORRESPONDENCE_ESTIMATION_BACK_PROJECTION_HPP_ #define PCL_REGISTRATION_IMPL_CORRESPONDENCE_ESTIMATION_BACK_PROJECTION_HPP_ #include <pcl/registration/correspondence_estimation_normal_shooting.h> /////////////////////////////////////////////////////////////////////////////////////////// template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> bool pcl::registration::CorrespondenceEstimationBackProjection<PointSource, PointTarget, NormalT, Scalar>::initCompute () { if (!source_normals_ || !target_normals_) { PCL_WARN ("[pcl::registration::%s::initCompute] Datasets containing normals for source/target have not been given!\n", getClassName ().c_str ()); return (false); } return (CorrespondenceEstimationBase<PointSource, PointTarget, Scalar>::initCompute ()); } /////////////////////////////////////////////////////////////////////////////////////////// template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> void pcl::registration::CorrespondenceEstimationBackProjection<PointSource, PointTarget, NormalT, Scalar>::rotatePointCloudNormals ( const pcl::PointCloud<NormalT> &cloud_in, pcl::PointCloud<NormalT> &cloud_out, const Eigen::Matrix<Scalar, 4, 4> &transform) { if (&cloud_in != &cloud_out) { // Note: could be replaced by cloud_out = cloud_in cloud_out.header = cloud_in.header; cloud_out.width = cloud_in.width; cloud_out.height = cloud_in.height; cloud_out.is_dense = cloud_in.is_dense; cloud_out.points.reserve (cloud_out.points.size ()); cloud_out.points.assign (cloud_in.points.begin (), cloud_in.points.end ()); } for (size_t i = 0; i < cloud_out.points.size (); ++i) { // Rotate normals (WARNING: transform.rotation () uses SVD internally!) Eigen::Matrix<Scalar, 3, 1> nt (cloud_in[i].normal_x, cloud_in[i].normal_y, cloud_in[i].normal_z); cloud_out[i].normal_x = static_cast<float> (transform (0, 0) * nt.coeffRef (0) + transform (0, 1) * nt.coeffRef (1) + transform (0, 2) * nt.coeffRef (2)); cloud_out[i].normal_y = static_cast<float> (transform (1, 0) * nt.coeffRef (0) + transform (1, 1) * nt.coeffRef (1) + transform (1, 2) * nt.coeffRef (2)); cloud_out[i].normal_z = static_cast<float> (transform (2, 0) * nt.coeffRef (0) + transform (2, 1) * nt.coeffRef (1) + transform (2, 2) * nt.coeffRef (2)); } } /////////////////////////////////////////////////////////////////////////////////////////// template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> void pcl::registration::CorrespondenceEstimationBackProjection<PointSource, PointTarget, NormalT, Scalar>::determineCorrespondences ( pcl::Correspondences &correspondences, double max_distance) { if (!initCompute ()) return; typedef typename pcl::traits::fieldList<PointTarget>::type FieldListTarget; correspondences.resize (indices_->size ()); std::vector<int> nn_indices (k_); std::vector<float> nn_dists (k_); float min_dist = std::numeric_limits<float>::max (); int min_index = 0; pcl::Correspondence corr; unsigned int nr_valid_correspondences = 0; // Check if the template types are the same. If true, avoid a copy. // Both point types MUST be registered using the POINT_CLOUD_REGISTER_POINT_STRUCT macro! if (isSamePointType<PointSource, PointTarget> ()) { PointTarget pt; // Iterate over the input set of source indices for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i) { tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists); // Among the K nearest neighbours find the one with minimum perpendicular distance to the normal min_dist = std::numeric_limits<float>::max (); // Find the best correspondence for (size_t j = 0; j < nn_indices.size (); j++) { float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x + source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y + source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ; float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle); if (dist < min_dist) { min_dist = dist; min_index = static_cast<int> (j); } } if (min_dist > max_distance) continue; corr.index_query = *idx_i; corr.index_match = nn_indices[min_index]; corr.distance = nn_dists[min_index];//min_dist; correspondences[nr_valid_correspondences++] = corr; } } else { PointTarget pt; // Iterate over the input set of source indices for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i) { tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists); // Among the K nearest neighbours find the one with minimum perpendicular distance to the normal min_dist = std::numeric_limits<float>::max (); // Find the best correspondence for (size_t j = 0; j < nn_indices.size (); j++) { PointSource pt_src; // Copy the source data to a target PointTarget format so we can search in the tree pcl::for_each_type <FieldListTarget> (pcl::NdConcatenateFunctor <PointSource, PointTarget> ( input_->points[*idx_i], pt_src)); float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x + source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y + source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ; float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle); if (dist < min_dist) { min_dist = dist; min_index = static_cast<int> (j); } } if (min_dist > max_distance) continue; corr.index_query = *idx_i; corr.index_match = nn_indices[min_index]; corr.distance = nn_dists[min_index];//min_dist; correspondences[nr_valid_correspondences++] = corr; } } correspondences.resize (nr_valid_correspondences); deinitCompute (); } /////////////////////////////////////////////////////////////////////////////////////////// template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> void pcl::registration::CorrespondenceEstimationBackProjection<PointSource, PointTarget, NormalT, Scalar>::determineReciprocalCorrespondences ( pcl::Correspondences &correspondences, double max_distance) { if (!initCompute ()) return; typedef typename pcl::traits::fieldList<PointSource>::type FieldListSource; typedef typename pcl::traits::fieldList<PointTarget>::type FieldListTarget; typedef typename pcl::intersect<FieldListSource, FieldListTarget>::type FieldList; // setup tree for reciprocal search pcl::KdTreeFLANN<PointSource> tree_reciprocal; // Set the internal point representation of choice if (point_representation_) tree_reciprocal.setPointRepresentation (point_representation_); tree_reciprocal.setInputCloud (input_, indices_); correspondences.resize (indices_->size ()); std::vector<int> nn_indices (k_); std::vector<float> nn_dists (k_); std::vector<int> index_reciprocal (1); std::vector<float> distance_reciprocal (1); float min_dist = std::numeric_limits<float>::max (); int min_index = 0; pcl::Correspondence corr; unsigned int nr_valid_correspondences = 0; int target_idx = 0; // Check if the template types are the same. If true, avoid a copy. // Both point types MUST be registered using the POINT_CLOUD_REGISTER_POINT_STRUCT macro! if (isSamePointType<PointSource, PointTarget> ()) { PointTarget pt; // Iterate over the input set of source indices for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i) { tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists); // Among the K nearest neighbours find the one with minimum perpendicular distance to the normal min_dist = std::numeric_limits<float>::max (); // Find the best correspondence for (size_t j = 0; j < nn_indices.size (); j++) { float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x + source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y + source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ; float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle); if (dist < min_dist) { min_dist = dist; min_index = static_cast<int> (j); } } if (min_dist > max_distance) continue; // Check if the correspondence is reciprocal target_idx = nn_indices[min_index]; tree_reciprocal.nearestKSearch (target_->points[target_idx], 1, index_reciprocal, distance_reciprocal); if (*idx_i != index_reciprocal[0]) continue; corr.index_query = *idx_i; corr.index_match = nn_indices[min_index]; corr.distance = nn_dists[min_index];//min_dist; correspondences[nr_valid_correspondences++] = corr; } } else { PointTarget pt; // Iterate over the input set of source indices for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i) { tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists); // Among the K nearest neighbours find the one with minimum perpendicular distance to the normal min_dist = std::numeric_limits<float>::max (); // Find the best correspondence for (size_t j = 0; j < nn_indices.size (); j++) { PointSource pt_src; // Copy the source data to a target PointTarget format so we can search in the tree pcl::for_each_type <FieldListTarget> (pcl::NdConcatenateFunctor <PointSource, PointTarget> ( input_->points[*idx_i], pt_src)); float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x + source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y + source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ; float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle); if (dist < min_dist) { min_dist = dist; min_index = static_cast<int> (j); } } if (min_dist > max_distance) continue; // Check if the correspondence is reciprocal target_idx = nn_indices[min_index]; tree_reciprocal.nearestKSearch (target_->points[target_idx], 1, index_reciprocal, distance_reciprocal); if (*idx_i != index_reciprocal[0]) continue; corr.index_query = *idx_i; corr.index_match = nn_indices[min_index]; corr.distance = nn_dists[min_index];//min_dist; correspondences[nr_valid_correspondences++] = corr; } } correspondences.resize (nr_valid_correspondences); deinitCompute (); } #endif // PCL_REGISTRATION_IMPL_CORRESPONDENCE_ESTIMATION_BACK_PROJECTION_HPP_
kalectro/pcl_groovy
registration/include/pcl/registration/impl/correspondence_estimation_backprojection.hpp
C++
bsd-3-clause
13,583
package xcordion.impl.command; import junit.framework.TestCase; import junit.framework.Assert; import org.junit.Test; import org.junit.Ignore; public class ForEachCommandTest { @Test @Ignore public void testPlaceholder() { Assert.fail("WRITE ME"); } }
pobrelkey/xcordion
xcordion2/xcordion2-java/src/test/java/xcordion/impl/command/ForEachCommandTest.java
Java
bsd-3-clause
282
/*========================================================================= Program: Visualization Toolkit Module: vtkDataSetEdgeSubdivisionCriterion.h Language: C++ Copyright 2003 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive license for use of this work by or on behalf of the U.S. Government. Redistribution and use in source and binary forms, with or without modification, are permitted provided that this Notice and any statement of authorship are reproduced on all copies. =========================================================================*/ #ifndef vtkDataSetEdgeSubdivisionCriterion_h #define vtkDataSetEdgeSubdivisionCriterion_h // .NAME vtkDataSetEdgeSubdivisionCriterion - a subclass of vtkEdgeSubdivisionCriterion for vtkDataSet objects. // // .SECTION Description // This is a subclass of vtkEdgeSubdivisionCriterion that is used for // tessellating cells of a vtkDataSet, particularly nonlinear // cells. // // It provides functions for setting the current cell being tessellated and a // convenience routine, \a EvaluateFields() to evaluate field values at a // point. You should call \a EvaluateFields() from inside \a EvaluateEdge() // whenever the result of \a EvaluateEdge() will be true. Otherwise, do // not call \a EvaluateFields() as the midpoint is about to be discarded. // (<i>Implementor's note</i>: This isn't true if UGLY_ASPECT_RATIO_HACK // has been defined. But in that case, we don't want the exact field values; // we need the linearly interpolated ones at the midpoint for continuity.) // // .SECTION See Also // vtkEdgeSubdivisionCriterion #include "vtkFiltersCoreModule.h" // For export macro #include "vtkEdgeSubdivisionCriterion.h" class vtkCell; class vtkDataSet; class VTKFILTERSCORE_EXPORT vtkDataSetEdgeSubdivisionCriterion : public vtkEdgeSubdivisionCriterion { public: vtkTypeMacro(vtkDataSetEdgeSubdivisionCriterion,vtkEdgeSubdivisionCriterion); static vtkDataSetEdgeSubdivisionCriterion* New(); virtual void PrintSelf( ostream& os, vtkIndent indent ); virtual void SetMesh( vtkDataSet* ); vtkDataSet* GetMesh(); //BTX const vtkDataSet* GetMesh() const; //ETX virtual void SetCellId( vtkIdType cell ); vtkIdType GetCellId() const; //BTX vtkIdType& GetCellId(); //ETX vtkCell* GetCell(); //BTX const vtkCell* GetCell() const; //ETX virtual bool EvaluateEdge( const double* p0, double* midpt, const double* p1, int field_start ); // Description: // Evaluate all of the fields that should be output with the // given \a vertex and store them just past the parametric coordinates // of \a vertex, at the offsets given by // \p vtkEdgeSubdivisionCriterion::GetFieldOffsets() plus \a field_start. // \a field_start contains the number of world-space coordinates (always 3) // plus the embedding dimension (the size of the parameter-space in which // the cell is embedded). It will range between 3 and 6, inclusive. // // You must have called SetCellId() before calling this routine or there // will not be a mesh over which to evaluate the fields. // // You must have called \p vtkEdgeSubdivisionCriterion::PassDefaultFields() // or \p vtkEdgeSubdivisionCriterion::PassField() or there will be no fields // defined for the output vertex. // // This routine is public and returns its input argument so that it // may be used as an argument to // \p vtkStreamingTessellator::AdaptivelySamplekFacet(): // @verbatim // vtkStreamingTessellator* t = vtkStreamingTessellator::New(); // vtkEdgeSubdivisionCriterion* s; // ... // t->AdaptivelySample1Facet( s->EvaluateFields( p0 ), s->EvaluateFields( p1 ) ); // ... // @endverbatim // Although this will work, using \p EvaluateFields() in this manner // should be avoided. It's much more efficient to fetch the corner values // for each attribute and copy them into \a p0, \a p1, ... as opposed to // performing shape function evaluations. The only case where you wouldn't // want to do this is when the field you are interpolating is discontinuous // at cell borders, such as with a discontinuous galerkin method or when // all the Gauss points for quadrature are interior to the cell. // // The final argument, \a weights, is the array of weights to apply to each // point's data when interpolating the field. This is returned by // \a vtkCell::EvaluateLocation() when evaluating the geometry. double* EvaluateFields( double* vertex, double* weights, int field_start ); // Description: // Evaluate either a cell or nodal field. // This exists because of the funky way that Exodus data will be handled. // Sure, it's a hack, but what are ya gonna do? void EvaluatePointDataField( double* result, double* weights, int field ); void EvaluateCellDataField( double* result, double* weights, int field ); // Description: // Get/Set the square of the allowable chord error at any edge's midpoint. // This value is used by EvaluateEdge. vtkSetMacro(ChordError2,double); vtkGetMacro(ChordError2,double); // Description: // Get/Set the square of the allowable error magnitude for the // scalar field \a s at any edge's midpoint. // A value less than or equal to 0 indicates that the field // should not be used as a criterion for subdivision. virtual void SetFieldError2( int s, double err ); double GetFieldError2( int s ) const; // Description: // Tell the subdivider not to use any field values as subdivision criteria. // Effectively calls SetFieldError2( a, -1. ) for all fields. virtual void ResetFieldError2(); // Description: // Return a bitfield specifying which FieldError2 criteria are positive (i.e., actively // used to decide edge subdivisions). // This is stored as separate state to make subdivisions go faster. vtkGetMacro(ActiveFieldCriteria,int); int GetActiveFieldCriteria() const { return this->ActiveFieldCriteria; } protected: vtkDataSetEdgeSubdivisionCriterion(); virtual ~vtkDataSetEdgeSubdivisionCriterion(); vtkDataSet* CurrentMesh; vtkIdType CurrentCellId; vtkCell* CurrentCellData; double ChordError2; double* FieldError2; int FieldError2Length; int FieldError2Capacity; int ActiveFieldCriteria; private: vtkDataSetEdgeSubdivisionCriterion( const vtkDataSetEdgeSubdivisionCriterion& ); // Not implemented. void operator = ( const vtkDataSetEdgeSubdivisionCriterion& ); // Not implemented. }; //BTX inline vtkIdType& vtkDataSetEdgeSubdivisionCriterion::GetCellId() { return this->CurrentCellId; } inline vtkIdType vtkDataSetEdgeSubdivisionCriterion::GetCellId() const { return this->CurrentCellId; } inline vtkDataSet* vtkDataSetEdgeSubdivisionCriterion::GetMesh() { return this->CurrentMesh; } inline const vtkDataSet* vtkDataSetEdgeSubdivisionCriterion::GetMesh() const { return this->CurrentMesh; } inline vtkCell* vtkDataSetEdgeSubdivisionCriterion::GetCell() { return this->CurrentCellData; } inline const vtkCell* vtkDataSetEdgeSubdivisionCriterion::GetCell() const { return this->CurrentCellData; } //ETX #endif // vtkDataSetEdgeSubdivisionCriterion_h
hlzz/dotfiles
graphics/VTK-7.0.0/Filters/Core/vtkDataSetEdgeSubdivisionCriterion.h
C
bsd-3-clause
7,567
// Copyright 2015 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. package asm import ( "bufio" "bytes" "fmt" "io/ioutil" "os" "path/filepath" "regexp" "sort" "strconv" "strings" "testing" "cmd/asm/internal/lex" "cmd/internal/obj" "cmd/internal/objabi" ) // An end-to-end test for the assembler: Do we print what we parse? // Output is generated by, in effect, turning on -S and comparing the // result against a golden file. func testEndToEnd(t *testing.T, goarch, file string) { input := filepath.Join("testdata", file+".s") architecture, ctxt := setArch(goarch) architecture.Init(ctxt) lexer := lex.NewLexer(input) parser := NewParser(ctxt, architecture, lexer) pList := new(obj.Plist) var ok bool testOut = new(bytes.Buffer) // The assembler writes test output to this buffer. ctxt.Bso = bufio.NewWriter(os.Stdout) defer ctxt.Bso.Flush() failed := false ctxt.DiagFunc = func(format string, args ...interface{}) { failed = true t.Errorf(format, args...) } pList.Firstpc, ok = parser.Parse() if !ok || failed { t.Errorf("asm: %s assembly failed", goarch) return } output := strings.Split(testOut.String(), "\n") // Reconstruct expected output by independently "parsing" the input. data, err := ioutil.ReadFile(input) if err != nil { t.Error(err) return } lineno := 0 seq := 0 hexByLine := map[string]string{} lines := strings.SplitAfter(string(data), "\n") Diff: for _, line := range lines { lineno++ // Ignore include of textflag.h. if strings.HasPrefix(line, "#include ") { continue } // The general form of a test input line is: // // comment // INST args [// printed form] [// hex encoding] parts := strings.Split(line, "//") printed := strings.TrimSpace(parts[0]) if printed == "" || strings.HasSuffix(printed, ":") { // empty or label continue } seq++ var hexes string switch len(parts) { default: t.Errorf("%s:%d: unable to understand comments: %s", input, lineno, line) case 1: // no comment case 2: // might be printed form or hex note := strings.TrimSpace(parts[1]) if isHexes(note) { hexes = note } else { printed = note } case 3: // printed form, then hex printed = strings.TrimSpace(parts[1]) hexes = strings.TrimSpace(parts[2]) if !isHexes(hexes) { t.Errorf("%s:%d: malformed hex instruction encoding: %s", input, lineno, line) } } if hexes != "" { hexByLine[fmt.Sprintf("%s:%d", input, lineno)] = hexes } // Canonicalize spacing in printed form. // First field is opcode, then tab, then arguments separated by spaces. // Canonicalize spaces after commas first. // Comma to separate argument gets a space; comma within does not. var buf []byte nest := 0 for i := 0; i < len(printed); i++ { c := printed[i] switch c { case '{', '[': nest++ case '}', ']': nest-- case ',': buf = append(buf, ',') if nest == 0 { buf = append(buf, ' ') } for i+1 < len(printed) && (printed[i+1] == ' ' || printed[i+1] == '\t') { i++ } continue } buf = append(buf, c) } f := strings.Fields(string(buf)) // Turn relative (PC) into absolute (PC) automatically, // so that most branch instructions don't need comments // giving the absolute form. if len(f) > 0 && strings.HasSuffix(printed, "(PC)") { last := f[len(f)-1] n, err := strconv.Atoi(last[:len(last)-len("(PC)")]) if err == nil { f[len(f)-1] = fmt.Sprintf("%d(PC)", seq+n) } } if len(f) == 1 { printed = f[0] } else { printed = f[0] + "\t" + strings.Join(f[1:], " ") } want := fmt.Sprintf("%05d (%s:%d)\t%s", seq, input, lineno, printed) for len(output) > 0 && (output[0] < want || output[0] != want && len(output[0]) >= 5 && output[0][:5] == want[:5]) { if len(output[0]) >= 5 && output[0][:5] == want[:5] { t.Errorf("mismatched output:\nhave %s\nwant %s", output[0], want) output = output[1:] continue Diff } t.Errorf("unexpected output: %q", output[0]) output = output[1:] } if len(output) > 0 && output[0] == want { output = output[1:] } else { t.Errorf("missing output: %q", want) } } for len(output) > 0 { if output[0] == "" { // spurious blank caused by Split on "\n" output = output[1:] continue } t.Errorf("unexpected output: %q", output[0]) output = output[1:] } // Checked printing. // Now check machine code layout. top := pList.Firstpc var text *obj.LSym ok = true ctxt.DiagFunc = func(format string, args ...interface{}) { t.Errorf(format, args...) ok = false } obj.Flushplist(ctxt, pList, nil, "") for p := top; p != nil; p = p.Link { if p.As == obj.ATEXT { text = p.From.Sym } hexes := hexByLine[p.Line()] if hexes == "" { continue } delete(hexByLine, p.Line()) if text == nil { t.Errorf("%s: instruction outside TEXT", p) } size := int64(len(text.P)) - p.Pc if p.Link != nil { size = p.Link.Pc - p.Pc } else if p.Isize != 0 { size = int64(p.Isize) } var code []byte if p.Pc < int64(len(text.P)) { code = text.P[p.Pc:] if size < int64(len(code)) { code = code[:size] } } codeHex := fmt.Sprintf("%x", code) if codeHex == "" { codeHex = "empty" } ok := false for _, hex := range strings.Split(hexes, " or ") { if codeHex == hex { ok = true break } } if !ok { t.Errorf("%s: have encoding %s, want %s", p, codeHex, hexes) } } if len(hexByLine) > 0 { var missing []string for key := range hexByLine { missing = append(missing, key) } sort.Strings(missing) for _, line := range missing { t.Errorf("%s: did not find instruction encoding", line) } } } func isHexes(s string) bool { if s == "" { return false } if s == "empty" { return true } for _, f := range strings.Split(s, " or ") { if f == "" || len(f)%2 != 0 || strings.TrimLeft(f, "0123456789abcdef") != "" { return false } } return true } // It would be nice if the error messages began with // the standard file:line: prefix, // but that's not where we are today. // It might be at the beginning but it might be in the middle of the printed instruction. var fileLineRE = regexp.MustCompile(`(?:^|\()(testdata[/\\][0-9a-z]+\.s:[0-9]+)(?:$|\))`) // Same as in test/run.go var ( errRE = regexp.MustCompile(`// ERROR ?(.*)`) errQuotesRE = regexp.MustCompile(`"([^"]*)"`) ) func testErrors(t *testing.T, goarch, file string) { input := filepath.Join("testdata", file+".s") architecture, ctxt := setArch(goarch) lexer := lex.NewLexer(input) parser := NewParser(ctxt, architecture, lexer) pList := new(obj.Plist) var ok bool testOut = new(bytes.Buffer) // The assembler writes test output to this buffer. ctxt.Bso = bufio.NewWriter(os.Stdout) defer ctxt.Bso.Flush() failed := false var errBuf bytes.Buffer ctxt.DiagFunc = func(format string, args ...interface{}) { failed = true s := fmt.Sprintf(format, args...) if !strings.HasSuffix(s, "\n") { s += "\n" } errBuf.WriteString(s) } pList.Firstpc, ok = parser.Parse() obj.Flushplist(ctxt, pList, nil, "") if ok && !failed { t.Errorf("asm: %s had no errors", goarch) } errors := map[string]string{} for _, line := range strings.Split(errBuf.String(), "\n") { if line == "" || strings.HasPrefix(line, "\t") { continue } m := fileLineRE.FindStringSubmatch(line) if m == nil { t.Errorf("unexpected error: %v", line) continue } fileline := m[1] if errors[fileline] != "" && errors[fileline] != line { t.Errorf("multiple errors on %s:\n\t%s\n\t%s", fileline, errors[fileline], line) continue } errors[fileline] = line } // Reconstruct expected errors by independently "parsing" the input. data, err := ioutil.ReadFile(input) if err != nil { t.Error(err) return } lineno := 0 lines := strings.Split(string(data), "\n") for _, line := range lines { lineno++ fileline := fmt.Sprintf("%s:%d", input, lineno) if m := errRE.FindStringSubmatch(line); m != nil { all := m[1] mm := errQuotesRE.FindAllStringSubmatch(all, -1) if len(mm) != 1 { t.Errorf("%s: invalid errorcheck line:\n%s", fileline, line) } else if err := errors[fileline]; err == "" { t.Errorf("%s: missing error, want %s", fileline, all) } else if !strings.Contains(err, mm[0][1]) { t.Errorf("%s: wrong error for %s:\n%s", fileline, all, err) } } else { if errors[fileline] != "" { t.Errorf("unexpected error on %s: %v", fileline, errors[fileline]) } } delete(errors, fileline) } var extra []string for key := range errors { extra = append(extra, key) } sort.Strings(extra) for _, fileline := range extra { t.Errorf("unexpected error on %s: %v", fileline, errors[fileline]) } } func Test386EndToEnd(t *testing.T) { defer func(old string) { objabi.GO386 = old }(objabi.GO386) for _, go386 := range []string{"387", "sse2"} { t.Logf("GO386=%v", go386) objabi.GO386 = go386 testEndToEnd(t, "386", "386") } } func TestARMEndToEnd(t *testing.T) { defer func(old int) { objabi.GOARM = old }(objabi.GOARM) for _, goarm := range []int{5, 6, 7} { t.Logf("GOARM=%d", goarm) objabi.GOARM = goarm testEndToEnd(t, "arm", "arm") if goarm == 6 { testEndToEnd(t, "arm", "armv6") } } } func TestARMErrors(t *testing.T) { testErrors(t, "arm", "armerror") } func TestARM64EndToEnd(t *testing.T) { testEndToEnd(t, "arm64", "arm64") } func TestARM64Encoder(t *testing.T) { testEndToEnd(t, "arm64", "arm64enc") } func TestARM64Errors(t *testing.T) { testErrors(t, "arm64", "arm64error") } func TestAMD64EndToEnd(t *testing.T) { testEndToEnd(t, "amd64", "amd64") } func Test386Encoder(t *testing.T) { testEndToEnd(t, "386", "386enc") } func TestAMD64Encoder(t *testing.T) { testEndToEnd(t, "amd64", "amd64enc") testEndToEnd(t, "amd64", "amd64enc_extra") } func TestAMD64Errors(t *testing.T) { testErrors(t, "amd64", "amd64error") } func TestMIPSEndToEnd(t *testing.T) { testEndToEnd(t, "mips", "mips") testEndToEnd(t, "mips64", "mips64") } func TestPPC64EndToEnd(t *testing.T) { testEndToEnd(t, "ppc64", "ppc64") } func TestPPC64Encoder(t *testing.T) { testEndToEnd(t, "ppc64", "ppc64enc") } func TestS390XEndToEnd(t *testing.T) { testEndToEnd(t, "s390x", "s390x") }
Cofyc/go
src/cmd/asm/internal/asm/endtoend_test.go
GO
bsd-3-clause
10,355
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/app/android/chrome_jni_onload.h" #include "chrome/app/android/chrome_android_initializer.h" #include "content/public/app/content_jni_onload.h" namespace android { bool OnJNIOnLoadInit() { if (!content::android::OnJNIOnLoadInit()) return false; return RunChrome(); } } // namespace android
endlessm/chromium-browser
chrome/app/android/chrome_jni_onload.cc
C++
bsd-3-clause
490
package ch.epfl.lamp.slick.direct import org.scalatest.FlatSpec import slick.driver.H2Driver.api._ class ProblemSpec extends FlatSpec with TestHelper { // TODO: WIP }
olafurpg/slick-direct
slick-direct/src/test/scala/ch/epfl/lamp/slick/direct/ProblemSpec.scala
Scala
bsd-3-clause
172
/* * ctm-cvb * * CollapsedBayesEngine */ #ifndef COLLAPSED_BAYES_ENGINE_H #define COLLAPSED_BAYES_ENGINE_H #include "InferenceEngine.h" #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> namespace ctm { class CollapsedBayesEngine : public InferenceEngine { /*** * Model hyperparameters learnt by maximisation */ struct Model { gsl_vector* mu; gsl_matrix* cov; gsl_matrix* inv_cov; gsl_matrix* log_beta; double gamma; double log_det_inv_cov; Model( int D, int K, int V ); ~Model(); }; /*** * Data collected in the 'expectation' step, to be used in the * maximisation step. */ struct CollectedData { // Expected counts gsl_matrix* n_ij; gsl_matrix* n_jk; double ndata; CollectedData( int D, int K, int V ); ~CollectedData(); }; /*** * Variational parameters to be optimised in the expectation step */ struct Parameters { // Stores \phi_{*kj} gsl_matrix* phi; gsl_matrix* log_phi; // Likelihood saved for optimisation purposes double lhood; Parameters( int K, int V ); ~Parameters(); }; public: CollapsedBayesEngine(InferenceOptions& options); // Load/Store in a file virtual void init( string filename ); virtual void save( string filename ); // Parse a single file virtual double infer( Corpus& data ); virtual double infer( Corpus& data, CollectedData* cd ); virtual void estimate( Corpus& data ); protected: Model* model; }; }; #endif // COLLAPSED_BAYES_ENGINE_H
arunchaganty/ctm-cvb
include/CollapsedBayesEngine.h
C
bsd-3-clause
1,922
isPrime :: Integral a => a -> Bool isPrime 2 = True isPrime 3 = True isPrime n = all (\ x -> x /= 0) [n `mod` x | x <- [2..(truncate $ sqrt (fromIntegral n) + 1)]] goldbach :: (Integral t, Integral t1) => t1 -> (t, t1) goldbach n = goldbach' 3 (n - 3) where goldbach' a b | isPrime a && isPrime b = (a, b) | otherwise = goldbach' (a + 2) (b - 2)
m00nlight/99-problems
haskell/p-40.hs
Haskell
bsd-3-clause
403
/** * Copyright (c) 2013, Yahoo! Inc. All rights reserved. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms */ package visualoozie.api; public class WorkflowNode { public enum NodeType{ START , KILL , DECISION , FORK , JOIN , END , ACTION } private String name; private NodeType type; private String[] to; public String getName() { return name; } public void setName(String name) { this.name = name; } public NodeType getType() { return type; } public void setType(NodeType type) { this.type = type; } public String[] getTo() { return to; } public void setTo(String[] to) { this.to = to; } }
jaoki/visualoozie
src/main/java/visualoozie/api/WorkflowNode.java
Java
bsd-3-clause
747
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__char_file_execl_43.cpp Label Definition File: CWE78_OS_Command_Injection.strings.label.xml Template File: sources-sink-43.tmpl.cpp */ /* * @description * CWE: 78 OS Command Injection * BadSource: file Read input from a file * GoodSource: Fixed string * Sinks: execl * BadSink : execute command with execl * Flow Variant: 43 Data flow: data flows using a C++ reference from one function to another in the same source file * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 #define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe" #define COMMAND_INT "cmd.exe" #define COMMAND_ARG1 "/c" #define COMMAND_ARG2 "dir " #define COMMAND_ARG3 data #else /* NOT _WIN32 */ #include <unistd.h> #define COMMAND_INT_PATH "/bin/sh" #define COMMAND_INT "sh" #define COMMAND_ARG1 "-c" #define COMMAND_ARG2 "ls " #define COMMAND_ARG3 data #endif #ifdef _WIN32 #define FILENAME "C:\\temp\\file.txt" #else #define FILENAME "/tmp/file.txt" #endif #ifdef _WIN32 #include <process.h> #define EXECL _execl #else /* NOT _WIN32 */ #define EXECL execl #endif namespace CWE78_OS_Command_Injection__char_file_execl_43 { #ifndef OMITBAD static void badSource(char * &data) { { /* Read input from a file */ size_t dataLen = strlen(data); FILE * pFile; /* if there is room in data, attempt to read the input from a file */ if (100-dataLen > 1) { pFile = fopen(FILENAME, "r"); if (pFile != NULL) { /* POTENTIAL FLAW: Read data from a file */ if (fgets(data+dataLen, (int)(100-dataLen), pFile) == NULL) { printLine("fgets() failed"); /* Restore NUL terminator if fgets fails */ data[dataLen] = '\0'; } fclose(pFile); } } } } void bad() { char * data; char dataBuffer[100] = COMMAND_ARG2; data = dataBuffer; badSource(data); /* execl - specify the path where the command is located */ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2BSource(char * &data) { /* FIX: Append a fixed string to data (not user / external input) */ strcat(data, "*.*"); } static void goodG2B() { char * data; char dataBuffer[100] = COMMAND_ARG2; data = dataBuffer; goodG2BSource(data); /* execl - specify the path where the command is located */ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE78_OS_Command_Injection__char_file_execl_43; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE78_OS_Command_Injection/s03/CWE78_OS_Command_Injection__char_file_execl_43.cpp
C++
bsd-3-clause
3,945
INSTALL_DIR=usr/local/lib DEPS="coreutils" "sudo" REBARPROFILE ?= default include ../../config.mk include ../../_build/${REBARPROFILE}/lib/fifo_utils/priv/pkgng.mk .PHONY: prepare prepare: -rm -r $(STAGE_DIR)/$(INSTALL_DIR)/$(COMPONENT_INTERNAL) -rm $(STAGE_DIR)/+* -rm $(STAGE_DIR)/plist mkdir -p $(STAGE_DIR)/$(INSTALL_DIR) cp -r ../../_build/${REBARPROFILE}/rel/$(COMPONENT_INTERNAL) $(STAGE_DIR)/$(INSTALL_DIR)/$(COMPONENT_INTERNAL)
project-fifo/fifo-zlogin
rel/pkgng/Makefile
Makefile
bsd-3-clause
447
/*- * Copyright (c) 1996-1999 * Kazutaka YOKOTA ([email protected]) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. * * $Id: atkbdc.c,v 1.1 1999/01/09 02:44:50 yokota Exp $ * from kbdio.c,v 1.13 1998/09/25 11:55:46 yokota Exp */ #include "atkbdc.h" #include "opt_kbd.h" #include <sys/param.h> #include <sys/systm.h> #include <sys/kernel.h> #include <sys/malloc.h> #include <sys/syslog.h> #include <machine/clock.h> #include <dev/kbd/atkbdcreg.h> #ifndef __i386__ #include <isa/isareg.h> #else #include <i386/isa/isa.h> #endif /* constants */ #define MAXKBDC MAX(NATKBDC, 1) /* macros */ #ifndef MAX #define MAX(x, y) ((x) > (y) ? (x) : (y)) #endif #define kbdcp(p) ((atkbdc_softc_t *)(p)) #define nextq(i) (((i) + 1) % KBDQ_BUFSIZE) #define availq(q) ((q)->head != (q)->tail) #if KBDIO_DEBUG >= 2 #define emptyq(q) ((q)->tail = (q)->head = (q)->qcount = 0) #else #define emptyq(q) ((q)->tail = (q)->head = 0) #endif /* local variables */ /* * We always need at least one copy of the kbdc_softc struct for the * low-level console. As the low-level console accesses the keyboard * controller before kbdc, and all other devices, is probed, we * statically allocate one entry. XXX */ static atkbdc_softc_t default_kbdc; static atkbdc_softc_t *atkbdc_softc[MAXKBDC] = { &default_kbdc }; static int verbose = KBDIO_DEBUG; /* function prototypes */ static int atkbdc_setup(atkbdc_softc_t *sc, int port); static int addq(kqueue *q, int c); static int removeq(kqueue *q); static int wait_while_controller_busy(atkbdc_softc_t *kbdc); static int wait_for_data(atkbdc_softc_t *kbdc); static int wait_for_kbd_data(atkbdc_softc_t *kbdc); static int wait_for_kbd_ack(atkbdc_softc_t *kbdc); static int wait_for_aux_data(atkbdc_softc_t *kbdc); static int wait_for_aux_ack(atkbdc_softc_t *kbdc); #if NATKBDC > 0 atkbdc_softc_t *atkbdc_get_softc(int unit) { atkbdc_softc_t *sc; if (unit >= sizeof(atkbdc_softc)/sizeof(atkbdc_softc[0])) return NULL; sc = atkbdc_softc[unit]; if (sc == NULL) { sc = atkbdc_softc[unit] = malloc(sizeof(*sc), M_DEVBUF, M_NOWAIT); if (sc == NULL) return NULL; bzero(sc, sizeof(*sc)); sc->port = -1; /* XXX */ } return sc; } int atkbdc_probe_unit(atkbdc_softc_t *sc, int unit, int port) { return atkbdc_setup(sc, port); } #endif /* NATKBDC > 0 */ /* the backdoor to the keyboard controller! XXX */ int atkbdc_configure(void) { return atkbdc_setup(atkbdc_softc[0], -1); } static int atkbdc_setup(atkbdc_softc_t *sc, int port) { if (port <= 0) port = IO_KBD; if (sc->port <= 0) { sc->command_byte = -1; sc->command_mask = 0; sc->lock = FALSE; sc->kbd.head = sc->kbd.tail = 0; sc->aux.head = sc->aux.tail = 0; #if KBDIO_DEBUG >= 2 sc->kbd.call_count = 0; sc->kbd.qcount = sc->kbd.max_qcount = 0; sc->aux.call_count = 0; sc->aux.qcount = sc->aux.max_qcount = 0; #endif } sc->port = port; /* may override the previous value */ return 0; } /* associate a port number with a KBDC */ KBDC kbdc_open(int port) { int s; int i; if (port <= 0) port = IO_KBD; s = spltty(); for (i = 0; i < sizeof(atkbdc_softc)/sizeof(atkbdc_softc[0]); ++i) { if (atkbdc_softc[i] == NULL) continue; if (atkbdc_softc[i]->port == port) { splx(s); return (KBDC)atkbdc_softc[i]; } if (atkbdc_softc[i]->port <= 0) { if (atkbdc_setup(atkbdc_softc[i], port)) break; splx(s); return (KBDC)atkbdc_softc[i]; } } splx(s); return NULL; } /* * I/O access arbitration in `kbdio' * * The `kbdio' module uses a simplistic convention to arbitrate * I/O access to the controller/keyboard/mouse. The convention requires * close cooperation of the calling device driver. * * The device driver which utilizes the `kbdio' module are assumed to * have the following set of routines. * a. An interrupt handler (the bottom half of the driver). * b. Timeout routines which may briefly polls the keyboard controller. * c. Routines outside interrupt context (the top half of the driver). * They should follow the rules below: * 1. The interrupt handler may assume that it always has full access * to the controller/keyboard/mouse. * 2. The other routines must issue `spltty()' if they wish to * prevent the interrupt handler from accessing * the controller/keyboard/mouse. * 3. The timeout routines and the top half routines of the device driver * arbitrate I/O access by observing the lock flag in `kbdio'. * The flag is manipulated via `kbdc_lock()'; when one wants to * perform I/O, call `kbdc_lock(kbdc, TRUE)' and proceed only if * the call returns with TRUE. Otherwise the caller must back off. * Call `kbdc_lock(kbdc, FALSE)' when necessary I/O operaion * is finished. This mechanism does not prevent the interrupt * handler from being invoked at any time and carrying out I/O. * Therefore, `spltty()' must be strategically placed in the device * driver code. Also note that the timeout routine may interrupt * `kbdc_lock()' called by the top half of the driver, but this * interruption is OK so long as the timeout routine observes the * the rule 4 below. * 4. The interrupt and timeout routines should not extend I/O operation * across more than one interrupt or timeout; they must complete * necessary I/O operation within one invokation of the routine. * This measns that if the timeout routine acquires the lock flag, * it must reset the flag to FALSE before it returns. */ /* set/reset polling lock */ int kbdc_lock(KBDC p, int lock) { int prevlock; prevlock = kbdcp(p)->lock; kbdcp(p)->lock = lock; return (prevlock != lock); } /* check if any data is waiting to be processed */ int kbdc_data_ready(KBDC p) { return (availq(&kbdcp(p)->kbd) || availq(&kbdcp(p)->aux) || (inb(kbdcp(p)->port + KBD_STATUS_PORT) & KBDS_ANY_BUFFER_FULL)); } /* queuing functions */ static int addq(kqueue *q, int c) { if (nextq(q->tail) != q->head) { q->q[q->tail] = c; q->tail = nextq(q->tail); #if KBDIO_DEBUG >= 2 ++q->call_count; ++q->qcount; if (q->qcount > q->max_qcount) q->max_qcount = q->qcount; #endif return TRUE; } return FALSE; } static int removeq(kqueue *q) { int c; if (q->tail != q->head) { c = q->q[q->head]; q->head = nextq(q->head); #if KBDIO_DEBUG >= 2 --q->qcount; #endif return c; } return -1; } /* * device I/O routines */ static int wait_while_controller_busy(struct atkbdc_softc *kbdc) { /* CPU will stay inside the loop for 100msec at most */ int retry = 5000; int port = kbdc->port; int f; while ((f = inb(port + KBD_STATUS_PORT)) & KBDS_INPUT_BUFFER_FULL) { if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); addq(&kbdc->kbd, inb(port + KBD_DATA_PORT)); } else if ((f & KBDS_BUFFER_FULL) == KBDS_AUX_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); addq(&kbdc->aux, inb(port + KBD_DATA_PORT)); } DELAY(KBDC_DELAYTIME); if (--retry < 0) return FALSE; } return TRUE; } /* * wait for any data; whether it's from the controller, * the keyboard, or the aux device. */ static int wait_for_data(struct atkbdc_softc *kbdc) { /* CPU will stay inside the loop for 200msec at most */ int retry = 10000; int port = kbdc->port; int f; while ((f = inb(port + KBD_STATUS_PORT) & KBDS_ANY_BUFFER_FULL) == 0) { DELAY(KBDC_DELAYTIME); if (--retry < 0) return 0; } DELAY(KBDD_DELAYTIME); return f; } /* wait for data from the keyboard */ static int wait_for_kbd_data(struct atkbdc_softc *kbdc) { /* CPU will stay inside the loop for 200msec at most */ int retry = 10000; int port = kbdc->port; int f; while ((f = inb(port + KBD_STATUS_PORT) & KBDS_BUFFER_FULL) != KBDS_KBD_BUFFER_FULL) { if (f == KBDS_AUX_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); addq(&kbdc->aux, inb(port + KBD_DATA_PORT)); } DELAY(KBDC_DELAYTIME); if (--retry < 0) return 0; } DELAY(KBDD_DELAYTIME); return f; } /* * wait for an ACK(FAh), RESEND(FEh), or RESET_FAIL(FCh) from the keyboard. * queue anything else. */ static int wait_for_kbd_ack(struct atkbdc_softc *kbdc) { /* CPU will stay inside the loop for 200msec at most */ int retry = 10000; int port = kbdc->port; int f; int b; while (retry-- > 0) { if ((f = inb(port + KBD_STATUS_PORT)) & KBDS_ANY_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); b = inb(port + KBD_DATA_PORT); if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) { if ((b == KBD_ACK) || (b == KBD_RESEND) || (b == KBD_RESET_FAIL)) return b; addq(&kbdc->kbd, b); } else if ((f & KBDS_BUFFER_FULL) == KBDS_AUX_BUFFER_FULL) { addq(&kbdc->aux, b); } } DELAY(KBDC_DELAYTIME); } return -1; } /* wait for data from the aux device */ static int wait_for_aux_data(struct atkbdc_softc *kbdc) { /* CPU will stay inside the loop for 200msec at most */ int retry = 10000; int port = kbdc->port; int f; while ((f = inb(port + KBD_STATUS_PORT) & KBDS_BUFFER_FULL) != KBDS_AUX_BUFFER_FULL) { if (f == KBDS_KBD_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); addq(&kbdc->kbd, inb(port + KBD_DATA_PORT)); } DELAY(KBDC_DELAYTIME); if (--retry < 0) return 0; } DELAY(KBDD_DELAYTIME); return f; } /* * wait for an ACK(FAh), RESEND(FEh), or RESET_FAIL(FCh) from the aux device. * queue anything else. */ static int wait_for_aux_ack(struct atkbdc_softc *kbdc) { /* CPU will stay inside the loop for 200msec at most */ int retry = 10000; int port = kbdc->port; int f; int b; while (retry-- > 0) { if ((f = inb(port + KBD_STATUS_PORT)) & KBDS_ANY_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); b = inb(port + KBD_DATA_PORT); if ((f & KBDS_BUFFER_FULL) == KBDS_AUX_BUFFER_FULL) { if ((b == PSM_ACK) || (b == PSM_RESEND) || (b == PSM_RESET_FAIL)) return b; addq(&kbdc->aux, b); } else if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) { addq(&kbdc->kbd, b); } } DELAY(KBDC_DELAYTIME); } return -1; } /* write a one byte command to the controller */ int write_controller_command(KBDC p, int c) { if (!wait_while_controller_busy(kbdcp(p))) return FALSE; outb(kbdcp(p)->port + KBD_COMMAND_PORT, c); return TRUE; } /* write a one byte data to the controller */ int write_controller_data(KBDC p, int c) { if (!wait_while_controller_busy(kbdcp(p))) return FALSE; outb(kbdcp(p)->port + KBD_DATA_PORT, c); return TRUE; } /* write a one byte keyboard command */ int write_kbd_command(KBDC p, int c) { if (!wait_while_controller_busy(kbdcp(p))) return FALSE; outb(kbdcp(p)->port + KBD_DATA_PORT, c); return TRUE; } /* write a one byte auxiliary device command */ int write_aux_command(KBDC p, int c) { if (!write_controller_command(p, KBDC_WRITE_TO_AUX)) return FALSE; return write_controller_data(p, c); } /* send a command to the keyboard and wait for ACK */ int send_kbd_command(KBDC p, int c) { int retry = KBD_MAXRETRY; int res = -1; while (retry-- > 0) { if (!write_kbd_command(p, c)) continue; res = wait_for_kbd_ack(kbdcp(p)); if (res == KBD_ACK) break; } return res; } /* send a command to the auxiliary device and wait for ACK */ int send_aux_command(KBDC p, int c) { int retry = KBD_MAXRETRY; int res = -1; while (retry-- > 0) { if (!write_aux_command(p, c)) continue; /* * FIXME: XXX * The aux device may have already sent one or two bytes of * status data, when a command is received. It will immediately * stop data transmission, thus, leaving an incomplete data * packet in our buffer. We have to discard any unprocessed * data in order to remove such packets. Well, we may remove * unprocessed, but necessary data byte as well... */ emptyq(&kbdcp(p)->aux); res = wait_for_aux_ack(kbdcp(p)); if (res == PSM_ACK) break; } return res; } /* send a command and a data to the keyboard, wait for ACKs */ int send_kbd_command_and_data(KBDC p, int c, int d) { int retry; int res = -1; for (retry = KBD_MAXRETRY; retry > 0; --retry) { if (!write_kbd_command(p, c)) continue; res = wait_for_kbd_ack(kbdcp(p)); if (res == KBD_ACK) break; else if (res != KBD_RESEND) return res; } if (retry <= 0) return res; for (retry = KBD_MAXRETRY, res = -1; retry > 0; --retry) { if (!write_kbd_command(p, d)) continue; res = wait_for_kbd_ack(kbdcp(p)); if (res != KBD_RESEND) break; } return res; } /* send a command and a data to the auxiliary device, wait for ACKs */ int send_aux_command_and_data(KBDC p, int c, int d) { int retry; int res = -1; for (retry = KBD_MAXRETRY; retry > 0; --retry) { if (!write_aux_command(p, c)) continue; emptyq(&kbdcp(p)->aux); res = wait_for_aux_ack(kbdcp(p)); if (res == PSM_ACK) break; else if (res != PSM_RESEND) return res; } if (retry <= 0) return res; for (retry = KBD_MAXRETRY, res = -1; retry > 0; --retry) { if (!write_aux_command(p, d)) continue; res = wait_for_aux_ack(kbdcp(p)); if (res != PSM_RESEND) break; } return res; } /* * read one byte from any source; whether from the controller, * the keyboard, or the aux device */ int read_controller_data(KBDC p) { if (availq(&kbdcp(p)->kbd)) return removeq(&kbdcp(p)->kbd); if (availq(&kbdcp(p)->aux)) return removeq(&kbdcp(p)->aux); if (!wait_for_data(kbdcp(p))) return -1; /* timeout */ return inb(kbdcp(p)->port + KBD_DATA_PORT); } #if KBDIO_DEBUG >= 2 static int call = 0; #endif /* read one byte from the keyboard */ int read_kbd_data(KBDC p) { #if KBDIO_DEBUG >= 2 if (++call > 2000) { call = 0; log(LOG_DEBUG, "kbdc: kbd q: %d calls, max %d chars, " "aux q: %d calls, max %d chars\n", kbdcp(p)->kbd.call_count, kbdcp(p)->kbd.max_qcount, kbdcp(p)->aux.call_count, kbdcp(p)->aux.max_qcount); } #endif if (availq(&kbdcp(p)->kbd)) return removeq(&kbdcp(p)->kbd); if (!wait_for_kbd_data(kbdcp(p))) return -1; /* timeout */ return inb(kbdcp(p)->port + KBD_DATA_PORT); } /* read one byte from the keyboard, but return immediately if * no data is waiting */ int read_kbd_data_no_wait(KBDC p) { int f; #if KBDIO_DEBUG >= 2 if (++call > 2000) { call = 0; log(LOG_DEBUG, "kbdc: kbd q: %d calls, max %d chars, " "aux q: %d calls, max %d chars\n", kbdcp(p)->kbd.call_count, kbdcp(p)->kbd.max_qcount, kbdcp(p)->aux.call_count, kbdcp(p)->aux.max_qcount); } #endif if (availq(&kbdcp(p)->kbd)) return removeq(&kbdcp(p)->kbd); f = inb(kbdcp(p)->port + KBD_STATUS_PORT) & KBDS_BUFFER_FULL; if (f == KBDS_AUX_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); addq(&kbdcp(p)->aux, inb(kbdcp(p)->port + KBD_DATA_PORT)); f = inb(kbdcp(p)->port + KBD_STATUS_PORT) & KBDS_BUFFER_FULL; } if (f == KBDS_KBD_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); return inb(kbdcp(p)->port + KBD_DATA_PORT); } return -1; /* no data */ } /* read one byte from the aux device */ int read_aux_data(KBDC p) { if (availq(&kbdcp(p)->aux)) return removeq(&kbdcp(p)->aux); if (!wait_for_aux_data(kbdcp(p))) return -1; /* timeout */ return inb(kbdcp(p)->port + KBD_DATA_PORT); } /* read one byte from the aux device, but return immediately if * no data is waiting */ int read_aux_data_no_wait(KBDC p) { int f; if (availq(&kbdcp(p)->aux)) return removeq(&kbdcp(p)->aux); f = inb(kbdcp(p)->port + KBD_STATUS_PORT) & KBDS_BUFFER_FULL; if (f == KBDS_KBD_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); addq(&kbdcp(p)->kbd, inb(kbdcp(p)->port + KBD_DATA_PORT)); f = inb(kbdcp(p)->port + KBD_STATUS_PORT) & KBDS_BUFFER_FULL; } if (f == KBDS_AUX_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); return inb(kbdcp(p)->port + KBD_DATA_PORT); } return -1; /* no data */ } /* discard data from the keyboard */ void empty_kbd_buffer(KBDC p, int wait) { int t; int b; int f; #if KBDIO_DEBUG >= 2 int c1 = 0; int c2 = 0; #endif int delta = 2; for (t = wait; t > 0; ) { if ((f = inb(kbdcp(p)->port + KBD_STATUS_PORT)) & KBDS_ANY_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); b = inb(kbdcp(p)->port + KBD_DATA_PORT); if ((f & KBDS_BUFFER_FULL) == KBDS_AUX_BUFFER_FULL) { addq(&kbdcp(p)->aux, b); #if KBDIO_DEBUG >= 2 ++c2; } else { ++c1; #endif } t = wait; } else { t -= delta; } DELAY(delta*1000); } #if KBDIO_DEBUG >= 2 if ((c1 > 0) || (c2 > 0)) log(LOG_DEBUG, "kbdc: %d:%d char read (empty_kbd_buffer)\n", c1, c2); #endif emptyq(&kbdcp(p)->kbd); } /* discard data from the aux device */ void empty_aux_buffer(KBDC p, int wait) { int t; int b; int f; #if KBDIO_DEBUG >= 2 int c1 = 0; int c2 = 0; #endif int delta = 2; for (t = wait; t > 0; ) { if ((f = inb(kbdcp(p)->port + KBD_STATUS_PORT)) & KBDS_ANY_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); b = inb(kbdcp(p)->port + KBD_DATA_PORT); if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) { addq(&kbdcp(p)->kbd, b); #if KBDIO_DEBUG >= 2 ++c1; } else { ++c2; #endif } t = wait; } else { t -= delta; } DELAY(delta*1000); } #if KBDIO_DEBUG >= 2 if ((c1 > 0) || (c2 > 0)) log(LOG_DEBUG, "kbdc: %d:%d char read (empty_aux_buffer)\n", c1, c2); #endif emptyq(&kbdcp(p)->aux); } /* discard any data from the keyboard or the aux device */ void empty_both_buffers(KBDC p, int wait) { int t; int f; #if KBDIO_DEBUG >= 2 int c1 = 0; int c2 = 0; #endif int delta = 2; for (t = wait; t > 0; ) { if ((f = inb(kbdcp(p)->port + KBD_STATUS_PORT)) & KBDS_ANY_BUFFER_FULL) { DELAY(KBDD_DELAYTIME); (void)inb(kbdcp(p)->port + KBD_DATA_PORT); #if KBDIO_DEBUG >= 2 if ((f & KBDS_BUFFER_FULL) == KBDS_KBD_BUFFER_FULL) ++c1; else ++c2; #endif t = wait; } else { t -= delta; } DELAY(delta*1000); } #if KBDIO_DEBUG >= 2 if ((c1 > 0) || (c2 > 0)) log(LOG_DEBUG, "kbdc: %d:%d char read (empty_both_buffers)\n", c1, c2); #endif emptyq(&kbdcp(p)->kbd); emptyq(&kbdcp(p)->aux); } /* keyboard and mouse device control */ /* NOTE: enable the keyboard port but disable the keyboard * interrupt before calling "reset_kbd()". */ int reset_kbd(KBDC p) { int retry = KBD_MAXRETRY; int again = KBD_MAXWAIT; int c = KBD_RESEND; /* keep the compiler happy */ while (retry-- > 0) { empty_both_buffers(p, 10); if (!write_kbd_command(p, KBDC_RESET_KBD)) continue; emptyq(&kbdcp(p)->kbd); c = read_controller_data(p); if (verbose || bootverbose) log(LOG_DEBUG, "kbdc: RESET_KBD return code:%04x\n", c); if (c == KBD_ACK) /* keyboard has agreed to reset itself... */ break; } if (retry < 0) return FALSE; while (again-- > 0) { /* wait awhile, well, in fact we must wait quite loooooooooooong */ DELAY(KBD_RESETDELAY*1000); c = read_controller_data(p); /* RESET_DONE/RESET_FAIL */ if (c != -1) /* wait again if the controller is not ready */ break; } if (verbose || bootverbose) log(LOG_DEBUG, "kbdc: RESET_KBD status:%04x\n", c); if (c != KBD_RESET_DONE) return FALSE; return TRUE; } /* NOTE: enable the aux port but disable the aux interrupt * before calling `reset_aux_dev()'. */ int reset_aux_dev(KBDC p) { int retry = KBD_MAXRETRY; int again = KBD_MAXWAIT; int c = PSM_RESEND; /* keep the compiler happy */ while (retry-- > 0) { empty_both_buffers(p, 10); if (!write_aux_command(p, PSMC_RESET_DEV)) continue; emptyq(&kbdcp(p)->aux); /* NOTE: Compaq Armada laptops require extra delay here. XXX */ for (again = KBD_MAXWAIT; again > 0; --again) { DELAY(KBD_RESETDELAY*1000); c = read_aux_data_no_wait(p); if (c != -1) break; } if (verbose || bootverbose) log(LOG_DEBUG, "kbdc: RESET_AUX return code:%04x\n", c); if (c == PSM_ACK) /* aux dev is about to reset... */ break; } if (retry < 0) return FALSE; for (again = KBD_MAXWAIT; again > 0; --again) { /* wait awhile, well, quite looooooooooooong */ DELAY(KBD_RESETDELAY*1000); c = read_aux_data_no_wait(p); /* RESET_DONE/RESET_FAIL */ if (c != -1) /* wait again if the controller is not ready */ break; } if (verbose || bootverbose) log(LOG_DEBUG, "kbdc: RESET_AUX status:%04x\n", c); if (c != PSM_RESET_DONE) /* reset status */ return FALSE; c = read_aux_data(p); /* device ID */ if (verbose || bootverbose) log(LOG_DEBUG, "kbdc: RESET_AUX ID:%04x\n", c); /* NOTE: we could check the device ID now, but leave it later... */ return TRUE; } /* controller diagnostics and setup */ int test_controller(KBDC p) { int retry = KBD_MAXRETRY; int again = KBD_MAXWAIT; int c = KBD_DIAG_FAIL; while (retry-- > 0) { empty_both_buffers(p, 10); if (write_controller_command(p, KBDC_DIAGNOSE)) break; } if (retry < 0) return FALSE; emptyq(&kbdcp(p)->kbd); while (again-- > 0) { /* wait awhile */ DELAY(KBD_RESETDELAY*1000); c = read_controller_data(p); /* DIAG_DONE/DIAG_FAIL */ if (c != -1) /* wait again if the controller is not ready */ break; } if (verbose || bootverbose) log(LOG_DEBUG, "kbdc: DIAGNOSE status:%04x\n", c); return (c == KBD_DIAG_DONE); } int test_kbd_port(KBDC p) { int retry = KBD_MAXRETRY; int again = KBD_MAXWAIT; int c = -1; while (retry-- > 0) { empty_both_buffers(p, 10); if (write_controller_command(p, KBDC_TEST_KBD_PORT)) break; } if (retry < 0) return FALSE; emptyq(&kbdcp(p)->kbd); while (again-- > 0) { c = read_controller_data(p); if (c != -1) /* try again if the controller is not ready */ break; } if (verbose || bootverbose) log(LOG_DEBUG, "kbdc: TEST_KBD_PORT status:%04x\n", c); return c; } int test_aux_port(KBDC p) { int retry = KBD_MAXRETRY; int again = KBD_MAXWAIT; int c = -1; while (retry-- > 0) { empty_both_buffers(p, 10); if (write_controller_command(p, KBDC_TEST_AUX_PORT)) break; } if (retry < 0) return FALSE; emptyq(&kbdcp(p)->kbd); while (again-- > 0) { c = read_controller_data(p); if (c != -1) /* try again if the controller is not ready */ break; } if (verbose || bootverbose) log(LOG_DEBUG, "kbdc: TEST_AUX_PORT status:%04x\n", c); return c; } int kbdc_get_device_mask(KBDC p) { return kbdcp(p)->command_mask; } void kbdc_set_device_mask(KBDC p, int mask) { kbdcp(p)->command_mask = mask & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS); } int get_controller_command_byte(KBDC p) { if (kbdcp(p)->command_byte != -1) return kbdcp(p)->command_byte; if (!write_controller_command(p, KBDC_GET_COMMAND_BYTE)) return -1; emptyq(&kbdcp(p)->kbd); kbdcp(p)->command_byte = read_controller_data(p); return kbdcp(p)->command_byte; } int set_controller_command_byte(KBDC p, int mask, int command) { if (get_controller_command_byte(p) == -1) return FALSE; command = (kbdcp(p)->command_byte & ~mask) | (command & mask); if (command & KBD_DISABLE_KBD_PORT) { if (!write_controller_command(p, KBDC_DISABLE_KBD_PORT)) return FALSE; } if (!write_controller_command(p, KBDC_SET_COMMAND_BYTE)) return FALSE; if (!write_controller_data(p, command)) return FALSE; kbdcp(p)->command_byte = command; if (verbose) log(LOG_DEBUG, "kbdc: new command byte:%04x (set_controller...)\n", command); return TRUE; }
MarginC/kame
freebsd3/sys/dev/kbd/atkbdc.c
C
bsd-3-clause
26,073
call this commnad yii migrate --migrationPath=@yii/rbac/migrations In case of yii2-app-base template, from which I have created my application, there is a config/console.php configuration file where the authManager needs to be declared. It is not sufficient to have it in the config/web.php declared only. 'authManager' => [ 'class' => 'yii\rbac\DbManager', 'defaultRoles' => ['guest'], ], ALTER TABLE `auth_assignment` CHANGE `created_at` `created_at` VARCHAR(50) NULL DEFAULT NULL; --------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------OR Directly--------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------- drop table if exists `auth_assignment`; drop table if exists `auth_item_child`; drop table if exists `auth_item`; drop table if exists `auth_rule`; create table `auth_rule` ( `name` varchar(64) not null, `data` text, `created_at` VARCHAR(50) NULL DEFAULT NULL, `updated_at` VARCHAR(50) NULL DEFAULT NULL, primary key (`name`) ) engine InnoDB; create table `auth_item` ( `name` varchar(64) not null, `type` integer not null, `description` text, `rule_name` varchar(64), `data` text, `created_at` VARCHAR(50) NULL DEFAULT NULL, `updated_at` VARCHAR(50) NULL DEFAULT NULL, primary key (`name`), foreign key (`rule_name`) references `auth_rule` (`name`) on delete set null on update cascade, key `type` (`type`) ) engine InnoDB; create table `auth_item_child` ( `parent` varchar(64) not null, `child` varchar(64) not null, primary key (`parent`, `child`), foreign key (`parent`) references `auth_item` (`name`) on delete cascade on update cascade, foreign key (`child`) references `auth_item` (`name`) on delete cascade on update cascade ) engine InnoDB; create table `auth_assignment` ( `item_name` varchar(64) not null, `user_id` varchar(64) not null, `created_at` VARCHAR(50) NULL DEFAULT NULL, primary key (`item_name`, `user_id`), foreign key (`item_name`) references `auth_item` (`name`) on delete cascade on update cascade ) engine InnoDB;
MobiLifeCompany/DeliveryV2WebAdmin
db/20160722_auth_tables.sql
SQL
bsd-3-clause
2,530
// +build l476xx // Peripheral: CAN_TxMailBox_Periph Controller Area Network TxMailBox. // Instances: // Registers: // 0x00 32 TIR CAN TX mailbox identifier register. // 0x04 32 TDTR CAN mailbox data length control and time stamp register. // 0x08 32 TDLR CAN mailbox data low register. // 0x0C 32 TDHR CAN mailbox data high register. // Import: // stm32/o/l476xx/mmap package can // DO NOT EDIT THIS FILE. GENERATED BY stm32xgen.
ziutek/emgo
egpath/src/stm32/hal/raw/can/l476xx--can_txmailbox.go
GO
bsd-3-clause
444
""" Vision-specific analysis functions. $Id: featureresponses.py 7714 2008-01-24 16:42:21Z antolikjan $ """ __version__='$Revision: 7714 $' from math import fmod,floor,pi,sin,cos,sqrt import numpy from numpy.oldnumeric import Float from numpy import zeros, array, size, empty, object_ #import scipy try: import pylab except ImportError: print "Warning: Could not import matplotlib; pylab plots will not work." import param import topo from topo.base.cf import CFSheet from topo.base.sheetview import SheetView from topo.misc.filepath import normalize_path from topo.misc.numbergenerator import UniformRandom from topo.plotting.plotgroup import create_plotgroup, plotgroups from topo.command.analysis import measure_sine_pref max_value = 0 global_index = () def _complexity_rec(x,y,index,depth,fm): """ Recurrent helper function for complexity() """ global max_value global global_index if depth<size(fm.features): for i in range(size(fm.features[depth].values)): _complexity_rec(x,y,index + (i,),depth+1,fm) else: if max_value < fm.full_matrix[index][x][y]: global_index = index max_value = fm.full_matrix[index][x][y] def complexity(full_matrix): global global_index global max_value """This function expects as an input a object of type FullMatrix which contains responses of all neurons in a sheet to stimuly with different varying parameter values. One of these parameters (features) has to be phase. In such case it computes the classic modulation ratio (see Hawken et al. for definition) for each neuron and returns them as a matrix. """ rows,cols = full_matrix.matrix_shape complexity = zeros(full_matrix.matrix_shape) complex_matrix = zeros(full_matrix.matrix_shape,object_) fftmeasure = zeros(full_matrix.matrix_shape,Float) i = 0 for f in full_matrix.features: if f.name == "phase": phase_index = i break i=i+1 sum = 0.0 res = 0.0 average = 0.0 for x in range(rows): for y in range(cols): complex_matrix[x,y] = []# max_value=-0.01 global_index = () _complexity_rec(x,y,(),0,full_matrix) #compute the sum of the responses over phases given the found index of highest response iindex = array(global_index) sum = 0.0 for i in range(size(full_matrix.features[phase_index].values)): iindex[phase_index] = i sum = sum + full_matrix.full_matrix[tuple(iindex.tolist())][x][y] #average average = sum / float(size(full_matrix.features[phase_index].values)) res = 0.0 #compute the sum of absolute values of the responses minus average for i in range(size(full_matrix.features[phase_index].values)): iindex[phase_index] = i res = res + abs(full_matrix.full_matrix[tuple(iindex.tolist())][x][y] - average) complex_matrix[x,y] = complex_matrix[x,y] + [full_matrix.full_matrix[tuple(iindex.tolist())][x][y]] #this is taking away the DC component #complex_matrix[x,y] -= numpy.min(complex_matrix[x,y]) if x==15 and y==15: pylab.figure() pylab.plot(complex_matrix[x,y]) if x==26 and y==26: pylab.figure() pylab.plot(complex_matrix[x,y]) #complexity[x,y] = res / (2*sum) fft = numpy.fft.fft(complex_matrix[x,y]+complex_matrix[x,y]+complex_matrix[x,y]+complex_matrix[x,y],2048) first_har = 2048/len(complex_matrix[0,0]) if abs(fft[0]) != 0: fftmeasure[x,y] = 2 *abs(fft[first_har]) /abs(fft[0]) else: fftmeasure[x,y] = 0 return fftmeasure def compute_ACDC_orientation_tuning_curves(full_matrix,curve_label,sheet): """ This function allows and alternative computation of orientation tuning curve where for each given orientation the response is computed as a maximum of AC or DC component across the phases instead of the maximum used as a standard in Topographica""" # this method assumes that only single frequency has been used i = 0 for f in full_matrix.features: if f.name == "phase": phase_index = i if f.name == "orientation": orientation_index = i if f.name == "frequency": frequency_index = i i=i+1 print sheet.curve_dict if not sheet.curve_dict.has_key("orientationACDC"): sheet.curve_dict["orientationACDC"]={} sheet.curve_dict["orientationACDC"][curve_label]={} rows,cols = full_matrix.matrix_shape for o in xrange(size(full_matrix.features[orientation_index].values)): s_w = zeros(full_matrix.matrix_shape) for x in range(rows): for y in range(cols): or_response=[] for p in xrange(size(full_matrix.features[phase_index].values)): index = [0,0,0] index[phase_index] = p index[orientation_index] = o index[frequency_index] = 0 or_response.append(full_matrix.full_matrix[tuple(index)][x][y]) fft = numpy.fft.fft(or_response+or_response+or_response+or_response,2048) first_har = 2048/len(or_response) s_w[x][y] = numpy.maximum(2 *abs(fft[first_har]),abs(fft[0])) s = SheetView((s_w,sheet.bounds), sheet.name , sheet.precedence, topo.sim.time(),sheet.row_precedence) sheet.curve_dict["orientationACDC"][curve_label].update({full_matrix.features[orientation_index].values[o]:s}) def phase_preference_scatter_plot(sheet_name,diameter=0.39): r = UniformRandom(seed=1023) preference_map = topo.sim[sheet_name].sheet_views['PhasePreference'] offset_magnitude = 0.03 datax = [] datay = [] (v,bb) = preference_map.view() for z in zeros(66): x = (r() - 0.5)*2*diameter y = (r() - 0.5)*2*diameter rand = r() xoff = sin(rand*2*pi)*offset_magnitude yoff = cos(rand*2*pi)*offset_magnitude xx = max(min(x+xoff,diameter),-diameter) yy = max(min(y+yoff,diameter),-diameter) x = max(min(x,diameter),-diameter) y = max(min(y,diameter),-diameter) [xc1,yc1] = topo.sim[sheet_name].sheet2matrixidx(xx,yy) [xc2,yc2] = topo.sim[sheet_name].sheet2matrixidx(x,y) if((xc1==xc2) & (yc1==yc2)): continue datax = datax + [v[xc1,yc1]] datay = datay + [v[xc2,yc2]] for i in range(0,len(datax)): datax[i] = datax[i] * 360 datay[i] = datay[i] * 360 if(datay[i] > datax[i] + 180): datay[i]= datay[i]- 360 if((datax[i] > 180) & (datay[i]> 180)): datax[i] = datax[i] - 360; datay[i] = datay[i] - 360 if((datax[i] > 180) & (datay[i] < (datax[i]-180))): datax[i] = datax[i] - 360; #datay[i] = datay[i] - 360 f = pylab.figure() ax = f.add_subplot(111, aspect='equal') pylab.plot(datax,datay,'ro') pylab.plot([0,360],[-180,180]) pylab.plot([-180,180],[0,360]) pylab.plot([-180,-180],[360,360]) ax.axis([-180,360,-180,360]) pylab.xticks([-180,0,180,360], [-180,0,180,360]) pylab.yticks([-180,0,180,360], [-180,0,180,360]) pylab.grid() pylab.savefig(normalize_path(str(topo.sim.timestr()) + sheet_name + "_scatter.png")) ############################################################################### # JABALERT: Should we move this plot and command to analysis.py or # pylabplots.py, where all the rest are? # # In any case, it requires generalization; it should not be hardcoded # to any particular map name, and should just do the right thing for # most networks for which it makes sense. E.g. it already measures # the ComplexSelectivity for all measured_sheets, but then # plot_modulation_ratio only accepts two with specific names. # plot_modulation_ratio should just plot whatever it is given, and # then analyze_complexity can simply pass in whatever was measured, # with the user controlling what is measured using the measure_map # attribute of each Sheet. That way the complexity of any sheet could # be measured, which is what we want. # # Specific changes needed: # - Make plot_modulation_ratio accept a list of sheets and # plot their individual modulation ratios and combined ratio. # - Remove complex_sheet_name argument, which is no longer needed # - Make sure it still works fine even if V1Simple doesn't exist; # as this is just for an optional scatter plot, it's fine to skip # it. # - Preferably remove the filename argument by default, so that # plots will show up in the GUI def analyze_complexity(full_matrix,simple_sheet_name,complex_sheet_name,filename=None): """ Compute modulation ratio for each neuron, to distinguish complex from simple cells. Uses full_matrix data obtained from measure_or_pref(). If there is a sheet named as specified in simple_sheet_name, also plots its phase preference as a scatter plot. """ import topo measured_sheets = [s for s in topo.sim.objects(CFSheet).values() if hasattr(s,'measure_maps') and s.measure_maps] for sheet in measured_sheets: # Divide by two to get into 0-1 scale - that means simple/complex boundry is now at 0.5 complx = array(complexity(full_matrix[sheet]))/2.0 # Should this be renamed to ModulationRatio? sheet.sheet_views['ComplexSelectivity']=SheetView((complx,sheet.bounds), sheet.name , sheet.precedence, topo.sim.time(),sheet.row_precedence) import topo.command.pylabplots topo.command.pylabplots.plot_modulation_ratio(full_matrix,simple_sheet_name=simple_sheet_name,complex_sheet_name=complex_sheet_name,filename=filename) # Avoid error if no simple sheet exists try: phase_preference_scatter_plot(simple_sheet_name,diameter=0.24999) except AttributeError: print "Skipping phase preference scatter plot; could not analyze region %s." \ % simple_sheet_name class measure_and_analyze_complexity(measure_sine_pref): """Macro for measuring orientation preference and then analyzing its complexity.""" def __call__(self,**params): fm = super(measure_and_analyze_complexity,self).__call__(**params) #from topo.command.analysis import measure_or_pref #fm = measure_or_pref() analyze_complexity(fm,simple_sheet_name="V1Simple",complex_sheet_name="V1Complex",filename="ModulationRatio") pg= create_plotgroup(name='Orientation Preference and Complexity',category="Preference Maps", doc='Measure preference for sine grating orientation.', pre_plot_hooks=[measure_and_analyze_complexity.instance()]) pg.add_plot('Orientation Preference',[('Hue','OrientationPreference')]) pg.add_plot('Orientation Preference&Selectivity',[('Hue','OrientationPreference'), ('Confidence','OrientationSelectivity')]) pg.add_plot('Orientation Selectivity',[('Strength','OrientationSelectivity')]) pg.add_plot('Modulation Ratio',[('Strength','ComplexSelectivity')]) pg.add_plot('Phase Preference',[('Hue','PhasePreference')]) pg.add_static_image('Color Key','command/or_key_white_vert_small.png')
jesuscript/topo-mpi
topo/analysis/vision.py
Python
bsd-3-clause
11,628
<?php use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $model common\models\Offer */ $this->title = $model->id; $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Offers'), 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="offer-view"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a(Yii::t('app', 'Update'), ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?> <?= Html::a(Yii::t('app', 'Delete'), ['delete', 'id' => $model->id], [ 'class' => 'btn btn-danger', 'data' => [ 'confirm' => Yii::t('app', 'Are you sure you want to delete this item?'), 'method' => 'post', ], ]) ?> </p> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'id', 'code', 'text:ntext', 'created_at', 'updated_at', ], ]) ?> </div>
Dench/resistor
backend/views/offer/view.php
PHP
bsd-3-clause
1,025
/* $OpenBSD: isp_sbus.c,v 1.7 1999/03/25 22:58:37 mjacob Exp $ */ /* release_03_25_99 */ /* * SBus specific probe and attach routines for Qlogic ISP SCSI adapters. * * Copyright (c) 1997 by Matthew Jacob * NASA AMES Research Center * 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 immediately at the beginning of the file, without modification, * this list of conditions, and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include <sys/param.h> #include <sys/systm.h> #include <sys/device.h> #include <sys/kernel.h> #include <sys/malloc.h> #include <sys/queue.h> #include <machine/autoconf.h> #include <machine/cpu.h> #include <machine/param.h> #include <machine/vmparam.h> #include <sparc/sparc/cpuvar.h> #include <dev/ic/isp_openbsd.h> #include <dev/microcode/isp/asm_sbus.h> static u_int16_t isp_sbus_rd_reg __P((struct ispsoftc *, int)); static void isp_sbus_wr_reg __P((struct ispsoftc *, int, u_int16_t)); static int isp_sbus_mbxdma __P((struct ispsoftc *)); static int isp_sbus_dmasetup __P((struct ispsoftc *, struct scsi_xfer *, ispreq_t *, u_int8_t *, u_int8_t)); static void isp_sbus_dmateardown __P((struct ispsoftc *, struct scsi_xfer *, u_int32_t)); static struct ispmdvec mdvec = { isp_sbus_rd_reg, isp_sbus_wr_reg, isp_sbus_mbxdma, isp_sbus_dmasetup, isp_sbus_dmateardown, NULL, NULL, NULL, ISP_RISC_CODE, ISP_CODE_LENGTH, ISP_CODE_ORG, ISP_CODE_VERSION, BIU_BURST_ENABLE, 0 }; struct isp_sbussoftc { struct ispsoftc sbus_isp; sdparam sbus_dev; struct intrhand sbus_ih; volatile u_char *sbus_reg; int sbus_node; int sbus_pri; struct ispmdvec sbus_mdvec; vm_offset_t sbus_kdma_allocs[MAXISPREQUEST]; int16_t sbus_poff[_NREG_BLKS]; }; static int isp_match __P((struct device *, void *, void *)); static void isp_sbus_attach __P((struct device *, struct device *, void *)); struct cfattach isp_sbus_ca = { sizeof (struct isp_sbussoftc), isp_match, isp_sbus_attach }; static int isp_match(parent, cfarg, aux) struct device *parent; void *cfarg; void *aux; { int rv; struct cfdata *cf = cfarg; #ifdef DEBUG static int oneshot = 1; #endif struct confargs *ca = aux; register struct romaux *ra = &ca->ca_ra; rv = (strcmp(cf->cf_driver->cd_name, ra->ra_name) == 0 || strcmp("PTI,ptisp", ra->ra_name) == 0 || strcmp("ptisp", ra->ra_name) == 0 || strcmp("SUNW,isp", ra->ra_name) == 0 || strcmp("QLGC,isp", ra->ra_name) == 0); if (rv == 0) return (rv); #ifdef DEBUG if (rv && oneshot) { oneshot = 0; printf("Qlogic ISP Driver, NetBSD (sbus) Platform Version " "%d.%d Core Version %d.%d\n", ISP_PLATFORM_VERSION_MAJOR, ISP_PLATFORM_VERSION_MINOR, ISP_CORE_VERSION_MAJOR, ISP_CORE_VERSION_MINOR); } #endif if (ca->ca_bustype == BUS_SBUS) return (1); ra->ra_len = NBPG; return (probeget(ra->ra_vaddr, 1) != -1); } static void isp_sbus_attach(parent, self, aux) struct device *parent, *self; void *aux; { int freq; struct confargs *ca = aux; struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) self; struct ispsoftc *isp = &sbc->sbus_isp; ISP_LOCKVAL_DECL; if (ca->ca_ra.ra_nintr != 1) { printf(": expected 1 interrupt, got %d\n", ca->ca_ra.ra_nintr); return; } printf("\n"); sbc->sbus_pri = ca->ca_ra.ra_intr[0].int_pri; sbc->sbus_mdvec = mdvec; if (ca->ca_ra.ra_vaddr) { sbc->sbus_reg = (volatile u_char *) ca->ca_ra.ra_vaddr; } else { sbc->sbus_reg = (volatile u_char *) mapiodev(ca->ca_ra.ra_reg, 0, ca->ca_ra.ra_len); } sbc->sbus_node = ca->ca_ra.ra_node; freq = getpropint(ca->ca_ra.ra_node, "clock-frequency", 0); if (freq) { /* * Convert from HZ to MHz, rounding up. */ freq = (freq + 500000)/1000000; #if 0 printf("%s: %d MHz\n", self->dv_xname, freq); #endif } sbc->sbus_mdvec.dv_clock = freq; /* * XXX: Now figure out what the proper burst sizes, etc., to use. */ sbc->sbus_mdvec.dv_conf1 |= BIU_SBUS_CONF1_FIFO_8; /* * Some early versions of the PTI SBus adapter * would fail in trying to download (via poking) * FW. We give up on them. */ if (strcmp("PTI,ptisp", ca->ca_ra.ra_name) == 0 || strcmp("ptisp", ca->ca_ra.ra_name) == 0) { sbc->sbus_mdvec.dv_fwlen = 0; } isp->isp_mdvec = &sbc->sbus_mdvec; isp->isp_bustype = ISP_BT_SBUS; isp->isp_type = ISP_HA_SCSI_UNKNOWN; isp->isp_param = &sbc->sbus_dev; bzero(isp->isp_param, sizeof (sdparam)); sbc->sbus_poff[BIU_BLOCK >> _BLK_REG_SHFT] = BIU_REGS_OFF; sbc->sbus_poff[MBOX_BLOCK >> _BLK_REG_SHFT] = SBUS_MBOX_REGS_OFF; sbc->sbus_poff[SXP_BLOCK >> _BLK_REG_SHFT] = SBUS_SXP_REGS_OFF; sbc->sbus_poff[RISC_BLOCK >> _BLK_REG_SHFT] = SBUS_RISC_REGS_OFF; sbc->sbus_poff[DMA_BLOCK >> _BLK_REG_SHFT] = DMA_REGS_OFF; /* Establish interrupt channel */ sbc->sbus_ih.ih_fun = (void *) isp_intr; sbc->sbus_ih.ih_arg = sbc; intr_establish(sbc->sbus_pri, &sbc->sbus_ih); ISP_LOCK(isp); isp_reset(isp); if (isp->isp_state != ISP_RESETSTATE) { ISP_UNLOCK(isp); return; } isp_init(isp); if (isp->isp_state != ISP_INITSTATE) { isp_uninit(isp); ISP_UNLOCK(isp); return; } /* * do generic attach. */ isp_attach(isp); if (isp->isp_state != ISP_RUNSTATE) { isp_uninit(isp); } ISP_UNLOCK(isp); } static u_int16_t isp_sbus_rd_reg(isp, regoff) struct ispsoftc *isp; int regoff; { struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) isp; int offset = sbc->sbus_poff[(regoff & _BLK_REG_MASK) >> _BLK_REG_SHFT]; offset += (regoff & 0xff); return (*((u_int16_t *) &sbc->sbus_reg[offset])); } static void isp_sbus_wr_reg (isp, regoff, val) struct ispsoftc *isp; int regoff; u_int16_t val; { struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) isp; int offset = sbc->sbus_poff[(regoff & _BLK_REG_MASK) >> _BLK_REG_SHFT]; offset += (regoff & 0xff); *((u_int16_t *) &sbc->sbus_reg[offset]) = val; } static int isp_sbus_mbxdma(isp) struct ispsoftc *isp; { size_t len; /* * NOTE: Since most Sun machines aren't I/O coherent, * map the mailboxes through kdvma space to force them * to be uncached. */ /* * Allocate and map the request queue. */ len = ISP_QUEUE_SIZE(RQUEST_QUEUE_LEN); isp->isp_rquest = (volatile caddr_t)malloc(len, M_DEVBUF, M_NOWAIT); if (isp->isp_rquest == 0) return (1); isp->isp_rquest_dma = (u_int32_t)kdvma_mapin((caddr_t)isp->isp_rquest, len, 0); if (isp->isp_rquest_dma == 0) return (1); /* * Allocate and map the result queue. */ len = ISP_QUEUE_SIZE(RESULT_QUEUE_LEN); isp->isp_result = (volatile caddr_t)malloc(len, M_DEVBUF, M_NOWAIT); if (isp->isp_result == 0) return (1); isp->isp_result_dma = (u_int32_t)kdvma_mapin((caddr_t)isp->isp_result, len, 0); if (isp->isp_result_dma == 0) return (1); return (0); } /* * TODO: If kdvma_mapin fails, try using multiple smaller chunks.. */ static int isp_sbus_dmasetup(isp, xs, rq, iptrp, optr) struct ispsoftc *isp; struct scsi_xfer *xs; ispreq_t *rq; u_int8_t *iptrp; u_int8_t optr; { struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) isp; vm_offset_t kdvma; int dosleep = (xs->flags & SCSI_NOSLEEP) != 0; if (xs->datalen == 0) { rq->req_seg_count = 1; return (CMD_QUEUED); } if (rq->req_handle > RQUEST_QUEUE_LEN || rq->req_handle < 1) { panic("%s: bad handle (%d) in isp_sbus_dmasetup\n", isp->isp_name, rq->req_handle); /* NOTREACHED */ } if (CPU_ISSUN4M) { kdvma = (vm_offset_t) kdvma_mapin((caddr_t)xs->data, xs->datalen, dosleep); if (kdvma == (vm_offset_t) 0) { XS_SETERR(xs, HBA_BOTCH); return (CMD_COMPLETE); } } else { kdvma = (vm_offset_t) xs->data; } if (sbc->sbus_kdma_allocs[rq->req_handle - 1] != (vm_offset_t) 0) { panic("%s: kdma handle already allocated\n", isp->isp_name); /* NOTREACHED */ } sbc->sbus_kdma_allocs[rq->req_handle - 1] = kdvma; if (xs->flags & SCSI_DATA_IN) { rq->req_flags |= REQFLAG_DATA_IN; } else { rq->req_flags |= REQFLAG_DATA_OUT; } rq->req_dataseg[0].ds_count = xs->datalen; rq->req_dataseg[0].ds_base = (u_int32_t) kdvma; rq->req_seg_count = 1; return (CMD_QUEUED); } static void isp_sbus_dmateardown(isp, xs, handle) struct ispsoftc *isp; struct scsi_xfer *xs; u_int32_t handle; { struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) isp; vm_offset_t kdvma; if (xs->flags & SCSI_DATA_IN) { cpuinfo.cache_flush(xs->data, xs->datalen - xs->resid); } if (handle >= RQUEST_QUEUE_LEN) { panic("%s: bad handle (%d) in isp_sbus_dmateardown\n", isp->isp_name, handle); /* NOTREACHED */ } if (sbc->sbus_kdma_allocs[handle] == (vm_offset_t) 0) { panic("%s: kdma handle not already allocated\n", isp->isp_name); /* NOTREACHED */ } kdvma = sbc->sbus_kdma_allocs[handle]; sbc->sbus_kdma_allocs[handle] = (vm_offset_t) 0; if (CPU_ISSUN4M) { dvma_mapout(kdvma, (vm_offset_t) xs->data, xs->datalen); } }
MarginC/kame
openbsd/sys/arch/sparc/dev/isp_sbus.c
C
bsd-3-clause
10,106
/* * Copyright (C) 2001 Peter Kelly ([email protected]) * Copyright (C) 2001 Tobias Anton ([email protected]) * Copyright (C) 2006 Samuel Weinig ([email protected]) * Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "sky/engine/config.h" #include "sky/engine/core/events/UIEvent.h" namespace blink { UIEventInit::UIEventInit() : view(nullptr) , detail(0) { } UIEvent::UIEvent() : m_detail(0) { } UIEvent::UIEvent(const AtomicString& eventType, bool canBubbleArg, bool cancelableArg, PassRefPtr<AbstractView> viewArg, int detailArg) : Event(eventType, canBubbleArg, cancelableArg) , m_view(viewArg) , m_detail(detailArg) { } UIEvent::UIEvent(const AtomicString& eventType, const UIEventInit& initializer) : Event(eventType, initializer) , m_view(initializer.view) , m_detail(initializer.detail) { } UIEvent::~UIEvent() { } void UIEvent::initUIEvent(const AtomicString& typeArg, bool canBubbleArg, bool cancelableArg, PassRefPtr<AbstractView> viewArg, int detailArg) { if (dispatched()) return; initEvent(typeArg, canBubbleArg, cancelableArg); m_view = viewArg; m_detail = detailArg; } bool UIEvent::isUIEvent() const { return true; } const AtomicString& UIEvent::interfaceName() const { return EventNames::UIEvent; } int UIEvent::keyCode() const { return 0; } int UIEvent::charCode() const { return 0; } int UIEvent::layerX() { return 0; } int UIEvent::layerY() { return 0; } int UIEvent::pageX() const { return 0; } int UIEvent::pageY() const { return 0; } int UIEvent::which() const { return 0; } } // namespace blink
collinjackson/mojo
sky/engine/core/events/UIEvent.cpp
C++
bsd-3-clause
2,459
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_45) on Tue Apr 17 08:41:58 IDT 2018 --> <title>DNXConstants.PRESERVATIONLEVEL</title> <meta name="date" content="2018-04-17"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="DNXConstants.PRESERVATIONLEVEL"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.OBJECTIDENTIFIER.html" title="interface in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRODUCER.html" title="interface in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html" target="_top">Frames</a></li> <li><a href="DNXConstants.PRESERVATIONLEVEL.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.exlibris.digitool.common.dnx</div> <h2 title="Interface DNXConstants.PRESERVATIONLEVEL" class="title">Interface DNXConstants.PRESERVATIONLEVEL</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants</a></dd> </dl> <hr> <br> <pre>public static interface <span class="typeNameLabel">DNXConstants.PRESERVATIONLEVEL</span></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html#PRESERVATIONLEVELDATEASSIGNED">PRESERVATIONLEVELDATEASSIGNED</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html#PRESERVATIONLEVELRATIONALE">PRESERVATIONLEVELRATIONALE</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html#PRESERVATIONLEVELROLE">PRESERVATIONLEVELROLE</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html#PRESERVATIONLEVELVALUE">PRESERVATIONLEVELVALUE</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html#sectionId">sectionId</a></span></code>&nbsp;</td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field.detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="sectionId"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>sectionId</h4> <pre>static final&nbsp;java.lang.String sectionId</pre> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../constant-values.html#com.exlibris.digitool.common.dnx.DNXConstants.PRESERVATIONLEVEL.sectionId">Constant Field Values</a></dd> </dl> </li> </ul> <a name="PRESERVATIONLEVELVALUE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>PRESERVATIONLEVELVALUE</h4> <pre>static final&nbsp;<a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a> PRESERVATIONLEVELVALUE</pre> </li> </ul> <a name="PRESERVATIONLEVELROLE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>PRESERVATIONLEVELROLE</h4> <pre>static final&nbsp;<a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a> PRESERVATIONLEVELROLE</pre> </li> </ul> <a name="PRESERVATIONLEVELRATIONALE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>PRESERVATIONLEVELRATIONALE</h4> <pre>static final&nbsp;<a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a> PRESERVATIONLEVELRATIONALE</pre> </li> </ul> <a name="PRESERVATIONLEVELDATEASSIGNED"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>PRESERVATIONLEVELDATEASSIGNED</h4> <pre>static final&nbsp;<a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a> PRESERVATIONLEVELDATEASSIGNED</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.OBJECTIDENTIFIER.html" title="interface in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRODUCER.html" title="interface in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html" target="_top">Frames</a></li> <li><a href="DNXConstants.PRESERVATIONLEVEL.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
ExLibrisGroup/Rosetta.dps-sdk-projects
5.5.0/javadoc/com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html
HTML
bsd-3-clause
10,934
import { takeLatest, call, put } from 'redux-saga/effects'; import { gql } from 'react-apollo'; import { push } from 'react-router-redux'; import jwtDecode from 'jwt-decode'; import { setJwtToken } from '../../utils/auth'; import { bootstrap } from '../../utils/sagas'; import { registerError, registerSuccess } from './actions'; import { REGISTER } from './constants'; import { loginSuccess } from '../Login/actions'; import { client } from '../../graphql'; import { homePage } from '../../local-urls'; const RegisterMutation = gql` mutation RegisterMutation($nick: String!, $password: String!, $name: String!, $email: String!){ register(nick: $nick, password: $password, name: $name, email: $email) } `; function sendRegister(user) { return client.mutate({ mutation: RegisterMutation, variables: user }); } function* register({ user }) { try { const response = yield call(sendRegister, user); const token = response.data.register; const userInfo = jwtDecode(token); setJwtToken(token); yield put(registerSuccess()); yield put(loginSuccess(userInfo)); yield put(push(homePage())); } catch (e) { yield put(registerError()); } } function* registerSaga() { yield takeLatest(REGISTER, register); } export default bootstrap([ registerSaga, ]);
zmora-agh/zmora-ui
app/containers/Register/sagas.js
JavaScript
bsd-3-clause
1,298
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>statsmodels.tsa.vector_ar.var_model.VARResults.pvalues &#8212; statsmodels 0.9.0 documentation</title> <link rel="stylesheet" href="../_static/nature.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt" href="statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt.html" /> <link rel="prev" title="statsmodels.tsa.vector_ar.var_model.VARResults.plotsim" href="statsmodels.tsa.vector_ar.var_model.VARResults.plotsim.html" /> <link rel="stylesheet" href="../_static/examples.css" type="text/css" /> <link rel="stylesheet" href="../_static/facebox.css" type="text/css" /> <script type="text/javascript" src="../_static/scripts.js"> </script> <script type="text/javascript" src="../_static/facebox.js"> </script> <script type="text/javascript"> $.facebox.settings.closeImage = "../_static/closelabel.png" $.facebox.settings.loadingImage = "../_static/loading.gif" </script> </head><body> <div class="headerwrap"> <div class = "header"> <a href = "../index.html"> <img src="../_static/statsmodels_hybi_banner.png" alt="Logo" style="padding-left: 15px"/></a> </div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt.html" title="statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt" accesskey="N">next</a> |</li> <li class="right" > <a href="statsmodels.tsa.vector_ar.var_model.VARResults.plotsim.html" title="statsmodels.tsa.vector_ar.var_model.VARResults.plotsim" accesskey="P">previous</a> |</li> <li><a href ="../install.html">Install</a></li> &nbsp;|&nbsp; <li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> &nbsp;|&nbsp; <li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> &nbsp;|&nbsp; <li><a href="../dev/index.html">Develop</a></li> &nbsp;|&nbsp; <li><a href="../examples/index.html">Examples</a></li> &nbsp;|&nbsp; <li><a href="../faq.html">FAQ</a></li> &nbsp;|&nbsp; <li class="nav-item nav-item-1"><a href="../tsa.html" >Time Series analysis <code class="docutils literal notranslate"><span class="pre">tsa</span></code></a> |</li> <li class="nav-item nav-item-2"><a href="statsmodels.tsa.vector_ar.var_model.VARResults.html" accesskey="U">statsmodels.tsa.vector_ar.var_model.VARResults</a> |</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="statsmodels-tsa-vector-ar-var-model-varresults-pvalues"> <h1>statsmodels.tsa.vector_ar.var_model.VARResults.pvalues<a class="headerlink" href="#statsmodels-tsa-vector-ar-var-model-varresults-pvalues" title="Permalink to this headline">¶</a></h1> <dl class="method"> <dt id="statsmodels.tsa.vector_ar.var_model.VARResults.pvalues"> <code class="descclassname">VARResults.</code><code class="descname">pvalues</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.pvalues"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.tsa.vector_ar.var_model.VARResults.pvalues" title="Permalink to this definition">¶</a></dt> <dd><p>Two-sided p-values for model coefficients from Student t-distribution</p> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="statsmodels.tsa.vector_ar.var_model.VARResults.plotsim.html" title="previous chapter">statsmodels.tsa.vector_ar.var_model.VARResults.plotsim</a></p> <h4>Next topic</h4> <p class="topless"><a href="statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt.html" title="next chapter">statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/generated/statsmodels.tsa.vector_ar.var_model.VARResults.pvalues.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2009-2017, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.7.4. </div> </body> </html>
statsmodels/statsmodels.github.io
0.9.0/generated/statsmodels.tsa.vector_ar.var_model.VARResults.pvalues.html
HTML
bsd-3-clause
6,727
<!doctype html> <html> <head> <title>LazyLoad Test</title> <style type="text/css"> fieldset { border: 1px solid #afafaf; margin-bottom: 1em; } .log { font: 10pt Consolas, Monaco, fixed; width: 100%; } #css-status { background-color: #fff; height: 30px; margin: 10px auto; width: 100px; } #n1,#n2,#n3,#n4,#n5 { width: 0; } </style> </head> <body> <h1>LazyLoad Test</h1> <form action="" method="get"> <fieldset> <legend>JavaScript</legend> <p> <input type="button" id="btnLoadJS" value="Load JS (sequential calls)" /> <input type="button" id="btnLoadJSSingle" value="Load JS (single call)" /> </p> <p> <textarea id="jslog" class="log" rows="15" cols="50"></textarea> </p> </fieldset> <fieldset> <legend>CSS</legend> <p> <input type="button" id="btnLoadCSS" value="Load CSS (sequential calls)" /> <input type="button" id="btnLoadCSSSingle" value="Load CSS (single call)" /> </p> <p> <textarea id="csslog" class="log" rows="15" cols="50"></textarea> </p> <div id="css-status"></div> <div id="n1"></div> <div id="n2"></div> <div id="n3"></div> <div id="n4"></div> <div id="n5"></div> </fieldset> </form> <script src="../lazyload.js"></script> <script type="text/javascript"> var btnLoadCSS = document.getElementById('btnLoadCSS'), btnLoadCSSSingle = document.getElementById('btnLoadCSSSingle'), btnLoadJS = document.getElementById('btnLoadJS'), btnLoadJSSingle = document.getElementById('btnLoadJSSingle'), cssLogEl = document.getElementById('csslog'), jsLogEl = document.getElementById('jslog'), n1 = document.getElementById('n1'), n2 = document.getElementById('n2'), n3 = document.getElementById('n3'), n4 = document.getElementById('n4'), n5 = document.getElementById('n5'), cssInterval = null, css = [ 'http://pieisgood.org/test/lazyload/../lazyload/css.php?num=1', 'http://pieisgood.org/test/lazyload/css.php?num=2', 'http://pieisgood.org/test/lazyload/css.php?num=3', 'http://pieisgood.org/test/lazyload/css.php?num=4', 'http://pieisgood.org/test/lazyload/css.php?num=5' ], js = [ 'http://pieisgood.org/test/lazyload/js.php?num=1', 'http://pieisgood.org/test/lazyload/js.php?num=2', 'http://pieisgood.org/test/lazyload/js.php?num=3', 'http://pieisgood.org/test/lazyload/js.php?num=4', 'http://pieisgood.org/test/lazyload/js.php?num=5' ]; function cssComplete() { csslog('callback'); } function csslog(message) { cssLogEl.value += "[" + (new Date()).toTimeString() + "] " + message + "\r\n"; } function cssPollStart() { var check = [n1, n2, n3, n4, n5], i, item; cssPollStop(); var links = document.getElementsByTagName('link'); cssInterval = setInterval(function () { for (i = 0; i < check.length; ++i) { item = check[i]; if (item.offsetWidth > 0) { check.splice(i, 1); i -= 1; csslog('stylesheet ' + item.id.substr(1) + ' applied'); } } if (!check.length) { cssPollStop(); } }, 15); } function cssPollStop() { clearInterval(cssInterval); } function jsComplete() { jslog('callback'); } function jslog(message) { jsLogEl.value += "[" + (new Date()).toTimeString() + "] " + message + "\r\n"; } btnLoadCSS.onclick = function () { cssPollStart(); csslog('loading (sequential calls)'); for (var i = 0; i < css.length; i += 1) { LazyLoad.css(css[i], cssComplete); } } btnLoadCSSSingle.onclick = function () { cssPollStart(); csslog('loading (single call)'); LazyLoad.css(css, cssComplete); } btnLoadJS.onclick = function () { jslog('loading (sequential calls)'); for (var i = 0; i < js.length; i += 1) { LazyLoad.js(js[i], jsComplete); } } btnLoadJSSingle.onclick = function () { jslog('loading (single call)'); LazyLoad.js(js, jsComplete); } </script> </body> </html>
smith/lazyload
test/index.html
HTML
bsd-3-clause
4,907
$(function () { var colors = Highcharts.getOptions().colors, categories = ['已关闭', 'NEW', '已解决'], name = 'Browser brands', data = [{ y: 290, color: colors[0], drilldown: { name: 'close bug version', categories: ['当前版本', '历史版本'], data: [20,270], color: colors[0] } }, { y: 64, color: colors[1], drilldown: { name: 'fix bug version', categories: ['当前版本', '历史版本'], data: [8,56], color: colors[1] } }, { y: 82, color: colors[2], drilldown: { name: 'NEW bug versions', categories: ['当前版本', '历史版本'], data: [5,77], color: colors[2] } }]; // Build the data arrays var browserData = []; var versionsData = []; for (var i = 0; i < data.length; i++) { // add browser data browserData.push({ name: categories[i], y: data[i].y, color: data[i].color }); // add version data for (var j = 0; j < data[i].drilldown.data.length; j++) { var brightness = 0.2 - (j / data[i].drilldown.data.length) / 5 ; versionsData.push({ name: data[i].drilldown.categories[j], y: data[i].drilldown.data[j], color: Highcharts.Color(data[i].color).brighten(brightness).get() }); } } // Create the chart $('#container11').highcharts({ chart: { type: 'pie' }, title: { text: '当前版本在历史版本总和占比' }, yAxis: { title: { text: 'Total percent market share' } }, plotOptions: { pie: { shadow: false, center: ['50%', '50%'] } }, tooltip: { valueSuffix: '' //这里更改tooltip显示的单位 }, series: [{ name: 'Browsers', data: browserData, size: '80%', dataLabels: { formatter: function() { return this.y > 5 ? this.point.name : null; }, color: 'white', distance: -30 } }, { name: 'Versions', data: versionsData, size: '100%', innerSize: '80%', dataLabels: { formatter: function() { // display only if larger than 1 return this.y > 0 ? '<b>'+ this.point.name +':</b> '+ this.y+'个' : null; } } }] }); });
qualityTeam5/PO-demo
src/11.js
JavaScript
bsd-3-clause
3,175