text
stringlengths
2
100k
meta
dict
--- layout: post title: 就部分同学因申请信息公开被约谈一事致北大校方的联名信 date: 2018-04-25 12:30 categories: Archive tags: 声援岳昕 description: 联名信 --- 来自微信 ~~[深约一丈]( https://mp.weixin.qq.com/s/TpQ4-z-Rm_w3SxEP027acg)~~ ,~~[北大BBS](https://bbs.pku.edu.cn/v2/post-read.php?bid=22&threadid=16397004)~~ --- 尊敬的北京大学校领导: 您好! 我们是关注沈阳事件及其后续进展的北大师生和校友。 首先需要表明,我们写下这封信不全是因为岳昕同学,还因为在沈阳事件曝光之后很多积极推动解决此事的同学们所经历的种种不公正待遇。 23日上午,我们在震惊与不解中得知这样的消息: 因我校外国语学院2014级本科生岳昕同学寻求沈阳事件真相向校方提交相关信息公开申请,外国语学院的辅导员老师深夜到其宿舍约谈,并单方面通知家人,其家人因此受到严重惊吓,岳昕同学因此陷入孤立无助的处境。 岳昕等同学怀着参与校园事务的热忱之心,怀着北大人的责任感,于4月9日早上向学校提交了信息公开申请表。我们连同岳昕同学在内,所做的一切仅仅是为了在寻求真相的基础上更好地解决沈阳事件,在今后的制度建设方面切实保障校内师生的合法权益。 可在这个过程中所发生的一系列事情令我们非常困惑和失望: 4月7日晚,邓宇昊同学发文表示将申请信息公开。但距离发文不过几小时,邓同学即被院系深夜约谈至凌晨三点多,最终在众多热心同学和约谈老师的力争下邓同学才被放回; 4月9日,十名师生以合理合法的方式在校长办公楼正式书面递交了信息公开申请。而在接下来的几天中,各相关院系开始约谈7日晚在理教邓同学被约谈现场和递交信息公开申请的同学。 虽然学校的这种做法以及于4月20日给出的信息公开反馈结果令我们存在诸多不解,但是出于对学校的信任,大家接下来均选择配合学校一起积极推进校园反性骚扰制度的建设,保障在校师生的合法权益。 可是在同学们非常冷静地对待此事的情况下,我们在前天早上得知的消息却是:外国语学院近期多次约谈岳昕同学,同时越过岳同学向其家长施压、凌晨到宿舍强行约谈,并且要求删除申请信息公开一事的相关资料。 虽然相关老师和外国语学院已及时就此事做出了声明,并且在声明当中表示“始终尊重每一位同学的基本权利,努力保障每一位同学的合法权益”,但是对于经历了一次又一次约谈的同学们来说,我们很难感受到来自校方真诚的关爱。 我们盼望着这些同学能尽快回归正常生活,我们绝不希望在此之后校园内仍然有类似的情况发生。我们真诚地希望同学们的合法权益不再受到侵犯,燕园内校方与同学之间的“误会”不再发生,北京大学国内国际的声誉与形象能够得到长久的维护。 此外我们还想说明的是,在经历了这些事情之后,我们深感个体的无力与渺小,越加感受到老师与同学们的支持对于意见的表达是多么重要。 有鉴于此,针对岳昕同学的遭遇及校方近期一系列约谈行为,我们将以集体联名的方式向校方提起以下四点倡议: 1. 妥善弥补因约谈行为对岳昕同学带来的伤害。切实敦促外国语学院于近期及时召开事件说明会,向全校范围内的师生公开,提前告知参与方式,以有效回应大家的困惑和质疑。保证以后不以任何形式就此事给岳昕同学施压,积极主动向岳昕同学的家人澄清此事,消除不必要的误解。保证岳昕同学的毕业等后续发展不受因校方干预所带来的消极影响。 2. 加强制度约束。面向全校师生明确北京大学约谈制度,出台约谈实施细则,落实“以学生为中心”的思想,应当首先保证同学们的正常学习生活不受影响,严禁打着“关心同学”等幌子随意约谈同学,侵犯大家的合法权益; 3. 充分保障同学合法权利。在进行约谈工作之前,应当开诚布公说明相关情况,告知被约谈者有选择是否接受的自由,不能越过同学本人向同学的家人朋友进行施压; 4. 完善约谈制度的群众监督与制约机制。在同学们自愿的前提下,约谈情况可以面向全校公开说明,并且保证同学们有权申诉违反校规校纪的约谈行为,有权公开违规行为,有权了解其他同学约谈情况,保证约谈中一旦出现不良行为,将会使其暴露在阳光下,受全体师生监督,以逐渐杜绝。 我们将持续关注从沈阳事件曝光以后校方针对同学们所开展的一系列约谈事件,与岳昕等受到无端压力的热心同学同荣辱,共进退!希望我们校方能与我们一道反思这一过程当中存在的问题,对一系列约谈同学的做法作出解释和说明,拿出有力措施保护善良的同学们,直至事件得到最终的妥善解决。 我们会择期将这封联名信附带签署名单寄至北京大学校长办公室。出于某些原因,我们选择暂时不在网络上公开参与联名师生和校友的具体信息。请愿意参加联署的北大同学/校友/老师将信息按照“姓名+年级”/“姓名+老师”的格式发送到邮箱 <[email protected]>,并附上将来是否愿意在网络公开个人具体信息;如果大家有任何建议、意见,也欢迎提出。 希望在我们的共同努力下,学校能变得更美好! 关注沈阳事件及其后续进展的北大师生及校友 2018年4月25日 发起人:李一鸣 2016级本科生
{ "pile_set_name": "Github" }
[![Build Status](https://travis-ci.org/isaacs/rimraf.svg?branch=master)](https://travis-ci.org/isaacs/rimraf) [![Dependency Status](https://david-dm.org/isaacs/rimraf.svg)](https://david-dm.org/isaacs/rimraf) [![devDependency Status](https://david-dm.org/isaacs/rimraf/dev-status.svg)](https://david-dm.org/isaacs/rimraf#info=devDependencies) The [UNIX command](http://en.wikipedia.org/wiki/Rm_(Unix)) `rm -rf` for node. Install with `npm install rimraf`, or just drop rimraf.js somewhere. ## API `rimraf(f, [opts], callback)` The first parameter will be interpreted as a globbing pattern for files. If you want to disable globbing you can do so with `opts.disableGlob` (defaults to `false`). This might be handy, for instance, if you have filenames that contain globbing wildcard characters. The callback will be called with an error if there is one. Certain errors are handled for you: * Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of `opts.maxBusyTries` times before giving up, adding 100ms of wait between each attempt. The default `maxBusyTries` is 3. * `ENOENT` - If the file doesn't exist, rimraf will return successfully, since your desired outcome is already the case. * `EMFILE` - Since `readdir` requires opening a file descriptor, it's possible to hit `EMFILE` if too many file descriptors are in use. In the sync case, there's nothing to be done for this. But in the async case, rimraf will gradually back off with timeouts up to `opts.emfileWait` ms, which defaults to 1000. ## rimraf.sync It can remove stuff synchronously, too. But that's not so good. Use the async API. It's better. ## CLI If installed with `npm install rimraf -g` it can be used as a global command `rimraf <path> [<path> ...]` which is useful for cross platform support. ## mkdirp If you need to create a directory recursively, check out [mkdirp](https://github.com/substack/node-mkdirp).
{ "pile_set_name": "Github" }
/** ****************************************************************************** * @file usb_bsp.c * @author MCD Application Team * @version V2.2.1 * @date 17-March-2018 * @brief This file implements the board support package for the USB host library ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2015 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, 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.st.com/SLA0044> * ****************************************************************************** */ /* Includes ------------------------------------------------------------------ */ #include "usbh_usr.h" #include "usb_bsp.h" #include "usb_hcd_int.h" #include "usbh_core.h" #include "delay.h" #include "variants.h" #ifdef U_DISK_SUPPORT /** * @brief USB_OTG_BSP_Init * Initializes BSP configurations * @param None * @retval None */ void USB_OTG_BSP_Init(USB_OTG_CORE_HANDLE * pdev) { // EXTI_InitTypeDef EXTI_InitStructure; #ifdef STM32F10X_CL #if defined(MKS_32_V1_4) RCC_OTGFSCLKConfig(RCC_OTGFSCLKSource_PLLVCO_Div2); #else RCC_OTGFSCLKConfig(RCC_OTGFSCLKSource_PLLVCO_Div3); #endif RCC_AHBPeriphClockCmd(RCC_AHBPeriph_OTG_FS, ENABLE); #else // USE_STM322xG_EVAL GPIO_InitTypeDef GPIO_InitStructure; #ifdef USE_USB_OTG_FS RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); /* Configure DM DP Pins */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11 | GPIO_Pin_12; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_PinAFConfig(GPIOA, GPIO_PinSource11, GPIO_AF_OTG1_FS); GPIO_PinAFConfig(GPIOA, GPIO_PinSource12, GPIO_AF_OTG1_FS); RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE); RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_OTG_FS, ENABLE); #else // USE_USB_OTG_HS #ifdef USE_ULPI_PHY // ULPI RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA | RCC_AHB1Periph_GPIOB | RCC_AHB1Periph_GPIOC | RCC_AHB1Periph_GPIOH | RCC_AHB1Periph_GPIOI, ENABLE); GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_OTG2_HS); // D0 GPIO_PinAFConfig(GPIOA, GPIO_PinSource5, GPIO_AF_OTG2_HS); // CLK GPIO_PinAFConfig(GPIOB, GPIO_PinSource0, GPIO_AF_OTG2_HS); // D1 GPIO_PinAFConfig(GPIOB, GPIO_PinSource1, GPIO_AF_OTG2_HS); // D2 GPIO_PinAFConfig(GPIOB, GPIO_PinSource5, GPIO_AF_OTG2_HS); // D7 GPIO_PinAFConfig(GPIOB, GPIO_PinSource10, GPIO_AF_OTG2_HS); // D3 GPIO_PinAFConfig(GPIOB, GPIO_PinSource11, GPIO_AF_OTG2_HS); // D4 GPIO_PinAFConfig(GPIOB, GPIO_PinSource12, GPIO_AF_OTG2_HS); // D5 GPIO_PinAFConfig(GPIOB, GPIO_PinSource13, GPIO_AF_OTG2_HS); // D6 GPIO_PinAFConfig(GPIOH, GPIO_PinSource4, GPIO_AF_OTG2_HS); // NXT GPIO_PinAFConfig(GPIOI, GPIO_PinSource11, GPIO_AF_OTG2_HS); // DIR GPIO_PinAFConfig(GPIOC, GPIO_PinSource0, GPIO_AF_OTG2_HS); // STP // CLK GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_Init(GPIOA, &GPIO_InitStructure); // D0 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init(GPIOA, &GPIO_InitStructure); // D1 D2 D3 D4 D5 D6 D7 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_5 | GPIO_Pin_10 | GPIO_Pin_11 | GPIO_Pin_12 | GPIO_Pin_13; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init(GPIOB, &GPIO_InitStructure); // STP GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_Init(GPIOC, &GPIO_InitStructure); // NXT GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_Init(GPIOH, &GPIO_InitStructure); // DIR GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_Init(GPIOI, &GPIO_InitStructure); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_OTG_HS | RCC_AHB1Periph_OTG_HS_ULPI, ENABLE); #else RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_14 | GPIO_Pin_15; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_Init(GPIOB, &GPIO_InitStructure); GPIO_PinAFConfig(GPIOB, GPIO_PinSource12, GPIO_AF_OTG2_FS); GPIO_PinAFConfig(GPIOB, GPIO_PinSource14, GPIO_AF_OTG2_FS); GPIO_PinAFConfig(GPIOB, GPIO_PinSource15, GPIO_AF_OTG2_FS); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_Init(GPIOB, &GPIO_InitStructure); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_OTG_HS, ENABLE); #endif #endif // USB_OTG_HS #endif // USE_STM322xG_EVAL Delay_init(); } /** * @brief USB_OTG_BSP_EnableInterrupt * Configures USB Global interrupt * @param None * @retval None */ void USB_OTG_BSP_EnableInterrupt(USB_OTG_CORE_HANDLE * pdev) { NVIC_InitTypeDef NVIC_InitStructure; #ifdef USE_USB_OTG_HS NVIC_InitStructure.NVIC_IRQChannel = OTG_HS_IRQn; #else NVIC_InitStructure.NVIC_IRQChannel = OTG_FS_IRQn; #endif NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); #ifdef USB_OTG_HS_DEDICATED_EP1_ENABLED NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1); NVIC_InitStructure.NVIC_IRQChannel = OTG_HS_EP1_OUT_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1); NVIC_InitStructure.NVIC_IRQChannel = OTG_HS_EP1_IN_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); #endif } /** * @brief BSP_Drive_VBUS * Drives the Vbus signal through IO * @param state : VBUS states * @retval None */ void USB_OTG_BSP_DriveVBUS(USB_OTG_CORE_HANDLE * pdev, uint8_t state) { /* * On-chip 5 V VBUS generation is not supported. For this reason, a charge * pump or, if 5 V are available on the application board, a basic power * switch, must be added externally to drive the 5 V VBUS line. The external * charge pump can be driven by any GPIO output. When the application * decides to power on VBUS using the chosen GPIO, it must also set the port * power bit in the host port control and status register (PPWR bit in * OTG_FS_HPRT). * * Bit 12 PPWR: Port power The application uses this field to control power * to this port, and the core clears this bit on an overcurrent condition. */ } /** * @brief USB_OTG_BSP_ConfigVBUS * Configures the IO for the Vbus and OverCurrent * @param None * @retval None */ void USB_OTG_BSP_ConfigVBUS(USB_OTG_CORE_HANDLE * pdev) { //VBus(+5v) ctrl pins init } /** * @brief USB_OTG_BSP_uDelay * This function provides delay time in micro sec * @param usec : Value of delay required in micro sec * @retval None */ void USB_OTG_BSP_uDelay(const uint32_t usec) { Delay_us(usec); } /** * @brief USB_OTG_BSP_mDelay * This function provides delay time in milli sec * @param msec : Value of delay required in milli sec * @retval None */ void USB_OTG_BSP_mDelay(const uint32_t msec) { Delay_ms(msec); } #ifdef USE_USB_OTG_FS void OTG_FS_IRQHandler(void) #else void OTG_HS_IRQHandler(void) #endif { USBH_OTG_ISR_Handler(&USB_OTG_Core); } #endif /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
{ "pile_set_name": "Github" }
Usage ===== To install and use `waveform`, simply run: ``` $ go install github.com/mdlayher/waveform/... ``` The `waveform` binary is now installed in your `$GOPATH`. It has several options available for generating waveform images: ``` $ waveform -h Usage of waveform: -alt="": hex alternate color of output waveform image -bg="#FFFFFF": hex background color of output waveform image -fg="#000000": hex foreground color of output waveform image -fn="solid": function used to color output waveform image [options: fuzz, gradient, solid, stripe] -resolution=1: number of times audio is read and drawn per second of audio -sharpness=1: sharpening factor used to add curvature to a scaled image -x=1: scaling factor for image X-axis -y=1: scaling factor for image Y-axis ``` `waveform` currently supports both WAV and FLAC audio files. An audio stream must be passed on `stdin`, and the resulting, PNG-encoded image will be written to `stdout`. Any errors which occur will be written to `stderr`.
{ "pile_set_name": "Github" }
#include "defines.hpp" #include <sstream> #include <string> #include <vector> #include <components/debug/debuglog.hpp> #include <components/misc/stringops.hpp> namespace Interpreter{ bool check(const std::string& str, const std::string& escword, unsigned int* i, unsigned int* start) { bool retval = str.find(escword) == 0; if(retval){ (*i) += escword.length(); (*start) = (*i) + 1; } return retval; } std::vector<std::string> globals; bool longerStr(const std::string& a, const std::string& b) { return a.length() > b.length(); } std::string fixDefinesReal(std::string text, bool dialogue, Context& context) { unsigned int start = 0; std::ostringstream retval; for(unsigned int i = 0; i < text.length(); i++) { char eschar = text[i]; if(eschar == '%' || eschar == '^') { retval << text.substr(start, i - start); std::string temp = Misc::StringUtils::lowerCase(text.substr(i+1, 100)); bool found = false; try { if( (found = check(temp, "actionslideright", &i, &start))){ retval << context.getActionBinding("#{sRight}"); } else if((found = check(temp, "actionreadymagic", &i, &start))){ retval << context.getActionBinding("#{sReady_Magic}"); } else if((found = check(temp, "actionprevweapon", &i, &start))){ retval << context.getActionBinding("#{sPrevWeapon}"); } else if((found = check(temp, "actionnextweapon", &i, &start))){ retval << context.getActionBinding("#{sNextWeapon}"); } else if((found = check(temp, "actiontogglerun", &i, &start))){ retval << context.getActionBinding("#{sAuto_Run}"); } else if((found = check(temp, "actionslideleft", &i, &start))){ retval << context.getActionBinding("#{sLeft}"); } else if((found = check(temp, "actionreadyitem", &i, &start))){ retval << context.getActionBinding("#{sReady_Weapon}"); } else if((found = check(temp, "actionprevspell", &i, &start))){ retval << context.getActionBinding("#{sPrevSpell}"); } else if((found = check(temp, "actionnextspell", &i, &start))){ retval << context.getActionBinding("#{sNextSpell}"); } else if((found = check(temp, "actionrestmenu", &i, &start))){ retval << context.getActionBinding("#{sRestKey}"); } else if((found = check(temp, "actionmenumode", &i, &start))){ retval << context.getActionBinding("#{sInventory}"); } else if((found = check(temp, "actionactivate", &i, &start))){ retval << context.getActionBinding("#{sActivate}"); } else if((found = check(temp, "actionjournal", &i, &start))){ retval << context.getActionBinding("#{sJournal}"); } else if((found = check(temp, "actionforward", &i, &start))){ retval << context.getActionBinding("#{sForward}"); } else if((found = check(temp, "pccrimelevel", &i, &start))){ retval << context.getPCBounty(); } else if((found = check(temp, "actioncrouch", &i, &start))){ retval << context.getActionBinding("#{sCrouch_Sneak}"); } else if((found = check(temp, "actionjump", &i, &start))){ retval << context.getActionBinding("#{sJump}"); } else if((found = check(temp, "actionback", &i, &start))){ retval << context.getActionBinding("#{sBack}"); } else if((found = check(temp, "actionuse", &i, &start))){ retval << context.getActionBinding("#{sUse}"); } else if((found = check(temp, "actionrun", &i, &start))){ retval << context.getActionBinding("#{sRun}"); } else if((found = check(temp, "pcclass", &i, &start))){ retval << context.getPCClass(); } else if((found = check(temp, "pcrace", &i, &start))){ retval << context.getPCRace(); } else if((found = check(temp, "pcname", &i, &start))){ retval << context.getPCName(); } else if((found = check(temp, "cell", &i, &start))){ retval << context.getCurrentCellName(); } else if(dialogue) { // In Dialogue, not messagebox if( (found = check(temp, "faction", &i, &start))){ retval << context.getNPCFaction(); } else if((found = check(temp, "nextpcrank", &i, &start))){ retval << context.getPCNextRank(); } else if((found = check(temp, "pcnextrank", &i, &start))){ retval << context.getPCNextRank(); } else if((found = check(temp, "pcrank", &i, &start))){ retval << context.getPCRank(); } else if((found = check(temp, "rank", &i, &start))){ retval << context.getNPCRank(); } else if((found = check(temp, "class", &i, &start))){ retval << context.getNPCClass(); } else if((found = check(temp, "race", &i, &start))){ retval << context.getNPCRace(); } else if((found = check(temp, "name", &i, &start))){ retval << context.getActorName(); } } else { // In messagebox or book, not dialogue /* empty outside dialogue */ if( (found = check(temp, "faction", &i, &start))); else if((found = check(temp, "nextpcrank", &i, &start))); else if((found = check(temp, "pcnextrank", &i, &start))); else if((found = check(temp, "pcrank", &i, &start))); else if((found = check(temp, "rank", &i, &start))); /* uses pc in messageboxes */ else if((found = check(temp, "class", &i, &start))){ retval << context.getPCClass(); } else if((found = check(temp, "race", &i, &start))){ retval << context.getPCRace(); } else if((found = check(temp, "name", &i, &start))){ retval << context.getPCName(); } } /* Not a builtin, try global variables */ if(!found){ /* if list of globals is empty, grab it and sort it by descending string length */ if(globals.empty()){ globals = context.getGlobals(); sort(globals.begin(), globals.end(), longerStr); } for(unsigned int j = 0; j < globals.size(); j++){ if(globals[j].length() > temp.length()){ // Just in case there's a global with a huuuge name temp = text.substr(i+1, globals[j].length()); transform(temp.begin(), temp.end(), temp.begin(), ::tolower); } if((found = check(temp, globals[j], &i, &start))){ char type = context.getGlobalType(globals[j]); switch(type){ case 's': retval << context.getGlobalShort(globals[j]); break; case 'l': retval << context.getGlobalLong(globals[j]); break; case 'f': retval << context.getGlobalFloat(globals[j]); break; } break; } } } } catch (std::exception& e) { Log(Debug::Error) << "Error: Failed to replace escape character, with the following error: " << e.what(); Log(Debug::Error) << "Full text below:\n" << text; } // Not found, or error if(!found){ /* leave unmodified */ i += 1; start = i; retval << eschar; } } } retval << text.substr(start, text.length() - start); return retval.str (); } std::string fixDefinesDialog(const std::string& text, Context& context){ return fixDefinesReal(text, true, context); } std::string fixDefinesMsgBox(const std::string& text, Context& context){ return fixDefinesReal(text, false, context); } std::string fixDefinesBook(const std::string& text, Context& context){ return fixDefinesReal(text, false, context); } }
{ "pile_set_name": "Github" }
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "CoreMinimal.h" #include "Interfaces/NetworkPredictionInterface.h" UNetworkPredictionInterface::UNetworkPredictionInterface(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { }
{ "pile_set_name": "Github" }
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class ZolozIdentificationCustomerEnrollcertifyQueryModel(object): def __init__(self): self._biz_id = None self._face_type = None self._need_img = None self._zim_id = None @property def biz_id(self): return self._biz_id @biz_id.setter def biz_id(self, value): self._biz_id = value @property def face_type(self): return self._face_type @face_type.setter def face_type(self, value): self._face_type = value @property def need_img(self): return self._need_img @need_img.setter def need_img(self, value): self._need_img = value @property def zim_id(self): return self._zim_id @zim_id.setter def zim_id(self, value): self._zim_id = value def to_alipay_dict(self): params = dict() if self.biz_id: if hasattr(self.biz_id, 'to_alipay_dict'): params['biz_id'] = self.biz_id.to_alipay_dict() else: params['biz_id'] = self.biz_id if self.face_type: if hasattr(self.face_type, 'to_alipay_dict'): params['face_type'] = self.face_type.to_alipay_dict() else: params['face_type'] = self.face_type if self.need_img: if hasattr(self.need_img, 'to_alipay_dict'): params['need_img'] = self.need_img.to_alipay_dict() else: params['need_img'] = self.need_img if self.zim_id: if hasattr(self.zim_id, 'to_alipay_dict'): params['zim_id'] = self.zim_id.to_alipay_dict() else: params['zim_id'] = self.zim_id return params @staticmethod def from_alipay_dict(d): if not d: return None o = ZolozIdentificationCustomerEnrollcertifyQueryModel() if 'biz_id' in d: o.biz_id = d['biz_id'] if 'face_type' in d: o.face_type = d['face_type'] if 'need_img' in d: o.need_img = d['need_img'] if 'zim_id' in d: o.zim_id = d['zim_id'] return o
{ "pile_set_name": "Github" }
/* impure.c. Handling of re-entrancy data structure for OpenRISC 1000. Copyright (C) 2014, Authors Contributor Stefan Wallentowitz <[email protected]> * The authors hereby grant permission to use, copy, modify, distribute, * and license this software and its documentation for any purpose, provided * that existing copyright notices are retained in all copies and that this * notice is included verbatim in any distributions. No written agreement, * license, or royalty fee is required for any of the authorized uses. * Modifications to this software may be copyrighted by their authors * and need not follow the licensing terms described here, provided that * the new terms are clearly indicated on the first page of each file where * they apply. */ #include <reent.h> #include "or1k-internals.h" #include <string.h> /* As an exception handler may also use the library, it is better to use * a different re-entrancy data structure for the exceptions. * This data structure is configured here and as part of the exception * handler (or1k_exception_handler) temporarily replaces the software's * impure data pointer. * * During initialization, the libraries standard _impure_data and the exception * impure data (_exception_impure_data) are initialized. Afterwards, * the current value _current_impure_ptr is set to _impure_ptr. * * At runtime __getreent is called to return the current reentrancy pointer, * which is stored in _current_impure_ptr. * * In the or1k_exception_handler the _current_impure_ptr is set to point to * _exception_impure_ptr. After the exception handler returned, it is set back * to _impure_ptr. */ /* Link in the external impure_data structure */ extern struct _reent *__ATTRIBUTE_IMPURE_PTR__ _impure_ptr; #ifdef __OR1K_MULTICORE__ struct _reent **_or1k_impure_ptr; struct _reent **_or1k_exception_impure_ptr; struct _reent **_or1k_current_impure_ptr; #else struct _reent *__ATTRIBUTE_IMPURE_PTR__ _or1k_impure_ptr; /* Create exception impure data structure */ static struct _reent _or1k_exception_impure_data = _REENT_INIT (_or1k_exception_impure_data); /* Link to the exception impure data structure */ struct _reent *__ATTRIBUTE_IMPURE_PTR__ _or1k_exception_impure_ptr = &_or1k_exception_impure_data; /* Link to the currently used data structure. */ struct _reent *__ATTRIBUTE_IMPURE_PTR__ _or1k_current_impure_ptr; #endif #ifdef __OR1K_MULTICORE__ #define OR1K_LIBC_GETREENT _or1k_current_impure_ptr[or1k_coreid()] #else #define OR1K_LIBC_GETREENT _or1k_current_impure_ptr #endif void _or1k_libc_impure_init (void) { #ifdef __OR1K_MULTICORE__ uint32_t c; _or1k_impure_ptr = _sbrk_r(0, sizeof(struct _reent*) * or1k_numcores()); _or1k_exception_impure_ptr = _sbrk_r(0, sizeof(struct _reent*) * or1k_numcores()); _or1k_current_impure_ptr = _sbrk_r(0, sizeof(struct _reent*) * or1k_numcores()); _or1k_impure_ptr[0] = _impure_ptr; _REENT_INIT_PTR(_impure_ptr); for (c = 1; c < or1k_numcores(); c++) { _or1k_impure_ptr[c] = _sbrk_r(0, sizeof(struct _reent)); _REENT_INIT_PTR(_or1k_impure_ptr[c]); } for (c = 0; c < or1k_numcores(); c++) { _or1k_exception_impure_ptr[c] = _sbrk_r(0, sizeof(struct _reent)); _REENT_INIT_PTR(_or1k_exception_impure_ptr[c]); } for (c = 0; c < or1k_numcores(); c++) { _or1k_current_impure_ptr[c] = _or1k_impure_ptr[c]; } #else // Initialize both impure data structures _REENT_INIT_PTR (_impure_ptr); _REENT_INIT_PTR (_or1k_exception_impure_ptr); // Use the standard impure ptr during normal software run _or1k_impure_ptr = _impure_ptr; // Set current to standard impure pointer _or1k_current_impure_ptr = _impure_ptr; #endif } struct _reent* _or1k_libc_getreent(void) { return OR1K_LIBC_GETREENT; } #ifdef __OR1K_MULTICORE__ struct _or1k_reent (*_or1k_reent)[]; #else struct _or1k_reent _or1k_reent; #endif void _or1k_reent_init(void) { #ifdef __OR1K_MULTICORE__ size_t memsize = sizeof(struct _or1k_reent) * or1k_numcores(); _or1k_reent = (struct _or1k_reent*) _sbrk_r(0, memsize); #endif }
{ "pile_set_name": "Github" }
; This file is for use with available_externally_a.ll ; RUN: true @foo = hidden unnamed_addr constant i32 0
{ "pile_set_name": "Github" }
{ "name": "angular", "version": "1.4.8", "description": "HTML enhanced for web apps", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "https://github.com/angular/angular.js.git" }, "keywords": [ "angular", "framework", "browser", "client-side" ], "author": "Angular Core Team <[email protected]>", "license": "MIT", "bugs": { "url": "https://github.com/angular/angular.js/issues" }, "homepage": "http://angularjs.org" }
{ "pile_set_name": "Github" }
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package storage import ( "fmt" "mime" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/serializer/recognizer" "k8s.io/apiserver/pkg/storage/storagebackend" ) // StorageCodecConfig are the arguments passed to newStorageCodecFn type StorageCodecConfig struct { StorageMediaType string StorageSerializer runtime.StorageSerializer StorageVersion schema.GroupVersion MemoryVersion schema.GroupVersion Config storagebackend.Config EncoderDecoratorFn func(runtime.Encoder) runtime.Encoder DecoderDecoratorFn func([]runtime.Decoder) []runtime.Decoder } // NewStorageCodec assembles a storage codec for the provided storage media type, the provided serializer, and the requested // storage and memory versions. func NewStorageCodec(opts StorageCodecConfig) (runtime.Codec, runtime.GroupVersioner, error) { mediaType, _, err := mime.ParseMediaType(opts.StorageMediaType) if err != nil { return nil, nil, fmt.Errorf("%q is not a valid mime-type", opts.StorageMediaType) } serializer, ok := runtime.SerializerInfoForMediaType(opts.StorageSerializer.SupportedMediaTypes(), mediaType) if !ok { return nil, nil, fmt.Errorf("unable to find serializer for %q", mediaType) } s := serializer.Serializer // Give callers the opportunity to wrap encoders and decoders. For decoders, each returned decoder will // be passed to the recognizer so that multiple decoders are available. var encoder runtime.Encoder = s if opts.EncoderDecoratorFn != nil { encoder = opts.EncoderDecoratorFn(encoder) } decoders := []runtime.Decoder{ // selected decoder as the primary s, // universal deserializer as a fallback opts.StorageSerializer.UniversalDeserializer(), // base64-wrapped universal deserializer as a last resort. // this allows reading base64-encoded protobuf, which should only exist if etcd2+protobuf was used at some point. // data written that way could exist in etcd2, or could have been migrated to etcd3. // TODO: flag this type of data if we encounter it, require migration (read to decode, write to persist using a supported encoder), and remove in 1.8 runtime.NewBase64Serializer(nil, opts.StorageSerializer.UniversalDeserializer()), } if opts.DecoderDecoratorFn != nil { decoders = opts.DecoderDecoratorFn(decoders) } encodeVersioner := runtime.NewMultiGroupVersioner( opts.StorageVersion, schema.GroupKind{Group: opts.StorageVersion.Group}, schema.GroupKind{Group: opts.MemoryVersion.Group}, ) // Ensure the storage receives the correct version. encoder = opts.StorageSerializer.EncoderForVersion( encoder, encodeVersioner, ) decoder := opts.StorageSerializer.DecoderToVersion( recognizer.NewDecoder(decoders...), runtime.NewCoercingMultiGroupVersioner( opts.MemoryVersion, schema.GroupKind{Group: opts.MemoryVersion.Group}, schema.GroupKind{Group: opts.StorageVersion.Group}, ), ) return runtime.NewCodec(encoder, decoder), encodeVersioner, nil }
{ "pile_set_name": "Github" }
from __future__ import absolute_import from __future__ import division from __future__ import print_function import _init_paths import os import cv2 import time # from opts import opts from opts_pose import opts from detectors.detector_factory import detector_factory image_ext = ['jpg', 'jpeg', 'png', 'webp'] video_ext = ['mp4', 'mov', 'avi', 'mkv'] time_stats = ['tot', 'load', 'pre', 'net', 'dec', 'post', 'merge'] def demo(opt): os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpus_str Detector = detector_factory[opt.task] detector = Detector(opt) if opt.demo == 'webcam' or \ opt.demo[opt.demo.rfind('.') + 1:].lower() in video_ext: cam = cv2.VideoCapture(0 if opt.demo == 'webcam' else opt.demo) detector.pause = False i = 0 start_time = time.time() if opt.output_video: fourcc = cv2.VideoWriter_fourcc(*'mp4v') # 如果是mp4视频,编码需要为mp4v im_width = int(cam.get(cv2.CAP_PROP_FRAME_WIDTH)) im_height = int(cam.get(cv2.CAP_PROP_FRAME_HEIGHT)) write_cap = cv2.VideoWriter(opt.output_video, fourcc, 25, (im_width, im_height)) while cam.grab(): i += 1 _, img = cam.retrieve() cv2.imshow('input', img) ret = detector.run(img) time_str = '' for stat in time_stats: time_str = time_str + '{} {:.3f}s |'.format(stat, ret[stat]) if opt.output_video: write_cap.write(ret['plot_img']) print('fps:{:.3f}'.format(i/(time.time()-start_time)), time_str) if cv2.waitKey(1) == 27: return # esc to quit else: if os.path.isdir(opt.demo): image_names = [] ls = os.listdir(opt.demo) for file_name in sorted(ls): ext = file_name[file_name.rfind('.') + 1:].lower() if ext in image_ext: image_names.append(os.path.join(opt.demo, file_name)) else: image_names = [opt.demo] for (image_name) in image_names: ret = detector.run(image_name) time_str = '' for stat in time_stats: time_str = time_str + '{} {:.3f}s |'.format(stat, ret[stat]) print(time_str) if __name__ == '__main__': opt = opts().init() demo(opt)
{ "pile_set_name": "Github" }
# ignore-walk [![Build Status](https://travis-ci.org/npm/ignore-walk.svg?branch=master)](https://travis-ci.org/npm/ignore-walk) Nested/recursive `.gitignore`/`.npmignore` parsing and filtering. Walk a directory creating a list of entries, parsing any `.ignore` files met along the way to exclude files. ## USAGE ```javascript const walk = require('ignore-walk') // All options are optional, defaults provided. // this function returns a promise, but you can also pass a cb // if you like that approach better. walk({ path: '...', // root dir to start in. defaults to process.cwd() ignoreFiles: [ '.gitignore' ], // list of filenames. defaults to ['.ignore'] includeEmpty: true|false, // true to include empty dirs, default false follow: true|false // true to follow symlink dirs, default false }, callback) // to walk synchronously, do it this way: const result = walk.sync({ path: '/wow/such/filepath' }) ``` If you want to get at the underlying classes, they're at `walk.Walker` and `walk.WalkerSync`. ## OPTIONS * `path` The path to start in. Defaults to `process.cwd()` * `ignoreFiles` Filenames to treat as ignore files. The default is `['.ignore']`. (This is where you'd put `.gitignore` or `.npmignore` or whatever.) If multiple ignore files are in a directory, then rules from each are applied in the order that the files are listed. * `includeEmpty` Set to `true` to include empty directories, assuming they are not excluded by any of the ignore rules. If not set, then this follows the standard `git` behavior of not including directories that are empty. Note: this will cause an empty directory to be included if it would contain an included entry, even if it would have otherwise been excluded itself. For example, given the rules `*` (ignore everything) and `!/a/b/c` (re-include the entry at `/a/b/c`), the directory `/a/b` will be included if it is empty. * `follow` Set to `true` to treat symbolically linked directories as directories, recursing into them. There is no handling for nested symlinks, so `ELOOP` errors can occur in some cases when using this option. Defaults to `false`.
{ "pile_set_name": "Github" }
/* * Hibernate OGM, Domain model persistence for NoSQL datastores * * License: GNU Lesser General Public License (LGPL), version 2.1 or later * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.ogm.backendtck.type.converter; import javax.persistence.AttributeConverter; /** * @author Gunnar Morling */ public class MyStringToUpperCaseStringConverter implements AttributeConverter<MyString, String> { @Override public String convertToDatabaseColumn(MyString attribute) { return attribute != null ? attribute.toString().toUpperCase() : null; } @Override public MyString convertToEntityAttribute(String dbData) { return dbData != null ? new MyString( dbData.toLowerCase() ) : null; } }
{ "pile_set_name": "Github" }
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'maximize', 'en-au', { maximize: 'Maximize', minimize: 'Minimize' // MISSING } );
{ "pile_set_name": "Github" }
/*! * jQVMap Version 1.0 * * http://jqvmap.com * * Copyright 2012, Peter Schmalfeldt <[email protected]> * Licensed under the MIT license. * * Fork Me @ https://github.com/manifestinteractive/jqvmap */ .jqvmap-label { position: absolute; display: none; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; background: #292929; color: white; font-family: sans-serif, Verdana; font-size: smaller; padding: 3px; } .jqvmap-zoomin, .jqvmap-zoomout { position: absolute; left: 10px; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; background: #000000; padding: 0px 7px; color: white; cursor: pointer; line-height: 20px; text-align: center; } .jqvmap-zoomin { top: 10px; } .jqvmap-zoomout { top: 40px; } .jqvmap-region { cursor: pointer; } .jqvmap-ajax_response { width: 100%; height: 500px; }
{ "pile_set_name": "Github" }
{ "SourceFileNode": { "statementList": [ { "InlineHtml": { "scriptSectionEndTag": null, "text": null, "scriptSectionStartTag": { "kind": "ScriptSectionStartTag", "textLength": 6 } } }, { "ClassDeclaration": { "attributes": null, "abstractOrFinalModifier": null, "classKeyword": { "kind": "ClassKeyword", "textLength": 5 }, "name": { "kind": "Name", "textLength": 1 }, "classBaseClause": null, "classInterfaceClause": null, "classMembers": { "ClassMembersNode": { "openBrace": { "kind": "OpenBraceToken", "textLength": 1 }, "classMemberDeclarations": [ { "ClassConstDeclaration": { "attributes": null, "modifiers": [ { "kind": "PublicKeyword", "textLength": 6 } ], "constKeyword": { "kind": "ConstKeyword", "textLength": 5 }, "constElements": { "ConstElementList": { "children": [ { "ConstElement": { "name": { "kind": "Name", "textLength": 1 }, "equalsToken": { "kind": "EqualsToken", "textLength": 1 }, "assignment": { "Variable": { "dollar": null, "name": { "kind": "VariableName", "textLength": 2 } } } } } ] } }, "semicolon": { "kind": "SemicolonToken", "textLength": 1 } } } ], "closeBrace": { "kind": "CloseBraceToken", "textLength": 1 } } } } } ], "endOfFileToken": { "kind": "EndOfFileToken", "textLength": 0 } } }
{ "pile_set_name": "Github" }
az: азербејџански az_AZ: 'азербејџански (Азербејџан)' az_Latn_AZ: 'азербејџански (латиница, Азербејџан)' az_Latn: 'азербејџански (латиница)' az_Cyrl_AZ: 'азербејџански (ћирилица, Азербејџан)' az_Cyrl: 'азербејџански (ћирилица)' ak: акан ak_GH: 'акан (Гана)' sq: албански sq_AL: 'албански (Албанија)' sq_XK: 'албански (Косово)' sq_MK: 'албански (Македонија)' am: амхарски am_ET: 'амхарски (Етиопија)' ar: арапски ar_DZ: 'арапски (Алжир)' ar_BH: 'арапски (Бахреин)' ar_EG: 'арапски (Египат)' ar_ER: 'арапски (Еритреја)' ar_EH: 'арапски (Западна Сахара)' ar_IL: 'арапски (Израел)' ar_IQ: 'арапски (Ирак)' ar_YE: 'арапски (Јемен)' ar_JO: 'арапски (Јордан)' ar_SS: 'арапски (Јужни Судан)' ar_QA: 'арапски (Катар)' ar_KM: 'арапски (Коморска Острва)' ar_KW: 'арапски (Кувајт)' ar_LB: 'арапски (Либан)' ar_LY: 'арапски (Либија)' ar_MA: 'арапски (Мароко)' ar_MR: 'арапски (Мауританија)' ar_OM: 'арапски (Оман)' ar_PS: 'арапски (Палестинске територије)' ar_SA: 'арапски (Саудијска Арабија)' ar_SY: 'арапски (Сирија)' ar_SO: 'арапски (Сомалија)' ar_SD: 'арапски (Судан)' ar_TN: 'арапски (Тунис)' ar_AE: 'арапски (Уједињени Арапски Емирати)' ar_TD: 'арапски (Чад)' ar_DJ: 'арапски (Џибути)' as: асамски as_IN: 'асамски (Индија)' af: африканс af_ZA: 'африканс (Јужноафричка Република)' af_NA: 'африканс (Намибија)' bm: бамбара bm_Latn_ML: 'бамбара (латиница, Мали)' bm_Latn: 'бамбара (латиница)' eu: баскијски eu_ES: 'баскијски (Шпанија)' be: белоруски be_BY: 'белоруски (Белорусија)' bn: бенгалски bn_BD: 'бенгалски (Бангладеш)' bn_IN: 'бенгалски (Индија)' bs: босански bs_BA: 'босански (Босна и Херцеговина)' bs_Latn_BA: 'босански (латиница, Босна и Херцеговина)' bs_Latn: 'босански (латиница)' bs_Cyrl_BA: 'босански (ћирилица, Босна и Херцеговина)' bs_Cyrl: 'босански (ћирилица)' br: бретонски br_FR: 'бретонски (Француска)' bg: бугарски bg_BG: 'бугарски (Бугарска)' my: бурмански my_MM: 'бурмански (Мијанмар (Бурма))' cy: велшки cy_GB: 'велшки (Велика Британија)' vi: вијетнамски vi_VN: 'вијетнамски (Вијетнам)' gl: галицијски gl_ES: 'галицијски (Шпанија)' lg: ганда lg_UG: 'ганда (Уганда)' ka: грузијски ka_GE: 'грузијски (Грузија)' el: грчки el_GR: 'грчки (Грчка)' el_CY: 'грчки (Кипар)' gu: гуџарати gu_IN: 'гуџарати (Индија)' da: дански da_GL: 'дански (Гренланд)' da_DK: 'дански (Данска)' ee: еве ee_GH: 'еве (Гана)' ee_TG: 'еве (Того)' en: енглески en_VI: 'енглески (Америчка Девичанска Острва)' en_AS: 'енглески (Америчка Самоа)' en_AI: 'енглески (Ангвила)' en_AG: 'енглески (Антигва и Барбуда)' en_AU: 'енглески (Аустралија)' en_BB: 'енглески (Барбадос)' en_BS: 'енглески (Бахами)' en_BE: 'енглески (Белгија)' en_BZ: 'енглески (Белизе)' en_BM: 'енглески (Бермуда)' en_CX: 'енглески (Божићно острво)' en_BW: 'енглески (Боцвана)' en_VG: 'енглески (Британска Девичанска Острва)' en_IO: 'енглески (Британска територија у Индијском океану)' en_VU: 'енглески (Вануату)' en_GB: 'енглески (Велика Британија)' en_GM: 'енглески (Гамбија)' en_GH: 'енглески (Гана)' en_GY: 'енглески (Гвајана)' en_GI: 'енглески (Гибралтар)' en_GD: 'енглески (Гренада)' en_GU: 'енглески (Гуам)' en_GG: 'енглески (Гурнси)' en_DG: 'енглески (Дијего Гарсија)' en_DM: 'енглески (Доминика)' en_ER: 'енглески (Еритреја)' en_ZM: 'енглески (Замбија)' en_ZW: 'енглески (Зимбабве)' en_IN: 'енглески (Индија)' en_IE: 'енглески (Ирска)' en_JM: 'енглески (Јамајка)' en_SS: 'енглески (Јужни Судан)' en_ZA: 'енглески (Јужноафричка Република)' en_KY: 'енглески (Кајманска Острва)' en_CM: 'енглески (Камерун)' en_CA: 'енглески (Канада)' en_KE: 'енглески (Кенија)' en_KI: 'енглески (Кирибати)' en_CC: 'енглески (Кокос (Келинг) Острва)' en_CK: 'енглески (Кукова Острва)' en_LS: 'енглески (Лесото)' en_LR: 'енглески (Либерија)' en_MG: 'енглески (Мадагаскар)' en_MW: 'енглески (Малави)' en_MY: 'енглески (Малезија)' en_MT: 'енглески (Малта)' en_MH: 'енглески (Маршалска Острва)' en_MU: 'енглески (Маурицијус)' en_FM: 'енглески (Микронезија)' en_MS: 'енглески (Монсерат)' en_NA: 'енглески (Намибија)' en_NR: 'енглески (Науру)' en_NG: 'енглески (Нигерија)' en_NU: 'енглески (Ниуе)' en_NZ: 'енглески (Нови Зеланд)' en_NF: 'енглески (Норфолк Острво)' en_TC: 'енглески (Острва Туркс и Каикос)' en_IM: 'енглески (Острво Ман)' en_PK: 'енглески (Пакистан)' en_PW: 'енглески (Палау)' en_PG: 'енглески (Папуа Нова Гвинеја)' en_PN: 'енглески (Питкерн)' en_PR: 'енглески (Порторико)' en_RW: 'енглески (Руанда)' en_WS: 'енглески (Самоа)' en_MO: 'енглески (САР Макао (Кина))' en_SZ: 'енглески (Свазиленд)' en_SH: 'енглески (Света Јелена)' en_LC: 'енглески (Света Луција)' en_SX: 'енглески (Свети Мартин)' en_MP: 'енглески (Северна Маријанска Острва)' en_SC: 'енглески (Сејшели)' en_VC: 'енглески (Сент Винсент и Гренадини)' en_KN: 'енглески (Сент Китс и Невис)' en_SL: 'енглески (Сијера Леоне)' en_SG: 'енглески (Сингапур)' en_US: 'енглески (Сједињене Америчке Државе)' en_SB: 'енглески (Соломонска Острва)' en_SD: 'енглески (Судан)' en_TZ: 'енглески (Танзанија)' en_TK: 'енглески (Токелау)' en_TO: 'енглески (Тонга)' en_TT: 'енглески (Тринидад и Тобаго)' en_TV: 'енглески (Тувалу)' en_UG: 'енглески (Уганда)' en_UM: 'енглески (Удаљена острва САД)' en_PH: 'енглески (Филипини)' en_FJ: 'енглески (Фиџи)' en_FK: 'енглески (Фокландска острва)' en_HK: 'енглески (Хонг Конг С. А. Р. Кина)' en_JE: 'енглески (Џерси)' eo: есперанто et: естонски et_EE: 'естонски (Естонија)' fy: 'западни фризијски' fy_NL: 'западни фризијски (Холандија)' zu: зулу zu_ZA: 'зулу (Јужноафричка Република)' ig: игбо ig_NG: 'игбо (Нигерија)' id: индонежански id_ID: 'индонежански (Индонезија)' ga: ирски ga_IE: 'ирски (Ирска)' is: исландски is_IS: 'исландски (Исланд)' it: италијански it_IT: 'италијански (Италија)' it_SM: 'италијански (Сан Марино)' it_CH: 'италијански (Швајцарска)' ja: јапански ja_JP: 'јапански (Јапан)' hy: јерменски hy_AM: 'јерменски (Јерменија)' yi: Јидиш yo: јоруба yo_BJ: 'јоруба (Бенин)' yo_NG: 'јоруба (Нигерија)' kk: казашки kk_KZ: 'казашки (Казахстан)' kk_Cyrl_KZ: 'казашки (ћирилица, Казахстан)' kk_Cyrl: 'казашки (ћирилица)' kl: калалисут kl_GL: 'калалисут (Гренланд)' kn: канада kn_IN: 'канада (Индија)' ca: каталонски ca_AD: 'каталонски (Андора)' ca_IT: 'каталонски (Италија)' ca_FR: 'каталонски (Француска)' ca_ES: 'каталонски (Шпанија)' ks: кашмирски ks_Arab_IN: 'кашмирски (арапско писмо, Индија)' ks_Arab: 'кашмирски (арапско писмо)' ks_IN: 'кашмирски (Индија)' qu: кечуа qu_BO: 'кечуа (Боливија)' qu_EC: 'кечуа (Еквадор)' qu_PE: 'кечуа (Перу)' ki: кикују ki_KE: 'кикују (Кенија)' zh: кинески zh_CN: 'кинески (Кина)' zh_Hans_CN: 'кинески (поједностављено кинеско писмо, Кина)' zh_Hans_MO: 'кинески (поједностављено кинеско писмо, САР Макао (Кина))' zh_Hans_SG: 'кинески (поједностављено кинеско писмо, Сингапур)' zh_Hans_HK: 'кинески (поједностављено кинеско писмо, Хонг Конг С. А. Р. Кина)' zh_Hans: 'кинески (поједностављено кинеско писмо)' zh_MO: 'кинески (САР Макао (Кина))' zh_SG: 'кинески (Сингапур)' zh_TW: 'кинески (Тајван)' zh_Hant_MO: 'кинески (традиционално кинеско писмо, САР Макао (Кина))' zh_Hant_TW: 'кинески (традиционално кинеско писмо, Тајван)' zh_Hant_HK: 'кинески (традиционално кинеско писмо, Хонг Конг С. А. Р. Кина)' zh_Hant: 'кинески (традиционално кинеско писмо)' zh_HK: 'кинески (Хонг Конг С. А. Р. Кина)' rw: кинјаруанда rw_RW: 'кинјаруанда (Руанда)' ky: киргиски ky_KG: 'киргиски (Киргистан)' ky_Cyrl_KG: 'киргиски (ћирилица, Киргистан)' ky_Cyrl: 'киргиски (ћирилица)' km: кмерски km_KH: 'кмерски (Камбоџа)' ko: корејски ko_KR: 'корејски (Јужна Кореја)' ko_KP: 'корејски (Северна Кореја)' kw: корнволски kw_GB: 'корнволски (Велика Британија)' lo: лаошки lo_LA: 'лаошки (Лаос)' lv: летонски lv_LV: 'летонски (Летонија)' ln: лингала ln_AO: 'лингала (Ангола)' ln_CG: 'лингала (Конго - Бразавил)' ln_CD: 'лингала (Конго - Киншаса)' ln_CF: 'лингала (Централноафричка Република)' lt: литвански lt_LT: 'литвански (Литванија)' lu: луба-катанга lu_CD: 'луба-катанга (Конго - Киншаса)' lb: луксембуршки lb_LU: 'луксембуршки (Луксембург)' hu: мађарски hu_HU: 'мађарски (Мађарска)' mk: македонски mk_MK: 'македонски (Македонија)' ml: малајалам ml_IN: 'малајалам (Индија)' ms: малајски ms_BN: 'малајски (Брунеј)' ms_Latn_BN: 'малајски (латиница, Брунеј)' ms_Latn_MY: 'малајски (латиница, Малезија)' ms_Latn_SG: 'малајски (латиница, Сингапур)' ms_Latn: 'малајски (латиница)' ms_MY: 'малајски (Малезија)' ms_SG: 'малајски (Сингапур)' mg: малгашки mg_MG: 'малгашки (Мадагаскар)' mt: малтешки mt_MT: 'малтешки (Малта)' gv: Манкс gv_IM: 'Манкс (Острво Ман)' mr: марати mr_IN: 'марати (Индија)' mn: монголски mn_MN: 'монголски (Монголија)' mn_Cyrl_MN: 'монголски (ћирилица, Монголија)' mn_Cyrl: 'монголски (ћирилица)' de: немачки de_AT: 'немачки (Аустрија)' de_BE: 'немачки (Белгија)' de_LI: 'немачки (Лихтенштајн)' de_LU: 'немачки (Луксембург)' de_DE: 'немачки (Немачка)' de_CH: 'немачки (Швајцарска)' ne: непалски ne_IN: 'непалски (Индија)' ne_NP: 'непалски (Непал)' 'no': Норвешки no_NO: 'Норвешки (Норвешка)' nb: 'норвешки бокмал' nb_NO: 'норвешки бокмал (Норвешка)' nb_SJ: 'норвешки бокмал (Свалбард и Јан Мајен)' nn: 'норвешки нинорск' nn_NO: 'норвешки нинорск (Норвешка)' or: орија or_IN: 'орија (Индија)' om: оромо om_ET: 'оромо (Етиопија)' om_KE: 'оромо (Кенија)' os: Осетски os_GE: 'Осетски (Грузија)' os_RU: 'Осетски (Русија)' pa: панџаби pa_Arab_PK: 'панџаби (арапско писмо, Пакистан)' pa_Arab: 'панџаби (арапско писмо)' pa_Guru_IN: 'панџаби (гурмуки писмо, Индија)' pa_Guru: 'панџаби (гурмуки писмо)' pa_IN: 'панџаби (Индија)' pa_PK: 'панџаби (Пакистан)' ps: паштунски ps_AF: 'паштунски (Авганистан)' fa: персијски fa_AF: 'персијски (Авганистан)' fa_IR: 'персијски (Иран)' pl: пољски pl_PL: 'пољски (Пољска)' pt: португалски pt_AO: 'португалски (Ангола)' pt_BR: 'португалски (Бразил)' pt_GW: 'португалски (Гвинеја-Бисао)' pt_CV: 'португалски (Зеленортска Острва)' pt_TL: 'португалски (Источни Тимор)' pt_MZ: 'португалски (Мозамбик)' pt_PT: 'португалски (Португал)' pt_ST: 'португалски (Сао Томе и Принципе)' pt_MO: 'португалски (САР Макао (Кина))' rm: рето-романски rm_CH: 'рето-романски (Швајцарска)' ro: румунски ro_MD: 'румунски (Молдавија)' ro_RO: 'румунски (Румунија)' rn: рунди rn_BI: 'рунди (Бурунди)' ru: руски ru_BY: 'руски (Белорусија)' ru_KZ: 'руски (Казахстан)' ru_KG: 'руски (Киргистан)' ru_MD: 'руски (Молдавија)' ru_RU: 'руски (Русија)' ru_UA: 'руски (Украјина)' sg: санго sg_CF: 'санго (Централноафричка Република)' sw: свахили sw_KE: 'свахили (Кенија)' sw_TZ: 'свахили (Танзанија)' sw_UG: 'свахили (Уганда)' nd: 'северни ндебеле' nd_ZW: 'северни ндебеле (Зимбабве)' se: 'северни сами' se_NO: 'северни сами (Норвешка)' se_FI: 'северни сами (Финска)' se_SE: 'северни сами (Шведска)' ii: 'сечуан ји' ii_CN: 'сечуан ји (Кина)' si: синхалски si_LK: 'синхалски (Шри Ланка)' sk: словачки sk_SK: 'словачки (Словачка)' sl: словеначки sl_SI: 'словеначки (Словенија)' so: сомалски so_ET: 'сомалски (Етиопија)' so_KE: 'сомалски (Кенија)' so_SO: 'сомалски (Сомалија)' so_DJ: 'сомалски (Џибути)' sr: српски sr_BA: 'српски (Босна и Херцеговина)' sr_XK: 'српски (Косово)' sr_Latn_BA: 'српски (латиница, Босна и Херцеговина)' sr_Latn_XK: 'српски (латиница, Косово)' sr_Latn_RS: 'српски (латиница, Србија)' sr_Latn_ME: 'српски (латиница, Црна Гора)' sr_Latn: 'српски (латиница)' sr_RS: 'српски (Србија)' sr_Cyrl_BA: 'српски (ћирилица, Босна и Херцеговина)' sr_Cyrl_XK: 'српски (ћирилица, Косово)' sr_Cyrl_RS: 'српски (ћирилица, Србија)' sr_Cyrl_ME: 'српски (ћирилица, Црна Гора)' sr_Cyrl: 'српски (ћирилица)' sr_ME: 'српски (Црна Гора)' sh: Српскохрватски sh_BA: 'Српскохрватски (Босна и Херцеговина)' tl: Тагалски tl_PH: 'Тагалски (Филипини)' th: тајландски th_TH: 'тајландски (Тајланд)' ta: тамилски ta_IN: 'тамилски (Индија)' ta_MY: 'тамилски (Малезија)' ta_SG: 'тамилски (Сингапур)' ta_LK: 'тамилски (Шри Ланка)' te: телугу te_IN: 'телугу (Индија)' bo: тибетански bo_IN: 'тибетански (Индија)' bo_CN: 'тибетански (Кина)' ti: тигриња ti_ER: 'тигриња (Еритреја)' ti_ET: 'тигриња (Етиопија)' to: тонга to_TO: 'тонга (Тонга)' tr: турски tr_CY: 'турски (Кипар)' tr_TR: 'турски (Турска)' uz: узбечки uz_AF: 'узбечки (Авганистан)' uz_Arab_AF: 'узбечки (арапско писмо, Авганистан)' uz_Arab: 'узбечки (арапско писмо)' uz_Latn_UZ: 'узбечки (латиница, Узбекистан)' uz_Latn: 'узбечки (латиница)' uz_Cyrl_UZ: 'узбечки (ћирилица, Узбекистан)' uz_Cyrl: 'узбечки (ћирилица)' uz_UZ: 'узбечки (Узбекистан)' ug: ујгурски ug_Arab_CN: 'ујгурски (арапско писмо, Кина)' ug_Arab: 'ујгурски (арапско писмо)' ug_CN: 'ујгурски (Кина)' uk: украјински uk_UA: 'украјински (Украјина)' ur: урду ur_IN: 'урду (Индија)' ur_PK: 'урду (Пакистан)' fo: фарски fo_FO: 'фарски (Фарска Острва)' fi: фински fi_FI: 'фински (Финска)' fr: француски fr_DZ: 'француски (Алжир)' fr_BE: 'француски (Белгија)' fr_BJ: 'француски (Бенин)' fr_BF: 'француски (Буркина Фасо)' fr_BI: 'француски (Бурунди)' fr_WF: 'француски (Валис и Футуна)' fr_VU: 'француски (Вануату)' fr_GA: 'француски (Габон)' fr_GP: 'француски (Гваделупе)' fr_GN: 'француски (Гвинеја)' fr_GQ: 'француски (Екваторијална Гвинеја)' fr_CM: 'француски (Камерун)' fr_CA: 'француски (Канада)' fr_KM: 'француски (Коморска Острва)' fr_CG: 'француски (Конго - Бразавил)' fr_CD: 'француски (Конго - Киншаса)' fr_LU: 'француски (Луксембург)' fr_MG: 'француски (Мадагаскар)' fr_YT: 'француски (Мајот)' fr_ML: 'француски (Мали)' fr_MA: 'француски (Мароко)' fr_MQ: 'француски (Мартиник)' fr_MR: 'француски (Мауританија)' fr_MU: 'француски (Маурицијус)' fr_MC: 'француски (Монако)' fr_NE: 'француски (Нигер)' fr_NC: 'француски (Нова Каледонија)' fr_CI: 'француски (Обала Слоноваче)' fr_RE: 'француски (Реинион)' fr_RW: 'француски (Руанда)' fr_BL: 'француски (Свети Бартоломеј)' fr_SC: 'француски (Сејшели)' fr_PM: 'француски (Сен Пјер и Микелон)' fr_SN: 'француски (Сенегал)' fr_MF: 'француски (Сент Мартин)' fr_SY: 'француски (Сирија)' fr_TG: 'француски (Того)' fr_TN: 'француски (Тунис)' fr_GF: 'француски (Француска Гвајана)' fr_PF: 'француски (Француска Полинезија)' fr_FR: 'француски (Француска)' fr_HT: 'француски (Хаити)' fr_CF: 'француски (Централноафричка Република)' fr_TD: 'француски (Чад)' fr_DJ: 'француски (Џибути)' fr_CH: 'француски (Швајцарска)' ff: Фулах ff_GN: 'Фулах (Гвинеја)' ff_CM: 'Фулах (Камерун)' ff_MR: 'Фулах (Мауританија)' ff_SN: 'Фулах (Сенегал)' ha: хауса ha_GH: 'хауса (Гана)' ha_Latn_GH: 'хауса (латиница, Гана)' ha_Latn_NE: 'хауса (латиница, Нигер)' ha_Latn_NG: 'хауса (латиница, Нигерија)' ha_Latn: 'хауса (латиница)' ha_NE: 'хауса (Нигер)' ha_NG: 'хауса (Нигерија)' he: хебрејски he_IL: 'хебрејски (Израел)' hi: хинди hi_IN: 'хинди (Индија)' nl: холандски nl_AW: 'холандски (Аруба)' nl_BE: 'холандски (Белгија)' nl_BQ: 'холандски (Карипска Холандија)' nl_CW: 'холандски (Курасао)' nl_SX: 'холандски (Свети Мартин)' nl_SR: 'холандски (Суринам)' nl_NL: 'холандски (Холандија)' hr: хрватски hr_BA: 'хрватски (Босна и Херцеговина)' hr_HR: 'хрватски (Хрватска)' cs: чешки cs_CZ: 'чешки (Чешка)' dz: џонга dz_BT: 'џонга (Бутан)' sv: шведски sv_AX: 'шведски (Оландска острва)' sv_FI: 'шведски (Финска)' sv_SE: 'шведски (Шведска)' gd: 'Шкотски Галски' gd_GB: 'Шкотски Галски (Велика Британија)' sn: шона sn_ZW: 'шона (Зимбабве)' es: шпански es_AR: 'шпански (Аргентина)' es_BO: 'шпански (Боливија)' es_VE: 'шпански (Венецуела)' es_GT: 'шпански (Гватемала)' es_DO: 'шпански (Доминиканска Република)' es_EC: 'шпански (Еквадор)' es_GQ: 'шпански (Екваторијална Гвинеја)' es_IC: 'шпански (Канарска острва)' es_CO: 'шпански (Колумбија)' es_CR: 'шпански (Костарика)' es_CU: 'шпански (Куба)' es_MX: 'шпански (Мексико)' es_NI: 'шпански (Никарагва)' es_PA: 'шпански (Панама)' es_PY: 'шпански (Парагвај)' es_PE: 'шпански (Перу)' es_PR: 'шпански (Порторико)' es_SV: 'шпански (Салвадор)' es_EA: 'шпански (Сеута и Мелиља)' es_US: 'шпански (Сједињене Америчке Државе)' es_UY: 'шпански (Уругвај)' es_PH: 'шпански (Филипини)' es_HN: 'шпански (Хондурас)' es_CL: 'шпански (Чиле)' es_ES: 'шпански (Шпанија)'
{ "pile_set_name": "Github" }
// Copyright (c) 2020, NVIDIA CORPORATION. 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 <gtest/gtest.h> #include <cmath> #include <complex> #include <tuple> #include <vector> #include "dali/kernels/common/utils.h" #include "dali/kernels/imgproc/convolution/baseline_convolution.h" #include "dali/kernels/imgproc/convolution/separable_convolution_cpu.h" #include "dali/kernels/scratch.h" #include "dali/test/tensor_test_utils.h" #include "dali/test/test_tensors.h" namespace dali { namespace kernels { template <typename T> void InitTriangleWindow(const TensorView<StorageCPU, T, 1> &window) { int radius = window.num_elements() / 2; for (int i = 0; i < radius; i++) { *window(i) = i + 1; *window(window.num_elements() - i - 1) = i + 1; } *window(radius) = radius + 1; } TEST(SeparableConvolutionTest, Axes1WithChannels) { std::array<int, 1> window_dims = {5}; TestTensorList<float, 1> kernel_window; TestTensorList<float, 2> input; TestTensorList<int, 2> output, baseline_output; TensorListShape<2> data_shape = uniform_list_shape<2>(1, {16, 3}); kernel_window.reshape(uniform_list_shape<1>(1, {window_dims[0]})); input.reshape(data_shape); output.reshape(data_shape); baseline_output.reshape(data_shape); auto kernel_window_v = kernel_window.cpu()[0]; auto in_v = input.cpu()[0]; auto out_v = output.cpu()[0]; auto baseline_out_v = baseline_output.cpu()[0]; std::mt19937 rng; UniformRandomFill(in_v, rng, 0, 255); InitTriangleWindow(kernel_window_v); SeparableConvolutionCpu<int, float, float, 1, true> kernel; KernelContext ctx; auto req = kernel.Setup(ctx, data_shape[0], window_dims); ScratchpadAllocator scratch_alloc; scratch_alloc.Reserve(req.scratch_sizes); auto scratchpad = scratch_alloc.GetScratchpad(); ctx.scratchpad = &scratchpad; kernel.Run(ctx, out_v, in_v, uniform_array<1, TensorView<StorageCPU, const float, 1>>(kernel_window_v)); testing::BaselineConvolve(baseline_out_v, in_v, kernel_window_v, 0, window_dims[0] / 2); Check(out_v, baseline_out_v); } TEST(SeparableConvolutionTest, Axes1NoChannels) { std::array<int, 1> window_dims = {5}; TestTensorList<float, 1> kernel_window; TestTensorList<float, 2> input; TestTensorList<int, 1> output; TestTensorList<int, 2> baseline_output; TensorListShape<2> data_shape = uniform_list_shape<2>(1, {16, 1}); kernel_window.reshape(uniform_list_shape<1>(1, {window_dims[0]})); input.reshape(data_shape); output.reshape(data_shape.first<1>()); baseline_output.reshape(data_shape); auto kernel_window_v = kernel_window.cpu()[0]; auto baseline_in_v = input.cpu()[0]; TensorView<StorageCPU, float, 1> in_v = {baseline_in_v.data, baseline_in_v.shape.first<1>()}; auto out_v = output.cpu()[0]; auto baseline_out_v = baseline_output.cpu()[0]; std::mt19937 rng; UniformRandomFill(in_v, rng, 0, 255); InitTriangleWindow(kernel_window_v); SeparableConvolutionCpu<int, float, float, 1, false> kernel; KernelContext ctx; auto req = kernel.Setup(ctx, data_shape[0].first<1>(), window_dims); ScratchpadAllocator scratch_alloc; scratch_alloc.Reserve(req.scratch_sizes); auto scratchpad = scratch_alloc.GetScratchpad(); ctx.scratchpad = &scratchpad; kernel.Run(ctx, out_v, in_v, uniform_array<1, TensorView<StorageCPU, const float, 1>>(kernel_window_v)); testing::BaselineConvolve(baseline_out_v, baseline_in_v, kernel_window_v, 0, window_dims[0] / 2); TensorView<StorageCPU, int, 1> compare_v = {baseline_out_v.data, baseline_out_v.shape.first<1>()}; Check(out_v, compare_v); } TEST(SeparableConvolutionTest, Axes2WithChannels) { std::array<int, 2> window_dims = {5, 7}; TestTensorList<float, 1> kernel_window_0, kernel_window_1; TestTensorList<int, 3> input; TestTensorList<float, 3> intermediate; TestTensorList<int, 3> output, baseline_output; TensorListShape<3> data_shape = uniform_list_shape<3>(1, {20, 16, 3}); kernel_window_0.reshape(uniform_list_shape<1>(1, {window_dims[0]})); kernel_window_1.reshape(uniform_list_shape<1>(1, {window_dims[1]})); input.reshape(data_shape); intermediate.reshape(data_shape); output.reshape(data_shape); baseline_output.reshape(data_shape); auto kernel_window_0_v = kernel_window_0.cpu()[0]; auto kernel_window_1_v = kernel_window_1.cpu()[0]; auto in_v = input.cpu()[0]; auto interm_v = intermediate.cpu()[0]; auto out_v = output.cpu()[0]; auto baseline_out_v = baseline_output.cpu()[0]; std::mt19937 rng; UniformRandomFill(in_v, rng, 0, 255); InitTriangleWindow(kernel_window_0_v); InitTriangleWindow(kernel_window_1_v); SeparableConvolutionCpu<int, int, float, 2, true> kernel; static_assert( std::is_same<typename SeparableConvolutionCpu<int, int, float, 2, true>::Intermediate, float>::value, "Unexpected intermediate type"); KernelContext ctx; auto req = kernel.Setup(ctx, data_shape[0], window_dims); ScratchpadAllocator scratch_alloc; scratch_alloc.Reserve(req.scratch_sizes); auto scratchpad = scratch_alloc.GetScratchpad(); ctx.scratchpad = &scratchpad; kernel.Run(ctx, out_v, in_v, {kernel_window_0_v, kernel_window_1_v}); testing::BaselineConvolve(interm_v, in_v, kernel_window_1_v, 1, window_dims[1] / 2); testing::BaselineConvolve(baseline_out_v, interm_v, kernel_window_0_v, 0, window_dims[0] / 2); Check(out_v, baseline_out_v); } TEST(SeparableConvolutionTest, Axes2NoChannels) { std::array<int, 2> window_dims = {5, 7}; TestTensorList<float, 1> kernel_window_0, kernel_window_1; TestTensorList<int, 3> input; TestTensorList<float, 3> intermediate; TestTensorList<int, 2> output; TestTensorList<int, 3> baseline_output; TensorListShape<3> data_shape = uniform_list_shape<3>(1, {20, 16, 1}); kernel_window_0.reshape(uniform_list_shape<1>(1, {window_dims[0]})); kernel_window_1.reshape(uniform_list_shape<1>(1, {window_dims[1]})); input.reshape(data_shape); intermediate.reshape(data_shape); output.reshape(data_shape.first<2>()); baseline_output.reshape(data_shape); auto kernel_window_0_v = kernel_window_0.cpu()[0]; auto kernel_window_1_v = kernel_window_1.cpu()[0]; auto baseline_in_v = input.cpu()[0]; TensorView<StorageCPU, int, 2> in_v = {baseline_in_v.data, baseline_in_v.shape.first<2>()}; auto interm_v = intermediate.cpu()[0]; auto out_v = output.cpu()[0]; auto baseline_out_v = baseline_output.cpu()[0]; std::mt19937 rng; UniformRandomFill(in_v, rng, 0, 255); InitTriangleWindow(kernel_window_0_v); InitTriangleWindow(kernel_window_1_v); SeparableConvolutionCpu<int, int, float, 2, false> kernel; static_assert( std::is_same<typename SeparableConvolutionCpu<int, int, float, 2, false>::Intermediate, float>::value, "Unexpected intermediate type"); KernelContext ctx; auto req = kernel.Setup(ctx, data_shape[0].first<2>(), window_dims); ScratchpadAllocator scratch_alloc; scratch_alloc.Reserve(req.scratch_sizes); auto scratchpad = scratch_alloc.GetScratchpad(); ctx.scratchpad = &scratchpad; kernel.Run(ctx, out_v, in_v, {kernel_window_0_v, kernel_window_1_v}); testing::BaselineConvolve(interm_v, baseline_in_v, kernel_window_1_v, 1, window_dims[1] / 2); testing::BaselineConvolve(baseline_out_v, interm_v, kernel_window_0_v, 0, window_dims[0] / 2); TensorView<StorageCPU, int, 2> compare_v = {baseline_out_v.data, baseline_out_v.shape.first<2>()}; Check(out_v, compare_v); } TEST(SeparableConvolutionTest, Axes3WithChannels) { std::array<int, 3> window_dims = {5, 7, 3}; TestTensorList<uint16_t, 1> kernel_window_0, kernel_window_1, kernel_window_2; TestTensorList<int16_t, 4> input; TestTensorList<int, 4> intermediate_0, intermediate_1; TestTensorList<int16_t, 4> output, baseline_output; TensorListShape<4> data_shape = uniform_list_shape<4>(1, {14, 20, 16, 3}); kernel_window_0.reshape(uniform_list_shape<1>(1, {window_dims[0]})); kernel_window_1.reshape(uniform_list_shape<1>(1, {window_dims[1]})); kernel_window_2.reshape(uniform_list_shape<1>(1, {window_dims[2]})); input.reshape(data_shape); intermediate_0.reshape(data_shape); intermediate_1.reshape(data_shape); output.reshape(data_shape); baseline_output.reshape(data_shape); auto kernel_window_0_v = kernel_window_0.cpu()[0]; auto kernel_window_1_v = kernel_window_1.cpu()[0]; auto kernel_window_2_v = kernel_window_2.cpu()[0]; auto in_v = input.cpu()[0]; auto interm_0_v = intermediate_0.cpu()[0]; auto interm_1_v = intermediate_1.cpu()[0]; auto out_v = output.cpu()[0]; auto baseline_out_v = baseline_output.cpu()[0]; std::mt19937 rng; UniformRandomFill(in_v, rng, 0, 255); InitTriangleWindow(kernel_window_0_v); InitTriangleWindow(kernel_window_1_v); InitTriangleWindow(kernel_window_2_v); SeparableConvolutionCpu<int16_t, int16_t, uint16_t, 3, true> kernel; static_assert( std::is_same< typename SeparableConvolutionCpu<int16_t, int16_t, uint16_t, 3, true>::Intermediate, int>::value, "Unexpected intermediate type"); KernelContext ctx; auto req = kernel.Setup(ctx, data_shape[0], window_dims); ScratchpadAllocator scratch_alloc; scratch_alloc.Reserve(req.scratch_sizes); auto scratchpad = scratch_alloc.GetScratchpad(); ctx.scratchpad = &scratchpad; kernel.Run(ctx, out_v, in_v, {kernel_window_0_v, kernel_window_1_v, kernel_window_2_v}); testing::BaselineConvolve(interm_0_v, in_v, kernel_window_2_v, 2, window_dims[2] / 2); testing::BaselineConvolve(interm_1_v, interm_0_v, kernel_window_1_v, 1, window_dims[1] / 2); testing::BaselineConvolve(baseline_out_v, interm_1_v, kernel_window_0_v, 0, window_dims[0] / 2); Check(out_v, baseline_out_v); } TEST(SeparableConvolutionTest, Axes3NoChannels) { std::array<int, 3> window_dims = {5, 7, 3}; TestTensorList<float, 1> kernel_window_0, kernel_window_1, kernel_window_2; TestTensorList<int, 4> input; TestTensorList<float, 4> intermediate_0, intermediate_1; TestTensorList<float, 3> output; TestTensorList<float, 4> baseline_output; TensorListShape<4> data_shape = uniform_list_shape<4>(1, {14, 20, 16, 1}); kernel_window_0.reshape(uniform_list_shape<1>(1, {window_dims[0]})); kernel_window_1.reshape(uniform_list_shape<1>(1, {window_dims[1]})); kernel_window_2.reshape(uniform_list_shape<1>(1, {window_dims[2]})); input.reshape(data_shape); intermediate_0.reshape(data_shape); intermediate_1.reshape(data_shape); output.reshape(data_shape.first<3>()); baseline_output.reshape(data_shape); auto kernel_window_0_v = kernel_window_0.cpu()[0]; auto kernel_window_1_v = kernel_window_1.cpu()[0]; auto kernel_window_2_v = kernel_window_2.cpu()[0]; auto baseline_in_v = input.cpu()[0]; TensorView<StorageCPU, int, 3> in_v = {baseline_in_v.data, baseline_in_v.shape.first<3>()}; auto interm_0_v = intermediate_0.cpu()[0]; auto interm_1_v = intermediate_1.cpu()[0]; auto out_v = output.cpu()[0]; auto baseline_out_v = baseline_output.cpu()[0]; std::mt19937 rng; UniformRandomFill(in_v, rng, 0, 255); InitTriangleWindow(kernel_window_0_v); InitTriangleWindow(kernel_window_1_v); InitTriangleWindow(kernel_window_2_v); SeparableConvolutionCpu<float, int, float, 3, false> kernel; static_assert( std::is_same<typename SeparableConvolutionCpu<float, int, float, 3, false>::Intermediate, float>::value, "Unexpected intermediate type"); KernelContext ctx; auto req = kernel.Setup(ctx, data_shape[0].first<3>(), window_dims); ScratchpadAllocator scratch_alloc; scratch_alloc.Reserve(req.scratch_sizes); auto scratchpad = scratch_alloc.GetScratchpad(); ctx.scratchpad = &scratchpad; kernel.Run(ctx, out_v, in_v, {kernel_window_0_v, kernel_window_1_v, kernel_window_2_v}); testing::BaselineConvolve(interm_0_v, baseline_in_v, kernel_window_2_v, 2, window_dims[2] / 2); testing::BaselineConvolve(interm_1_v, interm_0_v, kernel_window_1_v, 1, window_dims[1] / 2); testing::BaselineConvolve(baseline_out_v, interm_1_v, kernel_window_0_v, 0, window_dims[0] / 2); TensorView<StorageCPU, float, 3> compare_v = {baseline_out_v.data, baseline_out_v.shape.first<3>()}; Check(out_v, compare_v); } } // namespace kernels } // namespace dali
{ "pile_set_name": "Github" }
<?php /** * CoreShop. * * This source file is subject to the GNU General Public License version 3 (GPLv3) * For the full copyright and license information, please view the LICENSE.md and gpl-3.0.txt * files that are distributed with this source code. * * @copyright Copyright (c) 2015-2020 Dominik Pfaffenbauer (https://www.pfaffenbauer.at) * @license https://www.coreshop.org/license GNU General Public License version 3 (GPLv3) */ declare(strict_types=1); namespace CoreShop\Behat\Model\Index; use CoreShop\Component\Index\Model\IndexableInterface; use CoreShop\Component\Index\Model\IndexInterface; use CoreShop\Component\Resource\Exception\ImplementedByPimcoreException; use CoreShop\Component\Resource\Pimcore\Model\AbstractPimcoreModel; class TestEnableIndex extends AbstractPimcoreModel implements IndexableInterface { /** * {@inheritdoc} */ public function getIndexable(IndexInterface $index): bool { return $this->getIndexableEnabled($index) && $this->getPublished(); } /** * {@inheritdoc} */ public function getIndexableEnabled(IndexInterface $index): bool { $enabled = $this->getEnabled(); if (is_bool($enabled)) { return $enabled; } return false; } /** * {@inheritdoc} */ public function getIndexableName(IndexInterface $index, string $language): string { $name = $this->getName($language); if (null === $name) { return ''; } if (!is_string($name)) { return ''; } return $name; } /** * {@inheritdoc} */ public function getEnabled() { return new ImplementedByPimcoreException(__CLASS__, __METHOD__); } /** * {@inheritdoc} */ public function getName($language) { return new ImplementedByPimcoreException(__CLASS__, __METHOD__); } }
{ "pile_set_name": "Github" }
@import url("gtk-main.css");
{ "pile_set_name": "Github" }
"""Statistics analyzer for HotShot.""" import profile import pstats import hotshot.log from hotshot.log import ENTER, EXIT def load(filename): return StatsLoader(filename).load() class StatsLoader: def __init__(self, logfn): self._logfn = logfn self._code = {} self._stack = [] self.pop_frame = self._stack.pop def load(self): # The timer selected by the profiler should never be used, so make # sure it doesn't work: p = Profile() p.get_time = _brokentimer log = hotshot.log.LogReader(self._logfn) taccum = 0 for event in log: what, (filename, lineno, funcname), tdelta = event if tdelta > 0: taccum += tdelta # We multiply taccum to convert from the microseconds we # have to the seconds that the profile/pstats module work # with; this allows the numbers to have some basis in # reality (ignoring calibration issues for now). if what == ENTER: frame = self.new_frame(filename, lineno, funcname) p.trace_dispatch_call(frame, taccum * .000001) taccum = 0 elif what == EXIT: frame = self.pop_frame() p.trace_dispatch_return(frame, taccum * .000001) taccum = 0 # no further work for line events assert not self._stack return pstats.Stats(p) def new_frame(self, *args): # args must be filename, firstlineno, funcname # our code objects are cached since we don't need to create # new ones every time try: code = self._code[args] except KeyError: code = FakeCode(*args) self._code[args] = code # frame objects are create fresh, since the back pointer will # vary considerably if self._stack: back = self._stack[-1] else: back = None frame = FakeFrame(code, back) self._stack.append(frame) return frame class Profile(profile.Profile): def simulate_cmd_complete(self): pass class FakeCode: def __init__(self, filename, firstlineno, funcname): self.co_filename = filename self.co_firstlineno = firstlineno self.co_name = self.__name__ = funcname class FakeFrame: def __init__(self, code, back): self.f_back = back self.f_code = code def _brokentimer(): raise RuntimeError, "this timer should not be called"
{ "pile_set_name": "Github" }
"""Tokenization help for Python programs. generate_tokens(readline) is a generator that breaks a stream of text into Python tokens. It accepts a readline-like method which is called repeatedly to get the next line of input (or "" for EOF). It generates 5-tuples with these members: the token type (see token.py) the token (a string) the starting (row, column) indices of the token (a 2-tuple of ints) the ending (row, column) indices of the token (a 2-tuple of ints) the original line (string) It is designed to match the working of the Python tokenizer exactly, except that it produces COMMENT tokens for comments and gives type OP for all operators Older entry points tokenize_loop(readline, tokeneater) tokenize(readline, tokeneater=printtoken) are the same, except instead of generating tokens, tokeneater is a callback function to which the 5 fields described above are passed as 5 arguments, each time a new token is found.""" __author__ = 'Ka-Ping Yee <[email protected]>' __credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, ' 'Skip Montanaro, Raymond Hettinger') from itertools import chain import string, re from token import * import token __all__ = [x for x in dir(token) if not x.startswith("_")] __all__ += ["COMMENT", "tokenize", "generate_tokens", "NL", "untokenize"] del x del token COMMENT = N_TOKENS tok_name[COMMENT] = 'COMMENT' NL = N_TOKENS + 1 tok_name[NL] = 'NL' N_TOKENS += 2 def group(*choices): return '(' + '|'.join(choices) + ')' def any(*choices): return group(*choices) + '*' def maybe(*choices): return group(*choices) + '?' Whitespace = r'[ \f\t]*' Comment = r'#[^\r\n]*' Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment) Name = r'[a-zA-Z_]\w*' Hexnumber = r'0[xX][\da-fA-F]+[lL]?' Octnumber = r'(0[oO][0-7]+)|(0[0-7]*)[lL]?' Binnumber = r'0[bB][01]+[lL]?' Decnumber = r'[1-9]\d*[lL]?' Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber) Exponent = r'[eE][-+]?\d+' Pointfloat = group(r'\d+\.\d*', r'\.\d+') + maybe(Exponent) Expfloat = r'\d+' + Exponent Floatnumber = group(Pointfloat, Expfloat) Imagnumber = group(r'\d+[jJ]', Floatnumber + r'[jJ]') Number = group(Imagnumber, Floatnumber, Intnumber) # Tail end of ' string. Single = r"[^'\\]*(?:\\.[^'\\]*)*'" # Tail end of " string. Double = r'[^"\\]*(?:\\.[^"\\]*)*"' # Tail end of ''' string. Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''" # Tail end of """ string. Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""' Triple = group("[uUbB]?[rR]?'''", '[uUbB]?[rR]?"""') # Single-line ' or " string. String = group(r"[uUbB]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*'", r'[uUbB]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*"') # Because of leftmost-then-longest match semantics, be sure to put the # longest operators first (e.g., if = came before ==, == would get # recognized as two instances of =). Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=", r"//=?", r"[+\-*/%&|^=<>]=?", r"~") Bracket = '[][(){}]' Special = group(r'\r?\n', r'[:;.,`@]') Funny = group(Operator, Bracket, Special) PlainToken = group(Number, Funny, String, Name) Token = Ignore + PlainToken # First (or only) line of ' or " string. ContStr = group(r"[uUbB]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*" + group("'", r'\\\r?\n'), r'[uUbB]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*' + group('"', r'\\\r?\n')) PseudoExtras = group(r'\\\r?\n|\Z', Comment, Triple) PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name) tokenprog, pseudoprog, single3prog, double3prog = map( re.compile, (Token, PseudoToken, Single3, Double3)) endprogs = {"'": re.compile(Single), '"': re.compile(Double), "'''": single3prog, '"""': double3prog, "r'''": single3prog, 'r"""': double3prog, "u'''": single3prog, 'u"""': double3prog, "ur'''": single3prog, 'ur"""': double3prog, "R'''": single3prog, 'R"""': double3prog, "U'''": single3prog, 'U"""': double3prog, "uR'''": single3prog, 'uR"""': double3prog, "Ur'''": single3prog, 'Ur"""': double3prog, "UR'''": single3prog, 'UR"""': double3prog, "b'''": single3prog, 'b"""': double3prog, "br'''": single3prog, 'br"""': double3prog, "B'''": single3prog, 'B"""': double3prog, "bR'''": single3prog, 'bR"""': double3prog, "Br'''": single3prog, 'Br"""': double3prog, "BR'''": single3prog, 'BR"""': double3prog, 'r': None, 'R': None, 'u': None, 'U': None, 'b': None, 'B': None} triple_quoted = {} for t in ("'''", '"""', "r'''", 'r"""', "R'''", 'R"""', "u'''", 'u"""', "U'''", 'U"""', "ur'''", 'ur"""', "Ur'''", 'Ur"""', "uR'''", 'uR"""', "UR'''", 'UR"""', "b'''", 'b"""', "B'''", 'B"""', "br'''", 'br"""', "Br'''", 'Br"""', "bR'''", 'bR"""', "BR'''", 'BR"""'): triple_quoted[t] = t single_quoted = {} for t in ("'", '"', "r'", 'r"', "R'", 'R"', "u'", 'u"', "U'", 'U"', "ur'", 'ur"', "Ur'", 'Ur"', "uR'", 'uR"', "UR'", 'UR"', "b'", 'b"', "B'", 'B"', "br'", 'br"', "Br'", 'Br"', "bR'", 'bR"', "BR'", 'BR"' ): single_quoted[t] = t tabsize = 8 class TokenError(Exception): pass class StopTokenizing(Exception): pass def printtoken(type, token, srow_scol, erow_ecol, line): # for testing srow, scol = srow_scol erow, ecol = erow_ecol print "%d,%d-%d,%d:\t%s\t%s" % \ (srow, scol, erow, ecol, tok_name[type], repr(token)) def tokenize(readline, tokeneater=printtoken): """ The tokenize() function accepts two parameters: one representing the input stream, and one providing an output mechanism for tokenize(). The first parameter, readline, must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. The second parameter, tokeneater, must also be a callable object. It is called once for each token, with five arguments, corresponding to the tuples generated by generate_tokens(). """ try: tokenize_loop(readline, tokeneater) except StopTokenizing: pass # backwards compatible interface def tokenize_loop(readline, tokeneater): for token_info in generate_tokens(readline): tokeneater(*token_info) class Untokenizer: def __init__(self): self.tokens = [] self.prev_row = 1 self.prev_col = 0 def add_whitespace(self, start): row, col = start if row < self.prev_row or row == self.prev_row and col < self.prev_col: raise ValueError("start ({},{}) precedes previous end ({},{})" .format(row, col, self.prev_row, self.prev_col)) row_offset = row - self.prev_row if row_offset: self.tokens.append("\\\n" * row_offset) self.prev_col = 0 col_offset = col - self.prev_col if col_offset: self.tokens.append(" " * col_offset) def untokenize(self, iterable): it = iter(iterable) for t in it: if len(t) == 2: self.compat(t, it) break tok_type, token, start, end, line = t if tok_type == ENDMARKER: break self.add_whitespace(start) self.tokens.append(token) self.prev_row, self.prev_col = end if tok_type in (NEWLINE, NL): self.prev_row += 1 self.prev_col = 0 return "".join(self.tokens) def compat(self, token, iterable): indents = [] toks_append = self.tokens.append startline = token[0] in (NEWLINE, NL) prevstring = False for tok in chain([token], iterable): toknum, tokval = tok[:2] if toknum in (NAME, NUMBER): tokval += ' ' # Insert a space between two consecutive strings if toknum == STRING: if prevstring: tokval = ' ' + tokval prevstring = True else: prevstring = False if toknum == INDENT: indents.append(tokval) continue elif toknum == DEDENT: indents.pop() continue elif toknum in (NEWLINE, NL): startline = True elif startline and indents: toks_append(indents[-1]) startline = False toks_append(tokval) def untokenize(iterable): """Transform tokens back into Python source code. Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If only two tokens are passed, the resulting output is poor. Round-trip invariant for full input: Untokenized source will match input source exactly Round-trip invariant for limited intput: # Output text will tokenize the back to the input t1 = [tok[:2] for tok in generate_tokens(f.readline)] newcode = untokenize(t1) readline = iter(newcode.splitlines(1)).next t2 = [tok[:2] for tok in generate_tokens(readline)] assert t1 == t2 """ ut = Untokenizer() return ut.untokenize(iterable) def generate_tokens(readline): """ The generate_tokens() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. Alternately, readline can be a callable function terminating with StopIteration: readline = open(myfile).next # Example of alternate readline The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed is the logical line; continuation lines are included. """ lnum = parenlev = continued = 0 namechars, numchars = string.ascii_letters + '_', '0123456789' contstr, needcont = '', 0 contline = None indents = [0] while 1: # loop over lines in stream try: line = readline() except StopIteration: line = '' lnum += 1 pos, max = 0, len(line) if contstr: # continued string if not line: raise TokenError, ("EOF in multi-line string", strstart) endmatch = endprog.match(line) if endmatch: pos = end = endmatch.end(0) yield (STRING, contstr + line[:end], strstart, (lnum, end), contline + line) contstr, needcont = '', 0 contline = None elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n': yield (ERRORTOKEN, contstr + line, strstart, (lnum, len(line)), contline) contstr = '' contline = None continue else: contstr = contstr + line contline = contline + line continue elif parenlev == 0 and not continued: # new statement if not line: break column = 0 while pos < max: # measure leading whitespace if line[pos] == ' ': column += 1 elif line[pos] == '\t': column = (column//tabsize + 1)*tabsize elif line[pos] == '\f': column = 0 else: break pos += 1 if pos == max: break if line[pos] in '#\r\n': # skip comments or blank lines if line[pos] == '#': comment_token = line[pos:].rstrip('\r\n') nl_pos = pos + len(comment_token) yield (COMMENT, comment_token, (lnum, pos), (lnum, pos + len(comment_token)), line) yield (NL, line[nl_pos:], (lnum, nl_pos), (lnum, len(line)), line) else: yield ((NL, COMMENT)[line[pos] == '#'], line[pos:], (lnum, pos), (lnum, len(line)), line) continue if column > indents[-1]: # count indents or dedents indents.append(column) yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line) while column < indents[-1]: if column not in indents: raise IndentationError( "unindent does not match any outer indentation level", ("<tokenize>", lnum, pos, line)) indents = indents[:-1] yield (DEDENT, '', (lnum, pos), (lnum, pos), line) else: # continued statement if not line: raise TokenError, ("EOF in multi-line statement", (lnum, 0)) continued = 0 while pos < max: pseudomatch = pseudoprog.match(line, pos) if pseudomatch: # scan for tokens start, end = pseudomatch.span(1) spos, epos, pos = (lnum, start), (lnum, end), end if start == end: continue token, initial = line[start:end], line[start] if initial in numchars or \ (initial == '.' and token != '.'): # ordinary number yield (NUMBER, token, spos, epos, line) elif initial in '\r\n': yield (NL if parenlev > 0 else NEWLINE, token, spos, epos, line) elif initial == '#': assert not token.endswith("\n") yield (COMMENT, token, spos, epos, line) elif token in triple_quoted: endprog = endprogs[token] endmatch = endprog.match(line, pos) if endmatch: # all on one line pos = endmatch.end(0) token = line[start:pos] yield (STRING, token, spos, (lnum, pos), line) else: strstart = (lnum, start) # multiple lines contstr = line[start:] contline = line break elif initial in single_quoted or \ token[:2] in single_quoted or \ token[:3] in single_quoted: if token[-1] == '\n': # continued string strstart = (lnum, start) endprog = (endprogs[initial] or endprogs[token[1]] or endprogs[token[2]]) contstr, needcont = line[start:], 1 contline = line break else: # ordinary string yield (STRING, token, spos, epos, line) elif initial in namechars: # ordinary name yield (NAME, token, spos, epos, line) elif initial == '\\': # continued stmt continued = 1 else: if initial in '([{': parenlev += 1 elif initial in ')]}': parenlev -= 1 yield (OP, token, spos, epos, line) else: yield (ERRORTOKEN, line[pos], (lnum, pos), (lnum, pos+1), line) pos += 1 for indent in indents[1:]: # pop remaining indent levels yield (DEDENT, '', (lnum, 0), (lnum, 0), '') yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '') if __name__ == '__main__': # testing import sys if len(sys.argv) > 1: tokenize(open(sys.argv[1]).readline) else: tokenize(sys.stdin.readline)
{ "pile_set_name": "Github" }
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license cs.js Found: 118 Missing: 0 cy.js Found: 118 Missing: 0 de.js Found: 118 Missing: 0 el.js Found: 16 Missing: 102 eo.js Found: 118 Missing: 0 et.js Found: 31 Missing: 87 fa.js Found: 24 Missing: 94 fi.js Found: 23 Missing: 95 fr.js Found: 118 Missing: 0 hr.js Found: 23 Missing: 95 it.js Found: 118 Missing: 0 nb.js Found: 118 Missing: 0 nl.js Found: 118 Missing: 0 no.js Found: 118 Missing: 0 tr.js Found: 118 Missing: 0 ug.js Found: 39 Missing: 79 zh-cn.js Found: 118 Missing: 0
{ "pile_set_name": "Github" }
/* * This file is part of EasyRPG Player. * * EasyRPG Player 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. * * EasyRPG Player 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 EasyRPG Player. If not, see <http://www.gnu.org/licenses/>. */ #ifndef EP_SCENE_ACTORTARGET_H #define EP_SCENE_ACTORTARGET_H // Headers #include "scene.h" #include "window_actortarget.h" #include "window_help.h" #include "window_targetstatus.h" /** * Scene ActorTarget class. * Manages using of Items and Spells. */ class Scene_ActorTarget : public Scene { public: /** * Constructor. * * @param item_id item ID of item to use. */ Scene_ActorTarget(int item_id); /** * Constructor. * * @param skill_id skill ID of skill to use. * @param actor_index index of the spell caster in party. */ Scene_ActorTarget(int skill_id, int actor_index); void Start() override; void Update() override; /** * Update function used when an item will be used. */ void UpdateItem(); /** * Update function used when a skill will be used. */ void UpdateSkill(); private: /** Contains the actors of the party. */ std::unique_ptr<Window_ActorTarget> target_window; /** Contains the name of the item/skill that will be used. */ std::unique_ptr<Window_Help> help_window; /** Contains quantity/cost of item/spell. */ std::unique_ptr<Window_TargetStatus> status_window; /** ID of item/skill to use. */ int id; /* Index of spell caster in party (only for skills). */ int actor_index; /** True if item, false if skill. */ bool use_item; }; #endif
{ "pile_set_name": "Github" }
<?php defined('YII_DEBUG') or define('YII_DEBUG', true); defined('YII_ENV') or define('YII_ENV', 'test'); defined('YII_APP_BASE_PATH') or define('YII_APP_BASE_PATH', dirname(dirname(dirname(__DIR__)))); defined('FRONTEND_ENTRY_URL') or define('FRONTEND_ENTRY_URL', parse_url(\Codeception\Configuration::config()['config']['test_entry_url'], PHP_URL_PATH)); defined('FRONTEND_ENTRY_FILE') or define('FRONTEND_ENTRY_FILE', YII_APP_BASE_PATH . '/frontend/web/index-test.php'); require_once(YII_APP_BASE_PATH . '/vendor/autoload.php'); require_once(YII_APP_BASE_PATH . '/vendor/yiisoft/yii2/Yii.php'); require_once(YII_APP_BASE_PATH . '/common/config/bootstrap.php'); require_once(YII_APP_BASE_PATH . '/frontend/config/bootstrap.php'); // set correct script paths // the entry script file path for functional and acceptance tests $_SERVER['SCRIPT_FILENAME'] = FRONTEND_ENTRY_FILE; $_SERVER['SCRIPT_NAME'] = FRONTEND_ENTRY_URL; $_SERVER['SERVER_NAME'] = parse_url(\Codeception\Configuration::config()['config']['test_entry_url'], PHP_URL_HOST); $_SERVER['SERVER_PORT'] = parse_url(\Codeception\Configuration::config()['config']['test_entry_url'], PHP_URL_PORT) ?: '80'; Yii::setAlias('@tests', dirname(dirname(__DIR__)));
{ "pile_set_name": "Github" }
'use strict'; const acorn = require('acorn-jsx'); const esrecurse = require('../esrecurse/esrecurse'); const escodegen = require('escodegen'); const esquery = require('../esquery/esquery'); const bfs = require('acorn-bfs'); const htmlElements = require('./constants.js').htmlElements; const reactMethods = require('./constants.js').reactMethods; function getReactStates(node) { const stateStr = escodegen.generate(node); let states; eval(`states = ${stateStr}`); const output = []; for (const state in states) { output.push({ name: state, value: states[state], }); } return output; } /** * Returns array of props from React component passed to input * @param {Node} node * @returns {Array} Array of all JSX props on React component */ function getReactProps(node, parent) { if (node.openingElement.attributes.length === 0 || htmlElements.indexOf(node.openingElement.name.name) > 0) return {}; const result = node.openingElement.attributes .map(attribute => { const name = attribute.name.name; let valueName; if (attribute.value === null) valueName = undefined; else if (attribute.value.type === 'Literal') valueName = attribute.value.value; else if (attribute.value.expression.type === 'Literal') { valueName = attribute.value.expression.value; } else if (attribute.value.expression.type === 'Identifier') { valueName = attribute.value.expression.name; } else if (attribute.value.expression.type === 'CallExpression') { valueName = attribute.value.expression.callee.object.property.name; } else if (attribute.value.expression.type === 'BinaryExpression') { valueName = attribute.value.expression.left.name + attribute.value.expression.operator + (attribute.value.expression.right.name || attribute.value.expression.right.value); } else if (attribute.value.expression.type === 'MemberExpression') { let current = attribute.value.expression; while (current && current.property) { // && !current.property.name.match(/(state|props)/) valueName = `.${current.property.name}${valueName || ''}`; current = current.object; if (current.type === 'Identifier') { valueName = `.${current.name}${valueName || ''}`; break; } } valueName = valueName.replace('.', ''); } else if (attribute.value.expression.type === 'LogicalExpression') { valueName = attribute.value.expression.left.property.name; // valueType = attribute.value.expression.left.object.name; } else if (attribute.value.expression.type === 'JSXElement') { const nodez = attribute.value.expression; const output = { name: nodez.openingElement.name.name, children: getChildJSXElements(nodez, parent), props: getReactProps(nodez, parent), state: {}, methods: [], }; valueName = output; } else valueName = escodegen.generate(attribute.value); return { name, value: valueName, parent, }; }); return result; } /** * Returns array of children components of React component passed to input * @param {Node} node * @returns {Array} Array of (nested) children of React component passed in */ function getChildJSXElements(node, parent) { if (node.children.length === 0) return []; const childJsxComponentsArr = node .children .filter(jsx => jsx.type === 'JSXElement' && htmlElements.indexOf(jsx.openingElement.name.name) < 0); return childJsxComponentsArr .map(child => { return { name: child.openingElement.name.name, children: getChildJSXElements(child, parent), props: getReactProps(child, parent), state: {}, methods: [], }; }); } function forInFinder(arr, name) { const result = arr.map(ele => { const jsxnode = esquery(ele, 'JSXElement')[0]; const obj = {}; obj.variables = {}; esquery(ele, 'VariableDeclarator').forEach(vars => { if (vars.id.name !== 'i' && vars.init) { obj.variables[vars.id.name] = escodegen.generate(vars.init).replace('this.', ''); } }); if (ele.left.declarations) obj.variables[ele.left.declarations[0].id.name] = '[key]'; else if (ele.left.type === 'Identifier') obj.variables[ele.left.name] = '[key]'; if (jsxnode && htmlElements.indexOf(jsxnode.openingElement.name.name)) { let current = ele.right; let found; while (current && current.property) { found = `.${current.property.name}${found || ''}`; current = current.object; if (current.type === 'Identifier') { found = `.${current.name}${found || ''}`; break; } } obj.jsx = { name: jsxnode.openingElement.name.name, children: getChildJSXElements(jsxnode, name), props: getReactProps(jsxnode, name), state: {}, methods: [], iterated: 'forIn', source: found.replace('.', ''), }; const propsArr = obj.jsx.props; for (let i = 0; i < propsArr.length; i++) { for (const key in obj.variables) { if (propsArr[i].value.includes(key)) { if (obj.variables[key] === '[key]') { propsArr[i].value = propsArr[i].value.replace(`.${key}`, obj.variables[key]); } else propsArr[i].value = propsArr[i].value.replace(key, obj.variables[key]); } } } } return obj; }); return result; } function forLoopFinder(arr, name) { const result = arr.map(ele => { const jsxnode = esquery(ele, 'JSXElement')[0]; const obj = {}; obj.variables = {}; // finding variables in case information was reassigned esquery(ele, 'VariableDeclarator').forEach(vars => { if (vars.id.name !== 'i' && vars.init) { obj.variables[vars.id.name] = escodegen.generate(vars.init) .replace('this.', '').replace('.length', ''); } }); // defaulting each iteration to be represented by 'i' if (ele.init.declarations) obj.variables[ele.init.declarations[0].id.name] = '[i]'; else if (ele.init.type === 'AssignmentExpression') obj.variables[ele.init.left.name] = '[i]'; // building the object name if (jsxnode && htmlElements.indexOf(jsxnode.openingElement.name.name)) { let current = ele.test.right; let found; while (current && current.property) { found = `.${current.property.name}${found || ''}`; current = current.object; if (current.type === 'Identifier') { found = `.${current.name}${found || ''}`; break; } } obj.jsx = { name: jsxnode.openingElement.name.name, children: getChildJSXElements(jsxnode, name), props: getReactProps(jsxnode, name), state: {}, methods: [], iterated: 'forLoop', source: found.replace('.', '').replace('.length', ''), }; // replacing variables with their properties const propsArr = obj.jsx.props; for (let i = 0; i < propsArr.length; i++) { for (const key in obj.variables) { if (propsArr[i].value.includes(key)) { if (obj.variables[key] === '[i]') { propsArr[i].value = propsArr[i].value.replace(`.${key}`, obj.variables[key]); } else propsArr[i].value = propsArr[i].value.replace(key, obj.variables[key]); } } } } return obj; }); return result; } function higherOrderFunctionFinder(arr, name) { const result = arr.map(ele => { // since every higher order function will have some parameter // will be used to replace with what it actually is const param = ele.arguments[0].params[0].name; const jsxnode = esquery(ele, 'JSXElement')[0]; const obj = {}; obj.variables = {}; esquery(ele, 'VariableDeclarator').forEach(vars => { obj.variables[vars.id.name] = escodegen.generate(vars.init); }); if (jsxnode && htmlElements.indexOf(jsxnode.openingElement.name.name)) { let current = ele.callee.object; let found; while (current && current.property) { found = `.${current.property.name}${found || ''}`; current = current.object; if (current.type === 'Identifier') { found = `.${current.name}${found || ''}`; break; } } obj.jsx = { name: jsxnode.openingElement.name.name, children: getChildJSXElements(jsxnode, name), props: getReactProps(jsxnode, name), state: {}, methods: [], iterated: 'higherOrder', source: found.replace('.', ''), }; const propsArr = obj.jsx.props; for (let i = 0; i < propsArr.length; i++) { propsArr[i].value = propsArr[i].value.replace(param, `${obj.jsx.source}[i]`); for (const key in obj.variables) { if (propsArr[i].value.includes(key)) { propsArr[i].value = propsArr[i].value.replace(key, obj.variables[key]); } } } } return obj; }); return result; } /** * Returns if AST node is an ES6 React component * @param {Node} node * @return {Boolean} Determines if AST node is a React component node */ function isES6ReactComponent(node) { return (node.superClass.property && node.superClass.property.name === 'Component') || node.superClass.name === 'Component'; } /** * Recursively walks AST and extracts ES5 React component names, child components, props and state * @param {ast} ast * @returns {Object} Nested object containing name, children, * props and state properties of components */ function getES5ReactComponents(ast) { const output = { name: '', state: {}, props: {}, methods: [], children: [], }; let iter = []; let topJsxComponent; let outside; const checker = {}; esrecurse.visit(ast, { VariableDeclarator(node) { topJsxComponent = node.id.name; this.visitChildren(node); }, MemberExpression(node) { if (node.property && node.property.name === 'createClass') { output.name = topJsxComponent; } this.visitChildren(node); }, ObjectExpression(node) { node.properties.forEach(prop => { if (reactMethods.indexOf(prop.key.name) < 0 && prop.value.type === 'FunctionExpression') { output.methods.push(prop.key.name); } }); this.visitChildren(node); }, JSXElement(node) { output.children = getChildJSXElements(node, output.name); output.props = getReactProps(node, output.name); if (htmlElements.indexOf(node.openingElement.name.name) < 0) { outside = { name: node.openingElement.name.name, children: getChildJSXElements(node, output.name), props: getReactProps(node, output.name), state: {}, methods: [], }; } }, }); const forIn = esquery(ast, 'ForInStatement').filter(ele => { const searched = bfs(ele).filter(n => { return n.type === 'JSXElement'; }); return searched.length > 0; }); if (forIn.length > 0) iter = iter.concat(forInFinder(forIn, output.name)); const forLoop = esquery(ast, 'ForStatement').filter(ele => { const searched = bfs(ele).filter(n => { return n.type === 'JSXElement'; }); return searched.length > 0; }); if (forLoop.length > 0) iter = iter.concat(forLoopFinder(forLoop, output.name)); const higherOrderFunc = esquery(ast, 'CallExpression').filter(ele => { let higherOrderChecker = false; const searched = bfs(ele).filter(n => { return n.type === 'JSXElement'; }); if (ele.callee.property && ele.callee.property.name.match(/(map|forEach|filter|reduce)/)) { higherOrderChecker = ele.callee.property.name.match(/(map|forEach|filter|reduce)/); } return searched.length > 0 && higherOrderChecker; }); if (higherOrderFunc.length > 0) { iter = iter.concat(higherOrderFunctionFinder(higherOrderFunc, output.name)); } if (outside) output.children.push(outside); output.children.forEach((ele, i) => { checker[ele.name] = i; }); for (let i = 0; i < iter.length; i++) { if (checker.hasOwnProperty(iter[i].jsx.name)) { output.children[checker[iter[i].jsx.name]] = iter[i].jsx; } } return output; } /** * Recursively walks AST and extracts ES6 React component names, child components, props and state * @param {ast} ast * @returns {Object} Nested object containing name, children, * props and state properties of components */ function getES6ReactComponents(ast) { const output = { name: '', props: {}, state: {}, methods: [], children: [], }; let iter = []; let outside; const checker = {}; esrecurse.visit(ast, { ClassDeclaration(node) { if (isES6ReactComponent(node)) { output.name = node.id.name; this.visitChildren(node); } }, MethodDefinition(node) { if (reactMethods.indexOf(node.key.name) < 0) output.methods.push(node.key.name); this.visitChildren(node); }, JSXElement(node) { output.children = getChildJSXElements(node, output.name); output.props = getReactProps(node, output.name); if (htmlElements.indexOf(node.openingElement.name.name) < 0) { outside = { name: node.openingElement.name.name, children: getChildJSXElements(node, output.name), props: getReactProps(node, output.name), state: {}, methods: [], }; } const forIn = esquery(ast, 'ForInStatement').filter(ele => { const searched = bfs(ele).filter(n => { return n.type === 'JSXElement'; }); return searched.length > 0; }); if (forIn.length > 0) iter = iter.concat(forInFinder(forIn, output.name)); const forLoop = esquery(ast, 'ForStatement').filter(ele => { const searched = bfs(ele).filter(n => { return n.type === 'JSXElement'; }); return searched.length > 0; }); if (forLoop.length > 0) iter = iter.concat(forLoopFinder(forLoop, output.name)); const higherOrderFunc = esquery(ast, 'CallExpression').filter(ele => { let higherOrderChecker = false; const searched = bfs(ele).filter(n => { return n.type === 'JSXElement'; }); if (ele.callee.property && ele.callee.property.name.match(/(map|forEach|filter|reduce)/)) { higherOrderChecker = ele.callee.property.name.match(/(map|forEach|filter|reduce)/); } return searched.length > 0 && higherOrderChecker; }); if (higherOrderFunc.length > 0) iter = iter.concat(higherOrderFunctionFinder(higherOrderFunc, output.name)); }, }); if (outside) output.children.push(outside); output.children.forEach((ele, i) => { checker[ele.name] = i; }); for (let i = 0; i < iter.length; i++) { if (checker.hasOwnProperty(iter[i].jsx.name)) { output.children[checker[iter[i].jsx.name]] = iter[i].jsx; } } return output; } /** * Recursively walks AST extracts name, child component, and props for a stateless functional component * Still a WIP - no way to tell if it is actually a component or just a function * @param {ast} ast * @returns {Object} Nested object containing name, children, and props properties of components */ function getStatelessFunctionalComponents(ast, name) { const output = { name: name, state: {}, props: {}, methods: [], children: [], }; let iter = []; let outside; const checker = {}; esrecurse.visit(ast, { ObjectExpression(node) { node.properties.forEach(prop => { if (reactMethods.indexOf(prop.key.name) < 0 && prop.value.type === 'FunctionExpression') { output.methods.push(prop.key.name); } }); this.visitChildren(node); }, JSXElement(node) { output.children = getChildJSXElements(node, output.name); output.props = getReactProps(node, output.name); if (htmlElements.indexOf(node.openingElement.name.name) < 0) { outside = { name: node.openingElement.name.name, children: getChildJSXElements(node, output.name), props: getReactProps(node, output.name), state: {}, methods: [], }; } }, }); const forIn = esquery(ast, 'ForInStatement').filter(ele => { const searched = bfs(ele).filter(n => { return n.type === 'JSXElement'; }); return searched.length > 0; }); if (forIn.length > 0) iter = iter.concat(forInFinder(forIn, output.name)); const forLoop = esquery(ast, 'ForStatement').filter(ele => { const searched = bfs(ele).filter(n => { return n.type === 'JSXElement'; }); return searched.length > 0; }); if (forLoop.length > 0) iter = iter.concat(forLoopFinder(forLoop, output.name)); const higherOrderFunc = esquery(ast, 'CallExpression').filter(ele => { let higherOrderChecker = false; const searched = bfs(ele).filter(n => { return n.type === 'JSXElement'; }); if (ele.callee.property && ele.callee.property.name.match(/(map|forEach|filter|reduce)/)) { higherOrderChecker = ele.callee.property.name.match(/(map|forEach|filter|reduce)/); } return searched.length > 0 && higherOrderChecker; }); if (higherOrderFunc.length > 0) { iter = iter.concat(higherOrderFunctionFinder(higherOrderFunc, output.name)); } if (outside) output.children.push(outside); output.children.forEach((ele, i) => { checker[ele.name] = i; }); for (let i = 0; i < iter.length; i++) { if (checker.hasOwnProperty(iter[i].jsx.name)) { output.children[checker[iter[i].jsx.name]] = iter[i].jsx; } } return output; } /** * Helper function to convert Javascript stringified code to an AST using acorn-jsx library * @param js */ function jsToAst(js) { const ast = acorn.parse(js, { plugins: { jsx: true }, }); if (ast.body.length === 0) throw new Error('Empty AST input'); return ast; } function componentChecker(ast) { for (let i = 0; i < ast.body.length; i++) { if (ast.body[i].type === 'ClassDeclaration') return 'ES6'; if (ast.body[i].type === 'ExportDefaultDeclaration' && ast.body[i].declaration.type === 'ClassDeclaration') return 'ES6'; if (ast.body[i].type === 'VariableDeclaration' && ast.body[i].declarations[0].init && ast.body[i].declarations[0].init.callee && ast.body[i].declarations[0].init.callee.object && ast.body[i].declarations[0].init.callee.object.name === 'React' && ast.body[i].declarations[0].init.callee.property.name === 'createClass') return 'ES5'; } return 'SFC'; } module.exports = { jsToAst, componentChecker, getES5ReactComponents, getES6ReactComponents, getStatelessFunctionalComponents, forLoopFinder, forInFinder, higherOrderFunctionFinder, };
{ "pile_set_name": "Github" }
To: GitHub, Inc Attn: DMCA Agent 88 Colin P Kelly Jr St San Francisco, CA. 94107 via [email protected] [private], November 14th, 2018 Infringement Notice Dear Sirs/Madams, We have been notified that licence keys and activation codes for products of our company JetBrains s.r.o. (such as Upsource, PhpStorm, WebStorm, PyCharm, RubyMine, IntelliJ IDEA, AppCode, ReSharper, CLion, DataGrip), the URLs of the illegally run license servers, source and binary codes of illegal license servers, cracks (software which intentionally and illegally modifies JetBrains tools in order to run it on behalf of a third party without an authorization from JetBrains), and instructions on how to use the cracks and activation codes are publicly accessible on your website github.com. JetBrains s.r.o. is an owner of registered trademarks for all of the products specified above, those are proprietary desktop software products. The materials infringing JetBrains s.r.o. rights mentioned above are to be found in particular on the following links: https://github.com/stephenfri/jbl-server https://github.com/kosmosr/license_server https://github.com/HackersZone/JetBrains-License-Server [repository disabled per previous DMCA takedown] [repository disabled per previous DMCA takedown] [repository disabled per previous DMCA takedown] https://github.com/CrazyNing98/JetbrainsCrack https://github.com/LinuxDigger/JetbrainsCrack https://github.com/GalaxySuze/JetbrainsCrack https://github.com/sandeepvalapi/DevOps/wiki/Intellij_Idea_crack Because: 1) you and github.com users owning repositories / gists mentioned above are not the owners of the trademarks of these products and 2) you and github.com users owning repositories / gists mentioned above do not have any agreement with our company which would entitle you or them to redistribute our products, license keys or license keys generators for our products, we consider the occurrence of cracks, license keys, license keys generators to our products, license servers source and binary code, and URLs of license servers which are not authorized by JetBrains to distribute licenses to our products, source and binary codes of illegal license servers, as well as specific software which aims to circumvent technical measures which protect JetBrains tools from being run on behalf of a third party without an authorization from JetBrains, on the website github.com to be infringement of our proprietary rights. That´s why we demand that you: 1) immediately cease all use of our trademarks by the links specified above, 2) immediately remove all cracks, license keys, source code of license keys generators, license servers source code, and URLs of license servers which are not authorized by JetBrains to distribute licenses to our products, and any other references to our products from the website github.com, by the links specified above, 3) forbear from all further unauthorised use of our trademarks and from all further making accessible of license keys to our products, as well as source code of license keys generating software. I have read and understand GitHub's Guide to Filing a DMCA Notice. I have a good faith belief that use of the copyrighted materials described above on the infringing web pages is not authorized by the copyright owner, or its agent, or the law. I swear, under penalty of perjury, that the information in this notification is accurate and that I am the copyright owner, or am authorized to act on behalf of the owner, of an exclusive right that is allegedly infringed. You can contact JetBrains s.r.o. on any matters via email private. The address is private. Phone: private. Fax: private. The contact person is private (direct email private). This DMCA claim has been prepared and filed by private on behalf of private (private, JetBrains s.r.o.). A list of the links specified above is attached in a CSV format for your convenience. Thank you! Kind regards, private (on behalf of private, private, JetBrains s.r.o.) e-mail: private
{ "pile_set_name": "Github" }
/*********************************************************************** Copyright (c) 2006-2011, Skype Limited. All rights reserved. Redistribution and use in source and binary forms, with or without modification, (subject to the limitations in the disclaimer below) are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Skype Limited, nor the names of specific contributors, may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ #include "SKP_Silk_typedef.h" #include "SKP_Silk_common_pitch_est_defines.h" /********************************************************/ /* Auto Generated File from generate_pitch_est_tables.m */ /********************************************************/ const SKP_int16 SKP_Silk_CB_lags_stage2[PITCH_EST_NB_SUBFR][PITCH_EST_NB_CBKS_STAGE2_EXT] = { {0, 2,-1,-1,-1, 0, 0, 1, 1, 0, 1}, {0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0}, {0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0}, {0,-1, 2, 1, 0, 1, 1, 0, 0,-1,-1} }; const SKP_int16 SKP_Silk_CB_lags_stage3[PITCH_EST_NB_SUBFR][PITCH_EST_NB_CBKS_STAGE3_MAX] = { {-9,-7,-6,-5,-5,-4,-4,-3,-3,-2,-2,-2,-1,-1,-1, 0, 0, 0, 1, 1, 0, 1, 2, 2, 2, 3, 3, 4, 4, 5, 6, 5, 6, 8}, {-3,-2,-2,-2,-1,-1,-1,-1,-1, 0, 0,-1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 2, 1, 2, 2, 2, 2, 3}, { 3, 3, 2, 2, 2, 2, 1, 2, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,-1, 0, 0,-1,-1,-1,-1,-1,-2,-2,-2}, { 9, 8, 6, 5, 6, 5, 4, 4, 3, 3, 2, 2, 2, 1, 0, 1, 1, 0, 0, 0,-1,-1,-1,-2,-2,-2,-3,-3,-4,-4,-5,-5,-6,-7} }; const SKP_int16 SKP_Silk_Lag_range_stage3[ SKP_Silk_PITCH_EST_MAX_COMPLEX + 1 ] [ PITCH_EST_NB_SUBFR ][ 2 ] = { /* Lags to search for low number of stage3 cbks */ { {-2,6}, {-1,5}, {-1,5}, {-2,7} }, /* Lags to search for middle number of stage3 cbks */ { {-4,8}, {-1,6}, {-1,6}, {-4,9} }, /* Lags to search for max number of stage3 cbks */ { {-9,12}, {-3,7}, {-2,7}, {-7,13} } }; const SKP_int16 SKP_Silk_cbk_sizes_stage3[SKP_Silk_PITCH_EST_MAX_COMPLEX + 1] = { PITCH_EST_NB_CBKS_STAGE3_MIN, PITCH_EST_NB_CBKS_STAGE3_MID, PITCH_EST_NB_CBKS_STAGE3_MAX }; const SKP_int16 SKP_Silk_cbk_offsets_stage3[SKP_Silk_PITCH_EST_MAX_COMPLEX + 1] = { ((PITCH_EST_NB_CBKS_STAGE3_MAX - PITCH_EST_NB_CBKS_STAGE3_MIN) >> 1), ((PITCH_EST_NB_CBKS_STAGE3_MAX - PITCH_EST_NB_CBKS_STAGE3_MID) >> 1), 0 };
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-12-19 12:35 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('CMDB', '0036_auto_20181213_1404'), ] operations = [ migrations.AlterUniqueTogether( name='networkcard_assets', unique_together=set([('host', 'macaddress', 'ip')]), ), ]
{ "pile_set_name": "Github" }
# SPDX-License-Identifier: GPL-2.0-only acp_audio_dma-objs := acp-pcm-dma.o snd-soc-acp-da7219mx98357-mach-objs := acp-da7219-max98357a.o snd-soc-acp-rt5645-mach-objs := acp-rt5645.o snd-soc-acp-rt5682-mach-objs := acp3x-rt5682-max9836.o obj-$(CONFIG_SND_SOC_AMD_ACP) += acp_audio_dma.o obj-$(CONFIG_SND_SOC_AMD_CZ_DA7219MX98357_MACH) += snd-soc-acp-da7219mx98357-mach.o obj-$(CONFIG_SND_SOC_AMD_CZ_RT5645_MACH) += snd-soc-acp-rt5645-mach.o obj-$(CONFIG_SND_SOC_AMD_ACP3x) += raven/ obj-$(CONFIG_SND_SOC_AMD_RV_RT5682_MACH) += snd-soc-acp-rt5682-mach.o obj-$(CONFIG_SND_SOC_AMD_RENOIR) += renoir/
{ "pile_set_name": "Github" }
#include "wsconnection.h" #include <stdlib.h> #include <vector> #include <assert.h> #include <arpa/inet.h> #include <string.h> #include <endian.h> #include "connection.h" #include "httprequest.h" #include "httpresponse.h" #include "stringutil.h" #include "sockutil.h" #include "log.h" using namespace std; using namespace std::placeholders; namespace tnet { size_t WsConnection::ms_maxPayloadLen = 10 * 1024 * 1024; static void dummyCallback() {} WsConnection::WsConnection(const ConnectionPtr_t& conn, const WsCallback_t& callback) { m_fd = conn->getSockFd(); m_conn = conn; m_callback = callback; m_payloadLen = 0; m_final = 0; m_opcode = 0; m_mask = 0; m_lastOpcode = 0; m_sendCallback = std::bind(&dummyCallback); } WsConnection::~WsConnection() { LOG_INFO("wsconnection destroyed"); } void WsConnection::onOpen(const void* context) { m_status = FrameStart; m_callback(shared_from_this(), Ws_OpenEvent, context); } void WsConnection::onError() { m_callback(shared_from_this(), Ws_ErrorEvent, 0); } void WsConnection::onConnEvent(const ConnectionPtr_t& conn, ConnEvent event, const void* context) { switch(event) { case Conn_ReadEvent: { const StackBuffer* buffer = (const StackBuffer*)context; onRead(conn, buffer->buffer, buffer->count); } break; case Conn_WriteCompleteEvent: { m_sendCallback(); m_sendCallback = std::bind(&dummyCallback); } break; default: break; } } #define HANDLE(func) \ ret = func(data + readLen, count - readLen); \ readLen += (ret > 0 ? ret : 0); ssize_t WsConnection::onRead(const ConnectionPtr_t& conn, const char* data, size_t count) { size_t readLen = 0; ssize_t ret = 1; while(readLen < count && ret > 0) { switch(m_status) { case FrameStart: HANDLE(onFrameStart); case FramePayloadLen: HANDLE(onFramePayloadLen); break; case FramePayloadLen16: HANDLE(onFramePayloadLen16); break; case FramePayloadLen64: HANDLE(onFramePayloadLen64); break; case FrameMaskingKey: HANDLE(onFrameMaskingKey); break; case FrameData: HANDLE(onFrameData); break; case FrameFinal: ret = handleFrameData(conn); readLen += (ret > 0 ? ret : 0); break; default: return -1; break; } } if(ret > 0 && m_status == FrameFinal) { ret = handleFrameData(conn); } if(ret < 0) { LOG_ERROR("onReadError"); m_status = FrameError; m_callback(shared_from_this(), Ws_ErrorEvent, 0); //an error occur, only to shutdown connection conn->shutDown(); } return ret; } ssize_t WsConnection::onFrameStart(const char* data, size_t count) { m_cache.clear(); char header = data[0]; if(header & 0x70) { //reserved bits now not supported, abort return -1; } m_final = header & 0x80; m_opcode = header & 0x0f; m_status = FramePayloadLen; return 1; } ssize_t WsConnection::handleFramePayloadLen(size_t payloadLen) { m_payloadLen = payloadLen; m_cache.reserve(payloadLen); m_cache.clear(); if(m_payloadLen == 0) { m_status = FrameFinal; } else { m_status = isMaskFrame() ? FrameMaskingKey : FrameData; } return 0; } ssize_t WsConnection::onFramePayloadLen(const char* data, size_t count) { uint8_t payloadLen = (uint8_t)data[0]; m_mask = payloadLen & 0x80; payloadLen &= 0x7f; if(isControlFrame() && payloadLen >= 126) { //control frames must have payload < 126 return -1; } if(payloadLen < 126) { handleFramePayloadLen(payloadLen); } else if(payloadLen == 126) { m_status = FramePayloadLen16; } else if(payloadLen == 127) { m_status = FramePayloadLen64; } else { //payload error return -1; } return 1; } ssize_t WsConnection::tryRead(const char* data, size_t count, size_t tryReadData) { assert(m_cache.size() < tryReadData); size_t pendingSize = m_cache.size(); if(pendingSize + count < tryReadData) { m_cache.append(data, count); return 0; } m_cache.append(data, tryReadData - m_cache.size()); return tryReadData - pendingSize; } ssize_t WsConnection::onFramePayloadLen16(const char* data, size_t count) { ssize_t readLen = tryRead(data, count, 2); if(readLen == 0) { return readLen; } uint16_t payloadLen = *(uint16_t*)m_cache.data(); //memcpy(&payloadLen, m_cache.data(), sizeof(uint16_t)); if(payloadLen > ms_maxPayloadLen) { return -1; } payloadLen = ntohs(payloadLen); handleFramePayloadLen(payloadLen); return readLen; } ssize_t WsConnection::onFramePayloadLen64(const char* data, size_t count) { ssize_t readLen = tryRead(data, count, 8); if(readLen == 0) { return readLen; } uint64_t payloadLen = *(uint64_t*)m_cache.data(); //memcpy(&payloadLen, m_cache.data(), sizeof(uint64_t)); if(payloadLen > ms_maxPayloadLen) { return -1; } //todo ntohl64 payloadLen = be64toh(payloadLen); handleFramePayloadLen(payloadLen); return readLen; } ssize_t WsConnection::onFrameMaskingKey(const char* data, size_t count) { ssize_t readLen = tryRead(data, count, 4); if(readLen == 0) { return 0; } memcpy(m_maskingKey, m_cache.data(), sizeof(m_maskingKey)); m_cache.clear(); m_status = FrameData; return readLen; } ssize_t WsConnection::onFrameData(const char* data, size_t count) { ssize_t readLen = tryRead(data, count, m_payloadLen); if(readLen == 0) { return 0; } if(isMaskFrame()) { for(size_t i = 0; i < m_cache.size(); ++i) { m_cache[i] = m_cache[i] ^ m_maskingKey[i % 4]; } } m_status = FrameFinal; return readLen; } ssize_t WsConnection::handleFrameData(const ConnectionPtr_t& conn) { uint8_t opcode = m_opcode; string data = m_cache; if(isControlFrame()) { if(!isFinalFrame()) { //control frames must not be fragmented return -1; } } else if(m_opcode == 0) { //continuation frame if(m_appData.empty()) { //nothing to continue return -1; } m_appData += m_cache; if(isFinalFrame()) { opcode = m_lastOpcode; data = m_appData; string().swap(m_appData); } } else { //start of new data message if(!m_appData.empty()) { //can't start new message until the old one is finished return -1; } if(isFinalFrame()) { opcode = m_opcode; data = m_cache; } else { m_lastOpcode = m_opcode; m_appData = m_cache; } } string().swap(m_cache); if(isFinalFrame()) { if(handleMessage(conn, opcode, data) < 0) { return -1; } } m_status = FrameStart; return 0; } ssize_t WsConnection::handleMessage(const ConnectionPtr_t& conn, uint8_t opcode, const string& data) { switch(opcode) { case 0x1: //utf-8 data m_callback(shared_from_this(), Ws_MessageEvent, (void*)&data); break; case 0x2: //binary data m_callback(shared_from_this(), Ws_MessageEvent, (void*)&data); break; case 0x8: //clsoe m_callback(shared_from_this(), Ws_CloseEvent, 0); conn->shutDown(500); break; case 0x9: //ping sendFrame(true, 0xA, data); break; case 0xA: //pong m_callback(shared_from_this(), Ws_PongEvent, (void*)&data); break; default: //error LOG_ERROR("invalid opcode %d", opcode); return -1; } return 0; } void WsConnection::ping(const string& message) { sendFrame(true, 0x9, message); } void WsConnection::send(const string& message) { send(message, !isTextFrame()); } void WsConnection::send(const string& message, bool binary) { char opcode = binary ? 0x2 : 0x1; //for utf-8, we assume message is already utf-8 sendFrame(true, opcode, message); } void WsConnection::send(const string& message, const Callback_t& callback) { m_sendCallback = callback; send(message); } void WsConnection::send(const string& message, bool binary, const Callback_t& callback) { m_sendCallback = callback; send(message, binary); } void WsConnection::close() { sendFrame(true, (char)0x8); } void WsConnection::sendFrame(bool finalFrame, char opcode, const string& message) { ConnectionPtr_t conn = m_conn.lock(); if(!conn) { return; } string buf; opcode |= (finalFrame ? 0x80 : 0x00); buf.append((char*)&opcode, sizeof(opcode)); //char mask = isMaskFrame() ? 0x80 : 0x00; //chrome not support mask char mask = 0x00; size_t payloadLen = message.size(); if(payloadLen < 126) { char payload = mask | (char)payloadLen; buf.append((char*)&payload, sizeof(payload)); } else if(payloadLen <= 0xFFFF) { char payload = mask | 126; buf.append((char*)&payload, sizeof(payload)); uint16_t len = htons((uint16_t)payloadLen); buf.append((char*)&len, sizeof(uint16_t)); } else { char payload = mask | 127; buf.append((char*)&payload, sizeof(payload)); uint64_t len = htobe64(payloadLen); buf.append((char*)&len, sizeof(uint64_t)); } if(mask) { int randomKey = rand(); char maskingKey[4]; memcpy(maskingKey, &randomKey, sizeof(maskingKey)); buf.append(maskingKey, 4); size_t pos = buf.size(); buf.append(message); for(size_t i = 0; i < buf.size() - pos; ++i) { buf[i + pos] = buf[i + pos] ^ maskingKey[i % 4]; } } else { buf.append(message); } conn->send(buf); } void WsConnection::shutDown() { ConnectionPtr_t conn = m_conn.lock(); if(conn) { conn->shutDown(); } } }
{ "pile_set_name": "Github" }
# (C) Copyright David Abrahams 2001. # (C) Copyright MetaCommunications, Inc. 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) # The following #// line will be used by the regression test table generation # program as the column heading for HTML tables. Must not include a version # number. #//<a href="http://www.comeaucomputing.com/">Comeau<br>C++</a> import common ; import como ; import feature ; import generators ; import toolset : flags ; feature.extend-subfeature toolset como : platform : win ; # Initializes the Comeau toolset for windows. The command is the command which # invokes the compiler. You should either set environment variable # COMO_XXX_INCLUDE where XXX is the used backend (as described in the # documentation), or pass that as part of command, e.g: # # using como-win : 4.3 : "set COMO_BCC_INCLUDE=C:/include &&" como.exe ; # rule init ( version ? : command * : options * ) { local condition = [ common.check-init-parameters como-win : version $(version) ] ; command = [ common.get-invocation-command como-win : como.exe : $(command) ] ; common.handle-options como-win : $(condition) : $(command) : $(options) ; } generators.register-c-compiler como-win.compile.c++ : CPP : OBJ : <toolset>como <toolset-como:platform>win ; generators.register-c-compiler como-win.compile.c : C : OBJ : <toolset>como <toolset-como:platform>win ; generators.register-linker como-win.link : OBJ SEARCHED_LIB STATIC_LIB IMPORT_LIB : EXE : <toolset>como <toolset-como:platform>win ; # Note that status of shared libraries support is not clear, so we do not define # the link.dll generator. generators.register-archiver como-win.archive : OBJ : STATIC_LIB : <toolset>como <toolset-como:platform>win ; flags como-win C++FLAGS <exception-handling>off : --no_exceptions ; flags como-win C++FLAGS <exception-handling>on : --exceptions ; flags como-win CFLAGS <inlining>off : --no_inlining ; flags como-win CFLAGS <inlining>on <inlining>full : --inlining ; # The following seems to be VC-specific options. At least, when I uncomment # then, Comeau with bcc as backend reports that bcc32 invocation failed. # #flags como-win CFLAGS <debug-symbols>on : /Zi ; #flags como-win CFLAGS <optimization>off : /Od ; flags como-win CFLAGS <cflags> ; flags como-win CFLAGS : -D_WIN32 ; # Make sure that we get the Boost Win32 platform config header. flags como-win CFLAGS <threading>multi : -D_MT ; # Make sure that our config knows that threading is on. flags como-win C++FLAGS <cxxflags> ; flags como-win DEFINES <define> ; flags como-win UNDEFS <undef> ; flags como-win HDRS <include> ; flags como-win SYSHDRS <sysinclude> ; flags como-win LINKFLAGS <linkflags> ; flags como-win ARFLAGS <arflags> ; flags como-win NO_WARN <no-warn> ; #flags como-win STDHDRS : $(COMO_INCLUDE_PATH) ; #flags como-win STDLIB_PATH : $(COMO_STDLIB_PATH)$(SLASH) ; flags como-win LIBPATH <library-path> ; flags como-win LIBRARIES <library-file> ; flags como-win FINDLIBS <find-shared-library> ; flags como-win FINDLIBS <find-static-library> ; nl = " " ; # For como, we repeat all libraries so that dependencies are always resolved. # actions link bind LIBRARIES { $(CONFIG_COMMAND) --no_version --no_prelink_verbose $(LINKFLAGS) -o "$(<[1]:S=)" @"@($(<[1]:W).rsp:E=$(nl)"$(>)")" "$(LIBRARIES)" "$(FINDLIBS:S=.lib)" } actions compile.c { $(CONFIG_COMMAND) -c --c99 -e5 --no_version --display_error_number --diag_suppress=9,21,161,748,940,962 -U$(UNDEFS) -D$(DEFINES) $(WARN) $(CFLAGS) -I"$(HDRS)" -I"$(STDHDRS)" -I"$(SYSHDRS)" -o "$(<:D=)" "$(>)" } actions compile.c++ { $(CONFIG_COMMAND) -c -e5 --no_version --no_prelink_verbose --display_error_number --long_long --diag_suppress=9,21,161,748,940,962 --diag_error=461 -D__STL_LONG_LONG -U$(UNDEFS) -D$(DEFINES) $(WARN) $(CFLAGS) $(C++FLAGS) -I"$(HDRS)" -I"$(STDHDRS)" -I"$(SYSHDRS)" -o "$(<)" "$(>)" } actions archive { $(CONFIG_COMMAND) --no_version --no_prelink_verbose --prelink_object @"@($(<[1]:W).rsp:E=$(nl)"$(>)")" lib $(ARFLAGS) /nologo /out:"$(<:S=.lib)" @"@($(<[1]:W).rsp:E=$(nl)"$(>)")" }
{ "pile_set_name": "Github" }
// Source : https://leetcode.com/problems/diagonal-traverse/ // Author : Han Zichi // Date : 2017-02-07 /** * @param {number[]} nums * @return {number[]} */ var nextGreaterElements = function(nums) { let len = nums.length; nums = nums.concat(nums.slice(0, len - 1)); let ans = []; let stack = []; // 单调队列? nums.forEach((item, index) => { if (index === 0) { stack.push({ num: item, index: index }); } else { while (true) { if (!stack.length) break; if (item > stack[stack.length - 1].num) { let lastItem = stack.pop(); ans[lastItem.index] = item; } else { break; } } stack.push({ num: item, index: index }); } }); ans = ans.slice(0, len); for (let i = 0; i < len; i++) if (ans[i] === undefined) ans[i] = -1; return ans; };
{ "pile_set_name": "Github" }
typedef unsigned short uint16; typedef unsigned uint32; typedef unsigned char uint8; typedef struct { uint16 len; uint16 maxlen; uint32 offset; }tSmbStrHeader; typedef struct { char ident[8]; uint32 msgType; uint32 flags; tSmbStrHeader user; tSmbStrHeader domain; uint8 buffer[1024]; uint32 bufIndex; }tSmbNtlmAuthRequest; typedef struct { char ident[8]; uint32 msgType; tSmbStrHeader uDomain; uint32 flags; uint8 challengeData[8]; uint8 reserved[8]; tSmbStrHeader emptyString; uint8 buffer[1024]; uint32 bufIndex; }tSmbNtlmAuthChallenge; typedef struct { char ident[8]; uint32 msgType; tSmbStrHeader lmResponse; tSmbStrHeader ntResponse; tSmbStrHeader uDomain; tSmbStrHeader uUser; tSmbStrHeader uWks; tSmbStrHeader sessionKey; uint32 flags; uint8 buffer[1024]; uint32 bufIndex; }tSmbNtlmAuthResponse; #define SmbLength(ptr) (((ptr)->buffer - (uint8*)(ptr)) + (ptr)->bufIndex)
{ "pile_set_name": "Github" }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationWrapperBuilderFactory.java b/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationWrapperBuilderFactory.java index cf33525790377668a857f209c651a6759a6e30a5..f83e924c6d7caef6f87f2b01d7998ca46bbabe81 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationWrapperBuilderFactory.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationWrapperBuilderFactory.java @@ -71,7 +71,7 @@ public class NotificationWrapperBuilderFactory { } NotificationManagerProxyImpl notificationManagerProxy = - new NotificationManagerProxyImpl(context); + new BraveNotificationManagerProxyImpl(context); ChannelsInitializer channelsInitializer = new ChannelsInitializer(notificationManagerProxy, ChromeChannelDefinitions.getInstance(), context.getResources());
{ "pile_set_name": "Github" }
{% extends "two_factor/_base_focus.html" %} {% load i18n %} {% block content %} <h1>{% block title %}{% trans "Permission Denied" %}{% endblock %}</h1> <p>{% blocktrans %}The page you requested, enforces users to verify using two-factor authentication for security reasons. You need to enable these security features in order to access this page.{% endblocktrans %}</p> <p>{% blocktrans %}Two-factor authentication is not enabled for your account. Enable two-factor authentication for enhanced account security.{% endblocktrans %}</p> <p> <a href="javascript:history.go(-1)" class="pull-right btn btn-link">{% trans "Go back" %}</a> <a href="{% url 'two_factor:setup' %}" class="btn btn-primary"> {% trans "Enable Two-Factor Authentication" %}</a> </p> {% endblock %}
{ "pile_set_name": "Github" }
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef PluginViewBase_h #define PluginViewBase_h #include "AudioHardwareListener.h" #include "BridgeJSC.h" #include "PlatformLayer.h" #include "ScrollTypes.h" #include "Widget.h" #include <wtf/text/WTFString.h> namespace JSC { class ExecState; class JSGlobalObject; class JSObject; } namespace WebCore { class Scrollbar; // PluginViewBase is a widget that all plug-in views inherit from, both in Webkit and WebKit2. // It's intended as a stopgap measure until we can merge all plug-in views into a single plug-in view. class PluginViewBase : public Widget { public: virtual PlatformLayer* platformLayer() const { return 0; } #if PLATFORM(IOS) virtual bool willProvidePluginLayer() const { return false; } virtual void attachPluginLayer() { } virtual void detachPluginLayer() { } #endif virtual JSC::JSObject* scriptObject(JSC::JSGlobalObject*) { return 0; } virtual void storageBlockingStateChanged() { } virtual void privateBrowsingStateChanged(bool) { } virtual bool getFormValue(String&) { return false; } virtual bool scroll(ScrollDirection, ScrollGranularity) { return false; } // A plug-in can ask WebKit to handle scrollbars for it. virtual Scrollbar* horizontalScrollbar() { return 0; } virtual Scrollbar* verticalScrollbar() { return 0; } // FIXME: This is a hack that works around the fact that the WebKit2 PluginView isn't a ScrollableArea. virtual bool wantsWheelEvents() { return false; } virtual bool supportsKeyboardFocus() const { return false; } virtual bool canProcessDrag() const { return false; } virtual bool shouldAlwaysAutoStart() const { return false; } virtual void beginSnapshottingRunningPlugin() { } virtual bool shouldAllowNavigationFromDrags() const { return false; } virtual bool isPluginViewBase() const { return true; } virtual bool shouldNotAddLayer() const { return false; } virtual AudioHardwareActivityType audioHardwareActivity() const { return AudioHardwareActivityType::Unknown; } virtual void setJavaScriptPaused(bool) { } virtual RefPtr<JSC::Bindings::Instance> bindingInstance() { return nullptr; } virtual void willDetatchRenderer() { } protected: explicit PluginViewBase(PlatformWidget widget = 0) : Widget(widget) { } }; } // namespace WebCore SPECIALIZE_TYPE_TRAITS_WIDGET(PluginViewBase, isPluginViewBase()) #endif // PluginViewBase_h
{ "pile_set_name": "Github" }
LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := imageutils$(LIB_SUFFIX) LOCAL_SRC_FILES := blur-jni.cpp \ similar-jni.cpp \ blur.cpp \ similar.cpp ifeq ($(TARGET_ARCH_ABI),armeabi-v7a) LOCAL_CFLAGS += -DHAVE_ARMEABI_V7A=1 -mfloat-abi=softfp -mfpu=neon LOCAL_C_INCLUDES += $(NDK_ROOT)/sources/android/cpufeatures LOCAL_STATIC_LIBRARIES += cpufeatures endif LOCAL_C_INCLUDES += $(LOCAL_PATH)/../common LOCAL_STATIC_LIBRARIES += common include $(BUILD_SHARED_LIBRARY)
{ "pile_set_name": "Github" }
package fr.lteconsulting.pomexplorer.commands; import java.io.File; import java.util.Set; import fr.lteconsulting.pomexplorer.ApplicationSession; import fr.lteconsulting.pomexplorer.Client; import fr.lteconsulting.pomexplorer.DefaultPomFileLoader; import fr.lteconsulting.pomexplorer.Log; import fr.lteconsulting.pomexplorer.PomAnalysis; import fr.lteconsulting.pomexplorer.Project; import fr.lteconsulting.pomexplorer.Tools; import fr.lteconsulting.pomexplorer.graph.PomGraph.PomGraphReadTransaction; import fr.lteconsulting.pomexplorer.model.Gav; import fr.lteconsulting.pomexplorer.tools.FilteredGAVs; public class GavCommand { @Help( "list the session's GAVs" ) public void main( ApplicationSession session, Log log ) { list( session, log ); } @Help( "list the session's GAVs" ) public void list( ApplicationSession session, Log log ) { list( session, null, log ); } @Help( "list the session's GAVs, with filtering" ) public void list( ApplicationSession session, FilteredGAVs gavFilter, Log log ) { StringBuilder sb = new StringBuilder(); sb.append( "<br/>GAV list filtered with '" + (gavFilter != null ? gavFilter.getFilterDescription() : "no filter") + "' :<br/>" ); if( gavFilter != null ) { gavFilter.getGavs( session.session() ).stream().sorted( ( g1, g2 ) -> g1.toString().compareTo( g2.toString() ) ).forEach( gav -> sb.append( gav + "<br/>" ) ); } else { PomGraphReadTransaction tx = session.graph().read(); tx.gavs().stream().sorted( ( g1, g2 ) -> g1.toString().compareTo( g2.toString() ) ).forEach( gav -> sb.append( gav + "<br/>" ) ); } log.html( sb.toString() ); } @Help( "analyze all the gav's dependencies and add them in the pom graph." ) public void add( ApplicationSession session, Log log, Client client, Gav gav ) { log.html( "analyzing " + gav + "...<br/>" ); DefaultPomFileLoader loader = new DefaultPomFileLoader( session.session(), true ); File pomFile = loader.loadPomFileForGav( gav, null, log ); if( pomFile == null ) { log.html( Tools.errorMessage( "cannot fetch project " + gav ) ); return; } PomAnalysis analysis = new PomAnalysis( session.session(), loader, null, false, log ); analysis.addFile( pomFile ); analysis.loadProjects(); analysis.completeLoadedProjects(); analysis.addCompletedProjectsToSession(); Set<Project> addedToGraph = analysis.addCompletedProjectsToGraph(); log.html( "project " + gav + " fetched successfully, " + addedToGraph.size() + " project added to graph.<br/>" ); } @Help( "analyze gavs which have no associated project" ) public void resolve( ApplicationSession session, Log log, Client client ) { DefaultPomFileLoader loader = new DefaultPomFileLoader( session.session(), true ); PomAnalysis analysis = new PomAnalysis( session.session(), loader, null, false, log ); session.graph().read().gavs().stream().filter( gav -> session.projects().forGav( gav ) == null ).forEach( gav -> { log.html( "fetching pom file for " + gav + "...<br/>" ); File pomFile = loader.loadPomFileForGav( gav, null, log ); if( pomFile == null ) { log.html( Tools.errorMessage( "cannot fetch project " + gav ) ); return; } analysis.addFile( pomFile ); } ); analysis.loadProjects(); analysis.completeLoadedProjects(); analysis.addCompletedProjectsToSession(); Set<Project> addedToGraph = analysis.addCompletedProjectsToGraph(); log.html( "finished, " + addedToGraph.size() + " project added to graph.<br/>" ); } }
{ "pile_set_name": "Github" }
#pragma once #include <elle/reactor/fsm/Transition.hh> #include <elle/reactor/fsm/fwd.hh> namespace elle { namespace reactor { namespace fsm { /// A specialized Transition that occurs at the end of the source State. class EndTransition : public Transition { public: using Condition = std::function<bool ()>; public: /// Called when the origin State is over. /// /// \param trigger Who trigger the transition. If null, exn is null /// and our condition is true or null, set /// trigger = this. /// \param exn An exception pointer. virtual void done(Transition*& trigger, std::exception_ptr& exn) override; protected: /// Create a EndTransition. /// /// \param start The source State of the Transition. /// \param end The destination State of the Transition. EndTransition(State& start, State& end); /// Create a EndTransition. /// /// \param start The source State of the Transition. /// \param end The destination State of the Transition. /// \param condition The Condition to trigger the Transition. EndTransition(State& start, State& end, Condition const& condition); friend class Machine; ELLE_ATTRIBUTE(boost::optional<Condition>, condition); /*----------. | Printable | `----------*/ public: void print(std::ostream& stream) const override; }; } } }
{ "pile_set_name": "Github" }
// go run mksyscall.go -l32 -openbsd -arm -tags openbsd,arm syscall_bsd.go syscall_openbsd.go syscall_openbsd_arm.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build openbsd,arm package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(from int, to int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(from), uintptr(to), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall6(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) pgrp = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrtable() (rtable int, err error) { r0, _, e1 := RawSyscall(SYS_GETRTABLE, 0, 0, 0) rtable = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) tainted = bool(r0 != 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifoat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFOAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0) newoffset = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(name) if err != nil { return } _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrtable(rtable int) (err error) { _, _, e1 := RawSyscall(SYS_SETRTABLE, uintptr(rtable), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return }
{ "pile_set_name": "Github" }
exports.f = Object.getOwnPropertySymbols;
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.openjfx</groupId> <artifactId>javafx</artifactId> <version>@VERSION@</version> <packaging>pom</packaging> <name>openjfx</name> <description>OpenJFX JavaFX</description> <properties> <javafx.version>@VERSION@</javafx.version> </properties> <dependencyManagement> </dependencyManagement> <profiles> <profile> <id>linux</id> <activation> <os> <name>linux</name> </os> </activation> <properties> <javafx.platform>linux</javafx.platform> </properties> </profile> <profile> <id>macosx</id> <activation> <os> <name>mac os x</name> </os> </activation> <properties> <javafx.platform>mac</javafx.platform> </properties> </profile> <profile> <id>windows</id> <activation> <os> <family>windows</family> </os> </activation> <properties> <javafx.platform>win</javafx.platform> </properties> </profile> <profile> <id>javafx.platform.custom</id> <activation> <property> <name>javafx.platform</name> </property> </activation> <properties> <javafx.platform>${javafx.platform}</javafx.platform> </properties> </profile> </profiles> </project>
{ "pile_set_name": "Github" }
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var prefix = 'fas'; var iconName = 'suitcase'; var width = 512; var height = 512; var ligatures = []; var unicode = 'f0f2'; var svgPathData = 'M128 480h256V80c0-26.5-21.5-48-48-48H176c-26.5 0-48 21.5-48 48v400zm64-384h128v32H192V96zm320 80v256c0 26.5-21.5 48-48 48h-48V128h48c26.5 0 48 21.5 48 48zM96 480H48c-26.5 0-48-21.5-48-48V176c0-26.5 21.5-48 48-48h48v352z'; exports.definition = { prefix: prefix, iconName: iconName, icon: [ width, height, ligatures, unicode, svgPathData ]}; exports.faSuitcase = exports.definition; exports.prefix = prefix; exports.iconName = iconName; exports.width = width; exports.height = height; exports.ligatures = ligatures; exports.unicode = unicode; exports.svgPathData = svgPathData;
{ "pile_set_name": "Github" }
--- title: Cells.Application Property (Word) keywords: vbawd10.chm155845608 f1_keywords: - vbawd10.chm155845608 ms.prod: word api_name: - Word.Cells.Application ms.assetid: be60412c-86a7-bfd5-25d6-e35d9c7cca96 ms.date: 06/08/2017 --- # Cells.Application Property (Word) Returns an **[Application](application-object-word.md)** object that represents the Microsoft Word application. ## Syntax _expression_ . **Application** _expression_ A variable that represents a **[Cells](cells-object-word.md)** object. ## See also #### Concepts [Cells Collection Object](cells-object-word.md)
{ "pile_set_name": "Github" }
<?php /** * JBZoo Application * * This file is part of the JBZoo CCK package. * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @package Application * @license GPL-2.0 * @copyright Copyright (C) JBZoo.com, All rights reserved. * @link https://github.com/JBZoo/JBZoo * @author Denis Smetannikov <[email protected]> */ // no direct access defined('_JEXEC') or die('Restricted access'); $this->app->jbdebug->mark('layout::item_columns::start'); if ($vars['count']) { $i = 0; $bootstrap = $this->app->jbbootstrap; $count = $vars['count']; $rowItems = array_chunk($vars['objects'], $vars['cols_num']); $rowClass = $bootstrap->getRowClass(); $colClass = $bootstrap->columnClass($vars['cols_num']); echo '<div class="items items-col-' . $vars['cols_num'] . '">'; foreach ($rowItems as $row) { echo '<div class="' . $rowClass . ' item-row-' . $i . '">'; $j = 0; $i++; foreach ($row as $item) { $classes = array( 'item-column', $colClass ); $first = ($j == 0) ? $classes[] = 'first' : ''; $last = ($j == $count - 1) ? $classes[] = 'last' : ''; $j++; $isLast = $j % $vars['cols_num'] == 0 && $vars['cols_order'] == 0; if ($isLast) { $classes[] = 'last'; } echo '<div class="' . implode(' ', $classes) . '">' . ' <div class="item-box well">' . $item . '</div>' . '</div>'; } echo '</div>'; } echo '</div>'; } $this->app->jbdebug->mark('layout::item_columns::finish');
{ "pile_set_name": "Github" }
### 中国人权律师祝圣武:向大法弟子学习(视频) ------------------------ #### [首页](https://github.com/gfw-breaker/banned-news/blob/master/README.md) &nbsp;&nbsp;|&nbsp;&nbsp; [手把手翻墙教程](https://github.com/gfw-breaker/guides/wiki) &nbsp;&nbsp;|&nbsp;&nbsp; [禁闻聚合安卓版](https://github.com/gfw-breaker/bn-android) &nbsp;&nbsp;|&nbsp;&nbsp; [网门安卓版](https://github.com/oGate2/oGate) &nbsp;&nbsp;|&nbsp;&nbsp; [神州正道安卓版](https://github.com/SzzdOgate/update) <div class="zhidingtu"> <div class="ar-wrap-3x2"> <img alt="中国人权律师祝圣武在温哥华法轮功学员反迫害20周年集会上。(图片来源:唐风/大纪元)" class="ar-wrap-inside-fill" src="http://img.soundofhope.org/2019/07/dsc-0488-600x400-600x400.jpg"/> </div> <div class="caption"> 中国人权律师祝圣武在温哥华法轮功学员反迫害20周年集会上。(图片来源:唐风/大纪元) </div> </div> <hr/> <div class="content"> <p> <span class="content-info-date"> 【希望之声2019年7月21日】 </span> <span class="content-info-type"> (作者:祝圣武) </span> <em> 编者按:7月20日下午1时许,大温地区的部分法轮功学员在温哥华市中心艺术馆前举行反迫害二十周年集会,中国大陆人权律师祝圣武参加集会并演讲。他发言的题目是“向法轮大法弟子学习”。以下是根据祝圣武律师的演讲整理的文稿(附视频): </em> </p> <div class="widget ad-300x250 ad-ecf"> <!-- ZW30 Post Embed 300x250 1 --> <ins class="adsbygoogle" data-ad-client="ca-pub-1519518652909441" data-ad-slot="9768754376" style="display:inline-block;width:300px;height:250px"> </ins> </div> <p> 非常荣幸参加温哥华法轮大法反迫害二十周年集会!我是来自大陆的人权律师祝圣武。 </p> <p> 2017年9月,我因为反党反社会主义被吊销律师证,并被迫关闭我经营管理的山东信常律师事务所。被吊销律师证之前,我是中国互联网著作权纠纷领域非常有名的律师。2018年4月,我和妻子逃离中国大陆来到温哥华。 </p> <p> 今天,站在这片自由、民主的土地,面对各位大法弟子,我非常激动。我要大声的呼吁:向法轮大法弟子学习! </p> <p> 2017年5月,我开始为大法弟子辩护。为大法服务的时间非常短,但大法弟子对我的思想影响非常深远。我在齐齐哈尔市、玉溪市、文山壮族苗族自治州、曲靖市、昆明市为被绑架的大法弟子辩护。 </p> <p> 这些蒙难的大法弟子没有一个因为失去自由而恐惧,没有一个因为受苦受难而唉声叹气,没有一个因为受到共产党的惨无人道的酷刑、监禁而放弃信仰。他们始终高昂着头、高声歌颂着法轮大法。 </p> <p> 大法弟子用生命捍卫信仰的壮举,彻底震撼了我,彻底改变了我对于“信仰”这个词的理解。对中国人而言,守护信仰远远不只是日常的供奉,更要求信仰者勇于承受中国(中共)政府施加的极端残酷的迫害。 </p> <p> 玉溪市大法弟子李海艳,59岁,因为在居民小区宣传大法而被绑架。我见到她的时候,她刚刚因为拒绝放弃信仰而被连续戴脚镣手镣一个月。她已经绝食抗议了很多天,身体非常虚弱,手上、脚上、脸上都浮肿了。她带着脚镣和手镣,扶着墙猫着腰才得以走出来。会见的时候,共产党的打手就站在李海艳旁边监视着。我看着她刚强、高贵、备受折磨的身躯,我哭了。我从心底里敬佩她。 </p> <p> 文山壮族苗族自治州大法弟子王文瑛,62岁,家境富裕,丈夫是处长级官员。王文瑛被绑架后,中国(共)政府试图以他丈夫的工作来胁迫她,她断然拒绝。他的丈夫被株连而提前退休。她总是高高兴兴的和我讲她的故事。我们还偷偷的把看守所内的“三退”(编辑加注:声明退出共产党、共青团和少先队)人员名单带出来交给大法联络人。开庭的时候,她没有丝毫的恐惧,高声为大法辩护。 </p> <div> </div> <p> 文山壮族苗族自治州大法弟子李群,65岁,和王文瑛一同被绑架和审判。这是李群第三次被绑架和审判,之前她因为信仰法轮大法而于2004年被判监禁4年,2009年被判监禁5年。即使曾经被非法拘禁过9年,李群依然没有害怕残暴的中国(共)政府,坚持信仰。在法庭上,李群微笑着、平静的面对非法审判,有理有据的辩护。李群因此而被中共法庭再次判处非法拘禁4年。李群的故事就是一部英雄史诗,我以认识她这样的勇士而自豪。 </p> <p> 大法弟子们,我站在这里,向你们传达中国大法弟子舍身护法、英勇抗争的故事。 </p> <p> 大法弟子们,我站在这里,讲述这些英雄故事,因为我想告诉全世界,中国人都应该向法轮大法弟子学习。 </p> <p> 2017年8月28日,正是王文瑛、李群被非法审判的日子,我收到山东省律师协会的电话,要求我立即前往谈话。开庭后,我没有立即回山东,而是去玉溪市、曲靖市会见被绑架的大法弟子。 </p> <p> 9月6日,山东省司法厅指控我反党反社会主义并做出了吊销我律师证的拟处罚决定(并非正式的处罚决定)。我收到这个决定的时候,正在江苏省南通市为访民周庆有代理开庭。这是我最后一次代理出庭。回到济南后,山东省司法厅一次又一次的找我谈话,并一再保证,只要我在媒体上公开认错道歉就可以不被吊销律师证,同时威胁把我交给公安局办理。我拒绝了。我说我办理了法轮功案件之后,看到那么多法轮功弟子为了信仰可以放弃事业、家庭和生命,我不能为了一个律师证而唾弃我对民主、法治的信仰。9月8号,山东省律师协会发布了震惊中国的对我祝圣武进行谴责的《声明》,指“祝圣武……反对党的领导,反对社会主义制度……”9月22日,山东省律师协会吊销我的律师证。同日,《环球时报(海外版)》发表文章对我进行谴责,并威胁追究我的刑事责任。 </p> <p> 谢天谢地,我没有蹲监狱!谢天谢地,我平安的逃离了共产党中国! </p> <p> 今天,我站在这里,站在这么多可敬可爱的大法弟子面前,我感到非常的幸福!我要大声地谢谢你们!谢谢你们让我明白怎样才算是一个有骨气的中国人!谢谢你们为所有追求自由、民主、法治并坚持抗争的中国人点亮一盏又一盏明灯!谢谢你们为那些害怕黑暗、内心懦弱的中国人树立一座又一座道德丰碑! </p> <p> 法轮功弟子在中国所遭受的群体灭绝迫害,所遭受的包括绑架、非法拘禁、亲人朋友被株连、酷刑、故意伤害、故意杀害、虐杀、“活摘器官”等等的迫害,是人类历史上最残酷的政治迫害之一。法轮大法弟子是最可爱的中国人!共产党及其党徒终将为他们的恐怖主义罪行受到惩罚。 </p> <p> 承受了20年持续不断的残酷迫害,法轮大法不但没有被灭绝,反而深深地扎根于中国社会,传遍整个地球。这是人类文明史上的又一个奇迹。 </p> <p> 大法弟子们,历史终将彪炳你们的丰功伟业! </p> <div class="sohzw-video-wrapper"> <div class="ar-wrap-16x9"> <div class="ar-wrap-inside-fill"> </div> </div> </div> <p> (仅代表作者个人立场和观点) </p> <div class="content-info-btm"> <p class="content-info-zerenbianji"> <span class="content-info-title"> 责任编辑: </span> <span class="content-info-content"> 元明清 </span> </p> </div> </div> <hr/> 手机上长按并复制下列链接或二维码分享本文章:<br/> https://github.com/gfw-breaker/banned-news/blob/master/pages/soh_grpl/n3048038.md <br/> <a href='https://github.com/gfw-breaker/banned-news/blob/master/pages/soh_grpl/n3048038.md'><img src='https://github.com/gfw-breaker/banned-news/blob/master/pages/soh_grpl/n3048038.md.png'/></a> <br/> 原文地址(需翻墙访问):http://www.soundofhope.org/gb/2019/07/21/n3048038.html ------------------------ #### [首页](https://github.com/gfw-breaker/banned-news/blob/master/README.md) &nbsp;|&nbsp; [一键翻墙软件](https://github.com/gfw-breaker/nogfw/blob/master/README.md) &nbsp;| [《九评共产党》](https://github.com/gfw-breaker/9ping.md/blob/master/README.md#九评之一评共产党是什么) | [《解体党文化》](https://github.com/gfw-breaker/jtdwh.md/blob/master/README.md) | [《共产主义的终极目的》](https://github.com/gfw-breaker/gczydzjmd.md/blob/master/README.md) <img src='http://gfw-breaker.win/banned-news/pages/soh_grpl/n3048038.md' width='0px' height='0px'/>
{ "pile_set_name": "Github" }
/* ** ClanLib SDK ** Copyright (c) 1997-2016 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Magnus Norddahl */ #pragma once #include "../View/view.h" namespace clan { class Image; class ProgressView : public View { public: float progress() const; void set_progress(float value, bool animated = false); Image track_image() const; void set_track_image(const Image &value); Image progress_image() const; void set_progress_image(const Image &value); Colorf progress_color() const; void set_progress_color(const Colorf &value); }; }
{ "pile_set_name": "Github" }
#!/usr/bin/env python3 #pylint: disable=missing-docstring #* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/licenses/lgpl-2.1.html import chigger n = 3 line0 = chigger.graphs.Line(marker='circle', color=[0,0,1]) line1 = chigger.graphs.Line(marker='plus', color=[0,1,0], corner='right-top') graph = chigger.graphs.Graph(line0, line1) graph.setOptions('xaxis', lim=[0,n]) graph.setOptions('yaxis', lim=[0,n]) graph.setOptions('x2axis', lim=[0,n]) graph.setOptions('y2axis', lim=[0,n]) graph.setOptions('legend', visible=False) window = chigger.RenderWindow(graph, size=[300,300], test=True) window.write('secondary_initial.png') for i in range(n+1): line0.setOptions(x=[i], y=[i], append=True) line1.setOptions(x=[i], y=[n-i], append=True) window.write('secondary_' + str(i) + '.png') window.start()
{ "pile_set_name": "Github" }
# frozen_string_literal: true module Krane class DeployTaskConfigValidator < TaskConfigValidator def initialize(protected_namespaces, prune, *arguments) super(*arguments) @protected_namespaces = protected_namespaces @allow_protected_ns = !protected_namespaces.empty? @prune = prune @validations += %i(validate_protected_namespaces) end private def validate_protected_namespaces if @protected_namespaces.include?(namespace) if @allow_protected_ns && @prune @errors << "Refusing to deploy to protected namespace '#{namespace}' with pruning enabled" elsif @allow_protected_ns logger.warn("You're deploying to protected namespace #{namespace}, which cannot be pruned.") logger.warn("Existing resources can only be removed manually with kubectl. " \ "Removing templates from the set deployed will have no effect.") logger.warn("***Please do not deploy to #{namespace} unless you really know what you are doing.***") else @errors << "Refusing to deploy to protected namespace '#{namespace}'" end end end end end
{ "pile_set_name": "Github" }
/* * Initialization and support routines for self-booting compressed image. * * $Copyright Open Broadcom Corporation$ * * $Id: circularbuf.h 452258 2014-01-29 19:17:57Z $ */ #ifndef __CIRCULARBUF_H_INCLUDED__ #define __CIRCULARBUF_H_INCLUDED__ #include <osl.h> #include <typedefs.h> #include <bcmendian.h> /* Enumerations of return values provided by MsgBuf implementation */ typedef enum { CIRCULARBUF_FAILURE = -1, CIRCULARBUF_SUCCESS } circularbuf_ret_t; /* Core circularbuf circular buffer structure */ typedef struct circularbuf_s { uint16 depth; /* Depth of circular buffer */ uint16 r_ptr; /* Read Ptr */ uint16 w_ptr; /* Write Ptr */ uint16 e_ptr; /* End Ptr */ uint16 wp_ptr; /* wp_ptr/pending - scheduled for DMA. But, not yet complete. */ uint16 rp_ptr; /* rp_ptr/pending - scheduled for DMA. But, not yet complete. */ uint8 *buf_addr; void *mb_ctx; void (*mb_ring_bell)(void *ctx); } circularbuf_t; #define CBUF_ERROR_VAL 0x00000001 /* Error level tracing */ #define CBUF_TRACE_VAL 0x00000002 /* Function level tracing */ #define CBUF_INFORM_VAL 0x00000004 /* debug level tracing */ extern int cbuf_msg_level; #define CBUF_ERROR(args) do {if (cbuf_msg_level & CBUF_ERROR_VAL) printf args;} while (0) #define CBUF_TRACE(args) do {if (cbuf_msg_level & CBUF_TRACE_VAL) printf args;} while (0) #define CBUF_INFO(args) do {if (cbuf_msg_level & CBUF_INFORM_VAL) printf args;} while (0) #define CIRCULARBUF_START(x) ((x)->buf_addr) #define CIRCULARBUF_WRITE_PTR(x) ((x)->w_ptr) #define CIRCULARBUF_READ_PTR(x) ((x)->r_ptr) #define CIRCULARBUF_END_PTR(x) ((x)->e_ptr) #define circularbuf_debug_print(handle) \ CBUF_INFO(("%s:%d:\t%p rp=%4d r=%4d wp=%4d w=%4d e=%4d\n", \ __FUNCTION__, __LINE__, \ (void *) CIRCULARBUF_START(handle), \ (int) (handle)->rp_ptr, (int) (handle)->r_ptr, \ (int) (handle)->wp_ptr, (int) (handle)->w_ptr, \ (int) (handle)->e_ptr)); /* Callback registered by application/mail-box with the circularbuf implementation. * This will be invoked by the circularbuf implementation when write is complete and * ready for informing the peer */ typedef void (*mb_ring_t)(void *ctx); /* Public Functions exposed by circularbuf */ void circularbuf_init(circularbuf_t *handle, void *buf_base_addr, uint16 total_buf_len); void circularbuf_register_cb(circularbuf_t *handle, mb_ring_t mb_ring_func, void *ctx); /* Write Functions */ void * circularbuf_reserve_for_write(circularbuf_t *handle, uint16 size); void circularbuf_write_complete(circularbuf_t *handle, uint16 bytes_written); /* Read Functions */ void * circularbuf_get_read_ptr(circularbuf_t *handle, uint16 *avail_len); circularbuf_ret_t circularbuf_read_complete(circularbuf_t *handle, uint16 bytes_read); /* * circularbuf_get_read_ptr() updates rp_ptr by the amount that the consumer * is supposed to read. The consumer may not read the entire amount. * In such a case, circularbuf_revert_rp_ptr() call follows a corresponding * circularbuf_get_read_ptr() call to revert the rp_ptr back to * the point till which data has actually been processed. * It is not valid if it is preceded by multiple get_read_ptr() calls */ circularbuf_ret_t circularbuf_revert_rp_ptr(circularbuf_t *handle, uint16 bytes); #endif /* __CIRCULARBUF_H_INCLUDED__ */
{ "pile_set_name": "Github" }
$ groovy UserScript.groovy Caught: groovy.lang.MissingMethodException: No signature of method: User.givenName() is applicable for argument types: () values: [] Possible solutions: giveName(), getName(), setName(java.lang.String) at UserScript.run(UserScript.groovy:7)
{ "pile_set_name": "Github" }
""" ACE parser From wotsit.org and the SDK header (bitflags) Partial study of a new block type (5) I've called "new_recovery", as its syntax is very close to the former one (of type 2). Status: can only read totally file and header blocks. Author: Christophe Gisquet <[email protected]> Creation date: 19 january 2006 """ from hachoir_py3.parser import Parser from hachoir_py3.field import (StaticFieldSet, FieldSet, Bit, Bits, NullBits, RawBytes, Enum, UInt8, UInt16, UInt32, PascalString8, PascalString16, String, TimeDateMSDOS32) from hachoir_py3.core.text_handler import textHandler, filesizeHandler, hexadecimal from hachoir_py3.core.endian import LITTLE_ENDIAN from hachoir_py3.parser.common.msdos import MSDOSFileAttr32 MAGIC = b"**ACE**" OS_MSDOS = 0 OS_WIN32 = 2 HOST_OS = { 0: "MS-DOS", 1: "OS/2", 2: "Win32", 3: "Unix", 4: "MAC-OS", 5: "Win NT", 6: "Primos", 7: "APPLE GS", 8: "ATARI", 9: "VAX VMS", 10: "AMIGA", 11: "NEXT", } COMPRESSION_TYPE = { 0: "Store", 1: "Lempel-Ziv 77", 2: "ACE v2.0", } COMPRESSION_MODE = { 0: "fastest", 1: "fast", 2: "normal", 3: "good", 4: "best", } # TODO: Computing the CRC16 would also prove useful # def markerValidate(self): # return not self["extend"].value and self["signature"].value == MAGIC and \ # self["host_os"].value<12 class MarkerFlags(StaticFieldSet): format = ( (Bit, "extend", "Whether the header is extended"), (Bit, "has_comment", "Whether the archive has a comment"), (NullBits, "unused", 7, "Reserved bits"), (Bit, "sfx", "SFX"), (Bit, "limited_dict", "Junior SFX with 256K dictionary"), (Bit, "multi_volume", "Part of a set of ACE archives"), (Bit, "has_av_string", "This header holds an AV-string"), (Bit, "recovery_record", "Recovery record preset"), (Bit, "locked", "Archive is locked"), (Bit, "solid", "Archive uses solid compression") ) def markerFlags(self): yield MarkerFlags(self, "flags", "Marker flags") def markerHeader(self): yield String(self, "signature", 7, "Signature") yield UInt8(self, "ver_extract", "Version needed to extract archive") yield UInt8(self, "ver_created", "Version used to create archive") yield Enum(UInt8(self, "host_os", "OS where the files were compressed"), HOST_OS) yield UInt8(self, "vol_num", "Volume number") yield TimeDateMSDOS32(self, "time", "Date and time (MS DOS format)") yield Bits(self, "reserved", 64, "Reserved size for future extensions") flags = self["flags"] if flags["has_av_string"].value: yield PascalString8(self, "av_string", "AV String") if flags["has_comment"].value: size = filesizeHandler(UInt16(self, "comment_size", "Comment size")) yield size if size.value > 0: yield RawBytes(self, "compressed_comment", size.value, "Compressed comment") class FileFlags(StaticFieldSet): format = ( (Bit, "extend", "Whether the header is extended"), (Bit, "has_comment", "Presence of file comment"), (Bits, "unused", 10, "Unused bit flags"), (Bit, "encrypted", "File encrypted with password"), (Bit, "previous", "File continued from previous volume"), (Bit, "next", "File continues on the next volume"), (Bit, "solid", "File compressed using previously archived files") ) def fileFlags(self): yield FileFlags(self, "flags", "File flags") def fileHeader(self): yield filesizeHandler(UInt32(self, "compressed_size", "Size of the compressed file")) yield filesizeHandler(UInt32(self, "uncompressed_size", "Uncompressed file size")) yield TimeDateMSDOS32(self, "ftime", "Date and time (MS DOS format)") if self["/header/host_os"].value in (OS_MSDOS, OS_WIN32): yield MSDOSFileAttr32(self, "file_attr", "File attributes") else: yield textHandler(UInt32(self, "file_attr", "File attributes"), hexadecimal) yield textHandler(UInt32(self, "file_crc32", "CRC32 checksum over the compressed file)"), hexadecimal) yield Enum(UInt8(self, "compression_type", "Type of compression"), COMPRESSION_TYPE) yield Enum(UInt8(self, "compression_mode", "Quality of compression"), COMPRESSION_MODE) yield textHandler(UInt16(self, "parameters", "Compression parameters"), hexadecimal) yield textHandler(UInt16(self, "reserved", "Reserved data"), hexadecimal) # Filename yield PascalString16(self, "filename", "Filename") # Comment if self["flags/has_comment"].value: yield filesizeHandler(UInt16(self, "comment_size", "Size of the compressed comment")) if self["comment_size"].value > 0: yield RawBytes(self, "comment_data", self["comment_size"].value, "Comment data") def fileBody(self): size = self["compressed_size"].value if size > 0: yield RawBytes(self, "compressed_data", size, "Compressed data") def fileDesc(self): return "File entry: %s (%s)" % (self["filename"].value, self["compressed_size"].display) def recoveryHeader(self): yield filesizeHandler(UInt32(self, "rec_blk_size", "Size of recovery data")) self.body_size = self["rec_blk_size"].size yield String(self, "signature", 7, "Signature, normally '**ACE**'") yield textHandler(UInt32(self, "relative_start", "Relative start (to this block) of the data this block is mode of"), hexadecimal) yield UInt32(self, "num_blocks", "Number of blocks the data is split into") yield UInt32(self, "size_blocks", "Size of these blocks") yield UInt16(self, "crc16_blocks", "CRC16 over recovery data") # size_blocks blocks of size size_blocks follow # The ultimate data is the xor data of all those blocks size = self["size_blocks"].value for index in range(self["num_blocks"].value): yield RawBytes(self, "data[]", size, "Recovery block %i" % index) yield RawBytes(self, "xor_data", size, "The XOR value of the above data blocks") def recoveryDesc(self): return "Recovery block, size=%u" % self["body_size"].display def newRecoveryHeader(self): """ This header is described nowhere """ if self["flags/extend"].value: yield filesizeHandler(UInt32(self, "body_size", "Size of the unknown body following")) self.body_size = self["body_size"].value yield textHandler(UInt32(self, "unknown[]", "Unknown field, probably 0"), hexadecimal) yield String(self, "signature", 7, "Signature, normally '**ACE**'") yield textHandler(UInt32(self, "relative_start", "Offset (=crc16's) of this block in the file"), hexadecimal) yield textHandler(UInt32(self, "unknown[]", "Unknown field, probably 0"), hexadecimal) class BaseFlags(StaticFieldSet): format = ( (Bit, "extend", "Whether the header is extended"), (NullBits, "unused", 15, "Unused bit flags") ) def parseFlags(self): yield BaseFlags(self, "flags", "Unknown flags") def parseHeader(self): if self["flags/extend"].value: yield filesizeHandler(UInt32(self, "body_size", "Size of the unknown body following")) self.body_size = self["body_size"].value def parseBody(self): if self.body_size > 0: yield RawBytes(self, "body_data", self.body_size, "Body data, unhandled") class Block(FieldSet): TAG_INFO = { 0: ("header", "Archiver header", markerFlags, markerHeader, None), 1: ("file[]", fileDesc, fileFlags, fileHeader, fileBody), 2: ("recovery[]", recoveryDesc, recoveryHeader, None, None), 5: ("new_recovery[]", None, None, newRecoveryHeader, None) } def __init__(self, parent, name, description=None): FieldSet.__init__(self, parent, name, description) self.body_size = 0 self.desc_func = None type = self["block_type"].value if type in self.TAG_INFO: self._name, desc, self.parseFlags, self.parseHeader, self.parseBody = self.TAG_INFO[ type] if desc: if isinstance(desc, str): self._description = desc else: self.desc_func = desc else: self.warning("Processing as unknown block block of type %u" % type) if not self.parseFlags: self.parseFlags = parseFlags if not self.parseHeader: self.parseHeader = parseHeader if not self.parseBody: self.parseBody = parseBody def createFields(self): yield textHandler(UInt16(self, "crc16", "Archive CRC16 (from byte 4 on)"), hexadecimal) yield filesizeHandler(UInt16(self, "head_size", "Block size (from byte 4 on)")) yield UInt8(self, "block_type", "Block type") # Flags yield from self.parseFlags(self) # Rest of the header yield from self.parseHeader(self) size = self["head_size"].value - (self.current_size // 8) + (2 + 2) if size > 0: yield RawBytes(self, "extra_data", size, "Extra header data, unhandled") # Body in itself yield from self.parseBody(self) def createDescription(self): if self.desc_func: return self.desc_func(self) else: return "Block: %s" % self["type"].display class AceFile(Parser): endian = LITTLE_ENDIAN PARSER_TAGS = { "id": "ace", "category": "archive", "file_ext": ("ace",), "mime": ("application/x-ace-compressed",), "min_size": 50 * 8, "description": "ACE archive" } def validate(self): if self.stream.readBytes(7 * 8, len(MAGIC)) != MAGIC: return "Invalid magic" return True def createFields(self): while not self.eof: yield Block(self, "block[]")
{ "pile_set_name": "Github" }
# 2009 January 29 # # The author disclaims copyright to this source code. In place of # a legal notice, here is a blessing: # # May you do good and not evil. # May you find forgiveness for yourself and forgive others. # May you share freely, never taking more than you give. # #*********************************************************************** # # Verify that certain keywords can be used as identifiers. # # $Id: keyword1.test,v 1.1 2009/01/29 19:27:47 drh Exp $ set testdir [file dirname $argv0] source $testdir/tester.tcl db eval { CREATE TABLE t1(a, b); INSERT INTO t1 VALUES(1, 'one'); INSERT INTO t1 VALUES(2, 'two'); INSERT INTO t1 VALUES(3, 'three'); } set kwlist { abort after analyze asc attach before begin by cascade cast column conflict current_date current_time current_timestamp database deferred desc detach end each exclusive explain fail for glob if ignore immediate initially instead key like match of offset plan pragma query raise recursive regexp reindex release rename replace restrict rollback row savepoint temp temporary trigger vacuum view virtual with without }; set exprkw { cast current_date current_time current_timestamp raise } foreach kw $kwlist { do_test keyword1-$kw.1 { if {$kw=="if"} { db eval "CREATE TABLE \"$kw\"($kw $kw)" } else { db eval "CREATE TABLE ${kw}($kw $kw)" } db eval "INSERT INTO $kw VALUES(99)" db eval "INSERT INTO $kw SELECT a FROM t1" if {[lsearch $exprkw $kw]<0} { db eval "SELECT * FROM $kw ORDER BY $kw ASC" } else { db eval "SELECT * FROM $kw ORDER BY \"$kw\" ASC" } } {1 2 3 99} do_test keyword1-$kw.2 { if {$kw=="if"} { db eval "DROP TABLE \"$kw\"" db eval "CREATE INDEX \"$kw\" ON t1(a)" } else { db eval "DROP TABLE $kw" db eval "CREATE INDEX $kw ON t1(a)" } db eval "SELECT b FROM t1 INDEXED BY $kw WHERE a=2" } {two} } finish_test
{ "pile_set_name": "Github" }
################################################################################ # # uftp # ################################################################################ UFTP_VERSION = 4.10.2 UFTP_SITE = http://sourceforge.net/projects/uftp-multicast/files/source-tar UFTP_LICENSE = GPL-3.0+ UFTP_LICENSE_FILES = LICENSE.txt ifeq ($(BR2_PACKAGE_OPENSSL),y) UFTP_DEPENDENCIES += host-pkgconf openssl UFTP_MAKE_OPTS += CRYPT_LIB="`$(PKG_CONFIG_HOST_BINARY) --libs libcrypto`" else UFTP_MAKE_OPTS += NO_ENCRYPTION=1 endif define UFTP_BUILD_CMDS $(TARGET_CONFIGURE_OPTS) $(MAKE) -C $(@D) $(UFTP_MAKE_OPTS) endef define UFTP_INSTALL_TARGET_CMDS $(TARGET_CONFIGURE_OPTS) $(MAKE) -C $(@D) $(UFTP_MAKE_OPTS) \ DESTDIR=$(TARGET_DIR) install endef $(eval $(generic-package))
{ "pile_set_name": "Github" }
package mockit; import static org.junit.Assert.*; import org.junit.*; public final class TestedClassWithNoDITest { public static final class TestedClass { private final Dependency dependency = new Dependency(); public boolean doSomeOperation() { return dependency.doSomething() > 0; } } static class Dependency { int doSomething() { return -1; } } @Tested TestedClass tested1; @Tested final TestedClass tested2 = new TestedClass(); @Tested TestedClass tested3; @Tested NonPublicTestedClass tested4; @Tested final TestedClass tested5 = null; @Mocked Dependency mock; TestedClass tested; @Before public void setUp() { assertNotNull(mock); assertNull(tested); tested = new TestedClass(); assertNull(tested3); tested3 = tested; assertNull(tested1); assertNotNull(tested2); assertNull(tested4); assertNull(tested5); } @Test public void verifyTestedFields() { assertNull(tested5); assertNotNull(tested4); assertNotNull(tested3); assertSame(tested, tested3); assertNotNull(tested2); assertNotNull(tested1); } @Test public void exerciseAutomaticallyInstantiatedTestedObject() { new Expectations() {{ mock.doSomething(); result = 1; }}; assertTrue(tested1.doSomeOperation()); } @Test public void exerciseManuallyInstantiatedTestedObject() { new Expectations() {{ mock.doSomething(); result = 1; }}; assertTrue(tested2.doSomeOperation()); new FullVerifications() {}; } @Test public void exerciseAnotherManuallyInstantiatedTestedObject() { assertFalse(tested3.doSomeOperation()); new Verifications() {{ mock.doSomething(); times = 1; }}; } } class NonPublicTestedClass { @SuppressWarnings("RedundantNoArgConstructor") NonPublicTestedClass() {} }
{ "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/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.6"/> <title>qLibc: utilities/qio.c Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">qLibc </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.6 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>Globals</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('qio_8c_source.html','');}); </script> <div id="doc-content"> <div class="header"> <div class="headertitle"> <div class="title">qio.c</div> </div> </div><!--header--> <div class="contents"> <a href="qio_8c.html">Go to the documentation of this file.</a><div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span>&#160;<span class="comment">/******************************************************************************</span></div> <div class="line"><a name="l00002"></a><span class="lineno"> 2</span>&#160;<span class="comment"> * qLibc</span></div> <div class="line"><a name="l00003"></a><span class="lineno"> 3</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00004"></a><span class="lineno"> 4</span>&#160;<span class="comment"> * Copyright (c) 2010-2015 Seungyoung Kim.</span></div> <div class="line"><a name="l00005"></a><span class="lineno"> 5</span>&#160;<span class="comment"> * All rights reserved.</span></div> <div class="line"><a name="l00006"></a><span class="lineno"> 6</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00007"></a><span class="lineno"> 7</span>&#160;<span class="comment"> * Redistribution and use in source and binary forms, with or without</span></div> <div class="line"><a name="l00008"></a><span class="lineno"> 8</span>&#160;<span class="comment"> * modification, are permitted provided that the following conditions are met:</span></div> <div class="line"><a name="l00009"></a><span class="lineno"> 9</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00010"></a><span class="lineno"> 10</span>&#160;<span class="comment"> * 1. Redistributions of source code must retain the above copyright notice,</span></div> <div class="line"><a name="l00011"></a><span class="lineno"> 11</span>&#160;<span class="comment"> * this list of conditions and the following disclaimer.</span></div> <div class="line"><a name="l00012"></a><span class="lineno"> 12</span>&#160;<span class="comment"> * 2. Redistributions in binary form must reproduce the above copyright notice,</span></div> <div class="line"><a name="l00013"></a><span class="lineno"> 13</span>&#160;<span class="comment"> * this list of conditions and the following disclaimer in the documentation</span></div> <div class="line"><a name="l00014"></a><span class="lineno"> 14</span>&#160;<span class="comment"> * and/or other materials provided with the distribution.</span></div> <div class="line"><a name="l00015"></a><span class="lineno"> 15</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00016"></a><span class="lineno"> 16</span>&#160;<span class="comment"> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&quot;</span></div> <div class="line"><a name="l00017"></a><span class="lineno"> 17</span>&#160;<span class="comment"> * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE</span></div> <div class="line"><a name="l00018"></a><span class="lineno"> 18</span>&#160;<span class="comment"> * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE</span></div> <div class="line"><a name="l00019"></a><span class="lineno"> 19</span>&#160;<span class="comment"> * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE</span></div> <div class="line"><a name="l00020"></a><span class="lineno"> 20</span>&#160;<span class="comment"> * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR</span></div> <div class="line"><a name="l00021"></a><span class="lineno"> 21</span>&#160;<span class="comment"> * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF</span></div> <div class="line"><a name="l00022"></a><span class="lineno"> 22</span>&#160;<span class="comment"> * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS</span></div> <div class="line"><a name="l00023"></a><span class="lineno"> 23</span>&#160;<span class="comment"> * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN</span></div> <div class="line"><a name="l00024"></a><span class="lineno"> 24</span>&#160;<span class="comment"> * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)</span></div> <div class="line"><a name="l00025"></a><span class="lineno"> 25</span>&#160;<span class="comment"> * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE</span></div> <div class="line"><a name="l00026"></a><span class="lineno"> 26</span>&#160;<span class="comment"> * POSSIBILITY OF SUCH DAMAGE.</span></div> <div class="line"><a name="l00027"></a><span class="lineno"> 27</span>&#160;<span class="comment"> *****************************************************************************/</span></div> <div class="line"><a name="l00028"></a><span class="lineno"> 28</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00029"></a><span class="lineno"> 29</span>&#160;<span class="comment">/**</span></div> <div class="line"><a name="l00030"></a><span class="lineno"> 30</span>&#160;<span class="comment"> * @file qio.c I/O handling APIs.</span></div> <div class="line"><a name="l00031"></a><span class="lineno"> 31</span>&#160;<span class="comment"> */</span></div> <div class="line"><a name="l00032"></a><span class="lineno"> 32</span>&#160;</div> <div class="line"><a name="l00033"></a><span class="lineno"> 33</span>&#160;<span class="preprocessor">#include &lt;stdio.h&gt;</span></div> <div class="line"><a name="l00034"></a><span class="lineno"> 34</span>&#160;<span class="preprocessor">#include &lt;stdlib.h&gt;</span></div> <div class="line"><a name="l00035"></a><span class="lineno"> 35</span>&#160;<span class="preprocessor">#include &lt;stdbool.h&gt;</span></div> <div class="line"><a name="l00036"></a><span class="lineno"> 36</span>&#160;<span class="preprocessor">#include &lt;stdarg.h&gt;</span></div> <div class="line"><a name="l00037"></a><span class="lineno"> 37</span>&#160;<span class="preprocessor">#include &lt;string.h&gt;</span></div> <div class="line"><a name="l00038"></a><span class="lineno"> 38</span>&#160;<span class="preprocessor">#include &lt;unistd.h&gt;</span></div> <div class="line"><a name="l00039"></a><span class="lineno"> 39</span>&#160;<span class="preprocessor">#include &lt;poll.h&gt;</span></div> <div class="line"><a name="l00040"></a><span class="lineno"> 40</span>&#160;<span class="preprocessor">#include &lt;errno.h&gt;</span></div> <div class="line"><a name="l00041"></a><span class="lineno"> 41</span>&#160;<span class="preprocessor">#include &quot;qinternal.h&quot;</span></div> <div class="line"><a name="l00042"></a><span class="lineno"> 42</span>&#160;<span class="preprocessor">#include &quot;utilities/qio.h&quot;</span></div> <div class="line"><a name="l00043"></a><span class="lineno"> 43</span>&#160;</div> <div class="line"><a name="l00044"></a><span class="lineno"> 44</span>&#160;<span class="preprocessor">#define MAX_IOSEND_SIZE (32 * 1024)</span></div> <div class="line"><a name="l00045"></a><span class="lineno"> 45</span>&#160;<span class="preprocessor"></span><span class="comment"></span></div> <div class="line"><a name="l00046"></a><span class="lineno"> 46</span>&#160;<span class="comment">/**</span></div> <div class="line"><a name="l00047"></a><span class="lineno"> 47</span>&#160;<span class="comment"> * Test &amp; wait until the file descriptor has readable data.</span></div> <div class="line"><a name="l00048"></a><span class="lineno"> 48</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00049"></a><span class="lineno"> 49</span>&#160;<span class="comment"> * @param fd file descriptor</span></div> <div class="line"><a name="l00050"></a><span class="lineno"> 50</span>&#160;<span class="comment"> * @param timeoutms wait timeout milliseconds. 0 for no wait,</span></div> <div class="line"><a name="l00051"></a><span class="lineno"> 51</span>&#160;<span class="comment"> * -1 for infinite wait</span></div> <div class="line"><a name="l00052"></a><span class="lineno"> 52</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00053"></a><span class="lineno"> 53</span>&#160;<span class="comment"> * @return 1 if readable, 0 on timeout, -1 if an error occurred.</span></div> <div class="line"><a name="l00054"></a><span class="lineno"> 54</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00055"></a><span class="lineno"> 55</span>&#160;<span class="comment"> * @note</span></div> <div class="line"><a name="l00056"></a><span class="lineno"> 56</span>&#160;<span class="comment"> * The argument timeoutms can be used to set maximum wait time for a socket</span></div> <div class="line"><a name="l00057"></a><span class="lineno"> 57</span>&#160;<span class="comment"> * descriptor.</span></div> <div class="line"><a name="l00058"></a><span class="lineno"> 58</span>&#160;<span class="comment"> */</span></div> <div class="line"><a name="l00059"></a><span class="lineno"><a class="line" href="qio_8c.html#a8a695a43ebb605d243e56ad48937862e"> 59</a></span>&#160;<span class="keywordtype">int</span> <a class="code" href="qio_8c.html#a8a695a43ebb605d243e56ad48937862e">qio_wait_readable</a>(<span class="keywordtype">int</span> fd, <span class="keywordtype">int</span> timeoutms) {</div> <div class="line"><a name="l00060"></a><span class="lineno"> 60</span>&#160; <span class="keyword">struct </span>pollfd fds[1];</div> <div class="line"><a name="l00061"></a><span class="lineno"> 61</span>&#160;</div> <div class="line"><a name="l00062"></a><span class="lineno"> 62</span>&#160; fds[0].fd = fd;</div> <div class="line"><a name="l00063"></a><span class="lineno"> 63</span>&#160; fds[0].events = POLLIN;</div> <div class="line"><a name="l00064"></a><span class="lineno"> 64</span>&#160;</div> <div class="line"><a name="l00065"></a><span class="lineno"> 65</span>&#160; <span class="keywordtype">int</span> pollret = poll(fds, 1, timeoutms);</div> <div class="line"><a name="l00066"></a><span class="lineno"> 66</span>&#160; <span class="keywordflow">if</span> (pollret == 0) {</div> <div class="line"><a name="l00067"></a><span class="lineno"> 67</span>&#160; errno = ETIMEDOUT;</div> <div class="line"><a name="l00068"></a><span class="lineno"> 68</span>&#160; <span class="keywordflow">return</span> 0;</div> <div class="line"><a name="l00069"></a><span class="lineno"> 69</span>&#160; } <span class="keywordflow">else</span> <span class="keywordflow">if</span> (pollret &lt; 0) {</div> <div class="line"><a name="l00070"></a><span class="lineno"> 70</span>&#160; <span class="keywordflow">return</span> -1;</div> <div class="line"><a name="l00071"></a><span class="lineno"> 71</span>&#160; }</div> <div class="line"><a name="l00072"></a><span class="lineno"> 72</span>&#160;</div> <div class="line"><a name="l00073"></a><span class="lineno"> 73</span>&#160; <span class="keywordflow">if</span> (fds[0].revents &amp; POLLIN)</div> <div class="line"><a name="l00074"></a><span class="lineno"> 74</span>&#160; <span class="keywordflow">return</span> 1;</div> <div class="line"><a name="l00075"></a><span class="lineno"> 75</span>&#160; <span class="keywordflow">return</span> -1;</div> <div class="line"><a name="l00076"></a><span class="lineno"> 76</span>&#160;}</div> <div class="line"><a name="l00077"></a><span class="lineno"> 77</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00078"></a><span class="lineno"> 78</span>&#160;<span class="comment">/**</span></div> <div class="line"><a name="l00079"></a><span class="lineno"> 79</span>&#160;<span class="comment"> * Test &amp; wait until the file descriptor is ready for writing.</span></div> <div class="line"><a name="l00080"></a><span class="lineno"> 80</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00081"></a><span class="lineno"> 81</span>&#160;<span class="comment"> * @param fd file descriptor</span></div> <div class="line"><a name="l00082"></a><span class="lineno"> 82</span>&#160;<span class="comment"> * @param timeoutms wait timeout milliseconds. 0 for no wait,</span></div> <div class="line"><a name="l00083"></a><span class="lineno"> 83</span>&#160;<span class="comment"> * -1 for infinite wait</span></div> <div class="line"><a name="l00084"></a><span class="lineno"> 84</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00085"></a><span class="lineno"> 85</span>&#160;<span class="comment"> * @return 1 if writable, 0 on timeout, -1 if an error occurred.</span></div> <div class="line"><a name="l00086"></a><span class="lineno"> 86</span>&#160;<span class="comment"> */</span></div> <div class="line"><a name="l00087"></a><span class="lineno"><a class="line" href="qio_8c.html#ac905811f0daa394ffef7beab68585a55"> 87</a></span>&#160;<span class="keywordtype">int</span> <a class="code" href="qio_8c.html#ac905811f0daa394ffef7beab68585a55">qio_wait_writable</a>(<span class="keywordtype">int</span> fd, <span class="keywordtype">int</span> timeoutms) {</div> <div class="line"><a name="l00088"></a><span class="lineno"> 88</span>&#160; <span class="keyword">struct </span>pollfd fds[1];</div> <div class="line"><a name="l00089"></a><span class="lineno"> 89</span>&#160;</div> <div class="line"><a name="l00090"></a><span class="lineno"> 90</span>&#160; fds[0].fd = fd;</div> <div class="line"><a name="l00091"></a><span class="lineno"> 91</span>&#160; fds[0].events = POLLOUT;</div> <div class="line"><a name="l00092"></a><span class="lineno"> 92</span>&#160;</div> <div class="line"><a name="l00093"></a><span class="lineno"> 93</span>&#160; <span class="keywordtype">int</span> pollret = poll(fds, 1, timeoutms);</div> <div class="line"><a name="l00094"></a><span class="lineno"> 94</span>&#160; <span class="keywordflow">if</span> (pollret == 0) {</div> <div class="line"><a name="l00095"></a><span class="lineno"> 95</span>&#160; errno = ETIMEDOUT;</div> <div class="line"><a name="l00096"></a><span class="lineno"> 96</span>&#160; <span class="keywordflow">return</span> 0;</div> <div class="line"><a name="l00097"></a><span class="lineno"> 97</span>&#160; } <span class="keywordflow">else</span> <span class="keywordflow">if</span> (pollret &lt; 0) {</div> <div class="line"><a name="l00098"></a><span class="lineno"> 98</span>&#160; <span class="keywordflow">return</span> -1;</div> <div class="line"><a name="l00099"></a><span class="lineno"> 99</span>&#160; }</div> <div class="line"><a name="l00100"></a><span class="lineno"> 100</span>&#160;</div> <div class="line"><a name="l00101"></a><span class="lineno"> 101</span>&#160; <span class="keywordflow">if</span> (fds[0].revents &amp; POLLOUT)</div> <div class="line"><a name="l00102"></a><span class="lineno"> 102</span>&#160; <span class="keywordflow">return</span> 1;</div> <div class="line"><a name="l00103"></a><span class="lineno"> 103</span>&#160; <span class="keywordflow">return</span> -1;</div> <div class="line"><a name="l00104"></a><span class="lineno"> 104</span>&#160;}</div> <div class="line"><a name="l00105"></a><span class="lineno"> 105</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00106"></a><span class="lineno"> 106</span>&#160;<span class="comment">/**</span></div> <div class="line"><a name="l00107"></a><span class="lineno"> 107</span>&#160;<span class="comment"> * Read from a file descriptor.</span></div> <div class="line"><a name="l00108"></a><span class="lineno"> 108</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00109"></a><span class="lineno"> 109</span>&#160;<span class="comment"> * @param fd file descriptor</span></div> <div class="line"><a name="l00110"></a><span class="lineno"> 110</span>&#160;<span class="comment"> * @param buf data buffer pointer to write to</span></div> <div class="line"><a name="l00111"></a><span class="lineno"> 111</span>&#160;<span class="comment"> * @param nbytes the number of bytes to read from file descriptor &amp; write</span></div> <div class="line"><a name="l00112"></a><span class="lineno"> 112</span>&#160;<span class="comment"> * into buffer</span></div> <div class="line"><a name="l00113"></a><span class="lineno"> 113</span>&#160;<span class="comment"> * @param timeoutms wait timeout milliseconds. 0 for no wait, -1 for infinite</span></div> <div class="line"><a name="l00114"></a><span class="lineno"> 114</span>&#160;<span class="comment"> * wait</span></div> <div class="line"><a name="l00115"></a><span class="lineno"> 115</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00116"></a><span class="lineno"> 116</span>&#160;<span class="comment"> * @return the number of bytes read if successful, 0 on timeout, -1 for error.</span></div> <div class="line"><a name="l00117"></a><span class="lineno"> 117</span>&#160;<span class="comment"> */</span></div> <div class="line"><a name="l00118"></a><span class="lineno"><a class="line" href="qio_8c.html#aa34911362f1793ed1e744d3eb63500db"> 118</a></span>&#160;ssize_t <a class="code" href="qio_8c.html#aa34911362f1793ed1e744d3eb63500db">qio_read</a>(<span class="keywordtype">int</span> fd, <span class="keywordtype">void</span> *buf, <span class="keywordtype">size_t</span> nbytes, <span class="keywordtype">int</span> timeoutms) {</div> <div class="line"><a name="l00119"></a><span class="lineno"> 119</span>&#160; <span class="keywordflow">if</span> (nbytes == 0)</div> <div class="line"><a name="l00120"></a><span class="lineno"> 120</span>&#160; <span class="keywordflow">return</span> 0;</div> <div class="line"><a name="l00121"></a><span class="lineno"> 121</span>&#160;</div> <div class="line"><a name="l00122"></a><span class="lineno"> 122</span>&#160; ssize_t total = 0;</div> <div class="line"><a name="l00123"></a><span class="lineno"> 123</span>&#160; <span class="keywordflow">while</span> (total &lt; nbytes) {</div> <div class="line"><a name="l00124"></a><span class="lineno"> 124</span>&#160; <span class="keywordflow">if</span> (timeoutms &gt;= 0 &amp;&amp; <a class="code" href="qio_8c.html#a8a695a43ebb605d243e56ad48937862e">qio_wait_readable</a>(fd, timeoutms) &lt;= 0)</div> <div class="line"><a name="l00125"></a><span class="lineno"> 125</span>&#160; <span class="keywordflow">break</span>;</div> <div class="line"><a name="l00126"></a><span class="lineno"> 126</span>&#160;</div> <div class="line"><a name="l00127"></a><span class="lineno"> 127</span>&#160; ssize_t rsize = read(fd, buf + total, nbytes - total);</div> <div class="line"><a name="l00128"></a><span class="lineno"> 128</span>&#160; <span class="keywordflow">if</span> (rsize &lt;= 0) {</div> <div class="line"><a name="l00129"></a><span class="lineno"> 129</span>&#160; <span class="keywordflow">if</span> (errno == EAGAIN || errno == EINPROGRESS) {</div> <div class="line"><a name="l00130"></a><span class="lineno"> 130</span>&#160; <span class="comment">// possible with non-block io</span></div> <div class="line"><a name="l00131"></a><span class="lineno"> 131</span>&#160; usleep(1);</div> <div class="line"><a name="l00132"></a><span class="lineno"> 132</span>&#160; <span class="keywordflow">continue</span>;</div> <div class="line"><a name="l00133"></a><span class="lineno"> 133</span>&#160; }</div> <div class="line"><a name="l00134"></a><span class="lineno"> 134</span>&#160; <span class="keywordflow">break</span>;</div> <div class="line"><a name="l00135"></a><span class="lineno"> 135</span>&#160; }</div> <div class="line"><a name="l00136"></a><span class="lineno"> 136</span>&#160; total += rsize;</div> <div class="line"><a name="l00137"></a><span class="lineno"> 137</span>&#160; }</div> <div class="line"><a name="l00138"></a><span class="lineno"> 138</span>&#160;</div> <div class="line"><a name="l00139"></a><span class="lineno"> 139</span>&#160; <span class="keywordflow">if</span> (total &gt; 0)</div> <div class="line"><a name="l00140"></a><span class="lineno"> 140</span>&#160; <span class="keywordflow">return</span> total;</div> <div class="line"><a name="l00141"></a><span class="lineno"> 141</span>&#160; <span class="keywordflow">else</span> <span class="keywordflow">if</span> (errno == ETIMEDOUT)</div> <div class="line"><a name="l00142"></a><span class="lineno"> 142</span>&#160; <span class="keywordflow">return</span> 0;</div> <div class="line"><a name="l00143"></a><span class="lineno"> 143</span>&#160; <span class="keywordflow">return</span> -1;</div> <div class="line"><a name="l00144"></a><span class="lineno"> 144</span>&#160;}</div> <div class="line"><a name="l00145"></a><span class="lineno"> 145</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00146"></a><span class="lineno"> 146</span>&#160;<span class="comment">/**</span></div> <div class="line"><a name="l00147"></a><span class="lineno"> 147</span>&#160;<span class="comment"> * Write to a file descriptor.</span></div> <div class="line"><a name="l00148"></a><span class="lineno"> 148</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00149"></a><span class="lineno"> 149</span>&#160;<span class="comment"> * @param fd file descriptor</span></div> <div class="line"><a name="l00150"></a><span class="lineno"> 150</span>&#160;<span class="comment"> * @param buf data buffer pointer to read from</span></div> <div class="line"><a name="l00151"></a><span class="lineno"> 151</span>&#160;<span class="comment"> * @param nbytes the number of bytes to write to file descriptor &amp; read</span></div> <div class="line"><a name="l00152"></a><span class="lineno"> 152</span>&#160;<span class="comment"> * from buffer</span></div> <div class="line"><a name="l00153"></a><span class="lineno"> 153</span>&#160;<span class="comment"> * @param timeoutms wait timeout milliseconds. 0 for no wait, -1 for infinite</span></div> <div class="line"><a name="l00154"></a><span class="lineno"> 154</span>&#160;<span class="comment"> * wait</span></div> <div class="line"><a name="l00155"></a><span class="lineno"> 155</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00156"></a><span class="lineno"> 156</span>&#160;<span class="comment"> * @return the number of bytes written if successful, 0 on timeout,</span></div> <div class="line"><a name="l00157"></a><span class="lineno"> 157</span>&#160;<span class="comment"> * -1 for error.</span></div> <div class="line"><a name="l00158"></a><span class="lineno"> 158</span>&#160;<span class="comment"> */</span></div> <div class="line"><a name="l00159"></a><span class="lineno"><a class="line" href="qio_8c.html#a0645cf0a3bcfc79ee3829012243d46d8"> 159</a></span>&#160;ssize_t <a class="code" href="qio_8c.html#a0645cf0a3bcfc79ee3829012243d46d8">qio_write</a>(<span class="keywordtype">int</span> fd, <span class="keyword">const</span> <span class="keywordtype">void</span> *buf, <span class="keywordtype">size_t</span> nbytes, <span class="keywordtype">int</span> timeoutms) {</div> <div class="line"><a name="l00160"></a><span class="lineno"> 160</span>&#160; <span class="keywordflow">if</span> (nbytes == 0)</div> <div class="line"><a name="l00161"></a><span class="lineno"> 161</span>&#160; <span class="keywordflow">return</span> 0;</div> <div class="line"><a name="l00162"></a><span class="lineno"> 162</span>&#160;</div> <div class="line"><a name="l00163"></a><span class="lineno"> 163</span>&#160; ssize_t total = 0;</div> <div class="line"><a name="l00164"></a><span class="lineno"> 164</span>&#160; <span class="keywordflow">while</span> (total &lt; nbytes) {</div> <div class="line"><a name="l00165"></a><span class="lineno"> 165</span>&#160; <span class="keywordflow">if</span> (timeoutms &gt;= 0 &amp;&amp; <a class="code" href="qio_8c.html#ac905811f0daa394ffef7beab68585a55">qio_wait_writable</a>(fd, timeoutms) &lt;= 0)</div> <div class="line"><a name="l00166"></a><span class="lineno"> 166</span>&#160; <span class="keywordflow">break</span>;</div> <div class="line"><a name="l00167"></a><span class="lineno"> 167</span>&#160; ssize_t wsize = write(fd, buf + total, nbytes - total);</div> <div class="line"><a name="l00168"></a><span class="lineno"> 168</span>&#160; <span class="keywordflow">if</span> (wsize &lt;= 0) {</div> <div class="line"><a name="l00169"></a><span class="lineno"> 169</span>&#160; <span class="keywordflow">if</span> (errno == EAGAIN || errno == EINPROGRESS) {</div> <div class="line"><a name="l00170"></a><span class="lineno"> 170</span>&#160; <span class="comment">// possible with non-block io</span></div> <div class="line"><a name="l00171"></a><span class="lineno"> 171</span>&#160; usleep(1);</div> <div class="line"><a name="l00172"></a><span class="lineno"> 172</span>&#160; <span class="keywordflow">continue</span>;</div> <div class="line"><a name="l00173"></a><span class="lineno"> 173</span>&#160; }</div> <div class="line"><a name="l00174"></a><span class="lineno"> 174</span>&#160; <span class="keywordflow">break</span>;</div> <div class="line"><a name="l00175"></a><span class="lineno"> 175</span>&#160; }</div> <div class="line"><a name="l00176"></a><span class="lineno"> 176</span>&#160; total += wsize;</div> <div class="line"><a name="l00177"></a><span class="lineno"> 177</span>&#160; }</div> <div class="line"><a name="l00178"></a><span class="lineno"> 178</span>&#160;</div> <div class="line"><a name="l00179"></a><span class="lineno"> 179</span>&#160; <span class="keywordflow">if</span> (total &gt; 0)</div> <div class="line"><a name="l00180"></a><span class="lineno"> 180</span>&#160; <span class="keywordflow">return</span> total;</div> <div class="line"><a name="l00181"></a><span class="lineno"> 181</span>&#160; <span class="keywordflow">else</span> <span class="keywordflow">if</span> (errno == ETIMEDOUT)</div> <div class="line"><a name="l00182"></a><span class="lineno"> 182</span>&#160; <span class="keywordflow">return</span> 0;</div> <div class="line"><a name="l00183"></a><span class="lineno"> 183</span>&#160; <span class="keywordflow">return</span> -1;</div> <div class="line"><a name="l00184"></a><span class="lineno"> 184</span>&#160;}</div> <div class="line"><a name="l00185"></a><span class="lineno"> 185</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00186"></a><span class="lineno"> 186</span>&#160;<span class="comment">/**</span></div> <div class="line"><a name="l00187"></a><span class="lineno"> 187</span>&#160;<span class="comment"> * Transfer data between file descriptors</span></div> <div class="line"><a name="l00188"></a><span class="lineno"> 188</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00189"></a><span class="lineno"> 189</span>&#160;<span class="comment"> * @param outfd output file descriptor</span></div> <div class="line"><a name="l00190"></a><span class="lineno"> 190</span>&#160;<span class="comment"> * @param infd input file descriptor</span></div> <div class="line"><a name="l00191"></a><span class="lineno"> 191</span>&#160;<span class="comment"> * @param nbytes the number of bytes to copy between file descriptors.</span></div> <div class="line"><a name="l00192"></a><span class="lineno"> 192</span>&#160;<span class="comment"> * 0 means transfer until end of infd.</span></div> <div class="line"><a name="l00193"></a><span class="lineno"> 193</span>&#160;<span class="comment"> * @param timeoutms wait timeout milliseconds. 0 for no wait, -1 for infinite</span></div> <div class="line"><a name="l00194"></a><span class="lineno"> 194</span>&#160;<span class="comment"> * wait</span></div> <div class="line"><a name="l00195"></a><span class="lineno"> 195</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00196"></a><span class="lineno"> 196</span>&#160;<span class="comment"> * @return the number of bytes transferred if successful, 0 on timeout,</span></div> <div class="line"><a name="l00197"></a><span class="lineno"> 197</span>&#160;<span class="comment"> * -1 for error.</span></div> <div class="line"><a name="l00198"></a><span class="lineno"> 198</span>&#160;<span class="comment"> */</span></div> <div class="line"><a name="l00199"></a><span class="lineno"><a class="line" href="qio_8c.html#aafd34a0ab9f916ded37b1634cac3ab6a"> 199</a></span>&#160;off_t <a class="code" href="qio_8c.html#aafd34a0ab9f916ded37b1634cac3ab6a">qio_send</a>(<span class="keywordtype">int</span> outfd, <span class="keywordtype">int</span> infd, off_t nbytes, <span class="keywordtype">int</span> timeoutms) {</div> <div class="line"><a name="l00200"></a><span class="lineno"> 200</span>&#160; <span class="keywordflow">if</span> (nbytes == 0)</div> <div class="line"><a name="l00201"></a><span class="lineno"> 201</span>&#160; <span class="keywordflow">return</span> 0;</div> <div class="line"><a name="l00202"></a><span class="lineno"> 202</span>&#160;</div> <div class="line"><a name="l00203"></a><span class="lineno"> 203</span>&#160; <span class="keywordtype">unsigned</span> <span class="keywordtype">char</span> buf[MAX_IOSEND_SIZE];</div> <div class="line"><a name="l00204"></a><span class="lineno"> 204</span>&#160;</div> <div class="line"><a name="l00205"></a><span class="lineno"> 205</span>&#160; off_t total = 0; <span class="comment">// total size sent</span></div> <div class="line"><a name="l00206"></a><span class="lineno"> 206</span>&#160; <span class="keywordflow">while</span> (total &lt; nbytes) {</div> <div class="line"><a name="l00207"></a><span class="lineno"> 207</span>&#160; <span class="keywordtype">size_t</span> chunksize; <span class="comment">// this time sending size</span></div> <div class="line"><a name="l00208"></a><span class="lineno"> 208</span>&#160; <span class="keywordflow">if</span> (nbytes - total &lt;= <span class="keyword">sizeof</span>(buf))</div> <div class="line"><a name="l00209"></a><span class="lineno"> 209</span>&#160; chunksize = nbytes - total;</div> <div class="line"><a name="l00210"></a><span class="lineno"> 210</span>&#160; <span class="keywordflow">else</span></div> <div class="line"><a name="l00211"></a><span class="lineno"> 211</span>&#160; chunksize = <span class="keyword">sizeof</span>(buf);</div> <div class="line"><a name="l00212"></a><span class="lineno"> 212</span>&#160;</div> <div class="line"><a name="l00213"></a><span class="lineno"> 213</span>&#160; <span class="comment">// read</span></div> <div class="line"><a name="l00214"></a><span class="lineno"> 214</span>&#160; ssize_t rsize = <a class="code" href="qio_8c.html#aa34911362f1793ed1e744d3eb63500db">qio_read</a>(infd, buf, chunksize, timeoutms);</div> <div class="line"><a name="l00215"></a><span class="lineno"> 215</span>&#160; DEBUG(<span class="stringliteral">&quot;read %zd&quot;</span>, rsize);</div> <div class="line"><a name="l00216"></a><span class="lineno"> 216</span>&#160; <span class="keywordflow">if</span> (rsize &lt;= 0)</div> <div class="line"><a name="l00217"></a><span class="lineno"> 217</span>&#160; <span class="keywordflow">break</span>;</div> <div class="line"><a name="l00218"></a><span class="lineno"> 218</span>&#160;</div> <div class="line"><a name="l00219"></a><span class="lineno"> 219</span>&#160; <span class="comment">// write</span></div> <div class="line"><a name="l00220"></a><span class="lineno"> 220</span>&#160; ssize_t wsize = <a class="code" href="qio_8c.html#a0645cf0a3bcfc79ee3829012243d46d8">qio_write</a>(outfd, buf, rsize, timeoutms);</div> <div class="line"><a name="l00221"></a><span class="lineno"> 221</span>&#160; DEBUG(<span class="stringliteral">&quot;write %zd&quot;</span>, wsize);</div> <div class="line"><a name="l00222"></a><span class="lineno"> 222</span>&#160; <span class="keywordflow">if</span> (wsize &lt;= 0)</div> <div class="line"><a name="l00223"></a><span class="lineno"> 223</span>&#160; <span class="keywordflow">break</span>;</div> <div class="line"><a name="l00224"></a><span class="lineno"> 224</span>&#160;</div> <div class="line"><a name="l00225"></a><span class="lineno"> 225</span>&#160; total += wsize;</div> <div class="line"><a name="l00226"></a><span class="lineno"> 226</span>&#160; <span class="keywordflow">if</span> (rsize != wsize) {</div> <div class="line"><a name="l00227"></a><span class="lineno"> 227</span>&#160; DEBUG(<span class="stringliteral">&quot;size mismatch. read:%zd, write:%zd&quot;</span>, rsize, wsize);</div> <div class="line"><a name="l00228"></a><span class="lineno"> 228</span>&#160; <span class="keywordflow">break</span>;</div> <div class="line"><a name="l00229"></a><span class="lineno"> 229</span>&#160; }</div> <div class="line"><a name="l00230"></a><span class="lineno"> 230</span>&#160; }</div> <div class="line"><a name="l00231"></a><span class="lineno"> 231</span>&#160;</div> <div class="line"><a name="l00232"></a><span class="lineno"> 232</span>&#160; <span class="keywordflow">if</span> (total &gt; 0)</div> <div class="line"><a name="l00233"></a><span class="lineno"> 233</span>&#160; <span class="keywordflow">return</span> total;</div> <div class="line"><a name="l00234"></a><span class="lineno"> 234</span>&#160; <span class="keywordflow">else</span> <span class="keywordflow">if</span> (errno == ETIMEDOUT)</div> <div class="line"><a name="l00235"></a><span class="lineno"> 235</span>&#160; <span class="keywordflow">return</span> 0;</div> <div class="line"><a name="l00236"></a><span class="lineno"> 236</span>&#160; <span class="keywordflow">return</span> -1;</div> <div class="line"><a name="l00237"></a><span class="lineno"> 237</span>&#160;}</div> <div class="line"><a name="l00238"></a><span class="lineno"> 238</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00239"></a><span class="lineno"> 239</span>&#160;<span class="comment">/**</span></div> <div class="line"><a name="l00240"></a><span class="lineno"> 240</span>&#160;<span class="comment"> * Read a line from a file descriptor into the buffer pointed to until either a</span></div> <div class="line"><a name="l00241"></a><span class="lineno"> 241</span>&#160;<span class="comment"> * terminating newline or EOF. New-line characters(CR, LF ) will not be stored</span></div> <div class="line"><a name="l00242"></a><span class="lineno"> 242</span>&#160;<span class="comment"> * into buffer.</span></div> <div class="line"><a name="l00243"></a><span class="lineno"> 243</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00244"></a><span class="lineno"> 244</span>&#160;<span class="comment"> * @param fd file descriptor</span></div> <div class="line"><a name="l00245"></a><span class="lineno"> 245</span>&#160;<span class="comment"> * @param buf data buffer pointer</span></div> <div class="line"><a name="l00246"></a><span class="lineno"> 246</span>&#160;<span class="comment"> * @param bufsize buffer size</span></div> <div class="line"><a name="l00247"></a><span class="lineno"> 247</span>&#160;<span class="comment"> * @param timeoutms wait timeout milliseconds. 0 for no wait, -1 for infinite</span></div> <div class="line"><a name="l00248"></a><span class="lineno"> 248</span>&#160;<span class="comment"> * wait</span></div> <div class="line"><a name="l00249"></a><span class="lineno"> 249</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00250"></a><span class="lineno"> 250</span>&#160;<span class="comment"> * @return the number of bytes read if successful, 0 on timeout, -1 for error.</span></div> <div class="line"><a name="l00251"></a><span class="lineno"> 251</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00252"></a><span class="lineno"> 252</span>&#160;<span class="comment"> * @note</span></div> <div class="line"><a name="l00253"></a><span class="lineno"> 253</span>&#160;<span class="comment"> * Be sure the return value does not mean the length of actual stored data.</span></div> <div class="line"><a name="l00254"></a><span class="lineno"> 254</span>&#160;<span class="comment"> * It means how many bytes are readed from the file descriptor,</span></div> <div class="line"><a name="l00255"></a><span class="lineno"> 255</span>&#160;<span class="comment"> * so the new-line characters will be counted, but not be stored.</span></div> <div class="line"><a name="l00256"></a><span class="lineno"> 256</span>&#160;<span class="comment"> */</span></div> <div class="line"><a name="l00257"></a><span class="lineno"><a class="line" href="qio_8c.html#ab7ce64cc8cd837de47c91d1bdcb17cf5"> 257</a></span>&#160;ssize_t <a class="code" href="qio_8c.html#ab7ce64cc8cd837de47c91d1bdcb17cf5">qio_gets</a>(<span class="keywordtype">int</span> fd, <span class="keywordtype">char</span> *buf, <span class="keywordtype">size_t</span> bufsize, <span class="keywordtype">int</span> timeoutms) {</div> <div class="line"><a name="l00258"></a><span class="lineno"> 258</span>&#160; <span class="keywordflow">if</span> (bufsize &lt;= 1)</div> <div class="line"><a name="l00259"></a><span class="lineno"> 259</span>&#160; <span class="keywordflow">return</span> -1;</div> <div class="line"><a name="l00260"></a><span class="lineno"> 260</span>&#160;</div> <div class="line"><a name="l00261"></a><span class="lineno"> 261</span>&#160; ssize_t readcnt = 0;</div> <div class="line"><a name="l00262"></a><span class="lineno"> 262</span>&#160; <span class="keywordtype">char</span> *ptr;</div> <div class="line"><a name="l00263"></a><span class="lineno"> 263</span>&#160; <span class="keywordflow">for</span> (ptr = buf; readcnt &lt; (bufsize - 1); ptr++) {</div> <div class="line"><a name="l00264"></a><span class="lineno"> 264</span>&#160; ssize_t rsize = <a class="code" href="qio_8c.html#aa34911362f1793ed1e744d3eb63500db">qio_read</a>(fd, ptr, 1, timeoutms);</div> <div class="line"><a name="l00265"></a><span class="lineno"> 265</span>&#160; <span class="keywordflow">if</span> (rsize != 1) {</div> <div class="line"><a name="l00266"></a><span class="lineno"> 266</span>&#160; <span class="keywordflow">if</span> (errno == EAGAIN || errno == EINPROGRESS) {</div> <div class="line"><a name="l00267"></a><span class="lineno"> 267</span>&#160; <span class="comment">// possible with non-block io</span></div> <div class="line"><a name="l00268"></a><span class="lineno"> 268</span>&#160; usleep(1);</div> <div class="line"><a name="l00269"></a><span class="lineno"> 269</span>&#160; <span class="keywordflow">continue</span>;</div> <div class="line"><a name="l00270"></a><span class="lineno"> 270</span>&#160; }</div> <div class="line"><a name="l00271"></a><span class="lineno"> 271</span>&#160; <span class="keywordflow">break</span>;</div> <div class="line"><a name="l00272"></a><span class="lineno"> 272</span>&#160; }</div> <div class="line"><a name="l00273"></a><span class="lineno"> 273</span>&#160;</div> <div class="line"><a name="l00274"></a><span class="lineno"> 274</span>&#160; readcnt++;</div> <div class="line"><a name="l00275"></a><span class="lineno"> 275</span>&#160; <span class="keywordflow">if</span> (*ptr == <span class="charliteral">&#39;\r&#39;</span>)</div> <div class="line"><a name="l00276"></a><span class="lineno"> 276</span>&#160; ptr--;</div> <div class="line"><a name="l00277"></a><span class="lineno"> 277</span>&#160; <span class="keywordflow">else</span> <span class="keywordflow">if</span> (*ptr == <span class="charliteral">&#39;\n&#39;</span>)</div> <div class="line"><a name="l00278"></a><span class="lineno"> 278</span>&#160; <span class="keywordflow">break</span>;</div> <div class="line"><a name="l00279"></a><span class="lineno"> 279</span>&#160; }</div> <div class="line"><a name="l00280"></a><span class="lineno"> 280</span>&#160;</div> <div class="line"><a name="l00281"></a><span class="lineno"> 281</span>&#160; *ptr = <span class="charliteral">&#39;\0&#39;</span>;</div> <div class="line"><a name="l00282"></a><span class="lineno"> 282</span>&#160;</div> <div class="line"><a name="l00283"></a><span class="lineno"> 283</span>&#160; <span class="keywordflow">if</span> (readcnt &gt; 0)</div> <div class="line"><a name="l00284"></a><span class="lineno"> 284</span>&#160; <span class="keywordflow">return</span> readcnt;</div> <div class="line"><a name="l00285"></a><span class="lineno"> 285</span>&#160; <span class="keywordflow">else</span> <span class="keywordflow">if</span> (errno == ETIMEDOUT)</div> <div class="line"><a name="l00286"></a><span class="lineno"> 286</span>&#160; <span class="keywordflow">return</span> 0;</div> <div class="line"><a name="l00287"></a><span class="lineno"> 287</span>&#160; <span class="keywordflow">return</span> -1;</div> <div class="line"><a name="l00288"></a><span class="lineno"> 288</span>&#160;}</div> <div class="line"><a name="l00289"></a><span class="lineno"> 289</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00290"></a><span class="lineno"> 290</span>&#160;<span class="comment">/**</span></div> <div class="line"><a name="l00291"></a><span class="lineno"> 291</span>&#160;<span class="comment"> * Writes the string and a trailing newline to file descriptor.</span></div> <div class="line"><a name="l00292"></a><span class="lineno"> 292</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00293"></a><span class="lineno"> 293</span>&#160;<span class="comment"> * @param fd file descriptor</span></div> <div class="line"><a name="l00294"></a><span class="lineno"> 294</span>&#160;<span class="comment"> * @param str string pointer</span></div> <div class="line"><a name="l00295"></a><span class="lineno"> 295</span>&#160;<span class="comment"> * @param timeoutms wait timeout milliseconds. 0 for no wait, -1 for infinite</span></div> <div class="line"><a name="l00296"></a><span class="lineno"> 296</span>&#160;<span class="comment"> * wait</span></div> <div class="line"><a name="l00297"></a><span class="lineno"> 297</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00298"></a><span class="lineno"> 298</span>&#160;<span class="comment"> * @return the number of bytes written including trailing newline characters</span></div> <div class="line"><a name="l00299"></a><span class="lineno"> 299</span>&#160;<span class="comment"> * if successful, 0 for timeout and -1 for errors.</span></div> <div class="line"><a name="l00300"></a><span class="lineno"> 300</span>&#160;<span class="comment"> */</span></div> <div class="line"><a name="l00301"></a><span class="lineno"><a class="line" href="qio_8c.html#a2c00200ce1766b2b81dafd9b9f20f6d0"> 301</a></span>&#160;ssize_t <a class="code" href="qio_8c.html#a2c00200ce1766b2b81dafd9b9f20f6d0">qio_puts</a>(<span class="keywordtype">int</span> fd, <span class="keyword">const</span> <span class="keywordtype">char</span> *str, <span class="keywordtype">int</span> timeoutms) {</div> <div class="line"><a name="l00302"></a><span class="lineno"> 302</span>&#160; <span class="keywordtype">size_t</span> strsize = strlen(str);</div> <div class="line"><a name="l00303"></a><span class="lineno"> 303</span>&#160; <span class="keywordtype">char</span> *newstr = (<span class="keywordtype">char</span> *) malloc(strsize + 1 + 1);</div> <div class="line"><a name="l00304"></a><span class="lineno"> 304</span>&#160; <span class="keywordflow">if</span> (newstr == NULL)</div> <div class="line"><a name="l00305"></a><span class="lineno"> 305</span>&#160; <span class="keywordflow">return</span> -1;</div> <div class="line"><a name="l00306"></a><span class="lineno"> 306</span>&#160; strncpy(newstr, str, strsize);</div> <div class="line"><a name="l00307"></a><span class="lineno"> 307</span>&#160; newstr[strsize] = <span class="charliteral">&#39;\n&#39;</span>;</div> <div class="line"><a name="l00308"></a><span class="lineno"> 308</span>&#160; newstr[strsize + 1] = <span class="charliteral">&#39;\0&#39;</span>;</div> <div class="line"><a name="l00309"></a><span class="lineno"> 309</span>&#160; ssize_t ret = <a class="code" href="qio_8c.html#a0645cf0a3bcfc79ee3829012243d46d8">qio_write</a>(fd, newstr, strsize + 1, timeoutms);</div> <div class="line"><a name="l00310"></a><span class="lineno"> 310</span>&#160; free(newstr);</div> <div class="line"><a name="l00311"></a><span class="lineno"> 311</span>&#160; <span class="keywordflow">return</span> ret;</div> <div class="line"><a name="l00312"></a><span class="lineno"> 312</span>&#160;}</div> <div class="line"><a name="l00313"></a><span class="lineno"> 313</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00314"></a><span class="lineno"> 314</span>&#160;<span class="comment">/**</span></div> <div class="line"><a name="l00315"></a><span class="lineno"> 315</span>&#160;<span class="comment"> * Formatted output to a file descriptor</span></div> <div class="line"><a name="l00316"></a><span class="lineno"> 316</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00317"></a><span class="lineno"> 317</span>&#160;<span class="comment"> * @param fd file descriptor</span></div> <div class="line"><a name="l00318"></a><span class="lineno"> 318</span>&#160;<span class="comment"> * @param timeoutms wait timeout milliseconds. 0 for no wait, -1 for infinite</span></div> <div class="line"><a name="l00319"></a><span class="lineno"> 319</span>&#160;<span class="comment"> * wait</span></div> <div class="line"><a name="l00320"></a><span class="lineno"> 320</span>&#160;<span class="comment"> * @param format format string</span></div> <div class="line"><a name="l00321"></a><span class="lineno"> 321</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00322"></a><span class="lineno"> 322</span>&#160;<span class="comment"> * @return the number of bytes written including trailing newline characters</span></div> <div class="line"><a name="l00323"></a><span class="lineno"> 323</span>&#160;<span class="comment"> * if successful, 0 for timeout and -1 for errors.</span></div> <div class="line"><a name="l00324"></a><span class="lineno"> 324</span>&#160;<span class="comment"> */</span></div> <div class="line"><a name="l00325"></a><span class="lineno"><a class="line" href="qio_8c.html#ad2b7b0e9eb6e217a36422de18570b4e3"> 325</a></span>&#160;ssize_t <a class="code" href="qio_8c.html#ad2b7b0e9eb6e217a36422de18570b4e3">qio_printf</a>(<span class="keywordtype">int</span> fd, <span class="keywordtype">int</span> timeoutms, <span class="keyword">const</span> <span class="keywordtype">char</span> *format, ...) {</div> <div class="line"><a name="l00326"></a><span class="lineno"> 326</span>&#160; <span class="keywordtype">char</span> *buf;</div> <div class="line"><a name="l00327"></a><span class="lineno"> 327</span>&#160; DYNAMIC_VSPRINTF(buf, format);</div> <div class="line"><a name="l00328"></a><span class="lineno"> 328</span>&#160; <span class="keywordflow">if</span> (buf == NULL)</div> <div class="line"><a name="l00329"></a><span class="lineno"> 329</span>&#160; <span class="keywordflow">return</span> -1;</div> <div class="line"><a name="l00330"></a><span class="lineno"> 330</span>&#160;</div> <div class="line"><a name="l00331"></a><span class="lineno"> 331</span>&#160; ssize_t ret = <a class="code" href="qio_8c.html#a0645cf0a3bcfc79ee3829012243d46d8">qio_write</a>(fd, buf, strlen(buf), timeoutms);</div> <div class="line"><a name="l00332"></a><span class="lineno"> 332</span>&#160; free(buf);</div> <div class="line"><a name="l00333"></a><span class="lineno"> 333</span>&#160;</div> <div class="line"><a name="l00334"></a><span class="lineno"> 334</span>&#160; <span class="keywordflow">return</span> ret;</div> <div class="line"><a name="l00335"></a><span class="lineno"> 335</span>&#160;}</div> <div class="ttc" id="qio_8c_html_ad2b7b0e9eb6e217a36422de18570b4e3"><div class="ttname"><a href="qio_8c.html#ad2b7b0e9eb6e217a36422de18570b4e3">qio_printf</a></div><div class="ttdeci">ssize_t qio_printf(int fd, int timeoutms, const char *format,...)</div><div class="ttdoc">Formatted output to a file descriptor. </div><div class="ttdef"><b>Definition:</b> <a href="qio_8c_source.html#l00325">qio.c:325</a></div></div> <div class="ttc" id="qio_8c_html_ab7ce64cc8cd837de47c91d1bdcb17cf5"><div class="ttname"><a href="qio_8c.html#ab7ce64cc8cd837de47c91d1bdcb17cf5">qio_gets</a></div><div class="ttdeci">ssize_t qio_gets(int fd, char *buf, size_t bufsize, int timeoutms)</div><div class="ttdoc">Read a line from a file descriptor into the buffer pointed to until either a terminating newline or E...</div><div class="ttdef"><b>Definition:</b> <a href="qio_8c_source.html#l00257">qio.c:257</a></div></div> <div class="ttc" id="qio_8c_html_a2c00200ce1766b2b81dafd9b9f20f6d0"><div class="ttname"><a href="qio_8c.html#a2c00200ce1766b2b81dafd9b9f20f6d0">qio_puts</a></div><div class="ttdeci">ssize_t qio_puts(int fd, const char *str, int timeoutms)</div><div class="ttdoc">Writes the string and a trailing newline to file descriptor. </div><div class="ttdef"><b>Definition:</b> <a href="qio_8c_source.html#l00301">qio.c:301</a></div></div> <div class="ttc" id="qio_8c_html_aafd34a0ab9f916ded37b1634cac3ab6a"><div class="ttname"><a href="qio_8c.html#aafd34a0ab9f916ded37b1634cac3ab6a">qio_send</a></div><div class="ttdeci">off_t qio_send(int outfd, int infd, off_t nbytes, int timeoutms)</div><div class="ttdoc">Transfer data between file descriptors. </div><div class="ttdef"><b>Definition:</b> <a href="qio_8c_source.html#l00199">qio.c:199</a></div></div> <div class="ttc" id="qio_8c_html_aa34911362f1793ed1e744d3eb63500db"><div class="ttname"><a href="qio_8c.html#aa34911362f1793ed1e744d3eb63500db">qio_read</a></div><div class="ttdeci">ssize_t qio_read(int fd, void *buf, size_t nbytes, int timeoutms)</div><div class="ttdoc">Read from a file descriptor. </div><div class="ttdef"><b>Definition:</b> <a href="qio_8c_source.html#l00118">qio.c:118</a></div></div> <div class="ttc" id="qio_8c_html_ac905811f0daa394ffef7beab68585a55"><div class="ttname"><a href="qio_8c.html#ac905811f0daa394ffef7beab68585a55">qio_wait_writable</a></div><div class="ttdeci">int qio_wait_writable(int fd, int timeoutms)</div><div class="ttdoc">Test &amp; wait until the file descriptor is ready for writing. </div><div class="ttdef"><b>Definition:</b> <a href="qio_8c_source.html#l00087">qio.c:87</a></div></div> <div class="ttc" id="qio_8c_html_a0645cf0a3bcfc79ee3829012243d46d8"><div class="ttname"><a href="qio_8c.html#a0645cf0a3bcfc79ee3829012243d46d8">qio_write</a></div><div class="ttdeci">ssize_t qio_write(int fd, const void *buf, size_t nbytes, int timeoutms)</div><div class="ttdoc">Write to a file descriptor. </div><div class="ttdef"><b>Definition:</b> <a href="qio_8c_source.html#l00159">qio.c:159</a></div></div> <div class="ttc" id="qio_8c_html_a8a695a43ebb605d243e56ad48937862e"><div class="ttname"><a href="qio_8c.html#a8a695a43ebb605d243e56ad48937862e">qio_wait_readable</a></div><div class="ttdeci">int qio_wait_readable(int fd, int timeoutms)</div><div class="ttdoc">Test &amp; wait until the file descriptor has readable data. </div><div class="ttdef"><b>Definition:</b> <a href="qio_8c_source.html#l00059">qio.c:59</a></div></div> </div><!-- fragment --></div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="dir_7b5d38f1875f1b693f62ca6a108a1129.html">utilities</a></li><li class="navelem"><a class="el" href="qio_8c.html">qio.c</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.6 </li> </ul> </div> </body> </html>
{ "pile_set_name": "Github" }
# Azure Service Bus Geo-disaster recovery To learn more about Azure Service Bus, please visit our [marketing page](https://azure.microsoft.com/en-us/services/service-bus/). To learn more about our Geo-DR feature in general please follow [this](https://docs.microsoft.com/azure/service-bus-messaging/service-bus-geo-dr) link. This sample shows how to: 1. Achieve Geo-DR for an Service Bus namespace. 2. Create a namespace with live metadata replication between two customer chosen regions This sample consists of three parts: 1. The main scenario showing management (Setup, failover, remove pairing) of new or existing namespaces sample can be found [here](https://github.com/Azure/azure-service-bus/tree/master/samples/DotNet/Microsoft.ServiceBus.Messaging/GeoDR/SBGeoDR2/SBGeoDR2) 2. The scenario in which you want to use an existing namespace name as alias can be found [here](https://github.com/Azure/azure-service-bus/tree/master/samples/DotNet/Microsoft.ServiceBus.Messaging/GeoDR/SBGeoDR2/SBGeoDR_existing_namespace_name). Make sure to thoroughly look through the comments as this diverges slightly from the main scenario. Examine both, App.config and Program.cs. ***Note:*** If you do not failover but just do break pairing, there is no need to execute delete alias as namespace name and alias are the same. If you do failover you would need to delete the alias if you would want to use the namespace outside of a DR setup. 3. A sample on how to access the alias connection string which can be found [here](https://github.com/Azure/azure-service-bus/tree/master/samples/DotNet/Microsoft.ServiceBus.Messaging/GeoDR/TestGeoDR/ConsoleApp1). ## Getting Started ### Prerequisites In order to get started using the sample (as it uses the Service Bus management libraries), you must authenticate with Azure Active Directory (AAD). This requires you to authenticate as a Service Principal, which provides access to your Azure resources. To obtain a service principal please do the following steps: 1. Go to the Azure Portal and select Azure Active Directory in the left menu. 2. Create a new Application under App registrations / + New application registration. 1. The application should be of type Web app / API. 2. You can provide any URL for your application as sign on URL. 3. Navigate to your newly created application 3. Application or AppId is the client Id. Note it down as you will need it for the sample. 4. Select keys and create a new key. Note down the Value as you won't be able to access it later. 5. Go back to the root Azure Active Directory and select properties. 1. Note down the Directory ID as this is your TenantId. 6. You must have ‘Owner’ permissions under Role for the resource group that you wish to run the sample on. Regardless if you want to use an existing namespace or create a new one, make sure to add the newly created application as owner under Access Control (IAM). For more information on creating a Service Principal, refer to the following articles: * [Use the Azure Portal to create Active Directory application and service principal that can access resources](https://docs.microsoft.com/azure/azure-resource-manager/resource-group-create-service-principal-portal) * [Use Azure PowerShell to create a service principal to access resources](https://docs.microsoft.com/azure/azure-resource-manager/resource-group-authenticate-service-principal) * [Use Azure CLI to create a service principal to access resources](https://docs.microsoft.com/azure/azure-resource-manager/resource-group-authenticate-service-principal-cli) <!-- The above articles helps you to obtain an AppId (ClientId), TenantId, and ClientSecret (Authentication Key), all of which are required to authenticate the management libraries. Finally, when creating your Active Directory application, if you do not have a sign-on URL to input in the create step, simply input any URL format string e.g. https://contoso.org/exampleapp --> ### Required NuGet packages 1. Microsoft.Azure.Management.ServiceBus 2. Microsoft.IdentityModel.Clients.ActiveDirectory - used to authenticate with AAD ### Running the sample 1. Please use Visual Studio 2017 2. Make sure all assemblies are in place. 2. Populate the regarding values in the App.config. 3. Build the solution. 4. Make sure to execute on Screen option A before any other option. The Geo DR actions could be * CreatePairing For creating a paired region. After this, you should see metadata (i.e. Queues, Topics and Subscriptions replicated to the secondary namespace). * FailOver Simulating a failover. After this action, the secondary namespace becomes the primary * BreakPairing For breaking the pairing between a primary and secondary namespace * DeleteAlias For deleting an alias, that contains information about the primary-secondary pairing * GetConnectionStrings In a Geo DR enabled namespace, the Service Bus should be accessed only via the alias. This is because, the alias can point to either the primary Service Bus or the failed over Service Bus. This way, the user does not have to adjust the connection strings in his/her apps to point to a different Service Bus in the case of a failover. The way to get the alias connection string is shown in a seperate console app which you can also use to test your newly geo paired namespaces. It can be found [here](https://github.com/Azure/azure-service-bus/tree/master/samples/DotNet/Microsoft.ServiceBus.Messaging/GeoDR/TestGeoDR). ***Note:*** The AAD access data for the GeoDR sample must also be used for the Test sample.
{ "pile_set_name": "Github" }
/* * SonarLint for Visual Studio * Copyright (C) 2016-2020 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Abstractions; using System.Linq; using EnvDTE; using SonarLint.VisualStudio.Core.Binding; using SonarLint.VisualStudio.Core.Helpers; using SonarLint.VisualStudio.Integration.Resources; namespace SonarLint.VisualStudio.Integration { internal class SolutionRuleSetsInformationProvider : ISolutionRuleSetsInformationProvider { public const char RuleSetDirectoriesValueSpliter = ';'; private readonly IServiceProvider serviceProvider; private readonly ILogger logger; private readonly IFileSystem fileSystem; public SolutionRuleSetsInformationProvider(IServiceProvider serviceProvider, ILogger logger) : this(serviceProvider, logger, new FileSystem()) { } internal SolutionRuleSetsInformationProvider(IServiceProvider serviceProvider, ILogger logger, IFileSystem fileSystem) { this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); this.fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); } public IEnumerable<RuleSetDeclaration> GetProjectRuleSetsDeclarations(Project project) { if (project == null) { throw new ArgumentNullException(nameof(project)); } return GetProjectRuleSetsDeclarationsIterator(project); } private IEnumerable<RuleSetDeclaration> GetProjectRuleSetsDeclarationsIterator(Project project) { /* This method walks through all of the available configurations (e.g. Debug, Release, Foo) and * attempts to fetch the values of a couple of properties from the project (CodeAnalysisRuleSet * and CodeAnalysisRuleSetDirectories). The collected data is put into a data object * and returned to the caller. The collected data includes the DTE Property object itself, which * is used later to update the ruleset value. * * TODO: consider refactoring. The code seems over-complicated: it finds the "ruleset" * property for all configurations, then backtracks to find the configuration, then looks * for the corresponding "ruleset directories" property. * Note: we are now fetching the "ruleset directories" property from the MSBuild project, * rather than through the DTE (the previous version of this code that used the DTE fails * for C# and VB projects that use the new project system). */ var declarations = new List<RuleSetDeclaration>(); var projectSystem = this.serviceProvider.GetService<IProjectSystemHelper>(); var ruleSetProperties = VsShellUtils.GetProjectProperties(project, Constants.CodeAnalysisRuleSetPropertyKey); Debug.Assert(ruleSetProperties != null); Debug.Assert(ruleSetProperties.All(p => p != null), "Not expecting nulls in the list of properties"); if (!ruleSetProperties.Any()) { logger.WriteLine(Strings.CouldNotFindCodeAnalysisRuleSetPropertyOnProject, project.UniqueName); } foreach (Property ruleSetProperty in ruleSetProperties) { string activationContext = TryGetPropertyConfiguration(ruleSetProperty)?.ConfigurationName ?? string.Empty; string ruleSetDirectoriesValue = projectSystem.GetProjectProperty(project, Constants.CodeAnalysisRuleSetDirectoriesPropertyKey, activationContext); string[] ruleSetDirectories = ruleSetDirectoriesValue?.Split(new[] { RuleSetDirectoriesValueSpliter }, StringSplitOptions.RemoveEmptyEntries) ?? new string[0]; string ruleSetValue = ruleSetProperty.Value as string; var declaration = new RuleSetDeclaration(project, ruleSetProperty, ruleSetValue, activationContext, ruleSetDirectories); declarations.Add(declaration); } return declarations; } public string GetSolutionSonarQubeRulesFolder(SonarLintMode bindingMode) { bindingMode.ThrowIfNotConnected(); var projectSystem = this.serviceProvider.GetService<IProjectSystemHelper>(); string solutionFullPath = projectSystem.GetCurrentActiveSolution()?.FullName; // Solution closed? if (string.IsNullOrWhiteSpace(solutionFullPath)) { return null; } string solutionRoot = Path.GetDirectoryName(solutionFullPath); string ruleSetDirectoryRoot = Path.Combine(solutionRoot, bindingMode == SonarLintMode.LegacyConnected ? Constants.LegacySonarQubeManagedFolderName : Constants.SonarlintManagedFolderName); return ruleSetDirectoryRoot; } public bool TryGetProjectRuleSetFilePath(RuleSetDeclaration declaration, out string fullFilePath) { if (string.IsNullOrWhiteSpace(declaration.RuleSetPath)) { fullFilePath = null; return false; } var options = new List<string>(); options.Add(declaration.RuleSetPath); // Might be a full path options.Add(PathHelper.ResolveRelativePath(declaration.RuleSetPath, declaration.RuleSetProjectFullName)); // Relative to project // Note: currently we don't search in rule set directories since we expect the project rule set // to be relative to the project. We can add this in the future if it will be needed. fullFilePath = options.FirstOrDefault(fileSystem.File.Exists); return !string.IsNullOrWhiteSpace(fullFilePath); } private static Configuration TryGetPropertyConfiguration(Property property) { Configuration configuration = property.Collection.Parent as Configuration; // Could be null if the one used is the Project level one. Debug.Assert(configuration != null || property.Collection.Parent is Project, $"Unexpected property parent type: {property.Collection.Parent.GetType().FullName}"); return configuration; } } }
{ "pile_set_name": "Github" }
// VirtThread.cpp #include "VirtThread.h" static THREAD_FUNC_DECL CoderThread(void *p) { for (;;) { CVirtThread *t = (CVirtThread *)p; t->StartEvent.Lock(); if (t->Exit) return 0; t->Execute(); t->FinishedEvent.Set(); } } WRes CVirtThread::Create() { RINOK(StartEvent.CreateIfNotCreated()); RINOK(FinishedEvent.CreateIfNotCreated()); StartEvent.Reset(); FinishedEvent.Reset(); Exit = false; if (Thread.IsCreated()) return S_OK; return Thread.Create(CoderThread, this); } void CVirtThread::Start() { Exit = false; StartEvent.Set(); } void CVirtThread::WaitThreadFinish() { Exit = true; if (StartEvent.IsCreated()) StartEvent.Set(); if (Thread.IsCreated()) { Thread.Wait(); Thread.Close(); } }
{ "pile_set_name": "Github" }
apiVersion: v1 kind: Pod metadata: name: website labels: app: website role: frontend spec: containers: - name: website image: nginx volumeMounts: - mountPath: /cache name: cache-volume ports: - containerPort: 80 volumes: - name: cache-volume emptyDir: {}
{ "pile_set_name": "Github" }
/* LiquidCrystal Library - Hello World Demonstrates the use a 16x2 LCD display. The LiquidCrystal library works with all LCD displays that are compatible with the Hitachi HD44780 driver. There are many of them out there, and you can usually tell them by the 16-pin interface. This sketch prints "Hello World!" to the LCD and shows the time. The circuit: * LCD RS pin to digital pin 12 * LCD Enable pin to digital pin 11 * LCD D4 pin to digital pin 5 * LCD D5 pin to digital pin 4 * LCD D6 pin to digital pin 3 * LCD D7 pin to digital pin 2 * LCD R/W pin to ground * 10K resistor: * ends to +5V and ground * wiper to LCD VO pin (pin 3) Library originally added 18 Apr 2008 by David A. Mellis library modified 5 Jul 2009 by Limor Fried (http://www.ladyada.net) example added 9 Jul 2009 by Tom Igoe modified 22 Nov 2010 by Tom Igoe This example code is in the public domain. http://www.arduino.cc/en/Tutorial/LiquidCrystal */ // include the library code: #include <LiquidCrystal.h> // initialize the library with the numbers of the interface pins LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { // set up the LCD's number of columns and rows: lcd.begin(16, 2); // Print a message to the LCD. lcd.print("hello, world!"); } void loop() { // set the cursor to column 0, line 1 // (note: line 1 is the second row, since counting begins with 0): lcd.setCursor(0, 1); // print the number of seconds since reset: lcd.print(millis()/1000); }
{ "pile_set_name": "Github" }
#include <stdio.h> #include <stdlib.h> #include "item.h" #include "list.h" link new(Item item) { link t = malloc(sizeof(link)); t->item = item; t->next = NULL; return t; } link list_init(Item item) { return new(item); } void list_insert_next(link last, Item item) { last->next = new(item); } void list_print(link t) { while (t != NULL) { print_item(t->item); t = t->next; } }
{ "pile_set_name": "Github" }
// (C) Copyright Gennadiy Rozental 2002-2008. // 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) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision: 49312 $ // // Description : simple minimal testing definitions and implementation // *************************************************************************** #ifndef BOOST_TEST_MINIMAL_HPP_071894GER #define BOOST_TEST_MINIMAL_HPP_071894GER #define BOOST_CHECK(exp) \ ( (exp) \ ? static_cast<void>(0) \ : boost::minimal_test::report_error(#exp,__FILE__,__LINE__, BOOST_CURRENT_FUNCTION) ) #define BOOST_REQUIRE(exp) \ ( (exp) \ ? static_cast<void>(0) \ : boost::minimal_test::report_critical_error(#exp,__FILE__,__LINE__,BOOST_CURRENT_FUNCTION)) #define BOOST_ERROR( msg_ ) \ boost::minimal_test::report_error( (msg_),__FILE__,__LINE__, BOOST_CURRENT_FUNCTION, true ) #define BOOST_FAIL( msg_ ) \ boost::minimal_test::report_critical_error( (msg_),__FILE__,__LINE__, BOOST_CURRENT_FUNCTION, true ) //____________________________________________________________________________// // Boost.Test #include <boost/test/detail/global_typedef.hpp> #include <boost/test/impl/execution_monitor.ipp> #include <boost/test/impl/debug.ipp> #include <boost/test/utils/class_properties.hpp> #include <boost/test/utils/basic_cstring/io.hpp> // Boost #include <boost/cstdlib.hpp> // for exit codes#include <boost/cstdlib.hpp> // for exit codes #include <boost/current_function.hpp> // for BOOST_CURRENT_FUNCTION // STL #include <iostream> // std::cerr, std::endl #include <string> // std::string #include <boost/test/detail/suppress_warnings.hpp> //____________________________________________________________________________// int test_main( int argc, char* argv[] ); // prototype for users test_main() namespace boost { namespace minimal_test { typedef boost::unit_test::const_string const_string; inline unit_test::counter_t& errors_counter() { static unit_test::counter_t ec = 0; return ec; } inline void report_error( const char* msg, const char* file, int line, const_string func_name, bool is_msg = false ) { ++errors_counter(); std::cerr << file << "(" << line << "): "; if( is_msg ) std::cerr << msg; else std::cerr << "test " << msg << " failed"; if( func_name != "(unknown)" ) std::cerr << " in function: '" << func_name << "'"; std::cerr << std::endl; } inline void report_critical_error( const char* msg, const char* file, int line, const_string func_name, bool is_msg = false ) { report_error( msg, file, line, func_name, is_msg ); throw boost::execution_aborted(); } class caller { public: // constructor caller( int argc, char** argv ) : m_argc( argc ), m_argv( argv ) {} // execution monitor hook implementation int operator()() { return test_main( m_argc, m_argv ); } private: // Data members int m_argc; char** m_argv; }; // monitor } // namespace minimal_test } // namespace boost //____________________________________________________________________________// int BOOST_TEST_CALL_DECL main( int argc, char* argv[] ) { using namespace boost::minimal_test; try { ::boost::execution_monitor ex_mon; int run_result = ex_mon.execute( caller( argc, argv ) ); BOOST_CHECK( run_result == 0 || run_result == boost::exit_success ); } catch( boost::execution_exception const& exex ) { if( exex.code() != boost::execution_exception::no_error ) BOOST_ERROR( (std::string( "exception \"" ). append( exex.what().begin(), exex.what().end() ). append( "\" caught" ) ).c_str() ); std::cerr << "\n**** Testing aborted."; } if( boost::minimal_test::errors_counter() != 0 ) { std::cerr << "\n**** " << errors_counter() << " error" << (errors_counter() > 1 ? "s" : "" ) << " detected\n"; return boost::exit_test_failure; } std::cout << "\n**** no errors detected\n"; return boost::exit_success; } //____________________________________________________________________________// #include <boost/test/detail/enable_warnings.hpp> #endif // BOOST_TEST_MINIMAL_HPP_071894GER
{ "pile_set_name": "Github" }
package zmq.socket.radiodish; import zmq.Ctx; import zmq.Msg; import zmq.Options; import zmq.SocketBase; import zmq.ZError; import zmq.ZMQ; import zmq.io.IOThread; import zmq.io.SessionBase; import zmq.io.net.Address; import zmq.pipe.Pipe; import zmq.socket.pubsub.Dist; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Radio extends SocketBase { private final Map<String, List<Pipe>> subscriptions; private final Dist dist; public Radio(Ctx parent, int tid, int sid) { super(parent, tid, sid, true); options.type = ZMQ.ZMQ_RADIO; subscriptions = new HashMap<>(); dist = new Dist(); } @Override public void xattachPipe(Pipe pipe, boolean subscribe2all, boolean isLocallyInitiated) { assert (pipe != null); pipe.setNoDelay(); dist.attach(pipe); xreadActivated(pipe); } @Override public void xreadActivated(Pipe pipe) { Msg msg = pipe.read(); while (msg != null) { if (msg.isJoin()) { List<Pipe> pipes = subscriptions.computeIfAbsent(msg.getGroup(), k -> new ArrayList<>()); pipes.add(pipe); } else if (msg.isLeave()) { List<Pipe> pipes = subscriptions.get(msg.getGroup()); if (pipes != null) { pipes.remove(pipe); if (pipes.isEmpty()) { subscriptions.remove(msg.getGroup()); } } } msg = pipe.read(); } } @Override public void xwriteActivated(Pipe pipe) { dist.activated(pipe); } @Override public void xpipeTerminated(Pipe pipe) { subscriptions.entrySet().removeIf(entry -> { entry.getValue().remove(pipe); return entry.getValue().isEmpty(); }); dist.terminated(pipe); } @Override protected boolean xsend(Msg msg) { // SERVER sockets do not allow multipart data (ZMQ_SNDMORE) if (msg.hasMore()) { errno.set(ZError.EINVAL); return false; } dist.unmatch(); List<Pipe> range = subscriptions.get(msg.getGroup()); if (range != null) { for (int i = 0; i < range.size(); i++) { dist.match(range.get(i)); } } dist.sendToMatching(msg); return true; } @Override protected Msg xrecv() { errno.set(ZError.ENOTSUP); // Messages cannot be received from RADIO socket. throw new UnsupportedOperationException(); } @Override protected boolean xhasIn() { return false; } @Override protected boolean xhasOut() { return dist.hasOut(); } public static class RadioSession extends SessionBase { enum State { GROUP, BODY } private State state; private Msg pending; public RadioSession(IOThread ioThread, boolean connect, SocketBase socket, final Options options, final Address addr) { super(ioThread, connect, socket, options, addr); state = State.GROUP; } @Override public boolean pushMsg(Msg msg) { if (msg.isCommand()) { byte commandNameSize = msg.get(0); if (msg.size() < commandNameSize + 1) { return super.pushMsg(msg); } byte[] data = msg.data(); String commandName = new String(data, 1, commandNameSize, StandardCharsets.US_ASCII); int groupLength; String group; Msg joinLeaveMsg = new Msg(); // Set the msg type to either JOIN or LEAVE if (commandName.equals("JOIN")) { groupLength = msg.size() - 5; group = new String(data, 5, groupLength, StandardCharsets.US_ASCII); joinLeaveMsg.initJoin(); } else if (commandName.equals("LEAVE")) { groupLength = msg.size() - 6; group = new String(data, 6, groupLength, StandardCharsets.US_ASCII); joinLeaveMsg.initLeave(); } // If it is not a JOIN or LEAVE just push the message else { return super.pushMsg(msg); } // Set the group joinLeaveMsg.setGroup(group); // Push the join or leave command msg = joinLeaveMsg; return super.pushMsg(msg); } return super.pushMsg(msg); } @Override protected Msg pullMsg() { Msg msg; switch (state) { case GROUP: pending = super.pullMsg(); if (pending == null) { return null; } // First frame is the group msg = new Msg(pending.getGroup().getBytes(StandardCharsets.US_ASCII)); msg.setFlags(Msg.MORE); // Next status is the body state = State.BODY; break; case BODY: msg = pending; state = State.GROUP; break; default: throw new IllegalStateException(); } return msg; } @Override protected void reset() { super.reset(); state = State.GROUP; } } }
{ "pile_set_name": "Github" }
--- title: Rosling.bubbles() subtitle: "The Bubbles Animation in Hans Roslings Talk" date: '2017-04-04' slug: Rosling-bubbles --- In Hans Rosling's attractive talk `Debunking third-world myths with the best stats you've ever seen`, he used a lot of bubble plots to illustrate trends behind the data over time. This function gives an imitation of those moving bubbles, besides, as this function is based on `symbols`, we can also make use of other symbols such as squares, rectangles, thermometers, etc. Suppose we have observations of $n$ individuals over `ani.options('nmax')` years. In this animation, the data of each year will be shown in the bubbles (symbols) plot; as time goes on, certain trends will be revealed (like those in Rosling's talk). Please note that the arrangement of the data for bubbles (symbols) should be a matrix like $A_{ijk}$ in which $i$ is the individual id (from 1 to n), $j$ denotes the $j$-th variable (from 1 to p) and $k$ indicates the time from 1 to `ani.options('nmax')`. And the length of `x` and `y` should be equal to the number of rows of this matrix. ```{r demo-a, cache=TRUE, interval=.2} library(animation) ani.options(interval = 0.2, nmax = 50) ## use default arguments (random numbers); you may try to find the real data par(mar = c(4, 4, 0.2, 0.2)) Rosling.bubbles() ``` ```{r demo-b, cache=TRUE, interval=.2} ## rectangles Rosling.bubbles(type = 'rectangles', data = matrix(abs(rnorm(50 * 10 * 2)), ncol = 2)) ```
{ "pile_set_name": "Github" }
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * diff.c: code for diff'ing two, three or four buffers. * * There are three ways to diff: * - Shell out to an external diff program, using files. * - Use the compiled-in xdiff library. * - Let 'diffexpr' do the work, using files. */ #include "vim.h" #include "xdiff/xdiff.h" #if defined(FEAT_DIFF) || defined(PROTO) static int diff_busy = FALSE; // using diff structs, don't change them static int diff_need_update = FALSE; // ex_diffupdate needs to be called // flags obtained from the 'diffopt' option #define DIFF_FILLER 0x001 // display filler lines #define DIFF_IBLANK 0x002 // ignore empty lines #define DIFF_ICASE 0x004 // ignore case #define DIFF_IWHITE 0x008 // ignore change in white space #define DIFF_IWHITEALL 0x010 // ignore all white space changes #define DIFF_IWHITEEOL 0x020 // ignore change in white space at EOL #define DIFF_HORIZONTAL 0x040 // horizontal splits #define DIFF_VERTICAL 0x080 // vertical splits #define DIFF_HIDDEN_OFF 0x100 // diffoff when hidden #define DIFF_INTERNAL 0x200 // use internal xdiff algorithm #define DIFF_CLOSE_OFF 0x400 // diffoff when closing window #define ALL_WHITE_DIFF (DIFF_IWHITE | DIFF_IWHITEALL | DIFF_IWHITEEOL) static int diff_flags = DIFF_INTERNAL | DIFF_FILLER | DIFF_CLOSE_OFF; static long diff_algorithm = 0; #define LBUFLEN 50 // length of line in diff file static int diff_a_works = MAYBE; // TRUE when "diff -a" works, FALSE when it // doesn't work, MAYBE when not checked yet #if defined(MSWIN) static int diff_bin_works = MAYBE; // TRUE when "diff --binary" works, FALSE // when it doesn't work, MAYBE when not // checked yet #endif // used for diff input typedef struct { char_u *din_fname; // used for external diff mmfile_t din_mmfile; // used for internal diff } diffin_T; // used for diff result typedef struct { char_u *dout_fname; // used for external diff garray_T dout_ga; // used for internal diff } diffout_T; // two diff inputs and one result typedef struct { diffin_T dio_orig; // original file input diffin_T dio_new; // new file input diffout_T dio_diff; // diff result int dio_internal; // using internal diff } diffio_T; static int diff_buf_idx(buf_T *buf); static int diff_buf_idx_tp(buf_T *buf, tabpage_T *tp); static void diff_mark_adjust_tp(tabpage_T *tp, int idx, linenr_T line1, linenr_T line2, long amount, long amount_after); static void diff_check_unchanged(tabpage_T *tp, diff_T *dp); static int diff_check_sanity(tabpage_T *tp, diff_T *dp); static int check_external_diff(diffio_T *diffio); static int diff_file(diffio_T *diffio); static int diff_equal_entry(diff_T *dp, int idx1, int idx2); static int diff_cmp(char_u *s1, char_u *s2); #ifdef FEAT_FOLDING static void diff_fold_update(diff_T *dp, int skip_idx); #endif static void diff_read(int idx_orig, int idx_new, diffout_T *fname); static void diff_copy_entry(diff_T *dprev, diff_T *dp, int idx_orig, int idx_new); static diff_T *diff_alloc_new(tabpage_T *tp, diff_T *dprev, diff_T *dp); static int parse_diff_ed(char_u *line, linenr_T *lnum_orig, long *count_orig, linenr_T *lnum_new, long *count_new); static int parse_diff_unified(char_u *line, linenr_T *lnum_orig, long *count_orig, linenr_T *lnum_new, long *count_new); static int xdiff_out(void *priv, mmbuffer_t *mb, int nbuf); /* * Called when deleting or unloading a buffer: No longer make a diff with it. */ void diff_buf_delete(buf_T *buf) { int i; tabpage_T *tp; FOR_ALL_TABPAGES(tp) { i = diff_buf_idx_tp(buf, tp); if (i != DB_COUNT) { tp->tp_diffbuf[i] = NULL; tp->tp_diff_invalid = TRUE; if (tp == curtab) diff_redraw(TRUE); } } } /* * Check if the current buffer should be added to or removed from the list of * diff buffers. */ void diff_buf_adjust(win_T *win) { win_T *wp; int i; if (!win->w_p_diff) { // When there is no window showing a diff for this buffer, remove // it from the diffs. FOR_ALL_WINDOWS(wp) if (wp->w_buffer == win->w_buffer && wp->w_p_diff) break; if (wp == NULL) { i = diff_buf_idx(win->w_buffer); if (i != DB_COUNT) { curtab->tp_diffbuf[i] = NULL; curtab->tp_diff_invalid = TRUE; diff_redraw(TRUE); } } } else diff_buf_add(win->w_buffer); } /* * Add a buffer to make diffs for. * Call this when a new buffer is being edited in the current window where * 'diff' is set. * Marks the current buffer as being part of the diff and requiring updating. * This must be done before any autocmd, because a command may use info * about the screen contents. */ void diff_buf_add(buf_T *buf) { int i; if (diff_buf_idx(buf) != DB_COUNT) return; // It's already there. for (i = 0; i < DB_COUNT; ++i) if (curtab->tp_diffbuf[i] == NULL) { curtab->tp_diffbuf[i] = buf; curtab->tp_diff_invalid = TRUE; diff_redraw(TRUE); return; } semsg(_("E96: Cannot diff more than %d buffers"), DB_COUNT); } /* * Remove all buffers to make diffs for. */ static void diff_buf_clear(void) { int i; for (i = 0; i < DB_COUNT; ++i) if (curtab->tp_diffbuf[i] != NULL) { curtab->tp_diffbuf[i] = NULL; curtab->tp_diff_invalid = TRUE; diff_redraw(TRUE); } } /* * Find buffer "buf" in the list of diff buffers for the current tab page. * Return its index or DB_COUNT if not found. */ static int diff_buf_idx(buf_T *buf) { int idx; for (idx = 0; idx < DB_COUNT; ++idx) if (curtab->tp_diffbuf[idx] == buf) break; return idx; } /* * Find buffer "buf" in the list of diff buffers for tab page "tp". * Return its index or DB_COUNT if not found. */ static int diff_buf_idx_tp(buf_T *buf, tabpage_T *tp) { int idx; for (idx = 0; idx < DB_COUNT; ++idx) if (tp->tp_diffbuf[idx] == buf) break; return idx; } /* * Mark the diff info involving buffer "buf" as invalid, it will be updated * when info is requested. */ void diff_invalidate(buf_T *buf) { tabpage_T *tp; int i; FOR_ALL_TABPAGES(tp) { i = diff_buf_idx_tp(buf, tp); if (i != DB_COUNT) { tp->tp_diff_invalid = TRUE; if (tp == curtab) diff_redraw(TRUE); } } } /* * Called by mark_adjust(): update line numbers in "curbuf". */ void diff_mark_adjust( linenr_T line1, linenr_T line2, long amount, long amount_after) { int idx; tabpage_T *tp; // Handle all tab pages that use the current buffer in a diff. FOR_ALL_TABPAGES(tp) { idx = diff_buf_idx_tp(curbuf, tp); if (idx != DB_COUNT) diff_mark_adjust_tp(tp, idx, line1, line2, amount, amount_after); } } /* * Update line numbers in tab page "tp" for "curbuf" with index "idx". * This attempts to update the changes as much as possible: * When inserting/deleting lines outside of existing change blocks, create a * new change block and update the line numbers in following blocks. * When inserting/deleting lines in existing change blocks, update them. */ static void diff_mark_adjust_tp( tabpage_T *tp, int idx, linenr_T line1, linenr_T line2, long amount, long amount_after) { diff_T *dp; diff_T *dprev; diff_T *dnext; int i; int inserted, deleted; int n, off; linenr_T last; linenr_T lnum_deleted = line1; // lnum of remaining deletion int check_unchanged; if (diff_internal()) { // Will update diffs before redrawing. Set _invalid to update the // diffs themselves, set _update to also update folds properly just // before redrawing. // Do update marks here, it is needed for :%diffput. tp->tp_diff_invalid = TRUE; tp->tp_diff_update = TRUE; } if (line2 == MAXLNUM) { // mark_adjust(99, MAXLNUM, 9, 0): insert lines inserted = amount; deleted = 0; } else if (amount_after > 0) { // mark_adjust(99, 98, MAXLNUM, 9): a change that inserts lines inserted = amount_after; deleted = 0; } else { // mark_adjust(98, 99, MAXLNUM, -2): delete lines inserted = 0; deleted = -amount_after; } dprev = NULL; dp = tp->tp_first_diff; for (;;) { // If the change is after the previous diff block and before the next // diff block, thus not touching an existing change, create a new diff // block. Don't do this when ex_diffgetput() is busy. if ((dp == NULL || dp->df_lnum[idx] - 1 > line2 || (line2 == MAXLNUM && dp->df_lnum[idx] > line1)) && (dprev == NULL || dprev->df_lnum[idx] + dprev->df_count[idx] < line1) && !diff_busy) { dnext = diff_alloc_new(tp, dprev, dp); if (dnext == NULL) return; dnext->df_lnum[idx] = line1; dnext->df_count[idx] = inserted; for (i = 0; i < DB_COUNT; ++i) if (tp->tp_diffbuf[i] != NULL && i != idx) { if (dprev == NULL) dnext->df_lnum[i] = line1; else dnext->df_lnum[i] = line1 + (dprev->df_lnum[i] + dprev->df_count[i]) - (dprev->df_lnum[idx] + dprev->df_count[idx]); dnext->df_count[i] = deleted; } } // if at end of the list, quit if (dp == NULL) break; /* * Check for these situations: * 1 2 3 * 1 2 3 * line1 2 3 4 5 * 2 3 4 5 * 2 3 4 5 * line2 2 3 4 5 * 3 5 6 * 3 5 6 */ // compute last line of this change last = dp->df_lnum[idx] + dp->df_count[idx] - 1; // 1. change completely above line1: nothing to do if (last >= line1 - 1) { // 6. change below line2: only adjust for amount_after; also when // "deleted" became zero when deleted all lines between two diffs if (dp->df_lnum[idx] - (deleted + inserted != 0) > line2) { if (amount_after == 0) break; // nothing left to change dp->df_lnum[idx] += amount_after; } else { check_unchanged = FALSE; // 2. 3. 4. 5.: inserted/deleted lines touching this diff. if (deleted > 0) { if (dp->df_lnum[idx] >= line1) { off = dp->df_lnum[idx] - lnum_deleted; if (last <= line2) { // 4. delete all lines of diff if (dp->df_next != NULL && dp->df_next->df_lnum[idx] - 1 <= line2) { // delete continues in next diff, only do // lines until that one n = dp->df_next->df_lnum[idx] - lnum_deleted; deleted -= n; n -= dp->df_count[idx]; lnum_deleted = dp->df_next->df_lnum[idx]; } else n = deleted - dp->df_count[idx]; dp->df_count[idx] = 0; } else { // 5. delete lines at or just before top of diff n = off; dp->df_count[idx] -= line2 - dp->df_lnum[idx] + 1; check_unchanged = TRUE; } dp->df_lnum[idx] = line1; } else { off = 0; if (last < line2) { // 2. delete at end of diff dp->df_count[idx] -= last - lnum_deleted + 1; if (dp->df_next != NULL && dp->df_next->df_lnum[idx] - 1 <= line2) { // delete continues in next diff, only do // lines until that one n = dp->df_next->df_lnum[idx] - 1 - last; deleted -= dp->df_next->df_lnum[idx] - lnum_deleted; lnum_deleted = dp->df_next->df_lnum[idx]; } else n = line2 - last; check_unchanged = TRUE; } else { // 3. delete lines inside the diff n = 0; dp->df_count[idx] -= deleted; } } for (i = 0; i < DB_COUNT; ++i) if (tp->tp_diffbuf[i] != NULL && i != idx) { dp->df_lnum[i] -= off; dp->df_count[i] += n; } } else { if (dp->df_lnum[idx] <= line1) { // inserted lines somewhere in this diff dp->df_count[idx] += inserted; check_unchanged = TRUE; } else // inserted lines somewhere above this diff dp->df_lnum[idx] += inserted; } if (check_unchanged) // Check if inserted lines are equal, may reduce the // size of the diff. TODO: also check for equal lines // in the middle and perhaps split the block. diff_check_unchanged(tp, dp); } } // check if this block touches the previous one, may merge them. if (dprev != NULL && dprev->df_lnum[idx] + dprev->df_count[idx] == dp->df_lnum[idx]) { for (i = 0; i < DB_COUNT; ++i) if (tp->tp_diffbuf[i] != NULL) dprev->df_count[i] += dp->df_count[i]; dprev->df_next = dp->df_next; vim_free(dp); dp = dprev->df_next; } else { // Advance to next entry. dprev = dp; dp = dp->df_next; } } dprev = NULL; dp = tp->tp_first_diff; while (dp != NULL) { // All counts are zero, remove this entry. for (i = 0; i < DB_COUNT; ++i) if (tp->tp_diffbuf[i] != NULL && dp->df_count[i] != 0) break; if (i == DB_COUNT) { dnext = dp->df_next; vim_free(dp); dp = dnext; if (dprev == NULL) tp->tp_first_diff = dnext; else dprev->df_next = dnext; } else { // Advance to next entry. dprev = dp; dp = dp->df_next; } } if (tp == curtab) { // Don't redraw right away, this updates the diffs, which can be slow. need_diff_redraw = TRUE; // Need to recompute the scroll binding, may remove or add filler // lines (e.g., when adding lines above w_topline). But it's slow when // making many changes, postpone until redrawing. diff_need_scrollbind = TRUE; } } /* * Allocate a new diff block and link it between "dprev" and "dp". */ static diff_T * diff_alloc_new(tabpage_T *tp, diff_T *dprev, diff_T *dp) { diff_T *dnew; dnew = ALLOC_ONE(diff_T); if (dnew != NULL) { dnew->df_next = dp; if (dprev == NULL) tp->tp_first_diff = dnew; else dprev->df_next = dnew; } return dnew; } /* * Check if the diff block "dp" can be made smaller for lines at the start and * end that are equal. Called after inserting lines. * This may result in a change where all buffers have zero lines, the caller * must take care of removing it. */ static void diff_check_unchanged(tabpage_T *tp, diff_T *dp) { int i_org; int i_new; int off_org, off_new; char_u *line_org; int dir = FORWARD; // Find the first buffers, use it as the original, compare the other // buffer lines against this one. for (i_org = 0; i_org < DB_COUNT; ++i_org) if (tp->tp_diffbuf[i_org] != NULL) break; if (i_org == DB_COUNT) // safety check return; if (diff_check_sanity(tp, dp) == FAIL) return; // First check lines at the top, then at the bottom. off_org = 0; off_new = 0; for (;;) { // Repeat until a line is found which is different or the number of // lines has become zero. while (dp->df_count[i_org] > 0) { // Copy the line, the next ml_get() will invalidate it. if (dir == BACKWARD) off_org = dp->df_count[i_org] - 1; line_org = vim_strsave(ml_get_buf(tp->tp_diffbuf[i_org], dp->df_lnum[i_org] + off_org, FALSE)); if (line_org == NULL) return; for (i_new = i_org + 1; i_new < DB_COUNT; ++i_new) { if (tp->tp_diffbuf[i_new] == NULL) continue; if (dir == BACKWARD) off_new = dp->df_count[i_new] - 1; // if other buffer doesn't have this line, it was inserted if (off_new < 0 || off_new >= dp->df_count[i_new]) break; if (diff_cmp(line_org, ml_get_buf(tp->tp_diffbuf[i_new], dp->df_lnum[i_new] + off_new, FALSE)) != 0) break; } vim_free(line_org); // Stop when a line isn't equal in all diff buffers. if (i_new != DB_COUNT) break; // Line matched in all buffers, remove it from the diff. for (i_new = i_org; i_new < DB_COUNT; ++i_new) if (tp->tp_diffbuf[i_new] != NULL) { if (dir == FORWARD) ++dp->df_lnum[i_new]; --dp->df_count[i_new]; } } if (dir == BACKWARD) break; dir = BACKWARD; } } /* * Check if a diff block doesn't contain invalid line numbers. * This can happen when the diff program returns invalid results. */ static int diff_check_sanity(tabpage_T *tp, diff_T *dp) { int i; for (i = 0; i < DB_COUNT; ++i) if (tp->tp_diffbuf[i] != NULL) if (dp->df_lnum[i] + dp->df_count[i] - 1 > tp->tp_diffbuf[i]->b_ml.ml_line_count) return FAIL; return OK; } /* * Mark all diff buffers in the current tab page for redraw. */ void diff_redraw( int dofold) // also recompute the folds { win_T *wp; int n; need_diff_redraw = FALSE; FOR_ALL_WINDOWS(wp) if (wp->w_p_diff) { redraw_win_later(wp, SOME_VALID); #ifdef FEAT_FOLDING if (dofold && foldmethodIsDiff(wp)) foldUpdateAll(wp); #endif // A change may have made filler lines invalid, need to take care // of that for other windows. n = diff_check(wp, wp->w_topline); if ((wp != curwin && wp->w_topfill > 0) || n > 0) { if (wp->w_topfill > n) wp->w_topfill = (n < 0 ? 0 : n); else if (n > 0 && n > wp->w_topfill) wp->w_topfill = n; check_topfill(wp, FALSE); } } } static void clear_diffin(diffin_T *din) { if (din->din_fname == NULL) { vim_free(din->din_mmfile.ptr); din->din_mmfile.ptr = NULL; } else mch_remove(din->din_fname); } static void clear_diffout(diffout_T *dout) { if (dout->dout_fname == NULL) ga_clear_strings(&dout->dout_ga); else mch_remove(dout->dout_fname); } /* * Write buffer "buf" to a memory buffer. * Return FAIL for failure. */ static int diff_write_buffer(buf_T *buf, diffin_T *din) { linenr_T lnum; char_u *s; long len = 0; char_u *ptr; // xdiff requires one big block of memory with all the text. for (lnum = 1; lnum <= buf->b_ml.ml_line_count; ++lnum) len += (long)STRLEN(ml_get_buf(buf, lnum, FALSE)) + 1; ptr = alloc(len); if (ptr == NULL) { // Allocating memory failed. This can happen, because we try to read // the whole buffer text into memory. Set the failed flag, the diff // will be retried with external diff. The flag is never reset. buf->b_diff_failed = TRUE; if (p_verbose > 0) { verbose_enter(); smsg(_("Not enough memory to use internal diff for buffer \"%s\""), buf->b_fname); verbose_leave(); } return FAIL; } din->din_mmfile.ptr = (char *)ptr; din->din_mmfile.size = len; len = 0; for (lnum = 1; lnum <= buf->b_ml.ml_line_count; ++lnum) { for (s = ml_get_buf(buf, lnum, FALSE); *s != NUL; ) { if (diff_flags & DIFF_ICASE) { int c; int orig_len; char_u cbuf[MB_MAXBYTES + 1]; // xdiff doesn't support ignoring case, fold-case the text. c = PTR2CHAR(s); c = enc_utf8 ? utf_fold(c) : MB_TOLOWER(c); orig_len = mb_ptr2len(s); if (mb_char2bytes(c, cbuf) != orig_len) // TODO: handle byte length difference mch_memmove(ptr + len, s, orig_len); else mch_memmove(ptr + len, cbuf, orig_len); s += orig_len; len += orig_len; } else ptr[len++] = *s++; } ptr[len++] = NL; } return OK; } /* * Write buffer "buf" to file or memory buffer. * Return FAIL for failure. */ static int diff_write(buf_T *buf, diffin_T *din) { int r; char_u *save_ff; int save_lockmarks; if (din->din_fname == NULL) return diff_write_buffer(buf, din); // Always use 'fileformat' set to "unix". save_ff = buf->b_p_ff; buf->b_p_ff = vim_strsave((char_u *)FF_UNIX); save_lockmarks = cmdmod.lockmarks; // Writing the buffer is an implementation detail of performing the diff, // so it shouldn't update the '[ and '] marks. cmdmod.lockmarks = TRUE; r = buf_write(buf, din->din_fname, NULL, (linenr_T)1, buf->b_ml.ml_line_count, NULL, FALSE, FALSE, FALSE, TRUE); cmdmod.lockmarks = save_lockmarks; free_string_option(buf->b_p_ff); buf->b_p_ff = save_ff; return r; } /* * Update the diffs for all buffers involved. */ static void diff_try_update( diffio_T *dio, int idx_orig, exarg_T *eap) // "eap" can be NULL { buf_T *buf; int idx_new; if (dio->dio_internal) { ga_init2(&dio->dio_diff.dout_ga, sizeof(char *), 1000); } else { // We need three temp file names. dio->dio_orig.din_fname = vim_tempname('o', TRUE); dio->dio_new.din_fname = vim_tempname('n', TRUE); dio->dio_diff.dout_fname = vim_tempname('d', TRUE); if (dio->dio_orig.din_fname == NULL || dio->dio_new.din_fname == NULL || dio->dio_diff.dout_fname == NULL) goto theend; } // Check external diff is actually working. if (!dio->dio_internal && check_external_diff(dio) == FAIL) goto theend; // :diffupdate! if (eap != NULL && eap->forceit) for (idx_new = idx_orig; idx_new < DB_COUNT; ++idx_new) { buf = curtab->tp_diffbuf[idx_new]; if (buf_valid(buf)) buf_check_timestamp(buf, FALSE); } // Write the first buffer to a tempfile or mmfile_t. buf = curtab->tp_diffbuf[idx_orig]; if (diff_write(buf, &dio->dio_orig) == FAIL) goto theend; // Make a difference between the first buffer and every other. for (idx_new = idx_orig + 1; idx_new < DB_COUNT; ++idx_new) { buf = curtab->tp_diffbuf[idx_new]; if (buf == NULL || buf->b_ml.ml_mfp == NULL) continue; // skip buffer that isn't loaded // Write the other buffer and diff with the first one. if (diff_write(buf, &dio->dio_new) == FAIL) continue; if (diff_file(dio) == FAIL) continue; // Read the diff output and add each entry to the diff list. diff_read(idx_orig, idx_new, &dio->dio_diff); clear_diffin(&dio->dio_new); clear_diffout(&dio->dio_diff); } clear_diffin(&dio->dio_orig); theend: vim_free(dio->dio_orig.din_fname); vim_free(dio->dio_new.din_fname); vim_free(dio->dio_diff.dout_fname); } /* * Return TRUE if the options are set to use the internal diff library. * Note that if the internal diff failed for one of the buffers, the external * diff will be used anyway. */ int diff_internal(void) { return (diff_flags & DIFF_INTERNAL) != 0 #ifdef FEAT_EVAL && *p_dex == NUL #endif ; } /* * Return TRUE if the internal diff failed for one of the diff buffers. */ static int diff_internal_failed(void) { int idx; // Only need to do something when there is another buffer. for (idx = 0; idx < DB_COUNT; ++idx) if (curtab->tp_diffbuf[idx] != NULL && curtab->tp_diffbuf[idx]->b_diff_failed) return TRUE; return FALSE; } /* * Completely update the diffs for the buffers involved. * When using the external "diff" command the buffers are written to a file, * also for unmodified buffers (the file could have been produced by * autocommands, e.g. the netrw plugin). */ void ex_diffupdate(exarg_T *eap) // "eap" can be NULL { int idx_orig; int idx_new; diffio_T diffio; int had_diffs = curtab->tp_first_diff != NULL; if (diff_busy) { diff_need_update = TRUE; return; } // Delete all diffblocks. diff_clear(curtab); curtab->tp_diff_invalid = FALSE; // Use the first buffer as the original text. for (idx_orig = 0; idx_orig < DB_COUNT; ++idx_orig) if (curtab->tp_diffbuf[idx_orig] != NULL) break; if (idx_orig == DB_COUNT) goto theend; // Only need to do something when there is another buffer. for (idx_new = idx_orig + 1; idx_new < DB_COUNT; ++idx_new) if (curtab->tp_diffbuf[idx_new] != NULL) break; if (idx_new == DB_COUNT) goto theend; // Only use the internal method if it did not fail for one of the buffers. vim_memset(&diffio, 0, sizeof(diffio)); diffio.dio_internal = diff_internal() && !diff_internal_failed(); diff_try_update(&diffio, idx_orig, eap); if (diffio.dio_internal && diff_internal_failed()) { // Internal diff failed, use external diff instead. vim_memset(&diffio, 0, sizeof(diffio)); diff_try_update(&diffio, idx_orig, eap); } // force updating cursor position on screen curwin->w_valid_cursor.lnum = 0; theend: // A redraw is needed if there were diffs and they were cleared, or there // are diffs now, which means they got updated. if (had_diffs || curtab->tp_first_diff != NULL) { diff_redraw(TRUE); apply_autocmds(EVENT_DIFFUPDATED, NULL, NULL, FALSE, curbuf); } } /* * Do a quick test if "diff" really works. Otherwise it looks like there * are no differences. Can't use the return value, it's non-zero when * there are differences. */ static int check_external_diff(diffio_T *diffio) { FILE *fd; int ok; int io_error = FALSE; // May try twice, first with "-a" and then without. for (;;) { ok = FALSE; fd = mch_fopen((char *)diffio->dio_orig.din_fname, "w"); if (fd == NULL) io_error = TRUE; else { if (fwrite("line1\n", (size_t)6, (size_t)1, fd) != 1) io_error = TRUE; fclose(fd); fd = mch_fopen((char *)diffio->dio_new.din_fname, "w"); if (fd == NULL) io_error = TRUE; else { if (fwrite("line2\n", (size_t)6, (size_t)1, fd) != 1) io_error = TRUE; fclose(fd); fd = NULL; if (diff_file(diffio) == OK) fd = mch_fopen((char *)diffio->dio_diff.dout_fname, "r"); if (fd == NULL) io_error = TRUE; else { char_u linebuf[LBUFLEN]; for (;;) { // There must be a line that contains "1c1". if (vim_fgets(linebuf, LBUFLEN, fd)) break; if (STRNCMP(linebuf, "1c1", 3) == 0) ok = TRUE; } fclose(fd); } mch_remove(diffio->dio_diff.dout_fname); mch_remove(diffio->dio_new.din_fname); } mch_remove(diffio->dio_orig.din_fname); } #ifdef FEAT_EVAL // When using 'diffexpr' break here. if (*p_dex != NUL) break; #endif #if defined(MSWIN) // If the "-a" argument works, also check if "--binary" works. if (ok && diff_a_works == MAYBE && diff_bin_works == MAYBE) { diff_a_works = TRUE; diff_bin_works = TRUE; continue; } if (!ok && diff_a_works == TRUE && diff_bin_works == TRUE) { // Tried --binary, but it failed. "-a" works though. diff_bin_works = FALSE; ok = TRUE; } #endif // If we checked if "-a" works already, break here. if (diff_a_works != MAYBE) break; diff_a_works = ok; // If "-a" works break here, otherwise retry without "-a". if (ok) break; } if (!ok) { if (io_error) emsg(_("E810: Cannot read or write temp files")); emsg(_("E97: Cannot create diffs")); diff_a_works = MAYBE; #if defined(MSWIN) diff_bin_works = MAYBE; #endif return FAIL; } return OK; } /* * Invoke the xdiff function. */ static int diff_file_internal(diffio_T *diffio) { xpparam_t param; xdemitconf_t emit_cfg; xdemitcb_t emit_cb; vim_memset(&param, 0, sizeof(param)); vim_memset(&emit_cfg, 0, sizeof(emit_cfg)); vim_memset(&emit_cb, 0, sizeof(emit_cb)); param.flags = diff_algorithm; if (diff_flags & DIFF_IWHITE) param.flags |= XDF_IGNORE_WHITESPACE_CHANGE; if (diff_flags & DIFF_IWHITEALL) param.flags |= XDF_IGNORE_WHITESPACE; if (diff_flags & DIFF_IWHITEEOL) param.flags |= XDF_IGNORE_WHITESPACE_AT_EOL; if (diff_flags & DIFF_IBLANK) param.flags |= XDF_IGNORE_BLANK_LINES; emit_cfg.ctxlen = 0; // don't need any diff_context here emit_cb.priv = &diffio->dio_diff; emit_cb.outf = xdiff_out; if (xdl_diff(&diffio->dio_orig.din_mmfile, &diffio->dio_new.din_mmfile, &param, &emit_cfg, &emit_cb) < 0) { emsg(_("E960: Problem creating the internal diff")); return FAIL; } return OK; } /* * Make a diff between files "tmp_orig" and "tmp_new", results in "tmp_diff". * return OK or FAIL; */ static int diff_file(diffio_T *dio) { char_u *cmd; size_t len; char_u *tmp_orig = dio->dio_orig.din_fname; char_u *tmp_new = dio->dio_new.din_fname; char_u *tmp_diff = dio->dio_diff.dout_fname; #ifdef FEAT_EVAL if (*p_dex != NUL) { // Use 'diffexpr' to generate the diff file. eval_diff(tmp_orig, tmp_new, tmp_diff); return OK; } else #endif // Use xdiff for generating the diff. if (dio->dio_internal) { return diff_file_internal(dio); } else { len = STRLEN(tmp_orig) + STRLEN(tmp_new) + STRLEN(tmp_diff) + STRLEN(p_srr) + 27; cmd = alloc(len); if (cmd == NULL) return FAIL; // We don't want $DIFF_OPTIONS to get in the way. if (getenv("DIFF_OPTIONS")) vim_setenv((char_u *)"DIFF_OPTIONS", (char_u *)""); // Build the diff command and execute it. Always use -a, binary // differences are of no use. Ignore errors, diff returns // non-zero when differences have been found. vim_snprintf((char *)cmd, len, "diff %s%s%s%s%s%s%s%s %s", diff_a_works == FALSE ? "" : "-a ", #if defined(MSWIN) diff_bin_works == TRUE ? "--binary " : "", #else "", #endif (diff_flags & DIFF_IWHITE) ? "-b " : "", (diff_flags & DIFF_IWHITEALL) ? "-w " : "", (diff_flags & DIFF_IWHITEEOL) ? "-Z " : "", (diff_flags & DIFF_IBLANK) ? "-B " : "", (diff_flags & DIFF_ICASE) ? "-i " : "", tmp_orig, tmp_new); append_redir(cmd, (int)len, p_srr, tmp_diff); block_autocmds(); // avoid ShellCmdPost stuff (void)call_shell(cmd, SHELL_FILTER|SHELL_SILENT|SHELL_DOOUT); unblock_autocmds(); vim_free(cmd); return OK; } } /* * Create a new version of a file from the current buffer and a diff file. * The buffer is written to a file, also for unmodified buffers (the file * could have been produced by autocommands, e.g. the netrw plugin). */ void ex_diffpatch(exarg_T *eap) { char_u *tmp_orig; // name of original temp file char_u *tmp_new; // name of patched temp file char_u *buf = NULL; size_t buflen; win_T *old_curwin = curwin; char_u *newname = NULL; // name of patched file buffer #ifdef UNIX char_u dirbuf[MAXPATHL]; char_u *fullname = NULL; #endif #ifdef FEAT_BROWSE char_u *browseFile = NULL; int browse_flag = cmdmod.browse; #endif stat_T st; char_u *esc_name = NULL; #ifdef FEAT_BROWSE if (cmdmod.browse) { browseFile = do_browse(0, (char_u *)_("Patch file"), eap->arg, NULL, NULL, (char_u *)_(BROWSE_FILTER_ALL_FILES), NULL); if (browseFile == NULL) return; // operation cancelled eap->arg = browseFile; cmdmod.browse = FALSE; // don't let do_ecmd() browse again } #endif // We need two temp file names. tmp_orig = vim_tempname('o', FALSE); tmp_new = vim_tempname('n', FALSE); if (tmp_orig == NULL || tmp_new == NULL) goto theend; // Write the current buffer to "tmp_orig". if (buf_write(curbuf, tmp_orig, NULL, (linenr_T)1, curbuf->b_ml.ml_line_count, NULL, FALSE, FALSE, FALSE, TRUE) == FAIL) goto theend; #ifdef UNIX // Get the absolute path of the patchfile, changing directory below. fullname = FullName_save(eap->arg, FALSE); #endif esc_name = vim_strsave_shellescape( # ifdef UNIX fullname != NULL ? fullname : # endif eap->arg, TRUE, TRUE); if (esc_name == NULL) goto theend; buflen = STRLEN(tmp_orig) + STRLEN(esc_name) + STRLEN(tmp_new) + 16; buf = alloc(buflen); if (buf == NULL) goto theend; #ifdef UNIX // Temporarily chdir to /tmp, to avoid patching files in the current // directory when the patch file contains more than one patch. When we // have our own temp dir use that instead, it will be cleaned up when we // exit (any .rej files created). Don't change directory if we can't // return to the current. if (mch_dirname(dirbuf, MAXPATHL) != OK || mch_chdir((char *)dirbuf) != 0) dirbuf[0] = NUL; else { # ifdef TEMPDIRNAMES if (vim_tempdir != NULL) vim_ignored = mch_chdir((char *)vim_tempdir); else # endif vim_ignored = mch_chdir("/tmp"); shorten_fnames(TRUE); } #endif #ifdef FEAT_EVAL if (*p_pex != NUL) // Use 'patchexpr' to generate the new file. eval_patch(tmp_orig, # ifdef UNIX fullname != NULL ? fullname : # endif eap->arg, tmp_new); else #endif { // Build the patch command and execute it. Ignore errors. Switch to // cooked mode to allow the user to respond to prompts. vim_snprintf((char *)buf, buflen, "patch -o %s %s < %s", tmp_new, tmp_orig, esc_name); block_autocmds(); // Avoid ShellCmdPost stuff (void)call_shell(buf, SHELL_FILTER | SHELL_COOKED); unblock_autocmds(); } #ifdef UNIX if (dirbuf[0] != NUL) { if (mch_chdir((char *)dirbuf) != 0) emsg(_(e_prev_dir)); shorten_fnames(TRUE); } #endif // patch probably has written over the screen redraw_later(CLEAR); // Delete any .orig or .rej file created. STRCPY(buf, tmp_new); STRCAT(buf, ".orig"); mch_remove(buf); STRCPY(buf, tmp_new); STRCAT(buf, ".rej"); mch_remove(buf); // Only continue if the output file was created. if (mch_stat((char *)tmp_new, &st) < 0 || st.st_size == 0) emsg(_("E816: Cannot read patch output")); else { if (curbuf->b_fname != NULL) { newname = vim_strnsave(curbuf->b_fname, (int)(STRLEN(curbuf->b_fname) + 4)); if (newname != NULL) STRCAT(newname, ".new"); } #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif // don't use a new tab page, each tab page has its own diffs cmdmod.tab = 0; if (win_split(0, (diff_flags & DIFF_VERTICAL) ? WSP_VERT : 0) != FAIL) { // Pretend it was a ":split fname" command eap->cmdidx = CMD_split; eap->arg = tmp_new; do_exedit(eap, old_curwin); // check that split worked and editing tmp_new if (curwin != old_curwin && win_valid(old_curwin)) { // Set 'diff', 'scrollbind' on and 'wrap' off. diff_win_options(curwin, TRUE); diff_win_options(old_curwin, TRUE); if (newname != NULL) { // do a ":file filename.new" on the patched buffer eap->arg = newname; ex_file(eap); // Do filetype detection with the new name. if (au_has_group((char_u *)"filetypedetect")) do_cmdline_cmd((char_u *)":doau filetypedetect BufRead"); } } } } theend: if (tmp_orig != NULL) mch_remove(tmp_orig); vim_free(tmp_orig); if (tmp_new != NULL) mch_remove(tmp_new); vim_free(tmp_new); vim_free(newname); vim_free(buf); #ifdef UNIX vim_free(fullname); #endif vim_free(esc_name); #ifdef FEAT_BROWSE vim_free(browseFile); cmdmod.browse = browse_flag; #endif } /* * Split the window and edit another file, setting options to show the diffs. */ void ex_diffsplit(exarg_T *eap) { win_T *old_curwin = curwin; bufref_T old_curbuf; set_bufref(&old_curbuf, curbuf); #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif // Need to compute w_fraction when no redraw happened yet. validate_cursor(); set_fraction(curwin); // don't use a new tab page, each tab page has its own diffs cmdmod.tab = 0; if (win_split(0, (diff_flags & DIFF_VERTICAL) ? WSP_VERT : 0) != FAIL) { // Pretend it was a ":split fname" command eap->cmdidx = CMD_split; curwin->w_p_diff = TRUE; do_exedit(eap, old_curwin); if (curwin != old_curwin) // split must have worked { // Set 'diff', 'scrollbind' on and 'wrap' off. diff_win_options(curwin, TRUE); if (win_valid(old_curwin)) { diff_win_options(old_curwin, TRUE); if (bufref_valid(&old_curbuf)) // Move the cursor position to that of the old window. curwin->w_cursor.lnum = diff_get_corresponding_line( old_curbuf.br_buf, old_curwin->w_cursor.lnum); } // Now that lines are folded scroll to show the cursor at the same // relative position. scroll_to_fraction(curwin, curwin->w_height); } } } /* * Set options to show diffs for the current window. */ void ex_diffthis(exarg_T *eap UNUSED) { // Set 'diff', 'scrollbind' on and 'wrap' off. diff_win_options(curwin, TRUE); } static void set_diff_option(win_T *wp, int value) { win_T *old_curwin = curwin; curwin = wp; curbuf = curwin->w_buffer; ++curbuf_lock; set_option_value((char_u *)"diff", (long)value, NULL, OPT_LOCAL); --curbuf_lock; curwin = old_curwin; curbuf = curwin->w_buffer; } /* * Set options in window "wp" for diff mode. */ void diff_win_options( win_T *wp, int addbuf) // Add buffer to diff. { # ifdef FEAT_FOLDING win_T *old_curwin = curwin; // close the manually opened folds curwin = wp; newFoldLevel(); curwin = old_curwin; # endif // Use 'scrollbind' and 'cursorbind' when available if (!wp->w_p_diff) wp->w_p_scb_save = wp->w_p_scb; wp->w_p_scb = TRUE; if (!wp->w_p_diff) wp->w_p_crb_save = wp->w_p_crb; wp->w_p_crb = TRUE; if (!wp->w_p_diff) wp->w_p_wrap_save = wp->w_p_wrap; wp->w_p_wrap = FALSE; # ifdef FEAT_FOLDING if (!wp->w_p_diff) { if (wp->w_p_diff_saved) free_string_option(wp->w_p_fdm_save); wp->w_p_fdm_save = vim_strsave(wp->w_p_fdm); } set_string_option_direct_in_win(wp, (char_u *)"fdm", -1, (char_u *)"diff", OPT_LOCAL|OPT_FREE, 0); if (!wp->w_p_diff) { wp->w_p_fdc_save = wp->w_p_fdc; wp->w_p_fen_save = wp->w_p_fen; wp->w_p_fdl_save = wp->w_p_fdl; } wp->w_p_fdc = diff_foldcolumn; wp->w_p_fen = TRUE; wp->w_p_fdl = 0; foldUpdateAll(wp); // make sure topline is not halfway a fold changed_window_setting_win(wp); # endif if (vim_strchr(p_sbo, 'h') == NULL) do_cmdline_cmd((char_u *)"set sbo+=hor"); // Save the current values, to be restored in ex_diffoff(). wp->w_p_diff_saved = TRUE; set_diff_option(wp, TRUE); if (addbuf) diff_buf_add(wp->w_buffer); redraw_win_later(wp, NOT_VALID); } /* * Set options not to show diffs. For the current window or all windows. * Only in the current tab page. */ void ex_diffoff(exarg_T *eap) { win_T *wp; int diffwin = FALSE; FOR_ALL_WINDOWS(wp) { if (eap->forceit ? wp->w_p_diff : wp == curwin) { // Set 'diff' off. If option values were saved in // diff_win_options(), restore the ones whose settings seem to have // been left over from diff mode. set_diff_option(wp, FALSE); if (wp->w_p_diff_saved) { if (wp->w_p_scb) wp->w_p_scb = wp->w_p_scb_save; if (wp->w_p_crb) wp->w_p_crb = wp->w_p_crb_save; if (!wp->w_p_wrap) wp->w_p_wrap = wp->w_p_wrap_save; #ifdef FEAT_FOLDING free_string_option(wp->w_p_fdm); wp->w_p_fdm = vim_strsave( *wp->w_p_fdm_save ? wp->w_p_fdm_save : (char_u*)"manual"); if (wp->w_p_fdc == diff_foldcolumn) wp->w_p_fdc = wp->w_p_fdc_save; if (wp->w_p_fdl == 0) wp->w_p_fdl = wp->w_p_fdl_save; // Only restore 'foldenable' when 'foldmethod' is not // "manual", otherwise we continue to show the diff folds. if (wp->w_p_fen) wp->w_p_fen = foldmethodIsManual(wp) ? FALSE : wp->w_p_fen_save; foldUpdateAll(wp); #endif } // remove filler lines wp->w_topfill = 0; // make sure topline is not halfway a fold and cursor is // invalidated changed_window_setting_win(wp); // Note: 'sbo' is not restored, it's a global option. diff_buf_adjust(wp); } diffwin |= wp->w_p_diff; } // Also remove hidden buffers from the list. if (eap->forceit) diff_buf_clear(); if (!diffwin) { diff_need_update = FALSE; curtab->tp_diff_invalid = FALSE; curtab->tp_diff_update = FALSE; diff_clear(curtab); } // Remove "hor" from from 'scrollopt' if there are no diff windows left. if (!diffwin && vim_strchr(p_sbo, 'h') != NULL) do_cmdline_cmd((char_u *)"set sbo-=hor"); } /* * Read the diff output and add each entry to the diff list. */ static void diff_read( int idx_orig, // idx of original file int idx_new, // idx of new file diffout_T *dout) // diff output { FILE *fd = NULL; int line_idx = 0; diff_T *dprev = NULL; diff_T *dp = curtab->tp_first_diff; diff_T *dn, *dpl; char_u linebuf[LBUFLEN]; // only need to hold the diff line char_u *line; long off; int i; linenr_T lnum_orig, lnum_new; long count_orig, count_new; int notset = TRUE; // block "*dp" not set yet enum { DIFF_ED, DIFF_UNIFIED, DIFF_NONE } diffstyle = DIFF_NONE; if (dout->dout_fname == NULL) { diffstyle = DIFF_UNIFIED; } else { fd = mch_fopen((char *)dout->dout_fname, "r"); if (fd == NULL) { emsg(_("E98: Cannot read diff output")); return; } } for (;;) { if (fd == NULL) { if (line_idx >= dout->dout_ga.ga_len) break; // did last line line = ((char_u **)dout->dout_ga.ga_data)[line_idx++]; } else { if (vim_fgets(linebuf, LBUFLEN, fd)) break; // end of file line = linebuf; } if (diffstyle == DIFF_NONE) { // Determine diff style. // ed like diff looks like this: // {first}[,{last}]c{first}[,{last}] // {first}a{first}[,{last}] // {first}[,{last}]d{first} // // unified diff looks like this: // --- file1 2018-03-20 13:23:35.783153140 +0100 // +++ file2 2018-03-20 13:23:41.183156066 +0100 // @@ -1,3 +1,5 @@ if (isdigit(*line)) diffstyle = DIFF_ED; else if ((STRNCMP(line, "@@ ", 3) == 0)) diffstyle = DIFF_UNIFIED; else if ((STRNCMP(line, "--- ", 4) == 0) && (vim_fgets(linebuf, LBUFLEN, fd) == 0) && (STRNCMP(line, "+++ ", 4) == 0) && (vim_fgets(linebuf, LBUFLEN, fd) == 0) && (STRNCMP(line, "@@ ", 3) == 0)) diffstyle = DIFF_UNIFIED; else // Format not recognized yet, skip over this line. Cygwin diff // may put a warning at the start of the file. continue; } if (diffstyle == DIFF_ED) { if (!isdigit(*line)) continue; // not the start of a diff block if (parse_diff_ed(line, &lnum_orig, &count_orig, &lnum_new, &count_new) == FAIL) continue; } else if (diffstyle == DIFF_UNIFIED) { if (STRNCMP(line, "@@ ", 3) != 0) continue; // not the start of a diff block if (parse_diff_unified(line, &lnum_orig, &count_orig, &lnum_new, &count_new) == FAIL) continue; } else { emsg(_("E959: Invalid diff format.")); break; } // Go over blocks before the change, for which orig and new are equal. // Copy blocks from orig to new. while (dp != NULL && lnum_orig > dp->df_lnum[idx_orig] + dp->df_count[idx_orig]) { if (notset) diff_copy_entry(dprev, dp, idx_orig, idx_new); dprev = dp; dp = dp->df_next; notset = TRUE; } if (dp != NULL && lnum_orig <= dp->df_lnum[idx_orig] + dp->df_count[idx_orig] && lnum_orig + count_orig >= dp->df_lnum[idx_orig]) { // New block overlaps with existing block(s). // First find last block that overlaps. for (dpl = dp; dpl->df_next != NULL; dpl = dpl->df_next) if (lnum_orig + count_orig < dpl->df_next->df_lnum[idx_orig]) break; // If the newly found block starts before the old one, set the // start back a number of lines. off = dp->df_lnum[idx_orig] - lnum_orig; if (off > 0) { for (i = idx_orig; i < idx_new; ++i) if (curtab->tp_diffbuf[i] != NULL) dp->df_lnum[i] -= off; dp->df_lnum[idx_new] = lnum_new; dp->df_count[idx_new] = count_new; } else if (notset) { // new block inside existing one, adjust new block dp->df_lnum[idx_new] = lnum_new + off; dp->df_count[idx_new] = count_new - off; } else // second overlap of new block with existing block dp->df_count[idx_new] += count_new - count_orig + dpl->df_lnum[idx_orig] + dpl->df_count[idx_orig] - (dp->df_lnum[idx_orig] + dp->df_count[idx_orig]); // Adjust the size of the block to include all the lines to the // end of the existing block or the new diff, whatever ends last. off = (lnum_orig + count_orig) - (dpl->df_lnum[idx_orig] + dpl->df_count[idx_orig]); if (off < 0) { // new change ends in existing block, adjust the end if not // done already if (notset) dp->df_count[idx_new] += -off; off = 0; } for (i = idx_orig; i < idx_new; ++i) if (curtab->tp_diffbuf[i] != NULL) dp->df_count[i] = dpl->df_lnum[i] + dpl->df_count[i] - dp->df_lnum[i] + off; // Delete the diff blocks that have been merged into one. dn = dp->df_next; dp->df_next = dpl->df_next; while (dn != dp->df_next) { dpl = dn->df_next; vim_free(dn); dn = dpl; } } else { // Allocate a new diffblock. dp = diff_alloc_new(curtab, dprev, dp); if (dp == NULL) goto done; dp->df_lnum[idx_orig] = lnum_orig; dp->df_count[idx_orig] = count_orig; dp->df_lnum[idx_new] = lnum_new; dp->df_count[idx_new] = count_new; // Set values for other buffers, these must be equal to the // original buffer, otherwise there would have been a change // already. for (i = idx_orig + 1; i < idx_new; ++i) if (curtab->tp_diffbuf[i] != NULL) diff_copy_entry(dprev, dp, idx_orig, i); } notset = FALSE; // "*dp" has been set } // for remaining diff blocks orig and new are equal while (dp != NULL) { if (notset) diff_copy_entry(dprev, dp, idx_orig, idx_new); dprev = dp; dp = dp->df_next; notset = TRUE; } done: if (fd != NULL) fclose(fd); } /* * Copy an entry at "dp" from "idx_orig" to "idx_new". */ static void diff_copy_entry( diff_T *dprev, diff_T *dp, int idx_orig, int idx_new) { long off; if (dprev == NULL) off = 0; else off = (dprev->df_lnum[idx_orig] + dprev->df_count[idx_orig]) - (dprev->df_lnum[idx_new] + dprev->df_count[idx_new]); dp->df_lnum[idx_new] = dp->df_lnum[idx_orig] - off; dp->df_count[idx_new] = dp->df_count[idx_orig]; } /* * Clear the list of diffblocks for tab page "tp". */ void diff_clear(tabpage_T *tp) { diff_T *p, *next_p; for (p = tp->tp_first_diff; p != NULL; p = next_p) { next_p = p->df_next; vim_free(p); } tp->tp_first_diff = NULL; } /* * Check diff status for line "lnum" in buffer "buf": * Returns 0 for nothing special * Returns -1 for a line that should be highlighted as changed. * Returns -2 for a line that should be highlighted as added/deleted. * Returns > 0 for inserting that many filler lines above it (never happens * when 'diffopt' doesn't contain "filler"). * This should only be used for windows where 'diff' is set. */ int diff_check(win_T *wp, linenr_T lnum) { int idx; // index in tp_diffbuf[] for this buffer diff_T *dp; int maxcount; int i; buf_T *buf = wp->w_buffer; int cmp; if (curtab->tp_diff_invalid) ex_diffupdate(NULL); // update after a big change if (curtab->tp_first_diff == NULL || !wp->w_p_diff) // no diffs at all return 0; // safety check: "lnum" must be a buffer line if (lnum < 1 || lnum > buf->b_ml.ml_line_count + 1) return 0; idx = diff_buf_idx(buf); if (idx == DB_COUNT) return 0; // no diffs for buffer "buf" #ifdef FEAT_FOLDING // A closed fold never has filler lines. if (hasFoldingWin(wp, lnum, NULL, NULL, TRUE, NULL)) return 0; #endif // search for a change that includes "lnum" in the list of diffblocks. for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) if (lnum <= dp->df_lnum[idx] + dp->df_count[idx]) break; if (dp == NULL || lnum < dp->df_lnum[idx]) return 0; if (lnum < dp->df_lnum[idx] + dp->df_count[idx]) { int zero = FALSE; // Changed or inserted line. If the other buffers have a count of // zero, the lines were inserted. If the other buffers have the same // count, check if the lines are identical. cmp = FALSE; for (i = 0; i < DB_COUNT; ++i) if (i != idx && curtab->tp_diffbuf[i] != NULL) { if (dp->df_count[i] == 0) zero = TRUE; else { if (dp->df_count[i] != dp->df_count[idx]) return -1; // nr of lines changed. cmp = TRUE; } } if (cmp) { // Compare all lines. If they are equal the lines were inserted // in some buffers, deleted in others, but not changed. for (i = 0; i < DB_COUNT; ++i) if (i != idx && curtab->tp_diffbuf[i] != NULL && dp->df_count[i] != 0) if (!diff_equal_entry(dp, idx, i)) return -1; } // If there is no buffer with zero lines then there is no difference // any longer. Happens when making a change (or undo) that removes // the difference. Can't remove the entry here, we might be halfway // updating the window. Just report the text as unchanged. Other // windows might still show the change though. if (zero == FALSE) return 0; return -2; } // If 'diffopt' doesn't contain "filler", return 0. if (!(diff_flags & DIFF_FILLER)) return 0; // Insert filler lines above the line just below the change. Will return // 0 when this buf had the max count. maxcount = 0; for (i = 0; i < DB_COUNT; ++i) if (curtab->tp_diffbuf[i] != NULL && dp->df_count[i] > maxcount) maxcount = dp->df_count[i]; return maxcount - dp->df_count[idx]; } /* * Compare two entries in diff "*dp" and return TRUE if they are equal. */ static int diff_equal_entry(diff_T *dp, int idx1, int idx2) { int i; char_u *line; int cmp; if (dp->df_count[idx1] != dp->df_count[idx2]) return FALSE; if (diff_check_sanity(curtab, dp) == FAIL) return FALSE; for (i = 0; i < dp->df_count[idx1]; ++i) { line = vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx1], dp->df_lnum[idx1] + i, FALSE)); if (line == NULL) return FALSE; cmp = diff_cmp(line, ml_get_buf(curtab->tp_diffbuf[idx2], dp->df_lnum[idx2] + i, FALSE)); vim_free(line); if (cmp != 0) return FALSE; } return TRUE; } /* * Compare the characters at "p1" and "p2". If they are equal (possibly * ignoring case) return TRUE and set "len" to the number of bytes. */ static int diff_equal_char(char_u *p1, char_u *p2, int *len) { int l = (*mb_ptr2len)(p1); if (l != (*mb_ptr2len)(p2)) return FALSE; if (l > 1) { if (STRNCMP(p1, p2, l) != 0 && (!enc_utf8 || !(diff_flags & DIFF_ICASE) || utf_fold(utf_ptr2char(p1)) != utf_fold(utf_ptr2char(p2)))) return FALSE; *len = l; } else { if ((*p1 != *p2) && (!(diff_flags & DIFF_ICASE) || TOLOWER_LOC(*p1) != TOLOWER_LOC(*p2))) return FALSE; *len = 1; } return TRUE; } /* * Compare strings "s1" and "s2" according to 'diffopt'. * Return non-zero when they are different. */ static int diff_cmp(char_u *s1, char_u *s2) { char_u *p1, *p2; int l; if ((diff_flags & DIFF_IBLANK) && (*skipwhite(s1) == NUL || *skipwhite(s2) == NUL)) return 0; if ((diff_flags & (DIFF_ICASE | ALL_WHITE_DIFF)) == 0) return STRCMP(s1, s2); if ((diff_flags & DIFF_ICASE) && !(diff_flags & ALL_WHITE_DIFF)) return MB_STRICMP(s1, s2); p1 = s1; p2 = s2; // Ignore white space changes and possibly ignore case. while (*p1 != NUL && *p2 != NUL) { if (((diff_flags & DIFF_IWHITE) && VIM_ISWHITE(*p1) && VIM_ISWHITE(*p2)) || ((diff_flags & DIFF_IWHITEALL) && (VIM_ISWHITE(*p1) || VIM_ISWHITE(*p2)))) { p1 = skipwhite(p1); p2 = skipwhite(p2); } else { if (!diff_equal_char(p1, p2, &l)) break; p1 += l; p2 += l; } } // Ignore trailing white space. p1 = skipwhite(p1); p2 = skipwhite(p2); if (*p1 != NUL || *p2 != NUL) return 1; return 0; } /* * Return the number of filler lines above "lnum". */ int diff_check_fill(win_T *wp, linenr_T lnum) { int n; // be quick when there are no filler lines if (!(diff_flags & DIFF_FILLER)) return 0; n = diff_check(wp, lnum); if (n <= 0) return 0; return n; } /* * Set the topline of "towin" to match the position in "fromwin", so that they * show the same diff'ed lines. */ void diff_set_topline(win_T *fromwin, win_T *towin) { buf_T *frombuf = fromwin->w_buffer; linenr_T lnum = fromwin->w_topline; int fromidx; int toidx; diff_T *dp; int max_count; int i; fromidx = diff_buf_idx(frombuf); if (fromidx == DB_COUNT) return; // safety check if (curtab->tp_diff_invalid) ex_diffupdate(NULL); // update after a big change towin->w_topfill = 0; // search for a change that includes "lnum" in the list of diffblocks. for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) if (lnum <= dp->df_lnum[fromidx] + dp->df_count[fromidx]) break; if (dp == NULL) { // After last change, compute topline relative to end of file; no // filler lines. towin->w_topline = towin->w_buffer->b_ml.ml_line_count - (frombuf->b_ml.ml_line_count - lnum); } else { // Find index for "towin". toidx = diff_buf_idx(towin->w_buffer); if (toidx == DB_COUNT) return; // safety check towin->w_topline = lnum + (dp->df_lnum[toidx] - dp->df_lnum[fromidx]); if (lnum >= dp->df_lnum[fromidx]) { // Inside a change: compute filler lines. With three or more // buffers we need to know the largest count. max_count = 0; for (i = 0; i < DB_COUNT; ++i) if (curtab->tp_diffbuf[i] != NULL && max_count < dp->df_count[i]) max_count = dp->df_count[i]; if (dp->df_count[toidx] == dp->df_count[fromidx]) { // same number of lines: use same filler count towin->w_topfill = fromwin->w_topfill; } else if (dp->df_count[toidx] > dp->df_count[fromidx]) { if (lnum == dp->df_lnum[fromidx] + dp->df_count[fromidx]) { // more lines in towin and fromwin doesn't show diff // lines, only filler lines if (max_count - fromwin->w_topfill >= dp->df_count[toidx]) { // towin also only shows filler lines towin->w_topline = dp->df_lnum[toidx] + dp->df_count[toidx]; towin->w_topfill = fromwin->w_topfill; } else // towin still has some diff lines to show towin->w_topline = dp->df_lnum[toidx] + max_count - fromwin->w_topfill; } } else if (towin->w_topline >= dp->df_lnum[toidx] + dp->df_count[toidx]) { // less lines in towin and no diff lines to show: compute // filler lines towin->w_topline = dp->df_lnum[toidx] + dp->df_count[toidx]; if (diff_flags & DIFF_FILLER) { if (lnum == dp->df_lnum[fromidx] + dp->df_count[fromidx]) // fromwin is also out of diff lines towin->w_topfill = fromwin->w_topfill; else // fromwin has some diff lines towin->w_topfill = dp->df_lnum[fromidx] + max_count - lnum; } } } } // safety check (if diff info gets outdated strange things may happen) towin->w_botfill = FALSE; if (towin->w_topline > towin->w_buffer->b_ml.ml_line_count) { towin->w_topline = towin->w_buffer->b_ml.ml_line_count; towin->w_botfill = TRUE; } if (towin->w_topline < 1) { towin->w_topline = 1; towin->w_topfill = 0; } // When w_topline changes need to recompute w_botline and cursor position invalidate_botline_win(towin); changed_line_abv_curs_win(towin); check_topfill(towin, FALSE); #ifdef FEAT_FOLDING (void)hasFoldingWin(towin, towin->w_topline, &towin->w_topline, NULL, TRUE, NULL); #endif } /* * This is called when 'diffopt' is changed. */ int diffopt_changed(void) { char_u *p; int diff_context_new = 6; int diff_flags_new = 0; int diff_foldcolumn_new = 2; long diff_algorithm_new = 0; long diff_indent_heuristic = 0; tabpage_T *tp; p = p_dip; while (*p != NUL) { if (STRNCMP(p, "filler", 6) == 0) { p += 6; diff_flags_new |= DIFF_FILLER; } else if (STRNCMP(p, "context:", 8) == 0 && VIM_ISDIGIT(p[8])) { p += 8; diff_context_new = getdigits(&p); } else if (STRNCMP(p, "iblank", 6) == 0) { p += 6; diff_flags_new |= DIFF_IBLANK; } else if (STRNCMP(p, "icase", 5) == 0) { p += 5; diff_flags_new |= DIFF_ICASE; } else if (STRNCMP(p, "iwhiteall", 9) == 0) { p += 9; diff_flags_new |= DIFF_IWHITEALL; } else if (STRNCMP(p, "iwhiteeol", 9) == 0) { p += 9; diff_flags_new |= DIFF_IWHITEEOL; } else if (STRNCMP(p, "iwhite", 6) == 0) { p += 6; diff_flags_new |= DIFF_IWHITE; } else if (STRNCMP(p, "horizontal", 10) == 0) { p += 10; diff_flags_new |= DIFF_HORIZONTAL; } else if (STRNCMP(p, "vertical", 8) == 0) { p += 8; diff_flags_new |= DIFF_VERTICAL; } else if (STRNCMP(p, "foldcolumn:", 11) == 0 && VIM_ISDIGIT(p[11])) { p += 11; diff_foldcolumn_new = getdigits(&p); } else if (STRNCMP(p, "hiddenoff", 9) == 0) { p += 9; diff_flags_new |= DIFF_HIDDEN_OFF; } else if (STRNCMP(p, "closeoff", 8) == 0) { p += 8; diff_flags_new |= DIFF_CLOSE_OFF; } else if (STRNCMP(p, "indent-heuristic", 16) == 0) { p += 16; diff_indent_heuristic = XDF_INDENT_HEURISTIC; } else if (STRNCMP(p, "internal", 8) == 0) { p += 8; diff_flags_new |= DIFF_INTERNAL; } else if (STRNCMP(p, "algorithm:", 10) == 0) { p += 10; if (STRNCMP(p, "myers", 5) == 0) { p += 5; diff_algorithm_new = 0; } else if (STRNCMP(p, "minimal", 7) == 0) { p += 7; diff_algorithm_new = XDF_NEED_MINIMAL; } else if (STRNCMP(p, "patience", 8) == 0) { p += 8; diff_algorithm_new = XDF_PATIENCE_DIFF; } else if (STRNCMP(p, "histogram", 9) == 0) { p += 9; diff_algorithm_new = XDF_HISTOGRAM_DIFF; } else return FAIL; } if (*p != ',' && *p != NUL) return FAIL; if (*p == ',') ++p; } diff_algorithm_new |= diff_indent_heuristic; // Can't have both "horizontal" and "vertical". if ((diff_flags_new & DIFF_HORIZONTAL) && (diff_flags_new & DIFF_VERTICAL)) return FAIL; // If flags were added or removed, or the algorithm was changed, need to // update the diff. if (diff_flags != diff_flags_new || diff_algorithm != diff_algorithm_new) FOR_ALL_TABPAGES(tp) tp->tp_diff_invalid = TRUE; diff_flags = diff_flags_new; diff_context = diff_context_new == 0 ? 1 : diff_context_new; diff_foldcolumn = diff_foldcolumn_new; diff_algorithm = diff_algorithm_new; diff_redraw(TRUE); // recompute the scroll binding with the new option value, may // remove or add filler lines check_scrollbind((linenr_T)0, 0L); return OK; } /* * Return TRUE if 'diffopt' contains "horizontal". */ int diffopt_horizontal(void) { return (diff_flags & DIFF_HORIZONTAL) != 0; } /* * Return TRUE if 'diffopt' contains "hiddenoff". */ int diffopt_hiddenoff(void) { return (diff_flags & DIFF_HIDDEN_OFF) != 0; } /* * Return TRUE if 'diffopt' contains "closeoff". */ int diffopt_closeoff(void) { return (diff_flags & DIFF_CLOSE_OFF) != 0; } /* * Find the difference within a changed line. * Returns TRUE if the line was added, no other buffer has it. */ int diff_find_change( win_T *wp, linenr_T lnum, int *startp, // first char of the change int *endp) // last char of the change { char_u *line_org; char_u *line_new; int i; int si_org, si_new; int ei_org, ei_new; diff_T *dp; int idx; int off; int added = TRUE; char_u *p1, *p2; int l; // Make a copy of the line, the next ml_get() will invalidate it. line_org = vim_strsave(ml_get_buf(wp->w_buffer, lnum, FALSE)); if (line_org == NULL) return FALSE; idx = diff_buf_idx(wp->w_buffer); if (idx == DB_COUNT) // cannot happen { vim_free(line_org); return FALSE; } // search for a change that includes "lnum" in the list of diffblocks. for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) if (lnum <= dp->df_lnum[idx] + dp->df_count[idx]) break; if (dp == NULL || diff_check_sanity(curtab, dp) == FAIL) { vim_free(line_org); return FALSE; } off = lnum - dp->df_lnum[idx]; for (i = 0; i < DB_COUNT; ++i) if (curtab->tp_diffbuf[i] != NULL && i != idx) { // Skip lines that are not in the other change (filler lines). if (off >= dp->df_count[i]) continue; added = FALSE; line_new = ml_get_buf(curtab->tp_diffbuf[i], dp->df_lnum[i] + off, FALSE); // Search for start of difference si_org = si_new = 0; while (line_org[si_org] != NUL) { if (((diff_flags & DIFF_IWHITE) && VIM_ISWHITE(line_org[si_org]) && VIM_ISWHITE(line_new[si_new])) || ((diff_flags & DIFF_IWHITEALL) && (VIM_ISWHITE(line_org[si_org]) || VIM_ISWHITE(line_new[si_new])))) { si_org = (int)(skipwhite(line_org + si_org) - line_org); si_new = (int)(skipwhite(line_new + si_new) - line_new); } else { if (!diff_equal_char(line_org + si_org, line_new + si_new, &l)) break; si_org += l; si_new += l; } } if (has_mbyte) { // Move back to first byte of character in both lines (may // have "nn^" in line_org and "n^ in line_new). si_org -= (*mb_head_off)(line_org, line_org + si_org); si_new -= (*mb_head_off)(line_new, line_new + si_new); } if (*startp > si_org) *startp = si_org; // Search for end of difference, if any. if (line_org[si_org] != NUL || line_new[si_new] != NUL) { ei_org = (int)STRLEN(line_org); ei_new = (int)STRLEN(line_new); while (ei_org >= *startp && ei_new >= si_new && ei_org >= 0 && ei_new >= 0) { if (((diff_flags & DIFF_IWHITE) && VIM_ISWHITE(line_org[ei_org]) && VIM_ISWHITE(line_new[ei_new])) || ((diff_flags & DIFF_IWHITEALL) && (VIM_ISWHITE(line_org[ei_org]) || VIM_ISWHITE(line_new[ei_new])))) { while (ei_org >= *startp && VIM_ISWHITE(line_org[ei_org])) --ei_org; while (ei_new >= si_new && VIM_ISWHITE(line_new[ei_new])) --ei_new; } else { p1 = line_org + ei_org; p2 = line_new + ei_new; p1 -= (*mb_head_off)(line_org, p1); p2 -= (*mb_head_off)(line_new, p2); if (!diff_equal_char(p1, p2, &l)) break; ei_org -= l; ei_new -= l; } } if (*endp < ei_org) *endp = ei_org; } } vim_free(line_org); return added; } #if defined(FEAT_FOLDING) || defined(PROTO) /* * Return TRUE if line "lnum" is not close to a diff block, this line should * be in a fold. * Return FALSE if there are no diff blocks at all in this window. */ int diff_infold(win_T *wp, linenr_T lnum) { int i; int idx = -1; int other = FALSE; diff_T *dp; // Return if 'diff' isn't set. if (!wp->w_p_diff) return FALSE; for (i = 0; i < DB_COUNT; ++i) { if (curtab->tp_diffbuf[i] == wp->w_buffer) idx = i; else if (curtab->tp_diffbuf[i] != NULL) other = TRUE; } // return here if there are no diffs in the window if (idx == -1 || !other) return FALSE; if (curtab->tp_diff_invalid) ex_diffupdate(NULL); // update after a big change // Return if there are no diff blocks. All lines will be folded. if (curtab->tp_first_diff == NULL) return TRUE; for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) { // If this change is below the line there can't be any further match. if (dp->df_lnum[idx] - diff_context > lnum) break; // If this change ends before the line we have a match. if (dp->df_lnum[idx] + dp->df_count[idx] + diff_context > lnum) return FALSE; } return TRUE; } #endif /* * "dp" and "do" commands. */ void nv_diffgetput(int put, long count) { exarg_T ea; char_u buf[30]; #ifdef FEAT_JOB_CHANNEL if (bt_prompt(curbuf)) { vim_beep(BO_OPER); return; } #endif if (count == 0) ea.arg = (char_u *)""; else { vim_snprintf((char *)buf, 30, "%ld", count); ea.arg = buf; } if (put) ea.cmdidx = CMD_diffput; else ea.cmdidx = CMD_diffget; ea.addr_count = 0; ea.line1 = curwin->w_cursor.lnum; ea.line2 = curwin->w_cursor.lnum; ex_diffgetput(&ea); } /* * ":diffget" * ":diffput" */ void ex_diffgetput(exarg_T *eap) { linenr_T lnum; int count; linenr_T off = 0; diff_T *dp; diff_T *dprev; diff_T *dfree; int idx_cur; int idx_other; int idx_from; int idx_to; int i; int added; char_u *p; aco_save_T aco; buf_T *buf; int start_skip, end_skip; int new_count; int buf_empty; int found_not_ma = FALSE; // Find the current buffer in the list of diff buffers. idx_cur = diff_buf_idx(curbuf); if (idx_cur == DB_COUNT) { emsg(_("E99: Current buffer is not in diff mode")); return; } if (*eap->arg == NUL) { // No argument: Find the other buffer in the list of diff buffers. for (idx_other = 0; idx_other < DB_COUNT; ++idx_other) if (curtab->tp_diffbuf[idx_other] != curbuf && curtab->tp_diffbuf[idx_other] != NULL) { if (eap->cmdidx != CMD_diffput || curtab->tp_diffbuf[idx_other]->b_p_ma) break; found_not_ma = TRUE; } if (idx_other == DB_COUNT) { if (found_not_ma) emsg(_("E793: No other buffer in diff mode is modifiable")); else emsg(_("E100: No other buffer in diff mode")); return; } // Check that there isn't a third buffer in the list for (i = idx_other + 1; i < DB_COUNT; ++i) if (curtab->tp_diffbuf[i] != curbuf && curtab->tp_diffbuf[i] != NULL && (eap->cmdidx != CMD_diffput || curtab->tp_diffbuf[i]->b_p_ma)) { emsg(_("E101: More than two buffers in diff mode, don't know which one to use")); return; } } else { // Buffer number or pattern given. Ignore trailing white space. p = eap->arg + STRLEN(eap->arg); while (p > eap->arg && VIM_ISWHITE(p[-1])) --p; for (i = 0; vim_isdigit(eap->arg[i]) && eap->arg + i < p; ++i) ; if (eap->arg + i == p) // digits only i = atol((char *)eap->arg); else { i = buflist_findpat(eap->arg, p, FALSE, TRUE, FALSE); if (i < 0) return; // error message already given } buf = buflist_findnr(i); if (buf == NULL) { semsg(_("E102: Can't find buffer \"%s\""), eap->arg); return; } if (buf == curbuf) return; // nothing to do idx_other = diff_buf_idx(buf); if (idx_other == DB_COUNT) { semsg(_("E103: Buffer \"%s\" is not in diff mode"), eap->arg); return; } } diff_busy = TRUE; // When no range given include the line above or below the cursor. if (eap->addr_count == 0) { // Make it possible that ":diffget" on the last line gets line below // the cursor line when there is no difference above the cursor. if (eap->cmdidx == CMD_diffget && eap->line1 == curbuf->b_ml.ml_line_count && diff_check(curwin, eap->line1) == 0 && (eap->line1 == 1 || diff_check(curwin, eap->line1 - 1) == 0)) ++eap->line2; else if (eap->line1 > 0) --eap->line1; } if (eap->cmdidx == CMD_diffget) { idx_from = idx_other; idx_to = idx_cur; } else { idx_from = idx_cur; idx_to = idx_other; // Need to make the other buffer the current buffer to be able to make // changes in it. // set curwin/curbuf to buf and save a few things aucmd_prepbuf(&aco, curtab->tp_diffbuf[idx_other]); } // May give the warning for a changed buffer here, which can trigger the // FileChangedRO autocommand, which may do nasty things and mess // everything up. if (!curbuf->b_changed) { change_warning(0); if (diff_buf_idx(curbuf) != idx_to) { emsg(_("E787: Buffer changed unexpectedly")); goto theend; } } dprev = NULL; for (dp = curtab->tp_first_diff; dp != NULL; ) { if (dp->df_lnum[idx_cur] > eap->line2 + off) break; // past the range that was specified dfree = NULL; lnum = dp->df_lnum[idx_to]; count = dp->df_count[idx_to]; if (dp->df_lnum[idx_cur] + dp->df_count[idx_cur] > eap->line1 + off && u_save(lnum - 1, lnum + count) != FAIL) { // Inside the specified range and saving for undo worked. start_skip = 0; end_skip = 0; if (eap->addr_count > 0) { // A range was specified: check if lines need to be skipped. start_skip = eap->line1 + off - dp->df_lnum[idx_cur]; if (start_skip > 0) { // range starts below start of current diff block if (start_skip > count) { lnum += count; count = 0; } else { count -= start_skip; lnum += start_skip; } } else start_skip = 0; end_skip = dp->df_lnum[idx_cur] + dp->df_count[idx_cur] - 1 - (eap->line2 + off); if (end_skip > 0) { // range ends above end of current/from diff block if (idx_cur == idx_from) // :diffput { i = dp->df_count[idx_cur] - start_skip - end_skip; if (count > i) count = i; } else // :diffget { count -= end_skip; end_skip = dp->df_count[idx_from] - start_skip - count; if (end_skip < 0) end_skip = 0; } } else end_skip = 0; } buf_empty = BUFEMPTY(); added = 0; for (i = 0; i < count; ++i) { // remember deleting the last line of the buffer buf_empty = curbuf->b_ml.ml_line_count == 1; ml_delete(lnum, FALSE); --added; } for (i = 0; i < dp->df_count[idx_from] - start_skip - end_skip; ++i) { linenr_T nr; nr = dp->df_lnum[idx_from] + start_skip + i; if (nr > curtab->tp_diffbuf[idx_from]->b_ml.ml_line_count) break; p = vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx_from], nr, FALSE)); if (p != NULL) { ml_append(lnum + i - 1, p, 0, FALSE); vim_free(p); ++added; if (buf_empty && curbuf->b_ml.ml_line_count == 2) { // Added the first line into an empty buffer, need to // delete the dummy empty line. buf_empty = FALSE; ml_delete((linenr_T)2, FALSE); } } } new_count = dp->df_count[idx_to] + added; dp->df_count[idx_to] = new_count; if (start_skip == 0 && end_skip == 0) { // Check if there are any other buffers and if the diff is // equal in them. for (i = 0; i < DB_COUNT; ++i) if (curtab->tp_diffbuf[i] != NULL && i != idx_from && i != idx_to && !diff_equal_entry(dp, idx_from, i)) break; if (i == DB_COUNT) { // delete the diff entry, the buffers are now equal here dfree = dp; dp = dp->df_next; if (dprev == NULL) curtab->tp_first_diff = dp; else dprev->df_next = dp; } } // Adjust marks. This will change the following entries! if (added != 0) { mark_adjust(lnum, lnum + count - 1, (long)MAXLNUM, (long)added); if (curwin->w_cursor.lnum >= lnum) { // Adjust the cursor position if it's in/after the changed // lines. if (curwin->w_cursor.lnum >= lnum + count) curwin->w_cursor.lnum += added; else if (added < 0) curwin->w_cursor.lnum = lnum; } } changed_lines(lnum, 0, lnum + count, (long)added); if (dfree != NULL) { // Diff is deleted, update folds in other windows. #ifdef FEAT_FOLDING diff_fold_update(dfree, idx_to); #endif vim_free(dfree); } else // mark_adjust() may have changed the count in a wrong way dp->df_count[idx_to] = new_count; // When changing the current buffer, keep track of line numbers if (idx_cur == idx_to) off += added; } // If before the range or not deleted, go to next diff. if (dfree == NULL) { dprev = dp; dp = dp->df_next; } } // restore curwin/curbuf and a few other things if (eap->cmdidx != CMD_diffget) { // Syncing undo only works for the current buffer, but we change // another buffer. Sync undo if the command was typed. This isn't // 100% right when ":diffput" is used in a function or mapping. if (KeyTyped) u_sync(FALSE); aucmd_restbuf(&aco); } theend: diff_busy = FALSE; if (diff_need_update) ex_diffupdate(NULL); // Check that the cursor is on a valid character and update its // position. When there were filler lines the topline has become // invalid. check_cursor(); changed_line_abv_curs(); if (diff_need_update) // redraw already done by ex_diffupdate() diff_need_update = FALSE; else { // Also need to redraw the other buffers. diff_redraw(FALSE); apply_autocmds(EVENT_DIFFUPDATED, NULL, NULL, FALSE, curbuf); } } #ifdef FEAT_FOLDING /* * Update folds for all diff buffers for entry "dp". * Skip buffer with index "skip_idx". * When there are no diffs, all folds are removed. */ static void diff_fold_update(diff_T *dp, int skip_idx) { int i; win_T *wp; FOR_ALL_WINDOWS(wp) for (i = 0; i < DB_COUNT; ++i) if (curtab->tp_diffbuf[i] == wp->w_buffer && i != skip_idx) foldUpdate(wp, dp->df_lnum[i], dp->df_lnum[i] + dp->df_count[i]); } #endif /* * Return TRUE if buffer "buf" is in diff-mode. */ int diff_mode_buf(buf_T *buf) { tabpage_T *tp; FOR_ALL_TABPAGES(tp) if (diff_buf_idx_tp(buf, tp) != DB_COUNT) return TRUE; return FALSE; } /* * Move "count" times in direction "dir" to the next diff block. * Return FAIL if there isn't such a diff block. */ int diff_move_to(int dir, long count) { int idx; linenr_T lnum = curwin->w_cursor.lnum; diff_T *dp; idx = diff_buf_idx(curbuf); if (idx == DB_COUNT || curtab->tp_first_diff == NULL) return FAIL; if (curtab->tp_diff_invalid) ex_diffupdate(NULL); // update after a big change if (curtab->tp_first_diff == NULL) // no diffs today return FAIL; while (--count >= 0) { // Check if already before first diff. if (dir == BACKWARD && lnum <= curtab->tp_first_diff->df_lnum[idx]) break; for (dp = curtab->tp_first_diff; ; dp = dp->df_next) { if (dp == NULL) break; if ((dir == FORWARD && lnum < dp->df_lnum[idx]) || (dir == BACKWARD && (dp->df_next == NULL || lnum <= dp->df_next->df_lnum[idx]))) { lnum = dp->df_lnum[idx]; break; } } } // don't end up past the end of the file if (lnum > curbuf->b_ml.ml_line_count) lnum = curbuf->b_ml.ml_line_count; // When the cursor didn't move at all we fail. if (lnum == curwin->w_cursor.lnum) return FAIL; setpcmark(); curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = 0; return OK; } /* * Return the line number in the current window that is closest to "lnum1" in * "buf1" in diff mode. */ static linenr_T diff_get_corresponding_line_int( buf_T *buf1, linenr_T lnum1) { int idx1; int idx2; diff_T *dp; int baseline = 0; idx1 = diff_buf_idx(buf1); idx2 = diff_buf_idx(curbuf); if (idx1 == DB_COUNT || idx2 == DB_COUNT || curtab->tp_first_diff == NULL) return lnum1; if (curtab->tp_diff_invalid) ex_diffupdate(NULL); // update after a big change if (curtab->tp_first_diff == NULL) // no diffs today return lnum1; for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) { if (dp->df_lnum[idx1] > lnum1) return lnum1 - baseline; if ((dp->df_lnum[idx1] + dp->df_count[idx1]) > lnum1) { // Inside the diffblock baseline = lnum1 - dp->df_lnum[idx1]; if (baseline > dp->df_count[idx2]) baseline = dp->df_count[idx2]; return dp->df_lnum[idx2] + baseline; } if ( (dp->df_lnum[idx1] == lnum1) && (dp->df_count[idx1] == 0) && (dp->df_lnum[idx2] <= curwin->w_cursor.lnum) && ((dp->df_lnum[idx2] + dp->df_count[idx2]) > curwin->w_cursor.lnum)) /* * Special case: if the cursor is just after a zero-count * block (i.e. all filler) and the target cursor is already * inside the corresponding block, leave the target cursor * unmoved. This makes repeated CTRL-W W operations work * as expected. */ return curwin->w_cursor.lnum; baseline = (dp->df_lnum[idx1] + dp->df_count[idx1]) - (dp->df_lnum[idx2] + dp->df_count[idx2]); } // If we get here then the cursor is after the last diff return lnum1 - baseline; } /* * Return the line number in the current window that is closest to "lnum1" in * "buf1" in diff mode. Checks the line number to be valid. */ linenr_T diff_get_corresponding_line(buf_T *buf1, linenr_T lnum1) { linenr_T lnum = diff_get_corresponding_line_int(buf1, lnum1); // don't end up past the end of the file if (lnum > curbuf->b_ml.ml_line_count) return curbuf->b_ml.ml_line_count; return lnum; } /* * For line "lnum" in the current window find the equivalent lnum in window * "wp", compensating for inserted/deleted lines. */ linenr_T diff_lnum_win(linenr_T lnum, win_T *wp) { diff_T *dp; int idx; int i; linenr_T n; idx = diff_buf_idx(curbuf); if (idx == DB_COUNT) // safety check return (linenr_T)0; if (curtab->tp_diff_invalid) ex_diffupdate(NULL); // update after a big change // search for a change that includes "lnum" in the list of diffblocks. for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) if (lnum <= dp->df_lnum[idx] + dp->df_count[idx]) break; // When after the last change, compute relative to the last line number. if (dp == NULL) return wp->w_buffer->b_ml.ml_line_count - (curbuf->b_ml.ml_line_count - lnum); // Find index for "wp". i = diff_buf_idx(wp->w_buffer); if (i == DB_COUNT) // safety check return (linenr_T)0; n = lnum + (dp->df_lnum[i] - dp->df_lnum[idx]); if (n > dp->df_lnum[i] + dp->df_count[i]) n = dp->df_lnum[i] + dp->df_count[i]; return n; } /* * Handle an ED style diff line. * Return FAIL if the line does not contain diff info. */ static int parse_diff_ed( char_u *line, linenr_T *lnum_orig, long *count_orig, linenr_T *lnum_new, long *count_new) { char_u *p; long f1, l1, f2, l2; int difftype; // The line must be one of three formats: // change: {first}[,{last}]c{first}[,{last}] // append: {first}a{first}[,{last}] // delete: {first}[,{last}]d{first} p = line; f1 = getdigits(&p); if (*p == ',') { ++p; l1 = getdigits(&p); } else l1 = f1; if (*p != 'a' && *p != 'c' && *p != 'd') return FAIL; // invalid diff format difftype = *p++; f2 = getdigits(&p); if (*p == ',') { ++p; l2 = getdigits(&p); } else l2 = f2; if (l1 < f1 || l2 < f2) return FAIL; if (difftype == 'a') { *lnum_orig = f1 + 1; *count_orig = 0; } else { *lnum_orig = f1; *count_orig = l1 - f1 + 1; } if (difftype == 'd') { *lnum_new = f2 + 1; *count_new = 0; } else { *lnum_new = f2; *count_new = l2 - f2 + 1; } return OK; } /* * Parses unified diff with zero(!) context lines. * Return FAIL if there is no diff information in "line". */ static int parse_diff_unified( char_u *line, linenr_T *lnum_orig, long *count_orig, linenr_T *lnum_new, long *count_new) { char_u *p; long oldline, oldcount, newline, newcount; // Parse unified diff hunk header: // @@ -oldline,oldcount +newline,newcount @@ p = line; if (*p++ == '@' && *p++ == '@' && *p++ == ' ' && *p++ == '-') { oldline = getdigits(&p); if (*p == ',') { ++p; oldcount = getdigits(&p); } else oldcount = 1; if (*p++ == ' ' && *p++ == '+') { newline = getdigits(&p); if (*p == ',') { ++p; newcount = getdigits(&p); } else newcount = 1; } else return FAIL; // invalid diff format if (oldcount == 0) oldline += 1; if (newcount == 0) newline += 1; if (newline == 0) newline = 1; *lnum_orig = oldline; *count_orig = oldcount; *lnum_new = newline; *count_new = newcount; return OK; } return FAIL; } /* * Callback function for the xdl_diff() function. * Stores the diff output in a grow array. */ static int xdiff_out(void *priv, mmbuffer_t *mb, int nbuf) { diffout_T *dout = (diffout_T *)priv; char_u *p; // The header line always comes by itself, text lines in at least two // parts. We drop the text part. if (nbuf > 1) return 0; // sanity check if (STRNCMP(mb[0].ptr, "@@ ", 3) != 0) return 0; if (ga_grow(&dout->dout_ga, 1) == FAIL) return -1; p = vim_strnsave((char_u *)mb[0].ptr, mb[0].size); if (p == NULL) return -1; ((char_u **)dout->dout_ga.ga_data)[dout->dout_ga.ga_len++] = p; return 0; } #endif // FEAT_DIFF #if defined(FEAT_EVAL) || defined(PROTO) /* * "diff_filler()" function */ void f_diff_filler(typval_T *argvars UNUSED, typval_T *rettv UNUSED) { #ifdef FEAT_DIFF rettv->vval.v_number = diff_check_fill(curwin, tv_get_lnum(argvars)); #endif } /* * "diff_hlID()" function */ void f_diff_hlID(typval_T *argvars UNUSED, typval_T *rettv UNUSED) { #ifdef FEAT_DIFF linenr_T lnum = tv_get_lnum(argvars); static linenr_T prev_lnum = 0; static varnumber_T changedtick = 0; static int fnum = 0; static int change_start = 0; static int change_end = 0; static hlf_T hlID = (hlf_T)0; int filler_lines; int col; if (lnum < 0) // ignore type error in {lnum} arg lnum = 0; if (lnum != prev_lnum || changedtick != CHANGEDTICK(curbuf) || fnum != curbuf->b_fnum) { // New line, buffer, change: need to get the values. filler_lines = diff_check(curwin, lnum); if (filler_lines < 0) { if (filler_lines == -1) { change_start = MAXCOL; change_end = -1; if (diff_find_change(curwin, lnum, &change_start, &change_end)) hlID = HLF_ADD; // added line else hlID = HLF_CHD; // changed line } else hlID = HLF_ADD; // added line } else hlID = (hlf_T)0; prev_lnum = lnum; changedtick = CHANGEDTICK(curbuf); fnum = curbuf->b_fnum; } if (hlID == HLF_CHD || hlID == HLF_TXD) { col = tv_get_number(&argvars[1]) - 1; // ignore type error in {col} if (col >= change_start && col <= change_end) hlID = HLF_TXD; // changed text else hlID = HLF_CHD; // changed line } rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID; #endif } #endif
{ "pile_set_name": "Github" }
<domain type='vmware'> <name>firmware-efi</name> <uuid>564d9bef-acd9-b4e0-c8f0-aea8b9103515</uuid> <memory unit='KiB'>4096</memory> <os firmware='efi'> <type>hvm</type> </os> </domain>
{ "pile_set_name": "Github" }
package com.bird.web.sso; import lombok.Getter; import lombok.Setter; /** * @author liuxx * @date 2019/3/1 */ @Getter @Setter public abstract class SsoProperties { /** * cookie名称,默认为Sso-Token */ private String cookieName = "Sso-Token"; /** * 登录地址 */ private String loginPath; }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2007-2017 Xplenty, Inc. All Rights Reserved. * * Project and contact information: http://www.cascading.org/ * * This file is part of the Cascading project. * * 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 cascading.tuple.io; import java.util.List; import cascading.tuple.Tuple; /** Class IndexTuple allows for managing an int index value with a Tuple instance. Used internally for co-grouping values. */ public class IndexTuple extends Tuple implements Comparable<Object> { int index; Tuple tuple; /** Constructor IndexTuple creates a new IndexTuple instance. */ public IndexTuple() { super( (List<Object>) null ); } /** * Constructor IndexTuple creates a new IndexTuple instance. * * @param index of type int * @param tuple of type Tuple */ public IndexTuple( int index, Tuple tuple ) { super( (List<Comparable>) null ); this.index = index; this.tuple = tuple; } public void setIndex( int index ) { this.index = index; } public int getIndex() { return index; } public void setTuple( Tuple tuple ) { this.tuple = tuple; } public Tuple getTuple() { return tuple; } @Override public String print() { return printTo( new StringBuffer() ).toString(); } public StringBuffer printTo( StringBuffer buffer ) { buffer.append( "{" ); buffer.append( index ).append( ":" ); tuple.printTo( buffer ); buffer.append( "}" ); return buffer; } public int compareTo( Object object ) { if( object instanceof IndexTuple ) return compareTo( (IndexTuple) object ); return -1; } public int compareTo( IndexTuple indexTuple ) { int c = this.index - indexTuple.index; if( c != 0 ) return c; return this.tuple.compareTo( indexTuple.tuple ); } @Override public boolean equals( Object object ) { if( this == object ) return true; if( object == null || getClass() != object.getClass() ) return false; IndexTuple that = (IndexTuple) object; if( index != that.index ) return false; if( tuple != null ? !tuple.equals( that.tuple ) : that.tuple != null ) return false; return true; } @Override public int hashCode() { int result = index; result = 31 * result + ( tuple != null ? tuple.hashCode() : 0 ); return result; } @Override public String toString() { return "[" + index + "]" + tuple; } }
{ "pile_set_name": "Github" }
# AnotherFakeApi All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- [**testSpecialTags**](AnotherFakeApi.md#testSpecialTags) | **PATCH** another-fake/dummy | To test special tags <a name="testSpecialTags"></a> # **testSpecialTags** > Client testSpecialTags(body) To test special tags To test special tags ### Example ```java // Import classes: //import io.swagger.client.ApiException; //import io.swagger.client.api.AnotherFakeApi; AnotherFakeApi apiInstance = new AnotherFakeApi(); Client body = new Client(); // Client | client model try { Client result = apiInstance.testSpecialTags(body); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling AnotherFakeApi#testSpecialTags"); e.printStackTrace(); } ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | [**Client**](Client.md)| client model | ### Return type [**Client**](Client.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json
{ "pile_set_name": "Github" }
{ "token": "", "team_id": "", "enterprise_id": "", "api_app_id": "", "event": { "type": "star_added", "user": "", "item": { "type": "message", "channel": "", "message": { "bot_id": "", "type": "message", "text": "", "user": "", "ts": "0000000000.000000", "team": "", "bot_profile": { "id": "", "deleted": false, "name": "", "updated": 12345, "app_id": "", "icons": { "image_36": "https://www.example.com/", "image_48": "https://www.example.com/", "image_72": "https://www.example.com/" }, "team_id": "" }, "edited": { "user": "", "ts": "0000000000.000000" }, "attachments": [ { "service_name": "", "service_url": "https://www.example.com/", "title": "", "title_link": "https://www.example.com/", "author_name": "", "author_link": "https://www.example.com/", "thumb_url": "https://www.example.com/", "thumb_width": 12345, "thumb_height": 12345, "fallback": "", "video_html": "", "video_html_width": 12345, "video_html_height": 12345, "from_url": "https://www.example.com/", "service_icon": "https://www.example.com/", "id": 12345, "original_url": "https://www.example.com/", "msg_subtype": "", "callback_id": "", "color": "", "pretext": "", "author_id": "", "author_icon": "", "author_subname": "", "channel_id": "", "channel_name": "", "bot_id": "", "indent": false, "is_msg_unfurl": false, "is_reply_unfurl": false, "is_thread_root_unfurl": false, "is_app_unfurl": false, "app_unfurl_url": "", "text": "", "fields": [ { "title": "", "value": "", "short": false } ], "footer": "", "footer_icon": "", "ts": "", "mrkdwn_in": [ "" ], "actions": [ { "id": "", "name": "", "text": "", "style": "", "type": "button", "value": "", "confirm": { "title": "", "text": "", "ok_text": "", "dismiss_text": "" }, "options": [ { "text": "", "value": "" } ], "selected_options": [ { "text": "", "value": "" } ], "data_source": "", "min_query_length": 12345, "option_groups": [ { "text": "" } ], "url": "https://www.example.com/" } ], "filename": "", "size": 12345, "mimetype": "", "url": "https://www.example.com/", "metadata": { "thumb_64": false, "thumb_80": false, "thumb_160": false, "original_w": 12345, "original_h": 12345, "thumb_360_w": 12345, "thumb_360_h": 12345, "format": "", "extension": "", "rotation": 12345, "thumb_tiny": "" } } ], "is_starred": false, "permalink": "https://www.example.com/" }, "date_create": 12345 }, "event_ts": "0000000000.000000" }, "type": "event_callback", "event_id": "", "event_time": 12345, "authed_users": [ "" ] }
{ "pile_set_name": "Github" }
#include <KlayGE/KlayGE.hpp> #include <KFL/ErrorHandling.hpp> #include <KFL/Util.hpp> #include <KlayGE/Texture.hpp> #include <KFL/Math.hpp> #include <KlayGE/TexCompressionBC.hpp> #include <KlayGE/ResLoader.hpp> #include <iostream> #include <fstream> #include <vector> #include <cstring> using namespace std; using namespace KlayGE; namespace { void DecompressNormal(std::vector<uint8_t>& res_normals, std::vector<uint8_t> const & com_normals) { for (size_t i = 0; i < com_normals.size() / 4; ++ i) { float x = com_normals[i * 4 + 2] / 255.0f * 2 - 1; float y = com_normals[i * 4 + 1] / 255.0f * 2 - 1; float z = sqrt(1 - x * x - y * y); res_normals[i * 4 + 0] = static_cast<uint8_t>(MathLib::clamp(static_cast<int>((z * 0.5f + 0.5f) * 255 + 0.5f), 0, 255)); res_normals[i * 4 + 1] = com_normals[i * 4 + 1]; res_normals[i * 4 + 2] = com_normals[i * 4 + 2]; res_normals[i * 4 + 3] = 0; } } void DecompressNormalMapSubresource(uint32_t width, uint32_t height, ElementFormat restored_format, ElementInitData& restored_data, std::vector<uint8_t>& restored_data_block, ElementFormat com_format, ElementInitData const & com_data) { KFL_UNUSED(restored_format); std::vector<uint8_t> normals(width * height * 4); if (IsCompressedFormat(com_format)) { std::unique_ptr<TexCompression> tex_codec; switch (com_format) { case EF_BC3: tex_codec = MakeUniquePtr<TexCompressionBC3>(); break; case EF_BC5: tex_codec = MakeUniquePtr<TexCompressionBC5>(); break; default: KFL_UNREACHABLE("Compression formats other than BC3 and BC5 are not supported"); } for (uint32_t y_base = 0; y_base < height; y_base += 4) { for (uint32_t x_base = 0; x_base < width; x_base += 4) { uint32_t argb[16]; if (EF_BC5 == com_format) { uint16_t gr[16]; tex_codec->DecodeBlock(gr, static_cast<uint8_t const *>(com_data.data) + ((y_base / 4) * width / 4 + x_base / 4) * 16); for (int i = 0; i < 16; ++ i) { argb[i] = (gr[i] & 0xFF00) | ((gr[i] & 0xFF) << 16); } } else { BOOST_ASSERT(EF_BC3 == com_format); tex_codec->DecodeBlock(argb, static_cast<uint8_t const *>(com_data.data) + ((y_base / 4) * width / 4 + x_base / 4) * 16); } for (int y = 0; y < 4; ++ y) { if (y_base + y < height) { for (int x = 0; x < 4; ++ x) { if (x_base + x < width) { std::memcpy(&normals[((y_base + y) * width + (x_base + x)) * 4], &argb[y * 4 + x], sizeof(uint32_t)); } } } } } } } else { if (EF_GR8 == com_format) { uint8_t const * gr_data = static_cast<uint8_t const *>(com_data.data); for (uint32_t y = 0; y < height; ++ y) { for (uint32_t x = 0; x < width; ++ x) { normals[(y * width + x) * 4 + 0] = 0; normals[(y * width + x) * 4 + 1] = gr_data[y * com_data.row_pitch + x * 2 + 1]; normals[(y * width + x) * 4 + 2] = gr_data[y * com_data.row_pitch + x * 2 + 0]; normals[(y * width + x) * 4 + 3] = 0xFF; } } } else { BOOST_ASSERT(EF_ABGR8 == com_format); uint8_t const * abgr_data = static_cast<uint8_t const *>(com_data.data); for (uint32_t y = 0; y < height; ++ y) { for (uint32_t x = 0; x < width; ++ x) { normals[(y * width + x) * 4 + 0] = 0; normals[(y * width + x) * 4 + 1] = abgr_data[y * com_data.row_pitch + x * 4 + 1]; normals[(y * width + x) * 4 + 2] = abgr_data[y * com_data.row_pitch + x * 4 + 0]; normals[(y * width + x) * 4 + 3] = 0xFF; } } } } if (restored_format != EF_ARGB8) { std::vector<uint8_t> argb8_normals(width * height * 4); ResizeTexture(&argb8_normals[0], width * 4, width * height * 4, EF_ARGB8, width, height, 1, &normals[0], width * 4, width * height * 4, restored_format, width, height, 1, TextureFilter::Point); normals.swap(argb8_normals); } restored_data_block.resize(width * height * 4); restored_data.row_pitch = width * 4; restored_data.slice_pitch = width * height * 4; restored_data.data = &restored_data_block[0]; DecompressNormal(restored_data_block, normals); } void Normal2NaLength(std::string const & in_file, std::string const & out_file, ElementFormat new_format) { TexturePtr in_tex = LoadSoftwareTexture(in_file); auto const in_type = in_tex->Type(); auto const in_width = in_tex->Width(0); auto const in_height = in_tex->Height(0); auto const in_depth = in_tex->Depth(0); auto const in_num_mipmaps = in_tex->NumMipMaps(); auto const in_array_size = in_tex->ArraySize(); auto const in_format = in_tex->Format(); auto const & in_data = checked_cast<SoftwareTexture&>(*in_tex).SubresourceData(); TexCompressionBC4 bc4_codec; std::vector<std::vector<uint8_t>> level_lengths(in_num_mipmaps * in_array_size); std::vector<ElementInitData> new_data(level_lengths.size()); for (size_t array_index = 0; array_index < in_array_size; ++ array_index) { ElementInitData restored_data; std::vector<uint8_t> restored_data_block; if (in_format != EF_ARGB8) { DecompressNormalMapSubresource(in_width, in_height, EF_ARGB8, restored_data, restored_data_block, in_format, in_data[array_index * in_num_mipmaps]); } else { restored_data = in_data[array_index * in_num_mipmaps]; } std::vector<float3> the_normals(in_width * in_height); ResizeTexture(&the_normals[0], in_width * sizeof(float3), in_width * in_height * sizeof(float3), EF_BGR32F, in_width, in_height, 1, restored_data.data, restored_data.row_pitch, restored_data.slice_pitch, EF_ARGB8, in_width, in_height, 1, TextureFilter::Point); { if (IsCompressedFormat(new_format)) { new_data[array_index * in_num_mipmaps + 0].row_pitch = (in_width + 3) / 4 * 8; new_data[array_index * in_num_mipmaps + 0].slice_pitch = (in_width + 3) / 4 * (in_height + 3) / 4 * 8; std::vector<uint8_t>& new_lengths = level_lengths[array_index * in_num_mipmaps + 0]; new_lengths.resize(new_data[array_index * in_num_mipmaps + 0].slice_pitch); new_data[array_index * in_num_mipmaps + 0].data = &new_lengths[0]; array<uint8_t, 16> uncom_len; uncom_len.fill(255); BC4Block len_bc4; bc4_codec.EncodeBlock(&len_bc4, &uncom_len[0], TCM_Quality); uint32_t dest = 0; for (uint32_t y_base = 0; y_base < in_height; y_base += 4) { for (uint32_t x_base = 0; x_base < in_width; x_base += 4) { if (EF_BC4 == new_format) { std::memcpy(&new_lengths[dest], &len_bc4, sizeof(len_bc4)); dest += sizeof(len_bc4); } else { BOOST_ASSERT(EF_BC1 == new_format); BC1Block len_bc1; BC4ToBC1G(len_bc1, len_bc4); std::memcpy(&new_lengths[dest], &len_bc1, sizeof(len_bc1)); dest += sizeof(len_bc1); } } } } else { new_data[array_index * in_num_mipmaps + 0].row_pitch = in_width * sizeof(uint8_t); new_data[array_index * in_num_mipmaps + 0].slice_pitch = in_width * in_height * sizeof(uint8_t); std::vector<uint8_t>& new_lengths = level_lengths[array_index * in_num_mipmaps + 0]; new_lengths.resize(new_data[array_index * in_num_mipmaps + 0].slice_pitch, 255); new_data[array_index * in_num_mipmaps + 0].data = &new_lengths[0]; } } uint32_t the_width = in_width; uint32_t the_height = in_height; for (uint32_t level = 1; level < in_num_mipmaps; ++ level) { uint32_t new_width = std::max(the_width / 2, 1U); uint32_t new_height = std::max(the_height / 2, 1U); std::vector<float3> new_normals(new_width * new_height); if (IsCompressedFormat(new_format)) { new_data[array_index * in_num_mipmaps + level].row_pitch = (new_width + 3) / 4 * 8; new_data[array_index * in_num_mipmaps + level].slice_pitch = (new_width + 3) / 4 * (new_height + 3) / 4 * 8; } else { new_data[array_index * in_num_mipmaps + level].row_pitch = new_width * sizeof(uint8_t); new_data[array_index * in_num_mipmaps + level].slice_pitch = new_width * new_height * sizeof(uint8_t); } std::vector<uint8_t>& new_lengths = level_lengths[array_index * in_num_mipmaps + level]; new_lengths.resize(new_data[array_index * in_num_mipmaps + level].slice_pitch); new_data[array_index * in_num_mipmaps + level].data = &new_lengths[0]; uint32_t dest = 0; for (uint32_t y_base = 0; y_base < new_height; y_base += 4) { for (uint32_t x_base = 0; x_base < new_width; x_base += 4) { array<uint8_t, 16> uncom_len; for (uint32_t y = 0; y < 4; ++ y) { uint32_t y0 = MathLib::clamp((y_base + y) * 2 + 0, 0U, the_height - 1); uint32_t y1 = MathLib::clamp((y_base + y) * 2 + 1, 0U, the_height - 1); for (uint32_t x = 0; x < 4; ++ x) { uint32_t x0 = MathLib::clamp((x_base + x) * 2 + 0, 0U, the_width - 1); uint32_t x1 = MathLib::clamp((x_base + x) * 2 + 1, 0U, the_width - 1); float3 new_n = (the_normals[y0 * the_width + x0] + the_normals[y0 * the_width + x1] + the_normals[y1 * the_width + x0] + the_normals[y1 * the_width + x1]) * 0.25f; float len = MathLib::length(new_n); uncom_len[y * 4 + x] = static_cast<uint8_t>(MathLib::clamp(static_cast<int>(len * 255.0f + 0.5f), 0, 255)); if ((x_base + x < new_width) && (y_base + y < new_height)) { new_normals[(y_base + y) * new_width + (x_base + x)] = new_n; } } } if (IsCompressedFormat(new_format)) { BC4Block len_bc4; bc4_codec.EncodeBlock(&len_bc4, &uncom_len[0], TCM_Quality); if (EF_BC4 == new_format) { std::memcpy(&new_lengths[dest], &len_bc4, sizeof(len_bc4)); dest += sizeof(len_bc4); } else { BOOST_ASSERT(EF_BC1 == new_format); BC1Block len_bc1; BC4ToBC1G(len_bc1, len_bc4); std::memcpy(&new_lengths[dest], &len_bc1, sizeof(len_bc1)); dest += sizeof(len_bc1); } } else { for (uint32_t y = 0; y < 4; ++ y) { for (uint32_t x = 0; x < 4; ++ x) { if ((x_base + x < new_width) && (y_base + y < new_height)) { new_lengths[(y_base + y) * new_width + (x_base + x)] = uncom_len[y * 4 + x]; } } } } } } the_width = new_width; the_height = new_height; the_normals.swap(new_normals); } } TexturePtr out_tex = MakeSharedPtr<SoftwareTexture>(in_type, in_width, in_height, in_depth, in_num_mipmaps, in_array_size, new_format, true); out_tex->CreateHWResource(new_data, nullptr); SaveTexture(out_tex, out_file); } } int main(int argc, char* argv[]) { if (argc < 3) { cout << "Usage: Normal2NaLength xxx.dds yyy.dds [BC4 | BC1 | R]" << endl; return 1; } std::string in_file = ResLoader::Instance().Locate(argv[1]); if (in_file.empty()) { cout << "Couldn't locate " << in_file << endl; Context::Destroy(); return 1; } ElementFormat new_format = EF_BC4; if (argc >= 4) { std::string format_str(argv[3]); if ("BC4" == format_str) { new_format = EF_BC4; } else if ("BC1" == format_str) { new_format = EF_BC1; } else if ("R" == format_str) { new_format = EF_R8; } } Normal2NaLength(in_file, argv[2], new_format); cout << "Na Length map is saved to " << argv[2] << endl; Context::Destroy(); return 0; }
{ "pile_set_name": "Github" }
package cm.aptoide.pt.app.view; import android.view.LayoutInflater; import android.view.ViewGroup; import androidx.recyclerview.widget.RecyclerView; import cm.aptoide.pt.R; import cm.aptoide.pt.app.AppViewSimilarApp; import cm.aptoide.pt.app.view.similar.SimilarAppClickEvent; import java.text.DecimalFormat; import java.util.List; import rx.subjects.PublishSubject; /** * Created by franciscocalado on 11/05/18. */ public class AppViewSimilarAppsAdapter extends RecyclerView.Adapter<AppViewSimilarAppViewHolder> { private List<AppViewSimilarApp> similarApps; private DecimalFormat oneDecimalFormater; private PublishSubject<SimilarAppClickEvent> appClicked; private SimilarAppType type; public AppViewSimilarAppsAdapter(List<AppViewSimilarApp> similarApps, DecimalFormat oneDecimalFormater, PublishSubject<SimilarAppClickEvent> appClicked, SimilarAppType type) { this.similarApps = similarApps; this.oneDecimalFormater = oneDecimalFormater; this.appClicked = appClicked; this.type = type; } @Override public AppViewSimilarAppViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { return new AppViewSimilarAppViewHolder(LayoutInflater.from(viewGroup.getContext()) .inflate(R.layout.displayable_grid_ad, viewGroup, false), oneDecimalFormater, appClicked); } @Override public void onBindViewHolder(AppViewSimilarAppViewHolder appViewSimilarAppViewHolder, int position) { if (similarApps.get(position) != null) { appViewSimilarAppViewHolder.setSimilarApp(similarApps.get(position), type); } } @Override public int getItemViewType(int position) { return similarApps.get(position) .getNetworkAdType(); } @Override public int getItemCount() { return similarApps.size(); } public void update(List<AppViewSimilarApp> apps) { similarApps = apps; notifyDataSetChanged(); } public enum SimilarAppType { APPC_SIMILAR_APPS("appc_similar_apps"), SIMILAR_APPS("similar_apps"); private final String description; SimilarAppType(String description) { this.description = description; } public String getDescription() { return description; } } }
{ "pile_set_name": "Github" }
#include "Swift_watchOS_Native/Swift_watchOS_Native_base.xcconfig" VALIDATE_PRODUCT = YES
{ "pile_set_name": "Github" }
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.lifx.internal.protocol; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.nio.ByteBuffer; import org.eclipse.jdt.annotation.NonNullByDefault; /** * A generic handler that dynamically creates "standard" packet instances. * * <p> * Packet types must have an empty constructor and cannot require any * additional logic (other than parsing). * * @param <T> the packet subtype this handler constructs * * @author Tim Buckley - Initial Contribution * @author Karel Goderis - Enhancement for the V2 LIFX Firmware and LAN Protocol Specification */ @NonNullByDefault public class GenericHandler<T extends Packet> implements PacketHandler<T> { private Constructor<T> constructor; private boolean typeFound; private int type; public boolean isTypeFound() { return typeFound; } public int getType() { return type; } public GenericHandler(Class<T> clazz) { try { constructor = clazz.getConstructor(); } catch (NoSuchMethodException ex) { throw new IllegalArgumentException("Packet class cannot be handled by GenericHandler", ex); } try { Field typeField = clazz.getField("TYPE"); type = (int) typeField.get(null); typeFound = true; } catch (NoSuchFieldException | IllegalAccessException ex) { // silently ignore typeFound = false; } } @Override public T handle(ByteBuffer buf) { try { T ret = constructor.newInstance(); ret.parse(buf); return ret; } catch (ReflectiveOperationException ex) { throw new IllegalArgumentException("Unable to instantiate empty packet", ex); } } }
{ "pile_set_name": "Github" }
* { box-sizing: border-box; } body { padding: 0; margin: 0; font-family: 'Dosis', sans-serif; font-size: 18px; background-color: #eee; overflow: hidden; position: absolute; top: 0px; bottom: 0px; right: 0px; left: 0px; } h1 { margin-left: 38px; font-size: 42px; font-weight: 200; letter-spacing: 1px; } h2 { margin: 30px 0 20px 0; font-weight: 700; font-size: 22px; letter-spacing: 1px; } .column { position: absolute; top: 110px; bottom: 0px; border-left: 1px dotted #bbb; padding: 0 0 0 20px; display: none; } #example-list { position: absolute; top: 50px; left: 20px; right: 0px; bottom: 0px; font-family: Monaco, Menlo, "Ubuntu Mono", Consolas, source-code-pro, monospaceace; font-size: 12px; overflow: hidden; padding-bottom: 20px; } .example-item { padding: 4px 0 4px 0; cursor: pointer; } .example-item:hover { background-color: rgba(0, 0, 0, 0.05); } #code-editor { position: absolute; top: 50px; left: 20px; right: 0px; bottom: 0px; background: #eee; } #log-output { position: absolute; top: 50px; left: 20px; right: 0px; bottom: 0px; padding-bottom: 20px; font-family: Monaco, Menlo, "Ubuntu Mono", Consolas, source-code-pro, monospaceace; font-size: 12px; background: #eee; overflow: auto; white-space: pre-wrap; word-wrap: break-word; } .log-entry { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 1px dotted #b4b4b4; } .log-entry-details { color: #b4b4b4; margin-right: 8px; } .log-entry-info { color: black; } .log-entry-debug { color: black; } .log-entry-warn { color: #ff9100; } .log-entry-error { color: red; } #run-button { position: absolute; top: -2px; left: 24px; width: 26px; height: 26px; border-radius: 50%; z-index: 20000; cursor: pointer; background-color: #82CA6D; background-image: url("../img/run-icon.svg"); background-size: 16px 16px; background-position: center center; background-repeat: no-repeat; } #run-button:hover { background-color: #64a151; } #run-button:active { top: -1px; left: 25px; } .ace_gutter-cell { opacity: 0.3 !important; }
{ "pile_set_name": "Github" }
package org.rrd4j.core.jrrd; import java.io.IOException; import java.io.PrintStream; import java.text.NumberFormat; /** * Instances of this class model a data source in an RRD file. * * @author <a href="mailto:[email protected]">Ciaran Treanor</a> * @version $Revision: 1.1 $ */ public class DataSource { private static enum ds_param_en { DS_mrhb_cnt, DS_min_val, DS_max_val, DS_cde } private final long offset; private final long size; private final String name; private final DataSourceType type; private final int minimumHeartbeat; private final double minimum; private final double maximum; // initialized during RRDatabase construction private PDPStatusBlock pdpStatusBlock; DataSource(RRDFile file) throws IOException { offset = file.getFilePointer(); name = file.readString(Constants.DS_NAM_SIZE); type = DataSourceType.valueOf(file.readString(Constants.DST_SIZE).toUpperCase()); UnivalArray par = file.getUnivalArray(10); minimumHeartbeat = (int) par.getLong(ds_param_en.DS_mrhb_cnt); minimum = par.getDouble(ds_param_en.DS_min_val); maximum = par.getDouble(ds_param_en.DS_max_val); size = file.getFilePointer() - offset; } void loadPDPStatusBlock(RRDFile file) throws IOException { pdpStatusBlock = new PDPStatusBlock(file); } /** * Returns the primary data point status block for this data source. * * @return the primary data point status block for this data source. */ public PDPStatusBlock getPDPStatusBlock() { return pdpStatusBlock; } /** * Returns the minimum required heartbeat for this data source. * * @return the minimum required heartbeat for this data source. */ public int getMinimumHeartbeat() { return minimumHeartbeat; } /** * Returns the minimum value input to this data source can have. * * @return the minimum value input to this data source can have. */ public double getMinimum() { return minimum; } /** * Returns the type this data source is. * * @return the type this data source is. * @see DataSourceType */ public DataSourceType getType() { return type; } /** * Returns the maximum value input to this data source can have. * * @return the maximum value input to this data source can have. */ public double getMaximum() { return maximum; } /** * Returns the name of this data source. * * @return the name of this data source. */ public String getName() { return name; } void printInfo(PrintStream s, NumberFormat numberFormat) { StringBuilder sb = new StringBuilder("ds["); sb.append(name); s.print(sb); s.print("].type = \""); s.print(type); s.println("\""); s.print(sb); s.print("].minimal_heartbeat = "); s.println(minimumHeartbeat); s.print(sb); s.print("].min = "); s.println(Double.isNaN(minimum) ? "NaN" : numberFormat.format(minimum)); s.print(sb); s.print("].max = "); s.println(Double.isNaN(maximum) ? "NaN" : numberFormat.format(maximum)); s.print(sb); s.print("].last_ds = "); s.println(pdpStatusBlock.lastReading); s.print(sb); s.print("].value = "); double value = pdpStatusBlock.value; s.println(Double.isNaN(value) ? "NaN" : numberFormat.format(value)); s.print(sb); s.print("].unknown_sec = "); s.println(pdpStatusBlock.unknownSeconds); } void toXml(PrintStream s) { s.println("\t<ds>"); s.print("\t\t<name> "); s.print(name); s.println(" </name>"); s.print("\t\t<type> "); s.print(type); s.println(" </type>"); s.print("\t\t<minimal_heartbeat> "); s.print(minimumHeartbeat); s.println(" </minimal_heartbeat>"); s.print("\t\t<min> "); s.print(minimum); s.println(" </min>"); s.print("\t\t<max> "); s.print(maximum); s.println(" </max>"); s.println(); s.println("\t\t<!-- PDP Status -->"); s.print("\t\t<last_ds> "); s.print(pdpStatusBlock.lastReading); s.println(" </last_ds>"); s.print("\t\t<value> "); s.print(pdpStatusBlock.value); s.println(" </value>"); s.print("\t\t<unknown_sec> "); s.print(pdpStatusBlock.unknownSeconds); s.println(" </unknown_sec>"); s.println("\t</ds>"); s.println(); } /** * Returns a summary the contents of this data source. * * @return a summary of the information contained in this data source. */ public String toString() { StringBuilder sb = new StringBuilder("[DataSource: OFFSET=0x"); sb.append(Long.toHexString(offset)); sb.append(", SIZE=0x"); sb.append(Long.toHexString(size)); sb.append(", name="); sb.append(name); sb.append(", type="); sb.append(type.toString()); sb.append(", minHeartbeat="); sb.append(minimumHeartbeat); sb.append(", min="); sb.append(minimum); sb.append(", max="); sb.append(maximum); sb.append("]"); sb.append("\n\t\t"); sb.append(pdpStatusBlock.toString()); return sb.toString(); } }
{ "pile_set_name": "Github" }
<?php /* * This file is part of Piplin. * * Copyright (C) 2016-2017 piplin.com * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Piplin\Http\Requests; use Piplin\Http\Requests\Request; /** * Validate the user name and password. */ class StoreProfileRequest extends Request { /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ 'nickname' => 'required|max:255', 'password' => 'required|confirmed|min:6', ]; if (empty($this->get('password'))) { unset($rules['password']); } return $rules; } }
{ "pile_set_name": "Github" }
package ws.schild.jave.filters; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * A filterchain as described by <a * href="https://ffmpeg.org/ffmpeg-filters.html#Filtergraph-syntax-1">FFMPEG Documentation</a>. * * <p>A filterchain is a comma separated series of filters. * * @author mressler */ public class FilterChain implements VideoFilter { private List<Filter> filters; /** Create an empty filterchain. */ public FilterChain() { filters = new ArrayList<>(); } /** * Create a filterchain with the specified filters * * @param filters The ordered list of filters in this chain */ public FilterChain(Filter... filters) { this.filters = new ArrayList<>(Arrays.asList(filters)); } /** * Add one Filter to this filterchain * * @param filter The Filter to add to this chain. * @return this FilterChain for builder pattern magic */ public FilterChain addFilter(Filter filter) { filters.add(filter); return this; } public FilterChain prependFilter(Filter filter) { filters.add(0, filter); return this; } /** * Adds an input label to the first filter in this chain. * @param label The label to use for the input label for the first filter in this chain * @return this FilterChain for builder pattern magic * @throws IndexOutOfBoundsException if there are no filters in this chain. */ public FilterChain setInputLabel(String label) { filters.get(0).addInputLabel(label); return this; } /** * Adds an output label to the first filter in this chain. * @param label The label to use for the output label for the last filter in this chain * @return this FilterChain for builder pattern magic * @throws IndexOutOfBoundsException if there are no filters in this chain. */ public FilterChain setOutputLabel(String label) { filters.get(filters.size() - 1).addOutputLabel(label); return this; } @Override public String getExpression() { return filters.stream().map(VideoFilter::getExpression).collect(Collectors.joining(",")); } }
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_22) on Tue Mar 08 17:53:56 GMT 2011 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Issue (jslint4java parent 1.4.7 API) </TITLE> <META NAME="date" CONTENT="2011-03-08"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Issue (jslint4java parent 1.4.7 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Issue.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV CLASS&nbsp; &nbsp;<A HREF="../../../com/googlecode/jslint4java/Issue.IssueBuilder.html" title="class in com.googlecode.jslint4java"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?com/googlecode/jslint4java/Issue.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Issue.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;<A HREF="#nested_class_summary">NESTED</A>&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> com.googlecode.jslint4java</FONT> <BR> Class Issue</H2> <PRE> <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">java.lang.Object</A> <IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>com.googlecode.jslint4java.Issue</B> </PRE> <HR> <DL> <DT><PRE>public class <B>Issue</B><DT>extends <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A></DL> </PRE> <P> A single issue with the code that is being checked for problems. <P> <P> <DL> <DT><B>Author:</B></DT> <DD>dom</DD> </DL> <HR> <P> <!-- ======== NESTED CLASS SUMMARY ======== --> <A NAME="nested_class_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Nested Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/googlecode/jslint4java/Issue.IssueBuilder.html" title="class in com.googlecode.jslint4java">Issue.IssueBuilder</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Allow creating an issue in a couple of different ways.</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/googlecode/jslint4java/Issue.html#getA()">getA</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/googlecode/jslint4java/Issue.html#getB()">getB</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/googlecode/jslint4java/Issue.html#getC()">getC</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/googlecode/jslint4java/Issue.html#getCharacter()">getCharacter</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/googlecode/jslint4java/Issue.html#getD()">getD</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/googlecode/jslint4java/Issue.html#getEvidence()">getEvidence</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/googlecode/jslint4java/Issue.html#getLine()">getLine</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/googlecode/jslint4java/Issue.html#getRaw()">getRaw</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/googlecode/jslint4java/Issue.html#getReason()">getReason</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/googlecode/jslint4java/Issue.html#getSystemId()">getSystemId</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/googlecode/jslint4java/Issue.html#toString()">toString</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Provide four fields from this issue, separated by colons: systemId, line, character, reason.</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#clone()" title="class or interface in java.lang">clone</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#equals(java.lang.Object)" title="class or interface in java.lang">equals</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#finalize()" title="class or interface in java.lang">finalize</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#getClass()" title="class or interface in java.lang">getClass</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#hashCode()" title="class or interface in java.lang">hashCode</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#notify()" title="class or interface in java.lang">notify</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#notifyAll()" title="class or interface in java.lang">notifyAll</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#wait()" title="class or interface in java.lang">wait</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#wait(long)" title="class or interface in java.lang">wait</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#wait(long, int)" title="class or interface in java.lang">wait</A></CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="getA()"><!-- --></A><H3> getA</H3> <PRE> public <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> <B>getA</B>()</PRE> <DL> <DD><DL> <DT><B>Returns:</B><DD>A string of auxiliary information.</DL> </DD> </DL> <HR> <A NAME="getB()"><!-- --></A><H3> getB</H3> <PRE> public <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> <B>getB</B>()</PRE> <DL> <DD><DL> <DT><B>Returns:</B><DD>A string of auxiliary information.</DL> </DD> </DL> <HR> <A NAME="getC()"><!-- --></A><H3> getC</H3> <PRE> public <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> <B>getC</B>()</PRE> <DL> <DD><DL> <DT><B>Returns:</B><DD>A string of auxiliary information.</DL> </DD> </DL> <HR> <A NAME="getCharacter()"><!-- --></A><H3> getCharacter</H3> <PRE> public int <B>getCharacter</B>()</PRE> <DL> <DD><DL> <DT><B>Returns:</B><DD>the position of the issue within the line. Starts at 0.</DL> </DD> </DL> <HR> <A NAME="getD()"><!-- --></A><H3> getD</H3> <PRE> public <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> <B>getD</B>()</PRE> <DL> <DD><DL> <DT><B>Returns:</B><DD>a string of auxiliary information.</DL> </DD> </DL> <HR> <A NAME="getEvidence()"><!-- --></A><H3> getEvidence</H3> <PRE> public <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> <B>getEvidence</B>()</PRE> <DL> <DD><DL> <DT><B>Returns:</B><DD>the contents of the line in which this issue occurs.</DL> </DD> </DL> <HR> <A NAME="getLine()"><!-- --></A><H3> getLine</H3> <PRE> public int <B>getLine</B>()</PRE> <DL> <DD><DL> <DT><B>Returns:</B><DD>the number of the line on which this issue occurs.</DL> </DD> </DL> <HR> <A NAME="getRaw()"><!-- --></A><H3> getRaw</H3> <PRE> public <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> <B>getRaw</B>()</PRE> <DL> <DD><DL> <DT><B>Returns:</B><DD>a copy of the evidence, but before substitution has occurred.</DL> </DD> </DL> <HR> <A NAME="getReason()"><!-- --></A><H3> getReason</H3> <PRE> public <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> <B>getReason</B>()</PRE> <DL> <DD><DL> <DT><B>Returns:</B><DD>a textual description of this issue.</DL> </DD> </DL> <HR> <A NAME="getSystemId()"><!-- --></A><H3> getSystemId</H3> <PRE> public <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> <B>getSystemId</B>()</PRE> <DL> <DD><DL> <DT><B>Returns:</B><DD>the name of the file this issue occurred in.</DL> </DD> </DL> <HR> <A NAME="toString()"><!-- --></A><H3> toString</H3> <PRE> public <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> <B>toString</B>()</PRE> <DL> <DD>Provide four fields from this issue, separated by colons: systemId, line, character, reason. <P> <DD><DL> <DT><B>Overrides:</B><DD><CODE><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#toString()" title="class or interface in java.lang">toString</A></CODE> in class <CODE><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A></CODE></DL> </DD> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Issue.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV CLASS&nbsp; &nbsp;<A HREF="../../../com/googlecode/jslint4java/Issue.IssueBuilder.html" title="class in com.googlecode.jslint4java"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?com/googlecode/jslint4java/Issue.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Issue.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;<A HREF="#nested_class_summary">NESTED</A>&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2007-2011. All Rights Reserved. </BODY> </HTML>
{ "pile_set_name": "Github" }
package problem235
{ "pile_set_name": "Github" }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime.TypeSystem; public class ExternalDataDescriptor : DataManager.DataDescriptor { public interface IExternalDataContext { byte[] RawData { get; } void WriteData( ImageBuilders.SequentialRegion region ); object DataSection { get; } } private IExternalDataContext m_externContext; internal ExternalDataDescriptor() { } public ExternalDataDescriptor( DataManager owner , IExternalDataContext context , DataManager.Attributes flags , Abstractions.PlacementRequirements pr ) : base( owner, null, flags, pr ) { m_externContext = context; } public IExternalDataContext ExternContext { get { return m_externContext; } } public override object GetDataAtOffset( Runtime.TypeSystem.FieldRepresentation[] accessPath, int accessPathIndex, int offset ) { throw new NotImplementedException(); } internal override void IncludeExtraTypes( Runtime.TypeSystem.TypeSystem.Reachability reachability, CompilationSteps.PhaseDriver phase ) { throw new NotImplementedException(); } internal override void Reduce( GrowOnlySet<DataManager.DataDescriptor> visited, Runtime.TypeSystem.TypeSystem.Reachability reachability, bool fApply ) { } internal override void RefreshValues( CompilationSteps.PhaseDriver phase ) { } internal override void Write( ImageBuilders.SequentialRegion region ) { m_externContext.WriteData( region ); } protected override string ToString( bool fVerbose ) { return "ExternalDataDescriptor"; } } }
{ "pile_set_name": "Github" }
--- layout: page title: Sandboxes - Sinon.JS breadcrumb: sandbox --- Sandboxes removes the need to keep track of every fake created, which greatly simplifies cleanup. ```javascript var sandbox = require('sinon').createSandbox(); var myAPI = { hello: function () {} }; describe('myAPI.hello method', function () { beforeEach(function () { // stub out the `hello` method sandbox.stub(myAPI, 'hello'); }); afterEach(function () { // completely restore all fakes created through the sandbox sandbox.restore(); }); it('should be called once', function () { myAPI.hello(); sandbox.assert.calledOnce(myAPI.hello); }); it('should be called twice', function () { myAPI.hello(); myAPI.hello(); sandbox.assert.calledTwice(myAPI.hello); }); }); ``` ## Sandbox API #### Default sandbox Since `[email protected]`, the `sinon` object is a default sandbox. Unless you have a very advanced setup or need a special configuration, you probably want to only use that one. ```javascript const myObject = { 'hello': 'world' }; sinon.stub(myObject, 'hello').value('Sinon'); console.log(myObject.hello); // Sinon sinon.restore(); console.log(myObject.hello); // world ``` #### `var sandbox = sinon.createSandbox();` Creates a new sandbox object with spies, stubs, and mocks. #### `var sandbox = sinon.createSandbox(config);` The `sinon.createSandbox(config)` method is often an integration feature, and can be used for scenarios including a global object to coordinate all fakes through. Sandboxes are partially configured by default such that calling: ```javascript var sandbox = sinon.createSandbox({}); ``` will merge in extra defaults analogous to: ```javascript var sandbox = sinon.createSandbox({ // ... injectInto: null, properties: ["spy", "stub", "mock"], useFakeTimers: false, useFakeServer: false }); ``` The `useFakeTimers` and `useFakeServers` are **false** as opposed to the [defaults in `sinon.defaultConfig`](https://github.com/sinonjs/sinon/blob/master/lib/sinon/util/core/default-config.js): ```javascript sinon.defaultConfig = { // ... injectInto: null, properties: ["spy", "stub", "mock", "clock", "server", "requests"], useFakeTimers: true, useFakeServer: true } ``` To get a full sandbox with stubs, spies, etc. **and** fake timers and servers, you can call: ```javascript // Inject the sinon defaults explicitly. var sandbox = sinon.createSandbox(sinon.defaultConfig); // (OR) Add the extra properties that differ from the sinon defaults. var sandbox = sinon.createSandbox({ useFakeTimers: true useFakeServer: true }); ``` ##### injectInto The sandbox's methods can be injected into another object for convenience. The `injectInto` configuration option can name an object to add properties to. ##### properties What properties to inject. Note that only naming "server" here is not sufficient to have a `server` property show up in the target object, you also have to set `useFakeServer` to `true`. The list of properties that can be injected are the ones exposed by the object returned by the function `inject`, namely: ```javascript { //... properties: [ "spy", "stub", "mock", "createStubInstance", "fake", "replace", "replaceSetter", "replaceGetter", "clock", "server", "requests", "match" ] } ``` ##### useFakeTimers If set to `true`, the sandbox will have a `clock` property. You can optionally pass in a configuration object that follows the [specification for fake timers](../fake-timers), such as `{ toFake: ["setTimeout", "setInterval"] }`. ##### useFakeServer If `true`, `server` and `requests` properties are added to the sandbox. Can also be an object to use for fake server. The default one is `sinon.fakeServer`, but if you're using jQuery 1.3.x or some other library that does not set the XHR's `onreadystatechange` handler, you might want to do: ```javascript sinon.config = { useFakeServer: sinon.fakeServerWithClock }; ``` ##### exposing sandbox example To create an object `sandboxFacade` which gets the method `spy` injected, you can code: ```javascript // object that will have the spy method injected into it var sandboxFacade = {}; // create sandbox and inject properties (in this case spy) into sandboxFacade var sandbox = sinon.createSandbox({ injectInto: sandboxFacade, properties: ["spy"] }); ``` #### `sandbox.assert();` A convenience reference for [`sinon.assert`](./assertions) *Since `[email protected]`* #### `sandbox.replace(object, property, replacement);` Replaces `property` on `object` with `replacement` argument. Attempts to replace an already replaced value cause an exception. `replacement` can be any value, including `spies`, `stubs` and `fakes`. This method only works on non-accessor properties, for replacing accessors, use `sandbox.replaceGetter()` and `sandbox.replaceSetter()`. ```js var myObject = { myMethod: function() { return 'apple pie'; } }; sandbox.replace(myObject, 'myMethod', function () { return 'strawberry'; }); console.log(myObject.myMethod()); // strawberry ``` #### `sandbox.replaceGetter();` Replaces getter for `property` on `object` with `replacement` argument. Attempts to replace an already replaced getter cause an exception. `replacement` must be a `Function`, and can be instances of `spies`, `stubs` and `fakes`. ```js var myObject = { get myProperty: function() { return 'apple pie'; } }; sandbox.replaceGetter(myObject, 'myMethod', function () { return 'strawberry'; }); console.log(myObject.myProperty); // strawberry ``` #### `sandbox.replaceSetter();` Replaces setter for `property` on `object` with `replacement` argument. Attempts to replace an already replaced setter cause an exception. `replacement` must be a `Function`, and can be instances of `spies`, `stubs` and `fakes`. ```js var object = { set myProperty(value) { this.prop = value; } }; sandbox.replaceSetter(object, 'myProperty', function (value) { this.prop = 'strawberry ' + value; }); object.myProperty = 'pie'; console.log(object.prop); // strawberry pie ``` #### `sandbox.spy();` Works exactly like `sinon.spy` #### `sandbox.createStubInstance();` Works almost exactly like `sinon.createStubInstance`, only also adds the returned stubs to the internal collection of fakes for restoring through `sandbox.restore()`. #### `sandbox.stub();` Works exactly like `sinon.stub`. ##### Stubbing a non-function property ```javascript const myObject = { 'hello': 'world' }; sandbox.stub(myObject, 'hello').value('Sinon'); console.log(myObject.hello); // Sinon sandbox.restore(); console.log(myObject.hello); // world ``` #### `sandbox.mock();` Works exactly like `sinon.mock` #### `sandbox.useFakeTimers();` Fakes timers and binds the `clock` object to the sandbox such that it too is restored when calling `sandbox.restore()`. Access through `sandbox.clock`. #### `sandbox.useFakeXMLHttpRequest();` Fakes XHR and binds the resulting object to the sandbox such that it too is restored when calling `sandbox.restore()`. Since 2.x, you can no longer access requests through `sandbox.requests` - use `sandbox.useFakeServer` to do this. This function maps to `sinon.useFakeXMLHttpRequest`, only with sandboxing. #### `sandbox.useFakeServer();` Fakes XHR and binds a server object to the sandbox such that it too is restored when calling `sandbox.restore()`. Access requests through `sandbox.requests` and server through `sandbox.server` #### `sandbox.usingPromise(promiseLibrary);` Causes all stubs and mocks created from the sandbox to return promises using a specific Promise library instead of the global one when using `stub.rejects` or `stub.resolves`. Returns the stub to allow chaining. *Since `[email protected]`* #### `sandbox.restore();` Restores all fakes created through sandbox. #### `sandbox.reset();` Resets the internal state of all fakes created through sandbox. #### `sandbox.resetBehavior();` Resets the behaviour of all stubs created through the sandbox. *Since `[email protected]`* #### `sandbox.resetHistory();` Resets the history of all stubs created through the sandbox. *Since `[email protected]`* #### `sandbox.verify();` Verifies all mocks created through the sandbox. #### `sandbox.verifyAndRestore();` Verifies all mocks and restores all fakes created through the sandbox.
{ "pile_set_name": "Github" }
panic: too many errors [recovered] github.com/stephens2424/php.func·006 github.com/stephens2424/php.(*Parser).errorf github.com/stephens2424/php.(*Parser).expected github.com/stephens2424/php.(*Parser).expectCurrent github.com/stephens2424/php.(*Parser).expect github.com/stephens2424/php.(*Parser).expectStmtEnd github.com/stephens2424/php.(*Parser).parseStmt github.com/stephens2424/php.(*Parser).parseStmt github.com/stephens2424/php.(*Parser).parseNode github.com/stephens2424/php.(*Parser).Parse github.com/stephens2424/php.Fuzz github.com/dvyukov/go-fuzz/go-fuzz-dep.Main main.main
{ "pile_set_name": "Github" }
{ "name": "dbgobject-tree", "headless": true, "author": "Peter Salas", "description": "Provides an interface for traversing a tree of DbgObjects.", "dependencies": ["dbgobject", "dbgobject-inspector"], "includes": ["dbgobject-tree.css", "dbgobject-tree.js", "dbgobject-renderer.js", "tree-readers.js", "dbgobject-tree-renderer.js"] }
{ "pile_set_name": "Github" }
// Copyright 2017-2020 Lei Ni ([email protected]) and other Dragonboat 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 rsm import ( "crypto/md5" "encoding/binary" "sort" "strings" "github.com/lni/goutils/logutil" pb "github.com/lni/dragonboat/v3/raftpb" ) func addressEqual(addr1 string, addr2 string) bool { return strings.EqualFold(strings.TrimSpace(addr1), strings.TrimSpace(addr2)) } func deepCopyMembership(m pb.Membership) pb.Membership { c := pb.Membership{ ConfigChangeId: m.ConfigChangeId, Addresses: make(map[uint64]string), Removed: make(map[uint64]bool), Observers: make(map[uint64]string), Witnesses: make(map[uint64]string), } for nid, addr := range m.Addresses { c.Addresses[nid] = addr } for nid := range m.Removed { c.Removed[nid] = true } for nid, addr := range m.Observers { c.Observers[nid] = addr } for nid, addr := range m.Witnesses { c.Witnesses[nid] = addr } return c } type membership struct { clusterID uint64 nodeID uint64 ordered bool members *pb.Membership } func newMembership(clusterID uint64, nodeID uint64, ordered bool) *membership { return &membership{ clusterID: clusterID, nodeID: nodeID, ordered: ordered, members: &pb.Membership{ Addresses: make(map[uint64]string), Observers: make(map[uint64]string), Removed: make(map[uint64]bool), Witnesses: make(map[uint64]string), }, } } func (m *membership) id() string { return logutil.DescribeSM(m.clusterID, m.nodeID) } func (m *membership) set(n pb.Membership) { cm := deepCopyMembership(n) m.members = &cm } func (m *membership) get() pb.Membership { return deepCopyMembership(*m.members) } func (m *membership) getHash() uint64 { vals := make([]uint64, 0) for v := range m.members.Addresses { vals = append(vals, v) } sort.Slice(vals, func(i, j int) bool { return vals[i] < vals[j] }) vals = append(vals, m.members.ConfigChangeId) data := make([]byte, 8) hash := md5.New() for _, v := range vals { binary.LittleEndian.PutUint64(data, v) if _, err := hash.Write(data); err != nil { panic(err) } } md5sum := hash.Sum(nil) return binary.LittleEndian.Uint64(md5sum[:8]) } func (m *membership) isEmpty() bool { return len(m.members.Addresses) == 0 } func (m *membership) isConfChangeUpToDate(cc pb.ConfigChange) bool { if !m.ordered || cc.Initialize { return true } if m.members.ConfigChangeId == cc.ConfigChangeId { return true } return false } func (m *membership) isAddingRemovedNode(cc pb.ConfigChange) bool { if cc.Type == pb.AddNode || cc.Type == pb.AddObserver || cc.Type == pb.AddWitness { _, ok := m.members.Removed[cc.NodeID] return ok } return false } func (m *membership) isPromotingObserver(cc pb.ConfigChange) bool { if cc.Type == pb.AddNode { oa, ok := m.members.Observers[cc.NodeID] return ok && addressEqual(oa, string(cc.Address)) } return false } func (m *membership) isInvalidObserverPromotion(cc pb.ConfigChange) bool { if cc.Type == pb.AddNode { oa, ok := m.members.Observers[cc.NodeID] return ok && !addressEqual(oa, string(cc.Address)) } return false } func (m *membership) isAddingExistingMember(cc pb.ConfigChange) bool { // try to add again with the same node ID if cc.Type == pb.AddNode { _, ok := m.members.Addresses[cc.NodeID] if ok { return true } } if cc.Type == pb.AddObserver { _, ok := m.members.Observers[cc.NodeID] if ok { return true } } if cc.Type == pb.AddWitness { _, ok := m.members.Witnesses[cc.NodeID] if ok { return true } } if m.isPromotingObserver(cc) { return false } if cc.Type == pb.AddNode || cc.Type == pb.AddObserver || cc.Type == pb.AddWitness { for _, addr := range m.members.Addresses { if addressEqual(addr, string(cc.Address)) { return true } } for _, addr := range m.members.Observers { if addressEqual(addr, string(cc.Address)) { return true } } for _, addr := range m.members.Witnesses { if addressEqual(addr, string(cc.Address)) { return true } } } return false } func (m *membership) isAddingNodeAsObserver(cc pb.ConfigChange) bool { if cc.Type == pb.AddObserver { _, ok := m.members.Addresses[cc.NodeID] return ok } return false } func (m *membership) isAddingNodeAsWitness(cc pb.ConfigChange) bool { if cc.Type == pb.AddWitness { _, ok := m.members.Addresses[cc.NodeID] return ok } return false } func (m *membership) isAddingWitnessAsObserver(cc pb.ConfigChange) bool { if cc.Type == pb.AddObserver { _, ok := m.members.Witnesses[cc.NodeID] return ok } return false } func (m *membership) isAddingWitnessAsNode(cc pb.ConfigChange) bool { if cc.Type == pb.AddNode { _, ok := m.members.Witnesses[cc.NodeID] return ok } return false } func (m *membership) isAddingObserverAsWitness(cc pb.ConfigChange) bool { if cc.Type == pb.AddWitness { _, ok := m.members.Observers[cc.NodeID] return ok } return false } func (m *membership) isDeletingOnlyNode(cc pb.ConfigChange) bool { if cc.Type == pb.RemoveNode && len(m.members.Addresses) == 1 { _, ok := m.members.Addresses[cc.NodeID] return ok } return false } func (m *membership) applyConfigChange(cc pb.ConfigChange, index uint64) { m.members.ConfigChangeId = index switch cc.Type { case pb.AddNode: nodeAddr := string(cc.Address) delete(m.members.Observers, cc.NodeID) if _, ok := m.members.Witnesses[cc.NodeID]; ok { panic("not suppose to reach here") } m.members.Addresses[cc.NodeID] = nodeAddr case pb.AddObserver: if _, ok := m.members.Addresses[cc.NodeID]; ok { panic("not suppose to reach here") } m.members.Observers[cc.NodeID] = string(cc.Address) case pb.AddWitness: if _, ok := m.members.Addresses[cc.NodeID]; ok { panic("not suppose to reach here") } if _, ok := m.members.Observers[cc.NodeID]; ok { panic("not suppose to reach here") } m.members.Witnesses[cc.NodeID] = string(cc.Address) case pb.RemoveNode: delete(m.members.Addresses, cc.NodeID) delete(m.members.Observers, cc.NodeID) delete(m.members.Witnesses, cc.NodeID) m.members.Removed[cc.NodeID] = true default: panic("unknown config change type") } } var nid = logutil.NodeID func (m *membership) handleConfigChange(cc pb.ConfigChange, index uint64) bool { // order id requested by user ccid := cc.ConfigChangeId nodeBecomingObserver := m.isAddingNodeAsObserver(cc) nodeBecomingWitness := m.isAddingNodeAsWitness(cc) witnessBecomingNode := m.isAddingWitnessAsNode(cc) witnessBecomingObserver := m.isAddingWitnessAsObserver(cc) observerBecomingWitness := m.isAddingObserverAsWitness(cc) alreadyMember := m.isAddingExistingMember(cc) addRemovedNode := m.isAddingRemovedNode(cc) upToDateCC := m.isConfChangeUpToDate(cc) deleteOnlyNode := m.isDeletingOnlyNode(cc) invalidPromotion := m.isInvalidObserverPromotion(cc) accepted := upToDateCC && !addRemovedNode && !alreadyMember && !nodeBecomingObserver && !nodeBecomingWitness && !witnessBecomingNode && !witnessBecomingObserver && !observerBecomingWitness && !deleteOnlyNode && !invalidPromotion if accepted { // current entry index, it will be recorded as the conf change id of the members m.applyConfigChange(cc, index) if cc.Type == pb.AddNode { plog.Infof("%s applied ADD ccid %d (%d), %s (%s)", m.id(), ccid, index, nid(cc.NodeID), string(cc.Address)) } else if cc.Type == pb.RemoveNode { plog.Infof("%s applied REMOVE ccid %d (%d), %s", m.id(), ccid, index, nid(cc.NodeID)) } else if cc.Type == pb.AddObserver { plog.Infof("%s applied ADD OBSERVER ccid %d (%d), %s (%s)", m.id(), ccid, index, nid(cc.NodeID), string(cc.Address)) } else if cc.Type == pb.AddWitness { plog.Infof("%s applied ADD WITNESS ccid %d (%d), %s (%s)", m.id(), ccid, index, nid(cc.NodeID), string(cc.Address)) } else { plog.Panicf("unknown cc.Type value %d", cc.Type) } } else { if !upToDateCC { plog.Warningf("%s rej out-of-order ConfChange ccid %d (%d), type %s", m.id(), ccid, index, cc.Type) } else if addRemovedNode { plog.Warningf("%s rej add removed ccid %d (%d), %s", m.id(), ccid, index, nid(cc.NodeID)) } else if alreadyMember { plog.Warningf("%s rej add exist ccid %d (%d) %s (%s)", m.id(), ccid, index, nid(cc.NodeID), cc.Address) } else if nodeBecomingObserver { plog.Warningf("%s rej add exist as observer ccid %d (%d) %s (%s)", m.id(), ccid, index, nid(cc.NodeID), cc.Address) } else if nodeBecomingWitness { plog.Warningf("%s rej add exist as witness ccid %d (%d) %s (%s)", m.id(), ccid, index, nid(cc.NodeID), cc.Address) } else if witnessBecomingNode { plog.Warningf("%s rej add witness as node ccid %d (%d) %s (%s)", m.id(), ccid, index, nid(cc.NodeID), cc.Address) } else if witnessBecomingObserver { plog.Warningf("%s rej add witness as observer ccid %d (%d) %s (%s)", m.id(), ccid, index, nid(cc.NodeID), cc.Address) } else if observerBecomingWitness { plog.Warningf("%s rej add observer as witness ccid %d (%d) %s (%s)", m.id(), ccid, index, nid(cc.NodeID), cc.Address) } else if deleteOnlyNode { plog.Warningf("%s rej remove the only node %s", m.id(), nid(cc.NodeID)) } else if invalidPromotion { plog.Warningf("%s rej invalid observer promotion ccid %d (%d) %s (%s)", m.id(), ccid, index, nid(cc.NodeID), cc.Address) } else { plog.Panicf("config change rejected for unknown reasons") } } return accepted }
{ "pile_set_name": "Github" }
add_definitions(-DTRANSLATION_DOMAIN=\"kdevstandardoutputview\") ########### next target ############### declare_qt_logging_category(standardoutputview_LOG_PART_SRCS TYPE PLUGIN IDENTIFIER PLUGIN_STANDARDOUTPUTVIEW CATEGORY_BASENAME "standardoutputview" ) set(standardoutputview_LIB_SRCS standardoutputview.cpp outputwidget.cpp toolviewdata.cpp standardoutputviewmetadata.cpp ${standardoutputview_LOG_PART_SRCS} ) kdevplatform_add_plugin(kdevstandardoutputview JSON kdevstandardoutputview.json SOURCES ${standardoutputview_LIB_SRCS}) target_link_libraries(kdevstandardoutputview KDev::Interfaces KDev::Sublime KDev::Util KDev::OutputView ) if(BUILD_TESTING) add_subdirectory(tests) endif()
{ "pile_set_name": "Github" }
{ "type": "attributeSelector", "content": [ { "type": "attributeName", "content": [ { "type": "ident", "content": "a", "syntax": "less", "start": { "line": 1, "column": 2 }, "end": { "line": 1, "column": 2 } } ], "syntax": "less", "start": { "line": 1, "column": 2 }, "end": { "line": 1, "column": 2 } }, { "type": "attributeMatch", "content": "=", "syntax": "less", "start": { "line": 1, "column": 3 }, "end": { "line": 1, "column": 3 } }, { "type": "attributeValue", "content": [ { "type": "ident", "content": "b", "syntax": "less", "start": { "line": 1, "column": 4 }, "end": { "line": 1, "column": 4 } } ], "syntax": "less", "start": { "line": 1, "column": 4 }, "end": { "line": 1, "column": 4 } }, { "type": "space", "content": " ", "syntax": "less", "start": { "line": 1, "column": 5 }, "end": { "line": 1, "column": 5 } }, { "type": "attributeFlags", "content": [ { "type": "ident", "content": "i", "syntax": "less", "start": { "line": 1, "column": 6 }, "end": { "line": 1, "column": 6 } } ], "syntax": "less", "start": { "line": 1, "column": 6 }, "end": { "line": 1, "column": 6 } } ], "syntax": "less", "start": { "line": 1, "column": 1 }, "end": { "line": 1, "column": 7 } }
{ "pile_set_name": "Github" }
import random c_choice = random.randint(100,999) a = int(input("Guess a number?(100-999) ")) running = True while running: if a == c_choice: print("BINGO!") running = False elif a < c_choice: print("The answer is bigger.") a = int(input("Try again~ ")) elif a > c_choice: print("The answer is smaller.") a = int(input("Try again~ "))
{ "pile_set_name": "Github" }
// Copyright 2014 The Serviced 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 dao // -------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------- // **** USE OF THE METHODS IN THIS FILE IS DEPRECATED **** // // THAT MEANS DO NOT ADD MORE METHODS TO dao.ControlPlane // // Instead of adding new RPC calls via dao.ControlPlane, new RPCs should be added // rpc/master.ClientInterface // -------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------- import ( "time" "github.com/control-center/serviced/domain/addressassignment" "github.com/control-center/serviced/domain/logfilter" "github.com/control-center/serviced/domain/service" "github.com/control-center/serviced/metrics" ) // ControlPlaneError is a generic ControlPlane error type ControlPlaneError struct { Msg string } // Implement the Error() interface for ControlPlaneError func (s ControlPlaneError) Error() string { return s.Msg } // EntityRequest is a request for a control center object. type EntityRequest interface{} // ServiceRequest identifies a service plus some query parameters. type ServiceRequest struct { Tags []string TenantID string UpdatedSince time.Duration NameRegex string } // ServiceCloneRequest specifies a service to clone and how to modify the clone's name. type ServiceCloneRequest struct { ServiceID string Suffix string } // ServiceMigrationRequest is request to modify one or more services. type ServiceMigrationRequest struct { ServiceID string // The tenant service ID Modified []*service.Service // Services modified by the migration Added []*service.Service // Services added by the migration Deploy []*ServiceDeploymentRequest // ServiceDefinitions to be deployed by the migration LogFilters map[string]logfilter.LogFilter // LogFilters to add/replace } // ServiceStateRequest specifies a request for a service's service state. type ServiceStateRequest struct { ServiceID string ServiceStateID string } // ScheduleServiceRequest specifies a request to schedule a service to run. type ScheduleServiceRequest struct { ServiceIDs []string AutoLaunch bool Synchronous bool } // WaitServiceRequest is a request to wait for a set of services to gain the requested status. type WaitServiceRequest struct { ServiceIDs []string // List of service IDs to monitor DesiredState service.DesiredState // State which to monitor for Timeout time.Duration // Time to wait before cancelling the subprocess Recursive bool // Recursively wait for the desired state } // HostServiceRequest is a request for the service state of a host. type HostServiceRequest struct { HostID string ServiceStateID string } // AttachRequest is a request to run a command in the container of a running service. type AttachRequest struct { Running *RunningService Command string Args []string } // FindChildRequest is a request to locate a service's child by name. type FindChildRequest struct { ServiceID string ChildName string } // SnapshotRequest is a request to create a snapshot. type SnapshotRequest struct { ServiceID string Message string Tag string ContainerID string SnapshotSpacePercent int } // TagSnapshotRequest is a request to add a tag (label) to the specified snapshot. type TagSnapshotRequest struct { SnapshotID string TagName string } // SnapshotByTagRequest is request for the snapshot idenfified by the tag name. type SnapshotByTagRequest struct { ServiceID string TagName string } // RollbackRequest is a request to apply a snapshot to the current system. type RollbackRequest struct { SnapshotID string ForceRestart bool } // MetricRequest is a request for the metrics of the instances of a service. type MetricRequest struct { StartTime time.Time HostID string ServiceID string Instances []metrics.ServiceInstance } // The ControlPlane interface is the API for a serviced master. type ControlPlane interface { //--------------------------------------------------------------------------- // Service CRUD // Add a new service AddService(svc service.Service, serviceID *string) error // Clones a new service CloneService(request ServiceCloneRequest, serviceID *string) error // Deploy a new service DeployService(svc ServiceDeploymentRequest, serviceID *string) error // Update an existing service UpdateService(svc service.Service, _ *int) error // Migrate a service definition MigrateServices(request ServiceMigrationRequest, _ *int) error // Remove a service definition RemoveService(serviceID string, _ *int) error // Get a service from serviced GetService(serviceID string, svc *service.Service) error // Find a child service with the given name FindChildService(request FindChildRequest, svc *service.Service) error // Assign IP addresses to all services at and below the provided service AssignIPs(assignmentRequest addressassignment.AssignmentRequest, _ *int) (err error) // Get a list of tenant IDs GetTenantIDs(_ struct{}, tenantIDs *[]string) error //--------------------------------------------------------------------------- //ServiceState CRUD // Schedule the given service to start StartService(request ScheduleServiceRequest, affected *int) error // Schedule the given service to restart RestartService(request ScheduleServiceRequest, affected *int) error // Schedule the given service to rebalance RebalanceService(request ScheduleServiceRequest, affected *int) error // Schedule the given service to stop StopService(request ScheduleServiceRequest, affected *int) error // Schedule the given service to pause PauseService(request ScheduleServiceRequest, affected *int) error // Stop a running instance of a service StopRunningInstance(request HostServiceRequest, _ *int) error // Wait for a particular service state WaitService(request WaitServiceRequest, _ *int) error // Computes the status of the service based on its service instances GetServiceStatus(serviceID string, status *[]service.Instance) error // Get logs for the given app GetServiceLogs(serviceID string, logs *string) error // Get logs for the given app GetServiceStateLogs(request ServiceStateRequest, logs *string) error // Get all running services GetRunningServices(request EntityRequest, runningServices *[]RunningService) error // Get the services instances for a given service GetRunningServicesForHost(hostID string, runningServices *[]RunningService) error // Get the service instances for a given service GetRunningServicesForService(serviceID string, runningServices *[]RunningService) error // Attach to a running container with a predefined action Action(request AttachRequest, _ *int) error // ------------------------------------------------------------------------ // Metrics // Get service memory stats for a particular host GetHostMemoryStats(req MetricRequest, stats *metrics.MemoryUsageStats) error // Get service memory stats for a particular service GetServiceMemoryStats(req MetricRequest, stats *metrics.MemoryUsageStats) error // Get service memory stats for a particular service instance GetInstanceMemoryStats(req MetricRequest, stats *[]metrics.MemoryUsageStats) error // ----------------------------------------------------------------------- // Filesystem CRUD // Backup captures the state of the application stack and writes the output // to disk. Backup(backupRequest BackupRequest, filename *string) (err error) // GetBackupEstimate estimates space required to take backup and space available GetBackupEstimate(backupRequest BackupRequest, estimate *BackupEstimate) (err error) // AsyncBackup is the same as backup but asynchronous AsyncBackup(backupRequest BackupRequest, filename *string) (err error) // Restore reverts the full application stack from a backup file Restore(restoreRequest RestoreRequest, _ *int) (err error) // AsyncRestore is the same as restore but asynchronous AsyncRestore(restoreRequest RestoreRequest, _ *int) (err error) // Adds 1 or more tags to an existing snapshot TagSnapshot(request TagSnapshotRequest, _ *int) error // Removes a specific tag from an existing snapshot RemoveSnapshotTag(request SnapshotByTagRequest, snapshotID *string) error // Gets the snapshot from a specific service with a specific tag GetSnapshotByServiceIDAndTag(request SnapshotByTagRequest, snapshot *SnapshotInfo) error // ListBackups returns the list of backups ListBackups(dirpath string, files *[]BackupFile) (err error) // BackupStatus returns the current status of a running backup or restore BackupStatus(_ EntityRequest, status *string) (err error) // Snapshot captures the state of a single application Snapshot(req SnapshotRequest, snapshotID *string) (err error) // Rollback reverts a single application to the state of a snapshot Rollback(req RollbackRequest, _ *int) (err error) // DeleteSnapshot deletes a single snapshot DeleteSnapshot(snapshotID string, _ *int) (err error) // DeleteSnapshots deletes all snapshots for a service DeleteSnapshots(serviceID string, _ *int) (err error) // ListSnapshots returns a list of all snapshots for a service ListSnapshots(serviceID string, snapshots *[]SnapshotInfo) (err error) // ResetRegistry prompts all images to be re-pushed into the docker // registry. ResetRegistry(_ EntityRequest, _ *int) (err error) // RepairRegistry will try to recover the latest image of all service // images from the docker registry and save it to the index. RepairRegistry(_ EntityRequest, _ *int) (err error) // ReadyDFS waits for the DFS to be idle when creating a service shell. ReadyDFS(serviceID string, _ *int) (err error) }
{ "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 net.neoremind.kraps.rpc /** * A callback that [[RpcEndpoint]] can use to send back a message or failure. It's thread-safe * and can be called in any thread. */ trait RpcCallContext { /** * Reply a message to the sender. If the sender is [[RpcEndpoint]], its [[RpcEndpoint.receive]] * will be called. */ def reply(response: Any): Unit /** * Report a failure to the sender. */ def sendFailure(e: Throwable): Unit /** * The sender of this message. */ def senderAddress: RpcAddress }
{ "pile_set_name": "Github" }
begin select * from t1 where id in (select id from t2) commit
{ "pile_set_name": "Github" }
useLogger(CustomEventLogger()) class CustomEventLogger() : BuildAdapter(), TaskExecutionListener { override fun beforeExecute(task: Task) { println("[${task.name}]") } override fun afterExecute(task: Task, state: TaskState) { println() } override fun buildFinished(result: BuildResult) { println("build completed") if (result.failure != null) { (result.failure as Throwable).printStackTrace() } } }
{ "pile_set_name": "Github" }
<table class="action" align="center" width="100%" cellpadding="0" cellspacing="0"> <tr> <td align="center"> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center"> <table border="0" cellpadding="0" cellspacing="0"> <tr> <td> <a href="{{ $url }}" class="button button-{{ $color or 'blue' }}" target="_blank">{{ $slot }}</a> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table>
{ "pile_set_name": "Github" }
--- name: Bug Report about: Create a report to help us improve. title: '' labels: bug assignees: '' --- <!-- If you have an issue with a plugin create an issue on that plugin's GitHub page instead. --> <!-- Before opening an issue, please review the Troubleshooting Page on the Wiki to ensure that this is a new issue, and alternatively search the closed issues for similar problems. --> <!-- Link to the the Wiki - https://github.com/homebridge/HAP-NodeJS/wiki --> <!-- Provide a general summary in the Title above --> **Describe The Bug:** <!-- A clear and concise description of what the bug is. --> **To Reproduce:** <!-- Steps to reproduce the behavior. --> **Expected behavior:** <!-- A clear and concise description of what you expected to happen. --> **Logs:** <!-- Paste relevant output between the two ``` lines below --> <!-- Remove any sensitive information, passwords, etc. --> <!-- Please include the beginning of the log where the HAP-NodeJS initialization happens --> **Screenshots:** <!-- If applicable, add screenshots to help explain your problem. --> **Environment:** * **Node.js Version**: <!-- node -v --> * **NPM Version**: <!-- npm -v --> * **Operating System**: Raspbian / Ubuntu / Debian / Windows / macOS / Docker / other * **Process Supervisor**: Systemd / init.d / pm2 / launchctl / Docker / hb-service / other / none <!-- Click the "Preview" tab before you submit to ensure the formatting is correct. -->
{ "pile_set_name": "Github" }
# Open Source Help Wanted Projects The purpose of this repo is to maintain a list of open source projects by language that allow for the community to quickly indentify areas they can contribute. This is very helpful for individuals that are new to a language. I'm also hoping this will be used for hackathons and meetups. ## Go [golang.org](http://golang.org) - [Help Wanted](https://github.com/golang/go/labels/help%20wanted) - [Documentation](https://github.com/golang/go/issues?q=is%3Aopen+is%3Aissue+label%3ADocumentation) - [Contribution Guidelines](https://golang.org/doc/contribute.html) #### [InfluxDB](http://github.com/influxdata/influxdb) To see only help wanted issues, follow these links: - [All Help Wanted](https://github.com/influxdata/influxdb/issues?q=is%3Aopen+is%3Aissue+label%3Astatus%2Fhelp-wanted) - [Help Wanted - Difficulty: low](https://github.com/influxdata/influxdb/issues?q=is%3Aopen+is%3Aissue+label%3Astatus%2Fhelp-wanted+label%3Adifficulty%2Flow) - [Help Wanted - Difficulty: medium](https://github.com/influxdata/influxdb/issues?q=is%3Aopen+is%3Aissue+label%3Astatus%2Fhelp-wanted+label%3Adifficulty%2Fmedium) - [Help Wanted - Difficulty: high](https://github.com/influxdata/influxdb/issues?q=is%3Aopen+is%3Aissue+label%3Astatus%2Fhelp-wanted+label%3Adifficulty%2Fhigh) #### [Kapacitor](http://github.com/influxdata/kapacitor) To see only help wanted issues, follow these links: - [All Help Wanted](https://github.com/influxdata/kapacitor/labels/help%20wanted) - [Help Wanted - Difficulty: easy](https://github.com/influxdata/kapacitor/labels/difficulty-easy) - [Help Wanted - Difficulty: medium](https://github.com/influxdata/kapacitor/labels/difficulty-medium) - [Help Wanted - Difficulty: hard](https://github.com/influxdata/kapacitor/labels/difficulty-hard) #### [Docker](https://github.com/docker/docker) - [Beginner](https://github.com/docker/docker/issues?q=is%3Aopen+is%3Aissue+label%3Aexp%2Fbeginner) - [Intermediate](https://github.com/docker/docker/issues?q=is%3Aopen+is%3Aissue+label%3Aexp%2Fintermediate) - [Expert](https://github.com/docker/docker/issues?q=is%3Aopen+is%3Aissue+label%3Aexp%2Fexpert) #### [Mattermost Server](https://github.com/mattermost/mattermost-server) Open source Slack-alternative built on Go and React. - [All Help Wanted](https://mattermost.com/pl/help-wanted) - [Go Help Wanted - Difficulty: Easy](https://github.com/mattermost/mattermost-server/issues?q=is%3Aissue+is%3Aopen+label%3ADifficulty%2F1%3AEasy+label%3A%22Tech%2FGo%22) - [Go Help Wanted - Difficulty: Medium](https://github.com/mattermost/mattermost-server/issues?q=is%3Aissue+is%3Aopen+label%3ADifficulty%2F2%3AMedium+label%3A%22Tech%2FGo%22+) - [Go Help Wanted - Difficulty: Hard](https://github.com/mattermost/mattermost-server/issues?q=is%3Aissue+is%3Aopen+label%3ADifficulty%2F3%3AHard+label%3A%22Tech%2FGo%22+) #### [CockroachDB](https://github.com/cockroachdb/cockroach) - [All Help Wanted](https://github.com/cockroachdb/cockroach/labels/helpwanted) - [Help Wanted - Easy](https://github.com/cockroachdb/cockroach/issues?q=is%3Aopen+label%3Ahelpwanted+label%3Aeasy) #### [Caddy](https://github.com/mholt/caddy) - [All Help Wanted](https://github.com/mholt/caddy/labels/help%20wanted) - [Help Wanted - Easy](https://github.com/mholt/caddy/labels/easy) #### [Gogs](https://github.com/gogits/gogs) - [Help Wanted](https://github.com/gogits/gogs/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) #### [Arduino Create Agent](https://github.com/arduino/arduino-create-agent) This project works, but it's a mess of non idiomatic go code without tests. - [Help wanted - Refactor](https://github.com/arduino/arduino-create-agent/issues/3) #### [universal-translator](https://github.com/go-playground/universal-translator) - [Help Wanted - Tests](https://github.com/go-playground/universal-translator/issues/1) #### [Go kit](https://github.com/go-kit/kit) - [Help Wanted](https://github.com/go-kit/kit/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) - [Help Wanted, Newbie Friendly](https://github.com/go-kit/kit/issues?utf8=✓&q=is%3Aissue+is%3Aopen+label%3A"help+wanted"+label%3A"newbie+friendly") #### [fsnotify](https://github.com/fsnotify/fsnotify) - Help wanted to [investigate and reproduce issues](https://github.com/fsnotify/fsnotify/issues?q=is%3Aissue+is%3Aopen+label%3Ainvestigate), review [pull requests](https://github.com/fsnotify/fsnotify/pulls), support additional platforms, and clean up the existing code. #### [log](https://github.com/go-playground/log) - [Help Wanted](https://github.com/go-playground/log/issues/1) #### [gorilla/mux](https://github.com/gorilla/mux) - [Help Wanted](https://github.com/gorilla/mux/labels/helpwanted) - [Documentation](https://github.com/gorilla/mux/labels/documentation) #### [gorouter](https://github.com/vardius/gorouter) - [Help Wanted](https://github.com/vardius/gorouter/labels/help%20wanted) #### [go-api-boilerplate](https://github.com/vardius/go-api-boilerplate) - [Help Wanted](https://github.com/vardius/go-api-boilerplate/labels/help%20wanted) #### [httpexpect](https://github.com/gavv/httpexpect) - [Help Wanted](https://github.com/gavv/httpexpect/labels/help%20wanted) ## C++ #### [Roc Toolkit](https://roc-streaming.org/) - [Help Wanted](https://github.com/roc-streaming/roc-toolkit/labels/help%20wanted) - [Contribution Guidelines](https://roc-streaming.org/toolkit/docs/development/contribution_guidelines.html)
{ "pile_set_name": "Github" }
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ namespace pocketmine\permission; use pocketmine\plugin\Plugin; use pocketmine\utils\PluginException; class PermissionAttachment{ /** @var PermissionRemovedExecutor */ private $removed = null; /** * @var bool[] */ private $permissions = []; /** @var Permissible */ private $permissible; /** @var Plugin */ private $plugin; /** * @param Plugin $plugin * @param Permissible $permissible * * @throws PluginException */ public function __construct(Plugin $plugin, Permissible $permissible){ if(!$plugin->isEnabled()){ throw new PluginException("Plugin " . $plugin->getDescription()->getName() . " is disabled"); } $this->permissible = $permissible; $this->plugin = $plugin; } /** * @return Plugin */ public function getPlugin(){ return $this->plugin; } /** * @param PermissionRemovedExecutor $ex */ public function setRemovalCallback(PermissionRemovedExecutor $ex){ $this->removed = $ex; } /** * @return PermissionRemovedExecutor */ public function getRemovalCallback(){ return $this->removed; } /** * @return Permissible */ public function getPermissible(){ return $this->permissible; } /** * @return bool[] */ public function getPermissions(){ return $this->permissions; } /** * @return bool[] */ public function clearPermissions(){ $this->permissions = []; $this->permissible->recalculatePermissions(); } /** * @param bool[] $permissions */ public function setPermissions(array $permissions){ foreach($permissions as $key => $value){ $this->permissions[$key] = (bool) $value; } $this->permissible->recalculatePermissions(); } /** * @param string[] $permissions */ public function unsetPermissions(array $permissions){ foreach($permissions as $node){ unset($this->permissions[$node]); } $this->permissible->recalculatePermissions(); } /** * @param string|Permission $name * @param bool $value */ public function setPermission($name, $value){ $name = $name instanceof Permission ? $name->getName() : $name; if(isset($this->permissions[$name])){ if($this->permissions[$name] === $value){ return; } unset($this->permissions[$name]); //Fixes children getting overwritten } $this->permissions[$name] = $value; $this->permissible->recalculatePermissions(); } /** * @param string|Permission $name */ public function unsetPermission($name){ $name = $name instanceof Permission ? $name->getName() : $name; if(isset($this->permissions[$name])){ unset($this->permissions[$name]); $this->permissible->recalculatePermissions(); } } /** * @return void */ public function remove(){ $this->permissible->removeAttachment($this); } }
{ "pile_set_name": "Github" }
af: afrikáans af_NA: 'afrikáans (Namibia)' af_ZA: 'afrikáans (Sudáfrica)' ak: akan ak_GH: 'akan (Ghana)' sq: albanés sq_AL: 'albanés (Albania)' sq_XK: 'albanés (Kosovo)' sq_MK: 'albanés (Macedonia)' de: alemán de_DE: 'alemán (Alemania)' de_AT: 'alemán (Austria)' de_BE: 'alemán (Bélgica)' de_LI: 'alemán (Liechtenstein)' de_LU: 'alemán (Luxemburgo)' de_CH: 'alemán (Suiza)' am: amárico am_ET: 'amárico (Etiopía)' ar: árabe ar_SA: 'árabe (Arabia Saudí)' ar_DZ: 'árabe (Argelia)' ar_BH: 'árabe (Baréin)' ar_QA: 'árabe (Catar)' ar_TD: 'árabe (Chad)' ar_KM: 'árabe (Comoras)' ar_EG: 'árabe (Egipto)' ar_AE: 'árabe (Emiratos Árabes Unidos)' ar_ER: 'árabe (Eritrea)' ar_IQ: 'árabe (Iraq)' ar_IL: 'árabe (Israel)' ar_JO: 'árabe (Jordania)' ar_KW: 'árabe (Kuwait)' ar_LB: 'árabe (Líbano)' ar_LY: 'árabe (Libia)' ar_MA: 'árabe (Marruecos)' ar_MR: 'árabe (Mauritania)' ar_OM: 'árabe (Omán)' ar_EH: 'árabe (Sáhara Occidental)' ar_SY: 'árabe (Siria)' ar_SO: 'árabe (Somalia)' ar_SS: 'árabe (Sudán del Sur)' ar_SD: 'árabe (Sudán)' ar_PS: 'árabe (Territorios Palestinos)' ar_TN: 'árabe (Túnez)' ar_YE: 'árabe (Yemen)' ar_DJ: 'árabe (Yibuti)' hy: armenio hy_AM: 'armenio (Armenia)' as: asamés as_IN: 'asamés (India)' az: azerí az_AZ: 'azerí (Azerbaiyán)' az_Cyrl_AZ: 'azerí (cirílico, Azerbaiyán)' az_Cyrl: 'azerí (cirílico)' az_Latn_AZ: 'azerí (latín, Azerbaiyán)' az_Latn: 'azerí (latín)' bm: bambara bm_Latn_ML: 'bambara (latín, Mali)' bm_Latn: 'bambara (latín)' bn: bengalí bn_BD: 'bengalí (Bangladés)' bn_IN: 'bengalí (India)' be: bielorruso be_BY: 'bielorruso (Bielorrusia)' my: birmano my_MM: 'birmano (Myanmar (Birmania))' nb: 'bokmal noruego' nb_NO: 'bokmal noruego (Noruega)' nb_SJ: 'bokmal noruego (Svalbard y Jan Mayen)' bs: bosnio bs_BA: 'bosnio (Bosnia-Herzegovina)' bs_Cyrl_BA: 'bosnio (cirílico, Bosnia-Herzegovina)' bs_Cyrl: 'bosnio (cirílico)' bs_Latn_BA: 'bosnio (latín, Bosnia-Herzegovina)' bs_Latn: 'bosnio (latín)' br: bretón br_FR: 'bretón (Francia)' bg: búlgaro bg_BG: 'búlgaro (Bulgaria)' ks: cachemiro ks_Arab_IN: 'cachemiro (árabe, India)' ks_Arab: 'cachemiro (árabe)' ks_IN: 'cachemiro (India)' kn: canarés kn_IN: 'canarés (India)' ca: catalán ca_AD: 'catalán (Andorra)' ca_ES: 'catalán (España)' ca_FR: 'catalán (Francia)' ca_IT: 'catalán (Italia)' cs: checo cs_CZ: 'checo (República Checa)' zh: chino zh_CN: 'chino (China)' zh_HK: 'chino (RAE de Hong Kong (China))' zh_MO: 'chino (RAE de Macao (China))' zh_Hans_CN: 'chino (simplificado, China)' zh_Hans_HK: 'chino (simplificado, RAE de Hong Kong (China))' zh_Hans_MO: 'chino (simplificado, RAE de Macao (China))' zh_Hans_SG: 'chino (simplificado, Singapur)' zh_Hans: 'chino (simplificado)' zh_SG: 'chino (Singapur)' zh_TW: 'chino (Taiwán)' zh_Hant_HK: 'chino (tradicional, RAE de Hong Kong (China))' zh_Hant_MO: 'chino (tradicional, RAE de Macao (China))' zh_Hant_TW: 'chino (tradicional, Taiwán)' zh_Hant: 'chino (tradicional)' si: cingalés si_LK: 'cingalés (Sri Lanka)' ko: coreano ko_KP: 'coreano (Corea del Norte)' ko_KR: 'coreano (Corea del Sur)' kw: córnico kw_GB: 'córnico (Reino Unido)' hr: croata hr_BA: 'croata (Bosnia-Herzegovina)' hr_HR: 'croata (Croacia)' da: danés da_DK: 'danés (Dinamarca)' da_GL: 'danés (Groenlandia)' dz: dzongkha dz_BT: 'dzongkha (Bután)' sk: eslovaco sk_SK: 'eslovaco (Eslovaquia)' sl: esloveno sl_SI: 'esloveno (Eslovenia)' es: español es_AR: 'español (Argentina)' es_BO: 'español (Bolivia)' es_EA: 'español (Ceuta y Melilla)' es_CL: 'español (Chile)' es_CO: 'español (Colombia)' es_CR: 'español (Costa Rica)' es_CU: 'español (Cuba)' es_EC: 'español (Ecuador)' es_SV: 'español (El Salvador)' es_ES: 'español (España)' es_US: 'español (Estados Unidos)' es_PH: 'español (Filipinas)' es_GT: 'español (Guatemala)' es_GQ: 'español (Guinea Ecuatorial)' es_HN: 'español (Honduras)' es_IC: 'español (islas Canarias)' es_MX: 'español (México)' es_NI: 'español (Nicaragua)' es_PA: 'español (Panamá)' es_PY: 'español (Paraguay)' es_PE: 'español (Perú)' es_PR: 'español (Puerto Rico)' es_DO: 'español (República Dominicana)' es_UY: 'español (Uruguay)' es_VE: 'español (Venezuela)' eo: esperanto et: estonio et_EE: 'estonio (Estonia)' eu: euskera eu_ES: 'euskera (España)' ee: ewé ee_GH: 'ewé (Ghana)' ee_TG: 'ewé (Togo)' fo: feroés fo_FO: 'feroés (Islas Feroe)' fi: finés fi_FI: 'finés (Finlandia)' fr: francés fr_DZ: 'francés (Argelia)' fr_BE: 'francés (Bélgica)' fr_BJ: 'francés (Benín)' fr_BF: 'francés (Burkina Faso)' fr_BI: 'francés (Burundi)' fr_CM: 'francés (Camerún)' fr_CA: 'francés (Canadá)' fr_TD: 'francés (Chad)' fr_KM: 'francés (Comoras)' fr_CI: 'francés (Costa de Marfil)' fr_FR: 'francés (Francia)' fr_GA: 'francés (Gabón)' fr_GP: 'francés (Guadalupe)' fr_GF: 'francés (Guayana Francesa)' fr_GQ: 'francés (Guinea Ecuatorial)' fr_GN: 'francés (Guinea)' fr_HT: 'francés (Haití)' fr_LU: 'francés (Luxemburgo)' fr_MG: 'francés (Madagascar)' fr_ML: 'francés (Mali)' fr_MA: 'francés (Marruecos)' fr_MQ: 'francés (Martinica)' fr_MU: 'francés (Mauricio)' fr_MR: 'francés (Mauritania)' fr_YT: 'francés (Mayotte)' fr_MC: 'francés (Mónaco)' fr_NE: 'francés (Níger)' fr_NC: 'francés (Nueva Caledonia)' fr_PF: 'francés (Polinesia Francesa)' fr_CF: 'francés (República Centroafricana)' fr_CG: 'francés (República del Congo)' fr_CD: 'francés (República Democrática del Congo)' fr_RE: 'francés (Reunión)' fr_RW: 'francés (Ruanda)' fr_BL: 'francés (San Bartolomé)' fr_MF: 'francés (San Martín)' fr_PM: 'francés (San Pedro y Miquelón)' fr_SN: 'francés (Senegal)' fr_SC: 'francés (Seychelles)' fr_SY: 'francés (Siria)' fr_CH: 'francés (Suiza)' fr_TG: 'francés (Togo)' fr_TN: 'francés (Túnez)' fr_VU: 'francés (Vanuatu)' fr_WF: 'francés (Wallis y Futuna)' fr_DJ: 'francés (Yibuti)' fy: 'frisón occidental' fy_NL: 'frisón occidental (Países Bajos)' ff: fula ff_CM: 'fula (Camerún)' ff_GN: 'fula (Guinea)' ff_MR: 'fula (Mauritania)' ff_SN: 'fula (Senegal)' gd: 'gaélico escocés' gd_GB: 'gaélico escocés (Reino Unido)' gv: 'gaélico manés' gv_IM: 'gaélico manés (Isla de Man)' cy: galés cy_GB: 'galés (Reino Unido)' gl: gallego gl_ES: 'gallego (España)' lg: ganda lg_UG: 'ganda (Uganda)' ka: georgiano ka_GE: 'georgiano (Georgia)' el: griego el_CY: 'griego (Chipre)' el_GR: 'griego (Grecia)' kl: groenlandés kl_GL: 'groenlandés (Groenlandia)' gu: gujarati gu_IN: 'gujarati (India)' ha: hausa ha_GH: 'hausa (Ghana)' ha_Latn_GH: 'hausa (latín, Ghana)' ha_Latn_NE: 'hausa (latín, Níger)' ha_Latn_NG: 'hausa (latín, Nigeria)' ha_Latn: 'hausa (latín)' ha_NE: 'hausa (Níger)' ha_NG: 'hausa (Nigeria)' he: hebreo he_IL: 'hebreo (Israel)' hi: hindi hi_IN: 'hindi (India)' hu: húngaro hu_HU: 'húngaro (Hungría)' ig: igbo ig_NG: 'igbo (Nigeria)' id: indonesio id_ID: 'indonesio (Indonesia)' en: inglés en_AI: 'inglés (Anguila)' en_AG: 'inglés (Antigua y Barbuda)' en_AU: 'inglés (Australia)' en_BS: 'inglés (Bahamas)' en_BB: 'inglés (Barbados)' en_BE: 'inglés (Bélgica)' en_BZ: 'inglés (Belice)' en_BM: 'inglés (Bermudas)' en_BW: 'inglés (Botsuana)' en_CM: 'inglés (Camerún)' en_CA: 'inglés (Canadá)' en_DG: 'inglés (Diego García)' en_DM: 'inglés (Dominica)' en_ER: 'inglés (Eritrea)' en_US: 'inglés (Estados Unidos)' en_PH: 'inglés (Filipinas)' en_FJ: 'inglés (Fiyi)' en_GM: 'inglés (Gambia)' en_GH: 'inglés (Ghana)' en_GI: 'inglés (Gibraltar)' en_GD: 'inglés (Granada)' en_GU: 'inglés (Guam)' en_GG: 'inglés (Guernesey)' en_GY: 'inglés (Guyana)' en_IN: 'inglés (India)' en_IE: 'inglés (Irlanda)' en_CX: 'inglés (Isla Christmas)' en_IM: 'inglés (Isla de Man)' en_NU: 'inglés (Isla Niue)' en_NF: 'inglés (Isla Norfolk)' en_KY: 'inglés (Islas Caimán)' en_CC: 'inglés (Islas Cocos)' en_CK: 'inglés (Islas Cook)' en_FK: 'inglés (Islas Malvinas)' en_MP: 'inglés (Islas Marianas del Norte)' en_MH: 'inglés (Islas Marshall)' en_UM: 'inglés (Islas menores alejadas de EE. UU.)' en_PN: 'inglés (Islas Pitcairn)' en_SB: 'inglés (Islas Salomón)' en_TC: 'inglés (Islas Turcas y Caicos)' en_VG: 'inglés (Islas Vírgenes Británicas)' en_VI: 'inglés (Islas Vírgenes de EE. UU.)' en_JM: 'inglés (Jamaica)' en_JE: 'inglés (Jersey)' en_KE: 'inglés (Kenia)' en_KI: 'inglés (Kiribati)' en_LS: 'inglés (Lesoto)' en_LR: 'inglés (Liberia)' en_MG: 'inglés (Madagascar)' en_MY: 'inglés (Malasia)' en_MW: 'inglés (Malaui)' en_MT: 'inglés (Malta)' en_MU: 'inglés (Mauricio)' en_FM: 'inglés (Micronesia)' en_MS: 'inglés (Montserrat)' en_NA: 'inglés (Namibia)' en_NR: 'inglés (Nauru)' en_NG: 'inglés (Nigeria)' en_NZ: 'inglés (Nueva Zelanda)' en_PK: 'inglés (Pakistán)' en_PW: 'inglés (Palau)' en_PG: 'inglés (Papúa Nueva Guinea)' en_PR: 'inglés (Puerto Rico)' en_HK: 'inglés (RAE de Hong Kong (China))' en_MO: 'inglés (RAE de Macao (China))' en_GB: 'inglés (Reino Unido)' en_RW: 'inglés (Ruanda)' en_AS: 'inglés (Samoa Americana)' en_WS: 'inglés (Samoa)' en_KN: 'inglés (San Cristóbal y Nieves)' en_VC: 'inglés (San Vicente y las Granadinas)' en_SH: 'inglés (Santa Elena)' en_LC: 'inglés (Santa Lucía)' en_SC: 'inglés (Seychelles)' en_SL: 'inglés (Sierra Leona)' en_SG: 'inglés (Singapur)' en_SX: 'inglés (Sint Maarten)' en_SZ: 'inglés (Suazilandia)' en_ZA: 'inglés (Sudáfrica)' en_SS: 'inglés (Sudán del Sur)' en_SD: 'inglés (Sudán)' en_TZ: 'inglés (Tanzania)' en_IO: 'inglés (Territorio Británico del Océano Índico)' en_TK: 'inglés (Tokelau)' en_TO: 'inglés (Tonga)' en_TT: 'inglés (Trinidad y Tobago)' en_TV: 'inglés (Tuvalu)' en_UG: 'inglés (Uganda)' en_VU: 'inglés (Vanuatu)' en_ZM: 'inglés (Zambia)' en_ZW: 'inglés (Zimbabue)' ga: irlandés ga_IE: 'irlandés (Irlanda)' is: islandés is_IS: 'islandés (Islandia)' it: italiano it_IT: 'italiano (Italia)' it_SM: 'italiano (San Marino)' it_CH: 'italiano (Suiza)' ja: japonés ja_JP: 'japonés (Japón)' km: jemer km_KH: 'jemer (Camboya)' kk: kazajo kk_Cyrl_KZ: 'kazajo (cirílico, Kazajistán)' kk_Cyrl: 'kazajo (cirílico)' kk_KZ: 'kazajo (Kazajistán)' ki: kikuyu ki_KE: 'kikuyu (Kenia)' rw: kinyarwanda rw_RW: 'kinyarwanda (Ruanda)' ky: kirguís ky_Cyrl_KG: 'kirguís (cirílico, Kirguistán)' ky_Cyrl: 'kirguís (cirílico)' ky_KG: 'kirguís (Kirguistán)' rn: kiroundi rn_BI: 'kiroundi (Burundi)' lo: laosiano lo_LA: 'laosiano (Laos)' lv: letón lv_LV: 'letón (Letonia)' ln: lingala ln_AO: 'lingala (Angola)' ln_CF: 'lingala (República Centroafricana)' ln_CG: 'lingala (República del Congo)' ln_CD: 'lingala (República Democrática del Congo)' lt: lituano lt_LT: 'lituano (Lituania)' lu: luba-katanga lu_CD: 'luba-katanga (República Democrática del Congo)' lb: luxemburgués lb_LU: 'luxemburgués (Luxemburgo)' mk: macedonio mk_MK: 'macedonio (Macedonia)' ml: malayalam ml_IN: 'malayalam (India)' ms: malayo ms_BN: 'malayo (Brunéi)' ms_Latn_BN: 'malayo (latín, Brunéi)' ms_Latn_MY: 'malayo (latín, Malasia)' ms_Latn_SG: 'malayo (latín, Singapur)' ms_Latn: 'malayo (latín)' ms_MY: 'malayo (Malasia)' ms_SG: 'malayo (Singapur)' mg: malgache mg_MG: 'malgache (Madagascar)' mt: maltés mt_MT: 'maltés (Malta)' mr: marathi mr_IN: 'marathi (India)' mn: mongol mn_Cyrl_MN: 'mongol (cirílico, Mongolia)' mn_Cyrl: 'mongol (cirílico)' mn_MN: 'mongol (Mongolia)' nd: 'ndebele septentrional' nd_ZW: 'ndebele septentrional (Zimbabue)' nl: neerlandés nl_AW: 'neerlandés (Aruba)' nl_BE: 'neerlandés (Bélgica)' nl_BQ: 'neerlandés (Caribe neerlandés)' nl_CW: 'neerlandés (Curazao)' nl_NL: 'neerlandés (Países Bajos)' nl_SX: 'neerlandés (Sint Maarten)' nl_SR: 'neerlandés (Surinam)' ne: nepalí ne_IN: 'nepalí (India)' ne_NP: 'nepalí (Nepal)' 'no': noruego no_NO: 'noruego (Noruega)' nn: 'nynorsk noruego' nn_NO: 'nynorsk noruego (Noruega)' or: oriya or_IN: 'oriya (India)' om: oromo om_ET: 'oromo (Etiopía)' om_KE: 'oromo (Kenia)' os: osético os_GE: 'osético (Georgia)' os_RU: 'osético (Rusia)' ps: pastún ps_AF: 'pastún (Afganistán)' fa: persa fa_AF: 'persa (Afganistán)' fa_IR: 'persa (Irán)' pl: polaco pl_PL: 'polaco (Polonia)' pt: portugués pt_AO: 'portugués (Angola)' pt_BR: 'portugués (Brasil)' pt_CV: 'portugués (Cabo Verde)' pt_GW: 'portugués (Guinea-Bisáu)' pt_MZ: 'portugués (Mozambique)' pt_PT: 'portugués (Portugal)' pt_MO: 'portugués (RAE de Macao (China))' pt_ST: 'portugués (Santo Tomé y Príncipe)' pt_TL: 'portugués (Timor Oriental)' pa: punjabí pa_Arab_PK: 'punjabí (árabe, Pakistán)' pa_Arab: 'punjabí (árabe)' pa_Guru_IN: 'punjabí (gurmuji, India)' pa_Guru: 'punjabí (gurmuji)' pa_IN: 'punjabí (India)' pa_PK: 'punjabí (Pakistán)' qu: quechua qu_BO: 'quechua (Bolivia)' qu_EC: 'quechua (Ecuador)' qu_PE: 'quechua (Perú)' rm: retorrománico rm_CH: 'retorrománico (Suiza)' ro: rumano ro_MD: 'rumano (Moldavia)' ro_RO: 'rumano (Rumanía)' ru: ruso ru_BY: 'ruso (Bielorrusia)' ru_KZ: 'ruso (Kazajistán)' ru_KG: 'ruso (Kirguistán)' ru_MD: 'ruso (Moldavia)' ru_RU: 'ruso (Rusia)' ru_UA: 'ruso (Ucrania)' se: 'sami septentrional' se_FI: 'sami septentrional (Finlandia)' se_NO: 'sami septentrional (Noruega)' se_SE: 'sami septentrional (Suecia)' sg: sango sg_CF: 'sango (República Centroafricana)' sr: serbio sr_BA: 'serbio (Bosnia-Herzegovina)' sr_Cyrl_BA: 'serbio (cirílico, Bosnia-Herzegovina)' sr_Cyrl_XK: 'serbio (cirílico, Kosovo)' sr_Cyrl_ME: 'serbio (cirílico, Montenegro)' sr_Cyrl_RS: 'serbio (cirílico, Serbia)' sr_Cyrl: 'serbio (cirílico)' sr_XK: 'serbio (Kosovo)' sr_Latn_BA: 'serbio (latín, Bosnia-Herzegovina)' sr_Latn_XK: 'serbio (latín, Kosovo)' sr_Latn_ME: 'serbio (latín, Montenegro)' sr_Latn_RS: 'serbio (latín, Serbia)' sr_Latn: 'serbio (latín)' sr_ME: 'serbio (Montenegro)' sr_RS: 'serbio (Serbia)' sh: serbocroata sh_BA: 'serbocroata (Bosnia-Herzegovina)' sn: shona sn_ZW: 'shona (Zimbabue)' so: somalí so_ET: 'somalí (Etiopía)' so_KE: 'somalí (Kenia)' so_SO: 'somalí (Somalia)' so_DJ: 'somalí (Yibuti)' sv: sueco sv_FI: 'sueco (Finlandia)' sv_AX: 'sueco (Islas Åland)' sv_SE: 'sueco (Suecia)' sw: swahili sw_KE: 'swahili (Kenia)' sw_TZ: 'swahili (Tanzania)' sw_UG: 'swahili (Uganda)' tl: tagalo tl_PH: 'tagalo (Filipinas)' th: tailandés th_TH: 'tailandés (Tailandia)' ta: tamil ta_IN: 'tamil (India)' ta_MY: 'tamil (Malasia)' ta_SG: 'tamil (Singapur)' ta_LK: 'tamil (Sri Lanka)' te: telugu te_IN: 'telugu (India)' bo: tibetano bo_CN: 'tibetano (China)' bo_IN: 'tibetano (India)' ti: tigriña ti_ER: 'tigriña (Eritrea)' ti_ET: 'tigriña (Etiopía)' to: tongano to_TO: 'tongano (Tonga)' tr: turco tr_CY: 'turco (Chipre)' tr_TR: 'turco (Turquía)' uk: ucraniano uk_UA: 'ucraniano (Ucrania)' ug: uigur ug_Arab_CN: 'uigur (árabe, China)' ug_Arab: 'uigur (árabe)' ug_CN: 'uigur (China)' ur: urdu ur_IN: 'urdu (India)' ur_PK: 'urdu (Pakistán)' uz: uzbeko uz_AF: 'uzbeko (Afganistán)' uz_Arab_AF: 'uzbeko (árabe, Afganistán)' uz_Arab: 'uzbeko (árabe)' uz_Cyrl_UZ: 'uzbeko (cirílico, Uzbekistán)' uz_Cyrl: 'uzbeko (cirílico)' uz_Latn_UZ: 'uzbeko (latín, Uzbekistán)' uz_Latn: 'uzbeko (latín)' uz_UZ: 'uzbeko (Uzbekistán)' vi: vietnamita vi_VN: 'vietnamita (Vietnam)' ii: 'yi de Sichuán' ii_CN: 'yi de Sichuán (China)' yi: yídish yo: yoruba yo_BJ: 'yoruba (Benín)' yo_NG: 'yoruba (Nigeria)' zu: zulú zu_ZA: 'zulú (Sudáfrica)'
{ "pile_set_name": "Github" }