text
stringlengths
2
99.5k
meta
dict
# -*- coding: utf-8 -*- """ Version string and parsed tuple. Keeps it all in one place. """ __version__ = '0.3.1' VERSION = tuple(int(x) for x in __version__.split('.'))
{ "pile_set_name": "Github" }
/* * ALSA driver for Xilinx ML403 AC97 Controller Reference * IP: opb_ac97_controller_ref_v1_00_a (EDK 8.1i) * IP: opb_ac97_controller_ref_v1_00_a (EDK 9.1i) * * Copyright (c) by 2007 Joachim Foerster <JOFT@gmx.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /* Some notes / status of this driver: * * - Don't wonder about some strange implementations of things - especially the * (heavy) shadowing of codec registers, with which I tried to reduce read * accesses to a minimum, because after a variable amount of accesses, the AC97 * controller doesn't raise the register access finished bit anymore ... * * - Playback support seems to be pretty stable - no issues here. * - Capture support "works" now, too. Overruns don't happen any longer so often. * But there might still be some ... */ #include <linux/init.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/ioport.h> #include <linux/slab.h> #include <linux/io.h> #include <linux/interrupt.h> /* HZ */ #include <linux/param.h> /* jiffies, time_*() */ #include <linux/jiffies.h> /* schedule_timeout*() */ #include <linux/sched.h> /* spin_lock*() */ #include <linux/spinlock.h> /* struct mutex, mutex_init(), mutex_*lock() */ #include <linux/mutex.h> /* snd_printk(), snd_printd() */ #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/initval.h> #include <sound/ac97_codec.h> #include "pcm-indirect2.h" #define SND_ML403_AC97CR_DRIVER "ml403-ac97cr" MODULE_AUTHOR("Joachim Foerster <JOFT@gmx.de>"); MODULE_DESCRIPTION("Xilinx ML403 AC97 Controller Reference"); MODULE_LICENSE("GPL"); MODULE_SUPPORTED_DEVICE("{{Xilinx,ML403 AC97 Controller Reference}}"); static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE; module_param_array(index, int, NULL, 0444); MODULE_PARM_DESC(index, "Index value for ML403 AC97 Controller Reference."); module_param_array(id, charp, NULL, 0444); MODULE_PARM_DESC(id, "ID string for ML403 AC97 Controller Reference."); module_param_array(enable, bool, NULL, 0444); MODULE_PARM_DESC(enable, "Enable this ML403 AC97 Controller Reference."); /* Special feature options */ /*#define CODEC_WRITE_CHECK_RAF*/ /* don't return after a write to a codec * register, while RAF bit is not set */ /* Debug options for code which may be removed completely in a final version */ #ifdef CONFIG_SND_DEBUG /*#define CODEC_STAT*/ /* turn on some minimal "statistics" * about codec register usage */ #define SND_PCM_INDIRECT2_STAT /* turn on some "statistics" about the * process of copying bytes from the * intermediate buffer to the hardware * fifo and the other way round */ #endif /* Definition of a "level/facility dependent" printk(); may be removed * completely in a final version */ #undef PDEBUG #ifdef CONFIG_SND_DEBUG /* "facilities" for PDEBUG */ #define UNKNOWN (1<<0) #define CODEC_SUCCESS (1<<1) #define CODEC_FAKE (1<<2) #define INIT_INFO (1<<3) #define INIT_FAILURE (1<<4) #define WORK_INFO (1<<5) #define WORK_FAILURE (1<<6) #define PDEBUG_FACILITIES (UNKNOWN | INIT_FAILURE | WORK_FAILURE) #define PDEBUG(fac, fmt, args...) do { \ if (fac & PDEBUG_FACILITIES) \ snd_printd(KERN_DEBUG SND_ML403_AC97CR_DRIVER ": " \ fmt, ##args); \ } while (0) #else #define PDEBUG(fac, fmt, args...) /* nothing */ #endif /* Defines for "waits"/timeouts (portions of HZ=250 on arch/ppc by default) */ #define CODEC_TIMEOUT_ON_INIT 5 /* timeout for checking for codec * readiness (after insmod) */ #ifndef CODEC_WRITE_CHECK_RAF #define CODEC_WAIT_AFTER_WRITE 100 /* general, static wait after a write * access to a codec register, may be * 0 to completely remove wait */ #else #define CODEC_TIMEOUT_AFTER_WRITE 5 /* timeout after a write access to a * codec register, if RAF bit is used */ #endif #define CODEC_TIMEOUT_AFTER_READ 5 /* timeout after a read access to a * codec register (checking RAF bit) */ /* Infrastructure for codec register shadowing */ #define LM4550_REG_OK (1<<0) /* register exists */ #define LM4550_REG_DONEREAD (1<<1) /* read register once, value should be * the same currently in the register */ #define LM4550_REG_NOSAVE (1<<2) /* values written to this register will * not be saved in the register */ #define LM4550_REG_NOSHADOW (1<<3) /* don't do register shadowing, use plain * hardware access */ #define LM4550_REG_READONLY (1<<4) /* register is read only */ #define LM4550_REG_FAKEPROBE (1<<5) /* fake write _and_ read actions during * probe() correctly */ #define LM4550_REG_FAKEREAD (1<<6) /* fake read access, always return * default value */ #define LM4550_REG_ALLFAKE (LM4550_REG_FAKEREAD | LM4550_REG_FAKEPROBE) struct lm4550_reg { u16 value; u16 flag; u16 wmask; u16 def; }; struct lm4550_reg lm4550_regfile[64] = { [AC97_RESET / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_NOSAVE \ | LM4550_REG_FAKEREAD, .def = 0x0D50}, [AC97_MASTER / 2] = {.flag = LM4550_REG_OK | LM4550_REG_FAKEPROBE, .wmask = 0x9F1F, .def = 0x8000}, [AC97_HEADPHONE / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_FAKEPROBE, .wmask = 0x9F1F, .def = 0x8000}, [AC97_MASTER_MONO / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_FAKEPROBE, .wmask = 0x801F, .def = 0x8000}, [AC97_PC_BEEP / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_FAKEPROBE, .wmask = 0x801E, .def = 0x0}, [AC97_PHONE / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_FAKEPROBE, .wmask = 0x801F, .def = 0x8008}, [AC97_MIC / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_FAKEPROBE, .wmask = 0x805F, .def = 0x8008}, [AC97_LINE / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_FAKEPROBE, .wmask = 0x9F1F, .def = 0x8808}, [AC97_CD / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_FAKEPROBE, .wmask = 0x9F1F, .def = 0x8808}, [AC97_VIDEO / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_FAKEPROBE, .wmask = 0x9F1F, .def = 0x8808}, [AC97_AUX / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_FAKEPROBE, .wmask = 0x9F1F, .def = 0x8808}, [AC97_PCM / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_FAKEPROBE, .wmask = 0x9F1F, .def = 0x8008}, [AC97_REC_SEL / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_FAKEPROBE, .wmask = 0x707, .def = 0x0}, [AC97_REC_GAIN / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_FAKEPROBE, .wmask = 0x8F0F, .def = 0x8000}, [AC97_GENERAL_PURPOSE / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_FAKEPROBE, .def = 0x0, .wmask = 0xA380}, [AC97_3D_CONTROL / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_FAKEREAD \ | LM4550_REG_READONLY, .def = 0x0101}, [AC97_POWERDOWN / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_NOSHADOW \ | LM4550_REG_NOSAVE, .wmask = 0xFF00}, /* may not write ones to * REF/ANL/DAC/ADC bits * FIXME: Is this ok? */ [AC97_EXTENDED_ID / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_FAKEREAD \ | LM4550_REG_READONLY, .def = 0x0201}, /* primary codec */ [AC97_EXTENDED_STATUS / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_NOSHADOW \ | LM4550_REG_NOSAVE, .wmask = 0x1}, [AC97_PCM_FRONT_DAC_RATE / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_FAKEPROBE, .def = 0xBB80, .wmask = 0xFFFF}, [AC97_PCM_LR_ADC_RATE / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_FAKEPROBE, .def = 0xBB80, .wmask = 0xFFFF}, [AC97_VENDOR_ID1 / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_READONLY \ | LM4550_REG_FAKEREAD, .def = 0x4E53}, [AC97_VENDOR_ID2 / 2] = {.flag = LM4550_REG_OK \ | LM4550_REG_READONLY \ | LM4550_REG_FAKEREAD, .def = 0x4350} }; #define LM4550_RF_OK(reg) (lm4550_regfile[reg / 2].flag & LM4550_REG_OK) static void lm4550_regfile_init(void) { int i; for (i = 0; i < 64; i++) if (lm4550_regfile[i].flag & LM4550_REG_FAKEPROBE) lm4550_regfile[i].value = lm4550_regfile[i].def; } static void lm4550_regfile_write_values_after_init(struct snd_ac97 *ac97) { int i; for (i = 0; i < 64; i++) if ((lm4550_regfile[i].flag & LM4550_REG_FAKEPROBE) && (lm4550_regfile[i].value != lm4550_regfile[i].def)) { PDEBUG(CODEC_FAKE, "lm4550_regfile_write_values_after_" "init(): reg=0x%x value=0x%x / %d is different " "from def=0x%x / %d\n", i, lm4550_regfile[i].value, lm4550_regfile[i].value, lm4550_regfile[i].def, lm4550_regfile[i].def); snd_ac97_write(ac97, i * 2, lm4550_regfile[i].value); lm4550_regfile[i].flag |= LM4550_REG_DONEREAD; } } /* direct registers */ #define CR_REG(ml403_ac97cr, x) ((ml403_ac97cr)->port + CR_REG_##x) #define CR_REG_PLAYFIFO 0x00 #define CR_PLAYDATA(a) ((a) & 0xFFFF) #define CR_REG_RECFIFO 0x04 #define CR_RECDATA(a) ((a) & 0xFFFF) #define CR_REG_STATUS 0x08 #define CR_RECOVER (1<<7) #define CR_PLAYUNDER (1<<6) #define CR_CODECREADY (1<<5) #define CR_RAF (1<<4) #define CR_RECEMPTY (1<<3) #define CR_RECFULL (1<<2) #define CR_PLAYHALF (1<<1) #define CR_PLAYFULL (1<<0) #define CR_REG_RESETFIFO 0x0C #define CR_RECRESET (1<<1) #define CR_PLAYRESET (1<<0) #define CR_REG_CODEC_ADDR 0x10 /* UG082 says: * #define CR_CODEC_ADDR(a) ((a) << 1) * #define CR_CODEC_READ (1<<0) * #define CR_CODEC_WRITE (0<<0) */ /* RefDesign example says: */ #define CR_CODEC_ADDR(a) ((a) << 0) #define CR_CODEC_READ (1<<7) #define CR_CODEC_WRITE (0<<7) #define CR_REG_CODEC_DATAREAD 0x14 #define CR_CODEC_DATAREAD(v) ((v) & 0xFFFF) #define CR_REG_CODEC_DATAWRITE 0x18 #define CR_CODEC_DATAWRITE(v) ((v) & 0xFFFF) #define CR_FIFO_SIZE 32 struct snd_ml403_ac97cr { /* lock for access to (controller) registers */ spinlock_t reg_lock; /* mutex for the whole sequence of accesses to (controller) registers * which affect codec registers */ struct mutex cdc_mutex; int irq; /* for playback */ int enable_irq; /* for playback */ int capture_irq; int enable_capture_irq; struct resource *res_port; void *port; struct snd_ac97 *ac97; int ac97_fake; #ifdef CODEC_STAT int ac97_read; int ac97_write; #endif struct platform_device *pfdev; struct snd_card *card; struct snd_pcm *pcm; struct snd_pcm_substream *playback_substream; struct snd_pcm_substream *capture_substream; struct snd_pcm_indirect2 ind_rec; /* for playback */ struct snd_pcm_indirect2 capture_ind2_rec; }; static const struct snd_pcm_hardware snd_ml403_ac97cr_playback = { .info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_MMAP_VALID), .formats = SNDRV_PCM_FMTBIT_S16_BE, .rates = (SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000), .rate_min = 4000, .rate_max = 48000, .channels_min = 2, .channels_max = 2, .buffer_bytes_max = (128*1024), .period_bytes_min = CR_FIFO_SIZE/2, .period_bytes_max = (64*1024), .periods_min = 2, .periods_max = (128*1024)/(CR_FIFO_SIZE/2), .fifo_size = 0, }; static const struct snd_pcm_hardware snd_ml403_ac97cr_capture = { .info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_MMAP_VALID), .formats = SNDRV_PCM_FMTBIT_S16_BE, .rates = (SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000), .rate_min = 4000, .rate_max = 48000, .channels_min = 2, .channels_max = 2, .buffer_bytes_max = (128*1024), .period_bytes_min = CR_FIFO_SIZE/2, .period_bytes_max = (64*1024), .periods_min = 2, .periods_max = (128*1024)/(CR_FIFO_SIZE/2), .fifo_size = 0, }; static size_t snd_ml403_ac97cr_playback_ind2_zero(struct snd_pcm_substream *substream, struct snd_pcm_indirect2 *rec) { struct snd_ml403_ac97cr *ml403_ac97cr; int copied_words = 0; u32 full = 0; ml403_ac97cr = snd_pcm_substream_chip(substream); spin_lock(&ml403_ac97cr->reg_lock); while ((full = (in_be32(CR_REG(ml403_ac97cr, STATUS)) & CR_PLAYFULL)) != CR_PLAYFULL) { out_be32(CR_REG(ml403_ac97cr, PLAYFIFO), 0); copied_words++; } rec->hw_ready = 0; spin_unlock(&ml403_ac97cr->reg_lock); return (size_t) (copied_words * 2); } static size_t snd_ml403_ac97cr_playback_ind2_copy(struct snd_pcm_substream *substream, struct snd_pcm_indirect2 *rec, size_t bytes) { struct snd_ml403_ac97cr *ml403_ac97cr; u16 *src; int copied_words = 0; u32 full = 0; ml403_ac97cr = snd_pcm_substream_chip(substream); src = (u16 *)(substream->runtime->dma_area + rec->sw_data); spin_lock(&ml403_ac97cr->reg_lock); while (((full = (in_be32(CR_REG(ml403_ac97cr, STATUS)) & CR_PLAYFULL)) != CR_PLAYFULL) && (bytes > 1)) { out_be32(CR_REG(ml403_ac97cr, PLAYFIFO), CR_PLAYDATA(src[copied_words])); copied_words++; bytes = bytes - 2; } if (full != CR_PLAYFULL) rec->hw_ready = 1; else rec->hw_ready = 0; spin_unlock(&ml403_ac97cr->reg_lock); return (size_t) (copied_words * 2); } static size_t snd_ml403_ac97cr_capture_ind2_null(struct snd_pcm_substream *substream, struct snd_pcm_indirect2 *rec) { struct snd_ml403_ac97cr *ml403_ac97cr; int copied_words = 0; u32 empty = 0; ml403_ac97cr = snd_pcm_substream_chip(substream); spin_lock(&ml403_ac97cr->reg_lock); while ((empty = (in_be32(CR_REG(ml403_ac97cr, STATUS)) & CR_RECEMPTY)) != CR_RECEMPTY) { volatile u32 trash; trash = CR_RECDATA(in_be32(CR_REG(ml403_ac97cr, RECFIFO))); /* Hmmmm, really necessary? Don't want call to in_be32() * to be optimised away! */ trash++; copied_words++; } rec->hw_ready = 0; spin_unlock(&ml403_ac97cr->reg_lock); return (size_t) (copied_words * 2); } static size_t snd_ml403_ac97cr_capture_ind2_copy(struct snd_pcm_substream *substream, struct snd_pcm_indirect2 *rec, size_t bytes) { struct snd_ml403_ac97cr *ml403_ac97cr; u16 *dst; int copied_words = 0; u32 empty = 0; ml403_ac97cr = snd_pcm_substream_chip(substream); dst = (u16 *)(substream->runtime->dma_area + rec->sw_data); spin_lock(&ml403_ac97cr->reg_lock); while (((empty = (in_be32(CR_REG(ml403_ac97cr, STATUS)) & CR_RECEMPTY)) != CR_RECEMPTY) && (bytes > 1)) { dst[copied_words] = CR_RECDATA(in_be32(CR_REG(ml403_ac97cr, RECFIFO))); copied_words++; bytes = bytes - 2; } if (empty != CR_RECEMPTY) rec->hw_ready = 1; else rec->hw_ready = 0; spin_unlock(&ml403_ac97cr->reg_lock); return (size_t) (copied_words * 2); } static snd_pcm_uframes_t snd_ml403_ac97cr_pcm_pointer(struct snd_pcm_substream *substream) { struct snd_ml403_ac97cr *ml403_ac97cr; struct snd_pcm_indirect2 *ind2_rec = NULL; ml403_ac97cr = snd_pcm_substream_chip(substream); if (substream == ml403_ac97cr->playback_substream) ind2_rec = &ml403_ac97cr->ind_rec; if (substream == ml403_ac97cr->capture_substream) ind2_rec = &ml403_ac97cr->capture_ind2_rec; if (ind2_rec != NULL) return snd_pcm_indirect2_pointer(substream, ind2_rec); return (snd_pcm_uframes_t) 0; } static int snd_ml403_ac97cr_pcm_playback_trigger(struct snd_pcm_substream *substream, int cmd) { struct snd_ml403_ac97cr *ml403_ac97cr; int err = 0; ml403_ac97cr = snd_pcm_substream_chip(substream); switch (cmd) { case SNDRV_PCM_TRIGGER_START: PDEBUG(WORK_INFO, "trigger(playback): START\n"); ml403_ac97cr->ind_rec.hw_ready = 1; /* clear play FIFO */ out_be32(CR_REG(ml403_ac97cr, RESETFIFO), CR_PLAYRESET); /* enable play irq */ ml403_ac97cr->enable_irq = 1; enable_irq(ml403_ac97cr->irq); break; case SNDRV_PCM_TRIGGER_STOP: PDEBUG(WORK_INFO, "trigger(playback): STOP\n"); ml403_ac97cr->ind_rec.hw_ready = 0; #ifdef SND_PCM_INDIRECT2_STAT snd_pcm_indirect2_stat(substream, &ml403_ac97cr->ind_rec); #endif /* disable play irq */ disable_irq_nosync(ml403_ac97cr->irq); ml403_ac97cr->enable_irq = 0; break; default: err = -EINVAL; break; } PDEBUG(WORK_INFO, "trigger(playback): (done)\n"); return err; } static int snd_ml403_ac97cr_pcm_capture_trigger(struct snd_pcm_substream *substream, int cmd) { struct snd_ml403_ac97cr *ml403_ac97cr; int err = 0; ml403_ac97cr = snd_pcm_substream_chip(substream); switch (cmd) { case SNDRV_PCM_TRIGGER_START: PDEBUG(WORK_INFO, "trigger(capture): START\n"); ml403_ac97cr->capture_ind2_rec.hw_ready = 0; /* clear record FIFO */ out_be32(CR_REG(ml403_ac97cr, RESETFIFO), CR_RECRESET); /* enable record irq */ ml403_ac97cr->enable_capture_irq = 1; enable_irq(ml403_ac97cr->capture_irq); break; case SNDRV_PCM_TRIGGER_STOP: PDEBUG(WORK_INFO, "trigger(capture): STOP\n"); ml403_ac97cr->capture_ind2_rec.hw_ready = 0; #ifdef SND_PCM_INDIRECT2_STAT snd_pcm_indirect2_stat(substream, &ml403_ac97cr->capture_ind2_rec); #endif /* disable capture irq */ disable_irq_nosync(ml403_ac97cr->capture_irq); ml403_ac97cr->enable_capture_irq = 0; break; default: err = -EINVAL; break; } PDEBUG(WORK_INFO, "trigger(capture): (done)\n"); return err; } static int snd_ml403_ac97cr_pcm_playback_prepare(struct snd_pcm_substream *substream) { struct snd_ml403_ac97cr *ml403_ac97cr; struct snd_pcm_runtime *runtime; ml403_ac97cr = snd_pcm_substream_chip(substream); runtime = substream->runtime; PDEBUG(WORK_INFO, "prepare(): period_bytes=%d, minperiod_bytes=%d\n", snd_pcm_lib_period_bytes(substream), CR_FIFO_SIZE / 2); /* set sampling rate */ snd_ac97_set_rate(ml403_ac97cr->ac97, AC97_PCM_FRONT_DAC_RATE, runtime->rate); PDEBUG(WORK_INFO, "prepare(): rate=%d\n", runtime->rate); /* init struct for intermediate buffer */ memset(&ml403_ac97cr->ind_rec, 0, sizeof(struct snd_pcm_indirect2)); ml403_ac97cr->ind_rec.hw_buffer_size = CR_FIFO_SIZE; ml403_ac97cr->ind_rec.sw_buffer_size = snd_pcm_lib_buffer_bytes(substream); ml403_ac97cr->ind_rec.min_periods = -1; ml403_ac97cr->ind_rec.min_multiple = snd_pcm_lib_period_bytes(substream) / (CR_FIFO_SIZE / 2); PDEBUG(WORK_INFO, "prepare(): hw_buffer_size=%d, " "sw_buffer_size=%d, min_multiple=%d\n", CR_FIFO_SIZE, ml403_ac97cr->ind_rec.sw_buffer_size, ml403_ac97cr->ind_rec.min_multiple); return 0; } static int snd_ml403_ac97cr_pcm_capture_prepare(struct snd_pcm_substream *substream) { struct snd_ml403_ac97cr *ml403_ac97cr; struct snd_pcm_runtime *runtime; ml403_ac97cr = snd_pcm_substream_chip(substream); runtime = substream->runtime; PDEBUG(WORK_INFO, "prepare(capture): period_bytes=%d, minperiod_bytes=%d\n", snd_pcm_lib_period_bytes(substream), CR_FIFO_SIZE / 2); /* set sampling rate */ snd_ac97_set_rate(ml403_ac97cr->ac97, AC97_PCM_LR_ADC_RATE, runtime->rate); PDEBUG(WORK_INFO, "prepare(capture): rate=%d\n", runtime->rate); /* init struct for intermediate buffer */ memset(&ml403_ac97cr->capture_ind2_rec, 0, sizeof(struct snd_pcm_indirect2)); ml403_ac97cr->capture_ind2_rec.hw_buffer_size = CR_FIFO_SIZE; ml403_ac97cr->capture_ind2_rec.sw_buffer_size = snd_pcm_lib_buffer_bytes(substream); ml403_ac97cr->capture_ind2_rec.min_multiple = snd_pcm_lib_period_bytes(substream) / (CR_FIFO_SIZE / 2); PDEBUG(WORK_INFO, "prepare(capture): hw_buffer_size=%d, " "sw_buffer_size=%d, min_multiple=%d\n", CR_FIFO_SIZE, ml403_ac97cr->capture_ind2_rec.sw_buffer_size, ml403_ac97cr->capture_ind2_rec.min_multiple); return 0; } static int snd_ml403_ac97cr_hw_free(struct snd_pcm_substream *substream) { PDEBUG(WORK_INFO, "hw_free()\n"); return snd_pcm_lib_free_pages(substream); } static int snd_ml403_ac97cr_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *hw_params) { PDEBUG(WORK_INFO, "hw_params(): desired buffer bytes=%d, desired " "period bytes=%d\n", params_buffer_bytes(hw_params), params_period_bytes(hw_params)); return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params)); } static int snd_ml403_ac97cr_playback_open(struct snd_pcm_substream *substream) { struct snd_ml403_ac97cr *ml403_ac97cr; struct snd_pcm_runtime *runtime; ml403_ac97cr = snd_pcm_substream_chip(substream); runtime = substream->runtime; PDEBUG(WORK_INFO, "open(playback)\n"); ml403_ac97cr->playback_substream = substream; runtime->hw = snd_ml403_ac97cr_playback; snd_pcm_hw_constraint_step(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_BYTES, CR_FIFO_SIZE / 2); return 0; } static int snd_ml403_ac97cr_capture_open(struct snd_pcm_substream *substream) { struct snd_ml403_ac97cr *ml403_ac97cr; struct snd_pcm_runtime *runtime; ml403_ac97cr = snd_pcm_substream_chip(substream); runtime = substream->runtime; PDEBUG(WORK_INFO, "open(capture)\n"); ml403_ac97cr->capture_substream = substream; runtime->hw = snd_ml403_ac97cr_capture; snd_pcm_hw_constraint_step(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_BYTES, CR_FIFO_SIZE / 2); return 0; } static int snd_ml403_ac97cr_playback_close(struct snd_pcm_substream *substream) { struct snd_ml403_ac97cr *ml403_ac97cr; ml403_ac97cr = snd_pcm_substream_chip(substream); PDEBUG(WORK_INFO, "close(playback)\n"); ml403_ac97cr->playback_substream = NULL; return 0; } static int snd_ml403_ac97cr_capture_close(struct snd_pcm_substream *substream) { struct snd_ml403_ac97cr *ml403_ac97cr; ml403_ac97cr = snd_pcm_substream_chip(substream); PDEBUG(WORK_INFO, "close(capture)\n"); ml403_ac97cr->capture_substream = NULL; return 0; } static const struct snd_pcm_ops snd_ml403_ac97cr_playback_ops = { .open = snd_ml403_ac97cr_playback_open, .close = snd_ml403_ac97cr_playback_close, .ioctl = snd_pcm_lib_ioctl, .hw_params = snd_ml403_ac97cr_hw_params, .hw_free = snd_ml403_ac97cr_hw_free, .prepare = snd_ml403_ac97cr_pcm_playback_prepare, .trigger = snd_ml403_ac97cr_pcm_playback_trigger, .pointer = snd_ml403_ac97cr_pcm_pointer, }; static const struct snd_pcm_ops snd_ml403_ac97cr_capture_ops = { .open = snd_ml403_ac97cr_capture_open, .close = snd_ml403_ac97cr_capture_close, .ioctl = snd_pcm_lib_ioctl, .hw_params = snd_ml403_ac97cr_hw_params, .hw_free = snd_ml403_ac97cr_hw_free, .prepare = snd_ml403_ac97cr_pcm_capture_prepare, .trigger = snd_ml403_ac97cr_pcm_capture_trigger, .pointer = snd_ml403_ac97cr_pcm_pointer, }; static irqreturn_t snd_ml403_ac97cr_irq(int irq, void *dev_id) { struct snd_ml403_ac97cr *ml403_ac97cr; struct platform_device *pfdev; int cmp_irq; ml403_ac97cr = (struct snd_ml403_ac97cr *)dev_id; if (ml403_ac97cr == NULL) return IRQ_NONE; pfdev = ml403_ac97cr->pfdev; /* playback interrupt */ cmp_irq = platform_get_irq(pfdev, 0); if (irq == cmp_irq) { if (ml403_ac97cr->enable_irq) snd_pcm_indirect2_playback_interrupt( ml403_ac97cr->playback_substream, &ml403_ac97cr->ind_rec, snd_ml403_ac97cr_playback_ind2_copy, snd_ml403_ac97cr_playback_ind2_zero); else goto __disable_irq; } else { /* record interrupt */ cmp_irq = platform_get_irq(pfdev, 1); if (irq == cmp_irq) { if (ml403_ac97cr->enable_capture_irq) snd_pcm_indirect2_capture_interrupt( ml403_ac97cr->capture_substream, &ml403_ac97cr->capture_ind2_rec, snd_ml403_ac97cr_capture_ind2_copy, snd_ml403_ac97cr_capture_ind2_null); else goto __disable_irq; } else return IRQ_NONE; } return IRQ_HANDLED; __disable_irq: PDEBUG(INIT_INFO, "irq(): irq %d is meant to be disabled! So, now try " "to disable it _really_!\n", irq); disable_irq_nosync(irq); return IRQ_HANDLED; } static unsigned short snd_ml403_ac97cr_codec_read(struct snd_ac97 *ac97, unsigned short reg) { struct snd_ml403_ac97cr *ml403_ac97cr = ac97->private_data; #ifdef CODEC_STAT u32 stat; u32 rafaccess = 0; #endif unsigned long end_time; u16 value = 0; if (!LM4550_RF_OK(reg)) { snd_printk(KERN_WARNING SND_ML403_AC97CR_DRIVER ": " "access to unknown/unused codec register 0x%x " "ignored!\n", reg); return 0; } /* check if we can fake/answer this access from our shadow register */ if ((lm4550_regfile[reg / 2].flag & (LM4550_REG_DONEREAD | LM4550_REG_ALLFAKE)) && !(lm4550_regfile[reg / 2].flag & LM4550_REG_NOSHADOW)) { if (lm4550_regfile[reg / 2].flag & LM4550_REG_FAKEREAD) { PDEBUG(CODEC_FAKE, "codec_read(): faking read from " "reg=0x%x, val=0x%x / %d\n", reg, lm4550_regfile[reg / 2].def, lm4550_regfile[reg / 2].def); return lm4550_regfile[reg / 2].def; } else if ((lm4550_regfile[reg / 2].flag & LM4550_REG_FAKEPROBE) && ml403_ac97cr->ac97_fake) { PDEBUG(CODEC_FAKE, "codec_read(): faking read from " "reg=0x%x, val=0x%x / %d (probe)\n", reg, lm4550_regfile[reg / 2].value, lm4550_regfile[reg / 2].value); return lm4550_regfile[reg / 2].value; } else { #ifdef CODEC_STAT PDEBUG(CODEC_FAKE, "codec_read(): read access " "answered by shadow register 0x%x (value=0x%x " "/ %d) (cw=%d cr=%d)\n", reg, lm4550_regfile[reg / 2].value, lm4550_regfile[reg / 2].value, ml403_ac97cr->ac97_write, ml403_ac97cr->ac97_read); #else PDEBUG(CODEC_FAKE, "codec_read(): read access " "answered by shadow register 0x%x (value=0x%x " "/ %d)\n", reg, lm4550_regfile[reg / 2].value, lm4550_regfile[reg / 2].value); #endif return lm4550_regfile[reg / 2].value; } } /* if we are here, we _have_ to access the codec really, no faking */ if (mutex_lock_interruptible(&ml403_ac97cr->cdc_mutex) != 0) return 0; #ifdef CODEC_STAT ml403_ac97cr->ac97_read++; #endif spin_lock(&ml403_ac97cr->reg_lock); out_be32(CR_REG(ml403_ac97cr, CODEC_ADDR), CR_CODEC_ADDR(reg) | CR_CODEC_READ); spin_unlock(&ml403_ac97cr->reg_lock); end_time = jiffies + (HZ / CODEC_TIMEOUT_AFTER_READ); do { spin_lock(&ml403_ac97cr->reg_lock); #ifdef CODEC_STAT rafaccess++; stat = in_be32(CR_REG(ml403_ac97cr, STATUS)); if ((stat & CR_RAF) == CR_RAF) { value = CR_CODEC_DATAREAD( in_be32(CR_REG(ml403_ac97cr, CODEC_DATAREAD))); PDEBUG(CODEC_SUCCESS, "codec_read(): (done) reg=0x%x, " "value=0x%x / %d (STATUS=0x%x)\n", reg, value, value, stat); #else if ((in_be32(CR_REG(ml403_ac97cr, STATUS)) & CR_RAF) == CR_RAF) { value = CR_CODEC_DATAREAD( in_be32(CR_REG(ml403_ac97cr, CODEC_DATAREAD))); PDEBUG(CODEC_SUCCESS, "codec_read(): (done) " "reg=0x%x, value=0x%x / %d\n", reg, value, value); #endif lm4550_regfile[reg / 2].value = value; lm4550_regfile[reg / 2].flag |= LM4550_REG_DONEREAD; spin_unlock(&ml403_ac97cr->reg_lock); mutex_unlock(&ml403_ac97cr->cdc_mutex); return value; } spin_unlock(&ml403_ac97cr->reg_lock); schedule_timeout_uninterruptible(1); } while (time_after(end_time, jiffies)); /* read the DATAREAD register anyway, see comment below */ spin_lock(&ml403_ac97cr->reg_lock); value = CR_CODEC_DATAREAD(in_be32(CR_REG(ml403_ac97cr, CODEC_DATAREAD))); spin_unlock(&ml403_ac97cr->reg_lock); #ifdef CODEC_STAT snd_printk(KERN_WARNING SND_ML403_AC97CR_DRIVER ": " "timeout while codec read! " "(reg=0x%x, last STATUS=0x%x, DATAREAD=0x%x / %d, %d) " "(cw=%d, cr=%d)\n", reg, stat, value, value, rafaccess, ml403_ac97cr->ac97_write, ml403_ac97cr->ac97_read); #else snd_printk(KERN_WARNING SND_ML403_AC97CR_DRIVER ": " "timeout while codec read! " "(reg=0x%x, DATAREAD=0x%x / %d)\n", reg, value, value); #endif /* BUG: This is PURE speculation! But after _most_ read timeouts the * value in the register is ok! */ lm4550_regfile[reg / 2].value = value; lm4550_regfile[reg / 2].flag |= LM4550_REG_DONEREAD; mutex_unlock(&ml403_ac97cr->cdc_mutex); return value; } static void snd_ml403_ac97cr_codec_write(struct snd_ac97 *ac97, unsigned short reg, unsigned short val) { struct snd_ml403_ac97cr *ml403_ac97cr = ac97->private_data; #ifdef CODEC_STAT u32 stat; u32 rafaccess = 0; #endif #ifdef CODEC_WRITE_CHECK_RAF unsigned long end_time; #endif if (!LM4550_RF_OK(reg)) { snd_printk(KERN_WARNING SND_ML403_AC97CR_DRIVER ": " "access to unknown/unused codec register 0x%x " "ignored!\n", reg); return; } if (lm4550_regfile[reg / 2].flag & LM4550_REG_READONLY) { snd_printk(KERN_WARNING SND_ML403_AC97CR_DRIVER ": " "write access to read only codec register 0x%x " "ignored!\n", reg); return; } if ((val & lm4550_regfile[reg / 2].wmask) != val) { snd_printk(KERN_WARNING SND_ML403_AC97CR_DRIVER ": " "write access to codec register 0x%x " "with bad value 0x%x / %d!\n", reg, val, val); val = val & lm4550_regfile[reg / 2].wmask; } if (((lm4550_regfile[reg / 2].flag & LM4550_REG_FAKEPROBE) && ml403_ac97cr->ac97_fake) && !(lm4550_regfile[reg / 2].flag & LM4550_REG_NOSHADOW)) { PDEBUG(CODEC_FAKE, "codec_write(): faking write to reg=0x%x, " "val=0x%x / %d\n", reg, val, val); lm4550_regfile[reg / 2].value = (val & lm4550_regfile[reg / 2].wmask); return; } if (mutex_lock_interruptible(&ml403_ac97cr->cdc_mutex) != 0) return; #ifdef CODEC_STAT ml403_ac97cr->ac97_write++; #endif spin_lock(&ml403_ac97cr->reg_lock); out_be32(CR_REG(ml403_ac97cr, CODEC_DATAWRITE), CR_CODEC_DATAWRITE(val)); out_be32(CR_REG(ml403_ac97cr, CODEC_ADDR), CR_CODEC_ADDR(reg) | CR_CODEC_WRITE); spin_unlock(&ml403_ac97cr->reg_lock); #ifdef CODEC_WRITE_CHECK_RAF /* check CR_CODEC_RAF bit to see if write access to register is done; * loop until bit is set or timeout happens */ end_time = jiffies + HZ / CODEC_TIMEOUT_AFTER_WRITE; do { spin_lock(&ml403_ac97cr->reg_lock); #ifdef CODEC_STAT rafaccess++; stat = in_be32(CR_REG(ml403_ac97cr, STATUS)) if ((stat & CR_RAF) == CR_RAF) { #else if ((in_be32(CR_REG(ml403_ac97cr, STATUS)) & CR_RAF) == CR_RAF) { #endif PDEBUG(CODEC_SUCCESS, "codec_write(): (done) " "reg=0x%x, value=%d / 0x%x\n", reg, val, val); if (!(lm4550_regfile[reg / 2].flag & LM4550_REG_NOSHADOW) && !(lm4550_regfile[reg / 2].flag & LM4550_REG_NOSAVE)) lm4550_regfile[reg / 2].value = val; lm4550_regfile[reg / 2].flag |= LM4550_REG_DONEREAD; spin_unlock(&ml403_ac97cr->reg_lock); mutex_unlock(&ml403_ac97cr->cdc_mutex); return; } spin_unlock(&ml403_ac97cr->reg_lock); schedule_timeout_uninterruptible(1); } while (time_after(end_time, jiffies)); #ifdef CODEC_STAT snd_printk(KERN_WARNING SND_ML403_AC97CR_DRIVER ": " "timeout while codec write " "(reg=0x%x, val=0x%x / %d, last STATUS=0x%x, %d) " "(cw=%d, cr=%d)\n", reg, val, val, stat, rafaccess, ml403_ac97cr->ac97_write, ml403_ac97cr->ac97_read); #else snd_printk(KERN_WARNING SND_ML403_AC97CR_DRIVER ": " "timeout while codec write (reg=0x%x, val=0x%x / %d)\n", reg, val, val); #endif #else /* CODEC_WRITE_CHECK_RAF */ #if CODEC_WAIT_AFTER_WRITE > 0 /* officially, in AC97 spec there is no possibility for a AC97 * controller to determine, if write access is done or not - so: How * is Xilinx able to provide a RAF bit for write access? * => very strange, thus just don't check RAF bit (compare with * Xilinx's example app in EDK 8.1i) and wait */ schedule_timeout_uninterruptible(HZ / CODEC_WAIT_AFTER_WRITE); #endif PDEBUG(CODEC_SUCCESS, "codec_write(): (done) " "reg=0x%x, value=%d / 0x%x (no RAF check)\n", reg, val, val); #endif mutex_unlock(&ml403_ac97cr->cdc_mutex); return; } static int snd_ml403_ac97cr_chip_init(struct snd_ml403_ac97cr *ml403_ac97cr) { unsigned long end_time; PDEBUG(INIT_INFO, "chip_init():\n"); end_time = jiffies + HZ / CODEC_TIMEOUT_ON_INIT; do { if (in_be32(CR_REG(ml403_ac97cr, STATUS)) & CR_CODECREADY) { /* clear both hardware FIFOs */ out_be32(CR_REG(ml403_ac97cr, RESETFIFO), CR_RECRESET | CR_PLAYRESET); PDEBUG(INIT_INFO, "chip_init(): (done)\n"); return 0; } schedule_timeout_uninterruptible(1); } while (time_after(end_time, jiffies)); snd_printk(KERN_ERR SND_ML403_AC97CR_DRIVER ": " "timeout while waiting for codec, " "not ready!\n"); return -EBUSY; } static int snd_ml403_ac97cr_free(struct snd_ml403_ac97cr *ml403_ac97cr) { PDEBUG(INIT_INFO, "free():\n"); /* irq release */ if (ml403_ac97cr->irq >= 0) free_irq(ml403_ac97cr->irq, ml403_ac97cr); if (ml403_ac97cr->capture_irq >= 0) free_irq(ml403_ac97cr->capture_irq, ml403_ac97cr); /* give back "port" */ iounmap(ml403_ac97cr->port); kfree(ml403_ac97cr); PDEBUG(INIT_INFO, "free(): (done)\n"); return 0; } static int snd_ml403_ac97cr_dev_free(struct snd_device *snddev) { struct snd_ml403_ac97cr *ml403_ac97cr = snddev->device_data; PDEBUG(INIT_INFO, "dev_free():\n"); return snd_ml403_ac97cr_free(ml403_ac97cr); } static int snd_ml403_ac97cr_create(struct snd_card *card, struct platform_device *pfdev, struct snd_ml403_ac97cr **rml403_ac97cr) { struct snd_ml403_ac97cr *ml403_ac97cr; int err; static struct snd_device_ops ops = { .dev_free = snd_ml403_ac97cr_dev_free, }; struct resource *resource; int irq; *rml403_ac97cr = NULL; ml403_ac97cr = kzalloc(sizeof(*ml403_ac97cr), GFP_KERNEL); if (ml403_ac97cr == NULL) return -ENOMEM; spin_lock_init(&ml403_ac97cr->reg_lock); mutex_init(&ml403_ac97cr->cdc_mutex); ml403_ac97cr->card = card; ml403_ac97cr->pfdev = pfdev; ml403_ac97cr->irq = -1; ml403_ac97cr->enable_irq = 0; ml403_ac97cr->capture_irq = -1; ml403_ac97cr->enable_capture_irq = 0; ml403_ac97cr->port = NULL; ml403_ac97cr->res_port = NULL; PDEBUG(INIT_INFO, "Trying to reserve resources now ...\n"); resource = platform_get_resource(pfdev, IORESOURCE_MEM, 0); /* get "port" */ ml403_ac97cr->port = ioremap_nocache(resource->start, (resource->end) - (resource->start) + 1); if (ml403_ac97cr->port == NULL) { snd_printk(KERN_ERR SND_ML403_AC97CR_DRIVER ": " "unable to remap memory region (%pR)\n", resource); snd_ml403_ac97cr_free(ml403_ac97cr); return -EBUSY; } snd_printk(KERN_INFO SND_ML403_AC97CR_DRIVER ": " "remap controller memory region to " "0x%x done\n", (unsigned int)ml403_ac97cr->port); /* get irq */ irq = platform_get_irq(pfdev, 0); if (request_irq(irq, snd_ml403_ac97cr_irq, 0, dev_name(&pfdev->dev), (void *)ml403_ac97cr)) { snd_printk(KERN_ERR SND_ML403_AC97CR_DRIVER ": " "unable to grab IRQ %d\n", irq); snd_ml403_ac97cr_free(ml403_ac97cr); return -EBUSY; } ml403_ac97cr->irq = irq; snd_printk(KERN_INFO SND_ML403_AC97CR_DRIVER ": " "request (playback) irq %d done\n", ml403_ac97cr->irq); irq = platform_get_irq(pfdev, 1); if (request_irq(irq, snd_ml403_ac97cr_irq, 0, dev_name(&pfdev->dev), (void *)ml403_ac97cr)) { snd_printk(KERN_ERR SND_ML403_AC97CR_DRIVER ": " "unable to grab IRQ %d\n", irq); snd_ml403_ac97cr_free(ml403_ac97cr); return -EBUSY; } ml403_ac97cr->capture_irq = irq; snd_printk(KERN_INFO SND_ML403_AC97CR_DRIVER ": " "request (capture) irq %d done\n", ml403_ac97cr->capture_irq); err = snd_ml403_ac97cr_chip_init(ml403_ac97cr); if (err < 0) { snd_ml403_ac97cr_free(ml403_ac97cr); return err; } err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, ml403_ac97cr, &ops); if (err < 0) { PDEBUG(INIT_FAILURE, "probe(): snd_device_new() failed!\n"); snd_ml403_ac97cr_free(ml403_ac97cr); return err; } *rml403_ac97cr = ml403_ac97cr; return 0; } static void snd_ml403_ac97cr_mixer_free(struct snd_ac97 *ac97) { struct snd_ml403_ac97cr *ml403_ac97cr = ac97->private_data; PDEBUG(INIT_INFO, "mixer_free():\n"); ml403_ac97cr->ac97 = NULL; PDEBUG(INIT_INFO, "mixer_free(): (done)\n"); } static int snd_ml403_ac97cr_mixer(struct snd_ml403_ac97cr *ml403_ac97cr) { struct snd_ac97_bus *bus; struct snd_ac97_template ac97; int err; static struct snd_ac97_bus_ops ops = { .write = snd_ml403_ac97cr_codec_write, .read = snd_ml403_ac97cr_codec_read, }; PDEBUG(INIT_INFO, "mixer():\n"); err = snd_ac97_bus(ml403_ac97cr->card, 0, &ops, NULL, &bus); if (err < 0) return err; memset(&ac97, 0, sizeof(ac97)); ml403_ac97cr->ac97_fake = 1; lm4550_regfile_init(); #ifdef CODEC_STAT ml403_ac97cr->ac97_read = 0; ml403_ac97cr->ac97_write = 0; #endif ac97.private_data = ml403_ac97cr; ac97.private_free = snd_ml403_ac97cr_mixer_free; ac97.scaps = AC97_SCAP_AUDIO | AC97_SCAP_SKIP_MODEM | AC97_SCAP_NO_SPDIF; err = snd_ac97_mixer(bus, &ac97, &ml403_ac97cr->ac97); ml403_ac97cr->ac97_fake = 0; lm4550_regfile_write_values_after_init(ml403_ac97cr->ac97); PDEBUG(INIT_INFO, "mixer(): (done) snd_ac97_mixer()=%d\n", err); return err; } static int snd_ml403_ac97cr_pcm(struct snd_ml403_ac97cr *ml403_ac97cr, int device) { struct snd_pcm *pcm; int err; err = snd_pcm_new(ml403_ac97cr->card, "ML403AC97CR/1", device, 1, 1, &pcm); if (err < 0) return err; snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_ml403_ac97cr_playback_ops); snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_ml403_ac97cr_capture_ops); pcm->private_data = ml403_ac97cr; pcm->info_flags = 0; strcpy(pcm->name, "ML403AC97CR DAC/ADC"); ml403_ac97cr->pcm = pcm; snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_CONTINUOUS, snd_dma_continuous_data(GFP_KERNEL), 64 * 1024, 128 * 1024); return 0; } static int snd_ml403_ac97cr_probe(struct platform_device *pfdev) { struct snd_card *card; struct snd_ml403_ac97cr *ml403_ac97cr = NULL; int err; int dev = pfdev->id; if (dev >= SNDRV_CARDS) return -ENODEV; if (!enable[dev]) return -ENOENT; err = snd_card_new(&pfdev->dev, index[dev], id[dev], THIS_MODULE, 0, &card); if (err < 0) return err; err = snd_ml403_ac97cr_create(card, pfdev, &ml403_ac97cr); if (err < 0) { PDEBUG(INIT_FAILURE, "probe(): create failed!\n"); snd_card_free(card); return err; } PDEBUG(INIT_INFO, "probe(): create done\n"); card->private_data = ml403_ac97cr; err = snd_ml403_ac97cr_mixer(ml403_ac97cr); if (err < 0) { snd_card_free(card); return err; } PDEBUG(INIT_INFO, "probe(): mixer done\n"); err = snd_ml403_ac97cr_pcm(ml403_ac97cr, 0); if (err < 0) { snd_card_free(card); return err; } PDEBUG(INIT_INFO, "probe(): PCM done\n"); strcpy(card->driver, SND_ML403_AC97CR_DRIVER); strcpy(card->shortname, "ML403 AC97 Controller Reference"); sprintf(card->longname, "%s %s at 0x%lx, irq %i & %i, device %i", card->shortname, card->driver, (unsigned long)ml403_ac97cr->port, ml403_ac97cr->irq, ml403_ac97cr->capture_irq, dev + 1); err = snd_card_register(card); if (err < 0) { snd_card_free(card); return err; } platform_set_drvdata(pfdev, card); PDEBUG(INIT_INFO, "probe(): (done)\n"); return 0; } static int snd_ml403_ac97cr_remove(struct platform_device *pfdev) { snd_card_free(platform_get_drvdata(pfdev)); return 0; } /* work with hotplug and coldplug */ MODULE_ALIAS("platform:" SND_ML403_AC97CR_DRIVER); static struct platform_driver snd_ml403_ac97cr_driver = { .probe = snd_ml403_ac97cr_probe, .remove = snd_ml403_ac97cr_remove, .driver = { .name = SND_ML403_AC97CR_DRIVER, }, }; module_platform_driver(snd_ml403_ac97cr_driver);
{ "pile_set_name": "Github" }
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/geolocation/wifi_data_provider_common_win.h" #include <assert.h> #include <stdint.h> #include "base/strings/utf_string_conversions.h" #include "content/browser/geolocation/wifi_data_provider_common.h" namespace content { bool ConvertToAccessPointData(const NDIS_WLAN_BSSID& data, AccessPointData *access_point_data) { // Currently we get only MAC address, signal strength and SSID. // TODO(steveblock): Work out how to get age, channel and signal-to-noise. DCHECK(access_point_data); access_point_data->mac_address = MacAddressAsString16(data.MacAddress); access_point_data->radio_signal_strength = data.Rssi; // Note that _NDIS_802_11_SSID::Ssid::Ssid is not null-terminated. base::UTF8ToUTF16(reinterpret_cast<const char*>(data.Ssid.Ssid), data.Ssid.SsidLength, &access_point_data->ssid); return true; } int GetDataFromBssIdList(const NDIS_802_11_BSSID_LIST& bss_id_list, int list_size, WifiData::AccessPointDataSet* data) { // Walk through the BSS IDs. int found = 0; const uint8_t* iterator = reinterpret_cast<const uint8_t*>(&bss_id_list.Bssid[0]); const uint8_t* end_of_buffer = reinterpret_cast<const uint8_t*>(&bss_id_list) + list_size; for (int i = 0; i < static_cast<int>(bss_id_list.NumberOfItems); ++i) { const NDIS_WLAN_BSSID *bss_id = reinterpret_cast<const NDIS_WLAN_BSSID*>(iterator); // Check that the length of this BSS ID is reasonable. if (bss_id->Length < sizeof(NDIS_WLAN_BSSID) || iterator + bss_id->Length > end_of_buffer) { break; } AccessPointData access_point_data; if (ConvertToAccessPointData(*bss_id, &access_point_data)) { data->insert(access_point_data); ++found; } // Move to the next BSS ID. iterator += bss_id->Length; } return found; } } // namespace content
{ "pile_set_name": "Github" }
/*************************************************************************** * Copyright (C) 2002~2005 by Yuking * * yuking_net@sohu.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef _PY_MAP_TABLE_H #define _PY_MAP_TABLE_H typedef struct _ConsonantMap { char strPY[5]; char cMap; } ConsonantMap; typedef struct _SyllabaryMap { char strPY[4]; char cMap; } SyllabaryMap; #endif // kate: indent-mode cstyle; space-indent on; indent-width 0;
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class net.sf.mpxj.common.MPPResourceField14 (MPXJ 8.2.0 API)</title> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class net.sf.mpxj.common.MPPResourceField14 (MPXJ 8.2.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../net/sf/mpxj/common/MPPResourceField14.html" title="class in net.sf.mpxj.common">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?net/sf/mpxj/common/class-use/MPPResourceField14.html" target="_top">Frames</a></li> <li><a href="MPPResourceField14.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class net.sf.mpxj.common.MPPResourceField14" class="title">Uses of Class<br>net.sf.mpxj.common.MPPResourceField14</h2> </div> <div class="classUseContainer">No usage of net.sf.mpxj.common.MPPResourceField14</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../net/sf/mpxj/common/MPPResourceField14.html" title="class in net.sf.mpxj.common">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?net/sf/mpxj/common/class-use/MPPResourceField14.html" target="_top">Frames</a></li> <li><a href="MPPResourceField14.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2000&#x2013;2020 <a href="http://mpxj.org">Packwood Software</a>. All rights reserved.</small></p> </body> </html>
{ "pile_set_name": "Github" }
--- BUNDLE_PATH: vendor BUNDLE_DISABLE_SHARED_GEMS: '1'
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- * Scilab ( http://www.scilab.org/ ) - This file is part of Scilab * Copyright (C) 2008 - INRIA * Copyright (C) 2012 - 2016 - Scilab Enterprises * * This file is hereby licensed under the terms of the GNU GPL v2.0, * pursuant to article 5.3.4 of the CeCILL v.2.1. * This file was originally licensed under the terms of the CeCILL v2.1, * and continues to be available under such terms. * For more information, see the COPYING file which you should have received * along with this program. * --> <refentry xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svg="http://www.w3.org/2000/svg" xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:db="http://docbook.org/ns/docbook" xmlns:scilab="http://www.scilab.org" xml:lang="ja" xml:id="rcond"> <refnamediv> <refname>rcond</refname> <refpurpose>条件数の逆数</refpurpose> </refnamediv> <refsynopsisdiv> <title>呼び出し手順</title> <synopsis>r = rcond(X)</synopsis> </refsynopsisdiv> <refsection> <title>引数</title> <variablelist> <varlistentry> <term>X</term> <listitem> <para>実数または複素数の正方行列</para> </listitem> </varlistentry> <varlistentry> <term>r</term> <listitem> <para>正の実数</para> </listitem> </varlistentry> </variablelist> </refsection> <refsection> <title>説明</title> <para> <literal>rcond(X)</literal> は,1-ノルムにおける <literal>X</literal>の条件の逆数の推定値です. </para> <para> <literal>X</literal>が健全な場合, <literal>rcond(X)</literal> は 1 に近くなります. そうでない場合, <literal>rcond(X)</literal> は 0に近くなります. </para> <para> <note> <literal>rcond</literal>による1-ノルム逆条件数の推定は, <literal>cond</literal>による2-ノルム条件数の計算よりはるかに高速です. トレードオフとして,<literal>rcond</literal> は若干信頼性が低下する可能性があります. </note> </para> <para> Xの1-ノルムを Lapack/DLANGEで計算, そのLU分解をLapack/DGETRFで計算, 最後に条件をLapack/DGECONで推定します. </para> <para> <literal>rcond([])</literal> yields <literal>%inf</literal>. </para> </refsection> <refsection> <title>例</title> <programlisting role="example"><![CDATA[ A = diag([1:10]); rcond(A) A(1,1) = 0.000001; rcond(A) ]]></programlisting> <para>比較ベンチマーク</para> <programlisting role="example"><![CDATA[ A = ones(1000, 1000); timer(); cond(A); timer() timer(); 1/rcond(A); timer() ]]></programlisting> </refsection> <refsection role="see also"> <title>参照</title> <simplelist type="inline"> <member> <link linkend="svd">svd</link> </member> <member> <link linkend="cond">cond</link> </member> <member> <link linkend="inv">inv</link> </member> </simplelist> </refsection> <refsection role="history"> <title>履歴</title> <revhistory> <revision> <revnumber>6.0.2</revnumber> <revdescription> rcond([]) now yields %inf = 1/cond([]) instead of []. </revdescription> </revision> </revhistory> </refsection> </refentry>
{ "pile_set_name": "Github" }
/** * Copyright 2011 Twitter, Inc. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.pycascading; import java.io.ObjectInputStream; import java.io.Serializable; import org.python.core.Py; import cascading.flow.FlowProcess; import cascading.operation.Function; import cascading.operation.FunctionCall; import cascading.operation.OperationCall; import cascading.tuple.Fields; import cascading.tuple.TupleEntryCollector; /** * Wrapper for a Cascading Function that calls a Python function. * * @author Gabor Szabo */ @SuppressWarnings("rawtypes") public class CascadingFunctionWrapper extends CascadingRecordProducerWrapper implements Function, Serializable { private static final long serialVersionUID = -3512295576396796360L; public CascadingFunctionWrapper() { super(); } public CascadingFunctionWrapper(Fields fieldDeclaration) { super(fieldDeclaration); } public CascadingFunctionWrapper(int numArgs) { super(numArgs); } public CascadingFunctionWrapper(int numArgs, Fields fieldDeclaration) { super(numArgs, fieldDeclaration); } /** * We need to call setupArgs() from here, otherwise CascadingFunctionWrapper * is not initialized yet if we call it from CascadingBaseOperationWrapper. */ private void readObject(ObjectInputStream stream) { setupArgs(); } @Override public void prepare(FlowProcess flowProcess, OperationCall operationCall) { super.prepare(flowProcess, operationCall); } @Override public void operate(FlowProcess flowProcess, FunctionCall functionCall) { Object inputTuple = convertInput(functionCall.getArguments()); TupleEntryCollector outputCollector = functionCall.getOutputCollector(); callArgs[0] = Py.java2py(inputTuple); if (outputMethod == OutputMethod.COLLECTS) { // The Python function collects the output tuples itself into the output // collector callArgs[1] = Py.java2py(outputCollector); callFunction(); } else { // The Python function yields or returns records Object ret = callFunction(); collectOutput(outputCollector, ret); } } }
{ "pile_set_name": "Github" }
#ifndef AFTERBASE_H_HEADER_INCLUDED #define AFTERBASE_H_HEADER_INCLUDED #define HAVE_AFTERBASE_FLAG 0 # include "../asim_afterbase.h" #define R_OK 04 #endif /* AFTERBASE_H_HEADER_INCLUDED */
{ "pile_set_name": "Github" }
#region License /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #endregion using System.Text.Json; namespace Gremlin.Net.Structure.IO.GraphSON { internal class VertexDeserializer : IGraphSONDeserializer { public dynamic Objectify(JsonElement graphsonObject, GraphSONReader reader) { var id = reader.ToObject(graphsonObject.GetProperty("id")); var label = graphsonObject.TryGetProperty("label", out var labelProperty) ? labelProperty.GetString() : Vertex.DefaultLabel; return new Vertex(id, label); } } }
{ "pile_set_name": "Github" }
/** * $Id$ * Copyright (C) 2008 - 2014 Nils Asmussen * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <sys/common.h> #include <sys/driver.h> #include <sys/io.h> #include <sys/thread.h> #include <mutex> #include <stdlib.h> #include <vector> #include "listener.h" Listener *Listener::_inst; bool Listener::add(int client,ev_type type) { if(type != ev_type::TYPE_CREATED && type != ev_type::TYPE_DESTROYED && type != ev_type::TYPE_ACTIVE) return false; std::lock_guard<std::mutex> guard(_mutex); _list.push_back(WinListener(client,type)); return true; } void Listener::notify(const esc::WinMngEvents::Event *ev) { std::lock_guard<std::mutex> guard(_mutex); for(auto l = _list.begin(); l != _list.end(); ++l) { if(l->type == ev->type) send(l->client,MSG_WIN_EVENT,ev,sizeof(*ev)); } } void Listener::remove(int client,ev_type type) { std::lock_guard<std::mutex> guard(_mutex); for(auto l = _list.begin(); l != _list.end(); ++l) { if(l->client == client && l->type == type) { _list.erase(l); break; } } } void Listener::removeAll(int client) { std::lock_guard<std::mutex> guard(_mutex); while(!_list.empty()) { win_iter it = std::find_if(_list.begin(),_list.end(),[client] (const WinListener &l) { return l.client == client; }); if(it == _list.end()) break; _list.erase(it); } }
{ "pile_set_name": "Github" }
(* absyn.sml the signature *) (* $Log: absyn.sml,v $ Revision 1.51 1997/05/01 12:25:23 jont [Bug #30088] Get rid of MLWorks.Option * Revision 1.50 1996/10/28 17:28:04 andreww * [Bug #1708] * changing syntax of datatype replication. * * Revision 1.49 1996/10/04 17:56:20 andreww * [Bug #1592] * threading location argument to local declaration expression * syntax. * / * * Revision 1.48 1996/10/04 10:55:22 matthew * [Bug #1622] * Adding some locations * * Revision 1.47 1996/09/30 12:37:53 matthew * Removing require of module_id * * Revision 1.46 1996/09/18 11:53:39 andreww * [Bug #1577] * Adding production for datatype replication. * * Revision 1.45 1996/03/29 12:09:29 matthew * Adding WHEREsigxp properly * * Revision 1.44 1996/03/26 16:23:48 matthew * Adding explicit tyvars field to VALdec * * Revision 1.43 1996/01/16 12:21:29 daveb * Added location information to SIGNATUREtopdec. * Revision 1.42 1995/12/27 10:39:13 jont Removing Option in favour of MLWorks.Option Revision 1.41 1995/12/05 12:21:16 jont Add functions to check strdecs and strexps for the location of free imperative type variable errors Revision 1.40 1995/11/22 09:09:04 daveb Changed REQUIREtopdec to take a string instead of a module_id. Revision 1.39 1995/09/05 14:13:26 daveb Added types for different lengths of words, ints and reals. Revision 1.38 1995/08/31 13:13:07 jont Add location info to wild pats for use in redundancy warnings Revision 1.37 1995/01/17 12:51:10 matthew Rationalizing debugger Revision 1.36 1994/09/14 11:41:26 matthew Abstraction of debug information Revision 1.35 1994/02/28 05:52:22 nosa Type function, debugger structure, and structure recording for Modules Debugger. Revision 1.34 1993/12/03 16:36:08 nickh Added location information to COERCEexp. Revision 1.33 1993/11/25 09:31:30 matthew Added fixity annotations to APPexps and APPpats Revision 1.32 1993/09/03 10:20:01 nosa Runtime-instance in VALpats and LAYEREDpats and Compilation-instance in VALexps for polymorphic debugger. Revision 1.31 1993/08/12 14:55:33 daveb Require declarations now take moduleids instead of strings. Revision 1.30 1993/08/06 13:13:28 matthew Added location information to matches Revision 1.29 1993/07/09 11:52:53 nosa structure Option. Revision 1.28 1993/07/02 16:03:13 daveb Added field to some topdecs to indicate when signature matching is required to match an exception against a value specification. Revision 1.27 1993/05/20 11:59:22 matthew Added code for abstractions. Revision 1.26 1993/04/06 11:52:45 matthew Added MLVALUEexp. Just used internally for now. Revision 1.25 1993/03/09 11:17:15 matthew > Removed Datatypes substructure and replaced with Ident substructure and Type and Structure types. Revision 1.24 1993/02/16 17:44:10 matthew Added syntax for dynamic and coerce expressions Revision 1.23 1993/02/08 15:36:41 matthew Removed nameset structure and ref nameset from FunBind (which wasn't used) Revision 1.22 1993/01/25 18:28:40 matthew Changed Interface ref to Str ref in sigexps Revision 1.21 1992/12/17 17:00:23 matthew > Changed int and real scons to carry a location around Revision 1.20 1992/12/08 15:15:30 jont Removed a number of duplicated signatures and structures Revision 1.19 1992/10/14 12:06:39 richard Added location information to the `require' topdec. Revision 1.18 1992/10/09 13:38:55 clive Tynames now have a slot recording their definition point Revision 1.17 1992/09/08 15:14:44 matthew Added locations to some datatypes. Revision 1.16 1992/09/04 08:26:08 richard Installed central error reporting mechanism. Revision 1.15 1992/08/14 11:00:14 matthew Really added the function this time. Revision 1.14 1992/08/04 11:42:57 matthew Added Source_marks_to_tuple function Revision 1.13 1992/08/04 11:42:57 davidt Changed cut down signatures to full versions. Revision 1.12 1992/06/29 10:54:24 clive Added a slot to appexp for debugging type information for function call type Revision 1.11 1992/06/15 09:30:45 clive Added debug info to handlers Revision 1.10 1992/06/11 08:24:31 clive Added some maarks for typechecker error messages Revision 1.9 1992/05/19 15:15:09 clive Added marks for better error reporting Revision 1.8 1992/04/13 15:50:14 clive First version of the profiler Revision 1.7 1992/02/04 11:53:10 jont Removed a couple of irrelevant requires Revision 1.6 1991/11/22 17:08:42 jont Removed opens Revision 1.5 91/11/21 15:57:54 jont Added copyright message Revision 1.4 91/06/27 13:39:59 colin added Interface annotation for signature expressions Revision 1.3 91/06/27 09:04:02 nickh Added REQUIREtopdec of string. Revision 1.2 91/06/19 18:38:00 colin Added a type ref to HANDLEexp for ten15 code generator Revision 1.1 91/06/07 10:55:59 colin Initial revision Copyright 2013 Ravenbrook Limited <http://www.ravenbrook.com/>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) require "ident"; require "../typechecker/datatypes"; signature ABSYN = sig structure Set : sig type ''a Set val empty_set : ''a Set end structure Ident : IDENT structure Datatypes : DATATYPES type Type type Tyfun type Instance type DebuggerStr type Structure type RuntimeInfo type InstanceInfo type options (* this is included for Printing datatype replications only *) val print_type: options -> Type -> string val nullType : Type val nullTyfun : Tyfun val nullDebuggerStr : DebuggerStr val nullRuntimeInfo : RuntimeInfo val nullInstanceInfo : InstanceInfo datatype Exp = SCONexp of Ident.SCon * Type ref | VALexp of Ident.LongValId * Type ref * Ident.Location.T * (InstanceInfo * Instance ref option) ref | RECORDexp of (Ident.Lab * Exp) list| LOCALexp of Dec * Exp * Ident.Location.T | APPexp of Exp * Exp * Ident.Location.T * Type ref * bool | TYPEDexp of Exp * Ty * Ident.Location.T | HANDLEexp of Exp * Type ref * (Pat * Exp * Ident.Location.T) list * Ident.Location.T * string | RAISEexp of Exp * Ident.Location.T | FNexp of (Pat * Exp * Ident.Location.T) list * Type ref * string * Ident.Location.T | DYNAMICexp of (Exp * Ident.TyVar Set.Set * (Type * int * Ident.TyVar Set.Set) ref) | COERCEexp of (Exp * Ty * Type ref * Ident.Location.T) | MLVALUEexp of MLWorks.Internal.Value.T and Dec = (* the two lists in VALdec list the bindings before and after the first occurence of rec. tyvarset is used to hold information about tyvars scoped at this particular value declaration (see 4.6 in The Definition *) VALdec of (Pat * Exp * Ident.Location.T) list * (Pat * Exp * Ident.Location.T) list * Ident.TyVar Set.Set * Ident.TyVar list | TYPEdec of (Ident.TyVar list * Ident.TyCon * Ty * Tyfun ref option) list | DATATYPEdec of Ident.Location.T * (Ident.TyVar list * Ident.TyCon * Type ref * Tyfun ref option * ((Ident.ValId * Type ref) * Ty option) list) list | DATATYPErepl of Ident.Location.T * (Ident.TyCon * Ident.LongTyCon) * Datatypes.Valenv option ref| ABSTYPEdec of Ident.Location.T * (Ident.TyVar list * Ident.TyCon * Type ref * Tyfun ref option * ((Ident.ValId * Type ref) * Ty option) list) list * Dec | EXCEPTIONdec of ExBind list| LOCALdec of Dec * Dec | OPENdec of Ident.LongStrId list * Ident.Location.T | SEQUENCEdec of Dec list and ExBind = NEWexbind of ((Ident.ValId * Type ref) * Ty option * Ident.Location.T * string) | OLDexbind of ((Ident.ValId * Type ref) * Ident.LongValId * Ident.Location.T * string) and Pat = WILDpat of Ident.Location.T | SCONpat of Ident.SCon * Type ref | VALpat of (Ident.LongValId * (Type ref * RuntimeInfo ref)) * Ident.Location.T | RECORDpat of (Ident.Lab * Pat) list * bool * Type ref | APPpat of (Ident.LongValId * Type ref) * Pat * Ident.Location.T * bool | TYPEDpat of Pat * Ty * Ident.Location.T | LAYEREDpat of (Ident.ValId * (Type ref * RuntimeInfo ref)) * Pat and Ty = TYVARty of Ident.TyVar | RECORDty of (Ident.Lab * Ty) list | APPty of Ty list * Ident.LongTyCon * Ident.Location.T | FNty of Ty * Ty (* The following datatypes are for the modules syntax classes *) (* APPstrexp, STRUCTUREstrdec, ABSTRACTIONstrdec and FUNBIND each have a bool ref argument, which is for the type checker to mark signature matches that require some extra work in the lambda translator (when EXCONs are matched against value specifications). *) datatype StrExp = NEWstrexp of StrDec | OLDstrexp of Ident.LongStrId * Ident.Location.T * Structure option ref option | APPstrexp of Ident.FunId * StrExp * bool ref * Ident.Location.T * DebuggerStr ref option | CONSTRAINTstrexp of StrExp * SigExp * bool * bool ref * Ident.Location.T | LOCALstrexp of StrDec * StrExp and StrDec = DECstrdec of Dec | STRUCTUREstrdec of (Ident.StrId * (SigExp * bool) option * StrExp * bool ref * Ident.Location.T * DebuggerStr ref option * Structure option ref option) list | ABSTRACTIONstrdec of (Ident.StrId * (SigExp * bool) option * StrExp * bool ref * Ident.Location.T * DebuggerStr ref option * Structure option ref option) list | LOCALstrdec of StrDec * StrDec | SEQUENCEstrdec of StrDec list and SigExp = NEWsigexp of Spec * Structure option ref | OLDsigexp of Ident.SigId * Structure option ref * Ident.Location.T | WHEREsigexp of (SigExp * (Ident.TyVar list * Ident.LongTyCon * Ty * Ident.Location.T) list) and Spec = VALspec of (Ident.ValId * Ty * Ident.TyVar Set.Set) list * Ident.Location.T | TYPEspec of (Ident.TyVar list * Ident.TyCon) list | EQTYPEspec of (Ident.TyVar list * Ident.TyCon) list | DATATYPEspec of (Ident.TyVar list * Ident.TyCon * (Ident.ValId * Ty option * Ident.Location.T) list) list | DATATYPEreplSpec of Ident.Location.T * Ident.TyCon * Ident.LongTyCon * (Ident.ValId * Type option * Ident.Location.T) list option ref | EXCEPTIONspec of (Ident.ValId * Ty option * Ident.Location.T) list | STRUCTUREspec of (Ident.StrId * SigExp) list | SHARINGspec of Spec * (SharEq * Ident.Location.T) list | LOCALspec of Spec * Spec | OPENspec of Ident.LongStrId list * Ident.Location.T | INCLUDEspec of SigExp * Ident.Location.T | SEQUENCEspec of Spec list and SharEq = STRUCTUREshareq of Ident.LongStrId list | TYPEshareq of Ident.LongTyCon list datatype SigBind = SIGBIND of (Ident.SigId * SigExp * Ident.Location.T) list datatype FunBind = FUNBIND of (Ident.FunId * Ident.StrId * SigExp * StrExp * (SigExp * bool) option * string * bool ref * Ident.Location.T * DebuggerStr ref option * Structure option ref option) list datatype TopDec = STRDECtopdec of StrDec * Ident.Location.T | SIGNATUREtopdec of SigBind list * Ident.Location.T | FUNCTORtopdec of FunBind list * Ident.Location.T | REQUIREtopdec of string * Ident.Location.T val empty_tyvarset : Ident.TyVar Set.Set val expansivep : Exp -> bool val has_tyvar : Ty -> bool val check_strexp_for_free_imp : StrExp * Type -> Ident.Location.T option val check_strdec_for_free_imp : StrDec * Type -> Ident.Location.T option end
{ "pile_set_name": "Github" }
import Config from '@cli-engine/config' import cli from 'cli-ux' import * as path from 'path' import { ICommandInfo } from './command' import deps from './deps' import { IPluginModule, IPluginPJSON } from './plugins/plugin' const debug = require('debug')('cli:hooks') export abstract class Hook<T extends keyof IHooks> { constructor(protected config: Config, protected options: IHooks[T] = {}) {} public abstract run(): Promise<void> } export interface IHooks { init: {} update: {} 'plugins:parse': { module: IPluginModule pjson: IPluginPJSON } prerun: { Command: ICommandInfo argv: string[] } } interface IConstructor<T, O> { new (config: Config, options: O): T } type LegacyHook<T extends keyof IHooks> = (config: Config, options: IHooks[T]) => Promise<void> type HookConstructor<T extends keyof IHooks> = IConstructor<Hook<T>, IHooks[T]> export class Hooks { constructor(private config: Config) {} async run<T extends keyof IHooks>(event: T, options: IHooks[T] = {}): Promise<void> { let scripts = this.config.hooks[event] if (!scripts || !this.config.root) return for (let script of scripts) { script = path.join(this.config.root, script) debug(`%s %s`, event, script) let Hook: HookConstructor<T> | LegacyHook<T> try { Hook = deps.util.undefault(require(script)) } catch (err) { cli.warn(err, { context: `hook:${event} loading ${script}` }) continue } if (this.isLegacyHook(Hook)) { await Hook(this.config, options) } else { const hook = new Hook(this.config, options) await hook.run() } } } private isLegacyHook<T extends keyof IHooks>(Hook: HookConstructor<T> | LegacyHook<T>): Hook is LegacyHook<T> { return !Hook.prototype } }
{ "pile_set_name": "Github" }
options: parameters: author: '' catch_exceptions: 'True' category: '[GRC Hier Blocks]' cmake_opt: '' comment: '' copyright: '' description: '' gen_cmake: 'On' gen_linking: dynamic generate_options: qt_gui hier_block_src_path: '.:' id: test_udp_sink6 max_nouts: '0' output_language: python placement: (0,0) qt_qss_theme: '' realtime_scheduling: '' run: 'True' run_command: '{python} -u {filename}' run_options: prompt sizing_mode: fixed thread_safe_setters: '' title: '' states: bus_sink: false bus_source: false bus_structure: null coordinate: [8, 8] rotation: 0 state: enabled blocks: - name: center_freq id: variable parameters: comment: '' value: 1691e6 states: bus_sink: false bus_source: false bus_structure: null coordinate: [216, 28] rotation: 0 state: enabled - name: samp_rate id: variable parameters: comment: '' value: 1e6 states: bus_sink: false bus_source: false bus_structure: null coordinate: [8, 160] rotation: 0 state: enabled - name: analog_sig_source_x_0 id: analog_sig_source_x parameters: affinity: '' alias: '' amp: '1' comment: '' freq: '1000' maxoutbuf: '0' minoutbuf: '0' offset: '0' phase: '0' samp_rate: samp_rate type: complex waveform: analog.GR_COS_WAVE states: bus_sink: false bus_source: false bus_structure: null coordinate: [144, 268] rotation: 0 state: enabled - name: blocks_throttle_0 id: blocks_throttle parameters: affinity: '' alias: '' comment: '' ignoretag: 'True' maxoutbuf: '0' minoutbuf: '0' samples_per_second: samp_rate type: complex vlen: '1' states: bus_sink: false bus_source: false bus_structure: null coordinate: [424, 300] rotation: 0 state: enabled - name: network_udp_sink_0 id: network_udp_sink parameters: addr: ::1 affinity: '' alias: '' comment: '' header: '0' payloadsize: '1472' port: '2001' send_eof: 'False' type: complex states: bus_sink: false bus_source: false bus_structure: null coordinate: [662, 268] rotation: 0 state: true - name: qtgui_freq_sink_x_0 id: qtgui_freq_sink_x parameters: affinity: '' alias: '' alpha1: '1.0' alpha10: '1.0' alpha2: '1.0' alpha3: '1.0' alpha4: '1.0' alpha5: '1.0' alpha6: '1.0' alpha7: '1.0' alpha8: '1.0' alpha9: '1.0' autoscale: 'False' average: '1.0' axislabels: 'True' bw: samp_rate color1: '"blue"' color10: '"dark blue"' color2: '"red"' color3: '"green"' color4: '"black"' color5: '"cyan"' color6: '"magenta"' color7: '"yellow"' color8: '"dark red"' color9: '"dark green"' comment: '' ctrlpanel: 'False' fc: '0' fftsize: '1024' freqhalf: 'True' grid: 'False' gui_hint: '' label: Relative Gain label1: '' label10: '' label2: '' label3: '' label4: '' label5: '' label6: '' label7: '' label8: '' label9: '' legend: 'True' maxoutbuf: '0' minoutbuf: '0' name: '""' nconnections: '1' showports: 'True' tr_chan: '0' tr_level: '0.0' tr_mode: qtgui.TRIG_MODE_FREE tr_tag: '""' type: complex units: dB update_time: '0.10' width1: '1' width10: '1' width2: '1' width3: '1' width4: '1' width5: '1' width6: '1' width7: '1' width8: '1' width9: '1' wintype: firdes.WIN_BLACKMAN_hARRIS ymax: '10' ymin: '-140' states: bus_sink: false bus_source: false bus_structure: null coordinate: [552, 36] rotation: 0 state: enabled connections: - [analog_sig_source_x_0, '0', blocks_throttle_0, '0'] - [blocks_throttle_0, '0', network_udp_sink_0, '0'] - [blocks_throttle_0, '0', qtgui_freq_sink_x_0, '0'] metadata: file_format: 1
{ "pile_set_name": "Github" }
/* * Renjin : JVM-based interpreter for the R language for the statistical analysis * Copyright © 2010-2019 BeDataDriven Groep B.V. and contributors * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, a copy is available at * https://www.gnu.org/licenses/gpl-2.0.txt */ package org.renjin.primitives; import org.renjin.eval.Context; import org.renjin.eval.EvalException; import org.renjin.invoke.annotations.*; import org.renjin.invoke.reflection.converters.*; import org.renjin.primitives.vector.ConvertingDoubleVector; import org.renjin.primitives.vector.ConvertingStringVector; import org.renjin.repackaged.guava.base.Charsets; import org.renjin.sexp.*; import java.lang.invoke.MethodHandle; import java.util.Arrays; import java.util.function.Predicate; /** * Functions which operate on Vectors */ public class Vectors { @Builtin("length<-") public static Vector setLength(Vector source, int length) { if(length < 0) { throw new EvalException("%d : invalid value", length); } if(source.length() == length) { return source; } // Strange but true... // if source is null, then length(source) <- x is null for all x >= 0 if(source == Null.INSTANCE) { return Null.INSTANCE; } Vector.Builder copy = source.newBuilderWithInitialSize(length); for(int i=0;i!=Math.min(length, source.length());++i) { copy.setFrom(i, source, i); } AtomicVector sourceNames = source.getNames(); if(sourceNames != Null.INSTANCE) { StringVector.Builder newNames = new StringVector.Builder(); for (int i = 0; i < length; i++) { if(i < source.length()) { newNames.add(sourceNames.getElementAsString(i)); } else { newNames.add(""); } } copy.setAttribute(Symbols.NAMES, newNames.build()); } return copy.build(); } @Generic @Builtin public static int length(SEXP exp) { if(exp instanceof S4Object && exp.getAttribute(Symbols.DOT_XDATA) instanceof Environment) { return exp.getAttribute(Symbols.DOT_XDATA).length(); } return exp.length(); } public static StringVector asCharacter(@Current Context context, Vector source) { if(source instanceof StringVector) { return (StringVector) source.setAttributes(AttributeMap.EMPTY); } else if (source.length() > 100 || source.isDeferred()) { return new ConvertingStringVector(source); } else { return convertToStringVector(context, new StringVector.Builder(), source); } } private static StringVector convertToStringVector(Context context, StringVector.Builder builder, Vector source) { if(source instanceof ListVector) { for (int i = 0; i != source.length(); ++i) { SEXP value = ((ListVector) source).getElementAsSEXP(i); if(value instanceof AtomicVector && value.length() == 1) { builder.addFrom((AtomicVector)value, 0); } else { builder.add(Deparse.deparseExp(context, value)); } } } else { for (int i = 0; i != source.length(); ++i) { builder.addFrom(source, i); } } return builder.build(); } @Generic @Builtin("as.logical") @NoAttributes public static LogicalVector asLogical(ExternalPtr ptr) { Object instance = ptr.getInstance(); Class clazz = instance.getClass(); if (BooleanConverter.accept(clazz)) { return BooleanConverter.INSTANCE .convertToR((Boolean) instance); } else if (BooleanArrayConverter.accept(clazz)) { return BooleanArrayConverter.INSTANCE .convertToR((Boolean[]) instance); } else { return new LogicalArrayVector(Logical.NA); } } @Generic @Builtin("as.logical") @NoAttributes public static LogicalVector asLogical(Vector vector) { checkForListThatCannotBeCoercedToAtomicVector(vector, "logical"); return (LogicalVector) convertToAtomicVector(new LogicalArrayVector.Builder(), vector); } @Generic @Builtin("as.logical") @NoAttributes public static LogicalVector asLogical() { return LogicalArrayVector.EMPTY; } @Generic @Builtin("as.logical") @NoAttributes public static LogicalVector asLogical(PairList.Node pairlist) { return asLogical(pairlist.toVector()); } @Generic @Builtin("as.integer") @NoAttributes public static IntVector asInteger(ExternalPtr ptr) { Object instance = ptr.getInstance(); Class clazz = instance.getClass(); if (IntegerConverter.accept(clazz)) { return (IntVector) IntegerConverter.INSTANCE .convertToR((Number) instance); } else if (IntegerArrayConverter.accept(clazz)) { return (IntVector) IntegerArrayConverter.INSTANCE .convertToR((Number[]) instance); } else { return IntVector.valueOf(IntVector.NA); } } @Generic @NoAttributes @Builtin("as.integer") public static IntVector asInteger(Vector source) { checkForListThatCannotBeCoercedToAtomicVector(source, "integer"); return (IntVector) convertToAtomicVector(new IntArrayVector.Builder(), source); } @Generic @NoAttributes @Builtin("as.integer") public static IntVector asInteger() { return IntArrayVector.EMPTY; } @Generic @NoAttributes @Builtin("as.integer") public static IntVector asInteger(PairList.Node pairlist) { return asInteger(pairlist.toVector()); } @Generic @NoAttributes @Builtin("as.double") public static DoubleVector asDouble(ExternalPtr ptr) { Object instance = ptr.getInstance(); Class clazz = instance.getClass(); if (DoubleConverter.accept(clazz)) { return (DoubleVector) DoubleConverter.INSTANCE.convertToR(instance); } else if (DoubleArrayConverter.DOUBLE_ARRAY.accept(clazz)) { return DoubleArrayConverter.DOUBLE_ARRAY.convertToR(instance); } else { return new DoubleArrayVector(DoubleVector.NA); } } @Generic @NoAttributes @Builtin("as.double") public static DoubleVector asDouble(Vector source) { checkForListThatCannotBeCoercedToAtomicVector(source, "double"); if(source instanceof DoubleVector) { return (DoubleVector) source.setAttributes(AttributeMap.EMPTY); } else if(source.isDeferred() || source.length() > 100) { return new ConvertingDoubleVector(source); } else { return (DoubleVector) convertToAtomicVector(new DoubleArrayVector.Builder(), source); } } @Generic @NoAttributes @Builtin("as.double") public static DoubleVector asDouble(PairList.Node pairlist) { return asDouble(pairlist.toVector()); } @Generic @NoAttributes @Builtin("as.double") public static DoubleVector asDouble() { return DoubleArrayVector.EMPTY; } @Generic @NoAttributes @Builtin("as.raw") public static RawVector asRaw(Vector source) { /* * Vector iv = (Vector) values; RawVector.Builder b = new * RawVector.Builder(); int value; Raw raw; for (int i = 0; i < * values.length(); i++) { value = iv.getElementAsInt(i); if (value < 0 || * value > 255) { throw new * EvalException("out-of-range values treated as 0 in coercion to raw"); } * raw = new Raw(iv.getElementAsInt(i)); b.add(raw); } return (b.build()); */ checkForListThatCannotBeCoercedToAtomicVector(source, "raw"); return (RawVector) Vectors.convertToAtomicVector(new RawVector.Builder(), source); } @Generic @NoAttributes @Builtin("as.raw") public static RawVector asRaw(PairList.Node source) { return asRaw(source.toVector()); } public static Vector convertToAtomicVector(Vector.Builder builder, Vector source) { if(source instanceof ListVector) { for (int i = 0; i != source.length(); ++i) { SEXP value = ((ListVector) source).getElementAsSEXP(i); if(value instanceof AtomicVector && value.length() == 1) { builder.addFrom(value, 0); } else { builder.addNA(); } } } else { for (int i = 0; i != source.length(); ++i) { builder.addFrom(source, i); } } return builder.build(); } @Generic @NoAttributes @Builtin("as.complex") public static ComplexVector asComplex(Vector vector) { if(vector instanceof DoubleVector) { return doubleToComplex((DoubleVector) vector); } checkForListThatCannotBeCoercedToAtomicVector(vector, ""); return (ComplexVector) convertToAtomicVector(new ComplexArrayVector.Builder(), vector); } @Generic @NoAttributes @Builtin("as.complex") public static ComplexVector asComplex() { return ComplexArrayVector.EMPTY; } @Generic @NoAttributes @Builtin("as.complex") public static ComplexVector asComplex(PairList.Node pairlist) { return asComplex(pairlist.toVector()); } @Generic @Internal("as.vector") public static SEXP asVector(Vector x, String mode) { // Annoyingly, this function behaves a bit erraticaly // When "mode" if(mode.equals("any")) { // if the result is atomic all attributes are removed. if(x instanceof AtomicVector) { return x.setAttributes(AttributeMap.EMPTY); } else { return x; } } Vector.Builder result; if ("character".equals(mode)) { result = new StringVector.Builder(); } else if ("logical".equals(mode)) { result = new LogicalArrayVector.Builder(x.length()); checkForListThatCannotBeCoercedToAtomicVector(x, mode); } else if ("integer".equals(mode)) { result = new IntArrayVector.Builder(x.length()); checkForListThatCannotBeCoercedToAtomicVector(x, mode); } else if ("raw".equals(mode)) { result = new RawVector.Builder(); checkForListThatCannotBeCoercedToAtomicVector(x, mode); } else if ("numeric".equals(mode) || "double".equals(mode)) { result = new DoubleArrayVector.Builder(x.length()); checkForListThatCannotBeCoercedToAtomicVector(x, mode); } else if ("complex".equals(mode)) { // Special case: double -> complex treats NaNs as NA if(x instanceof DoubleVector) { return doubleToComplex((DoubleVector) x); } result = new ComplexArrayVector.Builder(x.length()); checkForListThatCannotBeCoercedToAtomicVector(x, mode); } else if ("list".equals(mode)) { // Special case: preserve names with mode = 'list' result = new ListVector.Builder(); result.setAttribute(Symbols.NAMES, x.getNames()); } else if("expression".equals(mode)) { result = new ExpressionVector.Builder(); // Special case if(x == Null.INSTANCE) { return new ExpressionVector(Null.INSTANCE); } else if(x instanceof ListVector) { // Exception, for list -> expression, copy attributes return new ExpressionVector(((ListVector) x).toArrayUnsafe(), x.getAttributes()); } } else if ("pairlist".equals(mode)) { // a pairlist is actually not a vector, so bail from here // as a special case return asPairList(x); } else if ("symbol".equals(mode)) { // weird but seen in the base package if (x.length() == 0) { throw new EvalException( "invalid type/length (symbol/0) in vector allocation"); } if (x instanceof ListVector) { throw new EvalException("vector of type 'list' cannot be coerced to symbol"); } return Symbol.get(x.getElementAsString(0)); } else { throw new EvalException("invalid 'mode' argument: " + mode); } for (int i = 0; i != x.length(); ++i) { result.setFrom(i, x, i); } return result.build(); } /** * Special handling for double -> complex */ private static ComplexVector doubleToComplex(DoubleVector x) { ComplexArrayVector.Builder result = new ComplexArrayVector.Builder(x.length()); // in this context, NaNs are treated exceptionally as NAs for (int i = 0; i < x.length(); i++) { result.set(i, x.getElementAsDouble(i), 0); } return result.build(); } /** * Checks that {@code x} is not a list, or if it is a list, is soley consists of * atomic vectors of length 1 * @param x * @param mode */ public static void checkForListThatCannotBeCoercedToAtomicVector(Vector x, String mode) { if(x instanceof ListVector) { ListVector list = (ListVector) x; for (int i = 0; i < list.length(); i++) { SEXP element = list.getElementAsSEXP(i); if(element == Null.INSTANCE || element.length() > 1 || !(element instanceof Vector)) { throw new EvalException("(list) object cannot be coerced to type '%s'", mode); } } } } private static PairList asPairList(Vector x) { PairList.Builder builder = new PairList.Builder(); for (int i = 0; i != x.length(); ++i) { builder.add(x.getName(i), x.getElementAsSEXP(i)); } // Attributes are only copied from lists, not atomic vectors // (go figure) if(x instanceof ListVector) { for (Symbol attribute : x.getAttributes().names()) { if (attribute != Symbols.NAMES) { builder.setAttribute(attribute, x.getAttribute(attribute)); } } } return builder.build(); } public static Predicate<SEXP> modePredicate(String mode) { switch (mode) { case "any": return (x -> true); case "function": return (x -> x instanceof Function); case "numeric": return (x -> x instanceof IntVector || x instanceof DoubleVector); case "symbol": case "name": return (x -> x instanceof Symbol); default: return (x -> x.getTypeName().equals(mode)); } } @Internal @NoAttributes public static SEXP vector(String mode, int length) { if ("logical".equals(mode)) { return LogicalArrayVector.unsafe(new int[length]); } else if ("integer".equals(mode)) { return IntArrayVector.unsafe(new int[length]); } else if ("numeric".equals(mode) || "double".equals(mode)) { return DoubleArrayVector.unsafe(new double[length]); } else if ("complex".equals(mode)) { throw new UnsupportedOperationException("implement me!"); } else if ("character".equals(mode)) { String values[] = new String[length]; Arrays.fill(values, ""); return new StringArrayVector(values); } else if ("list".equals(mode)) { SEXP values[] = new SEXP[length]; Arrays.fill(values, Null.INSTANCE); return new ListVector(values); } else if ("pairlist".equals(mode)) { SEXP values[] = new SEXP[length]; Arrays.fill(values, Null.INSTANCE); return PairList.Node.fromArray(values); } else if ("raw".equals(mode)) { byte values[] = new byte[length]; return new RawVector(values); } else if("expression".equals(mode)) { SEXP values[] = new SEXP[length]; Arrays.fill(values, Null.INSTANCE); return new ExpressionVector(values); } else { throw new EvalException(String.format( "vector: cannot make a vector of mode '%s'.", mode)); } } @Internal @NoAttributes public static ComplexVector complex(int lengthOut, AtomicVector realVector, AtomicVector imaginaryVector) { if(realVector.length() > lengthOut) { lengthOut = realVector.length(); } if(imaginaryVector.length() > lengthOut) { lengthOut = imaginaryVector.length(); } ComplexArrayVector.Builder result = new ComplexArrayVector.Builder(0, lengthOut); for(int i=0; i!=lengthOut;++i) { double real = 0; double imaginary = 0; if(realVector.length() > 0) { real = realVector.getElementAsDouble(i % realVector.length()); } if(imaginaryVector.length() > 0) { imaginary = imaginaryVector.getElementAsDouble(i % imaginaryVector.length()); } result.add(ComplexVector.complex(real, imaginary)); } return result.build(); } @Builtin public static ListVector list(@ArgumentList ListVector arguments) { return arguments; } @Internal public static SEXP drop(Vector x) { Vector dim = (Vector) x.getAttribute(Symbols.DIM); if(dim.length() == 0) { return x; } else { Vector dimnames = (Vector) x.getAttribute(Symbols.DIMNAMES); IntArrayVector.Builder newDim = new IntArrayVector.Builder(); ListVector.Builder newDimnames = new ListVector.Builder(); boolean haveDimNames = false; for(int i=0;i!=dim.length();++i) { if(dim.getElementAsInt(i) > 1) { newDim.add(dim.getElementAsInt(i)); if(dimnames != Null.INSTANCE) { Vector dimNameElement = dimnames.getElementAsSEXP(i); if(dimNameElement != Null.INSTANCE) { haveDimNames = true; } newDimnames.add(dimNameElement); } else { newDimnames.add(Null.INSTANCE); } } } AttributeMap.Builder newAttributes = x.getAttributes().copy(); if(newDim.length() == 0 || (newDim.length() == 1 && dim.length() > 1)) { newAttributes.remove(Symbols.DIM); newAttributes.remove(Symbols.DIMNAMES); if(haveDimNames) { newAttributes.setNames(newDimnames.build().getElementAsSEXP(0)); } } else { newAttributes.setDim(newDim.build()); if(haveDimNames) { newAttributes.setDimNames(newDimnames.build()); } else { newAttributes.setDimNames(Null.INSTANCE); } } return x.setAttributes(newAttributes); } } public static AtomicVector toType(AtomicVector x, Vector.Type type) { if(x.getVectorType() == type) { return x; } else if(type == DoubleVector.VECTOR_TYPE) { return asDouble(x); } else if(type == IntVector.VECTOR_TYPE) { return asInteger(x); } else if(type == LogicalVector.VECTOR_TYPE) { return asLogical(x); } else if(type == ComplexVector.VECTOR_TYPE) { return asComplex(x); } else if(type == StringVector.VECTOR_TYPE) { return new ConvertingStringVector(x); } else if(type == RawVector.VECTOR_TYPE) { return asRaw(x); } else { throw new IllegalArgumentException("type: " + type); } } @Generic @NoAttributes @Internal("as.vector") public static SEXP asVector(Symbol x, String mode) { if ("character".equals(mode)) { return StringVector.valueOf(x.getPrintName()); } else if ("list".equals(mode)) { return new ListVector(x); } else if ("expression".equals(mode)) { return new ExpressionVector(x); } else if ("symbol".equals(mode)) { return x; } else { throw new EvalException("'%s' cannot be coerced to vector of type '%s'", x.getTypeName(), mode); } } @Generic @Internal("as.vector") public static SEXP asVector(@Current Context context, ExternalPtr<?> ptr, String mode) { if(mode.equals("character")) { Object instance = ptr.getInstance(); if (StringConverter.accept(instance.getClass())) { return (StringVector) StringConverter.INSTANCE .convertToR((String) instance); } else if (StringArrayConverter.accept(instance.getClass())) { return (StringVector) StringArrayConverter.INSTANCE .convertToR(instance); } else { return StringArrayVector.valueOf(ptr.getInstance().toString()); } } else { throw new EvalException("cannot coerce type '" + ptr.getTypeName() + "' to vector of type 'character'"); } } @Generic @Internal("as.vector") public static SEXP asVector(@Current Context context, PairList x, String mode) { // Exceptionally, as.vector(x, 'pairlist') // preserves *all* attributes if("pairlist".equals(mode) || "any".equals(mode)) { return x; } // When coercing to list, we preserve all attributes if("list".equals(mode)) { return x.toVector(); } // .. When coercing to mode "expression", we just return a new // expression vector with this pairlist as its single element if("expression".equals(mode)) { return new ExpressionVector(x); } Vector.Builder result; if ("character".equals(mode)) { result = new StringVector.Builder(0, x.length()); } else if ("logical".equals(mode)) { result = new LogicalArrayVector.Builder(0, x.length()); } else if ("numeric".equals(mode) || "double".equals(mode)) { result = new DoubleArrayVector.Builder(0, x.length()); } else if ("complex".equals(mode)) { result = new ComplexArrayVector.Builder(0, x.length()); } else if ("integer".equals(mode)) { result = new IntArrayVector.Builder(0, x.length()); } else if ("list".equals(mode)) { result = new ListVector.Builder(); } else if ("raw".equals(mode)) { result = new RawVector.Builder(); } else { throw new EvalException("invalid 'mode' argument"); } for (PairList.Node node : x.nodes()) { if(node.getValue() instanceof AtomicVector && node.getValue() != Null.INSTANCE) { result.add(node.getValue()); } else { if(result instanceof StringArrayVector.Builder) { ((StringVector.Builder) result).add(Deparse.deparseExp(context, node.getValue())); } else { throw new EvalException("'%s' cannot be coerced to type '%s'", x.getTypeName(), mode); } } } return result.build(); } @Internal @NoAttributes public static StringVector rawToChar(RawVector vector, boolean multiple) { byte[] bytes = vector.toByteArray(); if(multiple) { StringVector.Builder result = new StringVector.Builder(0, vector.length()); for(int i=0;i!=vector.length();++i) { result.add(StringVector.valueOf(new String(bytes, i, 1))); } return result.build(); } else { return StringVector.valueOf(new String(bytes)); } } @Internal @NoAttributes public static RawVector rawToBits(RawVector vector) { RawVector.Builder bits = new RawVector.Builder(); for(int i=0;i!=vector.length();++i) { int intValue = vector.getElementAsInt(i); for(int bit=0;bit!=8;++bit) { int mask = 1 << bit; if( (intValue & mask) != 0) { bits.add(1); } else { bits.add(0); } } } return bits.build(); } @Internal @NoAttributes public static RawVector charToRaw(StringVector sv) { // the R lang docs inexplicably say that // this method converts a length-one character vector // to raw bytes 'without taking into account any declared encoding' // (AB) I think this means that we just dump out the // string how ever it was stored internally. In R, the // storage of a string depends on its encoding; in the JVM, // its always UTF-16. // this implementation splits the difference and dumps // out the string as UTF-8. if (sv.length() != 1) { throw new EvalException( "argument should be a character vector of length 1"); } return new RawVector(sv.getElementAsString(0).getBytes(Charsets.UTF_8)); } @Internal public static RawVector rawShift(RawVector rv, int n) { if (n > RawVector.NUM_BITS || n < (-1 * RawVector.NUM_BITS)) { throw new EvalException("argument 'shift' must be a small integer"); } RawVector.Builder b = new RawVector.Builder(); int r; for (int i = 0; i < rv.length(); i++) { if (n >= 0) { r = rv.getElementAsByte(i) << Math.abs(n); } else { r = rv.getElementAsByte(i) >> Math.abs(n); } b.add(r); } return (b.build()); } @Internal public static RawVector intToBits(Vector vector) { RawVector.Builder bits = new RawVector.Builder(); for(int i=0;i!=vector.length();++i) { int intValue = vector.getElementAsInt(i); for(int bit=0;bit!=Integer.SIZE;++bit) { int mask = 1 << bit; if( (intValue & mask) != 0) { bits.add(1); } else { bits.add(0); } } } return bits.build(); } @CompilerSpecialization public static double[] apply(MethodHandle method, double[] xa, double[] ya) throws Throwable { if(xa.length == ya.length) { int length = xa.length; double[] result = new double[length]; for (int i = 0; i < length; i++) { double x = xa[i]; double y = ya[i]; result[i] = (double)method.invokeExact(x, y); } return result; } else { throw new UnsupportedOperationException("TODO"); } } @CompilerSpecialization public static double[] apply(MethodHandle method, double[] xa, double y) throws Throwable { int length = xa.length; double[] result = new double[length]; for (int i = 0; i < length; i++) { double x = xa[i]; result[i] = (double)method.invokeExact(x, y); } return result; } @CompilerSpecialization public static double apply(MethodHandle method, double x, double y) throws Throwable { if(DoubleVector.isNA(x) || DoubleVector.isNA(y)) { return DoubleVector.NA; } else { return (double) method.invokeExact(x, y); } } @CompilerSpecialization public static double applyDD(MethodHandle method, double x) throws Throwable { if(DoubleVector.isNA(x)) { return DoubleVector.NA; } else { return (double) method.invokeExact(x); } } @CompilerSpecialization public static int[] applyBI(MethodHandle method, int[] a) throws Throwable { int n = a.length; int[] result = new int[n]; for (int i = 0; i < n; i++) { int x = a[i]; boolean b = (boolean) method.invoke(x); result[i] = b ? 1 : 0; } return result; } @CompilerSpecialization public static int[] applyBBNA(MethodHandle method, int[] a) throws Throwable { int n = a.length; int[] result = new int[n]; for (int i = 0; i < n; i++) { int x = a[i]; if(x == IntVector.NA) { result[i] = x; } else { boolean b = (boolean) method.invoke(x != 0); result[i] = b ? 1 : 0; } } return result; } @CompilerSpecialization public static int toInt(double x) { if(Double.isNaN(x)) { return IntVector.NA; } else { return (int) x; } } @CompilerSpecialization public static double toDouble(int x) { if(IntVector.isNA(x)) { return DoubleVector.NA; } else { return x; } } @CompilerSpecialization public static int[] toIntArray(int x) { return new int[] { x }; } @CompilerSpecialization public static double[] toDoubleArray(double x) { return new double[] { x }; } }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 74aae26292cbd47db8e70c928b7709a0 timeCreated: 1503311875 licenseType: Pro NativeFormatImporter: mainObjectFileID: 2100000 userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
object WebModule1: TWebModule1 OldCreateOrder = False Actions = < item Name = 'waTime' PathInfo = '/time' OnAction = TimeAction end item Name = 'waDate' PathInfo = '/date' OnAction = DateAction end item Default = True Name = 'waMenu' PathInfo = '/menu' OnAction = MenuAction end item Name = 'waStatus' PathInfo = '/status' OnAction = StatusAction end item Name = 'waTable' PathInfo = '/table' Producer = dsTableProcedure OnAction = TableAction end item Name = 'waRecord' PathInfo = '/record' Producer = dsPageProducer OnAction = RecordAction end> AfterDispatch = WebModuleAfterDispatch Height = 352 Width = 674 object EmployeeConnection: TFDConnection Params.Strings = ( 'ConnectionDef=EMPLOYEE') LoginPrompt = False Left = 50 Top = 24 end object EmployeeTable: TFDQuery IndexFieldNames = 'EMP_NO' Connection = EmployeeConnection SQL.Strings = ( 'SELECT EMP_NO, FIRST_NAME, LAST_NAME, PHONE_EXT, HIRE_DATE, SALA' + 'RY ' 'FROM EMPLOYEE ORDER BY EMP_NO') Left = 50 Top = 72 object EmployeeTableEMP_NO: TSmallintField AutoGenerateValue = arAutoInc FieldName = 'EMP_NO' Origin = 'EMP_NO' ProviderFlags = [pfInUpdate, pfInWhere, pfInKey] end object EmployeeTableFIRST_NAME: TStringField FieldName = 'FIRST_NAME' Origin = 'FIRST_NAME' Required = True Size = 15 end object EmployeeTableLAST_NAME: TStringField FieldName = 'LAST_NAME' Origin = 'LAST_NAME' Required = True end object EmployeeTablePHONE_EXT: TStringField FieldName = 'PHONE_EXT' Origin = 'PHONE_EXT' Size = 4 end object EmployeeTableHIRE_DATE: TSQLTimeStampField AutoGenerateValue = arDefault FieldName = 'HIRE_DATE' Origin = 'HIRE_DATE' end object EmployeeTableSALARY: TBCDField FieldName = 'SALARY' Origin = 'SALARY' Required = True Precision = 18 Size = 2 end end object FDPhysIBDriverLink1: TFDPhysIBDriverLink Left = 160 Top = 24 end object FDGUIxWaitCursor1: TFDGUIxWaitCursor Provider = 'Console' Left = 264 Top = 24 end object pageHead: TPageProducer HTMLDoc.Strings = ( '<HTML><HEAD>' '<TITLE>WebBroker Demo</TITLE>' '</HEAD>' '<BODY>' '<H1>Web Broker Demo</H1>') Left = 408 Top = 16 end object pageFooter: TPageProducer HTMLDoc.Strings = ( '<hr><I>Delphi Academy 2017</I>' '</BODY>' '</HTML>') Left = 408 Top = 72 end object dsTableProcedure: TDataSetTableProducer Columns = < item FieldName = 'EMP_NO' end item FieldName = 'FIRST_NAME' end item FieldName = 'LAST_NAME' end item FieldName = 'PHONE_EXT' end item FieldName = 'HIRE_DATE' end item FieldName = 'SALARY' end> DataSet = EmployeeTable TableAttributes.BgColor = 'White' TableAttributes.Border = 1 TableAttributes.CellSpacing = 0 TableAttributes.CellPadding = 4 OnFormatCell = dsTableProcedureFormatCell Left = 520 Top = 72 end object dsPageProducer: TDataSetPageProducer HTMLDoc.Strings = ( '<H3>Employee: <#LastName></H3>' '<ul>' '<li> Employee ID: <#Emp_No>' '<li> Name: <#First_Name> <#Last_Name>' '<li> Phone: <#Phone_Ext>' '<li> Hired On: <#Hire_Date>' '<li> Salary: <#Salary>' '</ul>') DataSet = EmployeeTable Left = 520 Top = 16 end end
{ "pile_set_name": "Github" }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_METRICS_USER_METRICS_H_ #define BASE_METRICS_USER_METRICS_H_ #include <string> #include "base/base_export.h" #include "base/callback.h" #include "base/metrics/user_metrics_action.h" #include "base/single_thread_task_runner.h" namespace base { // This module provides some helper functions for logging actions tracked by // the user metrics system. // For best practices on deciding when to emit a user action, see // https://chromium.googlesource.com/chromium/src.git/+/HEAD/tools/metrics/actions/README.md // Record that the user performed an action. // This function must be called after the task runner has been set with // SetRecordActionTaskRunner(). // // "Action" here means a user-generated event: // good: "Reload", "CloseTab", and "IMEInvoked" // not good: "SSLDialogShown", "PageLoaded", "DiskFull" // We use this to gather anonymized information about how users are // interacting with the browser. // WARNING: In calls to this function, UserMetricsAction should be followed by a // string literal parameter and not a variable e.g. // RecordAction(UserMetricsAction("my action name")); // This ensures that our processing scripts can associate this action's hash // with its metric name. Therefore, it will be possible to retrieve the metric // name from the hash later on. // // Once a new recorded action is added, run // tools/metrics/actions/extract_actions.py // to add the metric to actions.xml, then update the <owner>s and <description> // sections. Make sure to include the actions.xml file when you upload your code // for review! // // For more complicated situations (like when there are many different // possible actions), see RecordComputedAction(). BASE_EXPORT void RecordAction(const UserMetricsAction& action); // This function has identical input and behavior to RecordAction(), but is // not automatically found by the action-processing scripts. It can be used // when it's a pain to enumerate all possible actions, but if you use this // you need to also update the rules for extracting known actions in // tools/metrics/actions/extract_actions.py. // This function must be called after the task runner has been set with // SetRecordActionTaskRunner(). BASE_EXPORT void RecordComputedAction(const std::string& action); // Called with the action string. using ActionCallback = RepeatingCallback<void(const std::string&)>; // Add/remove action callbacks (see above). // These functions must be called after the task runner has been set with // SetRecordActionTaskRunner(). BASE_EXPORT void AddActionCallback(const ActionCallback& callback); BASE_EXPORT void RemoveActionCallback(const ActionCallback& callback); // Set the task runner on which to record actions. BASE_EXPORT void SetRecordActionTaskRunner( scoped_refptr<SingleThreadTaskRunner> task_runner); } // namespace base #endif // BASE_METRICS_USER_METRICS_H_
{ "pile_set_name": "Github" }
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding: utf-8 """ Kubeflow Pipelines API This file contains REST API specification for Kubeflow Pipelines. The file is autogenerated from the swagger definition. Contact: kubeflow-pipelines@google.com Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import unittest import datetime import kfp_server_api from kfp_server_api.models.api_job import ApiJob # noqa: E501 from kfp_server_api.rest import ApiException class TestApiJob(unittest.TestCase): """ApiJob unit test stubs""" def setUp(self): pass def tearDown(self): pass def make_instance(self, include_optional): """Test ApiJob include_option is a boolean, when False only required params are included, when True both required and optional params are included """ # model = kfp_server_api.models.api_job.ApiJob() # noqa: E501 if include_optional : return ApiJob( id = '0', name = '0', description = '0', pipeline_spec = kfp_server_api.models.api_pipeline_spec.apiPipelineSpec( pipeline_id = '0', pipeline_name = '0', workflow_manifest = '0', pipeline_manifest = '0', parameters = [ kfp_server_api.models.api_parameter.apiParameter( name = '0', value = '0', ) ], ), resource_references = [ kfp_server_api.models.api_resource_reference.apiResourceReference( key = kfp_server_api.models.api_resource_key.apiResourceKey( type = 'UNKNOWN_RESOURCE_TYPE', id = '0', ), name = '0', relationship = 'UNKNOWN_RELATIONSHIP', ) ], service_account = '0', max_concurrency = '0', trigger = kfp_server_api.models.api_trigger.apiTrigger( cron_schedule = kfp_server_api.models.cron_schedule_allow_scheduling_the_job_with_unix_like_cron.CronSchedule allow scheduling the job with unix-like cron( start_time = datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f'), end_time = datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f'), cron = '0', ), periodic_schedule = kfp_server_api.models.periodic_schedule_allow_scheduling_the_job_periodically_with_certain_interval.PeriodicSchedule allow scheduling the job periodically with certain interval( start_time = datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f'), end_time = datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f'), interval_second = '0', ), ), mode = 'UNKNOWN_MODE', created_at = datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f'), updated_at = datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f'), status = '0', error = '0', enabled = True, no_catchup = True ) else : return ApiJob( ) def testApiJob(self): """Test ApiJob""" inst_req_only = self.make_instance(include_optional=False) inst_req_and_optional = self.make_instance(include_optional=True) if __name__ == '__main__': unittest.main()
{ "pile_set_name": "Github" }
/*********************************************************************** * termcap.cpp - Show the used termcap variables * * * * This file is part of the FINAL CUT widget toolkit * * * * Copyright 2017-2020 Markus Gans * * * * FINAL CUT is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation; either version 3 of * * the License, or (at your option) any later version. * * * * FINAL CUT is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this program. If not, see * * <http://www.gnu.org/licenses/>. * ***********************************************************************/ #include <iomanip> #include <iostream> #include <string> #include <final/final.h> namespace fc = finalcut::fc; // Function prototype void tcapBoolean (const std::string&, bool); void tcapNumeric (const std::string&, int); void tcapString (const std::string&, const char[]); void debug (const finalcut::FApplication&); void booleans(); void numeric(); void string(); //---------------------------------------------------------------------- // struct data //---------------------------------------------------------------------- struct Data { struct alignas(alignof(std::string)) TermcapString { const std::string name; const fc::termcaps cap; }; static TermcapString strings[]; }; //---------------------------------------------------------------------- // struct data - string data array //---------------------------------------------------------------------- Data::TermcapString Data::strings[] = { { "t_bell", fc::t_bell }, { "t_erase_chars", fc::t_erase_chars }, { "t_clear_screen", fc::t_clear_screen }, { "t_clr_eos", fc::t_clr_eos }, { "t_clr_eol", fc::t_clr_eol }, { "t_clr_bol", fc::t_clr_bol }, { "t_cursor_home", fc::t_cursor_home }, { "t_cursor_to_ll", fc::t_cursor_to_ll }, { "t_carriage_return", fc::t_carriage_return }, { "t_tab", fc::t_tab }, { "t_back_tab", fc::t_back_tab }, { "t_insert_padding", fc::t_insert_padding }, { "t_insert_character", fc::t_insert_character }, { "t_parm_ich", fc::t_parm_ich }, { "t_repeat_char", fc::t_repeat_char }, { "t_initialize_color", fc::t_initialize_color }, { "t_initialize_pair", fc::t_initialize_pair }, { "t_set_a_foreground", fc::t_set_a_foreground }, { "t_set_a_background", fc::t_set_a_background }, { "t_set_foreground", fc::t_set_foreground }, { "t_set_background", fc::t_set_background }, { "t_set_color_pair", fc::t_set_color_pair }, { "t_orig_pair", fc::t_orig_pair }, { "t_orig_colors", fc::t_orig_colors }, { "t_no_color_video", fc::t_no_color_video }, { "t_cursor_address", fc::t_cursor_address }, { "t_column_address", fc::t_column_address }, { "t_row_address", fc::t_row_address }, { "t_cursor_visible", fc::t_cursor_visible }, { "t_cursor_invisible", fc::t_cursor_invisible }, { "t_cursor_normal", fc::t_cursor_normal }, { "t_cursor_up", fc::t_cursor_up }, { "t_cursor_down", fc::t_cursor_down }, { "t_cursor_left", fc::t_cursor_left }, { "t_cursor_right", fc::t_cursor_right }, { "t_parm_up_cursor", fc::t_parm_up_cursor }, { "t_parm_down_cursor", fc::t_parm_down_cursor }, { "t_parm_left_cursor", fc::t_parm_left_cursor }, { "t_parm_right_cursor", fc::t_parm_right_cursor }, { "t_save_cursor", fc::t_save_cursor }, { "t_restore_cursor", fc::t_restore_cursor }, { "t_scroll_forward", fc::t_scroll_forward }, { "t_scroll_reverse", fc::t_scroll_reverse }, { "t_enter_ca_mode", fc::t_enter_ca_mode }, { "t_exit_ca_mode", fc::t_exit_ca_mode }, { "t_enable_acs", fc::t_enable_acs }, { "t_enter_bold_mode", fc::t_enter_bold_mode }, { "t_exit_bold_mode", fc::t_exit_bold_mode }, { "t_enter_dim_mode", fc::t_enter_dim_mode }, { "t_exit_dim_mode", fc::t_exit_dim_mode }, { "t_enter_italics_mode", fc::t_enter_italics_mode }, { "t_exit_italics_mode", fc::t_exit_italics_mode }, { "t_enter_underline_mode", fc::t_enter_underline_mode }, { "t_exit_underline_mode", fc::t_exit_underline_mode }, { "t_enter_blink_mode", fc::t_enter_blink_mode }, { "t_exit_blink_mode", fc::t_exit_blink_mode }, { "t_enter_reverse_mode", fc::t_enter_reverse_mode }, { "t_exit_reverse_mode", fc::t_exit_reverse_mode }, { "t_enter_standout_mode", fc::t_enter_standout_mode }, { "t_exit_standout_mode", fc::t_exit_standout_mode }, { "t_enter_secure_mode", fc::t_enter_secure_mode }, { "t_exit_secure_mode", fc::t_exit_secure_mode }, { "t_enter_protected_mode", fc::t_enter_protected_mode }, { "t_exit_protected_mode", fc::t_exit_protected_mode }, { "t_enter_crossed_out_mode", fc::t_enter_crossed_out_mode }, { "t_exit_crossed_out_mode", fc::t_exit_crossed_out_mode }, { "t_enter_dbl_underline_mode", fc::t_enter_dbl_underline_mode }, { "t_exit_dbl_underline_mode", fc::t_exit_dbl_underline_mode }, { "t_set_attributes", fc::t_set_attributes }, { "t_exit_attribute_mode", fc::t_exit_attribute_mode }, { "t_enter_alt_charset_mode", fc::t_enter_alt_charset_mode }, { "t_exit_alt_charset_mode", fc::t_exit_alt_charset_mode }, { "t_enter_pc_charset_mode", fc::t_enter_pc_charset_mode }, { "t_exit_pc_charset_mode", fc::t_exit_pc_charset_mode }, { "t_enter_insert_mode", fc::t_enter_insert_mode }, { "t_exit_insert_mode", fc::t_exit_insert_mode }, { "t_enter_am_mode", fc::t_enter_am_mode }, { "t_exit_am_mode", fc::t_exit_am_mode }, { "t_acs_chars", fc::t_acs_chars }, { "t_keypad_xmit", fc::t_keypad_xmit }, { "t_keypad_local", fc::t_keypad_local }, { "t_key_mouse", fc::t_key_mouse } }; //---------------------------------------------------------------------- // Functions //---------------------------------------------------------------------- void tcapBoolean (const std::string& name, bool cap_bool) { std::cout << "FTermcap::" << name << ": "; if ( cap_bool ) std::cout << "true\r\n"; else std::cout << "false\r\n"; } //---------------------------------------------------------------------- void tcapNumeric (const std::string& name, int cap_num) { std::cout << "FTermcap::" << name << ": " << cap_num << "\r\n"; } //---------------------------------------------------------------------- void tcapString (const std::string& name, const char cap_str[]) { std::string sequence{}; std::cout << name << ": "; if ( cap_str == nullptr ) { std::cout << "\r\n"; return; } const uInt len = uInt(std::strlen(cap_str)); for (uInt i{0}; i < len; i++) { const uChar c = uChar(cap_str[i]); if ( c > 127 ) { std::ostringstream o; o << std::oct << int(c); sequence += "\\"; sequence += o.str(); } else if ( c < 32 ) { if ( c == 27 ) sequence += "\\E"; else { sequence += '^'; sequence += char(c + 64); } } else sequence += char(c); } std::cout << sequence << " "; std::cout << "\r\n"; } //---------------------------------------------------------------------- #if DEBUG void debug (const finalcut::FApplication& TermApp) { const auto& fterm = TermApp.getFTerm(); auto& debug_data = fterm.getFTermDebugData(); const finalcut::FString& ab_s = debug_data.getAnswerbackString(); const finalcut::FString& sec_da = debug_data.getSecDAString(); std::cout << "\n.------------------- debug -------------------\r\n"; #if defined(__linux__) std::cout << "| Framebuffer bpp: " << debug_data.getFramebufferBpp() << "\r\n"; #endif std::cout << "| after init_256colorTerminal(): " << debug_data.getTermType_256color() << "\r\n"; std::cout << "| after parseAnswerbackMsg(): " << debug_data.getTermType_Answerback() << "\r\n"; std::cout << "| after parseSecDA(): " << debug_data.getTermType_SecDA() << "\r\n"; if ( ! ab_s.isEmpty() ) tcapString ("| The answerback String", ab_s); if ( ! sec_da.isEmpty() ) tcapString ("| The SecDA String", sec_da); std::cout << "`------------------- debug -------------------\r\n"; } #else void debug (finalcut::FApplication&) { // FINAL CUT was compiled without debug option } #endif //---------------------------------------------------------------------- void booleans() { std::cout << "\r\n[Booleans]\r\n"; tcapBoolean ( "background_color_erase" , finalcut::FTermcap::background_color_erase ); tcapBoolean ( "can_change_color_palette" , finalcut::FTermcap::can_change_color_palette ); tcapBoolean ( "automatic_left_margin" , finalcut::FTermcap::automatic_left_margin ); tcapBoolean ( "automatic_right_margin" , finalcut::FTermcap::automatic_right_margin ); tcapBoolean ( "eat_nl_glitch" , finalcut::FTermcap::eat_nl_glitch ); tcapBoolean ( "has_ansi_escape_sequences" , finalcut::FTermcap::has_ansi_escape_sequences ); tcapBoolean ( "ansi_default_color" , finalcut::FTermcap::ansi_default_color ); tcapBoolean ( "osc_support" , finalcut::FTermcap::osc_support ); tcapBoolean ( "no_utf8_acs_chars" , finalcut::FTermcap::no_utf8_acs_chars ); } //---------------------------------------------------------------------- void numeric() { std::cout << "\r\n[Numeric]\r\n"; tcapNumeric ("max_color" , finalcut::FTermcap::max_color); tcapNumeric ("tabstop" , finalcut::FTermcap::tabstop); tcapNumeric ("attr_without_color" , finalcut::FTermcap::attr_without_color); } //---------------------------------------------------------------------- void string() { std::cout << "\r\n[String]\r\n"; const finalcut::FTermcap::tcap_map (&tcap_strings)[] \ = finalcut::FTermcap::strings; for (const auto& entry : Data::strings) { const std::string name = entry.name; const fc::termcaps cap = entry.cap; tcapString (name, tcap_strings[cap].string); } } //---------------------------------------------------------------------- // main part //---------------------------------------------------------------------- int main (int argc, char* argv[]) { // Disabling the switch to the alternative screen finalcut::FTerm::useAlternateScreen(false); // Disable color palette changes and terminal data requests auto& start_options = finalcut::FStartOptions::getFStartOptions(); start_options.color_change = false; start_options.terminal_data_request = false; // Create the application object as root widget finalcut::FApplication term_app {argc, argv}; // Force terminal initialization without calling show() term_app.initTerminal(); if ( finalcut::FApplication::isQuit() ) return 0; std::cout << "--------\r\nFTermcap\r\n--------\r\n\n"; std::cout << "Terminal: " << finalcut::FTerm::getTermType() << "\r\n"; debug (term_app); booleans(); numeric(); string(); return 0; }
{ "pile_set_name": "Github" }
#!/usr/bin/env ruby # ###################################################################### # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. ###################################################################### # require 'English' original_argv = ARGV.dup argv = [] found_include_option = false while (arg = original_argv.shift) if found_include_option $LOAD_PATH.unshift(arg) found_include_option = false else case arg when "-I", "--include" found_include_option = true when /\A-I/, /\A--include=?/ path = $POSTMATCH $LOAD_PATH.unshift(path) unless path.empty? else argv << arg end end end def extract_email_address(address) if /<(.+?)>/ =~ address $1 else address end end def sendmail(to, from, mail, server=nil, port=nil) server ||= "localhost" from = extract_email_address(from) to = to.collect {|address| extract_email_address(address)} Net::SMTP.start(server, port) do |smtp| smtp.open_message_stream(from, to) do |f| f.print(mail) end end end begin require 'svn/commit-mailer' Svn::Locale.set Svn::CommitMailer.run(argv) rescue Exception => error require 'net/smtp' require 'socket' to = [] subject = "Error" from = "#{ENV['USER']}@#{Socket.gethostname}" server = nil port = nil begin begin Svn::CommitMailer rescue NameError raise OptionParser::ParseError end _, _, _to, options = Svn::CommitMailer.parse(argv) to = [_to] to = options.error_to unless options.error_to.empty? from = options.from || from subject = "#{options.name}: #{subject}" if options.name server = options.server port = options.port rescue OptionParser::MissingArgument argv.delete_if {|arg| $!.args.include?(arg)} retry rescue OptionParser::ParseError if to.empty? _, _, _to, *_ = ARGV.reject {|arg| /^-/.match(arg)} to = [_to] end end detail = <<-EOM #{error.class}: #{error.message} #{error.backtrace.join("\n")} EOM to = to.compact if to.empty? STDERR.puts detail else sendmail(to, from, <<-MAIL, server, port) MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit From: #{from} To: #{to.join(', ')} Subject: #{subject} Date: #{Time.now.rfc2822} #{detail} MAIL end end
{ "pile_set_name": "Github" }
start : right right right right right right right right right right right done
{ "pile_set_name": "Github" }
/* Ion.RangeSlider, Flat UI Skin // css version 1.8.5 // by Denis Ineshin | ionden.com // ===================================================================================================================*/ /* ===================================================================================================================== // Skin details */ .irs-line-mid, .irs-line-left, .irs-line-right, .irs-diapason, .irs-slider { background: url(img/sprite-skin-flat.png) repeat-x; } .irs { height: 40px; } .irs-with-grid { height: 60px; } .irs-line { height: 12px; top: 25px; } .irs-line-left { height: 12px; background-position: 0 -30px; } .irs-line-mid { height: 12px; background-position: 0 0; } .irs-line-right { height: 12px; background-position: 100% -30px; } .irs-diapason { height: 12px; top: 25px; background-position: 0 -60px; } .irs-slider { width: 16px; height: 18px; top: 22px; background-position: 0 -90px; } #irs-active-slider, .irs-slider:hover { background-position: 0 -120px; } .irs-min, .irs-max { color: #999; font-size: 10px; line-height: 1.333; text-shadow: none; top: 0; padding: 1px 3px; background: #e1e4e9; border-radius: 4px; } .irs-from, .irs-to, .irs-single { color: #fff; font-size: 10px; line-height: 1.333; text-shadow: none; padding: 1px 5px; background: #ed5565; border-radius: 4px; } .irs-from:after, .irs-to:after, .irs-single:after { position: absolute; display: block; content: ""; bottom: -6px; left: 50%; width: 0; height: 0; margin-left: -3px; overflow: hidden; border: 3px solid transparent; border-top-color: #ed5565; } .irs-grid-pol { background: #e1e4e9; } .irs-grid-text { color: #999; } .irs-disabled { }
{ "pile_set_name": "Github" }
package types // Seccomp represents the config for a seccomp profile for syscall restriction. type Seccomp struct { DefaultAction Action `json:"defaultAction"` // Architectures is kept to maintain backward compatibility with the old // seccomp profile. Architectures []Arch `json:"architectures,omitempty"` ArchMap []Architecture `json:"archMap,omitempty"` Syscalls []*Syscall `json:"syscalls"` } // Architecture is used to represent a specific architecture // and its sub-architectures type Architecture struct { Arch Arch `json:"architecture"` SubArches []Arch `json:"subArchitectures"` } // Arch used for architectures type Arch string // Additional architectures permitted to be used for system calls // By default only the native architecture of the kernel is permitted const ( ArchX86 Arch = "SCMP_ARCH_X86" ArchX86_64 Arch = "SCMP_ARCH_X86_64" ArchX32 Arch = "SCMP_ARCH_X32" ArchARM Arch = "SCMP_ARCH_ARM" ArchAARCH64 Arch = "SCMP_ARCH_AARCH64" ArchMIPS Arch = "SCMP_ARCH_MIPS" ArchMIPS64 Arch = "SCMP_ARCH_MIPS64" ArchMIPS64N32 Arch = "SCMP_ARCH_MIPS64N32" ArchMIPSEL Arch = "SCMP_ARCH_MIPSEL" ArchMIPSEL64 Arch = "SCMP_ARCH_MIPSEL64" ArchMIPSEL64N32 Arch = "SCMP_ARCH_MIPSEL64N32" ArchPPC Arch = "SCMP_ARCH_PPC" ArchPPC64 Arch = "SCMP_ARCH_PPC64" ArchPPC64LE Arch = "SCMP_ARCH_PPC64LE" ArchS390 Arch = "SCMP_ARCH_S390" ArchS390X Arch = "SCMP_ARCH_S390X" ) // Action taken upon Seccomp rule match type Action string // Define actions for Seccomp rules const ( ActKill Action = "SCMP_ACT_KILL" ActTrap Action = "SCMP_ACT_TRAP" ActErrno Action = "SCMP_ACT_ERRNO" ActTrace Action = "SCMP_ACT_TRACE" ActAllow Action = "SCMP_ACT_ALLOW" ) // Operator used to match syscall arguments in Seccomp type Operator string // Define operators for syscall arguments in Seccomp const ( OpNotEqual Operator = "SCMP_CMP_NE" OpLessThan Operator = "SCMP_CMP_LT" OpLessEqual Operator = "SCMP_CMP_LE" OpEqualTo Operator = "SCMP_CMP_EQ" OpGreaterEqual Operator = "SCMP_CMP_GE" OpGreaterThan Operator = "SCMP_CMP_GT" OpMaskedEqual Operator = "SCMP_CMP_MASKED_EQ" ) // Arg used for matching specific syscall arguments in Seccomp type Arg struct { Index uint `json:"index"` Value uint64 `json:"value"` ValueTwo uint64 `json:"valueTwo"` Op Operator `json:"op"` } // Filter is used to conditionally apply Seccomp rules type Filter struct { Caps []string `json:"caps,omitempty"` Arches []string `json:"arches,omitempty"` } // Syscall is used to match a group of syscalls in Seccomp type Syscall struct { Name string `json:"name,omitempty"` Names []string `json:"names,omitempty"` Action Action `json:"action"` Args []*Arg `json:"args"` Comment string `json:"comment"` Includes Filter `json:"includes"` Excludes Filter `json:"excludes"` }
{ "pile_set_name": "Github" }
/some $pattern \$pattern test [^ g r o # u p $pattern \$pattern ] \Qquoted $pattern \$pattern # comment tab\E \# not comment blah/; / some $pattern test \$pattern [^ g r o # u p $pattern \$pattern ] [some $pattern \$pattern [:alpha:] blah] [some [[:alpha:]] blah] [some [:^alpha:] blah] [some [[:^alpha:]] blah] \Qquoted $pattern \$pattern # comment tab\E # some comment \# not comment blah /x;
{ "pile_set_name": "Github" }
Aaron Aron Ron Ronnie Ronny Abel Abe Abie Abner Ab Abbie Abraham Abe Abie Bram Adam Ad Addie Addy Ade Adrian Ade Alan Allan Allen Al Albert Al Bert Bertie Alexander Al Alex Alec Aleck Lex Sandy Sander Alfred Al Alf Alfie Fred Freddie Freddy Algernon Algie Algy Alger Alonso Alonzo Al Lon Lonnie Lonny Alvin Alwin Alwyn Al Vin Vinny Win Andrew Andy Drew Andre Andres Andreas Andy Anthony Antony Anton Tony Archibald Arch Archie Baldie Arnold Arnie Arthur Art Artie Augustus August Augustine Augie Gus Gussy Gust Gustus Austin Austen Baldwin Baldie Win Barrett Barry Barrie Bartholomew Bart Barty Bartlett Bartley Bat Batty Basil Baz Basie Benedict Ben Bennie Benny Benjamin Ben Bennie Benny Benjy Benjie Bennet Bennett Ben Bennie Benny Bernard Barnard Bernie Berney Barney Barnie Bert Albert Bertram Herbert Hubert Robert Blake Bradford Brad Ford Bradley Brad Brandon Branden Brandy Brenton Brent Bret Brett Brian Bryan Bryant Bruce Bruno Burton Burt Byron Ron Ronnie Ronny Caleb Cal Calvin Cal Vin Vinny Cameron Cam Ron Ronny Carl Karl Carlos Carey Cary Carry Casey Kasey Caspar Casper Cas Cass Cassius Cas Cass Cecil Cis Cedric Ced Rick Ricky Charles Charlie Charley Chuck Chas Chester Chet Christopher Kristopher Kristofer Chris Kris Cris Christy Kit Kester Kristof Toph Topher Christian Chris Christy Kit Clarence Clare Clair Clark Claude Claud Clayton Clay Clement Clem Clifford Cliff Ford Clinton Clint Clyde Craig Curtis Kurtis Curt Kurt Cyrus Cy Dale Daniel Dan Danny Darrell Darrel Darryl Daryl David Dave Davie Davy Dean Deane Dennis Denis Den Denny Derek Derrick Derry Rick Ricky Dexter Dex Dominic Dominick Dom Nick Donald Don Donnie Donny Douglas Doug Duane Dwayne Dustin Dusty Dwight Earl Earle Edgar Ed Eddie Eddy Ned Edward Ed Eddie Eddy Ned Ted Teddy Edwin Ed Eddie Eddy Ned Elbert Bert Bertie Elijah Eli Lige Elliot Elliott El Elmer El Elvin Elwin Elwyn El Vin Win Elwood El Woody Emery Emmery Emory Em Emil Emile Em Emmanuel Emanuel Immanuel Manuel Manny Mannie Eric Erik Erick Rick Ricky Ernest Earnest Ernie Ervin Erwin Irvin Irvine Irving Irwin Erv Vin Win Ethan Eugene Gene Everett Everette Fabian Fabe Fab Felix Ferdinand Ferdie Fred Freddie Fernando Ferdie Fern Floyd Floy Lloyd Francis Frank Frankie Franky Fran Francisco Frank Frankie Franky Fran Franklin Franklyn Frank Frankie Franky Frederick Frederic Fredrick Fredric Fred Freddie Freddy Rick Ricky Fred Freddie Alfred Frederick Winfred Gabriel Gabe Gabby Garrett Garret Gary Garry Geoffrey Jeffrey Jeff George Georgie Geordie Gerald Gerard Gerry Jerry Gilbert Gil Bert Glenn Glen Graham Grant Gregory Gregor Greg Gregg Griffith Griffin Griff Harold Hal Harry Harvey Harve Henry Harry Hank Herbert Herb Bert Bertie Herman Manny Mannie Howard Howie Hubert Hugh Bert Bertie Hugh Hughie Hugo Ian Immanuel Manny Mannie Emmanuel Irvin Irvine Irving Irwin Ervin Isaac Isaak Ike Isidore Isidor Isadore Isador Izzy Jack Jackie Jacky Jacob Jake James Jim Jimmy Jimmie Jamie Jem Jason Jay Jasper Jay Jeffrey Jeffery Geoffrey Jeff Jeremy Jeremiah Jerry Jerome Jerry Jesse Jess Jessie Jessy John Jack Jackie Jacky Johnny Jonathan Jon Jonny Joseph Joe Joey Jo Jos Joshua Josh Julian Julius Jule Jules Justin Karl Carl Keith Kelly Kelley Kelvin Kel Kelly Kenneth Ken Kenny Kevin Kev Kristopher Kris Kit Kester Christopher Lancelot Launcelot Lance Laurence Lawrence Lorence Lorenzo Lauren Loren Larry Lars Laurie Lawrie Lee Leigh Leo Leon Lee Leonard Leo Len Lenny Lennie Leopold Leo Poldie Leroy Lee Roy Leslie Lesley Les Lester Les Lewis Lew Lewie Lincoln Lin Linc Lynn Lloyd Loyd Loyde Floyd Loy Floy Louis Luis Lou Louie Luke Lucas Lynn Malcolm Mal Malc Mac Manuel Manny Mannie Emmanuel Mark Marc Marcus Markus Martin Mart Marty Marvin Mervin Marv Merv Matthew Matt Mat Matty Mattie Maximilian Max Melvin Mel Michael Mike Mickey Milton Milt Mitchell Mitch Morris Maurice Morry Mortimer Mort Morty Moses Mo Mose Moss Nathan Nathaniel Nat Nate Neal Neil Nicholas Nicolas Nick Nicky Norman Norm Oliver Ollie Noll Nollie Nolly Oscar Ossy Oswald Ossy Ozzie Ozzy Patrick Pat Patty Paddy Patsy Paul Pauly Peter Pete Phillip Philip Phil Pip Ralph Rafe Randall Randal Rand Randy Randolph Rand Randy Dolph Raphael Rafael Raff Rafe Raymond Raymund Ray Reginald Reg Reggie Rex Reuben Ruben Rube Ruby Reynold Ray Richard Dick Rick Ricky Rich Richie Rick Ricky Cedric Derek Eric Frederick Richard Roderic Robert Bob Bobbie Bobby Dob Rob Robbie Robby Robin Bert Roderic Roderick Rod Roddy Rick Ricky Rodney Rod Roger Rodger Rodge Roland Rolly Roly Ronald Ron Ronnie Ronny Ron Ronnie Aaron Byron Cameron Ronald Roscoe Ross Rudolph Rudolf Rudy Rolf Dolph Dolf Russell Russel Russ Ryan Samson Sampson Sam Sammy Samuel Sam Sammy Scott Scotty Sean Sebastian Seb Bass Sidney Sydney Sid Syd Silvester Sylvester Syl Vester Simon Solomon Sol Solly Sal Stanley Stan Stephen Steven Steve Stevie Stuart Stewart Stu Stew Terrence Terence Terrance Terry Theodore Ted Teddy Theo Timothy Tim Timmy Thomas Tom Tommy Todd Tracy Tracey Travis Troy Tyler Ty Valentine Val Victor Vic Vick Vincent Vince Vin Vinny Virgil Vergil Virge Vernon Vern Wallace Wally Walter Walt Wally Warren Wayne Wesley Wes William Bill Billy Billie Will Willie Willy Winfred Win Winnie Winny Fred Freddie Freddy Winston Win Winnie Winny Woodrow Wood Woody Zachariah Zacharias Zachary Zack Zacky Zach
{ "pile_set_name": "Github" }
#import "Braintree-Version.h" SpecBegin(BTVersion) it(@"returns the current version", ^{ expect(BRAINTREE_VERSION).to.match(@"\\d+\\.\\d+\\.\\d+"); }); SpecEnd
{ "pile_set_name": "Github" }
package main import ( "bufio" "log" "os" ) func main() { // Create a new string s s := "Hello, World" // Create a new buffered writer to write to os.Stdout w := bufio.NewWriter(os.Stdout) // Use w.WriteByte to write a single byte into w's buffer // // WriteByte writes a single byte. if err := w.WriteByte([]byte(s)[0]); err != nil { log.Fatalln(err) } // Flush w to actually write w's contents to os.Stdout if err := w.Flush(); err != nil { log.Fatalln(err) } }
{ "pile_set_name": "Github" }
{# Ivan Tcholakov <ivantcholakov@gmail.com>, 2014-2016 The MIT License, http://opensource.org/licenses/MIT #} <h4>PHP Implementation Tests</h4> <table class="ui compact celled table" style="table-layout: fixed; word-wrap: break-word;"> <tbody> <tr> <td style="width: 50%;"><pre><code>$my_random_boolean = Random::boolean() ? 1 : 0;</code></pre></td> <td>{{ my_random_boolean }}</td> </tr> <tr> <td><pre><code>$result_true = 0; $result_false = 0; for ($i = 1; $i <= 100; $i++) { if (Random::boolean()) { $result_true++; } else { $result_false++; } } </code></pre></td> <td>{{ 'result_true: ' ~ result_true ~ '; result_false: ' ~ result_false }}</td> </tr> <tr> <td><pre><code>$my_random_bytes = bin2hex(Random::bytes(10));</code></pre></td> <td>{{ my_random_bytes }}</td> </tr> <tr> <td><pre><code>$my_random_float = Random::float();</code></pre></td> <td>{{ my_random_float }}</td> </tr> <tr> <td><pre><code>$my_random_integer = Random::int(0, PHP_INT_MAX);</code></pre></td> <td>{{ my_random_integer }}</td> </tr> <tr> <td><pre><code>$my_random_integer_2 = Random::int(1, 100);</code></pre></td> <td>{{ my_random_integer_2 }}</td> </tr> <tr> <td><pre><code>$my_random_string = Random::string(20);</code></pre></td> <td>{{ my_random_string }}</td> </tr> <tr> <td><pre><code>$my_random_string_2 = Random::string(20, "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~");</code></pre></td> <td>{{ my_random_string_2 }}</td> </tr> </tbody> </table>
{ "pile_set_name": "Github" }
cmd_Release/obj.target/profiler/src/profiler.o := c++ '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/Users/wavded/.node-gyp/0.10.24/src -I/Users/wavded/.node-gyp/0.10.24/deps/uv/include -I/Users/wavded/.node-gyp/0.10.24/deps/v8/include -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-rtti -fno-exceptions -fno-threadsafe-statics -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/profiler/src/profiler.o.d.raw -c -o Release/obj.target/profiler/src/profiler.o ../src/profiler.cc Release/obj.target/profiler/src/profiler.o: ../src/profiler.cc \ ../src/heap_profiler.h \ /Users/wavded/.node-gyp/0.10.24/deps/v8/include/v8-profiler.h \ /Users/wavded/.node-gyp/0.10.24/deps/v8/include/v8.h \ /Users/wavded/.node-gyp/0.10.24/deps/v8/include/v8stdint.h \ /Users/wavded/.node-gyp/0.10.24/src/node.h \ /Users/wavded/.node-gyp/0.10.24/deps/uv/include/uv.h \ /Users/wavded/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-unix.h \ /Users/wavded/.node-gyp/0.10.24/deps/uv/include/uv-private/ngx-queue.h \ /Users/wavded/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-darwin.h \ /Users/wavded/.node-gyp/0.10.24/src/node_object_wrap.h \ ../src/cpu_profiler.h ../src/profiler.cc: ../src/heap_profiler.h: /Users/wavded/.node-gyp/0.10.24/deps/v8/include/v8-profiler.h: /Users/wavded/.node-gyp/0.10.24/deps/v8/include/v8.h: /Users/wavded/.node-gyp/0.10.24/deps/v8/include/v8stdint.h: /Users/wavded/.node-gyp/0.10.24/src/node.h: /Users/wavded/.node-gyp/0.10.24/deps/uv/include/uv.h: /Users/wavded/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-unix.h: /Users/wavded/.node-gyp/0.10.24/deps/uv/include/uv-private/ngx-queue.h: /Users/wavded/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-darwin.h: /Users/wavded/.node-gyp/0.10.24/src/node_object_wrap.h: ../src/cpu_profiler.h:
{ "pile_set_name": "Github" }
/* * Copyright 2020 Precog Data * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package quasar.api.resource import slamdata.Predef.String import scalaz.{Order, Show} import scalaz.std.string._ final case class ResourceName(value: String) extends scala.AnyVal object ResourceName extends ResourceNameInstances sealed abstract class ResourceNameInstances { implicit val order: Order[ResourceName] = Order.orderBy(_.value) implicit val show: Show[ResourceName] = Show.shows(_.value) }
{ "pile_set_name": "Github" }
// Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved. // Released under the terms of the CPL Common Public License version 1.0. package fitnesse.slim; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import fitnesse.slim.test.TestSlim; import fitnesse.slim.test.Zork; public class SlimMethodInvocationTest extends SlimMethodInvocationTestBase { @Override protected String getTestClassName() { return "fitnesse.slim.test.TestSlim"; } @Before @Override public void setUp() throws Exception { caller = new StatementExecutor(); caller.create("testSlim", getTestClassName(), new Object[0]); testSlim = (TestSlim) caller.getInstance("testSlim"); } @Test public void passAndReturnOneZorkWithPropertyEditor() throws Exception { Object retval = caller.call("testSlim", "oneZork", "zork_42"); assertEquals(new Zork(42), testSlim.getZork()); assertEquals("zork_42", retval); } }
{ "pile_set_name": "Github" }
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package java.io; /** * A character encoding is not supported - <a * href="http://java.sun.com/javase/6/docs/api/java/io/UnsupportedEncodingException.html">[Sun's * docs]</a>. */ public class UnsupportedEncodingException extends IOException { public UnsupportedEncodingException() { } public UnsupportedEncodingException(String msg) { super(msg); } }
{ "pile_set_name": "Github" }
// // ControlProperty+Driver.swift // RxCocoa // // Created by Krunoslav Zaher on 9/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift extension ControlProperty { /// Converts `ControlProperty` to `Driver` trait. /// /// `ControlProperty` already can't fail, so no special case needs to be handled. public func asDriver() -> Driver<E> { return self.asDriver { _ -> Driver<E> in #if DEBUG rxFatalError("Somehow driver received error from a source that shouldn't fail.") #else return Driver.empty() #endif } } }
{ "pile_set_name": "Github" }
package(default_visibility = ["//visibility:public"]) load( "@io_bazel_rules_go//go:def.bzl", "go_library", ) go_library( name = "go_default_library", srcs = [ "well_known_annotations.go", "well_known_annotations_windows.go", "well_known_labels.go", ], importpath = "k8s.io/kubernetes/pkg/kubelet/apis", deps = [ "//staging/src/k8s.io/api/core/v1:go_default_library", "//staging/src/k8s.io/apimachinery/pkg/util/sets:go_default_library", ] + select({ "@io_bazel_rules_go//go/platform:windows": [ "//pkg/features:go_default_library", "//staging/src/k8s.io/apiserver/pkg/util/feature:go_default_library", ], "//conditions:default": [], }), ) filegroup( name = "package-srcs", srcs = glob(["**"]), tags = ["automanaged"], visibility = ["//visibility:private"], ) filegroup( name = "all-srcs", srcs = [ ":package-srcs", "//pkg/kubelet/apis/config:all-srcs", "//pkg/kubelet/apis/podresources:all-srcs", "//pkg/kubelet/apis/resourcemetrics/v1alpha1:all-srcs", "//pkg/kubelet/apis/stats/v1alpha1:all-srcs", ], tags = ["automanaged"], )
{ "pile_set_name": "Github" }
leveldb File format =================== <beginning_of_file> [data block 1] [data block 2] ... [data block N] [meta block 1] ... [meta block K] [metaindex block] [index block] [Footer] (fixed size; starts at file_size - sizeof(Footer)) <end_of_file> The file contains internal pointers. Each such pointer is called a BlockHandle and contains the following information: offset: varint64 size: varint64 See [varints](https://developers.google.com/protocol-buffers/docs/encoding#varints) for an explanation of varint64 format. 1. The sequence of key/value pairs in the file are stored in sorted order and partitioned into a sequence of data blocks. These blocks come one after another at the beginning of the file. Each data block is formatted according to the code in `block_builder.cc`, and then optionally compressed. 2. After the data blocks we store a bunch of meta blocks. The supported meta block types are described below. More meta block types may be added in the future. Each meta block is again formatted using `block_builder.cc` and then optionally compressed. 3. A "metaindex" block. It contains one entry for every other meta block where the key is the name of the meta block and the value is a BlockHandle pointing to that meta block. 4. An "index" block. This block contains one entry per data block, where the key is a string >= last key in that data block and before the first key in the successive data block. The value is the BlockHandle for the data block. 5. At the very end of the file is a fixed length footer that contains the BlockHandle of the metaindex and index blocks as well as a magic number. metaindex_handle: char[p]; // Block handle for metaindex index_handle: char[q]; // Block handle for index padding: char[40-p-q];// zeroed bytes to make fixed length // (40==2*BlockHandle::kMaxEncodedLength) magic: fixed64; // == 0xdb4775248b80fb57 (little-endian) ## "filter" Meta Block If a `FilterPolicy` was specified when the database was opened, a filter block is stored in each table. The "metaindex" block contains an entry that maps from `filter.<N>` to the BlockHandle for the filter block where `<N>` is the string returned by the filter policy's `Name()` method. The filter block stores a sequence of filters, where filter i contains the output of `FilterPolicy::CreateFilter()` on all keys that are stored in a block whose file offset falls within the range [ i*base ... (i+1)*base-1 ] Currently, "base" is 2KB. So for example, if blocks X and Y start in the range `[ 0KB .. 2KB-1 ]`, all of the keys in X and Y will be converted to a filter by calling `FilterPolicy::CreateFilter()`, and the resulting filter will be stored as the first filter in the filter block. The filter block is formatted as follows: [filter 0] [filter 1] [filter 2] ... [filter N-1] [offset of filter 0] : 4 bytes [offset of filter 1] : 4 bytes [offset of filter 2] : 4 bytes ... [offset of filter N-1] : 4 bytes [offset of beginning of offset array] : 4 bytes lg(base) : 1 byte The offset array at the end of the filter block allows efficient mapping from a data block offset to the corresponding filter. ## "stats" Meta Block This meta block contains a bunch of stats. The key is the name of the statistic. The value contains the statistic. TODO(postrelease): record following stats. data size index size key size (uncompressed) value size (uncompressed) number of entries number of data blocks
{ "pile_set_name": "Github" }
'''OpenGL extension EXT.shader_implicit_conversions This module customises the behaviour of the OpenGL.raw.GLES2.EXT.shader_implicit_conversions to provide a more Python-friendly API Overview (from the spec) This extension provides support for implicitly converting signed integer types to unsigned types, as well as more general implicit conversion and function overloading infrastructure to support new data types introduced by other extensions. The official definition of this extension is available here: http://www.opengl.org/registry/specs/EXT/shader_implicit_conversions.txt ''' from OpenGL import platform, constant, arrays from OpenGL import extensions, wrapper import ctypes from OpenGL.raw.GLES2 import _types, _glgets from OpenGL.raw.GLES2.EXT.shader_implicit_conversions import * from OpenGL.raw.GLES2.EXT.shader_implicit_conversions import _EXTENSION_NAME def glInitShaderImplicitConversionsEXT(): '''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME ) ### END AUTOGENERATED SECTION
{ "pile_set_name": "Github" }
using System; using NetOffice; using NetOffice.Attributes; namespace NetOffice.MSComctlLibApi.Enums { /// <summary> /// SupportByVersion MSComctlLib 6 /// </summary> [SupportByVersion("MSComctlLib", 6)] [EntityType(EntityType.IsEnum)] public enum ScrollingConstants { /// <summary> /// SupportByVersion MSComctlLib 6 /// </summary> /// <remarks>0</remarks> [SupportByVersion("MSComctlLib", 6)] ccScrollingStandard = 0, /// <summary> /// SupportByVersion MSComctlLib 6 /// </summary> /// <remarks>1</remarks> [SupportByVersion("MSComctlLib", 6)] ccScrollingSmooth = 1 } }
{ "pile_set_name": "Github" }
// Copyright 2017 The Closure Rules Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.bazel.rules.closure.worker.testing; import io.bazel.rules.closure.worker.Annotations.Action; import io.bazel.rules.closure.worker.ErrorReporter; import io.bazel.rules.closure.worker.Program; import java.util.concurrent.atomic.AtomicBoolean; import javax.inject.Inject; /** Wrapper around a program that returns {@link ProgramResult} afterwards. */ public final class ProgramRunner<T extends Program> { private final Program delegate; private final AtomicBoolean failed; private final ErrorReporter reporter; @Inject ProgramRunner(T delegate, ErrorReporter reporter, @Action AtomicBoolean failed) { this.delegate = delegate; this.reporter = reporter; this.failed = failed; } /** Runs program and returns result of invocation. */ public ProgramResult run() throws Exception { delegate.run(); return new AutoValue_ProgramResult(reporter.getErrors(), reporter.getWarnings(), failed.get()); } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Licensed to the Apache Software Foundation (ASF) under one or more ~ contributor license agreements. See the NOTICE file distributed with ~ this work for additional information regarding copyright ownership. ~ The ASF licenses this file to You under the Apache License, Version 2.0 ~ (the "License"); you may not use this file except in compliance with ~ the License. You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. ~ --> <archetype-descriptor xsi:schemaLocation="http://maven.apache.org/plugins/maven-archetype-plugin/archetype-descriptor/1.0.0 http://maven.apache.org/xsd/archetype-descriptor-1.0.0.xsd" xmlns="http://maven.apache.org/plugins/maven-archetype-plugin/archetype-descriptor/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="archetype"> <requiredProperties> <requiredProperty key="groupId"> <defaultValue>org.apache.skywalking.apm.testcase</defaultValue> </requiredProperty> <requiredProperty key="artifactId"> <defaultValue>${scenario_name}</defaultValue> </requiredProperty> <requiredProperty key="version"> <defaultValue>1.0.0</defaultValue> </requiredProperty> <requiredProperty key="package"> <defaultValue>org.apache.skywalking.apm.testcase.${scenario_name}</defaultValue> </requiredProperty> <requiredProperty key="scenario_name"/> <requiredProperty key="scenario_case"> <defaultValue>${scenario_name}</defaultValue> </requiredProperty> </requiredProperties> <fileSets> <fileSet filtered="true" packaged="false" encoding="utf-8"> <directory/> <includes> <include>configuration.yml</include> <include>support-version.list</include> <include>bin/startup.sh</include> </includes> </fileSet> <fileSet filtered="true" packaged="false"> <directory>config</directory> </fileSet> <fileSet filtered="true" packaged="false"> <directory>src/main/assembly</directory> </fileSet> <fileSet filtered="true" packaged="true"> <directory>src/main/java</directory> </fileSet> <fileSet filtered="true" packaged="false"> <directory>src/main/resources</directory> </fileSet> </fileSets> </archetype-descriptor>
{ "pile_set_name": "Github" }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. /** * \class document::StructDataType * \ingroup datatype * * \brief A data type describing what can be contained in a struct field value. * * Describes what can be stored in a struct. */ #pragma once #include <vespa/document/datatype/structureddatatype.h> #include <vespa/vespalib/stllike/hash_map.h> #include <vespa/vespalib/util/compressionconfig.h> #include <memory> namespace document { class StructDataType final : public StructuredDataType { public: using UP = std::unique_ptr<StructDataType>; using SP = std::shared_ptr<StructDataType>; using CompressionConfig = vespalib::compression::CompressionConfig; StructDataType(); StructDataType(vespalib::stringref name); StructDataType(vespalib::stringref name, int32_t id); ~StructDataType(); /** * @throws vespalib::IllegalArgumentException if field conflicts with * already existing field. */ void addField(const Field& field); /** * Similar to addField(field), but does not throw exceptions on errors. * Fields that can be added are, and the other ones are skipped. Skipped * fields will logs a warning informing about the conflict. * * This is typically called from DocumentType::inherit() to add the fields * that does not conflict with existing fields. */ void addInheritedField(const Field& field); // Implementation of StructuredDataType std::unique_ptr<FieldValue> createFieldValue() const override; void print(std::ostream&, bool verbose, const std::string& indent) const override; uint32_t getFieldCount() const override { return _idFieldMap.size(); } const Field& getField(vespalib::stringref name) const override; /** * Retrieves a field based on its ID. To determine which ID to use, we also * need the document serialization version. */ const Field& getField(int32_t fieldId) const override; bool hasField(vespalib::stringref name) const override; bool hasField(int32_t fieldId) const override; bool hasField(const Field& f) const { return hasField(f.getId()); } Field::Set getFieldSet() const override; StructDataType* clone() const override; void setCompressionConfig(const CompressionConfig& cfg) { _compressionConfig = cfg; }; const CompressionConfig& getCompressionConfig() const { return _compressionConfig; } DECLARE_IDENTIFIABLE(StructDataType); private: using StringFieldMap = vespalib::hash_map<vespalib::string, Field::SP>; using IntFieldMap = vespalib::hash_map<int32_t, Field::SP>; StringFieldMap _nameFieldMap; IntFieldMap _idFieldMap; CompressionConfig _compressionConfig; /** @return "" if not conflicting. Error message otherwise. */ vespalib::string containsConflictingField(const Field& field) const; }; }
{ "pile_set_name": "Github" }
qbs *_FUNC_EVALUATETOTYP_STRING_EVALUATETOTYP=NULL; if (!_FUNC_EVALUATETOTYP_STRING_EVALUATETOTYP)_FUNC_EVALUATETOTYP_STRING_EVALUATETOTYP=qbs_new(0,0); qbs*oldstr2502=NULL; if(_FUNC_EVALUATETOTYP_STRING_A2->tmp||_FUNC_EVALUATETOTYP_STRING_A2->fixed||_FUNC_EVALUATETOTYP_STRING_A2->readonly){ oldstr2502=_FUNC_EVALUATETOTYP_STRING_A2; if (oldstr2502->cmem_descriptor){ _FUNC_EVALUATETOTYP_STRING_A2=qbs_new_cmem(oldstr2502->len,0); }else{ _FUNC_EVALUATETOTYP_STRING_A2=qbs_new(oldstr2502->len,0); } memcpy(_FUNC_EVALUATETOTYP_STRING_A2->chr,oldstr2502->chr,oldstr2502->len); } qbs *_FUNC_EVALUATETOTYP_STRING_A=NULL; if (!_FUNC_EVALUATETOTYP_STRING_A)_FUNC_EVALUATETOTYP_STRING_A=qbs_new(0,0); qbs *_FUNC_EVALUATETOTYP_STRING_E=NULL; if (!_FUNC_EVALUATETOTYP_STRING_E)_FUNC_EVALUATETOTYP_STRING_E=qbs_new(0,0); int32 *_FUNC_EVALUATETOTYP_LONG_SOURCETYP=NULL; if(_FUNC_EVALUATETOTYP_LONG_SOURCETYP==NULL){ _FUNC_EVALUATETOTYP_LONG_SOURCETYP=(int32*)mem_static_malloc(4); *_FUNC_EVALUATETOTYP_LONG_SOURCETYP=0; } int32 *_FUNC_EVALUATETOTYP_LONG_IDNUMBER=NULL; if(_FUNC_EVALUATETOTYP_LONG_IDNUMBER==NULL){ _FUNC_EVALUATETOTYP_LONG_IDNUMBER=(int32*)mem_static_malloc(4); *_FUNC_EVALUATETOTYP_LONG_IDNUMBER=0; } int32 *_FUNC_EVALUATETOTYP_LONG_I=NULL; if(_FUNC_EVALUATETOTYP_LONG_I==NULL){ _FUNC_EVALUATETOTYP_LONG_I=(int32*)mem_static_malloc(4); *_FUNC_EVALUATETOTYP_LONG_I=0; } byte_element_struct *byte_element_2503=NULL; if (!byte_element_2503){ if ((mem_static_pointer+=12)<mem_static_limit) byte_element_2503=(byte_element_struct*)(mem_static_pointer-12); else byte_element_2503=(byte_element_struct*)mem_static_malloc(12); } int32 *_FUNC_EVALUATETOTYP_LONG_U=NULL; if(_FUNC_EVALUATETOTYP_LONG_U==NULL){ _FUNC_EVALUATETOTYP_LONG_U=(int32*)mem_static_malloc(4); *_FUNC_EVALUATETOTYP_LONG_U=0; } byte_element_struct *byte_element_2504=NULL; if (!byte_element_2504){ if ((mem_static_pointer+=12)<mem_static_limit) byte_element_2504=(byte_element_struct*)(mem_static_pointer-12); else byte_element_2504=(byte_element_struct*)mem_static_malloc(12); } byte_element_struct *byte_element_2505=NULL; if (!byte_element_2505){ if ((mem_static_pointer+=12)<mem_static_limit) byte_element_2505=(byte_element_struct*)(mem_static_pointer-12); else byte_element_2505=(byte_element_struct*)mem_static_malloc(12); } qbs *_FUNC_EVALUATETOTYP_STRING_O=NULL; if (!_FUNC_EVALUATETOTYP_STRING_O)_FUNC_EVALUATETOTYP_STRING_O=qbs_new(0,0); qbs *_FUNC_EVALUATETOTYP_STRING_N=NULL; if (!_FUNC_EVALUATETOTYP_STRING_N)_FUNC_EVALUATETOTYP_STRING_N=qbs_new(0,0); qbs *_FUNC_EVALUATETOTYP_STRING_DST=NULL; if (!_FUNC_EVALUATETOTYP_STRING_DST)_FUNC_EVALUATETOTYP_STRING_DST=qbs_new(0,0); qbs *_FUNC_EVALUATETOTYP_STRING_BYTES=NULL; if (!_FUNC_EVALUATETOTYP_STRING_BYTES)_FUNC_EVALUATETOTYP_STRING_BYTES=qbs_new(0,0); int32 pass2506; int32 pass2507; int32 pass2508; int32 pass2509; int32 pass2510; int32 pass2511; int32 pass2512; int32 pass2513; int32 pass2514; int32 *_FUNC_EVALUATETOTYP_LONG_SIZE=NULL; if(_FUNC_EVALUATETOTYP_LONG_SIZE==NULL){ _FUNC_EVALUATETOTYP_LONG_SIZE=(int32*)mem_static_malloc(4); *_FUNC_EVALUATETOTYP_LONG_SIZE=0; } byte_element_struct *byte_element_2515=NULL; if (!byte_element_2515){ if ((mem_static_pointer+=12)<mem_static_limit) byte_element_2515=(byte_element_struct*)(mem_static_pointer-12); else byte_element_2515=(byte_element_struct*)mem_static_malloc(12); } byte_element_struct *byte_element_2516=NULL; if (!byte_element_2516){ if ((mem_static_pointer+=12)<mem_static_limit) byte_element_2516=(byte_element_struct*)(mem_static_pointer-12); else byte_element_2516=(byte_element_struct*)mem_static_malloc(12); } byte_element_struct *byte_element_2517=NULL; if (!byte_element_2517){ if ((mem_static_pointer+=12)<mem_static_limit) byte_element_2517=(byte_element_struct*)(mem_static_pointer-12); else byte_element_2517=(byte_element_struct*)mem_static_malloc(12); } int32 pass2518; int32 *_FUNC_EVALUATETOTYP_LONG_T1=NULL; if(_FUNC_EVALUATETOTYP_LONG_T1==NULL){ _FUNC_EVALUATETOTYP_LONG_T1=(int32*)mem_static_malloc(4); *_FUNC_EVALUATETOTYP_LONG_T1=0; } int32 pass2519; int32 *_FUNC_EVALUATETOTYP_LONG_T=NULL; if(_FUNC_EVALUATETOTYP_LONG_T==NULL){ _FUNC_EVALUATETOTYP_LONG_T=(int32*)mem_static_malloc(4); *_FUNC_EVALUATETOTYP_LONG_T=0; } qbs *_FUNC_EVALUATETOTYP_STRING_LK=NULL; if (!_FUNC_EVALUATETOTYP_STRING_LK)_FUNC_EVALUATETOTYP_STRING_LK=qbs_new(0,0); int32 pass2520; int32 pass2521; int32 pass2522; int32 pass2523; int32 pass2524; int32 pass2525; byte_element_struct *byte_element_2526=NULL; if (!byte_element_2526){ if ((mem_static_pointer+=12)<mem_static_limit) byte_element_2526=(byte_element_struct*)(mem_static_pointer-12); else byte_element_2526=(byte_element_struct*)mem_static_malloc(12); } byte_element_struct *byte_element_2527=NULL; if (!byte_element_2527){ if ((mem_static_pointer+=12)<mem_static_limit) byte_element_2527=(byte_element_struct*)(mem_static_pointer-12); else byte_element_2527=(byte_element_struct*)mem_static_malloc(12); } byte_element_struct *byte_element_2528=NULL; if (!byte_element_2528){ if ((mem_static_pointer+=12)<mem_static_limit) byte_element_2528=(byte_element_struct*)(mem_static_pointer-12); else byte_element_2528=(byte_element_struct*)mem_static_malloc(12); } int32 pass2529; int32 pass2530; int32 *_FUNC_EVALUATETOTYP_LONG_TSIZE=NULL; if(_FUNC_EVALUATETOTYP_LONG_TSIZE==NULL){ _FUNC_EVALUATETOTYP_LONG_TSIZE=(int32*)mem_static_malloc(4); *_FUNC_EVALUATETOTYP_LONG_TSIZE=0; } qbs *_FUNC_EVALUATETOTYP_STRING_INDEX=NULL; if (!_FUNC_EVALUATETOTYP_STRING_INDEX)_FUNC_EVALUATETOTYP_STRING_INDEX=qbs_new(0,0); byte_element_struct *byte_element_2531=NULL; if (!byte_element_2531){ if ((mem_static_pointer+=12)<mem_static_limit) byte_element_2531=(byte_element_struct*)(mem_static_pointer-12); else byte_element_2531=(byte_element_struct*)mem_static_malloc(12); } int32 pass2532; int32 pass2533; int32 *_FUNC_EVALUATETOTYP_LONG_BYTES=NULL; if(_FUNC_EVALUATETOTYP_LONG_BYTES==NULL){ _FUNC_EVALUATETOTYP_LONG_BYTES=(int32*)mem_static_malloc(4); *_FUNC_EVALUATETOTYP_LONG_BYTES=0; } int32 pass2534; int32 pass2535; byte_element_struct *byte_element_2536=NULL; if (!byte_element_2536){ if ((mem_static_pointer+=12)<mem_static_limit) byte_element_2536=(byte_element_struct*)(mem_static_pointer-12); else byte_element_2536=(byte_element_struct*)mem_static_malloc(12); } byte_element_struct *byte_element_2537=NULL; if (!byte_element_2537){ if ((mem_static_pointer+=12)<mem_static_limit) byte_element_2537=(byte_element_struct*)(mem_static_pointer-12); else byte_element_2537=(byte_element_struct*)mem_static_malloc(12); } byte_element_struct *byte_element_2538=NULL; if (!byte_element_2538){ if ((mem_static_pointer+=12)<mem_static_limit) byte_element_2538=(byte_element_struct*)(mem_static_pointer-12); else byte_element_2538=(byte_element_struct*)mem_static_malloc(12); } int32 pass2539; int32 pass2540; byte_element_struct *byte_element_2541=NULL; if (!byte_element_2541){ if ((mem_static_pointer+=12)<mem_static_limit) byte_element_2541=(byte_element_struct*)(mem_static_pointer-12); else byte_element_2541=(byte_element_struct*)mem_static_malloc(12); } int32 pass2542; int32 pass2543; int32 pass2544; int32 pass2545; int32 pass2546; int32 pass2547; int32 pass2548; int32 *_FUNC_EVALUATETOTYP_LONG_BITS=NULL; if(_FUNC_EVALUATETOTYP_LONG_BITS==NULL){ _FUNC_EVALUATETOTYP_LONG_BITS=(int32*)mem_static_malloc(4); *_FUNC_EVALUATETOTYP_LONG_BITS=0; }
{ "pile_set_name": "Github" }
""" """ import json import logging import ast import difflib import sys import os.path import astor CHECKS = { "array" : ast.Tuple(ctx=ast.Load(), elts=[ast.Name(id='list', ctx=ast.Load()), ast.Name(id='tuple', ctx=ast.Load())]), # "(list, tuple)", "boolean" : ast.Tuple(ctx=ast.Load(), elts=[ast.Name(id='bool', ctx=ast.Load())]), # "(bool, )", "integer" : ast.Tuple(ctx=ast.Load(), elts=[ast.Name(id='int', ctx=ast.Load())]), # "(int, )", "number" : ast.Tuple(ctx=ast.Load(), elts=[ast.Name(id='float', ctx=ast.Load()), ast.Name(id='int', ctx=ast.Load())]), # "(float, int)", "string" : ast.Tuple(ctx=ast.Load(), elts=[ast.Name(id='str', ctx=ast.Load())]), # "(str, )", } class JsonInterfaceGenerator(object): """ """ def __init__(self, protocol_version="1.2", debug_prints=False, *args, **kwargs): """ init """ super().__init__(*args, **kwargs) if protocol_version == None: protocol_version = "1.2" self.log = logging.getLogger("Main.ChromeController.WrapperGenerator") self.line_num = 0 self.do_debug_prints = debug_prints self.types = {} self.protocol = self.__load_protocol(protocol_version) self.__build_interface_class() def __load_json_file(self, fname): folder = os.path.split(__file__)[0] protocol_file_path = os.path.join(folder, "../", 'protocols', fname) protocol_file_path = os.path.abspath(protocol_file_path) assert(os.path.exists(protocol_file_path)), "Protocol file '{}' appears to be missing!".format(protocol_file_path) with open(protocol_file_path) as fp: protocol_str = fp.read() return json.loads(protocol_str) def __load_protocol(self, protocol_version): self.log.info("Loading protocol version %s", protocol_version) main_json_file = "browser_protocol-r{}.json".format(protocol_version) js_json_file = "js_protocol-r{}.json" .format(protocol_version) js_file_1 = self.__load_json_file(main_json_file) js_file_2 = self.__load_json_file(js_json_file) self.__validate_protocol_version(main_json_file, js_file_1, protocol_version) self.__validate_protocol_version(js_json_file, js_file_2, protocol_version) # assemble the two json files into the single command descriptor file. for domain in js_file_2['domains']: js_file_1['domains'].append(domain) return js_file_1 def __get_line(self): self.line_num += 1 return self.line_num def __validate_protocol_version(self, filename, js_file, protocol_version): file_protocol_rev = "{}.{}".format(js_file['version']["major"], js_file['version']["minor"]) errm_1 = "Version mismatch: {} - {} in file {}".format(file_protocol_rev, protocol_version, filename) assert file_protocol_rev == protocol_version, errm_1 def __build_interface_class(self): # body = ast. body = [ ast.Expr(value=ast.Str(s='\n\n\t')), self.__build__init() ] for subdom in self.protocol['domains']: subdom_funcs = self.__build_domain_interface(subdom) body += subdom_funcs # print(body) self.interface_class = ast.ClassDef( name = "ChromeRemoteDebugInterface", bases = [ast.Name(id="ChromeInterface", ctx=ast.Load())], body = body, keywords = [], decorator_list = [], starargs = None, kwargs = None, lineno = self.__get_line(), col_offset = 0, ) # code = astor.dump_tree(self.interface_class) # print(code) def __build__init(self): super_func_call = ast.Call(func=ast.Name(id='super', ctx=ast.Load()), args=[], keywords=[]) if (sys.version_info[0], sys.version_info[1]) == (3, 5) or \ (sys.version_info[0], sys.version_info[1]) == (3, 6) or \ (sys.version_info[0], sys.version_info[1]) == (3, 7) or \ (sys.version_info[0], sys.version_info[1]) == (3, 8): super_func = ast.Call( func=ast.Attribute(value=super_func_call, attr='__init__', ctx=ast.Load()), args=[ast.Starred(value=ast.Name(id='args', ctx=ast.Load()), ctx=ast.Load())], keywords=[ast.keyword(arg=None, value=ast.Name(id='kwargs', ctx=ast.Load()), ctx=ast.Load())], ) elif (sys.version_info[0], sys.version_info[1]) == (3,4): super_func = ast.Call( func=ast.Attribute(value=super_func_call, attr='__init__', ctx=ast.Load()), args=[], keywords=[], starargs=ast.Name(id='args', ctx=ast.Load()), kwargs=ast.Name(id='kwargs', ctx=ast.Load()), ) else: print("Version:", sys.version_info) raise RuntimeError("This script only functions on python 3.4, 3.5, 3.6, or 3.7. Active python version {}.{}".format(*sys.version_info)) super_init = ast.Expr( value=super_func, lineno = self.__get_line(), col_offset = 0, ) body = [super_init] sig = ast.arguments( args=[ast.arg('self', None)], vararg=ast.arg(arg='args', annotation=None), kwarg=ast.arg(arg='kwargs', annotation=None), varargannotation=None, posonlyargs=[], kwonlyargs=[], kwargannotation=None, defaults=[], kw_defaults=[]) func = ast.FunctionDef( name = "__init__", args = sig, body = body, decorator_list = [], lineno = self.__get_line(), col_offset = 0, ) return func def __build_domain_interface(self, subdom): assert "domain" in subdom dom_desc = subdom.get("descripton", "") dom_name = subdom['domain'] full_name = subdom['domain'] for typen in subdom.get('types', []): typestr = "{}_{}".format(dom_name, typen['id']) assert typen['id'] not in self.types, "Duplicate type name: {}".format(typen['id']) self.types[typestr] = typen functions = [] for command in subdom.get('commands', []): func = self.__build_function(dom_name, full_name, command) functions.append(func) return functions def __build_desc_string(self, dom_name, func_name, func_params): desc = [] fname = "{}.{}".format(dom_name, func_name) desc.append("Function path: {}".format(fname)) desc.append(" Domain: {}".format(dom_name)) desc.append(" Method name: {}".format(func_name)) desc.append("") if 'experimental' in func_params and func_params['experimental']: desc.append(" WARNING: This function is marked 'Experimental'!") desc.append("") if "parameters" in func_params: desc.append(" Parameters:") required = [param for param in func_params['parameters'] if not param.get("optional", False)] optional = [param for param in func_params['parameters'] if param.get("optional", False)] sections = [ (" Required arguments:", required), (" Optional arguments:", optional), ] sections = [section for section in sections if section[1]] for segment_name, items in sections: desc.append(segment_name) for param in items: if not "description" in param: param['description'] = "No description" if "type" in param: desc.append(" \'{}\' (type: {}) -> {}".format(param['name'], param['type'], param['description'])) else: desc.append(" \'{}\' (type: {}) -> {}".format(param['name'], param['$ref'], param['description'])) if "returns" in func_params: desc.append(" Returns:") for param in func_params['returns']: if not "description" in param: param['description'] = "No description" if "type" in param: desc.append(" \'{}\' (type: {}) -> {}".format(param['name'], param['type'], param['description'])) else: desc.append(" \'{}\' (type: {}) -> {}".format(param['name'], param['$ref'], param['description'])) else: desc.append(" No return value.") desc.append("") if "description" in func_params: desc.append(" Description: {}".format(func_params['description'])) desc = ["\t\t"+line for line in desc] ret = "\n".join(desc) return ret def __build_conditional_arg_check(self, argname, argtype): target_value = ast.Subscript( value=ast.Name(id='kwargs', ctx=ast.Load()), slice=ast.Index(ast.Str(s=argname)), ctx=ast.Load() ) presence_check = ast.Call(func = ast.Name(id='isinstance', ctx=ast.Load()), args = [target_value, argtype], keywords = [], lineno = self.__get_line()) # Assumes that argtype is a ast.Tuple of ast.Name items types = [t.id for t in argtype.elts] check_message = ast.BinOp( left = ast.Str(s='Optional argument \'{}\' must be of type \'{}\'. Received type: \'%s\''.format(argname, types)), op = ast.Mod(), right = ast.Call(func=ast.Name(id='type', ctx=ast.Load()), args=[target_value], keywords=[]), lineno = self.__get_line()) assert_check = ast.Assert( test = presence_check, msg = check_message, lineno = self.__get_line()) check_body = [assert_check] check = ast.Compare(left=ast.Str(s=argname, ctx=ast.Load()), ops=[ast.In()], comparators=[ast.Name(id='kwargs', ctx=ast.Load())]) new_ret = ast.If( test = check, body = check_body, orelse = [], lineno = self.__get_line()) return new_ret def __build_unconditional_arg_check(self, argname, argtype): presence_check = ast.Call(func = ast.Name(id='isinstance', ctx=ast.Load()), args = [ast.Name(id=argname, ctx=ast.Load()), argtype], keywords = [], lineno = self.__get_line()) types = [t.id for t in argtype.elts] check_message = ast.BinOp( left = ast.Str(s='Argument \'{}\' must be of type \'{}\'. Received type: \'%s\''.format(argname, types)), op = ast.Mod(), right = ast.Call(func=ast.Name(id='type', ctx=ast.Load()), args=[ast.Name(id=argname, ctx=ast.Load())], keywords=[]), lineno = self.__get_line()) new_ret = ast.Assert( test = presence_check, msg = check_message, lineno = self.__get_line()) return new_ret def __build_debug_print(self, prefix_str, var_name): pstmt = ast.Expr( value=ast.Call( func = ast.Name(id='print', ctx=ast.Load()), args = [ast.Str(s=prefix_str), ast.Name(id=var_name, ctx=ast.Load())], keywords = [], lineno = self.__get_line() ) ) return pstmt def __build_function(self, dom_name, full_name, func_params): assert 'name' in func_params func_name = func_params['name'] docstr = self.__build_desc_string(dom_name, func_name, func_params) args = [ast.arg('self', None)] message_params = [] func_body = [] if docstr: func_body.append(ast.Expr(ast.Str("\n"+docstr+"\n\t\t"))) for param in func_params.get("parameters", []): argname = param['name'] param_optional = param.get("optional", False) if param_optional is False: message_params.append(ast.keyword(argname, ast.Name(id=argname, ctx=ast.Load()))) args.append(ast.arg(argname, None)) if self.do_debug_prints: func_body.append(self.__build_debug_print(argname, argname)) param_type = param.get("type", None) if param_type in CHECKS: if param_optional: check = self.__build_conditional_arg_check(argname, CHECKS[param_type]) else: check = self.__build_unconditional_arg_check(argname, CHECKS[param_type]) if check: func_body.append(check) optional_params = [param.get("name") for param in func_params.get("parameters", []) if param.get("optional", False)] func_kwargs = None if len(optional_params): value = ast.List(elts=[ast.Str(s=param, ctx=ast.Store()) for param in optional_params], ctx=ast.Load()) create_list = ast.Assign(targets=[ast.Name(id='expected', ctx=ast.Store())], value=value) func_body.append(create_list) passed_arg_list = ast.Assign(targets=[ast.Name(id='passed_keys', ctx=ast.Store())], value=ast.Call(func=ast.Name(id='list', ctx=ast.Load()), args=[ast.Call(func=ast.Attribute(value=ast.Name(id='kwargs', ctx=ast.Load()), attr='keys', ctx=ast.Load()), args=[], keywords=[])], keywords=[])) func_body.append(passed_arg_list) comprehension = ast.comprehension(target=ast.Name(id='key', ctx=ast.Store()), iter=ast.Name(id='passed_keys', ctx=ast.Load()), ifs=[], is_async=False) comparator = ast.Name(id='expected', ctx=ast.Load()) listcomp = ast.ListComp(elt=ast.Compare(left=ast.Name(id='key', ctx=ast.Load()), ops=[ast.In()], comparators=[comparator]), generators=[comprehension]) check_message = ast.BinOp( left = ast.Str(s="Allowed kwargs are {}. Passed kwargs: %s".format(optional_params)), op = ast.Mod(), right = ast.Name(id='passed_keys', ctx=ast.Load()), lineno = self.__get_line()) kwarg_check = ast.Assert(test=ast.Call(func=ast.Name(id='all', ctx=ast.Load()), args=[listcomp], keywords=[]), msg=check_message) func_body.append(kwarg_check) func_kwargs = ast.Name(id='kwargs', ctx=ast.Load()) fname = "{}.{}".format(dom_name, func_name) fname = ast.Str(s=fname, ctx=ast.Load()) if (sys.version_info[0], sys.version_info[1]) == (3, 5) or \ (sys.version_info[0], sys.version_info[1]) == (3, 6) or \ (sys.version_info[0], sys.version_info[1]) == (3, 7) or \ (sys.version_info[0], sys.version_info[1]) == (3, 8): # More irritating minor semantic differences in the AST between 3.4 and 3.5 if func_kwargs: message_params.append(ast.keyword(arg=None, value=ast.Name(id='kwargs', ctx=ast.Load()))) communicate_call = ast.Call( func=ast.Attribute(value=ast.Name(id='self', ctx=ast.Load()), ctx=ast.Load(), attr='synchronous_command'), args=[fname], keywords=message_params) elif (sys.version_info[0], sys.version_info[1]) == (3,4): communicate_call = ast.Call( func=ast.Attribute(value=ast.Name(id='self', ctx=ast.Load()), ctx=ast.Load(), attr='synchronous_command'), args=[fname], kwargs=func_kwargs, keywords=message_params) else: print("Version:", sys.version_info) raise RuntimeError("This script only functions on python 3.4, 3.5, 3.6, or 3.7. Active python version {}.{}".format(*sys.version_info)) do_communicate = ast.Assign(targets=[ast.Name(id='subdom_funcs', ctx=ast.Store())], value=communicate_call) func_ret = ast.Return(value=ast.Name(id='subdom_funcs', ctx=ast.Load())) if len(optional_params) and self.do_debug_prints: func_body.append(self.__build_debug_print('kwargs', 'kwargs')) func_body.append(do_communicate) func_body.append(func_ret) if len(optional_params): kwarg = ast.arg(arg='kwargs', annotation=None) else: kwarg = None sig = ast.arguments( args=args, vararg=None, varargannotation=None, posonlyargs=[], kwonlyargs=[], kwarg=kwarg, kwargannotation=None, defaults=[], kw_defaults=[]) func = ast.FunctionDef( name = "{}_{}".format(full_name, func_name), args = sig, body = func_body, decorator_list = [], lineno = self.__get_line(), col_offset = 0, ) return func def __to_module(self): module_components = [ ast.ImportFrom(module="ChromeController.transport", names=[ast.alias('ChromeExecutionManager', None)], level=0), ast.ImportFrom(module="ChromeController.manager_base", names=[ast.alias('ChromeInterface', None)], level=0), self.interface_class, ] if sys.version_info >= (3, 8): mod = ast.Module(module_components, [], lineno=self.__get_line(), col_offset=1) else: mod = ast.Module(module_components, lineno=self.__get_line(), col_offset=1) mod = ast.fix_missing_locations(mod) return mod def dump_class(self): indent = " " return astor.to_source(self.__to_module(), indent_with=indent) def dump_ast(self): return astor.dump_tree(self.__to_module()) def compile_class(self): mod = self.__to_module() code = compile(self.__to_module(), "no filename", "exec") exec(code) built_class = locals()['ChromeRemoteDebugInterface'] return built_class def get_source(protocol_version=None): instance = JsonInterfaceGenerator(protocol_version=protocol_version) return instance.dump_class() def get_class_def(protocol_version=None): instance = JsonInterfaceGenerator(protocol_version=protocol_version) ret = instance.compile_class() return ret def get_printed_ast(protocol_version=None): instance = JsonInterfaceGenerator(protocol_version=protocol_version) return instance.dump_ast() def print_file_ast(): with open(__file__) as fp: this_source = fp.read() this_ast = ast.parse(this_source) print("AST:") print("astor.dump_tree(this_ast)") print(astor.dump_tree(this_ast)) def update_generated_class(output_diff, protocolversion="1.2"): log = logging.getLogger("Main.ChromeController.WrapperGenCaller") gen_filename = "Generated.py" cur_file = os.path.abspath(__file__) cur_dir = os.path.dirname(cur_file) fname = os.path.join(cur_dir, gen_filename) cls_def = get_source(protocol_version=protocolversion) try: with open(fname, "r", encoding='utf-8') as fp: have = fp.read() except IOError: # The class hasn't been generated yet? have = "" if have.strip() == cls_def.strip(): log.info("ChromeController wrapper is up to date. Nothing to do") else: log.warning("Note: If ChromeController is installed as a module, " "this may require administrator permissions") if output_diff: if have.strip() == cls_def.strip(): log.info("No changes!") else: log.info("Calculating changes") d = difflib.Differ() diff = d.compare(have.strip().splitlines(keepends=True), cls_def.strip().splitlines(keepends=True)) dstr = ''.join(diff) for line in dstr.split("\n"): if line.startswith(" "): continue log.info("Diff: %s", line) try: with open(fname, "w", encoding='utf-8') as fp: fp.write(cls_def) except IOError: raise IOError("Could not update class definition file: {}, and " "it is out of date!".format(fname)) def _save_json(name, json_blob): folder = os.path.split(__file__)[0] protocol_file_path = os.path.join(folder, "../", 'protocols', name) protocol_file_path = os.path.abspath(protocol_file_path) with open(protocol_file_path, "w") as fp: fp.write(json.dumps(json_blob, indent=4)) def fetch_new_protocol(): import requests log = logging.getLogger("Main.ChromeController.WrapperGenCaller") devtools_protocol_url = "https://raw.githubusercontent.com/ChromeDevTools/devtools-protocol/master/json/browser_protocol.json" js_protocol_url = "https://raw.githubusercontent.com/ChromeDevTools/devtools-protocol/master/json/js_protocol.json" devtools_protocol_resp = requests.get(devtools_protocol_url) js_protocol_resp = requests.get(js_protocol_url) devtools_protocol = devtools_protocol_resp.json() js_protocol = js_protocol_resp.json() devtools_protocol['version']['minor'] += "-DEV" js_protocol ['version']['minor'] += "-DEV" main_json_file_name = "browser_protocol-r{}.{}.json".format(devtools_protocol['version']['major'], devtools_protocol['version']['minor']) js_json_file_name = "js_protocol-r{}.{}.json" .format(js_protocol['version']['major'], js_protocol['version']['minor']) log.info("Saving file %s", main_json_file_name) _save_json(main_json_file_name, devtools_protocol) log.info("Saving file %s", js_json_file_name) _save_json(js_json_file_name, js_protocol) def test(): print(JsonInterfaceGenerator) # print_file_ast() instance = JsonInterfaceGenerator() print("ast:") print(instance.dump_ast()) newsauce = instance.dump_class() print("Class:") print(newsauce) print(instance.compile_class()) # print(instance) if __name__ == '__main__': test() print_file_ast()
{ "pile_set_name": "Github" }
#ifndef HEAP_H #define HEAP_H #define MAX_NODES 100 /* An implementation of a MinHeap, a tree based data structure in which which each node's value is lesser than its children.*/ typedef struct { int N; int heap[MAX_NODES]; } MinHeap; void add(MinHeap* h, int value); void rmv(MinHeap* h, int node); void sift(MinHeap* h, int node); void percolate(MinHeap* h, int node); void swap_nodes(MinHeap* h, int node1, int node2); int get_value_at_node(MinHeap* h, int node); #endif // HEAP_H
{ "pile_set_name": "Github" }
# Translation of Odoo Server. # This file contains the translation of the following modules: # * hr_expense_sequence # # Translators: # OCA Transbot <transbot@odoo-community.org>, 2017 msgid "" msgstr "" "Project-Id-Version: Odoo Server 10.0\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2017-07-01 01:04+0000\n" "PO-Revision-Date: 2017-07-01 01:04+0000\n" "Last-Translator: OCA Transbot <transbot@odoo-community.org>, 2017\n" "Language-Team: Italian (https://www.transifex.com/oca/teams/23907/it/)\n" "Language: it\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: \n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #. module: hr_expense_sequence #: model:ir.model,name:hr_expense_sequence.model_hr_expense_sheet msgid "Expense Report" msgstr "" #. module: hr_expense_sequence #: model_terms:ir.ui.view,arch_db:hr_expense_sequence.report_expense_sheet msgid "Expenses Report" msgstr "" #. module: hr_expense_sequence #: model:ir.model.fields,field_description:hr_expense_sequence.field_hr_expense_sheet__number msgid "Number" msgstr "Numero"
{ "pile_set_name": "Github" }
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/client/lib/matrix.h" #include <array> #include <numeric> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/ascii.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "tensorflow/compiler/xla/client/lib/arithmetic.h" #include "tensorflow/compiler/xla/client/lib/constants.h" #include "tensorflow/compiler/xla/client/lib/slicing.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/status.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" namespace xla { XlaOp IdentityMatrix(XlaBuilder* builder, PrimitiveType type, int64 m, int64 n) { auto a = Iota(builder, U32, m); auto b = Iota(builder, U32, n); auto indicator = Eq(a, Broadcast(b, {m}), /*broadcast_dimensions=*/{0}); return ConvertElementType(indicator, type); } XlaOp GetDiagonalMask(XlaOp x, int diagonal) { XlaBuilder* builder = x.builder(); return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> { TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x)); auto n_dims = static_cast<int32>(shape.rank()); TF_RET_CHECK(n_dims >= 2); auto m = shape.dimensions(n_dims - 2); auto n = shape.dimensions(n_dims - 1); absl::Span<const int64> major_dims = AsInt64Slice(shape.dimensions()).subspan(/*pos=*/0, /*len=*/n_dims - 2); auto a = Iota(builder, S32, n); auto b = Iota(builder, S32, m) + ConstantR0WithType(builder, S32, diagonal); auto indicator = Eq(b, Broadcast(a, {m}), /*broadcast_dimensions=*/{0}); auto mask = Broadcast(indicator, major_dims); return mask; }); } XlaOp GetMatrixDiagonal(XlaOp x, int k) { XlaBuilder* builder = x.builder(); return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> { TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x)); auto n_dims = static_cast<int32>(shape.rank()); TF_RET_CHECK(n_dims >= 2); const int64 m = shape.dimensions(n_dims - 2); const int64 n = shape.dimensions(n_dims - 1); auto mask = GetDiagonalMask(x, k); // TPUs don't support S64 add reduction at the moment. But fortunately // OR-reductions work just as well for integers. XlaComputation reducer = CreateScalarIdentityWithZeroComputation(shape.element_type(), builder); // k == 0, we can save one slice op. if (k == 0) { return Reduce(Select(mask, x, Zeros(builder, shape)), ScalarLike(x, 0), reducer, {m >= n ? n_dims - 2 : n_dims - 1}); } else if (k > 0) { auto result = Reduce(Select(mask, x, Zeros(builder, shape)), ScalarLike(x, 0), reducer, {n_dims - 2}); return SliceInMinorDims(result, {std::min<int64>(k, n)}, {std::min(m + k, n)}); } else { auto result = Reduce(Select(mask, x, Zeros(builder, shape)), ScalarLike(x, 0), reducer, {n_dims - 1}); return SliceInMinorDims(result, {std::min<int64>(-k, m)}, {std::min(m, n - k)}); } }); } XlaOp TriangleMask(XlaOp x, int diagonal) { XlaBuilder* builder = x.builder(); return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> { TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x)); const int64 n_dims = shape.rank(); TF_RET_CHECK(n_dims >= 2); const int64 m = shape.dimensions(n_dims - 2); const int64 n = shape.dimensions(n_dims - 1); absl::Span<const int64> major_dims = AsInt64Slice(shape.dimensions()).subspan(/*pos=*/0, /*len=*/n_dims - 2); auto a = Iota(builder, S32, n); auto b = Iota(builder, S32, m) + ConstantR0<int32>(builder, diagonal); XlaOp indicator; indicator = Ge(b, Broadcast(a, {m}), /*broadcast_dimensions=*/{0}); return Broadcast(indicator, major_dims); }); } XlaOp Triangle(XlaOp x, bool lower) { return lower ? Select(TriangleMask(x, 0), x, ZerosLike(x)) : Select(TriangleMask(x, -1), ZerosLike(x), x); } XlaOp UpperTriangle(XlaOp x) { return Triangle(x, false); } XlaOp LowerTriangle(XlaOp x) { return Triangle(x, true); } Status ValidateEinsumNumericDimensions(absl::Span<const int64> x_config, absl::Span<const int64> y_config, absl::Span<const int64> output_config) { for (auto dim : output_config) { if (absl::c_linear_search(x_config, dim) || absl::c_linear_search(y_config, dim)) { if (absl::c_count(output_config, dim) > 1) { return InvalidArgument("Einsum has repeated output dimension."); } continue; } return InvalidArgument( "Einsum has output dimension without corresponding input dimension."); } for (auto dim : x_config) { if (absl::c_linear_search(y_config, dim) || absl::c_linear_search(output_config, dim)) { if (absl::c_count(x_config, dim) > 1) { return InvalidArgument("Einsum has repeated lhs dimension."); } continue; } return InvalidArgument( "Einsum has lhs dimension without corresponding rhs or output " "dimension."); } for (auto dim : y_config) { if (absl::c_linear_search(x_config, dim) || absl::c_linear_search(output_config, dim)) { if (absl::c_count(y_config, dim) > 1) { return InvalidArgument("Einsum has repeated rhs dimension."); } continue; } return InvalidArgument( "Einsum has rhs dimension without corresponding lhs or output " "dimension."); } return Status::OK(); } xla::XlaOp Einsum(xla::XlaOp x, absl::Span<const int64> x_config, xla::XlaOp y, absl::Span<const int64> y_config, absl::Span<const int64> output_config, xla::PrecisionConfig::Precision precision) { XlaBuilder* builder = x.builder(); return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> { TF_RETURN_IF_ERROR( ValidateEinsumNumericDimensions(x_config, y_config, output_config)); const int64 x_rank = x_config.size(); const int64 y_rank = y_config.size(); const int64 output_rank = output_config.size(); absl::flat_hash_set<int64> x_map; absl::flat_hash_set<int64> y_map; absl::flat_hash_set<int64> output_map; auto find = [&](const absl::flat_hash_set<int64>& map, int64 d) { return map.count(d) != 0; }; auto insert = [&](absl::flat_hash_set<int64>& map, char d) { CHECK(!find(map, d)); map.insert(d); }; for (auto d : x_config) { insert(x_map, d); } for (auto d : y_config) { insert(y_map, d); } for (auto d : output_config) { insert(output_map, d); } DotDimensionNumbers dnums; std::vector<int64> lhs_outer_dims; auto is_batch_dim = [&](int64 d) { return find(x_map, d) && find(y_map, d) && find(output_map, d); }; auto is_contracting = [&](int64 d) { return find(x_map, d) && find(y_map, d); }; auto rhs_dimension_number = [&](int64 d) { return absl::c_find(y_config, d) - y_config.begin(); }; for (int64 i = 0; i < x_rank; ++i) { auto dim_name = x_config[i]; if (is_batch_dim(dim_name)) { dnums.add_lhs_batch_dimensions(i); dnums.add_rhs_batch_dimensions(rhs_dimension_number(dim_name)); } else if (is_contracting(dim_name)) { dnums.add_lhs_contracting_dimensions(i); dnums.add_rhs_contracting_dimensions(rhs_dimension_number(dim_name)); } else { lhs_outer_dims.push_back(i); } } std::vector<int64> rhs_outer_dims; for (int64 i = 0; i < y_rank; ++i) { auto dim_name = y_config[i]; if (!is_batch_dim(dim_name) && !is_contracting(dim_name)) { rhs_outer_dims.push_back(i); } } auto output_dimension_number = [&](char d) { return absl::c_find(output_config, d) - output_config.begin(); }; std::vector<int64> output_dims; output_dims.reserve(output_rank); for (auto d : dnums.lhs_batch_dimensions()) { output_dims.push_back(output_dimension_number(x_config[d])); } for (auto d : lhs_outer_dims) { output_dims.push_back(output_dimension_number(x_config[d])); } for (auto d : rhs_outer_dims) { output_dims.push_back(output_dimension_number(y_config[d])); } std::vector<int64> transpose_dims(output_rank); for (int64 i = 0; i < output_rank; ++i) { transpose_dims[output_dims[i]] = i; } PrecisionConfig precision_proto; precision_proto.add_operand_precision(precision); precision_proto.add_operand_precision(precision); return Transpose(DotGeneral(x, y, dnums, &precision_proto), transpose_dims); }); } XlaOp BatchDot(XlaOp x, XlaOp y, PrecisionConfig::Precision precision) { return BatchDot(x, false, y, false, precision); } XlaOp BatchDot(XlaOp x, bool transpose_x, XlaOp y, bool transpose_y, PrecisionConfig::Precision precision) { XlaBuilder* builder = x.builder(); return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> { TF_ASSIGN_OR_RETURN(Shape x_shape, builder->GetShape(x)); TF_ASSIGN_OR_RETURN(Shape y_shape, builder->GetShape(y)); // The batch dimensions must be broadcast-compatible and the matrix // dimensions must be valid. std::vector<int64> x_config; std::vector<int64> y_config; std::vector<int64> output_config; std::vector<int64> x_implicit_broadcast; std::vector<int64> y_implicit_broadcast; const int64 ndims = std::max(y_shape.rank(), x_shape.rank()); // If X and Y have unequal ranks, the major dimensions of the higher rank // shape are broadcasted. // // A dimension of size 1 can be implicitly broadcasted to any other // dimension. const int64 x_offset = std::max<int64>(0, y_shape.rank() - x_shape.rank()); const int64 y_offset = std::max<int64>(0, x_shape.rank() - y_shape.rank()); for (int i = 0; i < ndims - 2; ++i) { const int64 x_dim = i - x_offset; const int64 y_dim = i - y_offset; output_config.push_back(i); if (x_dim < 0) { y_config.push_back(i); } else if (y_dim < 0) { x_config.push_back(i); } else if (x_shape.dimensions(x_dim) == y_shape.dimensions(y_dim)) { y_config.push_back(i); x_config.push_back(i); } else if (x_shape.dimensions(x_dim) == 1) { y_config.push_back(i); x_implicit_broadcast.push_back(x_dim); } else if (y_shape.dimensions(y_dim) == 1) { x_config.push_back(i); y_implicit_broadcast.push_back(y_dim); } else { return InvalidArgument("Expected batch dot dimension to be equal or 1"); } } if (transpose_x) { x_config.push_back(ndims); x_config.push_back(ndims - 2); } else { x_config.push_back(ndims - 2); x_config.push_back(ndims); } if (transpose_y) { y_config.push_back(ndims - 1); y_config.push_back(ndims); } else { y_config.push_back(ndims); y_config.push_back(ndims - 1); } output_config.push_back(ndims - 2); output_config.push_back(ndims - 1); if (!x_implicit_broadcast.empty()) { x_shape = ShapeUtil::FilterDimensions( [&](int64 dim) { return !absl::c_linear_search(x_implicit_broadcast, dim); }, x_shape); x = Reshape(x, x_shape.dimensions()); } if (!y_implicit_broadcast.empty()) { y_shape = ShapeUtil::FilterDimensions( [&](int64 dim) { return !absl::c_linear_search(y_implicit_broadcast, dim); }, y_shape); y = Reshape(y, y_shape.dimensions()); } return Einsum(x, x_config, y, y_config, output_config, precision); }); } StatusOr<std::array<std::vector<int64>, 3>> ParseEinsumString( absl::string_view einsum_config) { std::array<std::vector<int64>, 3> einsum_config_numeric; std::vector<absl::string_view> main_split = absl::StrSplit(einsum_config, ','); if (main_split.size() != 2) { return InvalidArgument("Expected one \",\" in einsum_config."); } auto maybe_invalid_character = [](char d) { if (absl::ascii_isalpha(d)) { return Status::OK(); } if (d == '.') { return InvalidArgument("Unsupported \"...\" or \".\" in einsum config."); } return InvalidArgument("Unexpected character in einsum config."); }; auto& x_config = einsum_config_numeric[0]; x_config.reserve(main_split[0].size()); for (auto d : main_split[0]) { TF_RETURN_IF_ERROR(maybe_invalid_character(d)); x_config.push_back(static_cast<int64>(d)); } std::vector<absl::string_view> y_output_split = absl::StrSplit(main_split[1], "->"); if (y_output_split.size() != 2) { return InvalidArgument("Expected one \"->\" in einsum_config."); } auto& y_config = einsum_config_numeric[1]; y_config.reserve(y_output_split[0].size()); for (auto d : y_output_split[0]) { TF_RETURN_IF_ERROR(maybe_invalid_character(d)); y_config.push_back(static_cast<int64>(d)); } auto& output_config = einsum_config_numeric[2]; output_config.reserve(y_output_split[1].size()); for (auto d : y_output_split[1]) { TF_RETURN_IF_ERROR(maybe_invalid_character(d)); output_config.push_back(static_cast<int64>(d)); } return einsum_config_numeric; } XlaOp Einsum(XlaOp x, XlaOp y, absl::string_view einsum_config, PrecisionConfig::Precision precision) { XlaBuilder* builder = x.builder(); return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> { TF_ASSIGN_OR_RETURN(auto einsum_config_numeric, ParseEinsumString(einsum_config)); return Einsum(x, einsum_config_numeric[0], y, einsum_config_numeric[1], einsum_config_numeric[2], precision); }); } XlaOp TransposeInMinorDims(XlaOp x) { XlaBuilder* builder = x.builder(); return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> { TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x)); const int64 n_dims = shape.rank(); TF_RET_CHECK(n_dims >= 2); std::vector<int64> permutation(n_dims); std::iota(permutation.begin(), permutation.end(), 0); std::swap(permutation[n_dims - 1], permutation[n_dims - 2]); return Transpose(x, permutation); }); } XlaOp MaybeTransposeInMinorDims(XlaOp x, bool transpose) { return transpose ? TransposeInMinorDims(x) : x; } } // namespace xla
{ "pile_set_name": "Github" }
// Copyright 2017, OpenCensus Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* Package tag contains OpenCensus tags. Tags are key-value pairs. Tags provide additional cardinality to the OpenCensus instrumentation data. Tags can be propagated on the wire and in the same process via context.Context. Encode and Decode should be used to represent tags into their binary propagation form. */ package tag // import "go.opencensus.io/tag"
{ "pile_set_name": "Github" }
<BsNav as |nav|> <nav.item> <nav.linkTo @route="acceptance.link" @model="1"> first </nav.linkTo> </nav.item> <nav.item> <nav.linkTo @route="acceptance.link" @model="2"> second </nav.linkTo> </nav.item> <nav.item> <nav.linkTo @route="acceptance.link" @model={{@model}}> current </nav.linkTo> </nav.item> </BsNav>
{ "pile_set_name": "Github" }
## 课时 24:配置 react 基础配置已经全部配置好了,所以 react 的配置就只有将 jsx 的文件用 babel 编译一下就 ok 了,下面配置将 babel 的配置进行了修改 开启 react box.config.js ```js { "env": { "REACT": "react" // 配置 react } } ``` packages/react/webpack-chain.config.js ```js // [react 配置] module.exports = ({ config }) => { return () => { if (!process.env.REACT) return; const baseRule = config.module.rule("babel"); baseRule .use("babel") .loader(require.resolve("babel-loader")) .tap(options => { options.presets.push([ "@babel/preset-react", { corejs: "3", useBuiltIns: "usage", loose: true, modules: false, targets: { chrome: 59, edge: 13, firefox: 50, safari: 8 } } ]); return options; }); }; }; ```
{ "pile_set_name": "Github" }
// Copyright 2017 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package adapters import ( "errors" "fmt" "io" "io/ioutil" "os" "os/exec" "path/filepath" "runtime" "strings" "github.com/docker/docker/pkg/reexec" "github.com/wanchain/go-wanchain/node" "github.com/wanchain/go-wanchain/p2p/discover" ) // DockerAdapter is a NodeAdapter which runs simulation nodes inside Docker // containers. // // A Docker image is built which contains the current binary at /bin/p2p-node // which when executed runs the underlying service (see the description // of the execP2PNode function for more details) type DockerAdapter struct { ExecAdapter } // NewDockerAdapter builds the p2p-node Docker image containing the current // binary and returns a DockerAdapter func NewDockerAdapter() (*DockerAdapter, error) { // Since Docker containers run on Linux and this adapter runs the // current binary in the container, it must be compiled for Linux. // // It is reasonable to require this because the caller can just // compile the current binary in a Docker container. if runtime.GOOS != "linux" { return nil, errors.New("DockerAdapter can only be used on Linux as it uses the current binary (which must be a Linux binary)") } if err := buildDockerImage(); err != nil { return nil, err } return &DockerAdapter{ ExecAdapter{ nodes: make(map[discover.NodeID]*ExecNode), }, }, nil } // Name returns the name of the adapter for logging purposes func (d *DockerAdapter) Name() string { return "docker-adapter" } // NewNode returns a new DockerNode using the given config func (d *DockerAdapter) NewNode(config *NodeConfig) (Node, error) { if len(config.Services) == 0 { return nil, errors.New("node must have at least one service") } for _, service := range config.Services { if _, exists := serviceFuncs[service]; !exists { return nil, fmt.Errorf("unknown node service %q", service) } } // generate the config conf := &execNodeConfig{ Stack: node.DefaultConfig, Node: config, } conf.Stack.DataDir = "/data" conf.Stack.WSHost = "0.0.0.0" conf.Stack.WSOrigins = []string{"*"} conf.Stack.WSExposeAll = true conf.Stack.P2P.EnableMsgEvents = false conf.Stack.P2P.NoDiscovery = true conf.Stack.P2P.NAT = nil conf.Stack.NoUSB = true //conf.Stack.Logger = log.New("node.id", config.ID.String()) node := &DockerNode{ ExecNode: ExecNode{ ID: config.ID, Config: conf, adapter: &d.ExecAdapter, }, } node.newCmd = node.dockerCommand d.ExecAdapter.nodes[node.ID] = &node.ExecNode return node, nil } // DockerNode wraps an ExecNode but exec's the current binary in a docker // container rather than locally type DockerNode struct { ExecNode } // dockerCommand returns a command which exec's the binary in a Docker // container. // // It uses a shell so that we can pass the _P2P_NODE_CONFIG environment // variable to the container using the --env flag. func (n *DockerNode) dockerCommand() *exec.Cmd { return exec.Command( "sh", "-c", fmt.Sprintf( `exec docker run --interactive --env _P2P_NODE_CONFIG="${_P2P_NODE_CONFIG}" %s p2p-node %s %s`, dockerImage, strings.Join(n.Config.Node.Services, ","), n.ID.String(), ), ) } // dockerImage is the name of the Docker image which gets built to run the // simulation node const dockerImage = "p2p-node" // buildDockerImage builds the Docker image which is used to run the simulation // node in a Docker container. // // It adds the current binary as "p2p-node" so that it runs execP2PNode // when executed. func buildDockerImage() error { // create a directory to use as the build context dir, err := ioutil.TempDir("", "p2p-docker") if err != nil { return err } defer os.RemoveAll(dir) // copy the current binary into the build context bin, err := os.Open(reexec.Self()) if err != nil { return err } defer bin.Close() dst, err := os.OpenFile(filepath.Join(dir, "self.bin"), os.O_WRONLY|os.O_CREATE, 0755) if err != nil { return err } defer dst.Close() if _, err := io.Copy(dst, bin); err != nil { return err } // create the Dockerfile dockerfile := []byte(` FROM ubuntu:16.04 RUN mkdir /data ADD self.bin /bin/p2p-node `) if err := ioutil.WriteFile(filepath.Join(dir, "Dockerfile"), dockerfile, 0644); err != nil { return err } // run 'docker build' cmd := exec.Command("docker", "build", "-t", dockerImage, dir) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { return fmt.Errorf("error building docker image: %s", err) } return nil }
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html DIR="LTR"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="initial-scale=1.0"> <title>Google Chrome and Chrome OS additional Terms of Service</title> <style> :root { color-scheme: light dark } body { font-family:Arial; font-size:13px; } h2 { font-size:1em; margin-top:0 } </style> </head> <body> <h2> Google Chrome and Chrome OS additional Terms of Service </h2> <p> By using Chrome or Chrome OS, you agree to the Google Terms of Service located at https://policies.google.com/terms and these Google Chrome and Chrome OS additional Terms of Service. </p> <p> These Google Chrome and Chrome OS additional Terms of Service apply to the executable code version of Chrome and Chrome OS. Most source code for Chrome is available free of charge under open source software licence agreements at https://code.google.com/chromium/terms.html. </p> <p> Your use of certain components of Chrome and Chrome OS is subject to the following terms: </p> <section> <p> <strong> AVC </strong> </p> <p> THIS PRODUCT IS LICENSED UNDER THE AVC PATENT PORTFOLIO LICENCE FOR THE PERSONAL USE OF A CONSUMER, OR OTHER USES IN WHICH IT DOES NOT RECEIVE REMUNERATION, TO (i) ENCODE VIDEO IN COMPLIANCE WITH THE AVC STANDARD ('AVC VIDEO') AND/OR (ii) DECODE AVC VIDEO THAT WAS ENCODED BY A CONSUMER ENGAGED IN A PERSONAL ACTIVITY AND/OR WAS OBTAINED FROM A VIDEO PROVIDER LICENSED TO PROVIDE AVC VIDEO. NO LICENCE IS GRANTED OR SHALL BE IMPLIED FOR ANY OTHER USE. ADDITIONAL INFORMATION MAY BE OBTAINED FROM MPEG LA, L.L.C. SEE HTTP://WWW.MPEGLA.COM. </p> </section> <section> <p> <strong> Adobe </strong> </p> <p> Google Chrome may include one or more components provided by Adobe Systems Incorporated and Adobe Software Ireland Limited (collectively, “Adobe”). Your use of the Adobe software, as provided by Google (“Adobe Software”), is subject to the following additional terms (the “Adobe Terms”). You, the entity receiving the Adobe Software, will be hereinafter referred to as “Sublicensee”. </p> <p> 1. License Restrictions. </p> <p> (a) Flash Player, Version 10.x is designed only as a browser plug-in. Sublicensee may not modify or distribute this Adobe Software for use as anything but a browser plug-in for playing back content on a web page. For example, Sublicensee will not modify this Adobe Software in order to allow interoperation with applications that run outside the browser (e.g. stand-alone applications, widgets, device UI). </p> <p> (b) Sublicensee will not expose any APIs of the Flash Player, Version 10.x through a browser plug-in interface in such a way that allows such extension to be used to play back content from a web page as a stand-alone application. </p> <p> (c) The Chrome-Reader Software may not be used to render any PDF or EPUB documents that utilise digital-rights management protocols or systems other than Adobe DRM. </p> <p> (d) Adobe DRM must be enabled in the Chrome-Reader Software for all Adobe DRM-protected PDF and EPUB documents. </p> <p> (e) The Chrome-Reader Software may not, other than as explicitly permitted by the technical specifications, disable any capabilities provided by Adobe in the Adobe Software, including, but not limited to, support for PDF and EPUB formats and Adobe DRM. </p> <p> 2. Electronic Transmission. Sublicensee may allow the download of the Adobe Software from a website, the Internet, an intranet or similar technology (“Electronic Transmissions”), provided that Sublicensee agrees that any distributions of the Adobe Software by Sublicensee, including those on CD-ROM, DVD-ROM or other storage media and Electronic Transmissions, if expressly permitted, shall be subject to reasonable security measures to prevent unauthorised use. With relation to Electronic Transmissions approved hereunder, Sublicensee agrees to employ any reasonable usage restrictions set by Adobe, including those related to security and/or the restriction of distribution to end users of the Sublicensee's Product. </p> <p> 3. EULA and Distribution Terms. </p> <p> (a) Sublicensee shall ensure that the Adobe Software is distributed to end users under an enforceable end-user licence agreement, in favour of Sublicensee and its suppliers, containing at least each of the following minimum terms (the “End-User Licence”): (i) a prohibition against distribution and copying, (ii) a prohibition against modifications and derivative works, (iii) a prohibition against decompiling, reverse-engineering, disassembling and otherwise reducing the Adobe Software to a human-perceivable form, (iv) a provision indicating ownership of Sublicensee's Product (as defined in Section 8) by Sublicensee and its licensors, (v) a disclaimer of indirect, special, incidental, punitive and consequential damages and (vi) other industry-standard disclaimers and limitations, including, as applicable: a disclaimer of all applicable statutory warranties, to the full extent allowed by law. </p> <p> (b) Sublicensee shall ensure that the Adobe Software is distributed to Sublicensee’s distributors under an enforceable distribution licence agreement, in favour of Sublicensee and its suppliers, containing terms as protective of Adobe as the Adobe Terms. </p> <p> 4. Open Source. Sublicensee will not directly or indirectly grant, or purport to grant, to any third party any rights or immunities under Adobe’s intellectual property or proprietary rights that will subject such intellectual property to an open-source licence or scheme in which there is, or could be interpreted to be, a requirement that as a condition of use, modification and/or distribution, the Adobe Software be: (i) disclosed or distributed in source code form; (ii) licensed for the purpose of making derivative works; or (iii) redistributable at no charge. For clarification purposes, the foregoing restriction does not preclude Sublicensee from distributing, and Sublicensee will distribute the Adobe Software as bundled with the Google Software, without charge. </p> <p> 5. Additional Terms. With respect to any update, upgrade, new versions of the Adobe Software (collectively “Upgrades”) provided to Sublicenses, Adobe reserves the right to require additional terms and conditions applicable solely to the Upgrade and future versions thereof, and solely to the extent that such restrictions are imposed by Adobe on all licensees of such Upgrade. If Sublicensee does not agree to such additional terms or conditions, Sublicensee will have no licence rights with respect to such Upgrade, and Sublicensee’s licence rights with respect to the Adobe Software will terminate automatically on the 90th day from the date that such additional terms are made available to Sublicensee. </p> <p> 6. Proprietary Rights Notices. The Sublicensee shall not, and shall require its distributors not to, delete or in any manner alter the copyright notices, trademarks, logos or related notices, or other proprietary rights notices of Adobe (and its licensors, if any) appearing on or within the Adobe Software or accompanying materials. </p> <p> 7. Technical Requirements. Sublicensee and its distributors may only distribute Adobe Software and/or Upgrade on devices that (i) meet the technical specifications posted on http://www.adobe.com/mobile/licensees, (or a successor web site thereto), and (ii) has been verified by Adobe as set forth below. </p> <p> 8. Verification and Update. Sublicensee must submit to Adobe each Sublicensee product (and each version thereof) containing the Adobe Software and/or Upgrade (“Sublicensee Product”) that do not meet the Device Verification exemption criteria to be communicated by Google, for Adobe to verify. Sublicensee shall pay for each submission made by Sublicensee by procuring verification packages at Adobe’s then-current terms set forth at http://flashmobile.adobe.com/. Sublicensee Product that has not passed verification may not be distributed. Verification will be accomplished in accordance with Adobe’s then-current process described at http://flashmobile.adobe.com/ (“Verification”). </p> <p> 9. Profiles and Device Central. Sublicensee will be prompted to enter certain profile information about the Sublicensee Products either as part of the Verification process or some other method, and Sublicensee will provide such information, to Adobe. Adobe may (i) use such profile information as reasonably necessary to verify the Sublicensee Product (if such product is subject to Verification), and (ii) display such profile information in “Adobe Device Intelligence system”, located at https://devices.adobe.com/partnerportal/, and made available through Adobe’s authoring and development tools and services to enable developers and end users to see how content or applications are displayed in Sublicensee Products (e.g. how video images appear in certain phones). </p> <p> 10. Export. Sublicensee acknowledges that the laws and regulations of the United States restrict the export and re-export of commodities and technical data of United States origin, which may include the Adobe Software. Sublicensee agrees that it will not export or re-export the Adobe Software without the appropriate United States and foreign governmental clearances, if any. </p> <p> 11. Technology Pass-through Terms. </p> <p> (a) Except pursuant to applicable permissions or agreements therefore, from or with the applicable parties, Sublicensees shall not use and shall not allow the use of, the Adobe Software for the encoding or decoding of mp3 audio only (.mp3) data on any non-pc device (e.g. mobile phone or set-top box), nor may the mp3 encoders or decoders contained in the Adobe Software be used or accessed by any product other than the Adobe Software. The Adobe Software may be used for the encoding or decoding of MP3 data contained within a swf or flv file, which contains video, picture or other data. Sublicensee shall acknowledge that use of the Adobe Software for non-PC devices, as described in the prohibitions in this section, may require the payment of licensing royalties or other amounts to third parties who may hold intellectual property rights related to the MP3 technology and that Adobe nor Sublicensee has not paid any royalties or other amounts on account of third party intellectual property rights for such use. If Sublicensee requires an MP3 encoder or decoder for such use, Sublicensee is responsible for obtaining the necessary intellectual property license, including any applicable patent rights. </p> <p> (b) Sublicensee will not use, copy, reproduce and modify (i) the On2 source code (provided hereunder as a component of the Source Code) as necessary to enable the Adobe Software to decode video in the Flash video file format (.flv or .f4v), and (ii) the Sorenson Spark source code (provided hereunder as a component of the Source Code) for the limited purpose of making bug fixes and performance enhancements to the Adobe Software. All codecs provided with the Adobe Software may only be used and distributed as an integrated part of the Adobe Software and may not be accessed by any other application, including other Google applications. </p> <p> (c) The Source Code may be provided with an AAC codec and/or HE-AAC codec (“the AAC Codec”). Use of the AAC Codec is conditioned on Sublicensee obtaining a proper patent licence covering necessary patents as provided by VIA Licensing, for end products on or in which the AAC Codec will be used. Sublicensee acknowledges and agrees that Adobe is not providing a patent licence for an AAC Codec under this Agreement to Sublicensee or its sublicensees. </p> <p> (d) THE SOURCE CODE MAY CONTAIN CODE LICENSED UNDER THE AVC PATENT PORTFOLIO LICENCE FOR THE PERSONAL NON-COMMERCIAL USE OF A CONSUMER TO (i) ENCODE VIDEO IN COMPLIANCE WITH THE AVC STANDARD ("AVC VIDEO") AND/OR (ii) DECODE AVC VIDEO THAT WAS ENCODED BY A CONSUMER ENGAGED IN A PERSONAL NON-COMMERCIAL ACTIVITY AND/OR WAS OBTAINED FROM A VIDEO PROVIDER LICENSED TO PROVIDE AVC VIDEO. NO LICENCE IS GRANTED OR WILL BE IMPLIED FOR ANY OTHER USE. ADDITIONAL INFORMATION MAY BE OBTAINED FROM MPEG LA, L.L.C. See http://www.mpegla.com </p> <p> 12. Update. The Sublicensee will not circumvent Google’s or Adobe’s efforts to update the Adobe Software in all the Sublicensee’s products incorporating the Adobe Software as bundled with the Google Software (“Sublicensee Products”). </p> <p> 13. Attribution and Proprietary Notices. The Sublicensee will list the Adobe Software in publicly available Sublicensee Product specifications and include appropriate Adobe Software branding (specifically excluding the Adobe corporate logo) on the Sublicensee Product packaging or marketing materials in a manner consistent with branding of other third-party products contained within the Sublicensee Product. </p> <p> 14. No Warranty. THE ADOBE SOFTWARE IS MADE AVAILABLE TO SUBLICENSEE FOR USE AND REPRODUCTION “AS IS” AND ADOBE MAKES NO WARRANTY AS TO ITS USE OR PERFORMANCE. ADOBE AND ITS SUPPLIERS DO NOT AND CANNOT WARRANT THE PERFORMANCE OR RESULTS OBTAINED BY USING THE ADOBE SOFTWARE. EXCEPT FOR ANY WARRANTY, CONDITION, REPRESENTATION OR TERM TO THE EXTENT TO WHICH THE SAME CANNOT OR MAY NOT BE EXCLUDED OR LIMITED BY LAW APPLICABLE TO SUBLICENSEE IN SUBLICENSEE’S JURISDICTION, ADOBE AND ITS SUPPLIERS MAKE NO WARRANTIES, CONDITIONS, REPRESENTATIONS, OR TERMS (EXPRESS OR IMPLIED WHETHER BY STATUTE, COMMON LAW, CUSTOM, USAGE OR OTHERWISE) AS TO ANY MATTER INCLUDING WITHOUT LIMITATION NONINFRINGEMENT OF THIRD PARTY RIGHTS, MERCHANTABILITY, INTEGRATION, SATISFACTORY QUALITY, OR FITNESS FOR ANY PARTICULAR PURPOSE. SUBLICENSEE AGREES THAT SUBLICENSEE SHALL NOT MAKE ANY WARRANTY, EXPRESS OR IMPLIED, ON BEHALF OF ADOBE. </p> <p> 15. Limitation of Liability. IN NO EVENT WILL ADOBE OR ITS SUPPLIERS BE LIABLE TO SUBLICENSEE FOR ANY DAMAGES, CLAIMS OR COSTS WHATSOEVER OR ANY CONSEQUENTIAL, INDIRECT OR INCIDENTAL DAMAGES, OR ANY LOST PROFITS OR LOST SAVINGS, EVEN IF AN ADOBE REPRESENTATIVE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS, DAMAGES, CLAIMS OR COSTS OR FOR ANY CLAIM BY ANY THIRD PARTY. THE FOREGOING LIMITATIONS AND EXCLUSIONS APPLY TO THE EXTENT PERMITTED BY APPLICABLE LAW IN SUBLICENSEE’S JURISDICTION. ADOBE’S AGGREGATE LIABILITY AND THAT OF ITS SUPPLIERS UNDER OR IN CONNECTION WITH THIS AGREEMENT SHALL BE LIMITED TO ONE THOUSAND DOLLARS (US$1,000). Nothing contained in this Agreement limits Adobe’s liability to Sublicensee in the event of death or personal injury resulting from Adobe’s negligence or for the tort of deceit (fraud). Adobe is acting on behalf of its suppliers for the purpose of disclaiming, excluding and/or limiting obligations, warranties and liability as provided in this Agreement, but in no other respects and for no other purpose. </p> <p> 16. Content Protection Terms </p> <p> (a) Definitions. </p> <p> “Compliance and Robustness Rules” means the document setting forth compliance and robustness rules for the Adobe Software located at http://www.adobe.com/mobile/licensees, or a successor website thereto. </p> <p> “Content Protection Functions” means those aspects of the Adobe Software that are designed to ensure compliance with the Compliance and Robustness Rules, and to prevent playback, copying, modification, redistribution or other actions with respect to digital content distributed for consumption by users of the Adobe Software when such actions are not authorised by the owners of such digital content or its licensed distributors. </p> <p> “Content Protection Code” means code within certain designated versions of the Adobe Software that enables certain Content Protection Functions. </p> <p> “Key” means a cryptographic value contained in the Adobe Software for use in decrypting digital content. </p> <p> (b) Licence Restrictions. Sublicensee’s right to exercise the licences with respect to the Adobe Software is subject to the following additional restrictions and obligations. Sublicensee will ensure that Sublicensee’s customers comply with these restrictions and obligations to the same extent imposed on Sublicensee with respect to the Adobe Software; any failure by Sublicensee’s customers to comply with these additional restrictions and obligations shall be treated as a material breach by Sublicensee. </p> <p> b.1. (b.1) The Sublicensee and customers may only distribute the Adobe Software that meets the Robustness and Compliance Rules as so confirmed by the Sublicensee during the verification process described above in the Adobe Terms. </p> <p> b.2. Sublicensee shall not (i) circumvent the Content Protection Functions of either the Adobe Software or any related Adobe Software that is used to encrypt or decrypt digital content for authorised consumption by users of the Adobe Software or (ii) develop or distribute products that are designed to circumvent the Content Protection Functions of either the Adobe Software or any Adobe Software that is used to encrypt or decrypt digital content for authorised consumption by users of the Adobe Software. </p> <p> (c) The Keys are hereby designated as Adobe’s Confidential Information, and Sublicensee will, with respect to the Keys, adhere to Adobe’s Source Code Handling Procedure (to be provided by Adobe upon request). </p> <p> (d) Injunctive Relief. Sublicensee agrees that a breach of this Agreement may compromise the Content Protection Functions of the Adobe Software and may cause unique and lasting harm to the interests of Adobe and owners of digital content that rely on such Content Protection Functions, and that monetary damages may be inadequate to compensate fully for such harm. Therefore, Sublicensee further agrees that Adobe may be entitled to seek injunctive relief to prevent or limit the harm caused by any such breach, in addition to monetary damages. </p> <p> 17. Intended Third-party Beneficiary. Adobe Systems Incorporated and Adobe Software Ireland Limited are the intended third-party beneficiaries of Google’s agreement with Sublicensee with respect to the Adobe Software, including but not limited to, the Adobe Terms. Sublicensee agrees, notwithstanding anything to the contrary in its agreement with Google, that Google may disclose Sublicensee’s identity to Adobe and certify in writing that Sublicensee has entered into a licence agreement with Google that includes the Adobe Terms. Sublicensee must have an agreement with each of its licensees and if such licensees are allowed to redistribute the Adobe Software, such agreement will include the Adobe Terms. </p> </section> <p> Additionally, your use of certain components of Chrome OS is subject to the following terms: </p> <section> <p> <strong> MPEG-4 </strong> </p> <p> THIS PRODUCT IS LICENSED UNDER THE MPEG-4 VISUAL PATENT PORTFOLIO LICENCE FOR THE PERSONAL AND NON-COMMERCIAL USE OF A CONSUMER FOR (i) ENCODING VIDEO IN COMPLIANCE WITH THE MPEG-4 VISUAL STANDARD ('MPEG-4 VIDEO') AND/OR (ii) DECODING MPEG-4 VIDEO THAT WAS ENCODED BY A CONSUMER ENGAGED IN A PERSONAL AND NON-COMMERCIAL ACTIVITY AND/OR WAS OBTAINED FROM A VIDEO PROVIDER LICENSED BY MPEG LA TO PROVIDE MPEG-4 VIDEO. NO LICENCE IS GRANTED OR SHALL BE IMPLIED FOR ANY OTHER USE. ADDITIONAL INFORMATION INCLUDING THAT RELATING TO PROMOTIONAL, INTERNAL AND COMMERCIAL USES AND LICENSING MAY BE OBTAINED FROM MPEG LA, LLC. SEE HTTP://WWW.MPEGLA.COM. </p> </section> </body> </html>
{ "pile_set_name": "Github" }
Glossary Stack notation: "<stack before> -- <stack after>". Rightmost is top of stack (TOS). For example, in "a b -- c d", b is TOS before, d is TOS after. "R:" means that the Return Stack is modified. "I:" prefix means "IMMEDIATE", that is, that this stack transformation is made at compile time. Word references (wordref): When we say we have a "word reference", it's a pointer to a word's *code link*. For example, the address that "' DUP" puts on the stack is a wordref, that is, a reference to the code link of the word DUP. PF: Parameter field. The area following the code link of a word. For example, "' H@ 1+" points to the PF of the word H@. (cont.)
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- """ USID utilities for performing randomized singular value decomposition and reconstructing results Created on Mon Mar 28 09:45:08 2016 @author: Suhas Somnath, Chris Smith """ from __future__ import division, print_function, absolute_import import time from multiprocessing import cpu_count import numpy as np from sklearn.utils import gen_batches from sklearn.utils.extmath import randomized_svd from sidpy.hdf.reg_ref import get_indices_for_region_ref, create_region_reference from sidpy.hdf.hdf_utils import get_attr, write_simple_attrs from sidpy.proc.comp_utils import get_available_memory from sidpy.base.string_utils import format_time from sidpy.hdf.dtype_utils import check_dtype, stack_real_to_target_dtype from pyUSID.processing.process import Process from .proc_utils import get_component_slice from pyUSID.io.hdf_utils import find_results_groups, copy_attributes, \ reshape_to_n_dims, write_main_dataset, create_results_group, \ create_indexed_group, find_dataset from pyUSID.io.write_utils import Dimension, calc_chunks from pyUSID import USIDataset import h5py from matplotlib import pyplot as plt from pyUSID.viz import plot_utils class SVD(Process): """ This class provides a file-wrapper around the :meth:`sklearn.utils.extmath.randomized_svd` function. In other words, it extracts and then reformats the data present in the provided :class:`pyUSID.USIDataset` object, performs the randomized SVD operation and writes the results back to the USID HDF5 file after formatting the results in an USID compliant manner. """ def __init__(self, h5_main, num_components=None, **kwargs): """ Perform the SVD decomposition on the selected dataset and write the results to h5 file. Parameters ---------- h5_main : :class:`pyUSID.USIDataset` object USID Main HDF5 dataset that will be decomposed num_components : int, optional Number of components to decompose h5_main into. Default None. h5_target_group : h5py.Group, optional. Default = None Location where to look for existing results and to place newly computed results. Use this kwarg if the results need to be written to a different HDF5 file. By default, this value is set to the parent group containing `h5_main` kwargs Arguments to be sent to Process """ super(SVD, self).__init__(h5_main, 'SVD', **kwargs) ''' Calculate the size of the main data in memory and compare to max_mem We use the minimum of the actual dtype's itemsize and float32 since we don't want to read it in yet and do the proper type conversions. ''' n_samples, n_features = h5_main.shape self.data_transform_func, is_complex, is_compound, n_features, type_mult = check_dtype(h5_main) if num_components is None: num_components = min(n_samples, n_features) else: num_components = min(n_samples, n_features, num_components) self.num_components = num_components # Check that we can actually compute the SVD with the selected number of components self._check_available_mem() self.parms_dict = {'num_components': num_components} self.duplicate_h5_groups, self.partial_h5_groups = self._check_for_duplicates() # supercharge h5_main! self.h5_main = USIDataset(self.h5_main) self.__u = None self.__v = None self.__s = None def test(self, override=False): """ Applies randomised VD to the dataset. This function does NOT write results to the hdf5 file. Call compute() to write to the file. Handles complex, compound datasets such that the V matrix is of the same data-type as the input matrix. Parameters ---------- override : bool, optional. default = False Set to true to recompute results if prior results are available. Else, returns existing results Returns ------- U : :class:`numpy.ndarray` Abundance matrix S : :class:`numpy.ndarray` variance vector V : :class:`numpy.ndarray` eigenvector matrix """ ''' Check if a number of compnents has been set and ensure that the number is less than the minimum axis length of the data. If both conditions are met, use fsvd. If not use the regular svd. C.Smith -- We might need to put a lower limit on num_comps in the future. I don't know enough about svd to be sure. ''' if not override: if isinstance(self.duplicate_h5_groups, list) and len(self.duplicate_h5_groups) > 0: self.h5_results_grp = self.duplicate_h5_groups[-1] print('Returning previously computed results from: {}'.format(self.h5_results_grp.name)) print('set the "override" flag to True to recompute results') return reshape_to_n_dims(self.h5_results_grp['U'])[0], self.h5_results_grp['S'][()], \ reshape_to_n_dims(self.h5_results_grp['V'])[0] self.h5_results_grp = None t1 = time.time() self.__u, self.__s, self.__v = randomized_svd(self.data_transform_func(self.h5_main), self.num_components, n_iter=3) self.__v = stack_real_to_target_dtype(self.__v, self.h5_main.dtype) print('Took {} to compute randomized SVD'.format(format_time(time.time() - t1))) u_mat, success = reshape_to_n_dims(self.__u, h5_pos=self.h5_main.h5_pos_inds, h5_spec=np.expand_dims(np.arange(self.__u.shape[1]), axis=0)) if not success: raise ValueError('Could not reshape U to N-Dimensional dataset! Error:' + success) v_mat, success = reshape_to_n_dims(self.__v, h5_pos=np.expand_dims(np.arange(self.__u.shape[1]), axis=1), h5_spec=self.h5_main.h5_spec_inds) if not success: raise ValueError('Could not reshape V to N-Dimensional dataset! Error:' + success) return u_mat, self.__s, v_mat def compute(self, override=False): """ Computes SVD (by calling test_on_subset() if it has not already been called) and writes results to file. Consider calling test() to check results before writing to file. Results are deleted from memory upon writing to the HDF5 file Parameters ---------- override : bool, optional. default = False Set to true to recompute results if prior results are available. Else, returns existing results Returns ------- h5_results_grp : :class:`h5py.Group` object HDF5 Group containing all the results """ if self.__u is None and self.__v is None and self.__s is None: self.test(override=override) if self.h5_results_grp is None: self._write_results_chunk() self.delete_results() h5_group = self.h5_results_grp return h5_group def delete_results(self): """ Deletes results from memory. """ del self.__u, self.__s, self.__v self.__u = None self.__v = None self.__s = None def _write_results_chunk(self): """ Writes the provided SVD results to file Parameters ---------- """ comp_dim = Dimension('Principal Component', 'a. u.', len(self.__s)) h5_svd_group = create_results_group(self.h5_main, self.process_name, h5_parent_group=self._h5_target_group) self.h5_results_grp = h5_svd_group self._write_source_dset_provenance() write_simple_attrs(h5_svd_group, self.parms_dict) write_simple_attrs(h5_svd_group, {'svd_method': 'sklearn-randomized'}) h5_u = write_main_dataset(h5_svd_group, np.float32(self.__u), 'U', 'Abundance', 'a.u.', None, comp_dim, h5_pos_inds=self.h5_main.h5_pos_inds, h5_pos_vals=self.h5_main.h5_pos_vals, dtype=np.float32, chunks=calc_chunks(self.__u.shape, np.float32(0).itemsize)) # print(get_attr(self.h5_main, 'quantity')[0]) h5_v = write_main_dataset(h5_svd_group, self.__v, 'V', get_attr(self.h5_main, 'quantity')[0], 'a.u.', comp_dim, None, h5_spec_inds=self.h5_main.h5_spec_inds, h5_spec_vals=self.h5_main.h5_spec_vals, chunks=calc_chunks(self.__v.shape, self.h5_main.dtype.itemsize)) # No point making this 1D dataset a main dataset h5_s = h5_svd_group.create_dataset('S', data=np.float32(self.__s)) ''' Check h5_main for plot group references. Copy them into V if they exist ''' for key in self.h5_main.attrs.keys(): if '_Plot_Group' not in key: continue ref_inds = get_indices_for_region_ref(self.h5_main, self.h5_main.attrs[key], return_method='corners') ref_inds = ref_inds.reshape([-1, 2, 2]) ref_inds[:, 1, 0] = h5_v.shape[0] - 1 svd_ref = create_region_reference(h5_v, ref_inds) h5_v.attrs[key] = svd_ref # Marking completion: self._status_dset_name = 'completed_positions' self._h5_status_dset = h5_svd_group.create_dataset(self._status_dset_name, data=np.ones(self.h5_main.shape[0], dtype=np.uint8)) # keeping legacy option: h5_svd_group.attrs['last_pixel'] = self.h5_main.shape[0] def _check_available_mem(self): """ Check that there is enough memory to perform the SVD decomposition. Returns ------- sufficient_mem : bool True is enough memory found, False otherwise. """ if self.verbose: print('Checking memory availability.') n_samples, n_features = self.h5_main.shape s_mem_per_comp = np.float32(0).itemsize u_mem_per_comp = np.float32(0).itemsize * n_samples v_mem_per_comp = self.h5_main.dtype.itemsize * n_features mem_per_comp = s_mem_per_comp + u_mem_per_comp + v_mem_per_comp max_mem = get_available_memory() avail_mem = 0.75 * max_mem free_mem = avail_mem - self.h5_main.__sizeof__() if free_mem <= 0: error_message = 'Cannot load main dataset into memory.\n' + \ 'Available memory is {}. Dataset needs {}.'.format(avail_mem, self.h5_main.__sizeof__()) raise MemoryError(error_message) if self.verbose: print('Memory available for SVD is {}.'.format(free_mem)) print('Memory needed per component is {}.'.format(mem_per_comp)) cant_svd = (free_mem - self.num_components * mem_per_comp) <= 0 if cant_svd: max_comps = np.floor(free_mem / mem_per_comp, dtype=int) error_message = 'Not enough free memory for performing SVD with requested number of parameters.\n' + \ 'Maximum possible parameters is {}.'.format(max_comps) raise MemoryError(error_message) ############################################################################### def simplified_kpca(kpca, source_data): """ Performs kernel PCA on the provided dataset and returns the familiar eigenvector, eigenvalue, and scree matrices. Note that the positions in the eigenvalues may need to be transposed Parameters ---------- kpca : KernelPCA object configured Kernel PCA object ready to perform analysis source_data : 2D numpy array Data arranged as [iteration, features] example - [position, time] Returns ------- eigenvalues : 2D numpy array Eigenvalues in the original space arranged as [component,iteration] scree : 1D numpy array S component eigenvector : 2D numpy array Eigenvectors in the original space arranged as [component,features] """ X_kpca = kpca.fit(source_data.T) eigenvectors = X_kpca.alphas_.T eigenvalues = X_kpca.fit_transform(source_data) # kpca_explained_variance = np.var(kpca.fit_transform(source_data), axis=0) # information_content = kpca_explained_variance / np.sum(kpca_explained_variance) scree = kpca.lambdas_ return eigenvalues, scree, eigenvectors def rebuild_svd(h5_main, components=None, cores=None, max_RAM_mb=1024): """ Rebuild the Image from the SVD results on the windows Optionally, only use components less than n_comp. Parameters ---------- h5_main : hdf5 Dataset dataset which SVD was performed on components : {int, iterable of int, slice} optional Defines which components to keep Default - None, all components kept Input Types integer : Components less than the input will be kept length 2 iterable of integers : Integers define start and stop of component slice to retain other iterable of integers or slice : Selection of component indices to retain cores : int, optional How many cores should be used to rebuild Default - None, all but 2 cores will be used, min 1 max_RAM_mb : int, optional Maximum ammount of memory to use when rebuilding, in Mb. Default - 1024Mb Returns ------- rebuilt_data : HDF5 Dataset the rebuilt dataset """ comp_slice, num_comps = get_component_slice(components, total_components=h5_main.shape[1]) if isinstance(comp_slice, np.ndarray): comp_slice = list(comp_slice) dset_name = h5_main.name.split('/')[-1] # Ensuring that at least one core is available for use / 2 cores are available for other use max_cores = max(1, cpu_count() - 2) # print('max_cores',max_cores) if cores is not None: cores = min(round(abs(cores)), max_cores) else: cores = max_cores max_memory = min(max_RAM_mb * 1024 ** 2, 0.75 * get_available_memory()) if cores != 1: max_memory = int(max_memory / 2) ''' Get the handles for the SVD results ''' try: h5_svd_group = find_results_groups(h5_main, 'SVD')[-1] h5_S = h5_svd_group['S'] h5_U = h5_svd_group['U'] h5_V = h5_svd_group['V'] except KeyError: raise KeyError('SVD Results for {dset} were not found.'.format(dset=dset_name)) except: raise func, is_complex, is_compound, n_features, type_mult = check_dtype(h5_V) ''' Calculate the size of a single batch that will fit in the available memory ''' n_comps = h5_S[comp_slice].size mem_per_pix = (h5_U.dtype.itemsize + h5_V.dtype.itemsize * h5_V.shape[1]) * n_comps fixed_mem = h5_main.size * h5_main.dtype.itemsize if cores is None: free_mem = max_memory - fixed_mem else: free_mem = max_memory * 2 - fixed_mem batch_size = int(round(float(free_mem) / mem_per_pix)) batch_slices = gen_batches(h5_U.shape[0], batch_size) print('Reconstructing in batches of {} positions.'.format(batch_size)) print('Batchs should be {} Mb each.'.format(mem_per_pix * batch_size / 1024.0 ** 2)) ''' Loop over all batches. ''' ds_V = np.dot(np.diag(h5_S[comp_slice]), func(h5_V[comp_slice, :])) rebuild = np.zeros((h5_main.shape[0], ds_V.shape[1])) for ibatch, batch in enumerate(batch_slices): rebuild[batch, :] += np.dot(h5_U[batch, comp_slice], ds_V) rebuild = stack_real_to_target_dtype(rebuild, h5_V.dtype) print('Completed reconstruction of data from SVD results. Writing to file.') ''' Create the Group and dataset to hold the rebuild data ''' rebuilt_grp = create_indexed_group(h5_svd_group, 'Rebuilt_Data') h5_rebuilt = write_main_dataset(rebuilt_grp, rebuild, 'Rebuilt_Data', get_attr(h5_main, 'quantity'), get_attr(h5_main, 'units'), None, None, h5_pos_inds=h5_main.h5_pos_inds, h5_pos_vals=h5_main.h5_pos_vals, h5_spec_inds=h5_main.h5_spec_inds, h5_spec_vals=h5_main.h5_spec_vals, chunks=h5_main.chunks, compression=h5_main.compression) if isinstance(comp_slice, slice): rebuilt_grp.attrs['components_used'] = '{}-{}'.format(comp_slice.start, comp_slice.stop) else: rebuilt_grp.attrs['components_used'] = components copy_attributes(h5_main, h5_rebuilt, skip_refs=False) h5_main.file.flush() print('Done writing reconstructed data to file.') return h5_rebuilt def plot_svd(h5_main, savefig=False, num_plots = 16, **kwargs): ''' Replots the SVD showing the skree, abundance maps, and eigenvectors. If h5_main is a Dataset, it will default to the most recent SVD group from that Dataset. If h5_main is the results group, then it will plot the values for that group. Parameters ---------- h5_main : USIDataset or h5py Dataset or h5py Group savefig : bool, optional Saves the figures to disk with some default names num_plots : int Default number of eigenvectors and abundance plots to show kwargs : dict, optional keyword arguments for svd filtering Returns ------- None ''' if isinstance(h5_main, h5py.Group): _U = find_dataset(h5_main, 'U')[-1] _V = find_dataset(h5_main, 'V')[-1] units = 'arbitrary (a.u.)' h5_spec_vals = np.arange(_V.shape[1]) h5_svd_group = _U.parent else: h5_svd_group = find_results_groups(h5_main, 'SVD')[-1] units = h5_main.attrs['quantity'] h5_spec_vals = h5_main.get_spec_values('Time') h5_U = h5_svd_group['U'] h5_V = h5_svd_group['V'] h5_S = h5_svd_group['S'] _U = USIDataset(h5_U) [num_rows, num_cols] = _U.pos_dim_sizes abun_maps = np.reshape(h5_U[:,:16], (num_rows, num_cols,-1)) eigen_vecs = h5_V[:16, :] skree_sum = np.zeros(h5_S.shape) for i in range(h5_S.shape[0]): skree_sum[i] = np.sum(h5_S[:i])/np.sum(h5_S) plt.figure() plt.plot(skree_sum, 'bo') plt.title('Cumulative Variance') plt.xlabel('Total Components') plt.ylabel('Total variance ratio (a.u.)') if savefig: plt.savefig('Cumulative_variance_plot.png') fig_skree, axes = plot_utils.plot_scree(h5_S, title='Scree plot') fig_skree.tight_layout() if savefig: plt.savefig('Scree_plot.png') fig_abun, axes = plot_utils.plot_map_stack(abun_maps, num_comps=num_plots, title='SVD Abundance Maps', color_bar_mode='single', cmap='inferno', reverse_dims=True, fig_mult=(3.5,3.5), facecolor='white', **kwargs) fig_abun.tight_layout() if savefig: plt.savefig('Abundance_maps.png') fig_eigvec, axes = plot_utils.plot_curves(h5_spec_vals*1e3, eigen_vecs, use_rainbow_plots=False, x_label='Time (ms)', y_label=units, num_plots=num_plots, subtitle_prefix='Component', title='SVD Eigenvectors', evenly_spaced=False, **kwargs) fig_eigvec.tight_layout() if savefig: plt.savefig('Eigenvectors.png') return
{ "pile_set_name": "Github" }
pycodestyle is a tool to check your Python code against some of the style conventions in PEP 8. This package used to be called pep8 but was renamed to pycodestyle to reduce confusion WWW: https://pypi.org/project/pycodestyle/ WWW: https://pycodestyle.readthedocs.io/en/latest/
{ "pile_set_name": "Github" }
# T1202 - Indirect Command Execution ## [Description from ATT&CK](https://attack.mitre.org/wiki/Technique/T1202) <blockquote>Various Windows utilities may be used to execute commands, possibly without invoking [cmd](https://attack.mitre.org/software/S0106). For example, [Forfiles](https://attack.mitre.org/software/S0193), the Program Compatibility Assistant (pcalua.exe), components of the Windows Subsystem for Linux (WSL), as well as other utilities may invoke the execution of programs and commands from a [Command-Line Interface](https://attack.mitre.org/techniques/T1059), Run window, or via scripts. (Citation: VectorSec ForFiles Aug 2017) (Citation: Evi1cg Forfiles Nov 2017) Adversaries may abuse these features for [Defense Evasion](https://attack.mitre.org/tactics/TA0005), specifically to perform arbitrary execution while subverting detections and/or mitigation controls (such as Group Policy) that limit/prevent the usage of [cmd](https://attack.mitre.org/software/S0106) or file extensions more commonly associated with malicious payloads.</blockquote> ## Atomic Tests - [Atomic Test #1 - Indirect Command Execution - pcalua.exe](#atomic-test-1---indirect-command-execution---pcaluaexe) - [Atomic Test #2 - Indirect Command Execution - forfiles.exe](#atomic-test-2---indirect-command-execution---forfilesexe) <br/> ## Atomic Test #1 - Indirect Command Execution - pcalua.exe The Program Compatibility Assistant (pcalua.exe) may invoke the execution of programs and commands from a Command-Line Interface. [Reference](https://twitter.com/KyleHanslovan/status/912659279806640128) **Supported Platforms:** Windows #### Inputs | Name | Description | Type | Default Value | |------|-------------|------|---------------| | process | Process to execute | string | calc.exe| | payload_path | Path to payload | path | c:\temp\payload.dll| | payload_cpl_path | Path to payload | path | C:\Windows\system32\javacpl.cpl -c Java| #### Run it with `command_prompt`! ``` pcalua.exe -a #{process} pcalua.exe -a #{payload_path} pcalua.exe -a #{payload_cpl_path} ``` <br/> <br/> ## Atomic Test #2 - Indirect Command Execution - forfiles.exe forfiles.exe may invoke the execution of programs and commands from a Command-Line Interface. [Reference](https://github.com/api0cradle/LOLBAS/blob/master/OSBinaries/Forfiles.md) "This is basically saying for each occurrence of notepad.exe in c:\windows\system32 run calc.exe" **Supported Platforms:** Windows #### Inputs | Name | Description | Type | Default Value | |------|-------------|------|---------------| | process | Process to execute | string | calc.exe| #### Run it with `command_prompt`! ``` forfiles /p c:\windows\system32 /m notepad.exe /c #{process} forfiles /p c:\windows\system32 /m notepad.exe /c "c:\folder\normal.dll:evil.exe" ``` <br/>
{ "pile_set_name": "Github" }
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ("migrations", "0001_initial"), ] operations = [ migrations.AddField( model_name='task', name='projects', field=models.ManyToManyField(to='Project'), ), ]
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <dependenciesRoot> <dependency className="jetbrains.mps.lang.smodel.query.test.migrationTest.MigrateScopes"> <classNode dependClassName="java.lang.Override" /> <classNode dependClassName="java.lang.Throwable" /> <classNode dependClassName="java.util.ArrayList" /> <classNode dependClassName="java.util.Collection" /> <classNode dependClassName="jetbrains.mps.MPSLaunch" /> <classNode dependClassName="jetbrains.mps.internal.collections.runtime.ListSequence" /> <classNode dependClassName="jetbrains.mps.lang.migration.runtime.base.MigrationScript" /> <classNode dependClassName="jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations" /> <classNode dependClassName="jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations" /> <classNode dependClassName="jetbrains.mps.lang.smodel.query.migration.MigrateScopes" /> <classNode dependClassName="jetbrains.mps.lang.test.runtime.BaseMigrationTestBody" /> <classNode dependClassName="jetbrains.mps.lang.test.runtime.RunWithCommand" /> <classNode dependClassName="jetbrains.mps.lang.test.runtime.TestParametersCache" /> <classNode dependClassName="jetbrains.mps.lang.test.runtime.TransformationTest" /> <classNode dependClassName="jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory" /> <classNode dependClassName="org.jetbrains.mps.openapi.language.SConcept" /> <classNode dependClassName="org.jetbrains.mps.openapi.language.SContainmentLink" /> <classNode dependClassName="org.jetbrains.mps.openapi.model.SNode" /> <classNode dependClassName="org.junit.ClassRule" /> <classNode dependClassName="org.junit.Rule" /> <classNode dependClassName="org.junit.Test" /> <classNode extendsClassName="jetbrains.mps.lang.test.runtime.BaseTransformationTest" /> </dependency> </dependenciesRoot>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8" ?> <ConfirmClaimResponse> <Signature></Signature> <Claim> <Type>OWNERSHIP</Type> <Key>+5561988887777</Key> <KeyType>PHONE</KeyType> <ClaimerAccount> <Participant>12345678</Participant> <Branch>0001</Branch> <AccountNumber>0007654321</AccountNumber> <AccountType>CACC</AccountType> <OpeningDate>2010-01-10T03:00:00Z</OpeningDate> </ClaimerAccount> <Claimer> <Type>NATURAL_PERSON</Type> <TaxIdNumber>11122233300</TaxIdNumber> <Name>João Silva</Name> </Claimer> <DonorParticipant>87654321</DonorParticipant> <Id>123e4567-e89b-12d3-a456-426655440000</Id> <Status>CONFIRMED</Status> <ResolutionPeriodEnd>2020-01-17T10:00:00Z</ResolutionPeriodEnd> <CompletionPeriodEnd>2020-01-17T10:00:00Z</CompletionPeriodEnd> <LastModified>2020-01-10T10:00:00Z</LastModified> <ConfirmReason>USER_REQUESTED</ConfirmReason> </Claim> </ConfirmClaimResponse>
{ "pile_set_name": "Github" }
pub mod command; mod options; pub use command::Command as Table;
{ "pile_set_name": "Github" }
Sizes of pthreads-win32 structs ------------------------------- pthread_t 8 ptw32_thread_t 96 pthread_attr_t_ 28 sem_t_ 12 pthread_mutex_t_ 28 pthread_mutexattr_t_ 12 pthread_spinlock_t_ 8 pthread_barrier_t_ 36 pthread_barrierattr_t_ 4 pthread_key_t_ 16 pthread_cond_t_ 32 pthread_condattr_t_ 4 pthread_rwlock_t_ 28 pthread_rwlockattr_t_ 4 pthread_once_t_ 16 ptw32_cleanup_t 12 ptw32_mcs_node_t_ 16 sched_param 4 -------------------------------
{ "pile_set_name": "Github" }
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ var gTestfile = 'regress-352797-02.js'; //----------------------------------------------------------------------------- var BUGNUMBER = 352797; var summary = 'Do not assert: OBJ_GET_CLASS(cx, obj) == &js_BlockClass'; var actual = 'No Crash'; var expect = /No Crash/; //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function test() { enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); try { (function() { let (x = eval.call(<x/>.(1), "")) {} })(); } catch(ex) { printStatus('Note eval can no longer be called directly'); expect = /EvalError: (f|F)unction (eval|"eval") must be called directly, and not by way of a function of another name/; actual = ex + ''; } reportMatch(expect, actual, summary); exitFunc ('test'); }
{ "pile_set_name": "Github" }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package file import ( "github.com/zouyx/agollo/v4/env/config" ) //FileHandler 备份文件读写 type FileHandler interface { WriteConfigFile(config *config.ApolloConfig, configPath string) error GetConfigFile(configDir string, appID string, namespace string) string LoadConfigFile(configDir string, appID string, namespace string) (*config.ApolloConfig, error) }
{ "pile_set_name": "Github" }
#!/bin/sh # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # runTests.sh # curdir=`pwd` cd ../../common . ./libpkix_init.sh > /dev/null cd ${curdir} numtests=0 passed=0 testunit=STORE ########## # main ########## ParseArgs $* RunTests <<EOF pkixutil test_store genericCertStore rev_data/crlchecker ${HOSTDIR} EOF totalErrors=$? html_msg ${totalErrors} 0 "&nbsp;&nbsp;&nbsp;${testunit}: passed ${passed} of ${numtests} tests" exit ${totalErrors}
{ "pile_set_name": "Github" }
/* * Hibernate Validator, declare and validate application constraints * * License: Apache License, Version 2.0 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>. */ package org.hibernate.validator.internal.constraintvalidators.bv.time.past; import java.time.Clock; import java.time.OffsetDateTime; /** * Check that the {@code java.time.OffsetDateTime} passed is in the past. * * @author Khalid Alqinyah * @author Guillaume Smet */ public class PastValidatorForOffsetDateTime extends AbstractPastJavaTimeValidator<OffsetDateTime> { @Override protected OffsetDateTime getReferenceValue(Clock reference) { return OffsetDateTime.now( reference ); } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">iPhoneSimulator</Platform> <ProductVersion>8.0.30703</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{85D69336-9BF4-4B53-BE5D-4006F4042465}</ProjectGuid> <ProjectTypeGuids>{FEACFBD2-3405-455C-9665-78FE426C6842};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <OutputType>Exe</OutputType> <RootNamespace>ButtonLogger.iOS</RootNamespace> <IPhoneResourcePrefix>Resources</IPhoneResourcePrefix> <AssemblyName>ButtonLoggeriOS</AssemblyName> <NuGetPackageImportStamp /> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|iPhoneSimulator' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\iPhoneSimulator\Debug</OutputPath> <DefineConstants>DEBUG</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <ConsolePause>false</ConsolePause> <MtouchArch>x86_64</MtouchArch> <MtouchLink>None</MtouchLink> <MtouchDebug>true</MtouchDebug> <CodesignEntitlements /> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|iPhoneSimulator' "> <DebugType>none</DebugType> <Optimize>true</Optimize> <OutputPath>bin\iPhoneSimulator\Release</OutputPath> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <MtouchLink>None</MtouchLink> <MtouchArch>x86_64</MtouchArch> <ConsolePause>false</ConsolePause> <CodesignEntitlements /> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|iPhone' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\iPhone\Debug</OutputPath> <DefineConstants>DEBUG</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <ConsolePause>false</ConsolePause> <MtouchArch>ARM64</MtouchArch> <CodesignKey>iPhone Developer</CodesignKey> <MtouchDebug>true</MtouchDebug> <CodesignEntitlements>Entitlements.plist</CodesignEntitlements> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|iPhone' "> <DebugType>none</DebugType> <Optimize>true</Optimize> <OutputPath>bin\iPhone\Release</OutputPath> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <MtouchArch>ARM64</MtouchArch> <ConsolePause>false</ConsolePause> <CodesignKey>iPhone Developer</CodesignKey> <CodesignEntitlements>Entitlements.plist</CodesignEntitlements> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Ad-Hoc|iPhone' "> <DebugType>none</DebugType> <Optimize>True</Optimize> <OutputPath>bin\iPhone\Ad-Hoc</OutputPath> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <ConsolePause>False</ConsolePause> <MtouchArch>ARM64</MtouchArch> <BuildIpa>True</BuildIpa> <CodesignProvision>Automatic:AdHoc</CodesignProvision> <CodesignKey>iPhone Distribution</CodesignKey> <CodesignEntitlements>Entitlements.plist</CodesignEntitlements> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'AppStore|iPhone' "> <DebugType>none</DebugType> <Optimize>True</Optimize> <OutputPath>bin\iPhone\AppStore</OutputPath> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <ConsolePause>False</ConsolePause> <MtouchArch>ARM64</MtouchArch> <CodesignProvision>Automatic:AppStore</CodesignProvision> <CodesignKey>iPhone Distribution</CodesignKey> <CodesignEntitlements>Entitlements.plist</CodesignEntitlements> </PropertyGroup> <ItemGroup> <PackageReference Include="Xamarin.Forms" Version="3.1.0.637273" /> </ItemGroup> <ItemGroup> <Compile Include="Main.cs" /> <Compile Include="AppDelegate.cs" /> <None Include="Entitlements.plist" /> <None Include="Info.plist" /> <Compile Include="Properties\AssemblyInfo.cs" /> <ITunesArtwork Include="iTunesArtwork" /> <ITunesArtwork Include="iTunesArtwork@2x" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\ButtonLogger\ButtonLogger.csproj"> <Name>ButtonLogger</Name> </ProjectReference> </ItemGroup> <ItemGroup> <BundleResource Include="Resources\Default-568h%402x.png" /> <BundleResource Include="Resources\Default-Portrait.png" /> <BundleResource Include="Resources\Default-Portrait%402x.png" /> <BundleResource Include="Resources\Default.png" /> <BundleResource Include="Resources\Default%402x.png" /> <BundleResource Include="Resources\Icon-60%402x.png" /> <BundleResource Include="Resources\Icon-60%403x.png" /> <BundleResource Include="Resources\Icon-76.png" /> <BundleResource Include="Resources\Icon-76%402x.png" /> <BundleResource Include="Resources\Icon-Small-40.png" /> <BundleResource Include="Resources\Icon-Small-40%402x.png" /> <BundleResource Include="Resources\Icon-Small-40%403x.png" /> <BundleResource Include="Resources\Icon-Small.png" /> <BundleResource Include="Resources\Icon-Small%402x.png" /> <BundleResource Include="Resources\Icon-Small%403x.png" /> <InterfaceDefinition Include="Resources\LaunchScreen.storyboard" /> </ItemGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Xml" /> <Reference Include="System.Core" /> <Reference Include="Xamarin.iOS" /> </ItemGroup> <Import Project="$(MSBuildExtensionsPath)\Xamarin\iOS\Xamarin.iOS.CSharp.targets" /> <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild"> <PropertyGroup /> </Target> </Project>
{ "pile_set_name": "Github" }
import { Observable } from '../../Observable'; import { _switch } from '../../operator/switch'; Observable.prototype.switch = _switch; Observable.prototype._switch = _switch; //# sourceMappingURL=switch.js.map
{ "pile_set_name": "Github" }
/*! * Chai - getActual utility * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com> * MIT Licensed */ /** * ### .getActual(object, [actual]) * * Returns the `actual` value for an Assertion. * * @param {Object} object (constructed Assertion) * @param {Arguments} chai.Assertion.prototype.assert arguments * @namespace Utils * @name getActual */ module.exports = function getActual(obj, args) { return args.length > 4 ? args[4] : obj._obj; };
{ "pile_set_name": "Github" }
package net.sourceforge.vrapper.eclipse.keymap; import java.util.HashMap; import java.util.Queue; import net.sourceforge.vrapper.eclipse.commands.EclipseCommand; import net.sourceforge.vrapper.keymap.EmptyState; import net.sourceforge.vrapper.keymap.KeyMapInfo; import net.sourceforge.vrapper.keymap.State; import net.sourceforge.vrapper.log.VrapperLog; import net.sourceforge.vrapper.platform.PlatformSpecificStateProvider; import net.sourceforge.vrapper.vim.EditorAdaptor; import net.sourceforge.vrapper.vim.TextObjectProvider; import net.sourceforge.vrapper.vim.commands.Command; import net.sourceforge.vrapper.vim.commands.CommandExecutionException; import net.sourceforge.vrapper.vim.modes.AbstractVisualMode; import net.sourceforge.vrapper.vim.modes.ContentAssistMode; import net.sourceforge.vrapper.vim.modes.InsertMode; import net.sourceforge.vrapper.vim.modes.NormalMode; import net.sourceforge.vrapper.vim.modes.commandline.CommandLineMode; import net.sourceforge.vrapper.vim.modes.commandline.Evaluator; import net.sourceforge.vrapper.vim.modes.commandline.EvaluatorMapping; import org.eclipse.core.runtime.IConfigurationElement; /** * @see PlatformSpecificStateProvider */ public class AbstractEclipseSpecificStateProvider implements PlatformSpecificStateProvider, Comparable<AbstractEclipseSpecificStateProvider> { protected final HashMap<String, State<Command>> states = new HashMap<String, State<Command>>(); protected final HashMap<String, State<KeyMapInfo>> keyMaps = new HashMap<String, State<KeyMapInfo>>(); protected final EvaluatorMapping commands = new EvaluatorMapping(); protected int priority = 1; protected String name; protected TextObjectProvider textObjectProvider; protected AbstractEclipseSpecificStateProvider() { } public void configure(IConfigurationElement config) { try { String stringValue = config.getAttribute("priority"); name = config.getAttribute("name"); if (stringValue != null) priority = Integer.parseInt(stringValue); } catch (NumberFormatException e) { VrapperLog.error("wrong format of priority", e); } } @Override public final void initializeProvider(TextObjectProvider textObjProvider) { textObjectProvider = textObjProvider; states.put(NormalMode.NAME, normalModeBindings()); states.put(AbstractVisualMode.NAME, visualModeBindings()); keyMaps.put(NormalMode.NAME, normalModeKeymap()); keyMaps.put(AbstractVisualMode.NAME, visualModeKeymap()); states.put(InsertMode.NAME, insertModeBindings()); states.put(ContentAssistMode.NAME, contentAssistModeBindings()); } protected State<Command> normalModeBindings() { return EmptyState.getInstance(); } protected State<KeyMapInfo> normalModeKeymap() { return EmptyState.getInstance(); } protected State<Command> visualModeBindings() { return EmptyState.getInstance(); } protected State<KeyMapInfo> visualModeKeymap() { return EmptyState.getInstance(); } protected State<Command> insertModeBindings() { return EmptyState.getInstance(); } protected State<Command> contentAssistModeBindings() { return EmptyState.getInstance(); } protected static Command go(String where) { return new EclipseCommand("org.eclipse.ui.edit.text.goto." + where); } protected static Command cmd(String command) { return new EclipseCommand(command); } protected static EclipseCommand editText(String command) { return new EclipseCommand("org.eclipse.ui.edit.text." + command); } public String getName() { return name; } protected static class EclipseActionEvaluator implements Evaluator { private boolean force; private boolean async; protected EclipseActionEvaluator(boolean force, boolean async) { super(); this.force = force; this.async = async; } public Object evaluate(EditorAdaptor vim, Queue<String> command) throws CommandExecutionException { String name = command.poll(); if("!".equals(name)) { //we made a change where the '!' is separated from the command name //if that's the case (eclipseaction!), this isn't the name yet force = true; name = command.poll(); } String action = command.poll(); if (name != null && action != null) { CommandLineMode mode = (CommandLineMode) vim.getMode(CommandLineMode.NAME); mode.addCommand(name, new EclipseCommand(action, async), force); } return null; } } public String getFileType() { return "text"; } public State<Command> getState(String modeName) { return states.get(modeName); } public State<KeyMapInfo> getKeyMaps(String name) { return keyMaps.get(name); } public final EvaluatorMapping getCommands() { return commands; } protected void addFormatCommands(Command formatAll) { if (formatAll != null) { commands.add("formatall", formatAll); commands.add("format", formatAll); commands.add("fmt", formatAll); commands.add("fm", formatAll); } } public int compareTo(AbstractEclipseSpecificStateProvider o) { return -Integer.valueOf(priority).compareTo(Integer.valueOf(o.priority)); } }
{ "pile_set_name": "Github" }
/**************************************************************************** Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef __CCCOLLIDERDETECTOR_H__ #define __CCCOLLIDERDETECTOR_H__ #include "cocostudio/CCArmatureDefine.h" #include "cocostudio/CCDatas.h" #ifndef PT_RATIO #define PT_RATIO 32 #endif #if ENABLE_PHYSICS_CHIPMUNK_DETECT #include "chipmunk.h" #elif ENABLE_PHYSICS_BOX2D_DETECT #include "Box2D/Box2D.h" #endif namespace cocostudio { class Bone; /** * @js NA * @lua NA */ class ColliderFilter { public: virtual ~ColliderFilter() { } #if ENABLE_PHYSICS_BOX2D_DETECT public: ColliderFilter(uint16 categoryBits = 0x0001, uint16 maskBits = 0xFFFF, int16 groupIndex = 0); void updateShape(b2Fixture *fixture); virtual void setCategoryBits(uint16 categoryBits) { _categoryBits = categoryBits; } virtual uint16 getCategoryBits() const { return _categoryBits; } virtual void setMaskBits(uint16 maskBits) { _maskBits = maskBits; } virtual uint16 getMaskBits() const { return _maskBits; } virtual void setGroupIndex(int16 groupIndex) { _groupIndex = groupIndex; } virtual int16 getGroupIndex() const { return _groupIndex; } protected: uint16 _categoryBits; uint16 _maskBits; int16 _groupIndex; #elif ENABLE_PHYSICS_CHIPMUNK_DETECT public: ColliderFilter(cpCollisionType collisionType = 0, cpGroup group = 0); void updateShape(cpShape *shape); virtual void setCollisionType(cpCollisionType collisionType) { _collisionType = collisionType; } virtual cpCollisionType getCollisionType() const { return _collisionType; } virtual void setGroup(cpGroup group) { _group = group; } virtual cpGroup getGroup() const { return _group; } protected: cpCollisionType _collisionType; cpGroup _group; #endif }; class ColliderBody : public cocos2d::Object { public: ColliderBody(ContourData *contourData); ~ColliderBody(); inline ContourData *getContourData() { return _contourData; } #if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT void setColliderFilter(ColliderFilter *filter); ColliderFilter *getColliderFilter(); #endif #if ENABLE_PHYSICS_BOX2D_DETECT virtual void setB2Fixture(b2Fixture *fixture) { _fixture = fixture; } virtual b2Fixture *getB2Fixture() const { return _fixture; } #elif ENABLE_PHYSICS_CHIPMUNK_DETECT virtual void setShape(cpShape *shape) { _shape = shape; } virtual cpShape *getShape() const { return _shape; } #elif ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX virtual const std::vector<cocos2d::Point> &getCalculatedVertexList() const { return _calculatedVertexList; } #endif private: #if ENABLE_PHYSICS_BOX2D_DETECT b2Fixture *_fixture; ColliderFilter *_filter; #elif ENABLE_PHYSICS_CHIPMUNK_DETECT cpShape *_shape; ColliderFilter *_filter; #elif ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX std::vector<cocos2d::Point> _calculatedVertexList; #endif ContourData *_contourData; friend class ColliderDetector; }; /* * @brief ContourSprite used to draw the contour of the display * @js NA * @lua NA */ class ColliderDetector : public cocos2d::Object { public: static ColliderDetector *create(); static ColliderDetector *create(Bone *bone); public: /** * @js ctor */ ColliderDetector(); /** * @js NA * @lua NA */ ~ColliderDetector(void); virtual bool init(); virtual bool init(Bone *bone); void addContourData(ContourData *contourData); void addContourDataList(cocos2d::Vector<ContourData*> &contourDataList); void removeContourData(ContourData *contourData); void removeAll(); void updateTransform(kmMat4 &t); void setActive(bool active); bool getActive(); const cocos2d::Vector<ColliderBody*>& getColliderBodyList(); #if ENABLE_PHYSICS_BOX2D_DETECT || ENABLE_PHYSICS_CHIPMUNK_DETECT virtual void setColliderFilter(ColliderFilter *filter); virtual ColliderFilter *getColliderFilter(); #endif virtual void setBone(Bone *bone) { _bone = bone; } virtual Bone *getBone() const { return _bone; } #if ENABLE_PHYSICS_BOX2D_DETECT virtual void setBody(b2Body *body); virtual b2Body *getBody() const; #elif ENABLE_PHYSICS_CHIPMUNK_DETECT virtual void setBody(cpBody *body); virtual cpBody *getBody() const; #endif protected: cocos2d::Vector<ColliderBody*> _colliderBodyList; Bone *_bone; #if ENABLE_PHYSICS_BOX2D_DETECT b2Body *_body; ColliderFilter *_filter; #elif ENABLE_PHYSICS_CHIPMUNK_DETECT cpBody *_body; ColliderFilter *_filter; #endif protected: bool _active; }; } #endif /*__CCCOLLIDERDETECTOR_H__*/
{ "pile_set_name": "Github" }
1. Click "Init editors". 2. Expected: * Two inline editor should be created. * Elements used as editables should remain visible. * They should preserve `.custom-class` and `custom-attr="foo"`. * There should be floating toolbars with "Bold", "Italic", "Undo", "Redo", "Link" and "Unlink" buttons. 3. Scroll the webpage. 4. Expected: * Focused editor's toolbar should float around but always stick to editable. * Focused editor's toolbar should stick to the bottom of the editable if there's not enough space above. 5. Press <kbd>Alt+F10</kbd> when focusing the editor. 6. Expected: * Toolbar should gain focus. Editable should keep its styling. 7. Click "Destroy editors". 8. Expected: * Editors should be destroyed. * Element used as editables should remain visible. * They should preserve `.custom-class` and `custom-attr="foo"`. * Elements should contain its data (updated). * `.ck-body` regions should be removed from `<body>`. ## Notes: * You can play with: * `window.editables[ N ].isReadOnly`, * Changes to `window.editors[ name ].focusTracker.isFocused` should be logged to the console. * Features should work.
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title></title> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <link rel="stylesheet" type="text/css" href="../css/style.css" /> </head> <body> <div class="megasync-overlay"> <div class="megasync-content"> <div class="megasync-logo"></div> <div class="megasync-info">MEGAsync is being downloaded to your computer. Please install it as soon as the download has completed.<br />Once MEGAsync is running, your file will start downloading automatically.</div> <div class="megasync-dropdown"> <span>Please select your Linux Distro</span> </div> <div class="megasync-dropdown-list hidden"> <div class="megasync-dropdown-pad"> <div class="megasync-dropdown-scroll"> <div class="megasync-scr-pad"> <div class="megasync-dropdown-link centos">CentOS 7.0</div> <div class="megasync-dropdown-link debian">Debian 7.0</div> <div class="megasync-dropdown-link debian">Debian 8.0</div> <div class="megasync-dropdown-link elementary">Elementary OS Freya</div> <div class="megasync-dropdown-link fedora">Fedora 19</div> <div class="megasync-dropdown-link fedora">Fedora 20</div> <div class="megasync-dropdown-link fedora">Fedora 21</div> <div class="megasync-dropdown-link mint">Mint 17</div> <div class="megasync-dropdown-link opensuse">OpenSUSE 12.2</div> <div class="megasync-dropdown-link opensuse">OpenSUSE 12.3</div> <div class="megasync-dropdown-link opensuse">OpenSUSE 13.1</div> <div class="megasync-dropdown-link opensuse">OpenSUSE 13.2</div> <div class="megasync-dropdown-link redhat">Red Hat 7</div> <div class="megasync-dropdown-link ubuntu">Ubuntu 12.04</div> <div class="megasync-dropdown-link ubuntu">Ubuntu 12.10</div> <div class="megasync-dropdown-link ubuntu">Ubuntu 13.10</div> <div class="megasync-dropdown-link ubuntu">Ubuntu 14.04</div> <div class="megasync-dropdown-link ubuntu">Ubuntu 14.10</div> <div class="megasync-dropdown-link ubuntu">Ubuntu 15.04</div> </div> </div> <div class="megasync-list-arrow hidden"></div> </div> </div> <div class="megasync-table"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <th> </th> <th> <span class="globe">Web Browser</span> </th> <th> <span class="sync">MEGAsync</span> </th> </tr> <tr> <td> <span>Transfer Speed:</span> </td> <td> <span class="dots">Fast</span> </td> <td> <span class="tick">FASTER</span> </td> </tr> <tr> <td> <span>Resource Usage:</span> </td> <td> <span class="dots">Gluttonous</span> </td> <td> <span class="tick">LEAN & MEAN</span> </td> </tr> <tr> <td> <span>File Size:</span> </td> <td> <span class="dots">Limited</span> </td> <td> <span class="tick">UNLIMITED</span> </td> </tr> </table> </div> </div> </div> </body> </html>
{ "pile_set_name": "Github" }
@{ ViewData["Title"] = "Multi Column Responsive Dialog"; } @section ContentHeader { <h1>@ViewData["Title"]<small></small></h1> } <div class="alert alert-info alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <p>This sample demonstrates how to design responsive forms with multiple columns.</p> <p>A subclass of order dialog is styled with CSS to make it more compact.</p> <p>Open dialog then try resizing / maximizing dialog and window.</p> <p>This example uses flex box. See Responsive Dialog sample for more info.</p> <p style="text-align: right;"><b>Source Files:</b> @Html.AppSourceFile("Index.cshtml"), @Html.AppSourceFile("MultiColumnResponsiveDialog.ts") @Html.AppSourceFile("MultiColumnResponsiveGrid.ts") </p> </div> <div id="GridDiv"></div> <script type="text/javascript"> jQuery(function () { new Serene.BasicSamples.MultiColumnResponsiveGrid($('#GridDiv'), {}).init(); Q.initFullHeightGridPage($('#GridDiv')); }); </script>
{ "pile_set_name": "Github" }
// // TMQuiltViewController.m // TMQuiltView // // Created by Bruno Virlet on 7/20/12. // // Copyright (c) 2012 1000memories // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO // EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR // THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #import "TMQuiltViewController.h" #import "TMQuiltView.h" #import "TMQuiltViewCell.h" @interface TMQuiltViewController () <TMQuiltViewDataSource, TMQuiltViewDelegate> @end @implementation TMQuiltViewController @synthesize quiltView = _quiltView; - (void)dealloc { [_quiltView release], _quiltView = nil; [super dealloc]; } - (void)loadView { _quiltView = [[TMQuiltView alloc] initWithFrame:CGRectZero]; _quiltView.delegate = self; _quiltView.dataSource = self; _quiltView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; self.view = _quiltView; } - (void)viewDidLoad { [super viewDidLoad]; [self.quiltView reloadData]; } - (void)viewDidUnload { [super viewDidUnload]; self.quiltView = nil; } - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { [self.quiltView reloadData]; } #pragma mark - TMQuiltViewDataSource - (NSInteger)quiltViewNumberOfCells:(TMQuiltView *)quiltView { return 0; } - (TMQuiltViewCell *)quiltView:(TMQuiltView *)quiltView cellAtIndexPath:(NSIndexPath *)indexPath { TMQuiltViewCell *cell = [self.quiltView dequeueReusableCellWithReuseIdentifier:nil]; if (!cell) { cell = [[[TMQuiltViewCell alloc] initWithReuseIdentifier:nil] autorelease]; } return cell; } @end
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{44C36EB9-F502-41EC-B5B0-24364F7B935F}</ProjectGuid> <ProjectTypeGuids>{EFBA0AD7-5A72-4C68-AF49-83D382785DCF};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <OutputType>Library</OutputType> <RootNamespace>SampleBrowser.SfCarousel.Droid</RootNamespace> <AssemblyName>SampleBrowser.SfCarousel.Android</AssemblyName> <TargetFrameworkVersion>v9.0</TargetFrameworkVersion> <AndroidApplication>True</AndroidApplication> <AndroidResgenFile>Resources\Resource.designer.cs</AndroidResgenFile> <AndroidResgenClass>Resource</AndroidResgenClass> <AndroidManifest>Properties\AndroidManifest.xml</AndroidManifest> <MonoAndroidResourcePrefix>Resources</MonoAndroidResourcePrefix> <MonoAndroidAssetsPrefix>Assets</MonoAndroidAssetsPrefix> <NuGetPackageImportStamp> </NuGetPackageImportStamp> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug</OutputPath> <DefineConstants>DEBUG;</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <AndroidLinkMode>None</AndroidLinkMode> <AndroidEnableMultiDex>true</AndroidEnableMultiDex> <AndroidSupportedAbis>armeabi-v7a;x86</AndroidSupportedAbis> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release</OutputPath> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <AndroidManagedSymbols>true</AndroidManagedSymbols> <AndroidUseSharedRuntime>false</AndroidUseSharedRuntime> <AndroidSupportedAbis>armeabi-v7a;x86</AndroidSupportedAbis> <AotAssemblies>false</AotAssemblies> <EnableLLVM>false</EnableLLVM> <BundleAssemblies>false</BundleAssemblies> <AndroidEnableMultiDex>true</AndroidEnableMultiDex> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release-xml|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <OutputPath>bin\Release-xml\</OutputPath> <Optimize>true</Optimize> <DebugType>pdbonly</DebugType> <PlatformTarget>AnyCPU</PlatformTarget> <GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies> <ErrorReport>prompt</ErrorReport> <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet> <AotAssemblies>false</AotAssemblies> <EnableLLVM>false</EnableLLVM> <BundleAssemblies>false</BundleAssemblies> <AndroidEnableMultiDex>true</AndroidEnableMultiDex> <AndroidSupportedAbis>armeabi-v7a;x86</AndroidSupportedAbis> </PropertyGroup> <ItemGroup> <Reference Include="Mono.Android" /> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <PackageReference Include="SampleBrowser.Core"> <Version>18.2.0.44</Version> </PackageReference> <PackageReference Include="Syncfusion.Xamarin.Core"> <Version>18.2.0.44</Version> </PackageReference> <PackageReference Include="Syncfusion.Xamarin.SfCarousel"> <Version>18.2.0.44</Version> </PackageReference> <PackageReference Include="Syncfusion.Xamarin.DataSource"> <Version>18.2.0.44</Version> </PackageReference> <PackageReference Include="Syncfusion.Xamarin.GridCommon"> <Version>18.2.0.44</Version> </PackageReference> <PackageReference Include="Syncfusion.Xamarin.SfListView"> <Version>18.2.0.44</Version> </PackageReference> <PackageReference Include="Syncfusion.Xamarin.SfNumericUpDown"> <Version>18.2.0.44</Version> </PackageReference> <PackageReference Include="Xamarin.Android.Support.v17.Leanback"> <Version>28.0.0.1</Version> </PackageReference> <PackageReference Include="Xamarin.Android.Support.Design" Version="28.0.0.1" /> <PackageReference Include="Xamarin.Android.Support.v7.AppCompat" Version="28.0.0.1" /> <PackageReference Include="Xamarin.Android.Support.v4" Version="28.0.0.1" /> <PackageReference Include="Xamarin.Android.Support.v7.CardView" Version="28.0.0.1" /> <PackageReference Include="Xamarin.Android.Support.v7.MediaRouter" Version="28.0.0.1" /> <PackageReference Include="Xamarin.Forms"> <Version>3.6.0.344457</Version> </PackageReference> </ItemGroup> <ItemGroup> <Compile Include="MainActivity.cs" /> <Compile Include="Resources\Resource.Designer.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="SplashScreenActivity.cs" /> </ItemGroup> <ItemGroup> <AndroidAsset Include="Assets\carousel.ttf" /> <AndroidAsset Include="Assets\CarouselIcon.ttf" /> <None Include="Resources\AboutResources.txt" /> <None Include="Assets\AboutAssets.txt" /> </ItemGroup> <ItemGroup> <None Include="Properties\AndroidManifest.xml" /> </ItemGroup> <ItemGroup> <AndroidResource Include="Resources\layout\Tabbar.axml" /> <AndroidResource Include="Resources\layout\Toolbar.axml" /> <AndroidResource Include="Resources\values\styles.xml"> <SubType>Designer</SubType> </AndroidResource> </ItemGroup> <ItemGroup> <AndroidResource Include="..\..\Resources\Image\People\Person1.jpg"> <Link>Resources\drawable\Person1.jpg</Link> </AndroidResource> </ItemGroup> <ItemGroup> <AndroidResource Include="..\..\Resources\Image\People\Person2.jpg"> <Link>Resources\drawable\Person2.jpg</Link> </AndroidResource> </ItemGroup> <ItemGroup> <AndroidResource Include="..\..\Resources\Image\People\Person3.jpg"> <Link>Resources\drawable\Person3.jpg</Link> </AndroidResource> </ItemGroup> <ItemGroup> <AndroidResource Include="..\..\Resources\Image\People\Person4.jpg"> <Link>Resources\drawable\Person4.jpg</Link> </AndroidResource> </ItemGroup> <ItemGroup> <AndroidResource Include="..\..\Resources\Image\People\Person5.jpg"> <Link>Resources\drawable\Person5.jpg</Link> </AndroidResource> </ItemGroup> <ItemGroup> <AndroidResource Include="..\..\Resources\Image\Shapes\White_Circle.png"> <Link>Resources\drawable\White_Circle.png</Link> </AndroidResource> </ItemGroup> <ItemGroup> <AndroidResource Include="Resources\drawable\editor.png" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Carousel\SampleBrowser.SfCarousel.csproj"> <Project>{dce3aa32-d2ea-4b93-af87-79c0640926c6}</Project> <Name>SampleBrowser.SfCarousel</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" /> </Project>
{ "pile_set_name": "Github" }
module MarkdownUI class PaddedSegment def initialize(element, content) @element = element @content = content end def render element = @element.strip content = @content.strip klass = "ui #{element} padded segment" MarkdownUI::SectionTag.new(content, klass).render end end end
{ "pile_set_name": "Github" }
package com.quickblox.sample.conference.utils; import android.Manifest; /** * QuickBlox team */ public interface Consts { String DEFAULT_USER_PASSWORD = "x6Bt0VDy5"; String VERSION_NUMBER = "1.0"; int CALL_ACTIVITY_CLOSE = 1000; int ERR_LOGIN_ALREADY_TAKEN_HTTP_STATUS = 422; int ERR_MSG_DELETING_HTTP_STATUS = 401; //CALL ACTIVITY CLOSE REASONS int CALL_ACTIVITY_CLOSE_WIFI_DISABLED = 1001; String WIFI_DISABLED = "wifi_disabled"; String OPPONENTS = "opponents"; String CONFERENCE_TYPE = "conference_type"; String EXTRA_TAG = "currentRoomName"; int MAX_OPPONENTS_COUNT = 6; String PREF_CURREN_ROOM_NAME = "current_room_name"; String EXTRA_USER_ID = "user_id"; String EXTRA_USER_LOGIN = "user_login"; String EXTRA_USER_PASSWORD = "user_password"; String EXTRA_DIALOG_ID = "dialog_id"; String EXTRA_DIALOG_OCCUPANTS = "dialog_occupants"; String EXTRA_AS_LISTENER = "as_listener"; String EXTRA_DIALOG_IS_VIDEO = "dialog_is_video"; String EXTRA_PENDING_INTENT = "pending_Intent"; String EXTRA_LOGIN_RESULT = "login_result"; String EXTRA_LOGIN_ERROR_MESSAGE = "login_error_message"; int EXTRA_LOGIN_RESULT_CODE = 1002; String[] PERMISSIONS = {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}; }
{ "pile_set_name": "Github" }
// Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Preprocessed version of "boost/mpl/plus.hpp" header // -- DO NOT modify by hand! namespace boost { namespace mpl { template< typename Tag1 , typename Tag2 , BOOST_MPL_AUX_NTTP_DECL(int, tag1_) = BOOST_MPL_AUX_MSVC_VALUE_WKND(Tag1)::value , BOOST_MPL_AUX_NTTP_DECL(int, tag2_) = BOOST_MPL_AUX_MSVC_VALUE_WKND(Tag2)::value > struct plus_impl : if_c< ( tag1_ > tag2_ ) , aux::cast2nd_impl< plus_impl< Tag1,Tag1 >,Tag1, Tag2 > , aux::cast1st_impl< plus_impl< Tag2,Tag2 >,Tag1, Tag2 > >::type { }; /// for Digital Mars C++/compilers with no CTPS/TTP support template<> struct plus_impl< na,na > { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; template<> struct plus_impl< na,integral_c_tag > { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; template<> struct plus_impl< integral_c_tag,na > { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; template< typename T > struct plus_tag { typedef typename T::tag type; }; /// forward declaration template< typename BOOST_MPL_AUX_NA_PARAM(N1) , typename BOOST_MPL_AUX_NA_PARAM(N2) > struct plus2; template< typename BOOST_MPL_AUX_NA_PARAM(N1) , typename BOOST_MPL_AUX_NA_PARAM(N2) , typename N3 = na, typename N4 = na, typename N5 = na > struct plus : if_< is_na<N3> , plus2< N1,N2 > , plus< plus2< N1,N2 > , N3, N4, N5 > >::type { BOOST_MPL_AUX_LAMBDA_SUPPORT( 5 , plus , ( N1, N2, N3, N4, N5 ) ) }; template< typename N1 , typename N2 > struct plus2 : aux::msvc_eti_base< typename apply_wrap2< plus_impl< typename plus_tag<N1>::type , typename plus_tag<N2>::type > , N1 , N2 >::type >::type { BOOST_MPL_AUX_LAMBDA_SUPPORT(2, plus2, (N1, N2)) }; BOOST_MPL_AUX_NA_SPEC2(2, 5, plus) }} namespace boost { namespace mpl { namespace aux { template< typename T, T n1, T n2 > struct plus_wknd { BOOST_STATIC_CONSTANT(T, value = (n1 + n2)); typedef integral_c< T,value > type; }; } template<> struct plus_impl< integral_c_tag,integral_c_tag > { template< typename N1, typename N2 > struct apply : aux::plus_wknd< typename aux::largest_int< typename N1::value_type , typename N2::value_type >::type , N1::value , N2::value >::type { }; }; }}
{ "pile_set_name": "Github" }
#import "EXPMatchers+beNil.h" #import "EXPMatchers+equal.h" #import "EXPMatchers+beInstanceOf.h" #import "EXPMatchers+beKindOf.h" #import "EXPMatchers+beSubclassOf.h" #import "EXPMatchers+conformTo.h" #import "EXPMatchers+beTruthy.h" #import "EXPMatchers+beFalsy.h" #import "EXPMatchers+contain.h" #import "EXPMatchers+beSupersetOf.h" #import "EXPMatchers+haveCountOf.h" #import "EXPMatchers+beIdenticalTo.h" #import "EXPMatchers+beGreaterThan.h" #import "EXPMatchers+beGreaterThanOrEqualTo.h" #import "EXPMatchers+beLessThan.h" #import "EXPMatchers+beLessThanOrEqualTo.h" #import "EXPMatchers+beInTheRangeOf.h" #import "EXPMatchers+beCloseTo.h" #import "EXPMatchers+raise.h" #import "EXPMatchers+raiseWithReason.h" #import "EXPMatchers+respondTo.h" #import "EXPMatchers+notify.h" #import "EXPMatchers+beginWith.h" #import "EXPMatchers+endWith.h"
{ "pile_set_name": "Github" }
foo bar hop
{ "pile_set_name": "Github" }
// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ // // Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package klog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup. // It provides functions Info, Warning, Error, Fatal, plus formatting variants such as // Infof. It also provides V-style logging controlled by the -v and -vmodule=file=2 flags. // // Basic examples: // // klog.Info("Prepare to repel boarders") // // klog.Fatalf("Initialization failed: %s", err) // // See the documentation for the V function for an explanation of these examples: // // if klog.V(2) { // klog.Info("Starting transaction...") // } // // klog.V(2).Infoln("Processed", nItems, "elements") // // Log output is buffered and written periodically using Flush. Programs // should call Flush before exiting to guarantee all log output is written. // // By default, all log statements write to standard error. // This package provides several flags that modify this behavior. // As a result, flag.Parse must be called before any logging is done. // // -logtostderr=true // Logs are written to standard error instead of to files. // -alsologtostderr=false // Logs are written to standard error as well as to files. // -stderrthreshold=ERROR // Log events at or above this severity are logged to standard // error as well as to files. // -log_dir="" // Log files will be written to this directory instead of the // default temporary directory. // // Other flags provide aids to debugging. // // -log_backtrace_at="" // When set to a file and line number holding a logging statement, // such as // -log_backtrace_at=gopherflakes.go:234 // a stack trace will be written to the Info log whenever execution // hits that statement. (Unlike with -vmodule, the ".go" must be // present.) // -v=0 // Enable V-leveled logging at the specified level. // -vmodule="" // The syntax of the argument is a comma-separated list of pattern=N, // where pattern is a literal file name (minus the ".go" suffix) or // "glob" pattern and N is a V level. For instance, // -vmodule=gopher*=3 // sets the V level to 3 in all Go files whose names begin "gopher". // package klog import ( "bufio" "bytes" "errors" "flag" "fmt" "io" stdLog "log" "math" "os" "path/filepath" "runtime" "strconv" "strings" "sync" "sync/atomic" "time" "github.com/go-logr/logr" ) // severity identifies the sort of log: info, warning etc. It also implements // the flag.Value interface. The -stderrthreshold flag is of type severity and // should be modified only through the flag.Value interface. The values match // the corresponding constants in C++. type severity int32 // sync/atomic int32 // These constants identify the log levels in order of increasing severity. // A message written to a high-severity log file is also written to each // lower-severity log file. const ( infoLog severity = iota warningLog errorLog fatalLog numSeverity = 4 ) const severityChar = "IWEF" var severityName = []string{ infoLog: "INFO", warningLog: "WARNING", errorLog: "ERROR", fatalLog: "FATAL", } // get returns the value of the severity. func (s *severity) get() severity { return severity(atomic.LoadInt32((*int32)(s))) } // set sets the value of the severity. func (s *severity) set(val severity) { atomic.StoreInt32((*int32)(s), int32(val)) } // String is part of the flag.Value interface. func (s *severity) String() string { return strconv.FormatInt(int64(*s), 10) } // Get is part of the flag.Getter interface. func (s *severity) Get() interface{} { return *s } // Set is part of the flag.Value interface. func (s *severity) Set(value string) error { var threshold severity // Is it a known name? if v, ok := severityByName(value); ok { threshold = v } else { v, err := strconv.ParseInt(value, 10, 32) if err != nil { return err } threshold = severity(v) } logging.stderrThreshold.set(threshold) return nil } func severityByName(s string) (severity, bool) { s = strings.ToUpper(s) for i, name := range severityName { if name == s { return severity(i), true } } return 0, false } // OutputStats tracks the number of output lines and bytes written. type OutputStats struct { lines int64 bytes int64 } // Lines returns the number of lines written. func (s *OutputStats) Lines() int64 { return atomic.LoadInt64(&s.lines) } // Bytes returns the number of bytes written. func (s *OutputStats) Bytes() int64 { return atomic.LoadInt64(&s.bytes) } // Stats tracks the number of lines of output and number of bytes // per severity level. Values must be read with atomic.LoadInt64. var Stats struct { Info, Warning, Error OutputStats } var severityStats = [numSeverity]*OutputStats{ infoLog: &Stats.Info, warningLog: &Stats.Warning, errorLog: &Stats.Error, } // Level is exported because it appears in the arguments to V and is // the type of the v flag, which can be set programmatically. // It's a distinct type because we want to discriminate it from logType. // Variables of type level are only changed under logging.mu. // The -v flag is read only with atomic ops, so the state of the logging // module is consistent. // Level is treated as a sync/atomic int32. // Level specifies a level of verbosity for V logs. *Level implements // flag.Value; the -v flag is of type Level and should be modified // only through the flag.Value interface. type Level int32 // get returns the value of the Level. func (l *Level) get() Level { return Level(atomic.LoadInt32((*int32)(l))) } // set sets the value of the Level. func (l *Level) set(val Level) { atomic.StoreInt32((*int32)(l), int32(val)) } // String is part of the flag.Value interface. func (l *Level) String() string { return strconv.FormatInt(int64(*l), 10) } // Get is part of the flag.Getter interface. func (l *Level) Get() interface{} { return *l } // Set is part of the flag.Value interface. func (l *Level) Set(value string) error { v, err := strconv.ParseInt(value, 10, 32) if err != nil { return err } logging.mu.Lock() defer logging.mu.Unlock() logging.setVState(Level(v), logging.vmodule.filter, false) return nil } // moduleSpec represents the setting of the -vmodule flag. type moduleSpec struct { filter []modulePat } // modulePat contains a filter for the -vmodule flag. // It holds a verbosity level and a file pattern to match. type modulePat struct { pattern string literal bool // The pattern is a literal string level Level } // match reports whether the file matches the pattern. It uses a string // comparison if the pattern contains no metacharacters. func (m *modulePat) match(file string) bool { if m.literal { return file == m.pattern } match, _ := filepath.Match(m.pattern, file) return match } func (m *moduleSpec) String() string { // Lock because the type is not atomic. TODO: clean this up. logging.mu.Lock() defer logging.mu.Unlock() var b bytes.Buffer for i, f := range m.filter { if i > 0 { b.WriteRune(',') } fmt.Fprintf(&b, "%s=%d", f.pattern, f.level) } return b.String() } // Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the // struct is not exported. func (m *moduleSpec) Get() interface{} { return nil } var errVmoduleSyntax = errors.New("syntax error: expect comma-separated list of filename=N") // Syntax: -vmodule=recordio=2,file=1,gfs*=3 func (m *moduleSpec) Set(value string) error { var filter []modulePat for _, pat := range strings.Split(value, ",") { if len(pat) == 0 { // Empty strings such as from a trailing comma can be ignored. continue } patLev := strings.Split(pat, "=") if len(patLev) != 2 || len(patLev[0]) == 0 || len(patLev[1]) == 0 { return errVmoduleSyntax } pattern := patLev[0] v, err := strconv.ParseInt(patLev[1], 10, 32) if err != nil { return errors.New("syntax error: expect comma-separated list of filename=N") } if v < 0 { return errors.New("negative value for vmodule level") } if v == 0 { continue // Ignore. It's harmless but no point in paying the overhead. } // TODO: check syntax of filter? filter = append(filter, modulePat{pattern, isLiteral(pattern), Level(v)}) } logging.mu.Lock() defer logging.mu.Unlock() logging.setVState(logging.verbosity, filter, true) return nil } // isLiteral reports whether the pattern is a literal string, that is, has no metacharacters // that require filepath.Match to be called to match the pattern. func isLiteral(pattern string) bool { return !strings.ContainsAny(pattern, `\*?[]`) } // traceLocation represents the setting of the -log_backtrace_at flag. type traceLocation struct { file string line int } // isSet reports whether the trace location has been specified. // logging.mu is held. func (t *traceLocation) isSet() bool { return t.line > 0 } // match reports whether the specified file and line matches the trace location. // The argument file name is the full path, not the basename specified in the flag. // logging.mu is held. func (t *traceLocation) match(file string, line int) bool { if t.line != line { return false } if i := strings.LastIndex(file, "/"); i >= 0 { file = file[i+1:] } return t.file == file } func (t *traceLocation) String() string { // Lock because the type is not atomic. TODO: clean this up. logging.mu.Lock() defer logging.mu.Unlock() return fmt.Sprintf("%s:%d", t.file, t.line) } // Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the // struct is not exported func (t *traceLocation) Get() interface{} { return nil } var errTraceSyntax = errors.New("syntax error: expect file.go:234") // Syntax: -log_backtrace_at=gopherflakes.go:234 // Note that unlike vmodule the file extension is included here. func (t *traceLocation) Set(value string) error { if value == "" { // Unset. logging.mu.Lock() defer logging.mu.Unlock() t.line = 0 t.file = "" return nil } fields := strings.Split(value, ":") if len(fields) != 2 { return errTraceSyntax } file, line := fields[0], fields[1] if !strings.Contains(file, ".") { return errTraceSyntax } v, err := strconv.Atoi(line) if err != nil { return errTraceSyntax } if v <= 0 { return errors.New("negative or zero value for level") } logging.mu.Lock() defer logging.mu.Unlock() t.line = v t.file = file return nil } // flushSyncWriter is the interface satisfied by logging destinations. type flushSyncWriter interface { Flush() error Sync() error io.Writer } // init sets up the defaults and runs flushDaemon. func init() { logging.stderrThreshold = errorLog // Default stderrThreshold is ERROR. logging.setVState(0, nil, false) logging.logDir = "" logging.logFile = "" logging.logFileMaxSizeMB = 1800 logging.toStderr = true logging.alsoToStderr = false logging.skipHeaders = false logging.addDirHeader = false logging.skipLogHeaders = false go logging.flushDaemon() } // InitFlags is for explicitly initializing the flags. func InitFlags(flagset *flag.FlagSet) { if flagset == nil { flagset = flag.CommandLine } flagset.StringVar(&logging.logDir, "log_dir", logging.logDir, "If non-empty, write log files in this directory") flagset.StringVar(&logging.logFile, "log_file", logging.logFile, "If non-empty, use this log file") flagset.Uint64Var(&logging.logFileMaxSizeMB, "log_file_max_size", logging.logFileMaxSizeMB, "Defines the maximum size a log file can grow to. Unit is megabytes. "+ "If the value is 0, the maximum file size is unlimited.") flagset.BoolVar(&logging.toStderr, "logtostderr", logging.toStderr, "log to standard error instead of files") flagset.BoolVar(&logging.alsoToStderr, "alsologtostderr", logging.alsoToStderr, "log to standard error as well as files") flagset.Var(&logging.verbosity, "v", "number for the log level verbosity") flagset.BoolVar(&logging.addDirHeader, "add_dir_header", logging.addDirHeader, "If true, adds the file directory to the header of the log messages") flagset.BoolVar(&logging.skipHeaders, "skip_headers", logging.skipHeaders, "If true, avoid header prefixes in the log messages") flagset.BoolVar(&logging.skipLogHeaders, "skip_log_headers", logging.skipLogHeaders, "If true, avoid headers when opening log files") flagset.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr") flagset.Var(&logging.vmodule, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging") flagset.Var(&logging.traceLocation, "log_backtrace_at", "when logging hits line file:N, emit a stack trace") } // Flush flushes all pending log I/O. func Flush() { logging.lockAndFlushAll() } // loggingT collects all the global state of the logging setup. type loggingT struct { // Boolean flags. Not handled atomically because the flag.Value interface // does not let us avoid the =true, and that shorthand is necessary for // compatibility. TODO: does this matter enough to fix? Seems unlikely. toStderr bool // The -logtostderr flag. alsoToStderr bool // The -alsologtostderr flag. // Level flag. Handled atomically. stderrThreshold severity // The -stderrthreshold flag. // freeList is a list of byte buffers, maintained under freeListMu. freeList *buffer // freeListMu maintains the free list. It is separate from the main mutex // so buffers can be grabbed and printed to without holding the main lock, // for better parallelization. freeListMu sync.Mutex // mu protects the remaining elements of this structure and is // used to synchronize logging. mu sync.Mutex // file holds writer for each of the log types. file [numSeverity]flushSyncWriter // pcs is used in V to avoid an allocation when computing the caller's PC. pcs [1]uintptr // vmap is a cache of the V Level for each V() call site, identified by PC. // It is wiped whenever the vmodule flag changes state. vmap map[uintptr]Level // filterLength stores the length of the vmodule filter chain. If greater // than zero, it means vmodule is enabled. It may be read safely // using sync.LoadInt32, but is only modified under mu. filterLength int32 // traceLocation is the state of the -log_backtrace_at flag. traceLocation traceLocation // These flags are modified only under lock, although verbosity may be fetched // safely using atomic.LoadInt32. vmodule moduleSpec // The state of the -vmodule flag. verbosity Level // V logging level, the value of the -v flag/ // If non-empty, overrides the choice of directory in which to write logs. // See createLogDirs for the full list of possible destinations. logDir string // If non-empty, specifies the path of the file to write logs. mutually exclusive // with the log_dir option. logFile string // When logFile is specified, this limiter makes sure the logFile won't exceeds a certain size. When exceeds, the // logFile will be cleaned up. If this value is 0, no size limitation will be applied to logFile. logFileMaxSizeMB uint64 // If true, do not add the prefix headers, useful when used with SetOutput skipHeaders bool // If true, do not add the headers to log files skipLogHeaders bool // If true, add the file directory to the header addDirHeader bool // If set, all output will be redirected unconditionally to the provided logr.Logger logr logr.Logger } // buffer holds a byte Buffer for reuse. The zero value is ready for use. type buffer struct { bytes.Buffer tmp [64]byte // temporary byte array for creating headers. next *buffer } var logging loggingT // setVState sets a consistent state for V logging. // l.mu is held. func (l *loggingT) setVState(verbosity Level, filter []modulePat, setFilter bool) { // Turn verbosity off so V will not fire while we are in transition. l.verbosity.set(0) // Ditto for filter length. atomic.StoreInt32(&l.filterLength, 0) // Set the new filters and wipe the pc->Level map if the filter has changed. if setFilter { l.vmodule.filter = filter l.vmap = make(map[uintptr]Level) } // Things are consistent now, so enable filtering and verbosity. // They are enabled in order opposite to that in V. atomic.StoreInt32(&l.filterLength, int32(len(filter))) l.verbosity.set(verbosity) } // getBuffer returns a new, ready-to-use buffer. func (l *loggingT) getBuffer() *buffer { l.freeListMu.Lock() b := l.freeList if b != nil { l.freeList = b.next } l.freeListMu.Unlock() if b == nil { b = new(buffer) } else { b.next = nil b.Reset() } return b } // putBuffer returns a buffer to the free list. func (l *loggingT) putBuffer(b *buffer) { if b.Len() >= 256 { // Let big buffers die a natural death. return } l.freeListMu.Lock() b.next = l.freeList l.freeList = b l.freeListMu.Unlock() } var timeNow = time.Now // Stubbed out for testing. /* header formats a log header as defined by the C++ implementation. It returns a buffer containing the formatted header and the user's file and line number. The depth specifies how many stack frames above lives the source line to be identified in the log message. Log lines have this form: Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg... where the fields are defined as follows: L A single character, representing the log level (eg 'I' for INFO) mm The month (zero padded; ie May is '05') dd The day (zero padded) hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds threadid The space-padded thread ID as returned by GetTID() file The file name line The line number msg The user-supplied message */ func (l *loggingT) header(s severity, depth int) (*buffer, string, int) { _, file, line, ok := runtime.Caller(3 + depth) if !ok { file = "???" line = 1 } else { if slash := strings.LastIndex(file, "/"); slash >= 0 { path := file file = path[slash+1:] if l.addDirHeader { if dirsep := strings.LastIndex(path[:slash], "/"); dirsep >= 0 { file = path[dirsep+1:] } } } } return l.formatHeader(s, file, line), file, line } // formatHeader formats a log header using the provided file name and line number. func (l *loggingT) formatHeader(s severity, file string, line int) *buffer { now := timeNow() if line < 0 { line = 0 // not a real line number, but acceptable to someDigits } if s > fatalLog { s = infoLog // for safety. } buf := l.getBuffer() if l.skipHeaders { return buf } // Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand. // It's worth about 3X. Fprintf is hard. _, month, day := now.Date() hour, minute, second := now.Clock() // Lmmdd hh:mm:ss.uuuuuu threadid file:line] buf.tmp[0] = severityChar[s] buf.twoDigits(1, int(month)) buf.twoDigits(3, day) buf.tmp[5] = ' ' buf.twoDigits(6, hour) buf.tmp[8] = ':' buf.twoDigits(9, minute) buf.tmp[11] = ':' buf.twoDigits(12, second) buf.tmp[14] = '.' buf.nDigits(6, 15, now.Nanosecond()/1000, '0') buf.tmp[21] = ' ' buf.nDigits(7, 22, pid, ' ') // TODO: should be TID buf.tmp[29] = ' ' buf.Write(buf.tmp[:30]) buf.WriteString(file) buf.tmp[0] = ':' n := buf.someDigits(1, line) buf.tmp[n+1] = ']' buf.tmp[n+2] = ' ' buf.Write(buf.tmp[:n+3]) return buf } // Some custom tiny helper functions to print the log header efficiently. const digits = "0123456789" // twoDigits formats a zero-prefixed two-digit integer at buf.tmp[i]. func (buf *buffer) twoDigits(i, d int) { buf.tmp[i+1] = digits[d%10] d /= 10 buf.tmp[i] = digits[d%10] } // nDigits formats an n-digit integer at buf.tmp[i], // padding with pad on the left. // It assumes d >= 0. func (buf *buffer) nDigits(n, i, d int, pad byte) { j := n - 1 for ; j >= 0 && d > 0; j-- { buf.tmp[i+j] = digits[d%10] d /= 10 } for ; j >= 0; j-- { buf.tmp[i+j] = pad } } // someDigits formats a zero-prefixed variable-width integer at buf.tmp[i]. func (buf *buffer) someDigits(i, d int) int { // Print into the top, then copy down. We know there's space for at least // a 10-digit number. j := len(buf.tmp) for { j-- buf.tmp[j] = digits[d%10] d /= 10 if d == 0 { break } } return copy(buf.tmp[i:], buf.tmp[j:]) } func (l *loggingT) println(s severity, logr logr.InfoLogger, args ...interface{}) { buf, file, line := l.header(s, 0) // if logr is set, we clear the generated header as we rely on the backing // logr implementation to print headers if logr != nil { l.putBuffer(buf) buf = l.getBuffer() } fmt.Fprintln(buf, args...) l.output(s, logr, buf, file, line, false) } func (l *loggingT) print(s severity, logr logr.InfoLogger, args ...interface{}) { l.printDepth(s, logr, 1, args...) } func (l *loggingT) printDepth(s severity, logr logr.InfoLogger, depth int, args ...interface{}) { buf, file, line := l.header(s, depth) // if logr is set, we clear the generated header as we rely on the backing // logr implementation to print headers if logr != nil { l.putBuffer(buf) buf = l.getBuffer() } fmt.Fprint(buf, args...) if buf.Bytes()[buf.Len()-1] != '\n' { buf.WriteByte('\n') } l.output(s, logr, buf, file, line, false) } func (l *loggingT) printf(s severity, logr logr.InfoLogger, format string, args ...interface{}) { buf, file, line := l.header(s, 0) // if logr is set, we clear the generated header as we rely on the backing // logr implementation to print headers if logr != nil { l.putBuffer(buf) buf = l.getBuffer() } fmt.Fprintf(buf, format, args...) if buf.Bytes()[buf.Len()-1] != '\n' { buf.WriteByte('\n') } l.output(s, logr, buf, file, line, false) } // printWithFileLine behaves like print but uses the provided file and line number. If // alsoLogToStderr is true, the log message always appears on standard error; it // will also appear in the log file unless --logtostderr is set. func (l *loggingT) printWithFileLine(s severity, logr logr.InfoLogger, file string, line int, alsoToStderr bool, args ...interface{}) { buf := l.formatHeader(s, file, line) // if logr is set, we clear the generated header as we rely on the backing // logr implementation to print headers if logr != nil { l.putBuffer(buf) buf = l.getBuffer() } fmt.Fprint(buf, args...) if buf.Bytes()[buf.Len()-1] != '\n' { buf.WriteByte('\n') } l.output(s, logr, buf, file, line, alsoToStderr) } // printS if loggr is specified, no need to output with logging module. If // err arguments is specified, will call logr.Error, or output to errorLog severity func (l *loggingT) printS(err error, loggr logr.Logger, msg string, keysAndValues ...interface{}) { if loggr != nil { if err != nil { loggr.Error(err, msg, keysAndValues) } else { loggr.Info(msg, keysAndValues) } return } b := &bytes.Buffer{} b.WriteString(fmt.Sprintf("%q", msg)) if err != nil { b.WriteByte(' ') b.WriteString(fmt.Sprintf("err=%q", err.Error())) } kvListFormat(b, keysAndValues...) var s severity if err == nil { s = infoLog } else { s = errorLog } l.printDepth(s, logging.logr, 1, b) } const missingValue = "(MISSING)" func kvListFormat(b *bytes.Buffer, keysAndValues ...interface{}) { for i := 0; i < len(keysAndValues); i += 2 { var v interface{} k := keysAndValues[i] if i+1 < len(keysAndValues) { v = keysAndValues[i+1] } else { v = missingValue } b.WriteByte(' ') if _, ok := v.(fmt.Stringer); ok { b.WriteString(fmt.Sprintf("%s=%q", k, v)) } else { b.WriteString(fmt.Sprintf("%s=%#v", k, v)) } } } // redirectBuffer is used to set an alternate destination for the logs type redirectBuffer struct { w io.Writer } func (rb *redirectBuffer) Sync() error { return nil } func (rb *redirectBuffer) Flush() error { return nil } func (rb *redirectBuffer) Write(bytes []byte) (n int, err error) { return rb.w.Write(bytes) } // SetLogger will set the backing logr implementation for klog. // If set, all log lines will be suppressed from the regular Output, and // redirected to the logr implementation. // All log lines include the 'severity', 'file' and 'line' values attached as // structured logging values. // Use as: // ... // klog.SetLogger(zapr.NewLogger(zapLog)) func SetLogger(logr logr.Logger) { logging.logr = logr } // SetOutput sets the output destination for all severities func SetOutput(w io.Writer) { logging.mu.Lock() defer logging.mu.Unlock() for s := fatalLog; s >= infoLog; s-- { rb := &redirectBuffer{ w: w, } logging.file[s] = rb } } // SetOutputBySeverity sets the output destination for specific severity func SetOutputBySeverity(name string, w io.Writer) { logging.mu.Lock() defer logging.mu.Unlock() sev, ok := severityByName(name) if !ok { panic(fmt.Sprintf("SetOutputBySeverity(%q): unrecognized severity name", name)) } rb := &redirectBuffer{ w: w, } logging.file[sev] = rb } // output writes the data to the log files and releases the buffer. func (l *loggingT) output(s severity, log logr.InfoLogger, buf *buffer, file string, line int, alsoToStderr bool) { l.mu.Lock() if l.traceLocation.isSet() { if l.traceLocation.match(file, line) { buf.Write(stacks(false)) } } data := buf.Bytes() if log != nil { // TODO: set 'severity' and caller information as structured log info // keysAndValues := []interface{}{"severity", severityName[s], "file", file, "line", line} if s == errorLog { l.logr.Error(nil, string(data)) } else { log.Info(string(data)) } } else if l.toStderr { os.Stderr.Write(data) } else { if alsoToStderr || l.alsoToStderr || s >= l.stderrThreshold.get() { os.Stderr.Write(data) } if logging.logFile != "" { // Since we are using a single log file, all of the items in l.file array // will point to the same file, so just use one of them to write data. if l.file[infoLog] == nil { if err := l.createFiles(infoLog); err != nil { os.Stderr.Write(data) // Make sure the message appears somewhere. l.exit(err) } } l.file[infoLog].Write(data) } else { if l.file[s] == nil { if err := l.createFiles(s); err != nil { os.Stderr.Write(data) // Make sure the message appears somewhere. l.exit(err) } } switch s { case fatalLog: l.file[fatalLog].Write(data) fallthrough case errorLog: l.file[errorLog].Write(data) fallthrough case warningLog: l.file[warningLog].Write(data) fallthrough case infoLog: l.file[infoLog].Write(data) } } } if s == fatalLog { // If we got here via Exit rather than Fatal, print no stacks. if atomic.LoadUint32(&fatalNoStacks) > 0 { l.mu.Unlock() timeoutFlush(10 * time.Second) os.Exit(1) } // Dump all goroutine stacks before exiting. trace := stacks(true) // Write the stack trace for all goroutines to the stderr. if l.toStderr || l.alsoToStderr || s >= l.stderrThreshold.get() || alsoToStderr { os.Stderr.Write(trace) } // Write the stack trace for all goroutines to the files. logExitFunc = func(error) {} // If we get a write error, we'll still exit below. for log := fatalLog; log >= infoLog; log-- { if f := l.file[log]; f != nil { // Can be nil if -logtostderr is set. f.Write(trace) } } l.mu.Unlock() timeoutFlush(10 * time.Second) os.Exit(255) // C++ uses -1, which is silly because it's anded with 255 anyway. } l.putBuffer(buf) l.mu.Unlock() if stats := severityStats[s]; stats != nil { atomic.AddInt64(&stats.lines, 1) atomic.AddInt64(&stats.bytes, int64(len(data))) } } // timeoutFlush calls Flush and returns when it completes or after timeout // elapses, whichever happens first. This is needed because the hooks invoked // by Flush may deadlock when klog.Fatal is called from a hook that holds // a lock. func timeoutFlush(timeout time.Duration) { done := make(chan bool, 1) go func() { Flush() // calls logging.lockAndFlushAll() done <- true }() select { case <-done: case <-time.After(timeout): fmt.Fprintln(os.Stderr, "klog: Flush took longer than", timeout) } } // stacks is a wrapper for runtime.Stack that attempts to recover the data for all goroutines. func stacks(all bool) []byte { // We don't know how big the traces are, so grow a few times if they don't fit. Start large, though. n := 10000 if all { n = 100000 } var trace []byte for i := 0; i < 5; i++ { trace = make([]byte, n) nbytes := runtime.Stack(trace, all) if nbytes < len(trace) { return trace[:nbytes] } n *= 2 } return trace } // logExitFunc provides a simple mechanism to override the default behavior // of exiting on error. Used in testing and to guarantee we reach a required exit // for fatal logs. Instead, exit could be a function rather than a method but that // would make its use clumsier. var logExitFunc func(error) // exit is called if there is trouble creating or writing log files. // It flushes the logs and exits the program; there's no point in hanging around. // l.mu is held. func (l *loggingT) exit(err error) { fmt.Fprintf(os.Stderr, "log: exiting because of error: %s\n", err) // If logExitFunc is set, we do that instead of exiting. if logExitFunc != nil { logExitFunc(err) return } l.flushAll() os.Exit(2) } // syncBuffer joins a bufio.Writer to its underlying file, providing access to the // file's Sync method and providing a wrapper for the Write method that provides log // file rotation. There are conflicting methods, so the file cannot be embedded. // l.mu is held for all its methods. type syncBuffer struct { logger *loggingT *bufio.Writer file *os.File sev severity nbytes uint64 // The number of bytes written to this file maxbytes uint64 // The max number of bytes this syncBuffer.file can hold before cleaning up. } func (sb *syncBuffer) Sync() error { return sb.file.Sync() } // CalculateMaxSize returns the real max size in bytes after considering the default max size and the flag options. func CalculateMaxSize() uint64 { if logging.logFile != "" { if logging.logFileMaxSizeMB == 0 { // If logFileMaxSizeMB is zero, we don't have limitations on the log size. return math.MaxUint64 } // Flag logFileMaxSizeMB is in MB for user convenience. return logging.logFileMaxSizeMB * 1024 * 1024 } // If "log_file" flag is not specified, the target file (sb.file) will be cleaned up when reaches a fixed size. return MaxSize } func (sb *syncBuffer) Write(p []byte) (n int, err error) { if sb.nbytes+uint64(len(p)) >= sb.maxbytes { if err := sb.rotateFile(time.Now(), false); err != nil { sb.logger.exit(err) } } n, err = sb.Writer.Write(p) sb.nbytes += uint64(n) if err != nil { sb.logger.exit(err) } return } // rotateFile closes the syncBuffer's file and starts a new one. // The startup argument indicates whether this is the initial startup of klog. // If startup is true, existing files are opened for appending instead of truncated. func (sb *syncBuffer) rotateFile(now time.Time, startup bool) error { if sb.file != nil { sb.Flush() sb.file.Close() } var err error sb.file, _, err = create(severityName[sb.sev], now, startup) sb.nbytes = 0 if err != nil { return err } sb.Writer = bufio.NewWriterSize(sb.file, bufferSize) if sb.logger.skipLogHeaders { return nil } // Write header. var buf bytes.Buffer fmt.Fprintf(&buf, "Log file created at: %s\n", now.Format("2006/01/02 15:04:05")) fmt.Fprintf(&buf, "Running on machine: %s\n", host) fmt.Fprintf(&buf, "Binary: Built with %s %s for %s/%s\n", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH) fmt.Fprintf(&buf, "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg\n") n, err := sb.file.Write(buf.Bytes()) sb.nbytes += uint64(n) return err } // bufferSize sizes the buffer associated with each log file. It's large // so that log records can accumulate without the logging thread blocking // on disk I/O. The flushDaemon will block instead. const bufferSize = 256 * 1024 // createFiles creates all the log files for severity from sev down to infoLog. // l.mu is held. func (l *loggingT) createFiles(sev severity) error { now := time.Now() // Files are created in decreasing severity order, so as soon as we find one // has already been created, we can stop. for s := sev; s >= infoLog && l.file[s] == nil; s-- { sb := &syncBuffer{ logger: l, sev: s, maxbytes: CalculateMaxSize(), } if err := sb.rotateFile(now, true); err != nil { return err } l.file[s] = sb } return nil } const flushInterval = 5 * time.Second // flushDaemon periodically flushes the log file buffers. func (l *loggingT) flushDaemon() { for range time.NewTicker(flushInterval).C { l.lockAndFlushAll() } } // lockAndFlushAll is like flushAll but locks l.mu first. func (l *loggingT) lockAndFlushAll() { l.mu.Lock() l.flushAll() l.mu.Unlock() } // flushAll flushes all the logs and attempts to "sync" their data to disk. // l.mu is held. func (l *loggingT) flushAll() { // Flush from fatal down, in case there's trouble flushing. for s := fatalLog; s >= infoLog; s-- { file := l.file[s] if file != nil { file.Flush() // ignore error file.Sync() // ignore error } } } // CopyStandardLogTo arranges for messages written to the Go "log" package's // default logs to also appear in the Google logs for the named and lower // severities. Subsequent changes to the standard log's default output location // or format may break this behavior. // // Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not // recognized, CopyStandardLogTo panics. func CopyStandardLogTo(name string) { sev, ok := severityByName(name) if !ok { panic(fmt.Sprintf("log.CopyStandardLogTo(%q): unrecognized severity name", name)) } // Set a log format that captures the user's file and line: // d.go:23: message stdLog.SetFlags(stdLog.Lshortfile) stdLog.SetOutput(logBridge(sev)) } // logBridge provides the Write method that enables CopyStandardLogTo to connect // Go's standard logs to the logs provided by this package. type logBridge severity // Write parses the standard logging line and passes its components to the // logger for severity(lb). func (lb logBridge) Write(b []byte) (n int, err error) { var ( file = "???" line = 1 text string ) // Split "d.go:23: message" into "d.go", "23", and "message". if parts := bytes.SplitN(b, []byte{':'}, 3); len(parts) != 3 || len(parts[0]) < 1 || len(parts[2]) < 1 { text = fmt.Sprintf("bad log format: %s", b) } else { file = string(parts[0]) text = string(parts[2][1:]) // skip leading space line, err = strconv.Atoi(string(parts[1])) if err != nil { text = fmt.Sprintf("bad line number: %s", b) line = 1 } } // printWithFileLine with alsoToStderr=true, so standard log messages // always appear on standard error. logging.printWithFileLine(severity(lb), logging.logr, file, line, true, text) return len(b), nil } // setV computes and remembers the V level for a given PC // when vmodule is enabled. // File pattern matching takes the basename of the file, stripped // of its .go suffix, and uses filepath.Match, which is a little more // general than the *? matching used in C++. // l.mu is held. func (l *loggingT) setV(pc uintptr) Level { fn := runtime.FuncForPC(pc) file, _ := fn.FileLine(pc) // The file is something like /a/b/c/d.go. We want just the d. if strings.HasSuffix(file, ".go") { file = file[:len(file)-3] } if slash := strings.LastIndex(file, "/"); slash >= 0 { file = file[slash+1:] } for _, filter := range l.vmodule.filter { if filter.match(file) { l.vmap[pc] = filter.level return filter.level } } l.vmap[pc] = 0 return 0 } // Verbose is a boolean type that implements Infof (like Printf) etc. // See the documentation of V for more information. type Verbose struct { enabled bool logr logr.InfoLogger } func newVerbose(level Level, b bool) Verbose { if logging.logr == nil { return Verbose{b, nil} } return Verbose{b, logging.logr.V(int(level))} } // V reports whether verbosity at the call site is at least the requested level. // The returned value is a struct of type Verbose, which implements Info, Infoln // and Infof. These methods will write to the Info log if called. // Thus, one may write either // if glog.V(2).Enabled() { klog.Info("log this") } // or // klog.V(2).Info("log this") // The second form is shorter but the first is cheaper if logging is off because it does // not evaluate its arguments. // // Whether an individual call to V generates a log record depends on the setting of // the -v and --vmodule flags; both are off by default. If the level in the call to // V is at least the value of -v, or of -vmodule for the source file containing the // call, the V call will log. func V(level Level) Verbose { // This function tries hard to be cheap unless there's work to do. // The fast path is two atomic loads and compares. // Here is a cheap but safe test to see if V logging is enabled globally. if logging.verbosity.get() >= level { return newVerbose(level, true) } // It's off globally but it vmodule may still be set. // Here is another cheap but safe test to see if vmodule is enabled. if atomic.LoadInt32(&logging.filterLength) > 0 { // Now we need a proper lock to use the logging structure. The pcs field // is shared so we must lock before accessing it. This is fairly expensive, // but if V logging is enabled we're slow anyway. logging.mu.Lock() defer logging.mu.Unlock() if runtime.Callers(2, logging.pcs[:]) == 0 { return newVerbose(level, false) } v, ok := logging.vmap[logging.pcs[0]] if !ok { v = logging.setV(logging.pcs[0]) } return newVerbose(level, v >= level) } return newVerbose(level, false) } // Enabled will return true if this log level is enabled, guarded by the value // of v. // See the documentation of V for usage. func (v Verbose) Enabled() bool { return v.enabled } // Info is equivalent to the global Info function, guarded by the value of v. // See the documentation of V for usage. func (v Verbose) Info(args ...interface{}) { if v.enabled { logging.print(infoLog, v.logr, args...) } } // Infoln is equivalent to the global Infoln function, guarded by the value of v. // See the documentation of V for usage. func (v Verbose) Infoln(args ...interface{}) { if v.enabled { logging.println(infoLog, v.logr, args...) } } // Infof is equivalent to the global Infof function, guarded by the value of v. // See the documentation of V for usage. func (v Verbose) Infof(format string, args ...interface{}) { if v.enabled { logging.printf(infoLog, v.logr, format, args...) } } // InfoS is equivalent to the global InfoS function, guarded by the value of v. // See the documentation of V for usage. func (v Verbose) InfoS(msg string, keysAndValues ...interface{}) { if v.enabled { if v.logr != nil { v.logr.Info(msg, keysAndValues) return } logging.printS(nil, nil, msg, keysAndValues...) } } // Info logs to the INFO log. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. func Info(args ...interface{}) { logging.print(infoLog, logging.logr, args...) } // InfoDepth acts as Info but uses depth to determine which call frame to log. // InfoDepth(0, "msg") is the same as Info("msg"). func InfoDepth(depth int, args ...interface{}) { logging.printDepth(infoLog, logging.logr, depth, args...) } // Infoln logs to the INFO log. // Arguments are handled in the manner of fmt.Println; a newline is always appended. func Infoln(args ...interface{}) { logging.println(infoLog, logging.logr, args...) } // Infof logs to the INFO log. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. func Infof(format string, args ...interface{}) { logging.printf(infoLog, logging.logr, format, args...) } // InfoS structured logs to the INFO log. // The msg argument used to add constant description to the log line. // The key/value pairs would be join by "=" ; a newline is always appended. // // Basic examples: // >> klog.InfoS("Pod status updated", "pod", "kubedns", "status", "ready") // output: // >> I1025 00:15:15.525108 1 controller_utils.go:116] "Pod status updated" pod="kubedns" status="ready" func InfoS(msg string, keysAndValues ...interface{}) { logging.printS(nil, logging.logr, msg, keysAndValues...) } // Warning logs to the WARNING and INFO logs. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. func Warning(args ...interface{}) { logging.print(warningLog, logging.logr, args...) } // WarningDepth acts as Warning but uses depth to determine which call frame to log. // WarningDepth(0, "msg") is the same as Warning("msg"). func WarningDepth(depth int, args ...interface{}) { logging.printDepth(warningLog, logging.logr, depth, args...) } // Warningln logs to the WARNING and INFO logs. // Arguments are handled in the manner of fmt.Println; a newline is always appended. func Warningln(args ...interface{}) { logging.println(warningLog, logging.logr, args...) } // Warningf logs to the WARNING and INFO logs. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. func Warningf(format string, args ...interface{}) { logging.printf(warningLog, logging.logr, format, args...) } // Error logs to the ERROR, WARNING, and INFO logs. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. func Error(args ...interface{}) { logging.print(errorLog, logging.logr, args...) } // ErrorDepth acts as Error but uses depth to determine which call frame to log. // ErrorDepth(0, "msg") is the same as Error("msg"). func ErrorDepth(depth int, args ...interface{}) { logging.printDepth(errorLog, logging.logr, depth, args...) } // Errorln logs to the ERROR, WARNING, and INFO logs. // Arguments are handled in the manner of fmt.Println; a newline is always appended. func Errorln(args ...interface{}) { logging.println(errorLog, logging.logr, args...) } // Errorf logs to the ERROR, WARNING, and INFO logs. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. func Errorf(format string, args ...interface{}) { logging.printf(errorLog, logging.logr, format, args...) } // ErrorS structured logs to the ERROR, WARNING, and INFO logs. // the err argument used as "err" field of log line. // The msg argument used to add constant description to the log line. // The key/value pairs would be join by "=" ; a newline is always appended. // // Basic examples: // >> klog.ErrorS(err, "Failed to update pod status") // output: // >> E1025 00:15:15.525108 1 controller_utils.go:114] "Failed to update pod status" err="timeout" func ErrorS(err error, msg string, keysAndValues ...interface{}) { logging.printS(err, logging.logr, msg, keysAndValues...) } // Fatal logs to the FATAL, ERROR, WARNING, and INFO logs, // including a stack trace of all running goroutines, then calls os.Exit(255). // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. func Fatal(args ...interface{}) { logging.print(fatalLog, logging.logr, args...) } // FatalDepth acts as Fatal but uses depth to determine which call frame to log. // FatalDepth(0, "msg") is the same as Fatal("msg"). func FatalDepth(depth int, args ...interface{}) { logging.printDepth(fatalLog, logging.logr, depth, args...) } // Fatalln logs to the FATAL, ERROR, WARNING, and INFO logs, // including a stack trace of all running goroutines, then calls os.Exit(255). // Arguments are handled in the manner of fmt.Println; a newline is always appended. func Fatalln(args ...interface{}) { logging.println(fatalLog, logging.logr, args...) } // Fatalf logs to the FATAL, ERROR, WARNING, and INFO logs, // including a stack trace of all running goroutines, then calls os.Exit(255). // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. func Fatalf(format string, args ...interface{}) { logging.printf(fatalLog, logging.logr, format, args...) } // fatalNoStacks is non-zero if we are to exit without dumping goroutine stacks. // It allows Exit and relatives to use the Fatal logs. var fatalNoStacks uint32 // Exit logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. func Exit(args ...interface{}) { atomic.StoreUint32(&fatalNoStacks, 1) logging.print(fatalLog, logging.logr, args...) } // ExitDepth acts as Exit but uses depth to determine which call frame to log. // ExitDepth(0, "msg") is the same as Exit("msg"). func ExitDepth(depth int, args ...interface{}) { atomic.StoreUint32(&fatalNoStacks, 1) logging.printDepth(fatalLog, logging.logr, depth, args...) } // Exitln logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). func Exitln(args ...interface{}) { atomic.StoreUint32(&fatalNoStacks, 1) logging.println(fatalLog, logging.logr, args...) } // Exitf logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. func Exitf(format string, args ...interface{}) { atomic.StoreUint32(&fatalNoStacks, 1) logging.printf(fatalLog, logging.logr, format, args...) } // ObjectRef references a kubernetes object type ObjectRef struct { Name string `json:"name"` Namespace string `json:"namespace,omitempty"` } func (ref ObjectRef) String() string { if ref.Namespace != "" { return fmt.Sprintf("%s/%s", ref.Namespace, ref.Name) } return ref.Name } // KMetadata is a subset of the kubernetes k8s.io/apimachinery/pkg/apis/meta/v1.Object interface // this interface may expand in the future, but will always be a subset of the // kubernetes k8s.io/apimachinery/pkg/apis/meta/v1.Object interface type KMetadata interface { GetName() string GetNamespace() string } // KObj returns ObjectRef from ObjectMeta func KObj(obj KMetadata) ObjectRef { return ObjectRef{ Name: obj.GetName(), Namespace: obj.GetNamespace(), } } // KRef returns ObjectRef from name and namespace func KRef(namespace, name string) ObjectRef { return ObjectRef{ Name: name, Namespace: namespace, } }
{ "pile_set_name": "Github" }
/* * This file is a part of the Cairo-Dock project * * Copyright : (C) see the 'copyright' file. * E-mail : see the 'copyright' file. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __CAIRO_DOCK_APPLICATION_FACILITY__ #define __CAIRO_DOCK_APPLICATION_FACILITY__ #include <glib.h> #include "cairo-dock-struct.h" G_BEGIN_DECLS /* *@file cairo-dock-application-facility.h A set of utilities for handling appli-icons. */ void gldi_appli_icon_demands_attention (Icon *icon); // applications-manager void gldi_appli_icon_stop_demanding_attention (Icon *icon); // applications-manager void gldi_appli_icon_animate_on_active (Icon *icon, CairoDock *pParentDock); // applications-manager CairoDock *gldi_appli_icon_insert_in_dock (Icon *icon, CairoDock *pMainDock, gboolean bAnimate); CairoDock *gldi_appli_icon_detach (Icon *pIcon); void gldi_appli_icon_set_geometry_for_window_manager (Icon *icon, CairoDock *pDock); void gldi_appli_reserve_geometry_for_window_manager (GldiWindowActor *pAppli, Icon *icon, CairoDock *pMainDock); // applications-manager const CairoDockImageBuffer *gldi_appli_icon_get_image_buffer (Icon *pIcon); void gldi_window_inhibitors_set_name (GldiWindowActor *actor, const gchar *cNewName); // applications-manager void gldi_window_inhibitors_set_active_state (GldiWindowActor *actor, gboolean bActive); // applications-manager void gldi_window_inhibitors_set_hidden_state (GldiWindowActor *actor, gboolean bIsHidden); // applications-manager G_END_DECLS #endif
{ "pile_set_name": "Github" }
'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } /* * Complete the isPositive function. * If 'a' is positive, return "YES". * If 'a' is 0, throw an Error with the message "Zero Error" * If 'a' is negative, throw an Error with the message "Negative Error" */ function isPositive(a) { if (a > 0) { return 'YES'; } else if (a === 0) { throw new Error('Zero Error'); } else { throw new Error('Negative Error'); } } function main() { const n = +(readLine()); for (let i = 0; i < n; i++) { const a = +(readLine()); try { console.log(isPositive(a)); } catch (e) { console.log(e.message); } } }
{ "pile_set_name": "Github" }
/** * @license * Copyright The Closure Library Authors. * SPDX-License-Identifier: Apache-2.0 */ goog.module('goog.dom.vendorTest'); goog.setTestOnly(); const MockUserAgent = goog.require('goog.testing.MockUserAgent'); const PropertyReplacer = goog.require('goog.testing.PropertyReplacer'); const googArray = goog.require('goog.array'); const testSuite = goog.require('goog.testing.testSuite'); const userAgent = goog.require('goog.userAgent'); const userAgentTestUtil = goog.require('goog.userAgentTestUtil'); const util = goog.require('goog.labs.userAgent.util'); const vendor = goog.require('goog.dom.vendor'); let documentMode; let mockUserAgent; const propertyReplacer = new PropertyReplacer(); let getDocumentMode = () => documentMode; const UserAgents = { GECKO: 'GECKO', IE: 'IE', OPERA: 'OPERA', WEBKIT: 'WEBKIT' }; /** * Return whether a given user agent has been detected. * @param {number} agent Value in UserAgents. * @return {boolean} Whether the user agent has been detected. */ function getUserAgentDetected(agent) { switch (agent) { case UserAgents.GECKO: return userAgent.GECKO; case UserAgents.IE: return userAgent.IE; case UserAgents.OPERA: return userAgent.OPERA; case UserAgents.WEBKIT: return userAgent.WEBKIT; } return null; } /** * Test browser detection for a user agent configuration. * @param {Array<number>} expectedAgents Array of expected userAgents. * @param {string} uaString User agent string. * @param {string=} product Navigator product string. * @param {string=} opt_vendor Navigator vendor string. */ function assertUserAgent( expectedAgents, uaString, product = undefined, opt_vendor) { const mockNavigator = { 'userAgent': uaString, 'product': product, 'vendor': opt_vendor }; mockUserAgent.setNavigator(mockNavigator); mockUserAgent.setUserAgentString(uaString); // Force reread of navigator.userAgent; util.setUserAgent(null); userAgentTestUtil.reinitializeUserAgent(); for (let ua in UserAgents) { const isExpected = googArray.contains(expectedAgents, UserAgents[ua]); assertEquals(isExpected, getUserAgentDetected(UserAgents[ua])); } } function assertIe(uaString, expectedVersion) { assertUserAgent([UserAgents.IE], uaString); assertEquals( `User agent ${uaString} should have had version ${expectedVersion}` + ' but had ' + userAgent.VERSION, expectedVersion, userAgent.VERSION); } function assertGecko(uaString, expectedVersion) { assertUserAgent([UserAgents.GECKO], uaString, 'Gecko'); assertEquals( `User agent ${uaString} should have had version ${expectedVersion}` + ' but had ' + userAgent.VERSION, expectedVersion, userAgent.VERSION); } testSuite({ setUp() { mockUserAgent = new MockUserAgent(); mockUserAgent.install(); }, tearDown() { goog.dispose(mockUserAgent); documentMode = undefined; propertyReplacer.reset(); }, /** Tests for the vendor prefix for Webkit. */ testVendorPrefixWebkit() { assertUserAgent([UserAgents.WEBKIT], 'WebKit'); assertEquals('-webkit', vendor.getVendorPrefix()); }, /** Tests for the vendor prefix for Mozilla/Gecko. */ testVendorPrefixGecko() { assertUserAgent([UserAgents.GECKO], 'Gecko', 'Gecko'); assertEquals('-moz', vendor.getVendorPrefix()); }, /** Tests for the vendor prefix for Opera. */ testVendorPrefixOpera() { assertUserAgent([UserAgents.OPERA], 'Opera'); assertEquals('-o', vendor.getVendorPrefix()); }, /** Tests for the vendor prefix for IE. */ testVendorPrefixIE() { assertUserAgent([UserAgents.IE], 'MSIE'); assertEquals('-ms', vendor.getVendorPrefix()); }, /** Tests for the vendor Js prefix for Webkit. */ testVendorJsPrefixWebkit() { assertUserAgent([UserAgents.WEBKIT], 'WebKit'); assertEquals('Webkit', vendor.getVendorJsPrefix()); }, /** Tests for the vendor Js prefix for Mozilla/Gecko. */ testVendorJsPrefixGecko() { assertUserAgent([UserAgents.GECKO], 'Gecko', 'Gecko'); assertEquals('Moz', vendor.getVendorJsPrefix()); }, /** Tests for the vendor Js prefix for Opera. */ testVendorJsPrefixOpera() { assertUserAgent([UserAgents.OPERA], 'Opera'); assertEquals('O', vendor.getVendorJsPrefix()); }, /** Tests for the vendor Js prefix for IE. */ testVendorJsPrefixIE() { assertUserAgent([UserAgents.IE], 'MSIE'); assertEquals('ms', vendor.getVendorJsPrefix()); }, /** Tests for the vendor Js prefix if no UA detected. */ testVendorJsPrefixNone() { assertUserAgent([], ''); assertNull(vendor.getVendorJsPrefix()); }, /** Tests for the prefixed property name on Webkit. */ testPrefixedPropertyNameWebkit() { assertUserAgent([UserAgents.WEBKIT], 'WebKit'); assertEquals('webkitFoobar', vendor.getPrefixedPropertyName('foobar')); }, /** Tests for the prefixed property name on Webkit in an object. */ testPrefixedPropertyNameWebkitAndObject() { const mockDocument = { // setting a value of 0 on purpose, to ensure we only look for property // names, not their values. 'webkitFoobar': 0, }; assertUserAgent([UserAgents.WEBKIT], 'WebKit'); assertEquals( 'webkitFoobar', vendor.getPrefixedPropertyName('foobar', mockDocument)); }, /** Tests for the prefixed property name. */ testPrefixedPropertyName() { assertUserAgent([], ''); assertNull(vendor.getPrefixedPropertyName('foobar')); }, /** Tests for the prefixed property name in an object. */ testPrefixedPropertyNameAndObject() { const mockDocument = {'foobar': 0}; assertUserAgent([], ''); assertEquals( 'foobar', vendor.getPrefixedPropertyName('foobar', mockDocument)); }, /** Tests for the prefixed property name when it doesn't exist. */ testPrefixedPropertyNameAndObjectIsEmpty() { const mockDocument = {}; assertUserAgent([], ''); assertNull(vendor.getPrefixedPropertyName('foobar', mockDocument)); }, /** Test for prefixed event type. */ testPrefixedEventType() { assertUserAgent([], ''); assertEquals('foobar', vendor.getPrefixedEventType('foobar')); }, /** Test for browser-specific prefixed event type. */ testPrefixedEventTypeForBrowser() { assertUserAgent([UserAgents.WEBKIT], 'WebKit'); assertEquals('webkitfoobar', vendor.getPrefixedEventType('foobar')); }, });
{ "pile_set_name": "Github" }
apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: address-space-controller labels: app: enmasse roleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: enmasse.io:address-space-controller subjects: - kind: ServiceAccount name: address-space-controller namespace: ${NAMESPACE}
{ "pile_set_name": "Github" }
version https://git-lfs.github.com/spec/v1 oid sha256:a2181f85524209a29ab8b707bac9758e2fd483b5a98d1fa867fef6554e086289 size 54901
{ "pile_set_name": "Github" }
 Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.27703.2000 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "smbdoor", "smbdoor\smbdoor.vcxproj", "{81FDE815-185D-45CA-9E72-1680A3CA8E57}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{BD61FAF0-8A3A-4C26-9D2B-DD96D38DC6C5}" ProjectSection(SolutionItems) = preProject run.bat = run.bat EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|ARM = Debug|ARM Debug|ARM64 = Debug|ARM64 Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|ARM = Release|ARM Release|ARM64 = Release|ARM64 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Debug|ARM.ActiveCfg = Debug|ARM {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Debug|ARM.Build.0 = Debug|ARM {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Debug|ARM.Deploy.0 = Debug|ARM {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Debug|ARM64.ActiveCfg = Debug|ARM64 {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Debug|ARM64.Build.0 = Debug|ARM64 {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Debug|ARM64.Deploy.0 = Debug|ARM64 {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Debug|x64.ActiveCfg = Debug|x64 {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Debug|x64.Build.0 = Debug|x64 {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Debug|x64.Deploy.0 = Debug|x64 {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Debug|x86.ActiveCfg = Debug|Win32 {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Debug|x86.Build.0 = Debug|Win32 {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Debug|x86.Deploy.0 = Debug|Win32 {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Release|ARM.ActiveCfg = Release|ARM {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Release|ARM.Build.0 = Release|ARM {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Release|ARM.Deploy.0 = Release|ARM {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Release|ARM64.ActiveCfg = Release|ARM64 {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Release|ARM64.Build.0 = Release|ARM64 {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Release|ARM64.Deploy.0 = Release|ARM64 {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Release|x64.ActiveCfg = Release|x64 {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Release|x64.Build.0 = Release|x64 {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Release|x64.Deploy.0 = Release|x64 {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Release|x86.ActiveCfg = Release|Win32 {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Release|x86.Build.0 = Release|Win32 {81FDE815-185D-45CA-9E72-1680A3CA8E57}.Release|x86.Deploy.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {9E5FBD18-A527-4ECF-AACC-C81FB7020EAF} EndGlobalSection EndGlobal
{ "pile_set_name": "Github" }
<html> <head> <title>403 Forbidden</title> </head> <body> <p>Directory access is forbidden.</p> </body> </html>
{ "pile_set_name": "Github" }
module.exports = function(hljs) { var LISP_IDENT_RE = '[a-zA-Z_\\-\\+\\*\\/\\<\\=\\>\\&\\#][a-zA-Z0-9_\\-\\+\\*\\/\\<\\=\\>\\&\\#!]*'; var MEC_RE = '\\|[^]*?\\|'; var LISP_SIMPLE_NUMBER_RE = '(\\-|\\+)?\\d+(\\.\\d+|\\/\\d+)?((d|e|f|l|s|D|E|F|L|S)(\\+|\\-)?\\d+)?'; var SHEBANG = { className: 'meta', begin: '^#!', end: '$' }; var LITERAL = { className: 'literal', begin: '\\b(t{1}|nil)\\b' }; var NUMBER = { className: 'number', variants: [ {begin: LISP_SIMPLE_NUMBER_RE, relevance: 0}, {begin: '#(b|B)[0-1]+(/[0-1]+)?'}, {begin: '#(o|O)[0-7]+(/[0-7]+)?'}, {begin: '#(x|X)[0-9a-fA-F]+(/[0-9a-fA-F]+)?'}, {begin: '#(c|C)\\(' + LISP_SIMPLE_NUMBER_RE + ' +' + LISP_SIMPLE_NUMBER_RE, end: '\\)'} ] }; var STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null}); var COMMENT = hljs.COMMENT( ';', '$', { relevance: 0 } ); var VARIABLE = { begin: '\\*', end: '\\*' }; var KEYWORD = { className: 'symbol', begin: '[:&]' + LISP_IDENT_RE }; var IDENT = { begin: LISP_IDENT_RE, relevance: 0 }; var MEC = { begin: MEC_RE }; var QUOTED_LIST = { begin: '\\(', end: '\\)', contains: ['self', LITERAL, STRING, NUMBER, IDENT] }; var QUOTED = { contains: [NUMBER, STRING, VARIABLE, KEYWORD, QUOTED_LIST, IDENT], variants: [ { begin: '[\'`]\\(', end: '\\)' }, { begin: '\\(quote ', end: '\\)', keywords: {name: 'quote'} }, { begin: '\'' + MEC_RE } ] }; var QUOTED_ATOM = { variants: [ {begin: '\'' + LISP_IDENT_RE}, {begin: '#\'' + LISP_IDENT_RE + '(::' + LISP_IDENT_RE + ')*'} ] }; var LIST = { begin: '\\(\\s*', end: '\\)' }; var BODY = { endsWithParent: true, relevance: 0 }; LIST.contains = [ { className: 'name', variants: [ {begin: LISP_IDENT_RE}, {begin: MEC_RE} ] }, BODY ]; BODY.contains = [QUOTED, QUOTED_ATOM, LIST, LITERAL, NUMBER, STRING, COMMENT, VARIABLE, KEYWORD, MEC, IDENT]; return { illegal: /\S/, contains: [ NUMBER, SHEBANG, LITERAL, STRING, COMMENT, QUOTED, QUOTED_ATOM, LIST, IDENT ] }; };
{ "pile_set_name": "Github" }
package tracing import ( "go.opentelemetry.io/otel/api/core" "go.opentelemetry.io/otel/api/key" ) type Attrs map[string]string // keyValueSlice converts our internal representation of kv pairs to the tracing // SDK's kv representation. // func keyValueSlice(attrs Attrs) []core.KeyValue { var ( res = make([]core.KeyValue, len(attrs)) idx = 0 ) for k, v := range attrs { res[idx] = key.New(k).String(v) idx++ } return res }
{ "pile_set_name": "Github" }
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Simple GraphEditor example. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow.contrib import graph_editor as ge FLAGS = tf.flags.FLAGS def main(_): # create a graph g = tf.Graph() with g.as_default(): a = tf.constant(1.0, shape=[2, 3], name="a") b = tf.constant(2.0, shape=[2, 3], name="b") c = tf.add( tf.placeholder(dtype=np.float32), tf.placeholder(dtype=np.float32), name="c") # modify the graph ge.swap_inputs(c.op, [a, b]) # print the graph def print(g.as_graph_def()) # and print the value of c with tf.Session(graph=g) as sess: res = sess.run(c) print(res) if __name__ == "__main__": tf.app.run()
{ "pile_set_name": "Github" }
import _plotly_utils.basevalidators class FamilyValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="family", parent_name="layout.coloraxis.colorbar.title.font", **kwargs ): super(FamilyValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), no_blank=kwargs.pop("no_blank", True), role=kwargs.pop("role", "style"), strict=kwargs.pop("strict", True), **kwargs )
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.tencent.mars.xlogsample" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> </manifest>
{ "pile_set_name": "Github" }
<div><svg width="482" height="68"> <polygon points="9 17 1 13 1 21"></polygon> <polygon points="17 17 9 13 9 21"></polygon> <rect x="31" y="3" width="58" height="32" rx="10"></rect> <rect x="29" y="1" width="58" height="32" class="terminal" rx="10"></rect> <text class="terminal" x="39" y="21">DROP</text> <rect x="109" y="3" width="90" height="32" rx="10"></rect> <rect x="107" y="1" width="90" height="32" class="terminal" rx="10"></rect> <text class="terminal" x="117" y="21">DATABASE</text> <rect x="239" y="35" width="34" height="32" rx="10"></rect> <rect x="237" y="33" width="34" height="32" class="terminal" rx="10"></rect> <text class="terminal" x="247" y="53">IF</text> <rect x="293" y="35" width="68" height="32" rx="10"></rect> <rect x="291" y="33" width="68" height="32" class="terminal" rx="10"></rect> <text class="terminal" x="301" y="53">EXISTS</text> <a xlink:href="sql-grammar.html#name" xlink:title="name"> <rect x="401" y="3" width="54" height="32"></rect> <rect x="399" y="1" width="54" height="32" class="nonterminal"></rect> <text class="nonterminal" x="409" y="21">name</text> </a> <path class="line" d="m17 17 h2 m0 0 h10 m58 0 h10 m0 0 h10 m90 0 h10 m20 0 h10 m0 0 h132 m-162 0 h20 m142 0 h20 m-182 0 q10 0 10 10 m162 0 q0 -10 10 -10 m-172 10 v12 m162 0 v-12 m-162 12 q0 10 10 10 m142 0 q10 0 10 -10 m-152 10 h10 m34 0 h10 m0 0 h10 m68 0 h10 m20 -32 h10 m54 0 h10 m3 0 h-3"></path> <polygon points="473 17 481 13 481 21"></polygon> <polygon points="473 17 465 13 465 21"></polygon> </svg></div>
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="en"> <head> <title>Classes Reference</title> <link rel="stylesheet" type="text/css" href="css/jazzy.css" /> <link rel="stylesheet" type="text/css" href="css/highlight.css" /> <meta charset="utf-8"> <script src="js/jquery.min.js" defer></script> <script src="js/jazzy.js" defer></script> <script src="js/lunr.min.js" defer></script> <script src="js/typeahead.jquery.js" defer></script> <script src="js/jazzy.search.js" defer></script> </head> <body> <a name="//apple_ref/swift/Section/Classes" class="dashAnchor"></a> <a title="Classes Reference"></a> <header class="header"> <p class="header-col header-col--primary"> <a class="header-link" href="index.html"> AlamofireImage Docs </a> (77% documented) </p> <p class="header-col--secondary"> <form role="search" action="search.json"> <input type="text" placeholder="Search documentation" data-typeahead> </form> </p> <p class="header-col header-col--secondary"> <a class="header-link" href="https://github.com/Alamofire/AlamofireImage"> <img class="header-icon" src="img/gh.png"/> View on GitHub </a> </p> <p class="header-col header-col--secondary"> <a class="header-link" href="dash-feed://https%3A%2F%2Falamofire%2Egithub%2Eio%2FAlamofireImage%2Fdocsets%2FAlamofireImage%2Exml"> <img class="header-icon" src="img/dash.png"/> Install in Dash </a> </p> </header> <p class="breadcrumbs"> <a class="breadcrumb" href="index.html">AlamofireImage Reference</a> <img class="carat" src="img/carat.png" /> Classes Reference </p> <div class="content-wrapper"> <nav class="navigation"> <ul class="nav-groups"> <li class="nav-group-name"> <a class="nav-group-name-link" href="Classes.html">Classes</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="Classes/AutoPurgingImageCache.html">AutoPurgingImageCache</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Classes/ImageDownloader.html">ImageDownloader</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Classes/ImageDownloader/DownloadPrioritization.html">– DownloadPrioritization</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Classes/ImageResponseSerializer.html">ImageResponseSerializer</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Classes/RequestReceipt.html">RequestReceipt</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="Enums.html">Enumerations</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="Enums/AFIError.html">AFIError</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="Extensions.html">Extensions</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="Extensions/AlamofireExtension.html">AlamofireExtension</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Extensions/DataRequest.html">DataRequest</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Extensions/DataRequest.html">DataRequest</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Extensions/UIButton.html">UIButton</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Extensions/UIImage.html">UIImage</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Extensions/UIImageView.html">UIImageView</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Extensions/UIImageView/ImageTransition.html">– ImageTransition</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="Protocols.html">Protocols</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="Protocols/CompositeImageFilter.html">CompositeImageFilter</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Protocols/CoreImageFilter.html">CoreImageFilter</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Protocols/ImageCache.html">ImageCache</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Protocols/ImageFilter.html">ImageFilter</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Protocols/ImageRequestCache.html">ImageRequestCache</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Protocols/Roundable.html">Roundable</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Protocols/Sizable.html">Sizable</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="Structs.html">Structures</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="Structs/AspectScaledToFillSizeCircleFilter.html">AspectScaledToFillSizeCircleFilter</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Structs/AspectScaledToFillSizeFilter.html">AspectScaledToFillSizeFilter</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Structs/AspectScaledToFillSizeWithRoundedCornersFilter.html">AspectScaledToFillSizeWithRoundedCornersFilter</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Structs/AspectScaledToFitSizeFilter.html">AspectScaledToFitSizeFilter</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Structs/BlurFilter.html">BlurFilter</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Structs/CircleFilter.html">CircleFilter</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Structs/DynamicCompositeImageFilter.html">DynamicCompositeImageFilter</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Structs/DynamicImageFilter.html">DynamicImageFilter</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Structs/RoundedCornersFilter.html">RoundedCornersFilter</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Structs/ScaledToSizeCircleFilter.html">ScaledToSizeCircleFilter</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Structs/ScaledToSizeFilter.html">ScaledToSizeFilter</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Structs/ScaledToSizeWithRoundedCornersFilter.html">ScaledToSizeWithRoundedCornersFilter</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="Typealiases.html">Type Aliases</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="Typealiases.html#/s:14AlamofireImage15AFIDataResponsea">AFIDataResponse</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Typealiases.html#/s:14AlamofireImage9AFIResulta">AFIResult</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Typealiases.html#/s:14AlamofireImage16AnimationOptionsa">AnimationOptions</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Typealiases.html#/s:14AlamofireImage12ControlStatea">ControlState</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Typealiases.html#/Image">Image</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="Typealiases.html#/s:14AlamofireImage0B0a">Image</a> </li> </ul> </li> </ul> </nav> <article class="main-content"> <section class="section"> <div class="section-content top-matter"> <h1>Classes</h1> <p>The following classes are available globally.</p> </div> </section> <section class="section"> <div class="section-content"> <div class="task-group"> <ul class="item-container"> <li class="item"> <div> <code> <a name="/s:14AlamofireImage011AutoPurgingB5CacheC"></a> <a name="//apple_ref/swift/Class/AutoPurgingImageCache" class="dashAnchor"></a> <a class="token" href="#/s:14AlamofireImage011AutoPurgingB5CacheC">AutoPurgingImageCache</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>The <code>AutoPurgingImageCache</code> in an in-memory image cache used to store images up to a given memory capacity. When the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the internal access date of the image is updated.</p> <a href="Classes/AutoPurgingImageCache.html" class="slightly-smaller">See more</a> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">open</span> <span class="kd">class</span> <span class="kt">AutoPurgingImageCache</span> <span class="p">:</span> <span class="kt"><a href="Protocols/ImageRequestCache.html">ImageRequestCache</a></span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:14AlamofireImage14RequestReceiptC"></a> <a name="//apple_ref/swift/Class/RequestReceipt" class="dashAnchor"></a> <a class="token" href="#/s:14AlamofireImage14RequestReceiptC">RequestReceipt</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>The <code>RequestReceipt</code> is an object vended by the <code><a href="Classes/ImageDownloader.html">ImageDownloader</a></code> when starting a download request. It can be used to cancel active requests running on the <code><a href="Classes/ImageDownloader.html">ImageDownloader</a></code> session. As a general rule, image download requests should be cancelled using the <code>RequestReceipt</code> instead of calling <code>cancel</code> directly on the <code>request</code> itself. The <code><a href="Classes/ImageDownloader.html">ImageDownloader</a></code> is optimized to handle duplicate request scenarios as well as pending versus active downloads.</p> <a href="Classes/RequestReceipt.html" class="slightly-smaller">See more</a> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">open</span> <span class="kd">class</span> <span class="kt">RequestReceipt</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:14AlamofireImage0B10DownloaderC"></a> <a name="//apple_ref/swift/Class/ImageDownloader" class="dashAnchor"></a> <a class="token" href="#/s:14AlamofireImage0B10DownloaderC">ImageDownloader</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>The <code>ImageDownloader</code> class is responsible for downloading images in parallel on a prioritized queue. Incoming downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded image is cached in the underlying <code>NSURLCache</code> as well as the in-memory image cache that supports image filters. By default, any download request with a cached image equivalent in the image cache will automatically be served the cached image representation. Additional advanced features include supporting multiple image filters and completion handlers for a single request.</p> <a href="Classes/ImageDownloader.html" class="slightly-smaller">See more</a> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">open</span> <span class="kd">class</span> <span class="kt">ImageDownloader</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:14AlamofireImage0B18ResponseSerializerC"></a> <a name="//apple_ref/swift/Class/ImageResponseSerializer" class="dashAnchor"></a> <a class="token" href="#/s:14AlamofireImage0B18ResponseSerializerC">ImageResponseSerializer</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Undocumented</p> <a href="Classes/ImageResponseSerializer.html" class="slightly-smaller">See more</a> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">final</span> <span class="kd">class</span> <span class="kt">ImageResponseSerializer</span> <span class="p">:</span> <span class="kt">ResponseSerializer</span></code></pre> </div> </div> </section> </div> </li> </ul> </div> </div> </section> </article> </div> <section class="footer"> <p>&copy; 2020 <a class="link" href="http://alamofire.org/" target="_blank" rel="external">Alamofire Software Foundation</a>. All rights reserved. (Last updated: 2020-04-05)</p> <p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.13.2</a>, a <a class="link" href="https://realm.io" target="_blank" rel="external">Realm</a> project.</p> </section> </body> </div> </html>
{ "pile_set_name": "Github" }
This is the code to build the parlai website. - `generate.py`: does the actual rendering - `static`: assets in this folder will be copied verbatim to parl.ai/static/ - `templates`: contains html templates for a variety of pages
{ "pile_set_name": "Github" }
/* * Common power driver for PDAs and phones with one or two external * power supplies (AC/USB) connected to main and backup batteries, * and optional builtin charger. * * Copyright © 2007 Anton Vorontsov <cbou@mail.ru> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/module.h> #include <linux/platform_device.h> #include <linux/err.h> #include <linux/interrupt.h> #include <linux/notifier.h> #include <linux/power_supply.h> #include <linux/pda_power.h> #include <linux/regulator/consumer.h> #include <linux/timer.h> #include <linux/jiffies.h> #include <linux/usb/otg.h> static inline unsigned int get_irq_flags(struct resource *res) { return IRQF_SHARED | (res->flags & IRQF_TRIGGER_MASK); } static struct device *dev; static struct pda_power_pdata *pdata; static struct resource *ac_irq, *usb_irq; static struct timer_list charger_timer; static struct timer_list supply_timer; static struct timer_list polling_timer; static int polling; static struct power_supply *pda_psy_ac, *pda_psy_usb; #if IS_ENABLED(CONFIG_USB_PHY) static struct usb_phy *transceiver; static struct notifier_block otg_nb; #endif static struct regulator *ac_draw; enum { PDA_PSY_OFFLINE = 0, PDA_PSY_ONLINE = 1, PDA_PSY_TO_CHANGE, }; static int new_ac_status = -1; static int new_usb_status = -1; static int ac_status = -1; static int usb_status = -1; static int pda_power_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { switch (psp) { case POWER_SUPPLY_PROP_ONLINE: if (psy->desc->type == POWER_SUPPLY_TYPE_MAINS) val->intval = pdata->is_ac_online ? pdata->is_ac_online() : 0; else val->intval = pdata->is_usb_online ? pdata->is_usb_online() : 0; break; default: return -EINVAL; } return 0; } static enum power_supply_property pda_power_props[] = { POWER_SUPPLY_PROP_ONLINE, }; static char *pda_power_supplied_to[] = { "main-battery", "backup-battery", }; static const struct power_supply_desc pda_psy_ac_desc = { .name = "ac", .type = POWER_SUPPLY_TYPE_MAINS, .properties = pda_power_props, .num_properties = ARRAY_SIZE(pda_power_props), .get_property = pda_power_get_property, }; static const struct power_supply_desc pda_psy_usb_desc = { .name = "usb", .type = POWER_SUPPLY_TYPE_USB, .properties = pda_power_props, .num_properties = ARRAY_SIZE(pda_power_props), .get_property = pda_power_get_property, }; static void update_status(void) { if (pdata->is_ac_online) new_ac_status = !!pdata->is_ac_online(); if (pdata->is_usb_online) new_usb_status = !!pdata->is_usb_online(); } static void update_charger(void) { static int regulator_enabled; int max_uA = pdata->ac_max_uA; if (pdata->set_charge) { if (new_ac_status > 0) { dev_dbg(dev, "charger on (AC)\n"); pdata->set_charge(PDA_POWER_CHARGE_AC); } else if (new_usb_status > 0) { dev_dbg(dev, "charger on (USB)\n"); pdata->set_charge(PDA_POWER_CHARGE_USB); } else { dev_dbg(dev, "charger off\n"); pdata->set_charge(0); } } else if (ac_draw) { if (new_ac_status > 0) { regulator_set_current_limit(ac_draw, max_uA, max_uA); if (!regulator_enabled) { dev_dbg(dev, "charger on (AC)\n"); WARN_ON(regulator_enable(ac_draw)); regulator_enabled = 1; } } else { if (regulator_enabled) { dev_dbg(dev, "charger off\n"); WARN_ON(regulator_disable(ac_draw)); regulator_enabled = 0; } } } } static void supply_timer_func(unsigned long unused) { if (ac_status == PDA_PSY_TO_CHANGE) { ac_status = new_ac_status; power_supply_changed(pda_psy_ac); } if (usb_status == PDA_PSY_TO_CHANGE) { usb_status = new_usb_status; power_supply_changed(pda_psy_usb); } } static void psy_changed(void) { update_charger(); /* * Okay, charger set. Now wait a bit before notifying supplicants, * charge power should stabilize. */ mod_timer(&supply_timer, jiffies + msecs_to_jiffies(pdata->wait_for_charger)); } static void charger_timer_func(unsigned long unused) { update_status(); psy_changed(); } static irqreturn_t power_changed_isr(int irq, void *power_supply) { if (power_supply == pda_psy_ac) ac_status = PDA_PSY_TO_CHANGE; else if (power_supply == pda_psy_usb) usb_status = PDA_PSY_TO_CHANGE; else return IRQ_NONE; /* * Wait a bit before reading ac/usb line status and setting charger, * because ac/usb status readings may lag from irq. */ mod_timer(&charger_timer, jiffies + msecs_to_jiffies(pdata->wait_for_status)); return IRQ_HANDLED; } static void polling_timer_func(unsigned long unused) { int changed = 0; dev_dbg(dev, "polling...\n"); update_status(); if (!ac_irq && new_ac_status != ac_status) { ac_status = PDA_PSY_TO_CHANGE; changed = 1; } if (!usb_irq && new_usb_status != usb_status) { usb_status = PDA_PSY_TO_CHANGE; changed = 1; } if (changed) psy_changed(); mod_timer(&polling_timer, jiffies + msecs_to_jiffies(pdata->polling_interval)); } #if IS_ENABLED(CONFIG_USB_PHY) static int otg_is_usb_online(void) { return (transceiver->last_event == USB_EVENT_VBUS || transceiver->last_event == USB_EVENT_ENUMERATED); } static int otg_is_ac_online(void) { return (transceiver->last_event == USB_EVENT_CHARGER); } static int otg_handle_notification(struct notifier_block *nb, unsigned long event, void *unused) { switch (event) { case USB_EVENT_CHARGER: ac_status = PDA_PSY_TO_CHANGE; break; case USB_EVENT_VBUS: case USB_EVENT_ENUMERATED: usb_status = PDA_PSY_TO_CHANGE; break; case USB_EVENT_NONE: ac_status = PDA_PSY_TO_CHANGE; usb_status = PDA_PSY_TO_CHANGE; break; default: return NOTIFY_OK; } /* * Wait a bit before reading ac/usb line status and setting charger, * because ac/usb status readings may lag from irq. */ mod_timer(&charger_timer, jiffies + msecs_to_jiffies(pdata->wait_for_status)); return NOTIFY_OK; } #endif static int pda_power_probe(struct platform_device *pdev) { struct power_supply_config psy_cfg = {}; int ret = 0; dev = &pdev->dev; if (pdev->id != -1) { dev_err(dev, "it's meaningless to register several " "pda_powers; use id = -1\n"); ret = -EINVAL; goto wrongid; } pdata = pdev->dev.platform_data; if (pdata->init) { ret = pdata->init(dev); if (ret < 0) goto init_failed; } ac_draw = regulator_get(dev, "ac_draw"); if (IS_ERR(ac_draw)) { dev_dbg(dev, "couldn't get ac_draw regulator\n"); ac_draw = NULL; } update_status(); update_charger(); if (!pdata->wait_for_status) pdata->wait_for_status = 500; if (!pdata->wait_for_charger) pdata->wait_for_charger = 500; if (!pdata->polling_interval) pdata->polling_interval = 2000; if (!pdata->ac_max_uA) pdata->ac_max_uA = 500000; setup_timer(&charger_timer, charger_timer_func, 0); setup_timer(&supply_timer, supply_timer_func, 0); ac_irq = platform_get_resource_byname(pdev, IORESOURCE_IRQ, "ac"); usb_irq = platform_get_resource_byname(pdev, IORESOURCE_IRQ, "usb"); if (pdata->supplied_to) { psy_cfg.supplied_to = pdata->supplied_to; psy_cfg.num_supplicants = pdata->num_supplicants; } else { psy_cfg.supplied_to = pda_power_supplied_to; psy_cfg.num_supplicants = ARRAY_SIZE(pda_power_supplied_to); } #if IS_ENABLED(CONFIG_USB_PHY) transceiver = usb_get_phy(USB_PHY_TYPE_USB2); if (!IS_ERR_OR_NULL(transceiver)) { if (!pdata->is_usb_online) pdata->is_usb_online = otg_is_usb_online; if (!pdata->is_ac_online) pdata->is_ac_online = otg_is_ac_online; } #endif if (pdata->is_ac_online) { pda_psy_ac = power_supply_register(&pdev->dev, &pda_psy_ac_desc, &psy_cfg); if (IS_ERR(pda_psy_ac)) { dev_err(dev, "failed to register %s power supply\n", pda_psy_ac_desc.name); ret = PTR_ERR(pda_psy_ac); goto ac_supply_failed; } if (ac_irq) { ret = request_irq(ac_irq->start, power_changed_isr, get_irq_flags(ac_irq), ac_irq->name, pda_psy_ac); if (ret) { dev_err(dev, "request ac irq failed\n"); goto ac_irq_failed; } } else { polling = 1; } } if (pdata->is_usb_online) { pda_psy_usb = power_supply_register(&pdev->dev, &pda_psy_usb_desc, &psy_cfg); if (IS_ERR(pda_psy_usb)) { dev_err(dev, "failed to register %s power supply\n", pda_psy_usb_desc.name); ret = PTR_ERR(pda_psy_usb); goto usb_supply_failed; } if (usb_irq) { ret = request_irq(usb_irq->start, power_changed_isr, get_irq_flags(usb_irq), usb_irq->name, pda_psy_usb); if (ret) { dev_err(dev, "request usb irq failed\n"); goto usb_irq_failed; } } else { polling = 1; } } #if IS_ENABLED(CONFIG_USB_PHY) if (!IS_ERR_OR_NULL(transceiver) && pdata->use_otg_notifier) { otg_nb.notifier_call = otg_handle_notification; ret = usb_register_notifier(transceiver, &otg_nb); if (ret) { dev_err(dev, "failure to register otg notifier\n"); goto otg_reg_notifier_failed; } polling = 0; } #endif if (polling) { dev_dbg(dev, "will poll for status\n"); setup_timer(&polling_timer, polling_timer_func, 0); mod_timer(&polling_timer, jiffies + msecs_to_jiffies(pdata->polling_interval)); } if (ac_irq || usb_irq) device_init_wakeup(&pdev->dev, 1); return 0; #if IS_ENABLED(CONFIG_USB_PHY) otg_reg_notifier_failed: if (pdata->is_usb_online && usb_irq) free_irq(usb_irq->start, pda_psy_usb); #endif usb_irq_failed: if (pdata->is_usb_online) power_supply_unregister(pda_psy_usb); usb_supply_failed: if (pdata->is_ac_online && ac_irq) free_irq(ac_irq->start, pda_psy_ac); #if IS_ENABLED(CONFIG_USB_PHY) if (!IS_ERR_OR_NULL(transceiver)) usb_put_phy(transceiver); #endif ac_irq_failed: if (pdata->is_ac_online) power_supply_unregister(pda_psy_ac); ac_supply_failed: if (ac_draw) { regulator_put(ac_draw); ac_draw = NULL; } if (pdata->exit) pdata->exit(dev); init_failed: wrongid: return ret; } static int pda_power_remove(struct platform_device *pdev) { if (pdata->is_usb_online && usb_irq) free_irq(usb_irq->start, pda_psy_usb); if (pdata->is_ac_online && ac_irq) free_irq(ac_irq->start, pda_psy_ac); if (polling) del_timer_sync(&polling_timer); del_timer_sync(&charger_timer); del_timer_sync(&supply_timer); if (pdata->is_usb_online) power_supply_unregister(pda_psy_usb); if (pdata->is_ac_online) power_supply_unregister(pda_psy_ac); #if IS_ENABLED(CONFIG_USB_PHY) if (!IS_ERR_OR_NULL(transceiver)) usb_put_phy(transceiver); #endif if (ac_draw) { regulator_put(ac_draw); ac_draw = NULL; } if (pdata->exit) pdata->exit(dev); return 0; } #ifdef CONFIG_PM static int ac_wakeup_enabled; static int usb_wakeup_enabled; static int pda_power_suspend(struct platform_device *pdev, pm_message_t state) { if (pdata->suspend) { int ret = pdata->suspend(state); if (ret) return ret; } if (device_may_wakeup(&pdev->dev)) { if (ac_irq) ac_wakeup_enabled = !enable_irq_wake(ac_irq->start); if (usb_irq) usb_wakeup_enabled = !enable_irq_wake(usb_irq->start); } return 0; } static int pda_power_resume(struct platform_device *pdev) { if (device_may_wakeup(&pdev->dev)) { if (usb_irq && usb_wakeup_enabled) disable_irq_wake(usb_irq->start); if (ac_irq && ac_wakeup_enabled) disable_irq_wake(ac_irq->start); } if (pdata->resume) return pdata->resume(); return 0; } #else #define pda_power_suspend NULL #define pda_power_resume NULL #endif /* CONFIG_PM */ static struct platform_driver pda_power_pdrv = { .driver = { .name = "pda-power", }, .probe = pda_power_probe, .remove = pda_power_remove, .suspend = pda_power_suspend, .resume = pda_power_resume, }; module_platform_driver(pda_power_pdrv); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Anton Vorontsov <cbou@mail.ru>"); MODULE_ALIAS("platform:pda-power");
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <graph xmlns="http://www.xces.org/ns/GrAF/1.0/"> <header> <tagsDecl> <tagUsage gi="s" occurs="13"/> </tagsDecl> <annotationSets> <annotationSet name="xces" type="http://www.xces.org/schema/2003"/> </annotationSets> </header> <region xml:id="s-r0" anchors="18 31"/> <region xml:id="s-r1" anchors="38 42"/> <region xml:id="s-r2" anchors="49 144"/> <region xml:id="s-r3" anchors="145 299"/> <region xml:id="s-r4" anchors="300 474"/> <region xml:id="s-r5" anchors="481 569"/> <region xml:id="s-r6" anchors="570 662"/> <region xml:id="s-r7" anchors="663 922"/> <region xml:id="s-r8" anchors="929 1180"/> <region xml:id="s-r9" anchors="1187 1350"/> <region xml:id="s-r10" anchors="1351 1448"/> <region xml:id="s-r11" anchors="1449 1499"/> <region xml:id="s-r12" anchors="1506 1565"/> <node xml:id="s-n0"> <link targets="s-r0"/> </node> <a label="s" ref="s-n0" as="xces"> <fs> <f name="id" value="p1s1"/> </fs> </a> <node xml:id="s-n1"> <link targets="s-r1"/> </node> <a label="s" ref="s-n1" as="xces"> <fs> <f name="id" value="p2s1"/> </fs> </a> <node xml:id="s-n10"> <link targets="s-r10"/> </node> <a label="s" ref="s-n10" as="xces"> <fs> <f name="id" value="p6s1.1"/> </fs> </a> <node xml:id="s-n11"> <link targets="s-r11"/> </node> <a label="s" ref="s-n11" as="xces"> <fs> <f name="id" value="p6s4"/> </fs> </a> <node xml:id="s-n12"> <link targets="s-r12"/> </node> <a label="s" ref="s-n12" as="xces"> <fs> <f name="id" value="p7s1"/> </fs> </a> <node xml:id="s-n2"> <link targets="s-r2"/> </node> <a label="s" ref="s-n2" as="xces"> <fs> <f name="id" value="p3s1"/> </fs> </a> <node xml:id="s-n3"> <link targets="s-r3"/> </node> <a label="s" ref="s-n3" as="xces"> <fs> <f name="id" value="p3s2"/> </fs> </a> <node xml:id="s-n4"> <link targets="s-r4"/> </node> <a label="s" ref="s-n4" as="xces"> <fs> <f name="id" value="p3s3"/> </fs> </a> <node xml:id="s-n5"> <link targets="s-r5"/> </node> <a label="s" ref="s-n5" as="xces"> <fs> <f name="id" value="p4s1"/> </fs> </a> <node xml:id="s-n6"> <link targets="s-r6"/> </node> <a label="s" ref="s-n6" as="xces"> <fs> <f name="id" value="p4s2"/> </fs> </a> <node xml:id="s-n7"> <link targets="s-r7"/> </node> <a label="s" ref="s-n7" as="xces"> <fs> <f name="id" value="p4s3"/> </fs> </a> <node xml:id="s-n8"> <link targets="s-r8"/> </node> <a label="s" ref="s-n8" as="xces"> <fs> <f name="id" value="p5s1"/> </fs> </a> <node xml:id="s-n9"> <link targets="s-r9"/> </node> <a label="s" ref="s-n9" as="xces"> <fs> <f name="id" value="p6s1"/> </fs> </a> </graph>
{ "pile_set_name": "Github" }
@ECHO OFF :LOOP IF "%1"=="" ( EXIT /B 255 ) IF "%1"=="--version" ( ECHO 0.0-cmake-dummy EXIT /B 0 ) IF "%1"=="--exists" ( SHIFT ECHO Expected: %* ECHO Found: %PKG_CONFIG_PATH% IF NOT "%*"=="%PKG_CONFIG_PATH%" ( EXIT /B 1 ) ELSE ( EXIT /B 0 ) ) SHIFT IF NOT "%~1"=="" GOTO LOOP EXIT /B 255
{ "pile_set_name": "Github" }
#!/usr/bin/env python3 # Copyright (c) 2015-2018 The Bitcoin Unlimited developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import test_framework.loginit import os import os.path import time import sys if sys.version_info[0] < 3: raise "Use Python 3" import logging from binascii import unhexlify from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * from test_framework.mininode import NetworkThread from test_framework.nodemessages import * from test_framework.bumessages import * from test_framework.bunode import BasicBUCashNode, VersionlessProtoHandler class XVersionTest(BitcoinTestFramework): def __init__(self): self.nodes = [] BitcoinTestFramework.__init__(self) def setup_chain(self): pass def setup_network(self, split=False): pass def restart_node(self, send_initial_version = True): # remove any potential banlist banlist_fn = os.path.join( node_regtest_dir(self.options.tmpdir, 0), "banlist.dat") logging.info("Banlist file name: " + str(banlist_fn)) try: os.remove(banlist_fn) logging.info("Removed old banlist %s.") except: pass stop_nodes(self.nodes) wait_bitcoinds() logging.info("Initializing test directory " + str(self.options.tmpdir)) initialize_chain_clean(self.options.tmpdir, 1) self.nodes = [ start_node(0, self.options.tmpdir, ["-debug=net", "-use-xversion=0"]) ] self.pynode = pynode = BasicBUCashNode() pynode.connect(0, '127.0.0.1', p2p_port(0), self.nodes[0], protohandler = VersionlessProtoHandler(), send_initial_version = send_initial_version) return pynode.cnxns[0] def network_and_finish(self): nt = NetworkThread() nt.start() nt.join() def run_test(self): logging.info("Testing xversion handling") ex1_xver = { 1 : b"2", 3 : b"4"} def test_too_early(msg): """ Test that the given message if it comes right after start up will lead to rejection / banning as it comes too early. """ logging.info("Testing that an an early %s fails." % msg) conn = self.restart_node(send_initial_version = False) conn.send_message(msg, pushbuf = True) self.network_and_finish() assert conn.disconnected # test failure due to early receipt if 0: for msg in [msg_xversion_old(), msg_xverack_old(), msg_xversion_old({1:b"2",3:b"45"})]: test_too_early(msg) # test regular set up including xversion conn = self.restart_node() nt = NetworkThread() nt.start() conn.wait_for_verack() conn.send_message(msg_verack()) # now it is time for xversion conn.wait_for(lambda : conn.remote_xversion) conn.send_message(msg_xversion_old({1000 : b"test string"})) conn.wait_for_xverack_old() conn.send_message(msg_xverack_old()) # make sure xversion has actually been received properly # test that it contains the BU_LISTEN_PORT (replacement for buversion message) # FIXME: use proper constant assert 1<<17 in conn.remote_xversion.xver.keys() # Likewise, check that the remote end got our message node = self.nodes[0] peer_info = node.getpeerinfo() assert len(peer_info) == 1 assert "xversion_map" in peer_info[0] xv_map = peer_info[0]["xversion_map"] assert len(xv_map) == 1 assert unhexlify(list(xv_map.values())[0]) == b"test string" # send xupdate to test what would happen if someone tries to update non-chaneable key conn.send_message(msg_xupdate({1000 : b"test string changed"})) # some arbitrary sleep time time.sleep(3); # nothing should have changed, 1000 is not listed as a changeable key node = self.nodes[0] peer_info = node.getpeerinfo() assert len(peer_info) == 1 assert "xversion_map" in peer_info[0] xv_map = peer_info[0]["xversion_map"] assert len(xv_map) == 1 assert unhexlify(list(xv_map.values())[0]) == b"test string" # send xupdate to test what would happen if someone tries to update a non-existant key conn.send_message(msg_xupdate({1111 : b"bad string"})) # some arbitrary sleep time time.sleep(3); # nothing should have changed, 1111 is not listed as a known key node = self.nodes[0] peer_info = node.getpeerinfo() assert len(peer_info) == 1 assert "xversion_map" in peer_info[0] xv_map = peer_info[0]["xversion_map"] assert len(xv_map) == 1 # TODO appent to this test to test a changeable key once one has been implemented in the node conn.connection.disconnect_node() nt.join() if __name__ == '__main__': xvt = XVersionTest() xvt.main()
{ "pile_set_name": "Github" }
[ { "name": "Container", "categories": [ "Basics" ], "subcategories": [ "拥有单个子元素的布局widget" ], "description": "一个拥有绘制、定位、调整大小的 widget。", "link": "https://docs.flutter.io/flutter/widgets/Container-class.html", "image": "<svg viewBox='0 0 100 100'><defs><marker id='arrow-container-1' orient='auto-start-reverse' viewBox='0 0 1 1' markerWidth='3' markerHeight='3' refX='0.5' refY='0.5'><path d='M 1 0.5 L 0.5 0 L 0.5 1 z' fill='#f50057'/></marker><marker id='arrow-container-2' orient='auto-start-reverse' viewBox='0 0 1 1' markerWidth='3' markerHeight='3' refX='0.5' refY='0.5'><path d='M 1 0.5 L 0.5 0 L 0.5 1 z' fill='#ffffff'/></marker><filter id='shadow-container' x='-50%' y='-50%' width='200%' height='200%'><feGaussianBlur stdDeviation='4'/></filter><linearGradient id='gradient-container' x1='0' y1='0.2' x2='0.4' y2='0.9'><stop offset='55%' stop-color='#ffffff'/><stop offset='100%' stop-color='#fdccdd'/></linearGradient></defs><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='15' y='25' width='70' height='47.5' rx='10' ry='10' fill='#000000' filter='url(#shadow-container)'/><rect x='15' y='25' width='70' height='47.5' rx='10' ry='10' fill='url(#gradient-container)' stroke-width='5' stroke='#3b75ad'/><rect x='30' y='40' width='40' height='30' fill='#4dd0e1'/><line x1='20' y1='55' x2='27' y2='55' stroke='#f50057' stroke-width='2' marker-start='url(#arrow-container-1)' marker-end='url(#arrow-container-1)'/><line x1='73' y1='55' x2='80' y2='55' stroke='#f50057' stroke-width='2' marker-start='url(#arrow-container-1)' marker-end='url(#arrow-container-1)'/><line x1='50' y1='30' x2='50' y2='37' stroke='#f50057' stroke-width='2' marker-start='url(#arrow-container-1)' marker-end='url(#arrow-container-1)'/><line x1='50' y1='78' x2='50' y2='82' stroke='#f50057' stroke-width='2' marker-start='url(#arrow-container-1)' marker-end='url(#arrow-container-1)'/><line x1='16' y1='17.5' x2='85' y2='17.5' stroke='#ffffff' stroke-width='2' marker-start='url(#arrow-container-2)' marker-end='url(#arrow-container-2)'/><line x1='7.5' y1='26' x2='7.5' y2='72' stroke='#ffffff' stroke-width='2' marker-start='url(#arrow-container-2)' marker-end='url(#arrow-container-2)'/></svg>" }, { "name": "Row", "description": "在水平方向上排列子widget的列表。", "categories": [ "Basics" ], "subcategories": [ "拥有多个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/Row-class.html", "image": "<svg viewBox='0 0 100 100'><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='10' y='30' width='80' height='40' fill='#ffffff'/><rect x='15' y='40' width='20' height='20' fill='#4dd0e1'/><rect x='40' y='35' width='30' height='30' fill='#4dd0e1'/></svg>" }, { "name": "Column", "description": "在垂直方向上排列子widget的列表。", "categories": [ "Basics" ], "subcategories": [ "拥有多个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/Column-class.html", "image": "<svg viewBox='0 0 100 100'><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='30' y='10' width='40' height='80' fill='#ffffff'/><rect x='40' y='15' width='20' height='20' fill='#4dd0e1'/><rect x='35' y='40' width='30' height='30' fill='#4dd0e1'/></svg>" }, { "name": "Image", "description": "一个显示图片的widget", "categories": [ "Basics", "Assets, Images, and Icons" ], "subcategories": [ "信息展示" ], "link": "https://docs.flutter.io/flutter/widgets/Image-class.html", "image": "<svg viewBox='0 0 100 100'><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='20' y='20' width='60' height='60' fill='#ffffff'/><image x='22.5' y='22.5' width='55' height='55' xlink:href='/images/owl.jpg'/></svg>" }, { "name": "Text", "description": "单一格式的文本", "categories": [ "Basics", "Text" ], "subcategories": [], "link": "https://docs.flutter.io/flutter/widgets/Text-class.html", "image": "<svg viewBox='0 0 100 100'><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='20' y='30' width='60' height='40' fill='#ffffff'/><text x='50' y='60' text-anchor='middle' font-family='Roboto' font-size='25' fill='#3b75ad'>Abc</text></svg>" }, { "name": "Icon", "description": "A Material Design icon.", "categories": [ "Basics", "Assets, Images, and Icons" ], "subcategories": [ "信息展示" ], "link": "https://docs.flutter.io/flutter/widgets/Icon-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "RaisedButton", "description": "Material Design中的button, 一个凸起的材质矩形按钮", "categories": [ "Basics" ], "subcategories": [ "按钮" ], "link": "https://docs.flutter.io/flutter/material/RaisedButton-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VbDh6YmNiYVc3SHM/components_buttons_usage2.png'>" }, { "name": "Scaffold", "sample": "Scaffold_index", "description": "Material Design布局结构的基本实现。此类提供了用于显示drawer、snackbar和底部sheet的API。", "categories": [ "Basics" ], "subcategories": [ "App结构和导航" ], "link": "https://docs.flutter.io/flutter/material/Scaffold-class.html", "image": "<img alt='' src='https://storage.googleapis.com/material-design/publish/material_v_11/assets/0Bx4BSt6jniD7T0hfM01sSmRyTG8/layout_structure_regions_mobile.png'>" }, { "name": "Appbar", "sample": "AppBar_index", "description": "一个Material Design应用程序栏,由工具栏和其他可能的widget(如TabBar和FlexibleSpaceBar)组成。", "categories": [ "Basics" ], "subcategories": [ "App结构和导航" ], "link": "https://docs.flutter.io/flutter/material/AppBar-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VclpfSFpuelBGR1k/components_toolbars.png'>" }, { "name": "FlutterLogo", "description": "Flutter logo, 以widget形式. 这个widget遵从IconTheme。", "categories": [ "Basics" ], "subcategories": [], "link": "https://docs.flutter.io/flutter/material/FlutterLogo-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "Stack", "description": "可以允许其子widget简单的堆叠在一起", "categories": [ "Stack" ], "subcategories": [ "拥有多个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/Stack-class.html", "image": "<svg viewBox='0 0 100 100'><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='10' y='10' width='80' height='80' fill='#ffffff'/><rect x='25' y='25' width='40' height='30' fill='#3b75ad'/><rect x='45' y='35' width='30' height='30' fill='#4dd0e1'/><rect x='40' y='50' width='10' height='10' fill='#f50057'/></svg>" }, { "name": "Placeholder", "description": "一个绘制了一个盒子的的widget,代表日后有widget将会被添加到该盒子中", "categories": [ "Basics" ], "subcategories": [], "link": "https://docs.flutter.io/flutter/widgets/Placeholder-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "BottomNavigationBar", "description": "底部导航条,可以很容易地在tap之间切换和浏览顶级视图。", "categories": [], "subcategories": [ "App结构和导航" ], "link": "https://docs.flutter.io/flutter/material/BottomNavigationBar-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VWG5nei0wWXpoczA/components_bottom_navigation.png'>" }, { "name": "TabBar", "sample": "TabBar_index", "description": "一个显示水平选项卡的Material Design widget。", "categories": [], "subcategories": [ "App结构和导航" ], "link": "https://docs.flutter.io/flutter/material/TabBar-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VaWdBdnhMT3ViXzQ/components_tabs.png'>" }, { "name": "TabBarView", "sample": "TabBarView_index", "description": "显示与当前选中的选项卡相对应的页面视图。通常和TabBar一起使用。", "categories": [], "subcategories": [ "App结构和导航" ], "link": "https://docs.flutter.io/flutter/material/TabBarView-class.html", "image": "<img alt='' src='https://storage.googleapis.com/material-design/publish/material_v_11/assets/0B7WCemMG6e0VaWdBdnhMT3ViXzQ/components_tabs.png'>" }, { "name": "MaterialApp", "description": "一个方便的widget,它封装了应用程序实现Material Design所需要的一些widget。", "categories": [], "subcategories": [ "App结构和导航" ], "link": "https://docs.flutter.io/flutter/material/MaterialApp-class.html", "image": "<img alt='' src='https://storage.googleapis.com/material-design/publish/material_v_11/assets/0Bx4BSt6jniD7Y1huOXVQdlFPMmM/materialdesign_introduction.png'>" }, { "name": "WidgetsApp", "description": "一个方便的类,它封装了应用程序通常需要的一些widget。", "categories": [], "subcategories": [ "App结构和导航" ], "link": "https://docs.flutter.io/flutter/widgets/WidgetsApp-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "Drawer", "description": "从Scaffold边缘水平滑动以显示应用程序中导航链接的Material Design面板。", "categories": [], "subcategories": [ "App结构和导航" ], "link": "https://docs.flutter.io/flutter/material/Drawer-class.html", "image": "<img alt='' src='https://storage.googleapis.com/material-design/publish/material_v_11/assets/0B7WCemMG6e0VaDhWUXJTTng4ZGs/patterns_navigation_drawer.png'>" }, { "name": "FloatingActionButton", "description": "一个圆形图标按钮,它悬停在内容之上,以展示应用程序中的主要动作。FloatingActionButton通常用于Scaffold.floatingActionButton字段。", "categories": [], "subcategories": [ "按钮" ], "link": "https://docs.flutter.io/flutter/material/FloatingActionButton-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VN20tOXJoUjVxQjg/components_buttons_fab.png'>" }, { "name": "FlatButton", "description": "一个扁平的Material按钮", "categories": [], "subcategories": [ "按钮" ], "link": "https://docs.flutter.io/flutter/material/FlatButton-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VNDg3V3ZjU2hsNGc/components_buttons_usage3.png'>" }, { "name": "IconButton", "sample": "IconButton_index", "description": "一个Material图标按钮,点击时会有水波动画", "categories": [], "subcategories": [ "按钮" ], "link": "https://docs.flutter.io/flutter/material/IconButton-class.html", "image": "<img alt='' src='https://storage.googleapis.com/material-design/publish/material_v_11/assets/0B_udO5B8pzrzdXVuTlBoOTBjcU0/components_buttons_other1.png'>" }, { "name": "PopupMenuButton", "sample": "PopupMenuButton_index", "description": "当菜单隐藏式,点击或调用onSelected时显示一个弹出式菜单列表", "categories": [], "subcategories": [ "按钮" ], "link": "https://docs.flutter.io/flutter/material/PopupMenuButton-class.html", "image": "<img alt='' src='https://storage.googleapis.com/material-design/publish/material_v_11/assets/0B7WCemMG6e0VakJ6a0F2MFJaaDQ/components_menus.png'>" }, { "name": "ButtonBar", "description": "水平排列的按钮组", "categories": [], "subcategories": [ "按钮" ], "link": "https://docs.flutter.io/flutter/material/ButtonBar-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "TextField", "description": "文本输入框", "categories": [], "subcategories": [ "输入框和选择框" ], "link": "https://docs.flutter.io/flutter/material/TextField-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VbURLNTM0N0R6eUE/components_text_fields.png'>" }, { "name": "Checkbox", "description": "复选框,允许用户从一组中选择多个选项。", "categories": [], "subcategories": [ "输入框和选择框" ], "link": "https://docs.flutter.io/flutter/material/Checkbox-class.html", "image": "<img alt='' src='https://storage.googleapis.com/material-design/publish/material_v_9/0Bx4BSt6jniD7T2xGbGo0cUlPVG8/components_switches_check1.png'>" }, { "name": "Radio", "description": "单选框,允许用户从一组中选择一个选项。 ", "categories": [], "subcategories": [ "输入框和选择框" ], "link": "https://docs.flutter.io/flutter/material/Radio-class.html", "image": "<img alt='' src='https://storage.googleapis.com/material-design/publish/material_v_9/0Bx4BSt6jniD7Z1NaaXh2ZkpDRkE/components_switches_radio1.png'>" }, { "name": "Switch", "description": "On/off 用于切换一个单一状态", "categories": [], "subcategories": [ "输入框和选择框" ], "link": "https://docs.flutter.io/flutter/material/Switch-class.html", "image": "<img alt='' src='https://storage.googleapis.com/material-design/publish/material_v_9/0Bx4BSt6jniD7NDg4aGIzVXYxVEE/components_switches_switch1.png'>" }, { "name": "Slider", "description": "滑块,允许用户通过滑动滑块来从一系列值中选择。", "categories": [], "subcategories": [ "输入框和选择框" ], "link": "https://docs.flutter.io/flutter/material/Slider-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VTmJrQUYzajFIclE/components_sliders.png'>" }, { "name": "Date & Time Pickers", "description": "日期&时间选择器", "categories": [], "subcategories": [ "输入框和选择框" ], "link": "https://docs.flutter.io/flutter/material/showDatePicker.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VY2h4WElGdEhPb2c/components_pickers.png'>" }, { "name": "SimpleDialog", "description": "简单对话框可以显示附加的提示或操作", "categories": [], "subcategories": [ "对话框、Alert、Panel" ], "link": "https://docs.flutter.io/flutter/material/SimpleDialog-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VVGNnN3NvMGdoQTg/components_dialogs.png'>" }, { "name": "AlertDialog", "description": "一个会中断用户操作的对话款,需要用户确认", "categories": [], "subcategories": [ "对话框、Alert、Panel" ], "link": "https://docs.flutter.io/flutter/material/AlertDialog-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0Bzhp5Z4wHba3TzFHYVlrbWF2bnM/components_alerts_1.png'>" }, { "name": "BottomSheet", "description": "BottomSheet是一个从屏幕底部滑起的列表(以显示更多的内容)。你可以调用showBottomSheet()或showModalBottomSheet弹出", "categories": [], "subcategories": [ "对话框、Alert、Panel" ], "link": "https://docs.flutter.io/flutter/material/BottomSheet-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VVWZzZ1FIN09XWGc/components_bottom_sheets.png'>" }, { "name": "ExpansionPanel", "description": "Expansion panels contain creation flows and allow lightweight editing of an element. The ExpansionPanel widget implements this component.", "categories": [], "subcategories": [ "对话框、Alert、Panel" ], "link": "https://docs.flutter.io/flutter/material/ExpansionPanel-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VOXF3eEJ3azZMSjg/components_expansion_panels.png'>" }, { "name": "SnackBar", "description": "具有可选操作的轻量级消息提示,在屏幕的底部显示。", "categories": [], "subcategories": [ "对话框、Alert、Panel" ], "link": "https://docs.flutter.io/flutter/material/SnackBar-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VSjZkendtc19iZ2M/components_snackbars.png'>" }, { "name": "Chip", "description": "标签,一个Material widget。 它可以将一个复杂内容实体展现在一个小块中,如联系人。", "categories": [], "subcategories": [ "信息展示" ], "link": "https://docs.flutter.io/flutter/material/Chip-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VM1VORGxxWUx5U0E/components_chips.png'>" }, { "name": "Tooltip", "description": "一个文本提示工具,帮助解释一个按钮或其他用户界面,当widget长时间按下时(当用户采取其他适当操作时)显示一个提示标签。", "categories": [], "subcategories": [ "信息展示" ], "link": "https://docs.flutter.io/flutter/material/Tooltip-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VZ1JKMzJFcmhOWkk/components_tooltips.png'>" }, { "name": "DataTable", "description": "数据表显示原始数据集。它们通常出现在桌面企业产品中。DataTable Widget实现这个组件", "categories": [], "subcategories": [ "信息展示" ], "link": "https://docs.flutter.io/flutter/material/DataTable-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VWTJHMmJZdWZ5LU0/components_data_tables.png'>" }, { "name": "Card", "description": "一个 Material Design 卡片。拥有一个圆角和阴影 ", "categories": [], "subcategories": [ "信息展示" ], "link": "https://docs.flutter.io/flutter/material/Card-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VR0ptbC1RV1NLNlk/components_cards.png'>" }, { "name": "LinearProgressIndicator", "description": "一个线性进度条,另外还有一个圆形进度条CircularProgressIndicator", "categories": [], "subcategories": [ "信息展示" ], "link": "https://docs.flutter.io/flutter/material/LinearProgressIndicator-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VWkJiRjRLbzRNS3M/components_progress_and_activity.png'>" }, { "name": "ListTile", "description": "一个固定高度的行,通常包含一些文本,以及一个行前或行尾图标。", "categories": [], "subcategories": [ "布局" ], "link": "https://docs.flutter.io/flutter/material/ListTile-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0Bx4BSt6jniD7UUw0bzVwU2lMUHc/components_lists_keylines_single10.png'>" }, { "name": "Stepper", "description": "一个Material Design 步骤指示器,显示一系列步骤的过程", "categories": [], "subcategories": [ "布局" ], "link": "https://docs.flutter.io/flutter/material/Stepper-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VTndyUnNCR2tQREE/components_steppers.png'>" }, { "name": "Divider", "description": "一个逻辑1像素厚的水平分割线,两边都有填充", "categories": [], "subcategories": [ "布局" ], "link": "https://docs.flutter.io/flutter/material/Divider-class.html", "image": "<img alt='' src='https://material-design.storage.googleapis.com/publish/material_v_9/0B7WCemMG6e0VUVlmbHM1Q013RU0/components_dividers.png'>" }, { "name": "CupertinoActivityIndicator", "description": "一个iOS风格的loading指示器。显示一个圆形的转圈菊花", "categories": [ "Cupertino (iOS-style widgets)" ], "subcategories": [], "link": "https://docs.flutter.io/flutter/cupertino/CupertinoActivityIndicator-class.html", "image": "<img alt='' src='/images/widget-catalog/cupertino-activity-indicator.png'>" }, { "name": "CupertinoAlertDialog", "description": "iOS风格的alert dialog.", "categories": [ "Cupertino (iOS-style widgets)" ], "subcategories": [], "link": "https://docs.flutter.io/flutter/cupertino/CupertinoAlertDialog-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "CupertinoButton", "description": "iOS风格的button.", "categories": [ "Cupertino (iOS-style widgets)" ], "subcategories": [], "link": "https://docs.flutter.io/flutter/cupertino/CupertinoButton-class.html", "image": "<img alt='' src='/images/widget-catalog/cupertino-button.png'>" }, { "name": "CupertinoDialog", "description": "iOS风格的对话框", "categories": [ "Cupertino (iOS-style widgets)" ], "subcategories": [], "link": "https://docs.flutter.io/flutter/cupertino/CupertinoDialog-class.html", "image": "<img alt='' src='/images/widget-catalog/cupertino-dialog.png'>" }, { "name": "CupertinoDialogAction", "description": "通常用于CupertinoAlertDialog的一个button", "categories": [ "Cupertino (iOS-style widgets)" ], "subcategories": [], "link": "https://docs.flutter.io/flutter/cupertino/CupertinoDialogAction-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "CupertinoSlider", "description": "从一个范围中选一个值.", "categories": [ "Cupertino (iOS-style widgets)" ], "subcategories": [], "link": "https://docs.flutter.io/flutter/cupertino/CupertinoSlider-class.html", "image": "<img alt='' src='/images/widget-catalog/cupertino-slider.png'>" }, { "name": "CupertinoSwitch", "description": "iOS风格的开关. 用于单一状态的开/关", "categories": [ "Cupertino (iOS-style widgets)" ], "subcategories": [], "link": "https://docs.flutter.io/flutter/cupertino/CupertinoSwitch-class.html", "image": "<img alt='' src='/images/widget-catalog/cupertino-switch.png'>" }, { "name": "CupertinoPageTransition", "description": "提供iOS风格的页面过度动画", "categories": [ "Cupertino (iOS-style widgets)" ], "subcategories": [], "link": "https://docs.flutter.io/flutter/cupertino/CupertinoPageTransition-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "CupertinoFullscreenDialogTransition", "description": "一个iOS风格的过渡,用于调用全屏对话框。", "categories": [ "Cupertino (iOS-style widgets)" ], "subcategories": [], "link": "https://docs.flutter.io/flutter/cupertino/CupertinoFullscreenDialogTransition-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "CupertinoNavigationBar", "description": "iOS风格的导航栏. 通常和CupertinoPageScaffold一起使用。", "categories": [ "Cupertino (iOS-style widgets)" ], "subcategories": [], "link": "https://docs.flutter.io/flutter/cupertino/CupertinoNavigationBar-class.html", "image": "<img alt='' src='/images/widget-catalog/cupertino-nav-bar.png'>" }, { "name": "CupertinoTabBar", "description": "iOS风格的底部选项卡。 通常和CupertinoTabScaffold一起使用。", "categories": [ "Cupertino (iOS-style widgets)" ], "subcategories": [], "link": "https://docs.flutter.io/flutter/cupertino/CupertinoTabBar-class.html", "image": "<img alt='' src='/images/widget-catalog/cupertino-tab-bar.png'>" }, { "name": "CupertinoPageScaffold", "description": "一个iOS风格的页面的基本布局结构。包含内容和导航栏", "categories": [ "Cupertino (iOS-style widgets)" ], "subcategories": [], "link": "https://docs.flutter.io/flutter/cupertino/CupertinoPageScaffold-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "CupertinoTabScaffold", "description": "标签式iOS应用程序的结构。将选项卡栏放在内容选项卡之上", "categories": [ "Cupertino (iOS-style widgets)" ], "subcategories": [], "link": "https://docs.flutter.io/flutter/cupertino/CupertinoTabScaffold-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "CupertinoTabView", "description": "支持选项卡间并行导航项卡的根内容。通常与CupertinoTabScaffolde一起使用", "categories": [ "Cupertino (iOS-style widgets)" ], "subcategories": [], "link": "https://docs.flutter.io/flutter/cupertino/CupertinoTabView-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "Padding", "description": "一个widget, 会给其子widget添加指定的填充", "categories": [ "Styling" ], "subcategories": [ "拥有单个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/Padding-class.html", "image": "<svg viewBox='0 0 100 100'><defs><marker id='arrow-padding' orient='auto-start-reverse' viewBox='0 0 1 1' markerWidth='3' markerHeight='3' refX='0.5' refY='0.5'><path d='M 1 0.5 L 0.5 0 L 0.5 1 z' fill='#f50057'/></marker></defs><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='10' y='20' width='80' height='60' fill='#ffffff'/><rect x='25' y='30' width='50' height='30' fill='#4dd0e1'/><line x1='13' y1='45' x2='22' y2='45' stroke='#f50057' stroke-width='2' marker-start='url(#arrow-padding)' marker-end='url(#arrow-padding)'/><line x1='78' y1='45' x2='87' y2='45' stroke='#f50057' stroke-width='2' marker-start='url(#arrow-padding)' marker-end='url(#arrow-padding)'/><line x1='50' y1='23' x2='50' y2='27' stroke='#f50057' stroke-width='2' marker-start='url(#arrow-padding)' marker-end='url(#arrow-padding)'/><line x1='50' y1='63' x2='50' y2='77' stroke='#f50057' stroke-width='2' marker-start='url(#arrow-padding)' marker-end='url(#arrow-padding)'/></svg>" }, { "name": "Center", "description": "将其子widget居中显示在自身内部的widget", "categories": [ ], "subcategories": [ "拥有单个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/Center-class.html", "image": "<svg viewBox='0 0 100 100'><defs><marker id='arrow-center' orient='auto-start-reverse' viewBox='0 0 1 1' markerWidth='3' markerHeight='3' refX='0.5' refY='0.5'><path d='M 1 0.5 L 0.5 0 L 0.5 1 z' fill='#f50057'/></marker></defs><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='10' y='20' width='80' height='60' fill='#ffffff'/><rect x='25' y='35' width='50' height='30' fill='#4dd0e1'/><line x1='10' y1='50' x2='22' y2='50' stroke='#f50057' stroke-width='2' marker-end='url(#arrow-center)'/><line x1='90' y1='50' x2='78' y2='50' stroke='#f50057' stroke-width='2' marker-end='url(#arrow-center)'/><line x1='50' y1='20' x2='50' y2='32' stroke='#f50057' stroke-width='2' marker-end='url(#arrow-center)'/><line x1='50' y1='80' x2='50' y2='68' stroke='#f50057' stroke-width='2' marker-end='url(#arrow-center)'/></svg>" }, { "name": "Align", "description": "一个widget,它可以将其子widget对齐,并可以根据子widget的大小自动调整大小。", "categories": [ ], "subcategories": [ "拥有单个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/Align-class.html", "image": "<svg viewBox='0 0 100 100'><defs><marker id='arrow-align' orient='auto-start-reverse' viewBox='0 0 1 1' markerWidth='3' markerHeight='3' refX='0.5' refY='0.5'><path d='M 1 0.5 L 0.5 0 L 0.5 1 z' fill='#f50057'/></marker></defs><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='10' y='20' width='80' height='60' fill='#ffffff'/><rect x='15' y='50' width='50' height='30' fill='#4dd0e1'/><line x1='10' y1='65' x2='12' y2='65' stroke='#f50057' stroke-width='2' marker-end='url(#arrow-align)'/><line x1='90' y1='65' x2='68' y2='65' stroke='#f50057' stroke-width='2' marker-end='url(#arrow-align)'/><line x1='40' y1='20' x2='40' y2='47' stroke='#f50057' stroke-width='2' marker-end='url(#arrow-align)'/></svg>" }, { "name": "FittedBox", "description": "按自己的大小调整其子widget的大小和位置。", "categories": [ ], "subcategories": [ "拥有单个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/FittedBox-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "AspectRatio", "description": "一个widget,试图将子widget的大小指定为某个特定的长宽比", "categories": [ ], "subcategories": [ "拥有单个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/AspectRatio-class.html", "image": "<svg viewBox='0 0 100 100'><defs><marker id='arrow-aspect-ratio' orient='auto-start-reverse' viewBox='0 0 1 1' markerWidth='3' markerHeight='3' refX='0.5' refY='0.5'><path d='M 1 0.5 L 0.5 0 L 0.5 1 z' fill='#ffffff'/></marker></defs><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='25' y='35' width='50' height='30' fill='#ffffff'/><rect x='27.5' y='37.5' width='45' height='25' fill='#4dd0e1'/><line x1='31' y1='41' x2='69' y2='59' stroke='#ffffff' stroke-width='2' marker-start='url(#arrow-aspect-ratio)' marker-end='url(#arrow-aspect-ratio)'/></svg>" }, { "name": "ConstrainedBox", "description": "对其子项施加附加约束的widget", "categories": [ ], "subcategories": [ "拥有单个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/ConstrainedBox-class.html", "image": "<svg viewBox='0 0 100 100'><defs><marker id='arrow-constrained-box' orient='auto-start-reverse' viewBox='0 0 1 1' markerWidth='3' markerHeight='3' refX='0.5' refY='0.5'><path d='M 1 0.5 L 0.5 0 L 0.5 1 z' fill='#ffffff'/></marker></defs><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='20' y='30' width='50' height='40' fill='#ffffff'/><rect x='22.5' y='32.5' width='45' height='35' fill='#4dd0e1'/><path d='M63 23 v 40' stroke='#ffffff' stroke-width='1' stroke-linecap='round' stroke-dasharray='0.5 3.1' fill='transparent'/><path d='M77 23 v 54' stroke='#ffffff' stroke-width='1' stroke-linecap='round' stroke-dasharray='0.5 3.1' fill='transparent'/><path d='M13 63 h 50' stroke='#ffffff' stroke-width='1' stroke-linecap='round' stroke-dasharray='0.5 3.1' fill='transparent'/><path d='M13 77 h 64' stroke='#ffffff' stroke-width='1' stroke-linecap='round' stroke-dasharray='0.5 3.1' fill='transparent'/><path d='M50 25 L60 25' stroke='#ffffff' stroke-width='2' marker-end='url(#arrow-constrained-box)'/><path d='M90 25 L80 25' stroke='#ffffff' stroke-width='2' marker-end='url(#arrow-constrained-box)'/><path d='M15 50 L15 60' stroke='#ffffff' stroke-width='2' marker-end='url(#arrow-constrained-box)'/><path d='M15 90 L15 80' stroke='#ffffff' stroke-width='2' marker-end='url(#arrow-constrained-box)'/></svg>" }, { "name": "Baseline", "description": "根据子项的基线对它们的位置进行定位的widget。", "categories": [ ], "subcategories": [ "拥有单个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/Baseline-class.html", "image": "<svg viewBox='0 0 100 100'><defs><marker id='arrow-baseline' orient='auto-start-reverse' viewBox='0 0 1 1' markerWidth='3' markerHeight='3' refX='0.5' refY='0.5'><path d='M 1 0.5 L 0.5 0 L 0.5 1 z' fill='#ffffff'/></marker></defs><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='20' y='20' width='60' height='50' fill='#ffffff'/><rect x='20' y='45' width='60' height='30' fill='#4dd0e1'/><line x1='85' y1='20' x2='85' y2='66' stroke='#ffffff' stroke-width='2' marker-end='url(#arrow-baseline)'/><line x1='15' y1='20' x2='15' y2='66' stroke='#ffffff' stroke-width='2' marker-end='url(#arrow-baseline)'/><line x1='10' y1='70' x2='90' y2='70' stroke='#ffffff' stroke-width='2'/><text x='50' y='69' text-anchor='middle' font-family='Roboto' font-size='25' fill='#3b75ad'>Abc </text></svg>" }, { "name": "FractionallySizedBox", "description": "一个widget,它把它的子项放在可用空间的一小部分。关于布局算法的更多细节,见RenderFractionallySizedOverflowBox", "categories": [ ], "subcategories": [ "拥有单个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/FractionallySizedBox-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "IntrinsicHeight", "description": "一个widget,它将它的子widget的高度调整其本身实际的高度", "categories": [ ], "subcategories": [ "拥有单个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/IntrinsicHeight-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "IntrinsicWidth", "description": "一个widget,它将它的子widget的宽度调整其本身实际的宽度", "categories": [ ], "subcategories": [ "拥有单个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/IntrinsicWidth-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "LimitedBox", "description": "一个当其自身不受约束时才限制其大小的盒子", "categories": [ ], "subcategories": [ "拥有单个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/LimitedBox-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "Offstage", "description": "一个布局widget,可以控制其子widget的显示和隐藏。", "categories": [ ], "subcategories": [ "拥有单个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/Offstage-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "OverflowBox", "description": "对其子项施加不同约束的widget,它可能允许子项溢出父级。", "categories": [ ], "subcategories": [ "拥有单个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/OverflowBox-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "SizedBox", "description": "一个特定大小的盒子。这个widget强制它的孩子有一个特定的宽度和高度。如果宽度或高度为NULL,则此widget将调整自身大小以匹配该维度中的孩子的大小。", "categories": [ ], "subcategories": [ "拥有单个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/SizedBox-class.html", "image": "<svg viewBox='0 0 100 100'><defs><marker id='arrow-sized-box' orient='auto-start-reverse' viewBox='0 0 1 1' markerWidth='3' markerHeight='3' refX='0.5' refY='0.5'><path d='M 1 0.5 L 0.5 0 L 0.5 1 z' fill='#ffffff'/></marker></defs><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='25' y='35' width='50' height='30' fill='#ffffff'/><rect x='27.5' y='37.5' width='45' height='25' fill='#4dd0e1'/><line x1='28' y1='30' x2='72' y2='30' stroke='#ffffff' stroke-width='2' marker-start='url(#arrow-sized-box)' marker-end='url(#arrow-sized-box)'/><line x1='20' y1='38' x2='20' y2='62' stroke='#ffffff' stroke-width='2' marker-start='url(#arrow-sized-box)' marker-end='url(#arrow-sized-box)'/></svg>" }, { "name": "SizedOverflowBox", "description": "一个特定大小的widget,但是会将它的原始约束传递给它的孩子,它可能会溢出。", "categories": [ ], "subcategories": [ "拥有单个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/SizedOverflowBox-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "Transform", "description": "在绘制子widget之前应用转换的widget。", "categories": [ ], "subcategories": [ "拥有单个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/Transform-class.html", "image": "<svg viewBox='0 0 100 100'><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='17.5' y='42.5' width='50' height='30' fill='#ffffff'/><rect x='20' y='45' width='45' height='25' fill='#3b75ad'/><rect x='20' y='45' width='45' height='25' fill='#4dd0e1' transform='translate(15 -5) rotate(-23) skewX(-10)'/></svg>" }, { "name": "CustomSingleChildLayout", "description": "一个自定义的拥有单个子widget的布局widget", "categories": [ ], "subcategories": [ "拥有单个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/CustomSingleChildLayout-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "IndexedStack", "description": "从一个子widget列表中显示单个孩子的Stack", "categories": [ ], "subcategories": [ "拥有多个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/IndexedStack-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "Flow", "description": "一个实现流式布局算法的widget", "categories": [ ], "subcategories": [ "拥有多个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/Flow-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "Table", "description": "为其子widget使用表格布局算法的widget", "categories": [ ], "subcategories": [ "拥有多个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/Table-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "Wrap", "description": "可以在水平或垂直方向多行显示其子widget。", "categories": [ ], "subcategories": [ "拥有多个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/Wrap-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "ListBody", "description": "一个widget,它沿着一个给定的轴,顺序排列它的子元素", "categories": [ ], "subcategories": [ "拥有多个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/ListBody-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "ListView", "sample": "ListView_index", "description": "可滚动的列表控件。ListView是最常用的滚动widget,它在滚动方向上一个接一个地显示它的孩子。在纵轴上,孩子们被要求填充ListView。", "categories": [ ], "subcategories": [ "拥有多个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/ListView-class.html", "image": "<svg viewBox='0 0 100 100'><filter id='inset-shadow-block' x='-50%' y='-50%' width='200%' height='200%'><feComponentTransfer in='SourceAlpha'><feFuncA type='table' tableValues='1 0' /></feComponentTransfer><feGaussianBlur stdDeviation='2' result='Blur'/><feFlood flood-color='#666666' result='color'/><feComposite in2='Blur' operator='in'/><feComposite in2='SourceAlpha' operator='in' /><feMerge><feMergeNode /></feMerge></filter><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='30' y='10' width='40' height='80' fill='#ffffff'/><rect x='35' y='10' width='30' height='15' fill='#4dd0e1'/><rect x='35' y='30' width='30' height='20' fill='#4dd0e1'/><rect x='35' y='55' width='30' height='5' fill='#4dd0e1'/><rect x='35' y='65' width='30' height='15' fill='#4dd0e1'/><rect x='35' y='85' width='30' height='5' fill='#4dd0e1'/><rect x='30' y='10' width='40' height='80' fill='#ffffff' filter='url(#inset-shadow-block)'/></svg>" }, { "name": "CustomMultiChildLayout", "description": "使用一个委托来对多个孩子进行设置大小和定位的小部件", "categories": [ ], "subcategories": [ "拥有多个子元素的布局widget" ], "link": "https://docs.flutter.io/flutter/widgets/CustomMultiChildLayout-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "LayoutBuilder", "description": "构建一个可以依赖父窗口大小的widget树。", "categories": [ ], "subcategories": [ "Layout helpers" ], "link": "https://docs.flutter.io/flutter/widgets/LayoutBuilder-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "RichText", "description": "一个富文本Text,可以显示多种样式的text。", "categories": [ "Text" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/RichText-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "DefaultTextStyle", "description": "文字样式,用于指定Text widget的文字样式", "categories": [ "Text" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/DefaultTextStyle-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "RawImage", "description": "一个直接显示dart:ui.Image的widget", "categories": [ "Assets, Images, and Icons" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/RawImage-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "AssetBundle", "description": "包含应用程序可以使用的资源,如图像和字符串。对这些资源的访问是异步,所以他们可以来自网络(例如,从NetworkAssetBundle)或从本地文件系统,这并不会挂起用户界面。", "categories": [ "Assets, Images, and Icons" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/services/AssetBundle-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "Form", "description": "一个可选的、用于给多个TextField分组的widget", "categories": [ "Input" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/Form-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "FormField", "description": "一个单独的表单字段。此widget维护表单字段的当前状态,以便在UI中直观地反映更新和验证错误。", "categories": [ "Input" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/FormField-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "RawKeyboardListener", "description": "每当用户按下或释放键盘上的键时调用回调的widget。", "categories": [ "Input" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/RawKeyboardListener-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "AnimatedContainer", "description": "在一段时间内逐渐改变其值的容器。", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/AnimatedContainer-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "AnimatedCrossFade", "description": "一个widget,在两个孩子之间交叉淡入,并同时调整他们的尺寸", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/AnimatedCrossFade-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "Hero", "description": "将其子项标记为hero动画候选的widget。", "categories": [ "Animation and Motion" ], "subcategories": [ "Routing" ], "link": "https://docs.flutter.io/flutter/widgets/Hero-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "AnimatedBuilder", "description": "用于构建动画的通用小部件。AnimatedBuilder在有多个widget希望有一个动画作为一个较大的建造函数部分时会非常有用。要使用AnimatedBuilder,只需构建widget并将其传给builder函数即可。", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/AnimatedBuilder-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "Draggable", "description": "一个可拖动的widget", "categories": [ ], "subcategories": [ "Touch interactions" ], "link": "https://docs.flutter.io/flutter/widgets/Draggable-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "LongPressDraggable", "description": "可以使其子widget在长按时可拖动", "categories": [ "交互Widget" ], "subcategories": [ "Touch interactions" ], "link": "https://docs.flutter.io/flutter/widgets/LongPressDraggable-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "GestureDetector", "description": "一个检测手势的widget", "categories": [ "交互Widget" ], "subcategories": [ "Touch interactions" ], "link": "https://docs.flutter.io/flutter/widgets/GestureDetector-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "DragTarget", "description": "一个拖动的目标widget,在完成拖动时它可以接收数据", "categories": [ "交互Widget" ], "subcategories": [ "Touch interactions" ], "link": "https://docs.flutter.io/flutter/widgets/DragTarget-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "Dismissible", "description": "可以在拖动时隐藏的widget", "categories": [ "交互Widget" ], "subcategories": [ "Touch interactions" ], "link": "https://docs.flutter.io/flutter/widgets/Dismissible-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "IgnorePointer", "description": "在hit test中不可见的widget。当ignoring为true时,此widget及其子树不响应事件。但它在布局过程中仍然消耗空间,并像往常一样绘制它的孩子。它是无法捕获事件对象、因为它在RenderBox.hitTest中返回false ", "categories": [ "交互Widget" ], "subcategories": [ "Touch interactions" ], "link": "https://docs.flutter.io/flutter/widgets/IgnorePointer-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "AbsorbPointer", "description": "在hit test期间吸收(拦截)事件。当absorbing为true时,此小部件阻止其子树通过终止命中测试来接收指针事件。它在布局过程中仍然消耗空间,并像往常一样绘制它的孩子。它只是防止其孩子成为事件命中目标,因为它从RenderBox.hitTest返回true。", "categories": [ "交互Widget" ], "subcategories": [ "Touch interactions" ], "link": "https://docs.flutter.io/flutter/widgets/AbsorbPointer-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "Navigator", "description": "导航器,可以在多个页面(路由)栈之间跳转。", "categories": [ "交互Widget" ], "subcategories": [ "Routing" ], "link": "https://docs.flutter.io/flutter/widgets/Navigator-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "Theme", "description": "将主题应用于子widget。主题描述了应用选择的颜色和字体。", "categories": [ "Styling" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/material/Theme-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "MediaQuery", "description": "建立一个子树,在树中媒体查询解析不同的给定数据", "categories": [ "Styling" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/MediaQuery-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "ListView", "description": "一个可滚动的列表", "categories": [ "Scrolling" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/ListView-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "NestedScrollView", "description": "一个可以嵌套其它可滚动widget的widget", "categories": [ "Scrolling" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/NestedScrollView-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "GridView", "description": "一个可滚动的二维空间数组", "categories": [ "Scrolling" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/GridView-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "SingleChildScrollView", "description": "有一个子widget的可滚动的widget,子内容超过父容器时可以滚动。", "categories": [ "Scrolling" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/SingleChildScrollView-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "Scrollable", "description": "实现了可滚动widget的交互模型,但不包含UI显示相关的逻辑", "categories": [ "Scrolling", "交互Widget" ], "subcategories": [ "Touch interactions" ], "link": "https://docs.flutter.io/flutter/widgets/Scrollable-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "Scrollbar", "description": "一个Material Design 滚动条,表示当前滚动到了什么位置", "categories": [ "Scrolling" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/material/Scrollbar-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "CustomScrollView", "description": "一个使用slivers创建自定义的滚动效果的ScrollView", "categories": [ "Scrolling" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/CustomScrollView-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "NotificationListener", "description": "一个用来监听树上冒泡通知的widget。", "categories": [ "Scrolling" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/NotificationListener-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "ScrollConfiguration", "description": "控制可滚动组件在子树中的表现行为", "categories": [ "Scrolling" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/ScrollConfiguration-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "RefreshIndicator", "description": "Material Design下拉刷新指示器,包装一个可滚动widget", "categories": [ "Scrolling" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/material/RefreshIndicator-class.html", "image": "<img alt='' src='https://storage.googleapis.com/material-design/publish/material_v_12/assets/0B7WCemMG6e0VS2kzSmZwNnNKQVk/patterns-swipe-to-refresh.png'>" }, { "name": "Opacity", "description": "使其子widget透明的widget。", "categories": [ "Painting and effects" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/Opacity-class.html", "image": "<svg viewBox='0 0 100 100'><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='10' y='10' width='60' height='60' fill='#3b75ad'/><rect x='20' y='30' width='70' height='50' fill='#ffffff' opacity='0.8'/></svg>" }, { "name": "Transform", "description": "在绘制子widget之前应用转换的widget。", "categories": [ "Painting and effects" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/Transform-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "DecoratedBox", "description": "在孩子绘制之前或之后绘制装饰的widget。", "categories": [ "Painting and effects" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/DecoratedBox-class.html", "image": "<svg viewBox='0 0 100 100'><defs><filter id='shadow-decorated-box' x='-50%' y='-50%' width='200%' height='200%'><feGaussianBlur stdDeviation='4'/></filter><linearGradient id='gradient-decorated-box' x1='0' y1='0' x2='0.5' y2='1'><stop offset='50%' stop-color='#ffffff'/><stop offset='100%' stop-color='#f50057'/></linearGradient></defs><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='25' y='25' width='50' height='50' rx='10' ry='10' fill='#000000' filter='url(#shadow-decorated-box)'/><rect x='25' y='25' width='50' height='50' rx='10' ry='10' fill='url(#gradient-decorated-box)' stroke-width='5' stroke='#4dd0e1'/></svg>" }, { "name": "FractionalTranslation", "description": "绘制盒子之前给其添加一个偏移转换", "categories": [ "Painting and effects" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/FractionalTranslation-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "RotatedBox", "description": "可以延顺时针以90度的倍数旋转其子widget", "categories": [ "Painting and effects" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/RotatedBox-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "ClipOval", "description": "用椭圆剪辑其孩子的widget", "categories": [ "Painting and effects" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/ClipOval-class.html", "image": "<svg viewBox='0 0 100 100'><defs><clipPath id='clip-oval'><circle cx='40' cy='50' r='30'/></clipPath></defs><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='30' y='10' width='60' height='50' fill='#4dd0e1' opacity='0.05'/><circle cx='40' cy='50' r='30' fill='#ffffff'/><rect x='30' y='10' width='60' height='50' fill='#4dd0e1' clip-path='url(#clip-oval)'/></svg>" }, { "name": "ClipPath", "description": "用path剪辑其孩子的widget", "categories": [ "Painting and effects" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/ClipPath-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "ClipRect", "description": "用矩形剪辑其孩子的widget", "categories": [ "Painting and effects" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/ClipRect-class.html", "image": "<svg viewBox='0 0 100 100'><defs><clipPath id='clip-rect'><rect x='10' y='20' width='60' height='60'/></clipPath></defs><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='30' y='10' width='60' height='50' fill='#4dd0e1' opacity='0.05'/><rect x='10' y='20' width='60' height='60' fill='#ffffff'/><rect x='30' y='10' width='60' height='50' fill='#4dd0e1' clip-path='url(#clip-rect)'/></svg>" }, { "name": "CustomPaint", "description": "提供一个画布的widget,在绘制阶段可以在画布上绘制自定义图形", "categories": [ "Painting and effects" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/CustomPaint-class.html", "image": "<svg viewBox='0 0 100 100'><rect x='0' y='0' width='100' height='100' fill='#3949ab'/><rect x='20' y='20' width='60' height='60' fill='#ffffff'/><ellipse cx='40' cy='35' rx='10' ry='10' stroke-width='5' stroke='#4dd0e1' fill='transparent'/><ellipse cx='20' cy='71' rx='15' ry='20' stroke-width='5' stroke='#4dd0e1' fill='transparent' transform='rotate(-25)'/></svg>" }, { "name": "BackdropFilter", "description": "一个widget,它将过滤器应用到现有的绘图内容,然后绘制孩子。这种效果是比较昂贵的,尤其是如果过滤器是non-local,如blur。", "categories": [ "Painting and effects" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/BackdropFilter-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "Semantics", "description": "一个widget,用以描述widget树的具体语义。使用辅助工具、搜索引擎和其他语义分析软件来确定应用程序的含义。", "categories": [ "Accessibility" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/Semantics-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "MergeSemantics", "description": "合并其后代语义的widget。", "categories": [ "Accessibility" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/MergeSemantics-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "ExcludeSemantics", "description": "删除其后代所有语义的widget", "categories": [ "Accessibility" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/ExcludeSemantics-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "FutureBuilder", "description": "基于与Future交互的最新快照来构建自身的widget", "categories": [ "Async" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/FutureBuilder-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "StreamBuilder", "description": "基于与流交互的最新快照构建自身的widget", "categories": [ "Async" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/StreamBuilder-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "DecoratedBoxTransition", "description": "DecoratedBox的动画版本,可以给它的Decoration不同属性使用动画", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/DecoratedBoxTransition-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "FadeTransition", "description": "对透明度使用动画的widget", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/FadeTransition-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "PositionedTransition", "description": "Positioned的动画版本,它需要一个特定的动画来将孩子的位置从动画的生命周期的起始位置移到结束位置。 ", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/PositionedTransition-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "RotationTransition", "description": "对widget使用旋转动画", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/RotationTransition-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "ScaleTransition", "description": "对widget使用缩放动画", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/ScaleTransition-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "SizeTransition", "description": "Animates its own size and clips and aligns the child.", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/SizeTransition-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "SlideTransition", "description": "对相对于其正常位置的某个位置之间使用动画", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/SlideTransition-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "AnimatedDefaultTextStyle", "description": "在文本样式切换时使用动画", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/AnimatedDefaultTextStyle-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "AnimatedListState", "sample": "AnimatedListState_index", "description": "动画列表的state", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/AnimatedListState-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "AnimatedModalBarrier", "description": "一个阻止用户与widget交互的widget", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/AnimatedModalBarrier-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "AnimatedOpacity", "description": "Opacity的动画版本,在给定的透明度变化时,自动地在给定的一段时间内改变孩子的Opacity", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/AnimatedOpacity-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "AnimatedPhysicalModel", "description": "PhysicalModel的动画版本", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/AnimatedPhysicalModel-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "AnimatedPositioned", "description": "动画版本的Positioned,每当给定位置的变化,自动在给定的时间内转换孩子的位置。", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/AnimatedPositioned-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "AnimatedSize", "description": "动画widget,当给定的孩子的大小变化时,它自动地在给定时间内转换它的大小。", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/AnimatedSize-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "AnimatedWidget", "description": "当给定的Listenable改变值时,会重新构建该widget", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/AnimatedWidget-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" }, { "name": "AnimatedWidgetBaseState", "description": "具有隐式动画的widget的基类", "categories": [ "Animation and Motion" ], "subcategories": [ ], "link": "https://docs.flutter.io/flutter/widgets/AnimatedWidgetBaseState-class.html", "image": "<img alt='' src='/images/catalog-widget-placeholder.png'>" } ]
{ "pile_set_name": "Github" }