answer
stringlengths
15
1.25M
#include <linux/init.h> #include <linux/io.h> #include <linux/module.h> #include <linux/interrupt.h> #include <linux/clk.h> #include <linux/device.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/of_irq.h> #include <linux/of_platform.h> #include <linux/pm_runtime.h> #include <linux/busfreq-imx.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/initval.h> #include <sound/soc.h> #include <sound/dmaengine_pcm.h> #include "fsl_ssi.h" #include "imx-pcm.h" /** * FSLSSI_I2S_RATES: sample rates supported by the I2S * * This driver currently only supports the SSI running in I2S slave mode, * which means the codec determines the sample rate. Therefore, we tell * ALSA that we support all rates and let the codec driver decide what rates * are really supported. */ #define FSLSSI_I2S_RATES <API key> /** * FSLSSI_I2S_FORMATS: audio formats supported by the SSI * * This driver currently only supports the SSI running in I2S slave mode. * * The SSI has a limitation in that the samples must be in the same byte * order as the host CPU. This is because when multiple bytes are written * to the STX register, the bytes and bits must be written in the same * order. The STX is a shift register, so all the bits need to be aligned * (bit-endianness must match byte-endianness). Processors typically write * the bits within a byte in the same order that the bytes of a word are * written in. So if the host CPU is big-endian, then only big-endian * samples will be written to STX properly. */ #ifdef __BIG_ENDIAN #define FSLSSI_I2S_FORMATS (SNDRV_PCM_FMTBIT_S8 | <API key> | \ <API key> | <API key> | \ <API key> | <API key>) #else #define FSLSSI_I2S_FORMATS (SNDRV_PCM_FMTBIT_S8 | <API key> | \ <API key> | <API key> | \ <API key> | <API key>) #endif #define <API key> (<API key> | \ <API key> | <API key> | \ <API key> | <API key>) #define <API key> (<API key> | \ <API key> | <API key> | \ <API key> | <API key>) enum fsl_ssi_type { FSL_SSI_MCP8610, FSL_SSI_MX21, FSL_SSI_MX35, FSL_SSI_MX51, }; struct fsl_ssi_reg_val { u32 sier; u32 srcr; u32 stcr; u32 scr; }; struct <API key> { struct fsl_ssi_reg_val rx; struct fsl_ssi_reg_val tx; }; static bool <API key>(struct device *dev, unsigned int reg) { switch (reg) { case CCSR_SSI_STX0: case CCSR_SSI_STX1: case CCSR_SSI_SRX0: case CCSR_SSI_SRX1: case CCSR_SSI_SCR: case CCSR_SSI_SISR: case CCSR_SSI_SIER: case CCSR_SSI_STCR: case CCSR_SSI_SRCR: case CCSR_SSI_STCCR: case CCSR_SSI_SRCCR: case CCSR_SSI_SFCSR: case CCSR_SSI_STR: case CCSR_SSI_SOR: case CCSR_SSI_SACNT: case CCSR_SSI_SACADD: case CCSR_SSI_SACDAT: case CCSR_SSI_SATAG: case CCSR_SSI_STMSK: case CCSR_SSI_SRMSK: case CCSR_SSI_SACCST: case CCSR_SSI_SACCEN: case CCSR_SSI_SACCDIS: return true; default: return false; } } static bool <API key>(struct device *dev, unsigned int reg) { switch (reg) { case CCSR_SSI_STX0: case CCSR_SSI_STX1: case CCSR_SSI_SRX0: case CCSR_SSI_SRX1: case CCSR_SSI_SISR: case CCSR_SSI_SFCSR: case CCSR_SSI_SACADD: case CCSR_SSI_SACDAT: case CCSR_SSI_SATAG: case CCSR_SSI_SACCST: return true; default: return false; } } static bool <API key>(struct device *dev, unsigned int reg) { switch (reg) { case CCSR_SSI_STX0: case CCSR_SSI_STX1: case CCSR_SSI_SCR: case CCSR_SSI_SISR: case CCSR_SSI_SIER: case CCSR_SSI_STCR: case CCSR_SSI_SRCR: case CCSR_SSI_STCCR: case CCSR_SSI_SRCCR: case CCSR_SSI_SFCSR: case CCSR_SSI_STR: case CCSR_SSI_SOR: case CCSR_SSI_SACNT: case CCSR_SSI_SACADD: case CCSR_SSI_SACDAT: case CCSR_SSI_SATAG: case CCSR_SSI_STMSK: case CCSR_SSI_SRMSK: case CCSR_SSI_SACCEN: case CCSR_SSI_SACCDIS: return true; default: return false; } } static const struct regmap_config fsl_ssi_regconfig = { .max_register = CCSR_SSI_SACCDIS, .reg_bits = 32, .val_bits = 32, .reg_stride = 4, .val_format_endian = <API key>, .readable_reg = <API key>, .volatile_reg = <API key>, .writeable_reg = <API key>, .cache_type = REGCACHE_RBTREE, }; struct fsl_ssi_soc_data { bool imx; bool offline_config; u32 sisr_write_mask; }; /** * fsl_ssi_private: per-SSI private data * * @reg: Pointer to the regmap registers * @irq: IRQ of this SSI * @cpu_dai_drv: CPU DAI driver for this device * * @dai_fmt: DAI configuration this device is currently used with * @i2s_mode: i2s and network mode configuration of the device. Is used to * switch between normal and i2s/network mode * mode depending on the number of channels * @use_dma: DMA is used or FIQ with stream filter * @use_dual_fifo: DMA with support for both FIFOs used * @fifo_deph: Depth of the SSI FIFOs * @rxtx_reg_val: Specific register settings for receive/transmit configuration * * @clk: SSI clock * @baudclk: SSI baud clock for master mode * @baudclk_streams: Active streams that are using baudclk * @bitclk_freq: bitclock frequency set by .set_dai_sysclk * * @dma_params_tx: DMA transmit parameters * @dma_params_rx: DMA receive parameters * @ssi_phys: physical address of the SSI registers * * @fiq_params: FIQ stream filtering parameters * * @pdev: Pointer to pdev used for deprecated fsl-ssi sound card * * @dbg_stats: Debugging statistics * * @soc: SoC specifc data */ struct fsl_ssi_private { struct regmap *regs; unsigned int irq; struct snd_soc_dai_driver cpu_dai_drv; unsigned int dai_fmt; u8 i2s_mode; bool use_dma; bool use_dual_fifo; bool has_ipg_clk_name; unsigned int fifo_depth; struct <API key> rxtx_reg_val; struct clk *clk; struct clk *baudclk; unsigned int baudclk_streams; unsigned int bitclk_freq; /*regcache for SFCSR*/ u32 regcache_sfcsr; /* DMA params */ struct <API key> dma_params_tx; struct <API key> dma_params_rx; dma_addr_t ssi_phys; /* params for non-dma FIQ stream filtered mode */ struct imx_pcm_fiq_params fiq_params; /* Used when using fsl-ssi as sound-card. This is only used by ppc and * should be replaced with simple-sound-card. */ struct platform_device *pdev; struct fsl_ssi_dbg dbg_stats; const struct fsl_ssi_soc_data *soc; }; /* * imx51 and later SoCs have a slightly different IP that allows the * SSI configuration while the SSI unit is running. * * More important, it is necessary on those SoCs to configure the * sperate TX/RX DMA bits just before starting the stream * (fsl_ssi_trigger). The SDMA unit has to be configured before fsl_ssi * sends any DMA requests to the SDMA unit, otherwise it is not defined * how the SDMA unit handles the DMA request. * * SDMA units are present on devices starting at imx35 but the imx35 * reference manual states that the DMA bits should not be changed * while the SSI unit is running (SSIEN). So we support the necessary * online configuration of fsl-ssi starting at imx51. */ static struct fsl_ssi_soc_data fsl_ssi_mpc8610 = { .imx = false, .offline_config = true, .sisr_write_mask = CCSR_SSI_SISR_RFRC | CCSR_SSI_SISR_TFRC | CCSR_SSI_SISR_ROE0 | CCSR_SSI_SISR_ROE1 | CCSR_SSI_SISR_TUE0 | CCSR_SSI_SISR_TUE1, }; static struct fsl_ssi_soc_data fsl_ssi_imx21 = { .imx = true, .offline_config = true, .sisr_write_mask = 0, }; static struct fsl_ssi_soc_data fsl_ssi_imx35 = { .imx = true, .offline_config = true, .sisr_write_mask = CCSR_SSI_SISR_RFRC | CCSR_SSI_SISR_TFRC | CCSR_SSI_SISR_ROE0 | CCSR_SSI_SISR_ROE1 | CCSR_SSI_SISR_TUE0 | CCSR_SSI_SISR_TUE1, }; static struct fsl_ssi_soc_data fsl_ssi_imx51 = { .imx = true, .offline_config = false, .sisr_write_mask = CCSR_SSI_SISR_ROE0 | CCSR_SSI_SISR_ROE1 | CCSR_SSI_SISR_TUE0 | CCSR_SSI_SISR_TUE1, }; static const struct of_device_id fsl_ssi_ids[] = { { .compatible = "fsl,mpc8610-ssi", .data = &fsl_ssi_mpc8610 }, { .compatible = "fsl,imx51-ssi", .data = &fsl_ssi_imx51 }, { .compatible = "fsl,imx35-ssi", .data = &fsl_ssi_imx35 }, { .compatible = "fsl,imx21-ssi", .data = &fsl_ssi_imx21 }, {} }; MODULE_DEVICE_TABLE(of, fsl_ssi_ids); static bool fsl_ssi_is_ac97(struct fsl_ssi_private *ssi_private) { return !!(ssi_private->dai_fmt & SND_SOC_DAIFMT_AC97); } static bool <API key>(struct fsl_ssi_private *ssi_private) { return (ssi_private->dai_fmt & <API key>) == <API key>; } /** * fsl_ssi_isr: SSI interrupt handler * * Although it's possible to use the interrupt handler to send and receive * data to/from the SSI, we use the DMA instead. Programming is more * complicated, but the performance is much better. * * This interrupt handler is used only to gather statistics. * * @irq: IRQ of the SSI device * @dev_id: pointer to the ssi_private structure for this SSI device */ static irqreturn_t fsl_ssi_isr(int irq, void *dev_id) { struct fsl_ssi_private *ssi_private = dev_id; struct regmap *regs = ssi_private->regs; __be32 sisr; __be32 sisr2; /* We got an interrupt, so read the status register to see what we were interrupted for. We mask it with the Interrupt Enable register so that we only check for events that we're interested in. */ regmap_read(regs, CCSR_SSI_SISR, &sisr); sisr2 = sisr & ssi_private->soc->sisr_write_mask; /* Clear the bits that we set */ if (sisr2) regmap_write(regs, CCSR_SSI_SISR, sisr2); fsl_ssi_dbg_isr(&ssi_private->dbg_stats, sisr); return IRQ_HANDLED; } /* * Enable/Disable all rx/tx config flags at once. */ static void fsl_ssi_rxtx_config(struct fsl_ssi_private *ssi_private, bool enable) { struct regmap *regs = ssi_private->regs; struct <API key> *vals = &ssi_private->rxtx_reg_val; if (enable) { regmap_update_bits(regs, CCSR_SSI_SIER, vals->rx.sier | vals->tx.sier, vals->rx.sier | vals->tx.sier); regmap_update_bits(regs, CCSR_SSI_SRCR, vals->rx.srcr | vals->tx.srcr, vals->rx.srcr | vals->tx.srcr); regmap_update_bits(regs, CCSR_SSI_STCR, vals->rx.stcr | vals->tx.stcr, vals->rx.stcr | vals->tx.stcr); } else { regmap_update_bits(regs, CCSR_SSI_SRCR, vals->rx.srcr | vals->tx.srcr, 0); regmap_update_bits(regs, CCSR_SSI_STCR, vals->rx.stcr | vals->tx.stcr, 0); regmap_update_bits(regs, CCSR_SSI_SIER, vals->rx.sier | vals->tx.sier, 0); } } /* * Calculate the bits that have to be disabled for the current stream that is * getting disabled. This keeps the bits enabled that are necessary for the * second stream to work if 'stream_active' is true. * * Detailed calculation: * These are the values that need to be active after disabling. For non-active * second stream, this is 0: * vals_stream * !!stream_active * * The following computes the overall differences between the setup for the * to-disable stream and the active stream, a simple XOR: * vals_disable ^ (vals_stream * !!(stream_active)) * * The full expression adds a mask on all values we care about */ #define fsl_ssi_disable_val(vals_disable, vals_stream, stream_active) \ ((vals_disable) & \ ((vals_disable) ^ ((vals_stream) * (u32)!!(stream_active)))) /* * Enable/Disable a ssi configuration. You have to pass either * ssi_private->rxtx_reg_val.rx or tx as vals parameter. */ static void fsl_ssi_config(struct fsl_ssi_private *ssi_private, bool enable, struct fsl_ssi_reg_val *vals) { struct regmap *regs = ssi_private->regs; struct fsl_ssi_reg_val *avals; int nr_active_streams; u32 scr_val; int keep_active; regmap_read(regs, CCSR_SSI_SCR, &scr_val); nr_active_streams = !!(scr_val & CCSR_SSI_SCR_TE) + !!(scr_val & CCSR_SSI_SCR_RE); if (nr_active_streams - 1 > 0) keep_active = 1; else keep_active = 0; /* Find the other direction values rx or tx which we do not want to * modify */ if (&ssi_private->rxtx_reg_val.rx == vals) avals = &ssi_private->rxtx_reg_val.tx; else avals = &ssi_private->rxtx_reg_val.rx; /* If vals should be disabled, start with disabling the unit */ if (!enable) { u32 scr = fsl_ssi_disable_val(vals->scr, avals->scr, keep_active); regmap_update_bits(regs, CCSR_SSI_SCR, scr, 0); } /* * We are running on a SoC which does not support online SSI * reconfiguration, so we have to enable all necessary flags at once * even if we do not use them later (capture and playback configuration) */ if (ssi_private->soc->offline_config) { if ((enable && !nr_active_streams) || (!enable && !keep_active)) fsl_ssi_rxtx_config(ssi_private, enable); goto config_done; } /* * Configure single direction units while the SSI unit is running * (online configuration) */ if (enable) { regmap_update_bits(regs, CCSR_SSI_SIER, vals->sier, vals->sier); regmap_update_bits(regs, CCSR_SSI_SRCR, vals->srcr, vals->srcr); regmap_update_bits(regs, CCSR_SSI_STCR, vals->stcr, vals->stcr); } else { u32 sier; u32 srcr; u32 stcr; /* * Disabling the necessary flags for one of rx/tx while the * other stream is active is a little bit more difficult. We * have to disable only those flags that differ between both * streams (rx XOR tx) and that are set in the stream that is * disabled now. Otherwise we could alter flags of the other * stream */ /* These assignments are simply vals without bits set in avals*/ sier = fsl_ssi_disable_val(vals->sier, avals->sier, keep_active); srcr = fsl_ssi_disable_val(vals->srcr, avals->srcr, keep_active); stcr = fsl_ssi_disable_val(vals->stcr, avals->stcr, keep_active); regmap_update_bits(regs, CCSR_SSI_SRCR, srcr, 0); regmap_update_bits(regs, CCSR_SSI_STCR, stcr, 0); regmap_update_bits(regs, CCSR_SSI_SIER, sier, 0); } config_done: /* Enabling of subunits is done after configuration */ if (enable) regmap_update_bits(regs, CCSR_SSI_SCR, vals->scr, vals->scr); } static void fsl_ssi_rx_config(struct fsl_ssi_private *ssi_private, bool enable) { fsl_ssi_config(ssi_private, enable, &ssi_private->rxtx_reg_val.rx); } static void fsl_ssi_tx_config(struct fsl_ssi_private *ssi_private, bool enable) { fsl_ssi_config(ssi_private, enable, &ssi_private->rxtx_reg_val.tx); } /* * Setup rx/tx register values used to enable/disable the streams. These will * be used later in fsl_ssi_config to setup the streams without the need to * check for all different SSI modes. */ static void <API key>(struct fsl_ssi_private *ssi_private) { struct <API key> *reg = &ssi_private->rxtx_reg_val; reg->rx.sier = <API key>; reg->rx.srcr = CCSR_SSI_SRCR_RFEN0; reg->rx.scr = 0; reg->tx.sier = <API key>; reg->tx.stcr = CCSR_SSI_STCR_TFEN0; reg->tx.scr = 0; if (!fsl_ssi_is_ac97(ssi_private)) { reg->rx.scr = CCSR_SSI_SCR_SSIEN | CCSR_SSI_SCR_RE; reg->rx.sier |= <API key>; reg->tx.scr = CCSR_SSI_SCR_SSIEN | CCSR_SSI_SCR_TE; reg->tx.sier |= <API key>; } if (ssi_private->use_dma) { reg->rx.sier |= CCSR_SSI_SIER_RDMAE; reg->tx.sier |= CCSR_SSI_SIER_TDMAE; } else { reg->rx.sier |= CCSR_SSI_SIER_RIE; reg->tx.sier |= CCSR_SSI_SIER_TIE; } reg->rx.sier |= <API key>; reg->tx.sier |= <API key>; } static void fsl_ssi_setup_ac97(struct fsl_ssi_private *ssi_private) { struct regmap *regs = ssi_private->regs; /* * Setup the clock control register */ regmap_write(regs, CCSR_SSI_STCCR, CCSR_SSI_SxCCR_WL(17) | CCSR_SSI_SxCCR_DC(13)); regmap_write(regs, CCSR_SSI_SRCCR, CCSR_SSI_SxCCR_WL(17) | CCSR_SSI_SxCCR_DC(13)); /* * Enable AC97 mode and startup the SSI */ regmap_write(regs, CCSR_SSI_SACNT, <API key> | CCSR_SSI_SACNT_FV); regmap_write(regs, CCSR_SSI_SACCDIS, 0xff); regmap_write(regs, CCSR_SSI_SACCEN, 0x300); /* * Enable SSI, Transmit and Receive. AC97 has to communicate with the * codec before a stream is started. */ regmap_update_bits(regs, CCSR_SSI_SCR, CCSR_SSI_SCR_SSIEN | CCSR_SSI_SCR_TE | CCSR_SSI_SCR_RE, CCSR_SSI_SCR_SSIEN | CCSR_SSI_SCR_TE | CCSR_SSI_SCR_RE); regmap_write(regs, CCSR_SSI_SOR, CCSR_SSI_SOR_WAIT(3)); } /** * fsl_ssi_startup: create a new substream * * This is the first function called when a stream is opened. * * If this is the first stream open, then grab the IRQ and program most of * the SSI registers. */ static int fsl_ssi_startup(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct fsl_ssi_private *ssi_private = <API key>(rtd->cpu_dai); int ret; ret = clk_prepare_enable(ssi_private->clk); if (ret) return ret; pm_runtime_get_sync(dai->dev); /* When using dual fifo mode, it is safer to ensure an even period * size. If appearing to an odd number while DMA always starts its * task from fifo0, fifo1 would be neglected at the end of each * period. But SSI would still access fifo1 with an invalid data. */ if (ssi_private->use_dual_fifo) <API key>(substream->runtime, 0, <API key>, 2); return 0; } /** * fsl_ssi_shutdown: shutdown the SSI * */ static void fsl_ssi_shutdown(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct fsl_ssi_private *ssi_private = <API key>(rtd->cpu_dai); pm_runtime_put_sync(dai->dev); <API key>(ssi_private->clk); } /** * fsl_ssi_set_bclk - configure Digital Audio Interface bit clock * * Note: This function can be only called when using SSI as DAI master * * Quick instruction for parameters: * freq: Output BCLK frequency = samplerate * 32 (fixed) * channels * dir: SND_SOC_CLOCK_OUT -> TxBCLK, SND_SOC_CLOCK_IN -> RxBCLK. */ static int fsl_ssi_set_bclk(struct snd_pcm_substream *substream, struct snd_soc_dai *cpu_dai, struct snd_pcm_hw_params *hw_params) { struct fsl_ssi_private *ssi_private = <API key>(cpu_dai); struct regmap *regs = ssi_private->regs; int synchronous = ssi_private->cpu_dai_drv.symmetric_rates, ret; u32 pm = 999, div2, psr, stccr, mask, afreq, factor, i; unsigned long clkrate, baudrate, tmprate; u64 sub, savesub = 100000; unsigned int freq; bool baudclk_is_used; /* Prefer the explicitly set bitclock frequency */ if (ssi_private->bitclk_freq) freq = ssi_private->bitclk_freq; else freq = params_channels(hw_params) * 32 * params_rate(hw_params); /* Don't apply it to any non-baudclk circumstance */ if (IS_ERR(ssi_private->baudclk)) return -EINVAL; baudclk_is_used = ssi_private->baudclk_streams & ~(BIT(substream->stream)); /* It should be already enough to divide clock by setting pm alone */ psr = 0; div2 = 0; factor = (div2 + 1) * (7 * psr + 1) * 2; for (i = 0; i < 255; i++) { /* The bclk rate must be smaller than 1/5 sysclk rate */ if (factor * (i + 1) < 5) continue; tmprate = freq * factor * (i + 2); if (baudclk_is_used) clkrate = clk_get_rate(ssi_private->baudclk); else clkrate = clk_round_rate(ssi_private->baudclk, tmprate); clkrate /= factor; afreq = clkrate / (i + 1); if (freq == afreq) sub = 0; else if (freq / afreq == 1) sub = freq - afreq; else if (afreq / freq == 1) sub = afreq - freq; else continue; /* Calculate the fraction */ sub *= 100000; do_div(sub, freq); if (sub < savesub) { baudrate = tmprate; savesub = sub; pm = i; } /* We are lucky */ if (savesub == 0) break; } /* No proper pm found if it is still remaining the initial value */ if (pm == 999) { dev_err(cpu_dai->dev, "failed to handle the required sysclk\n"); return -EINVAL; } stccr = CCSR_SSI_SxCCR_PM(pm + 1) | (div2 ? CCSR_SSI_SxCCR_DIV2 : 0) | (psr ? CCSR_SSI_SxCCR_PSR : 0); mask = <API key> | CCSR_SSI_SxCCR_DIV2 | CCSR_SSI_SxCCR_PSR; if (substream->stream == <API key> || synchronous) regmap_update_bits(regs, CCSR_SSI_STCCR, mask, stccr); else regmap_update_bits(regs, CCSR_SSI_SRCCR, mask, stccr); if (!baudclk_is_used) { ret = clk_set_rate(ssi_private->baudclk, baudrate); if (ret) { dev_err(cpu_dai->dev, "failed to set baudclk rate\n"); return -EINVAL; } } return 0; } static int <API key>(struct snd_soc_dai *cpu_dai, int clk_id, unsigned int freq, int dir) { struct fsl_ssi_private *ssi_private = <API key>(cpu_dai); ssi_private->bitclk_freq = freq; return 0; } /** * fsl_ssi_hw_params - program the sample size * * Most of the SSI registers have been programmed in the startup function, * but the word length must be programmed here. Unfortunately, programming * the SxCCR.WL bits requires the SSI to be temporarily disabled. This can * cause a problem with supporting simultaneous playback and capture. If * the SSI is already playing a stream, then that stream may be temporarily * stopped when you start capture. * * Note: The SxCCR.DC and SxCCR.PM bits are only used if the SSI is the * clock master. */ static int fsl_ssi_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *hw_params, struct snd_soc_dai *cpu_dai) { struct fsl_ssi_private *ssi_private = <API key>(cpu_dai); struct regmap *regs = ssi_private->regs; unsigned int channels = params_channels(hw_params); unsigned int sample_size = <API key>(params_format(hw_params)); u32 wl = CCSR_SSI_SxCCR_WL(sample_size); int ret; u32 scr_val; int enabled; regmap_read(regs, CCSR_SSI_SCR, &scr_val); enabled = scr_val & CCSR_SSI_SCR_SSIEN; /* * If we're in synchronous mode, and the SSI is already enabled, * then STCCR is already set properly. */ if (enabled && ssi_private->cpu_dai_drv.symmetric_rates) return 0; if (<API key>(ssi_private)) { ret = fsl_ssi_set_bclk(substream, cpu_dai, hw_params); if (ret) return ret; /* Do not enable the clock if it is already enabled */ if (!(ssi_private->baudclk_streams & BIT(substream->stream))) { ret = clk_prepare_enable(ssi_private->baudclk); if (ret) return ret; ssi_private->baudclk_streams |= BIT(substream->stream); } } /* * FIXME: The documentation says that SxCCR[WL] should not be * modified while the SSI is enabled. The only time this can * happen is if we're trying to do simultaneous playback and * capture in asynchronous mode. Unfortunately, I have been enable * to get that to work at all on the P1022DS. Therefore, we don't * bother to disable/enable the SSI when setting SxCCR[WL], because * the SSI will stop anyway. Maybe one day, this will get fixed. */ /* In synchronous mode, the SSI uses STCCR for capture */ if ((substream->stream == <API key>) || ssi_private->cpu_dai_drv.symmetric_rates) regmap_update_bits(regs, CCSR_SSI_STCCR, <API key>, wl); else regmap_update_bits(regs, CCSR_SSI_SRCCR, <API key>, wl); if (!fsl_ssi_is_ac97(ssi_private)) regmap_update_bits(regs, CCSR_SSI_SCR, CCSR_SSI_SCR_NET | <API key>, channels == 1 ? 0 : ssi_private->i2s_mode); return 0; } static int fsl_ssi_hw_free(struct snd_pcm_substream *substream, struct snd_soc_dai *cpu_dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct fsl_ssi_private *ssi_private = <API key>(rtd->cpu_dai); if (<API key>(ssi_private) && ssi_private->baudclk_streams & BIT(substream->stream)) { <API key>(ssi_private->baudclk); ssi_private->baudclk_streams &= ~BIT(substream->stream); } return 0; } static int <API key>(struct fsl_ssi_private *ssi_private, unsigned int fmt) { struct regmap *regs = ssi_private->regs; u32 strcr = 0, stcr, srcr, scr, mask; u8 wm; ssi_private->dai_fmt = fmt; if (<API key>(ssi_private) && IS_ERR(ssi_private->baudclk)) { dev_err(&ssi_private->pdev->dev, "baudclk is missing which is necessary for master mode\n"); return -EINVAL; } <API key>(ssi_private); regmap_read(regs, CCSR_SSI_SCR, &scr); scr &= ~(CCSR_SSI_SCR_SYN | <API key>); scr |= <API key>; mask = <API key> | CCSR_SSI_STCR_TFDIR | CCSR_SSI_STCR_TXDIR | CCSR_SSI_STCR_TSCKP | CCSR_SSI_STCR_TFSI | CCSR_SSI_STCR_TFSL | CCSR_SSI_STCR_TEFS; regmap_read(regs, CCSR_SSI_STCR, &stcr); regmap_read(regs, CCSR_SSI_SRCR, &srcr); stcr &= ~mask; srcr &= ~mask; ssi_private->i2s_mode = CCSR_SSI_SCR_NET; switch (fmt & <API key>) { case SND_SOC_DAIFMT_I2S: switch (fmt & <API key>) { case <API key>: ssi_private->i2s_mode |= <API key>; regmap_update_bits(regs, CCSR_SSI_STCCR, <API key>, CCSR_SSI_SxCCR_DC(2)); regmap_update_bits(regs, CCSR_SSI_SRCCR, <API key>, CCSR_SSI_SxCCR_DC(2)); break; case <API key>: ssi_private->i2s_mode |= <API key>; break; default: return -EINVAL; } /* Data on rising edge of bclk, frame low, 1clk before data */ strcr |= CCSR_SSI_STCR_TFSI | CCSR_SSI_STCR_TSCKP | <API key> | CCSR_SSI_STCR_TEFS; break; case <API key>: /* Data on rising edge of bclk, frame high */ strcr |= <API key> | CCSR_SSI_STCR_TSCKP; break; case <API key>: /* Data on rising edge of bclk, frame high, 1clk before data */ strcr |= CCSR_SSI_STCR_TFSL | CCSR_SSI_STCR_TSCKP | <API key> | CCSR_SSI_STCR_TEFS; break; case <API key>: /* Data on rising edge of bclk, frame high */ strcr |= CCSR_SSI_STCR_TFSL | CCSR_SSI_STCR_TSCKP | <API key>; break; case SND_SOC_DAIFMT_AC97: ssi_private->i2s_mode |= <API key>; break; default: return -EINVAL; } scr |= ssi_private->i2s_mode; /* DAI clock inversion */ switch (fmt & <API key>) { case <API key>: /* Nothing to do for both normal cases */ break; case <API key>: /* Invert bit clock */ strcr ^= CCSR_SSI_STCR_TSCKP; break; case <API key>: /* Invert frame clock */ strcr ^= CCSR_SSI_STCR_TFSI; break; case <API key>: /* Invert both clocks */ strcr ^= CCSR_SSI_STCR_TSCKP; strcr ^= CCSR_SSI_STCR_TFSI; break; default: return -EINVAL; } /* DAI clock master masks */ switch (fmt & <API key>) { case <API key>: strcr |= CCSR_SSI_STCR_TFDIR | CCSR_SSI_STCR_TXDIR; scr |= <API key>; break; case <API key>: scr &= ~<API key>; break; default: return -EINVAL; } stcr |= strcr; srcr |= strcr; if (ssi_private->cpu_dai_drv.symmetric_rates) { /* Need to clear RXDIR when using SYNC mode */ srcr &= ~CCSR_SSI_SRCR_RXDIR; scr |= CCSR_SSI_SCR_SYN; } regmap_write(regs, CCSR_SSI_STCR, stcr); regmap_write(regs, CCSR_SSI_SRCR, srcr); regmap_write(regs, CCSR_SSI_SCR, scr); /* * Set the watermark for transmit FIFI 0 and receive FIFO 0. We don't * use FIFO 1. We program the transmit water to signal a DMA transfer * if there are only two (or fewer) elements left in the FIFO. Two * elements equals one frame (left channel, right channel). This value, * however, depends on the depth of the transmit buffer. * * We set the watermark on the same level as the DMA burstsize. For * fiq it is probably better to use the biggest possible watermark * size. */ if (ssi_private->use_dma) wm = ssi_private->fifo_depth - 2; else wm = ssi_private->fifo_depth; regmap_write(regs, CCSR_SSI_SFCSR, <API key>(wm) | <API key>(wm) | <API key>(wm) | <API key>(wm)); if (ssi_private->use_dual_fifo) { regmap_update_bits(regs, CCSR_SSI_SRCR, CCSR_SSI_SRCR_RFEN1, CCSR_SSI_SRCR_RFEN1); regmap_update_bits(regs, CCSR_SSI_STCR, CCSR_SSI_STCR_TFEN1, CCSR_SSI_STCR_TFEN1); regmap_update_bits(regs, CCSR_SSI_SCR, CCSR_SSI_SCR_TCH_EN, CCSR_SSI_SCR_TCH_EN); } if (fmt & SND_SOC_DAIFMT_AC97) fsl_ssi_setup_ac97(ssi_private); return 0; } /** * fsl_ssi_set_dai_fmt - configure Digital Audio Interface Format. */ static int fsl_ssi_set_dai_fmt(struct snd_soc_dai *cpu_dai, unsigned int fmt) { struct fsl_ssi_private *ssi_private = <API key>(cpu_dai); return <API key>(ssi_private, fmt); } /** * <API key> - set TDM slot number * * Note: This function can be only called when using SSI as DAI master */ static int <API key>(struct snd_soc_dai *cpu_dai, u32 tx_mask, u32 rx_mask, int slots, int slot_width) { struct fsl_ssi_private *ssi_private = <API key>(cpu_dai); struct regmap *regs = ssi_private->regs; u32 val; /* The slot number should be >= 2 if using Network mode or I2S mode */ regmap_read(regs, CCSR_SSI_SCR, &val); val &= <API key> | CCSR_SSI_SCR_NET; if (val && slots < 2) { dev_err(cpu_dai->dev, "slot number should be >= 2 in I2S or NET\n"); return -EINVAL; } regmap_update_bits(regs, CCSR_SSI_STCCR, <API key>, CCSR_SSI_SxCCR_DC(slots)); regmap_update_bits(regs, CCSR_SSI_SRCCR, <API key>, CCSR_SSI_SxCCR_DC(slots)); /* The register SxMSKs needs SSI to provide essential clock due to * hardware design. So we here temporarily enable SSI to set them. */ regmap_read(regs, CCSR_SSI_SCR, &val); val &= CCSR_SSI_SCR_SSIEN; regmap_update_bits(regs, CCSR_SSI_SCR, CCSR_SSI_SCR_SSIEN, CCSR_SSI_SCR_SSIEN); regmap_write(regs, CCSR_SSI_STMSK, tx_mask); regmap_write(regs, CCSR_SSI_SRMSK, rx_mask); regmap_update_bits(regs, CCSR_SSI_SCR, CCSR_SSI_SCR_SSIEN, val); return 0; } /** * fsl_ssi_trigger: start and stop the DMA transfer. * * This function is called by ALSA to start, stop, pause, and resume the DMA * transfer of data. * * The DMA channel is in external master start and pause mode, which * means the SSI completely controls the flow of data. */ static int fsl_ssi_trigger(struct snd_pcm_substream *substream, int cmd, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct fsl_ssi_private *ssi_private = <API key>(rtd->cpu_dai); struct regmap *regs = ssi_private->regs; switch (cmd) { case <API key>: case <API key>: case <API key>: if (substream->stream == <API key>) fsl_ssi_tx_config(ssi_private, true); else fsl_ssi_rx_config(ssi_private, true); break; case <API key>: case <API key>: case <API key>: if (substream->stream == <API key>) fsl_ssi_tx_config(ssi_private, false); else fsl_ssi_rx_config(ssi_private, false); break; default: return -EINVAL; } if (fsl_ssi_is_ac97(ssi_private)) { if (substream->stream == <API key>) regmap_write(regs, CCSR_SSI_SOR, CCSR_SSI_SOR_TX_CLR); else regmap_write(regs, CCSR_SSI_SOR, CCSR_SSI_SOR_RX_CLR); } return 0; } static int fsl_ssi_dai_probe(struct snd_soc_dai *dai) { struct fsl_ssi_private *ssi_private = <API key>(dai); if (ssi_private->soc->imx && ssi_private->use_dma) { dai->playback_dma_data = &ssi_private->dma_params_tx; dai->capture_dma_data = &ssi_private->dma_params_rx; } return 0; } static const struct snd_soc_dai_ops fsl_ssi_dai_ops = { .startup = fsl_ssi_startup, .shutdown = fsl_ssi_shutdown, .hw_params = fsl_ssi_hw_params, .hw_free = fsl_ssi_hw_free, .set_fmt = fsl_ssi_set_dai_fmt, .set_sysclk = <API key>, .set_tdm_slot = <API key>, .trigger = fsl_ssi_trigger, }; /* Template for the CPU dai driver structure */ static struct snd_soc_dai_driver <API key> = { .probe = fsl_ssi_dai_probe, .playback = { .stream_name = "CPU-Playback", .channels_min = 1, .channels_max = 2, .rates = FSLSSI_I2S_RATES, .formats = FSLSSI_I2S_FORMATS, }, .capture = { .stream_name = "CPU-Capture", .channels_min = 1, .channels_max = 2, .rates = FSLSSI_I2S_RATES, .formats = FSLSSI_I2S_FORMATS, }, .ops = &fsl_ssi_dai_ops, }; static const struct <API key> fsl_ssi_component = { .name = "fsl-ssi", }; static struct snd_soc_dai_driver fsl_ssi_ac97_dai = { .ac97_control = 1, .playback = { .stream_name = "AC97 Playback", .channels_min = 2, .channels_max = 2, .rates = <API key>, .formats = <API key>, }, .capture = { .stream_name = "AC97 Capture", .channels_min = 2, .channels_max = 2, .rates = <API key>, .formats = <API key>, }, .ops = &fsl_ssi_dai_ops, }; static struct fsl_ssi_private *fsl_ac97_data; static void fsl_ssi_ac97_write(struct snd_ac97 *ac97, unsigned short reg, unsigned short val) { struct regmap *regs = fsl_ac97_data->regs; unsigned int lreg; unsigned int lval; if (reg > 0x7f) return; lreg = reg << 12; regmap_write(regs, CCSR_SSI_SACADD, lreg); lval = val << 4; regmap_write(regs, CCSR_SSI_SACDAT, lval); regmap_update_bits(regs, CCSR_SSI_SACNT, <API key>, CCSR_SSI_SACNT_WR); udelay(100); } static unsigned short fsl_ssi_ac97_read(struct snd_ac97 *ac97, unsigned short reg) { struct regmap *regs = fsl_ac97_data->regs; unsigned short val = -1; u32 reg_val; unsigned int lreg; lreg = (reg & 0x7f) << 12; regmap_write(regs, CCSR_SSI_SACADD, lreg); regmap_update_bits(regs, CCSR_SSI_SACNT, <API key>, CCSR_SSI_SACNT_RD); udelay(100); regmap_read(regs, CCSR_SSI_SACDAT, &reg_val); val = (reg_val >> 4) & 0xffff; return val; } static struct snd_ac97_bus_ops fsl_ssi_ac97_ops = { .read = fsl_ssi_ac97_read, .write = fsl_ssi_ac97_write, }; /** * Make every character in a string lower-case */ static void make_lowercase(char *s) { char *p = s; char c; while ((c = *p)) { if ((c >= 'A') && (c <= 'Z')) *p = c + ('a' - 'A'); p++; } } static int fsl_ssi_imx_probe(struct platform_device *pdev, struct fsl_ssi_private *ssi_private, void __iomem *iomem) { struct device_node *np = pdev->dev.of_node; u32 dmas[4]; int ret; u32 buffer_size; if (ssi_private->has_ipg_clk_name) ssi_private->clk = devm_clk_get(&pdev->dev, "ipg"); else ssi_private->clk = devm_clk_get(&pdev->dev, NULL); if (IS_ERR(ssi_private->clk)) { ret = PTR_ERR(ssi_private->clk); dev_err(&pdev->dev, "could not get clock: %d\n", ret); return ret; } if (!ssi_private->has_ipg_clk_name) { ret = clk_prepare_enable(ssi_private->clk); if (ret) { dev_err(&pdev->dev, "clk_prepare_enable failed: %d\n", ret); return ret; } } /* For those SLAVE implementations, we ingore non-baudclk cases * and, instead, abandon MASTER mode that needs baud clock. */ ssi_private->baudclk = devm_clk_get(&pdev->dev, "baud"); if (IS_ERR(ssi_private->baudclk)) dev_dbg(&pdev->dev, "could not get baud clock: %ld\n", PTR_ERR(ssi_private->baudclk)); /* * We have burstsize be "fifo_depth - 2" to match the SSI * watermark setting in fsl_ssi_startup(). */ ssi_private->dma_params_tx.maxburst = ssi_private->fifo_depth - 2; ssi_private->dma_params_rx.maxburst = ssi_private->fifo_depth - 2; ssi_private->dma_params_tx.addr = ssi_private->ssi_phys + CCSR_SSI_STX0; ssi_private->dma_params_rx.addr = ssi_private->ssi_phys + CCSR_SSI_SRX0; ret = <API key>(np, "dmas", dmas, 4); if (ssi_private->use_dma && !ret && dmas[2] == <API key>) { ssi_private->use_dual_fifo = true; /* When using dual fifo mode, we need to keep watermark * as even numbers due to dma script limitation. */ ssi_private->dma_params_tx.maxburst &= ~0x1; ssi_private->dma_params_rx.maxburst &= ~0x1; } if (<API key>(np, "fsl,dma-buffer-size", &buffer_size)) buffer_size = IMX_SSI_DMABUF_SIZE; if (!ssi_private->use_dma) { /* * Some boards use an incompatible codec. To get it * working, we are using imx-fiq-pcm-audio, that * can handle those codecs. DMA is not possible in this * situation. */ ssi_private->fiq_params.irq = ssi_private->irq; ssi_private->fiq_params.base = iomem; ssi_private->fiq_params.dma_params_rx = &ssi_private->dma_params_rx; ssi_private->fiq_params.dma_params_tx = &ssi_private->dma_params_tx; ret = imx_pcm_fiq_init(pdev, &ssi_private->fiq_params); if (ret) goto error_pcm; } else { ret = imx_pcm_dma_init(pdev, buffer_size); if (ret) goto error_pcm; } return 0; error_pcm: if (!ssi_private->has_ipg_clk_name) <API key>(ssi_private->clk); return ret; } static void fsl_ssi_imx_clean(struct platform_device *pdev, struct fsl_ssi_private *ssi_private) { if (!ssi_private->use_dma) imx_pcm_fiq_exit(pdev); if (!ssi_private->has_ipg_clk_name) <API key>(ssi_private->clk); } static int fsl_ssi_probe(struct platform_device *pdev) { struct fsl_ssi_private *ssi_private; int ret = 0; struct device_node *np = pdev->dev.of_node; const struct of_device_id *of_id; const char *p, *sprop; const uint32_t *iprop; struct resource res; void __iomem *iomem; char name[64]; /* SSIs that are not connected on the board should have a * status = "disabled" * property in their device tree nodes. */ if (!<API key>(np)) return -ENODEV; of_id = of_match_device(fsl_ssi_ids, &pdev->dev); if (!of_id || !of_id->data) return -EINVAL; ssi_private = devm_kzalloc(&pdev->dev, sizeof(*ssi_private), GFP_KERNEL); if (!ssi_private) { dev_err(&pdev->dev, "could not allocate DAI object\n"); return -ENOMEM; } ssi_private->soc = of_id->data; sprop = of_get_property(np, "fsl,mode", NULL); if (sprop) { if (!strcmp(sprop, "ac97-slave")) ssi_private->dai_fmt = SND_SOC_DAIFMT_AC97; else if (!strcmp(sprop, "i2s-slave")) ssi_private->dai_fmt = SND_SOC_DAIFMT_I2S | <API key>; } ssi_private->use_dma = !<API key>(np, "fsl,fiq-stream-filter"); if (fsl_ssi_is_ac97(ssi_private)) { memcpy(&ssi_private->cpu_dai_drv, &fsl_ssi_ac97_dai, sizeof(fsl_ssi_ac97_dai)); fsl_ac97_data = ssi_private; <API key>(&fsl_ssi_ac97_ops, pdev); } else { /* Initialize this copy of the CPU DAI driver structure */ memcpy(&ssi_private->cpu_dai_drv, &<API key>, sizeof(<API key>)); } ssi_private->cpu_dai_drv.name = dev_name(&pdev->dev); /* Get the addresses and IRQ */ ret = <API key>(np, 0, &res); if (ret) { dev_err(&pdev->dev, "could not determine device resources\n"); return ret; } ssi_private->ssi_phys = res.start; iomem = devm_ioremap(&pdev->dev, res.start, resource_size(&res)); if (!iomem) { dev_err(&pdev->dev, "could not map device resources\n"); return -ENOMEM; } ret = <API key>(np, "clock-names", "ipg"); if (ret < 0) { ssi_private->has_ipg_clk_name = false; ssi_private->regs = <API key>(&pdev->dev, iomem, &fsl_ssi_regconfig); } else { ssi_private->has_ipg_clk_name = true; ssi_private->regs = <API key>(&pdev->dev, "ipg", iomem, &fsl_ssi_regconfig); } if (IS_ERR(ssi_private->regs)) { dev_err(&pdev->dev, "Failed to init register map\n"); return PTR_ERR(ssi_private->regs); } ssi_private->irq = <API key>(np, 0); if (!ssi_private->irq) { dev_err(&pdev->dev, "no irq for node %s\n", np->full_name); return -ENXIO; } /* Are the RX and the TX clocks locked? */ if (!of_find_property(np, "fsl,ssi-asynchronous", NULL)) { ssi_private->cpu_dai_drv.symmetric_rates = 1; ssi_private->cpu_dai_drv.symmetric_channels = 1; ssi_private->cpu_dai_drv.<API key> = 1; } /* Determine the FIFO depth. */ iprop = of_get_property(np, "fsl,fifo-depth", NULL); if (iprop) ssi_private->fifo_depth = be32_to_cpup(iprop); else /* Older 8610 DTs didn't have the fifo-depth property */ ssi_private->fifo_depth = 8; pm_runtime_enable(&pdev->dev); dev_set_drvdata(&pdev->dev, ssi_private); if (ssi_private->soc->imx) { ret = fsl_ssi_imx_probe(pdev, ssi_private, iomem); if (ret) goto error_irqmap; } ret = <API key>(&pdev->dev, &fsl_ssi_component, &ssi_private->cpu_dai_drv, 1); if (ret) { dev_err(&pdev->dev, "failed to register DAI: %d\n", ret); goto error_asoc_register; } if (ssi_private->use_dma) { ret = devm_request_irq(&pdev->dev, ssi_private->irq, fsl_ssi_isr, 0, dev_name(&pdev->dev), ssi_private); if (ret < 0) { dev_err(&pdev->dev, "could not claim irq %u\n", ssi_private->irq); goto error_irq; } } ret = <API key>(&ssi_private->dbg_stats, &pdev->dev); if (ret) goto error_asoc_register; /* * If codec-handle property is missing from SSI node, we assume * that the machine driver uses new binding which does not require * SSI driver to trigger machine driver's probe. */ if (!of_get_property(np, "codec-handle", NULL)) goto done; /* Trigger the machine driver's probe function. The platform driver * name of the machine driver is taken from /compatible property of the * device tree. We also pass the address of the CPU DAI driver * structure. */ sprop = of_get_property(<API key>("/"), "compatible", NULL); /* Sometimes the compatible name has a "fsl," prefix, so we strip it. */ p = strrchr(sprop, ','); if (p) sprop = p + 1; snprintf(name, sizeof(name), "snd-soc-%s", sprop); make_lowercase(name); ssi_private->pdev = <API key>(&pdev->dev, name, 0, NULL, 0); if (IS_ERR(ssi_private->pdev)) { ret = PTR_ERR(ssi_private->pdev); dev_err(&pdev->dev, "failed to register platform: %d\n", ret); goto error_sound_card; } done: if (ssi_private->dai_fmt) <API key>(ssi_private, ssi_private->dai_fmt); return 0; error_sound_card: <API key>(&ssi_private->dbg_stats); error_irq: <API key>(&pdev->dev); error_asoc_register: if (ssi_private->soc->imx) fsl_ssi_imx_clean(pdev, ssi_private); error_irqmap: if (ssi_private->use_dma) irq_dispose_mapping(ssi_private->irq); return ret; } static int fsl_ssi_remove(struct platform_device *pdev) { struct fsl_ssi_private *ssi_private = dev_get_drvdata(&pdev->dev); <API key>(&ssi_private->dbg_stats); if (ssi_private->pdev) <API key>(ssi_private->pdev); <API key>(&pdev->dev); if (ssi_private->soc->imx) fsl_ssi_imx_clean(pdev, ssi_private); if (ssi_private->use_dma) irq_dispose_mapping(ssi_private->irq); return 0; } #ifdef CONFIG_PM_RUNTIME static int <API key>(struct device *dev) { request_bus_freq(BUS_FREQ_AUDIO); return 0; } static int <API key>(struct device *dev) { release_bus_freq(BUS_FREQ_AUDIO); return 0; } #endif #ifdef CONFIG_PM_SLEEP static int fsl_ssi_suspend(struct device *dev) { struct fsl_ssi_private *ssi_private = dev_get_drvdata(dev); struct regmap *regs = ssi_private->regs; regmap_read(regs, CCSR_SSI_SFCSR, &ssi_private->regcache_sfcsr); regcache_cache_only(regs, true); regcache_mark_dirty(regs); return 0; } static int fsl_ssi_resume(struct device *dev) { struct fsl_ssi_private *ssi_private = dev_get_drvdata(dev); struct regmap *regs = ssi_private->regs; regcache_cache_only(regs, false); regmap_update_bits(regs, CCSR_SSI_SFCSR, <API key> | <API key> | <API key> | <API key>, ssi_private->regcache_sfcsr); return regcache_sync(regs); } #endif /* CONFIG_PM_SLEEP */ static const struct dev_pm_ops fsl_ssi_pm = { SET_RUNTIME_PM_OPS(<API key>, <API key>, NULL) <API key>(fsl_ssi_suspend, fsl_ssi_resume) }; static struct platform_driver fsl_ssi_driver = { .driver = { .name = "fsl-ssi-dai", .owner = THIS_MODULE, .of_match_table = fsl_ssi_ids, .pm = &fsl_ssi_pm, }, .probe = fsl_ssi_probe, .remove = fsl_ssi_remove, }; <API key>(fsl_ssi_driver); MODULE_ALIAS("platform:fsl-ssi-dai"); MODULE_AUTHOR("Timur Tabi <timur@freescale.com>"); MODULE_DESCRIPTION("Freescale Synchronous Serial Interface (SSI) ASoC Driver"); MODULE_LICENSE("GPL v2");
/* Generated on Tue Mar 4 13:50:34 EST 2014 */ #include "codelet-rdft.h" #ifdef HAVE_FMA /* Generated by: ../../../genfft/gen_r2cb.native -fma -reorder-insns -<API key> -compact -variables 4 -pipeline-latency 4 -sign 1 -n 16 -name r2cbIII_16 -dft-III -include r2cbIII.h */ /* * This function contains 66 FP additions, 36 FP multiplications, * (or, 46 additions, 16 multiplications, 20 fused multiply/add), * 55 stack variables, 9 constants, and 32 memory accesses */ #include "r2cbIII.h" static void r2cbIII_16(R *R0, R *R1, R *Cr, R *Ci, stride rs, stride csr, stride csi, INT v, INT ivs, INT ovs) { DK(KP668178637, +0.<API key>); DK(KP1_662939224, +1.<API key>); DK(KP198912367, +0.<API key>); DK(KP1_961570560, +1.<API key>); DK(KP707106781, +0.<API key>); DK(KP1_414213562, +1.<API key>); DK(KP414213562, +0.<API key>); DK(KP1_847759065, +1.<API key>); DK(KP2_000000000, +2.<API key>); { INT i; for (i = v; i > 0; i = i - 1, R0 = R0 + ovs, R1 = R1 + ovs, Cr = Cr + ivs, Ci = Ci + ivs, <API key>(64, rs), <API key>(64, csr), <API key>(64, csi)) { E TA, TD, Tv, TG, TE, TF; { E TK, TP, T7, T13, TW, TH, Tj, TC, To, Te, TX, TS, T12, Tt, TB; { E T4, Tf, T3, TU, Tz, T5, Tg, Th; { E T1, T2, Tx, Ty; T1 = Cr[0]; T2 = Cr[WS(csr, 7)]; Tx = Ci[0]; Ty = Ci[WS(csi, 7)]; T4 = Cr[WS(csr, 4)]; Tf = T1 - T2; T3 = T1 + T2; TU = Ty - Tx; Tz = Tx + Ty; T5 = Cr[WS(csr, 3)]; Tg = Ci[WS(csi, 4)]; Th = Ci[WS(csi, 3)]; } { E Tb, Tk, Ta, TR, Tn, Tc, Tq, Tr; { E T8, T9, Tl, Tm; T8 = Cr[WS(csr, 2)]; { E Tw, T6, TV, Ti; Tw = T4 - T5; T6 = T4 + T5; TV = Th - Tg; Ti = Tg + Th; TK = Tw - Tz; TA = Tw + Tz; TP = T3 - T6; T7 = T3 + T6; T13 = TV + TU; TW = TU - TV; TH = Tf + Ti; Tj = Tf - Ti; T9 = Cr[WS(csr, 5)]; } Tl = Ci[WS(csi, 2)]; Tm = Ci[WS(csi, 5)]; Tb = Cr[WS(csr, 1)]; Tk = T8 - T9; Ta = T8 + T9; TR = Tl - Tm; Tn = Tl + Tm; Tc = Cr[WS(csr, 6)]; Tq = Ci[WS(csi, 1)]; Tr = Ci[WS(csi, 6)]; } TC = Tk + Tn; To = Tk - Tn; { E Tp, Td, TQ, Ts; Tp = Tb - Tc; Td = Tb + Tc; TQ = Tr - Tq; Ts = Tq + Tr; Te = Ta + Td; TX = Ta - Td; TS = TQ - TR; T12 = TR + TQ; Tt = Tp - Ts; TB = Tp + Ts; } } } { E T10, TT, TY, TZ; R0[0] = KP2_000000000 * (T7 + Te); R0[WS(rs, 4)] = KP2_000000000 * (T13 - T12); T10 = TP - TS; TT = TP + TS; TY = TW - TX; TZ = TX + TW; { E T11, T14, TI, TL, Tu; T11 = T7 - Te; T14 = T12 + T13; R0[WS(rs, 5)] = KP1_847759065 * (FNMS(KP414213562, TT, TY)); R0[WS(rs, 1)] = KP1_847759065 * (FMA(KP414213562, TY, TT)); R0[WS(rs, 6)] = KP1_414213562 * (T14 - T11); R0[WS(rs, 2)] = KP1_414213562 * (T11 + T14); TD = TB - TC; TI = TC + TB; TL = To - Tt; Tu = To + Tt; { E TO, TJ, TN, TM; R0[WS(rs, 7)] = -(KP1_847759065 * (FNMS(KP414213562, TZ, T10))); R0[WS(rs, 3)] = KP1_847759065 * (FMA(KP414213562, T10, TZ)); TO = FMA(KP707106781, TI, TH); TJ = FNMS(KP707106781, TI, TH); TN = FMA(KP707106781, TL, TK); TM = FNMS(KP707106781, TL, TK); Tv = FMA(KP707106781, Tu, Tj); TG = FNMS(KP707106781, Tu, Tj); R1[WS(rs, 3)] = KP1_961570560 * (FMA(KP198912367, TO, TN)); R1[WS(rs, 7)] = -(KP1_961570560 * (FNMS(KP198912367, TN, TO))); R1[WS(rs, 5)] = KP1_662939224 * (FNMS(KP668178637, TJ, TM)); R1[WS(rs, 1)] = KP1_662939224 * (FMA(KP668178637, TM, TJ)); } } } } TE = FNMS(KP707106781, TD, TA); TF = FMA(KP707106781, TD, TA); R1[WS(rs, 2)] = -(KP1_662939224 * (FNMS(KP668178637, TG, TF))); R1[WS(rs, 6)] = -(KP1_662939224 * (FMA(KP668178637, TF, TG))); R1[WS(rs, 4)] = -(KP1_961570560 * (FMA(KP198912367, Tv, TE))); R1[0] = KP1_961570560 * (FNMS(KP198912367, TE, Tv)); } } } static const kr2c_desc desc = { 16, "r2cbIII_16", {46, 16, 20, 0}, &GENUS }; void X(codelet_r2cbIII_16) (planner *p) { X(kr2c_register) (p, r2cbIII_16, &desc); } #else /* HAVE_FMA */ /* Generated by: ../../../genfft/gen_r2cb.native -compact -variables 4 -pipeline-latency 4 -sign 1 -n 16 -name r2cbIII_16 -dft-III -include r2cbIII.h */ /* * This function contains 66 FP additions, 32 FP multiplications, * (or, 54 additions, 20 multiplications, 12 fused multiply/add), * 40 stack variables, 9 constants, and 32 memory accesses */ #include "r2cbIII.h" static void r2cbIII_16(R *R0, R *R1, R *Cr, R *Ci, stride rs, stride csr, stride csi, INT v, INT ivs, INT ovs) { DK(KP1_961570560, +1.<API key>); DK(KP390180644, +0.<API key>); DK(KP1_111140466, +1.<API key>); DK(KP1_662939224, +1.<API key>); DK(KP707106781, +0.<API key>); DK(KP1_414213562, +1.<API key>); DK(KP765366864, +0.<API key>); DK(KP1_847759065, +1.<API key>); DK(KP2_000000000, +2.<API key>); { INT i; for (i = v; i > 0; i = i - 1, R0 = R0 + ovs, R1 = R1 + ovs, Cr = Cr + ivs, Ci = Ci + ivs, <API key>(64, rs), <API key>(64, csr), <API key>(64, csi)) { E T7, TW, T13, Tj, TD, TK, TP, TH, Te, TX, T12, To, Tt, Tx, TS; E Tw, TT, TY; { E T3, Tf, TC, TV, T6, Tz, Ti, TU; { E T1, T2, TA, TB; T1 = Cr[0]; T2 = Cr[WS(csr, 7)]; T3 = T1 + T2; Tf = T1 - T2; TA = Ci[0]; TB = Ci[WS(csi, 7)]; TC = TA + TB; TV = TB - TA; } { E T4, T5, Tg, Th; T4 = Cr[WS(csr, 4)]; T5 = Cr[WS(csr, 3)]; T6 = T4 + T5; Tz = T4 - T5; Tg = Ci[WS(csi, 4)]; Th = Ci[WS(csi, 3)]; Ti = Tg + Th; TU = Tg - Th; } T7 = T3 + T6; TW = TU + TV; T13 = TV - TU; Tj = Tf - Ti; TD = Tz + TC; TK = Tz - TC; TP = T3 - T6; TH = Tf + Ti; } { E Ta, Tk, Tn, TR, Td, Tp, Ts, TQ; { E T8, T9, Tl, Tm; T8 = Cr[WS(csr, 2)]; T9 = Cr[WS(csr, 5)]; Ta = T8 + T9; Tk = T8 - T9; Tl = Ci[WS(csi, 2)]; Tm = Ci[WS(csi, 5)]; Tn = Tl + Tm; TR = Tl - Tm; } { E Tb, Tc, Tq, Tr; Tb = Cr[WS(csr, 1)]; Tc = Cr[WS(csr, 6)]; Td = Tb + Tc; Tp = Tb - Tc; Tq = Ci[WS(csi, 1)]; Tr = Ci[WS(csi, 6)]; Ts = Tq + Tr; TQ = Tr - Tq; } Te = Ta + Td; TX = Ta - Td; T12 = TR + TQ; To = Tk - Tn; Tt = Tp - Ts; Tx = Tp + Ts; TS = TQ - TR; Tw = Tk + Tn; } R0[0] = KP2_000000000 * (T7 + Te); R0[WS(rs, 4)] = KP2_000000000 * (T13 - T12); TT = TP + TS; TY = TW - TX; R0[WS(rs, 1)] = FMA(KP1_847759065, TT, KP765366864 * TY); R0[WS(rs, 5)] = FNMS(KP765366864, TT, KP1_847759065 * TY); { E T11, T14, TZ, T10; T11 = T7 - Te; T14 = T12 + T13; R0[WS(rs, 2)] = KP1_414213562 * (T11 + T14); R0[WS(rs, 6)] = KP1_414213562 * (T14 - T11); TZ = TP - TS; T10 = TX + TW; R0[WS(rs, 3)] = FMA(KP765366864, TZ, KP1_847759065 * T10); R0[WS(rs, 7)] = FNMS(KP1_847759065, TZ, KP765366864 * T10); } { E TJ, TN, TM, TO, TI, TL; TI = KP707106781 * (Tw + Tx); TJ = TH - TI; TN = TH + TI; TL = KP707106781 * (To - Tt); TM = TK - TL; TO = TL + TK; R1[WS(rs, 1)] = FMA(KP1_662939224, TJ, KP1_111140466 * TM); R1[WS(rs, 7)] = FNMS(KP1_961570560, TN, KP390180644 * TO); R1[WS(rs, 5)] = FNMS(KP1_111140466, TJ, KP1_662939224 * TM); R1[WS(rs, 3)] = FMA(KP390180644, TN, KP1_961570560 * TO); } { E Tv, TF, TE, TG, Tu, Ty; Tu = KP707106781 * (To + Tt); Tv = Tj + Tu; TF = Tj - Tu; Ty = KP707106781 * (Tw - Tx); TE = Ty + TD; TG = Ty - TD; R1[0] = FNMS(KP390180644, TE, KP1_961570560 * Tv); R1[WS(rs, 6)] = FNMS(KP1_662939224, TF, KP1_111140466 * TG); R1[WS(rs, 4)] = -(FMA(KP390180644, Tv, KP1_961570560 * TE)); R1[WS(rs, 2)] = FMA(KP1_111140466, TF, KP1_662939224 * TG); } } } } static const kr2c_desc desc = { 16, "r2cbIII_16", {54, 20, 12, 0}, &GENUS }; void X(codelet_r2cbIII_16) (planner *p) { X(kr2c_register) (p, r2cbIII_16, &desc); } #endif /* HAVE_FMA */
<?php namespace TYPO3\CMS\Extbase\Tests\Unit\Persistence\Generic\Mapper; use TYPO3\CMS\Core\Tests\<API key>; use TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap; use TYPO3\CMS\Core\DataHandling\TableColumnType; use TYPO3\CMS\Core\DataHandling\TableColumnSubType; /** * Test case */ class DataMapFactoryTest extends \TYPO3\CMS\Core\Tests\UnitTestCase { /** * @return array */ public function oneToOneRelation() { return array( array('<API key>'), array('TYPO3\\CMS\\Extbase\\Domain\\Model\\FrontendUser') ); } /** * @test * @dataProvider oneToOneRelation */ public function <API key>($className) { $mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE); $columnConfiguration = array( 'type' => 'select', 'foreign_table' => 'tx_myextension_bar', 'foreign_field' => 'parentid' ); $propertyMetaData = array( 'type' => $className, 'elementType' => NULL ); $mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('setOneToOneRelation', '<API key>', '<API key>'), array(), '', FALSE); $mockDataMapFactory->expects($this->once())->method('setOneToOneRelation')->will($this->returnValue($mockColumnMap)); $mockDataMapFactory->expects($this->never())->method('<API key>'); $mockDataMapFactory->expects($this->never())->method('<API key>'); $mockDataMapFactory->_callRef('setRelations', $mockColumnMap, $columnConfiguration, $propertyMetaData); } /** * @test */ public function <API key>() { $mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE); $matchFields = array( 'fieldname' => 'foo_model' ); $columnConfiguration = array( 'type' => 'select', 'foreign_table' => 'tx_myextension_bar', 'foreign_field' => 'parentid', '<API key>' => $matchFields ); $mockColumnMap->expects($this->once()) ->method('<API key>') ->with($matchFields); $mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy'), array(), '', FALSE); $mockDataMapFactory->_call('setOneToOneRelation', $mockColumnMap, $columnConfiguration); } /** * @test */ public function <API key>() { $mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE); $matchFields = array( 'fieldname' => 'foo_model' ); $columnConfiguration = array( 'type' => 'select', 'foreign_table' => 'tx_myextension_bar', 'foreign_field' => 'parentid', '<API key>' => $matchFields ); $mockColumnMap->expects($this->once()) ->method('<API key>') ->with($matchFields); $mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy'), array(), '', FALSE); $mockDataMapFactory->_call('<API key>', $mockColumnMap, $columnConfiguration); } /** * @test */ public function <API key>() { $mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE); $columnConfiguration = array( 'type' => 'select', 'foreign_table' => 'tx_myextension_bar', 'MM' => 'tx_myextension_mm' ); $propertyMetaData = array( 'type' => '<API key>', 'elementType' => NULL ); $mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('setOneToOneRelation', '<API key>', '<API key>'), array(), '', FALSE); $mockDataMapFactory->expects($this->never())->method('setOneToOneRelation'); $mockDataMapFactory->expects($this->never())->method('<API key>'); $mockDataMapFactory->expects($this->once())->method('<API key>')->will($this->returnValue($mockColumnMap)); $mockDataMapFactory->_callRef('setRelations', $mockColumnMap, $columnConfiguration, $propertyMetaData); } /** * @test */ public function <API key>() { $mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE); $columnConfiguration = array( 'type' => 'select', 'foreign_table' => 'tx_myextension_bar', 'foreign_field' => 'parentid', 'foreign_table_field' => 'parenttable' ); $propertyMetaData = array( 'type' => 'TYPO3\\CMS\\Extbase\\Persistence\\ObjectStorage', 'elementType' => '<API key>' ); $mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('setOneToOneRelation', '<API key>', '<API key>'), array(), '', FALSE); $mockDataMapFactory->expects($this->never())->method('setOneToOneRelation'); $mockDataMapFactory->expects($this->once())->method('<API key>')->will($this->returnValue($mockColumnMap)); $mockDataMapFactory->expects($this->never())->method('<API key>'); $mockDataMapFactory->_callRef('setRelations', $mockColumnMap, $columnConfiguration, $propertyMetaData); } /** * @test */ public function <API key>() { $mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE); $columnConfiguration = array( 'type' => 'select', 'foreign_table' => 'tx_myextension_bar', 'MM' => 'tx_myextension_mm' ); $propertyMetaData = array( 'type' => 'TYPO3\\CMS\\Extbase\\Persistence\\ObjectStorage', 'elementType' => '<API key>' ); $mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('setOneToOneRelation', '<API key>', '<API key>'), array(), '', FALSE); $mockDataMapFactory->expects($this->never())->method('setOneToOneRelation'); $mockDataMapFactory->expects($this->never())->method('<API key>'); $mockDataMapFactory->expects($this->once())->method('<API key>')->will($this->returnValue($mockColumnMap)); $mockDataMapFactory->_callRef('setRelations', $mockColumnMap, $columnConfiguration, $propertyMetaData); } /** * @test */ public function <API key>() { $mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE); $columnConfiguration = array( 'type' => 'inline', 'foreign_table' => '<API key>', 'MM' => 'tx_myextension_mm' ); $propertyMetaData = array( 'type' => 'TYPO3\\CMS\\Extbase\\Persistence\\ObjectStorage', 'elementType' => '<API key>' ); $mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('setOneToOneRelation', '<API key>', '<API key>'), array(), '', FALSE); $mockDataMapFactory->expects($this->never())->method('setOneToOneRelation'); $mockDataMapFactory->expects($this->never())->method('<API key>'); $mockDataMapFactory->expects($this->once())->method('<API key>')->will($this->returnValue($mockColumnMap)); $mockDataMapFactory->_callRef('setRelations', $mockColumnMap, $columnConfiguration, $propertyMetaData); } /** * @test */ public function <API key>() { $<API key> = array( 'rights' => array( 'type' => 'select', 'foreign_table' => '<API key>', 'foreign_table_where' => 'WHERE 1=1', 'MM' => 'tx_myextension_mm', 'MM_table_where' => 'WHERE 2=2' ) ); $mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE); $mockColumnMap->expects($this->once())->method('setTypeOfRelation')->with($this->equalTo(\TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::<API key>)); $mockColumnMap->expects($this->once())->method('<API key>')->with($this->equalTo('tx_myextension_mm')); $mockColumnMap->expects($this->once())->method('setChildTableName')->with($this->equalTo('<API key>')); $mockColumnMap->expects($this->once())->method('<API key>')->with($this->equalTo('WHERE 1=1')); $mockColumnMap->expects($this->once())->method('<API key>')->with($this->equalTo('sorting')); $mockColumnMap->expects($this->once())->method('<API key>')->with($this->equalTo('uid_local')); $mockColumnMap->expects($this->never())->method('<API key>'); $mockColumnMap->expects($this->never())->method('<API key>'); $mockColumnMap->expects($this->never())->method('<API key>'); $mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy'), array(), '', FALSE); $mockDataMapFactory->_callRef('<API key>', $mockColumnMap, $<API key>['rights']); } /** * @test */ public function <API key>() { $<API key> = array( 'lefts' => array( 'type' => 'select', 'foreign_table' => '<API key>', 'MM' => 'tx_myextension_mm', 'MM_opposite_field' => 'rights' ) ); $<API key>['rights']['MM_opposite_field'] = 'opposite_field'; $mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE); $mockColumnMap->expects($this->once())->method('setTypeOfRelation')->with($this->equalTo(\TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::<API key>)); $mockColumnMap->expects($this->once())->method('<API key>')->with($this->equalTo('tx_myextension_mm')); $mockColumnMap->expects($this->once())->method('setChildTableName')->with($this->equalTo('<API key>')); $mockColumnMap->expects($this->once())->method('<API key>')->with(NULL); $mockColumnMap->expects($this->once())->method('<API key>')->with($this->equalTo('sorting_foreign')); $mockColumnMap->expects($this->once())->method('<API key>')->with($this->equalTo('uid_foreign')); $mockColumnMap->expects($this->never())->method('<API key>'); $mockColumnMap->expects($this->never())->method('<API key>'); $mockColumnMap->expects($this->never())->method('<API key>'); $mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy'), array(), '', FALSE); $mockDataMapFactory->_callRef('<API key>', $mockColumnMap, $<API key>['lefts']); } /** * @test */ public function <API key>() { $<API key> = array( 'rights' => array( 'type' => 'inline', 'foreign_table' => '<API key>', 'MM' => 'tx_myextension_mm', 'foreign_sortby' => 'sorting' ) ); $mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE); $mockColumnMap->expects($this->once())->method('setTypeOfRelation')->with($this->equalTo(\TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::<API key>)); $mockColumnMap->expects($this->once())->method('<API key>')->with($this->equalTo('tx_myextension_mm')); $mockColumnMap->expects($this->once())->method('setChildTableName')->with($this->equalTo('<API key>')); $mockColumnMap->expects($this->once())->method('<API key>'); $mockColumnMap->expects($this->once())->method('<API key>')->with($this->equalTo('sorting')); $mockColumnMap->expects($this->once())->method('<API key>')->with($this->equalTo('uid_local')); $mockColumnMap->expects($this->never())->method('<API key>'); $mockColumnMap->expects($this->never())->method('<API key>'); $mockColumnMap->expects($this->never())->method('<API key>'); $mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('<API key>'), array(), '', FALSE); $mockDataMapFactory->expects($this->never())->method('<API key>'); $mockDataMapFactory->_callRef('<API key>', $mockColumnMap, $<API key>['rights']); } /** * @test */ public function <API key>() { $<API key> = array( 'rights' => array( 'type' => 'select', 'foreign_table' => '<API key>', 'foreign_table_where' => 'WHERE 1=1', 'MM' => 'tx_myextension_mm' ) ); $mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE); $mockColumnMap->expects($this->once())->method('<API key>')->with($this->equalTo('tx_myextension_mm')); $mockColumnMap->expects($this->once())->method('<API key>')->will($this->returnValue('tx_myextension_mm')); $mockColumnMap->expects($this->never())->method('<API key>'); $mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('getControlSection'), array(), '', FALSE); $mockDataMapFactory->expects($this->once())->method('getControlSection')->with($this->equalTo('tx_myextension_mm'))->will($this->returnValue(NULL)); $mockDataMapFactory->_callRef('<API key>', $mockColumnMap, $<API key>['rights']); } /** * @test */ public function <API key>() { $<API key> = array( 'rights' => array( 'type' => 'select', 'foreign_table' => '<API key>', 'foreign_table_where' => 'WHERE 1=1', 'MM' => 'tx_myextension_mm' ) ); $mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE); $mockColumnMap->expects($this->once())->method('<API key>')->with($this->equalTo('tx_myextension_mm')); $mockColumnMap->expects($this->once())->method('<API key>')->will($this->returnValue('tx_myextension_mm')); $mockColumnMap->expects($this->once())->method('<API key>')->with($this->equalTo('pid')); $mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('getControlSection'), array(), '', FALSE); $mockDataMapFactory->expects($this->once())->method('getControlSection')->with($this->equalTo('tx_myextension_mm'))->will($this->returnValue(array('ctrl' => array('foo' => 'bar')))); $mockDataMapFactory->_callRef('<API key>', $mockColumnMap, $<API key>['rights']); } /** * @return array */ public function <API key>() { return array( 'date field' => array('date', 'date'), 'datetime field' => array('datetime', 'datetime'), 'no date/datetime field' => array('', NULL), ); } /** * @param string $type * @param NULL|string $expectedValue * @test * @dataProvider <API key> */ public function <API key>($type, $expectedValue) { $columnDefinition = array( 'type' => 'input', 'dbType' => $type, 'eval' => $type, ); $mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array('<API key>'), array(), '', FALSE); if ($expectedValue !== NULL) { $mockColumnMap->expects($this->once())->method('<API key>')->with($this->equalTo($type)); } else { $mockColumnMap->expects($this->never())->method('<API key>'); } $accessibleClassName = $this-><API key>('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory'); $<API key> = new $accessibleClassName(); $<API key>->_callRef('setFieldEvaluations', $mockColumnMap, $columnDefinition); } /** * @test * @expectedException \TYPO3\CMS\Extbase\Persistence\Generic\Exception\<API key> */ public function <API key>() { $mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('getControlSection'), array(), '', FALSE); $cacheMock = $this->getMock('TYPO3\\CMS\\Core\\Cache\\Frontend\\VariableFrontend', array('get'), array(), '', FALSE); $cacheMock->expects($this->any())->method('get')->will($this->returnValue(FALSE)); $mockDataMapFactory->_set('dataMapCache', $cacheMock); $mockDataMapFactory->buildDataMap('UnknownObject'); } /** * @test */ public function <API key>() { $this->markTestSkipped('Incomplete mocking in a complex scenario. This should be a functional test'); $configuration = array( 'persistence' => array( 'classes' => array( 'TYPO3\\CMS\\Extbase\\Domain\\Model\\FrontendUser' => array( 'subclasses' => array( '<API key>' => '<API key>', '<API key>' => '<API key>' ) ), '<API key>' => array( 'subclasses' => array( '<API key>' => '<API key>', '<API key>' => '<API key>' ) ), '<API key>' => array( 'subclasses' => array() ) ) ) ); $expectedSubclasses = array( '<API key>', '<API key>', '<API key>', '<API key>' ); /** @var \TYPO3\CMS\Extbase\Object\<API key>|\<API key> $objectManager */ $objectManager = $this->getMock('TYPO3\\CMS\\Extbase\\Object\\ObjectManager', array('dummy'), array(), '', FALSE); /** @var $<API key> \TYPO3\CMS\Extbase\Configuration\<API key>|\<API key> */ $<API key> = $this->getMock('TYPO3\\CMS\\Extbase\\Configuration\\<API key>'); $<API key>->expects($this->once())->method('getConfiguration')->with('Framework')->will($this->returnValue($configuration)); /** @var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapFactory $dataMapFactory */ $dataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('test')); $dataMapFactory->_set('reflectionService', new \TYPO3\CMS\Extbase\Reflection\ReflectionService()); $dataMapFactory->_set('objectManager', $objectManager); $dataMapFactory->_set('<API key>', $<API key>); $cacheMock = $this->getMock('TYPO3\\CMS\\Core\\Cache\\Frontend\\VariableFrontend', array(), array(), '', FALSE); $cacheMock->expects($this->any())->method('get')->will($this->returnValue(FALSE)); $dataMapFactory->_set('dataMapCache', $cacheMock); $dataMap = $dataMapFactory->buildDataMap('TYPO3\\CMS\\Extbase\\Domain\\Model\\FrontendUser'); $this->assertSame($expectedSubclasses, $dataMap->getSubclasses()); } /** * @return array */ public function <API key>() { return array( 'Core classes' => array('TYPO3\\CMS\\Belog\\Domain\\Model\\LogEntry', '<API key>'), 'Core classes with namespaces and leading backslash' => array('\\TYPO3\\CMS\\Belog\\Domain\\Model\\LogEntry', '<API key>'), 'Extension classes' => array('ExtbaseTeam\\BlogExample\\Domain\\Model\\Blog', '<API key>'), 'Extension classes with namespaces and leading backslash' => array('\\ExtbaseTeam\\BlogExample\\Domain\\Model\\Blog', '<API key>'), 'Extension classes without namespace' => array('<API key>', '<API key>'), 'Extension classes without namespace but leading slash' => array('\\<API key>', '<API key>'), ); } /** * @test * @dataProvider <API key> */ public function <API key>($className, $expected) { $dataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy')); $this->assertSame($expected, $dataMapFactory->_call('resolveTableName', $className)); } /** * @test */ public function <API key>() { /** @var $dataMapFactory \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapFactory */ $dataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy')); /** @var \TYPO3\CMS\Extbase\Object\<API key>|\<API key> $objectManager */ $objectManager = $this->getMock('TYPO3\\CMS\\Extbase\\Object\\ObjectManager'); $columnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array('column', 'property')); $objectManager->expects($this->once())->method('get')->will($this->returnValue($columnMap)); $dataMapFactory->_set('objectManager', $objectManager); $this->assertEquals( $columnMap, $dataMapFactory->_call('createColumnMap', 'column', 'property') ); } /** * @return array */ public function <API key>() { return array( array(array('type' => 'input'), TableColumnType::INPUT, NULL), array(array('type' => 'text'), TableColumnType::TEXT, NULL), array(array('type' => 'check'), TableColumnType::CHECK, NULL), array(array('type' => 'radio'), TableColumnType::RADIO, NULL), array(array('type' => 'select'), TableColumnType::SELECT, NULL), array(array('type' => 'group', 'internal_type' => 'db'), TableColumnType::GROUP, TableColumnSubType::DB), array(array('type' => 'group', 'internal_type' => 'file'), TableColumnType::GROUP, TableColumnSubType::FILE), array(array('type' => 'group', 'internal_type' => 'file_reference'), TableColumnType::GROUP, TableColumnSubType::FILE_REFERENCE), array(array('type' => 'group', 'internal_type' => 'folder'), TableColumnType::GROUP, TableColumnSubType::FOLDER), array(array('type' => 'none'), TableColumnType::NONE, NULL), array(array('type' => 'passthrough'), TableColumnType::PASSTHROUGH, NULL), array(array('type' => 'user'), TableColumnType::USER, NULL), array(array('type' => 'flex'), TableColumnType::FLEX, NULL), array(array('type' => 'inline'), TableColumnType::INLINE, NULL), ); } /** * @test * @dataProvider <API key> * * @param array $columnConfiguration * @param string $type * @param string $internalType */ public function <API key>(array $columnConfiguration, $type, $internalType) { /** @var $dataMapFactory \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapFactory | <API key> */ $dataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy')); /** @var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap $columnMap */ $columnMap = $this->getAccessibleMock('TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap', array('dummy'), array(), '', FALSE); $dataMapFactory->_call('setType', $columnMap, $columnConfiguration); $this->assertEquals($type, (string) $columnMap->getType()); $this->assertEquals($internalType, (string) $columnMap->getInternalType()); } }
# Compile Options include $(MTK_PATH_BUILD)/Makefile WLAN_CHIP_LIST:=-UMT6620 -UMT6628 -UMT5931 -UMT6630 ccflags-y += $(WLAN_CHIP_LIST) WLAN_CHIP_ID=MT6630 ccflags-y:=$(filter-out -U$(WLAN_CHIP_ID),$(ccflags-y)) ccflags-y += -DLINUX -D$(WLAN_CHIP_ID) ifeq ($(HAVE_XLOG_FEATURE), yes) ccflags-y += -DCFG_SUPPORT_XLOG=1 else ccflags-y += -DCFG_SUPPORT_XLOG=0 endif ifeq ($(HAVE_AEE_FEATURE), yes) ccflags-y += -DCFG_SUPPORT_AEE=1 else ccflags-y += -DCFG_SUPPORT_AEE=0 endif # Disable ASSERT() for user load, enable for others ifneq ($(<API key>),user) ccflags-y += -DBUILD_QA_DBG=1 else ccflags-y += -DBUILD_QA_DBG=0 endif ifeq ($(<API key>),y) ccflags-y += -<API key>=1 else ccflags-y += -<API key>=0 endif #ifeq ($(<API key>), y) # ccflags-y += -D_HIF_SDIO=1 #endif ifeq ($(<API key>), yes) ccflags-y += -<API key>=1 ccflags-y += -DCFG_HS20_DEBUG=1 ccflags-y += -<API key>=1 else ifeq ($(<API key>), yes) ccflags-y += -<API key>=1 ccflags-y += -DCFG_HS20_DEBUG=1 ccflags-y += -<API key>=1 else ccflags-y += -<API key>=0 ccflags-y += -DCFG_HS20_DEBUG=0 ccflags-y += -<API key>=0 endif MODULE_NAME := wlan_$(shell echo $(strip $(WLAN_CHIP_ID)) | tr A-Z a-z) ccflags-y += -D_HIF_SDIO=1 ccflags-y += -DDBG=0 ccflags-y += -I$(src)/os -I$(src)/os/linux/include -I$(src)/os/linux/hif/sdio/include ccflags-y += -I$(src)/include -I$(src)/include/nic -I$(src)/include/mgmt obj-$(<API key>) += $(MODULE_NAME).o #obj-y += $(MODULE_NAME).o # Directory List COMMON_DIR := common/ OS_DIR := os/linux/ HIF_DIR := os/linux/hif/sdio/ NIC_DIR := nic/ MGMT_DIR := mgmt/ # Objects List COMMON_OBJS := $(COMMON_DIR)dump.o \ $(COMMON_DIR)wlan_lib.o \ $(COMMON_DIR)wlan_oid.o \ $(COMMON_DIR)wlan_bow.o NIC_OBJS := $(NIC_DIR)nic.o \ $(NIC_DIR)nic_tx.o \ $(NIC_DIR)nic_rx.o \ $(NIC_DIR)nic_pwr_mgt.o \ $(NIC_DIR)nic_rate.o \ $(NIC_DIR)cmd_buf.o \ $(NIC_DIR)que_mgt.o \ $(NIC_DIR)nic_cmd_event.o OS_OBJS := $(OS_DIR)gl_init.o \ $(OS_DIR)gl_kal.o \ $(OS_DIR)gl_bow.o \ $(OS_DIR)gl_wext.o \ $(OS_DIR)gl_wext_priv.o \ $(OS_DIR)gl_rst.o \ $(OS_DIR)gl_cfg80211.o \ $(OS_DIR)platform.o MGMT_OBJS := $(MGMT_DIR)ais_fsm.o \ $(MGMT_DIR)aaa_fsm.o \ $(MGMT_DIR)assoc.o \ $(MGMT_DIR)auth.o \ $(MGMT_DIR)bss.o \ $(MGMT_DIR)cnm.o \ $(MGMT_DIR)cnm_timer.o \ $(MGMT_DIR)cnm_mem.o \ $(MGMT_DIR)hem_mbox.o \ $(MGMT_DIR)mib.o \ $(MGMT_DIR)privacy.o \ $(MGMT_DIR)rate.o \ $(MGMT_DIR)rlm.o \ $(MGMT_DIR)rlm_domain.o \ $(MGMT_DIR)rlm_obss.o \ $(MGMT_DIR)rlm_protection.o \ $(MGMT_DIR)rsn.o \ $(MGMT_DIR)saa_fsm.o \ $(MGMT_DIR)scan.o \ $(MGMT_DIR)scan_fsm.o \ $(MGMT_DIR)swcr.o \ $(MGMT_DIR)roaming_fsm.o \ $(MGMT_DIR)tkip_mic.o \ $(MGMT_DIR)hs20.o \ $(MGMT_DIR)tdls.o # P2P Objects List COMMON_OBJS += $(COMMON_DIR)wlan_p2p.o NIC_OBJS += $(NIC_DIR)p2p_nic.o OS_OBJS += $(OS_DIR)gl_p2p.o \ $(OS_DIR)gl_p2p_cfg80211.o \ $(OS_DIR)gl_p2p_init.o \ $(OS_DIR)gl_p2p_kal.o MGMT_OBJS += $(MGMT_DIR)p2p_dev_fsm.o\ $(MGMT_DIR)p2p_dev_state.o\ $(MGMT_DIR)p2p_role_fsm.o\ $(MGMT_DIR)p2p_role_state.o\ $(MGMT_DIR)p2p_func.o\ $(MGMT_DIR)p2p_scan.o\ $(MGMT_DIR)p2p_ie.o\ $(MGMT_DIR)p2p_rlm.o\ $(MGMT_DIR)p2p_assoc.o\ $(MGMT_DIR)p2p_bss.o\ $(MGMT_DIR)p2p_rlm_obss.o MGMT_OBJS += $(MGMT_DIR)wapi.o ifeq ($(WLAN_PROC), y) OS_OBJS += gl_proc.o endif HIF_OBJS := $(HIF_DIR)arm.o \ $(HIF_DIR)sdio.o $(MODULE_NAME)-objs += $(COMMON_OBJS) $(MODULE_NAME)-objs += $(NIC_OBJS) $(MODULE_NAME)-objs += $(OS_OBJS) $(MODULE_NAME)-objs += $(HIF_OBJS) $(MODULE_NAME)-objs += $(MGMT_OBJS)
# Makefile for the kernel USB device drivers. # Object files in subdirectories obj-$(CONFIG_USB) += core/ obj-$(CONFIG_USB_DWC3) += dwc3/ obj-$(CONFIG_USB_DWC2) += dwc2/ obj-$(CONFIG_USB_MON) += mon/ obj-$(CONFIG_PCI) += host/ obj-$(CONFIG_USB_EHCI_HCD) += host/ obj-$(<API key>) += host/ obj-$(CONFIG_USB_OHCI_HCD) += host/ obj-$(CONFIG_USB_UHCI_HCD) += host/ obj-$(CONFIG_USB_FHCI_HCD) += host/ obj-$(CONFIG_USB_XHCI_HCD) += host/ obj-$(<API key>) += host/ obj-$(<API key>) += host/ obj-$(CONFIG_USB_U132_HCD) += host/ obj-$(<API key>) += host/ obj-$(CONFIG_USB_HWA_HCD) += host/ obj-$(<API key>) += host/ obj-$(<API key>) += host/ obj-$(<API key>) += host/ obj-$(<API key>) += host/ obj-$(<API key>) += host/ obj-$(<API key>) += host/ obj-$(<API key>) += c67x00/ obj-$(CONFIG_USB_WUSB) += wusbcore/ obj-$(CONFIG_USB_ACM) += class/ obj-$(CONFIG_USB_PRINTER) += class/ obj-$(CONFIG_USB_WDM) += class/ obj-$(CONFIG_USB_TMC) += class/ obj-$(CONFIG_USB_STORAGE) += storage/ obj-$(CONFIG_USB) += storage/ obj-$(CONFIG_USB_MDC800) += image/ obj-$(CONFIG_USB_MICROTEK) += image/ obj-$(CONFIG_USB_SERIAL) += serial/ obj-$(CONFIG_USB) += misc/ obj-$(CONFIG_USB_SUPPORT) += phy/ obj-$(<API key>) += early/ obj-$(CONFIG_USB_ATM) += atm/ obj-$(<API key>) += atm/ obj-$(<API key>) += musb/ obj-$(CONFIG_USB_CHIPIDEA) += chipidea/ obj-$(<API key>) += renesas_usbhs/ obj-$(CONFIG_USB_GADGET) += gadget/ obj-$(CONFIG_USB_COMMON) += common/ obj-$(CONFIG_USBIP_CORE) += usbip/ obj-$(<API key>) += notify/ obj-$(<API key>) += manager/
/* * \brief Regulator-session component * \author Stefan Kalkowski * \date 2013-06-13 */ #ifndef <API key> #define <API key> #include <root/component.h> #include <regulator_session/rpc_object.h> #include <regulator/driver.h> namespace Regulator { class Session_component; class Root; } class Regulator::Session_component : public Regulator::Session_rpc_object { private: Driver_factory &_driver_factory; Driver &_driver; public: /** * Constructor */ Session_component(Regulator_id regulator_id, Driver_factory &driver_factory) : Session_rpc_object(regulator_id), _driver_factory(driver_factory), _driver(_driver_factory.create(regulator_id)) { } /** * Destructor */ ~Session_component() { _driver.state(_id, false); _driver_factory.destroy(_driver); } void level(unsigned long level) { _driver.level(_id, level); } unsigned long level() { return _driver.level(_id); } void state(bool enable) { _driver.state(_id, enable); } bool state() { return _driver.state(_id); } }; class Regulator::Root : public Genode::Root_component<Regulator::Session_component> { private: Driver_factory &_driver_factory; Genode::Rpc_entrypoint &_ep; protected: Session_component *_create_session(const char *args) { using namespace Genode; char reg_name[64]; Arg_string::find_arg(args, "regulator").string(reg_name, sizeof(reg_name), 0); size_t ram_quota = Arg_string::find_arg(args, "ram_quota").ulong_value(0); /* delete ram quota by the memory needed for the session */ size_t session_size = max((size_t)4096, sizeof(Session_component)); if (ram_quota < session_size) throw Root::Quota_exceeded(); if (!strlen(reg_name)) throw Root::Invalid_args(); return new (md_alloc()) Session_component(<API key>(reg_name), _driver_factory); } public: Root(Genode::Rpc_entrypoint *session_ep, Genode::Allocator *md_alloc, Driver_factory &driver_factory) : Genode::Root_component<Regulator::Session_component>(session_ep, md_alloc), _driver_factory(driver_factory), _ep(*session_ep) { } }; #endif /* <API key> */
using System; using System.Text.RegularExpressions; using System.Windows.Forms; namespace WikiFunctions { <summary> Factory class for making instances of IArticleComparer </summary> public static class <API key> { <summary> </summary> <param name="comparator">The test string</param> <param name="isCaseSensitive">Whether the comparison should be case sensitive</param> <param name="isRegex">Whether to employ regular expression matching when comparing the test string</param> <param name="isSingleLine">Whether to apply the regular expression Single Line option</param> <param name="isMultiLine">Whether to apply the regular expression Multi Line option</param> <returns>An instance of IArticleComparer which can carry out the specified comparison</returns> public static IArticleComparer Create(string comparator, bool isCaseSensitive, bool isRegex, bool isSingleLine, bool isMultiLine) { if (comparator == null) throw new <API key>("comparator"); if (isRegex) { try { RegexOptions opts = RegexOptions.None; if (!isCaseSensitive) opts |= RegexOptions.IgnoreCase; if (isSingleLine) opts |= RegexOptions.Singleline; if (isMultiLine) opts |= RegexOptions.Multiline; return comparator.Contains("%%") ? (IArticleComparer)new <API key>(comparator, opts) : new <API key>(new Regex(comparator, opts | RegexOptions.Compiled)); } catch (ArgumentException ex) { //TODO: handle things like "bad regex" here // For now, tell the user then let normal exception handling process it as well MessageBox.Show(ex.Message, "Bad Regex"); throw; } } if (comparator.Contains("%%")) return isCaseSensitive ? (IArticleComparer)new <API key>(comparator) : new <API key>(comparator); return isCaseSensitive ? (IArticleComparer)new <API key>(comparator) : new <API key>(comparator); } } <summary> Class for scanning an article for content </summary> public interface IArticleComparer { <summary> Compares the article text against the criteria provided </summary> <param name="article">An article to check</param> <returns>Whether the article's text matches the criteria</returns> bool Matches(Article article); } }
<?php defined('JPATH_BASE') or die; jimport('joomla.form.formfield'); class JFormFieldAbout extends JFormField { protected $type = 'About'; protected function getInput() { return '<div id="gk_about_us">' . JText::_('<API key>') . '</div>'; } } // EOF
INSERT INTO spell_script_names VALUES (2823, 'spell_rog_poisons'), (8679, 'spell_rog_poisons'), (5761, 'spell_rog_poisons'), (3408, 'spell_rog_poisons');
/* testlib.c for c++ - test expectlib */ #include <stdio.h> #include "expect.h" extern "C" { extern int write(...); extern int strlen(...); } void timedout() { fprintf(stderr,"timed out\n"); exit(-1); } char move[100]; void read_first_move(int fd) { if (EXP_TIMEOUT == exp_expectl(fd,exp_glob,"first\r\n1.*\r\n",0,exp_end)) { timedout(); } sscanf(exp_match,"%*s 1. %s",move); } /* moves and counter-moves are printed out in different formats, sigh... */ void read_counter_move(int fd) { switch (exp_expectl(fd,exp_glob,"*...*\r\n",0,exp_end)) { case EXP_TIMEOUT: timedout(); case EXP_EOF: exit(-1); } sscanf(exp_match,"%*s %*s %*s %*s ... %s",move); } void read_move(int fd) { switch (exp_expectl(fd,exp_glob,"*...*\r\n*.*\r\n",0,exp_end)) { case EXP_TIMEOUT: timedout(); case EXP_EOF: exit(-1); } sscanf(exp_match,"%*s %*s ... %*s %*s %s",move); } void send_move(int fd) { write(fd,move,strlen(move)); } main(){ int fd1, fd2; exp_loguser = 1; exp_timeout = 3600; if (-1 == (fd1 = exp_spawnl("chess","chess",(char *)0))) { perror("chess"); exit(-1); } if (-1 == exp_expectl(fd1,exp_glob,"Chess\r\n",0,exp_end)) exit; if (-1 == write(fd1,"first\r",6)) exit; read_first_move(fd1); fd2 = exp_spawnl("chess","chess",(char *)0); if (-1 == exp_expectl(fd2,exp_glob,"Chess\r\n",0,exp_end)) exit; for (;;) { send_move(fd2); read_counter_move(fd2); send_move(fd1); read_move(fd1); } }
<?php /** * base class */ require_once 'PEAR.php'; class PEAR_Command_Common extends PEAR { // {{{ properties /** * PEAR_Config object used to pass user system and configuration * on when executing commands * * @var PEAR_Config */ var $config; /** * @var PEAR_Registry * @access protected */ var $_registry; /** * User Interface object, for all interaction with the user. * @var object */ var $ui; var $_deps_rel_trans = array( 'lt' => '<', 'le' => '<=', 'eq' => '=', 'ne' => '!=', 'gt' => '>', 'ge' => '>=', 'has' => '==' ); var $_deps_type_trans = array( 'pkg' => 'package', 'ext' => 'extension', 'php' => 'PHP', 'prog' => 'external program', 'ldlib' => 'external library for linking', 'rtlib' => 'external runtime library', 'os' => 'operating system', 'websrv' => 'web server', 'sapi' => 'SAPI backend' ); // {{{ constructor /** * PEAR_Command_Common constructor. * * @access public */ function PEAR_Command_Common(&$ui, &$config) { parent::PEAR(); $this->config = &$config; $this->ui = &$ui; } // {{{ getCommands() /** * Return a list of all the commands defined by this class. * @return array list of commands * @access public */ function getCommands() { $ret = array(); foreach (array_keys($this->commands) as $command) { $ret[$command] = $this->commands[$command]['summary']; } return $ret; } // {{{ getShortcuts() /** * Return a list of all the command shortcuts defined by this class. * @return array shortcut => command * @access public */ function getShortcuts() { $ret = array(); foreach (array_keys($this->commands) as $command) { if (isset($this->commands[$command]['shortcut'])) { $ret[$this->commands[$command]['shortcut']] = $command; } } return $ret; } // {{{ getOptions() function getOptions($command) { $shortcuts = $this->getShortcuts(); if (isset($shortcuts[$command])) { $command = $shortcuts[$command]; } if (isset($this->commands[$command]) && isset($this->commands[$command]['options'])) { return $this->commands[$command]['options']; } else { return null; } } // {{{ getGetoptArgs() function getGetoptArgs($command, &$short_args, &$long_args) { $short_args = ""; $long_args = array(); if (empty($this->commands[$command]) || empty($this->commands[$command]['options'])) { return; } reset($this->commands[$command]['options']); while (list($option, $info) = each($this->commands[$command]['options'])) { $larg = $sarg = ''; if (isset($info['arg'])) { if ($info['arg']{0} == '(') { $larg = '=='; $sarg = '::'; $arg = substr($info['arg'], 1, -1); } else { $larg = '='; $sarg = ':'; $arg = $info['arg']; } } if (isset($info['shortopt'])) { $short_args .= $info['shortopt'] . $sarg; } $long_args[] = $option . $larg; } } // {{{ getHelp() /** * Returns the help message for the given command * * @param string $command The command * @return mixed A fail string if the command does not have help or * a two elements array containing [0]=>help string, * [1]=> help string for the accepted cmd args */ function getHelp($command) { $config = &PEAR_Config::singleton(); if (!isset($this->commands[$command])) { return "No such command \"$command\""; } $help = null; if (isset($this->commands[$command]['doc'])) { $help = $this->commands[$command]['doc']; } if (empty($help)) { // XXX (cox) Fallback to summary if there is no doc (show both?) if (!isset($this->commands[$command]['summary'])) { return "No help for command \"$command\""; } $help = $this->commands[$command]['summary']; } if (preg_match_all('/{config\s+([^\}]+)}/e', $help, $matches)) { foreach($matches[0] as $k => $v) { $help = preg_replace("/$v/", $config->get($matches[1][$k]), $help); } } return array($help, $this->getHelpArgs($command)); } // {{{ getHelpArgs() /** * Returns the help for the accepted arguments of a command * * @param string $command * @return string The help string */ function getHelpArgs($command) { if (isset($this->commands[$command]['options']) && count($this->commands[$command]['options'])) { $help = "Options:\n"; foreach ($this->commands[$command]['options'] as $k => $v) { if (isset($v['arg'])) { if ($v['arg'][0] == '(') { $arg = substr($v['arg'], 1, -1); $sapp = " [$arg]"; $lapp = "[=$arg]"; } else { $sapp = " $v[arg]"; $lapp = "=$v[arg]"; } } else { $sapp = $lapp = ""; } if (isset($v['shortopt'])) { $s = $v['shortopt']; $help .= " -$s$sapp, --$k$lapp\n"; } else { $help .= " --$k$lapp\n"; } $p = " "; $doc = rtrim(str_replace("\n", "\n$p", $v['doc'])); $help .= " $doc\n"; } return $help; } return null; } // {{{ run() function run($command, $options, $params) { if (empty($this->commands[$command]['function'])) { // look for shortcuts foreach (array_keys($this->commands) as $cmd) { if (isset($this->commands[$cmd]['shortcut']) && $this->commands[$cmd]['shortcut'] == $command) { if (empty($this->commands[$cmd]['function'])) { return $this->raiseError("unknown command `$command'"); } else { $func = $this->commands[$cmd]['function']; } $command = $cmd; break; } } } else { $func = $this->commands[$command]['function']; } return $this->$func($command, $options, $params); } } ?>
<?php /** * Xmlconnect Form field renderer interface * * @category Mage * @package Mage_XmlConnect * @author Magento Core Team <core@magentocommerce.com> */ interface <API key> { public function render(<API key> $element); }
// <API key>: GPL-2.0 #ifndef <API key> #define <API key> #include <QMainWindow> #include <QFileDialog> #include <QFileInfo> extern "C" void smartrak_import(const char *file, struct dive_table *divetable); namespace Ui { class Smrtk2ssrfcWindow; } class Smrtk2ssrfcWindow : public QMainWindow { Q_OBJECT public: explicit Smrtk2ssrfcWindow(QWidget *parent = 0); ~Smrtk2ssrfcWindow(); private: Ui::Smrtk2ssrfcWindow *ui; QString filter(); void updateLastUsedDir(const QString &s); void closeCurrentFile(); private slots: void <API key>(); void <API key>(); void <API key>(); void <API key>(); void <API key>(); void <API key>(); }; #endif // <API key>
package org.zarroboogs.weibo.hot.bean.hotweibo; import org.json.*; public class TopicStruct { private String topicTitle; private String topicUrl; public TopicStruct () { } public TopicStruct (JSONObject json) { this.topicTitle = json.optString("topic_title"); this.topicUrl = json.optString("topic_url"); } public String getTopicTitle() { return this.topicTitle; } public void setTopicTitle(String topicTitle) { this.topicTitle = topicTitle; } public String getTopicUrl() { return this.topicUrl; } public void setTopicUrl(String topicUrl) { this.topicUrl = topicUrl; } }
/** \file lees_edwards.h Data and methods for Lees-Edwards periodic boundary conditions. The gist of LE-PBCs is to impose shear flow by constantly moving the PBC wrap such that: $x_{unfolded} == x_{folded} + x_{img} \times L + (y_{img} * \gamma * t)$, and $vx_{unfolded} = vx_{folded} + (y_{img} * \gamma)$. */ #ifndef LEES_EDWARDS_H #define LEES_EDWARDS_H #include "config.hpp" extern double lees_edwards_offset, lees_edwards_rate; extern int lees_edwards_count; #ifdef LEES_EDWARDS void <API key>(); #endif //LEES_EDWARDS #endif //LEES_EDWARDS_H
/* lzw.c -- compress files in LZW format. * This is a dummy version avoiding patent problems. */ #include <config.h> #include "tailor.h" #include "gzip.h" #include "lzw.h" static int msg_done = 0; /* Compress in to out with lzw method. */ int lzw(in, out) int in, out; { if (msg_done) return ERROR; msg_done = 1; fprintf(stderr,"output in compress .Z format not supported\n"); if (in != out) { /* avoid warnings on unused variables */ exit_code = ERROR; } return ERROR; }
<?php /** * @file * @ingroup SpecialPage */ /** * @todo document * @ingroup SpecialPage */ class ProtectedPagesForm { protected $IdLevel = 'level'; protected $IdType = 'type'; public function showList( $msg = '' ) { global $wgOut, $wgRequest; if( $msg != "" ) { $wgOut->setSubtitle( $msg ); } // Purge expired entries on one in every 10 queries if( !mt_rand( 0, 10 ) ) { Title::<API key>(); } $type = $wgRequest->getVal( $this->IdType ); $level = $wgRequest->getVal( $this->IdLevel ); $sizetype = $wgRequest->getVal( 'sizetype' ); $size = $wgRequest->getIntOrNull( 'size' ); $NS = $wgRequest->getIntOrNull( 'namespace' ); $indefOnly = $wgRequest->getBool( 'indefonly' ) ? 1 : 0; $cascadeOnly = $wgRequest->getBool('cascadeonly') ? 1 : 0; $pager = new ProtectedPagesPager( $this, array(), $type, $level, $NS, $sizetype, $size, $indefOnly, $cascadeOnly ); $wgOut->addHTML( $this->showOptions( $NS, $type, $level, $sizetype, $size, $indefOnly, $cascadeOnly ) ); if( $pager->getNumRows() ) { $s = $pager->getNavigationBar(); $s .= "<ul>" . $pager->getBody() . "</ul>"; $s .= $pager->getNavigationBar(); } else { $s = '<p>' . wfMsgHtml( 'protectedpagesempty' ) . '</p>'; } $wgOut->addHTML( $s ); } /** * Callback function to output a restriction * @param $row object Protected title * @return string Formatted <li> element */ public function formatRow( $row ) { global $wgUser, $wgLang, $wgContLang; wfProfileIn( __METHOD__ ); static $skin=null; if( is_null( $skin ) ) $skin = $wgUser->getSkin(); $title = Title::makeTitleSafe( $row->page_namespace, $row->page_title ); $link = $skin->link( $title ); $description_items = array (); $protType = wfMsgHtml( 'restriction-level-' . $row->pr_level ); $description_items[] = $protType; if( $row->pr_cascade ) { $description_items[] = wfMsg( '<API key>' ); } $expiry_description = ''; $stxt = ''; if( $row->pr_expiry != 'infinity' && strlen($row->pr_expiry) ) { $expiry = Block::decodeExpiry( $row->pr_expiry ); $expiry_description = wfMsg( 'protect-expiring' , $wgLang->timeanddate( $expiry ) , $wgLang->date( $expiry ) , $wgLang->time( $expiry ) ); $description_items[] = htmlspecialchars($expiry_description); } if(!is_null($size = $row->page_len)) { $stxt = $wgContLang->getDirMark() . ' ' . $skin->formatRevisionSize( $size ); } # Show a link to the change protection form for allowed users otherwise a link to the protection log if( $wgUser->isAllowed( 'protect' ) ) { $changeProtection = ' (' . $skin->linkKnown( $title, wfMsgHtml( 'protect_change' ), array(), array( 'action' => 'unprotect' ) ) . ')'; } else { $ltitle = SpecialPage::getTitleFor( 'Log' ); $changeProtection = ' (' . $skin->linkKnown( $ltitle, wfMsgHtml( 'protectlogpage' ), array(), array( 'type' => 'protect', 'page' => $title->getPrefixedText() ) ) . ')'; } wfProfileOut( __METHOD__ ); return Html::rawElement( 'li', array(), wfSpecialList( $link . $stxt, $wgLang->commaList( $description_items ) ) . $changeProtection ) . "\n"; } /** * @param $namespace int * @param $type string * @param $level string * @param $minsize int * @param $indefOnly bool * @param $cascadeOnly bool * @return string Input form * @private */ protected function showOptions( $namespace, $type='edit', $level, $sizetype, $size, $indefOnly, $cascadeOnly ) { global $wgScript; $title = SpecialPage::getTitleFor( 'Protectedpages' ); return Xml::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript ) ) . Xml::openElement( 'fieldset' ) . Xml::element( 'legend', array(), wfMsg( 'protectedpages' ) ) . Xml::hidden( 'title', $title->getPrefixedDBkey() ) . "\n" . $this->getNamespaceMenu( $namespace ) . "&nbsp;\n" . $this->getTypeMenu( $type ) . "&nbsp;\n" . $this->getLevelMenu( $level ) . "&nbsp;\n" . "<br /><span style='white-space: nowrap'>" . $this->getExpiryCheck( $indefOnly ) . "&nbsp;\n" . $this->getCascadeCheck( $cascadeOnly ) . "&nbsp;\n" . "</span><br /><span style='white-space: nowrap'>" . $this->getSizeLimit( $sizetype, $size ) . "&nbsp;\n" . "</span>" . "&nbsp;" . Xml::submitButton( wfMsg( 'allpagessubmit' ) ) . "\n" . Xml::closeElement( 'fieldset' ) . Xml::closeElement( 'form' ); } /** * Prepare the namespace filter drop-down; standard namespace * selector, sans the MediaWiki namespace * * @param mixed $namespace Pre-select namespace * @return string */ protected function getNamespaceMenu( $namespace = null ) { return "<span style='white-space: nowrap'>" . Xml::label( wfMsg( 'namespace' ), 'namespace' ) . '&nbsp;' . Xml::namespaceSelector( $namespace, '' ) . "</span>"; } /** * @return string Formatted HTML */ protected function getExpiryCheck( $indefOnly ) { return Xml::checkLabel( wfMsg('<API key>'), 'indefonly', 'indefonly', $indefOnly ) . "\n"; } /** * @return string Formatted HTML */ protected function getCascadeCheck( $cascadeOnly ) { return Xml::checkLabel( wfMsg('<API key>'), 'cascadeonly', 'cascadeonly', $cascadeOnly ) . "\n"; } /** * @return string Formatted HTML */ protected function getSizeLimit( $sizetype, $size ) { $max = $sizetype === 'max'; return Xml::radioLabel( wfMsg('minimum-size'), 'sizetype', 'min', 'wpmin', !$max ) . '&nbsp;' . Xml::radioLabel( wfMsg('maximum-size'), 'sizetype', 'max', 'wpmax', $max ) . '&nbsp;' . Xml::input( 'size', 9, $size, array( 'id' => 'wpsize' ) ) . '&nbsp;' . Xml::label( wfMsg('pagesize'), 'wpsize' ); } /** * Creates the input label of the restriction type * @param $pr_type string Protection type * @return string Formatted HTML */ protected function getTypeMenu( $pr_type ) { global $wgRestrictionTypes; $m = array(); // Temporary array $options = array(); // First pass to load the log names foreach( $wgRestrictionTypes as $type ) { $text = wfMsg("restriction-$type"); $m[$text] = $type; } // Third pass generates sorted XHTML content foreach( $m as $text => $type ) { $selected = ($type == $pr_type ); $options[] = Xml::option( $text, $type, $selected ) . "\n"; } return "<span style='white-space: nowrap'>" . Xml::label( wfMsg('restriction-type') , $this->IdType ) . '&nbsp;' . Xml::tags( 'select', array( 'id' => $this->IdType, 'name' => $this->IdType ), implode( "\n", $options ) ) . "</span>"; } /** * Creates the input label of the restriction level * @param $pr_level string Protection level * @return string Formatted HTML */ protected function getLevelMenu( $pr_level ) { global $wgRestrictionLevels; $m = array( wfMsg('<API key>') => 0 ); // Temporary array $options = array(); // First pass to load the log names foreach( $wgRestrictionLevels as $type ) { // Messages used can be '<API key>' and '<API key>' if( $type !='' && $type !='*') { $text = wfMsg("restriction-level-$type"); $m[$text] = $type; } } // Third pass generates sorted XHTML content foreach( $m as $text => $type ) { $selected = ($type == $pr_level ); $options[] = Xml::option( $text, $type, $selected ); } return "<span style='white-space: nowrap'>" . Xml::label( wfMsg( 'restriction-level' ) , $this->IdLevel ) . ' ' . Xml::tags( 'select', array( 'id' => $this->IdLevel, 'name' => $this->IdLevel ), implode( "\n", $options ) ) . "</span>"; } } /** * @todo document * @ingroup Pager */ class ProtectedPagesPager extends AlphabeticPager { public $mForm, $mConds; private $type, $level, $namespace, $sizetype, $size, $indefonly; function __construct( $form, $conds = array(), $type, $level, $namespace, $sizetype='', $size=0, $indefonly = false, $cascadeonly = false ) { $this->mForm = $form; $this->mConds = $conds; $this->type = ( $type ) ? $type : 'edit'; $this->level = $level; $this->namespace = $namespace; $this->sizetype = $sizetype; $this->size = intval($size); $this->indefonly = (bool)$indefonly; $this->cascadeonly = (bool)$cascadeonly; parent::__construct(); } function getStartBody() { # Do a link batch query $lb = new LinkBatch; while( $row = $this->mResult->fetchObject() ) { $lb->add( $row->page_namespace, $row->page_title ); } $lb->execute(); return ''; } function formatRow( $row ) { return $this->mForm->formatRow( $row ); } function getQueryInfo() { $conds = $this->mConds; $conds[] = '(pr_expiry>' . $this->mDb->addQuotes( $this->mDb->timestamp() ) . 'OR pr_expiry IS NULL)'; $conds[] = 'page_id=pr_page'; $conds[] = 'pr_type=' . $this->mDb->addQuotes( $this->type ); if( $this->sizetype=='min' ) { $conds[] = 'page_len>=' . $this->size; } else if( $this->sizetype=='max' ) { $conds[] = 'page_len<=' . $this->size; } if( $this->indefonly ) { $conds[] = "pr_expiry = 'infinity' OR pr_expiry IS NULL"; } if( $this->cascadeonly ) { $conds[] = "pr_cascade = '1'"; } if( $this->level ) $conds[] = 'pr_level=' . $this->mDb->addQuotes( $this->level ); if( !is_null($this->namespace) ) $conds[] = 'page_namespace=' . $this->mDb->addQuotes( $this->namespace ); return array( 'tables' => array( 'page_restrictions', 'page' ), 'fields' => 'pr_id,page_namespace,page_title,page_len,pr_type,pr_level,pr_expiry,pr_cascade', 'conds' => $conds ); } function getIndexField() { return 'pr_id'; } } /** * Constructor */ function <API key>() { $ppForm = new ProtectedPagesForm(); $ppForm->showList(); }
#!/bin/bash test_info() { cat <<EOF Verify that the ctdb_transaction test succeeds. Prerequisites: * An active CTDB cluster with at least 2 active nodes. Steps: 1. Verify that the status on all of the ctdb nodes is 'OK'. 2. Run two copies of ctdb_transaction on each node with a 30 second timeout. 3. Ensure that all ctdb_transaction processes complete successfully. Expected results: * ctdb_transaction runs without error. EOF } . "${TEST_SCRIPTS_DIR}/integration.bash" ctdb_test_init "$@" set -e cluster_is_healthy try_command_on_node 0 "$CTDB listnodes" num_nodes=$(echo "$out" | wc -l) if test "x${CTDB_TEST_TIMELIMIT}" == "x" ; then CTDB_TEST_TIMELIMIT=30 fi t="$CTDB_TEST_WRAPPER $VALGRIND ctdb_transaction --timelimit=${CTDB_TEST_TIMELIMIT}" echo "Running ctdb_transaction on all $num_nodes nodes." try_command_on_node -v -p all "$t & $t"
package com.earth2me.essentials.antibuild; import java.util.EnumMap; import java.util.List; import java.util.Map; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; public class EssentialsAntiBuild extends JavaPlugin implements IAntiBuild { private final transient Map<AntiBuildConfig, Boolean> settingsBoolean = new EnumMap<AntiBuildConfig, Boolean>(AntiBuildConfig.class); private final transient Map<AntiBuildConfig, List<Integer>> settingsList = new EnumMap<AntiBuildConfig, List<Integer>>(AntiBuildConfig.class); private transient EssentialsConnect ess = null; @Override public void onEnable() { final PluginManager pm = this.getServer().getPluginManager(); final Plugin essPlugin = pm.getPlugin("Essentials"); if (essPlugin == null || !essPlugin.isEnabled()) { return; } ess = new EssentialsConnect(essPlugin, this); final <API key> blockListener = new <API key>(this); pm.registerEvents(blockListener, this); } @Override public boolean <API key>(final AntiBuildConfig list, final int id) { final List<Integer> itemList = settingsList.get(list); return itemList != null && !itemList.isEmpty() && itemList.contains(id); } @Override public EssentialsConnect <API key>() { return ess; } @Override public Map<AntiBuildConfig, Boolean> getSettingsBoolean() { return settingsBoolean; } @Override public Map<AntiBuildConfig, List<Integer>> getSettingsList() { return settingsList; } @Override public boolean getSettingBool(final AntiBuildConfig protectConfig) { final Boolean bool = settingsBoolean.get(protectConfig); return bool == null ? protectConfig.<API key>() : bool; } }
'use strict'; --- Exports /** * JSONP formatter. like JSON, but with a callback invocation. * * Unicode escapes line and paragraph separators. * * @public * @function formatJSONP * @param {Object} req the request object * @param {Object} res the response object * @param {Object} body response body * @returns {String} */ function formatJSONP(req, res, body) { if (!body) { res.setHeader('Content-Length', 0); return (null); } if (Buffer.isBuffer(body)) { body = body.toString('base64'); } var _cb = req.query.callback || req.query.jsonp; var data; if (_cb) { data = 'typeof ' + _cb + ' === \'function\' && ' + _cb + '(' + JSON.stringify(body) + ');'; } else { data = JSON.stringify(body); } data = data.replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029'); res.setHeader('Content-Length', Buffer.byteLength(data)); return data; } module.exports = formatJSONP;
// The LLVM Compiler Infrastructure // This file is distributed under the University of Illinois Open Source // This header Bitcode enum values. // The enum values defined in this file should be considered permanent. If // new features are added, they should have values added at the end of the // respective lists. #ifndef <API key> #define <API key> #include "llvm/ADT/SmallVector.h" #include "llvm/Support/DataTypes.h" #include <cassert> namespace llvm { namespace bitc { enum StandardWidths { BlockIDWidth = 8, // We use VBR-8 for block IDs. CodeLenWidth = 4, // Codelen are VBR-4. BlockSizeWidth = 32 // BlockSize up to 2^32 32-bit words = 16GB per block. }; // The standard abbrev namespace always has a way to exit a block, enter a // nested block, define abbrevs, and define an unabbreviated record. enum FixedAbbrevIDs { END_BLOCK = 0, // Must be zero to guarantee termination for broken bitcode. ENTER_SUBBLOCK = 1, DEFINE_ABBREV - Defines an abbrev for the current block. It consists of a vbr5 for # operand infos. Each operand info is emitted with a single bit to indicate if it is a literal encoding. If so, the value is emitted with a vbr8. If not, the encoding is emitted as 3 bits followed by the info value as a vbr5 if needed. DEFINE_ABBREV = 2, // UNABBREV_RECORDs are emitted with a vbr6 for the record code, followed by // a vbr6 for the # operands, followed by vbr6's for each operand. UNABBREV_RECORD = 3, // This is not a code, this is a marker for the first abbrev assignment. <API key> = 4 }; StandardBlockIDs - All bitcode files can optionally include a BLOCKINFO block, which contains metadata about other blocks in the file. enum StandardBlockIDs { BLOCKINFO_BLOCK is used to define metadata about blocks, for example, standard abbrevs that should be available to all blocks of a specified ID. BLOCKINFO_BLOCK_ID = 0, // Block IDs 1-7 are reserved for future expansion. <API key> = 8 }; BlockInfoCodes - The blockinfo block contains metadata about user-defined blocks. enum BlockInfoCodes { // DEFINE_ABBREV has magic semantics here, applying to the current SETBID'd // block, instead of the BlockInfo block. <API key> = 1, // SETBID: [blockid <API key> = 2, // BLOCKNAME: [name] <API key> = 3 // <API key>: [id, name] }; } // End bitc namespace BitCodeAbbrevOp - This describes one or more operands in an abbreviation. This is actually a union of two different things: 1. It could be a literal integer value ("the operand is always 17"). 2. It could be an encoding specification ("this operand encoded like so"). class BitCodeAbbrevOp { uint64_t Val; // A literal value or data for an encoding. bool IsLiteral : 1; // Indicate whether this is a literal value or not. unsigned Enc : 3; // The encoding to use. public: enum Encoding { Fixed = 1, // A fixed width field, Val specifies number of bits. VBR = 2, // A VBR field where Val specifies the width of each chunk. Array = 3, // A sequence of fields, next field species elt encoding. Char6 = 4, // A 6-bit fixed field which maps to [a-zA-Z0-9._]. Blob = 5 // 32-bit aligned array of 8-bit characters. }; explicit BitCodeAbbrevOp(uint64_t V) : Val(V), IsLiteral(true) {} explicit BitCodeAbbrevOp(Encoding E, uint64_t Data = 0) : Val(Data), IsLiteral(false), Enc(E) {} bool isLiteral() const { return IsLiteral; } bool isEncoding() const { return !IsLiteral; } // Accessors for literals. uint64_t getLiteralValue() const { assert(isLiteral()); return Val; } // Accessors for encoding info. Encoding getEncoding() const { assert(isEncoding()); return (Encoding)Enc; } uint64_t getEncodingData() const { assert(isEncoding() && hasEncodingData()); return Val; } bool hasEncodingData() const { return hasEncodingData(getEncoding()); } static bool hasEncodingData(Encoding E) { switch (E) { default: assert(0 && "Unknown encoding"); case Fixed: case VBR: return true; case Array: case Char6: case Blob: return false; } } isChar6 - Return true if this character is legal in the Char6 encoding. static bool isChar6(char C) { if (C >= 'a' && C <= 'z') return true; if (C >= 'A' && C <= 'Z') return true; if (C >= '0' && C <= '9') return true; if (C == '.' || C == '_') return true; return false; } static unsigned EncodeChar6(char C) { if (C >= 'a' && C <= 'z') return C-'a'; if (C >= 'A' && C <= 'Z') return C-'A'+26; if (C >= '0' && C <= '9') return C-'0'+26+26; if (C == '.') return 62; if (C == '_') return 63; assert(0 && "Not a value Char6 character!"); return 0; } static char DecodeChar6(unsigned V) { assert((V & ~63) == 0 && "Not a Char6 encoded character!"); if (V < 26) return V+'a'; if (V < 26+26) return V-26+'A'; if (V < 26+26+10) return V-26-26+'0'; if (V == 62) return '.'; if (V == 63) return '_'; assert(0 && "Not a value Char6 character!"); return ' '; } }; BitCodeAbbrev - This class represents an abbreviation record. An abbreviation allows a complex record that has redundancy to be stored in a specialized format instead of the fully-general, fully-vbr, format. class BitCodeAbbrev { SmallVector<BitCodeAbbrevOp, 8> OperandList; unsigned char RefCount; // Number of things using this. ~BitCodeAbbrev() {} public: BitCodeAbbrev() : RefCount(1) {} void addRef() { ++RefCount; } void dropRef() { if (--RefCount == 0) delete this; } unsigned getNumOperandInfos() const { return static_cast<unsigned>(OperandList.size()); } const BitCodeAbbrevOp &getOperandInfo(unsigned N) const { return OperandList[N]; } void Add(const BitCodeAbbrevOp &OpInfo) { OperandList.push_back(OpInfo); } }; } // End llvm namespace #endif
(function(){CKEDITOR.on("dialogDefinition",function(a){var b;b=a.data.name;a=a.data.definition;"link"==b?(a.removeContents("target"),a.removeContents("upload"),a.removeContents("advanced"),b=a.getContents("info"),b.remove("emailSubject"),b.remove("emailBody")):"image"==b&&(a.removeContents("advanced"),b=a.getContents("Link"),b.remove("cmbTarget"),b=a.getContents("info"),b.remove("txtAlt"),b.remove("basic"))});var l={b:"strong",u:"u",i:"em",color:"span",size:"span",left:"div",right:"div",center:"div", justify:"div",quote:"blockquote",code:"code",url:"a",email:"span",img:"span","*":"li",list:"ol"},x={strong:"b",b:"b",u:"u",em:"i",i:"i",code:"code",li:"*"},m={strong:"b",em:"i",u:"u",li:"*",ul:"list",ol:"list",code:"code",a:"link",img:"img",blockquote:"quote"},y={color:"color",size:"font-size",left:"text-align",center:"text-align",right:"text-align",justify:"text-align"},z={url:"href",email:"mailhref",quote:"cite",list:"listType"},n=CKEDITOR.dtd,A=CKEDITOR.tools.extend({table:1},n.$block,n.$listItem, n.$tableContent,n.$list),C=/\s*(?:;\s*|$)/,q={smiley:":)",sad:":(",wink:";)",laugh:":D",cheeky:":P",blush:":*)",surprise:":-o",indecision:":|",angry:"\x3e:(",angel:"o:)",cool:"8-)",devil:"\x3e:-)",crying:";(",kiss:":-*"},B={},r=[],t;for(t in q)B[q[t]]=t,r.push(q[t].replace(/\(|\)|\:|\/|\*|\-|\|/g,function(a){return"\\"+a}));var r=new RegExp(r.join("|"),"g"),D=function(){var a=[],b={nbsp:" ",shy:"­"},c;for(c in b)a.push(c);a=new RegExp("\x26("+a.join("|")+");","g");return function(c){return c.replace(a, function(e,a){return b[a]})}}();CKEDITOR.BBCodeParser=function(){this._={bbcPartsRegex:/(?:\[([^\/\]=]*?)(?:=([^\]]*?))?\])|(?:\[\/([a-z]{1,16})\])/ig}};CKEDITOR.BBCodeParser.prototype={parse:function(a){for(var b,c,k=0;b=this._.bbcPartsRegex.exec(a);)if(c=b.index,c>k&&(k=a.substring(k,c),this.onText(k,1)),k=this._.bbcPartsRegex.lastIndex,(c=(b[1]||b[3]||"").toLowerCase())&&!l[c])this.onText(b[0]);else if(b[1]){var e=l[c],g={},h={};b=b[2];if("left"==c||"right"==c||"center"==c||"justify"==c)b=c;if(b)if("list"== c&&(isNaN(b)?/^[a-z]+$/.test(b)?b="lower-alpha":/^[A-Z]+$/.test(b)&&(b="upper-alpha"):b="decimal"),y[c]){"size"==c&&(b+="%");h[y[c]]=b;b=g;var f="",d=void 0;for(d in h)var u=(d+":"+h[d]).replace(C,";"),f=f+u;b.style=f}else z[c]&&(g[z[c]]=CKEDITOR.tools.htmlDecode(b));if("email"==c||"img"==c)g.bbcode=c;this.onTagOpen(e,g,CKEDITOR.dtd.$empty[e])}else if(b[3])this.onTagClose(l[c]);if(a.length>k)this.onText(a.substring(k,a.length),1)}};CKEDITOR.htmlParser.fragment.fromBBCode=function(a){function b(e){if(0< h.length)for(var a=0;a<h.length;a++){var b=h[a],c=b.name,g=CKEDITOR.dtd[c],f=d.name&&CKEDITOR.dtd[d.name];f&&!f[c]||e&&g&&!g[e]&&CKEDITOR.dtd[e]||(b=b.clone(),b.parent=d,d=b,h.splice(a,1),a--)}}function c(a,e){var b=d.children.length,c=0<b&&d.children[b-1],b=!c&&v.getRule(m[d.name],"breakAfterOpen"),c=c&&c.type==CKEDITOR.NODE_ELEMENT&&v.getRule(m[c.name],"breakAfterClose"),g=a&&v.getRule(m[a],e?"breakBeforeClose":"breakBeforeOpen");f&&(b||c||g)&&f--;f&&a in A&&f++;for(;f&&f--;)d.children.push(new CKEDITOR.htmlParser.element("br"))} function k(a,e){c(a.name,1);e=e||d||g;var b=e.children.length;a.previous=0<b&&e.children[b-1]||null;a.parent=e;e.children.push(a);a.returnPoint&&(d=a.returnPoint,delete a.returnPoint)}var e=new CKEDITOR.BBCodeParser,g=new CKEDITOR.htmlParser.fragment,h=[],f=0,d=g,u;e.onTagOpen=function(a,g){var f=new CKEDITOR.htmlParser.element(a,g);if(CKEDITOR.dtd.$removeEmpty[a])h.push(f);else{var w=d.name,p=w&&(CKEDITOR.dtd[w]||(d._.isBlockLike?CKEDITOR.dtd.div:CKEDITOR.dtd.span));if(p&&!p[a]){var p=!1,l;a==w? k(d,d.parent):(a in CKEDITOR.dtd.$listItem?(e.onTagOpen("ul",{}),l=d):(k(d,d.parent),h.unshift(d)),p=!0);d=l?l:d.returnPoint||d.parent;if(p){e.onTagOpen.apply(this,arguments);return}}b(a);c(a);f.parent=d;f.returnPoint=u;u=0;f.isEmpty?k(f):d=f}};e.onTagClose=function(a){for(var e=h.length-1;0<=e;e--)if(a==h[e].name){h.splice(e,1);return}for(var b=[],c=[],g=d;g.type&&g.name!=a;)g._.isBlockLike||c.unshift(g),b.push(g),g=g.parent;if(g.type){for(e=0;e<b.length;e++)a=b[e],k(a,a.parent);d=g;k(g,g.parent); g==d&&(d=d.parent);h=h.concat(c)}};e.onText=function(a){var e=CKEDITOR.dtd[d.name];if(!e||e["#"])c(),b(),a.replace(/(\r\n|[\r\n])|[^\r\n]*/g,function(a,e){if(void 0!==e&&e.length)f++;else if(a.length){var b=0;a.replace(r,function(e,c){k(new CKEDITOR.htmlParser.text(a.substring(b,c)),d);k(new CKEDITOR.htmlParser.element("smiley",{desc:B[e]}),d);b=c+e.length});b!=a.length&&k(new CKEDITOR.htmlParser.text(a.substring(b,a.length)),d)}})};for(e.parse(CKEDITOR.tools.htmlEncode(a));d.type!=CKEDITOR.<API key>;)a= d.parent,k(d,a),d=a;return g};var v=new (CKEDITOR.tools.createClass({$:function(){this._={output:[],rules:[]};this.setRules("list",{breakBeforeOpen:1,breakAfterOpen:1,breakBeforeClose:1,breakAfterClose:1});this.setRules("*",{breakBeforeOpen:1,breakAfterOpen:0,breakBeforeClose:1,breakAfterClose:0});this.setRules("quote",{breakBeforeOpen:1,breakAfterOpen:0,breakBeforeClose:0,breakAfterClose:1})},proto:{setRules:function(a,b){var c=this._.rules[a];c?CKEDITOR.tools.extend(c,b,!0):this._.rules[a]=b},getRule:function(a, b){return this._.rules[a]&&this._.rules[a][b]},openTag:function(a){a in l&&(this.getRule(a,"breakBeforeOpen")&&this.lineBreak(1),this.write("[",a))},openTagClose:function(a){"br"==a?this._.output.push("\n"):a in l&&(this.write("]"),this.getRule(a,"breakAfterOpen")&&this.lineBreak(1))},attribute:function(a,b){"option"==a&&this.write("\x3d",b)},closeTag:function(a){a in l&&(this.getRule(a,"breakBeforeClose")&&this.lineBreak(1),"*"!=a&&this.write("[/",a,"]"),this.getRule(a,"breakAfterClose")&&this.lineBreak(1))}, text:function(a){this.write(a)},comment:function(){},lineBreak:function(){!this._.hasLineBreak&&this._.output.length&&(this.write("\n"),this._.hasLineBreak=1)},write:function(){this._.hasLineBreak=0;var a=Array.prototype.join.call(arguments,"");this._.output.push(a)},reset:function(){this._.output=[];this._.hasLineBreak=0},getHtml:function(a){var b=this._.output.join("");a&&this.reset();return D(b)}}}));CKEDITOR.plugins.add("bbcode",{requires:"entities",beforeInit:function(a){CKEDITOR.tools.extend(a.config, {enterMode:CKEDITOR.ENTER_BR,basicEntities:!1,entities:!1,fillEmptyBlocks:!1},!0);a.filter.disable();a.activeEnterMode=a.enterMode=CKEDITOR.ENTER_BR},init:function(a){function b(a){var b=a.data;a=CKEDITOR.htmlParser.fragment.fromBBCode(a.data.dataValue);var c=new CKEDITOR.htmlParser.basicWriter;a.writeHtml(c,k);a=c.getHtml(!0);b.dataValue=a}var c=a.config,k=new CKEDITOR.htmlParser.filter;k.addRules({elements:{blockquote:function(a){var b=new CKEDITOR.htmlParser.element("div");b.children=a.children; a.children=[b];if(b=a.attributes.cite){var c=new CKEDITOR.htmlParser.element("cite");c.add(new CKEDITOR.htmlParser.text(b.replace(/^"|"$/g,"")));delete a.attributes.cite;a.children.unshift(c)}},span:function(a){var b;if(b=a.attributes.bbcode)"img"==b?(a.name="img",a.attributes.src=a.children[0].value,a.children=[]):"email"==b&&(a.name="a",a.attributes.href="mailto:"+a.children[0].value),delete a.attributes.bbcode},ol:function(a){a.attributes.listType?"decimal"!=a.attributes.listType&&(a.attributes.style= "list-style-type:"+a.attributes.listType):a.name="ul";delete a.attributes.listType},a:function(a){a.attributes.href||(a.attributes.href=a.children[0].value)},smiley:function(a){a.name="img";var b=a.attributes.desc,h=c.smiley_images[CKEDITOR.tools.indexOf(c.smiley_descriptions,b)],h=CKEDITOR.tools.htmlEncode(c.smiley_path+h);a.attributes={src:h,"data-cke-saved-src":h,title:b,alt:b}}}});a.dataProcessor.htmlFilter.addRules({elements:{$:function(b){var c=b.attributes,h=CKEDITOR.tools.parseCssText(c.style, 1),f,d=b.name;if(d in x)d=x[d];else if("span"==d)if(f=h.color)d="color",f=CKEDITOR.tools.convertRgbToHex(f);else{if(f=h["font-size"])if(c=f.match(/(\d+)%$/))f=c[1],d="size"}else if("ol"==d||"ul"==d){if(f=h["list-style-type"])switch(f){case "lower-alpha":f="a";break;case "upper-alpha":f="A"}else"ol"==d&&(f=1);d="list"}else if("blockquote"==d){try{var k=b.children[0],l=b.children[1],m="cite"==k.name&&k.children[0].value;m&&(f='"'+m+'"',b.children=l.children)}catch(n){}d="quote"}else if("a"==d){if(f= c.href)-1!==f.indexOf("mailto:")?(d="email",b.children=[new CKEDITOR.htmlParser.text(f.replace("mailto:",""))],f=""):((d=1==b.children.length&&b.children[0])&&d.type==CKEDITOR.NODE_TEXT&&d.value==f&&(f=""),d="url")}else if("img"==d){b.isEmpty=0;h=c["data-cke-saved-src"]||c.src;c=c.alt;if(h&&-1!=h.indexOf(a.config.smiley_path)&&c)return new CKEDITOR.htmlParser.text(q[c]);b.children=[new CKEDITOR.htmlParser.text(h)]}b.name=d;f&&(b.attributes.option=f);return null},div:function(a){var b=CKEDITOR.tools.parseCssText(a.attributes.style, 1)["text-align"]||"";if(b)return a.name=b,null},br:function(a){if((a=a.next)&&a.name in A)return!1}}},1);a.dataProcessor.writer=v;if(a.elementMode==CKEDITOR.ELEMENT_MODE_INLINE)a.once("contentDom",function(){a.on("setData",b)});else a.on("setData",b)},afterInit:function(a){var b;a._.elementsPath&&(b=a._.elementsPath.filters)&&b.push(function(b){var k=b.getName(),e=m[k]||!1;"link"==e&&0===b.getAttribute("href").indexOf("mailto:")?e="email":"span"==k?b.getStyle("font-size")?e="size":b.getStyle("color")&& (e="color"):"div"==k&&b.getStyle("text-align")?e=b.getStyle("text-align"):"img"==e&&(b=b.data("cke-saved-src")||b.getAttribute("src"))&&0===b.indexOf(a.config.smiley_path)&&(e="smiley");return e})}})})();
declare module Virtex { interface IOptions { ambientLightColor: number; cameraZ: number; <API key>: number; <API key>: number; <API key>: number; <API key>: number; doubleSided: boolean; element: string; fadeSpeed: number; far: number; fov: number; maxZoom: number; minZoom: number; near: number; object: string; shading: THREE.Shading; shininess: number; showStats: boolean; zoomSpeed: number; } } interface IVirtex { create: (options: Virtex.IOptions) => Virtex.Viewport; } declare var Detector: any; declare var Stats: any; declare var requestAnimFrame: any; declare module Virtex { class Viewport { options: IOptions; private _$element; private _$viewport; private _$loading; private _$loadingBar; private _$oldie; private _camera; private _lightGroup; private _modelGroup; private _renderer; private _scene; private _stats; private _viewportHalfX; private _viewportHalfY; private _isMouseDown; private _mouseX; private _mouseXOnMouseDown; private _mouseY; private _mouseYOnMouseDown; private _pinchStart; private <API key>; private <API key>; private _targetRotationX; private _targetRotationY; private _targetZoom; constructor(options: IOptions); private _init(); private _loadProgress(progress); private _onMouseDown(event); private _onMouseMove(event); private _onMouseUp(event); private _onMouseOut(event); private _onMouseWheel(event); private _onTouchStart(event); private _onTouchMove(event); private _onTouchEnd(event); private _draw(); private _render(); private _getWidth(); private _getHeight(); zoomIn(): void; zoomOut(): void; private _resize(); } }
using System.Windows.Forms; using <API key>; using ResourceManager; namespace <API key> { public class <API key> : GitPluginBase { public <API key>() { <API key>("Release Notes Generator"); Translate(); } public override bool Execute(GitUIBaseEventArgs gitUiCommands) { using (var form = new <API key>(gitUiCommands)) { if (form.ShowDialog(gitUiCommands.OwnerForm) == DialogResult.OK) { return true; } } return false; } } }
"""Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer from twisted.internet import protocol, interfaces from twisted.python.compat import _PY3 class Echo(protocol.Protocol): """As soon as any data is received, write it back (RFC 862)""" def dataReceived(self, data): self.transport.write(data) class Discard(protocol.Protocol): """Discard any received data (RFC 863)""" def dataReceived(self, data): # I'm ignoring you, nyah-nyah pass @implementer(interfaces.IProducer) class Chargen(protocol.Protocol): """Generate repeating noise (RFC 864)""" noise = r'@<API key>[\]^_`<API key>{|}~ !" def connectionMade(self): self.transport.registerProducer(self, 0) def resumeProducing(self): self.transport.write(self.noise) def pauseProducing(self): pass def stopProducing(self): pass class QOTD(protocol.Protocol): """Return a quote of the day (RFC 865)""" def connectionMade(self): self.transport.write(self.getQuote()) self.transport.loseConnection() def getQuote(self): """Return a quote. May be overrriden in subclasses.""" return "An apple a day keeps the doctor away.\r\n" class Who(protocol.Protocol): """Return list of active users (RFC 866)""" def connectionMade(self): self.transport.write(self.getUsers()) self.transport.loseConnection() def getUsers(self): """Return active users. Override in subclasses.""" return "root\r\n" class Daytime(protocol.Protocol): """Send back the daytime in ASCII form (RFC 867)""" def connectionMade(self): self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n') self.transport.loseConnection() class Time(protocol.Protocol): """Send back the time in machine readable form (RFC 868)""" def connectionMade(self): # is this correct only for 32-bit machines? result = struct.pack("!i", int(time.time())) self.transport.write(result) self.transport.loseConnection() __all__ = ["Echo", "Discard", "Chargen", "QOTD", "Who", "Daytime", "Time"] if _PY3: __all3__ = ["Echo"] for name in __all__[:]: if name not in __all3__: __all__.remove(name) del globals()[name] del name, __all3__
//! The `MozMap` (open-ended dictionary) type. use dom::bindings::conversions::jsid_to_string; use dom::bindings::str::DOMString; use js::conversions::{<API key>, ToJSValConvertible, ConversionResult}; use js::jsapi::GetPropertyKeys; use js::jsapi::HandleValue; use js::jsapi::JSContext; use js::jsapi::JSITER_OWNONLY; use js::jsapi::JSPROP_ENUMERATE; use js::jsapi::<API key>; use js::jsapi::JS_GetPropertyById; use js::jsapi::JS_NewPlainObject; use js::jsapi::MutableHandleValue; use js::jsval::ObjectValue; use js::jsval::UndefinedValue; use js::rust::IdVector; use std::collections::HashMap; use std::ops::Deref; The `MozMap` (open-ended dictionary) type. #[derive(Clone)] pub struct MozMap<T> { map: HashMap<DOMString, T>, } impl<T> MozMap<T> { Create an empty `MozMap`. pub fn new() -> Self { MozMap { map: HashMap::new(), } } } impl<T> Deref for MozMap<T> { type Target = HashMap<DOMString, T>; fn deref(&self) -> &HashMap<DOMString, T> { &self.map } } impl<T, C> <API key> for MozMap<T> where T: <API key><Config=C>, C: Clone, { type Config = C; unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, config: C) -> Result<ConversionResult<Self>, ()> { if !value.is_object() { return Ok(ConversionResult::Failure("MozMap value was not an object".into())); } rooted!(in(cx) let object = value.to_object()); let ids = IdVector::new(cx); assert!(GetPropertyKeys(cx, object.handle(), JSITER_OWNONLY, ids.get())); let mut map = HashMap::new(); for id in &*ids { rooted!(in(cx) let id = *id); rooted!(in(cx) let mut property = UndefinedValue()); if !JS_GetPropertyById(cx, object.handle(), id.handle(), property.handle_mut()) { return Err(()); } let property = match try!(T::from_jsval(cx, property.handle(), config.clone())) { ConversionResult::Success(property) => property, ConversionResult::Failure(message) => return Ok(ConversionResult::Failure(message)), }; let key = jsid_to_string(cx, id.handle()).unwrap(); map.insert(key, property); } Ok(ConversionResult::Success(MozMap { map: map, })) } } impl<T: ToJSValConvertible> ToJSValConvertible for MozMap<T> { #[inline] unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) { rooted!(in(cx) let js_object = JS_NewPlainObject(cx)); assert!(!js_object.handle().is_null()); rooted!(in(cx) let mut js_value = UndefinedValue()); for (key, value) in &self.map { let key = key.encode_utf16().collect::<Vec<_>>(); value.to_jsval(cx, js_value.handle_mut()); assert!(<API key>(cx, js_object.handle(), key.as_ptr(), key.len(), js_value.handle(), JSPROP_ENUMERATE, None, None)); } rval.set(ObjectValue(&*js_object.handle().get())); } }
#ifndef _BITSETV_H #define _BITSETV_H #include "bitset.h" typedef bitset * bitsetv; /* Create a vector of N_VECS bitsets, each of N_BITS, and of type TYPE. */ extern bitsetv bitsetv_alloc (bitset_bindex, bitset_bindex, enum bitset_type); /* Create a vector of N_VECS bitsets, each of N_BITS, and with attribute hints specified by ATTR. */ extern bitsetv bitsetv_create (bitset_bindex, bitset_bindex, unsigned int); /* Free vector of bitsets. */ extern void bitsetv_free (bitsetv); /* Zero vector of bitsets. */ extern void bitsetv_zero (bitsetv); /* Set vector of bitsets. */ extern void bitsetv_ones (bitsetv); /* Given a vector BSETV of N bitsets of size N, modify its contents to be the transitive closure of what was given. */ extern void <API key> (bitsetv); /* Given a vector BSETV of N bitsets of size N, modify its contents to be the reflexive transitive closure of what was given. This is the same as transitive closure but with all bits on the diagonal of the bit matrix set. */ extern void <API key> (bitsetv); /* Dump vector of bitsets. */ extern void bitsetv_dump (FILE *, const char *, const char *, bitsetv); /* Function to debug vector of bitsets from debugger. */ extern void debug_bitsetv (bitsetv); #endif /* _BITSETV_H */
// Themes import './styles/main.scss'; import './styles/themes/abductor.scss'; import './styles/themes/cardtable.scss'; import './styles/themes/hackerman.scss'; import './styles/themes/malfunction.scss'; import './styles/themes/neutral.scss'; import './styles/themes/ntos.scss'; import './styles/themes/paper.scss'; import './styles/themes/retro.scss'; import './styles/themes/syndicate.scss'; import './styles/themes/wizard.scss'; import { perf } from 'common/perf'; import { setupHotReloading } from 'tgui-dev-server/link/client'; import { setupHotKeys } from './hotkeys'; import { <API key> } from './links'; import { createRenderer } from './renderer'; import { configureStore, StoreProvider } from './store'; import { setupGlobalEvents } from './events'; perf.mark('inception', window.performance?.timing?.navigationStart); perf.mark('init'); const store = configureStore(); const renderApp = createRenderer(() => { const { getRoutedComponent } = require('./routes'); const Component = getRoutedComponent(store); return ( <StoreProvider store={store}> <Component /> </StoreProvider> ); }); const setupApp = () => { // Delay setup if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', setupApp); return; } setupGlobalEvents(); setupHotKeys(); <API key>(); // Subscribe for state updates store.subscribe(renderApp); // Dispatch incoming messages window.update = msg => store.dispatch(Byond.parseJson(msg)); // Process the early update queue while (true) { const msg = window.__updateQueue__.shift(); if (!msg) { break; } window.update(msg); } // Enable hot module reloading if (module.hot) { setupHotReloading(); module.hot.accept([ './components', './debug', './layouts', './routes', ], () => { renderApp(); }); } }; setupApp();
(function() { 'use strict'; Features.$inject = ['urls']; function Features(urls) { var self = this; urls.links().then(function(links) { angular.extend(self, links); }); } /** * Provides info what features are available on server */ angular.module('superdesk.features', ['superdesk.api']) .service('features', Features); })();
#ifndef <API key> #define <API key> #include <nuttx/config.h> #define GPIO_MODE_SHIFT (22) /* Bits 22-23: GPIO mode */ #define GPIO_MODE_MASK (3 << GPIO_MODE_SHIFT) # define GPIO_INPUT (0 << GPIO_MODE_SHIFT) /* GPIO Input */ # define GPIO_OUTPUT (1 << GPIO_MODE_SHIFT) /* GPIO Output */ # define GPIO_PERIPHERAL (2 << GPIO_MODE_SHIFT) /* Controlled by peripheral */ # define GPIO_INTERRUPT (3 << GPIO_MODE_SHIFT) /* Interrupting input */ #define GPIO_PULL_SHIFT (20) /* Bits 20-21: Pull-up/down resistor control */ #define GPIO_PULL_MASK (3 << GPIO_PULL_SHIFT) # define GPIO_PULL_NONE (0 << GPIO_PULL_SHIFT) # define GPIO_PULL_UP (1 << GPIO_PULL_SHIFT) # define GPIO_PULL_DOWN (2 << GPIO_PULL_SHIFT) # define GPIO_PULL_BUSKEEPER (3 << GPIO_PULL_SHIFT) #define GPIO_FUNC_SHIFT (17) /* Bits 17-19: Peripheral function */ #define GPIO_FUNC_MASK (7 << GPIO_FUNC_SHIFT) # define _GPIO_FUNCA (0 << GPIO_FUNC_SHIFT) /* Function A */ # define _GPIO_FUNCB (1 << GPIO_FUNC_SHIFT) /* Function B */ # define _GPIO_FUNCC (2 << GPIO_FUNC_SHIFT) /* Function C */ # define _GPIO_FUNCD (3 << GPIO_FUNC_SHIFT) /* Function D */ # define _GPIO_FUNCE (4 << GPIO_FUNC_SHIFT) /* Function E */ # define _GPIO_FUNCF (5 << GPIO_FUNC_SHIFT) /* Function F */ # define _GPIO_FUNCG (6 << GPIO_FUNC_SHIFT) /* Function G */ # define _GPIO_FUNCH (7 << GPIO_FUNC_SHIFT) /* Function H */ #define GPIO_FUNCA (GPIO_PERIPHERAL | _GPIO_FUNCA) /* Function A */ #define GPIO_FUNCB (GPIO_PERIPHERAL | _GPIO_FUNCB) /* Function B */ #define GPIO_FUNCC (GPIO_PERIPHERAL | _GPIO_FUNCC) /* Function C */ #define GPIO_FUNCD (GPIO_PERIPHERAL | _GPIO_FUNCD) /* Function D */ #define GPIO_FUNCE (GPIO_PERIPHERAL | _GPIO_FUNCE) /* Function E */ #define GPIO_FUNCF (GPIO_PERIPHERAL | _GPIO_FUNCF) /* Function F */ #define GPIO_FUNCG (GPIO_PERIPHERAL | _GPIO_FUNCG) /* Function G */ #define GPIO_FUNCH (GPIO_PERIPHERAL | _GPIO_FUNCH) /* Function H */ #define GPIO_PERIPH_EVENTS (1 << 16) /* Bit 16: Enable peripheral events */ #define GPIO_DRIVE_SHIFT (14) /* Bits 14-15: Interrupting input control */ #define GPIO_DRIVE_MASK (3 << GPIO_INT_SHIFT) /* Lowest drive strength*/ # define GPIO_DRIVE_LOW (0 << GPIO_INT_SHIFT) # define GPIO_DRIVE_MEDLOW (1 << GPIO_INT_SHIFT) # define GPIO_DRIVE_MEDHIGH (2 << GPIO_INT_SHIFT) # define GPIO_DRIVE_HIGH (3 << GPIO_INT_SHIFT) /* Highest drive strength */ #define GPIO_SLEW (1 << 13) /* Bit 13: Enable output slew control */ #define GPIO_OUTPUT_SET (1 << 12) /* Bit 12: Inital value of output */ #define GPIO_OUTPUT_CLEAR (0) #define GPIO_INT_SHIFT (10) /* Bits 10-11: Interrupting input control */ #define GPIO_INT_MASK (3 << GPIO_INT_SHIFT) # define GPIO_INT_CHANGE (0 << GPIO_INT_SHIFT) /* Pin change */ # define GPIO_INT_RISING (1 << GPIO_INT_SHIFT) /* Rising edge */ # define GPIO_INT_FALLING (2 << GPIO_INT_SHIFT) /* Falling edge */ /* These combinations control events. These help to clean up pin definitions. */ #define GPIO_EVENT_CHANGE (GPIO_PERIPH_EVENTS | GPIO_INT_CHANGE) /* Pin change */ #define GPIO_EVENT_RISING (GPIO_PERIPH_EVENTS | GPIO_INT_RISING) /* Rising edge */ #define GPIO_EVENT_FALLING (GPIO_PERIPH_EVENTS | GPIO_INT_FALLING) /* Falling edge */ #define GPIO_GLITCH_FILTER (1 << 9) /* Bit 9: Enable input/peripheral glitch filter */ #define <API key> (1 << 8) /* Bit 8: Enable Input Schmitt trigger */ #define GPIO_PORT_SHIFT (5) /* Bit 5-6: Port number */ #define GPIO_PORT_MASK (3 << GPIO_PORT_SHIFT) # define GPIO_PORTA (0 << GPIO_PORT_SHIFT) # define GPIO_PORTB (1 << GPIO_PORT_SHIFT) # define GPIO_PORTC (2 << GPIO_PORT_SHIFT) #define GPIO_PIN_SHIFT 0 /* Bits 0-4: GPIO number: 0-31 */ #define GPIO_PIN_MASK (31 << GPIO_PIN_SHIFT) #define GPIO_PIN0 (0 << GPIO_PIN_SHIFT) #define GPIO_PIN1 (1 << GPIO_PIN_SHIFT) #define GPIO_PIN2 (2 << GPIO_PIN_SHIFT) #define GPIO_PIN3 (3 << GPIO_PIN_SHIFT) #define GPIO_PIN4 (4 << GPIO_PIN_SHIFT) #define GPIO_PIN5 (5 << GPIO_PIN_SHIFT) #define GPIO_PIN6 (6 << GPIO_PIN_SHIFT) #define GPIO_PIN7 (7 << GPIO_PIN_SHIFT) #define GPIO_PIN8 (8 << GPIO_PIN_SHIFT) #define GPIO_PIN9 (9 << GPIO_PIN_SHIFT) #define GPIO_PIN10 (10 << GPIO_PIN_SHIFT) #define GPIO_PIN11 (11 << GPIO_PIN_SHIFT) #define GPIO_PIN12 (12 << GPIO_PIN_SHIFT) #define GPIO_PIN13 (13 << GPIO_PIN_SHIFT) #define GPIO_PIN14 (14 << GPIO_PIN_SHIFT) #define GPIO_PIN15 (15 << GPIO_PIN_SHIFT) #define GPIO_PIN16 (16 << GPIO_PIN_SHIFT) #define GPIO_PIN17 (17 << GPIO_PIN_SHIFT) #define GPIO_PIN18 (18 << GPIO_PIN_SHIFT) #define GPIO_PIN19 (19 << GPIO_PIN_SHIFT) #define GPIO_PIN20 (20 << GPIO_PIN_SHIFT) #define GPIO_PIN21 (21 << GPIO_PIN_SHIFT) #define GPIO_PIN22 (22 << GPIO_PIN_SHIFT) #define GPIO_PIN23 (23 << GPIO_PIN_SHIFT) #define GPIO_PIN24 (24 << GPIO_PIN_SHIFT) #define GPIO_PIN25 (25 << GPIO_PIN_SHIFT) #define GPIO_PIN26 (26 << GPIO_PIN_SHIFT) #define GPIO_PIN27 (27 << GPIO_PIN_SHIFT) #define GPIO_PIN28 (28 << GPIO_PIN_SHIFT) #define GPIO_PIN29 (29 << GPIO_PIN_SHIFT) #define GPIO_PIN30 (30 << GPIO_PIN_SHIFT) #define GPIO_PIN31 (31 << GPIO_PIN_SHIFT) /* Must be big enough to hold the 24-bit encoding */ typedef uint32_t gpio_pinset_t; #ifndef __ASSEMBLY__ #undef EXTERN #if defined(__cplusplus) #define EXTERN extern "C" extern "C" { #else #define EXTERN extern #endif #undef EXTERN #if defined(__cplusplus) } #endif #endif /* __ASSEMBLY__ */ #endif /* <API key> */
/* Colorbox Core Style: The following CSS is consistent between example themes and should not be altered. */ #colorbox, #cboxOverlay, #cboxWrapper { position: absolute; top: 0; left: 0; z-index: 9999; overflow: hidden; } #cboxOverlay { position: fixed; width: 100%; height: 100%; } #cboxMiddleLeft, #cboxBottomLeft { clear: left; } #cboxContent { position: relative; } #cboxLoadedContent { overflow: auto; -<API key>: touch; } #cboxTitle { margin: 0; } #cboxLoadingOverlay, #cboxLoadingGraphic { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } #cboxPrevious, #cboxNext, #cboxClose, #cboxSlideshow { cursor: pointer; } .cboxPhoto { float: left; margin: auto; border: 0; display: block; max-width: none; -<API key>: bicubic; } .cboxIframe { width: 100%; height: 100%; display: block; border: 0; } #colorbox, #cboxContent, #cboxLoadedContent { box-sizing: content-box; -moz-box-sizing: content-box; -webkit-box-sizing: content-box; } /* User Style: Change the following styles to modify the appearance of Colorbox. They are ordered & tabbed in a way that represents the nesting of the generated HTML. */ #cboxOverlay { background: #000; } #colorbox { outline: 0; } #cboxTopLeft { width: 14px; height: 14px; background: url(images/controls.png) no-repeat 0 0; } #cboxTopCenter { height: 14px; background: url(images/border.png) repeat-x top left; } #cboxTopRight { width: 14px; height: 14px; background: url(images/controls.png) no-repeat -36px 0; } #cboxBottomLeft { width: 14px; height: 43px; background: url(images/controls.png) no-repeat 0 -32px; } #cboxBottomCenter { height: 43px; background: url(images/border.png) repeat-x bottom left; } #cboxBottomRight { width: 14px; height: 43px; background: url(images/controls.png) no-repeat -36px -32px; } #cboxMiddleLeft { width: 14px; background: url(images/controls.png) repeat-y -175px 0; } #cboxMiddleRight { width: 14px; background: url(images/controls.png) repeat-y -211px 0; } #cboxContent { background: #FFF; overflow: visible; } .cboxIframe { background: #FFF; } #cboxError { padding: 50px; border: 1px solid #CCC; } #cboxLoadedContent { margin-bottom: 5px; } #cboxLoadingOverlay { background: url(images/loading_background.png) no-repeat center center; } #cboxLoadingGraphic { background: url(images/loading.gif) no-repeat center center; } #cboxTitle { position: absolute; bottom: -25px; left: 0; text-align: center; width: 100%; font-weight: bold; color: #7C7C7C; } #cboxCurrent { position: absolute; bottom: -25px; left: 58px; font-weight: bold; color: #7C7C7C; } /* these elements are buttons, and may need to have additional styles reset to avoid unwanted base styles */ #cboxPrevious, #cboxNext, #cboxSlideshow, #cboxClose { border: 0; padding: 0; margin: 0; overflow: visible; position: absolute; bottom: -29px; background: url(images/controls.png) no-repeat 0px 0px; width: 23px; height: 23px; text-indent: -9999px; } /* avoid outlines on :active (mouseclick), but preserve outlines on :focus (tabbed navigating) */ #cboxPrevious:active, #cboxNext:active, #cboxSlideshow:active, #cboxClose:active { outline: 0; } #cboxPrevious { left: 0px; background-position: -51px -25px; } #cboxPrevious:hover { background-position: -51px 0px; } #cboxNext { left: 27px; background-position: -75px -25px; } #cboxNext:hover { background-position: -75px 0px; } #cboxClose { right: 0; background-position: -100px -25px; } #cboxClose:hover { background-position: -100px 0px; } .cboxSlideshow_on #cboxSlideshow { background-position: -125px 0px; right: 27px; } .cboxSlideshow_on #cboxSlideshow:hover { background-position: -150px 0px; } .cboxSlideshow_off #cboxSlideshow { background-position: -150px -25px; right: 27px; } .cboxSlideshow_off #cboxSlideshow:hover { background-position: -125px 0px; }
require File.dirname(__FILE__)+"/env" module Actors # /actors/worker class Worker include Magent::Actor expose :echo def echo(payload) puts payload.inspect end end Magent.register(Worker.new) end if $0 == __FILE__ Magent::Processor.new(Magent.current_actor).run! end
UPDATE `version` SET `app_ver` = '1.4.0', `XmdsVersion` = 3; UPDATE `setting` SET `value` = 0 WHERE `setting` = 'PHONE_HOME_DATE'; UPDATE `version` SET `DBVersion` = '50';
# -*- coding: utf-8 -*- # This file is part of weboob. # weboob is free software: you can redistribute it and/or modify # (at your option) any later version. # weboob is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the import requests.cookies try: import cookielib except ImportError: import http.cookiejar as cookielib __all__ = ['WeboobCookieJar'] class WeboobCookieJar(requests.cookies.RequestsCookieJar): @classmethod def from_cookiejar(klass, cj): """ Create a WeboobCookieJar from another CookieJar instance. """ return requests.cookies.merge_cookies(klass(), cj) def export(self, filename): """ Export all cookies to a file, regardless of expiration, etc. """ cj = requests.cookies.merge_cookies(cookielib.LWPCookieJar(), self) cj.save(filename, ignore_discard=True, ignore_expires=True) def <API key>(self, attrs_set, request): for tup in self.<API key>(attrs_set): cookie = self.<API key>(tup, request) if cookie: yield cookie def make_cookies(self, response, request): """Return sequence of Cookie objects extracted from response object.""" # get cookie-attributes for RFC 2965 and Netscape protocols headers = response.info() rfc2965_hdrs = headers.getheaders("Set-Cookie2") ns_hdrs = headers.getheaders("Set-Cookie") rfc2965 = self._policy.rfc2965 netscape = self._policy.netscape if netscape: for cookie in self.<API key>(cookielib.parse_ns_headers(ns_hdrs), request): self.<API key>([cookie]) yield cookie if rfc2965: for cookie in self.<API key>(cookielib.split_header_words(rfc2965_hdrs), request): yield cookie def copy(self): new_cj = type(self)() new_cj.update(self) return new_cj
<?php /** * @package Core * @subpackage system * @deprecated */ require_once ( __DIR__ . "/kalturaSystemAction.class.php" ); /** * @package Core * @subpackage system * @deprecated */ class <API key> extends kalturaSystemAction { // TODO - read from the entryWrapper private static $allowed_names = array ( "conversionQuality" ); /** * Will anipulate a single entry */ public function execute() { $this-><API key>(); myDbHelper::$use_alternative_con = null; $command = $this->getP ( "command" ); if ( $command == "updateEntry" ) { $id = $this->getP ( "id" ); $entry = entryPeer::retrieveByPK( $id ); if ( $entry ) { $name = $this->getP ( "name" ); $value = $this->getP ( "value" ); $obj_wrapper = objectWrapperBase::getWrapperClass( $entry , 0 ); $updateable_fields = $obj_wrapper->getUpdateableFields( "2" ); if ( ! in_array ( $name , $updateable_fields ) ) die(); if ( $name ) { $setter = "set" . $name; call_user_func( array ( $entry , $setter ) , $value ); $entry->save(); } } } die(); } } ?>
/** * Action that sets up BCs for porous flow module */ class <API key> : public MooseObjectAction { public: static InputParameters validParams(); <API key>(const InputParameters & parameters); virtual void act() override; protected: /** * Setup a BC corresponding to hot/cold fluid injection */ void <API key>(); };
package lucee.runtime.type.comparator; import java.util.Comparator; import lucee.commons.lang.ComparatorUtil; import lucee.runtime.PageContext; import lucee.runtime.engine.<API key>; import lucee.runtime.exp.PageException; import lucee.runtime.op.Caster; /** * Implementation of a Comparator, compares to Softregister Objects */ public final class <API key> implements ExceptionComparator { private boolean isAsc; private PageException pageException=null; private boolean ignoreCase; private final Comparator comparator; /** * constructor of the class * @param isAsc is ascending or descending * @param ignoreCase do ignore case */ public <API key>(PageContext pc,boolean isAsc, boolean ignoreCase, boolean localeSensitive) { this.isAsc=isAsc; this.ignoreCase=ignoreCase; comparator = ComparatorUtil.toComparator( ignoreCase?ComparatorUtil.<API key>:ComparatorUtil.SORT_TYPE_TEXT , isAsc, localeSensitive?<API key>.getLocale(pc):null, null); } /** * @return Returns the expressionException. */ public PageException getPageException() { return pageException; } @Override public int compare(Object oLeft, Object oRight) { try { if(pageException!=null) return 0; else if(isAsc) return compareObjects(oLeft, oRight); else return compareObjects(oRight, oLeft); } catch (PageException e) { pageException=e; return 0; } } private int compareObjects(Object oLeft, Object oRight) throws PageException { String strLeft=Caster.toString(((SortRegister)oLeft).getValue()); String strRight=Caster.toString(((SortRegister)oRight).getValue()); return comparator.compare(strLeft, strRight); } }
#include "QXmppClient.h" #include "QXmppConstants.h" #include "QXmppUtils.h" #include "QXmppVCardIq.h" #include "QXmppVCardManager.h" class <API key> { public: QXmppVCardIq clientVCard; bool <API key>; }; QXmppVCardManager::QXmppVCardManager() : d(new <API key>) { d-><API key> = false; } QXmppVCardManager::~QXmppVCardManager() { delete d; } This function requests the server for vCard of the specified jid. Once received the signal vCardReceived() is emitted. \param jid Jid of the specific entry in the roster QString QXmppVCardManager::requestVCard(const QString& jid) { QXmppVCardIq request(jid); if(client()->sendPacket(request)) return request.id(); else return QString(); } Returns the vCard of the connected client. \return QXmppVCard const QXmppVCardIq& QXmppVCardManager::clientVCard() const { return d->clientVCard; } Sets the vCard of the connected client. \param clientVCard QXmppVCard void QXmppVCardManager::setClientVCard(const QXmppVCardIq& clientVCard) { d->clientVCard = clientVCard; d->clientVCard.setTo(""); d->clientVCard.setFrom(""); d->clientVCard.setType(QXmppIq::Set); client()->sendPacket(d->clientVCard); } This function requests the server for vCard of the connected user itself. Once received the signal clientVCardReceived() is emitted. Received vCard can be get using clientVCard(). QString QXmppVCardManager::requestClientVCard() { return requestVCard(); } Returns true if vCard of the connected client has been received else false. \return bool bool QXmppVCardManager::<API key>() const { return d-><API key>; } \cond QStringList QXmppVCardManager::discoveryFeatures() const { // XEP-0054: vcard-temp return QStringList() << ns_vcard; } bool QXmppVCardManager::handleStanza(const QDomElement &element) { if(element.tagName() == "iq" && QXmppVCardIq::isVCard(element)) { QXmppVCardIq vCardIq; vCardIq.parse(element); if (vCardIq.from().isEmpty()) { d->clientVCard = vCardIq; d-><API key> = true; emit clientVCardReceived(); } emit vCardReceived(vCardIq); return true; } return false; } \endcond
using Nop.Web.Framework.Mvc; namespace Nop.Admin.Models.Common { public partial class SystemWarningModel : BaseNopModel { public SystemWarningLevel Level { get; set; } public string Text { get; set; } } public enum SystemWarningLevel { Pass, Warning, Fail } }
Module Name: AzureRM.ApiManagement Module Guid: <API key> Download Help Link: None Help Version: 4.0.0.0 Locale: en-US ms.assetid: <API key> # AzureRM.ApiManagement Module ## Description This topic displays help topics for the Azure API Management Cmdlets. ## AzureRM.ApiManagement Cmdlets [<API key>](<API key>.md) Adds an API to a product. [<API key>](<API key>.md) Adds a product to a group. [<API key>](<API key>.md) Adds new deployment regions to a PsApiManagement instance. [<API key>](<API key>.md) Adds a user to a group. [<API key>](<API key>.md) Backs up an API Management service. [<API key>](<API key>.md) Exports an API to a file. [<API key>](<API key>.md) Gets a list or a particular API Management Service description. [<API key>](<API key>.md) Gets an API. [<API key>](<API key>.md) Gets an API Management authorization server. [<API key>](<API key>.md) Gets API Management certificates. [<API key>](<API key>.md) Gets all or specific API management groups. [<API key>](<API key>.md) Gets API Management Logger objects. [<API key>](<API key>.md) Gets OpenID Connect providers. [<API key>](<API key>.md) Gets a list or a specified API Operation. [<API key>](<API key>.md) Gets the specified scope policy. [<API key>](<API key>.md) Gets a list or a particular product. [<API key>](<API key>.md) [<API key>](<API key>.md) Gets a link with an SSO token to a deployed management portal of an API Management service. [<API key>](<API key>.md) Gets subscriptions. [<API key>](<API key>.md) Gets the access configuration for a tenant. [<API key>](<API key>.md) Gets the Git access configuration for a tenant. [<API key>](<API key>.md) Gets the status of the most recent synchronization between the configuration database and the Git repository. [<API key>](<API key>.md) Gets a user or users. [<API key>](<API key>.md) Generates an SSO URL for a user. [<API key>](<API key>.md) Imports an API from a file or a URL. [<API key>](<API key>.md) Imports a certificate in a PFX format for an API Management Service. [<API key>](<API key>.md) Creates an API Management deployment. [<API key>](<API key>.md) Creates an API. [<API key>](<API key>.md) Creates an authorization server. [<API key>](<API key>.md) Creates an API Management certificate. [<API key>](<API key>.md) Creates an instance of <API key>. [<API key>](<API key>.md) Creates an API management group. [<API key>](<API key>.md) Creates an instance of <API key>. [<API key>](<API key>.md) Creates an API Management Logger. [<API key>](<API key>.md) Creates an OpenID Connect provider. [<API key>](<API key>.md) Creates an API management operation. [<API key>](<API key>.md) Creates an API Management product. [<API key>](<API key>.md) Creates a new Property. [<API key>](<API key>.md) Creates an instance of <API key>. [<API key>](<API key>.md) Creates a subscription. [<API key>](<API key>.md) Registers a new user. [<API key>](<API key>.md) Creates an instance of <API key>. [<API key>](<API key>.md) Publishes changes from a Git branch to the configuration database. [<API key>](<API key>.md) Removes an API Management service. [<API key>](<API key>.md) Removes an API. [<API key>](<API key>.md) Removes an API from a product. [<API key>](<API key>.md) Removes an authorization server. [<API key>](<API key>.md) Removes an API Management certificate. [<API key>](<API key>.md) Removes an existing API management group. [<API key>](<API key>.md) Removes an API Management Logger. [<API key>](<API key>.md) Removes an OpenID Connect provider. [<API key>](<API key>.md) Removes an existing operation. [<API key>](<API key>.md) Removes the API Management policy from a specified scope. [<API key>](<API key>.md) Removes an existing API Management product. [<API key>](<API key>.md) Removes a product from a group. [<API key>](<API key>.md) Removes an API Management Property. [<API key>](<API key>.md) Removes an existing deployment region from PsApiManagement instance. [<API key>](<API key>.md) Deletes an existing subscription. [<API key>](<API key>.md) Deletes an existing user. [<API key>](<API key>.md) Removes a user from a group. [<API key>](<API key>.md) Restores an API Management Service from the specified Azure storage blob. [<API key>](<API key>.md) Saves changes by creating a commit for current configuration. [<API key>](<API key>.md) Modifies an API. [<API key>](<API key>.md) Modifies an authorization server. [<API key>](<API key>.md) Modifies an API Management certificate. [<API key>](<API key>.md) Configures an API management group. [<API key>](<API key>.md) Sets a custom hostname configuration for an API Management service proxy or portal. [<API key>](<API key>.md) Modifies an API Management Logger. [<API key>](<API key>.md) Modifies an OpenID Connect provider. [<API key>](<API key>.md) Sets API operation details. [<API key>](<API key>.md) Sets the specified scope policy for API Management. [<API key>](<API key>.md) Sets the API Management product details. [<API key>](<API key>.md) Modifies an API Management Property. [<API key>](<API key>.md) Sets existing subscription details. [<API key>](<API key>.md) Enables or disables tenant access. [<API key>](<API key>.md) Sets user details. [<API key>](<API key>.md) Updates deployment of an API Management Service. [<API key>](<API key>.md) Updates existing deployment region in PsApiManagement instance.
// Tests for the JavaScriptMVC compatibility layer. Will be removed eventually steal('funcunit/qunit', 'jquerypp/controller/view/test/qunit' , 'jquerypp/class/class_test.js' , 'jquerypp/model/test/qunit' , 'jquerypp/controller/controller_test.js' , 'jquerypp/view/test/qunit' , 'jquerypp/dom/route/route_test.js' , './integration.js');
package org.wso2.developerstudio.eclipse.gmf.esb.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.edit.provider.<API key>; import org.eclipse.emf.edit.provider.IItemLabelProvider; import org.eclipse.emf.edit.provider.<API key>; import org.eclipse.emf.edit.provider.IItemPropertySource; import org.eclipse.emf.edit.provider.<API key>; import org.eclipse.emf.edit.provider.<API key>; /** * This is the item provider adapter for a {@link org.wso2.developerstudio.eclipse.gmf.esb.<API key>} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class <API key> extends <API key> { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public <API key>(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<<API key>> <API key>(Object object) { if (<API key> == null) { super.<API key>(object); } return <API key>; } /** * This returns <API key>.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/<API key>")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { return getString("<API key>"); } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void <API key>(Collection<Object> newChildDescriptors, Object object) { super.<API key>(newChildDescriptors, object); } }
/** * @fileOverview */ /** * Constains the dictionary of language entries. * @namespace */ CKFinder.lang['el'] = { appTitle : 'CKFinder', // MISSING // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING ok : 'OK', // MISSING cancel : 'Cancel', // MISSING confirmationTitle : 'Confirmation', // MISSING messageTitle : 'Information', // MISSING inputTitle : 'Question', // MISSING undo : 'Undo', // MISSING redo : 'Redo', // MISSING skip : 'Skip', // MISSING skipAll : 'Skip all', // MISSING makeDecision : 'What action should be taken?', // MISSING rememberDecision: 'Remember my decision' // MISSING }, dir : 'ltr', // MISSING HelpLang : 'en', LangCode : 'el', // Date Format // d : Day // dd : Day (padding zero) // m : Month // mm : Month (padding zero) // yy : Year (two digits) // yyyy : Year (four digits) // h : Hour (12 hour clock) // hh : Hour (12 hour clock, padding zero) // H : Hour (24 hour clock) // HH : Hour (24 hour clock, padding zero) // M : Minute // MM : Minute (padding zero) // a : Firt char of AM/PM // aa : AM/PM DateTime : 'dd/mm/yyyy HH:MM', DateAmPm : ['ΜΜ', 'ΠΜ'], // Folders FoldersTitle : 'Φάκελοι', FolderLoading : 'Φόρτωση...', FolderNew : 'Παρακαλούμε πληκτρολογήστε την ονομασία του νέου φακέλου: ', FolderRename : 'Παρακαλούμε πληκτρολογήστε την νέα ονομασία του φακέλου: ', FolderDelete : 'Είστε σίγουροι ότι θέλετε να διαγράψετε το φάκελο "%1";', FolderRenaming : ' (Μετονομασία...)', FolderDeleting : ' (Διαγραφή...)', // Files FileRename : 'Παρακαλούμε πληκτρολογήστε την νέα ονομασία του αρχείου: ', FileRenameExt : 'Είστε σίγουροι ότι θέλετε να αλλάξετε την επέκταση του αρχείου; Μετά από αυτή την ενέργεια το αρχείο μπορεί να μην μπορεί να χρησιμοποιηθεί', FileRenaming : 'Μετονομασία...', FileDelete : 'Είστε σίγουροι ότι θέλετε να διαγράψετε το αρχείο "%1"?', FilesLoading : 'Loading...', // MISSING FilesEmpty : 'Empty folder', // MISSING FilesMoved : 'File %1 moved into %2:%3', // MISSING FilesCopied : 'File %1 copied into %2:%3', // MISSING // Basket BasketFolder : 'Basket', // MISSING BasketClear : 'Clear Basket', // MISSING BasketRemove : 'Remove from basket', // MISSING BasketOpenFolder : 'Open parent folder', // MISSING <API key> : 'Do you really want to remove all files from the basket?', // MISSING BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING BasketEmpty : 'No files in the basket, drag\'n\'drop some.', // MISSING BasketCopyFilesHere : 'Copy Files from Basket', // MISSING BasketMoveFilesHere : 'Move Files from Basket', // MISSING <API key> : 'File %s error: %e', // MISSING <API key> : 'The following files were moved: %s', // MISSING <API key> : 'The following files were copied: %s', // MISSING // Toolbar Buttons (some used elsewhere) Upload : 'Μεταφόρτωση', UploadTip : 'Μεταφόρτωση Νέου Αρχείου', Refresh : 'Ανανέωση', Settings : 'Ρυθμίσεις', Help : 'Βοήθεια', HelpTip : 'Βοήθεια', // Context Menus Select : 'Επιλογή', SelectThumbnail : 'Επιλογή Μικρογραφίας', View : 'Προβολή', Download : 'Λήψη Αρχείου', NewSubFolder : 'Νέος Υποφάκελος', Rename : 'Μετονομασία', Delete : 'Διαγραφή', CopyDragDrop : 'Copy file here', // MISSING MoveDragDrop : 'Move file here', // MISSING // Dialogs RenameDlgTitle : 'Rename', // MISSING NewNameDlgTitle : 'New name', // MISSING FileExistsDlgTitle : 'File already exists', // MISSING SysErrorDlgTitle : 'System error', // MISSING FileOverwrite : 'Overwrite', // MISSING FileAutorename : 'Auto-rename', // MISSING // Generic OkBtn : 'OK', CancelBtn : 'Ακύρωση', CloseBtn : 'Κλείσιμο', // Upload Panel UploadTitle : 'Μεταφόρτωση Νέου Αρχείου', UploadSelectLbl : 'επιλέξτε το αρχείο που θέλετε να μεταφερθεί κάνοντας κλίκ στο κουμπί', UploadProgressLbl : '(Η μεταφόρτωση εκτελείται, παρακαλούμε περιμένετε...)', UploadBtn : 'Μεταφόρτωση Επιλεγμένου Αρχείου', UploadBtnCancel : 'Cancel', // MISSING UploadNoFileMsg : 'Παρακαλούμε επιλέξτε ένα αρχείο από τον υπολογιστή σας', UploadNoFolder : 'Please select folder before uploading.', // MISSING UploadNoPerms : 'File upload not allowed.', // MISSING UploadUnknError : 'Error sending the file.', // MISSING UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING // Settings Panel SetTitle : 'Ρυθμίσεις', SetView : 'Προβολή:', SetViewThumb : 'Μικρογραφίες', SetViewList : 'Λίστα', SetDisplay : 'Εμφάνιση:', SetDisplayName : 'Όνομα Αρχείου', SetDisplayDate : 'Ημερομηνία', SetDisplaySize : 'Μέγεθος Αρχείου', SetSort : 'Ταξινόμηση:', SetSortName : 'βάσει Όνοματος Αρχείου', SetSortDate : 'βάσει Ημερομήνιας', SetSortSize : 'βάσει Μεγέθους', // Status Bar FilesCountEmpty : '<Κενός Φάκελος>', FilesCountOne : '1 αρχείο', FilesCountMany : '%1 αρχεία', // Size and Speed Kb : '%1 kB', KbPerSecond : '%1 kB/s', // Connector Error Messages. ErrorUnknown : 'Η ενέργεια δεν ήταν δυνατόν να εκτελεστεί. (Σφάλμα %1)', Errors : { 10 : 'Λανθασμένη Εντολή.', 11 : 'Το resource type δεν ήταν δυνατόν να προσδιορίστεί.', 12 : 'Το resource type δεν είναι έγκυρο.', 102 : 'Το όνομα αρχείου ή φακέλου δεν είναι έγκυρο.', 103 : 'Δεν ήταν δυνατή η εκτέλεση της ενέργειας λόγω έλλειψης δικαιωμάτων ασφαλείας.', 104 : 'Δεν ήταν δυνατή η εκτέλεση της ενέργειας λόγω περιορισμών του συστήματος αρχείων.', 105 : 'Λανθασμένη Επέκταση Αρχείου.', 109 : 'Λανθασμένη Ενέργεια.', 110 : 'Άγνωστο Λάθος.', 115 : 'Το αρχείο ή φάκελος υπάρχει ήδη.', 116 : 'Ο φάκελος δεν βρέθηκε. Παρακαλούμε ανανεώστε τη σελίδα και προσπαθήστε ξανά.', 117 : 'Το αρχείο δεν βρέθηκε. Παρακαλούμε ανανεώστε τη σελίδα και προσπαθήστε ξανά.', 118 : 'Source and target paths are equal.', // MISSING 201 : 'Ένα αρχείο με την ίδια ονομασία υπάρχει ήδη. Το μεταφορτωμένο αρχείο μετονομάστηκε σε "%1"', 202 : 'Λανθασμένο Αρχείο', 203 : 'Λανθασμένο Αρχείο. Το μέγεθος του αρχείου είναι πολύ μεγάλο.', 204 : 'Το μεταφορτωμένο αρχείο είναι χαλασμένο.', 205 : 'Δεν υπάρχει προσωρινός φάκελος για να χρησιμοποιηθεί για τις μεταφορτώσεις των αρχείων.', 206 : 'Η μεταφόρτωση ακυρώθηκε για λόγους ασφαλείας. Το αρχείο περιέχει δεδομένα μορφής HTML.', 207 : 'Το μεταφορτωμένο αρχείο μετονομάστηκε σε "%1"', 300 : 'Moving file(s) failed.', // MISSING 301 : 'Copying file(s) failed.', // MISSING 500 : 'Ο πλοηγός αρχείων έχει απενεργοποιηθεί για λόγους ασφαλείας. Παρακαλούμε επικοινωνήστε με τον διαχειριστή της ιστοσελίδας και ελέγξτε το αρχείο ρυθμίσεων του πλοηγού (CKFinder).', 501 : 'Η υποστήριξη των μικρογραφιών έχει απενεργοποιηθεί.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'Η ονομασία του αρχείου δεν μπορεί να είναι κενή', FileExists : 'File %s already exists', // MISSING FolderEmpty : 'Η ονομασία του φακέλου δεν μπορεί να είναι κενή', FileInvChar : 'Η ονομασία του αρχείου δεν μπορεί να περιέχει τους ακόλουθους χαρακτήρες: \n\\ / : * ? " < > |', FolderInvChar : 'Η ονομασία του φακέλου δεν μπορεί να περιέχει τους ακόλουθους χαρακτήρες: \n\\ / : * ? " < > |', PopupBlockView : 'Δεν ήταν εφικτό να ανοίξει το αρχείο σε νέο παράθυρο. Παρακαλώ, ελέγξτε τις ρυθμίσεις τους πλοηγού σας και απενεργοποιήστε όλους τους popup blockers για αυτή την ιστοσελίδα.' }, // Imageresize plugin Imageresize : { dialogTitle : 'Resize %s', // MISSING sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING resizeSuccess : 'Image resized successfully.', // MISSING thumbnailNew : 'Create new thumbnail', // MISSING thumbnailSmall : 'Small (%s)', // MISSING thumbnailMedium : 'Medium (%s)', // MISSING thumbnailLarge : 'Large (%s)', // MISSING newSize : 'Set new size', // MISSING width : 'Width', // MISSING height : 'Height', // MISSING invalidHeight : 'Invalid height.', // MISSING invalidWidth : 'Invalid width.', // MISSING invalidName : 'Invalid file name.', // MISSING newImage : 'Create new image', // MISSING noExtensionChange : 'The file extension cannot be changed.', // MISSING imageSmall : 'Source image is too small', // MISSING contextMenuName : 'Resize' // MISSING }, // Fileeditor plugin Fileeditor : { save : 'Save', // MISSING fileOpenError : 'Unable to open file.', // MISSING fileSaveSuccess : 'File saved successfully.', // MISSING contextMenuName : 'Edit', // MISSING loadingFile : 'Loading file, please wait...' // MISSING } };
(function (define) { 'use strict'; var undef; /** * Aggregate messages into batches as they are received. */ define(function (require) { var msgs = require('..'); /** * Aggregates messages into batches as they are received. Batches may * be chunked either by an absolute size and/or a timeout since the * first message was received for the chunk. Either a batch size or * timeout must be specified. * * @param {string} [name] the name to register the aggregator as * @param {number} [opts.batch=0] absolute size of a chunk. If <=0, * batch size is not a factor * @param {number} [opts.timeout=0] number of milliseconds since the * first message arrived to queue the chunk. If <=0, timeout is not a * factor * @param {string|Channel} [opts.output] the channel to post the * aggregated messages to * @param {string|Channel} [opts.input] the channel to receive message * from * @param {string|Channel} [opts.error] channel to receive errors * @returns the aggregator * @throws on invalid configuration, batch size or timeout is required */ msgs.prototype.batchingAggregator = msgs.utils.optionalName(function batchingAggregator(name, opts) { var timeout, batch; batch = []; opts = opts || {}; opts.batch = opts.batch || 0; opts.timeout = opts.timeout || 0; if (opts.batch <= 0 && opts.timeout <= 0) { throw new Error('Invalid configuration: batch size or timeout must be defined'); } function releaseHelper(release) { release(batch); batch = []; clearTimeout(timeout); timeout = undef; } return this.aggregator(name, function (message, release) { batch.push(message.payload); if (opts.batch > 0 && batch.length >= opts.batch) { releaseHelper(release); } else if (!timeout && opts.timeout > 0) { timeout = setTimeout(function () { releaseHelper(release); }, opts.timeout); } }, opts); }); return msgs; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); } // Boilerplate for AMD and Node ));
<widget-modal widget-modal-title="Administer Api Token"> <form name="cdf" class="form" ng-submit="ctrl.submit(cdf)" novalidate> <form-group input="apiUser" errors="{required: 'Api user name is required', minlength: 'Min length of 6 characters', maxlength: 'Max length of 50 characters', pattern : 'Special character(s) found. Please enter only letters, numbers or spaces.'}"> <label class="modal-label">Api User</label> <input type="text" name="apiUser" class="form-control" placeholder="Api User" ng-model="ctrl.apiUser" required disabled="true" maxlength="50" autocomplete="off" minlength="6" ng-pattern="/^[a-zA-Z0-9 ]*$/"/> <span class="text-danger"></span> </form-group> <form-group input="expDt" class="text-center" errors="{apiTokenError: 'Error updating api token.'}"> <br> <label class="modal-label" id="dtLabel">Expiration Date</label> <div class="row"> <div class="col-xs-offset-3 col-xs-6"> <date-picker <API key>="true" dp-Name="expDt" ng-model="ctrl.date"></date-picker> </div> </div> </form-group> <div class="button-row row text-center"> <button type="submit" class="btn btn-primary btn-wide">Save</button> </div> </form> </widget-modal>
package me.kafeitu.activiti.chapter15.leave; import me.kafeitu.activiti.chapter15.leave.ws.LeaveWebService; import org.apache.cxf.interceptor.<API key>; import org.apache.cxf.interceptor.<API key>; import org.apache.cxf.jaxws.<API key>; import org.junit.After; import org.junit.Before; import org.junit.Test; import javax.xml.namespace.QName; import javax.xml.ws.Service; import java.net.<API key>; import java.net.URL; import java.text.ParseException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class <API key> { /** * WebService */ @Before public void before() { LeaveWebserviceUtil.startServer(); } /** * * @throws ParseException */ @Test public void testTrue() throws ParseException, <API key> { /* // CXF <API key> factory = new <API key>(); factory.getInInterceptors().add(new <API key>()); factory.getOutInterceptors().add(new <API key>()); factory.setServiceClass(LeaveWebService.class); factory.setAddress(LeaveWebserviceUtil.WEBSERVICE_URL); LeaveWebService leaveWebService = (LeaveWebService) factory.create();*/ URL url = new URL(LeaveWebserviceUtil.WEBSERVICE_WSDL_URL); QName qname = new QName(LeaveWebserviceUtil.WEBSERVICE_URI, "LeaveWebService"); Service service = Service.create(url, qname); LeaveWebService leaveWebService = service.getPort(LeaveWebService.class); boolean audit = leaveWebService.generalManagerAudit("2013-01-01 09:00", "2013-01-05 17:30"); assertTrue(audit); } /** * * @throws ParseException */ @Test public void testFalse() throws ParseException { <API key> factory = new <API key>(); factory.getInInterceptors().add(new <API key>()); factory.getOutInterceptors().add(new <API key>()); factory.setServiceClass(LeaveWebService.class); factory.setAddress(LeaveWebserviceUtil.WEBSERVICE_URL); LeaveWebService leaveWebService = (LeaveWebService) factory.create(); boolean audit = leaveWebService.generalManagerAudit("2013-01-01 09:00", "2013-01-04 17:30"); assertFalse(audit); } @After public void after() { LeaveWebserviceUtil.stopServer(); } }
# Yieldmo ## Example html <amp-ad width="300" height="168" type="yieldmo" data-ymid="1349317029731662884"> </amp-ad> ## Configuration For semantics configuration, please [contact Yieldmo](https://yieldmo.com/#contact). Supported parameters: - `data-ymid` ## Multi-size Ad Yieldmo implicitly handles rendering different sized ads that are bid to the same placement. No additional configuration is required for the tag. Above the fold ads do not resize, so as not to not disrupt the user experience: ![](http://test.yieldmo.com.s3.amazonaws.com/amp-demo/big-notResized.gif) ![](http://test.yieldmo.com.s3.amazonaws.com/amp-demo/small-notResized.gif) Below the fold, ads resize: ![](http://test.yieldmo.com.s3.amazonaws.com/amp-demo/big-resized.gif) ![](http://test.yieldmo.com.s3.amazonaws.com/amp-demo/small-resized.gif)
<!DOCTYPE html> <html lang="en"> <head> <title>What is the Drop Box tool?</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta content="sakai.dropbox, main" name="description"> <meta content="student folders" name="search"> <link href="/library/skin/tool_base.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/library/skin/morpheus-default/tool.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/sakai-help-tool/css/help.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/library/js/jquery/featherlight/0.4.0/featherlight.min.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <script src="/library/webjars/jquery/1.11.3/jquery.min.js" type="text/javascript" charset="utf-8"></script><script src="/library/js/jquery/featherlight/0.4.0/featherlight.min.js" type="text/javascript" charset="utf-8"></script><script type="text/javascript" charset="utf-8"> $(document).ready(function(){ $("a[rel^='featherlight']").featherlight({ type: { image:true }, closeOnClick: 'anywhere' }); }); </script> </head> <body> <div id="wrapper"> <div id="article-content"> <div id="article-header"> <h1 class="article-title">What is the Drop Box tool?</h1> </div> <div id="article-description"> <p>The Drop Box tool creates a folder for each student in the course. &nbsp;Students are only able to access their own folder. Students and instructors can both place files in the Drop Box folders. &nbsp;</p> <p>The Drop Box mirrors the file management features and functionality of the Resources tool. See <a href="content.hlp?docId=<API key>">What is the Resources tool?</a> for more information on how to add, upload, edit, and delete files and folders within Drop Box. (As with Resources, multiple files can also be uploaded using <a href="content.hlp?docId=<API key>">Drag and Drop</a>.)</p> </div> <div id="steps-container"> <div id="step-6360" class="step-container"> <h2 class="step-title">To access this tool, select Drop Box from the Tool Menu in your site.</h2> <div class="<API key>"> <img src="/library/image/help/en/<API key>-/<API key>.png" width="146" height="126" class="step-image" alt="To access this tool, select Drop Box from the Tool Menu in your site."> </div> </div> <div class="clear"></div> <div id="step-6361" class="step-container"> <h2 class="step-title">Example: Folders for each student</h2> <div class="<API key> step-image-fullsize"> <img src="/library/image/help/en/<API key>-/<API key>.png" width="640" height="285" class="step-image" alt="Example: Folders for each student"><div class="step-image-caption"> <a href="/library/image/help/en/<API key>-/<API key>.png" rel="featherlight" target="_blank">Zoom</a> </div> </div> <div class="step-instructions"><p>Folders with the plus sign contain files.</p></div> </div> <div class="clear"></div> </div> </div> </div> </body> </html>
//>>built define("dojox/atom/widget/nls/hr/FeedEntryViewer",{displayOptions:"[opcije prikaza]",title:"Naslov",authors:"Autori",contributors:"Doprinositelji",id:"ID",close:"[zatvori]",updated:"A\u017eurirano",summary:"Sa\u017eetak",content:"Sadr\u017eaj"});
<!DOCTYPE html> <html lang="en"> <head> <title>How do I delete an alias?</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta content="sakai.aliases" name="description"> <meta content="" name="search"> <link href="/library/skin/tool_base.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/library/skin/morpheus-default/tool.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/sakai-help-tool/css/help.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/library/js/jquery/featherlight/0.4.0/featherlight.min.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <script src="/library/webjars/jquery/1.11.3/jquery.min.js" type="text/javascript" charset="utf-8"></script><script src="/library/js/jquery/featherlight/0.4.0/featherlight.min.js" type="text/javascript" charset="utf-8"></script><script type="text/javascript" charset="utf-8"> $(document).ready(function(){ $("a[rel^='featherlight']").featherlight({ type: { image:true }, closeOnClick: 'anywhere' }); }); </script> </head> <body> <div id="wrapper"> <div id="article-content"> <div id="article-header"> <h1 class="article-title">How do I delete an alias?</h1> </div> <div id="steps-container"> <div id="step-5445" class="step-container"> <h2 class="step-title">Go to the Aliases tool.</h2> <div class="step-instructions"><p>Select the <strong>Aliases</strong> tool from the Tool Menu in the Administration Workspace.</p></div> </div> <div class="clear"></div> <div id="step-5446" class="step-container"> <h3 class="step-title">Click on the alias you would like delete.</h3> <div class="<API key> step-image-fullsize"> <img src="/library/image/help/en/<API key>-/<API key>.png" width="640" height="469" class="step-image" alt="Click on the alias you would like delete."><div class="step-image-caption"> <a href="/library/image/help/en/<API key>-/<API key>.png" rel="featherlight" target="_blank">Zoom</a> </div> </div> </div> <div class="clear"></div> <div id="step-5447" class="step-container"> <h3 class="step-title">Click Remove Alias.</h3> <div class="<API key>"> <img src="/library/image/help/en/<API key>-/Click-Remove-Alias.png" width="578" height="319" class="step-image" alt="Click Remove Alias."> </div> </div> <div class="clear"></div> <div id="step-5448" class="step-container"> <h3 class="step-title">Confirm alias removal.</h3> <div class="<API key> step-image-fullsize"> <img src="/library/image/help/en/<API key>-/<API key>.png" width="640" height="194" class="step-image" alt="Confirm alias removal."><div class="step-image-caption"> <a href="/library/image/help/en/<API key>-/<API key>.png" rel="featherlight" target="_blank">Zoom</a> </div> </div> <div class="step-instructions"><p>Click <strong>Remove</strong> again when prompted to confirm the deletion of the alias.</p></div> </div> <div class="clear"></div> </div> </div> </div> </body> </html>
package org.keycloak.example.oauth; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.jboss.logging.Logger; import org.keycloak.<API key>; import org.keycloak.adapters.AdapterUtils; import org.keycloak.servlet.ServletOAuthClient; import org.keycloak.util.JsonSerialization; import org.keycloak.util.UriUtils; import javax.enterprise.context.ApplicationScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> * @version $Revision: 1 $ */ @ApplicationScoped @Named("databaseClient") public class DatabaseClient { @Inject @<API key> private HttpServletRequest request; @Inject private HttpServletResponse response; @Inject private FacesContext facesContext; @Inject private ServletOAuthClient oauthClient; @Inject private UserData userData; private static final Logger logger = Logger.getLogger(DatabaseClient.class); public void retrieveAccessToken() { try { oauthClient.redirectRelative("client.jsf", request, response); } catch (IOException e) { throw new RuntimeException(e); } } static class TypedList extends ArrayList<String> {} public void <API key>() { List<String> customers = <API key>(getBaseUrl() + "/database/customers"); userData.setCustomers(customers); } public void sendProductsRequest() { List<String> products = <API key>(getBaseUrl() + "/database/products"); userData.setProducts(products); } protected List<String> <API key>(String dbUri) { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(dbUri); try { if (userData.isHasAccessToken()) { get.addHeader("Authorization", "Bearer " + userData.getAccessToken()); } HttpResponse response = client.execute(get); switch (response.getStatusLine().getStatusCode()) { case 200: HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); try { return JsonSerialization.readValue(is, TypedList.class); } finally { is.close(); } case 401: facesContext.addMessage(null, new FacesMessage("Status: 401. Request not authenticated! You need to retrieve access token first.")); break; case 403: facesContext.addMessage(null, new FacesMessage("Status: 403. Access token has insufficient privileges")); break; default: facesContext.addMessage(null, new FacesMessage("Status: " + response.getStatusLine() + ". Not able to retrieve data. See log for details")); logger.warn("Error occured. Status: " + response.getStatusLine()); } return null; } catch (IOException e) { e.printStackTrace(); facesContext.addMessage(null, new FacesMessage("Unknown error. See log for details")); return null; } } public String getBaseUrl() { <API key> session = (<API key>)request.getAttribute(<API key>.class.getName()); return AdapterUtils.<API key>(request.getRequestURL().toString(), session); } }
# Oblivki ## Example html <amp-ad width="300" height="250" type="oblivki" data-use-a4a="true" data-block-key="<API key>" src="https://oblivki.biz/amp_a4a?key=<API key>" > </amp-ad> ## Configuration For configuration details and to generate your tags, please contact support@oblivki.biz Supported parameters: - `data-block-key`
<?php final class <API key> extends PhortuneController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $accounts = <API key>::loadAccountsForUser( $viewer, <API key>::newFromRequest($request)); if (count($accounts) == 1) { $account = head($accounts); $next_uri = $this->getApplicationURI($account->getID().'/'); } else { $next_uri = $this->getApplicationURI('account/'); } return id(new <API key>())->setURI($next_uri); } }
<?php /** * opSkinClassicPlugin actions. * * @package OpenPNE * @subpackage skin * @author Kousuke Ebihara <ebihara@tejimaya.com> */ class <API key> extends sfActions { public function executeCss(sfWebRequest $request) { opSkinClassicConfig::setCurrentTheme($request->getParameter('theme')); } public function executeLogin(sfWebRequest $request) { if ('@<API key>' !== opConfig::get('<API key>')) { $this->redirect('member/login'); } $this->form = $this->getUser()->getAuthForm(); unset($this->form['next_uri']); } }
using System; using System.Collections.Generic; using System.Threading; using XenAdmin.Network; using XenAPI; namespace XenAdmin.Actions { <summary> ParallelAction takes a list of any number of actions and runs a certain number of them simultaneously. Once one simultaneous action is finished the next one in the queue is started until all are complete </summary> public class ParallelAction : MultipleAction { //Change parameter to increase the number of concurrent actions running private const int <API key> = 25; private Dictionary<IXenConnection, List<AsyncAction>> actionsByConnection = new Dictionary<IXenConnection, List<AsyncAction>>(); private Dictionary<IXenConnection, <API key>> queuesByConnection = new Dictionary<IXenConnection, <API key>>(); private List<AsyncAction> <API key> = new List<AsyncAction>(); private <API key> <API key>; private readonly int <API key>; private int actionsCount; public ParallelAction(IXenConnection connection, string title, string startDescription, string endDescription, List<AsyncAction> subActions, bool suppressHistory, bool <API key>, int <API key> = <API key>) : base(connection, title, startDescription, endDescription, subActions, suppressHistory, <API key>) { if (Connection != null) { actionsByConnection.Add(Connection, subActions); actionsCount = subActions.Count; } else <API key>(); this.<API key> = <API key>; } public ParallelAction(IXenConnection connection, string title, string startDescription, string endDescription, List<AsyncAction> subActions, int <API key> = <API key>) : this(connection, title, startDescription, endDescription, subActions, false, false, <API key>) { } <summary> Use this constructor to create a cross connection ParallelAction. It takes a list of any number of actions, separates them by connections and runs a certain number of them simultaneously on each connection, all connections in parallel. Once one simultaneous action is finished the next one in the queue is started until all are complete. </summary> public ParallelAction(string title, string startDescription, string endDescription, List<AsyncAction> subActions, bool suppressHistory, bool <API key>, int <API key> = <API key>) : base(null, title, startDescription, endDescription, subActions, suppressHistory, <API key>) { <API key>(); this.<API key> = <API key>; } public ParallelAction(string title, string startDescription, string endDescription, List<AsyncAction> subActions, int <API key> = <API key>) : this(title, startDescription, endDescription, subActions, false, false, <API key>) { } private void <API key>() { actionsCount = 0; foreach (AsyncAction action in subActions) { if (action.Connection != null) { if (action.Connection.IsConnected) { if (!actionsByConnection.ContainsKey(action.Connection)) { actionsByConnection.Add(action.Connection, new List<AsyncAction>()); } actionsByConnection[action.Connection].Add(action); actionsCount++; } } else { <API key>.Add(action); actionsCount++; } } } protected override void RunSubActions(List<Exception> exceptions) { if (actionsCount == 0) return; foreach (IXenConnection connection in actionsByConnection.Keys) { queuesByConnection[connection] = new <API key>(Math.Min(<API key>, actionsByConnection[connection].Count)); foreach (AsyncAction subAction in actionsByConnection[connection]) { EnqueueAction(subAction, queuesByConnection[connection], exceptions); } } if (<API key>.Count > 0) <API key> = new <API key>(Math.Min(<API key>, <API key>.Count)); foreach (AsyncAction subAction in <API key>) { EnqueueAction(subAction, <API key>, exceptions); } lock (_lock) { Monitor.Wait(_lock); } } void EnqueueAction(AsyncAction action, <API key> queue, List<Exception> exceptions) { action.Completed += action_Completed; queue.EnqueueItem( () => { if (Cancelling) // don't start any more actions return; try { action.RunExternal(action.Session); } catch (Exception e) { Failure f = e as Failure; if (f != null && Connection != null && f.ErrorDescription[0] == Failure.<API key>) { Failure.ParseRBACFailure(f, action.Connection, action.Session ?? action.Connection.Session); } exceptions.Add(e); // Record the first exception we come to. Though later if there are more than one we will replace this with non specific one. if (Exception == null) Exception = e; } }); } protected override void <API key>() { int total = 0; foreach (IXenConnection connection in actionsByConnection.Keys) { foreach (var action in actionsByConnection[connection]) total += action.PercentComplete; } foreach (var action in <API key>) total += action.PercentComplete; PercentComplete = (int)(total / actionsCount); } private readonly object _lock = new object(); private volatile int i = 0; void action_Completed(ActionBase sender) { sender.Completed -= action_Completed; lock (_lock) { i++; if (i == actionsCount) { Monitor.Pulse(_lock); PercentComplete = 100; } } } protected override void <API key>(ActionBase sender) { base.<API key>(sender); foreach (IXenConnection connection in queuesByConnection.Keys) { queuesByConnection[connection].StopWorkers(false); } if (<API key> != null) <API key>.StopWorkers(false); } } }
cask 'malwarebytes' do version '3.0.3.433' sha256 '<SHA256-like>' # data-cdn.mbamupdates.com/web was verified as official when first introduced to the cask url "https://data-cdn.mbamupdates.com/web/mb#{version.major}_mac/Malwarebytes-#{version}.dmg" name 'Malwarebytes for Mac' homepage 'https: auto_updates true depends_on macos: '>= :yosemite' pkg "Install Malwarebytes #{version.major}.pkg" uninstall delete: '/Library/Application Support/Malwarebytes/MBAM', kext: 'com.malwarebytes.mbam.rtprotection', launchctl: [ 'com.malwarebytes.mbam.frontend.agent', 'com.malwarebytes.mbam.rtprotection.daemon', 'com.malwarebytes.mbam.settings.daemon', ], pkgutil: 'com.malwarebytes.mbam', quit: 'com.malwarebytes.mbam.frontend.agent', rmdir: '/Library/Application Support/Malwarebytes' end
#ifndef PLANNER_H #define PLANNER_H #include "nodes/plannodes.h" #include "nodes/relation.h" /* Hook for plugins to get control in planner() */ typedef PlannedStmt *(*planner_hook_type) (Query *parse, int cursorOptions, ParamListInfo boundParams); extern PGDLLIMPORT planner_hook_type planner_hook; extern PlannedStmt *planner(Query *parse, int cursorOptions, ParamListInfo boundParams); extern PlannedStmt *standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams); extern Plan *subquery_planner(PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction, PlannerInfo **subroot); extern Expr *expression_planner(Expr *expr); extern bool <API key>(Oid tableOid, Oid indexOid); #endif /* PLANNER_H */
/** * Asserts that device property values match properties in |expectedProperties|. * The method will *not* assert that the device contains *only* properties * specified in expected properties. * @param {Object} expectedProperties Expected device properties. * @param {Object} device Device object to test. */ function assertDeviceMatches(expectedProperties, device) { Object.keys(expectedProperties).forEach(function(key) { chrome.test.assertEq(expectedProperties[key], device[key], 'Property ' + key + ' of device ' + device.id); }); } /** * Verifies that list of devices contains all and only devices from set of * expected devices. If will fail the test if an unexpected device is found. * * @param {Object.<string, Object>} expectedDevices Expected set of test * devices. Maps device ID to device properties. * @param {Array.<Object>} devices List of input devices. */ function assertDevicesMatch(expectedDevices, devices) { var deviceIds = {}; devices.forEach(function(device) { chrome.test.assertFalse(!!deviceIds[device.id], 'Duplicated device id: \'' + device.id + '\'.'); deviceIds[device.id] = true; }); function sortedKeys(obj) { return Object.keys(obj).sort(); } chrome.test.assertEq(sortedKeys(expectedDevices), sortedKeys(deviceIds)); devices.forEach(function(device) { assertDeviceMatches(expectedDevices[device.id], device); }); } /** * * @param {Array.<Object>} devices List of devices returned by * chrome.audio.getInfo or chrome.audio.getDevices. * @return {Object.<string, Object>} List of devices formatted as map of * expected devices used to assert devices match expectation. */ function <API key>(devices) { var expectedDevicesMap = {}; devices.forEach(function(device) { expectedDevicesMap[device.id] = device; }); return expectedDevicesMap; } /** * @param {Array.<Object>} devices List of devices returned by * chrome.audio.getInfo or chrome.audio.getDevices. * @return {Array.<string>} Sorted list devices IDs for devices in |devices|. */ function getDeviceIds(devices) { return devices.map(function(device) {return device.id;}).sort(); } function EventListener(targetEvent) { this.targetEvent = targetEvent; this.listener = this.handleEvent.bind(this); this.targetEvent.addListener(this.listener); this.eventCount = 0; } EventListener.prototype.handleEvent = function() { ++this.eventCount; } EventListener.prototype.reset = function() { this.targetEvent.removeListener(this.listener); } var <API key> = null; chrome.test.runTests([ // Sets up a listener for audio.onDeviceChanged event - // |<API key>| test will later verify that no // onDeviceChanged events have been observed. function <API key>() { <API key> = new EventListener(chrome.audio.onDeviceChanged); chrome.test.succeed(); }, function getDevicesTest() { // Test output devices. Maps device ID -> tested device properties. var kTestDevices = { '30001': { id: '30001', stableDeviceId: '0', displayName: 'Jabra Speaker 1', deviceName: 'Jabra Speaker', streamType: 'OUTPUT' }, '30002': { id: '30002', stableDeviceId: '1', displayName: 'Jabra Speaker 2', deviceName: 'Jabra Speaker', streamType: 'OUTPUT' }, '30003': { id: '30003', stableDeviceId: '2', displayName: 'HDA Intel MID', deviceName: 'HDMI output', streamType: 'OUTPUT' }, '40001': { id: '40001', stableDeviceId: '3', displayName: 'Jabra Mic 1', deviceName: 'Jabra Mic', streamType: 'INPUT' }, '40002': { id: '40002', stableDeviceId: '4', displayName: 'Jabra Mic 2', deviceName: 'Jabra Mic', streamType: 'INPUT' }, '40003': { id: '40003', stableDeviceId: '5', displayName: 'Logitech Webcam', deviceName: 'Webcam Mic', streamType: 'INPUT' } }; chrome.audio.getDevices(chrome.test.callbackPass(function(devices) { assertDevicesMatch(kTestDevices, devices); })); }, function <API key>() { // Test output devices. Maps device ID -> tested device properties. var kTestDevices = { '30001': { id: '30001', stableDeviceId: '0', displayName: 'Jabra Speaker 1', deviceName: 'Jabra Speaker', streamType: 'OUTPUT' }, '30002': { id: '30002', stableDeviceId: '1', displayName: 'Jabra Speaker 2', deviceName: 'Jabra Speaker', streamType: 'OUTPUT' }, '30003': { id: '30003', stableDeviceId: '2', displayName: 'HDA Intel MID', deviceName: 'HDMI output', streamType: 'OUTPUT' }, '40001': { id: '40001', stableDeviceId: '3', displayName: 'Jabra Mic 1', deviceName: 'Jabra Mic', streamType: 'INPUT' }, '40002': { id: '40002', stableDeviceId: '4', displayName: 'Jabra Mic 2', deviceName: 'Jabra Mic', streamType: 'INPUT' }, '40003': { id: '40003', stableDeviceId: '5', displayName: 'Logitech Webcam', deviceName: 'Webcam Mic', streamType: 'INPUT' } }; chrome.audio.getDevices({}, chrome.test.callbackPass(function(devices) { assertDevicesMatch(kTestDevices, devices); })); }, function getInputDevicesTest() { var kTestDevices = { '40001': { id: '40001', streamType: 'INPUT' }, '40002': { id: '40002', streamType: 'INPUT' }, '40003': { id: '40003', streamType: 'INPUT' } }; chrome.audio.getDevices({ streamTypes: ['INPUT'] }, chrome.test.callbackPass(function(devices) { assertDevicesMatch(kTestDevices, devices); })); }, function <API key>() { var kTestDevices = { '30001': { id: '30001', streamType: 'OUTPUT' }, '30002': { id: '30002', streamType: 'OUTPUT' }, '30003': { id: '30003', streamType: 'OUTPUT' }, }; chrome.audio.getDevices({ streamTypes: ['OUTPUT'] }, chrome.test.callbackPass(function(devices) { assertDevicesMatch(kTestDevices, devices); })); }, function <API key>() { chrome.audio.getDevices(chrome.test.callbackPass(function(initial) { var <API key> = initial.filter(function(device) { return device.isActive; }); chrome.test.assertTrue(<API key>.length > 0); chrome.audio.getDevices({ isActive: true }, chrome.test.callbackPass(function(devices) { assertDevicesMatch( <API key>(<API key>), devices); })); var initialActiveInputs = <API key>.filter(function(device) { return device.streamType === 'INPUT'; }); chrome.test.assertTrue(initialActiveInputs.length > 0); chrome.audio.getDevices({ isActive: true, streamTypes: ['INPUT'] }, chrome.test.callbackPass(function(devices) { assertDevicesMatch( <API key>(initialActiveInputs), devices); })); var <API key> = <API key>.filter(function(device) { return device.streamType === 'OUTPUT'; }); chrome.test.assertTrue(<API key>.length > 0); chrome.audio.getDevices({ isActive: true, streamTypes: ['OUTPUT'] }, chrome.test.callbackPass(function(devices) { assertDevicesMatch( <API key>(<API key>), devices); })); })); }, function <API key>() { chrome.audio.getDevices(chrome.test.callbackPass(function(initial) { var <API key> = initial.filter(function(device) { return !device.isActive; }); chrome.test.assertTrue(<API key>.length > 0); chrome.audio.getDevices({ isActive: false }, chrome.test.callbackPass(function(devices) { assertDevicesMatch( <API key>(<API key>), devices); })); })); }, function setPropertiesTest() { chrome.audio.getDevices(chrome.test.callbackPass(function(initial) { var expectedDevices = <API key>(initial); // Update expected input devices with values that should be changed in // test. var updatedInput = expectedDevices['40002']; chrome.test.assertFalse(updatedInput.gain === 65); updatedInput.level = 65; // Update expected output devices with values that should be changed in // test. var updatedOutput = expectedDevices['30001']; chrome.test.assertFalse(updatedOutput.volume === 45); updatedOutput.level = 45; chrome.audio.setProperties('30001', { level: 45 }, chrome.test.callbackPass(function() { chrome.audio.setProperties('40002', { level: 65 }, chrome.test.callbackPass(function() { chrome.audio.getDevices(chrome.test.callbackPass(function(devices) { assertDevicesMatch(expectedDevices, devices); })); })); })); })); }, function inputMuteTest() { var getMute = function(callback) { chrome.audio.getMute('INPUT', chrome.test.callbackPass(callback)); }; getMute(function(originalValue) { chrome.audio.setMute( 'INPUT', !originalValue, chrome.test.callbackPass(function() { getMute(function(value) { chrome.test.assertEq(!originalValue, value); }); })); }); }, function outputMuteTest() { var getMute = function(callback) { chrome.audio.getMute('OUTPUT', chrome.test.callbackPass(callback)); }; getMute(function(originalValue) { chrome.audio.setMute( 'OUTPUT', !originalValue, chrome.test.callbackPass(function() { getMute(function(value) { chrome.test.assertEq(!originalValue, value); }); })); }); }, function <API key>() { chrome.audio.setActiveDevices({ input: ['40002', '40003'], output: ['30001'] }, chrome.test.callbackPass(function() { chrome.audio.getDevices({ isActive: true }, chrome.test.callbackPass(function(activeDevices) { chrome.test.assertEq(['30001', '40002', '40003'], getDeviceIds(activeDevices)); })); })); }, function <API key>() { chrome.audio.getDevices({ streamTypes: ['INPUT'], isActive: true }, chrome.test.callbackPass(function(initial) { var initialActiveInputs = getDeviceIds(initial); chrome.test.assertTrue(initialActiveInputs.length > 0); chrome.audio.setActiveDevices({ output: ['30003'] }, chrome.test.callbackPass(function() { chrome.audio.getDevices({ isActive: true }, chrome.test.callbackPass(function(devices) { var expected = ['30003'].concat(initialActiveInputs).sort(); chrome.test.assertEq(expected, getDeviceIds(devices)); })); })); })); }, function <API key>() { chrome.audio.getDevices({ isActive: true }, chrome.test.callbackPass(function(initial) { var initialActiveIds = getDeviceIds(initial); chrome.test.assertTrue(initialActiveIds.length > 0); chrome.audio.setActiveDevices({ input: ['0000000'], /* does not exist */ output: [] }, chrome.test.callbackFail('Failed to set active devices.', function() { chrome.audio.getDevices({ isActive: true }, chrome.test.callbackPass(function(devices) { chrome.test.assertEq(initialActiveIds, getDeviceIds(devices)); })); })); })); }, function <API key>() { chrome.audio.getDevices({ isActive: true }, chrome.test.callbackPass(function(initial) { var initialActiveIds = getDeviceIds(initial); chrome.test.assertTrue(initialActiveIds.length > 0); chrome.audio.setActiveDevices({ input: [], output: ['40001'] /* id is input node ID */ }, chrome.test.callbackFail('Failed to set active devices.', function() { chrome.audio.getDevices({ isActive: true }, chrome.test.callbackPass(function(devices) { chrome.test.assertEq(initialActiveIds, getDeviceIds(devices)); })); })); })); }, function <API key>() { chrome.audio.getDevices({ isActive: true }, chrome.test.callbackPass(function(initial) { chrome.test.assertTrue(getDeviceIds(initial).length > 0); chrome.audio.setActiveDevices({ input: [], output: [] }, chrome.test.callbackPass(function() { chrome.audio.getDevices({ isActive: true }, chrome.test.callbackPass(function(devices) { chrome.test.assertEq([], devices); })); })); })); }, function <API key>() { chrome.test.assertTrue(!!<API key>); chrome.test.assertEq(0, <API key>.eventCount); <API key>.reset(); <API key> = null; chrome.test.succeed(); }, // Tests verifying the app doesn't have access to deprecated part of the API: function <API key>() { chrome.audio.getInfo(chrome.test.callbackFail( 'audio.getInfo is deprecated, use audio.getDevices instead.')); }, function <API key>() { chrome.audio.getDevices(chrome.test.callbackPass(function(initial) { var expectedDevices = <API key>(initial); var expectedError = '|isMuted| property is deprecated, use |audio.setMute|.'; chrome.audio.setProperties('30001', { isMuted: true, // Output device - should have volume set. level: 55 }, chrome.test.callbackFail(expectedError, function() { // Assert that device properties haven't changed. chrome.audio.getDevices(chrome.test.callbackPass(function(devices) { assertDevicesMatch(expectedDevices, devices); })); })); })); }, function <API key>() { chrome.audio.getDevices(chrome.test.callbackPass(function(initial) { var expectedDevices = <API key>(initial); var expectedError = '|volume| property is deprecated, use |level|.'; chrome.audio.setProperties('30001', { volume: 2, // Output device - should have volume set. level: 55 }, chrome.test.callbackFail(expectedError, function() { // Assert that device properties haven't changed. chrome.audio.getDevices(chrome.test.callbackPass(function(devices) { assertDevicesMatch(expectedDevices, devices); })); })); })); }, function <API key>() { chrome.audio.getDevices(chrome.test.callbackPass(function(initial) { var expectedDevices = <API key>(initial); var expectedError = '|gain| property is deprecated, use |level|.'; chrome.audio.setProperties('40001', { gain: 2, // Output device - should have volume set. level: 55 }, chrome.test.callbackFail(expectedError, function() { // Assert that device properties haven't changed. chrome.audio.getDevices(chrome.test.callbackPass(function(devices) { assertDevicesMatch(expectedDevices, devices); })); })); })); }, function <API key>() { var kExpectedError = 'String list |ids| is deprecated, use DeviceIdLists type.'; chrome.audio.setActiveDevices([ '30003', '40002' ], chrome.test.callbackFail(kExpectedError)); }, ]);
// This macro reads the Hits Tree void AliPMDHitsRead(Int_t nevt = 1) { TStopwatch timer; timer.Start(); TH2F *h2 = new TH2F("h2"," Y vs. X",200,-100.,100.,200,-100.,100.); // FILE *fpw = fopen("alipmdhits.dat","w"); AliRunLoader *fRunLoader = AliRunLoader::Open("galice.root"); if (!fRunLoader) { printf("Can not open session for file "); } if (!fRunLoader->GetAliRun()) fRunLoader->LoadgAlice(); if (!fRunLoader->TreeE()) fRunLoader->LoadHeader(); if (!fRunLoader->TreeK()) fRunLoader->LoadKinematics(); gAlice = fRunLoader->GetAliRun(); if (gAlice) { printf("Alirun object found\n"); } else { printf("Could not found Alirun object\n"); } fPMD = (AliPMD*)gAlice->GetDetector("PMD"); fPMDLoader = fRunLoader->GetLoader("PMDLoader"); if (fPMDLoader == 0x0) { printf("Can not find PMDLoader\n"); } fPMDLoader->LoadHits("READ"); // This reads the PMD Hits tree and assigns the right track number // to a cell and stores in the summable digits tree const Int_t kPi0 = 111; const Int_t kGamma = 22; Int_t npmd; Int_t trackno; Int_t smnumber; Int_t trackpid; Int_t mtrackno; Int_t mtrackpid; Int_t xpad = -1, ypad = -1; Float_t edep; Float_t vx = -999.0, vy = -999.0, vz = -999.0; Float_t xPos, yPos, zPos; Float_t xx, yy; AliPMDUtility cc; for (Int_t ievt = 0; ievt < nevt; ievt++) { printf("Event Number = %d\n",ievt); Int_t nparticles = fRunLoader->GetHeader()->GetNtrack(); printf("Number of Particles = %d\n",nparticles); fRunLoader->GetEvent(ievt); // Pointer to specific detector hits. // Get pointers to Alice detectors and Hits containers TTree* treeH = fPMDLoader->TreeH(); Int_t ntracks = (Int_t) treeH->GetEntries(); printf("Number of Tracks in the TreeH = %d\n", ntracks); TClonesArray* hits = 0; if (fPMD) hits = fPMD->Hits(); // Start loop on tracks in the hits containers for (Int_t track=0; track<ntracks;track++) { gAlice->GetMCApp()->ResetHits(); treeH->GetEvent(track); if (fPMD) { npmd = hits->GetEntriesFast(); for (int ipmd = 0; ipmd < npmd; ipmd++) { fPMDHit = (AliPMDhit*) hits->UncheckedAt(ipmd); trackno = fPMDHit->GetTrack(); //fprintf(fpw,"trackno = %d\n",trackno); // get kinematics of the particles TParticle* mparticle = gAlice->GetMCApp()->Particle(trackno); trackpid = mparticle->GetPdgCode(); Int_t igatr = -999; Int_t ichtr = -999; Int_t igapid = -999; Int_t imo; Int_t igen = 0; Int_t idmo = -999; Int_t tracknoOld=0, trackpidOld=0, statusOld = 0; if (mparticle->GetFirstMother() == -1) { tracknoOld = trackno; trackpidOld = trackpid; statusOld = -1; vx = mparticle->Vx(); vy = mparticle->Vy(); vz = mparticle->Vz(); //fprintf(fpw,"==> Mother ID %5d %5d %5d Vertex: %13.3f %13.3f %13.3f\n", igen, -1, trackpid, vx, vy, vz); } Int_t igstatus = 0; while((imo = mparticle->GetFirstMother()) >= 0) { igen++; mparticle = gAlice->GetMCApp()->Particle(imo); idmo = mparticle->GetPdgCode(); vx = mparticle->Vx(); vy = mparticle->Vy(); vz = mparticle->Vz(); //printf("==> Mother ID %5d %5d %5d Vertex: %13.3f %13.3f %13.3f\n", igen, imo, idmo, vx, vy, vz); //fprintf(fpw,"==> Mother ID %5d %5d %5d Vertex: %13.3f %13.3f %13.3f\n", igen, imo, idmo, vx, vy, vz); if ((idmo == kGamma || idmo == -11 || idmo == 11) && vx == 0. && vy == 0. && vz == 0.) { igatr = imo; igapid = idmo; igstatus = 1; } if(igstatus == 0) { if (idmo == kPi0 && vx == 0. && vy == 0. && vz == 0.) { igatr = imo; igapid = idmo; } } ichtr = imo; } // end of while loop if (idmo == kPi0 && vx == 0. && vy == 0. && vz == 0.) { mtrackno = igatr; mtrackpid = igapid; } else { mtrackno = ichtr; mtrackpid = idmo; } if (statusOld == -1) { mtrackno = tracknoOld; mtrackpid = trackpidOld; } //printf("mtrackno = %d mtrackpid = %d\n",mtrackno,mtrackpid); xPos = fPMDHit->X(); yPos = fPMDHit->Y(); zPos = fPMDHit->Z(); Float_t time = fPMDHit->GetTime(); printf("++++++++++ time = %f\n",time); edep = fPMDHit->GetEnergy(); Int_t vol1 = fPMDHit->GetVolume(1); // Column Int_t vol2 = fPMDHit->GetVolume(2); // Row Int_t vol3 = fPMDHit->GetVolume(4); // UnitModule // For Super Module 1 & 2 // // nrow = 96, ncol = 48 // // For Super Module 3 & 4 // // nrow = 48, ncol = 96 // if (vol3 < 24) { smnumber = vol3; } else { smnumber = vol3 - 24; } xpad = vol1; ypad = vol2; if(zPos > 361.5) { cc.RectGeomCellPos(smnumber,xpad,ypad,xx,yy); h2->Fill(xx,yy); } } } } // Track Loop ended } h2->Draw(); fRunLoader->UnloadgAlice(); fRunLoader->UnloadHeader(); fRunLoader->UnloadKinematics(); fPMDLoader->UnloadHits(); timer.Stop(); timer.Print(); }
#!/usr/bin/env python """Valid certificate chain where the target certificate contains a public key with a 512-bit modulus (weak).""" import sys sys.path += ['../..'] import gencerts # Self-signed root certificate. root = gencerts.<API key>('Root') # Intermediate intermediate = gencerts.<API key>('Intermediate', root) # Target certificate. target = gencerts.<API key>('Target', intermediate) target.set_key(gencerts.<API key>( 512, gencerts.create_key_path(target.name))) chain = [target, intermediate, root] gencerts.write_chain(__doc__, chain, 'chain.pem')
#include "content/public/browser/<API key>.h" #include "content/browser/renderer_host/<API key>.h" namespace content { <API key>::<API key>() { <API key>::<API key>(this); } <API key>::~<API key>() { <API key>::<API key>(this); } } // namespace content
#include "ui/views/widget/desktop_aura/<API key>.h" #include <algorithm> #include <vector> #include <X11/extensions/shape.h> #include <X11/Xlib.h> #include <X11/Xregion.h> // Get rid of X11 macros which conflict with gtest. #undef Bool #undef None #include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "third_party/skia/include/core/SkRect.h" #include "third_party/skia/include/core/SkRegion.h" #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_paths.h" #include "ui/events/platform/x11/x11_event_source.h" #include "ui/gfx/path.h" #include "ui/gfx/path_x11.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gl/test/<API key>.h" #include "ui/views/test/views_test_base.h" #include "ui/views/test/<API key>.h" #include "ui/views/widget/desktop_aura/<API key>.h" #include "ui/views/widget/desktop_aura/x11_desktop_handler.h" #include "ui/views/widget/widget.h" namespace views { namespace { // Waits till |window| is minimized. class MinimizeWaiter : public <API key> { public: explicit MinimizeWaiter(XID window) : <API key>(window, "_NET_WM_STATE") { const char* kAtomsToCache[] = { "<API key>", NULL }; atom_cache_.reset(new ui::X11AtomCache(gfx::GetXDisplay(), kAtomsToCache)); } ~MinimizeWaiter() override {} private: // <API key>: bool ShouldKeepOnWaiting(const ui::PlatformEvent& event) override { std::vector<Atom> wm_states; if (ui::<API key>(xwindow(), "_NET_WM_STATE", &wm_states)) { std::vector<Atom>::iterator it = std::find( wm_states.begin(), wm_states.end(), atom_cache_->GetAtom("<API key>")); return it == wm_states.end(); } return true; } scoped_ptr<ui::X11AtomCache> atom_cache_; <API key>(MinimizeWaiter); }; // Waits till |<API key>| is updated to include // |expected_windows|. class <API key> : public <API key> { public: <API key>(XID* expected_windows, size_t count) : <API key>(ui::GetX11RootWindow(), "<API key>"), expected_windows_(expected_windows, expected_windows + count) { } ~<API key>() override {} // <API key>: void Wait() override { // <API key> may be created after // <API key> already contains |expected_windows|. if (!ShouldKeepOnWaiting(NULL)) return; <API key>::Wait(); } private: // <API key>: bool ShouldKeepOnWaiting(const ui::PlatformEvent& event) override { std::vector<XID> stack; ui::GetXWindowStack(ui::GetX11RootWindow(), &stack); for (size_t i = 0; i < expected_windows_.size(); ++i) { std::vector<XID>::iterator it = std::find( stack.begin(), stack.end(), expected_windows_[i]); if (it == stack.end()) return true; } return false; } std::vector<XID> expected_windows_; <API key>(<API key>); }; } // namespace class <API key> : public ViewsTestBase { public: <API key>() { } ~<API key>() override {} // Creates and shows a Widget with |bounds|. The caller takes ownership of // the returned widget. scoped_ptr<Widget> CreateAndShowWidget(const gfx::Rect& bounds) { scoped_ptr<Widget> toplevel(new Widget); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::<API key>; params.native_widget = new <API key>(toplevel.get()); params.bounds = bounds; params.<API key> = true; toplevel->Init(params); toplevel->Show(); return toplevel.Pass(); } // Creates and shows an X window with |bounds|. XID <API key>(const gfx::Rect& bounds) { XID root = DefaultRootWindow(xdisplay()); XID xid = XCreateSimpleWindow(xdisplay(), root, 0, 0, 1, 1, 0, // border_width 0, // border 0); // background ui::SetUseOSWindowFrame(xid, false); <API key>(xid, bounds); return xid; } // Shows |xid| and sets its bounds. void <API key>(XID xid, const gfx::Rect& bounds) { XMapWindow(xdisplay(), xid); XWindowChanges changes = {0}; changes.x = bounds.x(); changes.y = bounds.y(); changes.width = bounds.width(); changes.height = bounds.height(); XConfigureWindow(xdisplay(), xid, CWX | CWY | CWWidth | CWHeight, &changes); } Display* xdisplay() { return gfx::GetXDisplay(); } // Returns the topmost X window at the passed in screen position. XID <API key>(int screen_x, int screen_y) { <API key> finder; return finder.FindWindowAt(gfx::Point(screen_x, screen_y)); } // Returns the topmost aura::Window at the passed in screen position. Returns // NULL if the topmost window does not have an associated aura::Window. aura::Window* <API key>(int screen_x, int screen_y) { <API key> finder; return finder.<API key>(gfx::Point(screen_x, screen_y), std::set<aura::Window*>()); } // Returns the topmost aura::Window at the passed in screen position ignoring // |ignore_window|. Returns NULL if the topmost window does not have an // associated aura::Window. aura::Window* <API key>( int screen_x, int screen_y, aura::Window* ignore_window) { std::set<aura::Window*> ignore; ignore.insert(ignore_window); <API key> finder; return finder.<API key>(gfx::Point(screen_x, screen_y), ignore); } static void SetUpTestCase() { gfx::<API key>::InitializeOneOff(); ui::<API key>(); base::FilePath ui_test_pak_path; ASSERT_TRUE(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path)); ui::ResourceBundle::<API key>(ui_test_pak_path); } // ViewsTestBase: void SetUp() override { ViewsTestBase::SetUp(); // Make X11 synchronous for our display connection. This does not force the // window manager to behave synchronously. XSynchronize(xdisplay(), True); // Ensure that the X11DesktopHandler exists. The X11DesktopHandler is // necessary to properly track menu windows. X11DesktopHandler::get(); } void TearDown() override { XSynchronize(xdisplay(), False); ViewsTestBase::TearDown(); } private: <API key>(<API key>); }; TEST_F(<API key>, Basic) { // Avoid positioning test windows at 0x0 because window managers often have a // panel/launcher along one of the screen edges and do not allow windows to // position themselves to overlap the panel/launcher. scoped_ptr<Widget> widget1( CreateAndShowWidget(gfx::Rect(100, 100, 200, 100))); aura::Window* window1 = widget1->GetNativeWindow(); XID xid1 = window1->GetHost()-><API key>(); XID xid2 = <API key>(gfx::Rect(200, 100, 100, 200)); scoped_ptr<Widget> widget3( CreateAndShowWidget(gfx::Rect(100, 190, 200, 110))); aura::Window* window3 = widget3->GetNativeWindow(); XID xid3 = window3->GetHost()-><API key>(); XID xids[] = { xid1, xid2, xid3 }; <API key> waiter(xids, arraysize(xids)); waiter.Wait(); ui::X11EventSource::GetInstance()->DispatchXEvents(); EXPECT_EQ(xid1, <API key>(150, 150)); EXPECT_EQ(window1, <API key>(150, 150)); EXPECT_EQ(xid2, <API key>(250, 150)); EXPECT_EQ(NULL, <API key>(250, 150)); EXPECT_EQ(xid3, <API key>(250, 250)); EXPECT_EQ(window3, <API key>(250, 250)); EXPECT_EQ(xid3, <API key>(150, 250)); EXPECT_EQ(window3, <API key>(150, 250)); EXPECT_EQ(xid3, <API key>(150, 195)); EXPECT_EQ(window3, <API key>(150, 195)); EXPECT_NE(xid1, <API key>(1000, 1000)); EXPECT_NE(xid2, <API key>(1000, 1000)); EXPECT_NE(xid3, <API key>(1000, 1000)); EXPECT_EQ(NULL, <API key>(1000, 1000)); EXPECT_EQ(window1, <API key>(150, 150, window3)); EXPECT_EQ(NULL, <API key>(250, 250, window3)); EXPECT_EQ(NULL, <API key>(150, 250, window3)); EXPECT_EQ(window1, <API key>(150, 195, window3)); XDestroyWindow(xdisplay(), xid2); } // Test that the minimized state is properly handled. TEST_F(<API key>, Minimized) { scoped_ptr<Widget> widget1( CreateAndShowWidget(gfx::Rect(100, 100, 100, 100))); aura::Window* window1 = widget1->GetNativeWindow(); XID xid1 = window1->GetHost()-><API key>(); XID xid2 = <API key>(gfx::Rect(300, 100, 100, 100)); XID xids[] = { xid1, xid2 }; <API key> stack_waiter(xids, arraysize(xids)); stack_waiter.Wait(); ui::X11EventSource::GetInstance()->DispatchXEvents(); EXPECT_EQ(xid1, <API key>(150, 150)); { MinimizeWaiter minimize_waiter(xid1); XIconifyWindow(xdisplay(), xid1, 0); minimize_waiter.Wait(); } EXPECT_NE(xid1, <API key>(150, 150)); EXPECT_NE(xid2, <API key>(150, 150)); // Repeat test for an X window which does not belong to a views::Widget // because the code path is different. EXPECT_EQ(xid2, <API key>(350, 150)); { MinimizeWaiter minimize_waiter(xid2); XIconifyWindow(xdisplay(), xid2, 0); minimize_waiter.Wait(); } EXPECT_NE(xid1, <API key>(350, 150)); EXPECT_NE(xid2, <API key>(350, 150)); XDestroyWindow(xdisplay(), xid2); } // Test that non-rectangular windows are properly handled. TEST_F(<API key>, NonRectangular) { if (!ui::<API key>()) return; scoped_ptr<Widget> widget1( CreateAndShowWidget(gfx::Rect(100, 100, 100, 100))); XID xid1 = widget1->GetNativeWindow()->GetHost()-><API key>(); SkRegion* skregion1 = new SkRegion; skregion1->op(SkIRect::MakeXYWH(0, 10, 10, 90), SkRegion::kUnion_Op); skregion1->op(SkIRect::MakeXYWH(10, 0, 90, 100), SkRegion::kUnion_Op); // Widget takes ownership of |skregion1|. widget1->SetShape(skregion1); SkRegion skregion2; skregion2.op(SkIRect::MakeXYWH(0, 10, 10, 90), SkRegion::kUnion_Op); skregion2.op(SkIRect::MakeXYWH(10, 0, 90, 100), SkRegion::kUnion_Op); XID xid2 = <API key>(gfx::Rect(300, 100, 100, 100)); gfx::XScopedPtr<REGION, gfx::XObjectDeleter<REGION, int, XDestroyRegion>> region2(gfx::<API key>(skregion2)); XShapeCombineRegion(xdisplay(), xid2, ShapeBounding, 0, 0, region2.get(), false); XID xids[] = { xid1, xid2 }; <API key> stack_waiter(xids, arraysize(xids)); stack_waiter.Wait(); ui::X11EventSource::GetInstance()->DispatchXEvents(); EXPECT_EQ(xid1, <API key>(105, 120)); EXPECT_NE(xid1, <API key>(105, 105)); EXPECT_NE(xid2, <API key>(105, 105)); // Repeat test for an X window which does not belong to a views::Widget // because the code path is different. EXPECT_EQ(xid2, <API key>(305, 120)); EXPECT_NE(xid1, <API key>(305, 105)); EXPECT_NE(xid2, <API key>(305, 105)); XDestroyWindow(xdisplay(), xid2); } // Test that a window with an empty shape are properly handled. TEST_F(<API key>, <API key>) { if (!ui::<API key>()) return; scoped_ptr<Widget> widget1( CreateAndShowWidget(gfx::Rect(100, 100, 100, 100))); XID xid1 = widget1->GetNativeWindow()->GetHost()-><API key>(); SkRegion* skregion1 = new SkRegion; skregion1->op(SkIRect::MakeXYWH(0, 0, 0, 0), SkRegion::kUnion_Op); // Widget takes ownership of |skregion1|. widget1->SetShape(skregion1); XID xids[] = { xid1 }; <API key> stack_waiter(xids, arraysize(xids)); stack_waiter.Wait(); ui::X11EventSource::GetInstance()->DispatchXEvents(); EXPECT_NE(xid1, <API key>(105, 105)); } // Test that setting a Null shape removes the shape. TEST_F(<API key>, <API key>) { if (!ui::<API key>()) return; scoped_ptr<Widget> widget1( CreateAndShowWidget(gfx::Rect(100, 100, 100, 100))); XID xid1 = widget1->GetNativeWindow()->GetHost()-><API key>(); SkRegion* skregion1 = new SkRegion; skregion1->op(SkIRect::MakeXYWH(0, 0, 0, 0), SkRegion::kUnion_Op); // Widget takes ownership of |skregion1|. widget1->SetShape(skregion1); // Remove the shape - this is now just a normal window. widget1->SetShape(NULL); XID xids[] = { xid1 }; <API key> stack_waiter(xids, arraysize(xids)); stack_waiter.Wait(); ui::X11EventSource::GetInstance()->DispatchXEvents(); EXPECT_EQ(xid1, <API key>(105, 105)); } // Test that the TopmostWindowFinder finds windows which belong to menus // (which may or may not belong to Chrome). TEST_F(<API key>, Menu) { XID xid = <API key>(gfx::Rect(100, 100, 100, 100)); XID root = DefaultRootWindow(xdisplay()); <API key> swa; swa.override_redirect = True; XID menu_xid = XCreateWindow(xdisplay(), root, 0, 0, 1, 1, 0, // border width CopyFromParent, // depth InputOutput, CopyFromParent, // visual CWOverrideRedirect, &swa); { const char* kAtomsToCache[] = { "<API key>", NULL }; ui::X11AtomCache atom_cache(gfx::GetXDisplay(), kAtomsToCache); ui::SetAtomProperty(menu_xid, "_NET_WM_WINDOW_TYPE", "ATOM", atom_cache.GetAtom("<API key>")); } ui::SetUseOSWindowFrame(menu_xid, false); <API key>(menu_xid, gfx::Rect(140, 110, 100, 100)); ui::X11EventSource::GetInstance()->DispatchXEvents(); // |menu_xid| is never added to <API key>. XID xids[] = { xid }; <API key> stack_waiter(xids, arraysize(xids)); stack_waiter.Wait(); EXPECT_EQ(xid, <API key>(110, 110)); EXPECT_EQ(menu_xid, <API key>(150, 120)); EXPECT_EQ(menu_xid, <API key>(210, 120)); XDestroyWindow(xdisplay(), xid); XDestroyWindow(xdisplay(), menu_xid); } } // namespace views
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http: <html> <head> <title>This tests that the querySelector and querySelectorAll fast path for IDs is not overzelous.</title> <script src="../../../resources/testharness.js"></script> <script src="../../../resources/testharnessreport.js"></script> </head> <body> <script src="resources/id-fastpath-strict.js"></script> </body> </html>
li a { color: green; } body { background: white url("images/background.gif") no-repeat right bottom; }
<!DOCTYPE html> <! Copyright (c) 2013 Samsung Electronics Co., Ltd. Licensed under the Apache License, Version 2.0 (the License); you may not use this file except in compliance with the License. You may obtain a copy of the License at http: 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. Authors: Roman Frolow <r.frolow@samsung.com> <html> <head> <title><API key></title> <meta charset="utf-8"/> <script type="text/javascript" src="support/unitcommon.js"></script> <script type="text/javascript" src="support/systeminfo_common.js"></script> </head> <body> <div id="log"></div> <script type="text/javascript"> var t = async_test(document.title, {timeout: 90000}), <API key>, <API key>, retValue = null; setup({timeout: 90000}); t.step(function () { <API key> = t.step_func(function (error) { assert_unreached("<API key>() error callback invoked: name:" + error.name + ", msg:" + error.message); }); <API key> = t.step_func(function (property) { assert_own_property(property, "load", "CPU does not own load property."); assert_type(retValue, "unsigned long", "<API key> returns wrong value"); t.done(); }); retValue = tizen.systeminfo.<API key>("CPU", <API key>); }); </script> </body> </html>
/* without modification, are permitted provided that the following */ /* conditions are met: */ /* provided with the distribution. */ /* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF TEXAS AT */ /* AUSTIN ``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 UNIVERSITY OF TEXAS AT */ /* AUSTIN 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. */ /* The views and conclusions contained in the software and */ /* documentation are those of the authors and should not be */ /* interpreted as representing official policies, either expressed */ /* or implied, of The University of Texas at Austin. */ #ifndef COMMON_ALPHA #define COMMON_ALPHA #ifndef ASSEMBLER #define MB asm("mb") #define WMB asm("wmb") static void __inline blas_lock(unsigned long *address){ #ifndef __DECC unsigned long tmp1, tmp2; asm volatile( "1: ldq %1, %0\n" " bne %1, 2f\n" " ldq_l %1, %0\n" " bne %1, 2f\n" " or %1, 1, %2\n" " stq_c %2, %0\n" " beq %2, 2f\n" " mb\n " " br $31, 3f\n" "2: br $31, 1b\n" "3:\n" : "=m"(*address), "=&r"(tmp1), "=&r"(tmp2) : : "memory"); #else asm ( "10:" " ldq %t0, 0(%a0); " " bne %t0, 20f; " " ldq_l %t0, 0(%a0); " " bne %t0, 20f; " " or %t0, 1, %t1;" " stq_c %t1, 0(%a0); " " beq %t1, 20f; " " mb; " " br %r31,30f; " "20: " " br %r31,10b; " "30:", address); #endif } static __inline unsigned int rpcc(void){ unsigned int r0; #ifndef __DECC asm __volatile__("rpcc %0" : "=r"(r0) : : "memory"); #else r0 = asm("rpcc %v0"); #endif return r0; } #define HALT ldq $0, 0($0) #ifndef __DECC #define GET_IMAGE(res) asm __volatile__("fmov $f1, %0" : "=f"(res) : : "memory") #else #define GET_IMAGE(res) res = dasm("fmov $f1, %f0") #endif #ifdef SMP #ifdef USE64BITINT static __inline long blas_quickdivide(long x, long y){ return x/y; } #else extern unsigned int <API key>[]; static __inline int blas_quickdivide(unsigned int x, unsigned int y){ if (y <= 1) return x; return (int)((x * (unsigned long)<API key>[y]) >> 32); } #endif #endif #define BASE_ADDRESS ((0x1b0UL << 33) | (0x1c0UL << 23) | (0x000UL << 13)) #ifndef PAGESIZE #define PAGESIZE ( 8UL << 10) #define HUGE_PAGESIZE ( 4 << 20) #endif #define BUFFER_SIZE (32UL << 20) #else #ifndef F_INTERFACE #define REALNAME ASMNAME #else #define REALNAME ASMFNAME #endif #define PROLOGUE \ .arch ev6; \ .set noat; \ .set noreorder; \ .text; \ .align 5; \ .globl REALNAME; \ .ent REALNAME; \ REALNAME: #ifdef PROFILE #define PROFCODE \ ldgp $gp, 0($27); \ lda $28, _mcount; \ jsr $28, ($28), _mcount; \ .prologue 1 #else #define PROFCODE .prologue 0 #endif #if defined(__linux__) && defined(__ELF__) #define GNUSTACK .section .note.GNU-stack,"",@progbits #else #define GNUSTACK #endif #define EPILOGUE \ .end REALNAME; \ .ident VERSION; \ GNUSTACK #endif #ifdef DOUBLE #define SXADDQ s8addq #define SXSUBL s8subl #define LD ldt #define ST stt #define STQ stq #define ADD addt/su #define SUB subt/su #define MUL mult/su #define DIV divt/su #else #define SXADDQ s4addq #define SXSUBL s4subl #define LD lds #define ST sts #define STQ stl #define ADD adds/su #define SUB subs/su #define MUL muls/su #define DIV divs/su #endif #endif
/* eslint strict:0 */ var modules = Object.create(null); var inGuard = false; function define(id, factory) { modules[id] = { factory, module: {exports: {}}, isInitialized: false, hasError: false, }; if (__DEV__) { // HMR Object.assign(modules[id].module, { hot: { acceptCallback: null, accept: function(callback) { modules[id].module.hot.acceptCallback = callback; } } }); } } function require(id) { var mod = modules[id]; if (mod && mod.isInitialized) { return mod.module.exports; } return requireImpl(id); } function requireImpl(id) { if (global.ErrorUtils && !inGuard) { inGuard = true; var returnValue; try { returnValue = requireImpl.apply(this, arguments); } catch (e) { global.ErrorUtils.reportFatalError(e); } inGuard = false; return returnValue; } var mod = modules[id]; if (!mod) { var msg = 'Requiring unknown module "' + id + '"'; if (__DEV__) { msg += '. If you are sure the module is there, try restarting the packager.'; } throw new Error(msg); } if (mod.hasError) { throw new Error( 'Requiring module "' + id + '" which threw an exception' ); } try { // We must optimistically mark mod as initialized before running the factory to keep any // require cycles inside the factory from causing an infinite require loop. mod.isInitialized = true; __DEV__ && Systrace().beginEvent('JS_require_' + id); // keep args in sync with with defineModuleCode in // packager/react-packager/src/Resolver/index.js mod.factory.call(global, global, require, mod.module, mod.module.exports); __DEV__ && Systrace().endEvent(); } catch (e) { mod.hasError = true; mod.isInitialized = false; throw e; } return mod.module.exports; } const Systrace = __DEV__ && (() => { var _Systrace; try { _Systrace = require('Systrace'); } catch (e) {} return _Systrace && _Systrace.beginEvent ? _Systrace : { beginEvent: () => {}, endEvent: () => {} }; }); global.__d = define; global.require = require; if (__DEV__) { // HMR function accept(id, factory) { var mod = modules[id]; if (!mod) { define(id, factory); return; // new modules don't need to be accepted } if (!mod.module.hot) { console.warn( 'Cannot accept module because Hot Module Replacement ' + 'API was not installed.' ); return; } if (mod.module.hot.acceptCallback) { mod.factory = factory; mod.isInitialized = false; require(id); mod.module.hot.acceptCallback(); } else { console.warn( '[HMR] Module `' + id + '` can\'t be hot reloaded because it ' + 'doesn\'t provide accept callback hook. Reload the app to get the updates.' ); } } global.__accept = accept; }
#ifndef EXPAND_PICTURE_H #define EXPAND_PICTURE_H #include "typedefs.h" #if defined(__cplusplus) extern "C" { #endif//__cplusplus #define PADDING_LENGTH 32 // reference extension #define <API key> 16 // chroma reference extension #if defined(X86_ASM) void <API key> (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); void <API key> (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); void <API key> (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); #endif//X86_ASM #if defined(HAVE_NEON) void <API key> (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); void <API key> (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); #endif #if defined(HAVE_NEON_AARCH64) void <API key> (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); void <API key> (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); #endif #if defined(HAVE_MMI) void <API key> (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); void <API key> (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); void <API key> (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); #endif//HAVE_MMI typedef void (*PExpandPictureFunc) (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); typedef struct TagExpandPicFunc { PExpandPictureFunc pfExpandLumaPicture; PExpandPictureFunc <API key>[2]; } SExpandPicFunc; void PadMBLuma_c (uint8_t*& pDst, const int32_t& kiStride, const int32_t& kiPicW, const int32_t& kiPicH, const int32_t& kiMbX, const int32_t& kiMbY, const int32_t& kiMBWidth, const int32_t& kiMBHeight); void PadMBChroma_c (uint8_t*& pDst, const int32_t& kiStride, const int32_t& kiPicW, const int32_t& kiPicH, const int32_t& kiMbX, const int32_t& kiMbY, const int32_t& kiMBWidth, const int32_t& kiMBHeight); void <API key> (uint8_t* pData[3], int32_t iWidth, int32_t iHeight, int32_t iStride[3], PExpandPictureFunc pExpLuma, PExpandPictureFunc pExpChrom[2]); void <API key> (SExpandPicFunc* pExpandPicFunc, const uint32_t kuiCPUFlags); #if defined(__cplusplus) } #endif//__cplusplus #endif
'use strict'; /** @suppress {duplicate} */ var remoting = remoting || {}; /** * @param {chrome.runtime.Port} hangoutPort * @param {remoting.It2MeHostFacade} host * @param {remoting.HostInstaller} hostInstaller * @param {function()} onDisposedCallback Callback to notify the client when * the connection is torn down. * * @constructor * @implements {base.Disposable} */ remoting.It2MeHelpeeChannel = function(hangoutPort, host, hostInstaller, onDisposedCallback) { /** * @type {chrome.runtime.Port} * @private */ this.hangoutPort_ = hangoutPort; /** * @type {remoting.It2MeHostFacade} * @private */ this.host_ = host; /** * @type {?remoting.HostInstaller} * @private */ this.hostInstaller_ = hostInstaller; /** * @type {remoting.HostSession.State} * @private */ this.hostState_ = remoting.HostSession.State.UNKNOWN; /** * @type {?function()} * @private */ this.onDisposedCallback_ = onDisposedCallback; this.<API key> = this.onHangoutMessage_.bind(this); this.<API key> = this.<API key>.bind(this); }; /** @enum {string} */ remoting.It2MeHelpeeChannel.HangoutMessageTypes = { CONNECT: 'connect', CONNECT_RESPONSE: 'connectResponse', DISCONNECT: 'disconnect', DOWNLOAD_HOST: 'downloadHost', ERROR: 'error', HELLO: 'hello', HELLO_RESPONSE: 'helloResponse', HOST_STATE_CHANGED: 'hostStateChanged', IS_HOST_INSTALLED: 'isHostInstalled', <API key>: '<API key>' }; /** @enum {string} */ remoting.It2MeHelpeeChannel.Features = { REMOTE_ASSISTANCE: 'remoteAssistance' }; remoting.It2MeHelpeeChannel.prototype.init = function() { this.hangoutPort_.onMessage.addListener(this.<API key>); this.hangoutPort_.onDisconnect.addListener(this.<API key>); }; remoting.It2MeHelpeeChannel.prototype.dispose = function() { if (this.host_ !== null) { this.host_.unhookCallbacks(); this.host_.disconnect(); this.host_ = null; } if (this.hangoutPort_ !== null) { this.hangoutPort_.onMessage.removeListener(this.<API key>); this.hangoutPort_.onDisconnect.removeListener(this.<API key>); this.hostState_ = remoting.HostSession.State.DISCONNECTED; try { var MessageTypes = remoting.It2MeHelpeeChannel.HangoutMessageTypes; this.hangoutPort_.postMessage({ method: MessageTypes.HOST_STATE_CHANGED, state: this.hostState_ }); } catch (e) { // |postMessage| throws if |this.hangoutPort_| is disconnected // It is safe to ignore the exception. } this.hangoutPort_.disconnect(); this.hangoutPort_ = null; } if (this.onDisposedCallback_ !== null) { this.onDisposedCallback_(); this.onDisposedCallback_ = null; } }; /** * Message Handler for incoming runtime messages from Hangouts. * * @param {{method:string, data:Object.<string,*>}} message * @private */ remoting.It2MeHelpeeChannel.prototype.onHangoutMessage_ = function(message) { try { var MessageTypes = remoting.It2MeHelpeeChannel.HangoutMessageTypes; switch (message.method) { case MessageTypes.HELLO: this.hangoutPort_.postMessage({ method: MessageTypes.HELLO_RESPONSE, supportedFeatures: base.values(remoting.It2MeHelpeeChannel.Features) }); return true; case MessageTypes.IS_HOST_INSTALLED: this.<API key>(message); return true; case MessageTypes.DOWNLOAD_HOST: this.handleDownloadHost_(message); return true; case MessageTypes.CONNECT: this.handleConnect_(message); return true; case MessageTypes.DISCONNECT: this.dispose(); return true; } throw new Error('Unsupported message method=' + message.method); } catch(e) { var error = /** @type {Error} */ e; this.sendErrorResponse_(message, error.message); } return false; }; /** * Queries the |hostInstaller| for the installation status. * * @param {{method:string, data:Object.<string,*>}} message * @private */ remoting.It2MeHelpeeChannel.prototype.<API key> = function(message) { /** @type {remoting.It2MeHelpeeChannel} */ var that = this; /** @param {boolean} installed */ function sendResponse(installed) { var MessageTypes = remoting.It2MeHelpeeChannel.HangoutMessageTypes; that.hangoutPort_.postMessage({ method: MessageTypes.<API key>, result: installed }); } this.hostInstaller_.isInstalled().then( sendResponse, this.sendErrorResponse_.bind(this, message) ); }; /** * @param {{method:string, data:Object.<string,*>}} message * @private */ remoting.It2MeHelpeeChannel.prototype.handleDownloadHost_ = function(message) { try { this.hostInstaller_.download(); } catch (e) { var error = /** @type {Error} */ e; this.sendErrorResponse_(message, error.message); } }; /** * Disconnect the session if the |hangoutPort| gets disconnected. * @private */ remoting.It2MeHelpeeChannel.prototype.<API key> = function() { this.dispose(); }; /** * Connects to the It2Me Native messaging Host and retrieves the access code. * * @param {{method:string, data:Object.<string,*>}} message * @private */ remoting.It2MeHelpeeChannel.prototype.handleConnect_ = function(message) { var email = getStringAttr(message, 'email'); if (!email) { throw new Error('Missing required parameter: email'); } if (this.hostState_ !== remoting.HostSession.State.UNKNOWN) { throw new Error('An existing connection is in progress.'); } this.showConfirmDialog_().then( this.initializeHost_.bind(this) ).then( this.fetchOAuthToken_.bind(this) ).then( this.connectToHost_.bind(this, email), this.sendErrorResponse_.bind(this, message) ); }; /** * Prompts the user before starting the It2Me Native Messaging Host. This * ensures that even if Hangouts is compromised, an attacker cannot start the * host without explicit user confirmation. * * @return {Promise} A promise that resolves to a boolean value, indicating * whether the user accepts the remote assistance or not. * @private */ remoting.It2MeHelpeeChannel.prototype.showConfirmDialog_ = function() { if (base.isAppsV2()) { return this.<API key>(); } else { return this.<API key>(); } }; /** * @return {Promise} A promise that resolves to a boolean value, indicating * whether the user accepts the remote assistance or not. * @private */ remoting.It2MeHelpeeChannel.prototype.<API key> = function() { var messageHeader = l10n.<API key>( /*i18n-content*/'<API key>'); var message1 = l10n.<API key>( /*i18n-content*/'<API key>'); var message2 = l10n.<API key>( /*i18n-content*/'<API key>'); var message = base.escapeHTML(messageHeader) + '\n' + '- ' + base.escapeHTML(message1) + '\n' + '- ' + base.escapeHTML(message2) + '\n'; if(window.confirm(message)) { return Promise.resolve(); } else { return Promise.reject(new Error(remoting.Error.CANCELLED)); } }; /** * @return {Promise} A promise that resolves to a boolean value, indicating * whether the user accepts the remote assistance or not. * @private */ remoting.It2MeHelpeeChannel.prototype.<API key> = function() { var messageHeader = l10n.<API key>( /*i18n-content*/'<API key>'); var message1 = l10n.<API key>( /*i18n-content*/'<API key>'); var message2 = l10n.<API key>( /*i18n-content*/'<API key>'); var message = '<div>' + base.escapeHTML(messageHeader) + '</div>' + '<ul class="insetList">' + '<li>' + base.escapeHTML(message1) + '</li>' + '<li>' + base.escapeHTML(message2) + '</li>' + '</ul>'; /** * @param {function(*=):void} resolve * @param {function(*=):void} reject */ return new Promise(function(resolve, reject) { /** @param {number} result */ function <API key>(result) { if (result === 1) { resolve(); } else { reject(new Error(remoting.Error.CANCELLED)); } } remoting.MessageWindow.showConfirmWindow( '', // Empty string to use the package name as the dialog title. message, l10n.<API key>( /*i18n-content*/'<API key>'), l10n.<API key>( /*i18n-content*/'<API key>'), <API key> ); }); }; /** * @return {Promise} A promise that resolves when the host is initialized. * @private */ remoting.It2MeHelpeeChannel.prototype.initializeHost_ = function() { /** @type {remoting.It2MeHostFacade} */ var host = this.host_; /** * @param {function(*=):void} resolve * @param {function(*=):void} reject */ return new Promise(function(resolve, reject) { if (host.initialized()) { resolve(); } else { host.initialize(resolve, reject); } }); }; /** * @return {Promise} Promise that resolves with the OAuth token as the value. */ remoting.It2MeHelpeeChannel.prototype.fetchOAuthToken_ = function() { if (base.isAppsV2()) { /** * @param {function(*=):void} resolve */ return new Promise(function(resolve){ // TODO(jamiewalch): Make this work with {interactive: true} as well. chrome.identity.getAuthToken({ 'interactive': false }, resolve); }); } else { /** * @param {function(*=):void} resolve */ return new Promise(function(resolve) { /** @type {remoting.OAuth2} */ var oauth2 = new remoting.OAuth2(); var onAuthenticated = function() { oauth2.callWithToken( resolve, function() { throw new Error('Authentication failed.'); }); }; /** @param {remoting.Error} error */ var onError = function(error) { if (error != remoting.Error.NOT_AUTHENTICATED) { throw new Error('Unexpected error fetch auth token: ' + error); } oauth2.doAuthRedirect(onAuthenticated); }; oauth2.callWithToken(resolve, onError); }); } }; /** * Connects to the It2Me Native Messaging Host and retrieves the access code * in the |onHostStateChanged_| callback. * * @param {string} email * @param {string} accessToken * @private */ remoting.It2MeHelpeeChannel.prototype.connectToHost_ = function(email, accessToken) { base.debug.assert(this.host_.initialized()); this.host_.connect( email, 'oauth2:' + accessToken, this.onHostStateChanged_.bind(this), base.doNothing, // Ignore |onNatPolicyChanged|. console.log.bind(console), // Forward logDebugInfo to console.log. remoting.settings.<API key>, remoting.settings.XMPP_SERVER_USE_TLS, remoting.settings.DIRECTORY_BOT_JID, this.onHostConnectError_); }; /** * @param {remoting.Error} error * @private */ remoting.It2MeHelpeeChannel.prototype.onHostConnectError_ = function(error) { this.sendErrorResponse_(null, error); }; /** * @param {remoting.HostSession.State} state * @private */ remoting.It2MeHelpeeChannel.prototype.onHostStateChanged_ = function(state) { this.hostState_ = state; var MessageTypes = remoting.It2MeHelpeeChannel.HangoutMessageTypes; var HostState = remoting.HostSession.State; switch (state) { case HostState.<API key>: var accessCode = this.host_.getAccessCode(); this.hangoutPort_.postMessage({ method: MessageTypes.CONNECT_RESPONSE, accessCode: accessCode }); break; case HostState.CONNECTED: case HostState.DISCONNECTED: this.hangoutPort_.postMessage({ method: MessageTypes.HOST_STATE_CHANGED, state: state }); break; case HostState.ERROR: this.sendErrorResponse_(null, remoting.Error.UNEXPECTED); break; case HostState.<API key>: this.sendErrorResponse_(null, remoting.Error.INVALID_HOST_DOMAIN); break; default: // It is safe to ignore other state changes. } }; /** * @param {?{method:string, data:Object.<string,*>}} incomingMessage * @param {string|Error} error * @private */ remoting.It2MeHelpeeChannel.prototype.sendErrorResponse_ = function(incomingMessage, error) { if (error instanceof Error) { error = error.message; } console.error('Error responding to message method:' + (incomingMessage ? incomingMessage.method : 'null') + ' error:' + error); this.hangoutPort_.postMessage({ method: remoting.It2MeHelpeeChannel.HangoutMessageTypes.ERROR, message: error, request: incomingMessage }); };
#include "skia/ext/<API key>.h" #include "base/trace_event/<API key>.h" #include "base/trace_event/memory_dump_manager.h" #include "base/trace_event/process_memory_dump.h" #include "skia/ext/<API key>.h" namespace skia { namespace { const char kMallocBackingType[] = "malloc"; } <API key>::<API key>( base::trace_event::<API key> level_of_detail, base::trace_event::ProcessMemoryDump* process_memory_dump) : <API key>("", level_of_detail, process_memory_dump) {} <API key>::<API key>( const std::string& dump_name_prefix, base::trace_event::<API key> level_of_detail, base::trace_event::ProcessMemoryDump* process_memory_dump) : dump_name_prefix_(dump_name_prefix), <API key>(process_memory_dump), request_level_( level_of_detail == base::trace_event::<API key>::LIGHT ? SkTraceMemoryDump::<API key> : SkTraceMemoryDump::<API key>) {} <API key>::~<API key>() = default; void <API key>::dumpNumericValue(const char* dumpName, const char* valueName, const char* units, uint64_t value) { auto* dump = <API key>-><API key>(dumpName); dump->AddScalar(valueName, units, value); } void <API key>::dumpStringValue(const char* dump_name, const char* value_name, const char* value) { auto* dump = <API key>-><API key>(dump_name); dump->AddString(value_name, "", value); } void <API key>::setMemoryBacking(const char* dumpName, const char* backingType, const char* backingObjectId) { if (strcmp(backingType, kMallocBackingType) == 0) { auto* dump = <API key>-><API key>(dumpName); const char* <API key> = base::trace_event::MemoryDumpManager::GetInstance() -><API key>(); if (<API key>) { <API key>->AddSuballocation(dump->guid(), <API key>); } } else { NOTREACHED(); } } void <API key>::<API key>( const char* dumpName, const SkDiscardableMemory& <API key>) { std::string name = dump_name_prefix_ + dumpName; DCHECK(!<API key>->GetAllocatorDump(name)); const <API key>& <API key> = static_cast<const <API key>&>(<API key>); auto* dump = <API key>.<API key>( name.c_str(), <API key>); DCHECK(dump); } SkTraceMemoryDump::LevelOfDetail <API key>::getRequestedDetails() const { return request_level_; } bool <API key>::<API key>() const { // Chrome already dumps objects it imports into Skia. Avoid duplicate dumps // by asking Skia not to dump them. return false; } } // namespace skia
#include "MissFailoverRoute.h" #include <folly/dynamic.h> #include "mcrouter/lib/config/RouteHandleFactory.h" #include "mcrouter/routes/<API key>.h" #include "mcrouter/routes/McrouterRouteHandle.h" namespace facebook { namespace memcache { namespace mcrouter { <API key> makeNullRoute(); <API key> <API key>( std::vector<<API key>> targets) { if (targets.empty()) { return makeNullRoute(); } if (targets.size() == 1) { return std::move(targets[0]); } return <API key><MissFailoverRoute>(std::move(targets)); } <API key> <API key>( RouteHandleFactory<<API key>>& factory, const folly::dynamic& json) { std::vector<<API key>> children; if (json.isObject()) { if (auto jchildren = json.get_ptr("children")) { children = factory.createList(*jchildren); } } else { children = factory.createList(json); } return <API key>(std::move(children)); } }}} // facebook::memcache::mcrouter
#ifndef <API key> #define <API key> #include <set> #include "ash/ash_export.h" #include "ash/display/<API key>.h" #include "ash/wm/wm_types.h" #include "base/callback.h" #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/scoped_ptr.h" #include "ui/events/event_handler.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" #include "ui/wm/public/window_move_client.h" namespace aura { class Window; } namespace ui { class LocatedEvent; } namespace ash { class WindowResizer; class ASH_EXPORT <API key> : public ui::EventHandler, public aura::client::WindowMoveClient, public <API key>::Observer { public: <API key>(); ~<API key>() override; // Overridden from ui::EventHandler: void OnKeyEvent(ui::KeyEvent* event) override; void OnMouseEvent(ui::MouseEvent* event) override; void OnGestureEvent(ui::GestureEvent* event) override; // Overridden form aura::client::WindowMoveClient: aura::client::WindowMoveResult RunMoveLoop( aura::Window* source, const gfx::Vector2d& drag_offset, aura::client::WindowMoveSource move_source) override; void EndMoveLoop() override; // Overridden form ash::<API key>::Observer: void <API key>() override; private: class ScopedWindowResizer; enum <API key> { DRAG_COMPLETE, DRAG_REVERT, // To be used when WindowResizer::GetTarget() is destroyed. Neither // completes nor reverts the drag because both access the WindowResizer's // window. <API key> }; // Attempts to start a drag if one is not already in progress. Returns true if // successful. bool AttemptToStartDrag(aura::Window* window, const gfx::Point& point_in_parent, int window_component, aura::client::WindowMoveSource source); // Completes or reverts the drag if one is in progress. Returns true if a // drag was completed or reverted. bool CompleteDrag(<API key> status); void HandleMousePressed(aura::Window* target, ui::MouseEvent* event); void HandleMouseReleased(aura::Window* target, ui::MouseEvent* event); // Called during a drag to resize/position the window. void HandleDrag(aura::Window* target, ui::LocatedEvent* event); // Called during mouse moves to update window resize shadows. void HandleMouseMoved(aura::Window* target, ui::LocatedEvent* event); // Called for mouse exits to hide window resize shadows. void HandleMouseExited(aura::Window* target, ui::LocatedEvent* event); // Called when mouse capture is lost. void HandleCaptureLost(ui::LocatedEvent* event); // Sets |window|'s state type to |new_state_type|. Called after the drag has // been completed for fling gestures. void <API key>(aura::Window* window, wm::WindowStateType new_state_type); // Invoked from ScopedWindowResizer if the window is destroyed. void <API key>(); // The hittest result for the first finger at the time that it initially // touched the screen. |<API key>| is one of ui/base/hit_test.h int <API key>; // The window bounds when the drag was started. When a window is minimized, // maximized or snapped via a swipe/fling gesture, the restore bounds should // be set to the bounds of the window when the drag was started. gfx::Rect <API key>; // Are we running a nested message loop from RunMoveLoop(). bool in_move_loop_; // Is a window move/resize in progress because of gesture events? bool in_gesture_drag_; // Whether the drag was reverted. Set by CompleteDrag(). bool drag_reverted_; scoped_ptr<ScopedWindowResizer> window_resizer_; base::Closure quit_closure_; // Used to track if this object is deleted while running a nested message // loop. If non-null the destructor sets this to true. bool* destroyed_; <API key>(<API key>); }; } // namespace aura #endif // <API key>
#/bin/sh #set -x # Script for processing DETdigits.C (or digitITSDET.C) macros # and generating files with histograms. # Generated histograms can be then plot with plotDigits2.C. # Currently the macro has to be run in the directory # with the aliroot output, and one has to specify the # number of events and the number of files in the chain # to be prcessed. # By E.Sicking, CERN; I. Hrivnacova, IPN Orsay scriptdir=$ALICE_ROOT/test/vmctest/scripts export NEVENTS=10 export NFILES=4 for DET in SDD SSD SPD TPC TRD TOF EMCAL HMPID PHOS; do echo Processing $DET digits aliroot -b -q $scriptdir/digits${DET}.C\($NEVENTS,$NFILES\) done
.window { font-size:12px; position:absolute; overflow:hidden; background:transparent url('images/panel_title.png'); background1:#878787; padding:5px; border:1px solid #99BBE8; -moz-border-radius:5px; -<API key>: 5px; } .window-shadow{ position:absolute; background:#ddd; -moz-border-radius:5px; -<API key>: 5px; -moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2); -webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2); filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2); } .window .window-header{ background:transparent; padding:2px 0px 4px 0px; } .window .window-body{ background:#fff; border:1px solid #99BBE8; border-top-width:0px; } .window .window-header .panel-icon{ left:1px; top:1px; } .window .window-header .panel-with-icon{ padding-left:18px; } .window .window-header .panel-tool{ top:0px; right:1px; } .window-proxy{ position:absolute; overflow:hidden; border:1px dashed #15428b; } .window-mask{ position:absolute; left:0; top:0; width:100%; height:100%; filter:alpha(opacity=40); opacity:0.40; background:#ccc; display1:none; font-size:1px; *zoom:1; overflow:hidden; }
#include "components/<API key>/core/<API key>.h" #include "net/base/net_errors.h" #include "testing/gtest/include/gtest/gtest.h" namespace <API key> { TEST(SSLErrorOptionsMask, <API key>) { int mask; // Non-overridable cert error. mask = <API key>( net::<API key>, /* cert_error */ false, /* <API key> */ false /* <API key> */ ); EXPECT_EQ(0, mask); mask = <API key>( net::<API key>, /* cert_error */ true, /* <API key> */ false /* <API key> */ ); EXPECT_EQ(SSLErrorOptionsMask::<API key>, mask); mask = <API key>( net::<API key>, /* cert_error */ false, /* <API key> */ true /* <API key> */ ); EXPECT_EQ(SSLErrorOptionsMask::STRICT_ENFORCEMENT, mask); // Overridable cert error. mask = <API key>(net::<API key>, /* cert_error */ false, /* <API key> */ false /* <API key> */ ); EXPECT_EQ(SSLErrorOptionsMask::<API key>, mask); mask = <API key>(net::<API key>, /* cert_error */ true, /* <API key> */ false /* <API key> */ ); EXPECT_EQ(SSLErrorOptionsMask::<API key>, mask); mask = <API key>(net::<API key>, /* cert_error */ false, /* <API key> */ true /* <API key> */ ); EXPECT_EQ(SSLErrorOptionsMask::STRICT_ENFORCEMENT, mask); } } // namespace <API key>
<html> <head> <title>Weak Showers</title> <link rel="stylesheet" type="text/css" href="pythia.css"/> <link rel="shortcut icon" href="pythia32.gif"/> </head> <body> <h2>Weak Showers</h2> The emission of <i>W^+-</i> and <i>Z^0</i> gauge bosons off fermions is intended to be an integrated part of the initial- and final-state radiation frameworks, and is fully interleaved with QCD and QED emissions. It is a new and still not fully explored feature, however, and therefore it is off by default. The weak-emission machinery is described in detail in [<a href="Bibliography.html" target="page">Chr14</a>]; here we only bring up some of the most relevant points for using this machinery. <p/> In QCD and QED showers the real and virtual corrections are directly related with each other, which means that the appropriate Sudakov factors can be directly obtained as a by-product of the real-emission evolution. This does not hold for <i>W^+-</i>, owing to the flavour-changing character of emissions, so-called Bloch-Nordsieck violations. These effects are not expected to be large, but they are not properly included, since our evolution framework makes no distinction in this respect between QCD, QED or weak emissions. Another restriction is that there is no simulation of the full <i>gamma^*/Z^0</i> interference: at low masses the QED shower involves a pure <i>gamma^*</i> component, whereas the weak shower generates a pure <i>Z^0</i>. <p/> The non-negligible <i>W/Z</i> masses have a considerable impact both on the matrix elements and on the phase space for their emission. The shower on its own is not set up to handle those aspects with a particularly good accuracy. Therefore the weak shower emissions are always matched to the matrix element for emission off a <i>f fbar</i> weak dipole, or some other <i>2 &rarr; 3</i> matrix element that resembles the topology at hand. Even if the match may not be perfect, at least the main features should be caught that way. Notably, the correction procedure is used throughout the shower, not only for the emission closest to the hard <i>2 &rarr; 2</i> process. In such extended applications, emission rates are normalized to the invariant mass of the dipole at the time of the weak emission, i.e. discounting the energy change by previous QCD/QED emissions. <p/> Also the angular distribution in the subsequent <i>V = W^+-/Z^0</i> decay is matched to the matrix element expression for <i>f fbar &rarr; f fbar V &rarr; f fbar f' fbar'</i> (FSR) and <i>f fbar &rarr; g^* V &rarr; g^* f' fbar'</i> (ISR). Afterwards the <i>f' fbar'</i> system undergoes showers and hadronization just like any <i>W^+-/Z^0</i> decay products would. <p/> Special for the weak showers is that couplings are different for left- and righthanded fermions. With incoming unpolarized beams this should average out, at least so long as only one weak emission occurs. In the case of several weak emissions off the same fermion the correlation between them will carry a memory of the fermion helicity. Such a memory is retained for the affected dipole end, and is reflected in the <code>Particle::pol()</code> property, it being <i>+1</i> (<i>-1</i>) for fermions considered righthanded (lefthanded), and 0 for the bulk where no choice has been made. <p/> Most events will not contain a <i>W^+-/Z^0</i> emission at all, which means that dedicated generator studies of weak emissions can become quite inefficient. In a shower framework it is not straightforward to force such emissions to happen without biasing the event sample in some respect. An option is available to enhance the emission rate artificially, but it is then the responsibility of the user to correct the cross section accordingly, and not to pick an enhancement so big that the probability for more than one emission is non-negligible. (It is not enough to assign an event weight <i>1/e^n</i> where <i>e</i> is the enhancement factor and <i>n</i> is the number of emitted gauge bosons. This still misses to account for the change in phase space for late emissions by the effect of earlier ones, or equivalently for the unwanted change in the Sudakov form factor. See [<a href="Bibliography.html" target="page">Lon12a</a>] for a detailed discussion and possible solutions.) <p/> Another enhancement probability is to only allow some specific <i>W^+-/Z^0</i> decay modes. By default the shower is inclusive, since it should describe all that can happen with unit probability. This also holds even if the <i>W^+-</i> and <i>Z^0</i> produced in the hard process have been restricted to specific decay channels. The trick that allows this is that two new "aliases" have been produced, a <code>Zcopy</code> with identity code 93 and a <code>Wcopy</code> with code 94. These copies are used specifically to bookkeep decay channels open for <i>W^+-/Z^0</i> bosons produced in the shower. For the rest they are invisible, i.e. you will not find these codes in event listings, but only the regular 23 and 24 ones. The identity code duplication allows the selection of specific decay modes for 93 and 94, i.e. for only the gauge bosons produced in the shower. As above it is here up to the user to reweight the event to compensate for the bias introduced, and to watch out for possible complications. In this case there is no kinematics bias, but one would miss out on topologies where a not-selected decay channel could be part of the background to the selected one, notably when more than one gauge boson is produced. <p/> Note that the common theme is that a bias leads to an event-specific weight, since each event is unique. It also means that the cross-section information obtained e.g. by <code>Pythia::stat()</code> is misleading, since it has not been corrected for such weights. This is different from biases in a predetermined hard process, where the net reduction in cross section can be calculated once and for all at initialization, and events generated with unit weight thereafter. <p/> The weak shower introduces a possible doublecounting problem. Namely that it is now possible to produce weak bosons in association with jets from two different channels, Drell-Yan weak production with QCD emissions and QCD hard process with a weak emission. A method, built on a classification of each event with the <i>kT</i> jet algorithm, is used to remove the doublecounting. Specifically, consider a tentative final state consisting of a <i>W/Z</i> and two jets. Based on the principle that the shower emission ought to be softer than the hard emission, the emission of a hard <i>W/Z</i> should be vetoed in a QCD event, and that of two hard jets in a Drell-Yan event. The dividing criterion is this whether the first clustering step involves the <i>W/Z</i> or not. It is suggested to turn this method on only if you simulate both Drell-Yan weak production and QCD hard production with a weak shower. Do not turn on the veto algorithm if you only intend to generate one of the two processes. <h3>variables</h3> Below are listed the variables related to the weak shower and common to both the initial- and final-state radiation. For variables only related to the initial-state radiation (e.g. to turn the weak shower on for ISR) see <a href="SpacelikeShowers.html" target="page">Spacelike Showers</a> and for final-state radiation see <a href="TimelikeShowers.html" target="page">Timelike Showers</a>. <p/><code>parm&nbsp; </code><strong> WeakShower:enhancement &nbsp;</strong> (<code>default = <strong>1.</strong></code>; <code>minimum = 1.</code>; <code>maximum = 1000.</code>)<br/> Enhancement factor for the weak shower. This is used to increase the statistics of weak shower emissions. Remember afterwards to correct for the additional weak emissions (i.e. divide the rate of weak emissions by the same factor). <p/><code>flag&nbsp; </code><strong> WeakShower:singleEmission &nbsp;</strong> (<code>default = <strong>off</strong></code>)<br/> This parameter allows to stop the weak shower after a single emission. <br/>If on, only a single weak emission is allowed. <br/>If off, an unlimited number of weak emissions possible. <p/><code>flag&nbsp; </code><strong> WeakShower:vetoWeakJets &nbsp;</strong> (<code>default = <strong>off</strong></code>)<br/> There are two ways to produce weak bosons in association with jets, namely Drell-Yan weak production with QCD radiation and QCD hard process with weak radiation. In order to avoid double counting between the two production channels, a veto procedure built on the <i>kT</i> jet algorithm is implemented in the evolution starting from a <i>2 &rarr; 2</i> QCD process, process codes in the range 111 - 129. The veto algorithm finds the first cluster step, and if it does not involve a weak boson the radiation of the weak boson is vetoed when <code>WeakShower:vetoWeakJets</code> is on. Note that this flag does not affect other internal or external processes, only the 111 - 129 ones. For the Drell-Yan process the same veto algorithm is used, but this time the event should be vetoed if the first clustering does contain a weak boson, see <code>WeakShower:vetoQCDjets</code> below. <p/><code>flag&nbsp; </code><strong> WeakShower:vetoQCDjets &nbsp;</strong> (<code>default = <strong>off</strong></code>)<br/> This flag vetoes some QCD emission for Drell-Yan weak production to avoid doublecounting with weak emission in QCD hard processes. For more information see <code>WeakShower:vetoWeakJets</code> above. Note that this flag only affects the process codes 221 and 222, i.e. the main built-in processes for <i>gamma^*/Z^0/W^+-</i> production, and not other internal or external processes. <p/><code>parm&nbsp; </code><strong> WeakShower:vetoWeakDeltaR &nbsp;</strong> (<code>default = <strong>0.6</strong></code>; <code>minimum = 0.1</code>; <code>maximum = 2.</code>)<br/> The <i>delta R</i> parameter used in the <i>kT</i> clustering for the veto algorithm used to avoid double counting. Relates to the relative importance given to ISR and FSR emissionbs. </body> </html>
#include "ui/gfx/render_text.h" #include <algorithm> #include <climits> #include "base/command_line.h" #include "base/i18n/break_iterator.h" #include "base/logging.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/<API key>.h" #include "third_party/icu/source/common/unicode/rbbi.h" #include "third_party/icu/source/common/unicode/utf16.h" #include "third_party/skia/include/core/SkTypeface.h" #include "third_party/skia/include/effects/SkGradientShader.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/<API key>.h" #include "ui/gfx/<API key>.h" #include "ui/gfx/scoped_canvas.h" #include "ui/gfx/skia_util.h" #include "ui/gfx/switches.h" #include "ui/gfx/text_elider.h" #include "ui/gfx/text_utils.h" #include "ui/gfx/utf16_indexing.h" namespace gfx { namespace { // All chars are replaced by this char when the password style is set. // TODO(benrg): GTK uses the first of U+25CF, U+2022, U+2731, U+273A, '*' // that's available in the font (find_invisible_char() in gtkentry.c). const base::char16 <API key> = '*'; // Default color used for the text and cursor. const SkColor kDefaultColor = SK_ColorBLACK; // Default color used for drawing selection background. const SkColor <API key> = SK_ColorGRAY; // Fraction of the text size to lower a strike through below the baseline. const SkScalar <API key> = (-SK_Scalar1 * 6 / 21); // Fraction of the text size to lower an underline below the baseline. const SkScalar kUnderlineOffset = (SK_Scalar1 / 9); // Fraction of the text size to use for a strike through or under-line. const SkScalar kLineThickness = (SK_Scalar1 / 18); // Fraction of the text size to use for a top margin of a diagonal strike. const SkScalar <API key> = (SK_Scalar1 / 4); // Invalid value of baseline. Assigning this value to |baseline_| causes // re-calculation of baseline. const int kInvalidBaseline = INT_MAX; // Returns the baseline, with which the text best appears vertically centered. int <API key>(const Rect& display_rect, const FontList& font_list) { const int display_height = display_rect.height(); const int font_height = font_list.GetHeight(); // Lower and upper bound of baseline shift as we try to show as much area of // text as possible. In particular case of |display_height| == |font_height|, // we do not want to shift the baseline. const int min_shift = std::min(0, display_height - font_height); const int max_shift = std::abs(display_height - font_height); const int baseline = font_list.GetBaseline(); const int cap_height = font_list.GetCapHeight(); const int internal_leading = baseline - cap_height; // Some platforms don't support getting the cap height, and simply return // the entire font ascent from GetCapHeight(). Centering the ascent makes // the font look too low, so if GetCapHeight() returns the ascent, center // the entire font height instead. const int space = display_height - ((internal_leading != 0) ? cap_height : font_height); const int baseline_shift = space / 2 - internal_leading; return baseline + std::max(min_shift, std::min(max_shift, baseline_shift)); } // Converts |Font::FontStyle| flags to |SkTypeface::Style| flags. SkTypeface::Style <API key>(int font_style) { int skia_style = SkTypeface::kNormal; skia_style |= (font_style & Font::BOLD) ? SkTypeface::kBold : 0; skia_style |= (font_style & Font::ITALIC) ? SkTypeface::kItalic : 0; return static_cast<SkTypeface::Style>(skia_style); } // Given |font| and |display_width|, returns the width of the fade gradient. int <API key>(const FontList& font_list, int display_width) { // Fade in/out about 2.5 characters of the beginning/end of the string. // The .5 here is helpful if one of the characters is a space. // Use a quarter of the display width if the display width is very short. const int <API key> = font_list.<API key>(1); const double gradient_width = std::min(<API key> * 2.5, display_width / 4.0); DCHECK_GE(gradient_width, 0.0); return static_cast<int>(floor(gradient_width + 0.5)); } // Appends to |positions| and |colors| values corresponding to the fade over // |fade_rect| from color |c0| to color |c1|. void AddFadeEffect(const Rect& text_rect, const Rect& fade_rect, SkColor c0, SkColor c1, std::vector<SkScalar>* positions, std::vector<SkColor>* colors) { const SkScalar left = static_cast<SkScalar>(fade_rect.x() - text_rect.x()); const SkScalar width = static_cast<SkScalar>(fade_rect.width()); const SkScalar p0 = left / text_rect.width(); const SkScalar p1 = (left + width) / text_rect.width(); // Prepend 0.0 to |positions|, as required by Skia. if (positions->empty() && p0 != 0.0) { positions->push_back(0.0); colors->push_back(c0); } positions->push_back(p0); colors->push_back(c0); positions->push_back(p1); colors->push_back(c1); } // Creates a SkShader to fade the text, with |left_part| specifying the left // fade effect, if any, and |right_part| specifying the right fade effect. skia::RefPtr<SkShader> CreateFadeShader(const Rect& text_rect, const Rect& left_part, const Rect& right_part, SkColor color) { // Fade alpha of 51/255 corresponds to a fade of 0.2 of the original color. const SkColor fade_color = SkColorSetA(color, 51); std::vector<SkScalar> positions; std::vector<SkColor> colors; if (!left_part.IsEmpty()) AddFadeEffect(text_rect, left_part, fade_color, color, &positions, &colors); if (!right_part.IsEmpty()) AddFadeEffect(text_rect, right_part, color, fade_color, &positions, &colors); DCHECK(!positions.empty()); // Terminate |positions| with 1.0, as required by Skia. if (positions.back() != 1.0) { positions.push_back(1.0); colors.push_back(colors.back()); } SkPoint points[2]; points[0].iset(text_rect.x(), text_rect.y()); points[1].iset(text_rect.right(), text_rect.y()); return skia::AdoptRef( SkGradientShader::CreateLinear(&points[0], &colors[0], &positions[0], colors.size(), SkShader::kClamp_TileMode)); } // Converts a FontRenderParams::Hinting value to the corresponding // SkPaint::Hinting value. SkPaint::Hinting <API key>( FontRenderParams::Hinting params_hinting) { switch (params_hinting) { case FontRenderParams::HINTING_NONE: return SkPaint::kNo_Hinting; case FontRenderParams::HINTING_SLIGHT: return SkPaint::kSlight_Hinting; case FontRenderParams::HINTING_MEDIUM: return SkPaint::kNormal_Hinting; case FontRenderParams::HINTING_FULL: return SkPaint::kFull_Hinting; } return SkPaint::kNo_Hinting; } } // namespace namespace internal { // Value of |<API key>| that indicates that underline metrics have // not been set explicitly. const SkScalar <API key> = -1.0f; SkiaTextRenderer::SkiaTextRenderer(Canvas* canvas) : canvas_(canvas), canvas_skia_(canvas->sk_canvas()), <API key>(<API key>), underline_position_(0.0f) { DCHECK(canvas_skia_); paint_.setTextEncoding(SkPaint::<API key>); paint_.setStyle(SkPaint::kFill_Style); paint_.setAntiAlias(true); paint_.setSubpixelText(true); paint_.setLCDRenderText(true); paint_.setHinting(SkPaint::kNormal_Hinting); } SkiaTextRenderer::~SkiaTextRenderer() { } void SkiaTextRenderer::SetDrawLooper(SkDrawLooper* draw_looper) { paint_.setLooper(draw_looper); } void SkiaTextRenderer::SetFontRenderParams(const FontRenderParams& params, bool <API key>) { ApplyRenderParams(params, <API key>, &paint_); } void SkiaTextRenderer::SetTypeface(SkTypeface* typeface) { paint_.setTypeface(typeface); } void SkiaTextRenderer::SetTextSize(SkScalar size) { paint_.setTextSize(size); } void SkiaTextRenderer::<API key>(const std::string& family, int style) { DCHECK(!family.empty()); skia::RefPtr<SkTypeface> typeface = CreateSkiaTypeface(family.c_str(), style); if (typeface) { // |paint_| adds its own ref. So don't |release()| it from the ref ptr here. SetTypeface(typeface.get()); // Enable fake bold text if bold style is needed but new typeface does not // have it. paint_.setFakeBoldText((style & Font::BOLD) && !typeface->isBold()); } } void SkiaTextRenderer::SetForegroundColor(SkColor foreground) { paint_.setColor(foreground); } void SkiaTextRenderer::SetShader(SkShader* shader) { paint_.setShader(shader); } void SkiaTextRenderer::SetUnderlineMetrics(SkScalar thickness, SkScalar position) { <API key> = thickness; underline_position_ = position; } void SkiaTextRenderer::DrawPosText(const SkPoint* pos, const uint16* glyphs, size_t glyph_count) { const size_t byte_length = glyph_count * sizeof(glyphs[0]); canvas_skia_->drawPosText(&glyphs[0], byte_length, &pos[0], paint_); } void SkiaTextRenderer::DrawDecorations(int x, int y, int width, bool underline, bool strike, bool diagonal_strike) { if (underline) DrawUnderline(x, y, width); if (strike) DrawStrike(x, y, width); if (diagonal_strike) { if (!diagonal_) diagonal_.reset(new DiagonalStrike(canvas_, Point(x, y), paint_)); diagonal_->AddPiece(width, paint_.getColor()); } else if (diagonal_) { EndDiagonalStrike(); } } void SkiaTextRenderer::EndDiagonalStrike() { if (diagonal_) { diagonal_->Draw(); diagonal_.reset(); } } void SkiaTextRenderer::DrawUnderline(int x, int y, int width) { SkScalar x_scalar = SkIntToScalar(x); SkRect r = SkRect::MakeLTRB( x_scalar, y + underline_position_, x_scalar + width, y + underline_position_ + <API key>); if (<API key> == <API key>) { const SkScalar text_size = paint_.getTextSize(); r.fTop = SkScalarMulAdd(text_size, kUnderlineOffset, y); r.fBottom = r.fTop + SkScalarMul(text_size, kLineThickness); } canvas_skia_->drawRect(r, paint_); } void SkiaTextRenderer::DrawStrike(int x, int y, int width) const { const SkScalar text_size = paint_.getTextSize(); const SkScalar height = SkScalarMul(text_size, kLineThickness); const SkScalar offset = SkScalarMulAdd(text_size, <API key>, y); SkScalar x_scalar = SkIntToScalar(x); const SkRect r = SkRect::MakeLTRB(x_scalar, offset, x_scalar + width, offset + height); canvas_skia_->drawRect(r, paint_); } SkiaTextRenderer::DiagonalStrike::DiagonalStrike(Canvas* canvas, Point start, const SkPaint& paint) : canvas_(canvas), start_(start), paint_(paint), total_length_(0) { } SkiaTextRenderer::DiagonalStrike::~DiagonalStrike() { } void SkiaTextRenderer::DiagonalStrike::AddPiece(int length, SkColor color) { pieces_.push_back(Piece(length, color)); total_length_ += length; } void SkiaTextRenderer::DiagonalStrike::Draw() { const SkScalar text_size = paint_.getTextSize(); const SkScalar offset = SkScalarMul(text_size, <API key>); const int thickness = SkScalarCeilToInt(SkScalarMul(text_size, kLineThickness) * 2); const int height = SkScalarCeilToInt(text_size - offset); const Point end = start_ + Vector2d(total_length_, -height); const int clip_height = height + 2 * thickness; paint_.setAntiAlias(true); paint_.setStrokeWidth(SkIntToScalar(thickness)); const bool clipped = pieces_.size() > 1; SkCanvas* sk_canvas = canvas_->sk_canvas(); int x = start_.x(); for (size_t i = 0; i < pieces_.size(); ++i) { paint_.setColor(pieces_[i].second); if (clipped) { canvas_->Save(); sk_canvas->clipRect(RectToSkRect( Rect(x, end.y() - thickness, pieces_[i].first, clip_height))); } canvas_->DrawLine(start_, end, paint_); if (clipped) canvas_->Restore(); x += pieces_[i].first; } } StyleIterator::StyleIterator(const BreakList<SkColor>& colors, const std::vector<BreakList<bool> >& styles) : colors_(colors), styles_(styles) { color_ = colors_.breaks().begin(); for (size_t i = 0; i < styles_.size(); ++i) style_.push_back(styles_[i].breaks().begin()); } StyleIterator::~StyleIterator() {} Range StyleIterator::GetRange() const { Range range(colors_.GetRange(color_)); for (size_t i = 0; i < NUM_TEXT_STYLES; ++i) range = range.Intersect(styles_[i].GetRange(style_[i])); return range; } void StyleIterator::UpdatePosition(size_t position) { color_ = colors_.GetBreak(position); for (size_t i = 0; i < NUM_TEXT_STYLES; ++i) style_[i] = styles_[i].GetBreak(position); } LineSegment::LineSegment() : run(0) {} LineSegment::~LineSegment() {} Line::Line() : preceding_heights(0), baseline(0) {} Line::~Line() {} skia::RefPtr<SkTypeface> CreateSkiaTypeface(const std::string& family, int style) { SkTypeface::Style skia_style = <API key>(style); return skia::AdoptRef(SkTypeface::CreateFromName(family.c_str(), skia_style)); } void ApplyRenderParams(const FontRenderParams& params, bool <API key>, SkPaint* paint) { paint->setAntiAlias(params.antialiasing); paint->setLCDRenderText(!<API key> && params.subpixel_rendering != FontRenderParams::<API key>); paint->setSubpixelText(params.<API key>); paint->setAutohinted(params.autohinter); paint->setHinting(<API key>(params.hinting)); } } // namespace internal RenderText::~RenderText() { } RenderText* RenderText::CreateInstance() { #if defined(OS_MACOSX) static const bool use_harfbuzz = base::CommandLine::ForCurrentProcess()->HasSwitch( switches::<API key>); #else static const bool use_harfbuzz = !base::CommandLine::ForCurrentProcess()->HasSwitch( switches::<API key>); #endif return use_harfbuzz ? new RenderTextHarfBuzz : <API key>(); } RenderText* RenderText::<API key>() { static const bool use_harfbuzz = !base::CommandLine::ForCurrentProcess()->HasSwitch( switches::<API key>); return use_harfbuzz ? new RenderTextHarfBuzz : <API key>(); } void RenderText::SetText(const base::string16& text) { DCHECK(!composition_range_.IsValid()); if (text_ == text) return; text_ = text; // Adjust ranged styles and colors to accommodate a new text length. // Clear style ranges as they might break new text graphemes and apply // the first style to the whole text instead. const size_t text_length = text_.length(); colors_.SetMax(text_length); for (size_t style = 0; style < NUM_TEXT_STYLES; ++style) { BreakList<bool>& break_list = styles_[style]; break_list.SetValue(break_list.breaks().begin()->second); break_list.SetMax(text_length); } <API key> = false; // Reset selection model. SetText should always followed by SetSelectionModel // or SetCursorPosition in upper layer. SetSelectionModel(SelectionModel()); // Invalidate the cached text direction if it depends on the text contents. if (<API key> == <API key>) text_direction_ = base::i18n::UNKNOWN_DIRECTION; <API key> = -1; UpdateLayoutText(); } void RenderText::<API key>(HorizontalAlignment alignment) { if (<API key> != alignment) { <API key> = alignment; display_offset_ = Vector2d(); <API key> = false; } } void RenderText::SetFontList(const FontList& font_list) { font_list_ = font_list; const int font_style = font_list.GetFontStyle(); SetStyle(BOLD, (font_style & gfx::Font::BOLD) != 0); SetStyle(ITALIC, (font_style & gfx::Font::ITALIC) != 0); SetStyle(UNDERLINE, (font_style & gfx::Font::UNDERLINE) != 0); baseline_ = kInvalidBaseline; <API key> = false; ResetLayout(); } void RenderText::SetCursorEnabled(bool cursor_enabled) { cursor_enabled_ = cursor_enabled; <API key> = false; } void RenderText::ToggleInsertMode() { insert_mode_ = !insert_mode_; <API key> = false; } void RenderText::SetObscured(bool obscured) { if (obscured != obscured_) { obscured_ = obscured; <API key> = -1; <API key> = false; UpdateLayoutText(); } } void RenderText::<API key>(int index) { if (<API key> == index) return; <API key> = index; <API key> = false; UpdateLayoutText(); } void RenderText::<API key>(bool replace) { <API key> = replace; <API key> = false; UpdateLayoutText(); } void RenderText::SetMultiline(bool multiline) { if (multiline != multiline_) { multiline_ = multiline; <API key> = false; lines_.clear(); } } void RenderText::SetElideBehavior(ElideBehavior elide_behavior) { // TODO(skanuj) : Add a test for triggering layout change. if (elide_behavior_ != elide_behavior) { elide_behavior_ = elide_behavior; UpdateLayoutText(); } } void RenderText::SetDisplayRect(const Rect& r) { if (r != display_rect_) { display_rect_ = r; baseline_ = kInvalidBaseline; <API key> = false; lines_.clear(); if (elide_behavior_ != NO_ELIDE) UpdateLayoutText(); } } void RenderText::SetCursorPosition(size_t position) { MoveCursorTo(position, false); } void RenderText::MoveCursor(BreakType break_type, <API key> direction, bool select) { SelectionModel cursor(cursor_position(), selection_model_.caret_affinity()); // Cancelling a selection moves to the edge of the selection. if (break_type != LINE_BREAK && !selection().is_empty() && !select) { SelectionModel selection_start = <API key>(); int start_x = GetCursorBounds(selection_start, true).x(); int cursor_x = GetCursorBounds(cursor, true).x(); // Use the selection start if it is left (when |direction| is CURSOR_LEFT) // or right (when |direction| is CURSOR_RIGHT) of the selection end. if (direction == CURSOR_RIGHT ? start_x > cursor_x : start_x < cursor_x) cursor = selection_start; // Use the nearest word boundary in the proper |direction| for word breaks. if (break_type == WORD_BREAK) cursor = <API key>(cursor, break_type, direction); // Use an adjacent selection model if the cursor is not at a valid position. if (!IsValidCursorIndex(cursor.caret_pos())) cursor = <API key>(cursor, CHARACTER_BREAK, direction); } else { cursor = <API key>(cursor, break_type, direction); } if (select) cursor.set_selection_start(selection().start()); MoveCursorTo(cursor); } bool RenderText::MoveCursorTo(const SelectionModel& model) { // Enforce valid selection model components. size_t text_length = text().length(); Range range(std::min(model.selection().start(), text_length), std::min(model.caret_pos(), text_length)); // The current model only supports caret positions at valid cursor indices. if (!IsValidCursorIndex(range.start()) || !IsValidCursorIndex(range.end())) return false; SelectionModel sel(range, model.caret_affinity()); bool changed = sel != selection_model_; SetSelectionModel(sel); return changed; } bool RenderText::SelectRange(const Range& range) { Range sel(std::min(range.start(), text().length()), std::min(range.end(), text().length())); // Allow selection bounds at valid indicies amid multi-character graphemes. if (!IsValidLogicalIndex(sel.start()) || !IsValidLogicalIndex(sel.end())) return false; <API key> affinity = (sel.is_reversed() || sel.is_empty()) ? CURSOR_FORWARD : CURSOR_BACKWARD; SetSelectionModel(SelectionModel(sel, affinity)); return true; } bool RenderText::IsPointInSelection(const Point& point) { if (selection().is_empty()) return false; SelectionModel cursor = FindCursorPosition(point); return RangeContainsCaret( selection(), cursor.caret_pos(), cursor.caret_affinity()); } void RenderText::ClearSelection() { SetSelectionModel(SelectionModel(cursor_position(), selection_model_.caret_affinity())); } void RenderText::SelectAll(bool reversed) { const size_t length = text().length(); const Range all = reversed ? Range(length, 0) : Range(0, length); const bool success = SelectRange(all); DCHECK(success); } void RenderText::SelectWord() { if (obscured_) { SelectAll(false); return; } size_t selection_max = selection().GetMax(); base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD); bool success = iter.Init(); DCHECK(success); if (!success) return; size_t selection_min = selection().GetMin(); if (selection_min == text().length() && selection_min != 0) --selection_min; for (; selection_min != 0; --selection_min) { if (iter.IsStartOfWord(selection_min) || iter.IsEndOfWord(selection_min)) break; } if (selection_min == selection_max && selection_max != text().length()) ++selection_max; for (; selection_max < text().length(); ++selection_max) if (iter.IsEndOfWord(selection_max) || iter.IsStartOfWord(selection_max)) break; const bool reversed = selection().is_reversed(); MoveCursorTo(reversed ? selection_max : selection_min, false); MoveCursorTo(reversed ? selection_min : selection_max, true); } const Range& RenderText::GetCompositionRange() const { return composition_range_; } void RenderText::SetCompositionRange(const Range& composition_range) { CHECK(!composition_range.IsValid() || Range(0, text_.length()).Contains(composition_range)); composition_range_.set_end(composition_range.end()); composition_range_.set_start(composition_range.start()); ResetLayout(); } void RenderText::SetColor(SkColor value) { colors_.SetValue(value); } void RenderText::ApplyColor(SkColor value, const Range& range) { colors_.ApplyValue(value, range); } void RenderText::SetStyle(TextStyle style, bool value) { styles_[style].SetValue(value); <API key> = false; ResetLayout(); } void RenderText::ApplyStyle(TextStyle style, bool value, const Range& range) { // Do not change styles mid-grapheme to avoid breaking ligatures. const size_t start = IsValidCursorIndex(range.start()) ? range.start() : <API key>(range.start(), CURSOR_BACKWARD); const size_t end = IsValidCursorIndex(range.end()) ? range.end() : <API key>(range.end(), CURSOR_FORWARD); styles_[style].ApplyValue(value, Range(start, end)); <API key> = false; ResetLayout(); } bool RenderText::GetStyle(TextStyle style) const { return (styles_[style].breaks().size() == 1) && styles_[style].breaks().front().second; } void RenderText::<API key>(DirectionalityMode mode) { if (mode == <API key>) return; <API key> = mode; text_direction_ = base::i18n::UNKNOWN_DIRECTION; <API key> = false; ResetLayout(); } base::i18n::TextDirection RenderText::GetTextDirection() { if (text_direction_ == base::i18n::UNKNOWN_DIRECTION) { switch (<API key>) { case <API key>: // Derive the direction from the display text, which differs from text() // in the case of obscured (password) textfields. text_direction_ = base::i18n::<API key>(GetLayoutText()); break; case <API key>: text_direction_ = base::i18n::IsRTL() ? base::i18n::RIGHT_TO_LEFT : base::i18n::LEFT_TO_RIGHT; break; case <API key>: text_direction_ = base::i18n::LEFT_TO_RIGHT; break; case <API key>: text_direction_ = base::i18n::RIGHT_TO_LEFT; break; default: NOTREACHED(); } } return text_direction_; } <API key> RenderText::<API key>() { return GetTextDirection() == base::i18n::LEFT_TO_RIGHT ? CURSOR_RIGHT : CURSOR_LEFT; } SizeF RenderText::GetStringSizeF() { return GetStringSize(); } float RenderText::GetContentWidthF() { const float string_size = GetStringSizeF().width(); // The cursor is drawn one pixel beyond the int-enclosed text bounds. return cursor_enabled_ ? std::ceil(string_size) + 1 : string_size; } int RenderText::GetContentWidth() { return ToCeiledInt(GetContentWidthF()); } int RenderText::GetBaseline() { if (baseline_ == kInvalidBaseline) baseline_ = <API key>(display_rect(), font_list()); DCHECK_NE(kInvalidBaseline, baseline_); return baseline_; } void RenderText::Draw(Canvas* canvas) { EnsureLayout(); if (<API key>()) { Rect clip_rect(display_rect()); clip_rect.Inset(ShadowValue::GetMargin(shadows_)); canvas->Save(); canvas->ClipRect(clip_rect); } if (!text().empty() && focused()) DrawSelection(canvas); if (cursor_enabled() && cursor_visible() && focused()) DrawCursor(canvas, selection_model_); if (!text().empty()) DrawVisualText(canvas); if (<API key>()) canvas->Restore(); } void RenderText::DrawCursor(Canvas* canvas, const SelectionModel& position) { // Paint cursor. Replace cursor is drawn as rectangle for now. // TODO(msw): Draw a better cursor with a better indication of association. canvas->FillRect(GetCursorBounds(position, true), cursor_color_); } bool RenderText::IsValidLogicalIndex(size_t index) { // Check that the index is at a valid code point (not mid-surrgate-pair) and // that it's not truncated from the layout text (its glyph may be shown). // Indices within truncated text are disallowed so users can easily interact // with the underlying truncated text using the ellipsis as a proxy. This lets // users select all text, select the truncated text, and transition from the // last rendered glyph to the end of the text without getting invisible cursor // positions nor needing unbounded arrow key presses to traverse the ellipsis. return index == 0 || index == text().length() || (index < text().length() && (truncate_length_ == 0 || index < truncate_length_) && <API key>(text(), index)); } Rect RenderText::GetCursorBounds(const SelectionModel& caret, bool insert_mode) { // TODO(ckocagil): Support multiline. This function should return the height // of the line the cursor is on. |GetStringSize()| now returns // the multiline size, eliminate its use here. EnsureLayout(); size_t caret_pos = caret.caret_pos(); DCHECK(IsValidLogicalIndex(caret_pos)); // In overtype mode, ignore the affinity and always indicate that we will // overtype the next character. <API key> caret_affinity = insert_mode ? caret.caret_affinity() : CURSOR_FORWARD; int x = 0, width = 1; Size size = GetStringSize(); if (caret_pos == (caret_affinity == CURSOR_BACKWARD ? 0 : text().length())) { // The caret is attached to the boundary. Always return a 1-dip width caret, // since there is nothing to overtype. if ((GetTextDirection() == base::i18n::RIGHT_TO_LEFT) == (caret_pos == 0)) x = size.width(); } else { size_t grapheme_start = (caret_affinity == CURSOR_FORWARD) ? caret_pos : <API key>(caret_pos, CURSOR_BACKWARD); Range xspan(GetGlyphBounds(grapheme_start)); if (insert_mode) { x = (caret_affinity == CURSOR_BACKWARD) ? xspan.end() : xspan.start(); } else { // overtype mode x = xspan.GetMin(); width = xspan.length(); } } return Rect(ToViewPoint(Point(x, 0)), Size(width, size.height())); } const Rect& RenderText::<API key>() { <API key>(); return cursor_bounds_; } size_t RenderText::<API key>(size_t index, <API key> direction) { if (index > text().length()) return text().length(); EnsureLayout(); if (direction == CURSOR_FORWARD) { while (index < text().length()) { index++; if (IsValidCursorIndex(index)) return index; } return text().length(); } while (index > 0) { index if (IsValidCursorIndex(index)) return index; } return 0; } SelectionModel RenderText::<API key>() { const Range& sel = selection(); if (sel.is_empty()) return selection_model_; return SelectionModel(sel.start(), sel.is_reversed() ? CURSOR_BACKWARD : CURSOR_FORWARD); } const Vector2d& RenderText::<API key>() { <API key>(); return display_offset_; } void RenderText::SetDisplayOffset(int horizontal_offset) { const int extra_content = GetContentWidth() - display_rect_.width(); const int cursor_width = cursor_enabled_ ? 1 : 0; int min_offset = 0; int max_offset = 0; if (extra_content > 0) { switch (<API key>()) { case ALIGN_LEFT: min_offset = -extra_content; break; case ALIGN_RIGHT: max_offset = extra_content; break; case ALIGN_CENTER: // The extra space reserved for cursor at the end of the text is ignored // when centering text. So, to calculate the valid range for offset, we // exclude that extra space, calculate the range, and add it back to the // range (if cursor is enabled). min_offset = -(extra_content - cursor_width + 1) / 2 - cursor_width; max_offset = (extra_content - cursor_width) / 2; break; default: break; } } if (horizontal_offset < min_offset) horizontal_offset = min_offset; else if (horizontal_offset > max_offset) horizontal_offset = max_offset; <API key> = true; display_offset_.set_x(horizontal_offset); cursor_bounds_ = GetCursorBounds(selection_model_, insert_mode_); } RenderText::RenderText() : <API key>(base::i18n::IsRTL() ? ALIGN_RIGHT : ALIGN_LEFT), <API key>(<API key>), text_direction_(base::i18n::UNKNOWN_DIRECTION), cursor_enabled_(true), cursor_visible_(false), insert_mode_(true), cursor_color_(kDefaultColor), selection_color_(kDefaultColor), <API key>(<API key>), focused_(false), composition_range_(Range::InvalidRange()), colors_(kDefaultColor), styles_(NUM_TEXT_STYLES), <API key>(false), obscured_(false), <API key>(-1), truncate_length_(0), elide_behavior_(NO_ELIDE), <API key>(true), multiline_(false), <API key>(false), <API key>(true), baseline_(kInvalidBaseline), <API key>(false) { } SelectionModel RenderText::<API key>( const SelectionModel& current, BreakType break_type, <API key> direction) { EnsureLayout(); if (break_type == LINE_BREAK || text().empty()) return EdgeSelectionModel(direction); if (break_type == CHARACTER_BREAK) return <API key>(current, direction); DCHECK(break_type == WORD_BREAK); return <API key>(current, direction); } SelectionModel RenderText::EdgeSelectionModel( <API key> direction) { if (direction == <API key>()) return SelectionModel(text().length(), CURSOR_FORWARD); return SelectionModel(0, CURSOR_BACKWARD); } void RenderText::SetSelectionModel(const SelectionModel& model) { DCHECK_LE(model.selection().GetMax(), text().length()); selection_model_ = model; <API key> = false; } const base::string16& RenderText::GetLayoutText() const { return layout_text_; } const BreakList<size_t>& RenderText::GetLineBreaks() { if (line_breaks_.max() != 0) return line_breaks_; const base::string16& layout_text = GetLayoutText(); const size_t text_length = layout_text.length(); line_breaks_.SetValue(0); line_breaks_.SetMax(text_length); base::i18n::BreakIterator iter(layout_text, base::i18n::BreakIterator::BREAK_LINE); const bool success = iter.Init(); DCHECK(success); if (success) { do { line_breaks_.ApplyValue(iter.pos(), Range(iter.pos(), text_length)); } while (iter.Advance()); } return line_breaks_; } void RenderText::<API key>() { // Save the underline and color breaks to undo the temporary styles later. DCHECK(!<API key>); saved_colors_ = colors_; saved_underlines_ = styles_[UNDERLINE]; // Apply an underline to the composition range in |underlines|. if (composition_range_.IsValid() && !composition_range_.is_empty()) styles_[UNDERLINE].ApplyValue(true, composition_range_); // Apply the selected text color to the [un-reversed] selection range. if (!selection().is_empty() && focused()) { const Range range(selection().GetMin(), selection().GetMax()); colors_.ApplyValue(selection_color_, range); } <API key> = true; } void RenderText::<API key>() { // Restore the underline and color breaks to undo the temporary styles. DCHECK(<API key>); colors_ = saved_colors_; styles_[UNDERLINE] = saved_underlines_; <API key> = false; } Vector2d RenderText::GetLineOffset(size_t line_number) { Vector2d offset = display_rect().OffsetFromOrigin(); // TODO(ckocagil): Apply the display offset for multiline scrolling. if (!multiline()) offset.Add(<API key>()); else offset.Add(Vector2d(0, lines_[line_number].preceding_heights)); offset.Add(GetAlignmentOffset(line_number)); return offset; } Point RenderText::ToTextPoint(const Point& point) { return point - GetLineOffset(0); // TODO(ckocagil): Convert multiline view space points to text space. } Point RenderText::ToViewPoint(const Point& point) { if (!multiline()) return point + GetLineOffset(0); // TODO(ckocagil): Traverse individual line segments for RTL support. DCHECK(!lines_.empty()); int x = point.x(); size_t line = 0; for (; line < lines_.size() && x > lines_[line].size.width(); ++line) x -= lines_[line].size.width(); return Point(x, point.y()) + GetLineOffset(line); } std::vector<Rect> RenderText::<API key>(const Range& x) { std::vector<Rect> rects; if (!multiline()) { rects.push_back(Rect(ToViewPoint(Point(x.GetMin(), 0)), Size(x.length(), GetStringSize().height()))); return rects; } EnsureLayout(); // Each line segment keeps its position in text coordinates. Traverse all line // segments and if the segment intersects with the given range, add the view // rect corresponding to the intersection to |rects|. for (size_t line = 0; line < lines_.size(); ++line) { int line_x = 0; const Vector2d offset = GetLineOffset(line); for (size_t i = 0; i < lines_[line].segments.size(); ++i) { const internal::LineSegment* segment = &lines_[line].segments[i]; const Range intersection = segment->x_range.Intersect(x); if (!intersection.is_empty()) { Rect rect(line_x + intersection.start() - segment->x_range.start(), 0, intersection.length(), lines_[line].size.height()); rects.push_back(rect + offset); } line_x += segment->x_range.length(); } } return rects; } HorizontalAlignment RenderText::<API key>() { if (<API key> != ALIGN_TO_HEAD) return <API key>; return GetTextDirection() == base::i18n::RIGHT_TO_LEFT ? ALIGN_RIGHT : ALIGN_LEFT; } Vector2d RenderText::GetAlignmentOffset(size_t line_number) { // TODO(ckocagil): Enable |lines_| usage in other platforms. #if defined(OS_WIN) DCHECK_LT(line_number, lines_.size()); #endif Vector2d offset; HorizontalAlignment <API key> = <API key>(); if (<API key> != ALIGN_LEFT) { #if defined(OS_WIN) const int width = std::ceil(lines_[line_number].size.width()) + (cursor_enabled_ ? 1 : 0); #else const int width = GetContentWidth(); #endif offset.set_x(display_rect().width() - width); // Put any extra margin pixel on the left to match legacy behavior. if (<API key> == ALIGN_CENTER) offset.set_x((offset.x() + 1) / 2); } // Vertically center the text. if (multiline_) { const int text_height = lines_.back().preceding_heights + lines_.back().size.height(); offset.set_y((display_rect_.height() - text_height) / 2); } else { offset.set_y(GetBaseline() - <API key>()); } return offset; } void RenderText::ApplyFadeEffects(internal::SkiaTextRenderer* renderer) { const int width = display_rect().width(); if (multiline() || elide_behavior_ != FADE_TAIL || GetContentWidth() <= width) return; const int gradient_width = <API key>(font_list(), width); if (gradient_width == 0) return; HorizontalAlignment <API key> = <API key>(); Rect solid_part = display_rect(); Rect left_part; Rect right_part; if (<API key> != ALIGN_LEFT) { left_part = solid_part; left_part.Inset(0, 0, solid_part.width() - gradient_width, 0); solid_part.Inset(gradient_width, 0, 0, 0); } if (<API key> != ALIGN_RIGHT) { right_part = solid_part; right_part.Inset(solid_part.width() - gradient_width, 0, 0, 0); solid_part.Inset(0, 0, gradient_width, 0); } Rect text_rect = display_rect(); text_rect.Inset(GetAlignmentOffset(0).x(), 0, 0, 0); // TODO(msw): Use the actual text colors corresponding to each faded part. skia::RefPtr<SkShader> shader = CreateFadeShader( text_rect, left_part, right_part, colors_.breaks().front().second); if (shader) renderer->SetShader(shader.get()); } void RenderText::ApplyTextShadows(internal::SkiaTextRenderer* renderer) { skia::RefPtr<SkDrawLooper> looper = <API key>(shadows_); renderer->SetDrawLooper(looper.get()); } // static bool RenderText::RangeContainsCaret(const Range& range, size_t caret_pos, <API key> caret_affinity) { // NB: exploits unsigned wraparound (WG14/N1124 section 6.2.5 paragraph 9). size_t adjacent = (caret_affinity == CURSOR_BACKWARD) ? caret_pos - 1 : caret_pos + 1; return range.Contains(Range(caret_pos, adjacent)); } void RenderText::MoveCursorTo(size_t position, bool select) { size_t cursor = std::min(position, text().length()); if (IsValidCursorIndex(cursor)) SetSelectionModel(SelectionModel( Range(select ? selection().start() : cursor, cursor), (cursor == 0) ? CURSOR_FORWARD : CURSOR_BACKWARD)); } void RenderText::UpdateLayoutText() { layout_text_.clear(); line_breaks_.SetMax(0); if (obscured_) { size_t <API key> = static_cast<size_t>(UTF16IndexToOffset(text_, 0, text_.length())); layout_text_.assign(<API key>, <API key>); if (<API key> >= 0 && <API key> < static_cast<int>(text_.length())) { // Gets the index range in |text_| to be revealed. size_t start = <API key>; U16_SET_CP_START(text_.data(), 0, start); size_t end = start; UChar32 unused_char; U16_NEXT(text_.data(), end, text_.length(), unused_char); // Gets the index in |layout_text_| to be replaced. const size_t cp_start = static_cast<size_t>(UTF16IndexToOffset(text_, 0, start)); if (layout_text_.length() > cp_start) layout_text_.replace(cp_start, 1, text_.substr(start, end - start)); } } else { layout_text_ = text_; } const base::string16& text = layout_text_; if (truncate_length_ > 0 && truncate_length_ < text.length()) { // Truncate the text at a valid character break and append an ellipsis. icu::<API key> iter(text.c_str()); // Respect ELIDE_HEAD and ELIDE_MIDDLE preferences during truncation. if (elide_behavior_ == ELIDE_HEAD) { iter.setIndex32(text.length() - truncate_length_ + 1); layout_text_.assign(kEllipsisUTF16 + text.substr(iter.getIndex())); } else if (elide_behavior_ == ELIDE_MIDDLE) { iter.setIndex32(truncate_length_ / 2); const size_t ellipsis_start = iter.getIndex(); iter.setIndex32(text.length() - (truncate_length_ / 2)); const size_t ellipsis_end = iter.getIndex(); DCHECK_LE(ellipsis_start, ellipsis_end); layout_text_.assign(text.substr(0, ellipsis_start) + kEllipsisUTF16 + text.substr(ellipsis_end)); } else { iter.setIndex32(truncate_length_ - 1); layout_text_.assign(text.substr(0, iter.getIndex()) + kEllipsisUTF16); } } if (elide_behavior_ != NO_ELIDE && elide_behavior_ != FADE_TAIL && !layout_text_.empty() && GetContentWidth() > display_rect_.width()) { // This doesn't trim styles so ellipsis may get rendered as a different // style than the preceding text. See crbug.com/327850. layout_text_.assign(Elide(layout_text_, static_cast<float>(display_rect_.width()), elide_behavior_)); } // Replace the newline character with a newline symbol in single line mode. static const base::char16 kNewline[] = { '\n', 0 }; static const base::char16 kNewlineSymbol[] = { 0x2424, 0 }; if (!multiline_ && <API key>) base::ReplaceChars(layout_text_, kNewline, kNewlineSymbol, &layout_text_); ResetLayout(); } base::string16 RenderText::Elide(const base::string16& text, float available_width, ElideBehavior behavior) { if (available_width <= 0 || text.empty()) return base::string16(); if (behavior == ELIDE_EMAIL) return ElideEmail(text, available_width); // Create a RenderText copy with attributes that affect the rendering width. scoped_ptr<RenderText> render_text = <API key>(); render_text->SetFontList(font_list_); render_text-><API key>(<API key>); render_text->SetCursorEnabled(cursor_enabled_); render_text->set_truncate_length(truncate_length_); render_text->styles_ = styles_; render_text->colors_ = colors_; render_text->SetText(text); if (render_text->GetContentWidthF() <= available_width) return text; const base::string16 ellipsis = base::string16(kEllipsisUTF16); const bool insert_ellipsis = (behavior != TRUNCATE); const bool elide_in_middle = (behavior == ELIDE_MIDDLE); const bool elide_at_beginning = (behavior == ELIDE_HEAD); StringSlicer slicer(text, ellipsis, elide_in_middle, elide_at_beginning); render_text->SetText(ellipsis); const float ellipsis_width = render_text->GetContentWidthF(); if (insert_ellipsis && (ellipsis_width > available_width)) return base::string16(); // Use binary search to compute the elided text. size_t lo = 0; size_t hi = text.length() - 1; const base::i18n::TextDirection text_direction = GetTextDirection(); for (size_t guess = (lo + hi) / 2; lo <= hi; guess = (lo + hi) / 2) { // Restore colors. They will be truncated to size by SetText. render_text->colors_ = colors_; base::string16 new_text = slicer.CutString(guess, insert_ellipsis && behavior != ELIDE_TAIL); render_text->SetText(new_text); // This has to be an additional step so that the ellipsis is rendered with // same style as trailing part of the text. if (insert_ellipsis && behavior == ELIDE_TAIL) { // When ellipsis follows text whose directionality is not the same as that // of the whole text, it will be rendered with the directionality of the // whole text. Since we want ellipsis to indicate continuation of the // preceding text, we force the directionality of ellipsis to be same as // the preceding text using LTR or RTL markers. base::i18n::TextDirection <API key> = base::i18n::<API key>(new_text); new_text.append(ellipsis); if (<API key> != text_direction) { if (<API key> == base::i18n::LEFT_TO_RIGHT) new_text += base::i18n::kLeftToRightMark; else new_text += base::i18n::kRightToLeftMark; } render_text->SetText(new_text); } // Restore styles. Make sure style ranges don't break new text graphemes. render_text->styles_ = styles_; for (size_t style = 0; style < NUM_TEXT_STYLES; ++style) { BreakList<bool>& break_list = render_text->styles_[style]; break_list.SetMax(render_text->text_.length()); Range range; while (range.end() < break_list.max()) { BreakList<bool>::const_iterator current_break = break_list.GetBreak(range.end()); range = break_list.GetRange(current_break); if (range.end() < break_list.max() && !render_text->IsValidCursorIndex(range.end())) { range.set_end(render_text-><API key>(range.end(), CURSOR_FORWARD)); break_list.ApplyValue(current_break->second, range); } } } // We check the width of the whole desired string at once to ensure we // handle kerning/ligatures/etc. correctly. const float guess_width = render_text->GetContentWidthF(); if (guess_width == available_width) break; if (guess_width > available_width) { hi = guess - 1; // Move back on the loop terminating condition when the guess is too wide. if (hi < lo) lo = hi; } else { lo = guess + 1; } } return render_text->text(); } base::string16 RenderText::ElideEmail(const base::string16& email, float available_width) { // The returned string will have at least one character besides the ellipsis // on either side of '@'; if that's impossible, a single ellipsis is returned. // If possible, only the username is elided. Otherwise, the domain is elided // in the middle, splitting available width equally with the elided username. // If the username is short enough that it doesn't need half the available // width, the elided domain will occupy that extra width. // Split the email into its local-part (username) and domain-part. The email // spec allows for @ symbols in the username under some special requirements, // but not in the domain part, so splitting at the last @ symbol is safe. const size_t split_index = email.find_last_of('@'); DCHECK_NE(split_index, base::string16::npos); base::string16 username = email.substr(0, split_index); base::string16 domain = email.substr(split_index + 1); DCHECK(!username.empty()); DCHECK(!domain.empty()); // Subtract the @ symbol from the available width as it is mandatory. const base::string16 kAtSignUTF16 = base::ASCIIToUTF16("@"); available_width -= GetStringWidthF(kAtSignUTF16, font_list()); // Check whether eliding the domain is necessary: if eliding the username // is sufficient, the domain will not be elided. const float full_username_width = GetStringWidthF(username, font_list()); const float <API key> = available_width - std::min(full_username_width, GetStringWidthF(username.substr(0, 1) + kEllipsisUTF16, font_list())); if (GetStringWidthF(domain, font_list()) > <API key>) { // Elide the domain so that it only takes half of the available width. // Should the username not need all the width available in its half, the // domain will occupy the leftover width. // If |<API key>| is greater than |<API key>|: the // minimal username elision allowed by the specifications will not fit; thus // |<API key>| must be <= |<API key>| at all cost. const float <API key> = std::min<float>(<API key>, std::max<float>(available_width - full_username_width, available_width / 2)); domain = Elide(domain, <API key>, ELIDE_MIDDLE); // Failing to elide the domain such that at least one character remains // (other than the ellipsis itself) remains: return a single ellipsis. if (domain.length() <= 1U) return base::string16(kEllipsisUTF16); } // Fit the username in the remaining width (at this point the elided username // is guaranteed to fit with at least one character remaining given all the // precautions taken earlier). available_width -= GetStringWidthF(domain, font_list()); username = Elide(username, available_width, ELIDE_TAIL); return username + kAtSignUTF16 + domain; } void RenderText::<API key>() { if (<API key>) return; // TODO(ckocagil): Add support for scrolling multiline text. int delta_x = 0; if (cursor_enabled()) { // When cursor is enabled, ensure it is visible. For this, set the valid // flag true and calculate the current cursor bounds using the stale // |display_offset_|. Then calculate the change in offset needed to move the // cursor into the visible area. <API key> = true; cursor_bounds_ = GetCursorBounds(selection_model_, insert_mode_); // TODO(bidi): Show RTL glyphs at the cursor position for ALIGN_LEFT, etc. if (cursor_bounds_.right() > display_rect_.right()) delta_x = display_rect_.right() - cursor_bounds_.right(); else if (cursor_bounds_.x() < display_rect_.x()) delta_x = display_rect_.x() - cursor_bounds_.x(); } SetDisplayOffset(display_offset_.x() + delta_x); } void RenderText::DrawSelection(Canvas* canvas) { const std::vector<Rect> sel = GetSubstringBounds(selection()); for (std::vector<Rect>::const_iterator i = sel.begin(); i < sel.end(); ++i) canvas->FillRect(*i, <API key>); } } // namespace gfx
// modification, are permitted provided that the following conditions are // met: // documentation and/or other materials provided with the distribution. // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // 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 "IECore/NURBSPrimitive.h" #include "IECore/Renderer.h" #include "IECore/MurmurHash.h" using namespace std; using namespace IECore; using namespace Imath; using namespace boost; static IndexedIO::EntryID g_uOrderEntry("uOrder"); static IndexedIO::EntryID g_uKnotEntry("uKnot"); static IndexedIO::EntryID g_uMinEntry("uMin"); static IndexedIO::EntryID g_uMaxEntry("uMax"); static IndexedIO::EntryID g_vOrderEntry("vOrder"); static IndexedIO::EntryID g_vKnotEntry("vKnot"); static IndexedIO::EntryID g_vMinEntry("vMin"); static IndexedIO::EntryID g_vMaxEntry("vMax"); const unsigned int NURBSPrimitive::m_ioVersion = 0; <API key>(NURBSPrimitive); NURBSPrimitive::NURBSPrimitive() { vector<float> knot; knot.push_back( 0 ); knot.push_back( 0 ); knot.push_back( 0 ); knot.push_back( 0.333 ); knot.push_back( 0.666 ); knot.push_back( 1 ); knot.push_back( 1 ); knot.push_back( 1 ); setTopology( 4, new FloatVectorData( knot ), 0, 1, 4, new FloatVectorData( knot ), 0, 1 ); } NURBSPrimitive::NURBSPrimitive( int uOrder, <API key> uKnot, float uMin, float uMax, int vOrder, <API key> vKnot, float vMin, float vMax, <API key> p ) { setTopology( uOrder, uKnot, uMin, uMax, vOrder, vKnot, vMin, vMax ); if( p ) { V3fVectorDataPtr pData = p->copy(); pData->setInterpretation( GeometricData::Point ); variables.insert( <API key>::value_type( "P", PrimitiveVariable( PrimitiveVariable::Vertex, pData ) ) ); } } int NURBSPrimitive::uOrder() const { return m_uOrder; } const FloatVectorData *NURBSPrimitive::uKnot() const { return m_uKnot.get(); } float NURBSPrimitive::uMin() const { return m_uMin; } float NURBSPrimitive::uMax() const { return m_uMax; } int NURBSPrimitive::uVertices() const { return m_uKnot->readable().size() - m_uOrder; } int NURBSPrimitive::uSegments() const { return 1 + uVertices() - m_uOrder; } int NURBSPrimitive::vOrder() const { return m_vOrder; } const FloatVectorData *NURBSPrimitive::vKnot() const { return m_vKnot.get(); } float NURBSPrimitive::vMin() const { return m_vMin; } float NURBSPrimitive::vMax() const { return m_vMax; } int NURBSPrimitive::vVertices() const { return m_vKnot->readable().size() - m_vOrder; } int NURBSPrimitive::vSegments() const { return 1 + vVertices() - m_vOrder; } void NURBSPrimitive::setTopology( int uOrder, <API key> uKnot, float uMin, float uMax, int vOrder, <API key> vKnot, float vMin, float vMax ) { // check order isn't too small if( uOrder<2 ) { throw Exception( "Order in u direction too small." ); } if( vOrder<2 ) { throw Exception( "Order in v direction too small." ); } // check knots have enough entries for the order. // an order of N demands at least N control points // and numKnots==numControlPoints + order // so we need numKnots>=2*order if( (int)uKnot->readable().size() < uOrder * 2 ) { throw Exception( "Not enough knot values in u direction." ); } if( (int)vKnot->readable().size() < vOrder * 2 ) { throw Exception( "Not enough knot values in v direction." ); } // check knots are monotonically increasing const vector<float> &u = uKnot->readable(); float previous = u[0]; for( unsigned int i=0; i<u.size(); i++ ) { if( u[i]<previous ) { throw Exception( "Knots not monotonically increasing in u direction." ); } previous = u[i]; } const vector<float> &v = vKnot->readable(); previous = v[0]; for( unsigned int i=0; i<v.size(); i++ ) { if( v[i]<previous ) { throw Exception( "Knots not monotonically increasing in v direction." ); } previous = v[i]; } // check min and max parametric values are in range if( uMin > uMax ) { throw Exception( "uMin greater than uMax." ); } if( vMin > vMax ) { throw Exception( "vMin greater than vMax." ); } if( uMin < u[uOrder-2] ) { throw Exception( "uMin too small." ); } if( uMax > u[u.size()-uOrder+1] ) { throw Exception( "uMax too great." ); } if( vMin < v[vOrder-2] ) { throw Exception( "vMin too small." ); } if( vMax > v[v.size()-vOrder+1] ) { throw Exception( "vMax too great." ); } // set everything (taking copies of the data) m_uOrder = uOrder; m_uKnot = uKnot->copy(); m_uMin = uMin; m_uMax = uMax; m_vOrder = vOrder; m_vKnot = vKnot->copy(); m_vMin = vMin; m_vMax = vMax; } size_t NURBSPrimitive::variableSize( PrimitiveVariable::Interpolation interpolation ) const { switch( interpolation ) { case PrimitiveVariable::Constant : return 1; case PrimitiveVariable::Uniform : return uSegments() * vSegments(); case PrimitiveVariable::Vertex : return uVertices() * vVertices(); case PrimitiveVariable::Varying: case PrimitiveVariable::FaceVarying: return (uSegments()+1) * (vSegments()+1); default : return 0; } } void NURBSPrimitive::render( Renderer *renderer ) const { renderer->nurbs( m_uOrder, m_uKnot, m_uMin, m_uMax, m_vOrder, m_vKnot, m_vMin, m_vMax, variables ); } void NURBSPrimitive::copyFrom( const Object *other, IECore::Object::CopyContext *context ) { Primitive::copyFrom( other, context ); const NURBSPrimitive *tOther = static_cast<const NURBSPrimitive *>( other ); m_uOrder = tOther->m_uOrder; m_uKnot = context->copy<FloatVectorData>( tOther->m_uKnot ); m_uMin = tOther->m_uMin; m_uMax = tOther->m_uMax; m_vOrder = tOther->m_vOrder; m_vKnot = context->copy<FloatVectorData>( tOther->m_vKnot ); m_vMin = tOther->m_vMin; m_vMax = tOther->m_vMax; } void NURBSPrimitive::save( IECore::Object::SaveContext *context ) const { Primitive::save(context); IndexedIOPtr container = context->container( staticTypeName(), m_ioVersion ); container->write( g_uOrderEntry, m_uOrder ); context->save( m_uKnot, container, g_uKnotEntry ); container->write( g_uMinEntry, m_uMin ); container->write( g_uMaxEntry, m_uMax ); container->write( g_vOrderEntry, m_vOrder ); context->save( m_vKnot, container, g_vKnotEntry ); container->write( g_vMinEntry, m_vMin ); container->write( g_vMaxEntry, m_vMax ); } void NURBSPrimitive::load( IECore::Object::LoadContextPtr context ) { Primitive::load(context); unsigned int v = m_ioVersion; ConstIndexedIOPtr container = context->container( staticTypeName(), v ); container->read( g_uOrderEntry, m_uOrder ); m_uKnot = context->load<FloatVectorData>( container, g_uKnotEntry ); container->read( g_uMinEntry, m_uMin ); container->read( g_uMaxEntry, m_uMax ); container->read( g_vOrderEntry, m_vOrder ); m_vKnot = context->load<FloatVectorData>( container, g_vKnotEntry ); container->read( g_vMinEntry, m_vMin ); container->read( g_vMaxEntry, m_vMax ); } bool NURBSPrimitive::isEqualTo( const Object *other ) const { if( !Primitive::isEqualTo( other ) ) { return false; } const NURBSPrimitive *tOther = static_cast<const NURBSPrimitive *>( other ); if( m_uOrder!=tOther->m_uOrder ) { return false; } if( m_vOrder!=tOther->m_vOrder ) { return false; } if( m_uMin!=tOther->m_uMin ) { return false; } if( m_vMin!=tOther->m_vMin ) { return false; } if( m_uMax!=tOther->m_uMax ) { return false; } if( m_vMax!=tOther->m_vMax ) { return false; } if( !m_uKnot->isEqualTo( tOther->m_uKnot ) ) { return false; } if( !m_vKnot->isEqualTo( tOther->m_vKnot ) ) { return false; } return true; } void NURBSPrimitive::memoryUsage( Object::MemoryAccumulator &a ) const { Primitive::memoryUsage( a ); a.accumulate( sizeof( m_uOrder ) * 2 ); a.accumulate( sizeof( m_uMin ) * 4 ); a.accumulate( m_uKnot ); a.accumulate( m_vKnot ); } void NURBSPrimitive::hash( MurmurHash &h ) const { Primitive::hash( h ); } void NURBSPrimitive::topologyHash( MurmurHash &h ) const { h.append( m_uOrder ); m_uKnot->hash( h ); h.append( m_uMin ); h.append( m_uMax ); h.append( m_vOrder ); m_vKnot->hash( h ); h.append( m_vMin ); h.append( m_vMax ); }
.yui3-skin-sam .yui3-panel-content { -webkit-box-shadow: 0 0 5px #333; -moz-box-shadow: 0 0 5px #333; box-shadow: 0 0 5px #333; border: 1px solid black; background: white; } .yui3-skin-sam .yui3-panel .yui3-widget-hd { padding: 8px 28px 8px 8px; /* Room for close button. */ min-height: 13px; /* For the close button */ _height: 13px; /* IE6 */ color: white; background-color: #3961c5; background: -moz-linear-gradient( 0% 100% 90deg, #2647a0 7%, #3d67ce 50%, #426fd9 100% ); background: -webkit-gradient( linear, left bottom, left top, from(#2647a0), color-stop(0.07, #2647a0), color-stop(0.5, #3d67ce), to(#426fd9) ); /* TODO: Add support for IE and W3C gradients */ } .yui3-skin-sam .yui3-panel .yui3-widget-hd .yui3-widget-buttons { padding: 8px; } .yui3-skin-sam .yui3-panel .yui3-widget-bd { padding: 10px; } .yui3-skin-sam .yui3-panel .yui3-widget-ft { background: #EDF5FF; padding: 8px; text-align: right; } .yui3-skin-sam .yui3-panel .yui3-widget-ft .yui3-button { margin-left: 8px; } .yui3-skin-sam .yui3-panel .yui3-widget-hd .yui3-button-close { /* Reset base button styles */ background: transparent; filter: none; border: none; -<API key>: 0; -moz-border-radius: 0; border-radius: 0; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; /* Structure */ width: 13px; height: 13px; padding: 0; overflow: hidden; vertical-align: top; /* IE < 8 :( */ *font-size: 0; *line-height: 0; *letter-spacing: -1000px; *color: #86A5EC; *background: url(sprite_icons.png) no-repeat 1px 1px; } .yui3-skin-sam .yui3-panel .yui3-widget-hd .yui3-button-close:before { /* Displays the [x] icon in place of the "Close" text. Note: The `width` of this pseudo element is the same as its "host" element. */ content: url(sprite_icons.png); display: inline-block; text-align: center; font-size: 0; line-height: 0; width: 13px; margin: 1px 0 0 1px; } .yui3-skin-sam .yui3-panel-hidden .yui3-widget-hd .yui3-button-close { /* Required for IE > 7 to deal with pseudo :before element */ display: none; }
--TEST Test <API key>() function : usage variations - common key and value(Bug#43559) --FILE <?php /* Prototype : array <API key>(array $arr1[, array $...]) * Description: Recursively merges elements from passed arrays into one array * Source code: ext/standard/array.c */ /* * Testing the functionality of <API key>() by passing * arrays having common key and value. */ echo "*** Testing <API key>() : arrays with common key and value ***\n"; /* initialize the array having duplicate values */ // integer values $arr1 = array("a" => 1, "b" => 2); $arr2 = array("b" => 2, "c" => 4); echo "-- Integer values --\n"; var_dump( <API key>($arr1, $arr2) ); // float values $arr1 = array("a" => 1.1, "b" => 2.2); $arr2 = array("b" => 2.2, "c" => 3.3); echo "-- Float values --\n"; var_dump( <API key>($arr1, $arr2) ); // string values $arr1 = array("a" => "hello", "b" => "world"); $arr2 = array("b" => "world", "c" => "string"); echo "-- String values --\n"; var_dump( <API key>($arr1, $arr2) ); // boolean values $arr1 = array("a" => true, "b" => false); $arr2 = array("b" => false); echo "-- Boolean values --\n"; var_dump( <API key>($arr1, $arr2) ); // null values $arr1 = array( "a" => NULL); $arr2 = array( "a" => NULL); echo "-- Null values --\n"; var_dump( <API key>($arr1, $arr2) ); echo "Done"; ?> --EXPECTF *** Testing <API key>() : arrays with common key and value *** -- Integer values -- array(3) { ["a"]=> int(1) ["b"]=> array(2) { [0]=> int(2) [1]=> int(2) } ["c"]=> int(4) } -- Float values -- array(3) { ["a"]=> float(1.1) ["b"]=> array(2) { [0]=> float(2.2) [1]=> float(2.2) } ["c"]=> float(3.3) } -- String values -- array(3) { ["a"]=> string(5) "hello" ["b"]=> array(2) { [0]=> string(5) "world" [1]=> string(5) "world" } ["c"]=> string(6) "string" } -- Boolean values -- array(2) { ["a"]=> bool(true) ["b"]=> array(2) { [0]=> bool(false) [1]=> bool(false) } } -- Null values -- array(1) { ["a"]=> array(2) { [0]=> NULL [1]=> NULL } } Done
require 'optparse' require 'uri' require 'puma/server' require 'puma/const' require 'puma/configuration' require 'puma/binder' require 'puma/detect' require 'puma/daemon_ext' require 'puma/util' require 'puma/single' require 'puma/cluster' require 'puma/commonlogger' module Puma class << self # The CLI exports its Puma::Configuration object here to allow # apps to pick it up. An app needs to use it conditionally though # since it is not set if the app is launched via another # mechanism than the CLI class. attr_accessor :cli_config end # Handles invoke a Puma::Server in a command line style. class CLI # Create a new CLI object using +argv+ as the command line # arguments. # +stdout+ and +stderr+ can be set to IO-like objects which # this object will report status on. def initialize(argv, events=Events.stdio) @debug = false @argv = argv @events = events @status = nil @runner = nil @config = nil ENV['NEWRELIC_DISPATCHER'] ||= "Puma" setup_options <API key> @binder = Binder.new(@events) @binder.import_from_env end # The Binder object containing the sockets bound to. attr_reader :binder # The Configuration object used. attr_reader :config # The Hash of options used to configure puma. attr_reader :options # The Events object used to output information. attr_reader :events # Delegate +log+ to +@events+ def log(str) @events.log str end # Delegate +error+ to +@events+ def error(str) @events.error str end def debug(str) @events.log "- #{str}" if @options[:debug] end def clustered? @options[:workers] > 0 end def prune_bundler? @options[:prune_bundler] && clustered? && !@options[:preload_app] end def jruby? IS_JRUBY end def windows? RUBY_PLATFORM =~ /mswin32|ming32/ end def env @options[:environment] || ENV['RACK_ENV'] || 'development' end def write_state write_pid path = @options[:state] return unless path state = { 'pid' => Process.pid } cfg = @config.dup [ :logger, :<API key>, :before_worker_boot, :before_worker_fork, :after_worker_boot, :on_restart, :<API key> ].each { |k| cfg.options.delete(k) } state['config'] = cfg require 'yaml' File.open(path, 'w') { |f| f.write state.to_yaml } end # If configured, write the pid of the current process out # to a file. def write_pid path = @options[:pidfile] return unless path File.open(path, 'w') { |f| f.puts Process.pid } cur = Process.pid at_exit do delete_pidfile if cur == Process.pid end end def delete_pidfile path = @options[:pidfile] File.unlink(path) if path && File.exist?(path) end def graceful_stop @runner.stop_blocked log "=== puma shutdown: log "- Goodbye!" end def jruby_daemon_start require 'puma/jruby_restart' JRubyRestart.daemon_start(@restart_dir, restart_args) end def restart! @options[:on_restart].each do |block| block.call self end if jruby? <API key> require 'puma/jruby_restart' JRubyRestart.chdir_exec(@restart_dir, restart_args) elsif windows? <API key> argv = restart_args Dir.chdir(@restart_dir) argv += [redirects] if RUBY_VERSION >= '1.9' Kernel.exec(*argv) else redirects = {:close_others => true} @binder.listeners.each_with_index do |(l, io), i| ENV["PUMA_INHERIT_#{i}"] = "#{io.to_i}:#{l}" redirects[io.to_i] = io.to_i end argv = restart_args Dir.chdir(@restart_dir) argv += [redirects] if RUBY_VERSION >= '1.9' Kernel.exec(*argv) end end # Parse the options, load the rackup, start the server and wait # for it to finish. def run begin parse_options rescue UnsupportedOption exit 1 end dir = @options[:directory] Dir.chdir(dir) if dir prune_bundler if prune_bundler? <API key> if clustered? @events.formatter = Events::PidFormatter.new @options[:logger] = @events @runner = Cluster.new(self) else @runner = Single.new(self) end setup_signals set_process_title @status = :run @runner.run case @status when :halt log "* Stopping immediately!" when :run, :stop graceful_stop when :restart log "* Restarting..." @runner.before_restart restart! when :exit # nothing end end def stop @status = :stop @runner.stop end def restart @status = :restart @runner.restart end def <API key> @runner.<API key> if @runner.respond_to?(:<API key>) end def phased_restart unless @runner.respond_to?(:phased_restart) and @runner.phased_restart log "* phased-restart called but not available, restarting normally." return restart end true end def redirect_io @runner.redirect_io end def stats @runner.stats end def halt @status = :halt @runner.halt end private def title buffer = "puma #{Puma::Const::VERSION} (#{@options[:binds].join(',')})" buffer << " [#{@options[:tag]}]" if @options[:tag] buffer end def unsupported(str) @events.error(str) raise UnsupportedOption end def restart_args cmd = @options[:restart_cmd] if cmd cmd.split(' ') + @original_argv else @restart_argv end end def set_process_title Process.respond_to?(:setproctitle) ? Process.setproctitle(title) : $0 = title end def find_config if @options[:config_file] == '-' @options[:config_file] = nil else @options[:config_file] ||= %W(config/puma/#{env}.rb config/puma.rb).find { |f| File.exist?(f) } end end # Build the OptionParser object to handle the available options. def setup_options @options = { :min_threads => 0, :max_threads => 16, :quiet => false, :debug => false, :binds => [], :workers => 0, :daemon => false, :<API key> => [], :before_worker_boot => [], :before_worker_fork => [], :after_worker_boot => [] } @parser = OptionParser.new do |o| o.on "-b", "--bind URI", "URI to bind to (tcp://, unix://, ssl://)" do |arg| @options[:binds] << arg end o.on "-C", "--config PATH", "Load PATH as a config file" do |arg| @options[:config_file] = arg end o.on "--control URL", "The bind url to use for the control server", "Use 'auto' to use temp unix server" do |arg| if arg @options[:control_url] = arg elsif jruby? unsupported "No default url available on JRuby" end end o.on "--control-token TOKEN", "The token to use as authentication for the control server" do |arg| @options[:control_auth_token] = arg end o.on "-d", "--daemon", "Daemonize the server into the background" do @options[:daemon] = true @options[:quiet] = true end o.on "--debug", "Log lowlevel debugging information" do @options[:debug] = true end o.on "--dir DIR", "Change to DIR before starting" do |d| @options[:directory] = d.to_s @options[:worker_directory] = d.to_s end o.on "-e", "--environment ENVIRONMENT", "The environment to run the Rack app on (default development)" do |arg| @options[:environment] = arg end o.on "-I", "--include PATH", "Specify $LOAD_PATH directories" do |arg| $LOAD_PATH.unshift(*arg.split(':')) end o.on "-p", "--port PORT", "Define the TCP port to bind to", "Use -b for more advanced options" do |arg| @options[:binds] << "tcp://#{Configuration::DefaultTCPHost}:#{arg}" end o.on "--pidfile PATH", "Use PATH as a pidfile" do |arg| @options[:pidfile] = arg end o.on "--preload", "Preload the app. Cluster mode only" do @options[:preload_app] = true end o.on "--prune-bundler", "Prune out the bundler env if possible" do @options[:prune_bundler] = true end o.on "-q", "--quiet", "Quiet down the output" do @options[:quiet] = true end o.on "-R", "--restart-cmd CMD", "The puma command to run during a hot restart", "Default: inferred" do |cmd| @options[:restart_cmd] = cmd end o.on "-S", "--state PATH", "Where to store the state details" do |arg| @options[:state] = arg end o.on '-t', '--threads INT', "min:max threads to use (default 0:16)" do |arg| min, max = arg.split(":") if max @options[:min_threads] = min @options[:max_threads] = max else @options[:min_threads] = 0 @options[:max_threads] = arg end end o.on "--tcp-mode", "Run the app in raw TCP mode instead of HTTP mode" do @options[:mode] = :tcp end o.on "-V", "--version", "Print the version information" do puts "puma version #{Puma::Const::VERSION}" exit 0 end o.on "-w", "--workers COUNT", "Activate cluster mode: How many worker processes to create" do |arg| @options[:workers] = arg.to_i end o.on "--tag NAME", "Additional text to display in process listing" do |arg| @options[:tag] = arg end o.banner = "puma <options> <rackup file>" o.on_tail "-h", "--help", "Show help" do log o exit 0 end end end def <API key> # Use the same trick as unicorn, namely favor PWD because # it will contain an unresolved symlink, useful for when # the pwd is /data/releases/current. if dir = ENV['PWD'] s_env = File.stat(dir) s_pwd = File.stat(Dir.pwd) if s_env.ino == s_pwd.ino and (jruby? or s_env.dev == s_pwd.dev) @restart_dir = dir @options[:worker_directory] = dir end end @restart_dir ||= Dir.pwd @original_argv = @argv.dup require 'rubygems' # if $0 is a file in the current directory, then restart # it the same, otherwise add -S on there because it was # picked up in PATH. if File.exist?($0) arg0 = [Gem.ruby, $0] else arg0 = [Gem.ruby, "-S", $0] end # Detect and reinject -Ilib from the command line lib = File.expand_path "lib" arg0[1,0] = ["-I", lib] if $:[0] == lib if defined? Puma::WILD_ARGS @restart_argv = arg0 + Puma::WILD_ARGS + @original_argv else @restart_argv = arg0 + @original_argv end end def <API key> @options[:environment] = env ENV['RACK_ENV'] = env end def setup_signals begin Signal.trap "SIGUSR2" do restart end rescue Exception log "*** SIGUSR2 not implemented, signal based restart unavailable!" end begin Signal.trap "SIGUSR1" do phased_restart end rescue Exception log "*** SIGUSR1 not implemented, signal based restart unavailable!" end begin Signal.trap "SIGTERM" do stop end rescue Exception log "*** SIGTERM not implemented, signal based gracefully stopping unavailable!" end begin Signal.trap "SIGHUP" do redirect_io end rescue Exception log "*** SIGHUP not implemented, signal based logs reopening unavailable!" end if jruby? Signal.trap("INT") do @status = :exit graceful_stop exit end end end def <API key> @binder.listeners.each do |l, io| io.close uri = URI.parse(l) next unless uri.scheme == 'unix' File.unlink("#{uri.host}#{uri.path}") end end def parse_options @parser.parse! @argv @options[:rackup] = @argv.shift if @argv.last find_config @config = Puma::Configuration.new @options # Advertise the Configuration Puma.cli_config = @config @config.load if clustered? && (jruby? || windows?) unsupported 'worker mode not supported on JRuby or Windows' end if @options[:daemon] && windows? unsupported 'daemon mode not supported on Windows' end end def prune_bundler return unless defined?(Bundler) puma = Bundler.rubygems.loaded_specs("puma") dirs = puma.require_paths.map { |x| File.join(puma.full_gem_path, x) } puma_lib_dir = dirs.detect { |x| File.exist? File.join(x, '../bin/puma-wild') } unless puma_lib_dir log "! Unable to prune Bundler environment, continuing" return end deps = puma.<API key>.map do |d| spec = Bundler.rubygems.loaded_specs(d.name) "#{d.name}:#{spec.version.to_s}" end log '* Pruning Bundler environment' home = ENV['GEM_HOME'] Bundler.with_clean_env do ENV['GEM_HOME'] = home wild = File.expand_path(File.join(puma_lib_dir, "../bin/puma-wild")) args = [Gem.ruby, wild, '-I', dirs.join(':'), deps.join(',')] + @original_argv Kernel.exec(*args) end end end end
<?php namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Intl\Intl; use Symfony\Component\Locale\Locale; use Symfony\Component\OptionsResolver\<API key>; class LocaleType extends AbstractType { /** * {@inheritdoc} */ public function setDefaultOptions(<API key> $resolver) { $resolver->setDefaults(array( 'choices' => Intl::getLocaleBundle()->getLocaleNames(), )); } /** * {@inheritdoc} */ public function getParent() { return 'choice'; } /** * {@inheritdoc} */ public function getName() { return 'locale'; } }
KB.onClick('.accordion-toggle', function (e) { var sectionElement = KB.dom(e.target).parent('.accordion-section'); if (sectionElement) { KB.dom(sectionElement).toggleClass('accordion-collapsed'); } });
#include <config.h> #if defined(<API key>) #error "PHY not supported yet" /* We just assume that we are running 100FD for now */ /* We all use switches, right? ;-) */ #endif /* I assume ethernet behaves like au1000 */ #ifdef CONFIG_SOC_AU1000 /* Base address differ between cpu:s */ #define ETH0_BASE AU1000_ETH0_BASE #define MAC0_ENABLE AU1000_MAC0_ENABLE #else #ifdef CONFIG_SOC_AU1100 #define ETH0_BASE AU1100_ETH0_BASE #define MAC0_ENABLE AU1100_MAC0_ENABLE #else #ifdef CONFIG_SOC_AU1500 #define ETH0_BASE AU1500_ETH0_BASE #define MAC0_ENABLE AU1500_MAC0_ENABLE #else #ifdef CONFIG_SOC_AU1550 #define ETH0_BASE AU1550_ETH0_BASE #define MAC0_ENABLE AU1550_MAC0_ENABLE #else #error "No valid cpu set" #endif #endif #endif #endif #include <common.h> #include <malloc.h> #include <net.h> #include <command.h> #include <asm/io.h> #include <mach/au1x00.h> #if defined(CONFIG_CMD_MII) #include <miiphy.h> #endif /* Ethernet Transmit and Receive Buffers */ #define DBUF_LENGTH 1520 #define PKT_MAXBUF_SIZE 1518 static char txbuf[DBUF_LENGTH]; static int next_tx; static int next_rx; /* 4 rx and 4 tx fifos */ #define NO_OF_FIFOS 4 typedef struct{ u32 status; u32 addr; u32 len; /* Only used for tx */ u32 not_used; } mac_fifo_t; mac_fifo_t mac_fifo[NO_OF_FIFOS]; #define MAX_WAIT 1000 #if defined(CONFIG_CMD_MII) int au1x00_miiphy_read(struct mii_dev *bus, int addr, int devad, int reg) { unsigned short value = 0; volatile u32 *mii_control_reg = (volatile u32*)(ETH0_BASE+MAC_MII_CNTRL); volatile u32 *mii_data_reg = (volatile u32*)(ETH0_BASE+MAC_MII_DATA); u32 mii_control; unsigned int timedout = 20; while (*mii_control_reg & MAC_MII_BUSY) { udelay(1000); if (--timedout == 0) { printf("au1x00_eth: miiphy_read busy timeout!!\n"); return -1; } } mii_control = <API key>(reg) | <API key>(addr) | MAC_MII_READ; *mii_control_reg = mii_control; timedout = 20; while (*mii_control_reg & MAC_MII_BUSY) { udelay(1000); if (--timedout == 0) { printf("au1x00_eth: miiphy_read busy timeout!!\n"); return -1; } } value = *mii_data_reg; return value; } int au1x00_miiphy_write(struct mii_dev *bus, int addr, int devad, int reg, u16 value) { volatile u32 *mii_control_reg = (volatile u32*)(ETH0_BASE+MAC_MII_CNTRL); volatile u32 *mii_data_reg = (volatile u32*)(ETH0_BASE+MAC_MII_DATA); u32 mii_control; unsigned int timedout = 20; while (*mii_control_reg & MAC_MII_BUSY) { udelay(1000); if (--timedout == 0) { printf("au1x00_eth: miiphy_write busy timeout!!\n"); return -1; } } mii_control = <API key>(reg) | <API key>(addr) | MAC_MII_WRITE; *mii_data_reg = value; *mii_control_reg = mii_control; return 0; } #endif static int au1x00_send(struct eth_device *dev, void *packet, int length) { volatile mac_fifo_t *fifo_tx = (volatile mac_fifo_t*)(MAC0_TX_DMA_ADDR+MAC_TX_BUFF0_STATUS); int i; int res; /* tx fifo should always be idle */ fifo_tx[next_tx].len = length; fifo_tx[next_tx].addr = (virt_to_phys(packet))|TX_DMA_ENABLE; au_sync(); udelay(1); i=0; while(!(fifo_tx[next_tx].addr&TX_T_DONE)){ if(i>MAX_WAIT){ printf("TX timeout\n"); break; } udelay(1); i++; } /* Clear done bit */ fifo_tx[next_tx].addr = 0; fifo_tx[next_tx].len = 0; au_sync(); res = fifo_tx[next_tx].status; next_tx++; if(next_tx>=NO_OF_FIFOS){ next_tx=0; } return(res); } static int au1x00_recv(struct eth_device* dev){ volatile mac_fifo_t *fifo_rx = (volatile mac_fifo_t*)(MAC0_RX_DMA_ADDR+MAC_RX_BUFF0_STATUS); int length; u32 status; for(;;){ if(!(fifo_rx[next_rx].addr&RX_T_DONE)){ /* Nothing has been received */ return(-1); } status = fifo_rx[next_rx].status; length = status&0x3FFF; if(status&RX_ERROR){ printf("Rx error 0x%x\n", status); } else { /* Pass the packet up to the protocol layers. */ <API key>(net_rx_packets[next_rx], length - 4); } fifo_rx[next_rx].addr = (virt_to_phys(net_rx_packets[next_rx])) | RX_DMA_ENABLE; next_rx++; if(next_rx>=NO_OF_FIFOS){ next_rx=0; } } /* for */ return(0); /* Does anyone use this? */ } static int au1x00_init(struct eth_device* dev, bd_t * bd){ volatile u32 *macen = (volatile u32*)MAC0_ENABLE; volatile u32 *mac_ctrl = (volatile u32*)(ETH0_BASE+MAC_CONTROL); volatile u32 *mac_addr_high = (volatile u32*)(ETH0_BASE+MAC_ADDRESS_HIGH); volatile u32 *mac_addr_low = (volatile u32*)(ETH0_BASE+MAC_ADDRESS_LOW); volatile u32 *mac_mcast_high = (volatile u32*)(ETH0_BASE+MAC_MCAST_HIGH); volatile u32 *mac_mcast_low = (volatile u32*)(ETH0_BASE+MAC_MCAST_LOW); volatile mac_fifo_t *fifo_tx = (volatile mac_fifo_t*)(MAC0_TX_DMA_ADDR+MAC_TX_BUFF0_STATUS); volatile mac_fifo_t *fifo_rx = (volatile mac_fifo_t*)(MAC0_RX_DMA_ADDR+MAC_RX_BUFF0_STATUS); int i; next_tx = TX_GET_DMA_BUFFER(fifo_tx[0].addr); next_rx = RX_GET_DMA_BUFFER(fifo_rx[0].addr); /* We have to enable clocks before releasing reset */ *macen = MAC_EN_CLOCK_ENABLE; udelay(10); /* Enable MAC0 */ /* We have to release reset before accessing registers */ *macen = MAC_EN_CLOCK_ENABLE|MAC_EN_RESET0| MAC_EN_RESET1|MAC_EN_RESET2; udelay(10); for(i=0;i<NO_OF_FIFOS;i++){ fifo_tx[i].len = 0; fifo_tx[i].addr = virt_to_phys(&txbuf[0]); fifo_rx[i].addr = (virt_to_phys(net_rx_packets[i])) | RX_DMA_ENABLE; } /* Put mac addr in little endian */ #define ea eth_get_ethaddr() *mac_addr_high = (ea[5] << 8) | (ea[4] ) ; *mac_addr_low = (ea[3] << 24) | (ea[2] << 16) | (ea[1] << 8) | (ea[0] ) ; #undef ea *mac_mcast_low = 0; *mac_mcast_high = 0; /* Make sure the MAC buffer is in the correct endian mode */ #ifdef __LITTLE_ENDIAN *mac_ctrl = MAC_FULL_DUPLEX; udelay(1); *mac_ctrl = MAC_FULL_DUPLEX|MAC_RX_ENABLE|MAC_TX_ENABLE; #else *mac_ctrl = MAC_BIG_ENDIAN|MAC_FULL_DUPLEX; udelay(1); *mac_ctrl = MAC_BIG_ENDIAN|MAC_FULL_DUPLEX|MAC_RX_ENABLE|MAC_TX_ENABLE; #endif return(1); } static void au1x00_halt(struct eth_device* dev){ volatile u32 *macen = (volatile u32*)MAC0_ENABLE; /* Put MAC0 in reset */ *macen = 0; } int <API key>(bd_t *bis){ struct eth_device* dev; if ((dev = (struct eth_device*)malloc(sizeof *dev)) == NULL) { puts ("malloc failed\n"); return -1; } memset(dev, 0, sizeof *dev); strcpy(dev->name, "Au1X00 ethernet"); dev->iobase = 0; dev->priv = 0; dev->init = au1x00_init; dev->halt = au1x00_halt; dev->send = au1x00_send; dev->recv = au1x00_recv; eth_register(dev); #if defined(CONFIG_CMD_MII) int retval; struct mii_dev *mdiodev = mdio_alloc(); if (!mdiodev) return -ENOMEM; strncpy(mdiodev->name, dev->name, MDIO_NAME_LEN); mdiodev->read = au1x00_miiphy_read; mdiodev->write = au1x00_miiphy_write; retval = mdio_register(mdiodev); if (retval < 0) return retval; #endif return 1; } int cpu_eth_init(bd_t *bis) { <API key>(bis); return 0; }
#import <Foundation/NSObject.h> @class NSNotification; @interface <API key> : NSObject { id _observer; SEL _selector; } - initWithObserver:object selector:(SEL)selector; - observer; - (void)postNotification:(NSNotification *)note; @end
#include "PolyCollisionScene.h" #include "<API key>.h" #include "PolyEntity.h" using namespace Polycode; CollisionScene::CollisionScene(Vector3 size, bool virtualScene, bool deferInitCollision) : Scene(Scene::SCENE_3D, virtualScene), world(NULL), <API key>(NULL), dispatcher(NULL), axisSweep(NULL) { if(!deferInitCollision) { initCollisionScene(size); } } void CollisionScene::initCollisionScene(Vector3 size) { btVector3 worldAabbMin(-size.x * 0.5, -size.y * 0.5, -size.z * 0.5); btVector3 worldAabbMax(size.x * 0.5, size.y * 0.5, size.z * 0.5); <API key> = new <API key>(); dispatcher = new <API key>(<API key>); // dispatcher->setNearCallback(customNearCallback); axisSweep = new btAxisSweep3(worldAabbMin,worldAabbMax); world = new btCollisionWorld(dispatcher,axisSweep,<API key>); } void CollisionScene::fixedUpdate() { for(int i=0; i < collisionChildren.size(); i++) { if(collisionChildren[i]->enabled) collisionChildren[i]->Update(); } world-><API key>(); for(int i=0; i < collisionChildren.size(); i++) { if(collisionChildren[i]->enabled) collisionChildren[i]->lastPosition = collisionChildren[i]->getEntity()->getPosition(); } Scene::fixedUpdate(); } void CollisionScene::enableCollision(Entity *entity, bool val) { CollisionEntity *cEnt = <API key>(entity); if(cEnt) { cEnt->enabled = val; } } void CollisionScene::adjustForCollision(CollisionEntity *collisionEntity) { CollisionResult result; // Number elapsed = CoreServices::getInstance()->getCore()->getElapsed(); result.collided = false; for(int i=0; i < collisionChildren.size(); i++) { if(collisionChildren[i] != collisionEntity) { result = <API key>(collisionEntity, collisionChildren[i]); if(result.collided) { if(result.setOldPosition) { collisionEntity->getEntity()->setPosition(result.newPos); } else { collisionEntity->getEntity()->Translate(result.colNormal.x*result.colDist, result.colNormal.y*result.colDist, result.colNormal.z*result.colDist); } } } } } CollisionEntity *CollisionScene::<API key>(Entity *ent) { for(int i=0; i<collisionChildren.size();i++) { if(collisionChildren[i]->getEntity() == ent) return collisionChildren[i]; } return NULL; } bool CollisionScene::isColliding(Entity *ent1) { CollisionEntity *cEnt1 = <API key>(ent1); if(cEnt1) { int numManifolds = world->getDispatcher()->getNumManifolds(); for (int i=0;i<numManifolds;i++) { <API key>* contactManifold = world->getDispatcher()-><API key>(i); btCollisionObject* obA = (btCollisionObject*)contactManifold->getBody0(); btCollisionObject* obB = (btCollisionObject*)contactManifold->getBody1(); if(obA == cEnt1->collisionObject || obB == cEnt1->collisionObject) { return true; } } } else { return false; } return false; } CollisionResult CollisionScene::<API key>(CollisionEntity *cEnt1, CollisionEntity *cEnt2) { CollisionResult result; result.collided = false; result.setOldPosition = false; Vector3 collNormal; result.colNormal.set(0,0,0); result.colDist = 0; int numAdds = 0; int numManifolds = world->getDispatcher()->getNumManifolds(); for (int i=0;i<numManifolds;i++) { <API key>* contactManifold = world->getDispatcher()-><API key>(i); btCollisionObject* obA = (btCollisionObject*)contactManifold->getBody0(); btCollisionObject* obB = (btCollisionObject*)contactManifold->getBody1(); if((obA == cEnt1->collisionObject && obB == cEnt2->collisionObject) || (obA == cEnt2->collisionObject && obB == cEnt1->collisionObject)) { // contactManifold-><API key>(obA->getWorldTransform(), obB->getWorldTransform()); if(contactManifold->getNumContacts() > 0) { for(int j=0; j < contactManifold->getNumContacts(); j++) { if(contactManifold->getContactPoint(j).getDistance() <= btScalar(0.0)) { btVector3 vec = contactManifold->getContactPoint(j).m_normalWorldOnB; result.colNormal += Vector3(vec.getX(), vec.getY(), vec.getZ()); result.colDist += contactManifold->getContactPoint(j).getDistance(); numAdds++; } } // btVector3 vec = contactManifold->getContactPoint(0).m_normalWorldOnB; // result.colNormal.set(vec.getX(), vec.getY(), vec.getZ()); // result.colDist = contactManifold->getContactPoint(0).getDistance(); result.collided = true; } } } if(numAdds > 0) { result.colNormal = result.colNormal / (Number)numAdds; // result.colNormal = Vector3(0,1,0); // result.colNormal.Normalize(); result.colDist = result.colDist / (Number)numAdds; } return result; // return cEnt1->collisionObject->checkCollideWith(cEnt2->collisionObject); } RayTestResult CollisionScene::getFirstEntityInRay(const Vector3 &origin, const Vector3 &dest) { RayTestResult ret; ret.entity = NULL; btVector3 fromVec(origin.x, origin.y, origin.z); btVector3 toVec(dest.x, dest.y, dest.z); btCollisionWorld::<API key> cb(fromVec, toVec); world->rayTest (fromVec, toVec, cb); if (cb.hasHit ()) { CollisionEntity *retEnt = <API key>((btCollisionObject*)cb.m_collisionObject); if(retEnt) { ret.entity = retEnt->getEntity(); ret.position = Vector3(cb.m_hitPointWorld.getX(), cb.m_hitPointWorld.getY(), cb.m_hitPointWorld.getZ()); ret.normal = Vector3(cb.m_hitNormalWorld.getX(), cb.m_hitNormalWorld.getY(), cb.m_hitNormalWorld.getZ()); return ret; } } return ret; } CollisionEntity *CollisionScene::<API key>(btCollisionObject *collisionObject) { return (CollisionEntity*)collisionObject->getUserPointer(); } CollisionResult CollisionScene::<API key>(CollisionEntity *cEnt1, CollisionEntity *cEnt2) { return <API key>(cEnt1, cEnt2); } CollisionResult CollisionScene::testCollision(Entity *ent1, Entity *ent2) { CollisionEntity *cEnt1 = <API key>(ent1); CollisionEntity *cEnt2 = <API key>(ent2); CollisionResult result; result.collided = false; if(cEnt1 == NULL || cEnt2 == NULL) return result; return <API key>(cEnt1, cEnt2); } CollisionScene::~CollisionScene() { for(int i=0; i < collisionChildren.size(); i++) { delete collisionChildren[i]; } delete world; delete axisSweep; delete dispatcher; delete <API key>; } void CollisionScene::removeCollision(Entity *entity) { CollisionEntity *cEnt = <API key>(entity); if(cEnt) { world-><API key>(cEnt->collisionObject); for(int i=0; i < collisionChildren.size(); i++) { if(collisionChildren[i] == cEnt) { std::vector<CollisionEntity*>::iterator target = collisionChildren.begin()+i; delete *target; collisionChildren.erase(target); } } } } void CollisionScene::removeEntity(Entity *entity) { if(<API key>(entity)) { removeCollision(entity); } Scene::removeEntity(entity); } CollisionEntity *CollisionScene::trackCollision(Entity *newEntity, int type, int group) { CollisionEntity *newCollisionEntity = new CollisionEntity(newEntity, type); // if(type == CollisionEntity::<API key>) { // world->addCollisionObject(newCollisionEntity->collisionObject,btBroadphaseProxy::CharacterFilter, btBroadphaseProxy::StaticFilter|btBroadphaseProxy::DefaultFilter); // } else { newCollisionEntity->collisionObject->setCollisionFlags(btCollisionObject::<API key>); world->addCollisionObject(newCollisionEntity->collisionObject, group); collisionChildren.push_back(newCollisionEntity); return newCollisionEntity; } CollisionEntity *CollisionScene::addCollisionChild(Entity *newEntity, int type, int group) { addEntity(newEntity); return trackCollision(newEntity, type, group); }
#ifndef __util_h__ #define __util_h__ #define <API key> // So we can use the PAL_TRY_NAKED family of macros without dependencies on utilcode. inline void <API key>() {} #include <cor.h> #include <corsym.h> #include <clrdata.h> #include <palclr.h> #include <metahost.h> #include <new> #if !defined(FEATURE_PAL) #include <dia2.h> #endif #ifdef STRIKE #if defined(_MSC_VER) #pragma warning(disable:4200) #pragma warning(default:4200) #endif #include "data.h" #endif //STRIKE #include "cordebug.h" #include "static_assert.h" typedef LPCSTR LPCUTF8; typedef LPSTR LPUTF8; DECLARE_HANDLE(OBJECTHANDLE); struct IMDInternalImport; #if defined(_TARGET_WIN64_) #define WIN64_8SPACES "" #define WIN86_8SPACES " " #define POINTERSIZE "16" #define POINTERSIZE_HEX 16 #define POINTERSIZE_BYTES 8 #define POINTERSIZE_TYPE "I64" #else #define WIN64_8SPACES " " #define WIN86_8SPACES "" #define POINTERSIZE "8" #define POINTERSIZE_HEX 8 #define POINTERSIZE_BYTES 4 #define POINTERSIZE_TYPE "I32" #endif #if defined(_MSC_VER) #pragma warning(disable:4510 4512 4610) #endif #ifndef _ASSERTE #ifdef _DEBUG #define _ASSERTE(expr) \ do { if (!(expr) ) { ExtErr("_ASSERTE fired:\n\t%s\n", #expr); if (IsDebuggerPresent()) DebugBreak(); } } while (0) #else #define _ASSERTE(x) #endif #endif // ASSERTE #ifdef _DEBUG #define ASSERT_CHECK(expr, msg, reason) \ do { if (!(expr) ) { ExtOut(reason); ExtOut(msg); ExtOut(#expr); DebugBreak(); } } while (0) #endif // PREFIX macros - Begin // SOS does not have support for Contracts. Therefore we needed to duplicate // some of the PREFIX infrastructure from inc\check.h in here. // Issue - PREFast_:510 v4.51 does not support __assume(0) #if (defined(_MSC_VER) && !defined(_PREFAST_)) || defined(_PREFIX_) #if defined(_AMD64_) // Empty methods that consist of UNREACHABLE() result in a zero-sized declspec(noreturn) method // which causes the pdb file to make the next method declspec(noreturn) as well, thus breaking BBT // Remove when we get a VC compiler that fixes VSW 449170 # define __UNREACHABLE() DebugBreak(); __assume(0); #else # define __UNREACHABLE() __assume(0) #endif #else #define __UNREACHABLE() do { } while(true) #endif #if defined(_PREFAST_) || defined(_PREFIX_) #define COMPILER_ASSUME_MSG(_condition, _message) if (!(_condition)) __UNREACHABLE(); #else #if defined(DACCESS_COMPILE) #define COMPILER_ASSUME_MSG(_condition, _message) do { } while (0) #else #if defined(_DEBUG) #define COMPILER_ASSUME_MSG(_condition, _message) \ ASSERT_CHECK(_condition, _message, "Compiler optimization assumption invalid") #else #define COMPILER_ASSUME_MSG(_condition, _message) __assume(_condition) #endif // _DEBUG #endif // DACCESS_COMPILE #endif // _PREFAST_ || _PREFIX_ #define PREFIX_ASSUME(_condition) \ COMPILER_ASSUME_MSG(_condition, "") // PREFIX macros - End class MethodTable; #define MD_NOT_YET_LOADED ((DWORD_PTR)-1) /* * HANDLES * * The default type of handle is a strong handle. * */ #define HNDTYPE_DEFAULT HNDTYPE_STRONG #define <API key> HNDTYPE_WEAK_LONG #define HNDTYPE_WEAK_SHORT (0) #define HNDTYPE_WEAK_LONG (1) #define HNDTYPE_STRONG (2) #define HNDTYPE_PINNED (3) #define HNDTYPE_VARIABLE (4) #define HNDTYPE_REFCOUNTED (5) #define HNDTYPE_DEPENDENT (6) #define HNDTYPE_ASYNCPINNED (7) #define HNDTYPE_SIZEDREF (8) #define HNDTYPE_WEAK_WINRT (9) // Anything above this we consider abnormal and stop processing heap information const int <API key> = 1000; class BaseObject { MethodTable *m_pMethTab; }; const BYTE gElementTypeInfo[] = { #define TYPEINFO(e,ns,c,s,g,ia,ip,if,im,gv) s, #include "cortypeinfo.h" #undef TYPEINFO }; typedef struct tagLockEntry { tagLockEntry *pNext; // next entry tagLockEntry *pPrev; // prev entry DWORD dwULockID; DWORD dwLLockID; // owning lock WORD wReaderLevel; // reader nesting level } LockEntry; #define <API key> 1024 enum EEFLAVOR {UNKNOWNEE, MSCOREE, MSCORWKS, MSCOREND}; #include "sospriv.h" extern IXCLRDataProcess *g_clrData; extern ISOSDacInterface *g_sos; #include "dacprivate.h" interface ICorDebugProcess; extern ICorDebugProcess * g_pCorDebugProcess; // This class is templated for easy modification. We may need to update the CachedString // or related classes to use WCHAR instead of char in the future. template <class T, int count, int size> class StaticData { public: StaticData() { for (int i = 0; i < count; ++i) InUse[i] = false; } // Whether the individual data pointers in the cache are in use. bool InUse[count]; // The actual data itself. T Data[count][size]; // The number of arrays in the cache. static const int Count; // The size of each individual array. static const int Size; }; class CachedString { public: CachedString(); CachedString(const CachedString &str); ~CachedString(); const CachedString &operator=(const CachedString &str); // Returns the capacity of this string. size_t GetStrLen() const { return mSize; } // Returns a mutable character pointer. Be sure not to write past the // length of this string. inline operator char *() { return mPtr; } // Returns a const char representation of this string. inline operator const char *() const { return GetPtr(); } // To ensure no AV's, any time a constant pointer is requested, we will // return an empty string "" if we hit an OOM. This will only happen // if we hit an OOM and do not check for it before using the string. // If you request a non-const char pointer out of this class, it may be // null (see operator char *). inline const char *GetPtr() const { if (!mPtr || IsOOM()) return ""; return mPtr; } // Returns true if we ran out of memory trying to allocate the string // or the refcount. bool IsOOM() const { return mIndex == -2; } // allocate a string of the specified size. this will Clear() any // previously allocated string. call IsOOM() to check for failure. void Allocate(int size); private: // Copies rhs into this string. void Copy(const CachedString &rhs); // Clears this string, releasing any underlying memory. void Clear(); // Creates a new string. void Create(); // Sets an out of memory state. void SetOOM(); private: char *mPtr; // The reference count. This may be null if there is only one copy // of this string. mutable unsigned int *mRefCount; // mIndex contains the index of the cached pointer we are using, or: // ~0 - poison value we initialize it to for debugging purposes // -1 - mPtr points to a pointer we have new'ed // -2 - We hit an oom trying to allocate either mCount or mPtr int mIndex; // contains the size of current string int mSize; private: static StaticData<char, 4, 1024> cache; }; // Things in this namespace should not be directly accessed/called outside of // the output-related functions. namespace Output { extern unsigned int g_bSuppressOutput; extern unsigned int g_Indent; extern unsigned int g_DMLEnable; extern bool g_bDbgOutput; extern bool g_bDMLExposed; inline bool IsOutputSuppressed() { return g_bSuppressOutput > 0; } inline void ResetIndent() { g_Indent = 0; } inline void <API key>(bool enabled) { g_bDbgOutput = enabled; } inline bool <API key>() { return g_bDbgOutput; } inline void SetDMLExposed(bool exposed) { g_bDMLExposed = exposed; } inline bool IsDMLExposed() { return g_bDMLExposed; } enum FormatType { DML_None, DML_MethodTable, DML_MethodDesc, DML_EEClass, DML_Module, DML_IP, DML_Object, DML_Domain, DML_Assembly, DML_ThreadID, DML_ValueClass, DML_DumpHeapMT, DML_ListNearObj, DML_ThreadState, DML_PrintException, DML_RCWrapper, DML_CCWrapper, DML_ManagedVar, }; CachedString BuildVCValue(CLRDATA_ADDRESS mt, CLRDATA_ADDRESS addr, FormatType type, bool fill = true); CachedString BuildHexValue(CLRDATA_ADDRESS addr, FormatType type, bool fill = true); CachedString <API key>(__in_z LPCWSTR expansionName, ULONG frame, __in_z LPCWSTR simpleName, FormatType type); CachedString <API key>(__in_z LPCWSTR expansionName, ULONG frame, int indexInArray, FormatType type); //used for array indices (simpleName = "[<indexInArray>]") } class NoOutputHolder { public: NoOutputHolder(BOOL bSuppress = TRUE); ~NoOutputHolder(); private: BOOL mSuppress; }; class EnableDMLHolder { public: EnableDMLHolder(BOOL enable); ~EnableDMLHolder(); private: BOOL mEnable; }; size_t CountHexCharacters(CLRDATA_ADDRESS val); // Normal output. void DMLOut(PCSTR format, ...); /* Prints out DML strings. */ void IfDMLOut(PCSTR format, ...); /* Prints given DML string ONLY if DML is enabled; prints nothing otherwise. */ void ExtOut(PCSTR Format, ...); /* Prints out to ExtOut (no DML). */ void ExtWarn(PCSTR Format, ...); /* Prints out to ExtWarn (no DML). */ void ExtErr(PCSTR Format, ...); /* Prints out to ExtErr (no DML). */ void ExtDbgOut(PCSTR Format, ...); /* Prints out to ExtOut in a checked build (no DML). */ void WhitespaceOut(int count); /* Prints out "count" number of spaces in the output. */ // Change indent for ExtOut inline void IncrementIndent() { Output::g_Indent++; } inline void DecrementIndent() { if (Output::g_Indent > 0) Output::g_Indent inline void ExtOutIndent() { WhitespaceOut(Output::g_Indent << 2); } // DML Generation Methods #define DMLListNearObj(addr) Output::BuildHexValue(addr, Output::DML_ListNearObj).GetPtr() #define DMLDumpHeapMT(addr) Output::BuildHexValue(addr, Output::DML_DumpHeapMT).GetPtr() #define DMLMethodTable(addr) Output::BuildHexValue(addr, Output::DML_MethodTable).GetPtr() #define DMLMethodDesc(addr) Output::BuildHexValue(addr, Output::DML_MethodDesc).GetPtr() #define DMLClass(addr) Output::BuildHexValue(addr, Output::DML_EEClass).GetPtr() #define DMLModule(addr) Output::BuildHexValue(addr, Output::DML_Module).GetPtr() #define DMLIP(ip) Output::BuildHexValue(ip, Output::DML_IP).GetPtr() #define DMLObject(addr) Output::BuildHexValue(addr, Output::DML_Object).GetPtr() #define DMLDomain(addr) Output::BuildHexValue(addr, Output::DML_Domain).GetPtr() #define DMLAssembly(addr) Output::BuildHexValue(addr, Output::DML_Assembly).GetPtr() #define DMLThreadID(id) Output::BuildHexValue(id, Output::DML_ThreadID, false).GetPtr() #define DMLValueClass(mt, addr) Output::BuildVCValue(mt, addr, Output::DML_ValueClass).GetPtr() #define DMLRCWrapper(addr) Output::BuildHexValue(addr, Output::DML_RCWrapper).GetPtr() #define DMLCCWrapper(addr) Output::BuildHexValue(addr, Output::DML_CCWrapper).GetPtr() #define DMLManagedVar(expansionName,frame,simpleName) Output::<API key>(expansionName, frame, simpleName, Output::DML_ManagedVar).GetPtr() bool IsDMLEnabled(); #ifndef SOS_Assert #define SOS_Assert(x) #endif void ConvertToLower(__out_ecount(len) char *buffer, size_t len); extern const char * const DMLFormats[]; int GetHex(CLRDATA_ADDRESS addr, __out_ecount(len) char *out, size_t len, bool fill); // A simple string class for mutable strings. We cannot use STL, so this is a stand in replacement // for std::string (though it doesn't use the same interface). template <class T, size_t (__cdecl *LEN)(const T *), errno_t (__cdecl *COPY)(T *, size_t, const T * _Src)> class BaseString { public: BaseString() : mStr(0), mSize(0), mLength(0) { const size_t size = 64; mStr = new T[size]; mSize = size; mStr[0] = 0; } BaseString(const T *str) : mStr(0), mSize(0), mLength(0) { CopyFrom(str, LEN(str)); } BaseString(const BaseString<T, LEN, COPY> &rhs) : mStr(0), mSize(0), mLength(0) { *this = rhs; } ~BaseString() { Clear(); } const BaseString<T, LEN, COPY> &operator=(const BaseString<T, LEN, COPY> &rhs) { Clear(); CopyFrom(rhs.mStr, rhs.mLength); return *this; } const BaseString<T, LEN, COPY> &operator=(const T *str) { Clear(); CopyFrom(str, LEN(str)); return *this; } const BaseString<T, LEN, COPY> &operator +=(const T *str) { size_t len = LEN(str); CopyFrom(str, len); return *this; } const BaseString<T, LEN, COPY> &operator +=(const BaseString<T, LEN, COPY> &str) { CopyFrom(str.mStr, str.mLength); return *this; } BaseString<T, LEN, COPY> operator+(const T *str) const { return BaseString<T, LEN, COPY>(mStr, mLength, str, LEN(str)); } BaseString<T, LEN, COPY> operator+(const BaseString<T, LEN, COPY> &str) const { return BaseString<T, LEN, COPY>(mStr, mLength, str.mStr, str.mLength); } operator const T *() const { return mStr; } const T *c_str() const { return mStr; } size_t GetLength() const { return mLength; } private: BaseString(const T * str1, size_t len1, const T * str2, size_t len2) : mStr(0), mSize(0), mLength(0) { const size_t size = len1 + len2 + 1 + ((len1 + len2) >> 1); mStr = new T[size]; mSize = size; CopyFrom(str1, len1); CopyFrom(str2, len2); } void Clear() { mLength = 0; mSize = 0; if (mStr) { delete [] mStr; mStr = 0; } } void CopyFrom(const T *str, size_t len) { if (mLength + len + 1 >= mSize) Resize(mLength + len + 1); COPY(mStr+mLength, mSize-mLength, str); mLength += len; } void Resize(size_t size) { /* We always resize at least one half bigger than we need. When CopyFrom requests a resize * it asks for the exact size that's needed to concatenate strings. However in practice * it's common to add multiple strings together in a row, e.g.: * String foo = "One " + "Two " + "Three " + "Four " + "\n"; * Ensuring the size of the string is bigger than we need, and that the minimum size is 64, * we will cut down on a lot of needless resizes at the cost of a few bytes wasted in some * cases. */ size += size >> 1; if (size < 64) size = 64; T *newStr = new T[size]; if (mStr) { COPY(newStr, size, mStr); delete [] mStr; } else { newStr[0] = 0; } mStr = newStr; mSize = size; } private: T *mStr; size_t mSize, mLength; }; typedef BaseString<char, strlen, strcpy_s> String; typedef BaseString<WCHAR, _wcslen, wcscpy_s> WString; template<class T> void Flatten(__out_ecount(len) T *data, unsigned int len) { for (unsigned int i = 0; i < len; ++i) if (data[i] < 32 || (data[i] > 126 && data[i] <= 255)) data[i] = '.'; data[len] = 0; } void Flatten(__out_ecount(len) char *data, unsigned int len); /* Formats for the Format class. We support the following formats: * Pointer - Same as %p. * Hex - Same as %x (same as %p, but does not output preceding zeros. * PrefixHex - Same as %x, but prepends 0x. * Decimal - Same as %d. * Strings and wide strings don't use this. */ class Formats { public: enum Format { Default, Pointer, Hex, PrefixHex, Decimal, }; }; enum Alignment { AlignLeft, AlignRight }; namespace Output { /* Defines how a value will be printed. This class understands how to format * and print values according to the format and DML settings provided. * The raw templated class handles the pointer/integer case. Support for * character arrays and wide character arrays are handled by template * specializations. * * Note that this class is not used directly. Instead use the typedefs and * macros which define the type of data you are outputing (for example ObjectPtr, * MethodTablePtr, etc). */ template <class T> class Format { public: Format(T value) : mValue(value), mFormat(Formats::Default), mDml(Output::DML_None) { } Format(T value, Formats::Format format, Output::FormatType dmlType) : mValue(value), mFormat(format), mDml(dmlType) { } Format(const Format<T> &rhs) : mValue(rhs.mValue), mFormat(rhs.mFormat), mDml(rhs.mDml) { } /* Prints out the value according to the Format and DML settings provided. */ void Output() const { if (IsDMLEnabled() && mDml != Output::DML_None) { const int len = GetDMLWidth(mDml); char *buffer = (char*)alloca(len); BuildDML(buffer, len, (CLRDATA_ADDRESS)mValue, mFormat, mDml); DMLOut(buffer); } else { if (mFormat == Formats::Default || mFormat == Formats::Pointer) { ExtOut("%p", (__int64)mValue); } else { const char *format = NULL; if (mFormat == Formats::PrefixHex) { format = "0x%x"; } else if (mFormat == Formats::Hex) { format = "%x"; } else if (mFormat == Formats::Decimal) { format = "%d"; } ExtOut(format, (__int32)mValue); } } } /* Prints out the value based on a specified width and alignment. * Params: * align - Whether the output should be left or right justified. * width - The output width to fill. * Note: * This function guarantees that exactly width will be printed out (so if width is 24, * exactly 24 characters will be printed), even if the output wouldn't normally fit * in the space provided. This function makes no guarantees as to what part of the * data will be printed in the case that width isn't wide enough. */ void OutputColumn(Alignment align, int width) const { bool leftAlign = align == AlignLeft; if (IsDMLEnabled() && mDml != Output::DML_None) { const int len = GetDMLColWidth(mDml, width); char *buffer = (char*)alloca(len); BuildDMLCol(buffer, len, (CLRDATA_ADDRESS)mValue, mFormat, mDml, leftAlign, width); DMLOut(buffer); } else { int precision = GetPrecision(); if (mFormat == Formats::Default || mFormat == Formats::Pointer) { if (precision > width) precision = width; ExtOut(leftAlign ? "%-*.*p" : "%*.*p", width, precision, (__int64)mValue); } else { const char *format = NULL; if (mFormat == Formats::PrefixHex) { format = leftAlign ? "0x%-*.*x" : "0x%*.*x"; width -= 2; } else if (mFormat == Formats::Hex) { format = leftAlign ? "%-*.*x" : "%*.*x"; } else if (mFormat == Formats::Decimal) { format = leftAlign ? "%-*.*d" : "%*.*d"; } if (precision > width) precision = width; ExtOut(format, width, precision, (__int32)mValue); } } } /* Converts this object into a Wide char string. This allows you to write the following code: * WString foo = L"bar " + ObjectPtr(obj); * Where ObjectPtr is a subclass/typedef of this Format class. */ operator WString() const { String str = *this; const char *cstr = (const char *)str; int len = MultiByteToWideChar(CP_ACP, 0, cstr, -1, NULL, 0); WCHAR *buffer = (WCHAR *)alloca(len*sizeof(WCHAR)); MultiByteToWideChar(CP_ACP, 0, cstr, -1, buffer, len); return WString(buffer); } /* Converts this object into a String object. This allows you to write the following code: * String foo = "bar " + ObjectPtr(obj); * Where ObjectPtr is a subclass/typedef of this Format class. */ operator String() const { if (IsDMLEnabled() && mDml != Output::DML_None) { const int len = GetDMLColWidth(mDml, 0); char *buffer = (char*)alloca(len); BuildDMLCol(buffer, len, (CLRDATA_ADDRESS)mValue, mFormat, mDml, false, 0); return buffer; } else { char buffer[64]; if (mFormat == Formats::Default || mFormat == Formats::Pointer) { sprintf_s(buffer, _countof(buffer), "%p", (int *)(SIZE_T)mValue); ConvertToLower(buffer, _countof(buffer)); } else { const char *format = NULL; if (mFormat == Formats::PrefixHex) format = "0x%x"; else if (mFormat == Formats::Hex) format = "%x"; else if (mFormat == Formats::Decimal) format = "%d"; sprintf_s(buffer, _countof(buffer), format, (__int32)mValue); ConvertToLower(buffer, _countof(buffer)); } return buffer; } } private: int GetPrecision() const { if (mFormat == Formats::Hex || mFormat == Formats::PrefixHex) { ULONGLONG val = mValue; int count = 0; while (val) { val >>= 4; count++; } if (count == 0) count = 1; return count; } else if (mFormat == Formats::Decimal) { T val = mValue; int count = (val > 0) ? 0 : 1; while (val) { val /= 10; count++; } return count; } // mFormat == Formats::Pointer return sizeof(int*)*2; } static inline void BuildDML(__out_ecount(len) char *result, int len, CLRDATA_ADDRESS value, Formats::Format format, Output::FormatType dmlType) { BuildDMLCol(result, len, value, format, dmlType, true, 0); } static int GetDMLWidth(Output::FormatType dmlType) { return GetDMLColWidth(dmlType, 0); } static void BuildDMLCol(__out_ecount(len) char *result, int len, CLRDATA_ADDRESS value, Formats::Format format, Output::FormatType dmlType, bool leftAlign, int width) { char hex[64]; int count = GetHex(value, hex, _countof(hex), format != Formats::Hex); int i = 0; if (!leftAlign) { for (; i < width - count; ++i) result[i] = ' '; result[i] = 0; } int written = sprintf_s(result+i, len - i, DMLFormats[dmlType], hex, hex); SOS_Assert(written != -1); if (written != -1) { for (i = i + written; i < width; ++i) result[i] = ' '; result[i] = 0; } } static int GetDMLColWidth(Output::FormatType dmlType, int width) { return 1 + 4*sizeof(int*) + (int)strlen(DMLFormats[dmlType]) + width; } private: T mValue; Formats::Format mFormat; Output::FormatType mDml; }; /* Format class used for strings. */ template <> class Format<const char *> { public: Format(const char *value) : mValue(value) { } Format(const Format<const char *> &rhs) : mValue(rhs.mValue) { } void Output() const { if (IsDMLEnabled()) DMLOut("%s", mValue); else ExtOut("%s", mValue); } void OutputColumn(Alignment align, int width) const { int precision = (int)strlen(mValue); if (precision > width) precision = width; const char *format = align == AlignLeft ? "%-*.*s" : "%*.*s"; if (IsDMLEnabled()) DMLOut(format, width, precision, mValue); else ExtOut(format, width, precision, mValue); } private: const char *mValue; }; /* Format class for wide char strings. */ template <> class Format<const WCHAR *> { public: Format(const WCHAR *value) : mValue(value) { } Format(const Format<const WCHAR *> &rhs) : mValue(rhs.mValue) { } void Output() const { if (IsDMLEnabled()) DMLOut("%S", mValue); else ExtOut("%S", mValue); } void OutputColumn(Alignment align, int width) const { int precision = (int)_wcslen(mValue); if (precision > width) precision = width; const char *format = align == AlignLeft ? "%-*.*S" : "%*.*S"; if (IsDMLEnabled()) DMLOut(format, width, precision, mValue); else ExtOut(format, width, precision, mValue); } private: const WCHAR *mValue; }; template <class T> void InternalPrint(const T &t) { Format<T>(t).Output(); } template <class T> void InternalPrint(const Format<T> &t) { t.Output(); } inline void InternalPrint(const char t[]) { Format<const char *>(t).Output(); } } #define DefineFormatClass(name, format, dml) \ template <class T> \ Output::Format<T> name(T value) \ { return Output::Format<T>(value, format, dml); } DefineFormatClass(EEClassPtr, Formats::Pointer, Output::DML_EEClass); DefineFormatClass(ObjectPtr, Formats::Pointer, Output::DML_Object); DefineFormatClass(ExceptionPtr, Formats::Pointer, Output::DML_PrintException); DefineFormatClass(ModulePtr, Formats::Pointer, Output::DML_Module); DefineFormatClass(MethodDescPtr, Formats::Pointer, Output::DML_MethodDesc); DefineFormatClass(AppDomainPtr, Formats::Pointer, Output::DML_Domain); DefineFormatClass(ThreadState, Formats::Hex, Output::DML_ThreadState); DefineFormatClass(ThreadID, Formats::Hex, Output::DML_ThreadID); DefineFormatClass(RCWrapper, Formats::Pointer, Output::DML_RCWrapper); DefineFormatClass(CCWrapper, Formats::Pointer, Output::DML_CCWrapper); DefineFormatClass(InstructionPtr, Formats::Pointer, Output::DML_IP); DefineFormatClass(Decimal, Formats::Decimal, Output::DML_None); DefineFormatClass(Pointer, Formats::Pointer, Output::DML_None); DefineFormatClass(PrefixHex, Formats::PrefixHex, Output::DML_None); DefineFormatClass(Hex, Formats::Hex, Output::DML_None); #undef DefineFormatClass template <class T0> void Print(const T0 &val0) { Output::InternalPrint(val0); } template <class T0, class T1> void Print(const T0 &val0, const T1 &val1) { Output::InternalPrint(val0); Output::InternalPrint(val1); } template <class T0> void PrintLn(const T0 &val0) { Output::InternalPrint(val0); ExtOut("\n"); } template <class T0, class T1> void PrintLn(const T0 &val0, const T1 &val1) { Output::InternalPrint(val0); Output::InternalPrint(val1); ExtOut("\n"); } template <class T0, class T1, class T2> void PrintLn(const T0 &val0, const T1 &val1, const T2 &val2) { Output::InternalPrint(val0); Output::InternalPrint(val1); Output::InternalPrint(val2); ExtOut("\n"); } /* This class handles the formatting for output which is in a table format. To use this class you define * how the table is formatted by setting the number of columns in the table, the default column width, * the default column alignment, the indentation (whitespace) for the table, and the amount of padding * (whitespace) between each column. Once this has been setup, you output rows at a time or individual * columns to build the output instead of manually tabbing out space. * Also note that this class was built to work with the Format class. When outputing data, use the * predefined output types to specify the format (such as ObjectPtr, MethodDescPtr, Decimal, etc). This * tells the TableOutput class how to display the data, and where applicable, it automatically generates * the appropriate DML output. See the DefineFormatClass macro. */ class TableOutput { public: TableOutput() : mColumns(0), mDefaultWidth(0), mIndent(0), mPadding(0), mCurrCol(0), mDefaultAlign(AlignLeft), mWidths(0), mAlignments(0) { } /* Constructor. * Params: * numColumns - the number of columns the table has * defaultColumnWidth - the default width of each column * alignmentDefault - whether columns are by default left aligned or right aligned * indent - the amount of whitespace to prefix at the start of the row (in characters) * padding - the amount of whitespace to place between each column (in characters) */ TableOutput(int numColumns, int defaultColumnWidth, Alignment alignmentDefault = AlignLeft, int indent = 0, int padding = 1) : mColumns(numColumns), mDefaultWidth(defaultColumnWidth), mIndent(indent), mPadding(padding), mCurrCol(0), mDefaultAlign(alignmentDefault), mWidths(0), mAlignments(0) { } ~TableOutput() { Clear(); } /* See the documentation for the constructor. */ void ReInit(int numColumns, int defaultColumnWidth, Alignment alignmentDefault = AlignLeft, int indent = 0, int padding = 1); /* Sets the amount of whitespace to prefix at the start of the row (in characters). */ void SetIndent(int indent) { SOS_Assert(indent >= 0); mIndent = indent; } /* Sets the exact widths for the the given columns. * Params: * columns - the number of columns you are providing the width for, starting at the first column * ... - an int32 for each column (given by the number of columns in the first parameter). * Example: * If you have 5 columns in the table, you can set their widths like so: * tableOutput.SetWidths(5, 2, 3, 5, 7, 13); * Note: * It's fine to pass a value for "columns" less than the number of columns in the table. This * is useful when you set the default column width to be correct for most of the table, and need * to make a minor adjustment to a few. */ void SetWidths(int columns, ...); /* Individually sets a column to the given width. * Params: * col - the column to set, 0 indexed * width - the width of the column (note this must be non-negative) */ void SetColWidth(int col, int width); /* Individually sets the column alignment. * Params: * col - the column to set, 0 indexed * align - the new alignment (left or right) for the column */ void SetColAlignment(int col, Alignment align); /* The WriteRow family of functions allows you to write an entire row of the table at once. * The common use case for the TableOutput class is to individually output each column after * calculating what the value should contain. However, this would be tedious if you already * knew the contents of the entire row which usually happenes when you are printing out the * header for the table. To use this, simply pass each column as an individual parameter, * for example: * tableOutput.WriteRow("First Column", "Second Column", Decimal(3), PrefixHex(4), "Fifth Column"); */ template <class T0, class T1> void WriteRow(T0 t0, T1 t1) { WriteColumn(0, t0); WriteColumn(1, t1); } template <class T0, class T1, class T2> void WriteRow(T0 t0, T1 t1, T2 t2) { WriteColumn(0, t0); WriteColumn(1, t1); WriteColumn(2, t2); } template <class T0, class T1, class T2, class T3> void WriteRow(T0 t0, T1 t1, T2 t2, T3 t3) { WriteColumn(0, t0); WriteColumn(1, t1); WriteColumn(2, t2); WriteColumn(3, t3); } template <class T0, class T1, class T2, class T3, class T4> void WriteRow(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4) { WriteColumn(0, t0); WriteColumn(1, t1); WriteColumn(2, t2); WriteColumn(3, t3); WriteColumn(4, t4); } template <class T0, class T1, class T2, class T3, class T4, class T5> void WriteRow(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) { WriteColumn(0, t0); WriteColumn(1, t1); WriteColumn(2, t2); WriteColumn(3, t3); WriteColumn(4, t4); WriteColumn(5, t5); } template <class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9> void WriteRow(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9) { WriteColumn(0, t0); WriteColumn(1, t1); WriteColumn(2, t2); WriteColumn(3, t3); WriteColumn(4, t4); WriteColumn(5, t5); WriteColumn(6, t6); WriteColumn(7, t7); WriteColumn(8, t8); WriteColumn(9, t9); } /* The WriteColumn family of functions is used to output individual columns in the table. * The intent is that the bulk of the table will be generated in a loop like so: * while (condition) { * int value1 = <API key>(); * table.WriteColumn(0, value1); * * String value2 = <API key>(); * table.WriteColumn(1, value2); * } * Params: * col - the column to write, 0 indexed * t - the value to write * Note: * You should generally use the specific instances of the Format class to generate output. * For example, use the "Decimal", "Pointer", "ObjectPtr", etc. When passing data to this * function. This tells the Table class how to display the value. */ template <class T> void WriteColumn(int col, const Output::Format<T> &t) { SOS_Assert(col >= 0); SOS_Assert(col < mColumns); if (col != mCurrCol) OutputBlankColumns(col); if (col == 0) OutputIndent(); bool lastCol = col == mColumns - 1; if (!lastCol) t.OutputColumn(GetColAlign(col), GetColumnWidth(col)); else t.Output(); ExtOut(lastCol ? "\n" : GetWhitespace(mPadding)); if (lastCol) mCurrCol = 0; else mCurrCol = col+1; } template <class T> void WriteColumn(int col, T t) { WriteColumn(col, Output::Format<T>(t)); } void WriteColumn(int col, const String &str) { WriteColumn(col, Output::Format<const char *>(str)); } void WriteColumn(int col, const WString &str) { WriteColumn(col, Output::Format<const WCHAR *>(str)); } void WriteColumn(int col, __in_z WCHAR *str) { WriteColumn(col, Output::Format<const WCHAR *>(str)); } void WriteColumn(int col, const WCHAR *str) { WriteColumn(col, Output::Format<const WCHAR *>(str)); } inline void WriteColumn(int col, __in_z char *str) { WriteColumn(col, Output::Format<const char *>(str)); } /* Writes a column using a printf style format. You cannot use the Format class with * this function to specify how the output should look, use printf style formatting * with the appropriate parameters instead. */ void WriteColumnFormat(int col, const char *fmt, ...) { SOS_Assert(strstr(fmt, "%S") == NULL); char result[128]; va_list list; va_start(list, fmt); vsprintf_s(result, _countof(result), fmt, list); va_end(list); WriteColumn(col, result); } void WriteColumnFormat(int col, const WCHAR *fmt, ...) { WCHAR result[128]; va_list list; va_start(list, fmt); vswprintf_s(result, _countof(result), fmt, list); va_end(list); WriteColumn(col, result); } /* This function is a shortcut for writing the next column. (That is, the one after the * one you just wrote.) */ template <class T> void WriteColumn(T t) { WriteColumn(mCurrCol, t); } private: void Clear(); void AllocWidths(); int GetColumnWidth(int col); Alignment GetColAlign(int col); const char *GetWhitespace(int amount); void OutputBlankColumns(int col); void OutputIndent(); private: int mColumns, mDefaultWidth, mIndent, mPadding, mCurrCol; Alignment mDefaultAlign; int *mWidths; Alignment *mAlignments; }; HRESULT <API key>(DWORD_PTR ModulePtr, IXCLRDataModule* mod, const char* name, <API key> **ppMethodDefinitions, int numMethods, int *numMethodsNeeded); HRESULT <API key>(DWORD_PTR ModulePtr, IXCLRDataModule* mod, const char* name, DWORD_PTR **pOut, int *numMethodDescs); HRESULT FileNameForModule (DacpModuleData *pModule, __out_ecount (MAX_LONGPATH) WCHAR *fileName); HRESULT FileNameForModule (DWORD_PTR pModuleAddr, __out_ecount (MAX_LONGPATH) WCHAR *fileName); void IP2MethodDesc (DWORD_PTR IP, DWORD_PTR &methodDesc, JITTypes &jitType, DWORD_PTR &gcinfoAddr); const char *ElementTypeName (unsigned type); void DisplayFields (CLRDATA_ADDRESS cdaMT, DacpMethodTableData *pMTD, <API key> *pMTFD, DWORD_PTR dwStartAddr = 0, BOOL bFirst=TRUE, BOOL bValueClass=FALSE); int GetObjFieldOffset(CLRDATA_ADDRESS cdaObj, __in_z LPCWSTR wszFieldName, BOOL bFirst=TRUE); int GetObjFieldOffset(CLRDATA_ADDRESS cdaObj, CLRDATA_ADDRESS cdaMT, __in_z LPCWSTR wszFieldName, BOOL bFirst=TRUE); BOOL IsValidToken(DWORD_PTR ModuleAddr, mdTypeDef mb); void NameForToken_s(DacpModuleData *pModule, mdTypeDef mb, __out_ecount (capacity_mdName) WCHAR *mdName, size_t capacity_mdName, bool bClassName=true); void NameForToken_s(DWORD_PTR ModuleAddr, mdTypeDef mb, __out_ecount (capacity_mdName) WCHAR *mdName, size_t capacity_mdName, bool bClassName=true); HRESULT NameForToken_s(mdTypeDef mb, IMetaDataImport *pImport, __out_ecount (capacity_mdName) WCHAR *mdName, size_t capacity_mdName, bool bClassName); HRESULT NameForTokenNew_s(mdTypeDef mb, IMDInternalImport *pImport, __out_ecount (capacity_mdName) WCHAR *mdName, size_t capacity_mdName, bool bClassName); void vmmap(); void vmstat(); #ifndef FEATURE_PAL // Support for managed stack tracing DWORD_PTR GetDebuggerJitInfo(DWORD_PTR md); #endif // FEATURE_PAL template <typename SCALAR> inline int bitidx(SCALAR bitflag) { for (int idx = 0; idx < static_cast<int>(sizeof(bitflag))*8; ++idx) { if (bitflag & (1 << idx)) { _ASSERTE((bitflag & (~(1 << idx))) == 0); return idx; } } return -1; } HRESULT DllsName( ULONG_PTR addrContaining, __out_ecount (MAX_LONGPATH) WCHAR *dllName ); inline BOOL IsElementValueType (CorElementType cet) { return (cet >= <API key> && cet <= ELEMENT_TYPE_R8) || cet == <API key> || cet == ELEMENT_TYPE_I || cet == ELEMENT_TYPE_U; } #define safemove(dst, src) \ SafeReadMemory (TO_TADDR(src), &(dst), sizeof(dst), NULL) extern "C" PDEBUG_DATA_SPACES g_ExtData; template <class T> class ArrayHolder { public: ArrayHolder(T *ptr) : mPtr(ptr) { } ~ArrayHolder() { Clear(); } ArrayHolder(const ArrayHolder &rhs) { mPtr = const_cast<ArrayHolder *>(&rhs)->Detach(); } ArrayHolder &operator=(T *ptr) { Clear(); mPtr = ptr; return *this; } const T &operator[](int i) const { return mPtr[i]; } T &operator[](int i) { return mPtr[i]; } operator const T *() const { return mPtr; } operator T *() { return mPtr; } T **operator&() { return &mPtr; } T *GetPtr() { return mPtr; } T *Detach() { T *ret = mPtr; mPtr = NULL; return ret; } private: void Clear() { if (mPtr) { delete [] mPtr; mPtr = NULL; } } private: T *mPtr; }; // This class acts a smart pointer which calls the Release method on any object // you place in it when the ToRelease class falls out of scope. You may use it // just like you would a standard pointer to a COM object (including if (foo), // if (!foo), if (foo == 0), etc) except for two caveats: // 1. This class never calls AddRef and it always calls Release when it // goes out of scope. // 2. You should never use & to try to get a pointer to a pointer unless // you call Release first, or you will leak whatever this object contains // prior to updating its internal pointer. template<class T> class ToRelease { public: ToRelease() : m_ptr(NULL) {} ToRelease(T* ptr) : m_ptr(ptr) {} ~ToRelease() { Release(); } void operator=(T *ptr) { Release(); m_ptr = ptr; } T* operator->() { return m_ptr; } operator T*() { return m_ptr; } T** operator&() { return &m_ptr; } T* GetPtr() const { return m_ptr; } T* Detach() { T* pT = m_ptr; m_ptr = NULL; return pT; } void Release() { if (m_ptr != NULL) { m_ptr->Release(); m_ptr = NULL; } } private: T* m_ptr; }; struct ModuleInfo { ULONG64 baseAddr; ULONG64 size; BOOL hasPdb; }; extern ModuleInfo moduleInfo[]; BOOL InitializeHeapData(); BOOL IsServerBuild (); UINT GetMaxGeneration(); UINT GetGcHeapCount(); BOOL <API key>(); ULONG GetILSize(DWORD_PTR ilAddr); // REturns 0 if error occurs HRESULT DecodeILFromAddress(IMetaDataImport *pImport, TADDR ilAddr); void DecodeIL(IMetaDataImport *pImport, BYTE *buffer, ULONG bufSize); void DecodeDynamicIL(BYTE *data, ULONG Size, DacpObjectData& tokenArray); BOOL IsRetailBuild (size_t base); EEFLAVOR GetEEFlavor (); HRESULT <API key>(); VOID <API key>(); #ifndef FEATURE_PAL BOOL GetEEVersion(VS_FIXEDFILEINFO *pFileInfo); BOOL GetSOSVersion(VS_FIXEDFILEINFO *pFileInfo); #endif BOOL IsDumpFile (); // IsMiniDumpFile will return true if 1) we are in // a small format minidump, and <API key> is true. extern BOOL <API key>; BOOL IsMiniDumpFile(); void ReportOOM(); BOOL SafeReadMemory (TADDR offset, PVOID lpBuffer, ULONG cb, PULONG lpcbBytesRead); #if !defined(_TARGET_WIN64_) && !defined(_ARM64_) // on 64-bit platforms TADDR and CLRDATA_ADDRESS are identical inline BOOL SafeReadMemory (CLRDATA_ADDRESS offset, PVOID lpBuffer, ULONG cb, PULONG lpcbBytesRead) { return SafeReadMemory(TO_TADDR(offset), lpBuffer, cb, lpcbBytesRead); } #endif BOOL NameForMD_s (DWORD_PTR pMD, __out_ecount (capacity_mdName) WCHAR *mdName, size_t capacity_mdName); BOOL NameForMT_s (DWORD_PTR MTAddr, __out_ecount (capacity_mdName) WCHAR *mdName, size_t capacity_mdName); WCHAR *<API key>(TADDR mt, TADDR cmt = NULL); void isRetAddr(DWORD_PTR retAddr, DWORD_PTR* whereCalled); DWORD_PTR <API key> (___in __in_z const char *const str); enum ModuleHeapType { <API key>, <API key> }; HRESULT PrintDomainHeapInfo(const char *name, CLRDATA_ADDRESS adPtr, DWORD_PTR *size, DWORD_PTR *wasted = 0); DWORD_PTR PrintModuleHeapInfo(DWORD_PTR *moduleList, int count, ModuleHeapType type, DWORD_PTR *wasted = 0); void PrintHeapSize(DWORD_PTR total, DWORD_PTR wasted); void DomainInfo(DacpAppDomainData *pDomain); void AssemblyInfo(DacpAssemblyData *pAssembly); DWORD_PTR LoaderHeapInfo(CLRDATA_ADDRESS pLoaderHeapAddr, DWORD_PTR *wasted = 0); DWORD_PTR JitHeapInfo(); DWORD_PTR VSDHeapInfo(CLRDATA_ADDRESS appDomain, DWORD_PTR *wasted = 0); DWORD GetNumComponents(TADDR obj); struct GenUsageStat { size_t allocd; size_t freed; size_t unrooted; }; struct HeapUsageStat { GenUsageStat genUsage[4]; // gen0, 1, 2, LOH }; extern <API key> <API key>; BOOL GCHeapUsageStats(const DacpGcHeapDetails& heap, BOOL bIncUnreachable, HeapUsageStat *hpUsage); class HeapStat { protected: struct Node { DWORD_PTR data; DWORD count; size_t totalSize; Node* left; Node* right; Node () : data(0), count(0), totalSize(0), left(NULL), right(NULL) { } }; BOOL bHasStrings; Node *head; BOOL fLinear; public: HeapStat () : bHasStrings(FALSE), head(NULL), fLinear(FALSE) {} ~HeapStat() { Delete(); } // TODO: Change the aSize argument to size_t when we start supporting // TODO: object sizes above 4GB void Add (DWORD_PTR aData, DWORD aSize); void Sort (); void Print (const char* label = NULL); void Delete (); void HasStrings(BOOL abHasStrings) { bHasStrings = abHasStrings; } private: int CompareData(DWORD_PTR n1, DWORD_PTR n2); void SortAdd (Node *&root, Node *entry); void LinearAdd (Node *&root, Node *entry); void ReverseLeftMost (Node *root); void Linearize(); }; class CGCDesc; // The information MethodTableCache returns. struct MethodTableInfo { bool IsInitialized() { return BaseSize != 0; } DWORD BaseSize; // Caching BaseSize and ComponentSize for a MethodTable DWORD ComponentSize; // here has HUGE perf benefits in heap traversals. BOOL bContainsPointers; DWORD_PTR* GCInfoBuffer; // Start of memory of GC info CGCDesc* GCInfo; // Just past GC info (which is how it is stored) bool ArrayOfVC; }; class MethodTableCache { protected: struct Node { DWORD_PTR data; // This is the key (the method table pointer) MethodTableInfo info; // The info associated with this MethodTable Node* left; Node* right; Node (DWORD_PTR aData) : data(aData), left(NULL), right(NULL) { info.BaseSize = 0; info.ComponentSize = 0; info.bContainsPointers = false; info.GCInfo = NULL; info.ArrayOfVC = false; info.GCInfoBuffer = NULL; } }; Node *head; public: MethodTableCache () : head(NULL) {} ~MethodTableCache() { Clear(); } // Always succeeds, if it is not present it adds an empty Info struct and returns that // Thus you must call 'IsInitialized' on the returned value before using it MethodTableInfo* Lookup(DWORD_PTR aData); void Clear (); private: int CompareData(DWORD_PTR n1, DWORD_PTR n2); void ReverseLeftMost (Node *root); }; extern MethodTableCache g_special_mtCache; struct DumpArrayFlags { DWORD_PTR startIndex; DWORD_PTR Length; BOOL bDetail; LPSTR strObject; BOOL bNoFieldsForElement; DumpArrayFlags () : startIndex(0), Length((DWORD_PTR)-1), bDetail(FALSE), strObject (0), bNoFieldsForElement(FALSE) {} ~DumpArrayFlags () { if (strObject) delete [] strObject; } }; //DumpArrayFlags #define <API key> 0x08000000 #define <API key> 0x40000000 #define BIT_SBLK_SPIN_LOCK 0x10000000 #define <API key> 0x000003FF // special value of 0 + 1023 thread ids #define <API key> 0x0000FC00 // 64 recursion levels #define <API key> 16 // shift right this much to get appdomain index #define <API key> 0x000007FF // 2048 appdomain indices #define SBLK_RECLEVEL_SHIFT 10 // shift right this much to get recursion level #define <API key> 0x04000000 #define MASK_HASHCODE ((1<<HASHCODE_BITS)-1) #define SYNCBLOCKINDEX_BITS 26 #define MASK_SYNCBLOCKINDEX ((1<<SYNCBLOCKINDEX_BITS)-1) HRESULT GetMTOfObject(TADDR obj, TADDR *mt); struct <API key> { BYTE* alloc_ptr; // starting point for next allocation BYTE* alloc_limit; // ending point for allocation region/quantum }; struct AllocInfo { <API key> *array; int num; // number of allocation contexts in array AllocInfo() : array(NULL) , num(0) {} void Init() { extern void GetAllocContextPtrs(AllocInfo *pallocInfo); GetAllocContextPtrs(this); } ~AllocInfo() { if (array != NULL) delete[] array; } }; struct GCHandleStatistics { HeapStat hs; DWORD strongHandleCount; DWORD pinnedHandleCount; DWORD <API key>; DWORD refCntHandleCount; DWORD weakLongHandleCount; DWORD <API key>; DWORD variableCount; DWORD sizedRefCount; DWORD dependentCount; DWORD <API key>; DWORD unknownHandleCount; GCHandleStatistics() : strongHandleCount(0), pinnedHandleCount(0), <API key>(0), refCntHandleCount(0), weakLongHandleCount(0), <API key>(0), variableCount(0), sizedRefCount(0), dependentCount(0), <API key>(0), unknownHandleCount(0) {} ~GCHandleStatistics() { hs.Delete(); } }; struct SegmentLookup { DacpHeapSegmentData *m_segments; int m_iSegmentsSize; int m_iSegmentCount; SegmentLookup(); ~SegmentLookup(); void Clear(); BOOL AddSegment(DacpHeapSegmentData *pData); CLRDATA_ADDRESS GetHeap(CLRDATA_ADDRESS object, BOOL& bFound); }; class GCHeapSnapshot { private: BOOL m_isBuilt; DacpGcHeapDetails *m_heapDetails; DacpGcHeapData m_gcheap; SegmentLookup m_segments; BOOL AddSegments(DacpGcHeapDetails& details); public: GCHeapSnapshot(); BOOL Build(); void Clear(); BOOL IsBuilt() { return m_isBuilt; } DacpGcHeapData *GetHeapData() { return &m_gcheap; } int GetHeapCount() { return m_gcheap.HeapCount; } DacpGcHeapDetails *GetHeap(CLRDATA_ADDRESS objectPointer); int GetGeneration(CLRDATA_ADDRESS objectPointer); }; extern GCHeapSnapshot g_snapshot; BOOL IsSameModuleName (const char *str1, const char *str2); BOOL IsModule (DWORD_PTR moduleAddr); BOOL IsMethodDesc (DWORD_PTR value); BOOL IsMethodTable (DWORD_PTR value); BOOL IsStringObject (size_t obj); BOOL IsObjectArray (DWORD_PTR objPointer); BOOL IsObjectArray (DacpObjectData *pData); /* Returns a list of all modules in the process. * Params: * name - The name of the module you would like. If mName is NULL the all modules are returned. * numModules - The number of modules in the array returned. * Returns: * An array of modules whose length is *numModules, NULL if an error occurred. Note that if this * function succeeds but finds no modules matching the name given, this function returns a valid * array, but *numModules will equal 0. * Note: * You must clean up the return value of this array by calling delete [] on it, or using the * ArrayHolder class. */ DWORD_PTR *ModuleFromName(__in_opt LPSTR name, int *numModules); void GetInfoFromName(DWORD_PTR ModuleAddr, const char* name); void GetInfoFromModule (DWORD_PTR ModuleAddr, ULONG token, DWORD_PTR *ret=NULL); typedef void (*VISITGCHEAPFUNC)(DWORD_PTR objAddr,size_t Size,DWORD_PTR methodTable,LPVOID token); BOOL GCHeapsTraverse(VISITGCHEAPFUNC pFunc, LPVOID token, BOOL verify=true); struct strobjInfo { size_t methodTable; DWORD m_StringLength; }; // Just to make figuring out which fill pointer element matches a generation // a bit less confusing. This gen_segment function is ported from gc.cpp. inline unsigned int gen_segment (int gen) { return (<API key> - gen - 1); } inline CLRDATA_ADDRESS SegQueue(DacpGcHeapDetails& heapDetails, int seg) { return heapDetails.<API key>[seg - 1]; } inline CLRDATA_ADDRESS SegQueueLimit(DacpGcHeapDetails& heapDetails, int seg) { return heapDetails.<API key>[seg]; } #define FinalizerListSeg (<API key>+1) #define <API key> (<API key>) void <API key>(DacpGcHeapDetails& heapDetails, HeapStat *stat, BOOL bAllReady, BOOL bShort); CLRDATA_ADDRESS GetAppDomainForMT(CLRDATA_ADDRESS mtPtr); CLRDATA_ADDRESS GetAppDomain(CLRDATA_ADDRESS objPtr); void GCHeapInfo(const DacpGcHeapDetails &heap, DWORD_PTR &total_size); BOOL GCObjInHeap(TADDR taddrObj, const DacpGcHeapDetails &heap, TADDR_SEGINFO& trngSeg, int& gen, TADDR_RANGE& allocCtx, BOOL &bLarge); BOOL VerifyObject(const DacpGcHeapDetails &heap, const DacpHeapSegmentData &seg, DWORD_PTR objAddr, DWORD_PTR MTAddr, size_t objSize, BOOL bVerifyMember); BOOL VerifyObject(const DacpGcHeapDetails &heap, DWORD_PTR objAddr, DWORD_PTR MTAddr, size_t objSize, BOOL bVerifyMember); BOOL IsMTForFreeObj(DWORD_PTR pMT); void <API key> (TADDR StackTop, TADDR StackBottom, BOOL verifyFields); enum ARGTYPE {COBOOL,COSIZE_T,COHEX,COSTRING}; struct CMDOption { const char* name; void *vptr; ARGTYPE type; BOOL hasValue; BOOL hasSeen; }; struct CMDValue { void *vptr; ARGTYPE type; }; BOOL GetCMDOption(const char *string, CMDOption *option, size_t nOption, CMDValue *arg, size_t maxArg, size_t *nArg); void DumpMDInfo(DWORD_PTR dwStartAddr, CLRDATA_ADDRESS dwRequestedIP = 0, BOOL fStackTraceFormat = FALSE); void <API key>(DacpMethodDescData * pMethodDescData, BOOL fStackTraceFormat); void GetDomainList(DWORD_PTR *&domainList, int &numDomain); HRESULT GetThreadList(DWORD_PTR **threadList, int *numThread); CLRDATA_ADDRESS <API key>(); // returns current managed thread if any void GetAllocContextPtrs(AllocInfo *pallocInfo); void <API key>(); size_t FunctionType (size_t EIP); size_t Align (size_t nbytes); // Aligns large objects size_t AlignLarge (size_t nbytes); ULONG OSPageSize (); size_t NextOSPageAddress (size_t addr); // This version of objectsize reduces the lookup of methodtables in the DAC. // It uses g_special_mtCache for it's work. BOOL GetSizeEfficient(DWORD_PTR dwAddrCurrObj, DWORD_PTR dwAddrMethTable, BOOL bLarge, size_t& s, BOOL& bContainsPointers); // ObjSize now uses the methodtable cache for its work too. size_t ObjectSize (DWORD_PTR obj, BOOL fIsLargeObject=FALSE); size_t ObjectSize(DWORD_PTR obj, DWORD_PTR mt, BOOL fIsValueClass, BOOL fIsLargeObject=FALSE); void CharArrayContent(TADDR pos, ULONG num, bool widechar); void StringObjectContent (size_t obj, BOOL fLiteral=FALSE, const int length=-1); // length=-1: dump everything in the string object. UINT <API key> (DWORD_PTR handlearray[],UINT arraySize); void <API key>(TADDR rngStart, TADDR rngEnd, BOOL <API key>, HeapStat* stat, BOOL bShort); const char *EHTypeName(EHClauseType et); template<typename T> inline const LPCSTR GetTransparency(const T &t) { if (!t.<API key>) { return "Not calculated"; } else if (t.bIsCritical && !t.bIsTreatAsSafe) { return "Critical"; } else if (t.bIsCritical) { return "Safe critical"; } else { return "Transparent"; } } struct StringHolder { LPSTR data; StringHolder() : data(NULL) { } ~StringHolder() { if(data) delete [] data; } }; ULONG DebuggeeType(); inline BOOL IsKernelDebugger () { return DebuggeeType() == DEBUG_CLASS_KERNEL; } void ResetGlobals(void); HRESULT LoadClrDebugDll(void); extern "C" void UnloadClrDebugDll(void); extern IMetaDataImport* MDImportForModule (DacpModuleData *pModule); extern IMetaDataImport* MDImportForModule (DWORD_PTR pModule); /* This cache is used to read data from the target process if the reads are known * to be sequential. */ class LinearReadCache { public: LinearReadCache(ULONG pageSize = 0x10000); ~LinearReadCache(); /* Reads an address out of the target process, caching the page of memory read. * Params: * addr - The address to read out of the target process. * t - A pointer to the data to stuff it in. We will read sizeof(T) data * from the process and write it into the location t points to. This * parameter must be non-null. * Returns: * True if the read succeeded. False if it did not, usually as a result * of the memory simply not being present in the target process. * Note: * The state of *t is undefined if this function returns false. We may * have written partial data to it if we return false, so you must * absolutely NOT use it if Read returns false. */ template <class T> bool Read(TADDR addr, T *t, bool update = true) { _ASSERTE(t); // Unfortunately the ctor can fail the alloc for the byte array. In this case // we'll just fall back to non-cached reads. if (mPage == NULL) return MisalignedRead(addr, t); // Is addr on the current page? If not read the page of memory addr is on. // If this fails, we will fall back to a raw read out of the process (which // is what MisalignedRead does). if ((addr < mCurrPageStart) || (addr - mCurrPageStart > mCurrPageSize)) if (!update || !MoveToPage(addr)) return MisalignedRead(addr, t); // If MoveToPage succeeds, we MUST be on the right page. _ASSERTE(addr >= mCurrPageStart); // However, the amount of data requested may fall off of the page. In that case, // fall back to MisalignedRead. TADDR offset = addr - mCurrPageStart; if (offset + sizeof(T) > mCurrPageSize) return MisalignedRead(addr, t); // If we reach here we know we are on the right page of memory in the cache, and // that the read won't fall off of the end of the page. #ifdef _DEBUG mReads++; #endif *t = *reinterpret_cast<T*>(mPage+offset); return true; } void EnsureRangeInCache(TADDR start, unsigned int size) { if (mCurrPageStart == start) { if (size <= mCurrPageSize) return; // Total bytes to read, don't overflow buffer. unsigned int total = size + mCurrPageSize; if (total + mCurrPageSize > mPageSize) total = <API key>; // Read into the middle of the buffer, update current page size. ULONG read = 0; HRESULT hr = g_ExtData->ReadVirtual(mCurrPageStart+mCurrPageSize, mPage+mCurrPageSize, total, &read); mCurrPageSize += read; if (hr != S_OK) { mCurrPageStart = 0; mCurrPageSize = 0; } } else { MoveToPage(start, size); } } void ClearStats() { #ifdef _DEBUG mMisses = 0; mReads = 0; mMisaligned = 0; #endif } void PrintStats(const char *func) { #ifdef _DEBUG char buffer[1024]; sprintf_s(buffer, _countof(buffer), "Cache (%s): %d reads (%2.1f%% hits), %d misses (%2.1f%%), %d misaligned (%2.1f%%).\n", func, mReads, 100*(mReads-mMisses)/(float)(mReads+mMisaligned), mMisses, 100*mMisses/(float)(mReads+mMisaligned), mMisaligned, 100*mMisaligned/(float)(mReads+mMisaligned)); OutputDebugStringA(buffer); #endif } private: /* Sets the cache to the page specified by addr, or false if we could not move to * that page. */ bool MoveToPage(TADDR addr, unsigned int size = 0x18); /* Attempts to read from the target process if the data is possibly hanging off * the end of a page. */ template<class T> inline bool MisalignedRead(TADDR addr, T *t) { ULONG fetched = 0; HRESULT hr = g_ExtData->ReadVirtual(addr, (BYTE*)t, sizeof(T), &fetched); if (FAILED(hr) || fetched != sizeof(T)) return false; mMisaligned++; return true; } private: TADDR mCurrPageStart; ULONG mPageSize, mCurrPageSize; BYTE *mPage; int mMisses, mReads, mMisaligned; }; // Methods for creating a database out of the gc heap and it's roots in xml format or CLRProfiler format #include <unordered_map> #include <unordered_set> #include <list> class TypeTree; enum { FORMAT_XML=0, FORMAT_CLRPROFILER=1 }; enum { TYPE_START=0,TYPE_TYPES=1,TYPE_ROOTS=2,TYPE_OBJECTS=3,TYPE_HIGHEST=4}; class HeapTraverser { private: TypeTree *m_pTypeTree; size_t m_curNID; FILE *m_file; int m_format; // from the enum above size_t m_objVisited; // for UI updates bool m_verify; LinearReadCache mCache; std::unordered_map<TADDR, std::list<TADDR>> mDependentHandleMap; public: HeapTraverser(bool verify); ~HeapTraverser(); FILE *getFile() { return m_file; } BOOL Initialize(); BOOL CreateReport (FILE *fp, int format); private: // First all types are added to a tree void insert(size_t mTable); size_t getID(size_t mTable); // Functions for writing to the output file. void PrintType(size_t ID,LPCWSTR name); void PrintObjectHead(size_t objAddr,size_t typeID,size_t Size); void PrintObjectMember(size_t memberValue, bool dependentHandle); void PrintObjectTail(); void PrintRootHead(); void PrintRoot(LPCWSTR kind,size_t Value); void PrintRootTail(); void PrintSection(int Type,BOOL bOpening); // Root and object member helper functions void FindGCRootOnStacks(); void PrintRefs(size_t obj, size_t methodTable, size_t size); // Callback functions used during traversals static void GatherTypes(DWORD_PTR objAddr,size_t Size,DWORD_PTR methodTable, LPVOID token); static void PrintHeap(DWORD_PTR objAddr,size_t Size,DWORD_PTR methodTable, LPVOID token); static void PrintOutTree(size_t methodTable, size_t ID, LPVOID token); void TraceHandles(); }; class GCRootImpl { private: struct MTInfo { TADDR MethodTable; WCHAR *TypeName; TADDR *Buffer; CGCDesc *GCDesc; bool ArrayOfVC; bool ContainsPointers; size_t BaseSize; size_t ComponentSize; const WCHAR *GetTypeName() { if (!TypeName) TypeName = <API key>(MethodTable); if (!TypeName) return W("<error>"); return TypeName; } MTInfo() : MethodTable(0), TypeName(0), Buffer(0), GCDesc(0), ArrayOfVC(false), ContainsPointers(false), BaseSize(0), ComponentSize(0) { } ~MTInfo() { if (Buffer) delete [] Buffer; if (TypeName) delete [] TypeName; } }; struct RootNode { RootNode *Next; RootNode *Prev; TADDR Object; MTInfo *MTInfo; bool FilledRefs; bool FromDependentHandle; RootNode *GCRefs; const WCHAR *GetTypeName() { if (!MTInfo) return W("<unknown>"); return MTInfo->GetTypeName(); } RootNode() : Next(0), Prev(0) { Clear(); } void Clear() { if (Next && Next->Prev == this) Next->Prev = NULL; if (Prev && Prev->Next == this) Prev->Next = NULL; Next = 0; Prev = 0; Object = 0; MTInfo = 0; FilledRefs = false; FromDependentHandle = false; GCRefs = 0; } void Remove(RootNode *&list) { RootNode *curr_next = Next; // We've already considered this object, remove it. if (Prev == NULL) { // If we've filtered out the head, update it. list = curr_next; if (curr_next) curr_next->Prev = NULL; } else { // Otherwise remove the current item from the list Prev->Next = curr_next; if (curr_next) curr_next->Prev = Prev; } } }; public: static void <API key>(std::unordered_map<TADDR, std::list<TADDR>> &map); public: // Finds all objects which root "target" and prints the path from the root // to "target". If all is true, all possible paths to the object are printed. // If all is false, only completely unique paths will be printed. int PrintRootsForObject(TADDR obj, bool all, bool noStacks); // Finds a path from root to target if it exists and prints it out. Returns // true if it found a path, false otherwise. bool PrintPathToObject(TADDR root, TADDR target); // Calculates the size of the closure of objects kept alive by root. size_t ObjSize(TADDR root); // Walks each root, printing out the total amount of memory held alive by it. void ObjSize(); // Returns the set of all live objects in the process. const std::unordered_set<TADDR> &GetLiveObjects(bool excludeFQ = false); // See !FindRoots. int FindRoots(int gen, TADDR target); private: // typedefs typedef void (*ReportCallback)(TADDR root, RootNode *path, bool printHeader); // Book keeping and debug. void ClearAll(); void ClearNodes(); void ClearSizeData(); // Printing roots int <API key>(int gen = -1); int <API key>(); int PrintRootsOnThread(DWORD osThreadId); int PrintRootsOnFQ(bool <API key> = false); int <API key>(); int PrintRootsInRange(LinearReadCache &cache, TADDR start, TADDR stop, ReportCallback func, bool printHeader); // Calculate gc root RootNode *FilterRoots(RootNode *&list); RootNode *FindPathToTarget(TADDR root); RootNode *GetGCRefs(RootNode *path, RootNode *node); void <API key>(); //Reporting: void ReportOneHandlePath(const SOSHandleData &handle, RootNode *node, bool printHeader); void ReportOnePath(DWORD thread, const SOSStackRefData &stackRef, RootNode *node, bool printThread, bool printFrame); static void ReportOneFQEntry(TADDR root, RootNode *path, bool printHeader); static void ReportOlderGenEntry(TADDR root, RootNode *path, bool printHeader); void ReportSizeInfo(const SOSHandleData &handle, TADDR obj); void ReportSizeInfo(DWORD thread, const SOSStackRefData &ref, TADDR obj); // Data reads: TADDR ReadPointer(TADDR location); TADDR ReadPointerCached(TADDR location); // Object/MT data: MTInfo *GetMTInfo(TADDR mt); DWORD GetComponents(TADDR obj, TADDR mt); size_t GetSizeOfObject(TADDR obj, MTInfo *info); // RootNode management: RootNode *NewNode(TADDR obj = 0, MTInfo *mtinfo = 0, bool fromDependent = false); void DeleteNode(RootNode *node); private: bool mAll, // Print all roots or just unique roots? mSize; // Print rooting information or total size info? std::list<RootNode*> mCleanupList; // A list of RootNode's we've newed up. This is only used to delete all of them later. std::list<RootNode*> mRootNewList; // A list of unused RootNodes that are free to use instead of having to "new" up more. std::unordered_map<TADDR, MTInfo*> mMTs; // The MethodTable cache which maps from MT -> MethodTable data (size, gcdesc, string typename) std::unordered_map<TADDR, RootNode*> mTargets; // The objects that we are searching for. std::unordered_set<TADDR> mConsidered; // A hashtable of objects we've already visited. std::unordered_map<TADDR, size_t> mSizes; // A mapping from object address to total size of data the object roots. std::unordered_map<TADDR, std::list<TADDR>> mDependentHandleMap; LinearReadCache mCache; // A linear cache which stops us from having to read from the target process more than 1-2 times per object. }; // Helper class used for type-safe bitflags // T - the enum type specifying the individual bit flags // U - the underlying/storage type // Requirement: // sizeof(T) <= sizeof(U) template <typename T, typename U> struct Flags { typedef T UnderlyingType; typedef U BitFlagEnumType; <API key>(sizeof(BitFlagEnumType) <= sizeof(UnderlyingType)); Flags(UnderlyingType v) : m_val(v) { } Flags(BitFlagEnumType v) : m_val(v) { } Flags(const Flags& other) : m_val(other.m_val) { } Flags& operator = (const Flags& other) { m_val = other.m_val; return *this; } Flags operator | (Flags other) const { return Flags<T, U>(m_val | other._val); } void operator |= (Flags other) { m_val |= other.m_val; } Flags operator & (Flags other) const { return Flags<T, U>(m_val & other.m_val); } void operator &= (Flags other) { m_val &= other.m_val; } Flags operator ^ (Flags other) const { return Flags<T, U>(m_val ^ other._val); } void operator ^= (Flags other) { m_val ^= other.m_val; } BOOL operator == (Flags other) const { return m_val == other.m_val; } BOOL operator != (Flags other) const { return m_val != other.m_val; } private: UnderlyingType m_val; }; #ifndef FEATURE_PAL // Flags defining activation policy for COM objects enum CIOptionsBits { cciLatestFx = 0x01, // look in the most recent .NETFx installation cciMatchFx = 0x02, // NYI: Look in the .NETFx installation matching the debuggee's runtime cciAnyFx = 0x04, // look in any .NETFx installation cciFxMask = 0x0f, cciDbiColocated = 0x10, // NYI: Look next to the already loaded DBI module cciDacColocated = 0x20, // Look next to the already loaded DAC module cciDbgPath = 0x40, // Look in all folders in the debuggers symbols and binary path }; typedef Flags<DWORD, CIOptionsBits> CIOptions; HRESULT <API key>( REFCLSID clsid, REFIID iid, LPCWSTR dllName, CIOptions cciOptions, void** ppItf); // A typesafe version of GetProcAddress template <typename T> BOOL GetProcAddressT( ___in PCSTR FunctionName, __in_opt PCWSTR DllName, __inout T* OutFunctionPointer, __inout HMODULE* InOutDllHandle ) { _ASSERTE(InOutDllHandle != NULL); _ASSERTE(OutFunctionPointer != NULL); T FunctionPointer = NULL; HMODULE DllHandle = *InOutDllHandle; if (DllHandle == NULL) { DllHandle = LoadLibraryExW(DllName, NULL, <API key>); if (DllHandle != NULL) *InOutDllHandle = DllHandle; } if (DllHandle != NULL) { FunctionPointer = (T) GetProcAddress(DllHandle, FunctionName); } *OutFunctionPointer = FunctionPointer; return FunctionPointer != NULL; } #endif // FEATURE_PAL struct ImageInfo { ULONG64 modBase; }; HRESULT GetClrModuleImages( ___in IXCLRDataModule* Module, ___in <API key> DesiredType, ___out ImageInfo* FirstAdd); // Helper class used in <API key>() to keep track of explicit EE Frames // (i.e., "internal frames") on the stack. Call Init() with the appropriate // ICorDebugThread3, and this class will initialize itself with the set of internal // frames. You can then call <API key> during your stack walk to // have this class output any internal frames that "precede" (i.e., that are closer to // the leaf than) the specified ICorDebugFrame. class <API key> { private: // TODO: Verify constructor AND destructor is called for each array element // TODO: Comment about hard-coding 1000 ToRelease<<API key>> m_rgpInternalFrame2[1000]; ULONG32 <API key>; ULONG32 m_iInternalFrameCur; public: <API key>(); HRESULT Init(ICorDebugThread3 * pThread3); HRESULT <API key>(ICorDebugFrame * pFrame); private: HRESULT <API key>(); }; #endif // __util_h__
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="de"> <head> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class org.apache.commons.lang3.SerializationUtils (Apache Commons Lang 3.4 API)</title> <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="Uses of Class org.apache.commons.lang3.SerializationUtils (Apache Commons Lang 3.4 API)"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <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><a href="../../../../../org/apache/commons/lang3/SerializationUtils.html" title="class in org.apache.commons.lang3">Class</a></li> <li class="navBarCell1Rev">Use</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>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/commons/lang3/class-use/SerializationUtils.html" target="_top">Frames</a></li> <li><a href="SerializationUtils.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h2 title="Uses of Class org.apache.commons.lang3.SerializationUtils" class="title">Uses of Class<br>org.apache.commons.lang3.SerializationUtils</h2> </div> <div class="classUseContainer">No usage of org.apache.commons.lang3.SerializationUtils</div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </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><a href="../../../../../org/apache/commons/lang3/SerializationUtils.html" title="class in org.apache.commons.lang3">Class</a></li> <li class="navBarCell1Rev">Use</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>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/commons/lang3/class-use/SerializationUtils.html" target="_top">Frames</a></li> <li><a href="SerializationUtils.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> <p class="legalCopy"><small>Copyright & </body> </html>
package org.bouncycastle.crypto.test; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Vector; import org.bouncycastle.crypto.<API key>; import org.bouncycastle.crypto.<API key>; import org.bouncycastle.crypto.engines.NaccacheSternEngine; import org.bouncycastle.crypto.generators.<API key>; import org.bouncycastle.crypto.params.<API key>; import org.bouncycastle.crypto.params.<API key>; import org.bouncycastle.crypto.params.<API key>; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; public class NaccacheSternTest extends SimpleTest { static final boolean debug = false; static final NaccacheSternEngine cryptEng = new NaccacheSternEngine(); static final NaccacheSternEngine decryptEng = new NaccacheSternEngine(); static { cryptEng.setDebug(debug); decryptEng.setDebug(debug); } // Values from NaccacheStern paper static final BigInteger a = BigInteger.valueOf(101); static final BigInteger u1 = BigInteger.valueOf(3); static final BigInteger u2 = BigInteger.valueOf(5); static final BigInteger u3 = BigInteger.valueOf(7); static final BigInteger b = BigInteger.valueOf(191); static final BigInteger v1 = BigInteger.valueOf(11); static final BigInteger v2 = BigInteger.valueOf(13); static final BigInteger v3 = BigInteger.valueOf(17); static final BigInteger ONE = BigInteger.valueOf(1); static final BigInteger TWO = BigInteger.valueOf(2); static final BigInteger sigma = u1.multiply(u2).multiply(u3).multiply(v1) .multiply(v2).multiply(v3); static final BigInteger p = TWO.multiply(a).multiply(u1).multiply(u2) .multiply(u3).add(ONE); static final BigInteger q = TWO.multiply(b).multiply(v1).multiply(v2) .multiply(v3).add(ONE); static final BigInteger n = p.multiply(q); static final BigInteger phi_n = p.subtract(ONE).multiply(q.subtract(ONE)); static final BigInteger g = BigInteger.valueOf(131); static final Vector smallPrimes = new Vector(); // static final BigInteger paperTest = BigInteger.valueOf(202); static final String input = "<SHA256-like>"; static final BigInteger paperTest = BigInteger.valueOf(202); // to check that we handling byte extension by big number correctly. static final String edgeInput = "<SHA256-like>"; public String getName() { return "NaccacheStern"; } public void performTest() { // Test with given key from NaccacheSternPaper (totally insecure) // First the Parameters from the NaccacheStern Paper smallPrimes.addElement(u1); smallPrimes.addElement(u2); smallPrimes.addElement(u3); smallPrimes.addElement(v1); smallPrimes.addElement(v2); smallPrimes.addElement(v3); <API key> pubParameters = new <API key>(false, g, n, sigma.bitLength()); <API key> privParameters = new <API key>(g, n, sigma.bitLength(), smallPrimes, phi_n); <API key> pair = new <API key>(pubParameters, privParameters); // Initialize Engines with KeyPair if (debug) { System.out.println("initializing encryption engine"); } cryptEng.init(true, pair.getPublic()); if (debug) { System.out.println("initializing decryption engine"); } decryptEng.init(false, pair.getPrivate()); byte[] data = paperTest.toByteArray(); if (!new BigInteger(data).equals(new BigInteger(enDeCrypt(data)))) { fail("failed NaccacheStern paper test"); } // key generation test // 768 Bit test if (debug) { System.out.println(); System.out.println("768 Bit TEST"); } // specify key generation parameters <API key> genParam = new <API key>(new SecureRandom(), 768, 8, 30, debug); // Initialize Key generator and generate key pair <API key> pGen = new <API key>(); pGen.init(genParam); pair = pGen.generateKeyPair(); if (((<API key>)pair.getPublic()).getModulus().bitLength() < 768) { System.out.println("FAILED: key size is <786 bit, exactly " + ((<API key>)pair.getPublic()).getModulus().bitLength() + " bit"); fail("failed key generation (768) length test"); } // Initialize Engines with KeyPair if (debug) { System.out.println("initializing " + genParam.getStrength() + " bit encryption engine"); } cryptEng.init(true, pair.getPublic()); if (debug) { System.out.println("initializing " + genParam.getStrength() + " bit decryption engine"); } decryptEng.init(false, pair.getPrivate()); // Basic data input data = Hex.decode(input); if (!new BigInteger(1, data).equals(new BigInteger(1, enDeCrypt(data)))) { fail("failed encryption decryption (" + genParam.getStrength() + ") basic test"); } // Data starting with FF byte (would be interpreted as negative // BigInteger) data = Hex.decode(edgeInput); if (!new BigInteger(1, data).equals(new BigInteger(1, enDeCrypt(data)))) { fail("failed encryption decryption (" + genParam.getStrength() + ") edgeInput test"); } // 1024 Bit Test /* if (debug) { System.out.println(); System.out.println("1024 Bit TEST"); } // specify key generation parameters genParam = new <API key>(new SecureRandom(), 1024, 8, 40); pGen.init(genParam); pair = pGen.generateKeyPair(); if (((<API key>)pair.getPublic()).getModulus().bitLength() < 1024) { if (debug) { System.out.println("FAILED: key size is <1024 bit, exactly " + ((<API key>)pair.getPublic()).getModulus().bitLength() + " bit"); } fail("failed key generation (1024) length test"); } // Initialize Engines with KeyPair if (debug) { System.out.println("initializing " + genParam.getStrength() + " bit encryption engine"); } cryptEng.init(true, pair.getPublic()); if (debug) { System.out.println("initializing " + genParam.getStrength() + " bit decryption engine"); } decryptEng.init(false, pair.getPrivate()); if (debug) { System.out.println("Data is " + new BigInteger(1, data)); } // Basic data input data = Hex.decode(input); if (!new BigInteger(1, data).equals(new BigInteger(1, enDeCrypt(data)))) { fail("failed encryption decryption (" + genParam.getStrength() + ") basic test"); } // Data starting with FF byte (would be interpreted as negative // BigInteger) data = Hex.decode(edgeInput); if (!new BigInteger(1, data).equals(new BigInteger(1, enDeCrypt(data)))) { fail("failed encryption decryption (" + genParam.getStrength() + ") edgeInput test"); } */ // END OF TEST CASE try { new NaccacheSternEngine().processBlock(new byte[]{ 1 }, 0, 1); fail("failed initialisation check"); } catch (<API key> e) { // expected } catch (<API key> e) { fail("failed initialisation check"); } if (debug) { System.out.println("All tests successful"); } } private byte[] enDeCrypt(byte[] input) { // create work array byte[] data = new byte[input.length]; System.arraycopy(input, 0, data, 0, data.length); // Perform encryption like in the paper from Naccache-Stern if (debug) { System.out.println("encrypting data. Data representation\n" // + "As String:.... " + new String(data) + "\n" + "As BigInteger: " + new BigInteger(1, data)); System.out.println("data length is " + data.length); } try { data = cryptEng.processData(data); } catch (<API key> e) { if (debug) { System.out.println("failed - exception " + e.toString() + "\n" + e.getMessage()); } fail("failed - exception " + e.toString() + "\n" + e.getMessage()); } if (debug) { System.out.println("enrypted data representation\n" // + "As String:.... " + new String(data) + "\n" + "As BigInteger: " + new BigInteger(1, data)); System.out.println("data length is " + data.length); } try { data = decryptEng.processData(data); } catch (<API key> e) { if (debug) { System.out.println("failed - exception " + e.toString() + "\n" + e.getMessage()); } fail("failed - exception " + e.toString() + "\n" + e.getMessage()); } if (debug) { System.out.println("decrypted data representation\n" // + "As String:.... " + new String(data) + "\n" + "As BigInteger: " + new BigInteger(1, data)); System.out.println("data length is " + data.length); } return data; } public static void main(String[] args) { runTest(new NaccacheSternTest()); } }
require File.expand_path('../../../spec_helper', __FILE__) describe :rational_quo, shared: true do it "needs to be reviewed for spec completeness" end
<?php namespace Symfony\Component\Security\Core\Authorization\Voter; interface <API key> extends VoterInterface { public function supportsAttribute(string $attribute): bool; /** * @param string $subjectType The type of the subject inferred by `get_class` or `get_debug_type` */ public function supportsType(string $subjectType): bool; }
})(); Clazz._coreLoaded = true;
// Don't need this for our purposes module = function(){}; if(typeof equal != 'undefined') { equals = equal; } ok = function(actual, message) { equal(actual, true, message); } raises = function(fn, expected, message) { raisesError(fn, message); }; asyncTest = function(name, delay, fn) { test(name, fn); } start = function() { // Just pass through... } notStrictEqual = function(a, b, message) { equal(a === b, false, message); } var ensureArray = function(obj) { if(obj === null) { return []; } else if(Object.isArray(obj) && (!obj.indexOf || !obj.lastIndexOf)) { return obj.concat(); } else if(!Object.isArray(obj) && typeof obj == 'object') { return Array.prototype.slice.call(obj); } else { return obj; } } var CompatibleMethods = [ { module: Array.prototype, methods: [ { name: 'first', method: function(arr, n, guard){ if(guard) { return arr[0]; } return ensureArray(arr).first(n); } }, { name: 'last', method: function(arr, n, third){ // This is the same check that Underscore makes to hack // _.last to work with _.map if(third) n = 1; return ensureArray(arr).last(n); } }, { name: 'rest', method: function(arr, n, guard){ if(n === undefined) n = 1; if(guard) { return arr.slice(1); } return ensureArray(arr).from(n); } }, { name: 'compact', method: function(arr){ return ensureArray(arr).compact(true); } }, /* Object.extend is no longer compatible as it has conflict resolution now. { name: 'extend', method: function(){ return Object.SugarMethods['merge'].method.apply(this, arguments); } }, */ /* Array#flatten is no longer compatible as it has levels of flattening (not just deep/shallow) { name: 'flatten', method: function(arr){ return ensureArray(arr).flatten(); } }, */ { name: 'uniq', method: function(arr){ return ensureArray(arr).unique(); } }, { name: 'intersection', method: function(arr){ arr = ensureArray(arr); var args = Array.prototype.slice.call(arguments, 1); return Array.prototype.intersect.apply(arr, args); } }, { name: 'union', method: function(arr, a){ arr = ensureArray(arr); var args = Array.prototype.slice.call(arguments, 1); return Array.prototype.union.apply(arr, args); } }, /* { name: 'difference', method: function(arr, a){ arr = ensureArray(arr); var args = Array.prototype.slice.call(arguments, 1); return Array.prototype.subtract.apply(arr, args); } }, */ { name: 'indexOf', method: function(arr, a){ return ensureArray(arr).indexOf(a); } }, { name: 'lastIndexOf', method: function(arr, a){ return ensureArray(arr).lastIndexOf(a); } }, { name: 'range', method: function(start, stop, step){ if(arguments.length == 1){ stop = arguments[0]; start = 0; } var shift = step < 0 ? 1 : -1; return start.upto(stop + shift, null, step); } }, // Collections // _.each -> Array#forEach OR Object.each // _.map -> Array#map // _.reduce -> Array#reduce // _.reduceRight -> Array#reduceRight // _.invoke is doing some strange tapdancing for passing methods directly... // _.sortedIndex ... no direct equivalent // _.toArray ... no direct equivalent for arguments... Array.create? // _.size ... no direct equivalent for objects... obj.keys().length? { name: 'detect', method: function(arr, fn, context){ return Array.SugarMethods['find'].method.call(arr, fn.bind(context)); } }, { name: 'select', method: function(arr, fn, context){ return Array.SugarMethods['findAll'].method.call(arr, fn.bind(context)); } }, { name: 'reject', method: function(arr, fn, context){ return Array.SugarMethods['exclude'].method.call(arr, fn.bind(context)); } }, { name: 'all', method: function(arr, fn, context){ return Array.SugarMethods['all'].method.call(arr, fn.bind(context)); } }, { name: 'any', method: function(arr, fn, context){ if(!fn) fn = function(a){ return a; }; return Array.SugarMethods['some'].method.call(arr, fn.bind(context)); } }, /* { name: 'include', method: function(arr, val){ return Array.SugarMethods['has'].method.call(arr, val); } }, */ { name: 'pluck', method: function(arr, prop){ return Array.SugarMethods['map'].method.call(arr, prop); } }, { name: 'max', method: function(arr, fn, context){ if(!fn) fn = function(a){ return a; }; return Array.SugarMethods['max'].method.call(arr, fn.bind(context))[0]; } }, { name: 'min', method: function(arr, fn, context){ if(!fn) fn = function(a){ return a; }; return Array.SugarMethods['min'].method.call(arr, fn.bind(context))[0]; } }, { name: 'sortBy', method: function(arr, fn, context){ return Array.SugarMethods['sortBy'].method.call(arr, fn.bind(context)); } }, { name: 'groupBy', method: function(arr, fn){ return Array.SugarMethods['groupBy'].method.call(arr, fn); } }, // Objects // _.functions ... no direct equivalent // _.defaults ... no direct equivalent // _.tap ... no direct equivalent // _.isElement ... no direct equivalent // _.isArguments ... no direct equivalent // _.isNaN ... no direct equivalent // _.isNull ... no direct equivalent // _.isUndefined ... no direct equivalent { name: 'keys', method: function(){ return Object.SugarMethods['keys'].method.apply(this, arguments); } }, { name: 'values', method: function(){ return Object.SugarMethods['values'].method.apply(this, arguments); } }, { name: 'clone', method: function(){ return Object.SugarMethods['clone'].method.apply(this, arguments); } }, { name: 'isEqual', method: function(a, b){ if (a && a._chain) a = a._wrapped; if (b && b._chain) b = b._wrapped; if (a && a.isEqual) return a.isEqual(b); if (b && b.isEqual) return b.isEqual(a); return Object.SugarMethods['equal'].method.apply(this, arguments); } }, { name: 'isEmpty', method: function(){ return Object.SugarMethods['isEmpty'].method.apply(this, arguments); } }, { name: 'isArray', method: function(arr){ return Array.isArray(arr); } }, { name: 'isFunction', method: function(){ return Object.SugarMethods['isFunction'].method.apply(this, arguments); } }, { name: 'isString', method: function(){ return Object.SugarMethods['isString'].method.apply(this, arguments); } }, { name: 'isNumber', method: function(){ if(isNaN(arguments[0])) { // Sugar differs here as it's trying to stay aligned with Javascript and is // checking types only. return false; } return Object.SugarMethods['isNumber'].method.apply(this, arguments); } }, { name: 'isBoolean', method: function(){ return Object.SugarMethods['isBoolean'].method.apply(this, arguments); } }, { name: 'isDate', method: function(){ return Object.SugarMethods['isDate'].method.apply(this, arguments); } }, { name: 'isRegExp', method: function(){ return Object.SugarMethods['isRegExp'].method.apply(this, arguments); } }, // Functions // _.bindAll ... no direct equivalent (similar to bindAsEventListener??) // _.memoize ... no direct equivalent // _.debounce ... no direct equivalent // _.once ... no direct equivalent.. is this not similar to memoize? // _.wrap ... no direct equivalent.. // _.compose ... no direct equivalent.. math stuff { name: 'bind', method: function(fn){ var args = Array.prototype.slice.call(arguments, 1); return Function.prototype.bind.apply(fn, args); } }, { name: 'after', method: function(num, fn){ return Function.prototype.after.apply(fn, [num]); } }, { name: 'delay', method: function(fn){ var args = Array.prototype.slice.call(arguments, 1); return Function.prototype.delay.apply(fn, args); } }, { name: 'defer', method: function(fn){ var args = Array.prototype.slice.call(arguments, 1); return Function.prototype.delay.apply(fn, [1].concat(args)); } }, { name: 'throttle', method: function(fn, wait){ return Function.prototype.lazy.apply(fn, [wait]); } }, // Utility // _.noConflict ... no direct equivalent // _.identity ... no direct equivalent // _.mixin ... no direct equivalent // _.uniqueId ... no direct equivalent // _.template ... no direct equivalent // _.chain ... no direct equivalent // _.value ... no direct equivalent { name: 'times', method: function(n, fn){ return n.times(fn); } } ] } ]; var mapMethods = function() { var proto; CompatibleMethods.forEach(function(cm) { cm.methods.forEach(function(m) { _[m.name] = m.method; }); }); } mapMethods();
package aima.core.probability.util; import java.util.HashSet; import java.util.Map; import java.util.Set; import aima.core.probability.RandomVariable; import aima.core.probability.domain.Domain; import aima.core.probability.proposition.TermProposition; /** * Default implementation of the RandomVariable interface. * * Note: Also implements the TermProposition interface so its easy to use * RandomVariables in conjunction with propositions about them in the * Probability Model APIs. * * @author Ciaran O'Reilly */ public class RandVar implements RandomVariable, TermProposition { private String name = null; private Domain domain = null; private Set<RandomVariable> scope = new HashSet<RandomVariable>(); public RandVar(String name, Domain domain) { ProbUtil.<API key>(name); if (null == domain) { throw new <API key>( "Domain of RandomVariable must be specified."); } this.name = name; this.domain = domain; this.scope.add(this); } // <API key> @Override public String getName() { return name; } @Override public Domain getDomain() { return domain; } // END-RandomVariable // <API key> @Override public RandomVariable getTermVariable() { return this; } @Override public Set<RandomVariable> getScope() { return scope; } @Override public Set<RandomVariable> getUnboundScope() { return scope; } @Override public boolean holds(Map<RandomVariable, Object> possibleWorld) { return possibleWorld.containsKey(getTermVariable()); } // END-TermProposition @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof RandomVariable)) { return false; } // The name (not the name:domain combination) uniquely identifies a // Random Variable RandomVariable other = (RandomVariable) o; return this.name.equals(other.getName()); } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { return getName(); } }
#include <spine/EventData.h> #include <spine/extension.h> spEventData* spEventData_create (const char* name) { spEventData* self = NEW(spEventData); MALLOC_STR(self->name, name); return self; } void spEventData_dispose (spEventData* self) { FREE(self->stringValue); FREE(self->name); FREE(self); }
package aima.core.probability.bayes.exact; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import aima.core.probability.<API key>; import aima.core.probability.Factor; import aima.core.probability.RandomVariable; import aima.core.probability.bayes.BayesInference; import aima.core.probability.bayes.BayesianNetwork; import aima.core.probability.bayes.FiniteNode; import aima.core.probability.bayes.Node; import aima.core.probability.proposition.<API key>; import aima.core.probability.util.ProbabilityTable; /** * Artificial Intelligence A Modern Approach (3rd Edition): Figure 14.11, page * 528.<br> * <br> * * <pre> * function ELIMINATION-ASK(X, e, bn) returns a distribution over X * inputs: X, the query variable * e, observed values for variables E * bn, a Bayesian network specifying joint distribution P(X<sub>1</sub>, ..., X<sub>n</sub>) * * factors <- [] * for each var in ORDER(bn.VARS) do * factors <- [MAKE-FACTOR(var, e) | factors] * if var is hidden variable the factors <- SUM-OUT(var, factors) * return NORMALIZE(POINTWISE-PRODUCT(factors)) * </pre> * * Figure 14.11 The variable elimination algorithm for inference in Bayesian * networks. <br> * <br> * <b>Note:</b> The implementation has been extended to handle queries with * multiple variables. <br> * * @author Ciaran O'Reilly */ public class EliminationAsk implements BayesInference { private static final ProbabilityTable _identity = new ProbabilityTable( new double[] { 1.0 }); public EliminationAsk() { } // function ELIMINATION-ASK(X, e, bn) returns a distribution over X * a Bayes net with variables {X} &cup; E &cup; Y /* Y = hidden * variables // * @return a distribution over the query variables. */ public <API key> eliminationAsk(final RandomVariable[] X, final <API key>[] e, final BayesianNetwork bn) { Set<RandomVariable> hidden = new HashSet<RandomVariable>(); List<RandomVariable> VARS = new ArrayList<RandomVariable>(); calculateVariables(X, e, bn, hidden, VARS); // factors <- [] List<Factor> factors = new ArrayList<Factor>(); // for each var in ORDER(bn.VARS) do for (RandomVariable var : order(bn, VARS)) { // factors <- [MAKE-FACTOR(var, e) | factors] factors.add(0, makeFactor(var, e, bn)); // if var is hidden variable then factors <- SUM-OUT(var, factors) if (hidden.contains(var)) { factors = sumOut(var, factors, bn); } } // return NORMALIZE(POINTWISE-PRODUCT(factors)) Factor product = pointwiseProduct(factors); // Note: Want to ensure the order of the product matches the // query variables return ((ProbabilityTable) product.pointwiseProductPOS(_identity, X)) .normalize(); } // <API key> public <API key> ask(final RandomVariable[] X, final <API key>[] observedEvidence, final BayesianNetwork bn) { return this.eliminationAsk(X, observedEvidence, bn); } // END-BayesInference // PROTECTED METHODS * a Bayes net with variables {X} &cup; E &cup; Y /* Y = hidden * variables // * @param hidden * to be populated with the relevant hidden variables Y. * @param bnVARS * to be populated with the subset of the random variables * comprising the Bayesian Network with any irrelevant hidden * variables removed. */ protected void calculateVariables(final RandomVariable[] X, final <API key>[] e, final BayesianNetwork bn, Set<RandomVariable> hidden, Collection<RandomVariable> bnVARS) { bnVARS.addAll(bn.<API key>()); hidden.addAll(bnVARS); for (RandomVariable x : X) { hidden.remove(x); } for (<API key> ap : e) { hidden.removeAll(ap.getScope()); } return; } /** * <b>Note:</b>Override this method for a more efficient implementation as * outlined in AIMA3e pgs. 527-28. The default implementation does not * perform any of these.<br> * * @param bn * the Bayesian Network over which the query is being made. Note, * is necessary to provide this in order to be able to determine * the dependencies between variables. * @param vars * a subset of the RandomVariables making up the Bayesian * Network, with any irrelevant hidden variables alreay removed. * @return a possibly opimal ordering for the random variables to be * iterated over by the algorithm. For example, one fairly effective * ordering is a greedy one: eliminate whichever variable minimizes * the size of the next factor to be constructed. */ protected List<RandomVariable> order(BayesianNetwork bn, Collection<RandomVariable> vars) { // Note: Trivial Approach: // For simplicity just return in the reverse order received, // i.e. received will be the default topological order for // the Bayesian Network and we want to ensure the network // is iterated from bottom up to ensure when hidden variables // are come across all the factors dependent on them have // been seen so far. List<RandomVariable> order = new ArrayList<RandomVariable>(vars); Collections.reverse(order); return order; } // PRIVATE METHODS private Factor makeFactor(RandomVariable var, <API key>[] e, BayesianNetwork bn) { Node n = bn.getNode(var); if (!(n instanceof FiniteNode)) { throw new <API key>( "Elimination-Ask only works with finite Nodes."); } FiniteNode fn = (FiniteNode) n; List<<API key>> evidence = new ArrayList<<API key>>(); for (<API key> ap : e) { if (fn.getCPT().contains(ap.getTermVariable())) { evidence.add(ap); } } return fn.getCPT().getFactorFor( evidence.toArray(new <API key>[evidence.size()])); } private List<Factor> sumOut(RandomVariable var, List<Factor> factors, BayesianNetwork bn) { List<Factor> summedOutFactors = new ArrayList<Factor>(); List<Factor> toMultiply = new ArrayList<Factor>(); for (Factor f : factors) { if (f.contains(var)) { toMultiply.add(f); } else { // This factor does not contain the variable // so no need to sum out - see AIMA3e pg. 527. summedOutFactors.add(f); } } summedOutFactors.add(pointwiseProduct(toMultiply).sumOut(var)); return summedOutFactors; } private Factor pointwiseProduct(List<Factor> factors) { Factor product = factors.get(0); for (int i = 1; i < factors.size(); i++) { product = product.pointwiseProduct(factors.get(i)); } return product; } }
namespace Microsoft.OData.Client { using Microsoft.OData.Core; <summary> Arguments used to configure the odata message reader settings. </summary> public class <API key> { <summary> Initializes a new instance of the <see cref="<API key>"/> class. </summary> <param name="settings">The settings.</param> public <API key>(<API key> settings) { WebUtil.CheckArgumentNull(settings, "settings"); this.Settings = settings; } <summary> Gets the settings. </summary> public <API key> Settings { get; private set; } } }
if (typeof jQuery === 'undefined') { throw new Error('Tempus Dominus Bootstrap4\'s requires jQuery. jQuery must be included before Tempus Dominus Bootstrap4\'s JavaScript.'); } +function ($) { var version = $.fn.jquery.split(' ')[0].split('.'); if ((version[0] < 2 && version[1] < 9) || (version[0] === 1 && version[1] === 9 && version[2] < 1) || (version[0] >= 4)) { throw new Error('Tempus Dominus Bootstrap4\'s requires at least jQuery v1.9.1 but less than v4.0.0'); } }(jQuery); if (typeof moment === 'undefined') { throw new Error('Tempus Dominus Bootstrap4\'s requires moment.js. Moment.js must be included before Tempus Dominus Bootstrap4\'s JavaScript.'); } var version = moment.version.split('.') if ((version[0] <= 2 && version[1] < 17) || (version[0] >= 3)) { throw new Error('Tempus Dominus Bootstrap4\'s requires at least moment.js v2.17.0 but less than v3.0.0'); } +function () { var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function <API key>(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // ReSharper disable once InconsistentNaming var DateTimePicker = function ($, moment) { // ReSharper disable InconsistentNaming var NAME = 'datetimepicker', VERSION = '5.0.0-alpha7', DATA_KEY = '' + NAME, EVENT_KEY = '.' + DATA_KEY, EMIT_EVENT_KEY = DATA_KEY + '.', DATA_API_KEY = '.data-api', Selector = { DATA_TOGGLE: '[data-toggle="' + DATA_KEY + '"]' }, ClassName = { INPUT: NAME + '-input' }, Event = { CHANGE: 'change' + EVENT_KEY, BLUR: 'blur' + EVENT_KEY, KEYUP: 'keyup' + EVENT_KEY, KEYDOWN: 'keydown' + EVENT_KEY, FOCUS: 'focus' + EVENT_KEY, CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY, //emitted UPDATE: EMIT_EVENT_KEY + 'update', ERROR: EMIT_EVENT_KEY + 'error', HIDE: EMIT_EVENT_KEY + 'hide', SHOW: EMIT_EVENT_KEY + 'show' }, Default = { timeZone: '', format: false, dayViewHeaderFormat: 'MMMM YYYY', extraFormats: false, stepping: 1, minDate: false, maxDate: false, useCurrent: true, collapse: true, locale: moment.locale(), defaultDate: false, disabledDates: false, enabledDates: false, icons: { time: 'fa fa-clock-o', date: 'fa fa-calendar', up: 'fa fa-arrow-up', down: 'fa fa-arrow-down', previous: 'fa fa-chevron-left', next: 'fa fa-chevron-right', today: 'fa fa-calendar-check-o', clear: 'fa fa-delete', close: 'fa fa-times' }, tooltips: { today: 'Go to today', clear: 'Clear selection', close: 'Close the picker', selectMonth: 'Select Month', prevMonth: 'Previous Month', nextMonth: 'Next Month', selectYear: 'Select Year', prevYear: 'Previous Year', nextYear: 'Next Year', selectDecade: 'Select Decade', prevDecade: 'Previous Decade', nextDecade: 'Next Decade', prevCentury: 'Previous Century', nextCentury: 'Next Century', pickHour: 'Pick Hour', incrementHour: 'Increment Hour', decrementHour: 'Decrement Hour', pickMinute: 'Pick Minute', incrementMinute: 'Increment Minute', decrementMinute: 'Decrement Minute', pickSecond: 'Pick Second', incrementSecond: 'Increment Second', decrementSecond: 'Decrement Second', togglePeriod: 'Toggle Period', selectTime: 'Select Time', selectDate: 'Select Date' }, useStrict: false, sideBySide: false, daysOfWeekDisabled: false, calendarWeeks: false, viewMode: 'days', toolbarPlacement: 'default', buttons: { showToday: false, showClear: false, showClose: false }, widgetPositioning: { horizontal: 'auto', vertical: 'auto' }, widgetParent: null, ignoreReadonly: false, keepOpen: false, focusOnShow: true, inline: false, keepInvalid: false, keyBinds: { up: function up() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(7, 'd')); } else { this.date(d.clone().add(this.stepping(), 'm')); } return true; }, down: function down() { if (!this.widget) { this.show(); return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(7, 'd')); } else { this.date(d.clone().subtract(this.stepping(), 'm')); } return true; }, 'control up': function controlUp() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'y')); } else { this.date(d.clone().add(1, 'h')); } return true; }, 'control down': function controlDown() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'y')); } else { this.date(d.clone().subtract(1, 'h')); } return true; }, left: function left() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'd')); } return true; }, right: function right() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'd')); } return true; }, pageUp: function pageUp() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'M')); } return true; }, pageDown: function pageDown() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'M')); } return true; }, enter: function enter() { this.hide(); return true; }, escape: function escape() { if (!this.widget) { return false; } this.hide(); return true; }, 'control space': function controlSpace() { if (!this.widget) { return false; } if (this.widget.find('.timepicker').is(':visible')) { this.widget.find('.btn[data-action="togglePeriod"]').click(); } return true; }, t: function t() { this.date(this.getMoment()); return true; }, 'delete': function _delete() { if (!this.widget) { return false; } this.clear(); return true; } }, debug: false, allowInputToggle: false, <API key>: false, disabledHours: false, enabledHours: false, viewDate: false, allowMultidate: false, multidateSeparator: ',' }, DatePickerModes = [{ CLASS_NAME: 'days', NAV_FUNCTION: 'M', NAV_STEP: 1 }, { CLASS_NAME: 'months', NAV_FUNCTION: 'y', NAV_STEP: 1 }, { CLASS_NAME: 'years', NAV_FUNCTION: 'y', NAV_STEP: 10 }, { CLASS_NAME: 'decades', NAV_FUNCTION: 'y', NAV_STEP: 100 }], KeyMap = { 'up': 38, 38: 'up', 'down': 40, 40: 'down', 'left': 37, 37: 'left', 'right': 39, 39: 'right', 'tab': 9, 9: 'tab', 'escape': 27, 27: 'escape', 'enter': 13, 13: 'enter', 'pageUp': 33, 33: 'pageUp', 'pageDown': 34, 34: 'pageDown', 'shift': 16, 16: 'shift', 'control': 17, 17: 'control', 'space': 32, 32: 'space', 't': 84, 84: 't', 'delete': 46, 46: 'delete' }, ViewModes = ['times', 'days', 'months', 'years', 'decades'], keyState = {}, keyPressHandled = {}; var MinViewModeNumber = 0; // ReSharper restore InconsistentNaming // ReSharper disable once DeclarationHides // ReSharper disable once InconsistentNaming var DateTimePicker = function () { /** @namespace eData.dateOptions */ /** @namespace moment.tz */ function DateTimePicker(element, options) { _classCallCheck(this, DateTimePicker); this._options = this._getOptions(options); this._element = element; this._dates = []; this._datesFormatted = []; this._viewDate = null; this.unset = true; this.component = false; this.widget = false; this.use24Hours = null; this.actualFormat = null; this.parseFormats = null; this.currentViewMode = null; this._int(); } /** * @return {string} */ //private DateTimePicker.prototype._int = function _int() { var targetInput = this._element.data('target-input'); if (this._element.is('input')) { this.input = this._element; } else if (targetInput !== undefined) { if (targetInput === 'nearest') { this.input = this._element.find('input'); } else { this.input = $(targetInput); } } this._dates = []; this._dates[0] = this.getMoment(); this._viewDate = this.getMoment().clone(); $.extend(true, this._options, this._dataToOptions()); this.options(this._options); this._initFormatting(); if (this.input !== undefined && this.input.is('input') && this.input.val().trim().length !== 0) { this._setValue(this._parseInputDate(this.input.val().trim()), 0); } else if (this._options.defaultDate && this.input !== undefined && this.input.attr('placeholder') === undefined) { this._setValue(this._options.defaultDate, 0); } if (this._options.inline) { this.show(); } }; DateTimePicker.prototype._update = function _update() { if (!this.widget) { return; } this._fillDate(); this._fillTime(); }; DateTimePicker.prototype._setValue = function _setValue(targetMoment, index) { var oldDate = this.unset ? null : this._dates[index]; var outpValue = ''; // case of calling setValue(null or false) if (!targetMoment) { if (!this._options.allowMultidate || this._dates.length === 1) { this.unset = true; this._dates = []; this._datesFormatted = []; } else { outpValue = this._element.data('date') + ','; outpValue = outpValue.replace(oldDate.format(this.actualFormat) + ',', '').replace(',,', '').replace(/,\s*$/, ''); this._dates.splice(index, 1); this._datesFormatted.splice(index, 1); } if (this.input !== undefined) { this.input.val(outpValue); this.input.trigger('input'); } this._element.data('date', outpValue); this._notifyEvent({ type: DateTimePicker.Event.CHANGE, date: false, oldDate: oldDate }); this._update(); return; } targetMoment = targetMoment.clone().locale(this._options.locale); if (this._hasTimeZone()) { targetMoment.tz(this._options.timeZone); } if (this._options.stepping !== 1) { targetMoment.minutes(Math.round(targetMoment.minutes() / this._options.stepping) * this._options.stepping).seconds(0); } if (this._isValid(targetMoment)) { this._dates[index] = targetMoment; this._datesFormatted[index] = targetMoment.format('YYYY-MM-DD'); this._viewDate = targetMoment.clone(); if (this._options.allowMultidate && this._dates.length > 1) { for (var i = 0; i < this._dates.length; i++) { outpValue += '' + this._dates[i].format(this.actualFormat) + this._options.multidateSeparator; } outpValue = outpValue.replace(/,\s*$/, ''); } else { outpValue = this._dates[index].format(this.actualFormat); } if (this.input !== undefined) { this.input.val(outpValue); this.input.trigger('input'); } this._element.data('date', outpValue); this.unset = false; this._update(); this._notifyEvent({ type: DateTimePicker.Event.CHANGE, date: this._dates[index].clone(), oldDate: oldDate }); } else { if (!this._options.keepInvalid) { if (this.input !== undefined) { this.input.val('' + (this.unset ? '' : this._dates[index].format(this.actualFormat))); this.input.trigger('input'); } } else { this._notifyEvent({ type: DateTimePicker.Event.CHANGE, date: targetMoment, oldDate: oldDate }); } this._notifyEvent({ type: DateTimePicker.Event.ERROR, date: targetMoment, oldDate: oldDate }); } }; DateTimePicker.prototype._change = function _change(e) { var val = $(e.target).val().trim(), parsedDate = val ? this._parseInputDate(val) : null; this._setValue(parsedDate); e.<API key>(); return false; }; //noinspection JSMethodCanBeStatic DateTimePicker.prototype._getOptions = function _getOptions(options) { options = $.extend(true, {}, Default, options); return options; }; DateTimePicker.prototype._hasTimeZone = function _hasTimeZone() { return moment.tz !== undefined && this._options.timeZone !== undefined && this._options.timeZone !== null && this._options.timeZone !== ''; }; DateTimePicker.prototype._isEnabled = function _isEnabled(granularity) { if (typeof granularity !== 'string' || granularity.length > 1) { throw new TypeError('isEnabled expects a single character string parameter'); } switch (granularity) { case 'y': return this.actualFormat.indexOf('Y') !== -1; case 'M': return this.actualFormat.indexOf('M') !== -1; case 'd': return this.actualFormat.toLowerCase().indexOf('d') !== -1; case 'h': case 'H': return this.actualFormat.toLowerCase().indexOf('h') !== -1; case 'm': return this.actualFormat.indexOf('m') !== -1; case 's': return this.actualFormat.indexOf('s') !== -1; default: return false; } }; DateTimePicker.prototype._hasTime = function _hasTime() { return this._isEnabled('h') || this._isEnabled('m') || this._isEnabled('s'); }; DateTimePicker.prototype._hasDate = function _hasDate() { return this._isEnabled('y') || this._isEnabled('M') || this._isEnabled('d'); }; DateTimePicker.prototype._dataToOptions = function _dataToOptions() { var eData = this._element.data(); var dataOptions = {}; if (eData.dateOptions && eData.dateOptions instanceof Object) { dataOptions = $.extend(true, dataOptions, eData.dateOptions); } $.each(this._options, function (key) { var attributeName = 'date' + key.charAt(0).toUpperCase() + key.slice(1); //todo data api key if (eData[attributeName] !== undefined) { dataOptions[key] = eData[attributeName]; } else { delete dataOptions[key]; } }); return dataOptions; }; DateTimePicker.prototype._notifyEvent = function _notifyEvent(e) { if (e.type === DateTimePicker.Event.CHANGE && e.date && e.date.isSame(e.oldDate) || !e.date && !e.oldDate) { return; } this._element.trigger(e); }; DateTimePicker.prototype._viewUpdate = function _viewUpdate(e) { if (e === 'y') { e = 'YYYY'; } this._notifyEvent({ type: DateTimePicker.Event.UPDATE, change: e, viewDate: this._viewDate.clone() }); }; DateTimePicker.prototype._showMode = function _showMode(dir) { if (!this.widget) { return; } if (dir) { this.currentViewMode = Math.max(MinViewModeNumber, Math.min(3, this.currentViewMode + dir)); } this.widget.find('.datepicker > div').hide().filter('.datepicker-' + DatePickerModes[this.currentViewMode].CLASS_NAME).show(); }; DateTimePicker.prototype._isInDisabledDates = function _isInDisabledDates(testDate) { return this._options.disabledDates[testDate.format('YYYY-MM-DD')] === true; }; DateTimePicker.prototype._isInEnabledDates = function _isInEnabledDates(testDate) { return this._options.enabledDates[testDate.format('YYYY-MM-DD')] === true; }; DateTimePicker.prototype._isInDisabledHours = function _isInDisabledHours(testDate) { return this._options.disabledHours[testDate.format('H')] === true; }; DateTimePicker.prototype._isInEnabledHours = function _isInEnabledHours(testDate) { return this._options.enabledHours[testDate.format('H')] === true; }; DateTimePicker.prototype._isValid = function _isValid(targetMoment, granularity) { if (!targetMoment.isValid()) { return false; } if (this._options.disabledDates && granularity === 'd' && this._isInDisabledDates(targetMoment)) { return false; } if (this._options.enabledDates && granularity === 'd' && !this._isInEnabledDates(targetMoment)) { return false; } if (this._options.minDate && targetMoment.isBefore(this._options.minDate, granularity)) { return false; } if (this._options.maxDate && targetMoment.isAfter(this._options.maxDate, granularity)) { return false; } if (this._options.daysOfWeekDisabled && granularity === 'd' && this._options.daysOfWeekDisabled.indexOf(targetMoment.day()) !== -1) { return false; } if (this._options.disabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && this._isInDisabledHours(targetMoment)) { return false; } if (this._options.enabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && !this._isInEnabledHours(targetMoment)) { return false; } if (this._options.<API key> && (granularity === 'h' || granularity === 'm' || granularity === 's')) { var found = false; $.each(this._options.<API key>, function () { if (targetMoment.isBetween(this[0], this[1])) { found = true; return false; } }); if (found) { return false; } } return true; }; DateTimePicker.prototype._parseInputDate = function _parseInputDate(inputDate) { if (this._options.parseInputDate === undefined) { if (!moment.isMoment(inputDate)) { inputDate = this.getMoment(inputDate); } } else { inputDate = this._options.parseInputDate(inputDate); } //inputDate.locale(this.options.locale); return inputDate; }; DateTimePicker.prototype._keydown = function _keydown(e) { var handler = null, index = void 0, index2 = void 0, keyBindKeys = void 0, allModifiersPressed = void 0; var pressedKeys = [], pressedModifiers = {}, currentKey = e.which, pressed = 'p'; keyState[currentKey] = pressed; for (index in keyState) { if (keyState.hasOwnProperty(index) && keyState[index] === pressed) { pressedKeys.push(index); if (parseInt(index, 10) !== currentKey) { pressedModifiers[index] = true; } } } for (index in this._options.keyBinds) { if (this._options.keyBinds.hasOwnProperty(index) && typeof this._options.keyBinds[index] === 'function') { keyBindKeys = index.split(' '); if (keyBindKeys.length === pressedKeys.length && KeyMap[currentKey] === keyBindKeys[keyBindKeys.length - 1]) { allModifiersPressed = true; for (index2 = keyBindKeys.length - 2; index2 >= 0; index2 if (!(KeyMap[keyBindKeys[index2]] in pressedModifiers)) { allModifiersPressed = false; break; } } if (allModifiersPressed) { handler = this._options.keyBinds[index]; break; } } } } if (handler) { if (handler.call(this.widget)) { e.stopPropagation(); e.preventDefault(); } } }; //noinspection JSMethodCanBeStatic,<API key> DateTimePicker.prototype._keyup = function _keyup(e) { keyState[e.which] = 'r'; if (keyPressHandled[e.which]) { keyPressHandled[e.which] = false; e.stopPropagation(); e.preventDefault(); } }; DateTimePicker.prototype._indexGivenDates = function _indexGivenDates(givenDatesArray) { // Store given enabledDates and disabledDates as keys. // This way we can check their existence in O(1) time instead of looping through whole array. var givenDatesIndexed = {}, self = this; $.each(givenDatesArray, function () { var dDate = self._parseInputDate(this); if (dDate.isValid()) { givenDatesIndexed[dDate.format('YYYY-MM-DD')] = true; } }); return Object.keys(givenDatesIndexed).length ? givenDatesIndexed : false; }; DateTimePicker.prototype._indexGivenHours = function _indexGivenHours(givenHoursArray) { // Store given enabledHours and disabledHours as keys. // This way we can check their existence in O(1) time instead of looping through whole array. var givenHoursIndexed = {}; $.each(givenHoursArray, function () { givenHoursIndexed[this] = true; }); return Object.keys(givenHoursIndexed).length ? givenHoursIndexed : false; }; DateTimePicker.prototype._initFormatting = function _initFormatting() { var format = this._options.format || 'L LT', self = this; this.actualFormat = format.replace(/(\[[^\[]*])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput) { return self._dates[0].localeData().longDateFormat(formatInput) || formatInput; //todo taking the first date should be ok }); this.parseFormats = this._options.extraFormats ? this._options.extraFormats.slice() : []; if (this.parseFormats.indexOf(format) < 0 && this.parseFormats.indexOf(this.actualFormat) < 0) { this.parseFormats.push(this.actualFormat); } this.use24Hours = this.actualFormat.toLowerCase().indexOf('a') < 1 && this.actualFormat.replace(/\[.*?]/g, '').indexOf('h') < 1; if (this._isEnabled('y')) { MinViewModeNumber = 2; } if (this._isEnabled('M')) { MinViewModeNumber = 1; } if (this._isEnabled('d')) { MinViewModeNumber = 0; } this.currentViewMode = Math.max(MinViewModeNumber, this.currentViewMode); if (!this.unset) { this._setValue(this._dates[0], 0); } }; DateTimePicker.prototype._getLastPickedDate = function _getLastPickedDate() { return this._dates[this.<API key>()]; }; DateTimePicker.prototype.<API key> = function <API key>() { return this._dates.length - 1; }; //public DateTimePicker.prototype.getMoment = function getMoment(d) { var returnMoment = void 0; if (d === undefined || d === null) { returnMoment = moment(); //TODO should this use format? and locale? } else if (this._hasTimeZone()) { // There is a string to parse and a default time zone // parse with the tz function which takes a default time zone if it is not in the format string returnMoment = moment.tz(d, this.parseFormats, this._options.useStrict, this._options.timeZone); } else { returnMoment = moment(d, this.parseFormats, this._options.useStrict); } if (this._hasTimeZone()) { returnMoment.tz(this._options.timeZone); } return returnMoment; }; DateTimePicker.prototype.toggle = function toggle() { return this.widget ? this.hide() : this.show(); }; DateTimePicker.prototype.ignoreReadonly = function ignoreReadonly(_ignoreReadonly) { if (arguments.length === 0) { return this._options.ignoreReadonly; } if (typeof _ignoreReadonly !== 'boolean') { throw new TypeError('ignoreReadonly () expects a boolean parameter'); } this._options.ignoreReadonly = _ignoreReadonly; }; DateTimePicker.prototype.options = function options(newOptions) { if (arguments.length === 0) { return $.extend(true, {}, this._options); } if (!(newOptions instanceof Object)) { throw new TypeError('options() this.options parameter should be an object'); } $.extend(true, this._options, newOptions); var self = this; $.each(this._options, function (key, value) { if (self[key] !== undefined) { self[key](value); } }); }; DateTimePicker.prototype.date = function date(newDate, index) { index = index || 0; if (arguments.length === 0) { if (this.unset) { return null; } if (this._options.allowMultidate) { return this._dates.join(this._options.multidateSeparator); } else { return this._dates[index].clone(); } } if (newDate !== null && typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { throw new TypeError('date() parameter must be one of [null, string, moment or Date]'); } this._setValue(newDate === null ? null : this._parseInputDate(newDate), index); }; DateTimePicker.prototype.format = function format(newFormat) { <summary>test su</summary> <param name="newFormat">info about para</param> <returns type="string|boolean">returns foo</returns> if (arguments.length === 0) { return this._options.format; } if (typeof newFormat !== 'string' && (typeof newFormat !== 'boolean' || newFormat !== false)) { throw new TypeError('format() expects a string or boolean:false parameter ' + newFormat); } this._options.format = newFormat; if (this.actualFormat) { this._initFormatting(); // reinitialize formatting } }; DateTimePicker.prototype.timeZone = function timeZone(newZone) { if (arguments.length === 0) { return this._options.timeZone; } if (typeof newZone !== 'string') { throw new TypeError('newZone() expects a string parameter'); } this._options.timeZone = newZone; }; DateTimePicker.prototype.dayViewHeaderFormat = function dayViewHeaderFormat(newFormat) { if (arguments.length === 0) { return this._options.dayViewHeaderFormat; } if (typeof newFormat !== 'string') { throw new TypeError('dayViewHeaderFormat() expects a string parameter'); } this._options.dayViewHeaderFormat = newFormat; }; DateTimePicker.prototype.extraFormats = function extraFormats(formats) { if (arguments.length === 0) { return this._options.extraFormats; } if (formats !== false && !(formats instanceof Array)) { throw new TypeError('extraFormats() expects an array or false parameter'); } this._options.extraFormats = formats; if (this.parseFormats) { this._initFormatting(); // reinit formatting } }; DateTimePicker.prototype.disabledDates = function disabledDates(dates) { if (arguments.length === 0) { return this._options.disabledDates ? $.extend({}, this._options.disabledDates) : this._options.disabledDates; } if (!dates) { this._options.disabledDates = false; this._update(); return true; } if (!(dates instanceof Array)) { throw new TypeError('disabledDates() expects an array parameter'); } this._options.disabledDates = this._indexGivenDates(dates); this._options.enabledDates = false; this._update(); }; DateTimePicker.prototype.enabledDates = function enabledDates(dates) { if (arguments.length === 0) { return this._options.enabledDates ? $.extend({}, this._options.enabledDates) : this._options.enabledDates; } if (!dates) { this._options.enabledDates = false; this._update(); return true; } if (!(dates instanceof Array)) { throw new TypeError('enabledDates() expects an array parameter'); } this._options.enabledDates = this._indexGivenDates(dates); this._options.disabledDates = false; this._update(); }; DateTimePicker.prototype.daysOfWeekDisabled = function daysOfWeekDisabled(_daysOfWeekDisabled) { if (arguments.length === 0) { return this._options.daysOfWeekDisabled.splice(0); } if (typeof _daysOfWeekDisabled === 'boolean' && !_daysOfWeekDisabled) { this._options.daysOfWeekDisabled = false; this._update(); return true; } if (!(_daysOfWeekDisabled instanceof Array)) { throw new TypeError('daysOfWeekDisabled() expects an array parameter'); } this._options.daysOfWeekDisabled = _daysOfWeekDisabled.reduce(function (previousValue, currentValue) { currentValue = parseInt(currentValue, 10); if (currentValue > 6 || currentValue < 0 || isNaN(currentValue)) { return previousValue; } if (previousValue.indexOf(currentValue) === -1) { previousValue.push(currentValue); } return previousValue; }, []).sort(); if (this._options.useCurrent && !this._options.keepInvalid) { for (var i = 0; i < this._dates.length; i++) { var tries = 0; while (!this._isValid(this._dates[i], 'd')) { this._dates[i].add(1, 'd'); if (tries === 31) { throw 'Tried 31 times to find a valid date'; } tries++; } this._setValue(this._dates[i], i); } } this._update(); }; DateTimePicker.prototype.maxDate = function maxDate(_maxDate) { if (arguments.length === 0) { return this._options.maxDate ? this._options.maxDate.clone() : this._options.maxDate; } if (typeof _maxDate === 'boolean' && _maxDate === false) { this._options.maxDate = false; this._update(); return true; } if (typeof _maxDate === 'string') { if (_maxDate === 'now' || _maxDate === 'moment') { _maxDate = this.getMoment(); } } var parsedDate = this._parseInputDate(_maxDate); if (!parsedDate.isValid()) { throw new TypeError('maxDate() Could not parse date parameter: ' + _maxDate); } if (this._options.minDate && parsedDate.isBefore(this._options.minDate)) { throw new TypeError('maxDate() date parameter is before this.options.minDate: ' + parsedDate.format(this.actualFormat)); } this._options.maxDate = parsedDate; for (var i = 0; i < this._dates.length; i++) { if (this._options.useCurrent && !this._options.keepInvalid && this._dates[i].isAfter(_maxDate)) { this._setValue(this._options.maxDate, i); } } if (this._viewDate.isAfter(parsedDate)) { this._viewDate = parsedDate.clone().subtract(this._options.stepping, 'm'); } this._update(); }; DateTimePicker.prototype.minDate = function minDate(_minDate) { if (arguments.length === 0) { return this._options.minDate ? this._options.minDate.clone() : this._options.minDate; } if (typeof _minDate === 'boolean' && _minDate === false) { this._options.minDate = false; this._update(); return true; } if (typeof _minDate === 'string') { if (_minDate === 'now' || _minDate === 'moment') { _minDate = this.getMoment(); } } var parsedDate = this._parseInputDate(_minDate); if (!parsedDate.isValid()) { throw new TypeError('minDate() Could not parse date parameter: ' + _minDate); } if (this._options.maxDate && parsedDate.isAfter(this._options.maxDate)) { throw new TypeError('minDate() date parameter is after this.options.maxDate: ' + parsedDate.format(this.actualFormat)); } this._options.minDate = parsedDate; for (var i = 0; i < this._dates.length; i++) { if (this._options.useCurrent && !this._options.keepInvalid && this._dates[i].isBefore(_minDate)) { this._setValue(this._options.minDate, i); } } if (this._viewDate.isBefore(parsedDate)) { this._viewDate = parsedDate.clone().add(this._options.stepping, 'm'); } this._update(); }; DateTimePicker.prototype.defaultDate = function defaultDate(_defaultDate) { if (arguments.length === 0) { return this._options.defaultDate ? this._options.defaultDate.clone() : this._options.defaultDate; } if (!_defaultDate) { this._options.defaultDate = false; return true; } if (typeof _defaultDate === 'string') { if (_defaultDate === 'now' || _defaultDate === 'moment') { _defaultDate = this.getMoment(); } else { _defaultDate = this.getMoment(_defaultDate); } } var parsedDate = this._parseInputDate(_defaultDate); if (!parsedDate.isValid()) { throw new TypeError('defaultDate() Could not parse date parameter: ' + _defaultDate); } if (!this._isValid(parsedDate)) { throw new TypeError('defaultDate() date passed is invalid according to component setup validations'); } this._options.defaultDate = parsedDate; if (this._options.defaultDate && this._options.inline || this.input !== undefined && this.input.val().trim() === '') { this._setValue(this._options.defaultDate, 0); } }; DateTimePicker.prototype.locale = function locale(_locale) { if (arguments.length === 0) { return this._options.locale; } if (!moment.localeData(_locale)) { throw new TypeError('locale() locale ' + _locale + ' is not loaded from moment locales!'); } for (var i = 0; i < this._dates.length; i++) { this._dates[i].locale(this._options.locale); } this._viewDate.locale(this._options.locale); if (this.actualFormat) { this._initFormatting(); // reinitialize formatting } if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.stepping = function stepping(_stepping) { if (arguments.length === 0) { return this._options.stepping; } _stepping = parseInt(_stepping, 10); if (isNaN(_stepping) || _stepping < 1) { _stepping = 1; } this._options.stepping = _stepping; }; DateTimePicker.prototype.useCurrent = function useCurrent(_useCurrent) { var useCurrentOptions = ['year', 'month', 'day', 'hour', 'minute']; if (arguments.length === 0) { return this._options.useCurrent; } if (typeof _useCurrent !== 'boolean' && typeof _useCurrent !== 'string') { throw new TypeError('useCurrent() expects a boolean or string parameter'); } if (typeof _useCurrent === 'string' && useCurrentOptions.indexOf(_useCurrent.toLowerCase()) === -1) { throw new TypeError('useCurrent() expects a string parameter of ' + useCurrentOptions.join(', ')); } this._options.useCurrent = _useCurrent; }; DateTimePicker.prototype.collapse = function collapse(_collapse) { if (arguments.length === 0) { return this._options.collapse; } if (typeof _collapse !== 'boolean') { throw new TypeError('collapse() expects a boolean parameter'); } if (this._options.collapse === _collapse) { return true; } this._options.collapse = _collapse; if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.icons = function icons(_icons) { if (arguments.length === 0) { return $.extend({}, this._options.icons); } if (!(_icons instanceof Object)) { throw new TypeError('icons() expects parameter to be an Object'); } $.extend(this._options.icons, _icons); if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.tooltips = function tooltips(_tooltips) { if (arguments.length === 0) { return $.extend({}, this._options.tooltips); } if (!(_tooltips instanceof Object)) { throw new TypeError('tooltips() expects parameter to be an Object'); } $.extend(this._options.tooltips, _tooltips); if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.useStrict = function useStrict(_useStrict) { if (arguments.length === 0) { return this._options.useStrict; } if (typeof _useStrict !== 'boolean') { throw new TypeError('useStrict() expects a boolean parameter'); } this._options.useStrict = _useStrict; }; DateTimePicker.prototype.sideBySide = function sideBySide(_sideBySide) { if (arguments.length === 0) { return this._options.sideBySide; } if (typeof _sideBySide !== 'boolean') { throw new TypeError('sideBySide() expects a boolean parameter'); } this._options.sideBySide = _sideBySide; if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.viewMode = function viewMode(_viewMode) { if (arguments.length === 0) { return this._options.viewMode; } if (typeof _viewMode !== 'string') { throw new TypeError('viewMode() expects a string parameter'); } if (DateTimePicker.ViewModes.indexOf(_viewMode) === -1) { throw new TypeError('viewMode() parameter must be one of (' + DateTimePicker.ViewModes.join(', ') + ') value'); } this._options.viewMode = _viewMode; this.currentViewMode = Math.max(DateTimePicker.ViewModes.indexOf(_viewMode) - 1, DateTimePicker.MinViewModeNumber); this._showMode(); }; DateTimePicker.prototype.calendarWeeks = function calendarWeeks(_calendarWeeks) { if (arguments.length === 0) { return this._options.calendarWeeks; } if (typeof _calendarWeeks !== 'boolean') { throw new TypeError('calendarWeeks() expects parameter to be a boolean value'); } this._options.calendarWeeks = _calendarWeeks; this._update(); }; DateTimePicker.prototype.buttons = function buttons(_buttons) { if (arguments.length === 0) { return $.extend({}, this._options.buttons); } if (!(_buttons instanceof Object)) { throw new TypeError('buttons() expects parameter to be an Object'); } $.extend(this._options.buttons, _buttons); if (typeof this._options.buttons.showToday !== 'boolean') { throw new TypeError('buttons.showToday expects a boolean parameter'); } if (typeof this._options.buttons.showClear !== 'boolean') { throw new TypeError('buttons.showClear expects a boolean parameter'); } if (typeof this._options.buttons.showClose !== 'boolean') { throw new TypeError('buttons.showClose expects a boolean parameter'); } if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.keepOpen = function keepOpen(_keepOpen) { if (arguments.length === 0) { return this._options.keepOpen; } if (typeof _keepOpen !== 'boolean') { throw new TypeError('keepOpen() expects a boolean parameter'); } this._options.keepOpen = _keepOpen; }; DateTimePicker.prototype.focusOnShow = function focusOnShow(_focusOnShow) { if (arguments.length === 0) { return this._options.focusOnShow; } if (typeof _focusOnShow !== 'boolean') { throw new TypeError('focusOnShow() expects a boolean parameter'); } this._options.focusOnShow = _focusOnShow; }; DateTimePicker.prototype.inline = function inline(_inline) { if (arguments.length === 0) { return this._options.inline; } if (typeof _inline !== 'boolean') { throw new TypeError('inline() expects a boolean parameter'); } this._options.inline = _inline; }; DateTimePicker.prototype.clear = function clear() { this._setValue(null); //todo }; DateTimePicker.prototype.keyBinds = function keyBinds(_keyBinds) { if (arguments.length === 0) { return this._options.keyBinds; } this._options.keyBinds = _keyBinds; }; DateTimePicker.prototype.debug = function debug(_debug) { if (typeof _debug !== 'boolean') { throw new TypeError('debug() expects a boolean parameter'); } this._options.debug = _debug; }; DateTimePicker.prototype.allowInputToggle = function allowInputToggle(_allowInputToggle) { if (arguments.length === 0) { return this._options.allowInputToggle; } if (typeof _allowInputToggle !== 'boolean') { throw new TypeError('allowInputToggle() expects a boolean parameter'); } this._options.allowInputToggle = _allowInputToggle; }; DateTimePicker.prototype.keepInvalid = function keepInvalid(_keepInvalid) { if (arguments.length === 0) { return this._options.keepInvalid; } if (typeof _keepInvalid !== 'boolean') { throw new TypeError('keepInvalid() expects a boolean parameter'); } this._options.keepInvalid = _keepInvalid; }; DateTimePicker.prototype.datepickerInput = function datepickerInput(_datepickerInput) { if (arguments.length === 0) { return this._options.datepickerInput; } if (typeof _datepickerInput !== 'string') { throw new TypeError('datepickerInput() expects a string parameter'); } this._options.datepickerInput = _datepickerInput; }; DateTimePicker.prototype.parseInputDate = function parseInputDate(_parseInputDate2) { if (arguments.length === 0) { return this._options.parseInputDate; } if (typeof _parseInputDate2 !== 'function') { throw new TypeError('parseInputDate() should be as function'); } this._options.parseInputDate = _parseInputDate2; }; DateTimePicker.prototype.<API key> = function <API key>(<API key>) { if (arguments.length === 0) { return this._options.<API key> ? $.extend({}, this._options.<API key>) : this._options.<API key>; } if (!<API key>) { this._options.<API key> = false; this._update(); return true; } if (!(<API key> instanceof Array)) { throw new TypeError('<API key>() expects an array parameter'); } this._options.<API key> = <API key>; this._update(); }; DateTimePicker.prototype.disabledHours = function disabledHours(hours) { if (arguments.length === 0) { return this._options.disabledHours ? $.extend({}, this._options.disabledHours) : this._options.disabledHours; } if (!hours) { this._options.disabledHours = false; this._update(); return true; } if (!(hours instanceof Array)) { throw new TypeError('disabledHours() expects an array parameter'); } this._options.disabledHours = this._indexGivenHours(hours); this._options.enabledHours = false; if (this._options.useCurrent && !this._options.keepInvalid) { for (var i = 0; i < this._dates.length; i++) { var tries = 0; while (!this._isValid(this._dates[i], 'h')) { this._dates[i].add(1, 'h'); if (tries === 24) { throw 'Tried 24 times to find a valid date'; } tries++; } this._setValue(this._dates[i], i); } } this._update(); }; DateTimePicker.prototype.enabledHours = function enabledHours(hours) { if (arguments.length === 0) { return this._options.enabledHours ? $.extend({}, this._options.enabledHours) : this._options.enabledHours; } if (!hours) { this._options.enabledHours = false; this._update(); return true; } if (!(hours instanceof Array)) { throw new TypeError('enabledHours() expects an array parameter'); } this._options.enabledHours = this._indexGivenHours(hours); this._options.disabledHours = false; if (this._options.useCurrent && !this._options.keepInvalid) { for (var i = 0; i < this._dates.length; i++) { var tries = 0; while (!this._isValid(this._dates[i], 'h')) { this._dates[i].add(1, 'h'); if (tries === 24) { throw 'Tried 24 times to find a valid date'; } tries++; } this._setValue(this._dates[i], i); } } this._update(); }; DateTimePicker.prototype.viewDate = function viewDate(newDate) { if (arguments.length === 0) { return this._viewDate.clone(); } if (!newDate) { this._viewDate = (this._dates[0] || this.getMoment()).clone(); return true; } if (typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { throw new TypeError('viewDate() parameter must be one of [string, moment or Date]'); } this._viewDate = this._parseInputDate(newDate); this._viewUpdate(); }; DateTimePicker.prototype.allowMultidate = function allowMultidate(_allowMultidate) { if (typeof _allowMultidate !== 'boolean') { throw new TypeError('allowMultidate() expects a boolean parameter'); } this._options.allowMultidate = _allowMultidate; }; DateTimePicker.prototype.multidateSeparator = function multidateSeparator(_multidateSeparator) { if (arguments.length === 0) { return this._options.multidateSeparator; } if (typeof _multidateSeparator !== 'string' || _multidateSeparator.length > 1) { throw new TypeError('multidateSeparator expects a single character string parameter'); } this._options.multidateSeparator = _multidateSeparator; }; _createClass(DateTimePicker, null, [{ key: 'NAME', get: function get() { return NAME; } /** * @return {string} */ }, { key: 'VERSION', get: function get() { return VERSION; } /** * @return {string} */ }, { key: 'DATA_KEY', get: function get() { return DATA_KEY; } /** * @return {string} */ }, { key: 'EVENT_KEY', get: function get() { return EVENT_KEY; } /** * @return {string} */ }, { key: 'DATA_API_KEY', get: function get() { return DATA_API_KEY; } }, { key: 'DatePickerModes', get: function get() { return DatePickerModes; } }, { key: 'ViewModes', get: function get() { return ViewModes; } /** * @return {number} */ }, { key: 'MinViewModeNumber', get: function get() { return MinViewModeNumber; } }, { key: 'Event', get: function get() { return Event; } }, { key: 'Selector', get: function get() { return Selector; } }, { key: 'Default', get: function get() { return Default; } }, { key: 'ClassName', get: function get() { return ClassName; } }]); return DateTimePicker; }(); return DateTimePicker; }(jQuery, moment); //noinspection <API key> /* global DateTimePicker */ var <API key> = function ($) { // eslint-disable-line no-unused-vars // ReSharper disable once InconsistentNaming var JQUERY_NO_CONFLICT = $.fn[DateTimePicker.NAME], verticalModes = ['top', 'bottom', 'auto'], horizontalModes = ['left', 'right', 'auto'], toolbarPlacements = ['default', 'top', 'bottom'], <API key> = function <API key>($element) { var selector = $element.data('target'), $selector = void 0; if (!selector) { selector = $element.attr('href') || ''; selector = /^#[a-z]/i.test(selector) ? selector : null; } $selector = $(selector); if ($selector.length === 0) { return $selector; } if (!$selector.data(DateTimePicker.DATA_KEY)) { $.extend({}, $selector.data(), $(this).data()); } return $selector; }; // ReSharper disable once InconsistentNaming var <API key> = function (_DateTimePicker) { _inherits(<API key>, _DateTimePicker); function <API key>(element, options) { _classCallCheck(this, <API key>); var _this = <API key>(this, _DateTimePicker.call(this, element, options)); _this._init(); return _this; } <API key>.prototype._init = function _init() { if (this._element.hasClass('input-group')) { // in case there is more then one 'input-group-addon' Issue var datepickerButton = this._element.find('.datepickerbutton'); if (datepickerButton.length === 0) { this.component = this._element.find('.input-group-addon'); } else { this.component = datepickerButton; } } }; <API key>.prototype.<API key> = function <API key>() { var headTemplate = $('<thead>').append($('<tr>').append($('<th>').addClass('prev').attr('data-action', 'previous').append($('<span>').addClass(this._options.icons.previous))).append($('<th>').addClass('picker-switch').attr('data-action', 'pickerSwitch').attr('colspan', '' + (this._options.calendarWeeks ? '6' : '5'))).append($('<th>').addClass('next').attr('data-action', 'next').append($('<span>').addClass(this._options.icons.next)))), contTemplate = $('<tbody>').append($('<tr>').append($('<td>').attr('colspan', '' + (this._options.calendarWeeks ? '8' : '7')))); return [$('<div>').addClass('datepicker-days').append($('<table>').addClass('table table-sm').append(headTemplate).append($('<tbody>'))), $('<div>').addClass('datepicker-months').append($('<table>').addClass('table-condensed').append(headTemplate.clone()).append(contTemplate.clone())), $('<div>').addClass('datepicker-years').append($('<table>').addClass('table-condensed').append(headTemplate.clone()).append(contTemplate.clone())), $('<div>').addClass('datepicker-decades').append($('<table>').addClass('table-condensed').append(headTemplate.clone()).append(contTemplate.clone()))]; }; <API key>.prototype.<API key> = function <API key>() { var topRow = $('<tr>'), middleRow = $('<tr>'), bottomRow = $('<tr>'); if (this._isEnabled('h')) { topRow.append($('<td>').append($('<a>').attr({ href: ' tabindex: '-1', 'title': this._options.tooltips.incrementHour }).addClass('btn').attr('data-action', 'incrementHours').append($('<span>').addClass(this._options.icons.up)))); middleRow.append($('<td>').append($('<span>').addClass('timepicker-hour').attr({ 'data-time-component': 'hours', 'title': this._options.tooltips.pickHour }).attr('data-action', 'showHours'))); bottomRow.append($('<td>').append($('<a>').attr({ href: ' tabindex: '-1', 'title': this._options.tooltips.decrementHour }).addClass('btn').attr('data-action', 'decrementHours').append($('<span>').addClass(this._options.icons.down)))); } if (this._isEnabled('m')) { if (this._isEnabled('h')) { topRow.append($('<td>').addClass('separator')); middleRow.append($('<td>').addClass('separator').html(':')); bottomRow.append($('<td>').addClass('separator')); } topRow.append($('<td>').append($('<a>').attr({ href: ' tabindex: '-1', 'title': this._options.tooltips.incrementMinute }).addClass('btn').attr('data-action', 'incrementMinutes').append($('<span>').addClass(this._options.icons.up)))); middleRow.append($('<td>').append($('<span>').addClass('timepicker-minute').attr({ 'data-time-component': 'minutes', 'title': this._options.tooltips.pickMinute }).attr('data-action', 'showMinutes'))); bottomRow.append($('<td>').append($('<a>').attr({ href: ' tabindex: '-1', 'title': this._options.tooltips.decrementMinute }).addClass('btn').attr('data-action', 'decrementMinutes').append($('<span>').addClass(this._options.icons.down)))); } if (this._isEnabled('s')) { if (this._isEnabled('m')) { topRow.append($('<td>').addClass('separator')); middleRow.append($('<td>').addClass('separator').html(':')); bottomRow.append($('<td>').addClass('separator')); } topRow.append($('<td>').append($('<a>').attr({ href: ' tabindex: '-1', 'title': this._options.tooltips.incrementSecond }).addClass('btn').attr('data-action', 'incrementSeconds').append($('<span>').addClass(this._options.icons.up)))); middleRow.append($('<td>').append($('<span>').addClass('timepicker-second').attr({ 'data-time-component': 'seconds', 'title': this._options.tooltips.pickSecond }).attr('data-action', 'showSeconds'))); bottomRow.append($('<td>').append($('<a>').attr({ href: ' tabindex: '-1', 'title': this._options.tooltips.decrementSecond }).addClass('btn').attr('data-action', 'decrementSeconds').append($('<span>').addClass(this._options.icons.down)))); } if (!this.use24Hours) { topRow.append($('<td>').addClass('separator')); middleRow.append($('<td>').append($('<button>').addClass('btn btn-primary').attr({ 'data-action': 'togglePeriod', tabindex: '-1', 'title': this._options.tooltips.togglePeriod }))); bottomRow.append($('<td>').addClass('separator')); } return $('<div>').addClass('timepicker-picker').append($('<table>').addClass('table-condensed').append([topRow, middleRow, bottomRow])); }; <API key>.prototype.<API key> = function <API key>() { var hoursView = $('<div>').addClass('timepicker-hours').append($('<table>').addClass('table-condensed')), minutesView = $('<div>').addClass('timepicker-minutes').append($('<table>').addClass('table-condensed')), secondsView = $('<div>').addClass('timepicker-seconds').append($('<table>').addClass('table-condensed')), ret = [this.<API key>()]; if (this._isEnabled('h')) { ret.push(hoursView); } if (this._isEnabled('m')) { ret.push(minutesView); } if (this._isEnabled('s')) { ret.push(secondsView); } return ret; }; <API key>.prototype._getToolbar = function _getToolbar() { var row = []; if (this._options.buttons.showToday) { row.push($('<td>').append($('<a>').attr({ 'data-action': 'today', 'title': this._options.tooltips.today }).append($('<span>').addClass(this._options.icons.today)))); } if (!this._options.sideBySide && this._hasDate() && this._hasTime()) { row.push($('<td>').append($('<a>').attr({ 'data-action': 'togglePicker', 'title': this._options.tooltips.selectTime }).append($('<span>').addClass(this._options.icons.time)))); } if (this._options.buttons.showClear) { row.push($('<td>').append($('<a>').attr({ 'data-action': 'clear', 'title': this._options.tooltips.clear }).append($('<span>').addClass(this._options.icons.clear)))); } if (this._options.buttons.showClose) { row.push($('<td>').append($('<a>').attr({ 'data-action': 'close', 'title': this._options.tooltips.close }).append($('<span>').addClass(this._options.icons.close)))); } return row.length === 0 ? '' : $('<table>').addClass('table-condensed').append($('<tbody>').append($('<tr>').append(row))); }; <API key>.prototype._getTemplate = function _getTemplate() { var template = $('<div>').addClass('<API key> dropdown-menu'), dateView = $('<div>').addClass('datepicker').append(this.<API key>()), timeView = $('<div>').addClass('timepicker').append(this.<API key>()), content = $('<ul>').addClass('list-unstyled'), toolbar = $('<li>').addClass('picker-switch' + (this._options.collapse ? ' accordion-toggle' : '')).append(this._getToolbar()); if (this._options.inline) { template.removeClass('dropdown-menu'); } if (this.use24Hours) { template.addClass('usetwentyfour'); } if (this._isEnabled('s') && !this.use24Hours) { template.addClass('wider'); } if (this._options.sideBySide && this._hasDate() && this._hasTime()) { template.addClass('timepicker-sbs'); if (this._options.toolbarPlacement === 'top') { template.append(toolbar); } template.append($('<div>').addClass('row').append(dateView.addClass('col-md-6')).append(timeView.addClass('col-md-6'))); if (this._options.toolbarPlacement === 'bottom' || this._options.toolbarPlacement === 'default') { template.append(toolbar); } return template; } if (this._options.toolbarPlacement === 'top') { content.append(toolbar); } if (this._hasDate()) { content.append($('<li>').addClass(this._options.collapse && this._hasTime() ? 'collapse' : '').addClass(this._options.collapse && this._hasTime() && this._options.viewMode === 'time' ? '' : 'show').append(dateView)); } if (this._options.toolbarPlacement === 'default') { content.append(toolbar); } if (this._hasTime()) { content.append($('<li>').addClass(this._options.collapse && this._hasDate() ? 'collapse' : '').addClass(this._options.collapse && this._hasDate() && this._options.viewMode === 'time' ? 'show' : '').append(timeView)); } if (this._options.toolbarPlacement === 'bottom') { content.append(toolbar); } return template.append(content); }; <API key>.prototype._place = function _place(e) { var self = e && e.data && e.data.picker || this, vertical = self._options.widgetPositioning.vertical, horizontal = self._options.widgetPositioning.horizontal, parent = void 0; var position = (self.component || self._element).position(), offset = (self.component || self._element).offset(); if (self._options.widgetParent) { parent = self._options.widgetParent.append(self.widget); } else if (self._element.is('input')) { parent = self._element.after(self.widget).parent(); } else if (self._options.inline) { parent = self._element.append(self.widget); return; } else { parent = self._element; self._element.children().first().after(self.widget); } // Top and bottom logic if (vertical === 'auto') { //noinspection JSValidateTypes if (offset.top + self.widget.height() * 1.5 >= $(window).height() + $(window).scrollTop() && self.widget.height() + self._element.outerHeight() < offset.top) { vertical = 'top'; } else { vertical = 'bottom'; } } // Left and right logic if (horizontal === 'auto') { if (parent.width() < offset.left + self.widget.outerWidth() / 2 && offset.left + self.widget.outerWidth() > $(window).width()) { horizontal = 'right'; } else { horizontal = 'left'; } } if (vertical === 'top') { self.widget.addClass('top').removeClass('bottom'); } else { self.widget.addClass('bottom').removeClass('top'); } if (horizontal === 'right') { self.widget.addClass('float-right'); } else { self.widget.removeClass('float-right'); } // find the first parent element that has a relative css positioning if (parent.css('position') !== 'relative') { parent = parent.parents().filter(function () { return $(this).css('position') === 'relative'; }).first(); } if (parent.length === 0) { throw new Error('datetimepicker component should be placed within a relative positioned container'); } self.widget.css({ top: vertical === 'top' ? 'auto' : position.top + self._element.outerHeight() + 'px', bottom: vertical === 'top' ? parent.outerHeight() - (parent === self._element ? 0 : position.top) + 'px' : 'auto', left: horizontal === 'left' ? (parent === self._element ? 0 : position.left) + 'px' : 'auto', right: horizontal === 'left' ? 'auto' : parent.outerWidth() - self._element.outerWidth() - (parent === self._element ? 0 : position.left) + 'px' }); }; <API key>.prototype._fillDow = function _fillDow() { var row = $('<tr>'), currentDate = this._viewDate.clone().startOf('w').startOf('d'); if (this._options.calendarWeeks === true) { row.append($('<th>').addClass('cw').text(' } while (currentDate.isBefore(this._viewDate.clone().endOf('w'))) { row.append($('<th>').addClass('dow').text(currentDate.format('dd'))); currentDate.add(1, 'd'); } this.widget.find('.datepicker-days thead').append(row); }; <API key>.prototype._fillMonths = function _fillMonths() { var spans = [], monthsShort = this._viewDate.clone().startOf('y').startOf('d'); while (monthsShort.isSame(this._viewDate, 'y')) { spans.push($('<span>').attr('data-action', 'selectMonth').addClass('month').text(monthsShort.format('MMM'))); monthsShort.add(1, 'M'); } this.widget.find('.datepicker-months td').empty().append(spans); }; <API key>.prototype._updateMonths = function _updateMonths() { var monthsView = this.widget.find('.datepicker-months'), monthsViewHeader = monthsView.find('th'), months = monthsView.find('tbody').find('span'), self = this; monthsViewHeader.eq(0).find('span').attr('title', this._options.tooltips.prevYear); monthsViewHeader.eq(1).attr('title', this._options.tooltips.selectYear); monthsViewHeader.eq(2).find('span').attr('title', this._options.tooltips.nextYear); monthsView.find('.disabled').removeClass('disabled'); if (!this._isValid(this._viewDate.clone().subtract(1, 'y'), 'y')) { monthsViewHeader.eq(0).addClass('disabled'); } monthsViewHeader.eq(1).text(this._viewDate.year()); if (!this._isValid(this._viewDate.clone().add(1, 'y'), 'y')) { monthsViewHeader.eq(2).addClass('disabled'); } months.removeClass('active'); if (this._getLastPickedDate().isSame(this._viewDate, 'y') && !this.unset) { months.eq(this._getLastPickedDate().month()).addClass('active'); } months.each(function (index) { if (!self._isValid(self._viewDate.clone().month(index), 'M')) { $(this).addClass('disabled'); } }); }; <API key>.prototype._getStartEndYear = function _getStartEndYear(factor, year) { var step = factor / 10, startYear = Math.floor(year / factor) * factor, endYear = startYear + step * 9, focusValue = Math.floor(year / step) * step; return [startYear, endYear, focusValue]; }; <API key>.prototype._updateYears = function _updateYears() { var yearsView = this.widget.find('.datepicker-years'), yearsViewHeader = yearsView.find('th'), yearCaps = this._getStartEndYear(10, this._viewDate.year()), startYear = this._viewDate.clone().year(yearCaps[0]), endYear = this._viewDate.clone().year(yearCaps[1]); var html = ''; yearsViewHeader.eq(0).find('span').attr('title', this._options.tooltips.prevDecade); yearsViewHeader.eq(1).attr('title', this._options.tooltips.selectDecade); yearsViewHeader.eq(2).find('span').attr('title', this._options.tooltips.nextDecade); yearsView.find('.disabled').removeClass('disabled'); if (this._options.minDate && this._options.minDate.isAfter(startYear, 'y')) { yearsViewHeader.eq(0).addClass('disabled'); } yearsViewHeader.eq(1).text(startYear.year() + '-' + endYear.year()); if (this._options.maxDate && this._options.maxDate.isBefore(endYear, 'y')) { yearsViewHeader.eq(2).addClass('disabled'); } html += '<span data-action="selectYear" class="year old">' + (startYear.year() - 1) + '</span>'; while (!startYear.isAfter(endYear, 'y')) { html += '<span data-action="selectYear" class="year' + (startYear.isSame(this._getLastPickedDate(), 'y') && !this.unset ? ' active' : '') + (!this._isValid(startYear, 'y') ? ' disabled' : '') + '">' + startYear.year() + '</span>'; startYear.add(1, 'y'); } html += '<span data-action="selectYear" class="year old">' + startYear.year() + '</span>'; yearsView.find('td').html(html); }; <API key>.prototype._updateDecades = function _updateDecades() { var decadesView = this.widget.find('.datepicker-decades'), decadesViewHeader = decadesView.find('th'), yearCaps = this._getStartEndYear(100, this._viewDate.year()), startDecade = this._viewDate.clone().year(yearCaps[0]), endDecade = this._viewDate.clone().year(yearCaps[1]); var minDateDecade = false, maxDateDecade = false, endDecadeYear = void 0, html = ''; decadesViewHeader.eq(0).find('span').attr('title', this._options.tooltips.prevCentury); decadesViewHeader.eq(2).find('span').attr('title', this._options.tooltips.nextCentury); decadesView.find('.disabled').removeClass('disabled'); if (startDecade.year() === 0 || this._options.minDate && this._options.minDate.isAfter(startDecade, 'y')) { decadesViewHeader.eq(0).addClass('disabled'); } decadesViewHeader.eq(1).text(startDecade.year() + '-' + endDecade.year()); if (this._options.maxDate && this._options.maxDate.isBefore(endDecade, 'y')) { decadesViewHeader.eq(2).addClass('disabled'); } if (startDecade.year() - 10 < 0) { html += '<span>&nbsp;</span>'; } else { html += '<span data-action="selectDecade" class="decade old" data-selection="' + (startDecade.year() + 6) + '">' + (startDecade.year() - 10) + '</span>'; } while (!startDecade.isAfter(endDecade, 'y')) { endDecadeYear = startDecade.year() + 11; minDateDecade = this._options.minDate && this._options.minDate.isAfter(startDecade, 'y') && this._options.minDate.year() <= endDecadeYear; maxDateDecade = this._options.maxDate && this._options.maxDate.isAfter(startDecade, 'y') && this._options.maxDate.year() <= endDecadeYear; html += '<span data-action="selectDecade" class="decade' + (this._getLastPickedDate().isAfter(startDecade) && this._getLastPickedDate().year() <= endDecadeYear ? ' active' : '') + (!this._isValid(startDecade, 'y') && !minDateDecade && !maxDateDecade ? ' disabled' : '') + '" data-selection="' + (startDecade.year() + 6) + '">' + startDecade.year() + '</span>'; startDecade.add(10, 'y'); } html += '<span data-action="selectDecade" class="decade old" data-selection="' + (startDecade.year() + 6) + '">' + startDecade.year() + '</span>'; decadesView.find('td').html(html); }; <API key>.prototype._fillDate = function _fillDate() { var daysView = this.widget.find('.datepicker-days'), daysViewHeader = daysView.find('th'), html = []; var currentDate = void 0, row = void 0, clsName = void 0, i = void 0; if (!this._hasDate()) { return; } daysViewHeader.eq(0).find('span').attr('title', this._options.tooltips.prevMonth); daysViewHeader.eq(1).attr('title', this._options.tooltips.selectMonth); daysViewHeader.eq(2).find('span').attr('title', this._options.tooltips.nextMonth); daysView.find('.disabled').removeClass('disabled'); daysViewHeader.eq(1).text(this._viewDate.format(this._options.dayViewHeaderFormat)); if (!this._isValid(this._viewDate.clone().subtract(1, 'M'), 'M')) { daysViewHeader.eq(0).addClass('disabled'); } if (!this._isValid(this._viewDate.clone().add(1, 'M'), 'M')) { daysViewHeader.eq(2).addClass('disabled'); } currentDate = this._viewDate.clone().startOf('M').startOf('w').startOf('d'); for (i = 0; i < 42; i++) { //always display 42 days (should show 6 weeks) if (currentDate.weekday() === 0) { row = $('<tr>'); if (this._options.calendarWeeks) { row.append('<td class="cw">' + currentDate.week() + '</td>'); } html.push(row); } clsName = ''; if (currentDate.isBefore(this._viewDate, 'M')) { clsName += ' old'; } if (currentDate.isAfter(this._viewDate, 'M')) { clsName += ' new'; } if (this._options.allowMultidate) { var index = this._datesFormatted.indexOf(currentDate.format('YYYY-MM-DD')); if (index !== -1) { if (currentDate.isSame(this._datesFormatted[index], 'd') && !this.unset) { clsName += ' active'; } } } else { if (currentDate.isSame(this._getLastPickedDate(), 'd') && !this.unset) { clsName += ' active'; } } if (!this._isValid(currentDate, 'd')) { clsName += ' disabled'; } if (currentDate.isSame(this.getMoment(), 'd')) { clsName += ' today'; } if (currentDate.day() === 0 || currentDate.day() === 6) { clsName += ' weekend'; } row.append('<td data-action="selectDay" data-day="' + currentDate.format('L') + '" class="day' + clsName + '">' + currentDate.date() + '</td>'); currentDate.add(1, 'd'); } daysView.find('tbody').empty().append(html); this._updateMonths(); this._updateYears(); this._updateDecades(); }; <API key>.prototype._fillHours = function _fillHours() { var table = this.widget.find('.timepicker-hours table'), currentHour = this._viewDate.clone().startOf('d'), html = []; var row = $('<tr>'); if (this._viewDate.hour() > 11 && !this.use24Hours) { currentHour.hour(12); } while (currentHour.isSame(this._viewDate, 'd') && (this.use24Hours || this._viewDate.hour() < 12 && currentHour.hour() < 12 || this._viewDate.hour() > 11)) { if (currentHour.hour() % 4 === 0) { row = $('<tr>'); html.push(row); } row.append('<td data-action="selectHour" class="hour' + (!this._isValid(currentHour, 'h') ? ' disabled' : '') + '">' + currentHour.format(this.use24Hours ? 'HH' : 'hh') + '</td>'); currentHour.add(1, 'h'); } table.empty().append(html); }; <API key>.prototype._fillMinutes = function _fillMinutes() { var table = this.widget.find('.timepicker-minutes table'), currentMinute = this._viewDate.clone().startOf('h'), html = [], step = this._options.stepping === 1 ? 5 : this._options.stepping; var row = $('<tr>'); while (this._viewDate.isSame(currentMinute, 'h')) { if (currentMinute.minute() % (step * 4) === 0) { row = $('<tr>'); html.push(row); } row.append('<td data-action="selectMinute" class="minute' + (!this._isValid(currentMinute, 'm') ? ' disabled' : '') + '">' + currentMinute.format('mm') + '</td>'); currentMinute.add(step, 'm'); } table.empty().append(html); }; <API key>.prototype._fillSeconds = function _fillSeconds() { var table = this.widget.find('.timepicker-seconds table'), currentSecond = this._viewDate.clone().startOf('m'), html = []; var row = $('<tr>'); while (this._viewDate.isSame(currentSecond, 'm')) { if (currentSecond.second() % 20 === 0) { row = $('<tr>'); html.push(row); } row.append('<td data-action="selectSecond" class="second' + (!this._isValid(currentSecond, 's') ? ' disabled' : '') + '">' + currentSecond.format('ss') + '</td>'); currentSecond.add(5, 's'); } table.empty().append(html); }; <API key>.prototype._fillTime = function _fillTime() { var toggle = void 0, newDate = void 0; var timeComponents = this.widget.find('.timepicker span[data-time-component]'); if (!this.use24Hours) { toggle = this.widget.find('.timepicker [data-action=togglePeriod]'); newDate = this._getLastPickedDate().clone().add(this._getLastPickedDate().hours() >= 12 ? -12 : 12, 'h'); toggle.text(this._getLastPickedDate().format('A')); if (this._isValid(newDate, 'h')) { toggle.removeClass('disabled'); } else { toggle.addClass('disabled'); } } timeComponents.filter('[data-time-component=hours]').text(this._getLastPickedDate().format('' + (this.use24Hours ? 'HH' : 'hh'))); timeComponents.filter('[data-time-component=minutes]').text(this._getLastPickedDate().format('mm')); timeComponents.filter('[data-time-component=seconds]').text(this._getLastPickedDate().format('ss')); this._fillHours(); this._fillMinutes(); this._fillSeconds(); }; <API key>.prototype._doAction = function _doAction(e, action) { var lastPicked = this._getLastPickedDate(); if ($(e.currentTarget).is('.disabled')) { return false; } action = action || $(e.currentTarget).data('action'); switch (action) { case 'next': { var navFnc = DateTimePicker.DatePickerModes[this.currentViewMode].NAV_FUNCTION; this._viewDate.add(DateTimePicker.DatePickerModes[this.currentViewMode].NAV_STEP, navFnc); this._fillDate(); this._viewUpdate(navFnc); break; } case 'previous': { var _navFnc = DateTimePicker.DatePickerModes[this.currentViewMode].NAV_FUNCTION; this._viewDate.subtract(DateTimePicker.DatePickerModes[this.currentViewMode].NAV_STEP, _navFnc); this._fillDate(); this._viewUpdate(_navFnc); break; } case 'pickerSwitch': this._showMode(1); break; case 'selectMonth': { var month = $(e.target).closest('tbody').find('span').index($(e.target)); this._viewDate.month(month); if (this.currentViewMode === DateTimePicker.MinViewModeNumber) { this._setValue(lastPicked.clone().year(this._viewDate.year()).month(this._viewDate.month()), this.<API key>()); if (!this._options.inline) { this.hide(); } } else { this._showMode(-1); this._fillDate(); } this._viewUpdate('M'); break; } case 'selectYear': { var year = parseInt($(e.target).text(), 10) || 0; this._viewDate.year(year); if (this.currentViewMode === DateTimePicker.MinViewModeNumber) { this._setValue(lastPicked.clone().year(this._viewDate.year()), this.<API key>()); if (!this._options.inline) { this.hide(); } } else { this._showMode(-1); this._fillDate(); } this._viewUpdate('YYYY'); break; } case 'selectDecade': { var _year = parseInt($(e.target).data('selection'), 10) || 0; this._viewDate.year(_year); if (this.currentViewMode === DateTimePicker.MinViewModeNumber) { this._setValue(lastPicked.clone().year(this._viewDate.year()), this.<API key>()); if (!this._options.inline) { this.hide(); } } else { this._showMode(-1); this._fillDate(); } this._viewUpdate('YYYY'); break; } case 'selectDay': { var day = this._viewDate.clone(); if ($(e.target).is('.old')) { day.subtract(1, 'M'); } if ($(e.target).is('.new')) { day.add(1, 'M'); } this._setValue(day.date(parseInt($(e.target).text(), 10)), this.<API key>()); if (!this._hasTime() && !this._options.keepOpen && !this._options.inline) { this.hide(); } break; } case 'incrementHours': { var newDate = lastPicked.clone().add(1, 'h'); if (this._isValid(newDate, 'h')) { this._setValue(newDate, this.<API key>()); } break; } case 'incrementMinutes': { var _newDate = lastPicked.clone().add(this._options.stepping, 'm'); if (this._isValid(_newDate, 'm')) { this._setValue(_newDate, this.<API key>()); } break; } case 'incrementSeconds': { var _newDate2 = lastPicked.clone().add(1, 's'); if (this._isValid(_newDate2, 's')) { this._setValue(_newDate2, this.<API key>()); } break; } case 'decrementHours': { var _newDate3 = lastPicked.clone().subtract(1, 'h'); if (this._isValid(_newDate3, 'h')) { this._setValue(_newDate3, this.<API key>()); } break; } case 'decrementMinutes': { var _newDate4 = lastPicked.clone().subtract(this._options.stepping, 'm'); if (this._isValid(_newDate4, 'm')) { this._setValue(_newDate4, this.<API key>()); } break; } case 'decrementSeconds': { var _newDate5 = lastPicked.clone().subtract(1, 's'); if (this._isValid(_newDate5, 's')) { this._setValue(_newDate5, this.<API key>()); } break; } case 'togglePeriod': { this._setValue(lastPicked.clone().add(lastPicked.hours() >= 12 ? -12 : 12, 'h'), this.<API key>()); break; } case 'togglePicker': { var $this = $(e.target), $link = $this.closest('a'), $parent = $this.closest('ul'), expanded = $parent.find('.show'), closed = $parent.find('.collapse:not(.show)'), $span = $this.is('span') ? $this : $this.find('span'); var collapseData = void 0; if (expanded && expanded.length) { collapseData = expanded.data('collapse'); if (collapseData && collapseData.transitioning) { return true; } if (expanded.collapse) { // if collapse plugin is available through bootstrap.js then use it expanded.collapse('hide'); closed.collapse('show'); } else { // otherwise just toggle in class on the two views expanded.removeClass('show'); closed.addClass('show'); } $span.toggleClass(this._options.icons.time + ' ' + this._options.icons.date); if ($span.hasClass(this._options.icons.date)) { $link.attr('title', this._options.tooltips.selectDate); } else { $link.attr('title', this._options.tooltips.selectTime); } } } break; case 'showPicker': this.widget.find('.timepicker > div:not(.timepicker-picker)').hide(); this.widget.find('.timepicker .timepicker-picker').show(); break; case 'showHours': this.widget.find('.timepicker .timepicker-picker').hide(); this.widget.find('.timepicker .timepicker-hours').show(); break; case 'showMinutes': this.widget.find('.timepicker .timepicker-picker').hide(); this.widget.find('.timepicker .timepicker-minutes').show(); break; case 'showSeconds': this.widget.find('.timepicker .timepicker-picker').hide(); this.widget.find('.timepicker .timepicker-seconds').show(); break; case 'selectHour': { var hour = parseInt($(e.target).text(), 10); if (!this.use24Hours) { if (lastPicked.hours() >= 12) { if (hour !== 12) { hour += 12; } } else { if (hour === 12) { hour = 0; } } } this._setValue(lastPicked.clone().hours(hour), this.<API key>()); this._doAction(e, 'showPicker'); break; } case 'selectMinute': this._setValue(lastPicked.clone().minutes(parseInt($(e.target).text(), 10)), this.<API key>()); this._doAction(e, 'showPicker'); break; case 'selectSecond': this._setValue(lastPicked.clone().seconds(parseInt($(e.target).text(), 10)), this.<API key>()); this._doAction(e, 'showPicker'); break; case 'clear': this.clear(); break; case 'today': { var todaysDate = this.getMoment(); if (this._isValid(todaysDate, 'd')) { this._setValue(todaysDate, this.<API key>()); } break; } } return false; }; //public <API key>.prototype.hide = function hide() { var transitioning = false; if (!this.widget) { return; } // Ignore event if in the middle of a picker transition this.widget.find('.collapse').each(function () { var collapseData = $(this).data('collapse'); if (collapseData && collapseData.transitioning) { transitioning = true; return false; } return true; }); if (transitioning) { return; } if (this.component && this.component.hasClass('btn')) { this.component.toggleClass('active'); } this.widget.hide(); $(window).off('resize', this._place()); this.widget.off('click', '[data-action]'); this.widget.off('mousedown', false); this.widget.remove(); this.widget = false; this._notifyEvent({ type: DateTimePicker.Event.HIDE, date: this._getLastPickedDate().clone() }); if (this.input !== undefined) { this.input.blur(); } this._viewDate = this._getLastPickedDate().clone(); }; <API key>.prototype.show = function show() { var currentMoment = void 0; var <API key> = { 'year': function year(m) { return m.month(0).date(1).hours(0).seconds(0).minutes(0); }, 'month': function month(m) { return m.date(1).hours(0).seconds(0).minutes(0); }, 'day': function day(m) { return m.hours(0).seconds(0).minutes(0); }, 'hour': function hour(m) { return m.seconds(0).minutes(0); }, 'minute': function minute(m) { return m.seconds(0); } }; if (this.input !== undefined) { if (this.input.prop('disabled') || !this._options.ignoreReadonly && this.input.prop('readonly') || this.widget) { return; } if (this.input.val() !== undefined && this.input.val().trim().length !== 0) { this._setValue(this._parseInputDate(this.input.val().trim()), 0); } else if (this.unset && this._options.useCurrent) { currentMoment = this.getMoment(); if (typeof this._options.useCurrent === 'string') { currentMoment = <API key>[this._options.useCurrent](currentMoment); } this._setValue(currentMoment, 0); } } else if (this.unset && this._options.useCurrent) { currentMoment = this.getMoment(); if (typeof this._options.useCurrent === 'string') { currentMoment = <API key>[this._options.useCurrent](currentMoment); } this._setValue(currentMoment, 0); } this.widget = this._getTemplate(); this._fillDow(); this._fillMonths(); this.widget.find('.timepicker-hours').hide(); this.widget.find('.timepicker-minutes').hide(); this.widget.find('.timepicker-seconds').hide(); this._update(); this._showMode(); $(window).on('resize', { picker: this }, this._place); this.widget.on('click', '[data-action]', $.proxy(this._doAction, this)); // this handles clicks on the widget this.widget.on('mousedown', false); if (this.component && this.component.hasClass('btn')) { this.component.toggleClass('active'); } this._place(); this.widget.show(); if (this.input !== undefined && this._options.focusOnShow && !this.input.is(':focus')) { this.input.focus(); } this._notifyEvent({ type: DateTimePicker.Event.SHOW }); }; <API key>.prototype.destroy = function destroy() { this.hide(); //todo doc off? this._element.removeData(DateTimePicker.DATA_KEY); this._element.removeData('date'); }; <API key>.prototype.disable = function disable() { this.hide(); if (this.component && this.component.hasClass('btn')) { this.component.addClass('disabled'); } if (this.input !== undefined) { this.input.prop('disabled', true); //todo disable this/comp if input is null } }; <API key>.prototype.enable = function enable() { if (this.component && this.component.hasClass('btn')) { this.component.removeClass('disabled'); } if (this.input !== undefined) { this.input.prop('disabled', false); //todo enable comp/this if input is null } }; <API key>.prototype.toolbarPlacement = function toolbarPlacement(_toolbarPlacement) { if (arguments.length === 0) { return this._options.toolbarPlacement; } if (typeof _toolbarPlacement !== 'string') { throw new TypeError('toolbarPlacement() expects a string parameter'); } if (toolbarPlacements.indexOf(_toolbarPlacement) === -1) { throw new TypeError('toolbarPlacement() parameter must be one of (' + toolbarPlacements.join(', ') + ') value'); } this._options.toolbarPlacement = _toolbarPlacement; if (this.widget) { this.hide(); this.show(); } }; <API key>.prototype.widgetPositioning = function widgetPositioning(_widgetPositioning) { if (arguments.length === 0) { return $.extend({}, this._options.widgetPositioning); } if ({}.toString.call(_widgetPositioning) !== '[object Object]') { throw new TypeError('widgetPositioning() expects an object variable'); } if (_widgetPositioning.horizontal) { if (typeof _widgetPositioning.horizontal !== 'string') { throw new TypeError('widgetPositioning() horizontal variable must be a string'); } _widgetPositioning.horizontal = _widgetPositioning.horizontal.toLowerCase(); if (horizontalModes.indexOf(_widgetPositioning.horizontal) === -1) { throw new TypeError('widgetPositioning() expects horizontal parameter to be one of (' + horizontalModes.join(', ') + ')'); } this._options.widgetPositioning.horizontal = _widgetPositioning.horizontal; } if (_widgetPositioning.vertical) { if (typeof _widgetPositioning.vertical !== 'string') { throw new TypeError('widgetPositioning() vertical variable must be a string'); } _widgetPositioning.vertical = _widgetPositioning.vertical.toLowerCase(); if (verticalModes.indexOf(_widgetPositioning.vertical) === -1) { throw new TypeError('widgetPositioning() expects vertical parameter to be one of (' + verticalModes.join(', ') + ')'); } this._options.widgetPositioning.vertical = _widgetPositioning.vertical; } this._update(); }; <API key>.prototype.widgetParent = function widgetParent(_widgetParent) { if (arguments.length === 0) { return this._options.widgetParent; } if (typeof _widgetParent === 'string') { _widgetParent = $(_widgetParent); } if (_widgetParent !== null && typeof _widgetParent !== 'string' && !(_widgetParent instanceof $)) { throw new TypeError('widgetParent() expects a string or a jQuery object parameter'); } this._options.widgetParent = _widgetParent; if (this.widget) { this.hide(); this.show(); } }; //static <API key>._jQueryHandleThis = function _jQueryHandleThis(me, option, argument) { var data = $(me).data(DateTimePicker.DATA_KEY); if ((typeof option === 'undefined' ? 'undefined' : _typeof(option)) === 'object') { $.extend({}, DateTimePicker.Default, option); } if (!data) { data = new <API key>($(me), option); $(me).data(DateTimePicker.DATA_KEY, data); } if (typeof option === 'string') { if (data[option] === undefined) { throw new Error('No method named "' + option + '"'); } if (argument === undefined) { return data[option](); } else { return data[option](argument); } } }; <API key>._jQueryInterface = function _jQueryInterface(option, argument) { if (this.length === 1) { return <API key>._jQueryHandleThis(this[0], option, argument); } return this.each(function () { <API key>._jQueryHandleThis(this, option, argument); }); }; return <API key>; }(DateTimePicker); $(document).on(DateTimePicker.Event.CLICK_DATA_API, DateTimePicker.Selector.DATA_TOGGLE, function () { var $target = <API key>($(this)); if ($target.length === 0) { return; } <API key>._jQueryInterface.call($target, 'toggle'); }).on(DateTimePicker.Event.CHANGE, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = <API key>($(this)); if ($target.length === 0) { return; } <API key>._jQueryInterface.call($target, '_change', event); }).on(DateTimePicker.Event.BLUR, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = <API key>($(this)), config = $target.data(DateTimePicker.DATA_KEY); if ($target.length === 0) { return; } if (config._options.debug || window.debug) { return; } <API key>._jQueryInterface.call($target, 'hide', event); }).on(DateTimePicker.Event.KEYDOWN, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = <API key>($(this)); if ($target.length === 0) { return; } <API key>._jQueryInterface.call($target, '_keydown', event); }).on(DateTimePicker.Event.KEYUP, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = <API key>($(this)); if ($target.length === 0) { return; } <API key>._jQueryInterface.call($target, '_keyup', event); }).on(DateTimePicker.Event.FOCUS, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = <API key>($(this)), config = $target.data(DateTimePicker.DATA_KEY); if ($target.length === 0) { return; } if (!config._options.allowInputToggle) { return; } <API key>._jQueryInterface.call($target, config, event); }); $.fn[DateTimePicker.NAME] = <API key>._jQueryInterface; $.fn[DateTimePicker.NAME].Constructor = <API key>; $.fn[DateTimePicker.NAME].noConflict = function () { $.fn[DateTimePicker.NAME] = JQUERY_NO_CONFLICT; return <API key>._jQueryInterface; }; return <API key>; }(jQuery); }();
#import <UIKit/UIKit.h> @interface UIView (WMF_RoundCorners) /** * @warning Watch out for race conditions with auto layout when using these methods! Be sure to call them after layout, * e.g. in @c <API key>. */ Round all corners of the receiver, making it circular. - (void)wmf_makeCircular; /** * Round the given corners of the receiver. * @param corners The corners to apply rounding to. * @param radius The radius to apply to @c corners. */ - (void)wmf_roundCorners:(UIRectCorner)corners toRadius:(float)radius; @end
The Elixir and Phoenix communities are friendly and welcoming. All questions and comments are valuable, so please come join the discussion! There are a number of places to connect with community members at all experience levels. * We're on freenode IRC in [\ * We have a [Slack channel](https://elixir-slackin.herokuapp.com/). * The Phoenix repo has an [issue tracker](https://github.com/phoenixframework/phoenix/issues). * For general Phoenix questions, email the [phoenix-talk mailing list](http://groups.google.com/group/phoenix-talk). * To discuss new features in the framework, email the [phoenix-core mailing list](http://groups.google.com/group/phoenix-core). * Ask or answer questions about Phoenix on [stackoverflow](http://stackoverflow.com/questions/tagged/phoenix-framework). * Follow the Phoenix Framework on [Twitter](https://twitter.com/elixirphoenix). * For questions about these guides, please report an [issue](https: