text
stringlengths 2
100k
| meta
dict |
---|---|
//-------------------------------------------------------------------------
/*
Copyright (C) 1996, 2003 - 3D Realms Entertainment
This file is NOT part of Duke Nukem 3D version 1.5 - Atomic Edition
However, it is either an older version of a file that is, or is
some test code written during the development of Duke Nukem 3D.
This file is provided purely for educational interest.
Duke Nukem 3D is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Prepared for public release: 03/21/2003 - Charlie Wiederhold, 3D Realms
*/
//-------------------------------------------------------------------------
//
// Includes
#include <stdio.h>
#include <dos.h>
#include <fcntl.h>
#include <malloc.h>
#include <sys\stat.h>
// Defines
#define MAXXDIM 320
#define MAXYDIM 400
#define MAXMEMNEEDED (1<<24)
#define MINMEMNEEDED (1<<22)
#define MAXTILES 1024
#define MAXPALOOKUPS 64
#define NUMOPTIONS 8
#define NUMKEYS 9
#define MAXPLAYERS 16
#define MAXOBJECTS 1024
#define MAXVIEWOBJECTS MAXOBJECTS
#define MAXSTATUS 32
#define MAXCHANNELS 8
#define MAXSOUNDS 128
#define sc_Escape 0x01 // Menu
#define sc_P 0x19 // Pause
#define sc_F1 0x3b // Help
#define sc_F2 0x3c // Load
#define sc_F3 0x3d // Save
#define sc_F4 0x3e // initaboard()
#define sc_Tab 0x0f // Topdown view
#define sc_CapsLock 0x3a // Runlock
#define sc_UpArrow 0xc8 // Move Fowards
#define sc_DownArrow 0xd0 // Move Backwards
#define sc_LeftArrow 0xcb // Move Left
#define sc_RightArrow 0xcd // Move Right
#define sc_A 0x1e // Up/Jump
#define sc_Z 0x2c // Down/Duck
#define sc_F 0x21 // Flash ight
#define sc_kpad_1 0x4f // Look Up
#define sc_kpad_0 0x52 // Look Down
#define sc_LeftAlt 0x38 // Strafe
#define sc_Comma 0x33 // Strafe Left
#define sc_Period 0x34 // Strafe Right
#define sc_LeftControl 0x1d // Use Weapon
#define sc_LeftShift 0x2a // Run
#define sc_Space 0x39 // Use
#define IO_LOAD 0
#define IO_SAVE 1
#define IO_NOCLOSE 2
#define CLIP_HITCEILING 1
#define CLIP_HITFLOOR 2
#define CLIP_HALT 4
#define TOPHEIGHT(X,Y,H) map.h1[((Y)<<8)+(X)]=(H)
#define TOPCOLOR(X,Y,C) map.c1[((Y)<<8)+(X)]=(C)
#define TOPSHADE(X,Y,S) map.s1[((Y)<<8)+(X)]=(S)
#define BOTHEIGHT(X,Y,H) map.h2[((Y)<<8)+(X)]=(H)
#define BOTCOLOR(X,Y,C) map.c2[((Y)<<8)+(X)]=(C)
#define BOTSHADE(X,Y,S) map.s2[((Y)<<8)+(X)]=(S)
// Typedefs
typedef struct
{
char **ptr;
long amount;
} chunktype;
typedef struct
{
unsigned char *h1, *h2, *c1, *c2, *s1, *s2;
short headobject[MAXSTATUS+1];
short prevobject[MAXOBJECTS];
short nextobject[MAXOBJECTS];
short objectstat[MAXOBJECTS];
} maptype;
typedef struct
{
short viewobject;
short viewobjectang;
long viewobjectdist;
} viewobjecttype;
typedef struct
{
long sndno,i;
char *ptr;
} soundplayingtype;
typedef struct
{
char *fn, pri;
long len;
} soundtype;
typedef struct
{
long posx, posy, posz, horiz;
long vel, svel, zvel, angvel;
short ang, i;
// Flags
char runmode, topdown, flashlight;
} selftype;
typedef struct
{
long x, y, z, xvel, yvel, zvel, templong;
short picnum, angvel, owner, clipdist, ang;
} objecttype;
typedef struct
{
char manufacturer;
char version;
char encoding;
char bits_per_pixel;
short xmin,ymin;
short xmax,ymax;
short hres;
short vres;
char palette[48];
char reserved;
char colour_planes;
short bytes_per_line;
short palette_type;
char filler[58];
} pcxtype;
// Globals
maptype map;
selftype self[MAXPLAYERS];
objecttype object[MAXOBJECTS];
// Disposible (Non savable) globals
soundplayingtype soundplaying[MAXCHANNELS];
soundtype sounds[MAXSOUNDS];
viewobjecttype scrnobj[MAXVIEWOBJECTS];
short viewobjectcnt;
long frameplace,xdim,ydim;
unsigned char palookup[MAXPALOOKUPS][256],palette[768];
long pixs, vidmode, detmode;
long moustat, mousx, mousy;
long randomseed, screenpeek;
int iofil;
short sintable[2048], tantable[2048];
short radarang[320], muly80[MAXYDIM];
long mul16000[4] = {0,16000,32000,48000};
char *scrbuf;
pcxtype pcxheader;
unsigned int pcxwidth, pcxdepth;
unsigned int pcxbytes, pcxbits;
char atile[] =
{
0,0,
254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,
254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,
254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,
254, 0,254,254, 0,254, 0, 0, 0, 0,254, 0,254,254,254, 0,
254, 0,254,254, 0,254, 0,254,254,254,254, 0,254,254,254, 0,
254, 0,254,254, 0,254, 0,254,254,254,254, 0,254,254,254, 0,
254, 0,254,254, 0,254, 0,254,254,254,254, 0,254,254,254, 0,
254, 0, 0, 0, 0,254, 0, 0, 0,254,254, 0,254,254,254, 0,
254, 0,254,254, 0,254, 0,254,254,254,254, 0,254,254,254, 0,
254, 0,254,254, 0,254, 0,254,254,254,254, 0,254,254,254, 0,
254, 0,254,254, 0,254, 0,254,254,254,254, 0,254,254,254, 0,
254, 0,254,254, 0,254, 0, 0, 0, 0,254, 0, 0, 0,254, 0,
254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,
254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,
254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,
254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254
};
char *mainmem;
long memptr, totalmemory, chunkloc, maxchunks;
chunktype *chunk;
volatile char keystatus[256], readch, oldreadch, extended;
volatile long clockspeed, totalclock, numframes;
void (__interrupt __far *oldtimerhandler)();
void __interrupt __far timerhandler(void);
void (__interrupt __far *oldkeyhandler)();
void __interrupt __far keyhandler(void);
// Pragmas
#pragma aux toutp =\
"out dx, al",\
parm [edx][eax]\
modify exact \
#pragma aux toutpw =\
"out dx, ax",\
parm [edx][eax]\
modify exact \
#pragma aux setvmode =\
"int 0x10",\
parm [eax]\
#pragma aux drawpixel =\
"mov byte ptr [edi], al",\
parm [edi][eax]\
#pragma aux drawpixels =\
"mov word ptr [edi], ax",\
parm [edi][eax]\
#pragma aux drawpixeles =\
"mov dword ptr [edi], eax",\
parm [edi][eax]\
#pragma aux labs =\
"test eax, eax",\
"jns skipnegate",\
"neg eax",\
"skipnegate:",\
parm nomemory [eax]\
#pragma aux scale =\
"imul ebx",\
"idiv ecx",\
parm [eax][ebx][ecx]\
modify [eax edx]\
#pragma aux sqr =\
"imul eax, eax",\
parm nomemory [eax]\
modify exact [eax]\
value [eax]
#pragma aux sgn =\
"add ebx, ebx",\
"sbb eax, eax",\
"cmp eax, ebx",\
"adc al, 0",\
parm nomemory [ebx]\
modify exact [eax ebx]\
#pragma aux mulscale =\
"imul ebx",\
"shrd eax, edx, cl",\
parm [eax][ebx][ecx]\
modify [edx]\
#pragma aux divscale =\
"cdq",\
"shld edx, eax, cl",\
"sal eax, cl",\
"idiv ebx",\
parm [eax][ebx][ecx]\
modify [edx]\
#pragma aux groudiv =\
"shl eax, 12",\
"sub eax, ecx",\
"shld edx, eax, 16",\
"sar ebx, 8",\
"idiv bx",\
parm [eax][ebx][ecx]\
modify [edx]\
#pragma aux drawtopslab =\
"shr ecx, 1",\
"jnc skipdraw1a",\
"mov [edi], al",\
"add edi, 80",\
"skipdraw1a: shr ecx, 1",\
"jnc skipdraw2a",\
"mov [edi], al",\
"mov [edi+80], al",\
"add edi, 160",\
"skipdraw2a: jecxz skipdraw4a",\
"startdrawa: mov [edi], al",\
"mov [edi+80], al",\
"mov [edi+160], al",\
"mov [edi+240], al",\
"add edi, 320",\
"loop startdrawa",\
"skipdraw4a: mov eax, edi",\
parm [edi][ecx][eax]\
modify [edi ecx eax]\
#pragma aux drawbotslab =\
"shr ecx, 1",\
"jnc skipdraw1b",\
"mov [edi], al",\
"sub edi, 80",\
"skipdraw1b: shr ecx, 1",\
"jnc skipdraw2b",\
"mov [edi], al",\
"mov [edi-80], al",\
"sub edi, 160",\
"skipdraw2b: jecxz skipdraw4b",\
"startdrawb: mov [edi], al",\
"mov [edi-80], al",\
"mov [edi-160], al",\
"mov [edi-240], al",\
"sub edi, 320",\
"loop startdrawb",\
"skipdraw4b: mov eax, edi",\
parm [edi][ecx][eax]\
modify [edi ecx eax]\
#pragma aux clearbuf =\
"rep stosd",\
parm [edi][ecx][eax]\
modify exact [edi ecx]\
#pragma aux clearbufbyte =\
"cmp ecx, 4",\
"jae longcopy",\
"test cl, 1",\
"jz preskip",\
"stosb",\
"preskip: shr ecx, 1",\
"rep stosw",\
"jmp endit",\
"longcopy: test edi, 1",\
"jz skip1",\
"stosb",\
"dec ecx",\
"skip1: test edi, 2",\
"jz skip2",\
"stosw",\
"sub ecx, 2",\
"skip2: mov ebx, ecx",\
"shr ecx, 2",\
"rep stosd",\
"test bl, 2",\
"jz skip3",\
"stosw",\
"skip3: test bl, 1",\
"jz endit",\
"stosb",\
"endit:",\
parm [edi][ecx][eax]\
modify [ebx]\
#pragma aux copybuf =\
"rep movsd",\
parm [esi][edi][ecx]\
modify exact [ecx esi edi]\
#pragma aux copybytes =\
"rep movsb",\
parm [esi][edi][ecx]\
modify exact [ecx esi edi]\
#pragma aux copybufbyte =\
"cmp ecx, 4",\
"jae longcopy",\
"test cl, 1",\
"jz preskip",\
"movsb",\
"preskip: shr ecx, 1",\
"rep movsw",\
"jmp endit",\
"longcopy: test edi, 1",\
"jz skip1",\
"movsb",\
"dec ecx",\
"skip1: test edi, 2",\
"jz skip2",\
"movsw",\
"sub ecx, 2",\
"skip2: mov ebx, ecx",\
"shr ecx, 2",\
"rep movsd",\
"test bl, 2",\
"jz skip3",\
"movsw",\
"skip3: test bl, 1",\
"jz endit",\
"movsb",\
"endit:",\
parm [esi][edi][ecx]\
modify [ebx]\
#pragma aux showscreen4pix320200 =\
"mov dx, 0x3c4",\
"mov ax, 0x0f02",\
"out dx, ax",\
"mov ecx, 4000",\
"mov esi, scrbuf",\
"mov edi, frameplace",\
"rep movsd",\
modify [eax ecx edx esi edi]\
#pragma aux showscreen4pix320400 =\
"mov dx, 0x3c4",\
"mov ax, 0x0f02",\
"out dx, ax",\
"mov ecx, 8000",\
"mov esi, scrbuf",\
"mov edi, frameplace",\
"rep movsd",\
modify [eax ecx edx esi edi]\
#pragma aux showscreen2pix320200 =\
"mov dx, 0x3c4",\
"mov ax, 0x0302",\
"out dx, ax",\
"mov ecx, 4000",\
"mov esi, scrbuf",\
"mov edi, frameplace",\
"rep movsd",\
"mov ax, 0x0c02",\
"out dx, ax",\
"mov ecx, 4000",\
"mov edi, frameplace",\
"rep movsd",\
modify [eax ecx edx esi edi]\
#pragma aux showscreen2pix320400 =\
"mov dx, 0x3c4",\
"mov ax, 0x0302",\
"out dx, ax",\
"mov ecx, 8000",\
"mov esi, scrbuf",\
"mov edi, frameplace",\
"rep movsd",\
"mov ax, 0x0c02",\
"out dx, ax",\
"mov ecx, 8000",\
"mov edi, frameplace",\
"rep movsd",\
modify [eax ecx edx esi edi]\
#pragma aux showscreen1pix320200 =\
"mov dx, 0x3c4",\
"mov ax, 0x0102",\
"out dx, ax",\
"mov ecx, 4000",\
"mov esi, scrbuf",\
"mov edi, frameplace",\
"rep movsd",\
"mov ax, 0x0202",\
"out dx, ax",\
"mov ecx, 4000",\
"mov edi, frameplace",\
"rep movsd",\
"mov ax, 0x0402",\
"out dx, ax",\
"mov ecx, 4000",\
"mov edi, frameplace",\
"rep movsd",\
"mov ax, 0x0802",\
"out dx, ax",\
"mov ecx, 4000",\
"mov edi, frameplace",\
"rep movsd",\
modify [eax ecx edx esi edi]\
#pragma aux showscreen1pix320400 =\
"mov dx, 0x3c4",\
"mov ax, 0x0102",\
"out dx, ax",\
"mov ecx, 8000",\
"mov esi, scrbuf",\
"mov edi, frameplace",\
"rep movsd",\
"mov ax, 0x0202",\
"out dx, ax",\
"mov ecx, 8000",\
"mov edi, frameplace",\
"rep movsd",\
"mov ax, 0x0402",\
"out dx, ax",\
"mov ecx, 8000",\
"mov edi, frameplace",\
"rep movsd",\
"mov ax, 0x0802",\
"out dx, ax",\
"mov ecx, 8000",\
"mov edi, frameplace",\
"rep movsd",\
modify [eax ecx edx esi edi]\
#pragma aux limitrate =\
"mov dx, 0x3da",\
"wait1: in al, dx",\
"test al, 8",\
"jnz wait1",\
"wait2: in al, dx",\
"test al, 8",\
"jz wait2",\
modify exact [eax edx]\
#pragma aux setupmouse =\
"mov eax, 0",\
"int 33h",\
"mov moustat,eax",\
#pragma aux readmouse =\
"mov eax, 11d",\
"int 33h",\
"sar ecx, 1",\
"sar edx, 1",\
"mov mousx, ecx",\
"mov mousy, edx",\
modify [eax ecx edx]\
#pragma aux interruptend =\
"mov al, 20h",\
"out 20h, al",\
modify [eax]\
#pragma aux readkey =\
"in al, 0x60",\
"mov readch, al",\
"in al, 0x61",\
"or al, 0x80",\
"out 0x61, al",\
"and al, 0x7f",\
"out 0x61, al",\
modify [eax]\
// Interrupt Handlers
void __interrupt __far timerhandler()
{
clockspeed++;
interruptend();
}
void __interrupt __far keyhandler()
{
oldreadch = readch;
readkey();
if ((readch|1) == 0xe1)
extended = 128;
else
{
if (oldreadch != readch)
keystatus[(readch&127)+extended] = ((readch>>7)^1);
extended = 0;
}
interruptend();
}
// Fixed math
tsqrt(long num)
{
long root, temp;
root = 128;
do
{
temp = root;
root = ((root+(num/root))>>1);
}
while (labs(temp-root) > 1);
return(root);
}
long trand(void)
{
randomseed = (randomseed*43+1)&(65535|(65535<<16));
return(randomseed);
}
getangle(long xvect, long yvect)
{
if ((xvect|yvect) == 0) return(0);
if (xvect == yvect) return(256+((xvect<0)<<10));
if (xvect == -yvect) return(768+((xvect>0)<<10));
if (labs(xvect) > labs(yvect))
return(radarang[scale(yvect,320>>1,xvect)+(320>>1)]+((xvect<0)<<10));
return(radarang[(320>>1)-scale(xvect,320>>1,yvect)]+512+((yvect<0)<<10));
}
short angdif(short a,short na)
{
a &= 2047;
na &= 2047;
if(labs(a-na) < 1024)
return (na-a);
else
{
if(na > 1024) na -= 2048;
if(a > 1024) a -= 2048;
na -= 2048;
a -= 2048;
return (na-a);
}
}
rotatepoint(long xpivot, long ypivot, long x, long y, short daang, long *x2, long *y2)
{
*x2 = xpivot+mulscale(x-xpivot,sintable[(daang+2560)&2047],14)-mulscale(y-ypivot,sintable[(daang+2048)&2047],14);
*y2 = ypivot+mulscale(y-ypivot,sintable[(daang+2560)&2047],14)+mulscale(x-xpivot,sintable[(daang+2048)&2047],14);
}
// I/O
char loadpcx(char *fname,char *p)
{
FILE *fp;
int c, i, j, n;
/* attempt to open the file */
if((fp=fopen(fname,"rb")) == NULL)
return(1);
/* read in the pcxheader */
if( fread((char *)&pcxheader,1,sizeof(pcxtype),fp) != sizeof(pcxtype) )
return(1);
if(pcxheader.bits_per_pixel == 1)
pcxbits=pcxheader.colour_planes;
else
pcxbits=pcxheader.bits_per_pixel;
/* check to make sure it's a picture */
if(pcxbits !=8 || pcxheader.manufacturer != 0x0a || pcxheader.version != 5 )
{
fclose(fp);
return(1);
}
/* Find the palette */
if( fseek(fp,-769L,SEEK_END) == 0 )
if( fgetc(fp) !=0x0c || fread( palette,1,768,fp) != 768 )
{
fclose(fp);
return(1);
}
for(i=0;i<768;++i)
palette[i]=palette[i] >> 2;
fseek(fp,128L,SEEK_SET);
/* allocate a big buffer */
pcxwidth = (pcxheader.xmax-pcxheader.xmin)+1;
pcxdepth = (pcxheader.ymax-pcxheader.ymin)+1;
pcxbytes=pcxheader.bytes_per_line;
/* unpack the file */
for(j=0;j<pcxdepth;++j)
{
n = pcxbytes;
do
{
c=fgetc(fp) & 0xff; /* get a key byte */
if((c & 0xc0) == 0xc0) /* if it's a run of bytes field */
{
i = c&0x3f; /* and off the high pcxbits */
c=fgetc(fp); /* get the run byte */
while(i--)
*(p++)=c; /* run the byte */
}
else *(p++)=c; /* else just store it */
}
while(n--);
}
fclose(fp);
return(0);
}
iodata(char *fn,char *ptr,long len,char iotype)
{
if(iotype&IO_SAVE)
{
if (iofil != -1 || (iofil = open(fn,O_WRONLY|O_CREAT|O_TRUNC|O_BINARY,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP) ) != -1 )
{
write(iofil,ptr,len);
if( (iotype&IO_NOCLOSE) != IO_NOCLOSE)
{
close(iofil);
iofil = -1;
}
return 1;
}
return 0;
}
if (iofil != -1 || (iofil = open(fn,O_BINARY|O_RDWR,S_IREAD)) != -1)
{
read(iofil,ptr,len);
if( (iotype&IO_NOCLOSE) != IO_NOCLOSE)
{
close(iofil);
iofil = -1;
}
return 1;
}
return 0;
}
long spawn(long picnum, long owner)
{
long i;
i = insertobject(0);
object[i].owner = owner;
object[i].picnum = picnum;
object[i].x = self[screenpeek].posx;
object[i].y = self[screenpeek].posy;
object[i].z = self[screenpeek].posz;
// map.h2[((self[screenpeek].posx>>10)<<8) + (self[screenpeek].posy>>10)]<<12;
// self[screenpeek].posz;
object[i].templong = 0;
switch(picnum)
{
case 1:
object[i].ang = self[screenpeek].ang;
object[i].xvel =
sintable[(2560+self[screenpeek].ang)&2047]>>1;
object[i].yvel =
sintable[(2048+self[screenpeek].ang)&2047]>>1;
object[i].zvel = (self[screenpeek].horiz - 200)<<8;
break;
}
return(i);
}
initaboard()
{
long i, j;
randomseed = 17L;
screenpeek = 0;
for(i=0;i<MAXPLAYERS;i++)
{
self[i].posx = 0;
self[i].posy = 0;
self[i].posz = ((128-32)<<12);
self[i].ang = 0;
self[i].horiz = (MAXYDIM>>1);
}
for(i=0;i<256;i++)
for(j=0;j<256;j++)
{
if(j < 2 || j > 253 || i < 2 || i > 253)
{
map.h1[(i<<8)+j] = 0;
map.h2[(i<<8)+j] = 0;
}
else
{
map.h1[(i<<8)+j] = (i>128)<<7;
map.h2[(i<<8)+j] = 128;
}
map.c1[(i<<8)+j] = 0;
map.c2[(i<<8)+j] = 0;
}
// loadpcx("cave.pcx",&map.c1[0]);
self[screenpeek].posx = 128<<10;
self[screenpeek].posy = 128<<10;
self[screenpeek].posz = 128<<12;
initobjectlists();
}
// Memory Management
char freemem(char **addr)
{
long i;
for(i=0;i<maxchunks;i++)
if(*chunk[i].ptr == *addr)
{
chunk[i].amount = 0;
*chunk[i].ptr = (char *) NULL;
if(i == chunkloc)
chunkloc = (chunkloc - 1)%maxchunks;
return 1;
}
return 0;
}
char *getmem(char **addr,long memlen)
{
long i, templong;
// Check to see if the ptr already exists
for(i=0;i<maxchunks;i++)
if( i != chunkloc &&
chunk[i].ptr == addr &&
chunk[i].amount <= memlen )
{
chunk[i].amount = memlen;
return(*addr);
}
// Set the last pointer to NULL
*chunk[chunkloc].ptr = (char *) NULL;
// Set the next chunk to addr
chunk[chunkloc].ptr = addr;
// At end of memory!?
if( (memptr + memlen ) > totalmemory )
memptr = 0;
*addr = mainmem + memptr;
chunk[chunkloc].amount = memlen;
// NULLify all other chunks occupying same location
for(i=0;i<maxchunks;i++)
if( i != chunkloc &&
chunk[i].amount > 0 &&
*chunk[i].ptr >= (mainmem + memptr) &&
*chunk[i].ptr < (mainmem + memptr + memlen) )
{
*chunk[i].ptr = (char *) NULL;
chunk[i].amount = 0;
}
memptr += memlen;
chunkloc = (chunkloc + 1)%maxchunks;
return(mainmem + memptr - memlen);
}
// Inits/Uninits
setscreenmode()
{
long i, j;
// iodata("palette.dat",&palette[0],768L,IO_LOAD|IO_NOCLOSE);
// iodata("palette.dat",&palookup[0][0],MAXPALOOKUPS<<8,IO_LOAD);
setvmode(0x13);
toutp(0x3c4,0x4); toutp(0x3c5,0x6);
toutp(0x3d4,0x14); toutp(0x3d5,0x0);
toutp(0x3d4,0x17); toutp(0x3d5,0xe3);
if (ydim == 400)
{
toutp(0x3d4,0x9);
toutp(0x3d5,inp(0x3d5)&254);
}
for(i=0;i<768;i+=3)
{
palette[i] = i/5;
palette[i+1] = i/5;
palette[i+2] = i/3;
}
for(i=0;i<MAXPALOOKUPS;i++)
for(j=0;j<256;j++)
palookup[i][j] = MAXPALOOKUPS - i - 1;
toutp(0x3c8,0);
for(i=0;i<768;i++)
toutp(0x3c9,palette[i]);
}
void clearmemvars(void)
{
long i;
for(i=0;i<maxchunks;i++)
{
chunk[i].ptr = (char **) NULL;
chunk[i].amount = 0;
}
memptr = 0;
chunkloc = 0;
}
void initmem(void)
{
totalmemory = MAXMEMNEEDED;
do
{
mainmem = (char *) malloc(totalmemory + 1);
if(mainmem == (char *) NULL)
totalmemory -= (1<<16);
} while(mainmem == (char *) NULL && totalmemory >= MINMEMNEEDED);
if( totalmemory < MINMEMNEEDED )
{
puts("Not enough memory.");
exit(-1);
}
chunk = (chunktype *)mainmem;
totalmemory -= totalmemory>>10;
mainmem += totalmemory>>10;
maxchunks
= ( (totalmemory >> 10) / sizeof(chunktype) ) - 1;
printf("Alloc:%ld(%ld chunks) @ 0x%X.\n",totalmemory,maxchunks,mainmem);
clearmemvars();
}
void initgame(void)
{
int i, fil;
pixs = 4;
vidmode = 1;
xdim = MAXXDIM;
ydim = MAXYDIM;
frameplace = 0xa0000;
detmode = 1;
iofil = -1;
for(i=0;i<MAXYDIM;i++)
muly80[i] = i*80;
initmem();
iodata("tables.dat",(char *)&sintable[0],4096L,IO_LOAD|IO_NOCLOSE);
iodata("tables.dat",(char *)&tantable[0],4096L,IO_LOAD|IO_NOCLOSE);
iodata("tables.dat",(char *)&radarang[0],640L,IO_LOAD);
setupmouse();
if(moustat == 1)
puts("Mouse installed.");
else
puts("Mouse not found.");
oldkeyhandler = _dos_getvect(0x9);
_disable(); _dos_setvect(0x9, keyhandler); _enable();
clockspeed = 0L;
totalclock = 0L;
numframes = 0L;
toutp(0x43,54); toutp(0x40,4972&255); toutp(0x40,4972>>8);
oldtimerhandler = _dos_getvect(0x8);
_disable(); _dos_setvect(0x8, timerhandler); _enable();
getmem(&map.h1,65536L*6);
map.h2 = map.h1 + 65536L;
map.c1 = map.h2 + 65536L;
map.c2 = map.c1 + 65536L;
map.s1 = map.c2 + 65536L;
map.s2 = map.s1 + 65536L;
getmem(&scrbuf,128000L);
setscreenmode();
}
void uninitgame(void)
{
int i;
toutp(0x43,54); toutp(0x40,255); toutp(0x40,255);
_dos_setvect(0x8, oldtimerhandler);
_dos_setvect(0x9, oldkeyhandler);
setvmode(0x3);
free(mainmem);
}
void gameexit(char *message)
{
uninitgame();
puts(message);
exit(0);
}
// Sounds
void playsound(long i,long sndnum)
{
long j;
char pri;
pri = sounds[sndnum].pri;
j = 0;
while(soundplaying[j].ptr != NULL && j < MAXCHANNELS)
j++;
if(j == MAXCHANNELS)
for(j=0;j<MAXCHANNELS;j++)
if(sounds[soundplaying[j].sndno].pri <= pri)
break;
if(j == MAXCHANNELS)
return;
if(soundplaying[j].ptr == (char *) NULL)
{
getmem(&soundplaying[j].ptr,sounds[sndnum].len);
iodata(sounds[sndnum].fn,soundplaying[j].ptr,sounds[sndnum].len,IO_LOAD);
}
soundplaying[j].sndno = sndnum;
soundplaying[j].i = i;
}
void pan3dsounds(long i)
{
long j;
for(j=0;j<MAXCHANNELS;j++)
if(soundplaying[j].ptr != (char *) NULL)
{
// Pan it here to current player;
}
}
// Drawing Code
void shiftpalette(char r,char g,char b,long e)
{
int i;
char temparray[768];
toutp(0x3c8,0);
for(i=0;i<768;i+=3)
{
temparray[i+0] =
palette[i+0]+((((long)r-(long)palette[i+0])*(long)(e&127))>>6);
temparray[i+1] =
palette[i+1]+((((long)g-(long)palette[i+1])*(long)(e&127))>>6);
temparray[i+2] =
palette[i+2]+((((long)b-(long)palette[i+2])*(long)(e&127))>>6);
toutp(0x3c9,temparray[i+0]);
toutp(0x3c9,temparray[i+1]);
toutp(0x3c9,temparray[i+2]);
}
}
void fadepalette(char dir,char fspeed)
{
long i;
if(dir)
for(i = 0;i < 63;i += fspeed)
{
shiftpalette(0,0,0,i);
limitrate();
}
else
for(i = 0;i < 63;i += fspeed)
{
shiftpalette(0,0,0,63-i);
limitrate();
}
}
void light(long x, long y, long z, long myang, long deg, long rad)
{
long dadist, daplc, daang, dasin, dacos, truex, truey, dashade, anginc;
unsigned char *mapptr, *didits1, *didits2;
getmem(&didits1,65536L);
getmem(&didits2,65536L);
clearbuf(didits1,16384);
clearbuf(didits2,16384);
z >>= 12;
anginc = 1 + (rad>>4);
for(daang=myang-deg;daang < myang+deg; daang += anginc )
{
dacos = sintable[(daang+512)&2047]>>4;
dasin = sintable[(daang)&2047]>>4;
truex = x;
truey = y;
for(dadist = 1;dadist < rad; dadist++)
{
daplc = ((truex>>10)<<8)+(truey>>10);
mapptr = &map.h1[daplc];
if(didits1[daplc] == 0)
{
didits1[daplc] = 1;
dashade = scale(63, dadist + (labs(z - *mapptr)>>1), rad);
mapptr += (65536L<<2);
if(dashade < 0) *mapptr = 0;
else if(dashade < *mapptr) *mapptr = dashade;
if( z < *(mapptr-(65536L<<2)) ) break;
mapptr -= (65536L*3);
}
else mapptr += 65536L;
if(didits2[daplc] == 0)
{
didits2[daplc] = 1;
dashade = scale(63, dadist + (labs(z - *mapptr)>>1), rad);
mapptr += (65536L<<2);
if(dashade < 0) *mapptr = 0;
else if(dashade < *mapptr) *mapptr = dashade;
if( z > *(mapptr-(65536L<<2)) ) break;
}
truex += dacos;
truey += dasin;
}
}
freemem(&didits2);
freemem(&didits1);
}
void blast(long gridx, long gridy, long rad, char blastingcol)
{
short tempshort;
long i, j, dax, day, daz, dasqr, templong;
templong = rad+2;
for(i=-templong;i<=templong;i++)
for(j=-templong;j<=templong;j++)
{
dax = ((gridx+i+256)&255);
day = ((gridy+j+256)&255);
if(dax < 1 || dax > 255 || day < 1 || day > 255)
continue;
dasqr = sqr(rad)-(sqr(i)+sqr(j));
if (dasqr >= 0)
daz = tsqrt(dasqr)<<1;
else
daz = -tsqrt(-dasqr)<<1;
if ((self[screenpeek].posz>>12)-daz < map.h1[(dax<<8)+day])
{
map.h1[(dax<<8)+day] = (self[screenpeek].posz>>12)-daz;
if (((self[screenpeek].posz>>12)-daz) < 0)
map.h1[(dax<<8)+day] = 0;
}
if ((self[screenpeek].posz>>12)+daz > map.h2[(dax<<8)+day])
{
map.h2[(dax<<8)+day] = (self[screenpeek].posz>>12)+daz;
if (((self[screenpeek].posz>>12)+daz) > 255)
map.h2[(dax<<8)+day] = 255;
}
/* tempshort = map.h1[(dax<<8)+day];
if (tempshort >= map.h2[(dax<<8)+day]) tempshort = (self[screenpeek].posz>>12);
tempshort = labs(64-(tempshort&127))+(rand()&3)-2;
if (tempshort < 0) tempshort = 0;
if (tempshort > 63) tempshort = 63;
map.c1[(dax<<8)+day] = (char)(tempshort+blastingcol);
tempshort = map.h2[(dax<<8)+day];
if (tempshort <= map.h1[(dax<<8)+day]) tempshort = (self[screenpeek].posz>>12);
tempshort = labs(64-(tempshort&127))+(rand()&3)-2;
if (tempshort < 0) tempshort = 0;
if (tempshort > 63) tempshort = 63;
map.c2[(dax<<8)+day] = (char)(tempshort+blastingcol);
*/
}
}
void grouvline (long x)
{
long dist[2], dinc[2], incr[2];
short grid[2], dir[2];
unsigned char *mapptr;
char oh1, oh2;
short um, dm, h, i, horiz;
long plc1, plc2, cosval, sinval;
long snx, sny, dax, c, shade, cnt;
long posx, posy, posz, posa;
plc1 = (x>>2) + FP_OFF(scrbuf);
plc2 = plc1 + muly80[ (ydim-1) ];
switch(pixs)
{
case 1:
if ((x&2) > 0)
{
plc1 += 32000<<vidmode;
plc2 += 32000<<vidmode;
}
if ((x&1) > 0)
{
plc1 += 16000<<vidmode;
plc2 += 16000<<vidmode;
}
break;
case 2:
if ((x&2) > 0)
{
plc1 += 16000<<vidmode;
plc2 += 16000<<vidmode;
}
break;
}
posx = self[screenpeek].posx;
posy = self[screenpeek].posy;
posz = self[screenpeek].posz;
posa = self[screenpeek].ang;
horiz = self[screenpeek].horiz;
cosval = sintable[(posa+2560)&2047];
sinval = sintable[(posa+2048)&2047];
dax = (x<<1) + (pixs-1) - xdim;
incr[0] = cosval - scale(sinval,dax,xdim);
incr[1] = sinval + scale(cosval,dax,xdim);
if (incr[0] < 0) dir[0] = -1, incr[0] = -incr[0]; else dir[0] = 1;
if (incr[1] < 0) dir[1] = -1, incr[1] = -incr[1]; else dir[1] = 1;
snx = (posx&1023); if (dir[0] == 1) snx ^= 1023;
sny = (posy&1023); if (dir[1] == 1) sny ^= 1023;
cnt = ((snx*incr[1] - sny*incr[0])>>10);
grid[0] = ((posx>>10)&255); grid[1] = ((posy>>10)&255);
if (incr[0] != 0)
{
dinc[0] = divscale(65536>>vidmode,incr[0],12);
dist[0] = mulscale(dinc[0],snx,10);
}
if (incr[1] != 0)
{
dinc[1] = divscale(65536>>vidmode,incr[1],12);
dist[1] = mulscale(dinc[1],sny,10);
}
um = (0)-horiz;
dm = (ydim-1)-horiz;
i = incr[0]; incr[0] = incr[1]; incr[1] = -i;
shade = 0;
while (dist[cnt>=0] < 8192)
{
i = (cnt>=0);
grid[i] = ((grid[i]+dir[i])&255);
dist[i] += dinc[i];
cnt += incr[i];
shade++;
}
mapptr = &map.h1[(grid[0]<<8)+grid[1]];
while (shade < 256)
{
i = (cnt>=0);
oh1 = *mapptr;
oh2 = *(mapptr+65536);
h = groudiv((long)oh1,dist[i],posz);
if (um <= h)
{
c = (shade>>2) + *(mapptr + (65536<<2)); // map.s1[bufplc];
if(c > 63) c = 63;
c = palookup[c][*(mapptr + (65536<<1))]; // map.c1[bufplc]
if (h > dm) break;
plc1 = drawtopslab(plc1,h-um+1,c);
um = h+1;
}
h = groudiv((long)oh2,dist[i],posz);
if (dm >= h)
{
c = (shade>>2) + *(mapptr + (65536*5)); // map.s2[bufplc];
if(c > 63) c = 63;
c = palookup[c][*(mapptr + (65536*3))]; // map.c2[bufplc]
if (h < um) break;
plc2 = drawbotslab(plc2,dm-h+1,c);
dm = h-1;
}
grid[i] = ((grid[i]+dir[i])&255);
mapptr = &map.h1[(grid[0]<<8)+grid[1]];
if (*mapptr > oh1) // map.h1[bufplc]
{
h = groudiv((long)*mapptr,dist[i],posz); // map.h1[bufplc]
if (um <= h)
{
c = (shade>>2) + *(mapptr + (65536<<2)); // map.s1[bufplc];
if(c > 63) c = 63;
c = palookup[c][*(mapptr + (65536<<1))]; // map.c1[bufplc]
if (h > dm) break;
plc1 = drawtopslab(plc1,h-um+1,c);
um = h+1;
}
}
if (*(mapptr + 65536) < oh2) // map.h2[bufplc]
{
h = groudiv((long)*(mapptr + 65536),dist[i],posz); // map.h2[bufplc]
if (dm >= h)
{
c = (shade>>2) + *(mapptr + (65536*5)); // map.s2[bufplc];
if(c > 63) c = 63;
c = palookup[c][*(mapptr + (65536*3))]; // map.c2[bufplc]
if (h < um) break;
plc2 = drawbotslab(plc2,dm-h+1,c);
dm = h-1;
}
}
dist[i] += dinc[i];
cnt += incr[i];
shade++;
}
if (dm >= um)
{
if (shade >= 256) c = 0;
drawtopslab(plc1,dm-um+1,c);
}
}
void drawobject(long thex, long they, long thez, char *tileptr,char shade)
{
long x, y, x1, y1, x2, y2, dasizx, dasizy, xscale, yscale;
char *p;
dasizx = *(tileptr++);
dasizy = *(tileptr++);
x1 = thex;
y1 = they;
x2 = x1 + dasizx;
y2 = y1 + dasizy;
if ((x2 >= xdim) || (x2 < 0) || (x1 >= xdim) || (y2 < 0) || (y1 >= ydim))
return;
if(thez > (65536L<<1)) return;
// else if(thez > 256)
// {
// xscale = 1 + mulscale(dasizx,thez,18);
// yscale = 1 + mulscale(dasizy,thez,18);
// }
// else
xscale = yscale = 1;
p = scrbuf + muly80[y1];
switch(pixs)
{
case 1:
for(y=y1;y<y2;y++)
{
for(x=x1;x<x2;x+=xscale)
{
if(*tileptr < 255)
*(p + (mul16000[(x&3)]<<vidmode) + (x>>2)) =
*tileptr;
tileptr += xscale;
}
p += 80;
}
break;
case 2:
for(y=y1;y<y2;y++)
{
for(x=x1;x<x2;x+=(xscale<<1))
{
if(*tileptr < 255)
*(p + (mul16000[(x>>1)&1]<<vidmode) + (x>>2)) =
*tileptr;
tileptr += (xscale<<1);
}
tileptr += (x-x2)*(xscale<<1);
p += 80;
}
break;
case 4:
for(y=y1;y<y2;y++)
{
for(x=x1;x<x2;x+=(xscale<<2))
{
if(*tileptr < 255)
*(p + (x>>2) ) = palookup[shade][*tileptr];
tileptr += (xscale<<2);
}
tileptr += (x-x2)*(xscale<<2);
p += 80;
}
break;
}
}
void sortobjectstoview(void)
{
long tempx, tempy, dadist, posx, posy;
short i, j, daang, daangdif;
viewobjecttype tempviewobject;
daang = self[screenpeek].ang;
posx = self[screenpeek].posx;
posy = self[screenpeek].posy;
viewobjectcnt = 0;
for(j=0;j<MAXSTATUS;j++)
for(i = map.headobject[j];i>=0;i=map.nextobject[i])
{
daangdif = angdif(daang,getangle(object[i].x-posx,object[i].y-posy));
if( labs(daangdif) < (256) )
{
dadist = mulscale(object[i].x-posx,\
sintable[(-daang+2560)&2047],14)-mulscale(object[i].y-posy,\
sintable[(-daang+2048)&2047],14);
if( dadist > 0xff ) // && dadist < 0x18000)
{
scrnobj[viewobjectcnt].viewobject = i;
scrnobj[viewobjectcnt].viewobjectdist = dadist;
scrnobj[viewobjectcnt].viewobjectang = daangdif;
viewobjectcnt++;
}
}
}
// Bubble sort by z (furthest to closest)
for(i=0;i<(viewobjectcnt-1);i++)
for(j = (i+1);j<viewobjectcnt; j++)
if(scrnobj[j].viewobjectdist > scrnobj[i].viewobjectdist)
{
copybytes(&scrnobj[i], &tempviewobject, sizeof(viewobjecttype));
copybytes(&scrnobj[j], &scrnobj[i], sizeof(viewobjecttype));
copybytes(&tempviewobject, &scrnobj[j], sizeof(viewobjecttype));
}
}
void animateobjects(void)
{
long i, j;
if(self[screenpeek].flashlight)
light(
self[screenpeek].posx,
self[screenpeek].posy,
self[screenpeek].posz,
self[screenpeek].ang,
128,
96);
for(i=0;i<viewobjectcnt;i++)
{
j = scrnobj[i].viewobject;
light(
object[j].x,
object[j].y,
object[j].z,
0,
1024,
96);
}
}
void drawallobjects(void)
{
long i, j, posx, posy, posz, horiz;
long scrnx, scrny;
posx = self[screenpeek].posx;
posy = self[screenpeek].posy;
posz = self[screenpeek].posz;
horiz = self[screenpeek].horiz;
for(j=0;j<viewobjectcnt;j++)
{
i = scrnobj[j].viewobject;
scrnx = mulscale(MAXXDIM,256+scrnobj[j].viewobjectang,9);
scrny = scale( object[i].z-posz, 32, scrnobj[j].viewobjectdist);
drawobject(scrnx,horiz + scrny,scrnobj[j].viewobjectdist,atile,scrnobj[j].viewobjectdist>>10);
}
}
void drawmap(void)
{
long i, j;
if(self[screenpeek].topdown == 0)
{
for(i=0;i<MAXXDIM;i+=pixs)
grouvline(i);
drawallobjects();
}
else
clearbuf(scrbuf,16000,0xffffffff);
}
void nextpage(void)
{
if (vidmode == 0) //Copy to screen
{
if (pixs == 4) showscreen4pix320200();
if (pixs == 2) showscreen2pix320200();
if (pixs == 1) showscreen1pix320200();
}
else
{
if (pixs == 4) showscreen4pix320400();
if (pixs == 2) showscreen2pix320400();
if (pixs == 1) showscreen1pix320400();
}
toutp(0x3d4,0xc); toutp(0x3d5,(frameplace&65535)>>8); //Nextpage
if (vidmode == 0)
{
frameplace += 16384;
if (frameplace >= 0xb0000) frameplace = 0xa0000;
}
else
{
frameplace += 32768;
if (frameplace > 0xa8000) frameplace = 0xa0000;
}
}
void drawscreen(void)
{
sortobjectstoview();
animateobjects();
drawmap(); //Draw to non-video memory
nextpage();
}
// Object Code
void initobjectlists(void)
{
long i;
for(i=0;i<MAXSTATUS;i++)
map.headobject[i] = -1;
map.headobject[MAXSTATUS] = 0;
for(i=0;i<MAXOBJECTS;i++)
{
map.prevobject[i] = i-1;
map.nextobject[i] = i+1;
map.objectstat[i] = MAXSTATUS;
}
map.prevobject[0] = -1;
map.nextobject[MAXOBJECTS-1] = -1;
}
insertobject(short statnum)
{
short blanktouse;
if ((statnum >= MAXSTATUS) || (map.headobject[MAXSTATUS] == -1))
return(-1); //list full
blanktouse = map.headobject[MAXSTATUS];
map.headobject[MAXSTATUS] = map.nextobject[blanktouse];
if (map.headobject[MAXSTATUS] >= 0)
map.prevobject[map.headobject[MAXSTATUS]] = -1;
map.prevobject[blanktouse] = -1;
map.nextobject[blanktouse] = map.headobject[statnum];
if (map.headobject[statnum] >= 0)
map.prevobject[map.headobject[statnum]] = blanktouse;
map.headobject[statnum] = blanktouse;
map.objectstat[blanktouse] = statnum;
return(blanktouse);
}
deleteobject (short deleteme)
{
if (map.objectstat[deleteme] == MAXSTATUS)
return(-1);
if (map.headobject[map.objectstat[deleteme]] == deleteme)
map.headobject[map.objectstat[deleteme]] = map.nextobject[deleteme];
if (map.prevobject[deleteme] >= 0) map.nextobject[map.prevobject[deleteme]] = map.nextobject[deleteme];
if (map.nextobject[deleteme] >= 0) map.prevobject[map.nextobject[deleteme]] = map.prevobject[deleteme];
if (map.headobject[MAXSTATUS] >= 0) map.prevobject[map.headobject[MAXSTATUS]] = deleteme;
map.prevobject[deleteme] = -1;
map.nextobject[deleteme] = map.headobject[MAXSTATUS];
map.headobject[MAXSTATUS] = deleteme;
map.objectstat[deleteme] = MAXSTATUS;
return(0);
}
long clipmove(long *x, long *y, long *z, long vx, long vy, long vz, unsigned long rad)
{
long hiz, loz, dax, day, daz, retcode;
char charx, chary;
retcode = 0;
if( vx|vy|vz )
{
dax = *x;
day = *y;
daz = *z;
dax += vx;
day += vy;
daz += vz;
charx = (dax>>10)&255;
chary = (day>>10)&255;
hiz = map.h1[ (charx << 8) + chary ]<<12;
loz = map.h2[ (charx << 8) + chary ]<<12;
if( ( hiz + rad ) > daz )
{
daz = ( hiz + rad );
retcode = CLIP_HITCEILING|CLIP_HALT;
}
if( ( loz - rad ) < daz )
{
daz = ( loz - rad );
retcode |= CLIP_HITFLOOR;
}
dax &= 0x3ffffff;
day &= 0x3ffffff;
if( (retcode&CLIP_HALT) != CLIP_HALT )
{
*x = dax;
*y = day;
}
*z += (daz-(*z))>>2;
}
return(retcode);
}
void loadboard(char *fn)
{
iodata(fn,(char *)&map,sizeof(map),IO_LOAD|IO_NOCLOSE);
iodata(fn,(char *)&self[0],sizeof(self),IO_LOAD|IO_NOCLOSE);
iodata(fn,(char *)&object[0],sizeof(object),IO_LOAD|IO_NOCLOSE);
iodata(fn,&map.h1[0],65536L,IO_LOAD|IO_NOCLOSE);
iodata(fn,&map.c1[0],65536L,IO_LOAD|IO_NOCLOSE);
iodata(fn,&map.h2[0],65536L,IO_LOAD|IO_NOCLOSE);
iodata(fn,&map.c2[0],65536L,IO_LOAD);
}
void saveboard(char *fn)
{
iodata(fn,(char *)&map,sizeof(map),IO_SAVE|IO_NOCLOSE);
iodata(fn,(char *)&self[0],sizeof(self),IO_SAVE|IO_NOCLOSE);
iodata(fn,(char *)&object[0],sizeof(object),IO_SAVE|IO_NOCLOSE);
iodata(fn,&map.h1[0],65536L,IO_SAVE|IO_NOCLOSE);
iodata(fn,&map.c1[0],65536L,IO_SAVE|IO_NOCLOSE);
iodata(fn,&map.h2[0],65536L,IO_SAVE|IO_NOCLOSE);
iodata(fn,&map.c2[0],65536L,IO_SAVE);
}
// Player Code
void processinput(short snum)
{
long i, xvel, yvel, clipval;
if(keystatus[sc_F2] > 0)
saveboard("level_01.map");
if(keystatus[sc_F3] > 0)
loadboard("level_01.map");
if( keystatus[sc_F4] > 0)
initaboard();
if( keystatus[sc_P] > 0)
{
keystatus[sc_P] = 0;
while( keystatus[sc_P] == 0);
keystatus[sc_P] = 0;
}
if (keystatus[sc_LeftControl] > 0)
blast(((self[snum].posx>>10)&255),((self[snum].posy>>10)&255),16,trand()&255);
self[snum].vel = 0L;
self[snum].svel = 0L;
self[snum].angvel = 0;
if (moustat == 1)
{
readmouse();
self[snum].ang += mousx;
self[snum].vel = (((long)-mousy)<<1);
}
if(keystatus[sc_Space] > 0)
{
spawn(1, -1);
keystatus[sc_Space] = 0;
}
if (keystatus[sc_kpad_1] > 0)
self[snum].horiz += 16L;
if (keystatus[sc_kpad_0] > 0)
self[snum].horiz -= 16L;
if ( keystatus[sc_A] > 0 )
self[snum].posz -= (16384<<1);
// self[snum].zvel = -(4096*clockspeed>>1);
if ( keystatus[sc_Z] > 0 )
self[snum].zvel += (1024*clockspeed>>1);
if ( keystatus[sc_LeftAlt] == 0 )
{
if (keystatus[sc_RightArrow] > 0)
self[snum].angvel += 32;
if (keystatus[sc_LeftArrow] > 0)
self[snum].angvel -= 32;
}
else
{
if (keystatus[sc_RightArrow] > 0) self[snum].svel = -12L;
if (keystatus[sc_LeftArrow] > 0) self[snum].svel = 12L;
}
if (keystatus[sc_Comma] > 0) self[snum].svel = 12L;
if (keystatus[sc_Period] > 0) self[snum].svel = -12L;
if (keystatus[sc_DownArrow] > 0) self[snum].vel = -12L;
if (keystatus[sc_UpArrow] > 0) self[snum].vel = 12L;
if(keystatus[sc_F] > 0)
{
self[snum].flashlight = 1-self[snum].flashlight;
keystatus[sc_F] = 0;
}
if(keystatus[sc_CapsLock] > 0)
{
self[snum].runmode = 1-self[snum].runmode;
keystatus[sc_CapsLock] = 0;
}
if(keystatus[sc_Tab] > 0)
{
self[snum].topdown = 1-self[snum].topdown;
keystatus[sc_Tab] = 0;
}
if (keystatus[sc_LeftShift] > 0 || self[snum].runmode )
{
self[snum].vel <<= 1;
self[snum].svel <<= 1;
self[snum].angvel <<= 1;
}
if (self[snum].angvel != 0)
{
self[snum].ang += (self[snum].angvel*clockspeed)>>3;
self[snum].ang = (self[snum].ang+2048)&2047;
}
xvel =
((self[snum].vel*clockspeed*sintable[(2560+self[snum].ang)&2047])>>12)+
((self[snum].svel*clockspeed*sintable[(2048+self[snum].ang)&2047])>>12);
yvel =
((self[snum].vel*clockspeed*sintable[(2048+self[snum].ang)&2047])>>12)-
((self[snum].svel*clockspeed*sintable[(2560+self[snum].ang)&2047])>>12);
clipval = clipmove(
&self[snum].posx,
&self[snum].posy,
&self[snum].posz,
xvel,
yvel,
self[snum].zvel,
2048<<5);
if( (clipval&CLIP_HITFLOOR) != CLIP_HITFLOOR )
{
if(self[snum].zvel < 0x10000)
self[snum].zvel += clockspeed<<9;
}
else
self[snum].zvel = 0;
if (detmode == 0)
{
if ((self[snum].vel|self[snum].svel|self[snum].angvel) == 0)
pixs = 1;
else
pixs = 2;
}
if (keystatus[0x10] > 0) keystatus[0x10] = 0, pixs = 1;
if (keystatus[0x11] > 0) keystatus[0x11] = 0, pixs = 2;
if (keystatus[0x12] > 0) keystatus[0x12] = 0, pixs = 4;
if (keystatus[0x13] > 0) keystatus[0x13] = 0, detmode = 1-detmode;
if ((keystatus[0x1f]|keystatus[0x20]) > 0)
{
if (keystatus[0x1f] > 0)
{
if (vidmode == 0)
{
frameplace = 0xa0000;
vidmode = 1;
toutp(0x3d4,0x9); toutp(0x3d5,inp(0x3d5)&254);
keystatus[0x1f] = 0;
ydim = 400L;
self[snum].horiz <<= 1;
}
}
if (keystatus[0x20] > 0)
{
if (vidmode == 1)
{
vidmode = 0;
toutp(0x3d4,0x9); toutp(0x3d5,inp(0x3d5)|1);
keystatus[0x20] = 0;
ydim = 200L;
self[snum].horiz >>= 1;
}
}
}
numframes++;
totalclock += clockspeed;
clockspeed = 0L;
}
// Object Code
char thinkobject(long i)
{
long j;
objecttype *o;
char killit_flag;
o = &object[i];
killit_flag = 0;
switch(o->picnum)
{
case 1:
j = ((o->x>>10)<<8)+(o->y>>10);
if(map.h2[j] == map.h1[j] )
{
killit_flag = 1;
break;
}
object[i].templong++;
if(object[i].templong > 10)
killit_flag = 1;
break;
}
if(killit_flag) deleteobject(i);
return(killit_flag);
}
void processobjects(void)
{
long i, j, nexti;
for(j=0;j<MAXSTATUS;j++)
{
i = map.headobject[j];
while(i >= 0)
{
nexti = map.nextobject[i];
if( thinkobject(i) == 0 )
clipmove(
&object[i].x,
&object[i].y,
&object[i].z,
object[i].xvel,
object[i].yvel,
object[i].zvel,
0);
i = nexti;
}
}
}
// Main Game Loop
void gameloop(void)
{
initaboard();
drawscreen();
fadepalette(0,4);
while (keystatus[sc_Escape] == 0)
{
clearbuf(&map.s1[0],65536L>>1,0x1f1f1f1f);
processobjects();
processinput(screenpeek);
drawscreen();
pan3dsounds(self[screenpeek].i);
}
fadepalette(1,4);
}
void main(int argc, char *argv)
{
initgame();
gameloop();
gameexit("Thank you for playing!");
}
// "Duke 2000"
// "Virchua Duke"
// "Son of Death
// "Cromium"
// "Potent"
// "Flotsom"
// Volume One
// "Duke is brain dead",
// "BOOT TO THE HEAD"
// Damage too duke
// Weapons are computer cont. Only logical thinking
// is disappearing.
// " Flips! "
// Flash on screen, inst.
// "BUMS"
// "JAIL"/"MENTAL WARD (Cop code for looney? T. asks Cop.)"
// "GUTS OR GLORY"
// ( Duke's Mission
// Duke: "Looks like some kind of transporter...?"
// Byte: "...YES"
// Duke: "Waa, here goes nuthin'. "
// (Duke puts r. arm in device)
// Duke: AAAAHHHHHHHHHHHHHHHHHHHHHHHHH!!!
// (Duke's arm is seved.)
// Byte: NO.NO.NO.NO.NO.NO.NO...
// ( Byte directs duke to the nearest heat source)
// (Shut Up Mode)
// ( Duke Staggers, end of arm bleeding, usual oozing arm guts. )
// Byte: Left, Left, Left, Left, Right.
// ( Duke, loozing consc, trips on broken pipe, )
// ( hits temple on edge of step. )
// ( Rats everywhere, byte pushing them away with weapon,
// ( eventually covered, show usual groosums, Duke appears dead
// ( Duke wakes up, in hospital, vision less blurry
// ( Hospital doing brain scan, 1/3 cran. mass MISSING!
// Doc: Hummm? ( Grabbing upper lip to "appear" smart. )
// Stand back boys
// Schrapnel has busted my scull!
// Now I'nsane, Mental ward, got to escape.
// Search light everywhere.
// (M)Mendor, The Tree Dweller.
// (M)BashMan, The Destructor.
// (M)Lash, The Scavenger.
// (F)Mag, The Slut.
// (F)
// NRA OR SOMETHIN'
// Duke Nukem
// 5th Dimention
// Pentagon Man!
// I Hope your not stupid!
// The 70's meet the future.
// Dirty Harry style. 70's music with futuristic edge
// The Instant De-Welder(tm)
// I think I'm going to puke...
// Badge attitude.
// He's got a Badge, a Bulldog, a Bronco (beat up/bondoed).
// Gfx:
// Lite rail systems
// A church. Large cross
// Sniper Scope,
// Really use the phone
// The Boiler Room
// The IRS, nuking other government buildings?
// You wouldn't have a belt of booz, would ya?
// Slow turning signes
// More persise shooting/descructions
// Faces, use phoneoms and its lookup. Talking, getting in fights.
// Drug dealers, pimps, and all galore
// Weapons, Anything lying around.
// Trees to clime, burning trees.
// Sledge Hammer, Sledge hammer with Spike
// sancurary, get away from it all.
// Goodlife = ( War + Greed ) / Peace
// MonsterisM (ACTION)
// An exper
// Global Hunter (RPG)
// Slick a Wick (PUZZLE)
// Roach Condo (FUNNY)
// AntiProfit (RPG)
// Pen Patrol (TD SIM)
// 97.5 KPIG! - Wanker County
// "Fauna" - Native Indiginouns Animal Life
// Red Mercury
| {
"pile_set_name": "Github"
} |
#![allow(unused)]
use std::{convert::TryFrom, io};
use libc::{c_int, c_long, c_uint, syscall};
use super::io_uring_params;
const SETUP: c_long = 425;
const ENTER: c_long = 426;
const REGISTER: c_long = 427;
pub(crate) fn setup(
entries: c_uint,
p: *mut io_uring_params,
) -> io::Result<c_int> {
assert!(
(1..=4096).contains(&entries),
"entries must be between 1 and 4096 (inclusive)"
);
assert_eq!(
entries.count_ones(),
1,
"entries must be a power of 2"
);
#[allow(unsafe_code)]
let ret = unsafe {
syscall(SETUP, i64::from(entries), p as c_long)
};
if ret < 0 {
let mut err = io::Error::last_os_error();
if let Some(12) = err.raw_os_error() {
err = io::Error::new(
io::ErrorKind::Other,
"Not enough lockable memory. You probably \
need to raise the memlock rlimit, which \
often defaults to a pretty low number.",
);
}
return Err(err);
}
Ok(i32::try_from(ret).unwrap())
}
pub(crate) fn enter(
fd: c_int,
to_submit: c_uint,
min_complete: c_uint,
flags: c_uint,
sig: *mut libc::sigset_t,
) -> io::Result<c_int> {
loop {
// this is strapped into an interruption
// diaper loop because it's the one that
// might actually block a lot
#[allow(unsafe_code)]
let ret = unsafe {
syscall(
ENTER,
i64::from(fd),
i64::from(to_submit),
i64::from(min_complete),
i64::from(flags),
sig as c_long,
core::mem::size_of::<libc::sigset_t>()
as c_long,
)
};
if ret < 0 {
let err = io::Error::last_os_error();
if err.kind() == io::ErrorKind::Interrupted {
continue;
}
return Err(err);
} else {
return Ok(i32::try_from(ret).unwrap());
}
}
}
pub(crate) fn register(
fd: c_int,
opcode: c_uint,
arg: *const libc::c_void,
nr_args: c_uint,
) -> io::Result<c_int> {
#[allow(unsafe_code)]
let ret = unsafe {
syscall(
REGISTER,
i64::from(fd),
i64::from(opcode),
arg as c_long,
i64::from(nr_args),
)
};
if ret < 0 {
return Err(io::Error::last_os_error());
}
Ok(i32::try_from(ret).unwrap())
}
| {
"pile_set_name": "Github"
} |
package:
name: meld3
version: 0.6.10
source:
fn: meld3-0.6.10.tar.gz
url: https://pypi.python.org/packages/source/m/meld3/meld3-0.6.10.tar.gz
md5: 42e58624e9d427be7659d7a28e2b0b6f
# patches:
# List any patch files here
# - fix.patch
# build:
# entry_points:
# Put any entry points (scripts to be generated automatically) here. The
# syntax is module:function. For example
#
# - meld3 = meld3:main
#
# Would create an entry point called meld3 that calls meld3.main()
# If this is a new build for the same version, increment the build
# number. If you do not include this key, it defaults to 0.
# number: 1
requirements:
build:
- python
run:
- python
test:
# Python imports
imports:
- meld3
# commands:
# You can put test commands to be run here. Use this to test that the
# entry points work.
# You can also put a file called run_test.py in the recipe that will be run
# at test time.
# requires:
# Put any test requirements here. For example
# - nose
about:
home: https://github.com/supervisor/meld3
license: ZPL
# See
# http://docs.continuum.io/conda/build.html for
# more information about meta.yaml
| {
"pile_set_name": "Github"
} |
# Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
# pylint: disable=no-init,invalid-name
import math
import numpy as np
import mantid.simpleapi as ms
from mantid import logger, mtd
from mantid.api import (PythonAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty,
ITableWorkspaceProperty, PropertyMode, WorkspaceFactory, Progress)
from mantid.kernel import Direction, IntArrayProperty
# pylint: disable=too-many-instance-attributes
class Symmetrise(PythonAlgorithm):
_sample = None
_x_min = None
_x_max = None
_spectra_range = None
_output_workspace = None
_props_output_workspace = None
_positive_min_index = None
_positive_max_index = None
_negative_min_index = None
def category(self):
return 'CorrectionFunctions\\SpecialCorrections'
def summary(self):
return 'Make asymmetric workspace data symmetric.'
def PyInit(self):
self.declareProperty(MatrixWorkspaceProperty('InputWorkspace', '', Direction.Input),
doc='Sample to run with')
self.declareProperty(IntArrayProperty(name='SpectraRange'),
doc='Range of spectra to symmetrise (defaults to entire range if not set)')
self.declareProperty('XMin', 0.0, doc='X value marking lower limit of curve to copy')
self.declareProperty('XMax', 0.0, doc='X value marking upper limit of curve to copy')
self.declareProperty(MatrixWorkspaceProperty('OutputWorkspace', '',
Direction.Output), doc='Name to call the output workspace.')
self.declareProperty(ITableWorkspaceProperty('OutputPropertiesTable', '',
Direction.Output, PropertyMode.Optional),
doc='Name to call the properties output table workspace.')
# pylint: disable=too-many-locals
def PyExec(self):
workflow_prog = Progress(self, start=0.0, end=0.3, nreports=4)
workflow_prog.report('Setting up algorithm')
self._setup()
input_ws = mtd[self._sample]
min_spectrum_index = input_ws.getIndexFromSpectrumNumber(int(self._spectra_range[0]))
max_spectrum_index = input_ws.getIndexFromSpectrumNumber(int(self._spectra_range[1]))
# Crop to the required spectra range
workflow_prog.report('Cropping Workspace')
cropped_input = ms.CropWorkspace(InputWorkspace=input_ws,
OutputWorkspace='__symm',
StartWorkspaceIndex=min_spectrum_index,
EndWorkspaceIndex=max_spectrum_index)
# Find the smallest data array in the first spectra
len_x = len(cropped_input.readX(0))
len_y = len(cropped_input.readY(0))
len_e = len(cropped_input.readE(0))
sample_array_len = min(len_x, len_y, len_e)
sample_x = cropped_input.readX(0)
# Get slice bounds of array
try:
workflow_prog.report('Calculating array points')
self._calculate_array_points(sample_x, sample_array_len)
except Exception as exc:
raise RuntimeError('Failed to calculate array slice boundaries: %s' % exc.message)
max_sample_index = sample_array_len - 1
centre_range_len = self._positive_min_index + self._negative_min_index
positive_diff_range_len = max_sample_index - self._positive_max_index
output_cut_index = max_sample_index - self._positive_min_index - positive_diff_range_len - 1
new_array_len = 2 * max_sample_index - centre_range_len - 2 * positive_diff_range_len - 1
logger.information('Sample array length = %d' % sample_array_len)
logger.information('Positive X min at i=%d, x=%f'
% (self._positive_min_index, sample_x[self._positive_min_index]))
logger.information('Negative X min at i=%d, x=%f'
% (self._negative_min_index, sample_x[self._negative_min_index]))
logger.information('Positive X max at i=%d, x=%f'
% (self._positive_max_index, sample_x[self._positive_max_index]))
logger.information('New array length = %d' % new_array_len)
logger.information('Output array LR split index = %d' % output_cut_index)
# Create an empty workspace with enough storage for the new data
workflow_prog.report('Creating OutputWorkspace')
out_ws = WorkspaceFactory.Instance().create(cropped_input, cropped_input.getNumberHistograms(),
int(new_array_len), int(new_array_len))
# For each spectrum copy positive values to the negative
pop_prog = Progress(self, start=0.3, end=0.95, nreports=out_ws.getNumberHistograms())
for idx in range(out_ws.getNumberHistograms()):
pop_prog.report('Populating data in workspace %i' % idx)
# Strip any additional array cells
x_in = cropped_input.readX(idx)[:sample_array_len]
y_in = cropped_input.readY(idx)[:sample_array_len]
e_in = cropped_input.readE(idx)[:sample_array_len]
# Get some zeroed data to overwrite with copies from sample
x_out = np.zeros(new_array_len)
y_out = np.zeros(new_array_len)
e_out = np.zeros(new_array_len)
# Left hand side (reflected)
x_out[:output_cut_index] = -x_in[self._positive_max_index - 1:self._positive_min_index:-1]
y_out[:output_cut_index] = y_in[self._positive_max_index - 1:self._positive_min_index:-1]
e_out[:output_cut_index] = e_in[self._positive_max_index - 1:self._positive_min_index:-1]
# Right hand side (copied)
x_out[output_cut_index:] = x_in[self._negative_min_index:self._positive_max_index]
y_out[output_cut_index:] = y_in[self._negative_min_index:self._positive_max_index]
e_out[output_cut_index:] = e_in[self._negative_min_index:self._positive_max_index]
# Set output spectrum data
out_ws.setX(idx, x_out)
out_ws.setY(idx, y_out)
out_ws.setE(idx, e_out)
logger.information('Symmetrise spectrum %d' % idx)
end_prog = Progress(self, start=0.95, end=1.0, nreports=3)
end_prog.report('Deleting temp workspaces')
ms.DeleteWorkspace(cropped_input)
if self._props_output_workspace != '':
end_prog.report('Generating property table')
self._generate_props_table()
self.setProperty('OutputWorkspace', out_ws)
end_prog.report('Algorithm Complete')
def validateInputs(self):
"""
Checks for invalid input properties.
"""
from IndirectCommon import CheckHistZero
issues = dict()
input_workspace_name = self.getPropertyValue('InputWorkspace')
# Validate spectra range
spectra_range = self.getProperty('SpectraRange').value
if len(spectra_range) != 0 and len(spectra_range) != 2:
issues['SpectraRange'] = 'Must be in format "spec_min,spec_max"'
if len(spectra_range) == 2:
spec_min = spectra_range[0]
spec_max = spectra_range[1]
num_sample_spectra, _ = CheckHistZero(input_workspace_name)
min_spectra_number = mtd[input_workspace_name].getSpectrum(0).getSpectrumNo()
max_spectra_number = mtd[input_workspace_name].getSpectrum(num_sample_spectra - 1).getSpectrumNo()
if spec_min < min_spectra_number:
issues['SpectraRange'] = 'Minimum spectra must be greater than or equal to %d' % min_spectra_number
if spec_max > max_spectra_number:
issues['SpectraRange'] = 'Maximum spectra must be less than or equal to %d' % max_spectra_number
if spec_max < spec_min:
issues['SpectraRange'] = 'Minimum spectra must be smaller than maximum spectra'
# Validate X range
x_min = self.getProperty('XMin').value
if x_min < -1e-5:
issues['XMin'] = 'XMin must be greater than or equal to zero'
x_max = self.getProperty('XMax').value
if x_max < 1e-5:
issues['XMax'] = 'XMax must be greater than zero'
if math.fabs(x_max - x_min) < 1e-5:
issues['XMin'] = 'X range is close to zero'
issues['XMax'] = 'X range is close to zero'
if x_max < x_min:
issues['XMin'] = 'XMin must be less than XMax'
issues['XMax'] = 'XMax must be greater than XMin'
# Valudate X range against workspace X range
sample_x = mtd[input_workspace_name].readX(0)
sample_x_min = sample_x.min()
sample_x_max = sample_x.max()
if x_max > sample_x_max:
issues['XMax'] = 'XMax value (%f) is greater than largest X value (%f)' % (x_max, sample_x_max)
if -x_min < sample_x_min:
issues['XMin'] = 'Negative XMin value (%f) is less than smallest X value (%f)' % (-x_min, sample_x_min)
return issues
def _setup(self):
"""
Get the algorithm properties and validate them.
"""
from IndirectCommon import CheckHistZero
self._sample = self.getPropertyValue('InputWorkspace')
self._x_min = math.fabs(self.getProperty('XMin').value)
self._x_max = math.fabs(self.getProperty('XMax').value)
self._spectra_range = self.getProperty('SpectraRange').value
# If the user did not enter a spectra range, use the spectra range of the workspace
if len(self._spectra_range) == 0:
num_sample_spectra, _ = CheckHistZero(self._sample)
min_spectra_number = mtd[self._sample].getSpectrum(0).getSpectrumNo()
max_spectra_number = mtd[self._sample].getSpectrum(num_sample_spectra - 1).getSpectrumNo()
self._spectra_range = [min_spectra_number, max_spectra_number]
self._output_workspace = self.getPropertyValue('OutputWorkspace')
self._props_output_workspace = self.getPropertyValue('OutputPropertiesTable')
def _calculate_array_points(self, sample_x, sample_array_len):
"""
Finds the points in the array that match the cut points.
@param sample_x - Sample X axis data
@param sample_array_len - Length of data array for sample data
"""
# Find array index of the first negative XMin
delta_x = sample_x[1] - sample_x[0]
negative_min_diff = np.absolute(sample_x + self._x_min)
self._negative_min_index = np.where(negative_min_diff < delta_x)[0][-1]
self._check_bounds(self._negative_min_index, sample_array_len, label='Negative')
# Find array index of the first positive XMin, that is smaller than the required
positive_min_diff = np.absolute(sample_x + sample_x[self._negative_min_index])
self._positive_min_index = np.where(positive_min_diff < delta_x)[0][-1]
self._check_bounds(self._positive_min_index, sample_array_len, label='Positive')
# Find array index of the first positive XMax, that is smaller than the required
self._positive_max_index = np.where(sample_x < self._x_max)[0][-1]
if self._positive_max_index == sample_array_len:
self._positive_max_index -= 1
self._check_bounds(self._positive_max_index, sample_array_len, label='Positive')
def _check_bounds(self, index, num_pts, label=''):
"""
Check if the index falls within the bounds of the x range.
Throws a ValueError if the x point falls outside of the range.
@param index - value of the index within the x range.
@param num_pts - total number of points in the range.
@param label - label to call the point if an error is thrown.
"""
if index < 0:
raise ValueError('%s point %d < 0' % (label, index))
elif index >= num_pts:
raise ValueError('%s point %d > %d' % (label, index, num_pts))
def _generate_props_table(self):
"""
Creates a table workspace with values calculated in algorithm.
"""
props_table = ms.CreateEmptyTableWorkspace(OutputWorkspace=self._props_output_workspace)
props_table.addColumn('int', 'NegativeXMinIndex')
props_table.addColumn('int', 'PositiveXMinIndex')
props_table.addColumn('int', 'PositiveXMaxIndex')
props_table.addRow([int(self._negative_min_index), int(self._positive_min_index),
int(self._positive_max_index)])
self.setProperty('OutputPropertiesTable', self._props_output_workspace)
# Register algorithm with Mantid
AlgorithmFactory.subscribe(Symmetrise)
| {
"pile_set_name": "Github"
} |
module Goliath
module Rack
#
# Include this to enable middleware that can perform pre- and
# post-processing.
#
# For internal reasons, you can't do the following as you would in Rack:
#
# def call(env)
# # ... do pre-processing
# status, headers, body = @app.call(env)
# new_body = make_totally_awesome(body) ## !! BROKEN !!
# [status, headers, new_body]
# end
#
# This class creates a "aroundware" helper to do that kind of
# processing. Goliath proceeds asynchronously, but will still "unwind" the
# request by walking up the callback chain. Delegating out to the aroundware
# also lets you carry state around -- the ban on instance variables no
# longer applies, as each aroundware is unique per request.
#
# @see Goliath::Rack::AsyncMiddleware
# @see Goliath::Rack::SimpleAroundware
# @see Goliath::Rack::BarrierAroundware
#
class SimpleAroundwareFactory
include Goliath::Rack::Validator
# Called by the framework to create the middleware.
#
# Any extra args passed to the use statement are sent to each
# aroundware_klass as it is created.
#
# @example
# class Awesomizer2011
# include Goliath::Rack::SimpleAroundware
# def initialize(env, aq)
# @awesomeness_quotient = aq
# super(env)
# end
# # ... define pre_process and post_process ...
# end
#
# class AwesomeApiWithShortening < Goliath::API
# use Goliath::Rack::SimpleAroundwareFactory, Awesomizer2011, 3
# # ... stuff ...
# end
#
# @param app [#call] the downstream app
# @param aroundware_klass a class that quacks like a
# Goliath::Rack::SimpleAroundware and an EM::Deferrable
# @param *args [Array] extra args to pass to the aroundware
# @return [Goliath::Rack::AroundwareFactory]
def initialize app, aroundware_klass, *args
@app = app
@aroundware_klass = aroundware_klass
@aroundware_args = args
end
# Coordinates aroundware to process a request.
#
# We hook the aroundware in the middle of the async_callback chain:
# * send the downstream response to the aroundware, whether received directly
# from @app.call or via async callback
# * have the upstream callback chain be invoked when the aroundware completes
#
# @param env [Goliath::Env] The goliath environment
# @return [Array] The [status_code, headers, body] tuple
def call(env)
aroundware = new_aroundware(env)
aroundware_resp = aroundware.pre_process
return aroundware_resp if final_response?(aroundware_resp)
hook_into_callback_chain(env, aroundware)
downstream_resp = @app.call(env)
# if downstream resp is final, pass it to the aroundware; it will invoke
# the callback chain at its leisure. Our response is *always* async.
if final_response?(downstream_resp)
aroundware.accept_response(:downstream_resp, true, downstream_resp)
end
return Goliath::Connection::AsyncResponse
end
# Put aroundware in the middle of the async_callback chain:
# * save the old callback chain;
# * have the downstream callback send results to the aroundware (possibly
# completing it)
# * set the old callback chain to fire when the aroundware completes
def hook_into_callback_chain(env, aroundware)
async_callback = env['async.callback']
# The response from the downstream app is accepted by the aroundware...
# ... and we immediately call post_process and hand it upstream
downstream_callback = Proc.new do |resp|
safely(env){ aroundware.accept_response(:downstream_resp, true, resp) }
new_resp = safely(env){ aroundware.post_process }
async_callback.call(new_resp)
end
env['async.callback'] = downstream_callback
end
def final_response?(resp)
resp != Goliath::Connection::AsyncResponse
end
# Generate a aroundware to process the request, using request env & any args
# passed to this AroundwareFactory at creation
#
# @param env [Goliath::Env] The goliath environment
# @return [Goliath::Rack::SimpleAroundware] The aroundware to process this request
def new_aroundware(env)
@aroundware_klass.new(env, *@aroundware_args)
end
end
end
end
| {
"pile_set_name": "Github"
} |
/******************************************************************************
* SOFA, Simulation Open-Framework Architecture *
* (c) 2006 INRIA, USTL, UJF, CNRS, MGH *
* *
* 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 2.1 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, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#include <SofaOpenglVisual/ClipPlane.h>
#include <sofa/core/visual/VisualParams.h>
#include <sofa/core/ObjectFactory.h>
#include <cmath>
using sofa::core::objectmodel::ComponentState ;
namespace sofa
{
namespace component
{
namespace visualmodel
{
int ClipPlaneClass = core::RegisterObject("OpenGL Clipping Plane")
.add< ClipPlane >()
;
ClipPlane::ClipPlane()
: position(initData(&position, sofa::defaulttype::Vector3(0,0,0), "position", "Point crossed by the clipping plane"))
, normal(initData(&normal, sofa::defaulttype::Vector3(1,0,0), "normal", "Normal of the clipping plane, pointing toward the clipped region"))
, id(initData(&id, 0, "id", "Clipping plane OpenGL ID"))
, active(initData(&active,true,"active","Control whether the clipping plane should be applied or not"))
{
}
ClipPlane::~ClipPlane()
{
}
sofa::core::objectmodel::ComponentState ClipPlane::checkDataValues()
{
if(id.getValue() < 0)
{
msg_error() << "plane ID cannot be negative. The component is disabled." ;
return ComponentState::Invalid;
}
return ComponentState::Valid;
}
void ClipPlane::init()
{
d_componentState.setValue(checkDataValues()) ;
}
void ClipPlane::reinit()
{
if(d_componentState.getValue() == ComponentState::Invalid)
msg_error() << "Reiniting an invalid component is not allowed. It must be inited first" ;
}
void ClipPlane::fwdDraw(core::visual::VisualParams*)
{
if(d_componentState.getValue() == ComponentState::Invalid)
return ;
wasActive = glIsEnabled(GL_CLIP_PLANE0+id.getValue());
if (active.getValue())
{
glGetClipPlane(GL_CLIP_PLANE0+id.getValue(), saveEq);
sofa::defaulttype::Vector3 p = position.getValue();
sofa::defaulttype::Vector3 n = normal.getValue();
GLdouble c[4] = { (GLdouble) -n[0], (GLdouble)-n[1], (GLdouble)-n[2], (GLdouble)(p*n) };
glClipPlane(GL_CLIP_PLANE0+id.getValue(), c);
if (!wasActive)
glEnable(GL_CLIP_PLANE0+id.getValue());
}
else
{
if (wasActive)
glDisable(GL_CLIP_PLANE0+id.getValue());
}
}
void ClipPlane::bwdDraw(core::visual::VisualParams*)
{
if (active.getValue())
{
glClipPlane(GL_CLIP_PLANE0+id.getValue(), saveEq);
if (!wasActive)
glDisable(GL_CLIP_PLANE0+id.getValue());
}
else
{
if (wasActive)
glEnable(GL_CLIP_PLANE0+id.getValue());
}
}
} // namespace visualmodel
} //namespace component
} //namespace sofa
| {
"pile_set_name": "Github"
} |
/*
Description: Foundation 4 docs style for highlight.js
Author: Dan Allen <[email protected]>
Website: http://foundation.zurb.com/docs/
Version: 1.0
Date: 2013-04-02
*/
.hljs {
display: block;
overflow-x: auto;
padding: 0.5em;
background: #eee;
-webkit-text-size-adjust: none;
}
.hljs-header,
.hljs-decorator,
.hljs-annotation {
color: #000077;
}
.hljs-horizontal_rule,
.hljs-link_url,
.hljs-emphasis,
.hljs-attribute {
color: #070;
}
.hljs-emphasis {
font-style: italic;
}
.hljs-link_label,
.hljs-strong,
.hljs-value,
.hljs-string,
.scss .hljs-value .hljs-string {
color: #d14;
}
.hljs-strong {
font-weight: bold;
}
.hljs-blockquote,
.hljs-comment {
color: #998;
font-style: italic;
}
.asciidoc .hljs-title,
.hljs-function .hljs-title {
color: #900;
}
.hljs-class {
color: #458;
}
.hljs-id,
.hljs-pseudo,
.hljs-constant,
.hljs-hexcolor {
color: teal;
}
.hljs-variable {
color: #336699;
}
.hljs-bullet,
.hljs-javadoc {
color: #997700;
}
.hljs-pi,
.hljs-doctype {
color: #3344bb;
}
.hljs-code,
.hljs-number {
color: #099;
}
.hljs-important {
color: #f00;
}
.smartquote,
.hljs-label {
color: #970;
}
.hljs-preprocessor,
.hljs-pragma {
color: #579;
}
.hljs-reserved,
.hljs-keyword,
.scss .hljs-value {
color: #000;
}
.hljs-regexp {
background-color: #fff0ff;
color: #880088;
}
.hljs-symbol {
color: #990073;
}
.hljs-symbol .hljs-string {
color: #a60;
}
.hljs-tag {
color: #007700;
}
.hljs-at_rule,
.hljs-at_rule .hljs-keyword {
color: #088;
}
.hljs-at_rule .hljs-preprocessor {
color: #808;
}
.scss .hljs-tag,
.scss .hljs-attribute {
color: #339;
}
| {
"pile_set_name": "Github"
} |
FILE(REMOVE_RECURSE
"CMakeFiles/uarm_generate_messages_cpp"
"/home/ewenwan/ewenwan/catkin_ws/devel/include/uarm/CoordsWithTime.h"
"/home/ewenwan/ewenwan/catkin_ws/devel/include/uarm/Angles.h"
"/home/ewenwan/ewenwan/catkin_ws/devel/include/uarm/CoordsWithTS4.h"
"/home/ewenwan/ewenwan/catkin_ws/devel/include/uarm/Coords.h"
)
# Per-language clean rules from dependency scanning.
FOREACH(lang)
INCLUDE(CMakeFiles/uarm_generate_messages_cpp.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)
| {
"pile_set_name": "Github"
} |
// most Object methods by ES6 should accept primitives
var $export = require('./$.export')
, core = require('./$.core')
, fails = require('./$.fails');
module.exports = function(KEY, exec){
var fn = (core.Object || {})[KEY] || Object[KEY]
, exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
}; | {
"pile_set_name": "Github"
} |
Utils/
| {
"pile_set_name": "Github"
} |
package session
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/corehandlers"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/csm"
"github.com/aws/aws-sdk-go/aws/defaults"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/aws/request"
)
const (
// ErrCodeSharedConfig represents an error that occurs in the shared
// configuration logic
ErrCodeSharedConfig = "SharedConfigErr"
)
// ErrSharedConfigSourceCollision will be returned if a section contains both
// source_profile and credential_source
var ErrSharedConfigSourceCollision = awserr.New(ErrCodeSharedConfig, "only source profile or credential source can be specified, not both", nil)
// ErrSharedConfigECSContainerEnvVarEmpty will be returned if the environment
// variables are empty and Environment was set as the credential source
var ErrSharedConfigECSContainerEnvVarEmpty = awserr.New(ErrCodeSharedConfig, "EcsContainer was specified as the credential_source, but 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' was not set", nil)
// ErrSharedConfigInvalidCredSource will be returned if an invalid credential source was provided
var ErrSharedConfigInvalidCredSource = awserr.New(ErrCodeSharedConfig, "credential source values must be EcsContainer, Ec2InstanceMetadata, or Environment", nil)
// A Session provides a central location to create service clients from and
// store configurations and request handlers for those services.
//
// Sessions are safe to create service clients concurrently, but it is not safe
// to mutate the Session concurrently.
//
// The Session satisfies the service client's client.ConfigProvider.
type Session struct {
Config *aws.Config
Handlers request.Handlers
}
// New creates a new instance of the handlers merging in the provided configs
// on top of the SDK's default configurations. Once the Session is created it
// can be mutated to modify the Config or Handlers. The Session is safe to be
// read concurrently, but it should not be written to concurrently.
//
// If the AWS_SDK_LOAD_CONFIG environment is set to a truthy value, the New
// method could now encounter an error when loading the configuration. When
// The environment variable is set, and an error occurs, New will return a
// session that will fail all requests reporting the error that occurred while
// loading the session. Use NewSession to get the error when creating the
// session.
//
// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value
// the shared config file (~/.aws/config) will also be loaded, in addition to
// the shared credentials file (~/.aws/credentials). Values set in both the
// shared config, and shared credentials will be taken from the shared
// credentials file.
//
// Deprecated: Use NewSession functions to create sessions instead. NewSession
// has the same functionality as New except an error can be returned when the
// func is called instead of waiting to receive an error until a request is made.
func New(cfgs ...*aws.Config) *Session {
// load initial config from environment
envCfg, envErr := loadEnvConfig()
if envCfg.EnableSharedConfig {
var cfg aws.Config
cfg.MergeIn(cfgs...)
s, err := NewSessionWithOptions(Options{
Config: cfg,
SharedConfigState: SharedConfigEnable,
})
if err != nil {
// Old session.New expected all errors to be discovered when
// a request is made, and would report the errors then. This
// needs to be replicated if an error occurs while creating
// the session.
msg := "failed to create session with AWS_SDK_LOAD_CONFIG enabled. " +
"Use session.NewSession to handle errors occurring during session creation."
// Session creation failed, need to report the error and prevent
// any requests from succeeding.
s = &Session{Config: defaults.Config()}
s.logDeprecatedNewSessionError(msg, err, cfgs)
}
return s
}
s := deprecatedNewSession(cfgs...)
if envErr != nil {
msg := "failed to load env config"
s.logDeprecatedNewSessionError(msg, envErr, cfgs)
}
if csmCfg, err := loadCSMConfig(envCfg, []string{}); err != nil {
if l := s.Config.Logger; l != nil {
l.Log(fmt.Sprintf("ERROR: failed to load CSM configuration, %v", err))
}
} else if csmCfg.Enabled {
err := enableCSM(&s.Handlers, csmCfg, s.Config.Logger)
if err != nil {
msg := "failed to enable CSM"
s.logDeprecatedNewSessionError(msg, err, cfgs)
}
}
return s
}
// NewSession returns a new Session created from SDK defaults, config files,
// environment, and user provided config files. Once the Session is created
// it can be mutated to modify the Config or Handlers. The Session is safe to
// be read concurrently, but it should not be written to concurrently.
//
// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value
// the shared config file (~/.aws/config) will also be loaded in addition to
// the shared credentials file (~/.aws/credentials). Values set in both the
// shared config, and shared credentials will be taken from the shared
// credentials file. Enabling the Shared Config will also allow the Session
// to be built with retrieving credentials with AssumeRole set in the config.
//
// See the NewSessionWithOptions func for information on how to override or
// control through code how the Session will be created, such as specifying the
// config profile, and controlling if shared config is enabled or not.
func NewSession(cfgs ...*aws.Config) (*Session, error) {
opts := Options{}
opts.Config.MergeIn(cfgs...)
return NewSessionWithOptions(opts)
}
// SharedConfigState provides the ability to optionally override the state
// of the session's creation based on the shared config being enabled or
// disabled.
type SharedConfigState int
const (
// SharedConfigStateFromEnv does not override any state of the
// AWS_SDK_LOAD_CONFIG env var. It is the default value of the
// SharedConfigState type.
SharedConfigStateFromEnv SharedConfigState = iota
// SharedConfigDisable overrides the AWS_SDK_LOAD_CONFIG env var value
// and disables the shared config functionality.
SharedConfigDisable
// SharedConfigEnable overrides the AWS_SDK_LOAD_CONFIG env var value
// and enables the shared config functionality.
SharedConfigEnable
)
// Options provides the means to control how a Session is created and what
// configuration values will be loaded.
//
type Options struct {
// Provides config values for the SDK to use when creating service clients
// and making API requests to services. Any value set in with this field
// will override the associated value provided by the SDK defaults,
// environment or config files where relevant.
//
// If not set, configuration values from from SDK defaults, environment,
// config will be used.
Config aws.Config
// Overrides the config profile the Session should be created from. If not
// set the value of the environment variable will be loaded (AWS_PROFILE,
// or AWS_DEFAULT_PROFILE if the Shared Config is enabled).
//
// If not set and environment variables are not set the "default"
// (DefaultSharedConfigProfile) will be used as the profile to load the
// session config from.
Profile string
// Instructs how the Session will be created based on the AWS_SDK_LOAD_CONFIG
// environment variable. By default a Session will be created using the
// value provided by the AWS_SDK_LOAD_CONFIG environment variable.
//
// Setting this value to SharedConfigEnable or SharedConfigDisable
// will allow you to override the AWS_SDK_LOAD_CONFIG environment variable
// and enable or disable the shared config functionality.
SharedConfigState SharedConfigState
// Ordered list of files the session will load configuration from.
// It will override environment variable AWS_SHARED_CREDENTIALS_FILE, AWS_CONFIG_FILE.
SharedConfigFiles []string
// When the SDK's shared config is configured to assume a role with MFA
// this option is required in order to provide the mechanism that will
// retrieve the MFA token. There is no default value for this field. If
// it is not set an error will be returned when creating the session.
//
// This token provider will be called when ever the assumed role's
// credentials need to be refreshed. Within the context of service clients
// all sharing the same session the SDK will ensure calls to the token
// provider are atomic. When sharing a token provider across multiple
// sessions additional synchronization logic is needed to ensure the
// token providers do not introduce race conditions. It is recommend to
// share the session where possible.
//
// stscreds.StdinTokenProvider is a basic implementation that will prompt
// from stdin for the MFA token code.
//
// This field is only used if the shared configuration is enabled, and
// the config enables assume role wit MFA via the mfa_serial field.
AssumeRoleTokenProvider func() (string, error)
// When the SDK's shared config is configured to assume a role this option
// may be provided to set the expiry duration of the STS credentials.
// Defaults to 15 minutes if not set as documented in the
// stscreds.AssumeRoleProvider.
AssumeRoleDuration time.Duration
// Reader for a custom Credentials Authority (CA) bundle in PEM format that
// the SDK will use instead of the default system's root CA bundle. Use this
// only if you want to replace the CA bundle the SDK uses for TLS requests.
//
// Enabling this option will attempt to merge the Transport into the SDK's HTTP
// client. If the client's Transport is not a http.Transport an error will be
// returned. If the Transport's TLS config is set this option will cause the SDK
// to overwrite the Transport's TLS config's RootCAs value. If the CA
// bundle reader contains multiple certificates all of them will be loaded.
//
// The Session option CustomCABundle is also available when creating sessions
// to also enable this feature. CustomCABundle session option field has priority
// over the AWS_CA_BUNDLE environment variable, and will be used if both are set.
CustomCABundle io.Reader
// The handlers that the session and all API clients will be created with.
// This must be a complete set of handlers. Use the defaults.Handlers()
// function to initialize this value before changing the handlers to be
// used by the SDK.
Handlers request.Handlers
}
// NewSessionWithOptions returns a new Session created from SDK defaults, config files,
// environment, and user provided config files. This func uses the Options
// values to configure how the Session is created.
//
// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value
// the shared config file (~/.aws/config) will also be loaded in addition to
// the shared credentials file (~/.aws/credentials). Values set in both the
// shared config, and shared credentials will be taken from the shared
// credentials file. Enabling the Shared Config will also allow the Session
// to be built with retrieving credentials with AssumeRole set in the config.
//
// // Equivalent to session.New
// sess := session.Must(session.NewSessionWithOptions(session.Options{}))
//
// // Specify profile to load for the session's config
// sess := session.Must(session.NewSessionWithOptions(session.Options{
// Profile: "profile_name",
// }))
//
// // Specify profile for config and region for requests
// sess := session.Must(session.NewSessionWithOptions(session.Options{
// Config: aws.Config{Region: aws.String("us-east-1")},
// Profile: "profile_name",
// }))
//
// // Force enable Shared Config support
// sess := session.Must(session.NewSessionWithOptions(session.Options{
// SharedConfigState: session.SharedConfigEnable,
// }))
func NewSessionWithOptions(opts Options) (*Session, error) {
var envCfg envConfig
var err error
if opts.SharedConfigState == SharedConfigEnable {
envCfg, err = loadSharedEnvConfig()
if err != nil {
return nil, fmt.Errorf("failed to load shared config, %v", err)
}
} else {
envCfg, err = loadEnvConfig()
if err != nil {
return nil, fmt.Errorf("failed to load environment config, %v", err)
}
}
if len(opts.Profile) != 0 {
envCfg.Profile = opts.Profile
}
switch opts.SharedConfigState {
case SharedConfigDisable:
envCfg.EnableSharedConfig = false
case SharedConfigEnable:
envCfg.EnableSharedConfig = true
}
// Only use AWS_CA_BUNDLE if session option is not provided.
if len(envCfg.CustomCABundle) != 0 && opts.CustomCABundle == nil {
f, err := os.Open(envCfg.CustomCABundle)
if err != nil {
return nil, awserr.New("LoadCustomCABundleError",
"failed to open custom CA bundle PEM file", err)
}
defer f.Close()
opts.CustomCABundle = f
}
return newSession(opts, envCfg, &opts.Config)
}
// Must is a helper function to ensure the Session is valid and there was no
// error when calling a NewSession function.
//
// This helper is intended to be used in variable initialization to load the
// Session and configuration at startup. Such as:
//
// var sess = session.Must(session.NewSession())
func Must(sess *Session, err error) *Session {
if err != nil {
panic(err)
}
return sess
}
func deprecatedNewSession(cfgs ...*aws.Config) *Session {
cfg := defaults.Config()
handlers := defaults.Handlers()
// Apply the passed in configs so the configuration can be applied to the
// default credential chain
cfg.MergeIn(cfgs...)
if cfg.EndpointResolver == nil {
// An endpoint resolver is required for a session to be able to provide
// endpoints for service client configurations.
cfg.EndpointResolver = endpoints.DefaultResolver()
}
cfg.Credentials = defaults.CredChain(cfg, handlers)
// Reapply any passed in configs to override credentials if set
cfg.MergeIn(cfgs...)
s := &Session{
Config: cfg,
Handlers: handlers,
}
initHandlers(s)
return s
}
func enableCSM(handlers *request.Handlers, cfg csmConfig, logger aws.Logger) error {
if logger != nil {
logger.Log("Enabling CSM")
}
r, err := csm.Start(cfg.ClientID, csm.AddressWithDefaults(cfg.Host, cfg.Port))
if err != nil {
return err
}
r.InjectHandlers(handlers)
return nil
}
func newSession(opts Options, envCfg envConfig, cfgs ...*aws.Config) (*Session, error) {
cfg := defaults.Config()
handlers := opts.Handlers
if handlers.IsEmpty() {
handlers = defaults.Handlers()
}
// Get a merged version of the user provided config to determine if
// credentials were.
userCfg := &aws.Config{}
userCfg.MergeIn(cfgs...)
cfg.MergeIn(userCfg)
// Ordered config files will be loaded in with later files overwriting
// previous config file values.
var cfgFiles []string
if opts.SharedConfigFiles != nil {
cfgFiles = opts.SharedConfigFiles
} else {
cfgFiles = []string{envCfg.SharedConfigFile, envCfg.SharedCredentialsFile}
if !envCfg.EnableSharedConfig {
// The shared config file (~/.aws/config) is only loaded if instructed
// to load via the envConfig.EnableSharedConfig (AWS_SDK_LOAD_CONFIG).
cfgFiles = cfgFiles[1:]
}
}
// Load additional config from file(s)
sharedCfg, err := loadSharedConfig(envCfg.Profile, cfgFiles, envCfg.EnableSharedConfig)
if err != nil {
if len(envCfg.Profile) == 0 && !envCfg.EnableSharedConfig && (envCfg.Creds.HasKeys() || userCfg.Credentials != nil) {
// Special case where the user has not explicitly specified an AWS_PROFILE,
// or session.Options.profile, shared config is not enabled, and the
// environment has credentials, allow the shared config file to fail to
// load since the user has already provided credentials, and nothing else
// is required to be read file. Github(aws/aws-sdk-go#2455)
} else if _, ok := err.(SharedConfigProfileNotExistsError); !ok {
return nil, err
}
}
if err := mergeConfigSrcs(cfg, userCfg, envCfg, sharedCfg, handlers, opts); err != nil {
return nil, err
}
s := &Session{
Config: cfg,
Handlers: handlers,
}
initHandlers(s)
if csmCfg, err := loadCSMConfig(envCfg, cfgFiles); err != nil {
if l := s.Config.Logger; l != nil {
l.Log(fmt.Sprintf("ERROR: failed to load CSM configuration, %v", err))
}
} else if csmCfg.Enabled {
err = enableCSM(&s.Handlers, csmCfg, s.Config.Logger)
if err != nil {
return nil, err
}
}
// Setup HTTP client with custom cert bundle if enabled
if opts.CustomCABundle != nil {
if err := loadCustomCABundle(s, opts.CustomCABundle); err != nil {
return nil, err
}
}
return s, nil
}
type csmConfig struct {
Enabled bool
Host string
Port string
ClientID string
}
var csmProfileName = "aws_csm"
func loadCSMConfig(envCfg envConfig, cfgFiles []string) (csmConfig, error) {
if envCfg.CSMEnabled != nil {
if *envCfg.CSMEnabled {
return csmConfig{
Enabled: true,
ClientID: envCfg.CSMClientID,
Host: envCfg.CSMHost,
Port: envCfg.CSMPort,
}, nil
}
return csmConfig{}, nil
}
sharedCfg, err := loadSharedConfig(csmProfileName, cfgFiles, false)
if err != nil {
if _, ok := err.(SharedConfigProfileNotExistsError); !ok {
return csmConfig{}, err
}
}
if sharedCfg.CSMEnabled != nil && *sharedCfg.CSMEnabled == true {
return csmConfig{
Enabled: true,
ClientID: sharedCfg.CSMClientID,
Host: sharedCfg.CSMHost,
Port: sharedCfg.CSMPort,
}, nil
}
return csmConfig{}, nil
}
func loadCustomCABundle(s *Session, bundle io.Reader) error {
var t *http.Transport
switch v := s.Config.HTTPClient.Transport.(type) {
case *http.Transport:
t = v
default:
if s.Config.HTTPClient.Transport != nil {
return awserr.New("LoadCustomCABundleError",
"unable to load custom CA bundle, HTTPClient's transport unsupported type", nil)
}
}
if t == nil {
// Nil transport implies `http.DefaultTransport` should be used. Since
// the SDK cannot modify, nor copy the `DefaultTransport` specifying
// the values the next closest behavior.
t = getCABundleTransport()
}
p, err := loadCertPool(bundle)
if err != nil {
return err
}
if t.TLSClientConfig == nil {
t.TLSClientConfig = &tls.Config{}
}
t.TLSClientConfig.RootCAs = p
s.Config.HTTPClient.Transport = t
return nil
}
func loadCertPool(r io.Reader) (*x509.CertPool, error) {
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, awserr.New("LoadCustomCABundleError",
"failed to read custom CA bundle PEM file", err)
}
p := x509.NewCertPool()
if !p.AppendCertsFromPEM(b) {
return nil, awserr.New("LoadCustomCABundleError",
"failed to load custom CA bundle PEM file", err)
}
return p, nil
}
func mergeConfigSrcs(cfg, userCfg *aws.Config,
envCfg envConfig, sharedCfg sharedConfig,
handlers request.Handlers,
sessOpts Options,
) error {
// Region if not already set by user
if len(aws.StringValue(cfg.Region)) == 0 {
if len(envCfg.Region) > 0 {
cfg.WithRegion(envCfg.Region)
} else if envCfg.EnableSharedConfig && len(sharedCfg.Region) > 0 {
cfg.WithRegion(sharedCfg.Region)
}
}
if cfg.EnableEndpointDiscovery == nil {
if envCfg.EnableEndpointDiscovery != nil {
cfg.WithEndpointDiscovery(*envCfg.EnableEndpointDiscovery)
} else if envCfg.EnableSharedConfig && sharedCfg.EnableEndpointDiscovery != nil {
cfg.WithEndpointDiscovery(*sharedCfg.EnableEndpointDiscovery)
}
}
// Regional Endpoint flag for STS endpoint resolving
mergeSTSRegionalEndpointConfig(cfg, []endpoints.STSRegionalEndpoint{
userCfg.STSRegionalEndpoint,
envCfg.STSRegionalEndpoint,
sharedCfg.STSRegionalEndpoint,
endpoints.LegacySTSEndpoint,
})
// Regional Endpoint flag for S3 endpoint resolving
mergeS3UsEast1RegionalEndpointConfig(cfg, []endpoints.S3UsEast1RegionalEndpoint{
userCfg.S3UsEast1RegionalEndpoint,
envCfg.S3UsEast1RegionalEndpoint,
sharedCfg.S3UsEast1RegionalEndpoint,
endpoints.LegacyS3UsEast1Endpoint,
})
// Configure credentials if not already set by the user when creating the
// Session.
if cfg.Credentials == credentials.AnonymousCredentials && userCfg.Credentials == nil {
creds, err := resolveCredentials(cfg, envCfg, sharedCfg, handlers, sessOpts)
if err != nil {
return err
}
cfg.Credentials = creds
}
cfg.S3UseARNRegion = userCfg.S3UseARNRegion
if cfg.S3UseARNRegion == nil {
cfg.S3UseARNRegion = &envCfg.S3UseARNRegion
}
if cfg.S3UseARNRegion == nil {
cfg.S3UseARNRegion = &sharedCfg.S3UseARNRegion
}
return nil
}
func mergeSTSRegionalEndpointConfig(cfg *aws.Config, values []endpoints.STSRegionalEndpoint) {
for _, v := range values {
if v != endpoints.UnsetSTSEndpoint {
cfg.STSRegionalEndpoint = v
break
}
}
}
func mergeS3UsEast1RegionalEndpointConfig(cfg *aws.Config, values []endpoints.S3UsEast1RegionalEndpoint) {
for _, v := range values {
if v != endpoints.UnsetS3UsEast1Endpoint {
cfg.S3UsEast1RegionalEndpoint = v
break
}
}
}
func initHandlers(s *Session) {
// Add the Validate parameter handler if it is not disabled.
s.Handlers.Validate.Remove(corehandlers.ValidateParametersHandler)
if !aws.BoolValue(s.Config.DisableParamValidation) {
s.Handlers.Validate.PushBackNamed(corehandlers.ValidateParametersHandler)
}
}
// Copy creates and returns a copy of the current Session, copying the config
// and handlers. If any additional configs are provided they will be merged
// on top of the Session's copied config.
//
// // Create a copy of the current Session, configured for the us-west-2 region.
// sess.Copy(&aws.Config{Region: aws.String("us-west-2")})
func (s *Session) Copy(cfgs ...*aws.Config) *Session {
newSession := &Session{
Config: s.Config.Copy(cfgs...),
Handlers: s.Handlers.Copy(),
}
initHandlers(newSession)
return newSession
}
// ClientConfig satisfies the client.ConfigProvider interface and is used to
// configure the service client instances. Passing the Session to the service
// client's constructor (New) will use this method to configure the client.
func (s *Session) ClientConfig(service string, cfgs ...*aws.Config) client.Config {
s = s.Copy(cfgs...)
region := aws.StringValue(s.Config.Region)
resolved, err := s.resolveEndpoint(service, region, s.Config)
if err != nil {
s.Handlers.Validate.PushBack(func(r *request.Request) {
if len(r.ClientInfo.Endpoint) != 0 {
// Error occurred while resolving endpoint, but the request
// being invoked has had an endpoint specified after the client
// was created.
return
}
r.Error = err
})
}
return client.Config{
Config: s.Config,
Handlers: s.Handlers,
PartitionID: resolved.PartitionID,
Endpoint: resolved.URL,
SigningRegion: resolved.SigningRegion,
SigningNameDerived: resolved.SigningNameDerived,
SigningName: resolved.SigningName,
}
}
func (s *Session) resolveEndpoint(service, region string, cfg *aws.Config) (endpoints.ResolvedEndpoint, error) {
if ep := aws.StringValue(cfg.Endpoint); len(ep) != 0 {
return endpoints.ResolvedEndpoint{
URL: endpoints.AddScheme(ep, aws.BoolValue(cfg.DisableSSL)),
SigningRegion: region,
}, nil
}
resolved, err := cfg.EndpointResolver.EndpointFor(service, region,
func(opt *endpoints.Options) {
opt.DisableSSL = aws.BoolValue(cfg.DisableSSL)
opt.UseDualStack = aws.BoolValue(cfg.UseDualStack)
// Support for STSRegionalEndpoint where the STSRegionalEndpoint is
// provided in envConfig or sharedConfig with envConfig getting
// precedence.
opt.STSRegionalEndpoint = cfg.STSRegionalEndpoint
// Support for S3UsEast1RegionalEndpoint where the S3UsEast1RegionalEndpoint is
// provided in envConfig or sharedConfig with envConfig getting
// precedence.
opt.S3UsEast1RegionalEndpoint = cfg.S3UsEast1RegionalEndpoint
// Support the condition where the service is modeled but its
// endpoint metadata is not available.
opt.ResolveUnknownService = true
},
)
if err != nil {
return endpoints.ResolvedEndpoint{}, err
}
return resolved, nil
}
// ClientConfigNoResolveEndpoint is the same as ClientConfig with the exception
// that the EndpointResolver will not be used to resolve the endpoint. The only
// endpoint set must come from the aws.Config.Endpoint field.
func (s *Session) ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) client.Config {
s = s.Copy(cfgs...)
var resolved endpoints.ResolvedEndpoint
if ep := aws.StringValue(s.Config.Endpoint); len(ep) > 0 {
resolved.URL = endpoints.AddScheme(ep, aws.BoolValue(s.Config.DisableSSL))
resolved.SigningRegion = aws.StringValue(s.Config.Region)
}
return client.Config{
Config: s.Config,
Handlers: s.Handlers,
Endpoint: resolved.URL,
SigningRegion: resolved.SigningRegion,
SigningNameDerived: resolved.SigningNameDerived,
SigningName: resolved.SigningName,
}
}
// logDeprecatedNewSessionError function enables error handling for session
func (s *Session) logDeprecatedNewSessionError(msg string, err error, cfgs []*aws.Config) {
// Session creation failed, need to report the error and prevent
// any requests from succeeding.
s.Config.MergeIn(cfgs...)
s.Config.Logger.Log("ERROR:", msg, "Error:", err)
s.Handlers.Validate.PushBack(func(r *request.Request) {
r.Error = err
})
}
| {
"pile_set_name": "Github"
} |
import React from 'react'
import './assets/scss-styles.scss'
export default () => <p id="feature-scss-inclusion">We love useless text.</p>
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head><link rel="apple-touch-icon" sizes="180x180" href="/glide/apple-touch-icon.png"><link rel="icon" type="image/png" sizes="32x32" href="/glide/favicon-32x32.png"><link rel="icon" type="image/png" sizes="16x16" href="/glide/favicon-16x16.png"><link rel="manifest" href="/glide/manifest.json">
<!-- Generated by javadoc (1.8.0_221) on Thu Jan 09 10:43:59 PST 2020 -->
<title>DrawableCrossFadeTransition (glide API)</title>
<meta name="date" content="2020-01-09">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="DrawableCrossFadeTransition (glide API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/bumptech/glide/request/transition/DrawableCrossFadeFactory.Builder.html" title="class in com.bumptech.glide.request.transition"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../com/bumptech/glide/request/transition/NoTransition.html" title="class in com.bumptech.glide.request.transition"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/bumptech/glide/request/transition/DrawableCrossFadeTransition.html" target="_top">Frames</a></li>
<li><a href="DrawableCrossFadeTransition.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.bumptech.glide.request.transition</div>
<h2 title="Class DrawableCrossFadeTransition" class="title">Class DrawableCrossFadeTransition</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>com.bumptech.glide.request.transition.DrawableCrossFadeTransition</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../../com/bumptech/glide/request/transition/Transition.html" title="interface in com.bumptech.glide.request.transition">Transition</a><android.graphics.drawable.Drawable></dd>
</dl>
<hr>
<br>
<pre>public class <span class="typeNameLabel">DrawableCrossFadeTransition</span>
extends java.lang.Object
implements <a href="../../../../../com/bumptech/glide/request/transition/Transition.html" title="interface in com.bumptech.glide.request.transition">Transition</a><android.graphics.drawable.Drawable></pre>
<div class="block">A cross fade <a href="../../../../../com/bumptech/glide/request/transition/Transition.html" title="interface in com.bumptech.glide.request.transition"><code>Transition</code></a> for <code>Drawable</code>s that uses an
<code>TransitionDrawable</code> to transition from an existing drawable
already visible on the target to a new drawable. If no existing drawable exists, this class can
instead fall back to a default animation that doesn't rely on <code>TransitionDrawable</code>.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested.class.summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="nested.classes.inherited.from.class.com.bumptech.glide.request.transition.Transition">
<!-- -->
</a>
<h3>Nested classes/interfaces inherited from interface com.bumptech.glide.request.transition.<a href="../../../../../com/bumptech/glide/request/transition/Transition.html" title="interface in com.bumptech.glide.request.transition">Transition</a></h3>
<code><a href="../../../../../com/bumptech/glide/request/transition/Transition.ViewAdapter.html" title="interface in com.bumptech.glide.request.transition">Transition.ViewAdapter</a></code></li>
</ul>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../com/bumptech/glide/request/transition/DrawableCrossFadeTransition.html#DrawableCrossFadeTransition-int-boolean-">DrawableCrossFadeTransition</a></span>(int duration,
boolean isCrossFadeEnabled)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/bumptech/glide/request/transition/DrawableCrossFadeTransition.html#transition-android.graphics.drawable.Drawable-com.bumptech.glide.request.transition.Transition.ViewAdapter-">transition</a></span>(android.graphics.drawable.Drawable current,
<a href="../../../../../com/bumptech/glide/request/transition/Transition.ViewAdapter.html" title="interface in com.bumptech.glide.request.transition">Transition.ViewAdapter</a> adapter)</code>
<div class="block">Animates from the previous drawable to the current drawable in one of two ways.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="DrawableCrossFadeTransition-int-boolean-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>DrawableCrossFadeTransition</h4>
<pre>public DrawableCrossFadeTransition(int duration,
boolean isCrossFadeEnabled)</pre>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>duration</code> - The duration that the cross fade animation should run if there is something to
cross fade from when a new <code>Drawable</code> is put.</dd>
<dd><code>isCrossFadeEnabled</code> - If <code>true</code>, animates the previous resource's alpha to 0 while
animating the new resource's alpha to 100. Otherwise, only animates the new resource's
alpha to 100 while leaving the previous resource's alpha at 100. See <code>TransitionDrawable.setCrossFadeEnabled(boolean)</code>.</dd>
</dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="transition-android.graphics.drawable.Drawable-com.bumptech.glide.request.transition.Transition.ViewAdapter-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>transition</h4>
<pre>public boolean transition(android.graphics.drawable.Drawable current,
<a href="../../../../../com/bumptech/glide/request/transition/Transition.ViewAdapter.html" title="interface in com.bumptech.glide.request.transition">Transition.ViewAdapter</a> adapter)</pre>
<div class="block">Animates from the previous drawable to the current drawable in one of two ways.
<ol>
<li>Using the default animation provided in the constructor if the previous drawable is null
<li>Using the cross fade animation with the duration provided in the constructor if the
previous drawable is non null
</ol></div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../../com/bumptech/glide/request/transition/Transition.html#transition-R-com.bumptech.glide.request.transition.Transition.ViewAdapter-">transition</a></code> in interface <code><a href="../../../../../com/bumptech/glide/request/transition/Transition.html" title="interface in com.bumptech.glide.request.transition">Transition</a><android.graphics.drawable.Drawable></code></dd>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>current</code> - The new resource that will be displayed in the view.</dd>
<dd><code>adapter</code> - The <a href="../../../../../com/bumptech/glide/request/transition/Transition.ViewAdapter.html" title="interface in com.bumptech.glide.request.transition"><code>Transition.ViewAdapter</code></a> wrapping a view that can at least return an
<code>View</code> from <a href="../../../../../com/bumptech/glide/request/transition/Transition.ViewAdapter.html#getView--"><code>Transition.ViewAdapter.getView()</code></a>.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>True if in the process of running the transition, the new resource was put on the view,
false if the caller needs to manually put the current resource on the view.</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/bumptech/glide/request/transition/DrawableCrossFadeFactory.Builder.html" title="class in com.bumptech.glide.request.transition"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../com/bumptech/glide/request/transition/NoTransition.html" title="class in com.bumptech.glide.request.transition"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/bumptech/glide/request/transition/DrawableCrossFadeTransition.html" target="_top">Frames</a></li>
<li><a href="DrawableCrossFadeTransition.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2000 Greg Haerr <[email protected]>
* Copyright (c) 1991 David I. Bell
*/
#include <stdlib.h>
#include "serv.h"
/*
* Macro to distinguish cases of clipping.
*/
#define GAPVAL(leftgap, rightgap, topgap, bottomgap) \
(((leftgap) << 3) + ((rightgap) << 2) + ((topgap) << 1) + (bottomgap))
static GR_COUNT GsSplitClipRect(MWCLIPRECT *srcrect, MWCLIPRECT *destrect,
GR_COORD minx, GR_COORD miny, GR_COORD maxx,
GR_COORD maxy);
/*
* Set the clip rectangles for a window taking into account other
* windows that may be obscuring it. The windows that may be obscuring
* this one are the siblings of each direct ancestor which are higher
* in priority than those ancestors. Also, each parent limits the visible
* area of the window. The clipping is not done if it is already up to
* date of if the window is not outputtable.
*/
void
GsSetClipWindow(GR_WINDOW *wp, MWCLIPREGION *userregion, int flags)
{
GR_WINDOW *pwp; /* parent window */
GR_WINDOW *sibwp; /* sibling windows */
MWCLIPRECT *clip; /* first clip rectangle */
GR_COUNT count; /* number of clip rectangles */
GR_COUNT newcount; /* number of new rectangles */
GR_COUNT i; /* current index */
GR_COORD minx; /* minimum clip x coordinate */
GR_COORD miny; /* minimum clip y coordinate */
GR_COORD maxx; /* maximum clip x coordinate */
GR_COORD maxy; /* maximum clip y coordinate */
GR_COORD diff; /* difference in coordinates */
GR_SIZE bs; /* border size */
GR_BOOL toomany; /* TRUE if too many clip rects */
MWCLIPRECT cliprects[MAX_CLIPRECTS]; /* clip rectangles */
if (!wp->realized || !wp->output || (wp == clipwp))
return;
clipwp = wp;
/*
* Start with the rectangle for the complete window.
* We will then cut pieces out of it as needed.
*/
count = 1;
clip = cliprects;
clip->x = wp->x;
clip->y = wp->y;
clip->width = wp->width;
clip->height = wp->height;
/*
* First walk upwards through all parent windows,
* and restrict the visible part of this window to the part
* that shows through all of those parent windows.
*/
pwp = wp;
while (pwp != rootwp) {
pwp = pwp->parent;
diff = pwp->x - clip->x;
if (diff > 0) {
clip->width -= diff;
clip->x = pwp->x;
}
diff = (pwp->x + pwp->width) - (clip->x + clip->width);
if (diff < 0)
clip->width += diff;
diff = pwp->y - clip->y;
if (diff > 0) {
clip->height -= diff;
clip->y = pwp->y;
}
diff = (pwp->y + pwp->height) - (clip->y + clip->height);
if (diff < 0)
clip->height += diff;
}
/*
* If the window is completely clipped out of view, then
* set the clipping region to indicate that.
*/
if ((clip->width <= 0) || (clip->height <= 0)) {
GdSetClipRects(clipwp->psd, 1, cliprects);
return;
}
/*
* Now examine all windows that obscure this window, and
* for each obscuration, break up the clip rectangles into
* the smaller pieces that are still visible. The windows
* that can obscure us are the earlier siblings of all of
* our parents.
*/
toomany = GR_FALSE;
pwp = wp;
/*while (pwp != rootwp) {*/
while (pwp != NULL) {
wp = pwp;
pwp = wp->parent;
if(!pwp) {
/* We're clipping the root window*/
sibwp = rootwp->children;
wp = NULL;
} else
sibwp = pwp->children;
for (; sibwp != wp; sibwp = sibwp->siblings) {
if (!sibwp->realized || !sibwp->output)
continue;
bs = sibwp->bordersize;
minx = sibwp->x - bs;
miny = sibwp->y - bs;
maxx = sibwp->x + sibwp->width + bs - 1;
maxy = sibwp->y + sibwp->height + bs - 1;
newcount = count;
for (i = 0; i < count; i++) {
if (newcount > MAX_CLIPRECTS - 3) {
toomany = GR_TRUE;
break;
}
newcount += GsSplitClipRect(&cliprects[i],
&cliprects[newcount],
minx, miny, maxx, maxy);
}
count = newcount;
}
if(pwp == rootwp)
break;
}
if (toomany) {
GsError(GR_ERROR_TOO_MUCH_CLIPPING, wp->id);
clip->x = 0;
clip->y = 0;
clip->width = -1;
clip->height = -1;
count = 1;
}
/*
* Set the clip rectangles.
*/
GdSetClipRects(clipwp->psd, count, cliprects);
}
/*
* Check the specified clip rectangle against the specified rectangular
* region, and reduce it or split it up into multiple clip rectangles
* such that the specified region is not contained in any of the clip
* rectangles. The source clip rectangle can be modified in place, and
* in addition more clip rectangles can be generated, which are placed in
* the indicated destination location. The maximum number of new clip
* rectangles needed is 3. Returns the number of clip rectangles added.
* If the source clip rectangle is totally obliterated, it is set to an
* impossible region and 0 is returned. When splits are done, we prefer
* to create wide regions instead of high regions.
*/
static GR_COUNT
GsSplitClipRect(MWCLIPRECT *srcrect, MWCLIPRECT *destrect, GR_COORD minx,
GR_COORD miny, GR_COORD maxx, GR_COORD maxy)
{
GR_COORD x;
GR_COORD y;
GR_SIZE width;
GR_SIZE height;
GR_COORD dx;
GR_COORD dy;
int gaps;
/*
* First see if there is any overlap at all.
* If not, then nothing to do.
*/
x = srcrect->x;
y = srcrect->y;
width = srcrect->width;
height = srcrect->height;
if ((minx > maxx) || (miny > maxy) || (maxx < x) || (maxy < y) ||
(x + width <= minx) || (y + height <= miny))
return 0;
/*
* There is an overlap. Calculate a value to differentiate
* various cases, and then handle each case separately. The
* cases are classified on whether there are gaps on the left,
* right, top, and bottom sides of the clip rectangle.
*/
gaps = 0;
if (x < minx)
gaps |= GAPVAL(1, 0, 0, 0);
if (x + width - 1 > maxx)
gaps |= GAPVAL(0, 1, 0, 0);
if (y < miny)
gaps |= GAPVAL(0, 0, 1, 0);
if (y + height - 1 > maxy)
gaps |= GAPVAL(0, 0, 0, 1);
switch (gaps) {
case GAPVAL(0, 0, 0, 0): /* no gaps at all */
srcrect->x = 0;
srcrect->y = 0;
srcrect->width = 0;
srcrect->height = 0;
return 0;
case GAPVAL(0, 0, 0, 1): /* gap on bottom */
dy = maxy - y + 1;
srcrect->y += dy;
srcrect->height -= dy;
return 0;
case GAPVAL(0, 0, 1, 0): /* gap on top */
srcrect->height = miny - y;
return 0;
case GAPVAL(0, 0, 1, 1): /* gap on top, bottom */
srcrect->height = miny - y;
destrect->x = x;
destrect->width = width;
destrect->y = maxy + 1;
destrect->height = y + height - maxy - 1;
return 1;
case GAPVAL(0, 1, 0, 0): /* gap on right */
dx = maxx - x + 1;
srcrect->x += dx;
srcrect->width -= dx;
return 0;
case GAPVAL(0, 1, 0, 1): /* gap on right, bottom */
dx = maxx - x + 1;
srcrect->x += dx;
srcrect->width -= dx;
srcrect->height = maxy - y + 1;
destrect->x = x;
destrect->width = width;
destrect->y = maxy + 1;
destrect->height = y + height - maxy - 1;
return 1;
case GAPVAL(0, 1, 1, 0): /* gap on right, top */
dx = maxx - x + 1;
srcrect->height = miny - y;
destrect->x = x + dx;
destrect->width = width - dx;
destrect->y = miny;
destrect->height = y + height - miny;
return 1;
case GAPVAL(0, 1, 1, 1): /* gap on right, top, bottom */
dx = maxx - x + 1;
srcrect->height = miny - y;
destrect->x = x;
destrect->width = width;
destrect->y = maxy + 1;
destrect->height = y + height - maxy - 1;
destrect++;
destrect->x = x + dx;
destrect->width = width - dx;
destrect->y = miny;
destrect->height = maxy - miny + 1;
return 2;
case GAPVAL(1, 0, 0, 0): /* gap on left */
srcrect->width = minx - x;
return 0;
case GAPVAL(1, 0, 0, 1): /* gap on left, bottom */
srcrect->width = minx - x;
srcrect->height = maxy - y + 1;
destrect->x = x;
destrect->width = width;
destrect->y = maxy + 1;
destrect->height = y + height - maxy - 1;
return 1;
case GAPVAL(1, 0, 1, 0): /* gap on left, top */
srcrect->height = miny - y;
destrect->x = x;
destrect->width = minx - x;
destrect->y = miny;
destrect->height = y + height - miny;
return 1;
case GAPVAL(1, 0, 1, 1): /* gap on left, top, bottom */
srcrect->height = miny - y;
destrect->x = x;
destrect->width = minx - x;
destrect->y = miny;
destrect->height = maxy - miny + 1;
destrect++;
destrect->x = x;
destrect->width = width;
destrect->y = maxy + 1;
destrect->height = y + height - maxy - 1;
return 2;
case GAPVAL(1, 1, 0, 0): /* gap on left, right */
destrect->x = maxx + 1;
destrect->width = x + width - maxx - 1;
destrect->y = y;
destrect->height = height;
srcrect->width = minx - x;
return 1;
case GAPVAL(1, 1, 0, 1): /* gap on left, right, bottom */
dy = maxy - y + 1;
srcrect->y += dy;
srcrect->height -= dy;
destrect->x = x;
destrect->width = minx - x;
destrect->y = y;
destrect->height = dy;
destrect++;
destrect->x = maxx + 1;
destrect->width = x + width - maxx - 1;
destrect->y = y;
destrect->height = dy;
return 2;
case GAPVAL(1, 1, 1, 0): /* gap on left, right, top */
srcrect->height = miny - y;
destrect->x = x;
destrect->width = minx - x;
destrect->y = miny;
destrect->height = y + height - miny;
destrect++;
destrect->x = maxx + 1;
destrect->width = x + width - maxx - 1;
destrect->y = miny;
destrect->height = y + height - miny;
return 2;
case GAPVAL(1, 1, 1, 1): /* gap on all sides */
srcrect->height = miny - y;
destrect->x = x;
destrect->width = minx - x;
destrect->y = miny;
destrect->height = maxy - miny + 1;
destrect++;
destrect->x = maxx + 1;
destrect->width = x + width - maxx - 1;
destrect->y = miny;
destrect->height = maxy - miny + 1;
destrect++;
destrect->x = x;
destrect->width = width;
destrect->y = maxy + 1;
destrect->height = y + height - maxy - 1;
return 3;
}
return 0; /* NOTREACHED */
}
| {
"pile_set_name": "Github"
} |
<div>
<div class="form-group">
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">Menu</div>
<!-- List group -->
<ul class="list-group">
<li class="list-group-item">
<span class="glyphicon glyphicon-user"></span>
<a ui-sref="userInformation({locale: locale})">Dashboard</a>
</li>
<li class="list-group-item">
<span class="glyphicon glyphicon-list-alt"></span>
<a ui-sref="orders({locale: locale})">Orders</a>
</li>
</ul>
</div>
</div>
</div> | {
"pile_set_name": "Github"
} |
/*
* Copyright 2014 the original author or 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.dsl.ftp;
import java.io.File;
import java.util.Comparator;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.integration.dsl.file.RemoteFileInboundChannelAdapterSpec;
import org.springframework.integration.file.remote.session.SessionFactory;
import org.springframework.integration.ftp.filters.FtpRegexPatternFileListFilter;
import org.springframework.integration.ftp.filters.FtpSimplePatternFileListFilter;
import org.springframework.integration.ftp.inbound.FtpInboundFileSynchronizer;
import org.springframework.integration.ftp.inbound.FtpInboundFileSynchronizingMessageSource;
/**
* A {@link RemoteFileInboundChannelAdapterSpec} for a {@link FtpInboundFileSynchronizingMessageSource}.
*
* @author Artem Bilan
*/
public class FtpInboundChannelAdapterSpec
extends RemoteFileInboundChannelAdapterSpec<FTPFile, FtpInboundChannelAdapterSpec,
FtpInboundFileSynchronizingMessageSource> {
FtpInboundChannelAdapterSpec(SessionFactory<FTPFile> sessionFactory, Comparator<File> comparator) {
super(new FtpInboundFileSynchronizer(sessionFactory));
this.target = new FtpInboundFileSynchronizingMessageSource(this.synchronizer, comparator);
}
/**
* @see FtpSimplePatternFileListFilter
* @see #filter(org.springframework.integration.file.filters.FileListFilter)
*/
@Override
public FtpInboundChannelAdapterSpec patternFilter(String pattern) {
return filter(new FtpSimplePatternFileListFilter(pattern));
}
/**
* @see FtpRegexPatternFileListFilter
* @see #filter(org.springframework.integration.file.filters.FileListFilter)
*/
@Override
public FtpInboundChannelAdapterSpec regexFilter(String regex) {
return filter(new FtpRegexPatternFileListFilter(regex));
}
}
| {
"pile_set_name": "Github"
} |
/// Source : https://leetcode.com/problems/n-queens-ii/
/// Author : liuyubobobo
/// Time : 2018-01-07
#include <iostream>
#include <vector>
using namespace std;
/// Basic Recursive
/// Time Complexity: O(n^n)
/// Space Complexity: O(n)
class Solution {
public:
int totalNQueens(int n) {
vector<int> row;
vector<bool> col(n, false), dia1(2 * n - 1, false), dia2(2 * n - 1, false);
return dfs(n, 0, row, col, dia1, dia2);
}
private:
int dfs(int n, int index, vector<int>& row,
vector<bool>& col, vector<bool>& dia1, vector<bool>& dia2){
if(index == n)
return 1;
int res = 0;
for(int i = 0; i < n; i ++)
if(!col[i] && !dia1[index + i] && !dia2[index - i + n - 1]){
row.push_back(i);
col[i] = true;
dia1[index + i] = true;
dia2[index - i + n - 1] = true;
res += dfs(n, index + 1, row, col, dia1, dia2);
col[i] = false;
dia1[index + i] = false;
dia2[index - i + n - 1] = false;
row.pop_back();
}
return res;
}
};
int main() {
return 0;
} | {
"pile_set_name": "Github"
} |
package main
import "testing"
import "time"
func TestPrint1(t *testing.T) {
print1()
}
func TestGoPrint1(t *testing.T) {
goPrint1()
time.Sleep(1 * time.Millisecond)
}
| {
"pile_set_name": "Github"
} |
.jqx-widget-classic{}
.jqx-fill-state-normal-classic, .jqx-widget-header-classic{ border-color: #aaa; background-color:#E8E8E8; background-image:-webkit-gradient(linear,0 0,0 100%,from(#fafafa),to(#dadada)); background-image:-moz-linear-gradient(top,#fafafa,#dadada); background-image:-o-linear-gradient(top,#fafafa,#dadada)}
.jqx-fill-state-hover-classic{ border-color:#999; background-color:#E8E8E8; background-image:-webkit-gradient(linear,0 0,0 100%,from(#fafafa),to(#dadada)); background-image:-moz-linear-gradient(top,#fafafa,#dadada); background-image:-o-linear-gradient(top,#fafafa,#dadada)}
.jqx-fill-state-pressed-classic{ background-color:#7A7A7A; background-image:-webkit-gradient(linear,0 0,0 100%,from(#989898),to(#696969)); background-image:-moz-linear-gradient(top,#989898,#696969); background-image:-o-linear-gradient(top,#989898,#696969); border-color:#666; color:white; text-shadow:0 1px 0 #333; border-image:initial}
.jqx-grid-column-menubutton-classic{ background-color:transparent}
.jqx-calendar-row-header-classic, .jqx-calendar-top-left-header-classic{ background-color:#f2f2f2; border:0px solid #f2f2f2}
.jqx-calendar-column-header-classic{ background-color:#FFF; border-top:1px solid #FFF; border-bottom:1px solid #e9e9e9}
.jqx-scrollbar-state-normal-classic{ background-color:#efefef; border:1px solid #efefef}
.jqx-scrollbar-button-state-normal-classic{ border:1px solid #ececed; background-color:#ececed}
.jqx-scrollbar-thumb-state-normal-classic{ background-color:#E8E8E8; background-image:-webkit-gradient(linear,left top,right top,from(#fafafa),to(#dadada)); background-image:-moz-linear-gradient(left,#fafafa,#dadada); background-image:-o-linear-gradient(left,#fafafa,#dadada); border:1px solid #bbb}
.jqx-scrollbar-thumb-state-hover-classic{ background-color:#e8e8e8; border:1px solid #aaa}
.jqx-scrollbar-thumb-state-pressed-classic, .jqx-progressbar-value-vertical-classic{ background-color:#7A7A7A; background-image:-webkit-gradient(linear,left top,right top,from(#989898),to(#696969)); background-image:-moz-linear-gradient(left,#989898,#696969); background-image:-o-linear-gradient(left,#989898,#696969); border:1px solid #666}
.jqx-icon-arrow-up-selected-classic{background-image:url('images/icon-up-white.png'); background-repeat:no-repeat; background-position:center}
.jqx-icon-arrow-down-selected-classic{background-image:url('images/icon-down-white.png'); background-repeat:no-repeat; background-position:center}
.jqx-icon-arrow-left-selected-classic{background-image:url('images/icon-left-white.png'); background-repeat:no-repeat; background-position:center}
.jqx-icon-arrow-right-selected-classic{background-image:url('images/icon-right-white.png');background-repeat:no-repeat; background-position:center}
.jqx-scrollbar-classic .jqx-icon-arrow-up-selected-classic{background-image:url('images/icon-up.png'); background-repeat:no-repeat; background-position:center}
.jqx-scrollbar-classic .jqx-icon-arrow-down-selected-classic{background-image:url('images/icon-down.png'); background-repeat:no-repeat; background-position:center}
.jqx-scrollbar-classic .jqx-icon-arrow-left-selected-classic{background-image:url('images/icon-left.png'); background-repeat:no-repeat; background-position:center}
.jqx-scrollbar-classic .jqx-icon-arrow-right-selected-classic{background-image:url('images/icon-right.png');background-repeat:no-repeat; background-position:center}
.jqx-slider-track-horizontal-classic, .jqx-slider-track-vertical-classic{border-color: #e8e8e8; background: #e8e8e8;}
.jqx-slider-rangebar-classic{background:#7A7A7A;}
.jqx-grid-column-sortdescbutton-classic, jqx-grid-column-filterbutton-classic, .jqx-grid-column-sortascbutton-classic{ background-color:transparent; border-style:solid; border-width:0px 0px 0px 0px; border-color:#aaa}
.jqx-scrollbar-button-state-hover-classic, .jqx-grid-cell-hover-classic, .jqx-menu-item-hover-classic, .jqx-menu-item-top-hover-classic, .jqx-tree-item-hover-classic{filter: none; background-color:#eee !important; background-image:-webkit-gradient(linear,0 0,0 100%,from(#fafafa),to(#eee)); background-image:-moz-linear-gradient(top,#fafafa,#eee); background-image:-o-linear-gradient(top,#fafafa,#eee); border-color:#999; color:#222 !important; text-shadow:0 1px 0 #f2f2f2;}
.jqx-tree-item-selected-classic, .jqx-menu-item-selected-classic, .jqx-menu-item-top-selected-classic{ background-color:#7A7A7A; filter:progid:DXImageTransform.Microsoft.gradient( startColorstr='#989898',endColorstr='#696969',GradientType=0 ); background-image:-webkit-gradient(linear,0 0,0 100%,from(#989898),to(#696969)); background-image:-moz-linear-gradient(top,#989898,#696969); background-image:-o-linear-gradient(top,#989898,#696969); border-color:#666; color:white; text-shadow:0 1px 0 #333;border-image:initial}
.jqx-expander-header-expanded-classic, .jqx-scrollbar-button-state-pressed-classic, .jqx-grid-cell-selected-classic{color: #222 !important; text-shadow:0 1px 0 #f2f2f2; background-color: #dadada !important; filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e8e8e8', endColorstr='#dadada',GradientType=0 ); /* IE6-9 */ background-image: -webkit-gradient(linear,0 0,0 100%,from(#E8E8E8),to(#dadada));background-image: -moz-linear-gradient(top,#E8E8E8,#dadada); background-image: -o-linear-gradient(top,#E8E8E8,#dadada);}
.jqx-expander-header-expanded-classic{ border-color: #aaa;}
.jqx-menu-vertical-classic{ background:#E8E8E8; filter: none;}
.jqx-menu-item-arrow-right-selected-classic{background-image:url(images/icon-right-white.png); background-position:100% 50%; background-repeat:no-repeat}
.jqx-menu-item-arrow-down-selected-classic{background-image:url(images/icon-down-white.png); background-position:100% 50%; background-repeat:no-repeat}
.jqx-menu-item-arrow-up-selected-classic{background-image:url(images/icon-up-white.png);background-position:100% 50%; background-repeat:no-repeat}
.jqx-menu-item-arrow-left-selected-classic{background-image:url(images/icon-left-white.png); background-position:0 50%; background-repeat:no-repeat}
.jqx-radiobutton-classic{border:none; background: none;}
.jqx-radiobutton-default-classic{filter: none; background:transparent url(images/roundbg_classic_normal.png) left center scroll repeat-x; border:0px solid #c9c9c9; -moz-border-radius:0px; -webkit-border-radius:0px; border-radius:0px}
.jqx-radiobutton-hover-classic{filter: none; -moz-border-radius:0px;-webkit-border-radius:0px;border-radius:0px;background:transparent url(images/roundbg_classic_hover.png) left center scroll repeat-x; border:0px solid #000}
.jqx-radiobutton-check-checked-classic{filter: none; margin:0px; width:12px;height:12px;background:transparent url(images/roundbg_check_black.png) left top no-repeat; border:none}
.jqx-radiobutton-check-indeterminate-classic{filter: none; background:transparent url(images/roundbg_check_indeterminate.png) left top no-repeat; border:none}
.jqx-radiobutton-check-indeterminate-disabled-classic{filter: none; background:transparent url(images/roundbg_check_disabled.png) left top no-repeat;border:none}
.jqx-fill-state-focus-classic { border-color: #747474;}
.jqx-grid-bottomright-classic, .jqx-panel-bottomright-classic, .jqx-listbox-bottomright-classic{background-color: #efefef;}
.jqx-tabs-title-selected-top-classic, .jqx-tabs-selection-tracker-top-classic {border-color: #aaa; border-bottom: 1px solid #fff; text-shadow:0 1px 0 #f2f2f2; filter: none; color: #222; background: #fff;}
.jqx-tabs-title-selected-bottom-classic, .jqx-tabs-selection-tracker-bottom-classic {border-color: #aaa; border-top: 1px solid #fff; text-shadow:0 1px 0 #f2f2f2; filter: none; color: #222; background: #fff;} | {
"pile_set_name": "Github"
} |
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const common = require('../common');
const assert = require('assert');
const net = require('net');
let exchanges = 0;
let starttime = null;
let timeouttime = null;
const timeout = 1000;
const echo_server = net.createServer(function(socket) {
socket.setTimeout(timeout);
socket.on('timeout', function() {
console.log('server timeout');
timeouttime = new Date();
console.dir(timeouttime);
socket.destroy();
});
socket.on('error', function(e) {
throw new Error(
'Server side socket should not get error. We disconnect willingly.');
});
socket.on('data', function(d) {
console.log(d);
socket.write(d);
});
socket.on('end', function() {
socket.end();
});
});
echo_server.listen(common.PORT, function() {
console.log(`server listening at ${common.PORT}`);
const client = net.createConnection(common.PORT);
client.setEncoding('UTF8');
client.setTimeout(0); // disable the timeout for client
client.on('connect', function() {
console.log('client connected.');
client.write('hello\r\n');
});
client.on('data', function(chunk) {
assert.strictEqual('hello\r\n', chunk);
if (exchanges++ < 5) {
setTimeout(function() {
console.log('client write "hello"');
client.write('hello\r\n');
}, 500);
if (exchanges === 5) {
console.log(`wait for timeout - should come in ${timeout} ms`);
starttime = new Date();
console.dir(starttime);
}
}
});
client.on('timeout', function() {
throw new Error("client timeout - this shouldn't happen");
});
client.on('end', function() {
console.log('client end');
client.end();
});
client.on('close', function() {
console.log('client disconnect');
echo_server.close();
});
});
process.on('exit', function() {
assert.ok(starttime != null);
assert.ok(timeouttime != null);
const diff = timeouttime - starttime;
console.log(`diff = ${diff}`);
assert.ok(timeout < diff);
// Allow for 800 milliseconds more
assert.ok(diff < timeout + 800);
});
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) OpenTX
*
* Based on code named
* th9x - http://code.google.com/p/th9x
* er9x - http://code.google.com/p/er9x
* gruvin9x - http://code.google.com/p/gruvin9x
*
* License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#ifndef _RTC_H_
#define _RTC_H_
#include <inttypes.h>
#define SECS_PER_HOUR 3600ul
#define SECS_PER_DAY 86400ul
#define TM_YEAR_BASE 1900
#define TIME_T_MIN (-LONG_MAX)
#define TIME_T_MAX (LONG_MAX)
typedef long int gtime_t;
struct gtm
{
int8_t tm_sec; /* Seconds. [0-60] (1 leap second) */
int8_t tm_min; /* Minutes. [0-59] */
int8_t tm_hour; /* Hours. [0-23] */
int8_t tm_mday; /* Day. [1-31] */
int8_t tm_mon; /* Month. [0-11] */
uint8_t tm_year; /* Year - 1900. Limited to the year 2155. */
int8_t tm_wday; /* Day of week. [0-6] */
int16_t tm_yday; /* Day of year. [0-365] Needed internally for calculations */
};
extern gtime_t g_rtcTime;
extern uint8_t g_ms100; // global to allow time set function to reset to zero
void rtcInit();
void rtcSetTime(const struct gtm * tm);
gtime_t gmktime (struct gtm *tm);
uint8_t rtcAdjust(uint16_t year, uint8_t mon, uint8_t day, uint8_t hour, uint8_t min, uint8_t sec);
#if defined(__cplusplus) && !defined(SIMU)
extern "C" {
#endif
void gettime(struct gtm * tm);
#if defined(__cplusplus) && !defined(SIMU)
}
#endif
#endif // _RTC_H_
| {
"pile_set_name": "Github"
} |
# Gradle 插件
Gradle 的核心为真实世界提供了很少的自动化.
所有的实用特性,类似编译java源码的能力, 是由*插件*提供的. 插件添加了新的任务(如:[JavaCompile](https://docs.gradle.org/current/dsl/org.gradle.api.tasks.compile.JavaCompile.html)),域对象(如:[SourceSet](https://docs.gradle.org/current/dsl/org.gradle.api.tasks.SourceSet.html)),公约(如:Java资源位置是`src/main/java`)以及来自其他插件延伸核心对象和对象。
在本章中,我们将讨论如何使用插件和关于插件的周边概念和术语。
| {
"pile_set_name": "Github"
} |
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is MPEG4IP.
*
* The Initial Developer of the Original Code is Cisco Systems Inc.
* Portions created by Cisco Systems Inc. are
* Copyright (C) Cisco Systems Inc. 2001. All Rights Reserved.
*
* Contributor(s):
* Dave Mackie [email protected]
*/
#include "mp4common.h"
MP4FtypAtom::MP4FtypAtom()
: MP4Atom("ftyp")
{
MP4StringProperty* pProp = new MP4StringProperty("majorBrand");
pProp->SetFixedLength(4);
AddProperty(pProp); /* 0 */
AddProperty( /* 1 */
new MP4Integer32Property("minorVersion"));
MP4Integer32Property* pCount =
new MP4Integer32Property("compatibleBrandsCount");
pCount->SetImplicit();
AddProperty(pCount); /* 2 */
MP4TableProperty* pTable =
new MP4TableProperty("compatibleBrands", pCount);
AddProperty(pTable); /* 3 */
pProp = new MP4StringProperty("brand");
pProp->SetFixedLength(4);
pTable->AddProperty(pProp);
}
void MP4FtypAtom::Generate()
{
MP4Atom::Generate();
((MP4StringProperty*)m_pProperties[0])->SetValue("mp42");
MP4StringProperty* pBrandProperty = (MP4StringProperty*)
((MP4TableProperty*)m_pProperties[3])->GetProperty(0);
ASSERT(pBrandProperty);
pBrandProperty->AddValue("mp42");
pBrandProperty->AddValue("isom");
((MP4Integer32Property*)m_pProperties[2])->IncrementValue();
((MP4Integer32Property*)m_pProperties[2])->IncrementValue();
}
void MP4FtypAtom::Read()
{
// table entry count computed from atom size
((MP4Integer32Property*)m_pProperties[2])->SetReadOnly(false);
((MP4Integer32Property*)m_pProperties[2])->SetValue((m_size - 8) / 4);
((MP4Integer32Property*)m_pProperties[2])->SetReadOnly(true);
MP4Atom::Read();
}
| {
"pile_set_name": "Github"
} |
form=词
tags=
萼绿华家萼绿春。
山瓶何处下青云。
浓香气味已醺人。
竹叶传杯惊老眼,
松醪题赋倒纶巾。
须防银字暖朱唇。
残腊晴寒出众芳。
风流勾引破春光。
年年长为此花忙。
夜久莫教银烛灺,
酒边何似玉台妆。
冰肌温处觅馀香。
棐几明窗乐未央。
熏炉茗碗是家常。
客来长揖对胡床。
蟹眼汤深轻泛乳,
龙涎灰暖细烘香。
为君行草写秋阳。
翡翠钗头缀玉虫。
秋蟾飘下广寒宫。
数枝金粟露华浓。
花底清歌生皓齿,
烛边疏影映酥胸。
恼人风味冷香中。
花气天然百和芬。
仙风吹过海中春。
龙涎沈水总销魂。
清润巧萦金缕细,
氤氲偏傍玉脂温。
别来长是惜馀熏。
花气薰人百和香。
少陵佳句是仙方。
空教蜂蝶为花忙。
和露摘来轻换骨,
傍怀闻处恼回肠。
去年时候入思量。
花气蒸浓古鼎烟。
水沈春透露华鲜。
心清无暇数龙涎。
乞与病夫僧帐座,
不妨公子醉茵眠。
普熏三界扫腥膻。
目送归州铁瓮城。
隔江想见蜀山青。
风前团扇仆频更。
梦里有时身化鹤,
人间无数草为萤。
此时山月下楼明。
曲室明窗烛吐光。
瓦炉灰暖炷瓢香。
夜阑茗碗间飞觞。
坐稳蒲团凭棐几,
熏馀纸帐掩梨床。
个中风味更难忘。
榕叶桄榔驿枕溪。
海风吹断瘴云低。
薄寒初觉到征衣。
岁晚可堪归梦远,
愁深偏恨得书稀。
荒庭日脚又垂西。
山绕平湖波撼城,
湖光倒影浸山青,
水晶楼下欲三更。
雾柳暗时云度月,
露荷翻处水流萤,
萧萧散发到天明。
睡起中庭月未蹉。
繁香随影上轻罗。
多情肯放一春过。
比似雪时犹带韵,
不如梅处却缘多。
酒边枕畔奈愁何。
燕掠风樯款款飞。
艳桃秾李闹长堤。
骑鲸人去晓莺啼。
可意湖山留我住,
断肠烟水送君归。
三春不是别离时。
一枕秋风两处凉。
雨声初歇漏声长。
池塘零落藕花香。
归梦等闲归燕去,
断肠分付断云行。
画屏今夜更思量。
月转花枝清影疏。
露华浓处滴真珠。
天香遗恨罥花须。
沐出乌云多态度,
晕成娥绿费功夫。
归时分付与妆梳。
云气吞江卷夕阳。
白头波上电飞忙。
奔雷惊雨溅胡床。
玉节故人同壮观,
锦囊公子更平章。
榕阴归梦十分凉。
以上张元干作品《浣溪沙》共16首
| {
"pile_set_name": "Github"
} |
/*
* Process Hacker -
* internal object manager
*
* Copyright (C) 2009-2016 wj32
*
* This file is part of Process Hacker.
*
* Process Hacker 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.
*
* Process Hacker 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 Process Hacker. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _PH_REFP_H
#define _PH_REFP_H
#define PH_OBJECT_TYPE_TABLE_SIZE 256
/** The object was allocated from the small free list. */
#define PH_OBJECT_FROM_SMALL_FREE_LIST 0x1
/** The object was allocated from the type free list. */
#define PH_OBJECT_FROM_TYPE_FREE_LIST 0x2
/**
* The object header contains object manager information including the reference count of an object
* and its type.
*/
typedef struct _PH_OBJECT_HEADER
{
union
{
struct
{
USHORT TypeIndex;
UCHAR Flags;
UCHAR Reserved1;
#ifdef _WIN64
ULONG Reserved2;
#endif
union
{
LONG RefCount;
struct
{
LONG SavedTypeIndex : 16;
LONG SavedFlags : 8;
LONG Reserved : 7;
LONG DeferDelete : 1; // MUST be the high bit, so that RefCount < 0 when deferring delete
};
};
#ifdef _WIN64
ULONG Reserved3;
#endif
};
SLIST_ENTRY DeferDeleteListEntry;
};
#ifdef DEBUG
PVOID StackBackTrace[16];
LIST_ENTRY ObjectListEntry;
#endif
/**
* The body of the object. For use by the \ref PhObjectToObjectHeader and
* \ref PhObjectHeaderToObject macros.
*/
QUAD_PTR Body;
} PH_OBJECT_HEADER, *PPH_OBJECT_HEADER;
#ifndef DEBUG
#ifdef _WIN64
C_ASSERT(FIELD_OFFSET(PH_OBJECT_HEADER, TypeIndex) == 0x0);
C_ASSERT(FIELD_OFFSET(PH_OBJECT_HEADER, Flags) == 0x2);
C_ASSERT(FIELD_OFFSET(PH_OBJECT_HEADER, Reserved1) == 0x3);
C_ASSERT(FIELD_OFFSET(PH_OBJECT_HEADER, Reserved2) == 0x4);
C_ASSERT(FIELD_OFFSET(PH_OBJECT_HEADER, RefCount) == 0x8);
C_ASSERT(FIELD_OFFSET(PH_OBJECT_HEADER, Reserved3) == 0xc);
C_ASSERT(FIELD_OFFSET(PH_OBJECT_HEADER, DeferDeleteListEntry) == 0x0);
C_ASSERT(FIELD_OFFSET(PH_OBJECT_HEADER, Body) == 0x10);
#else
C_ASSERT(FIELD_OFFSET(PH_OBJECT_HEADER, TypeIndex) == 0x0);
C_ASSERT(FIELD_OFFSET(PH_OBJECT_HEADER, Flags) == 0x2);
C_ASSERT(FIELD_OFFSET(PH_OBJECT_HEADER, Reserved1) == 0x3);
C_ASSERT(FIELD_OFFSET(PH_OBJECT_HEADER, RefCount) == 0x4);
C_ASSERT(FIELD_OFFSET(PH_OBJECT_HEADER, DeferDeleteListEntry) == 0x0);
C_ASSERT(FIELD_OFFSET(PH_OBJECT_HEADER, Body) == 0x8);
#endif
#endif
/**
* Gets a pointer to the object header for an object.
*
* \param Object A pointer to an object.
*
* \return A pointer to the object header of the object.
*/
#define PhObjectToObjectHeader(Object) ((PPH_OBJECT_HEADER)CONTAINING_RECORD((PCHAR)(Object), PH_OBJECT_HEADER, Body))
/**
* Gets a pointer to an object from an object header.
*
* \param ObjectHeader A pointer to an object header.
*
* \return A pointer to an object.
*/
#define PhObjectHeaderToObject(ObjectHeader) ((PVOID)&((PPH_OBJECT_HEADER)(ObjectHeader))->Body)
/**
* Calculates the total size to allocate for an object.
*
* \param Size The size of the object to allocate.
*
* \return The new size, including space for the object header.
*/
#define PhAddObjectHeaderSize(Size) ((Size) + UFIELD_OFFSET(PH_OBJECT_HEADER, Body))
/** An object type specifies a kind of object and its delete procedure. */
typedef struct _PH_OBJECT_TYPE
{
/** The flags that were used to create the object type. */
USHORT Flags;
UCHAR TypeIndex;
UCHAR Reserved;
/** The total number of objects of this type that are alive. */
ULONG NumberOfObjects;
/** An optional procedure called when objects of this type are freed. */
PPH_TYPE_DELETE_PROCEDURE DeleteProcedure;
/** The name of the type. */
PWSTR Name;
/** A free list to use when allocating for this type. */
PH_FREE_LIST FreeList;
} PH_OBJECT_TYPE, *PPH_OBJECT_TYPE;
/**
* Increments a reference count, but will never increment from a nonpositive value to 1.
*
* \param RefCount A pointer to a reference count.
*/
FORCEINLINE
BOOLEAN
PhpInterlockedIncrementSafe(
_Inout_ PLONG RefCount
)
{
/* Here we will attempt to increment the reference count, making sure that it is positive. */
return _InterlockedIncrementPositive(RefCount);
}
PPH_OBJECT_HEADER PhpAllocateObject(
_In_ PPH_OBJECT_TYPE ObjectType,
_In_ SIZE_T ObjectSize
);
VOID PhpFreeObject(
_In_ PPH_OBJECT_HEADER ObjectHeader
);
VOID PhpDeferDeleteObject(
_In_ PPH_OBJECT_HEADER ObjectHeader
);
NTSTATUS PhpDeferDeleteObjectRoutine(
_In_ PVOID Parameter
);
#endif
| {
"pile_set_name": "Github"
} |
<resources>
<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Light">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
</resources>
| {
"pile_set_name": "Github"
} |
/*******************************************************************************
* Copyright 2014 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.ai.utils.random;
import com.badlogic.gdx.math.MathUtils;
/** @author davebaol */
public final class GaussianDoubleDistribution extends DoubleDistribution {
public static final GaussianDoubleDistribution STANDARD_NORMAL = new GaussianDoubleDistribution(0, 1);
private final double mean;
private final double standardDeviation;
public GaussianDoubleDistribution (double mean, double standardDeviation) {
this.mean = mean;
this.standardDeviation = standardDeviation;
}
@Override
public double nextDouble () {
return mean + MathUtils.random.nextGaussian() * standardDeviation;
}
public double getMean () {
return mean;
}
public double getStandardDeviation () {
return standardDeviation;
}
}
| {
"pile_set_name": "Github"
} |
gcr.io/google_containers/kube-apiserver-arm:v1.5.6
| {
"pile_set_name": "Github"
} |
template_path: valid_template.json
| {
"pile_set_name": "Github"
} |
var semver = require('semver');
module.exports = function(grunt) {
grunt.registerTask('version', 'Updates the current release version', function() {
var done = this.async(),
pkg = grunt.config('pkg'),
version = grunt.option('ver');
if (!semver.valid(version)) {
throw new Error('Must provide a version number (Ex: --ver=1.0.0):\n\t' + version + '\n\n');
}
pkg.version = version;
grunt.config('pkg', pkg);
grunt.log.writeln('Updating to version ' + version);
grunt.task.run(['release']);
done();
});
};
| {
"pile_set_name": "Github"
} |
<?php
/**
* TechDivision\Import\Repositories\Finders\AbstractFinder
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
*
* PHP version 5
*
* @author Tim Wagner <[email protected]>
* @copyright 2019 TechDivision GmbH <[email protected]>
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @link https://github.com/techdivision/import
* @link http://www.techdivision.com
*/
namespace TechDivision\Import\Repositories\Finders;
/**
* An abstract finder implementation.
*
* @author Tim Wagner <[email protected]>
* @copyright 2019 TechDivision GmbH <[email protected]>
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @link https://github.com/techdivision/import
* @link http://www.techdivision.com
*/
abstract class AbstractFinder implements FinderInterface
{
/**
* The unique key of the prepared statement that has to be executed.
*
* @var string
*/
protected $key;
/**
* The entity's primary key name.
*
* @var string
*/
protected $primaryKeyName;
/**
* The finder's entity name.
*
* @var string
*/
protected $entityName;
/**
* The prepared statement.
*
* @var \PDOStatement
*/
protected $preparedStatement;
/**
* Initialize the repository with the passed connection and utility class name.
* .
* @param \PDOStatement $preparedStatement The prepared statement
* @param string $key The unqiue key of the prepared statement that has to be executed.
* @param string $primaryKeyName The entity's primary key
* @param string $entityName The finder's entity name
*/
public function __construct(\PDOStatement $preparedStatement, $key, $primaryKeyName, $entityName)
{
$this->preparedStatement = $preparedStatement;
$this->primaryKeyName = $primaryKeyName;
$this->entityName = $entityName;
$this->key = $key;
}
/**
* Return's the finder's unique key.
*
* @return string The unique key
*/
public function getKey()
{
return $this->key;
}
/**
* Return's the entity's primary key name.
*
* @return string The entity's primary key name
*/
public function getPrimaryKeyName()
{
return $this->primaryKeyName;
}
/**
* Return's the finder's entity name.
*
* @return string The finder's entity name
*/
public function getEntityName()
{
return $this->entityName;
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build arm,linux
package unix
import (
"syscall"
"unsafe"
)
func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
func NsecToTimespec(nsec int64) (ts Timespec) {
ts.Sec = int32(nsec / 1e9)
ts.Nsec = int32(nsec % 1e9)
return
}
func NsecToTimeval(nsec int64) (tv Timeval) {
nsec += 999 // round up to microsecond
tv.Sec = int32(nsec / 1e9)
tv.Usec = int32(nsec % 1e9 / 1e3)
return
}
func Pipe(p []int) (err error) {
if len(p) != 2 {
return EINVAL
}
var pp [2]_C_int
err = pipe2(&pp, 0)
p[0] = int(pp[0])
p[1] = int(pp[1])
return
}
//sysnb pipe2(p *[2]_C_int, flags int) (err error)
func Pipe2(p []int, flags int) (err error) {
if len(p) != 2 {
return EINVAL
}
var pp [2]_C_int
err = pipe2(&pp, flags)
p[0] = int(pp[0])
p[1] = int(pp[1])
return
}
// Underlying system call writes to newoffset via pointer.
// Implemented in assembly to avoid allocation.
func seek(fd int, offset int64, whence int) (newoffset int64, err syscall.Errno)
func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
newoffset, errno := seek(fd, offset, whence)
if errno != 0 {
return 0, errno
}
return newoffset, nil
}
//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error)
//sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error)
//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sysnb getgroups(n int, list *_Gid_t) (nn int, err error) = SYS_GETGROUPS32
//sysnb setgroups(n int, list *_Gid_t) (err error) = SYS_SETGROUPS32
//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error)
//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error)
//sysnb socket(domain int, typ int, proto int) (fd int, err error)
//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error)
//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error)
//sysnb socketpair(domain int, typ int, flags int, fd *[2]int32) (err error)
//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error)
//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error)
// 64-bit file system and 32-bit uid calls
// (16-bit uid calls are not always supported in newer kernels)
//sys Dup2(oldfd int, newfd int) (err error)
//sys Fchown(fd int, uid int, gid int) (err error) = SYS_FCHOWN32
//sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64
//sysnb Getegid() (egid int) = SYS_GETEGID32
//sysnb Geteuid() (euid int) = SYS_GETEUID32
//sysnb Getgid() (gid int) = SYS_GETGID32
//sysnb Getuid() (uid int) = SYS_GETUID32
//sysnb InotifyInit() (fd int, err error)
//sys Lchown(path string, uid int, gid int) (err error) = SYS_LCHOWN32
//sys Listen(s int, n int) (err error)
//sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64
//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT
//sys Setfsgid(gid int) (err error) = SYS_SETFSGID32
//sys Setfsuid(uid int) (err error) = SYS_SETFSUID32
//sysnb Setregid(rgid int, egid int) (err error) = SYS_SETREGID32
//sysnb Setresgid(rgid int, egid int, sgid int) (err error) = SYS_SETRESGID32
//sysnb Setresuid(ruid int, euid int, suid int) (err error) = SYS_SETRESUID32
//sysnb Setreuid(ruid int, euid int) (err error) = SYS_SETREUID32
//sys Shutdown(fd int, how int) (err error)
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
//sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64
// Vsyscalls on amd64.
//sysnb Gettimeofday(tv *Timeval) (err error)
//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
//sys Pause() (err error)
func Time(t *Time_t) (Time_t, error) {
var tv Timeval
err := Gettimeofday(&tv)
if err != nil {
return 0, err
}
if t != nil {
*t = Time_t(tv.Sec)
}
return Time_t(tv.Sec), nil
}
func Utime(path string, buf *Utimbuf) error {
tv := []Timeval{
{Sec: buf.Actime},
{Sec: buf.Modtime},
}
return Utimes(path, tv)
}
//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64
//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64
//sys Truncate(path string, length int64) (err error) = SYS_TRUNCATE64
//sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64
func Fadvise(fd int, offset int64, length int64, advice int) (err error) {
_, _, e1 := Syscall6(SYS_ARM_FADVISE64_64, uintptr(fd), uintptr(advice), uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
//sys mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error)
func Fstatfs(fd int, buf *Statfs_t) (err error) {
_, _, e := Syscall(SYS_FSTATFS64, uintptr(fd), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf)))
if e != 0 {
err = e
}
return
}
func Statfs(path string, buf *Statfs_t) (err error) {
pathp, err := BytePtrFromString(path)
if err != nil {
return err
}
_, _, e := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(pathp)), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf)))
if e != 0 {
err = e
}
return
}
func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) {
page := uintptr(offset / 4096)
if offset != int64(page)*4096 {
return 0, EINVAL
}
return mmap2(addr, length, prot, flags, fd, page)
}
type rlimit32 struct {
Cur uint32
Max uint32
}
//sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_UGETRLIMIT
const rlimInf32 = ^uint32(0)
const rlimInf64 = ^uint64(0)
func Getrlimit(resource int, rlim *Rlimit) (err error) {
err = prlimit(0, resource, nil, rlim)
if err != ENOSYS {
return err
}
rl := rlimit32{}
err = getrlimit(resource, &rl)
if err != nil {
return
}
if rl.Cur == rlimInf32 {
rlim.Cur = rlimInf64
} else {
rlim.Cur = uint64(rl.Cur)
}
if rl.Max == rlimInf32 {
rlim.Max = rlimInf64
} else {
rlim.Max = uint64(rl.Max)
}
return
}
//sysnb setrlimit(resource int, rlim *rlimit32) (err error) = SYS_SETRLIMIT
func Setrlimit(resource int, rlim *Rlimit) (err error) {
err = prlimit(0, resource, rlim, nil)
if err != ENOSYS {
return err
}
rl := rlimit32{}
if rlim.Cur == rlimInf64 {
rl.Cur = rlimInf32
} else if rlim.Cur < uint64(rlimInf32) {
rl.Cur = uint32(rlim.Cur)
} else {
return EINVAL
}
if rlim.Max == rlimInf64 {
rl.Max = rlimInf32
} else if rlim.Max < uint64(rlimInf32) {
rl.Max = uint32(rlim.Max)
} else {
return EINVAL
}
return setrlimit(resource, &rl)
}
func (r *PtraceRegs) PC() uint64 { return uint64(r.Uregs[15]) }
func (r *PtraceRegs) SetPC(pc uint64) { r.Uregs[15] = uint32(pc) }
func (iov *Iovec) SetLen(length int) {
iov.Len = uint32(length)
}
func (msghdr *Msghdr) SetControllen(length int) {
msghdr.Controllen = uint32(length)
}
func (cmsg *Cmsghdr) SetLen(length int) {
cmsg.Len = uint32(length)
}
//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
func Poll(fds []PollFd, timeout int) (n int, err error) {
if len(fds) == 0 {
return poll(nil, 0, timeout)
}
return poll(&fds[0], len(fds), timeout)
}
| {
"pile_set_name": "Github"
} |
// g2o - General Graph Optimization
// Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef G2O_OPTIMIZATION_ALGORITHM_WITH_HESSIAN_H
#define G2O_OPTIMIZATION_ALGORITHM_WITH_HESSIAN_H
#include "optimization_algorithm.h"
namespace g2o {
class Solver;
/**
* \brief Base for solvers operating on the approximated Hessian, e.g., Gauss-Newton, Levenberg
*/
class OptimizationAlgorithmWithHessian : public OptimizationAlgorithm
{
public:
explicit OptimizationAlgorithmWithHessian(Solver* solver);
virtual ~OptimizationAlgorithmWithHessian();
virtual bool init(bool online = false);
virtual bool computeMarginals(SparseBlockMatrix<MatrixXd>& spinv, const std::vector<std::pair<int, int> >& blockIndices);
virtual bool buildLinearStructure();
virtual void updateLinearSystem();
virtual bool updateStructure(const std::vector<HyperGraph::Vertex*>& vset, const HyperGraph::EdgeSet& edges);
//! return the underlying solver used to solve the linear system
Solver* solver() { return _solver;}
/**
* write debug output of the Hessian if system is not positive definite
*/
virtual void setWriteDebug(bool writeDebug);
virtual bool writeDebug() const { return _writeDebug->value();}
protected:
Solver* _solver;
Property<bool>* _writeDebug;
};
}// end namespace
#endif
| {
"pile_set_name": "Github"
} |
steel_ stainless _type 302
113 317.70801 8.0600004 6
6 0.001000 14 0.007000 24 0.180000 25 0.010000 26 0.712000 28 0.090000
1.00E-03,1.582E-03 1.25E-03,1.940E-03 1.50E-03,2.286E-03 1.75E-03,2.623E-03
2.00E-03,2.952E-03 2.50E-03,3.588E-03 3.00E-03,4.200E-03 3.50E-03,4.792E-03
4.00E-03,5.367E-03 4.50E-03,5.926E-03 5.00E-03,6.473E-03 5.50E-03,7.009E-03
6.00E-03,7.534E-03 7.00E-03,8.558E-03 8.00E-03,9.551E-03 9.00E-03,1.052E-02
1.00E-02,1.146E-02 1.25E-02,1.375E-02 1.50E-02,1.594E-02 1.75E-02,1.807E-02
2.00E-02,2.014E-02 2.50E-02,2.416E-02 3.00E-02,2.806E-02 3.50E-02,3.188E-02
4.00E-02,3.565E-02 4.50E-02,3.937E-02 5.00E-02,4.308E-02 5.50E-02,4.677E-02
6.00E-02,5.046E-02 7.00E-02,5.784E-02 8.00E-02,6.526E-02 9.00E-02,7.274E-02
1.00E-01,8.027E-02 1.25E-01,9.933E-02 1.50E-01,1.185E-01 1.75E-01,1.376E-01
2.00E-01,1.564E-01 2.50E-01,1.927E-01 3.00E-01,2.271E-01 3.50E-01,2.597E-01
4.00E-01,2.909E-01 4.50E-01,3.209E-01 5.00E-01,3.499E-01 5.50E-01,3.780E-01
6.00E-01,4.053E-01 7.00E-01,4.579E-01 8.00E-01,5.080E-01 9.00E-01,5.562E-01
1.00E+00,6.024E-01 1.25E+00,7.115E-01 1.50E+00,8.129E-01 1.75E+00,9.079E-01
2.00E+00,9.975E-01 2.50E+00,1.163E+00 3.00E+00,1.313E+00 3.50E+00,1.450E+00
4.00E+00,1.575E+00 4.50E+00,1.691E+00 5.00E+00,1.798E+00 5.50E+00,1.898E+00
6.00E+00,1.992E+00 7.00E+00,2.163E+00 8.00E+00,2.316E+00 9.00E+00,2.455E+00
1.00E+01,2.583E+00 1.25E+01,2.863E+00 1.50E+01,3.104E+00 1.75E+01,3.315E+00
2.00E+01,3.506E+00 2.50E+01,3.839E+00 3.00E+01,4.124E+00 3.50E+01,4.374E+00
4.00E+01,4.597E+00 4.50E+01,4.797E+00 5.00E+01,4.979E+00 5.50E+01,5.145E+00
6.00E+01,5.299E+00 7.00E+01,5.574E+00 8.00E+01,5.815E+00 9.00E+01,6.029E+00
1.00E+02,6.222E+00 1.25E+02,6.635E+00 1.50E+02,6.977E+00 1.75E+02,7.269E+00
2.00E+02,7.523E+00 2.50E+02,7.952E+00 3.00E+02,8.306E+00 3.50E+02,8.607E+00
4.00E+02,8.869E+00 4.50E+02,9.101E+00 5.00E+02,9.309E+00 5.50E+02,9.497E+00
6.00E+02,9.670E+00 7.00E+02,9.975E+00 8.00E+02,1.024E+01 9.00E+02,1.048E+01
1.00E+03,1.069E+01 1.25E+03,1.113E+01 1.50E+03,1.149E+01 1.75E+03,1.180E+01
2.00E+03,1.207E+01 2.50E+03,1.251E+01 3.00E+03,1.288E+01 3.50E+03,1.319E+01
4.00E+03,1.345E+01 4.50E+03,1.369E+01 5.00E+03,1.390E+01 5.50E+03,1.409E+01
6.00E+03,1.427E+01 7.00E+03,1.457E+01 8.00E+03,1.484E+01 9.00E+03,1.508E+01
1.00E+04,1.529E+01
| {
"pile_set_name": "Github"
} |
class AddDescriptionToTeams < ActiveRecord::Migration
def up
add_column :teams, :description, :text
Team.reset_column_information
Team.where(:name => Team::ADMINS).update_all(['description = ?', 'Most powerful users with full spectrum of permissions.'])
add_index :teams, [:organization_id, :name], :unique => true
end
def down
remove_column :teams, :description
remove_index :teams, [:organization_id, :name]
end
end
| {
"pile_set_name": "Github"
} |
# where py object files go (they have a name prefix to prevent filename clashes)
PY_BUILD = $(BUILD)/py
# where autogenerated header files go
HEADER_BUILD = $(BUILD)/genhdr
# file containing qstr defs for the core Python bit
PY_QSTR_DEFS = $(PY_SRC)/qstrdefs.h
# If qstr autogeneration is not disabled we specify the output header
# for all collected qstrings.
ifneq ($(QSTR_AUTOGEN_DISABLE),1)
QSTR_DEFS_COLLECTED = $(HEADER_BUILD)/qstrdefs.collected.h
endif
# Any files listed by this variable will cause a full regeneration of qstrs
QSTR_GLOBAL_DEPENDENCIES += $(PY_SRC)/mpconfig.h mpconfigport.h
# some code is performance bottleneck and compiled with other optimization options
CSUPEROPT = -O3
# this sets the config file for FatFs
CFLAGS_MOD += -DFFCONF_H=\"lib/oofatfs/ffconf.h\"
ifeq ($(MICROPY_PY_USSL),1)
CFLAGS_MOD += -DMICROPY_PY_USSL=1
ifeq ($(MICROPY_SSL_AXTLS),1)
CFLAGS_MOD += -DMICROPY_SSL_AXTLS=1 -I$(TOP)/lib/axtls/ssl -I$(TOP)/lib/axtls/crypto -I$(TOP)/extmod/axtls-include
AXTLS_DIR = lib/axtls
$(BUILD)/$(AXTLS_DIR)/%.o: CFLAGS += -Wno-all -Wno-unused-parameter -Wno-uninitialized -Wno-sign-compare -Wno-old-style-definition $(AXTLS_DEFS_EXTRA)
SRC_MOD += $(addprefix $(AXTLS_DIR)/,\
ssl/asn1.c \
ssl/loader.c \
ssl/tls1.c \
ssl/tls1_svr.c \
ssl/tls1_clnt.c \
ssl/x509.c \
crypto/aes.c \
crypto/bigint.c \
crypto/crypto_misc.c \
crypto/hmac.c \
crypto/md5.c \
crypto/rsa.c \
crypto/sha1.c \
)
else ifeq ($(MICROPY_SSL_MBEDTLS),1)
# Can be overridden by ports which have "builtin" mbedTLS
MICROPY_SSL_MBEDTLS_INCLUDE ?= $(TOP)/lib/mbedtls/include
CFLAGS_MOD += -DMICROPY_SSL_MBEDTLS=1 -I$(MICROPY_SSL_MBEDTLS_INCLUDE)
LDFLAGS_MOD += -L$(TOP)/lib/mbedtls/library -lmbedx509 -lmbedtls -lmbedcrypto
endif
endif
#ifeq ($(MICROPY_PY_LWIP),1)
#CFLAGS_MOD += -DMICROPY_PY_LWIP=1 -I../lib/lwip/src/include -I../lib/lwip/src/include/ipv4 -I../extmod/lwip-include
#endif
ifeq ($(MICROPY_PY_LWIP),1)
LWIP_DIR = lib/lwip/src
INC += -I$(TOP)/lib/lwip/src/include -I$(TOP)/lib/lwip/src/include/ipv4 -I$(TOP)/extmod/lwip-include
CFLAGS_MOD += -DMICROPY_PY_LWIP=1
SRC_MOD += extmod/modlwip.c lib/netutils/netutils.c
SRC_MOD += $(addprefix $(LWIP_DIR)/,\
core/def.c \
core/dns.c \
core/init.c \
core/mem.c \
core/memp.c \
core/netif.c \
core/pbuf.c \
core/raw.c \
core/stats.c \
core/sys.c \
core/tcp.c \
core/tcp_in.c \
core/tcp_out.c \
core/timers.c \
core/udp.c \
core/ipv4/autoip.c \
core/ipv4/icmp.c \
core/ipv4/igmp.c \
core/ipv4/inet.c \
core/ipv4/inet_chksum.c \
core/ipv4/ip_addr.c \
core/ipv4/ip.c \
core/ipv4/ip_frag.c \
)
ifeq ($(MICROPY_PY_LWIP_SLIP),1)
CFLAGS_MOD += -DMICROPY_PY_LWIP_SLIP=1
SRC_MOD += $(LWIP_DIR)/netif/slipif.c
endif
endif
ifeq ($(MICROPY_PY_BTREE),1)
BTREE_DIR = lib/berkeley-db-1.xx
BTREE_DEFS = -D__DBINTERFACE_PRIVATE=1 -Dmpool_error=printf -Dabort=abort_ "-Dvirt_fd_t=void*" $(BTREE_DEFS_EXTRA)
INC += -I$(TOP)/$(BTREE_DIR)/PORT/include
SRC_MOD += extmod/modbtree.c
SRC_MOD += $(addprefix $(BTREE_DIR)/,\
btree/bt_close.c \
btree/bt_conv.c \
btree/bt_debug.c \
btree/bt_delete.c \
btree/bt_get.c \
btree/bt_open.c \
btree/bt_overflow.c \
btree/bt_page.c \
btree/bt_put.c \
btree/bt_search.c \
btree/bt_seq.c \
btree/bt_split.c \
btree/bt_utils.c \
mpool/mpool.c \
)
CFLAGS_MOD += -DMICROPY_PY_BTREE=1
# we need to suppress certain warnings to get berkeley-db to compile cleanly
# and we have separate BTREE_DEFS so the definitions don't interfere with other source code
$(BUILD)/$(BTREE_DIR)/%.o: CFLAGS += -Wno-old-style-definition -Wno-sign-compare -Wno-unused-parameter $(BTREE_DEFS)
$(BUILD)/extmod/modbtree.o: CFLAGS += $(BTREE_DEFS)
endif
# py object files
PY_CORE_O_BASENAME = $(addprefix py/,\
mpstate.o \
nlr.o \
nlrx86.o \
nlrx64.o \
nlrthumb.o \
nlrxtensa.o \
nlrsetjmp.o \
malloc.o \
gc.o \
pystack.o \
qstr.o \
vstr.o \
mpprint.o \
unicode.o \
mpz.o \
reader.o \
lexer.o \
parse.o \
scope.o \
compile.o \
emitcommon.o \
emitbc.o \
asmbase.o \
asmx64.o \
emitnx64.o \
asmx86.o \
emitnx86.o \
asmthumb.o \
emitnthumb.o \
emitinlinethumb.o \
asmarm.o \
emitnarm.o \
asmxtensa.o \
emitnxtensa.o \
emitinlinextensa.o \
formatfloat.o \
parsenumbase.o \
parsenum.o \
emitglue.o \
persistentcode.o \
runtime.o \
runtime_utils.o \
scheduler.o \
nativeglue.o \
stackctrl.o \
argcheck.o \
warning.o \
map.o \
obj.o \
objarray.o \
objattrtuple.o \
objbool.o \
objboundmeth.o \
objcell.o \
objclosure.o \
objcomplex.o \
objdeque.o \
objdict.o \
objenumerate.o \
objexcept.o \
objfilter.o \
objfloat.o \
objfun.o \
objgenerator.o \
objgetitemiter.o \
objint.o \
objint_longlong.o \
objint_mpz.o \
objlist.o \
objmap.o \
objmodule.o \
objobject.o \
objpolyiter.o \
objproperty.o \
objnone.o \
objnamedtuple.o \
objrange.o \
objreversed.o \
objset.o \
objsingleton.o \
objslice.o \
objstr.o \
objstrunicode.o \
objstringio.o \
objtuple.o \
objtype.o \
objzip.o \
opmethods.o \
sequence.o \
stream.o \
binary.o \
builtinimport.o \
builtinevex.o \
builtinhelp.o \
modarray.o \
modbuiltins.o \
modcollections.o \
modgc.o \
modio.o \
modmath.o \
modcmath.o \
modmicropython.o \
modstruct.o \
modsys.o \
moduerrno.o \
modthread.o \
vm.o \
bc.o \
showbc.o \
repl.o \
smallint.o \
frozenmod.o \
)
PY_EXTMOD_O_BASENAME = \
extmod/moductypes.o \
extmod/modujson.o \
extmod/modure.o \
extmod/moduzlib.o \
extmod/moduheapq.o \
extmod/modutimeq.o \
extmod/moduhashlib.o \
extmod/moducryptolib.o \
extmod/modubinascii.o \
extmod/virtpin.o \
extmod/machine_mem.o \
extmod/machine_pinbase.o \
extmod/machine_signal.o \
extmod/machine_pulse.o \
extmod/machine_i2c.o \
extmod/machine_spi.o \
extmod/modussl_axtls.o \
extmod/modussl_mbedtls.o \
extmod/modurandom.o \
extmod/moduselect.o \
extmod/moduwebsocket.o \
extmod/modwebrepl.o \
extmod/modframebuf.o \
extmod/vfs.o \
extmod/vfs_reader.o \
extmod/vfs_posix.o \
extmod/vfs_posix_file.o \
extmod/vfs_fat.o \
extmod/vfs_fat_diskio.o \
extmod/vfs_fat_file.o \
extmod/utime_mphal.o \
extmod/uos_dupterm.o \
lib/embed/abort_.o \
lib/utils/printf.o \
# prepend the build destination prefix to the py object files
PY_CORE_O = $(addprefix $(BUILD)/, $(PY_CORE_O_BASENAME))
PY_EXTMOD_O = $(addprefix $(BUILD)/, $(PY_EXTMOD_O_BASENAME))
# this is a convenience variable for ports that want core, extmod and frozen code
PY_O = $(PY_CORE_O) $(PY_EXTMOD_O)
# object file for frozen files
ifneq ($(FROZEN_DIR),)
PY_O += $(BUILD)/$(BUILD)/frozen.o
endif
# object file for frozen bytecode (frozen .mpy files)
ifneq ($(FROZEN_MPY_DIR),)
PY_O += $(BUILD)/$(BUILD)/frozen_mpy.o
endif
# Sources that may contain qstrings
SRC_QSTR_IGNORE = py/nlr%
SRC_QSTR = $(SRC_MOD) $(filter-out $(SRC_QSTR_IGNORE),$(PY_CORE_O_BASENAME:.o=.c)) $(PY_EXTMOD_O_BASENAME:.o=.c)
# Anything that depends on FORCE will be considered out-of-date
FORCE:
.PHONY: FORCE
$(HEADER_BUILD)/mpversion.h: FORCE | $(HEADER_BUILD)
$(Q)$(PYTHON) $(PY_SRC)/makeversionhdr.py $@
# mpconfigport.mk is optional, but changes to it may drastically change
# overall config, so they need to be caught
MPCONFIGPORT_MK = $(wildcard mpconfigport.mk)
# qstr data
# Adding an order only dependency on $(HEADER_BUILD) causes $(HEADER_BUILD) to get
# created before we run the script to generate the .h
# Note: we need to protect the qstr names from the preprocessor, so we wrap
# the lines in "" and then unwrap after the preprocessor is finished.
$(HEADER_BUILD)/qstrdefs.generated.h: $(PY_QSTR_DEFS) $(QSTR_DEFS) $(QSTR_DEFS_COLLECTED) $(PY_SRC)/makeqstrdata.py mpconfigport.h $(MPCONFIGPORT_MK) $(PY_SRC)/mpconfig.h | $(HEADER_BUILD)
$(ECHO) "GEN $@"
$(Q)cat $(PY_QSTR_DEFS) $(QSTR_DEFS) $(QSTR_DEFS_COLLECTED) | $(SED) 's/^Q(.*)/"&"/' | $(CPP) $(CFLAGS) - | $(SED) 's/^"\(Q(.*)\)"/\1/' > $(HEADER_BUILD)/qstrdefs.preprocessed.h
$(Q)$(PYTHON) $(PY_SRC)/makeqstrdata.py $(HEADER_BUILD)/qstrdefs.preprocessed.h > $@
# Force nlr code to always be compiled with space-saving optimisation so
# that the function preludes are of a minimal and predictable form.
$(PY_BUILD)/nlr%.o: CFLAGS += -Os
# optimising gc for speed; 5ms down to 4ms on pybv2
$(PY_BUILD)/gc.o: CFLAGS += $(CSUPEROPT)
# optimising vm for speed, adds only a small amount to code size but makes a huge difference to speed (20% faster)
$(PY_BUILD)/vm.o: CFLAGS += $(CSUPEROPT)
# Optimizing vm.o for modern deeply pipelined CPUs with branch predictors
# may require disabling tail jump optimization. This will make sure that
# each opcode has its own dispatching jump which will improve branch
# branch predictor efficiency.
# https://marc.info/?l=lua-l&m=129778596120851
# http://hg.python.org/cpython/file/b127046831e2/Python/ceval.c#l828
# http://www.emulators.com/docs/nx25_nostradamus.htm
#-fno-crossjumping
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2011 The Closure Compiler 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 com.google.javascript.jscomp;
/**
* Unit tests for {#link {@link PeepholeReplaceKnownMethods}
*
*/
public class PeepholeReplaceKnownMethodsTest extends CompilerTestCase {
private boolean late = true;
public PeepholeReplaceKnownMethodsTest() {
super("");
}
@Override
public void setUp() {
enableLineNumberCheck(true);
}
@Override
public CompilerPass getProcessor(final Compiler compiler) {
CompilerPass peepholePass = new PeepholeOptimizationsPass(compiler,
new PeepholeReplaceKnownMethods(late));
return peepholePass;
}
public void testStringIndexOf() {
fold("x = 'abcdef'.indexOf('b')", "x = 1");
fold("x = 'abcdefbe'.indexOf('b', 2)", "x = 6");
fold("x = 'abcdef'.indexOf('bcd')", "x = 1");
fold("x = 'abcdefsdfasdfbcdassd'.indexOf('bcd', 4)", "x = 13");
fold("x = 'abcdef'.lastIndexOf('b')", "x = 1");
fold("x = 'abcdefbe'.lastIndexOf('b')", "x = 6");
fold("x = 'abcdefbe'.lastIndexOf('b', 5)", "x = 1");
// Both elements must be strings. Don't do anything if either one is not
// string.
fold("x = 'abc1def'.indexOf(1)", "x = 3");
fold("x = 'abcNaNdef'.indexOf(NaN)", "x = 3");
fold("x = 'abcundefineddef'.indexOf(undefined)", "x = 3");
fold("x = 'abcnulldef'.indexOf(null)", "x = 3");
fold("x = 'abctruedef'.indexOf(true)", "x = 3");
// The following test case fails with JSC_PARSE_ERROR. Hence omitted.
// foldSame("x = 1.indexOf('bcd');");
foldSame("x = NaN.indexOf('bcd')");
foldSame("x = undefined.indexOf('bcd')");
foldSame("x = null.indexOf('bcd')");
foldSame("x = true.indexOf('bcd')");
foldSame("x = false.indexOf('bcd')");
// Avoid dealing with regex or other types.
foldSame("x = 'abcdef'.indexOf(/b./)");
foldSame("x = 'abcdef'.indexOf({a:2})");
foldSame("x = 'abcdef'.indexOf([1,2])");
}
public void testStringJoinAddSparse() {
fold("x = [,,'a'].join(',')", "x = ',,a'");
}
public void testNoStringJoin() {
foldSame("x = [].join(',',2)");
foldSame("x = [].join(f)");
}
public void testStringJoinAdd() {
fold("x = ['a', 'b', 'c'].join('')", "x = \"abc\"");
fold("x = [].join(',')", "x = \"\"");
fold("x = ['a'].join(',')", "x = \"a\"");
fold("x = ['a', 'b', 'c'].join(',')", "x = \"a,b,c\"");
fold("x = ['a', foo, 'b', 'c'].join(',')",
"x = [\"a\",foo,\"b,c\"].join()");
fold("x = [foo, 'a', 'b', 'c'].join(',')",
"x = [foo,\"a,b,c\"].join()");
fold("x = ['a', 'b', 'c', foo].join(',')",
"x = [\"a,b,c\",foo].join()");
// Works with numbers
fold("x = ['a=', 5].join('')", "x = \"a=5\"");
fold("x = ['a', '5'].join(7)", "x = \"a75\"");
// Works on boolean
fold("x = ['a=', false].join('')", "x = \"a=false\"");
fold("x = ['a', '5'].join(true)", "x = \"atrue5\"");
fold("x = ['a', '5'].join(false)", "x = \"afalse5\"");
// Only optimize if it's a size win.
fold("x = ['a', '5', 'c'].join('a very very very long chain')",
"x = [\"a\",\"5\",\"c\"].join(\"a very very very long chain\")");
// TODO(user): Its possible to fold this better.
foldSame("x = ['', foo].join('-')");
foldSame("x = ['', foo, ''].join()");
fold("x = ['', '', foo, ''].join(',')",
"x = [',', foo, ''].join()");
fold("x = ['', '', foo, '', ''].join(',')",
"x = [',', foo, ','].join()");
fold("x = ['', '', foo, '', '', bar].join(',')",
"x = [',', foo, ',', bar].join()");
fold("x = [1,2,3].join('abcdef')",
"x = '1abcdef2abcdef3'");
fold("x = [1,2].join()", "x = '1,2'");
fold("x = [null,undefined,''].join(',')", "x = ',,'");
fold("x = [null,undefined,0].join(',')", "x = ',,0'");
// This can be folded but we don't currently.
foldSame("x = [[1,2],[3,4]].join()"); // would like: "x = '1,2,3,4'"
}
public void testStringJoinAdd_b1992789() {
fold("x = ['a'].join('')", "x = \"a\"");
fold("x = [foo()].join('')", "x = '' + foo()");
fold("[foo()].join('')", "'' + foo()");
}
public void testFoldStringSubstr() {
fold("x = 'abcde'.substr(0,2)", "x = 'ab'");
fold("x = 'abcde'.substr(1,2)", "x = 'bc'");
fold("x = 'abcde'['substr'](1,3)", "x = 'bcd'");
fold("x = 'abcde'.substr(2)", "x = 'cde'");
// we should be leaving negative indexes alone for now
foldSame("x = 'abcde'.substr(-1)");
foldSame("x = 'abcde'.substr(1, -2)");
foldSame("x = 'abcde'.substr(1, 2, 3)");
foldSame("x = 'a'.substr(0, 2)");
}
public void testFoldStringSubstring() {
fold("x = 'abcde'.substring(0,2)", "x = 'ab'");
fold("x = 'abcde'.substring(1,2)", "x = 'b'");
fold("x = 'abcde'['substring'](1,3)", "x = 'bc'");
fold("x = 'abcde'.substring(2)", "x = 'cde'");
// we should be leaving negative indexes alone for now
foldSame("x = 'abcde'.substring(-1)");
foldSame("x = 'abcde'.substring(1, -2)");
foldSame("x = 'abcde'.substring(1, 2, 3)");
foldSame("x = 'a'.substring(0, 2)");
}
public void testFoldStringCharAt() {
fold("x = 'abcde'.charAt(0)", "x = 'a'");
fold("x = 'abcde'.charAt(1)", "x = 'b'");
fold("x = 'abcde'.charAt(2)", "x = 'c'");
fold("x = 'abcde'.charAt(3)", "x = 'd'");
fold("x = 'abcde'.charAt(4)", "x = 'e'");
foldSame("x = 'abcde'.charAt(5)"); // or x = ''
foldSame("x = 'abcde'.charAt(-1)"); // or x = ''
foldSame("x = 'abcde'.charAt(y)");
foldSame("x = 'abcde'.charAt()"); // or x = 'a'
foldSame("x = 'abcde'.charAt(0, ++z)"); // or (++z, 'a')
foldSame("x = 'abcde'.charAt(null)"); // or x = 'a'
foldSame("x = 'abcde'.charAt(true)"); // or x = 'b'
fold("x = '\\ud834\udd1e'.charAt(0)", "x = '\\ud834'");
fold("x = '\\ud834\udd1e'.charAt(1)", "x = '\\udd1e'");
}
public void testFoldStringCharCodeAt() {
fold("x = 'abcde'.charCodeAt(0)", "x = 97");
fold("x = 'abcde'.charCodeAt(1)", "x = 98");
fold("x = 'abcde'.charCodeAt(2)", "x = 99");
fold("x = 'abcde'.charCodeAt(3)", "x = 100");
fold("x = 'abcde'.charCodeAt(4)", "x = 101");
foldSame("x = 'abcde'.charCodeAt(5)"); // or x = (0/0)
foldSame("x = 'abcde'.charCodeAt(-1)"); // or x = (0/0)
foldSame("x = 'abcde'.charCodeAt(y)");
foldSame("x = 'abcde'.charCodeAt()"); // or x = 97
foldSame("x = 'abcde'.charCodeAt(0, ++z)"); // or (++z, 97)
foldSame("x = 'abcde'.charCodeAt(null)"); // or x = 97
foldSame("x = 'abcde'.charCodeAt(true)"); // or x = 98
fold("x = '\\ud834\udd1e'.charCodeAt(0)", "x = 55348");
fold("x = '\\ud834\udd1e'.charCodeAt(1)", "x = 56606");
}
public void testFoldStringSplit() {
late = false;
fold("x = 'abcde'.split('foo')", "x = ['abcde']");
fold("x = 'abcde'.split()", "x = ['abcde']");
fold("x = 'abcde'.split(null)", "x = ['abcde']");
fold("x = 'a b c d e'.split(' ')", "x = ['a','b','c','d','e']");
fold("x = 'a b c d e'.split(' ', 0)", "x = []");
fold("x = 'abcde'.split('cd')", "x = ['ab','e']");
fold("x = 'a b c d e'.split(' ', 1)", "x = ['a']");
fold("x = 'a b c d e'.split(' ', 3)", "x = ['a','b','c']");
fold("x = 'a b c d e'.split(null, 1)", "x = ['a b c d e']");
fold("x = 'aaaaa'.split('a')", "x = ['', '', '', '', '', '']");
fold("x = 'xyx'.split('x')", "x = ['', 'y', '']");
// Empty separator
fold("x = 'abcde'.split('')", "x = ['a','b','c','d','e']");
fold("x = 'abcde'.split('', 3)", "x = ['a','b','c']");
// Empty separator AND empty string
fold("x = ''.split('')", "x = []");
// Separator equals string
fold("x = 'aaa'.split('aaa')", "x = ['','']");
fold("x = ' '.split(' ')", "x = ['','']");
foldSame("x = 'abcde'.split(/ /)");
foldSame("x = 'abcde'.split(' ', -1)");
late = true;
foldSame("x = 'a b c d e'.split(' ')");
}
public void testJoinBug() {
fold("var x = [].join();", "var x = '';");
fold("var x = [x].join();", "var x = '' + x;");
foldSame("var x = [x,y].join();");
foldSame("var x = [x,y,z].join();");
foldSame("shape['matrix'] = [\n" +
" Number(headingCos2).toFixed(4),\n" +
" Number(-headingSin2).toFixed(4),\n" +
" Number(headingSin2 * yScale).toFixed(4),\n" +
" Number(headingCos2 * yScale).toFixed(4),\n" +
" 0,\n" +
" 0\n" +
" ].join()");
}
public void testToUpper() {
fold("'a'.toUpperCase()", "'A'");
fold("'A'.toUpperCase()", "'A'");
fold("'aBcDe'.toUpperCase()", "'ABCDE'");
}
public void testToLower() {
fold("'A'.toLowerCase()", "'a'");
fold("'a'.toLowerCase()", "'a'");
fold("'aBcDe'.toLowerCase()", "'abcde'");
}
public void testFoldParseNumbers() {
enableNormalize();
enableEcmaScript5(true);
fold("x = parseInt('123')", "x = 123");
fold("x = parseInt(' 123')", "x = 123");
fold("x = parseInt('123', 10)", "x = 123");
fold("x = parseInt('0xA')", "x = 10");
fold("x = parseInt('0xA', 16)", "x = 10");
fold("x = parseInt('07', 8)", "x = 7");
fold("x = parseInt('08')", "x = 8");
fold("x = parseInt('0')", "x = 0");
fold("x = parseFloat('0')", "x = 0");
fold("x = parseFloat('1.23')", "x = 1.23");
fold("x = parseFloat('1.2300')", "x = 1.23");
fold("x = parseFloat(' 0.3333')", "x = 0.3333");
fold("x = parseFloat('0100')", "x = 100");
fold("x = parseFloat('0100.000')", "x = 100");
//Mozilla Dev Center test cases
fold("x = parseInt(' 0xF', 16)", "x = 15");
fold("x = parseInt(' F', 16)", "x = 15");
fold("x = parseInt('17', 8)", "x = 15");
fold("x = parseInt('015', 10)", "x = 15");
fold("x = parseInt('1111', 2)", "x = 15");
fold("x = parseInt('12', 13)", "x = 15");
fold("x = parseInt(021, 8)", "x = 15");
fold("x = parseInt(15.99, 10)", "x = 15");
fold("x = parseFloat('3.14')", "x = 3.14");
fold("x = parseFloat(3.14)", "x = 3.14");
//Valid calls - unable to fold
foldSame("x = parseInt('FXX123', 16)");
foldSame("x = parseInt('15*3', 10)");
foldSame("x = parseInt('15e2', 10)");
foldSame("x = parseInt('15px', 10)");
foldSame("x = parseInt('-0x08')");
foldSame("x = parseInt('1', -1)");
foldSame("x = parseFloat('3.14more non-digit characters')");
foldSame("x = parseFloat('314e-2')");
foldSame("x = parseFloat('0.0314E+2')");
foldSame("x = parseFloat('3.333333333333333333333333')");
//Invalid calls
foldSame("x = parseInt('0xa', 10)");
foldSame("x = parseInt('')");
enableEcmaScript5(false);
foldSame("x = parseInt('08')");
}
@Override
protected int getNumRepetitions() {
// Reduce this to 2 if we get better expression evaluators.
return 2;
}
private void foldSame(String js) {
testSame(js);
}
private void fold(String js, String expected) {
test(js, expected);
}
}
| {
"pile_set_name": "Github"
} |
TIMESTAMP = 1527915942
SHA256 (gnome3/gnome-terminal-3.28.2.tar.xz) = a283dca4980eecf9184a55aac03fef99f85748461ff190423a2253f3b4557279
SIZE (gnome3/gnome-terminal-3.28.2.tar.xz) = 2094920
| {
"pile_set_name": "Github"
} |
package com.jeesuite.mybatis.plugin.cache;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.persistence.Id;
import javax.persistence.Table;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Invocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jeesuite.common.json.JsonUtils;
import com.jeesuite.common.util.DigestUtils;
import com.jeesuite.mybatis.MybatisConfigs;
import com.jeesuite.mybatis.MybatisRuntimeContext;
import com.jeesuite.mybatis.core.BaseEntity;
import com.jeesuite.mybatis.core.InterceptorHandler;
import com.jeesuite.mybatis.crud.CrudMethods;
import com.jeesuite.mybatis.exception.MybatisHanlerInitException;
import com.jeesuite.mybatis.kit.CacheKeyUtils;
import com.jeesuite.mybatis.kit.ReflectUtils;
import com.jeesuite.mybatis.parser.EntityInfo;
import com.jeesuite.mybatis.parser.EntityInfo.MapperMethod;
import com.jeesuite.mybatis.parser.MybatisMapperParser;
import com.jeesuite.mybatis.plugin.JeesuiteMybatisInterceptor;
import com.jeesuite.mybatis.plugin.cache.annotation.Cache;
import com.jeesuite.mybatis.plugin.cache.annotation.CacheIgnore;
import com.jeesuite.mybatis.plugin.cache.provider.DefaultCacheProvider;
import com.jeesuite.mybatis.plugin.pagination.PageExecutor;
import com.jeesuite.spring.InstanceFactory;
/**
* 自动缓存拦截处理
* @description <br>
* @author <a href="mailto:[email protected]">vakin</a>
* @date 2015年12月7日
* @Copyright (c) 2015, jwww
*/
public class CacheHandler implements InterceptorHandler {
protected static final Logger logger = LoggerFactory.getLogger(CacheHandler.class);
public static final String CURRENT_USER_CONTEXT_NAME = "currentUser";
private static final String BLOCK_ON_CONCURRENT_LOCK_RETURN = "_block_on_concurrentLock";
public static final String NAME = "cache";
public final static long IN_1MINS = 60;
public final static long IN_1HOUR = 60 * 60;
public static long defaultCacheExpire = IN_1HOUR;
private static final String STR_PARAM = "param";
protected static final String DOT = ".";
// 计算关联key集合权重的基数
private static long baseScore = System.currentTimeMillis() / 1000 - 3600;
private boolean dynamicCacheTime = false;
private boolean nullValueCache = false;
//null缓存占位符(避免频繁查询不存在对象造成缓存穿透导致频繁查询db)
public static final String NULL_PLACEHOLDER = "~null";
private static final String VALUE_TEMPLATE = "_%s_%s";
private static final String KEY_NAME = "cache.expired.methods";
//需要缓存的所有mapper
private static List<String> cacheEnableMappers = new ArrayList<>();
private static Map<String, Map<String, QueryMethodCache>> queryCacheMethods = new HashMap<>();
private static Map<String, UpdateByPkMethodCache> updateCacheMethods = new HashMap<>();
//记录当前线程写入的所有缓存key
private static ThreadLocal<List<String>> transactionWriteCacheKeys = new ThreadLocal<>();
private ThreadLocal<String> concurrentLockKey = new ThreadLocal<>();
//<mtId,[关联查询方法列表]>
private static Map<String, List<String>> requiredCheckCacheMethodMapppings = new HashMap<>();
protected static CacheProvider cacheProvider;
private ScheduledExecutorService clearExpiredKeysTimer;
public void setCacheProvider(CacheProvider cacheProvider) {
CacheHandler.cacheProvider = cacheProvider;
}
private static CacheProvider getCacheProvider() {
if(cacheProvider == null){
synchronized (CacheHandler.class) {
if(cacheProvider != null)return cacheProvider;
if(cacheProvider == null){
cacheProvider = InstanceFactory.getInstance(CacheProvider.class);
}
if(cacheProvider == null){
cacheProvider = new DefaultCacheProvider();
}
logger.info("Initializing cacheProvider use:{} ",cacheProvider.getClass().getName());
}
}
return cacheProvider;
}
@Override
public Object onInterceptor(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
MappedStatement mt = (MappedStatement)args[0];
concurrentLockKey.remove();
boolean getLock = false;
String cacheKey = null;
if(mt.getSqlCommandType().equals(SqlCommandType.SELECT)){
//分页查询
if(PageExecutor.getPageParams() != null){
return null;
}
//事务方法内部的查询不走缓存
if(MybatisRuntimeContext.isTransactionalOn()){
if(logger.isDebugEnabled())logger.debug(">>auto_cache_process isTransactionalOn SKIP -> mapperId:{}",mt.getId());
return null;
}
//按主键查询
QueryMethodCache cacheInfo = getQueryMethodCache(mt.getId());
if(cacheInfo == null)return null;
//
if(skipCache(cacheInfo)){
if(logger.isDebugEnabled())logger.debug(">>auto_cache_process cache_mark_expired SKIP -> userId:{}, mapperId:{}",MybatisRuntimeContext.getCurrentUserId(),mt.getId());
return null;
}
cacheKey = genarateQueryCacheKey(cacheInfo.keyPattern, args[1]);
//并发控制防止缓存穿透
if(!cacheInfo.concurrency){
concurrentLockKey.set("concurrent:" + cacheKey);
getLock = getCacheProvider().setnx(concurrentLockKey.get(), "1", 30);
if(!getLock){
if(logger.isDebugEnabled())logger.debug(">>auto_cache_process not_getConcurrentLock BLOCK -> mapperId:{}",mt.getId());
return BLOCK_ON_CONCURRENT_LOCK_RETURN;
}
if(logger.isDebugEnabled())logger.debug(">>auto_cache_process getConcurrentLock CONTINUE -> mapperId:{}",mt.getId());
}
Object cacheObject = null;
boolean nullPlaceholder = false;
//
if(!cacheInfo.isSecondQueryById()){
//从缓存读取
cacheObject = getCacheProvider().get(cacheKey);
nullPlaceholder = nullValueCache && NULL_PLACEHOLDER.equals(cacheObject);
if(StringUtils.isNotBlank(cacheInfo.refKey) && (nullPlaceholder || cacheObject == null)){
cacheObject = getCacheProvider().get(cacheInfo.refKey);
nullPlaceholder = nullValueCache && NULL_PLACEHOLDER.equals(cacheObject);
}
if(nullPlaceholder){
logger.debug(">>auto_cache_process method[{}] find NULL_PLACEHOLDER result from cacheKey:{}",mt.getId(),cacheKey);
}else if(cacheObject != null){
logger.debug(">>auto_cache_process method[{}] find result from cacheKey:{}",mt.getId(),cacheKey);
}
}else{
//新根据缓存KEY找到与按ID缓存的KEY
String refCacheKey = nullValueCache ? getCacheProvider().get(cacheKey) : getCacheProvider().getStr(cacheKey);
if(refCacheKey != null){
if(nullPlaceholder = (nullValueCache && NULL_PLACEHOLDER.equals(refCacheKey))){
cacheObject = NULL_PLACEHOLDER;
}else{
cacheObject = getCacheProvider().get(refCacheKey);
if(cacheObject != null && logger.isDebugEnabled())logger.debug(">>auto_cache_process method[{}] find result from cacheKey:{} ,ref by:{}",mt.getId(),refCacheKey,cacheKey);
}
}
}
if(nullPlaceholder){
cacheObject = new ArrayList<>(0);
}else if(cacheObject != null && !(cacheObject instanceof Collection)){
cacheObject = Arrays.asList(cacheObject);
}
return cacheObject;
} else{
tryRemarkCleanRalationCache(mt);
}
return null;
}
@SuppressWarnings("rawtypes")
@Override
public void onFinished(Invocation invocation,Object result) {
try {
if(BLOCK_ON_CONCURRENT_LOCK_RETURN.equals(result))return;
Object[] args = invocation.getArgs();
MappedStatement mt = (MappedStatement)args[0];
String mapperNameSpace = mt.getId().substring(0, mt.getId().lastIndexOf(DOT));
QueryMethodCache cacheInfo = null;
if(mt.getSqlCommandType().equals(SqlCommandType.SELECT)){
if(result == null)return;
if((cacheInfo = getQueryMethodCache(mt.getId())) == null)return;
final String cacheKey = genarateQueryCacheKey(cacheInfo.keyPattern, args[1]);
if(result instanceof List){
List list = (List)result;
if(list.isEmpty()){
if(nullValueCache){
getCacheProvider().set(cacheKey,NULL_PLACEHOLDER, IN_1MINS);
}
return;
}
result = cacheInfo.collectionResult ? result : list.get(0);
}
//
if(!cacheInfo.isSecondQueryById()){
if(getCacheProvider().set(cacheKey,result, cacheInfo.getExpire())){
if(logger.isDebugEnabled())logger.debug(">>auto_cache_process method[{}] put result to cache,cacheKey:{}",mt.getId(),cacheKey);
}
if(cacheInfo.uniqueIndex){
cacheUniqueSelectRef(result, mt, cacheKey);
}
}else{
//之前没有按主键的缓存,增加按主键缓存
String idCacheKey = genarateQueryCacheKey(getQueryByPkMethodCache(mt.getId()).keyPattern,result);
if(idCacheKey != null && cacheKey != null){
if(!getCacheProvider().exists(idCacheKey)){
//缓存idkey->实体
getCacheProvider().set(idCacheKey,result, cacheInfo.getExpire());
}
//缓存fieldkey->idkey
cacheFieldRefKey(cacheKey,idCacheKey, cacheInfo.getExpire());
if(logger.isDebugEnabled())logger.debug(">>auto_cache_process method[{}] put result to cache,cacheKey:{},and add ref cacheKey:{}",mt.getId(),idCacheKey,cacheKey);
}
}
}else{
if(!cacheEnableMappers.contains(mapperNameSpace))return;
//返回0,未更新成功
if(result != null && ((int)result) == 0)return;
boolean insertAction = mt.getSqlCommandType().equals(SqlCommandType.INSERT);
boolean updateAction = mt.getSqlCommandType().equals(SqlCommandType.UPDATE);
boolean deleteAcrion = mt.getSqlCommandType().equals(SqlCommandType.DELETE);
if(updateCacheMethods.containsKey(mt.getId())){
String idCacheKey = null;
UpdateByPkMethodCache updateMethodCache = updateCacheMethods.get(mt.getId());
if(deleteAcrion){
idCacheKey = genarateQueryCacheKey(updateMethodCache.keyPattern,args[1]);
getCacheProvider().remove(idCacheKey);
if(logger.isDebugEnabled())logger.debug(">>auto_cache_process method[{}] remove cacheKey:{} from cache",mt.getId(),idCacheKey);
}else{
idCacheKey = genarateQueryCacheKey(updateMethodCache.keyPattern,args[1]);
if(insertAction || updateAction){
if(result != null){
QueryMethodCache queryByPkMethodCache = getQueryByPkMethodCache(mt.getId());
getCacheProvider().set(idCacheKey,args[1], queryByPkMethodCache.getExpire());
if(logger.isDebugEnabled())logger.debug(">>auto_cache_process method[{}] update cacheKey:{}",mt.getId(),idCacheKey);
//插入其他唯一字段引用
if(insertAction)cacheUniqueSelectRef(args[1], mt, idCacheKey);
//
addCurrentThreadCacheKey(idCacheKey);
}
}
}
}
}
} finally {
//清除并发控制锁
String lockKey = concurrentLockKey.get();
if(lockKey != null){
cacheProvider.remove(lockKey);
concurrentLockKey.remove();
}
}
}
/**
* 缓存其他唯一结果查询方法和主键缓存的引用
* @param object
* @param mt
* @param cacheKey
*/
private void cacheUniqueSelectRef(Object object, MappedStatement mt, String cacheKey) {
Collection<QueryMethodCache> mcs = queryCacheMethods.get(mt.getId().substring(0, mt.getId().lastIndexOf(DOT))).values();
outter:for (QueryMethodCache methodCache : mcs) {
if(methodCache.isPk)continue;
try {
Object[] cacheFieldValues = new Object[methodCache.fieldNames.length];
for (int i = 0; i < cacheFieldValues.length; i++) {
if(methodCache.fieldNames[i] == null)break outter;
cacheFieldValues[i] = ReflectUtils.getObjectValue(object, methodCache.fieldNames[i]);
if(cacheFieldValues[i] == null)continue outter;
}
String fieldCacheKey = genarateQueryCacheKey(methodCache.keyPattern , cacheFieldValues);
cacheFieldRefKey(fieldCacheKey,cacheKey, methodCache.getExpire());
if(logger.isDebugEnabled())logger.debug(">>auto_cache_process method[{}] add ref cacheKey:{}",mt.getId(),fieldCacheKey);
} catch (Exception e) {
logger.warn("cacheUniqueSelectRef:"+cacheKey,e);
}
}
}
/**
* 缓存字段查询到idkey
* @param fieldCacheKey
* @param idCacheKey
* @param expired
*/
private void cacheFieldRefKey(String fieldCacheKey,String idCacheKey,long expired){
if(nullValueCache){
getCacheProvider().set(fieldCacheKey, idCacheKey, expired);
}else{
getCacheProvider().setStr(fieldCacheKey, idCacheKey, expired);
}
}
/**
* 生成查询缓存key
* @param cacheInfo
* @param param
* @return
*/
@SuppressWarnings("unchecked")
private String genarateQueryCacheKey(String keyPattern,Object param){
String text;
try {
Object[] args;
if(param instanceof Map){
Map<String, Object> map = (Map<String, Object>) param;
if(map.containsKey(STR_PARAM + "1")){
args = new String[map.size()/2];
for (int i = 0; i < args.length; i++) {
args[i] = CacheKeyUtils.objcetToString(map.get(STR_PARAM + (i+1)));
}
}else{
args = new String[]{CacheKeyUtils.objcetToString(map)};
}
}else if(param instanceof BaseEntity){
Serializable id = ((BaseEntity)param).getId();
if(id != null && !"0".equals(id.toString())){
args = new String[]{(((BaseEntity)param).getId()).toString()};
}else{
args = new String[]{CacheKeyUtils.objcetToString(param)};
}
}else if(param instanceof Object[]){
args = (Object[])param;
}else if(param == null){
args = new Object[0];
}else{
args = new String[]{CacheKeyUtils.objcetToString(param)};
}
text = StringUtils.join(args,"-");
} catch (Exception e) {
text = JsonUtils.toJson(param);
e.printStackTrace();
}
if(text.length() > 64)text = DigestUtils.md5(text);
return String.format(keyPattern, text);
}
private QueryMethodCache getQueryMethodCache(String mtId){
String key1 = mtId.substring(0, mtId.lastIndexOf(DOT));
if(queryCacheMethods.containsKey(key1)){
return queryCacheMethods.get(key1).get(mtId);
}
return null;
}
private QueryMethodCache getQueryByPkMethodCache(String mtId){
mtId = mtId.substring(0, mtId.lastIndexOf(DOT));
if(queryCacheMethods.containsKey(mtId)){
return queryCacheMethods.get(mtId).get(mtId + "." + CrudMethods.selectByPrimaryKey.name());
}
return null;
}
private boolean skipCache(QueryMethodCache metadata){
if(!metadata.checkExpired)return false;
String mapperId = metadata.methodName;
String contextParamVal;
if(metadata.contextParam != null){
contextParamVal = MybatisRuntimeContext.getContextParam(metadata.contextParam);
if(contextParamVal == null){
logger.warn(">>auto_cache_process checkSkipCache contextParamValIsNull ->method:{},contextParam:{}",mapperId,metadata.contextParam);
return true;
}
}else{
contextParamVal = StringUtils.EMPTY;
}
String value = String.format(VALUE_TEMPLATE, contextParamVal,mapperId);
//
boolean result;
//可能标记了多个查询方法,所以这里不能remove
if(StringUtils.isBlank(contextParamVal)){
result = getCacheProvider().existZsetValue(KEY_NAME, value);
if(result){
result = getCacheProvider().setnx(value, DOT, metadata.expire);
if(logger.isDebugEnabled()){
logger.debug(">>auto_cache_process NoContextParam ->checkKey:{},skip:{}",value, result);
}
}
}else{
result = getCacheProvider().removeZsetValue(KEY_NAME, value);
}
if(logger.isDebugEnabled()){
logger.debug(">>auto_cache_process checkSkipCache ->method:{},checkKey:{},skip:{}",mapperId,value, result);
}
return result;
}
private void tryRemarkCleanRalationCache(MappedStatement mt){
String mapperId = mt.getId();
if(!requiredCheckCacheMethodMapppings.containsKey(mapperId))return;
List<String> list = requiredCheckCacheMethodMapppings.get(mapperId);
//
long score = System.currentTimeMillis() / 1000 - baseScore;
String contextParam;
QueryMethodCache metadata;
for (String queryMapperId : list) {
metadata = getQueryMethodCache(queryMapperId);
if(!metadata.checkExpired)continue;
if(metadata.contextParam != null){
contextParam = MybatisRuntimeContext.getContextParam(metadata.contextParam);
if(contextParam == null){
logger.warn(">>auto_cache_process markCacheExpired contextParamValIsNull ->method:{},queryMethod:{},contextParam:{}",mapperId,queryMapperId,metadata.contextParam);
return;
}
}else{
contextParam = StringUtils.EMPTY;
}
String value = String.format(VALUE_TEMPLATE, contextParam,queryMapperId);
getCacheProvider().addZsetValue(KEY_NAME, value, score);
if(metadata.contextParam == null){
getCacheProvider().remove(value);
}
if(logger.isDebugEnabled())logger.debug(">>auto_cache_process markCacheExpired ->method:{}, addKey :{},cleanScore:{}",mapperId,value,score);
}
}
@Override
public void start(JeesuiteMybatisInterceptor context) {
nullValueCache = MybatisConfigs.getBoolean(context.getGroupName(), MybatisConfigs.CACHE_NULL_VALUE, false);
dynamicCacheTime = MybatisConfigs.getBoolean(context.getGroupName(), MybatisConfigs.CACHE_DYNAMIC_EXPIRE, false);
defaultCacheExpire = Long.parseLong(MybatisConfigs.getProperty(context.getGroupName(), MybatisConfigs.CACHE_EXPIRE_SECONDS, String.valueOf(IN_1HOUR)));
logger.info("nullValueCache:{},defaultCacheExpireSeconds:{},dynamicCacheTime:{}",nullValueCache,defaultCacheExpire,dynamicCacheTime);
List<EntityInfo> entityInfos = MybatisMapperParser.getEntityInfos(context.getGroupName());
Class<BaseEntity> baseEntityClass = BaseEntity.class;
QueryMethodCache methodCache = null;
for (EntityInfo ei : entityInfos) {
if(ei.getMapperClass().isAnnotationPresent(CacheIgnore.class))continue;
if(!baseEntityClass.isAssignableFrom(ei.getEntityClass())){
logger.warn("[{}] not extends from [{}],ignore register auto cache!!!!",ei.getEntityClass().getName(),baseEntityClass.getName());
continue;
}
Class<?> mapperClass = ei.getMapperClass();
//按主键查询方法定义
QueryMethodCache queryByPKMethod = generateQueryByPKMethod(mapperClass, ei.getEntityClass());
if(queryByPKMethod == null)continue;
Map<String, QueryMethodCache> tmpMap = new HashMap<>();
//主键查询方法
tmpMap.put(queryByPKMethod.methodName, queryByPKMethod);
String keyPatternForPK = queryByPKMethod.keyPattern;
//接口定义的自动缓存方法
for (MapperMethod method : ei.getMapperMethods()) {
if(method.getMethod().isAnnotationPresent(Cache.class)){
if(tmpMap.containsKey(method.getFullName()))continue;
methodCache = generateQueryMethodCacheByMethod(ei, method);
tmpMap.put(method.getFullName(), methodCache);
logger.info("解析查询方法{}自动缓存配置 ok,keyPattern:[{}]",methodCache.methodName,methodCache.keyPattern);
}
}
//缓存需要自动缓存的mapper
cacheEnableMappers.add(ei.getMapperClass().getName());
logger.info("解析查询方法{}自动缓存配置 ok,keyPattern:[{}]",queryByPKMethod.methodName,queryByPKMethod.keyPattern);
queryCacheMethods.put(mapperClass.getName(), tmpMap);
//更新缓存方法
generateUpdateByPkCacheMethod(mapperClass, ei.getEntityClass(), keyPatternForPK);
}
//
if(queryCacheMethods.isEmpty())return;
//
registerClearExpiredKeyTask();
}
private void registerClearExpiredKeyTask(){
clearExpiredKeysTimer = Executors.newScheduledThreadPool(1);
clearExpiredKeysTimer.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
long maxScore = System.currentTimeMillis()/1000 - baseScore - defaultCacheExpire - 3600;
boolean res = cacheProvider.removeZsetValues(KEY_NAME, 0, maxScore);
logger.info("CacheRefresher clearExpiredMarkKeysTimer runing:cacheName:{} , score range:0~{} ,result:{}",KEY_NAME,maxScore,res);
}
}, 5, 2, TimeUnit.MINUTES);
}
/**
* 生成按主键查询缓存定义
* @param mapperClass
* @param entityClass
* @return
*/
private QueryMethodCache generateQueryByPKMethod(Class<?> mapperClass,Class<?> entityClass){
QueryMethodCache methodCache = null;
Field[] fields = entityClass.getDeclaredFields();
//主键key前缀
for (Field field : fields) {
if(field.isAnnotationPresent(Id.class)){
methodCache = new QueryMethodCache();
methodCache.isPk = true;
methodCache.collectionResult = false;
methodCache.keyPattern = entityClass.getSimpleName() + ".id:%s";
methodCache.methodName = mapperClass.getName() + "." + CrudMethods.selectByPrimaryKey.name();
methodCache.expire = defaultCacheExpire;
}
}
return methodCache;
}
private void generateUpdateByPkCacheMethod(Class<?> mapperClass,Class<?> entityClass,String keyPatternForPK){
String methodName = null;
methodName = mapperClass.getName() + "." + CrudMethods.insert.name();
updateCacheMethods.put(methodName, new UpdateByPkMethodCache(entityClass,methodName, keyPatternForPK, SqlCommandType.INSERT));
methodName = mapperClass.getName() + "." + CrudMethods.insertSelective.name();
updateCacheMethods.put(methodName, new UpdateByPkMethodCache(entityClass,methodName, keyPatternForPK, SqlCommandType.INSERT));
//
methodName = mapperClass.getName() + "." + CrudMethods.updateByPrimaryKey.name();
updateCacheMethods.put(methodName, new UpdateByPkMethodCache(entityClass,methodName, keyPatternForPK, SqlCommandType.UPDATE));
methodName = mapperClass.getName() + "." + CrudMethods.updateByPrimaryKeySelective.name();
updateCacheMethods.put(methodName, new UpdateByPkMethodCache(entityClass,methodName, keyPatternForPK, SqlCommandType.UPDATE));
//按主键删除
methodName = mapperClass.getName() + "." + CrudMethods.deleteByPrimaryKey.name();
updateCacheMethods.put(methodName, new UpdateByPkMethodCache(entityClass,methodName, keyPatternForPK, SqlCommandType.DELETE));
}
/**
* 按查询方法生成缓存key前缀
* @param entityClassName
* @param method
* @return
*/
private QueryMethodCache generateQueryMethodCacheByMethod(EntityInfo entityInfo,MapperMethod mapperMethod){
Method method = mapperMethod.getMethod();
Cache cacheAnnotation = method.getAnnotation(Cache.class);
String[] evictOnMethods = cacheAnnotation.evictOnMethods();
Class<?> mapperClass = entityInfo.getMapperClass();
Class<?> entityClass = entityInfo.getEntityClass();
QueryMethodCache methodCache = new QueryMethodCache();
methodCache.methodName = mapperClass.getName() + DOT + method.getName();
methodCache.concurrency = cacheAnnotation.concurrency();
methodCache.uniqueIndex = cacheAnnotation.uniqueIndex();
if(cacheAnnotation.userScope()){
methodCache.contextParam = CURRENT_USER_CONTEXT_NAME;
}else if(cacheAnnotation.scopeContext().length > 0){
methodCache.contextParam = cacheAnnotation.scopeContext()[0];
}
if(cacheAnnotation.refKey().length > 0){
methodCache.refKey = cacheAnnotation.refKey()[0];
}
if(methodCache.contextParam != null && evictOnMethods.length == 0){
evictOnMethods = new String[]{"*"};
}
methodCache.checkExpired = evictOnMethods.length > 0;
if(cacheAnnotation.expire() > 0){
methodCache.expire = cacheAnnotation.expire();
}else if(cacheAnnotation.userScope()){
methodCache.expire = IN_1MINS * 10 < defaultCacheExpire ? IN_1MINS * 10 : defaultCacheExpire;
}
if(methodCache.uniqueIndex && method.getReturnType() != entityClass){
throw new MybatisHanlerInitException("@Cache with[uniqueIndex = true] but ReturnType not Match ["+entityClass.getName()+"]");
}
methodCache.collectionResult = method.getReturnType() == List.class || method.getReturnType() == Set.class;
methodCache.fieldNames = new String[method.getParameterTypes().length];
StringBuilder sb = new StringBuilder(entityClass.getSimpleName()).append(DOT).append(method.getName());
Annotation[][] annotations = method.getParameterAnnotations();
boolean uniqueQuery = method.getReturnType().isAnnotationPresent(Table.class);
for (int i = 0; i < annotations.length; i++) {
Annotation[] aa = annotations[i];
if(aa.length > 0){
String fieldName = null;
inner:for (Annotation annotation : aa) {
if(annotation.toString().contains(Param.class.getName())){
fieldName = ((Param)annotation).value();
break inner;
}
}
if(uniqueQuery && MybatisMapperParser.entityHasProperty(entityClass, fieldName)){
methodCache.fieldNames[i] = fieldName;
}
}
//
sb.append(i == 0 ? ":" : "_").append("%s");
}
methodCache.keyPattern = sb.toString();
if(uniqueQuery){
for (String name : methodCache.fieldNames) {
if(StringUtils.isBlank(name)){
methodCache.fieldNames = null;
break;
}
}
}
//
buildEvictOnMethods(mapperClass.getName(),mapperMethod,evictOnMethods);
return methodCache;
}
private void buildEvictOnMethods(String mapperClassName,MapperMethod method,String[] evictOnMethods) {
if(evictOnMethods == null|| evictOnMethods.length == 0){
return;
}
String targetMethodFullNamePrefix = mapperClassName.substring(0, mapperClassName.lastIndexOf(".") + 1);
String targetMapperClassName = null;
for (String methodName : evictOnMethods) {
if("*".equals(methodName)){
methodName = mapperClassName + ".*";
}
if(!methodName.startsWith(targetMethodFullNamePrefix)){
methodName = targetMethodFullNamePrefix + methodName;
}
targetMapperClassName = methodName.substring(0,methodName.lastIndexOf("."));
if(!methodName.endsWith("*")){
addCacheCheckRelations(methodName, method.getFullName());
}else{
EntityInfo methodEntityInfo = MybatisMapperParser.getEntityInfoByMapper(targetMapperClassName);
if(methodEntityInfo == null){
continue;
}
for (MapperMethod mm : methodEntityInfo.getMapperMethods()) {
if(mm.getSqlType() == SqlCommandType.SELECT)continue;
if(mm.getFullName().contains(methodName.replace("*", ""))){
addCacheCheckRelations(mm.getFullName(), method.getFullName());
}
}
}
}
}
private void addCacheCheckRelations(String updateMethodName,String queryMethodName){
List<String> list = requiredCheckCacheMethodMapppings.get(updateMethodName);
if(list == null){
list = new ArrayList<>();
requiredCheckCacheMethodMapppings.put(updateMethodName, list);
}
list.add(queryMethodName);
}
/**
* 查询缓存方法
*/
private class QueryMethodCache{
String methodName;
String keyPattern;
long expire = defaultCacheExpire;//过期时间(秒)
boolean isPk = false;//主键查询
boolean uniqueIndex = false;
boolean collectionResult = false;//查询结果是集合
String[] fieldNames;//作为查询条件的字段名称
boolean checkExpired = false; //是否需要检查缓存过期时间
String contextParam;
boolean concurrency = true;
String refKey;
public QueryMethodCache() {}
public void setExpire(long expire) {
this.expire = expire > 0 ? expire : defaultCacheExpire;
}
public long getExpire() {
if(!dynamicCacheTime)return expire;
//缓存时间加上随机,防止造成缓存同时失效雪崩
long rnd = RandomUtils.nextLong(0, IN_1HOUR);
return expire + (rnd > expire ? RandomUtils.nextLong(0, expire) : rnd);
}
/**
* 是否需要通过关联主键二次查询
* @return
*/
public boolean isSecondQueryById(){
return isPk == false && uniqueIndex;
}
}
/**
* 按主键更新(add,update,delete)的方法
*/
private class UpdateByPkMethodCache{
public String keyPattern;
public UpdateByPkMethodCache(Class<?> entityClass,String methodName, String keyPattern, SqlCommandType sqlCommandType) {
this.keyPattern = keyPattern;
}
}
private void addCurrentThreadCacheKey(String key){
List<String> keys = transactionWriteCacheKeys.get();
if(keys == null){
keys = new ArrayList<>();
transactionWriteCacheKeys.set(keys);
}
keys.add(key);
}
/**
* 回滚当前事务写入的缓存
*/
public static void rollbackCache(){
List<String> keys = transactionWriteCacheKeys.get();
if(keys == null)return;
for (String key : keys) {
getCacheProvider().remove(key);
}
}
@Override
public void close() {
try {
getCacheProvider().close();
} catch (Exception e) {}
try {
clearExpiredKeysTimer.shutdown();
} catch (Exception e) {}
}
@Override
public int interceptorOrder() {
return 1;
}
}
| {
"pile_set_name": "Github"
} |
"Filed out from Dolphin Smalltalk 7"!
TextDocument subclass: #XmlPad
instanceVariableNames: 'viewOptions'
classVariableNames: 'RememberPlacementMask'
poolDictionaries: ''
classInstanceVariableNames: ''!
XmlPad guid: (GUID fromString: '{0b798c7b-c80f-46ab-9dd4-d8832b78d33c}')!
XmlPad addClassConstant: 'RememberPlacementMask' value: 16r1!
XmlPad comment: '`XmlPad` is a simple XML text editor. It is intended to demonstrate the `DocumentShell` hierarchy of Dolphin''s application framework, the `ScintillaView` editor component, and the use of the MSXML. XmlPad also demonstrates how to use the registry to save and restore user preferences.
```
XmlPad show
```'!
!XmlPad categoriesForClass!MVP-Presenters! !
!XmlPad methodsFor!
about
"Pop up a little helpful info. about this sample program."
self class about!
basicValidateXml
(self parseXml: self getDocumentData validate: true) free!
booleanOptions
^#(#('AutoCompleteEnabled' #isAutoCompleteEnabled #isAutoCompleteEnabled:))!
booleanViewOptions
^#(#('IdentationGuides' #hasIndentationGuides #hasIndentationGuides:) #('FormattingMarks' #hasFormattingMarks #hasFormattingMarks:) #('WordWrap' #hasWordWrap #hasWordWrap:) #('LineNumbers' #hasLineNumbers #hasLineNumbers:) #('AutoCompleteSingle' #isAutoCompletionSingleMatchChosen #isAutoCompletionSingleMatchChosen:) #('AutoCompleteTruncate' #isAutoCompletionTruncating #isAutoCompletionTruncating:) #('Folding' #isFoldingEnabled #isFoldingEnabled:))!
canSave
"Answer whether the document is in a valid state and can be saved. Here we check that the document consists of valid Xml."
^
[self basicValidateXml.
true] on: DOMParseError
do:
[:ex |
MessageBox
confirm: 'The XML contains one or more errors and is invalid. Are you sure that you would like to save it?'
caption: ex tag displayString]!
hasFormattingMarks
^self scintilla whitespaceVisibility ~~ #invisible!
hasFormattingMarks: aBoolean
^self scintilla whitespaceVisibility: (aBoolean ifTrue: [#visibleAlways] ifFalse: [#invisible])!
hasIndentationGuides
^self scintilla hasIndentationGuides!
hasIndentationGuides: aBoolean
^self scintilla hasIndentationGuides: aBoolean!
hasLineNumbers
^self scintilla hasLineNumbers!
hasLineNumbers: aBoolean
^self scintilla hasLineNumbers: aBoolean!
hasWordWrap
^self scintilla wordWrap!
hasWordWrap: aBoolean
^self scintilla wordWrap: aBoolean!
initialize
super initialize.
viewOptions := 0.!
isAutoCompleteEnabled
^false!
isAutoCompleteEnabled: aBoolean
"Currently ignored as auto-completion is not implemented yet"
!
isAutoCompletionSingleMatchChosen
^self scintilla isAutoCompletionSingleMatchChosen!
isAutoCompletionSingleMatchChosen: aBoolean
^self scintilla isAutoCompletionSingleMatchChosen: aBoolean!
isAutoCompletionTruncating
^self scintilla isAutoCompletionTruncating!
isAutoCompletionTruncating: aBoolean
^self scintilla isAutoCompletionTruncating: aBoolean!
isFoldingEnabled
^self scintilla isFoldingEnabled!
isFoldingEnabled: aBoolean
self scintilla isFoldingEnabled: aBoolean!
isRememberingPlacement
^viewOptions allMask: RememberPlacementMask!
isRememberingPlacement: aBoolean
viewOptions := viewOptions mask: RememberPlacementMask set: aBoolean!
parseXml
^self parseXml: self getDocumentData validate: false!
parseXml: aString validate: aBoolean
| dom |
dom := IXMLDOMDocument new.
"Preserve whitespace in case there are any mixed text/element nodes. This allows the
formatter to preserve the text of these nodes exactly."
dom
preserveWhiteSpace: false;
validateOnParse: aBoolean;
resolveExternals: aBoolean.
(dom loadXML: aString asString)
ifFalse: [dom parseErrorClass signal: 'Error in XML' with: dom parseError].
^dom!
queryCommand: query
"Private - Enters details about a potential command for the receiver into
the <CommandQuery>, query"
| cmd |
cmd := query commandSymbol.
cmd == #viewToolbar
ifTrue:
[query
isEnabled: true;
isChecked: self toolbar isWindowVisible.
^true].
cmd == #viewStatusBar
ifTrue:
[query
isEnabled: true;
isChecked: self statusBar isWindowVisible.
^true].
^super queryCommand: query!
reformatXml
| dom formatter reformatted |
dom := [self parseXml] on: DOMParseError
do:
[:ex |
statusModel value: ex tag.
nil].
dom ifNil: [^self].
formatter := XmlFormatter new.
reformatted := formatter format: dom.
"
DiffBrowser compare: originalText with: reformatted.
"
"Replace the text using the Scintilla target feature (this is like an invisible selection).
If we just set the text, then it would not be undoable."
(self scintilla)
targetAll;
replaceTarget: reformatted!
restoreBooleanOptions: anArrayOfPairs
| values |
values := self userSettingsKey subValues.
anArrayOfPairs
do: [:each | values at: each first ifPresent: [:bool | self perform: each third with: bool asBoolean]]!
restoreTabWidth
self userSettingsKey subValues at: 'TabWidth' ifPresent: [:width | self tabWidth: width]!
restoreTextStyles
self userSettingsKey at: 'TextStyles'
ifPresent:
[:key |
| styles |
styles := Object fromRegKey: key.
self scintilla textStyles: styles]!
restoreUserSettings
self restoreViewOptions.
self restoreBooleanOptions: self booleanOptions!
restoreViewOptions
self restoreBooleanOptions: self booleanViewOptions.
self restoreTextStyles.
self restoreTabWidth!
saveBooleanOptions: anArrayOfPairs
| values |
values := self userSettingsKey subValues.
anArrayOfPairs do: [:each | values at: each first put: (self perform: each second) asParameter]!
saveFontSetting
self userSettingsKey valueAt: 'Font' put: self view actualFont logFont!
saveOptions
self saveViewOptions.
self saveBooleanOptions: self booleanOptions!
saveTabWidth
self userSettingsKey valueAt: 'TabWidth' put: self tabWidth!
saveTextStyles
self scintilla textStyles asArray storeUnderRegKey: self userSettingsKey as: 'TextStyles'!
saveUserSettings
"Private - Save the users configuration to the registry."
self
saveOptions;
saveWindowPlacement!
saveViewOptions
self userSettingsKey valueAt: 'SavePlacement' put: self isRememberingPlacement asParameter.
self saveTabWidth.
self saveBooleanOptions: self booleanViewOptions.
self saveTextStyles!
saveWindowPlacement
self isRememberingPlacement
ifTrue:
[| placement |
placement := self view placement.
placement showCmd: (self view isMaximized ifTrue: [SW_SHOWMAXIMIZED] ifFalse: [SW_SHOW]).
self userSettingsKey valueAt: 'placement' put: placement]
ifFalse: [self userSettingsKey removeSubValue: 'placement' ifAbsent: []]!
scintilla
^documentPresenter view!
statusBar
^self view viewNamed: 'statusbar'!
tabWidth
^self scintilla tabWidth!
tabWidth: anInteger
self scintilla tabWidth: anInteger!
toolbar
^self view viewNamed: 'toolbar'!
userSettingsKey
"Private - Answer the <RegKey> under which user settings are stored for the RulesSetBrowser
itself."
^self class userSettingsKey!
validateXml
statusModel value: (
[self basicValidateXml.
nil] on: DOMParseError do: [:ex | ex tag])!
viewStatusBar
| statusBar |
statusBar := self statusBar.
statusBar isWindowVisible ifTrue: [statusBar hide] ifFalse: [statusBar show]!
viewToolbar
| toolbar |
toolbar := self toolbar.
toolbar isWindowVisible ifTrue: [toolbar hide] ifFalse: [toolbar show]! !
!XmlPad categoriesFor: #about!commands!public! !
!XmlPad categoriesFor: #basicValidateXml!helpers!private! !
!XmlPad categoriesFor: #booleanOptions!helpers!private! !
!XmlPad categoriesFor: #booleanViewOptions!helpers!private! !
!XmlPad categoriesFor: #canSave!public!testing! !
!XmlPad categoriesFor: #hasFormattingMarks!public!testing! !
!XmlPad categoriesFor: #hasFormattingMarks:!accessing!public! !
!XmlPad categoriesFor: #hasIndentationGuides!public!testing! !
!XmlPad categoriesFor: #hasIndentationGuides:!accessing!public! !
!XmlPad categoriesFor: #hasLineNumbers!public!testing! !
!XmlPad categoriesFor: #hasLineNumbers:!accessing!public! !
!XmlPad categoriesFor: #hasWordWrap!public!testing! !
!XmlPad categoriesFor: #hasWordWrap:!accessing!public! !
!XmlPad categoriesFor: #initialize!initializing!public! !
!XmlPad categoriesFor: #isAutoCompleteEnabled!public! !
!XmlPad categoriesFor: #isAutoCompleteEnabled:!public! !
!XmlPad categoriesFor: #isAutoCompletionSingleMatchChosen!public!testing! !
!XmlPad categoriesFor: #isAutoCompletionSingleMatchChosen:!public! !
!XmlPad categoriesFor: #isAutoCompletionTruncating!public!testing! !
!XmlPad categoriesFor: #isAutoCompletionTruncating:!public! !
!XmlPad categoriesFor: #isFoldingEnabled!public!testing! !
!XmlPad categoriesFor: #isFoldingEnabled:!accessing!public! !
!XmlPad categoriesFor: #isRememberingPlacement!commands!public! !
!XmlPad categoriesFor: #isRememberingPlacement:!public!testing! !
!XmlPad categoriesFor: #parseXml!helpers!private! !
!XmlPad categoriesFor: #parseXml:validate:!helpers!private! !
!XmlPad categoriesFor: #queryCommand:!commands!private! !
!XmlPad categoriesFor: #reformatXml!commands!public! !
!XmlPad categoriesFor: #restoreBooleanOptions:!operations!private! !
!XmlPad categoriesFor: #restoreTabWidth!operations!private! !
!XmlPad categoriesFor: #restoreTextStyles!helpers!private! !
!XmlPad categoriesFor: #restoreUserSettings!helpers!private! !
!XmlPad categoriesFor: #restoreViewOptions!operations!private! !
!XmlPad categoriesFor: #saveBooleanOptions:!helpers!private! !
!XmlPad categoriesFor: #saveFontSetting!helpers!private! !
!XmlPad categoriesFor: #saveOptions!helpers!private! !
!XmlPad categoriesFor: #saveTabWidth!helpers!private! !
!XmlPad categoriesFor: #saveTextStyles!helpers!private! !
!XmlPad categoriesFor: #saveUserSettings!helpers!private! !
!XmlPad categoriesFor: #saveViewOptions!helpers!private! !
!XmlPad categoriesFor: #saveWindowPlacement!helpers!private! !
!XmlPad categoriesFor: #scintilla!accessing!private! !
!XmlPad categoriesFor: #statusBar!accessing!private! !
!XmlPad categoriesFor: #tabWidth!accessing!private! !
!XmlPad categoriesFor: #tabWidth:!accessing!private! !
!XmlPad categoriesFor: #toolbar!accessing!private! !
!XmlPad categoriesFor: #userSettingsKey!accessing!private! !
!XmlPad categoriesFor: #validateXml!commands!public! !
!XmlPad categoriesFor: #viewStatusBar!commands!private! !
!XmlPad categoriesFor: #viewToolbar!commands!private! !
!XmlPad class methodsFor!
about
"Private - Pop up a little helpful info. about this sample program."
(MessageBox new)
caption: ('About Dolphin <1d>' expandMacrosWith: self);
icon: self icon;
text: (self aboutTemplate expandMacrosWith: VMLibrary default fullVersion);
open!
aboutTemplate
"Private - Answer the text to be used in the receiver's about box"
^'XmlPad Sample<n><1s><n>
XmlPad is a simple text-based XML editor. It is intended to demonstrate the DocumentShell hierarchy
of Dolphin''s application framework, the Scintilla view component, and the use of the MSXML.
It is also useful for editing Xml!!<n>
DISCLAIMER: This software is freely provided purely as an educational sample and as such it
is provided "as is", WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.'!
defaultFileExtension
"Answer a default extension that will be used for files saved from
the receiver"
^'xml'!
explicitDependencies
AdvancedFindDialog
!
fileTypes
"Answer an Array of file types that can be associated with this class of document."
^#(#('XML Files (*.xml)' '*.xml') #('All Files (*.*)' '*.*'))!
icon
"Answers an Icon that can be used to represent this class and which is displayed in the
caption of the dialog box."
^Icon fromId: 'XML.ICO'!
initialize
"
self initialize
"
self addClassConstant: 'RememberPlacementMask' value: 1!
installKeyName
"Private - Answer the name of the base installation registry key."
^'Software\Object Arts'!
resource_Default_view
"Answer the literal data from which the 'Default view' resource can be reconstituted.
DO NOT EDIT OR RECATEGORIZE THIS METHOD.
If you wish to modify this resource evaluate:
ViewComposer openOn: (ResourceIdentifier class: self selector: #resource_Default_view)
"
^#(#'!!STL' 4 788558 10 ##(Smalltalk.STBViewProxy) ##(Smalltalk.ShellView) 34 27 nil nil 8 #(13565952 65536) 416 nil 327686 ##(Smalltalk.Color) #face3d nil 549 nil nil nil 416 788230 ##(Smalltalk.BorderLayout) 1 1 410 ##(Smalltalk.Toolbar) 34 25 nil 416 34 2 8 1140853508 131137 528 nil 466 #default nil 519 nil 263174 ##(Smalltalk.Font) nil true 459014 ##(Smalltalk.LOGFONT) 8 #[243 255 255 255 0 0 0 0 0 0 0 0 0 0 0 0 144 1 0 0 0 0 0 0 3 2 1 34 65 114 105 97 108 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] 328198 ##(Smalltalk.Point) 193 193 nil 528 592 8 1867527152 170 192 8 #() 170 192 34 18 36585 1246790 1 ##(Smalltalk.ToolbarSystemButton) 528 1 1180998 4 ##(Smalltalk.CommandDescription) #copySelection 8 'Copy' 1 1 nil 36585 1 3 36581 802 528 1 834 #find 8 'Find' 1 1 nil 36581 1 25 36577 802 528 1 834 #fileOpen 8 'Open' 1 1 nil 36577 1 15 36591 802 528 1 834 #undo 8 'Undo' 1 1 nil 36591 1 7 36587 802 528 1 834 #pasteClipboard 8 'Paste' 1 1 nil 36587 1 5 36583 802 528 1 834 #cutSelection 8 'Cut' 1 1 nil 36583 1 1 36579 802 528 1 834 #fileSave 8 'Save' 1 1 nil 36579 1 17 36575 802 528 1 834 #fileNew 8 'New' 1 1 nil 36575 1 13 36589 802 528 1 834 #clearSelection 8 'Delete' 1 1 nil 36589 1 11 34 11 1168 928 1120 1049158 1 ##(Smalltalk.ToolbarSeparator) 528 1 880 1282 528 1 1072 816 1024 1216 976 nil nil 1 nil 690 33 33 690 45 45 nil 656198 1 ##(Smalltalk.FlowLayout) 1 1 1 983302 ##(Smalltalk.MessageSequence) 138 144 34 1 721670 ##(Smalltalk.MessageSend) #createAt:extent: 34 2 690 1 1 690 2369 51 528 983302 ##(Smalltalk.WINDOWPLACEMENT) 8 #[44 0 0 0 0 0 0 0 1 0 0 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 0 0 0 0 0 0 0 0 160 4 0 0 25 0 0 0] 8 #() 690 193 193 nil 27 410 ##(Smalltalk.StatusBar) 34 18 nil 416 34 2 8 1140850948 1 1616 nil 592 nil 7 nil 610 nil true 642 8 #[243 255 255 255 0 0 0 0 0 0 0 0 0 0 0 0 144 1 0 0 0 0 0 0 3 2 1 34 65 114 105 97 108 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] 690 193 193 nil 1616 nil 8 1867315760 170 192 34 2 853766 ##(Smalltalk.StatusBarItem) 1 -1 1616 nil 459270 ##(Smalltalk.Message) #displayString 8 #() 787814 3 ##(Smalltalk.BlockClosure) 0 nil 918822 ##(Smalltalk.CompiledMethod) 3 3 1792 #defaultGetImageBlock 462740483 8 #[31 105 226 0 159 106] #icon #imageIndex 1888 7 257 nil nil 8 'status' 34 1 1808 1115142 ##(Smalltalk.StatusBarNullItem) 513 1 1616 nil nil 1394 138 144 34 1 1458 #createAt:extent: 34 2 690 1 1491 690 2369 45 1616 1538 8 #[44 0 0 0 0 0 0 0 1 0 0 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 0 0 0 0 233 2 0 0 160 4 0 0 255 2 0 0] 8 #() 1600 nil 27 nil nil 410 ##(Smalltalk.ScintillaView) 34 50 nil 416 34 2 8 1174475012 262145 2176 721990 2 ##(Smalltalk.ValueHolder) nil false 1310726 ##(Smalltalk.EqualitySearchPolicy) nil 592 nil 23 nil nil nil 2176 nil 8 1533228637 852486 ##(Smalltalk.NullConverter) nil nil 9 nil 170 192 34 60 #identifierStart 1182790 1 ##(Smalltalk.ScintillaTextStyle) 27 466 #purple nil 3 nil nil nil nil #identifierStart nil 1401 nil #sgmlDoubleString 2386 49 466 #maroon 196934 1 ##(Smalltalk.RGB) 33546207 1 nil nil nil nil #sgmlDoubleString nil nil nil #entity 2386 21 2416 nil 1 nil nil nil nil #entity nil nil nil #comment 2386 19 466 #olive nil 1 nil nil nil nil #comment nil nil nil #singleString 2386 15 2466 16646399 nil 1 nil nil nil nil #singleString nil nil nil #sgmlTag 2386 43 466 #navy 2466 33546207 1 nil nil nil nil #sgmlTag nil nil nil #sgmlError 2386 53 2448 2466 13422079 1 nil nil nil nil #sgmlError nil nil nil #sgmlSpecial 2386 55 2466 33475687 2466 33546207 1 nil nil nil nil #sgmlSpecial nil nil nil #indentGuide 2386 75 nil nil 1 nil nil nil nil #indentGuide nil nil nil #callTip 2386 77 466 #gray 466 #white 1 nil nil nil nil #callTip nil nil nil #otherInsideTag 2386 17 2416 nil 1 nil nil nil nil #otherInsideTag nil nil nil #lineNumber 2386 67 nil nil 1 nil nil nil nil #lineNumber nil nil nil #unknownAttribute 2386 9 466 #teal nil 1 nil nil nil nil #unknownAttribute nil nil nil #sgmlBlock 2386 63 2466 13369345 2466 29464985 1 nil nil nil nil #sgmlBlock nil nil nil #styleTagEnd 2386 23 2592 nil 1 nil nil nil nil #styleTagEnd nil nil nil #unquotedValue 2386 39 2466 12648641 nil 1 nil nil nil nil #unquotedValue nil nil nil #CDATA 2386 35 2448 2466 31580671 129 nil nil nil nil #CDATA nil nil nil #sgmlFirstParam 2386 47 2466 52225 2466 33546207 1 nil nil nil nil #sgmlFirstParam nil nil nil #sgmlComment 2386 59 2528 2466 33546207 1 nil nil nil nil #sgmlComment nil nil nil #identifierEnd 2386 25 2416 nil 3 nil nil nil nil #identifierEnd nil 1401 nil #sgmlSingleString 2386 51 2466 26419 2466 33546207 1 nil nil nil nil #sgmlSingleString nil nil nil #question 2386 37 2448 nil 1 nil nil nil nil #question nil nil nil #number 2386 11 2466 16711169 nil 1 nil nil nil nil #number nil nil nil #normal 2386 1 nil nil 1 nil nil nil nil #normal nil nil nil #unknownTag 2386 5 2592 nil 1 nil nil nil nil #unknownTag nil nil nil #sgmlCommand 2386 45 2592 2466 33546207 3 nil nil nil nil #sgmlCommand nil 1401 nil #doubleString 2386 13 2466 16646399 nil 1 nil nil nil nil #doubleString nil nil nil #attribute 2386 7 2816 nil 1 nil nil nil nil #attribute nil nil nil #tag 2386 3 2592 nil 1 nil nil nil nil #tag nil nil nil #sgmlEntity 2386 57 2466 6710887 2466 33546207 1 nil nil nil nil #sgmlEntity nil nil nil nil 1245510 1 ##(Smalltalk.NullScintillaStyler) #normal 170 192 34 14 #folderSub 1641542 2 ##(Smalltalk.ScintillaMarkerDefinition) 59 11 2752 466 #black 2176 #folderSub nil nil nil nil nil nil #folderOpenMid 3394 53 11 2752 3424 2176 #folderOpenMid nil nil nil nil nil nil #folderOpen 3394 63 15 2752 3424 2176 #folderOpen nil nil nil nil nil nil #folderEnd 3394 51 11 2752 3424 2176 #folderEnd nil nil nil nil nil nil #folderMidTail 3394 55 11 2752 3424 2176 #folderMidTail nil nil nil nil nil nil #folder 3394 61 17 2752 3424 2176 #folder nil nil nil nil nil nil #folderTail 3394 57 11 2752 3424 2176 #folderTail nil nil nil nil nil nil 138 ##(Smalltalk.IdentitySet) 752 nil 170 176 752 123903 nil nil nil nil 466 #silver nil nil 65 nil nil nil 8 '' 5 170 192 34 4 #container 170 192 34 60 #identifierStart 2400 #sgmlDoubleString 2432 #entity 2496 #comment 2512 #singleString 2544 #sgmlTag 2576 #sgmlError 2624 #sgmlSpecial 2656 #indentGuide 2704 #callTip 2720 #otherInsideTag 2768 #lineNumber 2784 #unknownAttribute 2800 #number 3120 #styleTagEnd 2880 #CDATA 2928 #sgmlFirstParam 2960 #sgmlComment 3008 #identifierEnd 3040 #sgmlBlock 2832 #sgmlSingleString 3056 #question 3104 #unquotedValue 2896 #normal 3152 #unknownTag 3168 #sgmlCommand 3184 #doubleString 3216 #attribute 3248 #tag 3264 #sgmlEntity 3280 #xml 2352 nil nil #plusMinus 33 130003 nil 170 192 34 6 8 'indicator0' 1510470 3 ##(Smalltalk.ScintillaIndicatorStyle) 1 2176 466 #commonGreen 3 false nil nil nil nil nil nil nil 8 'indicator1' 3714 3 2176 466 #blue 5 false nil nil nil nil nil nil nil 8 'indicator2' 3714 5 2176 466 #red 1 false nil nil nil nil nil nil nil nil nil 170 192 34 6 #Warning 2386 1027 466 #darkGoldenrod 466 #ivory 1 nil nil nil nil #Warning nil nil nil #Notification 2386 1029 nil 466 #gainsboro 1 nil nil nil nil #Notification nil nil nil #Error 2386 1031 466 #firebrick 466 #floralWhite 1 nil nil nil nil #Error nil nil nil nil 1394 138 144 34 10 1458 #createAt:extent: 34 2 690 1 51 690 2369 1441 2176 1458 #textLimit: 8 #(1073741823) 2176 1458 #caretPeriod: 8 #(530) 2176 1458 #wordWrap: 8 #(true) 2176 1458 #margins: 34 1 34 3 985158 3 ##(Smalltalk.ScintillaMargin) 1 2176 1 3 nil nil nil nil 4274 3 2176 33 nil nil 67108863 nil nil 4274 5 2176 33 nil 3 -67108863 nil nil 2176 1458 #canHScroll: 8 #(false) 2176 1458 #targetRange: 34 1 525062 ##(Smalltalk.Interval) 1 -1 3 2176 1458 #maxCompletionListHeight: 8 #(9) 2176 1458 #edgeColumn: 8 #(1) 2176 1458 #setLexerLanguage: 8 #(#xml) 2176 1538 8 #[44 0 0 0 0 0 0 0 1 0 0 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 0 0 0 0 25 0 0 0 160 4 0 0 233 2 0 0] 8 #() 1600 nil 29 170 192 34 6 528 8 'toolbar' 2176 8 'document' 1616 8 'statusbar' nil 461638 4 ##(Smalltalk.MenuBar) nil true 34 4 265030 4 ##(Smalltalk.Menu) nil true 34 6 984134 2 ##(Smalltalk.CommandMenuItem) 1 834 #fileNew 8 '&New' 9373 1 nil nil nil 4754 1 834 #fileOpen 8 '&Open...' 9375 1 nil nil nil 4754 1 834 #fileSave 8 '&Save' 9383 1 nil nil nil 4754 1 834 #fileSaveAs 8 'Save &As...' 1 1 nil nil nil 983366 1 ##(Smalltalk.DividerMenuItem) 4097 4754 1 834 #exit 8 'E&xit' 1025 1 nil nil nil 8 '&File' nil 1 nil nil 36603 nil nil 4706 nil true 34 15 4754 1 834 #undo 8 '&Undo' 9397 1 nil nil nil 4754 1 834 #redo 8 '&Redo' 9395 1 nil nil nil 4962 4097 4754 1 834 #cutSelection 8 'Cu&t' 9393 1 nil nil nil 4754 1 834 #copySelection 8 '&Copy' 9351 1 nil nil nil 4754 1 834 #pasteClipboard 8 '&Paste' 9389 1 nil nil nil 4754 1 834 #clearSelection 8 'Cle&ar' 1025 1 nil nil nil 4754 1 834 #selectAll 8 'Select All' 9347 1 nil nil nil 4962 4097 4754 1 834 #reformatXml 8 'Refor&mat' 1 1 nil nil nil 4754 1 834 #validateXml 8 '&Validate' 1 1 nil nil nil 4962 4097 4754 1 834 #find 8 '&Find...' 9357 1 nil nil nil 4754 1 834 #findNext 8 'Find &Next' 1253 1 nil nil nil 4754 1 834 #findReplace 8 'R&eplace...' 9361 1 nil nil nil 8 '&Edit' nil 1 nil nil 36629 nil nil 4706 nil true 34 7 4754 1 834 #viewToolbar 8 '&Toolbar' 1025 1 nil nil nil 4754 1 834 #viewStatusBar 8 '&Status Bar' 1025 1 nil nil nil 4962 4097 4754 1 834 #foldAll 8 '&Fold All' 1 1 nil nil nil 4754 1 834 #unfoldAll 8 '&Unfold All' 1 1 nil nil nil 4962 4097 4706 nil true 34 1 4754 1 834 #editStyles 8 'Text &Styles' 1 1 nil nil nil 8 '&Options' nil 134217729 nil nil 36641 nil nil 8 '&View' nil 1 nil nil 36643 nil nil 4706 nil true 34 3 4754 1 834 #help 8 '&Help Topics' 1025 1 nil nil nil 4962 4097 4754 1 834 #about 8 '&About' 1 1 nil nil nil 8 '&Help' nil 1 nil nil 36649 nil nil 8 '' nil 1 nil nil nil nil nil nil nil nil 1 nil nil nil nil 1 nil nil 1394 138 144 34 1 1458 #createAt:extent: 34 2 690 7039 21 690 2401 1653 416 1538 8 #[44 0 0 0 0 0 0 0 0 0 0 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 191 13 0 0 10 0 0 0 111 18 0 0 68 3 0 0] 34 3 528 2176 1616 1600 nil 27 )!
toolName
^self name!
userSettingsKey
"Private - Answer the <RegKey> under which user specific settings should be stored."
^self userSettingsRootKey createKey: self toolName!
userSettingsRootKey
^RegKey userRoot createKey: self installKeyName! !
!XmlPad class categoriesFor: #about!enquiries!private! !
!XmlPad class categoriesFor: #aboutTemplate!enquiries!private! !
!XmlPad class categoriesFor: #defaultFileExtension!constants!public! !
!XmlPad class categoriesFor: #explicitDependencies!must not strip!private! !
!XmlPad class categoriesFor: #fileTypes!constants!public! !
!XmlPad class categoriesFor: #icon!constants!public! !
!XmlPad class categoriesFor: #initialize!development!initializing!public! !
!XmlPad class categoriesFor: #installKeyName!accessing!public! !
!XmlPad class categoriesFor: #resource_Default_view!public!resources-views! !
!XmlPad class categoriesFor: #toolName!accessing!public! !
!XmlPad class categoriesFor: #userSettingsKey!accessing!public! !
!XmlPad class categoriesFor: #userSettingsRootKey!accessing!public! !
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2000-2015 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
/* Copyright (c) 1998, 1999 Apple Computer, Inc. All Rights Reserved */
/* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
/*
* Copyright (c) 1982, 1986, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)protosw.h 8.1 (Berkeley) 6/2/93
* $FreeBSD: src/sys/sys/protosw.h,v 1.28.2.2 2001/07/03 11:02:01 ume Exp $
*/
#ifndef _SYS_PROTOSW_H_
#define _SYS_PROTOSW_H_
#include <sys/appleapiopts.h>
#include <sys/cdefs.h>
/* XXX: this will go away */
#define PR_SLOWHZ 2 /* 2 slow timeouts per second */
/*
* The arguments to the ctlinput routine are
* (*protosw[].pr_ctlinput)(cmd, sa, arg);
* where cmd is one of the commands below, sa is a pointer to a sockaddr,
* and arg is a `void *' argument used within a protocol family.
*/
#define PRC_IFDOWN 0 /* interface transition */
#define PRC_ROUTEDEAD 1 /* select new route if possible ??? */
#define PRC_IFUP 2 /* interface has come back up */
#define PRC_QUENCH2 3 /* DEC congestion bit says slow down */
#define PRC_QUENCH 4 /* some one said to slow down */
#define PRC_MSGSIZE 5 /* message size forced drop */
#define PRC_HOSTDEAD 6 /* host appears to be down */
#define PRC_HOSTUNREACH 7 /* deprecated (use PRC_UNREACH_HOST) */
#define PRC_UNREACH_NET 8 /* no route to network */
#define PRC_UNREACH_HOST 9 /* no route to host */
#define PRC_UNREACH_PROTOCOL 10 /* dst says bad protocol */
#define PRC_UNREACH_PORT 11 /* bad port # */
/* was PRC_UNREACH_NEEDFRAG 12 (use PRC_MSGSIZE) */
#define PRC_UNREACH_SRCFAIL 13 /* source route failed */
#define PRC_REDIRECT_NET 14 /* net routing redirect */
#define PRC_REDIRECT_HOST 15 /* host routing redirect */
#define PRC_REDIRECT_TOSNET 16 /* redirect for type of service & net */
#define PRC_REDIRECT_TOSHOST 17 /* redirect for tos & host */
#define PRC_TIMXCEED_INTRANS 18 /* packet lifetime expired in transit */
#define PRC_TIMXCEED_REASS 19 /* lifetime expired on reass q */
#define PRC_PARAMPROB 20 /* header incorrect */
#define PRC_UNREACH_ADMIN_PROHIB 21 /* packet administrativly prohibited */
#define PRC_NCMDS 22
#define PRC_IS_REDIRECT(cmd) \
((cmd) >= PRC_REDIRECT_NET && (cmd) <= PRC_REDIRECT_TOSHOST)
#ifdef BSD_KERNEL_PRIVATE
#include <sys/eventhandler.h>
#endif
#ifdef KERNEL_PRIVATE
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/queue.h>
#include <kern/locks.h>
/* Forward declare these structures referenced from prototypes below. */
struct mbuf;
struct proc;
struct sockaddr;
struct socket;
struct sockopt;
struct socket_filter;
struct uio;
struct ifnet;
#ifdef XNU_KERNEL_PRIVATE
struct domain_old;
#endif /* XNU_KERNEL_PRIVATE */
#pragma pack(4)
#ifdef XNU_KERNEL_PRIVATE
/*
* Legacy protocol switch table.
*
* NOTE: Do not modify this structure, as there are modules outside of xnu
* which rely on the size and layout for binary compatibility. This structure
* is simply used by the exported net_{add,del}_proto_old, pffindproto_old
* routines, and by the domain_old structure. Internally, protocol switch
* tables are stored in the private variant of protosw defined down below.
*/
struct protosw_old {
#else
struct protosw {
#endif /* !XNU_KERNEL_PRIVATE */
short pr_type; /* socket type used for */
struct domain *pr_domain; /* domain protocol a member of */
short pr_protocol; /* protocol number */
unsigned int pr_flags; /* see below */
/*
* protocol-protocol hooks
*/
void (*pr_input) /* input to protocol (from below) */
(struct mbuf *, int len);
int (*pr_output) /* output to protocol (from above) */
(struct mbuf *m, struct socket *so);
void (*pr_ctlinput) /* control input (from below) */
(int, struct sockaddr *, void *, struct ifnet *);
int (*pr_ctloutput) /* control output (from above) */
(struct socket *, struct sockopt *);
/*
* user-protocol hook
*/
void *pr_ousrreq;
/*
* utility hooks
*/
void (*pr_init)(void); /* initialization hook */
void (*pr_unused)(void); /* placeholder - fasttimo is removed */
void (*pr_unused2)(void); /* placeholder - slowtimo is removed */
void (*pr_drain)(void); /* flush any excess space possible */
int (*pr_sysctl) /* sysctl for protocol */
(int *, u_int, void *, size_t *, void *, size_t);
#ifdef XNU_KERNEL_PRIVATE
struct pr_usrreqs_old *pr_usrreqs; /* supersedes pr_usrreq() */
#else
struct pr_usrreqs *pr_usrreqs; /* supersedes pr_usrreq() */
#endif /* !XNU_KERNEL_PRIVATE */
int (*pr_lock) /* lock function for protocol */
(struct socket *so, int refcnt, void *debug);
int (*pr_unlock) /* unlock for protocol */
(struct socket *so, int refcnt, void *debug);
lck_mtx_t *(*pr_getlock) /* retrieve protocol lock */
(struct socket *so, int flags);
/*
* Implant hooks
*/
TAILQ_HEAD(, socket_filter) pr_filter_head;
#ifdef XNU_KERNEL_PRIVATE
struct protosw_old *pr_next; /* chain for domain */
#else
struct protosw *pr_next; /* chain for domain */
#endif /* !XNU_KERNEL_PRIVATE */
u_int32_t reserved[1]; /* padding for future use */
};
#pragma pack()
#ifdef XNU_KERNEL_PRIVATE
/*
* Protocol switch table.
*
* Each protocol has a handle initializing one of these structures,
* which is used for protocol-protocol and system-protocol communication.
*
* A protocol is called through the pr_init entry before any other.
* The system will call the pr_drain entry if it is low on space and this
* should throw away any non-critical data.
*
* Protocols pass data between themselves as chains of mbufs using
* the pr_input and pr_output hooks. Pr_input passes data up (towards
* the users) and pr_output passes it down (towards the interfaces); control
* information passes up and down on pr_ctlinput and pr_ctloutput.
* The protocol is responsible for the space occupied by any the
* arguments to these entries and must dispose it.
*
* The userreq routine interfaces protocols to the system and is
* described below.
*
* After a protocol is attached, its pr_domain will be set to the domain
* which the protocol belongs to, and its pr_protosw will be set to the
* address of the protosw instance. The latter is useful for finding
* the real/original protosw instance, in the event so_proto is altered
* to point to an alternative/derivative protosw. E.g. the list of
* socket filters is only applicable on the original protosw instance.
*
* Internal, private and extendable representation of protosw.
*/
struct protosw {
TAILQ_ENTRY(protosw) pr_entry; /* chain for domain */
struct domain *pr_domain; /* domain protocol a member of */
struct protosw *pr_protosw; /* pointer to self */
u_int16_t pr_type; /* socket type used for */
u_int16_t pr_protocol; /* protocol number */
u_int32_t pr_flags; /* see below */
/*
* protocol-protocol hooks
*/
void (*pr_input) /* input to protocol (from below) */
(struct mbuf *, int len);
int (*pr_output) /* output to protocol (from above) */
(struct mbuf *m, struct socket *so);
void (*pr_ctlinput) /* control input (from below) */
(int, struct sockaddr *, void *, struct ifnet *);
int (*pr_ctloutput) /* control output (from above) */
(struct socket *, struct sockopt *);
/*
* user-protocol hook
*/
struct pr_usrreqs *pr_usrreqs; /* user request; see list below */
/*
* utility hooks
*/
void (*pr_init) /* initialization hook */
(struct protosw *, struct domain *);
void (*pr_drain)(void); /* flush any excess space possible */
int (*pr_sysctl) /* sysctl for protocol */
(int *, u_int, void *, size_t *, void *, size_t);
int (*pr_lock) /* lock function for protocol */
(struct socket *so, int refcnt, void *debug);
int (*pr_unlock) /* unlock for protocol */
(struct socket *so, int refcnt, void *debug);
lck_mtx_t *(*pr_getlock) /* retrieve protocol lock */
(struct socket *so, int flags);
/*
* misc
*/
TAILQ_HEAD(, socket_filter) pr_filter_head;
struct protosw_old *pr_old;
};
/*
* Values for the flags argument of pr_getlock
*/
#define PR_F_WILLUNLOCK 0x01 /* Will unlock (e.g., msleep) after the pr_getlock call */
#endif /* XNU_KERNEL_PRIVATE */
/*
* Values for pr_flags.
* PR_ADDR requires PR_ATOMIC;
* PR_ADDR and PR_CONNREQUIRED are mutually exclusive.
* PR_IMPLOPCL means that the protocol allows sendto without prior connect,
* and the protocol understands the MSG_EOF flag. The first property is
* is only relevant if PR_CONNREQUIRED is set (otherwise sendto is allowed
* anyhow).
*/
#define PR_ATOMIC 0x01 /* exchange atomic messages only */
#define PR_ADDR 0x02 /* addresses given with messages */
#define PR_CONNREQUIRED 0x04 /* connection required by protocol */
#define PR_WANTRCVD 0x08 /* want PRU_RCVD calls */
#define PR_RIGHTS 0x10 /* passes capabilities */
#define PR_IMPLOPCL 0x20 /* implied open/close */
#define PR_LASTHDR 0x40 /* enforce ipsec policy; last header */
#define PR_PROTOLOCK 0x80 /* protocol takes care of it's own locking */
#define PR_PCBLOCK 0x100 /* protocol supports per pcb locking */
#define PR_DISPOSE 0x200 /* protocol requires late lists disposal */
#ifdef BSD_KERNEL_PRIVATE
#define PR_INITIALIZED 0x400 /* protocol has been initialized */
#define PR_ATTACHED 0x800 /* protocol is attached to a domain */
#define PR_MULTICONN 0x1000 /* supports multiple connect calls */
#define PR_EVCONNINFO 0x2000 /* protocol generates conninfo event */
#define PR_PRECONN_WRITE 0x4000 /* protocol supports preconnect write */
#define PR_DATA_IDEMPOTENT 0x8000 /* protocol supports idempotent data at connectx-time */
#define PR_OLD 0x10000000 /* added via net_add_proto */
/* pseudo-public domain flags */
#define PRF_USERFLAGS \
(PR_ATOMIC|PR_ADDR|PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS| \
PR_IMPLOPCL|PR_LASTHDR|PR_PROTOLOCK|PR_PCBLOCK|PR_DISPOSE)
#endif /* BSD_KERNEL_PRIVATE */
#ifdef BSD_KERNEL_PRIVATE
#ifdef PRCREQUESTS
char *prcrequests[] = {
"IFDOWN", "ROUTEDEAD", "IFUP", "DEC-BIT-QUENCH2",
"QUENCH", "MSGSIZE", "HOSTDEAD", "#7",
"NET-UNREACH", "HOST-UNREACH", "PROTO-UNREACH", "PORT-UNREACH",
"#12", "SRCFAIL-UNREACH", "NET-REDIRECT", "HOST-REDIRECT",
"TOSNET-REDIRECT", "TOSHOST-REDIRECT", "TX-INTRANS", "TX-REASS",
"PARAMPROB", "ADMIN-UNREACH"
};
#endif /* PRCREQUESTS */
/*
* The arguments to ctloutput are:
* (*protosw[].pr_ctloutput)(req, so, level, optname, optval, p);
* req is one of the actions listed below, so is a (struct socket *),
* level is an indication of which protocol layer the option is intended.
* optname is a protocol dependent socket option request,
* optval is a pointer to a mbuf-chain pointer, for value-return results.
* The protocol is responsible for disposal of the mbuf chain *optval
* if supplied,
* the caller is responsible for any space held by *optval, when returned.
* A non-zero return from usrreq gives an
* UNIX error number which should be passed to higher level software.
*/
#define PRCO_GETOPT 0
#define PRCO_SETOPT 1
#define PRCO_NCMDS 2
#ifdef PRCOREQUESTS
char *prcorequests[] = {
"GETOPT", "SETOPT",
};
#endif /* PRCOREQUESTS */
/*
* In earlier BSD network stacks, a single pr_usrreq() function pointer was
* invoked with an operation number indicating what operation was desired.
* We now provide individual function pointers which protocols can implement,
* which offers a number of benefits (such as type checking for arguments).
* These older constants are still present in order to support TCP debugging.
*/
#define PRU_ATTACH 0 /* attach protocol to up */
#define PRU_DETACH 1 /* detach protocol from up */
#define PRU_BIND 2 /* bind socket to address */
#define PRU_LISTEN 3 /* listen for connection */
#define PRU_CONNECT 4 /* establish connection to peer */
#define PRU_ACCEPT 5 /* accept connection from peer */
#define PRU_DISCONNECT 6 /* disconnect from peer */
#define PRU_SHUTDOWN 7 /* won't send any more data */
#define PRU_RCVD 8 /* have taken data; more room now */
#define PRU_SEND 9 /* send this data */
#define PRU_ABORT 10 /* abort (fast DISCONNECT, DETATCH) */
#define PRU_CONTROL 11 /* control operations on protocol */
#define PRU_SENSE 12 /* return status into m */
#define PRU_RCVOOB 13 /* retrieve out of band data */
#define PRU_SENDOOB 14 /* send out of band data */
#define PRU_SOCKADDR 15 /* fetch socket's address */
#define PRU_PEERADDR 16 /* fetch peer's address */
#define PRU_CONNECT2 17 /* connect two sockets */
/* begin for protocols internal use */
#define PRU_FASTTIMO 18 /* 200ms timeout */
#define PRU_SLOWTIMO 19 /* 500ms timeout */
#define PRU_PROTORCV 20 /* receive from below */
#define PRU_PROTOSEND 21 /* send to below */
/* end for protocol's internal use */
#define PRU_SEND_EOF 22 /* send and close */
#define PRU_NREQ 22
#ifdef PRUREQUESTS
char *prurequests[] = {
"ATTACH", "DETACH", "BIND", "LISTEN",
"CONNECT", "ACCEPT", "DISCONNECT", "SHUTDOWN",
"RCVD", "SEND", "ABORT", "CONTROL",
"SENSE", "RCVOOB", "SENDOOB", "SOCKADDR",
"PEERADDR", "CONNECT2", "FASTTIMO", "SLOWTIMO",
"PROTORCV", "PROTOSEND", "SEND_EOF",
};
#endif /* PRUREQUESTS */
#endif /* BSD_KERNEL_PRIVATE */
struct stat;
struct ucred;
struct uio;
struct recv_msg_elem;
#ifdef XNU_KERNEL_PRIVATE
/*
* Legacy user-protocol hooks.
*
* NOTE: Do not modify this structure, as there are modules outside of xnu
* which rely on the size and layout for binary compatibility. This structure
* is simply used by the protosw_old structure. Internally, user-protocol
* hooks use the private variant of pr_usrreqs defined down below.
*/
struct pr_usrreqs_old {
#else
struct pr_usrreqs {
#endif /* !XNU_KERNEL_PRIVATE */
int (*pru_abort)(struct socket *so);
int (*pru_accept)(struct socket *so, struct sockaddr **nam);
int (*pru_attach)(struct socket *so, int proto, struct proc *p);
int (*pru_bind)(struct socket *so, struct sockaddr *nam,
struct proc *p);
int (*pru_connect)(struct socket *so, struct sockaddr *nam,
struct proc *p);
int (*pru_connect2)(struct socket *so1, struct socket *so2);
int (*pru_control)(struct socket *so, u_long cmd, caddr_t data,
struct ifnet *ifp, struct proc *p);
int (*pru_detach)(struct socket *so);
int (*pru_disconnect)(struct socket *so);
int (*pru_listen)(struct socket *so, struct proc *p);
int (*pru_peeraddr)(struct socket *so, struct sockaddr **nam);
int (*pru_rcvd)(struct socket *so, int flags);
int (*pru_rcvoob)(struct socket *so, struct mbuf *m, int flags);
int (*pru_send)(struct socket *so, int flags, struct mbuf *m,
struct sockaddr *addr, struct mbuf *control,
struct proc *p);
int (*pru_sense)(struct socket *so, void *sb, int isstat64);
int (*pru_shutdown)(struct socket *so);
int (*pru_sockaddr)(struct socket *so, struct sockaddr **nam);
int (*pru_sosend)(struct socket *so, struct sockaddr *addr,
struct uio *uio, struct mbuf *top, struct mbuf *control,
int flags);
int (*pru_soreceive)(struct socket *so, struct sockaddr **paddr,
struct uio *uio, struct mbuf **mp0, struct mbuf **controlp,
int *flagsp);
int (*pru_sopoll)(struct socket *so, int events,
struct ucred *cred, void *);
};
#ifdef XNU_KERNEL_PRIVATE
/*
* If the ordering here looks odd, that's because it's alphabetical. These
* should eventually be merged back into struct protosw.
*
* Internal, private and extendable representation of pr_usrreqs.
*
* NOTE: When adding new ones, also add default callbacks in pru_sanitize().
*/
struct pr_usrreqs {
uint32_t pru_flags; /* see PRUF flags below */
int (*pru_abort)(struct socket *);
int (*pru_accept)(struct socket *, struct sockaddr **);
int (*pru_attach)(struct socket *, int proto, struct proc *);
int (*pru_bind)(struct socket *, struct sockaddr *, struct proc *);
int (*pru_connect)(struct socket *, struct sockaddr *,
struct proc *);
int (*pru_connect2)(struct socket *, struct socket *);
int (*pru_connectx)(struct socket *, struct sockaddr *,
struct sockaddr *, struct proc *, uint32_t,
sae_associd_t, sae_connid_t *, uint32_t, void *, uint32_t,
struct uio *, user_ssize_t *);
int (*pru_control)(struct socket *, u_long, caddr_t,
struct ifnet *, struct proc *);
int (*pru_detach)(struct socket *);
int (*pru_disconnect)(struct socket *);
int (*pru_disconnectx)(struct socket *,
sae_associd_t, sae_connid_t);
int (*pru_listen)(struct socket *, struct proc *);
int (*pru_peeraddr)(struct socket *, struct sockaddr **);
int (*pru_rcvd)(struct socket *, int);
int (*pru_rcvoob)(struct socket *, struct mbuf *, int);
int (*pru_send)(struct socket *, int, struct mbuf *,
struct sockaddr *, struct mbuf *, struct proc *);
int (*pru_send_list)(struct socket *, int, struct mbuf *,
struct sockaddr *, struct mbuf *, struct proc *);
#define PRUS_OOB 0x1
#define PRUS_EOF 0x2
#define PRUS_MORETOCOME 0x4
int (*pru_sense)(struct socket *, void *, int);
int (*pru_shutdown)(struct socket *);
int (*pru_sockaddr)(struct socket *, struct sockaddr **);
int (*pru_sopoll)(struct socket *, int, struct ucred *, void *);
int (*pru_soreceive)(struct socket *, struct sockaddr **,
struct uio *, struct mbuf **, struct mbuf **, int *);
int (*pru_soreceive_list)(struct socket *, struct recv_msg_elem *, u_int,
int *);
int (*pru_sosend)(struct socket *, struct sockaddr *,
struct uio *, struct mbuf *, struct mbuf *, int);
int (*pru_sosend_list)(struct socket *, struct uio **, u_int, int);
int (*pru_socheckopt)(struct socket *, struct sockopt *);
int (*pru_preconnect)(struct socket *so);
};
/* Values for pru_flags */
#define PRUF_OLD 0x10000000 /* added via net_add_proto */
#ifdef BSD_KERNEL_PRIVATE
/*
* For faster access than net_uptime(), bypassing the initialization.
*/
extern u_int64_t _net_uptime;
#endif /* BSD_KERNEL_PRIVATE */
#endif /* XNU_KERNEL_PRIVATE */
__BEGIN_DECLS
extern int pru_abort_notsupp(struct socket *so);
extern int pru_accept_notsupp(struct socket *so, struct sockaddr **nam);
extern int pru_attach_notsupp(struct socket *so, int proto, struct proc *p);
extern int pru_bind_notsupp(struct socket *so, struct sockaddr *nam,
struct proc *p);
extern int pru_connect_notsupp(struct socket *so, struct sockaddr *nam,
struct proc *p);
extern int pru_connect2_notsupp(struct socket *so1, struct socket *so2);
#ifdef XNU_KERNEL_PRIVATE
extern int pru_connectx_notsupp(struct socket *, struct sockaddr *,
struct sockaddr *, struct proc *, uint32_t, sae_associd_t,
sae_connid_t *, uint32_t, void *, uint32_t, struct uio *, user_ssize_t *);
extern int pru_disconnectx_notsupp(struct socket *, sae_associd_t,
sae_connid_t);
extern int pru_socheckopt_null(struct socket *, struct sockopt *);
#endif /* XNU_KERNEL_PRIVATE */
extern int pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
struct ifnet *ifp, struct proc *p);
extern int pru_detach_notsupp(struct socket *so);
extern int pru_disconnect_notsupp(struct socket *so);
extern int pru_listen_notsupp(struct socket *so, struct proc *p);
extern int pru_peeraddr_notsupp(struct socket *so, struct sockaddr **nam);
extern int pru_rcvd_notsupp(struct socket *so, int flags);
extern int pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags);
extern int pru_send_notsupp(struct socket *so, int flags, struct mbuf *m,
struct sockaddr *addr, struct mbuf *control, struct proc *p);
extern int pru_send_list_notsupp(struct socket *so, int flags, struct mbuf *m,
struct sockaddr *addr, struct mbuf *control, struct proc *p);
extern int pru_sense_null(struct socket *so, void * sb, int isstat64);
extern int pru_shutdown_notsupp(struct socket *so);
extern int pru_sockaddr_notsupp(struct socket *so, struct sockaddr **nam);
extern int pru_sosend_notsupp(struct socket *so, struct sockaddr *addr,
struct uio *uio, struct mbuf *top, struct mbuf *control, int flags);
extern int pru_sosend_list_notsupp(struct socket *so, struct uio **uio,
u_int, int flags);
extern int pru_soreceive_notsupp(struct socket *so,
struct sockaddr **paddr, struct uio *uio, struct mbuf **mp0,
struct mbuf **controlp, int *flagsp);
extern int pru_soreceive_list_notsupp(struct socket *, struct recv_msg_elem *, u_int,
int *);
extern int pru_sopoll_notsupp(struct socket *so, int events,
struct ucred *cred, void *);
#ifdef XNU_KERNEL_PRIVATE
extern void pru_sanitize(struct pr_usrreqs *);
extern void domaininit(void);
extern void domainfin(void);
extern void pfctlinput(int, struct sockaddr *);
extern void pfctlinput2(int, struct sockaddr *, void *);
extern struct protosw *pffindproto_locked(int, int, int);
extern struct protosw *pffindprotonotype(int, int);
extern struct protosw *pffindtype(int, int);
extern struct protosw_old *pffindproto_old(int, int, int);
extern int net_add_proto(struct protosw *, struct domain *, int);
extern void net_init_proto(struct protosw *, struct domain *);
extern int net_del_proto(int, int, struct domain *);
extern int net_add_proto_old(struct protosw_old *, struct domain_old *);
extern int net_del_proto_old(int, int, struct domain_old *);
extern void net_update_uptime(void);
extern void net_update_uptime_with_time(const struct timeval *);
extern u_int64_t net_uptime(void);
extern void net_uptime2timeval(struct timeval *);
#else
extern int net_add_proto(struct protosw *, struct domain *);
extern int net_del_proto(int, int, struct domain *);
#endif /* XNU_KERNEL_PRIVATE */
extern struct protosw *pffindproto(int family, int protocol, int type);
__END_DECLS
#endif /* KERNEL_PRIVATE */
#endif /* !_SYS_PROTOSW_H_ */
| {
"pile_set_name": "Github"
} |
#define Xgreycirc_width 16
#define Xgreycirc_height 16
static char Xgreycirc_bits[] = {
0xe0, 0x07, 0x18, 0x18, 0x04, 0x20, 0xe2, 0x47, 0xf2, 0x4f, 0xb9, 0x9a,
0x59, 0x9d, 0xb9, 0x9a, 0x59, 0x9d, 0xb9, 0x9a, 0x59, 0x9d, 0xf2, 0x4f,
0xe2, 0x47, 0x04, 0x20, 0x18, 0x18, 0xe0, 0x07};
| {
"pile_set_name": "Github"
} |
{
"pile_set_name": "Github"
} |
|
//--------------------------------------------------------------------------------------------------
// $Id $
//
// ElectronEnergyRegressionEvaluate
//
// Helper Class for applying electron energy regression calculation
//
// Authors: A.Takeda, S.Xie, E. Di Marco
//--------------------------------------------------------------------------------------------------
/// --> NOTE if you want to use this class as standalone without the CMSSW part
/// you need to uncomment the below line and compile normally with scramv1 b
/// Then you need just to load it in your root macro the lib with the correct path, eg:
/// gSystem->Load("/data/benedet/CMSSW_5_2_2/lib/slc5_amd64_gcc462/pluginEGammaEGammaAnalysisTools.so");
//#define STANDALONE // <---- this line
#ifndef ELECTRONENERGYREGRESSIONEVALUATE_H
#define ELECTRONENERGYREGRESSIONEVALUATE_H
#include "TFile.h"
#include "TTree.h"
// For applying regression
#include "CondFormats/EgammaObjects/interface/GBRForest.h"
#ifndef STANDALONE
#include "DataFormats/EgammaCandidates/interface/GsfElectronFwd.h"
#include "EgammaAnalysis/ElectronTools/interface/SuperClusterHelper.h"
//#include "RecoEcal/EgammaCoreTools/interface/EcalClusterLazyTools.h"
#endif
class ElectronEnergyRegressionEvaluate {
public:
ElectronEnergyRegressionEvaluate();
~ElectronEnergyRegressionEvaluate();
enum ElectronEnergyRegressionType {
kNoTrkVar,
kNoTrkVarV1,
kWithTrkVar,
kWithTrkVarV1,
kWithTrkVarV2,
kWithSubCluVar
};
void initialize(std::string weightsFile, ElectronEnergyRegressionEvaluate::ElectronEnergyRegressionType type);
bool isInitialized() const { return fIsInitialized; }
#ifndef STANDALONE
double calculateRegressionEnergy(const reco::GsfElectron *ele,
SuperClusterHelper &mySCHelper,
double rho,
double nvertices,
bool printDebug = false);
double calculateRegressionEnergyUncertainty(const reco::GsfElectron *ele,
SuperClusterHelper &mySCHelper,
double rho,
double nvertices,
bool printDebug = false);
#endif
// Evaluates regression without tracker variables
double regressionValueNoTrkVar(double SCRawEnergy,
double scEta,
double scPhi,
double R9,
double etawidth,
double phiwidth,
double NClusters,
double HoE,
double rho,
double vertices,
double EtaSeed,
double PhiSeed,
double ESeed,
double E3x3Seed,
double E5x5Seed,
double see,
double spp,
double sep,
double EMaxSeed,
double E2ndSeed,
double ETopSeed,
double EBottomSeed,
double ELeftSeed,
double ERightSeed,
double E2x5MaxSeed,
double E2x5TopSeed,
double E2x5BottomSeed,
double E2x5LeftSeed,
double E2x5RightSeed,
double IEtaSeed,
double IPhiSeed,
double EtaCrySeed,
double PhiCrySeed,
double PreShowerOverRaw,
bool printDebug = false);
// Evaluates regression without tracker variables
double regressionUncertaintyNoTrkVar(double SCRawEnergy,
double scEta,
double scPhi,
double R9,
double etawidth,
double phiwidth,
double NClusters,
double HoE,
double rho,
double vertices,
double EtaSeed,
double PhiSeed,
double ESeed,
double E3x3Seed,
double E5x5Seed,
double see,
double spp,
double sep,
double EMaxSeed,
double E2ndSeed,
double ETopSeed,
double EBottomSeed,
double ELeftSeed,
double ERightSeed,
double E2x5MaxSeed,
double E2x5TopSeed,
double E2x5BottomSeed,
double E2x5LeftSeed,
double E2x5RightSeed,
double IEtaSeed,
double IPhiSeed,
double EtaCrySeed,
double PhiCrySeed,
double PreShowerOverRaw,
bool printDebug = false);
// Evaluates regression without tracker variables
double regressionValueNoTrkVarV1(double SCRawEnergy,
double scEta,
double scPhi,
double R9,
double etawidth,
double phiwidth,
double NClusters,
double HoE,
double rho,
double vertices,
double EtaSeed,
double PhiSeed,
double ESeed,
double E3x3Seed,
double E5x5Seed,
double see,
double spp,
double sep,
double EMaxSeed,
double E2ndSeed,
double ETopSeed,
double EBottomSeed,
double ELeftSeed,
double ERightSeed,
double E2x5MaxSeed,
double E2x5TopSeed,
double E2x5BottomSeed,
double E2x5LeftSeed,
double E2x5RightSeed,
double IEtaSeed,
double IPhiSeed,
double EtaCrySeed,
double PhiCrySeed,
double PreShowerOverRaw,
int IsEcalDriven,
bool printDebug = false);
// Evaluates regression without tracker variables
double regressionUncertaintyNoTrkVarV1(double SCRawEnergy,
double scEta,
double scPhi,
double R9,
double etawidth,
double phiwidth,
double NClusters,
double HoE,
double rho,
double vertices,
double EtaSeed,
double PhiSeed,
double ESeed,
double E3x3Seed,
double E5x5Seed,
double see,
double spp,
double sep,
double EMaxSeed,
double E2ndSeed,
double ETopSeed,
double EBottomSeed,
double ELeftSeed,
double ERightSeed,
double E2x5MaxSeed,
double E2x5TopSeed,
double E2x5BottomSeed,
double E2x5LeftSeed,
double E2x5RightSeed,
double IEtaSeed,
double IPhiSeed,
double EtaCrySeed,
double PhiCrySeed,
double PreShowerOverRaw,
int IsEcalDriven,
bool printDebug = false);
// Evaluates regression using tracker variables
// This option is now deprecated. we keep it only
// for backwards compatibility
double regressionValueWithTrkVar(double electronP,
double SCRawEnergy,
double scEta,
double scPhi,
double R9,
double etawidth,
double phiwidth,
double NClusters,
double HoE,
double rho,
double vertices,
double EtaSeed,
double PhiSeed,
double ESeed,
double E3x3Seed,
double E5x5Seed,
double see,
double spp,
double sep,
double EMaxSeed,
double E2ndSeed,
double ETopSeed,
double EBottomSeed,
double ELeftSeed,
double ERightSeed,
double E2x5MaxSeed,
double E2x5TopSeed,
double E2x5BottomSeed,
double E2x5LeftSeed,
double E2x5RightSeed,
double pt,
double GsfTrackPIn,
double fbrem,
double Charge,
double EoP,
double IEtaSeed,
double IPhiSeed,
double EtaCrySeed,
double PhiCrySeed,
double PreShowerOverRaw,
bool printDebug = false);
// Evaluates regression using tracker variables
// This option is now deprecated. we keep it only
// for backwards compatibility
double regressionUncertaintyWithTrkVar(double electronP,
double SCRawEnergy,
double scEta,
double scPhi,
double R9,
double etawidth,
double phiwidth,
double NClusters,
double HoE,
double rho,
double vertices,
double EtaSeed,
double PhiSeed,
double ESeed,
double E3x3Seed,
double E5x5Seed,
double see,
double spp,
double sep,
double EMaxSeed,
double E2ndSeed,
double ETopSeed,
double EBottomSeed,
double ELeftSeed,
double ERightSeed,
double E2x5MaxSeed,
double E2x5TopSeed,
double E2x5BottomSeed,
double E2x5LeftSeed,
double E2x5RightSeed,
double pt,
double GsfTrackPIn,
double fbrem,
double Charge,
double EoP,
double IEtaSeed,
double IPhiSeed,
double EtaCrySeed,
double PhiCrySeed,
double PreShowerOverRaw,
bool printDebug = false);
// Evaluates regression using tracker variables
double regressionValueWithTrkVarV1(double SCRawEnergy,
double scEta,
double scPhi,
double R9,
double etawidth,
double phiwidth,
double NClusters,
double HoE,
double rho,
double vertices,
double EtaSeed,
double PhiSeed,
double ESeed,
double E3x3Seed,
double E5x5Seed,
double see,
double spp,
double sep,
double EMaxSeed,
double E2ndSeed,
double ETopSeed,
double EBottomSeed,
double ELeftSeed,
double ERightSeed,
double E2x5MaxSeed,
double E2x5TopSeed,
double E2x5BottomSeed,
double E2x5LeftSeed,
double E2x5RightSeed,
double IEtaSeed,
double IPhiSeed,
double EtaCrySeed,
double PhiCrySeed,
double PreShowerOverRaw,
int IsEcalDriven,
double GsfTrackPIn,
double fbrem,
double Charge,
double EoP,
double TrackMomentumError,
double EcalEnergyError,
int Classification,
bool printDebug = false);
// Evaluates regression using tracker variables
double regressionUncertaintyWithTrkVarV1(double SCRawEnergy,
double scEta,
double scPhi,
double R9,
double etawidth,
double phiwidth,
double NClusters,
double HoE,
double rho,
double vertices,
double EtaSeed,
double PhiSeed,
double ESeed,
double E3x3Seed,
double E5x5Seed,
double see,
double spp,
double sep,
double EMaxSeed,
double E2ndSeed,
double ETopSeed,
double EBottomSeed,
double ELeftSeed,
double ERightSeed,
double E2x5MaxSeed,
double E2x5TopSeed,
double E2x5BottomSeed,
double E2x5LeftSeed,
double E2x5RightSeed,
double IEtaSeed,
double IPhiSeed,
double EtaCrySeed,
double PhiCrySeed,
double PreShowerOverRaw,
int IsEcalDriven,
double GsfTrackPIn,
double fbrem,
double Charge,
double EoP,
double TrackMomentumError,
double EcalEnergyError,
int Classification,
bool printDebug = false);
double regressionValueWithTrkVarV1(std::vector<double> &inputvars, bool printDebug = false);
double regressionUncertaintyWithTrkVarV1(std::vector<double> &inputvars, bool printDebug = false);
// Evaluates regression using tracker variables
double regressionValueWithTrkVarV2(double SCRawEnergy,
double scEta,
double scPhi,
double R9,
double etawidth,
double phiwidth,
double NClusters,
double HoE,
double rho,
double vertices,
double EtaSeed,
double PhiSeed,
double ESeed,
double E3x3Seed,
double E5x5Seed,
double see,
double spp,
double sep,
double EMaxSeed,
double E2ndSeed,
double ETopSeed,
double EBottomSeed,
double ELeftSeed,
double ERightSeed,
double E2x5MaxSeed,
double E2x5TopSeed,
double E2x5BottomSeed,
double E2x5LeftSeed,
double E2x5RightSeed,
double IEtaSeed,
double IPhiSeed,
double EtaCrySeed,
double PhiCrySeed,
double PreShowerOverRaw,
int IsEcalDriven,
double GsfTrackPIn,
double fbrem,
double Charge,
double EoP,
double TrackMomentumError,
double EcalEnergyError,
int Classification,
double detaIn,
double dphiIn,
double detaCalo,
double dphiCalo,
double GsfTrackChiSqr,
double KFTrackNLayers,
double ElectronEnergyOverPout,
bool printDebug = false);
// Evaluates regression using tracker variables
double regressionUncertaintyWithTrkVarV2(double SCRawEnergy,
double scEta,
double scPhi,
double R9,
double etawidth,
double phiwidth,
double NClusters,
double HoE,
double rho,
double vertices,
double EtaSeed,
double PhiSeed,
double ESeed,
double E3x3Seed,
double E5x5Seed,
double see,
double spp,
double sep,
double EMaxSeed,
double E2ndSeed,
double ETopSeed,
double EBottomSeed,
double ELeftSeed,
double ERightSeed,
double E2x5MaxSeed,
double E2x5TopSeed,
double E2x5BottomSeed,
double E2x5LeftSeed,
double E2x5RightSeed,
double IEtaSeed,
double IPhiSeed,
double EtaCrySeed,
double PhiCrySeed,
double PreShowerOverRaw,
int IsEcalDriven,
double GsfTrackPIn,
double fbrem,
double Charge,
double EoP,
double TrackMomentumError,
double EcalEnergyError,
int Classification,
double detaIn,
double dphiIn,
double detaCalo,
double dphiCalo,
double GsfTrackChiSqr,
double KFTrackNLayers,
double ElectronEnergyOverPout,
bool printDebug = false);
double regressionValueWithTrkVarV2(std::vector<double> &inputvars, bool printDebug = false);
double regressionUncertaintyWithTrkVarV2(std::vector<double> &inputvars, bool printDebug = false);
// Evaluates regression uncertainty with subcluster variables and without track variables
double regressionValueWithSubClusters(double SCRawEnergy,
double scEta,
double scPhi,
double R9,
double etawidth,
double phiwidth,
double NClusters,
double HoE,
double rho,
double vertices,
double EtaSeed,
double PhiSeed,
double ESeed,
double E3x3Seed,
double E5x5Seed,
double see,
double spp,
double sep,
double EMaxSeed,
double E2ndSeed,
double ETopSeed,
double EBottomSeed,
double ELeftSeed,
double ERightSeed,
double E2x5MaxSeed,
double E2x5TopSeed,
double E2x5BottomSeed,
double E2x5LeftSeed,
double E2x5RightSeed,
double IEtaSeed,
double IPhiSeed,
double EtaCrySeed,
double PhiCrySeed,
double PreShowerOverRaw,
double isEcalDriven,
double isEtaGap,
double isPhiGap,
double isDeeGap,
double ESubs,
double ESub1,
double EtaSub1,
double PhiSub1,
double EMaxSub1,
double E3x3Sub1,
double ESub2,
double EtaSub2,
double PhiSub2,
double EMaxSub2,
double E3x3Sub2,
double ESub3,
double EtaSub3,
double PhiSub3,
double EMaxSub3,
double E3x3Sub3,
double NPshwClusters,
double EPshwSubs,
double EPshwSub1,
double EtaPshwSub1,
double PhiPshwSub1,
double EPshwSub2,
double EtaPshwSub2,
double PhiPshwSub2,
double EPshwSub3,
double EtaPshwSub3,
double PhiPshwSub3,
bool isEB,
bool printDebug = false);
// Evaluates regression uncertainty with subcluster variables and without track variables
double regressionUncertaintyWithSubClusters(double SCRawEnergy,
double scEta,
double scPhi,
double R9,
double etawidth,
double phiwidth,
double NClusters,
double HoE,
double rho,
double vertices,
double EtaSeed,
double PhiSeed,
double ESeed,
double E3x3Seed,
double E5x5Seed,
double see,
double spp,
double sep,
double EMaxSeed,
double E2ndSeed,
double ETopSeed,
double EBottomSeed,
double ELeftSeed,
double ERightSeed,
double E2x5MaxSeed,
double E2x5TopSeed,
double E2x5BottomSeed,
double E2x5LeftSeed,
double E2x5RightSeed,
double IEtaSeed,
double IPhiSeed,
double EtaCrySeed,
double PhiCrySeed,
double PreShowerOverRaw,
double isEcalDriven,
double isEtaGap,
double isPhiGap,
double isDeeGap,
double ESubs,
double ESub1,
double EtaSub1,
double PhiSub1,
double EMaxSub1,
double E3x3Sub1,
double ESub2,
double EtaSub2,
double PhiSub2,
double EMaxSub2,
double E3x3Sub2,
double ESub3,
double EtaSub3,
double PhiSub3,
double EMaxSub3,
double E3x3Sub3,
double NPshwClusters,
double EPshwSubs,
double EPshwSub1,
double EtaPshwSub1,
double PhiPshwSub1,
double EPshwSub2,
double EtaPshwSub2,
double PhiPshwSub2,
double EPshwSub3,
double EtaPshwSub3,
double PhiPshwSub3,
bool isEB,
bool printDebug = false);
private:
bool fIsInitialized;
ElectronEnergyRegressionEvaluate::ElectronEnergyRegressionType fVersionType;
GBRForest *forestCorrection_eb; // Pointer to the GBRForest for barrel
GBRForest *forestCorrection_ee; // Pointer to the GBRForest for endcap
GBRForest *forestUncertainty_eb;
GBRForest *forestUncertainty_ee;
};
#endif
| {
"pile_set_name": "Github"
} |
obj.foo = hello
obj.bar = bar
obj.xyz = 44
get abc
obj.abc = abc
obj2 in MyConstructor instance? true
obj3 is an Object? true
44
| {
"pile_set_name": "Github"
} |
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: TeleportAreaLocked
m_Shader: {fileID: 4800000, guid: 787d7485aa6482341a9f55fa37fb84f1, type: 3}
m_ShaderKeywords: RECEIVE_SHADOWS _ALPHAPREMULTIPLY_ON _EMISSION
m_LightmapFlags: 1
m_CustomRenderQueue: 3000
stringTagMap:
RenderType: Transparent
m_SavedProperties:
serializedVersion: 2
m_TexEnvs:
- first:
name: _BumpMap
second:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- first:
name: _DetailAlbedoMap
second:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- first:
name: _DetailMask
second:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- first:
name: _DetailNormalMap
second:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- first:
name: _EmissionMap
second:
m_Texture: {fileID: 2800000, guid: 934c5a234f38a8243a04fbdbc71693ef, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- first:
name: _FalloffTex
second:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- first:
name: _Illum
second:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- first:
name: _MainTex
second:
m_Texture: {fileID: 2800000, guid: f33ccd07f9433f44f8c5430938b168ac, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- first:
name: _MetallicGlossMap
second:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- first:
name: _OcclusionMap
second:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- first:
name: _ParallaxMap
second:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- first:
name: _ShadowTex
second:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- first:
name: _SpecGlossMap
second:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- first:
name: g_tOverrideLightmap
second:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- first:
name: _BumpScale
second: 1
- first:
name: _ColorMask
second: 15
- first:
name: _Cutoff
second: 0.5
- first:
name: _Darken
second: 0.641
- first:
name: _DetailNormalMapScale
second: 1
- first:
name: _DstBlend
second: 10
- first:
name: _Emission
second: 0.01
- first:
name: _EmissionScaleUI
second: 0
- first:
name: _GlossMapScale
second: 1
- first:
name: _Glossiness
second: 0.126
- first:
name: _GlossyReflections
second: 1
- first:
name: _Metallic
second: 0.368
- first:
name: _Mode
second: 3
- first:
name: _OcclusionStrength
second: 1
- first:
name: _Parallax
second: 0.02
- first:
name: _SeeThru
second: 0.358
- first:
name: _SmoothnessTextureChannel
second: 0
- first:
name: _SpecularHighlights
second: 1
- first:
name: _SrcBlend
second: 1
- first:
name: _Stencil
second: 0
- first:
name: _StencilComp
second: 8
- first:
name: _StencilOp
second: 0
- first:
name: _StencilReadMask
second: 255
- first:
name: _StencilWriteMask
second: 255
- first:
name: _UVSec
second: 0
- first:
name: _ZWrite
second: 0
- first:
name: g_bEnableMetallic
second: 0
- first:
name: g_bReceiveShadows
second: 1
- first:
name: g_flReflectanceBias
second: 0
- first:
name: g_flReflectanceMax
second: 1
- first:
name: g_flReflectanceMin
second: 0
- first:
name: g_flReflectanceScale
second: 1
m_Colors:
- first:
name: _Color
second: {r: 0.7867738, g: 0.5544188, b: 0.1388565, a: 0.5}
- first:
name: _EmissionColor
second: {r: 0.7867738, g: 0.5544188, b: 0.1388565, a: 0.5}
- first:
name: _EmissionColorUI
second: {r: 1, g: 1, b: 1, a: 1}
- first:
name: _SpecColor
second: {r: 0.2, g: 0.2, b: 0.2, a: 1}
- first:
name: _Specular
second: {r: 0, g: 0, b: 0, a: 0}
- first:
name: _TintColor
second: {r: 0.7867738, g: 0.5544187, b: 0.13885644, a: 0.45490196}
| {
"pile_set_name": "Github"
} |
<?php
/**
* authSources_SearchUsers.php
*
* ProcessMaker Open Source Edition
* Copyright (C) 2004 - 2008 Colosa Inc.23
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, contact Colosa Inc, 2566 Le Jeune Rd.,
* Coral Gables, FL, 33134, USA, or email [email protected].
*/
global $RBAC;
if ($RBAC->userCanAccess('PM_SETUP_ADVANCE') != 1) {
G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels');
G::header('location: ../login/login');
die();
}
$G_MAIN_MENU = 'processmaker';
$G_SUB_MENU = 'users';
$G_ID_MENU_SELECTED = 'USERS';
$G_ID_SUB_MENU_SELECTED = 'AUTH_SOURCES';
$G_PUBLISH = new Publisher();
$fields = $RBAC->getAuthSource($_GET['sUID']);
if (file_exists(PATH_XMLFORM . 'ldapAdvanced/' . $fields['AUTH_SOURCE_PROVIDER'] . 'Edit.xml')) {
$pluginEnabled = 0;
if ($pluginEnabled == 0) {
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'login/showMessage', '', array('MESSAGE' => G::LoadTranslation('ID_AUTH_SOURCE_FEATURE_MISSING') ));
G::RenderPage('publish', 'blank');
} else {
$c = new Configurations();
$configPage = $c->getConfiguration('additionalTablesList', 'pageSize', '', $_SESSION['USER_LOGGED']);
$Config['pageSize'] = isset($configPage['pageSize']) ? $configPage['pageSize'] : 20;
$oHeadPublisher = headPublisher::getSingleton();
$oHeadPublisher->assign("FORMATS", $c->getFormats());
$oHeadPublisher->assign("CONFIG", $Config);
if (file_exists(PATH_XMLFORM . 'ldapAdvanced/' . $fields['AUTH_SOURCE_PROVIDER'] . 'Flag')) {
$oHeadPublisher = headPublisher::getSingleton();
$oHeadPublisher->assign("Fields", $fields);
$oHeadPublisher->addExtJsScript(PATH_TPL. 'ldapAdvanced/library', false, true);
$oHeadPublisher->addExtJsScript(PATH_TPL. 'ldapAdvanced/ldapAdvancedSearch', false, true);
G::RenderPage('publish', 'extJs');
die();
}
}
}
$G_PUBLISH->AddContent('xmlform', 'xmlform', 'authSources/authSources_SearchUsers', '', array('AUTH_SOURCE_UID' => $_GET['sUID']), '../authSources/authSources_ImportUsers');
G::RenderPage('publish', 'blank');
| {
"pile_set_name": "Github"
} |
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInstanceHandles
* @typechecks static-only
*/
'use strict';
var ReactRootIndex = require("./ReactRootIndex");
var invariant = require("./invariant");
var SEPARATOR = '.';
var SEPARATOR_LENGTH = SEPARATOR.length;
/**
* Maximum depth of traversals before we consider the possibility of a bad ID.
*/
var MAX_TREE_DEPTH = 100;
/**
* Creates a DOM ID prefix to use when mounting React components.
*
* @param {number} index A unique integer
* @return {string} React root ID.
* @internal
*/
function getReactRootIDString(index) {
return SEPARATOR + index.toString(36);
}
/**
* Checks if a character in the supplied ID is a separator or the end.
*
* @param {string} id A React DOM ID.
* @param {number} index Index of the character to check.
* @return {boolean} True if the character is a separator or end of the ID.
* @private
*/
function isBoundary(id, index) {
return id.charAt(index) === SEPARATOR || index === id.length;
}
/**
* Checks if the supplied string is a valid React DOM ID.
*
* @param {string} id A React DOM ID, maybe.
* @return {boolean} True if the string is a valid React DOM ID.
* @private
*/
function isValidID(id) {
return id === '' || (
id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR
);
}
/**
* Checks if the first ID is an ancestor of or equal to the second ID.
*
* @param {string} ancestorID
* @param {string} descendantID
* @return {boolean} True if `ancestorID` is an ancestor of `descendantID`.
* @internal
*/
function isAncestorIDOf(ancestorID, descendantID) {
return (
descendantID.indexOf(ancestorID) === 0 &&
isBoundary(descendantID, ancestorID.length)
);
}
/**
* Gets the parent ID of the supplied React DOM ID, `id`.
*
* @param {string} id ID of a component.
* @return {string} ID of the parent, or an empty string.
* @private
*/
function getParentID(id) {
return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : '';
}
/**
* Gets the next DOM ID on the tree path from the supplied `ancestorID` to the
* supplied `destinationID`. If they are equal, the ID is returned.
*
* @param {string} ancestorID ID of an ancestor node of `destinationID`.
* @param {string} destinationID ID of the destination node.
* @return {string} Next ID on the path from `ancestorID` to `destinationID`.
* @private
*/
function getNextDescendantID(ancestorID, destinationID) {
("production" !== process.env.NODE_ENV ? invariant(
isValidID(ancestorID) && isValidID(destinationID),
'getNextDescendantID(%s, %s): Received an invalid React DOM ID.',
ancestorID,
destinationID
) : invariant(isValidID(ancestorID) && isValidID(destinationID)));
("production" !== process.env.NODE_ENV ? invariant(
isAncestorIDOf(ancestorID, destinationID),
'getNextDescendantID(...): React has made an invalid assumption about ' +
'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.',
ancestorID,
destinationID
) : invariant(isAncestorIDOf(ancestorID, destinationID)));
if (ancestorID === destinationID) {
return ancestorID;
}
// Skip over the ancestor and the immediate separator. Traverse until we hit
// another separator or we reach the end of `destinationID`.
var start = ancestorID.length + SEPARATOR_LENGTH;
var i;
for (i = start; i < destinationID.length; i++) {
if (isBoundary(destinationID, i)) {
break;
}
}
return destinationID.substr(0, i);
}
/**
* Gets the nearest common ancestor ID of two IDs.
*
* Using this ID scheme, the nearest common ancestor ID is the longest common
* prefix of the two IDs that immediately preceded a "marker" in both strings.
*
* @param {string} oneID
* @param {string} twoID
* @return {string} Nearest common ancestor ID, or the empty string if none.
* @private
*/
function getFirstCommonAncestorID(oneID, twoID) {
var minLength = Math.min(oneID.length, twoID.length);
if (minLength === 0) {
return '';
}
var lastCommonMarkerIndex = 0;
// Use `<=` to traverse until the "EOL" of the shorter string.
for (var i = 0; i <= minLength; i++) {
if (isBoundary(oneID, i) && isBoundary(twoID, i)) {
lastCommonMarkerIndex = i;
} else if (oneID.charAt(i) !== twoID.charAt(i)) {
break;
}
}
var longestCommonID = oneID.substr(0, lastCommonMarkerIndex);
("production" !== process.env.NODE_ENV ? invariant(
isValidID(longestCommonID),
'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s',
oneID,
twoID,
longestCommonID
) : invariant(isValidID(longestCommonID)));
return longestCommonID;
}
/**
* Traverses the parent path between two IDs (either up or down). The IDs must
* not be the same, and there must exist a parent path between them. If the
* callback returns `false`, traversal is stopped.
*
* @param {?string} start ID at which to start traversal.
* @param {?string} stop ID at which to end traversal.
* @param {function} cb Callback to invoke each ID with.
* @param {?boolean} skipFirst Whether or not to skip the first node.
* @param {?boolean} skipLast Whether or not to skip the last node.
* @private
*/
function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) {
start = start || '';
stop = stop || '';
("production" !== process.env.NODE_ENV ? invariant(
start !== stop,
'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.',
start
) : invariant(start !== stop));
var traverseUp = isAncestorIDOf(stop, start);
("production" !== process.env.NODE_ENV ? invariant(
traverseUp || isAncestorIDOf(start, stop),
'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' +
'not have a parent path.',
start,
stop
) : invariant(traverseUp || isAncestorIDOf(start, stop)));
// Traverse from `start` to `stop` one depth at a time.
var depth = 0;
var traverse = traverseUp ? getParentID : getNextDescendantID;
for (var id = start; /* until break */; id = traverse(id, stop)) {
var ret;
if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) {
ret = cb(id, traverseUp, arg);
}
if (ret === false || id === stop) {
// Only break //after// visiting `stop`.
break;
}
("production" !== process.env.NODE_ENV ? invariant(
depth++ < MAX_TREE_DEPTH,
'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' +
'traversing the React DOM ID tree. This may be due to malformed IDs: %s',
start, stop
) : invariant(depth++ < MAX_TREE_DEPTH));
}
}
/**
* Manages the IDs assigned to DOM representations of React components. This
* uses a specific scheme in order to traverse the DOM efficiently (e.g. in
* order to simulate events).
*
* @internal
*/
var ReactInstanceHandles = {
/**
* Constructs a React root ID
* @return {string} A React root ID.
*/
createReactRootID: function() {
return getReactRootIDString(ReactRootIndex.createReactRootIndex());
},
/**
* Constructs a React ID by joining a root ID with a name.
*
* @param {string} rootID Root ID of a parent component.
* @param {string} name A component's name (as flattened children).
* @return {string} A React ID.
* @internal
*/
createReactID: function(rootID, name) {
return rootID + name;
},
/**
* Gets the DOM ID of the React component that is the root of the tree that
* contains the React component with the supplied DOM ID.
*
* @param {string} id DOM ID of a React component.
* @return {?string} DOM ID of the React component that is the root.
* @internal
*/
getReactRootIDFromNodeID: function(id) {
if (id && id.charAt(0) === SEPARATOR && id.length > 1) {
var index = id.indexOf(SEPARATOR, 1);
return index > -1 ? id.substr(0, index) : id;
}
return null;
},
/**
* Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
* should would receive a `mouseEnter` or `mouseLeave` event.
*
* NOTE: Does not invoke the callback on the nearest common ancestor because
* nothing "entered" or "left" that element.
*
* @param {string} leaveID ID being left.
* @param {string} enterID ID being entered.
* @param {function} cb Callback to invoke on each entered/left ID.
* @param {*} upArg Argument to invoke the callback with on left IDs.
* @param {*} downArg Argument to invoke the callback with on entered IDs.
* @internal
*/
traverseEnterLeave: function(leaveID, enterID, cb, upArg, downArg) {
var ancestorID = getFirstCommonAncestorID(leaveID, enterID);
if (ancestorID !== leaveID) {
traverseParentPath(leaveID, ancestorID, cb, upArg, false, true);
}
if (ancestorID !== enterID) {
traverseParentPath(ancestorID, enterID, cb, downArg, true, false);
}
},
/**
* Simulates the traversal of a two-phase, capture/bubble event dispatch.
*
* NOTE: This traversal happens on IDs without touching the DOM.
*
* @param {string} targetID ID of the target node.
* @param {function} cb Callback to invoke.
* @param {*} arg Argument to invoke the callback with.
* @internal
*/
traverseTwoPhase: function(targetID, cb, arg) {
if (targetID) {
traverseParentPath('', targetID, cb, arg, true, false);
traverseParentPath(targetID, '', cb, arg, false, true);
}
},
/**
* Traverse a node ID, calling the supplied `cb` for each ancestor ID. For
* example, passing `.0.$row-0.1` would result in `cb` getting called
* with `.0`, `.0.$row-0`, and `.0.$row-0.1`.
*
* NOTE: This traversal happens on IDs without touching the DOM.
*
* @param {string} targetID ID of the target node.
* @param {function} cb Callback to invoke.
* @param {*} arg Argument to invoke the callback with.
* @internal
*/
traverseAncestors: function(targetID, cb, arg) {
traverseParentPath('', targetID, cb, arg, true, false);
},
/**
* Exposed for unit testing.
* @private
*/
_getFirstCommonAncestorID: getFirstCommonAncestorID,
/**
* Exposed for unit testing.
* @private
*/
_getNextDescendantID: getNextDescendantID,
isAncestorIDOf: isAncestorIDOf,
SEPARATOR: SEPARATOR
};
module.exports = ReactInstanceHandles;
| {
"pile_set_name": "Github"
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
internal partial class Interop
{
internal partial class Kernel32
{
[DllImport(Libraries.Kernel32, SetLastError = true)]
internal static extern int SetConsoleTextAttribute(IntPtr hConsoleOutput, short wAttributes);
}
}
| {
"pile_set_name": "Github"
} |
{
"images" : [
{
"idiom" : "universal",
"filename" : "[email protected]",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
} | {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE 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 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 V8DebuggerScript_h
#define V8DebuggerScript_h
#include "platform/inspector_protocol/Allocator.h"
#include "platform/inspector_protocol/String16.h"
#include <v8.h>
namespace blink {
class V8DebuggerScript {
PROTOCOL_DISALLOW_COPY(V8DebuggerScript);
public:
V8DebuggerScript(v8::Isolate*, v8::Local<v8::Object>, bool isLiveEdit);
~V8DebuggerScript();
const String16& scriptId() const { return m_id; }
const String16& url() const { return m_url; }
bool hasSourceURL() const { return !m_sourceURL.isEmpty(); }
const String16& sourceURL() const;
const String16& sourceMappingURL() const { return m_sourceMappingURL; }
v8::Local<v8::String> source(v8::Isolate*) const;
const String16& hash() const { return m_hash; }
int startLine() const { return m_startLine; }
int startColumn() const { return m_startColumn; }
int endLine() const { return m_endLine; }
int endColumn() const { return m_endColumn; }
int executionContextId() const { return m_executionContextId; }
const String16& executionContextAuxData() const { return m_executionContextAuxData; }
bool isInternalScript() const { return m_isInternalScript; }
bool isLiveEdit() const { return m_isLiveEdit; }
void setSourceURL(const String16&);
void setSourceMappingURL(const String16&);
void setSource(v8::Isolate*, v8::Local<v8::String>);
private:
String16 m_id;
String16 m_url;
String16 m_sourceURL;
String16 m_sourceMappingURL;
v8::Global<v8::String> m_source;
String16 m_hash;
int m_startLine;
int m_startColumn;
int m_endLine;
int m_endColumn;
int m_executionContextId;
String16 m_executionContextAuxData;
bool m_isInternalScript;
bool m_isLiveEdit;
};
} // namespace blink
#endif // V8DebuggerScript_h
| {
"pile_set_name": "Github"
} |
FROM nodesource/wheezy-base
MAINTAINER William Blankenship <[email protected]>
RUN curl https://deb.nodesource.com/node/pool/main/n/nodejs/nodejs_0.10.43-1nodesource1~wheezy1_amd64.deb > node.deb \
&& dpkg -i node.deb \
&& rm node.deb
RUN npm install -g pangyp\
&& ln -s $(which pangyp) $(dirname $(which pangyp))/node-gyp\
&& npm cache clear\
&& node-gyp configure || echo ""
ENV NODE_ENV production
WORKDIR /usr/src/app
CMD ["npm","start"]
RUN apt-get update \
&& apt-get upgrade -y --force-yes \
&& rm -rf /var/lib/apt/lists/*; | {
"pile_set_name": "Github"
} |
Redux Favicon
=============
[](https://travis-ci.org/joshwcomeau/redux-favicon)
[](https://www.npmjs.com/package/redux-favicon)
[](https://coveralls.io/github/joshwcomeau/redux-favicon?branch=master)
Redux [middleware](http://rackt.org/redux/docs/advanced/Middleware.html) that lets you display notification badges in the favicon:

Uses [Favico.js](http://lab.ejci.net/favico.js/) under the hood, exposing its customization when needed but allowing you to display notification badges as easily as:
```js
// app.actions.js
export function newMessage() {
return {
type: 'NEW_MESSAGE',
meta: { favicon: 'increment' }
}
}
```
## Installation
#### Preferred: NPM
```js
npm i -S redux-favicon
```
#### Also available: UMD
UMD builds are also available, for single-file usage or quick hacking in a JSbin. Simply add `dist/redux-favicon.js` or `dist/redux-favicon.min.js` to your file in a `<script>` tag. The middleware will be available under `ReduxSounds`.
## Setup
Import the module into your configure-store file, pre-load it with settings, and apply it to the store:
```js
/* configure-store.js */
import { createStore, combineReducers, applyMiddleware } from 'redux';
import faviconMiddleware from 'redux-favicon';
import reducer from '../reducers';
// Redux Favicon accepts a configuration object. The options are explained below.
const faviconConfig = {
animation: 'slide',
position: 'up',
type: 'rectangle',
bgColor: '#123456',
textColor: '#314159'
};
// Pre-load our middleware with our config.
const loadedFaviconMiddleware = faviconMiddleware(faviconConfig);
// Use as you would any other middleware.
const store = createStore(reducer, applyMiddleware(loadedFaviconMiddleware));
// (Using the condensed createStore released in Redux v3.1.0)
```
The config file is optional, but you do need to invoke the favicon middleware either way.
## Options
Redux Favicon uses [Favico.js](http://lab.ejci.net/favico.js/) v0.3.10 under the hood. Favico.js offers some additional bells and whistles that are untested with this middleware, but the following options are supported:
| Attribute | Default | Details |
|------------|------------|----------------------------------------------------------------------------------------------------------|
| bgColor | #d00 | Badge background color |
| textColor | #fff | Badge text color |
| fontFamily | sans-serif | Text font family (Arial, Verdana, Times New Roman, serif, sans-serif,...) |
| fontStyle | bold | Font style (normal, italic, oblique, bold, bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800, 900) |
| type | circle | Badge shape (circle, rectangle) |
| position | down | Badge position (up, down, left, upleft) |
| animation | slide | Badge animation type (slide, fade, pop, popFade, none ) |
## Usage
Once your store is created, dispatching actions that trigger sounds is simple.
Using the convention established in the [rafScheduler Middleware example](https://github.com/rackt/redux/blob/46083e73d952feb367bf3fa4e13c1e419a224100/docs/advanced/Middleware.md#seven-examples), a new `meta` property can be attached to actions.
By attaching a `favicon` property to the `meta` object, you can specify the new number you'd like to display. Several convenience strings are offered as well.
Examples:
```js
// Set a new badge number.
// Accepts any integer.
// Sending 0 or a negative number hides the badge.
{
type: UPDATE_SCORE,
meta: {
favicon: 12
}
}
// Increase the current favicon number by 1.
// If there is no favicon badge currently displayed, it will be set to `1`
{
type: RECEIVE_MESSAGE,
meta: {
favicon: 'increment'
}
}
// Decrease the current favicon number by 1.
// If the current value is 1 or lower, this action removes the badge.
{
type: RECEIVE_MESSAGE,
meta: {
favicon: 'decrement'
}
}
// Remove the badge
// This is equivalent to sending a value of `0`
{
type: RECEIVE_MESSAGE,
meta: {
favicon: 'reset'
}
}
```
## Troubleshooting
I've done my best to make common errors communicated and explained via the console. Here are some of the errors you might encounter:
```
redux-favicon middleware not preloaded!
You need to first call reduxFavicon with its configuration to initialize it, THEN pass it to createStore.
```
When passing the middleware to the store, be sure to invoke it first:
```js
// Note that faviconMiddleware is being invoked:
const store = createStore(reducer, applyMiddleware( faviconMiddleware() ));
// ^^
```
-----
```
Warning: Favico not affected.
You provided a floating-point value: _____.
You need to provide an integer, or a keyword value.
```
This error is shown when the value dispatched to redux-favicon is a non-integer value. Decimals cannot be displayed in the favicon badge, only whole numbers.
-----
```
Warning: Favico not affected.
You provided a string value: ______.
The only strings we accept are: 'increment', 'decrement', 'reset'.
```
This one is pretty self-explanatory. String values are generally disallowed, with the exception of a few handy shortcuts for specifying relative adjustments or resets.
-----
```
Warning: Favico provided an illegal type.
You provided a a value of type: ______.
We only accept integers or strings.
```
Also pretty self-explanatory, redux-favicon does not like when you give it an array, object, function, etc.
-----
## Tests
To run: `npm run test`
Using Mocha for test-running, Chai Expect for assertions, and Istanbul for test coverage.
## Planned functionality
I don't have much planned, beyond maintenance. I could wrap additional Favico features (like dynamically specifying an image for a favicon, or using the user's webcam), but these aren't features that I personally have a need for.
Do get in touch if you have ideas for ways to improve this project :)
## Contributions
Contributors welcome! Please discuss additional features with me before implementing them, and please supply tests along with any bug fixes.
## License
[MIT](https://github.com/joshwcomeau/redux-favicon/blob/master/LICENSE.md)
| {
"pile_set_name": "Github"
} |
using Xunit;
namespace Shouldly.Tests.Strings.DetailedDifference.CaseInsensitive
{
public static class NullScenario
{
[Fact]
public static void ShouldNotShowDifferenceWhenActualIsMissing()
{
var str = (string?)null;
Verify.ShouldFail(() =>
str.ShouldBe("null", StringCompareShould.IgnoreCase),
errorWithSource:
@"str
should be with options: Ignoring case
""null""
but was
null",
errorWithoutSource:
@"null
should be with options: Ignoring case
""null""
but was not");
}
[Fact]
public static void ShouldNotShowDifferenceWhenExpectedIsMissing()
{
var str = "null";
Verify.ShouldFail(() =>
str.ShouldBe(null, StringCompareShould.IgnoreCase),
errorWithSource:
@"str
should be with options: Ignoring case
null
but was
""null""",
errorWithoutSource:
@"""null""
should be with options: Ignoring case
null
but was not");
}
}
}
| {
"pile_set_name": "Github"
} |
{
"name": "keen-dashboards",
"homepage": "https://keenlabs.github.io/dashboards/",
"main": "./dist/keen-dashboards.css",
"authors": [
"Dustin Larimer <[email protected]>",
"Sean Dokko <[email protected]>",
"Ritchie Benevedes <[email protected]>"
],
"license": "MIT",
"authors": [
"Dustin Larimer <[email protected]>",
"Taylor Barnett <[email protected]>"
],
"keywords": [
"keen io",
"dashboards",
"dataviz",
"visualization"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests",
"assets/img",
"assets/js",
"assets/css/keen-static.css"
]
}
| {
"pile_set_name": "Github"
} |
<md-dialog aria-label="pay dialog" ng-style="setDialogWidth()">
<div ng-show="publicInfo.status === 'loading'" layout="row" layout-align="center center" layout-margin layout-padding>
<md-progress-circular md-mode="indeterminate"></md-progress-circular>
</div>
<md-dialog-content ng-show="publicInfo.status !== 'loading'">
<div class="md-dialog-content">
<div layout="column" layout-align="center center" ng-show="publicInfo.status === 'type'">
<div style="margin-bottom: 20px;" translate>请选择支付方式:</div>
<md-radio-group ng-model="publicInfo.myPayType" flex>
<md-radio-button ng-repeat="pt in publicInfo.payType" value="{{pt.type}}" >
{{ pt.name }}
</md-radio-button>
</md-radio-group>
</div>
<div layout="column" layout-align="center center" ng-show="publicInfo.status === 'pay'">
<div ng-if="publicInfo.config.alipay && publicInfo.myPayType === 'alipay'" layout="column" layout-align="center center">
<qr size="getQrCodeSize()" layout-margin text="qrCode()" image="true" ng-click="pay()"></qr>
<div translate>支付宝扫码支付</div>
<div translate>手机请点击二维码付款</div>
</div>
<div style="margin-top: 30px;" ng-if="publicInfo.config.paypal && publicInfo.myPayType === 'paypal'" layout="column" layout-align="center center">
<div translate>请点击下面按钮完成PayPal支付</div>
<div style="margin-top: 5px;" id="paypal-button-container"></div>
</div>
</div>
<div layout="column" layout-align="center center" ng-if="publicInfo.status === 'choose'">
<div style="margin-bottom: 20px;" translate>请选择续费周期:</div>
<md-radio-group ng-model="publicInfo.orderId" ng-change="publicInfo.setOrder(publicInfo.orderId)" flex>
<md-radio-button style="margin-top: 15px; margin-bottom: 5px; width: 100%;" layout="row" layout-align="center center" ng-repeat-start="order in publicInfo.orders" value="{{order.id}}" ng-hide="order[publicInfo.myPayType] === 0">
<div layout="row" layout-align="space-between center" style="min-width: 210px; max-width: 390px;">
<span flex="65" translate>{{ order.name }}</span>
<span flex="35" style="text-align:right; color: #888">
<span>{{ publicInfo.myPayType === 'alipay' ? '¥' : '$' }}</span><span>{{ order[publicInfo.myPayType] }}</span>
</span>
</div>
</md-radio-button>
<div style="margin: 5px 0 5px 30px; color: #666; font-size: 0.85em;" ng-show="+publicInfo.orderId === +order.id && order.shortComment">{{ order.shortComment }}</div>
<div style="margin: 5px 0 5px 30px; color: #666; font-size: 0.85em;" ng-if="publicInfo.selectedOrder.baseId" ng-show="+publicInfo.orderId === +order.id" ng-repeat-end>有效期:{{ publicInfo.account.data.to | date : 'yyyy-MM-dd HH:mm' }}</div>
</md-radio-group>
</div>
<div layout="column" layout-align="center center" ng-show="publicInfo.status === 'giftcard'">
<form>
<md-input-container class="md-block" flex-gt-sm>
<label translate>充值码</label>
<input ng-model="publicInfo.giftCardPassword">
</md-input-container>
</form>
</div>
<div layout="column" layout-align="center center" ng-show="publicInfo.status === 'success'">
<div style="margin-bottom: 20px;">支付成功</div>
<div style="margin-bottom: 20px;">{{ publicInfo.message }}</div>
</div>
<div layout="column" layout-align="center center" ng-show="publicInfo.status === 'error'">
<div style="margin-bottom: 20px;">支付失败</div>
<div style="margin-bottom: 20px;">{{ publicInfo.message }}</div>
</div>
<div layout="column" layout-align="center center" ng-show="publicInfo.status === 'comment'">
<div class="markdown-table" marked="publicInfo.comment"></div>
</div>
</div>
</md-dialog-content>
<md-dialog-actions layout="row" layout-align="center center" ng-show="publicInfo.status !== 'loading'">
<md-button class="md-primary" ng-show="publicInfo.status === 'giftcard'" ng-click="publicInfo.close()">
{{ '取消' | translate }}
</md-button>
<md-button class="md-primary" ng-show="publicInfo.status === 'giftcard'" ng-click="publicInfo.payByGiftCard()" ng-disabled="!publicInfo.giftCardPassword">
{{ '下一步' | translate }}
</md-button>
<md-button class="md-primary" ng-show="publicInfo.status === 'type'" ng-click="publicInfo.close()">
{{ '取消' | translate }}
</md-button>
<md-button class="md-primary" ng-show="publicInfo.status === 'type'" ng-click="publicInfo.jumpToPayPage()" ng-disabled="!publicInfo.myPayType">
{{ '下一步' | translate }}
</md-button>
<md-button class="md-primary" ng-show="publicInfo.status === 'choose'" ng-click="publicInfo.close()">
{{ '取消' | translate }}
</md-button>
<md-button class="md-primary" ng-show="publicInfo.status === 'choose'" ng-click="publicInfo.showComment()" ng-disabled="!publicInfo.orderId">
{{ publicInfo.selectedOrder.comment ? '详情' : '支付' | translate }}
</md-button>
<md-button class="md-primary" ng-show="publicInfo.status === 'pay' || publicInfo.status === 'success' || publicInfo.status === 'error'" ng-click="publicInfo.close()">
{{ '关闭' | translate }}
</md-button>
<md-button class="md-primary" ng-show="publicInfo.status === 'comment'" ng-click="publicInfo.jumpToPayPage()">
{{ '返回' | translate }}
</md-button>
<md-button class="md-primary" ng-show="publicInfo.status === 'comment'" ng-click="publicInfo.createOrder()" ng-disabled="publicInfo.time > 0">
支付<span ng-show="publicInfo.time">({{ publicInfo.time }})</span>
</md-button>
</md-dialog-actions>
</md-dialog>
| {
"pile_set_name": "Github"
} |
{
"name": "on-finished",
"description": "Execute a callback when a request closes, finishes, or errors",
"version": "2.3.0",
"contributors": [
{
"name": "Douglas Christopher Wilson",
"email": "[email protected]"
},
{
"name": "Jonathan Ong",
"email": "[email protected]",
"url": "http://jongleberry.com"
}
],
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/jshttp/on-finished.git"
},
"dependencies": {
"ee-first": "1.1.1"
},
"devDependencies": {
"istanbul": "0.3.9",
"mocha": "2.2.5"
},
"engines": {
"node": ">= 0.8"
},
"files": [
"HISTORY.md",
"LICENSE",
"index.js"
],
"scripts": {
"test": "mocha --reporter spec --bail --check-leaks test/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/",
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/"
},
"gitHead": "34babcb58126a416fcf5205768204f2e12699dda",
"bugs": {
"url": "https://github.com/jshttp/on-finished/issues"
},
"homepage": "https://github.com/jshttp/on-finished",
"_id": "[email protected]",
"_shasum": "20f1336481b083cd75337992a16971aa2d906947",
"_from": "on-finished@>=2.3.0 <2.4.0",
"_npmVersion": "1.4.28",
"_npmUser": {
"name": "dougwilson",
"email": "[email protected]"
},
"maintainers": [
{
"name": "dougwilson",
"email": "[email protected]"
},
{
"name": "jongleberry",
"email": "[email protected]"
}
],
"dist": {
"shasum": "20f1336481b083cd75337992a16971aa2d906947",
"tarball": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
"readme": "ERROR: No README data found!"
}
| {
"pile_set_name": "Github"
} |
//
// This file is part of an OMNeT++/OMNEST simulation example.
//
// Copyright (C) 1992-2015 Andras Varga
//
// This file is distributed WITHOUT ANY WARRANTY. See the file
// `license' for details on this and other legal matters.
//
import
"telnetclient",
"exttelnetclient",
"telnetserver",
"cloud";
//
// Model of the network, consisting of several clients, a server and a cloud
//
module TelnetNet
parameters:
numClients: numeric const;
submodules:
server: TelnetServer;
display: "i=device/server;p=426,166";
cloud: Cloud;
gatesizes:
in[numClients+2],
out[numClients+2];
display: "i=misc/cloud;p=274,170";
extClient: ExtTelnetClient;
parameters:
addr = 1,
srvAddr = 0;
display: "i=device/pc2,gold;p=102,80";
client: TelnetClient[numClients];
parameters:
addr = 2+index,
srvAddr = 0;
display: "i=device/pc2;p=102,150,col";
connections:
server.out --> cloud.in[0];
server.in <-- cloud.out[0];
extClient.out --> cloud.in[1];
extClient.in <-- cloud.out[1];
for i=0..numClients-1 do
client[i].out --> cloud.in[i+2];
client[i].in <-- cloud.out[i+2];
endfor;
endmodule
//
// Instantiates TelnetNet
//
network telnetNet : TelnetNet
parameters:
numClients = input(3,"Number of clients:");
endnetwork
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2008-2017 Nicira, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <config.h>
#include "openvswitch/ofp-meter.h"
#include "byte-order.h"
#include "nx-match.h"
#include "openvswitch/ofp-errors.h"
#include "openvswitch/ofp-msgs.h"
#include "openvswitch/ofp-parse.h"
#include "openvswitch/ofp-print.h"
#include "openvswitch/ofpbuf.h"
#include "openvswitch/vlog.h"
VLOG_DEFINE_THIS_MODULE(ofp_meter);
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
void
ofputil_format_meter_id(struct ds *s, uint32_t meter_id, char separator)
{
if (meter_id <= OFPM13_MAX) {
ds_put_format(s, "meter%c%"PRIu32, separator, meter_id);
} else {
const char *name;
switch (meter_id) {
case OFPM13_SLOWPATH:
name = "slowpath";
break;
case OFPM13_CONTROLLER:
name = "controller";
break;
case OFPM13_ALL:
name = "all";
break;
default:
name = "unknown";
}
ds_put_format(s, "meter%c%s", separator, name);
}
}
void
ofputil_format_meter_band(struct ds *s, enum ofp13_meter_flags flags,
const struct ofputil_meter_band *mb)
{
ds_put_cstr(s, "\ntype=");
switch (mb->type) {
case OFPMBT13_DROP:
ds_put_cstr(s, "drop");
break;
case OFPMBT13_DSCP_REMARK:
ds_put_cstr(s, "dscp_remark");
break;
default:
ds_put_format(s, "%u", mb->type);
}
ds_put_format(s, " rate=%"PRIu32, mb->rate);
if (flags & OFPMF13_BURST) {
ds_put_format(s, " burst_size=%"PRIu32, mb->burst_size);
}
if (mb->type == OFPMBT13_DSCP_REMARK) {
ds_put_format(s, " prec_level=%"PRIu8, mb->prec_level);
}
}
static enum ofperr
ofputil_pull_bands(struct ofpbuf *msg, size_t len, uint16_t *n_bands,
struct ofpbuf *bands)
{
const struct ofp13_meter_band_header *ombh;
struct ofputil_meter_band *mb;
uint16_t n = 0;
ombh = ofpbuf_try_pull(msg, len);
if (!ombh) {
return OFPERR_OFPBRC_BAD_LEN;
}
while (len >= sizeof (struct ofp13_meter_band_drop)) {
size_t ombh_len = ntohs(ombh->len);
/* All supported band types have the same length. */
if (ombh_len != sizeof (struct ofp13_meter_band_drop)) {
return OFPERR_OFPBRC_BAD_LEN;
}
mb = ofpbuf_put_uninit(bands, sizeof *mb);
mb->type = ntohs(ombh->type);
if (mb->type != OFPMBT13_DROP && mb->type != OFPMBT13_DSCP_REMARK) {
return OFPERR_OFPMMFC_BAD_BAND;
}
mb->rate = ntohl(ombh->rate);
mb->burst_size = ntohl(ombh->burst_size);
mb->prec_level = (mb->type == OFPMBT13_DSCP_REMARK) ?
((struct ofp13_meter_band_dscp_remark *)ombh)->prec_level : 0;
n++;
len -= ombh_len;
ombh = ALIGNED_CAST(struct ofp13_meter_band_header *,
(char *) ombh + ombh_len);
}
if (len) {
return OFPERR_OFPBRC_BAD_LEN;
}
*n_bands = n;
return 0;
}
enum ofperr
ofputil_decode_meter_mod(const struct ofp_header *oh,
struct ofputil_meter_mod *mm,
struct ofpbuf *bands)
{
struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
ofpraw_pull_assert(&b);
const struct ofp13_meter_mod *omm = ofpbuf_pull(&b, sizeof *omm);
/* Translate the message. */
mm->command = ntohs(omm->command);
if (mm->command != OFPMC13_ADD &&
mm->command != OFPMC13_MODIFY &&
mm->command != OFPMC13_DELETE) {
return OFPERR_OFPMMFC_BAD_COMMAND;
}
mm->meter.meter_id = ntohl(omm->meter_id);
if (mm->command == OFPMC13_DELETE) {
mm->meter.flags = 0;
mm->meter.n_bands = 0;
mm->meter.bands = NULL;
} else {
enum ofperr error;
mm->meter.flags = ntohs(omm->flags);
if (mm->meter.flags & OFPMF13_KBPS &&
mm->meter.flags & OFPMF13_PKTPS) {
return OFPERR_OFPMMFC_BAD_FLAGS;
}
error = ofputil_pull_bands(&b, b.size, &mm->meter.n_bands, bands);
if (error) {
return error;
}
mm->meter.bands = bands->data;
}
return 0;
}
void
ofputil_decode_meter_request(const struct ofp_header *oh, uint32_t *meter_id)
{
const struct ofp13_meter_multipart_request *omr = ofpmsg_body(oh);
*meter_id = ntohl(omr->meter_id);
}
struct ofpbuf *
ofputil_encode_meter_request(enum ofp_version ofp_version,
enum ofputil_meter_request_type type,
uint32_t meter_id)
{
struct ofpbuf *msg;
enum ofpraw raw;
switch (type) {
case OFPUTIL_METER_CONFIG:
raw = OFPRAW_OFPST13_METER_CONFIG_REQUEST;
break;
case OFPUTIL_METER_STATS:
raw = OFPRAW_OFPST13_METER_REQUEST;
break;
default:
case OFPUTIL_METER_FEATURES:
raw = OFPRAW_OFPST13_METER_FEATURES_REQUEST;
break;
}
msg = ofpraw_alloc(raw, ofp_version, 0);
if (type != OFPUTIL_METER_FEATURES) {
struct ofp13_meter_multipart_request *omr;
omr = ofpbuf_put_zeros(msg, sizeof *omr);
omr->meter_id = htonl(meter_id);
}
return msg;
}
static void
ofputil_put_bands(uint16_t n_bands, const struct ofputil_meter_band *mb,
struct ofpbuf *msg)
{
uint16_t n = 0;
for (n = 0; n < n_bands; ++n) {
/* Currently all band types have same size. */
struct ofp13_meter_band_dscp_remark *ombh;
size_t ombh_len = sizeof *ombh;
ombh = ofpbuf_put_zeros(msg, ombh_len);
ombh->type = htons(mb->type);
ombh->len = htons(ombh_len);
ombh->rate = htonl(mb->rate);
ombh->burst_size = htonl(mb->burst_size);
ombh->prec_level = mb->prec_level;
mb++;
}
}
/* Encode a meter stat for 'mc' and append it to 'replies'. */
void
ofputil_append_meter_config(struct ovs_list *replies,
const struct ofputil_meter_config *mc)
{
struct ofpbuf *msg = ofpbuf_from_list(ovs_list_back(replies));
size_t start_ofs = msg->size;
struct ofp13_meter_config *reply;
ofpbuf_put_uninit(msg, sizeof *reply);
ofputil_put_bands(mc->n_bands, mc->bands, msg);
reply = ofpbuf_at_assert(msg, start_ofs, sizeof *reply);
reply->flags = htons(mc->flags);
reply->meter_id = htonl(mc->meter_id);
reply->length = htons(msg->size - start_ofs);
ofpmp_postappend(replies, start_ofs);
}
/* Encode a meter stat for 'ms' and append it to 'replies'. */
void
ofputil_append_meter_stats(struct ovs_list *replies,
const struct ofputil_meter_stats *ms)
{
struct ofp13_meter_stats *reply;
uint16_t n = 0;
uint16_t len;
len = sizeof *reply + ms->n_bands * sizeof(struct ofp13_meter_band_stats);
reply = ofpmp_append(replies, len);
reply->meter_id = htonl(ms->meter_id);
reply->len = htons(len);
memset(reply->pad, 0, sizeof reply->pad);
reply->flow_count = htonl(ms->flow_count);
reply->packet_in_count = htonll(ms->packet_in_count);
reply->byte_in_count = htonll(ms->byte_in_count);
reply->duration_sec = htonl(ms->duration_sec);
reply->duration_nsec = htonl(ms->duration_nsec);
for (n = 0; n < ms->n_bands; ++n) {
const struct ofputil_meter_band_stats *src = &ms->bands[n];
struct ofp13_meter_band_stats *dst = &reply->band_stats[n];
dst->packet_band_count = htonll(src->packet_count);
dst->byte_band_count = htonll(src->byte_count);
}
}
/* Converts an OFPMP_METER_CONFIG reply in 'msg' into an abstract
* ofputil_meter_config in 'mc', with mc->bands pointing to bands decoded into
* 'bands'. The caller must have initialized 'bands' and retains ownership of
* it across the call.
*
* Multiple OFPST13_METER_CONFIG replies can be packed into a single OpenFlow
* message. Calling this function multiple times for a single 'msg' iterates
* through the replies. 'bands' is cleared for each reply.
*
* Returns 0 if successful, EOF if no replies were left in this 'msg',
* otherwise a positive errno value. */
int
ofputil_decode_meter_config(struct ofpbuf *msg,
struct ofputil_meter_config *mc,
struct ofpbuf *bands)
{
const struct ofp13_meter_config *omc;
enum ofperr err;
/* Pull OpenFlow headers for the first call. */
if (!msg->header) {
ofpraw_pull_assert(msg);
}
if (!msg->size) {
return EOF;
}
omc = ofpbuf_try_pull(msg, sizeof *omc);
if (!omc) {
VLOG_WARN_RL(&rl, "OFPMP_METER_CONFIG reply has %"PRIu32" leftover "
"bytes at end", msg->size);
return OFPERR_OFPBRC_BAD_LEN;
}
ofpbuf_clear(bands);
err = ofputil_pull_bands(msg, ntohs(omc->length) - sizeof *omc,
&mc->n_bands, bands);
if (err) {
return err;
}
mc->meter_id = ntohl(omc->meter_id);
mc->flags = ntohs(omc->flags);
mc->bands = bands->data;
return 0;
}
static void
ofp_print_meter_flags(struct ds *s, enum ofp13_meter_flags flags)
{
if (flags & OFPMF13_KBPS) {
ds_put_cstr(s, "kbps ");
}
if (flags & OFPMF13_PKTPS) {
ds_put_cstr(s, "pktps ");
}
if (flags & OFPMF13_BURST) {
ds_put_cstr(s, "burst ");
}
if (flags & OFPMF13_STATS) {
ds_put_cstr(s, "stats ");
}
flags &= ~(OFPMF13_KBPS | OFPMF13_PKTPS | OFPMF13_BURST | OFPMF13_STATS);
if (flags) {
ds_put_format(s, "flags:0x%x ", (unsigned)flags);
}
}
void
ofputil_format_meter_config(struct ds *s,
const struct ofputil_meter_config *mc)
{
uint16_t i;
ofputil_format_meter_id(s, mc->meter_id, '=');
ds_put_char(s, ' ');
ofp_print_meter_flags(s, mc->flags);
ds_put_cstr(s, "bands=");
for (i = 0; i < mc->n_bands; ++i) {
ofputil_format_meter_band(s, mc->flags, &mc->bands[i]);
}
ds_put_char(s, '\n');
}
static enum ofperr
ofputil_pull_band_stats(struct ofpbuf *msg, size_t len, uint16_t *n_bands,
struct ofpbuf *bands)
{
const struct ofp13_meter_band_stats *ombs;
struct ofputil_meter_band_stats *mbs;
uint16_t n, i;
ombs = ofpbuf_try_pull(msg, len);
if (!ombs) {
return OFPERR_OFPBRC_BAD_LEN;
}
n = len / sizeof *ombs;
if (len != n * sizeof *ombs) {
return OFPERR_OFPBRC_BAD_LEN;
}
mbs = ofpbuf_put_uninit(bands, len);
for (i = 0; i < n; ++i) {
mbs[i].packet_count = ntohll(ombs[i].packet_band_count);
mbs[i].byte_count = ntohll(ombs[i].byte_band_count);
}
*n_bands = n;
return 0;
}
/* Converts an OFPMP_METER reply in 'msg' into an abstract
* ofputil_meter_stats in 'ms', with ms->bands pointing to band stats
* decoded into 'bands'.
*
* Multiple OFPMP_METER replies can be packed into a single OpenFlow
* message. Calling this function multiple times for a single 'msg' iterates
* through the replies. 'bands' is cleared for each reply.
*
* Returns 0 if successful, EOF if no replies were left in this 'msg',
* otherwise a positive errno value. */
int
ofputil_decode_meter_stats(struct ofpbuf *msg,
struct ofputil_meter_stats *ms,
struct ofpbuf *bands)
{
const struct ofp13_meter_stats *oms;
enum ofperr err;
/* Pull OpenFlow headers for the first call. */
if (!msg->header) {
ofpraw_pull_assert(msg);
}
if (!msg->size) {
return EOF;
}
oms = ofpbuf_try_pull(msg, sizeof *oms);
if (!oms) {
VLOG_WARN_RL(&rl, "OFPMP_METER reply has %"PRIu32" leftover bytes "
"at end", msg->size);
return OFPERR_OFPBRC_BAD_LEN;
}
ofpbuf_clear(bands);
err = ofputil_pull_band_stats(msg, ntohs(oms->len) - sizeof *oms,
&ms->n_bands, bands);
if (err) {
return err;
}
ms->meter_id = ntohl(oms->meter_id);
ms->flow_count = ntohl(oms->flow_count);
ms->packet_in_count = ntohll(oms->packet_in_count);
ms->byte_in_count = ntohll(oms->byte_in_count);
ms->duration_sec = ntohl(oms->duration_sec);
ms->duration_nsec = ntohl(oms->duration_nsec);
ms->bands = bands->data;
return 0;
}
void
ofputil_format_meter_stats(struct ds *s, const struct ofputil_meter_stats *ms)
{
uint16_t i;
ofputil_format_meter_id(s, ms->meter_id, ':');
ds_put_char(s, ' ');
ds_put_format(s, "flow_count:%"PRIu32" ", ms->flow_count);
ds_put_format(s, "packet_in_count:%"PRIu64" ", ms->packet_in_count);
ds_put_format(s, "byte_in_count:%"PRIu64" ", ms->byte_in_count);
ds_put_cstr(s, "duration:");
ofp_print_duration(s, ms->duration_sec, ms->duration_nsec);
ds_put_char(s, ' ');
ds_put_cstr(s, "bands:\n");
for (i = 0; i < ms->n_bands; ++i) {
ds_put_format(s, "%d: ", i);
ds_put_format(s, "packet_count:%"PRIu64" ", ms->bands[i].packet_count);
ds_put_format(s, "byte_count:%"PRIu64"\n", ms->bands[i].byte_count);
}
}
void
ofputil_decode_meter_features(const struct ofp_header *oh,
struct ofputil_meter_features *mf)
{
const struct ofp13_meter_features *omf = ofpmsg_body(oh);
mf->max_meters = ntohl(omf->max_meter);
mf->band_types = ntohl(omf->band_types);
mf->capabilities = ntohl(omf->capabilities);
mf->max_bands = omf->max_bands;
mf->max_color = omf->max_color;
}
struct ofpbuf *
ofputil_encode_meter_features_reply(const struct ofputil_meter_features *mf,
const struct ofp_header *request)
{
struct ofpbuf *reply;
struct ofp13_meter_features *omf;
reply = ofpraw_alloc_stats_reply(request, 0);
omf = ofpbuf_put_zeros(reply, sizeof *omf);
omf->max_meter = htonl(mf->max_meters);
omf->band_types = htonl(mf->band_types);
omf->capabilities = htonl(mf->capabilities);
omf->max_bands = mf->max_bands;
omf->max_color = mf->max_color;
return reply;
}
static const char *
ofputil_meter_band_types_to_name(uint32_t bit)
{
switch (bit) {
case 1 << OFPMBT13_DROP: return "drop";
case 1 << OFPMBT13_DSCP_REMARK: return "dscp_remark";
}
return NULL;
}
static const char *
ofputil_meter_capabilities_to_name(uint32_t bit)
{
enum ofp13_meter_flags flag = bit;
switch (flag) {
case OFPMF13_KBPS: return "kbps";
case OFPMF13_PKTPS: return "pktps";
case OFPMF13_BURST: return "burst";
case OFPMF13_STATS: return "stats";
}
return NULL;
}
void
ofputil_format_meter_features(struct ds *s,
const struct ofputil_meter_features *mf)
{
ds_put_format(s, "\nmax_meter:%"PRIu32, mf->max_meters);
ds_put_format(s, " max_bands:%"PRIu8, mf->max_bands);
ds_put_format(s, " max_color:%"PRIu8"\n", mf->max_color);
ds_put_cstr(s, "band_types: ");
ofp_print_bit_names(s, mf->band_types,
ofputil_meter_band_types_to_name, ' ');
ds_put_char(s, '\n');
ds_put_cstr(s, "capabilities: ");
ofp_print_bit_names(s, mf->capabilities,
ofputil_meter_capabilities_to_name, ' ');
ds_put_char(s, '\n');
}
struct ofpbuf *
ofputil_encode_meter_mod(enum ofp_version ofp_version,
const struct ofputil_meter_mod *mm)
{
struct ofpbuf *msg;
struct ofp13_meter_mod *omm;
msg = ofpraw_alloc(OFPRAW_OFPT13_METER_MOD, ofp_version,
NXM_TYPICAL_LEN + mm->meter.n_bands * 16);
omm = ofpbuf_put_zeros(msg, sizeof *omm);
omm->command = htons(mm->command);
if (mm->command != OFPMC13_DELETE) {
omm->flags = htons(mm->meter.flags);
}
omm->meter_id = htonl(mm->meter.meter_id);
ofputil_put_bands(mm->meter.n_bands, mm->meter.bands, msg);
ofpmsg_update_length(msg);
return msg;
}
/* Parse a string representation of a meter modification message to '*mm'.
* If successful, 'mm->meter.bands' must be free()d by the caller. */
static char * OVS_WARN_UNUSED_RESULT
parse_ofp_meter_mod_str__(struct ofputil_meter_mod *mm, char *string,
struct ofpbuf *bands, int command,
enum ofputil_protocol *usable_protocols)
{
enum {
F_METER = 1 << 0,
F_FLAGS = 1 << 1,
F_BANDS = 1 << 2,
} fields;
char *save_ptr = NULL;
char *band_str = NULL;
char *name;
/* Meters require at least OF 1.3. */
*usable_protocols = OFPUTIL_P_OF13_UP;
switch (command) {
case -1:
fields = F_METER;
break;
case OFPMC13_ADD:
fields = F_METER | F_FLAGS | F_BANDS;
break;
case OFPMC13_DELETE:
fields = F_METER;
break;
case OFPMC13_MODIFY:
fields = F_METER | F_FLAGS | F_BANDS;
break;
default:
OVS_NOT_REACHED();
}
mm->command = command;
mm->meter.meter_id = 0;
mm->meter.flags = 0;
mm->meter.n_bands = 0;
mm->meter.bands = NULL;
if (fields & F_BANDS) {
band_str = strstr(string, "band");
if (!band_str) {
return xstrdup("must specify bands");
}
*band_str = '\0';
band_str = strchr(band_str + 1, '=');
if (!band_str) {
return xstrdup("must specify bands");
}
band_str++;
}
for (name = strtok_r(string, "=, \t\r\n", &save_ptr); name;
name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
if (fields & F_FLAGS && !strcmp(name, "kbps")) {
mm->meter.flags |= OFPMF13_KBPS;
} else if (fields & F_FLAGS && !strcmp(name, "pktps")) {
mm->meter.flags |= OFPMF13_PKTPS;
} else if (fields & F_FLAGS && !strcmp(name, "burst")) {
mm->meter.flags |= OFPMF13_BURST;
} else if (fields & F_FLAGS && !strcmp(name, "stats")) {
mm->meter.flags |= OFPMF13_STATS;
} else {
char *value;
value = strtok_r(NULL, ", \t\r\n", &save_ptr);
if (!value) {
return xasprintf("field %s missing value", name);
}
if (!strcmp(name, "meter")) {
if (!strcmp(value, "all")) {
mm->meter.meter_id = OFPM13_ALL;
} else if (!strcmp(value, "controller")) {
mm->meter.meter_id = OFPM13_CONTROLLER;
} else if (!strcmp(value, "slowpath")) {
mm->meter.meter_id = OFPM13_SLOWPATH;
} else {
char *error = str_to_u32(value, &mm->meter.meter_id);
if (error) {
return error;
}
if (mm->meter.meter_id > OFPM13_MAX
|| !mm->meter.meter_id) {
return xasprintf("invalid value for %s", name);
}
}
} else {
return xasprintf("unknown keyword %s", name);
}
}
}
if (fields & F_METER && !mm->meter.meter_id) {
return xstrdup("must specify 'meter'");
}
if (fields & F_FLAGS && !mm->meter.flags) {
return xstrdup("meter must specify either 'kbps' or 'pktps'");
}
if (fields & F_BANDS) {
uint16_t n_bands = 0;
struct ofputil_meter_band *band = NULL;
int i;
for (name = strtok_r(band_str, "=, \t\r\n", &save_ptr); name;
name = strtok_r(NULL, "=, \t\r\n", &save_ptr)) {
char *value;
value = strtok_r(NULL, ", \t\r\n", &save_ptr);
if (!value) {
return xasprintf("field %s missing value", name);
}
if (!strcmp(name, "type")) {
/* Start a new band */
band = ofpbuf_put_zeros(bands, sizeof *band);
n_bands++;
if (!strcmp(value, "drop")) {
band->type = OFPMBT13_DROP;
} else if (!strcmp(value, "dscp_remark")) {
band->type = OFPMBT13_DSCP_REMARK;
} else {
return xasprintf("field %s unknown value %s", name, value);
}
} else if (!band || !band->type) {
return xstrdup("band must start with the 'type' keyword");
} else if (!strcmp(name, "rate")) {
char *error = str_to_u32(value, &band->rate);
if (error) {
return error;
}
} else if (!strcmp(name, "burst_size")) {
char *error = str_to_u32(value, &band->burst_size);
if (error) {
return error;
}
} else if (!strcmp(name, "prec_level")) {
char *error = str_to_u8(value, name, &band->prec_level);
if (error) {
return error;
}
} else {
return xasprintf("unknown keyword %s", name);
}
}
/* validate bands */
if (!n_bands) {
return xstrdup("meter must have bands");
}
mm->meter.n_bands = n_bands;
mm->meter.bands = ofpbuf_steal_data(bands);
for (i = 0; i < n_bands; ++i) {
band = &mm->meter.bands[i];
if (!band->type) {
return xstrdup("band must have 'type'");
}
if (band->type == OFPMBT13_DSCP_REMARK) {
if (!band->prec_level) {
return xstrdup("'dscp_remark' band must have"
" 'prec_level'");
}
} else {
if (band->prec_level) {
return xstrdup("Only 'dscp_remark' band may have"
" 'prec_level'");
}
}
if (!band->rate) {
return xstrdup("band must have 'rate'");
}
if (mm->meter.flags & OFPMF13_BURST) {
if (!band->burst_size) {
return xstrdup("band must have 'burst_size' "
"when 'burst' flag is set");
}
} else {
if (band->burst_size) {
return xstrdup("band may have 'burst_size' only "
"when 'burst' flag is set");
}
}
}
}
return NULL;
}
/* Convert 'str_' (as described in the Meter Syntax section of the
* ovs-ofctl man page) into 'mm' for sending the specified meter_mod
* 'command' to a switch.
*
* Returns NULL if successful, otherwise a malloc()'d string describing the
* error. The caller is responsible for freeing the returned string.
* If successful, 'mm->meter.bands' must be free()'d by the caller. */
char * OVS_WARN_UNUSED_RESULT
parse_ofp_meter_mod_str(struct ofputil_meter_mod *mm, const char *str_,
int command, enum ofputil_protocol *usable_protocols)
{
struct ofpbuf bands;
char *string;
char *error;
ofpbuf_init(&bands, 64);
string = xstrdup(str_);
error = parse_ofp_meter_mod_str__(mm, string, &bands, command,
usable_protocols);
free(string);
ofpbuf_uninit(&bands);
return error;
}
void
ofputil_format_meter_mod(struct ds *s, const struct ofputil_meter_mod *mm)
{
switch (mm->command) {
case OFPMC13_ADD:
ds_put_cstr(s, " ADD ");
break;
case OFPMC13_MODIFY:
ds_put_cstr(s, " MOD ");
break;
case OFPMC13_DELETE:
ds_put_cstr(s, " DEL ");
break;
default:
ds_put_format(s, " cmd:%d ", mm->command);
}
ofputil_format_meter_config(s, &mm->meter);
}
| {
"pile_set_name": "Github"
} |
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgxsEAmr439JoRs7Xc
7OIKgYSbo+bFM1zPrW1V/JZGgKShRANCAARLl7a4+BenigrAVY2rEZxYk0URtji4
NFLScdXF9SPR5zcOCll+Hpyj8KLjbrX+CmsXwgMZrkYM2SOQSlOcd6Ay
-----END PRIVATE KEY-----
| {
"pile_set_name": "Github"
} |
var baseIteratee = require('./_baseIteratee'),
createInverter = require('./_createInverter');
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* This method is like `_.invert` except that the inverted object is generated
* from the results of running each element of `object` thru `iteratee`. The
* corresponding inverted value of each inverted key is an array of keys
* responsible for generating the inverted value. The iteratee is invoked
* with one argument: (value).
*
* @static
* @memberOf _
* @since 4.1.0
* @category Object
* @param {Object} object The object to invert.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invertBy(object);
* // => { '1': ['a', 'c'], '2': ['b'] }
*
* _.invertBy(object, function(value) {
* return 'group' + value;
* });
* // => { 'group1': ['a', 'c'], 'group2': ['b'] }
*/
var invertBy = createInverter(function(result, value, key) {
if (hasOwnProperty.call(result, value)) {
result[value].push(key);
} else {
result[value] = [key];
}
}, baseIteratee);
module.exports = invertBy;
| {
"pile_set_name": "Github"
} |
<?php
/*
|--------------------------------------------------------------------------
| Module API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
| {
"pile_set_name": "Github"
} |
# From http://downloads.yoctoproject.org/releases/matchbox/matchbox-panel/0.9/matchbox-panel-0.9.3.tar.bz2.md5
md5 56d1807636f3919e22e51896ab7ccd2e matchbox-panel-0.9.3.tar.bz2
# Locally computed
sha256 32b1062f7da84967e7019d01ab805935caa7ab7321a7ced0e30ebe75e5df1670 COPYING
| {
"pile_set_name": "Github"
} |
package endpoints4s.algebra
import endpoints4s.{Invalid, Valid, Validated}
import org.scalatest.freespec.AnyFreeSpec
/**
* Tests that must be run on all [[JsonSchemas]] interpreters.
*/
trait JsonSchemasOptionalFieldsTest extends AnyFreeSpec with JsonSchemasFixtures {
// Abstract over concrete JSON library (such as circe, Play JSON, or ujson)
trait Json {
type Json
def obj(fields: (String, Json)*): Json
def arr(items: Json*): Json
def num(x: BigDecimal): Json
def str(s: String): Json
def bool(b: Boolean): Json
def `null`: Json
}
val Json: Json
def decodeJson[A](schema: JsonSchema[A], json: Json.Json): Validated[A]
def encodeJson[A](schema: JsonSchema[A], value: A): Json.Json
"empty record" in {
checkRoundTrip(
emptyRecord,
Json.obj(),
()
)
}
"invalid empty record" in {
val jsonSchema = emptyRecord
val json = Json.arr()
checkDecodingFailure(jsonSchema, json, Seq("Invalid JSON object: []"))
}
"missing optional field" in {
checkRoundTrip(
optField[Int]("relevant"),
Json.obj(),
None
)
}
"optional field" in {
checkRoundTrip(
optField[Int]("relevant"),
Json.obj("relevant" -> Json.num(123)),
Some(123)
)
}
"optional field null" in {
val schema = optField[Int]("relevant")
val json = Json.obj("relevant" -> Json.`null`)
// We don’t use “testRoundtrip” here because we decode a `null` field
// but we don’t produce that field when encoding
decodeJson(schema, json) match {
case Valid(None) =>
assert(encodeJson(schema, None) == Json.obj())
case Valid(Some(n)) => fail(s"Decoded $n")
case Invalid(errors) => fail(errors.mkString(". "))
}
}
"nested optional field" in {
checkRoundTrip(
optField[Int]("level1")(field[Int]("level2")),
Json.obj("level1" -> Json.obj("level2" -> Json.num(123))),
Some(123)
)
}
"missing nested optional field" in {
checkRoundTrip(
optField[Int]("level1")(field[Int]("level2")),
Json.obj(),
None
)
}
"single record" in {
checkRoundTrip(
field[String]("field1"),
Json.obj("field1" -> Json.str("string1")),
"string1"
)
}
"ignore extra record fields" in {
val schema = field[Int]("relevant")
val json = Json.obj("relevant" -> Json.num(1), "irrelevant" -> Json.num(0))
val decoded = decodeJson(schema, json)
decoded match {
case Valid(n) => assert(n == 1)
case Invalid(errors) => fail(errors.toString())
}
val encoded = encodeJson(schema, 1)
assert(encoded == Json.obj("relevant" -> Json.num(1)))
}
"encoding and decoding optional field with default value, when field is present" in {
val schema = optFieldWithDefault[Int]("value", 42)
checkRoundTrip(
schema,
Json.obj("value" -> Json.num(1)),
1
)
}
"decoding optional field with default value fallbacks to default value when absent" in {
val schema = optFieldWithDefault[Int]("value", 42)
assert(decodeJson(schema, Json.obj()) == Valid(42))
}
"encoding optional field with default value always emits the field" in {
val schema = optFieldWithDefault[Int]("value", 42)
assert(encodeJson(schema, 42) == Json.obj("value" -> Json.num(42)))
}
"decoding optional field with default value fails if field if present but invalid" in {
val schema = optFieldWithDefault[Int]("value", 42)
val invalidJson = Json.obj("value" -> Json.str("one"))
assert(decodeJson(schema, invalidJson).isInstanceOf[Invalid])
}
def checkRoundTrip[A](schema: JsonSchema[A], json: Json.Json, decoded: A) =
decodeJson(schema, json) match {
case Valid(a) =>
assert(a == decoded && encodeJson(schema, a) == json)
case Invalid(errors) =>
fail(errors.mkString(". "))
}
def checkDecodingFailure[A](
schema: JsonSchema[A],
json: Json.Json,
expectedErrors: Seq[String]
) =
decodeJson(schema, json) match {
case Valid(_) => fail("Expected decoding failure")
case Invalid(errors) => assert(errors == expectedErrors)
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0640"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "EC9A2514F036BD8E4243236B"
BuildableName = "libPods-MJExtension.a"
BlueprintName = "Pods-MJExtension"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
</Testables>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hudi.common.bloom;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Unit tests {@link SimpleBloomFilter} and {@link HoodieDynamicBoundedBloomFilter}.
*/
public class TestBloomFilter {
// name attribute is optional, provide a unique name for test
// multiple parameters, uses Collection<Object[]>
public static List<Arguments> bloomFilterTypeCodes() {
return Arrays.asList(
Arguments.of(BloomFilterTypeCode.SIMPLE.name()),
Arguments.of(BloomFilterTypeCode.DYNAMIC_V0.name())
);
}
@ParameterizedTest
@MethodSource("bloomFilterTypeCodes")
public void testAddKey(String typeCode) {
List<String> inputs;
int[] sizes = {100, 1000, 10000};
for (int size : sizes) {
inputs = new ArrayList<>();
BloomFilter filter = getBloomFilter(typeCode, size, 0.000001, size * 10);
for (int i = 0; i < size; i++) {
String key = UUID.randomUUID().toString();
inputs.add(key);
filter.add(key);
}
for (java.lang.String key : inputs) {
assertTrue(filter.mightContain(key), "Filter should have returned true for " + key);
}
for (int i = 0; i < 100; i++) {
String randomKey = UUID.randomUUID().toString();
if (inputs.contains(randomKey)) {
assertTrue(filter.mightContain(randomKey), "Filter should have returned true for " + randomKey);
}
}
}
}
@ParameterizedTest
@MethodSource("bloomFilterTypeCodes")
public void testSerialize(String typeCode) {
List<String> inputs;
int[] sizes = {100, 1000, 10000};
for (int size : sizes) {
inputs = new ArrayList<>();
BloomFilter filter = getBloomFilter(typeCode, size, 0.000001, size * 10);
for (int i = 0; i < size; i++) {
String key = UUID.randomUUID().toString();
inputs.add(key);
filter.add(key);
}
String serString = filter.serializeToString();
BloomFilter recreatedBloomFilter = BloomFilterFactory
.fromString(serString, typeCode);
for (String key : inputs) {
assertTrue(recreatedBloomFilter.mightContain(key), "Filter should have returned true for " + key);
}
}
}
BloomFilter getBloomFilter(String typeCode, int numEntries, double errorRate, int maxEntries) {
if (typeCode.equalsIgnoreCase(BloomFilterTypeCode.SIMPLE.name())) {
return BloomFilterFactory.createBloomFilter(numEntries, errorRate, -1, typeCode);
} else {
return BloomFilterFactory.createBloomFilter(numEntries, errorRate, maxEntries, typeCode);
}
}
}
| {
"pile_set_name": "Github"
} |
require('../../modules/es6.symbol');
module.exports = require('../../modules/_core').Symbol['for'];
| {
"pile_set_name": "Github"
} |
/*
* The Sleuth Kit
*
* Contact: Brian Carrier [carrier <at> sleuthkit [dot] org]
* Copyright (c) 2010-2012 Basis Technology Corporation. All Rights
* reserved.
*
* This software is distributed under the Common Public License 1.0
*/
/**
* \file TskImgDB.cpp
* Some common defines used by the framework data model.
*/
#include "TskImgDB.h"
/// Default constructor
TskImgDB::TskImgDB()
{
}
/// Destructor
TskImgDB::~TskImgDB()
{
}
void TskImgDB::storeParObjId(const int64_t & fsObjId, const TSK_FS_FILE * fs_file, const int64_t & objId) {
map<TSK_INUM_T, map<uint32_t, int64_t> > &fsMap = m_parentDirIdCache[fsObjId];
//store only if does not exist -- otherwise '..' and '.' entries will overwrite
if (fsMap.count(fs_file->name->meta_addr) == 0) {
fsMap[fs_file->name->meta_addr][fs_file->name->meta_seq] = objId;
}
else {
map<uint32_t, int64_t> &fileMap = fsMap[fs_file->name->meta_addr];
if (fileMap.count(fs_file->name->meta_seq) == 0) {
fileMap[fs_file->name->meta_seq] = objId;
}
}
}
int64_t TskImgDB::findParObjId(const TSK_FS_FILE * fs_file, const int64_t & fsObjId) {
//get from cache by parent meta addr, if available
map<TSK_INUM_T, map<uint32_t, int64_t> > &fsMap = m_parentDirIdCache[fsObjId];
if (fsMap.count(fs_file->name->par_addr) > 0) {
map<uint32_t, int64_t> &fileMap = fsMap[fs_file->name->par_addr];
if (fileMap.count(fs_file->name->par_seq) > 0) {
return fileMap[fs_file->name->par_seq];
}
}
return getFileId(fsObjId, fs_file->name->par_addr);
}
TskBlackboardAttribute TskImgDB::createAttribute(uint64_t artifactID, int attributeTypeID, uint64_t objectID, string moduleName, string context,
TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE valueType, int valueInt, uint64_t valueLong, double valueDouble,
string valueString, vector<unsigned char> valueBytes){
return TskBlackboardAttribute(artifactID, attributeTypeID, objectID, moduleName, context,
valueType, valueInt, valueLong, valueDouble, valueString, valueBytes);
}
TskBlackboardArtifact TskImgDB::createArtifact(uint64_t artifactID, uint64_t objID, int artifactTypeID){
return TskBlackboardArtifact(artifactID, objID, artifactTypeID);
}
map<int, TskArtifactNames> TskImgDB::getAllArtifactTypes(){
return TskBlackboard::getAllArtifactTypes();
}
map<int, TskAttributeNames> TskImgDB::getAllAttributeTypes(){
return TskBlackboard::getAllAttributeTypes();
}
| {
"pile_set_name": "Github"
} |
require('../../modules/es6.number.max-safe-integer');
module.exports = 0x1fffffffffffff; | {
"pile_set_name": "Github"
} |
#!/usr/bin/perl
# This file contains an asPHP function for each Node subclass in the S2 compiler.
# If new nodes are added to the S2 compiler in future, this will need to be updated.
package S2::Node;
sub asPHP {
die "asPHP not implemented for $_[0]";
}
sub asPHP_bool {
my ($this, $bp, $o) = @_;
my $ck = $S2::CUR_COMPILER->{'checker'};
my $s2type = $this->getType($ck);
# already boolean
if ($s2type->equals($S2::Type::BOOL) || $s2type->equals($S2::Type::INT)) {
$this->asPHP($bp, $o);
return;
}
# S2 semantics and perl semantics differ ("0" is true in S2)
if ($s2type->equals($S2::Type::STRING)) {
$o->write("((");
$this->asPHP($bp, $o);
$o->write(") !== '')");
return;
}
# is the object defined?
if ($s2type->isSimple()) {
$o->write("\$this->is_object_defined(");
$this->asPHP($bp, $o);
$o->write(")");
return;
}
# does the array have elements?
if ($s2type->isArrayOf() || $s2type->isHashOf()) {
$o->write("(!empty(");
$this->asPHP($bp, $o);
$o->write("))");
return;
}
S2::error($this, "Unhandled internal case for NodeTerm::asPHP_bool()");
}
package S2::NodeArguments;
sub asPHP {
my ($this, $bp, $o, $make_array) = @_;
$make_array = 1 unless defined($make_array);
$o->write("array(") if $make_array;
my $didFirst = 0;
foreach my $n (@{$this->{'args'}}) {
$o->write(", ") if $didFirst++;
$n->asPHP($bp, $o);
}
$o->write(")") if $make_array;
}
package S2::NodeArrayLiteral;
sub asPHP {
my ($this, $bp, $o) = @_;
$o->writeln("array(");
$o->tabIn();
my $size = scalar @{$this->{'vals'}};
for (my $i=0; $i<$size; $i++) {
$o->tabwrite("");
if ($this->{'isHash'}) {
$this->{'keys'}->[$i]->asPHP($bp, $o);
$o->write(" => ");
}
$this->{'vals'}->[$i]->asPHP($bp, $o);
$o->writeln(",");
}
$o->tabOut();
$o->tabwrite(")");
}
package S2::NodeAssignExpr;
sub asPHP {
my ($this, $bp, $o) = @_;
$this->{'lhs'}->asPHP($bp, $o);
$o->write(" = ");
$this->{'rhs'}->asPHP($bp, $o);
}
package S2::NodeBranchStmt;
sub asPHP {
my ($this, $bp, $o) = @_;
if ($this->{type} == $S2::TokenKeyword::BREAK) {
$o->tabwriteln("break;");
}
else {
$o->tabwriteln("continue;");
}
}
package S2::NodeClass;
sub asPHP {
my ($this, $bp, $o) = @_;
# {TODO}
}
package S2::NodeClassVarDecl;
sub asPHP {
my ($this, $bp, $o) = @_;
# {TODO}
}
package S2::NodeCondExpr;
sub asPHP {
my ($this, $bp, $o) = @_;
$o->write("(");
$this->{'test_expr'}->asPHP_bool($bp, $o);
$o->write(" ? ");
$this->{'true_expr'}->asPHP($bp, $o);
$o->write(" : ");
$this->{'false_expr'}->asPHP($bp, $o);
$o->write(")");
}
package S2::NodeDeleteStmt;
sub asPHP {
my ($this, $bp, $o) = @_;
$o->tabwrite("unset(");
$this->{'var'}->asPHP($bp, $o);
$o->writeln(");");
}
package S2::NodeEqExpr;
sub asPHP {
my ($this, $bp, $o) = @_;
$this->{'lhs'}->asPHP($bp, $o);
if ($this->{'op'} == $S2::TokenPunct::EQ) {
$o->write(" === ");
} else {
$o->write(" !== ");
}
$this->{'rhs'}->asPHP($bp, $o);
}
package S2::NodeExpr;
sub asPHP {
my ($this, $bp, $o) = @_;
$this->{'expr'}->asPHP($bp, $o);
}
package S2::NodeExprStmt;
sub asPHP {
my ($this, $bp, $o) = @_;
$o->tabwrite("");
$this->{'expr'}->asPHP($bp, $o);
$o->writeln(";");
}
package S2::NodeForeachStmt;
sub asPHP {
my ($this, $bp, $o) = @_;
$o->tabwrite("foreach (");
$o->write("$this->get_string_characters(") if ($this->{'isString'});
$this->{'listexpr'}->asPHP($bp, $o);
$o->write(")") if ($this->{'isString'});
$o->write(" as ");
$this->{'vardecl'}->asPHP($bp, $o) if $this->{'vardecl'};
$this->{'varref'}->asPHP($bp, $o) if $this->{'varref'};
if ($this->{'isHash'}) {
$o->write(" => $__dummy");
}
$o->write(") ");
$this->{'stmts'}->asPHP($bp, $o);
$o->newline();
}
package S2::NodeFormals;
# Not called directly during code generation
package S2::NodeFunction;
sub asPHP {
my ($this, $bp, $o) = @_;
$o->tabwriteln("// ".S2::Checker::functionID($this->{classname} ? $this->{classname}->getIdent() : undef, $this->{name}->getIdent(), $this->{formals}));
unless ($this->{'attr'}->{'builtin'}) {
# We recieve our args in a PHP local variable called $funcargs.
# When the function is called, we copy the values therein
# into the local variable array.
my $argnum = 0;
if ($this->{'classname'} && ! $this->{'isCtor'}) {
$o->tabwriteln("\$locals['this'] = \$funcargs[".($argnum++)."];");
}
if ($this->{'formals'}) {
my $nts = $this->{'formals'}->getFormals();
foreach my $nt (@$nts) {
$o->tabwriteln("\$locals['".$bp->decorateLocal($nt->getName(), $this->{'stmts'})."'] = \$funcargs[".($argnum++)."];");
}
}
if ($this->{'stmts'}) {
$this->{'stmts'}->asPHP($bp, $o, 0);
}
}
else {
# Generate a stub for the builtin function
$o->write("\$this->call_builtin_function(\"");
if ($this->{'classname'}) {
$o->write($bp->quoteStringInner($this->{'classname'}));
}
$o->write('", "');
$o->write($bp->quoteStringInner($this->{'name'}->getIdent()).'", $funcargs);');
}
}
package S2::NodeIfStmt;
sub asPHP {
my ($this, $bp, $o) = @_;
# if
$o->tabwrite("if (");
$this->{'expr'}->asPHP_bool($bp, $o);
$o->write(") ");
$this->{'thenblock'}->asPHP($bp, $o);
$o->newline();
# else-if
my $i = 0;
foreach my $expr (@{$this->{'elseifexprs'}}) {
my $block = $this->{'elseifblocks'}->[$i++];
$o->tabwrite("elseif (");
$expr->asPHP_bool($bp, $o);
$o->write(") ");
$block->asPHP($bp, $o);
$o->newline();
}
# else
if ($this->{'elseblock'}) {
$o->tabwrite("else ");
$this->{'elseblock'}->asPHP($bp, $o);
$o->newline();
}
$o->newline();
}
package S2::NodeIncExpr;
sub asPHP {
my ($this, $bp, $o) = @_;
$o->write("(");
if ($this->{'bPre'}) { $o->write($this->{'op'}->getPunct()); }
$this->{'expr'}->asPHP($bp, $o);
if ($this->{'bPost'}) { $o->write($this->{'op'}->getPunct()); }
$o->write(")");
}
package S2::NodeInstanceOf;
sub asPHP {
my ($this, $bp, $o) = @_;
if ($this->{exact}) {
$o->write("((");
$this->{'expr'}->asPHP($bp, $o);
$o->write(")['_type'] === ".$bp->quoteString($this->{qClass}).")");
}
else {
$o->write("\$this->object_isa(");
$this->{'expr'}->asPHP($bp, $o);
$o->write(",".$bp->quoteString($this->{qClass}).")");
}
}
package S2::NodeLayerInfo;
# {TODO}
package S2::NodeLogAndExpr;
sub asPHP {
my ($this, $bp, $o) = @_;
$this->{'lhs'}->asPHP_bool($bp, $o);
$o->write(" && ");
$this->{'rhs'}->asPHP_bool($bp, $o);
}
package S2::NodeLogOrExpr;
sub asPHP {
my ($this, $bp, $o) = @_;
$this->{'lhs'}->asPHP_bool($bp, $o);
$o->write(" || ");
$this->{'rhs'}->asPHP_bool($bp, $o);
}
package S2::NodeNamedType;
# Not called directly during code generation
package S2::NodePrintStmt;
sub asPHP {
my ($this, $bp, $o) = @_;
$o->tabwrite("echo(");
$this->{'expr'}->asPHP($bp, $o);
$o->write(" . \"\\n\"") if $this->{'doNewline'};
$o->writeln(");");
}
package S2::NodeProduct;
sub asPHP {
my ($this, $bp, $o) = @_;
$o->write("floor") if $this->{'op'} == $S2::TokenPunct::DIV;
$o->write("(");
$this->{'lhs'}->asPHP($bp, $o);
if ($this->{'op'} == $S2::TokenPunct::MULT) {
$o->write(" * ");
} elsif ($this->{'op'} == $S2::TokenPunct::DIV) {
$o->write(" / ");
} elsif ($this->{'op'} == $S2::TokenPunct::MOD) {
$o->write(" % ");
}
$this->{'rhs'}->asPHP($bp, $o);
$o->write(")");
}
package S2::NodeProperty;
# {TODO}
package S2::NodePropertyPair;
# {TODO}
package S2::NodePropGroup;
# {TODO}
package S2::NodeRange;
sub asPHP {
my ($this, $bp, $o) = @_;
$o->write("\$this->make_range_array(");
$this->{'lhs'}->asPHP($bp, $o);
$o->write(", ");
$this->{'rhs'}->asPHP($bp, $o);
$o->write(")");
}
package S2::NodeRelExpr;
sub asPHP {
my ($this, $bp, $o) = @_;
$this->{'lhs'}->asPHP($bp, $o);
if ($this->{'op'} == $S2::TokenPunct::LT) {
$o->write(" < ");
}
elsif ($this->{'op'} == $S2::TokenPunct::LTE) {
$o->write(" <= ");
}
elsif ($this->{'op'} == $S2::TokenPunct::GT) {
$o->write(" > ");
}
elsif ($this->{'op'} == $S2::TokenPunct::GTE) {
$o->write(" >= ");
}
$this->{'rhs'}->asPHP($bp, $o);
}
package S2::NodeReturnStmt;
sub asPHP {
my ($this, $bp, $o) = @_;
$o->tabwrite("return");
if ($this->{'expr'}) {
$o->write(" ");
$this->{'expr'}->asPHP($bp, $o);
}
$o->writeln(";");
}
package S2::NodeSet;
# {TODO}
package S2::NodeStmt;
# Abstract class. Never called in code generation.
package S2::NodeStmtBlock;
sub asPHP {
my ($this, $bp, $o, $doCurlies) = @_;
$doCurlies = 1 unless defined $doCurlies;
if ($doCurlies) {
$o->writeln("{");
$o->tabIn();
}
foreach my $ns (@{$this->{'stmtlist'}}) {
$ns->asPHP($bp, $o);
}
if ($doCurlies) {
$o->tabOut();
$o->tabwrite("}");
}
}
package S2::NodeSum;
sub asPHP {
my ($this, $bp, $o) = @_;
$this->{'lhs'}->asPHP($bp, $o);
if ($this->{'myType'} == $S2::Type::STRING) {
$o->write(" . ");
} elsif ($this->{'op'} == $S2::TokenPunct::PLUS) {
$o->write(" + ");
} elsif ($this->{'op'} == $S2::TokenPunct::MINUS) {
$o->write(" - ");
}
$this->{'rhs'}->asPHP($bp, $o);
}
package S2::NodeTerm;
sub asPHP {
my ($this, $bp, $o) = @_;
my $type = $this->{'type'};
if ($type == $S2::NodeTerm::INTEGER) {
$this->{'tokInt'}->asPHP($bp, $o);
return;
}
if ($type == $S2::NodeTerm::STRING) {
if (defined $this->{'nodeString'}) {
$o->write("(");
$this->{'nodeString'}->asPHP($bp, $o);
$o->write(")");
return;
}
if ($this->{'ctorclass'}) {
my $pkg = $bp->getBuiltinPackage() || "S2::Builtin";
$o->write("\$this->construct_object(".$bp->quoteString($this->{'ctorclass'}).", ");
$this->{'tokStr'}->asPHP($bp, $o);
$o->write(")");
return;
}
$this->{'tokStr'}->asPHP($bp, $o);
return;
}
if ($type == $S2::NodeTerm::BOOL) {
$o->write($this->{'boolValue'} ? "TRUE" : "FALSE");
return;
}
if ($type == $S2::NodeTerm::SUBEXPR) {
$o->write("(");
$this->{'subExpr'}->asPHP($bp, $o);
$o->write(")");
return;
}
if ($type == $S2::NodeTerm::ARRAY) {
$this->{'subExpr'}->asPHP($bp, $o);
return;
}
if ($type == $S2::NodeTerm::NEW) {
$o->write("array('_type'=>" .
$bp->quoteString($this->{'newClass'}->getIdent()) .
")");
return;
}
if ($type == $S2::NodeTerm::NEWNULL) {
$o->write("NULL");
return;
}
if ($type == $S2::NodeTerm::REVERSEFUNC) {
if ($this->{'subType'}->isArrayOf()) {
$o->write("array_reverse(");
$this->{'subExpr'}->asPHP($bp, $o);
$o->write(")");
} elsif ($this->{'subType'}->equals($S2::Type::STRING)) {
$o->write("strrev(");
$this->{'subExpr'}->asPHP($bp, $o);
$o->write(")");
}
return;
}
if ($type == $S2::NodeTerm::SIZEFUNC) {
if ($this->{'subType'}->isArrayOf() || $this->{'subType'}->isHashOf()) {
$o->write("count(");
$this->{'subExpr'}->asPHP($bp, $o);
$o->write(")");
}
elsif ($this->{'subType'}->equals($S2::Type::STRING)) {
$o->write("strlen(");
$this->{'subExpr'}->asPHP($bp, $o);
$o->write(")");
}
return;
}
if ($type == $S2::NodeTerm::DEFINEDTEST) {
$o->write("\$this->is_object_defined(");
$this->{'subExpr'}->asPHP($bp, $o);
$o->write(")");
return;
}
if ($type == $S2::NodeTerm::ISNULLFUNC) {
$o->write("(!\$this->is_object_defined(");
$this->{'subExpr'}->asPHP($bp, $o);
$o->write("))");
return;
}
if ($type == $S2::NodeTerm::VARREF) {
$this->{'var'}->asPHP($bp, $o);
return;
}
if ($type == $S2::NodeTerm::OBJ_INTERPOLATE) {
$o->write("\$this->stringify_object(");
$this->{'var'}->asPHP($bp, $o);
$o->write(", '$this->{'objint_method'}()'");
$o->write(", '$this->{'funcClass'}'");
$o->write(")");
return;
}
if ($type == $S2::NodeTerm::FUNCCALL || $type == $S2::NodeTerm::METHCALL) {
# builtin functions can be optimized.
if ($this->{'funcBuiltin'}) {
# these built-in functions can be inlined.
if ($this->{'funcID'} eq "string(int)") {
$this->{'funcArgs'}->asPHP($bp, $o, 0);
return;
}
if ($this->{'funcID'} eq "int(string)") {
# cast from string to int by adding zero to it
$o->write("floor(");
$this->{'funcArgs'}->asPHP($bp, $o, 0);
$o->write("+0)");
return;
}
$o->write("\$this->call_builtin_function(\"");
if ($this->{'funcClass'}) {
$o->write($bp->quoteStringInner($this->{'funcClass'}));
}
$o->write('", "');
$o->write($bp->quoteStringInner($this->{'funcIdent'}->getIdent()).'"');
} else {
if ($type == $S2::NodeTerm::METHCALL && ! { map { $_=>1 } qw(string int bool) }->{$this->{'funcClass'}}) {
$o->write("\$this->call_method(");
$this->{var}->asPHP($bp, $o);
$o->write(",");
$o->write($bp->quoteString($this->{'funcID_noclass'}));
$o->write(",");
$o->write($bp->quoteString($this->{'funcClass'}));
$o->write($this->{'var'}->isSuper() ? ",TRUE" : ",FALSE");
$o->write(",");
}
else {
$o->write("\$this->call_function(");
$o->write($bp->quoteString($this->{'funcID'}));
$o->write(",");
}
}
$o->write("array(");
# "this" pointer
if ($type == $S2::NodeTerm::METHCALL) {
$this->{'var'}->asPHP($bp, $o);
$o->write(", ");
}
$this->{'funcArgs'}->asPHP($bp, $o, 0);
$o->write("))");
return;
}
die "Unknown term type";
}
package S2::NodeText;
# Not used directly during code generation
package S2::NodeType;
# Not used directly during code generation
package S2::NodeTypeCastOp;
sub asPHP {
my ($this, $bp, $o) = @_;
if (! $this->{downcast}) {
$this->{expr}->asPHP($bp, $o);
return;
}
# For downcasts, need to call function at runtime to ensure the
# object is of the correct type.
$o->write("\$this->downcast_object(");
$this->{'expr'}->asPHP($bp, $o);
$o->write(",".$bp->quoteString($this->{toClass}).")");
}
package S2::NodeUnaryExpr;
sub asPHP {
my ($this, $bp, $o) = @_;
$o->write("(");
if ($this->{'bNot'}) { $o->write("! "); }
if ($this->{'bNegative'}) { $o->write("-"); }
$this->{'expr'}->asPHP($bp, $o);
$o->write(")");
}
package S2::NodeUnnecessary;
sub asPHP {
my ($this, $bp, $o) = @_;
# Do nothing for PHP output.
}
package S2::NodeVarDecl;
sub asPHP {
my ($this, $bp, $o) = @_;
# PHP doesn't have declarations, so we compile this just like a VarRef
$o->write("\$locals[".$bp->quoteString($bp->decorateLocal($this->{'nt'}->getName(), $this->{owningScope}))."]");
}
package S2::NodeVarDeclStmt;
sub asPHP {
my ($this, $bp, $o) = @_;
# Since PHP doesn't have declarations, we just initialize the variable.
$o->tabwrite("");
$this->{'nvd'}->asPHP($bp, $o);
if ($this->{'expr'}) {
$o->write(" = ");
$this->{'expr'}->asPHP($bp, $o);
} else {
my $t = $this->{'nvd'}->getType();
if ($t->equals($S2::Type::STRING)) {
$o->write(" = \"\"");
}
elsif ($t->equals($S2::Type::INT)) {
$o->write(" = 0");
}
elsif ($t->equals($S2::Type::BOOL)) {
$o->write(" = FALSE");
}
elsif ($t->isArrayOf || $t->isHashOf) {
$o->write(" = array()");
}
else {
$o->write(" = NULL");
}
}
$o->writeln(";");
}
package S2::NodeVarRef;
sub asPHP {
my ($this, $bp, $o) = @_;
if ($this->{'type'} == $LOCAL) {
$o->write("\$locals");
} elsif ($this->{'type'} == $OBJECT) {
$o->write("\$locals['this']");
} elsif ($this->{'type'} == $PROPERTY) {
$o->write("\$this->properties");
$first = 0;
}
my $first = 1;
foreach my $lev (@{$this->{'levels'}}) {
if ($first && $this->{'type'} == $LOCAL) {
$o->write("['".$bp->decorateLocal($lev->{'var'}, $this->{owningScope})."']");
}
else {
$o->write("['".$lev->{'var'}."']");
}
foreach my $d (@{$lev->{'derefs'}}) {
$o->write("["); # [ or {
$d->{'expr'}->asPHP($bp, $o);
$o->write("]");
}
$first = 0;
}
if ($this->{'useAsString'}) {
$o->write("['as_string']");
}
}
package S2::TokenStringLiteral;
sub asPHP {
my ($this, $bp, $o) = @_;
$o->write($bp->quoteString($this->{'text'}));
}
package S2::TokenIntegerLiteral;
sub asPHP {
my ($this, $bp, $o) = @_;
$o->write($this->{'chars'});
}
1;
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 1eb18b8db6c77f04c96874806a37143d
folderAsset: yes
timeCreated: 1466714102
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
<?php
return [
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages.
|
*/
'accepted' => 'O campo :attribute deve ser aceito.',
'active_url' => 'O campo :attribute deve conter uma URL válida.',
'after' => 'O campo :attribute deve conter uma data posterior a :date.',
'after_or_equal' => 'O campo :attribute deve conter uma data superior ou igual a :date.',
'alpha' => 'O campo :attribute deve conter apenas letras.',
'alpha_dash' => 'O campo :attribute deve conter apenas letras, números e traços.',
'alpha_num' => 'O campo :attribute deve conter apenas letras e números .',
'array' => 'O campo :attribute deve conter um array.',
'before' => 'O campo :attribute deve conter uma data anterior a :date.',
'before_or_equal' => 'O campo :attribute deve conter uma data inferior ou igual a :date.',
'between' => [
'numeric' => 'O campo :attribute deve conter um número entre :min e :max.',
'file' => 'O campo :attribute deve conter um arquivo de :min a :max kilobytes.',
'string' => 'O campo :attribute deve conter entre :min a :max caracteres.',
'array' => 'O campo :attribute deve conter de :min a :max itens.',
],
'boolean' => 'O campo :attribute deve conter o valor verdadeiro ou falso.',
'confirmed' => 'A confirmação para o campo :attribute não coincide.',
'date' => 'O campo :attribute não contém uma data válida.',
'date_equals' => 'O campo :attribute deve ser uma data igual a :date.',
'date_format' => 'A data informada para o campo :attribute não respeita o formato :format.',
'different' => 'Os campos :attribute e :other devem conter valores diferentes.',
'digits' => 'O campo :attribute deve conter :digits dígitos.',
'digits_between' => 'O campo :attribute deve conter entre :min a :max dígitos.',
'dimensions' => 'O valor informado para o campo :attribute não é uma dimensão de imagem válida.',
'distinct' => 'O campo :attribute contém um valor duplicado.',
'email' => 'O campo :attribute não contém um endereço de email válido.',
'ends_with' => 'O campo :attribute deve terminar com um dos seguintes valores: :values',
'exists' => 'O valor selecionado para o campo :attribute é inválido.',
'file' => 'O campo :attribute deve conter um arquivo.',
'filled' => 'O campo :attribute é obrigatório.',
'gt' => [
'numeric' => 'O campo :attribute deve ser maior que :value.',
'file' => 'O arquivo :attribute deve ser maior que :value kilobytes.',
'string' => 'O campo :attribute deve ser maior que :value caracteres.',
'array' => 'O campo :attribute deve ter mais que :value itens.',
],
'gte' => [
'numeric' => 'O campo :attribute deve ser maior ou igual a :value.',
'file' => 'O arquivo :attribute deve ser maior ou igual a :value kilobytes.',
'string' => 'O campo :attribute deve ser maior ou igual a :value caracteres.',
'array' => 'O campo :attribute deve ter :value itens ou mais.',
],
'image' => 'O campo :attribute deve conter uma imagem.',
'in' => 'O campo :attribute não contém um valor válido.',
'in_array' => 'O campo :attribute não existe em :other.',
'integer' => 'O campo :attribute deve conter um número inteiro.',
'ip' => 'O campo :attribute deve conter um IP válido.',
'ipv4' => 'O campo :attribute deve conter um IPv4 válido.',
'ipv6' => 'O campo :attribute deve conter um IPv6 válido.',
'json' => 'O campo :attribute deve conter uma string JSON válida.',
'lt' => [
'numeric' => 'O campo :attribute deve ser menor que :value.',
'file' => 'O arquivo :attribute ser menor que :value kilobytes.',
'string' => 'O campo :attribute deve ser menor que :value caracteres.',
'array' => 'O campo :attribute deve ter menos que :value itens.',
],
'lte' => [
'numeric' => 'O campo :attribute deve ser menor ou igual a :value.',
'file' => 'O arquivo :attribute ser menor ou igual a :value kilobytes.',
'string' => 'O campo :attribute deve ser menor ou igual a :value caracteres.',
'array' => 'O campo :attribute não deve ter mais que :value itens.',
],
'max' => [
'numeric' => 'O campo :attribute não pode conter um valor superior a :max.',
'file' => 'O campo :attribute não pode conter um arquivo com mais de :max kilobytes.',
'string' => 'O campo :attribute não pode conter mais de :max caracteres.',
'array' => 'O campo :attribute deve conter no máximo :max itens.',
],
'mimes' => 'O campo :attribute deve conter um arquivo do tipo: :values.',
'mimetypes' => 'O campo :attribute deve conter um arquivo do tipo: :values.',
'min' => [
'numeric' => 'O campo :attribute deve conter um número superior ou igual a :min.',
'file' => 'O campo :attribute deve conter um arquivo com no mínimo :min kilobytes.',
'string' => 'O campo :attribute deve conter no mínimo :min caracteres.',
'array' => 'O campo :attribute deve conter no mínimo :min itens.',
],
'not_in' => 'O campo :attribute contém um valor inválido.',
'not_regex' => 'O formato do valor :attribute é inválido.',
'numeric' => 'O campo :attribute deve conter um valor numérico.',
'password' => 'A senha está incorreta.',
'present' => 'O campo :attribute deve estar presente.',
'regex' => 'O formato do valor informado no campo :attribute é inválido.',
'required' => 'O campo :attribute é obrigatório.',
'required_if' => 'O campo :attribute é obrigatório quando o valor do campo :other é igual a :value.',
'required_unless' => 'O campo :attribute é obrigatório a menos que :other esteja presente em :values.',
'required_with' => 'O campo :attribute é obrigatório quando :values está presente.',
'required_with_all' => 'O campo :attribute é obrigatório quando um dos :values está presente.',
'required_without' => 'O campo :attribute é obrigatório quando :values não está presente.',
'required_without_all' => 'O campo :attribute é obrigatório quando nenhum dos :values está presente.',
'same' => 'Os campos :attribute e :other devem conter valores iguais.',
'size' => [
'numeric' => 'O campo :attribute deve conter o número :size.',
'file' => 'O campo :attribute deve conter um arquivo com o tamanho de :size kilobytes.',
'string' => 'O campo :attribute deve conter :size caracteres.',
'array' => 'O campo :attribute deve conter :size itens.',
],
'starts_with' => 'O campo :attribute deve começar com um dos seguintes valores: :values',
'string' => 'O campo :attribute deve ser uma string.',
'timezone' => 'O campo :attribute deve conter um fuso horário válido.',
'unique' => 'O valor informado para o campo :attribute já está em uso.',
'uploaded' => 'Falha no Upload do arquivo :attribute.',
'url' => 'O formato da URL informada para o campo :attribute é inválido.',
'uuid' => 'O campo :attribute deve ser um UUID válido.',
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
'attributes' => [
'address' => 'endereço',
'age' => 'idade',
'body' => 'conteúdo',
'city' => 'cidade',
'country' => 'país',
'date' => 'data',
'day' => 'dia',
'description' => 'descrição',
'excerpt' => 'resumo',
'first_name' => 'primeiro nome',
'gender' => 'gênero',
'hour' => 'hora',
'last_name' => 'sobrenome',
'message' => 'mensagem',
'minute' => 'minuto',
'mobile' => 'celular',
'month' => 'mês',
'name' => 'nome',
'password_confirmation' => 'confirmação da senha',
'password' => 'senha',
'phone' => 'telefone',
'second' => 'segundo',
'sex' => 'sexo',
'state' => 'estado',
'subject' => 'assunto',
'text' => 'texto',
'time' => 'hora',
'title' => 'título',
'username' => 'usuário',
'year' => 'ano',
'email' => 'e-mail',
'remember' => 'lembrar-me',
],
];
| {
"pile_set_name": "Github"
} |
# $Id: Makefile.kmk $
## @file
# Sub-Makefile for the New VGA BIOS ROM.
#
#
# Copyright (C) 2012 Oracle Corporation
#
# This file is part of VirtualBox Open Source Edition (OSE), as
# available from http://www.virtualbox.org. This file is free software;
# you can redistribute it and/or modify it under the terms of the GNU
# General Public License (GPL) as published by the Free Software
# Foundation, in version 2 as it comes in the "COPYING" file of the
# VirtualBox OSE distribution. VirtualBox OSE is distributed in the
# hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
#
SUB_DEPTH = ../../../../..
include $(KBUILD_PATH)/subheader.kmk
ifdef VBOX_WITH_OPEN_WATCOM
#
# VBoxVgaBios - The VGA BIOS.
#
MISCBINS += VBoxVgaBios
VBoxVgaBios_TEMPLATE = VBoxBios
VBoxVgaBios_ASFLAGS = -0
VBoxVgaBios_DEFS = VBE
VBoxVgaBios_SOURCES = \
vgarom.asm \
vberom.asm \
vgabios.c \
vbe.c
VBoxVgaBios_LDFLAGS = \
output raw offset=0xC0000 \
order \
clname CODE \
segment VGAROM segaddr=0xC000 \
segment _TEXT segaddr=0xC000 offset=0xA00 \
segment VBE32 segaddr=0xC000 offset=0x4600 \
clname DATA \
segment _DATA segaddr=0xC000 offset=0x4800 \
#
# Updates the alternative source file.
#
update-vgabios-source +| $(PATH_SUB_CURRENT)/VBoxVgaBiosAlternative.asm $(PATH_SUB_CURRENT)/VBoxVgaBiosAlternative.md5sum: \
$$(VBoxVgaBios_1_TARGET) \
$(VBOX_MAKE_ALTERNATIVE_SOURCE) \
$(VBOX_VBOXCMP)
if1of ($(KBUILD_TYPE), release)
$(VBOX_MAKE_ALTERNATIVE_SOURCE) \
--bios-image $< \
--bios-map $(basename $<).map \
--bios-sym $(basename $<).sym \
--bios-type vga \
--output $(VBoxVgaBios_0_OUTDIR)/VBoxVgaBiosAlternative.asm
$(QUIET)yasm -f bin -o $(VBoxVgaBios_0_OUTDIR)/VBoxVgaBiosAlternative.bin $(VBoxVgaBios_0_OUTDIR)/VBoxVgaBiosAlternative.asm
$(VBOX_VBOXCMP) $< $(VBoxVgaBios_0_OUTDIR)/VBoxVgaBiosAlternative.bin
$(CP) --changed -- $(VBoxVgaBios_0_OUTDIR)/VBoxVgaBiosAlternative.asm $(PATH_ROOT)/src/VBox/Devices/Graphics/BIOS/VBoxVgaBiosAlternative.asm
$(REDIRECT) -C $(dir $(VBoxVgaBios_1_TARGET)) -- \
$(MD5SUM_EXT) -bo $(VBoxVgaBios_0_OUTDIR)/VBoxVgaBiosAlternative.md5sum $(notdir $(VBoxVgaBios_1_TARGET))
$(CP) --changed -- $(VBoxVgaBios_0_OUTDIR)/VBoxVgaBiosAlternative.md5sum $(PATH_ROOT)/src/VBox/Devices/Graphics/BIOS/VBoxVgaBiosAlternative.md5sum
$(RM) -f -- $(VBoxVgaBios_0_OUTDIR)/VBoxVgaBiosAlternative.asm $(VBoxVgaBios_0_OUTDIR)/VBoxVgaBiosAlternative.bin $(VBoxVgaBios_0_OUTDIR)/VBoxVgaBiosAlternative.md5sum
else
$(QUIET)$(ECHO) "Fatal error: Can only update VBoxVgaBiosAlternative.asm/md5sum with a release build."
$(QUIET)exit 1
endif
endif # VBOX_WITH_OPEN_WATCOM
#
# The library containing the VGA BIOS image.
#
LIBRARIES += VgaBiosBin
VgaBiosBin_TEMPLATE = VBOXR3
VgaBiosBin_DEFS = IN_VBOXDD2
VgaBiosBin_SOURCES = \
$(VgaBiosBin_0_OUTDIR)/VgaBiosBin.c
VgaBiosBin_DEPS = \
$(VgaBiosBin_0_OUTDIR)/vbetables.h
VgaBiosBin_CLEAN = \
$(VgaBiosBin_0_OUTDIR)/VgaBiosBin.c \
$(VgaBiosBin_0_OUTDIR)/vbetables.h
ifdef VBOX_WITH_OPEN_WATCOM
$$(VgaBiosBin_0_OUTDIR)/VgaBiosBin.c: $$(VBoxVgaBios_1_TARGET) $(VBOX_BIN2C) | $$(dir $$@)
$(call MSG_TOOL,bin2c,VgaBiosBin,$<,$@)
$(QUIET)$(VBOX_BIN2C) -min 32 -max 36 -mask 0x0fff -ascii -export VgaBiosBinary $< $@
else
VgaBiosBin_CLEAN += $(VgaBiosBin_0_OUTDIR)/VBoxVgaBios.rom
$$(VgaBiosBin_0_OUTDIR)/VgaBiosBin.c + $$(VgaBiosBin_0_OUTDIR)/VBoxVgaBios.rom: \
$(PATH_SUB_CURRENT)/VBoxVgaBiosAlternative.asm \
$(PATH_SUB_CURRENT)/VBoxVgaBiosAlternative.md5sum \
$(VBOX_BIN2C) | $$(dir $$@)
$(call MSG_TOOL,bin2c,VgaBiosBin,$<,$@)
$(QUIET)yasm -f bin -o $(VgaBiosBin_0_OUTDIR)/VBoxVgaBios.rom $<
$(QUIET)$(REDIRECT) -C $(VgaBiosBin_0_OUTDIR) -- \
$(MD5SUM_EXT) -c $(basename $<).md5sum
$(QUIET)$(VBOX_BIN2C) -min 32 -max 36 -mask 0x0fff -ascii -export VgaBiosBinary $(VgaBiosBin_0_OUTDIR)/VBoxVgaBios.rom $@
$(QUIET)$(RM) -f -- $$(VgaBiosBin_0_OUTDIR)/VBoxVgaBios.rom
endif
# Rule for making the vbetables.h that DevVGA uses.
$$(VgaBiosBin_0_OUTDIR)/vbetables.h: $(MAKEFILE_CURRENT) $$(vbetables-gen_1_TARGET) | $$(dir $$@)
$(QUIET)$(REDIRECT) -wo $@ -- $(vbetables-gen_1_TARGET)
#
# The VBE tables.
#
BLDPROGS += vbetables-gen
vbetables-gen_TEMPLATE = VBOXBLDPROG
vbetables-gen_SOURCES = vbetables-gen.c
vbetables-gen_CLEAN = $(vbetables-gen)
#
# The VGA BIOS Logo.
#
LIBRARIES += VgaDefBiosLogo
VgaDefBiosLogo_TEMPLATE = VBOXR3
VgaDefBiosLogo_INCS = $(VBOX_PATH_DEVICES_SRC)
VgaDefBiosLogo_SOURCES = $(VgaDefBiosLogo_0_OUTDIR)/VgaDefBiosLogo.c
VgaDefBiosLogo_CLEAN = $(VgaDefBiosLogo_0_OUTDIR)/VgaDefBiosLogo.c
# Rule for making the bios logo.
$$(VgaDefBiosLogo_0_OUTDIR)/VgaDefBiosLogo.c: $(VBOX_BRAND_BIOS_LOGO) $(VBOX_BIN2C) | $$(dir $$@)
$(call MSG_TOOL,bin2c,VgaDefBiosLogo,$<,$@)
$(QUIET)$(VBOX_BIN2C) VgaDefBiosLogo $< $@
include $(FILE_KBUILD_SUB_FOOTER)
| {
"pile_set_name": "Github"
} |
#!/usr/bin/perl -T
# nagios: -epn
#
# Author: Hari Sekhon
# Date: 2014-05-26 19:34:51 +0100 (Mon, 26 May 2014)
#
# https://github.com/harisekhon/nagios-plugins
#
# License: see accompanying LICENSE file
#
$DESCRIPTION = "Nagios Plugin to check whether a Neo4j instance allows a remote shell using the Neo4j REST API
Tested on Neo4j 1.9, 2.0, 2.3, 3.0, 3.1, 3.2";
$VERSION = "0.3";
use strict;
use warnings;
BEGIN {
use File::Basename;
use lib dirname(__FILE__) . "/lib";
}
use HariSekhonUtils;
#use Data::Dumper;
use JSON;
use LWP::Simple '$ua';
$ua->agent("Hari Sekhon $progname version $main::VERSION");
set_port_default(7474);
env_creds("Neo4j");
my $expect_enabled;
%options = (
%hostoptions,
%useroptions,
%ssloptions,
);
if($progname =~ /enabled/){
$expect_enabled = 1;
} else {
$options{"expect-enabled"} = [ \$expect_enabled, "Check remote shell is enabled instead of disabled" ];
}
get_options();
$host = validate_host($host);
$port = validate_port($port);
$user = validate_user($user);
$password = validate_password($password);
validate_ssl();
vlog2;
set_timeout();
$status = "OK";
my $url_prefix = "http://$host:$port";
my $url = "$url_prefix/db/manage/server/jmx/domain/org.neo4j/instance%3Dkernel%230%2Cname%3DConfiguration";
my $content = curl $url, "Neo4j", $user, $password;
my $json;
try {
$json = decode_json($content);
};
catch {
quit "CRITICAL", "invalid json returned by Neo4j at '$url_prefix'. Try with -vvv to see full output";
};
#vlog3(Dumper($json));
isArray($json) or quit "UNKNOWN", "output returned by Neo4j is not structured in output array. $nagios_plugins_support_msg_api";
defined($json->[0]->{"attributes"}) or quit "UNKNOWN", "'attributes' field not returned by Neo4j! $nagios_plugins_support_msg_api";
isArray($json->[0]->{"attributes"}) or quit "UNKNOWN", "attributes field returned by Neo4j is not an array as expected! $nagios_plugins_support_msg_api";
my $remote_shell_enabled;
foreach my $item (@{$json->[0]{"attributes"}}){
defined($item->{"name"}) or quit "UNKNOWN", "'name' field not returned for items in 'attributes' by Neo4j! $nagios_plugins_support_msg_api";
next unless $item->{"name"} =~ /^remote_shell_enabled|dbms.shell.enabled$/;
defined($item->{"value"}) or quit "UNKNOWN", "'value' field not returned for items in 'attributes' by Neo4j! $nagios_plugins_support_msg_api";
$remote_shell_enabled = $item->{"value"};
last;
}
defined($remote_shell_enabled) or quit "UNKNOWN", "failed to find remote_shell_enabled in output from Neo4j. $nagios_plugins_support_msg_api";
$msg = "Neo4j ";
if($remote_shell_enabled){
$msg .= "remote shell enabled";
unless($expect_enabled){
critical;
$msg = uc $msg;
}
} else {
$msg .= "remote shell is disabled";
if($expect_enabled){
critical;
$msg = uc $msg;
}
}
quit $status, $msg;
| {
"pile_set_name": "Github"
} |
#ifndef CEREAL_RAPIDXML_PRINT_HPP_INCLUDED
#define CEREAL_RAPIDXML_PRINT_HPP_INCLUDED
// Copyright (C) 2006, 2009 Marcin Kalicinski
// Version 1.13
// Revision $DateTime: 2009/05/13 01:46:17 $
#include "rapidxml.hpp"
// Only include streams if not disabled
#ifndef CEREAL_RAPIDXML_NO_STREAMS
#include <ostream>
#include <iterator>
#endif
namespace cereal {
namespace rapidxml
{
///////////////////////////////////////////////////////////////////////
// Printing flags
const int print_no_indenting = 0x1; //!< Printer flag instructing the printer to suppress indenting of XML. See print() function.
///////////////////////////////////////////////////////////////////////
// Internal
//! \cond internal
namespace internal
{
///////////////////////////////////////////////////////////////////////////
// Internal character operations
// Copy characters from given range to given output iterator
template<class OutIt, class Ch>
inline OutIt copy_chars(const Ch *begin, const Ch *end, OutIt out)
{
while (begin != end)
*out++ = *begin++;
return out;
}
// Copy characters from given range to given output iterator and expand
// characters into references (< > ' " &)
template<class OutIt, class Ch>
inline OutIt copy_and_expand_chars(const Ch *begin, const Ch *end, Ch noexpand, OutIt out)
{
while (begin != end)
{
if (*begin == noexpand)
{
*out++ = *begin; // No expansion, copy character
}
else
{
switch (*begin)
{
case Ch('<'):
*out++ = Ch('&'); *out++ = Ch('l'); *out++ = Ch('t'); *out++ = Ch(';');
break;
case Ch('>'):
*out++ = Ch('&'); *out++ = Ch('g'); *out++ = Ch('t'); *out++ = Ch(';');
break;
case Ch('\''):
*out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('p'); *out++ = Ch('o'); *out++ = Ch('s'); *out++ = Ch(';');
break;
case Ch('"'):
*out++ = Ch('&'); *out++ = Ch('q'); *out++ = Ch('u'); *out++ = Ch('o'); *out++ = Ch('t'); *out++ = Ch(';');
break;
case Ch('&'):
*out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('m'); *out++ = Ch('p'); *out++ = Ch(';');
break;
default:
*out++ = *begin; // No expansion, copy character
}
}
++begin; // Step to next character
}
return out;
}
// Fill given output iterator with repetitions of the same character
template<class OutIt, class Ch>
inline OutIt fill_chars(OutIt out, int n, Ch ch)
{
for (int i = 0; i < n; ++i)
*out++ = ch;
return out;
}
// Find character
template<class Ch, Ch ch>
inline bool find_char(const Ch *begin, const Ch *end)
{
while (begin != end)
if (*begin++ == ch)
return true;
return false;
}
///////////////////////////////////////////////////////////////////////////
// Internal printing operations
// Print node
template<class OutIt, class Ch>
inline OutIt print_node(OutIt out, const xml_node<Ch> *node, int flags, int indent);
// Print children of the node
template<class OutIt, class Ch>
inline OutIt print_children(OutIt out, const xml_node<Ch> *node, int flags, int indent)
{
for (xml_node<Ch> *child = node->first_node(); child; child = child->next_sibling())
out = print_node(out, child, flags, indent);
return out;
}
// Print attributes of the node
template<class OutIt, class Ch>
inline OutIt print_attributes(OutIt out, const xml_node<Ch> *node, int /*flags*/)
{
for (xml_attribute<Ch> *attribute = node->first_attribute(); attribute; attribute = attribute->next_attribute())
{
if (attribute->name() && attribute->value())
{
// Print attribute name
*out = Ch(' '), ++out;
out = copy_chars(attribute->name(), attribute->name() + attribute->name_size(), out);
*out = Ch('='), ++out;
// Print attribute value using appropriate quote type
if (find_char<Ch, Ch('"')>(attribute->value(), attribute->value() + attribute->value_size()))
{
*out = Ch('\''), ++out;
out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('"'), out);
*out = Ch('\''), ++out;
}
else
{
*out = Ch('"'), ++out;
out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('\''), out);
*out = Ch('"'), ++out;
}
}
}
return out;
}
// Print data node
template<class OutIt, class Ch>
inline OutIt print_data_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
{
assert(node->type() == node_data);
if (!(flags & print_no_indenting))
out = fill_chars(out, indent, Ch('\t'));
out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out);
return out;
}
// Print data node
template<class OutIt, class Ch>
inline OutIt print_cdata_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
{
assert(node->type() == node_cdata);
if (!(flags & print_no_indenting))
out = fill_chars(out, indent, Ch('\t'));
*out = Ch('<'); ++out;
*out = Ch('!'); ++out;
*out = Ch('['); ++out;
*out = Ch('C'); ++out;
*out = Ch('D'); ++out;
*out = Ch('A'); ++out;
*out = Ch('T'); ++out;
*out = Ch('A'); ++out;
*out = Ch('['); ++out;
out = copy_chars(node->value(), node->value() + node->value_size(), out);
*out = Ch(']'); ++out;
*out = Ch(']'); ++out;
*out = Ch('>'); ++out;
return out;
}
// Print element node
template<class OutIt, class Ch>
inline OutIt print_element_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
{
assert(node->type() == node_element);
// Print element name and attributes, if any
if (!(flags & print_no_indenting))
out = fill_chars(out, indent, Ch('\t'));
*out = Ch('<'), ++out;
out = copy_chars(node->name(), node->name() + node->name_size(), out);
out = print_attributes(out, node, flags);
// If node is childless
if (node->value_size() == 0 && !node->first_node())
{
// Print childless node tag ending
*out = Ch('/'), ++out;
*out = Ch('>'), ++out;
}
else
{
// Print normal node tag ending
*out = Ch('>'), ++out;
// Test if node contains a single data node only (and no other nodes)
xml_node<Ch> *child = node->first_node();
if (!child)
{
// If node has no children, only print its value without indenting
out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out);
}
else if (child->next_sibling() == 0 && child->type() == node_data)
{
// If node has a sole data child, only print its value without indenting
out = copy_and_expand_chars(child->value(), child->value() + child->value_size(), Ch(0), out);
}
else
{
// Print all children with full indenting
if (!(flags & print_no_indenting))
*out = Ch('\n'), ++out;
out = print_children(out, node, flags, indent + 1);
if (!(flags & print_no_indenting))
out = fill_chars(out, indent, Ch('\t'));
}
// Print node end
*out = Ch('<'), ++out;
*out = Ch('/'), ++out;
out = copy_chars(node->name(), node->name() + node->name_size(), out);
*out = Ch('>'), ++out;
}
return out;
}
// Print declaration node
template<class OutIt, class Ch>
inline OutIt print_declaration_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
{
// Print declaration start
if (!(flags & print_no_indenting))
out = fill_chars(out, indent, Ch('\t'));
*out = Ch('<'), ++out;
*out = Ch('?'), ++out;
*out = Ch('x'), ++out;
*out = Ch('m'), ++out;
*out = Ch('l'), ++out;
// Print attributes
out = print_attributes(out, node, flags);
// Print declaration end
*out = Ch('?'), ++out;
*out = Ch('>'), ++out;
return out;
}
// Print comment node
template<class OutIt, class Ch>
inline OutIt print_comment_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
{
assert(node->type() == node_comment);
if (!(flags & print_no_indenting))
out = fill_chars(out, indent, Ch('\t'));
*out = Ch('<'), ++out;
*out = Ch('!'), ++out;
*out = Ch('-'), ++out;
*out = Ch('-'), ++out;
out = copy_chars(node->value(), node->value() + node->value_size(), out);
*out = Ch('-'), ++out;
*out = Ch('-'), ++out;
*out = Ch('>'), ++out;
return out;
}
// Print doctype node
template<class OutIt, class Ch>
inline OutIt print_doctype_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
{
assert(node->type() == node_doctype);
if (!(flags & print_no_indenting))
out = fill_chars(out, indent, Ch('\t'));
*out = Ch('<'), ++out;
*out = Ch('!'), ++out;
*out = Ch('D'), ++out;
*out = Ch('O'), ++out;
*out = Ch('C'), ++out;
*out = Ch('T'), ++out;
*out = Ch('Y'), ++out;
*out = Ch('P'), ++out;
*out = Ch('E'), ++out;
*out = Ch(' '), ++out;
out = copy_chars(node->value(), node->value() + node->value_size(), out);
*out = Ch('>'), ++out;
return out;
}
// Print pi node
template<class OutIt, class Ch>
inline OutIt print_pi_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
{
assert(node->type() == node_pi);
if (!(flags & print_no_indenting))
out = fill_chars(out, indent, Ch('\t'));
*out = Ch('<'), ++out;
*out = Ch('?'), ++out;
out = copy_chars(node->name(), node->name() + node->name_size(), out);
*out = Ch(' '), ++out;
out = copy_chars(node->value(), node->value() + node->value_size(), out);
*out = Ch('?'), ++out;
*out = Ch('>'), ++out;
return out;
}
// Print node
template<class OutIt, class Ch>
inline OutIt print_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
{
// Print proper node type
switch (node->type())
{
// Document
case node_document:
out = print_children(out, node, flags, indent);
break;
// Element
case node_element:
out = print_element_node(out, node, flags, indent);
break;
// Data
case node_data:
out = print_data_node(out, node, flags, indent);
break;
// CDATA
case node_cdata:
out = print_cdata_node(out, node, flags, indent);
break;
// Declaration
case node_declaration:
out = print_declaration_node(out, node, flags, indent);
break;
// Comment
case node_comment:
out = print_comment_node(out, node, flags, indent);
break;
// Doctype
case node_doctype:
out = print_doctype_node(out, node, flags, indent);
break;
// Pi
case node_pi:
out = print_pi_node(out, node, flags, indent);
break;
#ifndef __GNUC__
// Unknown
default:
assert(0);
break;
#endif
}
// If indenting not disabled, add line break after node
if (!(flags & print_no_indenting))
*out = Ch('\n'), ++out;
// Return modified iterator
return out;
}
}
//! \endcond
///////////////////////////////////////////////////////////////////////////
// Printing
//! Prints XML to given output iterator.
//! \param out Output iterator to print to.
//! \param node Node to be printed. Pass xml_document to print entire document.
//! \param flags Flags controlling how XML is printed.
//! \return Output iterator pointing to position immediately after last character of printed text.
template<class OutIt, class Ch>
inline OutIt print(OutIt out, const xml_node<Ch> &node, int flags = 0)
{
return internal::print_node(out, &node, flags, 0);
}
#ifndef CEREAL_RAPIDXML_NO_STREAMS
//! Prints XML to given output stream.
//! \param out Output stream to print to.
//! \param node Node to be printed. Pass xml_document to print entire document.
//! \param flags Flags controlling how XML is printed.
//! \return Output stream.
template<class Ch>
inline std::basic_ostream<Ch> &print(std::basic_ostream<Ch> &out, const xml_node<Ch> &node, int flags = 0)
{
print(std::ostream_iterator<Ch>(out), node, flags);
return out;
}
//! Prints formatted XML to given output stream. Uses default printing flags. Use print() function to customize printing process.
//! \param out Output stream to print to.
//! \param node Node to be printed.
//! \return Output stream.
template<class Ch>
inline std::basic_ostream<Ch> &operator <<(std::basic_ostream<Ch> &out, const xml_node<Ch> &node)
{
return print(out, node);
}
#endif
}
} // namespace cereal
#endif
| {
"pile_set_name": "Github"
} |
/* some very targetted corrections to roll back nameclashes between
* Moodle and Bootstrap like .row, .label, .content, .controls
*
* Mostly relies on these styles being more specific than the Bootstrap
* ones in order to overule them.
*/
// .label vs .label
li.activity.label,
.file-picker td.label {
background: inherit;
color: inherit;
border: inherit;
text-shadow: none;
padding: 8px;
white-space: normal;
display: block;
font-size: inherit;
line-height: inherit;
}
.file-picker td.label {
display: table-cell;
text-align: right;
}
// Some of this dialog is sized in ems so a different font size
// effects the whole layout.
.choosercontainer #chooseform .option label {
font-size: 12px;
}
/* block.invisible vs .invisible
* block.hidden vs .invisible
*
* uses .invisible where the rest of Moodle uses .dimmed
* fixible in block renderer?
*
* There's seems to be even more naming confusion here since,
* blocks can be actually 'visible' (or not) to students,
* marked 'visible' but really just dimmed to indicate to editors
* that students can't see them or 'visible' to the user who
* collapses them, 'visible' if you have the right role and in
* different circumstances different sections of a block can
* be 'visible' or not.
*
* currently worked around in renderers.php function block{}
* by rewriting the class name "invisible" to "dimmed",
* though the blocks don't look particularly different apart
* from their contents disappearing. Maybe try .muted? or
* dimming all the edit icons apart from unhide, might be a
* nice effect, though they'd still be active. Maybe reverse
* it to white?
*/
li.section.hidden,
.block.hidden,
.block.invisible {
visibility: visible !important;
display: block !important;
}
/* .row vs .row
*
* very tricky to track down this when it goes wrong,
* since the styles are applied to generated content
*
* basically if you see things shifted left or right compared
* with where they should be check for a .row
*/
#turnitintool_style .row,
.forumpost .row {
margin-left: 0 !important;
// not sure if this needs !important
}
#turnitintool_style .row:before,
#turnitintool_style .row:after,
.forumpost .row:before,
.forumpost .row:after {
content: none;
}
/* fieldset.hidden vs .hidden
*
* Moodle uses fieldset.hidden for mforms, to signify a collection of
* form elements that don't have a box drawn round them. Bootstrap
* uses hidden for stuff that is hidden in various responsive modes.
*
* Relatedly, there is also fieldset.invisiblefieldset which hides the
* border and sets the display to inline.
*
* Originally this just set block and visible, but it is used
* in random question dialogue in Quiz,
* that dialogue is hidden and shown, so when hidden the
* above workaround leaves you with a button floating around
*/
fieldset.hidden {
display: inherit !important;
visibility: inherit !important;
}
/* .controls vs .controls
*
* in expanding course list, can be fixed in renderer though
*/
/* .container vs .container
*
* bootstrap uses .container to set the width of the layout at 960px or so, Moodle uses it
* in the Quiz to contain the questions to add. If you don't overule the Bootstrap code,
* it becomes near unuseable.
*/
#questionbank + .container {
width: auto;
}
// In Moodle .hide is the eye icon
// In Bootstrap it hides things
// these were done originally in two different places,
// by two different people, not sure if both needed
img.hide {
display: inherit;
}
img.icon.hide {
display: inline-block !important;
}
// In Moodle course texts are defined as labels.
// In Bootstrap they are styled to have centered text which looks off on courses texts
.section .label {
text-align: center;
}
// Input boxes for images sizes don't need a 3em width setting.
.atto_image_size input[type="text"] {
width: auto;
}
// Bootstrap lists usually needs a class. But when using the editor you can't
// expect users to do so. This will fix it when lists are used in the content area.
.pagelayout-admin .show {
display: inline !important;
}
.pagelayout-admin .modal.show {
display: block !important;
}
// When adding lots of levels the table overflows
// Content. The rubric styles.css set this to a max with of 720px which only makes things worse.
.gradingform_rubric {
max-width: none !important;
}
| {
"pile_set_name": "Github"
} |
# Datastore MySQL Suite
## Description
The suite runs the following MySQL versions against the SQL datastore unit tests:
- 5.5
- 5.6
- 5.7
- 8.0
A special unit test binary is built from sources that targets the docker
containers running MySQL.
| {
"pile_set_name": "Github"
} |
/*
* Copyright Debezium Authors.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package io.debezium.util;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.BiFunction;
import java.util.function.Function;
import io.debezium.annotation.Immutable;
/**
* A utility for creating iterators.
*
* @author Randall Hauch
*/
@Immutable
public class Iterators {
public static <T> Iterator<T> empty() {
return new Iterator<T>() {
@Override
public boolean hasNext() {
return false;
}
@Override
public T next() {
throw new NoSuchElementException();
}
};
}
public static <T> Iterator<T> with(final T value) {
return new Iterator<T>() {
private boolean finished = false;
@Override
public boolean hasNext() {
return !finished;
}
@Override
public T next() {
if (finished) {
throw new NoSuchElementException();
}
finished = true;
return value;
}
};
}
public static <T> Iterator<T> with(T value1, T value2) {
return new Iterator<T>() {
private int remaining = 2;
@Override
public boolean hasNext() {
return remaining > 0;
}
@Override
public T next() {
if (remaining == 2) {
--remaining;
return value1;
}
if (remaining == 1) {
--remaining;
return value2;
}
throw new NoSuchElementException();
}
};
}
public static <T> Iterator<T> with(T value1, T value2, T value3) {
return new Iterator<T>() {
private int remaining = 3;
@Override
public boolean hasNext() {
return remaining > 0;
}
@Override
public T next() {
if (remaining == 3) {
--remaining;
return value1;
}
if (remaining == 2) {
--remaining;
return value2;
}
if (remaining == 1) {
--remaining;
return value3;
}
throw new NoSuchElementException();
}
};
}
@SafeVarargs
public static <T> Iterator<T> with(T value1, T value2, T value3, T... additional) {
return new Iterator<T>() {
private int index = 0;
@Override
public boolean hasNext() {
return index < additional.length + 3;
}
@Override
public T next() {
try {
if (index == 0) {
return value1;
}
if (index == 1) {
return value2;
}
if (index == 2) {
return value3;
}
if (index < additional.length + 3) {
return additional[index - 3];
}
--index;
throw new NoSuchElementException();
}
finally {
++index;
}
}
};
}
public static <T> Iterator<T> with(T[] values) {
return new Iterator<T>() {
private int index = 0;
@Override
public boolean hasNext() {
return index < values.length;
}
@Override
public T next() {
try {
if (index < values.length) {
return values[index];
}
--index;
throw new NoSuchElementException();
}
finally {
++index;
}
}
};
}
public static <T, U, V> Iterator<V> around(Iterable<? extends T> first,
Iterable<? extends U> second,
BiFunction<T, U, V> conversion) {
return around(first.iterator(), second.iterator(), conversion);
}
public static <T, U, V> Iterator<V> around(final Iterator<? extends T> first,
final Iterator<? extends U> second,
final BiFunction<T, U, V> combineFirstAndSecond) {
return new Iterator<V>() {
@Override
public boolean hasNext() {
return second.hasNext();
}
@Override
public V next() {
return combineFirstAndSecond.apply(first.next(), second.next());
}
};
}
public static <V, T> Iterator<T> around(final Iterable<? extends V> iterable, Function<V, T> conversion) {
return around(iterable.iterator(), conversion);
}
public static <V, T> Iterator<T> around(final Iterator<? extends V> iterator, Function<V, T> conversion) {
return new Iterator<T>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public T next() {
return conversion.apply(iterator.next());
}
@Override
public void remove() {
iterator.remove();
}
};
}
public static <T> Iterable<T> around(final Iterator<T> iterator) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return iterator;
}
};
}
public static <T> Iterator<T> readOnly(final Iterator<T> iterator) {
return new Iterator<T>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public T next() {
return iterator.next();
}
};
}
public static <V, T> Iterator<T> readOnly(final Iterator<? extends V> iterator, Function<V, T> conversion) {
return new Iterator<T>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public T next() {
return conversion.apply(iterator.next());
}
};
}
public static <T> Iterator<T> readOnly(final Iterable<T> iterable) {
return readOnly(iterable.iterator());
}
public static <V, T> Iterator<T> readOnly(final Iterable<V> iterable, Function<V, T> conversion) {
return readOnly(iterable.iterator(), conversion);
}
public static <T> Iterable<T> readOnlyIterable(final Iterable<T> iterable) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return readOnly(iterable.iterator());
}
};
}
public static <V, T> Iterable<T> readOnlyIterable(final Iterable<? extends V> iterable, Function<V, T> conversion) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return readOnly(iterable.iterator(), conversion);
}
};
}
public static <T> Iterator<T> join(Iterable<T> first, T last) {
return join(first.iterator(), with(last));
}
public static <T> Iterator<T> join(Iterable<T> first, T last1, T last2) {
return join(first.iterator(), with(last1, last2));
}
public static <T> Iterator<T> join(Iterable<T> first, T last1, T last2, T last3) {
return join(first.iterator(), with(last1, last2, last3));
}
public static <T> Iterator<T> join(Iterable<T> first, T last1, T last2, T last3, T last4) {
return join(first.iterator(), with(last1, last2, last3, last4));
}
public static <T> Iterator<T> join(Iterable<T> first, Iterable<T> second) {
return join(first.iterator(), second.iterator());
}
public static <T> Iterator<T> join(Iterator<T> first, Iterator<T> second) {
return new Iterator<T>() {
private boolean completedFirst = false;
@Override
public boolean hasNext() {
if (!completedFirst) {
if (first.hasNext()) {
return true;
}
completedFirst = true;
}
return second.hasNext();
}
@Override
public T next() {
if (!completedFirst) {
if (first.hasNext()) {
return first.next();
}
completedFirst = true;
}
return second.next();
}
@Override
public void remove() {
if (!completedFirst) {
first.remove();
}
second.remove();
}
};
}
/**
* Get an {@link Iterable} from an {@link Iterator}.
*
* @param iterator the source iterator
* @param <T> the iterator type
*
* @return the iterable
*/
public static <T> Iterable<T> toIterable(Iterator<T> iterator) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return iterator;
}
};
}
/**
* An iterator that is able to transform its contents to another type.
*
* @param <F> the source transform type
* @param <T> the destination transform type
*/
public static interface TransformedIterator<F, T> extends Iterator<T> {
T transform(F from);
}
/**
* Transform an iterator from a given type to super types.
*
* @param fromIterator the source iterator
* @param function the function to be applied when performing element transformation
*
* @param <F> the source transform type
* @param <T> the destination transform type
*
* @return the transformed iterator
*/
public static <F, T> Iterator<T> transform(Iterator<F> fromIterator, Function<? super F, ? extends T> function) {
return new TransformedIterator<F, T>() {
@Override
public boolean hasNext() {
return fromIterator.hasNext();
}
@Override
public T next() {
return transform(fromIterator.next());
}
@Override
public void remove() {
fromIterator.remove();
}
@Override
public T transform(F from) {
return function.apply(from);
}
};
}
/**
* A read only iterator that is able to preview the next value without consuming it or altering the behavior or semantics
* of the normal {@link Iterator} methods.
*
* @param <T> the type of value
*/
public static interface PreviewIterator<T> extends Iterator<T> {
/**
* Peek at the next value without consuming or using it. This method returns the same value if called multiple times
* between {@link Iterator#next}.
*
* @return the next value, or null if there are no more
*/
T peek();
}
/**
* Get a read-only iterator that can peek at the next value before it is retrieved with {@link Iterator#next()}.
*
* @param iter the original iterator
* @return the peeking iterator; may be null if {@code iter} is null
*/
public static <T> PreviewIterator<T> preview(Iterator<T> iter) {
if (iter == null) {
return null;
}
if (iter instanceof PreviewIterator) {
return (PreviewIterator<T>) iter;
}
return new PreviewIterator<T>() {
private T nextValue;
@Override
public boolean hasNext() {
return nextValue != null || iter.hasNext();
}
@Override
public T next() {
if (nextValue != null) {
T next = nextValue;
nextValue = null;
return next;
}
return iter.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public T peek() {
if (nextValue != null) {
return nextValue;
}
if (iter.hasNext()) {
nextValue = iter.next();
return nextValue;
}
return null;
}
};
}
}
| {
"pile_set_name": "Github"
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "proto/arg.h"
int main(int argc, char **argv)
{
int nbargs, err_arg, mask;
struct arg *argp;
char *err_msg = NULL;
const char *err_ptr = NULL;
if (argc < 2) {
printf("Usage: %s arg_list [arg_mask]\n"
" mask defaults to 0x86543290\n"
" eg: %s 10k,+20,Host,1.2.3.4,24,::5.6.7.8,120s\n", *argv, *argv);
return 1;
}
mask = ARG7(0,SIZE,SINT,STR,IPV4,MSK4,IPV6,TIME);
if (argc >= 3)
mask = atoll(argv[2]);
printf("Using mask=0x%08x\n", mask);
nbargs = make_arg_list(argv[1], strlen(argv[1]), mask,
&argp, &err_msg, &err_ptr, &err_arg);
printf("nbargs=%d\n", nbargs);
if (nbargs < 0) {
printf("err_msg=%s\n", err_msg); free(err_msg);
printf("err_ptr=%s (str+%d)\n", err_ptr, err_ptr - argv[1]);
printf("err_arg=%d\n", err_arg);
return 1;
}
if (nbargs > 0) {
int arg;
for (arg = 0; arg < nbargs; arg++)
printf("arg %d: type=%d, int=0x%08x\n",
arg, argp[arg].type, *(int*)&argp[arg].data.uint);
}
return 0;
}
| {
"pile_set_name": "Github"
} |
/*
* light_ws2812_config.h
*
* Created: 18.01.2014 09:58:15
*
* User Configuration file for the light_ws2812_lib
*
*/
#ifndef WS2812_CONFIG_H_
#define WS2812_CONFIG_H_
///////////////////////////////////////////////////////////////////////
// Define I/O pin
///////////////////////////////////////////////////////////////////////
#define ws2812_port A // Data port
#define ws2812_pin 1 // Data out pin
#endif /* WS2812_CONFIG_H_ */
| {
"pile_set_name": "Github"
} |
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27004.2009
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Finished-PictureBot_Regex", "Finished-PictureBot_Regex\Finished-PictureBot_Regex.csproj", "{B3569BA8-CE73-4044-9239-D6B2C7638656}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B3569BA8-CE73-4044-9239-D6B2C7638656}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B3569BA8-CE73-4044-9239-D6B2C7638656}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B3569BA8-CE73-4044-9239-D6B2C7638656}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B3569BA8-CE73-4044-9239-D6B2C7638656}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3FA9E537-2704-4C50-BD96-D9F9AD73EB8C}
EndGlobalSection
EndGlobal
| {
"pile_set_name": "Github"
} |
# --------------------------------------------------------
# Multitask Network Cascade
# Modified from py-faster-rcnn (https://github.com/rbgirshick/py-faster-rcnn)
# Copyright (c) 2016, Haozhi Qi
# Licensed under The MIT License [see LICENSE for details]
# --------------------------------------------------------
import time
class Timer(object):
"""A simple timer."""
def __init__(self):
self.total_time = 0.
self.calls = 0
self.start_time = 0.
self.diff = 0.
self.average_time = 0.
def tic(self):
# using time.time instead of time.clock because time time.clock
# does not normalize for multithreading
self.start_time = time.time()
def toc(self, average=True):
self.diff = time.time() - self.start_time
self.total_time += self.diff
self.calls += 1
self.average_time = self.total_time / self.calls
if average:
return self.average_time
else:
return self.diff
| {
"pile_set_name": "Github"
} |
//=============================================================================
// MuseScore
// Music Composition & Notation
//
// Copyright (C) 2002-2011 Werner Schweer
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2
// as published by the Free Software Foundation and appearing in
// the file LICENCE.GPL
//=============================================================================
#ifndef __ICON_H__
#define __ICON_H__
#include "element.h"
#include "mscore.h"
namespace Ms {
//---------------------------------------------------------
// Icon
// dummy element, used for drag&drop
//---------------------------------------------------------
class Icon final : public Element
{
IconType _iconType { IconType::NONE };
QByteArray _action;
QIcon _icon;
int _extent { 40 };
public:
Icon(Score* s)
: Element(s) { }
virtual ~Icon() {}
Icon* clone() const override { return new Icon(*this); }
ElementType type() const override { return ElementType::ICON; }
IconType iconType() const { return _iconType; }
void setIconType(IconType val) { _iconType = val; }
void setAction(const QByteArray& a, const QIcon& i) { _action = a; _icon = i; }
const QByteArray& action() const { return _action; }
QIcon icon() const { return _icon; }
void setExtent(int v) { _extent = v; }
int extent() const { return _extent; }
void write(XmlWriter&) const override;
void read(XmlReader&) override;
void draw(QPainter*) const override;
void layout() override;
QVariant getProperty(Pid) const override;
bool setProperty(Pid, const QVariant&) override;
};
} // namespace Ms
#endif
| {
"pile_set_name": "Github"
} |
// Intel Media Hardware Codec SDK Interface [8/17/2016 SwordTwelve]
#ifndef INTELHARDCODEC_INTERFACE_H
#define INTELHARDCODEC_INTERFACE_H
#ifdef __cplusplus
class IntelHardCodec_Interface
{
//导出接口
public:
public: //DLL 接口
virtual int WINAPI Init(HWND hWnd,int mode = 1) = 0;
virtual int WINAPI Decode(unsigned char * pData, int len, OUT unsigned char * pYUVData) = 0;
virtual void WINAPI Close() = 0;
};
//视频获取定义接口指针类型
typedef IntelHardCodec_Interface* LPIntelHardDecoder;
LPIntelHardDecoder APIENTRY Create_IntelHardDecoder();//创建控制接口指针
void APIENTRY Release_IntelHardDecoder(LPIntelHardDecoder lpHardDecoder);//销毁控制接口指针
#endif//__cplusplus
#endif//INTELHARDCODEC_INTERFACE_H | {
"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.
OK_RELEASEAUDIT_WARNINGS=0
OK_FINDBUGS_WARNINGS=0
OK_JAVADOC_WARNINGS=0
| {
"pile_set_name": "Github"
} |
// TODO how to test this route since it points to a file on AWS s3?
describe('GET /export/avatar-:memberId.png', () => {});
| {
"pile_set_name": "Github"
} |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/macros.h"
#include "net/cookies/cookie_constants.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace net {
TEST(CookieConstantsTest, TestCookiePriority) {
// Basic cases.
EXPECT_EQ("low", CookiePriorityToString(COOKIE_PRIORITY_LOW));
EXPECT_EQ("medium", CookiePriorityToString(COOKIE_PRIORITY_MEDIUM));
EXPECT_EQ("high", CookiePriorityToString(COOKIE_PRIORITY_HIGH));
EXPECT_EQ(COOKIE_PRIORITY_LOW, StringToCookiePriority("low"));
EXPECT_EQ(COOKIE_PRIORITY_MEDIUM, StringToCookiePriority("medium"));
EXPECT_EQ(COOKIE_PRIORITY_HIGH, StringToCookiePriority("high"));
// Case Insensitivity of StringToCookiePriority().
EXPECT_EQ(COOKIE_PRIORITY_LOW, StringToCookiePriority("LOW"));
EXPECT_EQ(COOKIE_PRIORITY_MEDIUM, StringToCookiePriority("Medium"));
EXPECT_EQ(COOKIE_PRIORITY_HIGH, StringToCookiePriority("hiGH"));
// Value of default priority.
EXPECT_EQ(COOKIE_PRIORITY_DEFAULT, COOKIE_PRIORITY_MEDIUM);
// Numeric values.
EXPECT_LT(COOKIE_PRIORITY_LOW, COOKIE_PRIORITY_MEDIUM);
EXPECT_LT(COOKIE_PRIORITY_MEDIUM, COOKIE_PRIORITY_HIGH);
// Unrecognized tokens are interpreted as COOKIE_PRIORITY_DEFAULT.
const char* const bad_tokens[] = {
"", "lo", "lowerest", "high ", " high", "0"};
for (size_t i = 0; i < arraysize(bad_tokens); ++i) {
EXPECT_EQ(COOKIE_PRIORITY_DEFAULT, StringToCookiePriority(bad_tokens[i]));
}
}
} // namespace net
| {
"pile_set_name": "Github"
} |
//===-- MipsAsmBackend.h - Mips Asm Backend ------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the MipsAsmBackend class.
//
//===----------------------------------------------------------------------===//
//
#ifndef LLVM_LIB_TARGET_MIPS_MCTARGETDESC_MIPSASMBACKEND_H
#define LLVM_LIB_TARGET_MIPS_MCTARGETDESC_MIPSASMBACKEND_H
#include "MCTargetDesc/MipsFixupKinds.h"
#include "llvm/ADT/Triple.h"
#include "llvm/MC/MCAsmBackend.h"
namespace llvm {
class MCAssembler;
struct MCFixupKindInfo;
class MCObjectWriter;
class MCRegisterInfo;
class MCSymbolELF;
class Target;
class MipsAsmBackend : public MCAsmBackend {
Triple TheTriple;
bool IsN32;
public:
MipsAsmBackend(const Target &T, const MCRegisterInfo &MRI, const Triple &TT,
StringRef CPU, bool N32)
: MCAsmBackend(TT.isLittleEndian() ? support::little : support::big),
TheTriple(TT), IsN32(N32) {}
std::unique_ptr<MCObjectTargetWriter>
createObjectTargetWriter() const override;
void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
const MCValue &Target, MutableArrayRef<char> Data,
uint64_t Value, bool IsResolved,
const MCSubtargetInfo *STI) const override;
Optional<MCFixupKind> getFixupKind(StringRef Name) const override;
const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override;
unsigned getNumFixupKinds() const override {
return Mips::NumTargetFixupKinds;
}
/// @name Target Relaxation Interfaces
/// @{
/// MayNeedRelaxation - Check whether the given instruction may need
/// relaxation.
///
/// \param Inst - The instruction to test.
bool mayNeedRelaxation(const MCInst &Inst,
const MCSubtargetInfo &STI) const override {
return false;
}
/// fixupNeedsRelaxation - Target specific predicate for whether a given
/// fixup requires the associated instruction to be relaxed.
bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
const MCRelaxableFragment *DF,
const MCAsmLayout &Layout) const override {
// FIXME.
llvm_unreachable("RelaxInstruction() unimplemented");
return false;
}
/// RelaxInstruction - Relax the instruction in the given fragment
/// to the next wider instruction.
///
/// \param Inst - The instruction to relax, which may be the same
/// as the output.
/// \param [out] Res On return, the relaxed instruction.
void relaxInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
MCInst &Res) const override {}
/// @}
bool writeNopData(raw_ostream &OS, uint64_t Count) const override;
bool shouldForceRelocation(const MCAssembler &Asm, const MCFixup &Fixup,
const MCValue &Target) override;
bool isMicroMips(const MCSymbol *Sym) const override;
}; // class MipsAsmBackend
} // namespace
#endif
| {
"pile_set_name": "Github"
} |
// -*- mode: c++; c-basic-offset: 4 -*-
#ifndef CLICK_FROMFLANDUMP_HH
#define CLICK_FROMFLANDUMP_HH
#include <click/element.hh>
#include <click/task.hh>
class HandlerCall;
/*
=c
FromFlanDump(FILENAME [, I<KEYWORDS>])
=s traces
reads packets from a DAG file
=d
Reads packets from a file in DAG format, produced by the University of
Waikato's DAG tools. Pushes them out the output, and optionally stops the
driver when there are no more packets. If TIMING is true, then FromFlanDump
tries to maintain the timing of the original packet stream. TIMING is false by
default.
FromFlanDump also transparently reads gzip- and bzip2-compressed files, if you
have zcat(1) and bzcat(1) installed.
Keyword arguments are:
=over 8
=item SAMPLE
Unsigned real number between 0 and 1. FromFlanDump will output each packet with
probability SAMPLE. Default is 1. FromFlanDump uses fixed-point arithmetic, so
the actual sampling probability may differ substantially from the requested
sampling probability. Use the C<sampling_prob> handler to find out the actual
probability.
=item STOP
Boolean. If true, then FromFlanDump will ask the router to stop when it is done
reading its tcpdump file. Default is false.
=item START
Absolute time in seconds since the epoch. FromFlanDump will output packets with
timestamps after that time.
=item START_AFTER
Argument is relative time in seconds (or supply a suffix like `min', `h').
FromFlanDump will skip the first I<T> seconds in the log.
=item END
Absolute time in seconds since the epoch. FromFlanDump will stop when
encountering a packet with timestamp at or after that time.
=item END_AFTER
Argument is relative time in seconds (or supply a suffix like `min', `h').
FromFlanDump will stop at the first packet whose timestamp is at least I<T>
seconds after the first timestamp in the log.
=item INTERVAL
Argument is relative time in seconds (or supply a suffix like `min', `h').
FromFlanDump will stop at the first packet whose timestamp is at least I<T>
seconds after the first packet output.
=item END_CALL
Specify the handler to call, instead of stopping FromFlanDump, once the end
time is reached.
=item TIMING
Boolean. Same as the TIMING argument.
=item ACTIVE
Boolean. If false, then FromFlanDump will not emit packets (until the
`C<active>' handler is written). Default is true.
=item MMAP
Boolean. If true, then FromFlanDump will use mmap(2) to access the tcpdump
file. This can result in slightly better performance on some machines.
FromFlanDump's regular file discipline is pretty optimized, so the difference
is often small in practice. Default is true on most operating systems, but
false on Linux.
=back
You can supply at most one of START and START_AFTER, and at most one of END,
END_AFTER, and INTERVAL.
Only available in user-level processes.
=n
By default, `tcpdump -w FILENAME' dumps only the first 68 bytes of
each packet. You probably want to run `tcpdump -w FILENAME -s 2000' or some
such.
FromFlanDump sets packets' extra length annotations to any additional length
recorded in the dump.
=h sampling_prob read-only
Returns the sampling probability (see the SAMPLE keyword argument).
=h active read/write
Value is a Boolean.
=h encap read-only
Returns the file's encapsulation type.
=h filesize read-only
Returns the length of the FromFlanDump file, in bytes, or "-" if that
length cannot be determined.
=h filepos read-only
Returns FromFlanDump's position in the file, in bytes.
=h extend_interval write-only
Text is a time interval. If END_TIME or one of its cousins was specified, then
writing to this handler extends END_TIME by that many seconds. Also, ACTIVE is
set to true.
=a
FromDump, ToDump, mmap(2) */
class FromFlanDump : public Element { public:
FromFlanDump() CLICK_COLD;
~FromFlanDump() CLICK_COLD;
const char *class_name() const { return "FromFlanDump"; }
const char *port_count() const { return PORTS_0_1; }
int configure(Vector<String> &, ErrorHandler *) CLICK_COLD;
int initialize(ErrorHandler *) CLICK_COLD;
void cleanup(CleanupStage) CLICK_COLD;
void add_handlers() CLICK_COLD;
bool run_task(Task *);
Packet *pull(int);
void set_active(bool);
private:
static const uint32_t BUFFER_SIZE = 32768;
static const int SAMPLING_SHIFT = 28;
class FlanFile { public:
FlanFile();
~FlanFile();
int open(const String &basename, const String &filename, int record_size, ErrorHandler *);
int read_more(off_t);
off_t last_record() const;
uint16_t read_uint16(off_t) const;
uint32_t read_uint32(off_t) const;
private:
int _fd;
const uint8_t *_buffer;
off_t _offset;
uint32_t _len;
FILE *_pipe;
bool _my_buffer;
int _record_size;
enum { BUFFER_SIZE = 65536 };
};
enum { FF_FLID = 0, FF_TIME, FF_SIZE, FF_FLAGS,
FF_SADDR, FF_DADDR, FF_DPORT, FF_CT_PKT, FF_CT_BYTES, FF_BEG,
FF_FIRST_PKT = FF_FLID, FF_LAST_PKT = FF_FLAGS + 1,
FF_FIRST_FLOW = FF_SADDR, FF_LAST_FLOW = FF_BEG + 1,
FF_LAST = FF_LAST_FLOW };
FlanFile *_ff[FF_LAST];
off_t _record;
off_t _last_record;
bool _flows : 1;
bool _stop : 1;
bool _active;
Task _task;
String _dirname;
int error_helper(ErrorHandler *, const char *);
int read_buffer(ErrorHandler *);
int read_into(void *, uint32_t, ErrorHandler *);
bool read_packet(ErrorHandler *);
static String read_handler(Element *, void *) CLICK_COLD;
static int write_handler(const String &, Element *, void *, ErrorHandler *) CLICK_COLD;
};
inline off_t
FromFlanDump::FlanFile::last_record() const
{
return (_offset + _len) / _record_size;
}
inline uint16_t
FromFlanDump::FlanFile::read_uint16(off_t o) const
{
return *reinterpret_cast<const uint16_t *>(_buffer + o<<1 - _offset);
}
inline uint32_t
FromFlanDump::FlanFile::read_uint32(off_t o) const
{
return *reinterpret_cast<const uint16_t *>(_buffer + o<<2 - _offset);
}
#endif
| {
"pile_set_name": "Github"
} |
// Tencent is pleased to support the open source community by making TNN available.
//
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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.
#ifndef TNN_SOURCE_TNN_DEVICE_METAL_METAL_COMMAND_QUEUE_H_
#define TNN_SOURCE_TNN_DEVICE_METAL_METAL_COMMAND_QUEUE_H_
#include "tnn/core/context.h"
#include "tnn/device/metal/metal_macro.h"
#import <Metal/Metal.h>
#include <string>
TNN_OBJC_CLASS(TNNMMetalContextImpl);
@interface TNNMetalCommandQueueImpl : NSObject <MTLCommandQueue> {
__strong id<MTLCommandQueue> mtl_command_queue_;
}
@property(weak, nonatomic) TNNMMetalContextImpl *_Nullable metalContextImpl;
- (instancetype _Nullable)initWithCommandQueue:(nullable id<MTLCommandQueue>)command_queue;
@end
#endif // TNN_SOURCE_TNN_DEVICE_METAL_METAL_COMMAND_QUEUE_H_
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2011 Google, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 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. ``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
* 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.
*/
module html {
// http://www.whatwg.org/specs/web-apps/current-work/#htmlspanelement
interface HTMLSpanElement : HTMLElement {
};
}
| {
"pile_set_name": "Github"
} |
{
"Execute binaries from npm packages.\n%s": "Kjør binærfiler fra npm-pakker.\n%s",
"Package to be installed.": "Pakken som skal installeres.",
"Location of the npm cache.": "Hvor npm-cachen er.",
"Skip installation if a package is missing.": "La være å installere dersom pakken mangler.",
"Path to user npmrc.": "Sti til brukerens npmrc.",
"Execute string as if inside `npm run-script`.": "Kjør streng som om den var inni `npm run-script`.",
"Shell to execute the command with, if any.": "Skall å kjøre kommandoen med, hvis noe.",
"Generate shell code to use npx as the \"command not found\" fallback.": "Generer skallkode for å bruke npx som \"kommandoen finnes ikke\" fallback.",
"Ignores existing binaries in $PATH, or in the local project. This forces npx to do a temporary install and use the latest version.": "Ignorerer eksisterende binærfiler i $PATH eller i det lokale prosjektet. Dette tvinger npx til å installere siste versjon av pakken midlertidig.",
"npm binary to use for internal operations.": "npm-binærfil som skal brukes for interne operasjoner.",
"For the full documentation, see the manual page for npx(1).": "For hele dokumentasjonen, se brukermanualen for npx(1).",
"Unable to guess a binary name from %s. Please use --package.": "Klarer ikke å gjette en binærfils navn ut fra %s. Vennligst bruk --package.",
"\nERROR: You must supply a command.\n": "\nFEIL: Du må legge ved en kommando.\n",
"Command failed: %s %s": "Kommando feilet: %s %s",
"Install for %s failed with code %s": "Installasjon for %s feilet med kode %s",
"%s not found. Trying with npx...": "Kunne ikke finne%s. Prøver med npx...",
"command not found: %s": "kommando ikke funnet: %s",
"options": "innstillinger",
"command": "kommando",
"version": "versjon",
"command-arg": "kommando-argument",
"command-string": "kommando-streng",
"shell": "skall",
"package": "pakke",
"npx: installed %s in %ss": "npx: installerte %s på %ss",
"Suppress output from npx itself. Subcommands will not be affected.": "Skjul kommandoer fra npx. Sub-kommandoer vil ikke berøres.",
"Extra node argument when calling a node binary.": "Ekstra node-argument når en node-binærfil blir kalt."
}
| {
"pile_set_name": "Github"
} |
package uk.co.senab.photoview;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
/**
* Created by Swifty.Wang on 2015/5/29.
*/
public class ProgressLoading extends Dialog {
private static ProgressLoading dialog;
public ProgressLoading(Context context) {
super(context);
}
public static void show(Context context) {
show(context, false);
}
/**
* press back button can dismiss progressdialog
*
* @param context
* @param cancelable
*/
public static void show(Context context, Boolean cancelable) {
dialog = new ProgressLoading(context);
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(cancelable);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
FrameLayout detail_layout = new FrameLayout(context);
ProgressBar progressBar = new ProgressBar(context);
detail_layout.addView(progressBar);
dialog.setContentView(detail_layout);
dialog.getWindow()
.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.show();
}
public static void DismissDialog() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
public static void setOndismissListener(OnDismissListener ondismissListener) {
dialog.setOnDismissListener(ondismissListener);
}
}
| {
"pile_set_name": "Github"
} |
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Vicente J. Botet Escriba 2008-2009,2012. 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/thread for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_THREAD_NULL_MUTEX_HPP
#define BOOST_THREAD_NULL_MUTEX_HPP
#include <boost/thread/detail/config.hpp>
#include <boost/thread/detail/delete.hpp>
#include <boost/chrono/chrono.hpp>
/// \file
/// Describes null_mutex class
namespace boost
{
/// Implements a mutex that simulates a mutex without doing any operation and
/// simulates a successful operation.
class null_mutex
{
public:
BOOST_THREAD_NO_COPYABLE( null_mutex) /*< no copyable >*/
null_mutex() {}
/// Simulates a mutex lock() operation. Empty function.
void lock()
{
}
/// Simulates a mutex try_lock() operation.
/// Equivalent to "return true;"
bool try_lock()
{
return true;
}
/// Simulates a mutex unlock() operation.
/// Empty function.
void unlock()
{
}
#ifdef BOOST_THREAD_USES_CHRONO
/// Simulates a mutex try_lock_until() operation.
/// Equivalent to "return true;"
template <typename Clock, typename Duration>
bool try_lock_until(chrono::time_point<Clock, Duration> const &)
{
return true;
}
/// Simulates a mutex try_lock_for() operation.
/// Equivalent to "return true;"
template <typename Rep, typename Period>
bool try_lock_for(chrono::duration<Rep, Period> const &)
{
return true;
}
#endif
/// Simulates a mutex lock_shared() operation.
/// Empty function.
void lock_shared()
{
}
/// Simulates a mutex try_lock_shared() operation.
/// Equivalent to "return true;"
bool try_lock_shared()
{
return true;
}
/// Simulates a mutex unlock_shared() operation.
/// Empty function.
void unlock_shared()
{
}
/// Simulates a mutex try_lock_shared_until() operation.
/// Equivalent to "return true;"
template <typename Clock, typename Duration>
bool try_lock_shared_until(chrono::time_point<Clock, Duration> const &)
{
return true;
}
/// Simulates a mutex try_lock_shared_for() operation.
/// Equivalent to "return true;"
template <typename Rep, typename Period>
bool try_lock_shared_for(chrono::duration<Rep, Period> const &)
{
return true;
}
/// Simulates a mutex lock_upgrade() operation.
/// Empty function.
void lock_upgrade()
{
}
/// Simulates a mutex try_lock_upgrade() operation.
/// Equivalent to "return true;"
bool try_lock_upgrade()
{
return true;
}
/// Simulates a mutex unlock_upgrade() operation.
/// Empty function.
void unlock_upgrade()
{
}
/// Simulates a mutex try_lock_upgrade_until() operation.
/// Equivalent to "return true;"
template <typename Clock, typename Duration>
bool try_lock_upgrade_until(chrono::time_point<Clock, Duration> const &)
{
return true;
}
/// Simulates a mutex try_lock_upgrade_for() operation.
/// Equivalent to "return true;"
template <typename Rep, typename Period>
bool try_lock_upgrade_for(chrono::duration<Rep, Period> const &)
{
return true;
}
/// Simulates a mutex try_unlock_shared_and_lock() operation.
/// Equivalent to "return true;"
bool try_unlock_shared_and_lock()
{
return true;
}
#ifdef BOOST_THREAD_USES_CHRONO
/// Simulates a mutex try_unlock_shared_and_lock_until() operation.
/// Equivalent to "return true;"
template <typename Clock, typename Duration>
bool try_unlock_shared_and_lock_until(chrono::time_point<Clock, Duration> const &)
{
return true;
}
/// Simulates a mutex try_unlock_shared_and_lock_for() operation.
/// Equivalent to "return true;"
template <typename Rep, typename Period>
bool try_unlock_shared_and_lock_for(chrono::duration<Rep, Period> const &)
{
return true;
}
#endif
/// Simulates unlock_and_lock_shared().
/// Empty function.
void unlock_and_lock_shared()
{
}
/// Simulates a mutex try_unlock_shared_and_lock_upgrade() operation.
/// Equivalent to "return true;"
bool try_unlock_shared_and_lock_upgrade()
{
return true;
}
#ifdef BOOST_THREAD_USES_CHRONO
/// Simulates a mutex try_unlock_shared_and_lock_upgrade_until() operation.
/// Equivalent to "return true;"
template <typename Clock, typename Duration>
bool try_unlock_shared_and_lock_upgrade_until(chrono::time_point<Clock, Duration> const &)
{
return true;
}
/// Simulates a mutex try_unlock_shared_and_lock_upgrade_for() operation.
/// Equivalent to "return true;"
template <typename Rep, typename Period>
bool try_unlock_shared_and_lock_upgrade_for(chrono::duration<Rep, Period> const &)
{
return true;
}
#endif
/// Simulates unlock_and_lock_upgrade().
/// Empty function.
void unlock_and_lock_upgrade()
{
}
/// Simulates unlock_upgrade_and_lock().
/// Empty function.
void unlock_upgrade_and_lock()
{
}
/// Simulates a mutex try_unlock_upgrade_and_lock() operation.
/// Equivalent to "return true;"
bool try_unlock_upgrade_and_lock()
{
return true;
}
#ifdef BOOST_THREAD_USES_CHRONO
/// Simulates a mutex try_unlock_upgrade_and_lock_until() operation.
/// Equivalent to "return true;"
template <typename Clock, typename Duration>
bool try_unlock_upgrade_and_lock_until(chrono::time_point<Clock, Duration> const &)
{
return true;
}
/// Simulates a mutex try_unlock_upgrade_and_lock_for() operation.
/// Equivalent to "return true;"
template <typename Rep, typename Period>
bool try_unlock_upgrade_and_lock_for(chrono::duration<Rep, Period> const &)
{
return true;
}
#endif
/// Simulates unlock_upgrade_and_lock_shared().
/// Empty function.
void unlock_upgrade_and_lock_shared()
{
}
};
} //namespace boost {
#endif
| {
"pile_set_name": "Github"
} |
/* -*- mode: C; c-basic-offset: 3; -*- */
/*--------------------------------------------------------------------*/
/*--- Compiler specific stuff. m_compiler.c ---*/
/*--------------------------------------------------------------------*/
/*
This file is part of Valgrind, a dynamic binary instrumentation
framework.
Copyright (C) 2014-2014 Florian Krohm
[email protected]
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307, USA.
The GNU General Public License is contained in the file COPYING.
*/
/* Currently, this file provides definitions for builtins that not all
compilers or compiler versions provide.
Missing builtins are rare. Therefore, no attempt has been made to
provide efficient implementations.
*/
#include "config.h"
#include "pub_core_basics.h"
#include "pub_core_libcbase.h"
#include "pub_core_libcassert.h"
#include "pub_core_debuglog.h"
#ifndef HAVE_BUILTIN_POPCOUT
/* From the GCC documentation:
Returns the number of 1-bits in x. */
UInt
__builtin_popcount(UInt x)
{
UInt i, count = 0;
for (i = 0; i < 32; ++i) {
count += x & 1;
x >>= 1;
}
return count;
}
UInt
__builtin_popcountll(ULong x)
{
UInt i, count = 0;
for (i = 0; i < 64; ++i) {
count += x & 1;
x >>= 1;
}
return count;
}
#endif
#ifndef HAVE_BUILTIN_CLZ
/* From the GCC documentation:
Returns the number of leading 0-bits in x, starting at the most
significant position. If x is 0, the result is undefined. */
UInt
__builtin_clz(UInt x)
{
UInt count = 32;
UInt y;
y = x >> 16; if (y != 0) { count -= 16; x = y; }
y = x >> 8; if (y != 0) { count -= 8; x = y; }
y = x >> 4; if (y != 0) { count -= 4; x = y; }
y = x >> 2; if (y != 0) { count -= 2; x = y; }
y = x >> 1; if (y != 0) return count - 2;
return count - x;
}
UInt
__builtin_clzll(ULong x)
{
UInt count = 64;
ULong y;
y = x >> 32; if (y != 0) { count -= 32; x = y; }
y = x >> 16; if (y != 0) { count -= 16; x = y; }
y = x >> 8; if (y != 0) { count -= 8; x = y; }
y = x >> 4; if (y != 0) { count -= 4; x = y; }
y = x >> 2; if (y != 0) { count -= 2; x = y; }
y = x >> 1; if (y != 0) return count - 2;
return count - x;
}
#endif
#ifndef HAVE_BUILTIN_CTZ
/* From the GCC documentation:
Returns the number of trailing 0-bits in x, starting at the least
significant bit position. If x is 0, the result is undefined. */
UInt
__builtin_ctz(UInt x)
{
UInt i, count = 0;
for (i = 0; i < 32; ++i) {
if (x & 1) break;
++count;
x >>= 1;
}
return count;
}
UInt
__builtin_ctzll(ULong x)
{
UInt i, count = 0;
for (i = 0; i < 64; ++i) {
if (x & 1) break;
++count;
x >>= 1;
}
return count;
}
#endif
#ifdef __INTEL_COMPILER
/* Provide certain functions Intel's ICC compiler expects to be defined. */
void *
__intel_memcpy(void *dest, const void *src, SizeT sz)
{
return VG_(memcpy)( dest, src, sz );
}
void *
__intel_mic_avx512f_memcpy(void *dest, const void *src, SizeT sz)
{
return VG_(memcpy)( dest, src, sz );
}
void *
__intel_new_memcpy(void *dest, const void *src, SizeT sz)
{
return VG_(memcpy)( dest, src, sz );
}
void *
__intel_ssse3_memcpy(void *dest, const void *src, SizeT sz)
{
return VG_(memcpy)( dest, src, sz );
}
void *
__intel_ssse3_rep_memcpy(void *dest, const void *src, SizeT sz)
{
return VG_(memcpy)( dest, src, sz );
}
void *
_intel_fast_memcpy(void *dest, const void *src, SizeT sz)
{
return VG_(memcpy)( dest, src, sz );
}
void *
__intel_lrb_memcpy(void *dest, const void *src, SizeT sz)
{
return VG_(memcpy)( dest, src, sz );
}
void *
__intel_memset(void *dest, int value, SizeT num)
{
return VG_(memset)( dest, value, num );
}
void *
__intel_new_memset(void *dest, int value, SizeT num)
{
return VG_(memset)( dest, value, num );
}
void *
__intel_mic_avx512f_memset(void *dest, int value, SizeT num)
{
return VG_(memset)( dest, value, num );
}
void *
__intel_lrb_memset(void *dest, int value, SizeT num)
{
return VG_(memset)( dest, value, num );
}
void *
_intel_fast_memset(void *dest, int value, SizeT num)
{
return VG_(memset)( dest, value, num );
}
#endif
/*====================================================================*/
/*=== gcc -fsanitize=undefined helper function support ===*/
/*====================================================================*/
void __ubsan_handle_type_mismatch ( void );
void __ubsan_handle_type_mismatch ( void )
{
VG_(debugLog)(0, "main:ubsan", "In %s", __func__);
vg_assert(0);
}
void __ubsan_handle_mul_overflow ( void );
void __ubsan_handle_mul_overflow ( void )
{
VG_(debugLog)(0, "main:ubsan", "In %s", __func__);
vg_assert(0);
}
void __ubsan_handle_add_overflow ( void );
void __ubsan_handle_add_overflow ( void )
{
VG_(debugLog)(0, "main:ubsan", "In %s", __func__);
vg_assert(0);
}
void __ubsan_handle_sub_overflow ( void );
void __ubsan_handle_sub_overflow ( void )
{
VG_(debugLog)(0, "main:ubsan", "In %s", __func__);
vg_assert(0);
}
void __ubsan_handle_divrem_overflow ( void );
void __ubsan_handle_divrem_overflow ( void )
{
VG_(debugLog)(0, "main:ubsan", "In %s", __func__);
vg_assert(0);
}
void __ubsan_handle_negate_overflow ( void );
void __ubsan_handle_negate_overflow ( void )
{
VG_(debugLog)(0, "main:ubsan", "In %s", __func__);
vg_assert(0);
}
void __ubsan_handle_out_of_bounds ( void );
void __ubsan_handle_out_of_bounds ( void )
{
VG_(debugLog)(0, "main:ubsan", "In %s", __func__);
vg_assert(0);
}
void __ubsan_handle_shift_out_of_bounds ( void );
void __ubsan_handle_shift_out_of_bounds ( void )
{
VG_(debugLog)(0, "main:ubsan", "In %s", __func__);
vg_assert(0);
}
void __ubsan_handle_vla_bound_not_positive ( void );
void __ubsan_handle_vla_bound_not_positive ( void )
{
VG_(debugLog)(0, "main:ubsan", "In %s", __func__);
vg_assert(0);
}
void __ubsan_handle_nonnull_arg ( void );
void __ubsan_handle_nonnull_arg ( void )
{
VG_(debugLog)(0, "main:ubsan", "In %s", __func__);
vg_assert(0);
}
/*--------------------------------------------------------------------*/
/*--- end ---*/
/*--------------------------------------------------------------------*/
| {
"pile_set_name": "Github"
} |
//
// PageVisitedNotifier.h
// PageVisitedCaptureManager
//
// Created by Ophat Phuetkasickonphasutha on 10/2/13.
// Copyright 2013 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "PageVisitedDelegate.h"
@protocol PageVisitedDelegate;
@class FirefoxUrlInfoInquirer;
@interface PageVisitedNotifier : NSObject{
@private
id <PageVisitedDelegate> mPageVisitedDelegate;
NSString * mPageURLSafari;
NSString * mPageURLFirefox;
NSString * mPageURLChrome;
AXObserverRef mObserver1;
AXObserverRef mObserver2;
AXObserverRef mObserver3;
AXUIElementRef mProcess1;
AXUIElementRef mProcess2;
AXUIElementRef mProcess3;
CFRunLoopRef mLoop1;
CFRunLoopRef mLoop2;
CFRunLoopRef mLoop3;
FirefoxUrlInfoInquirer *mFirefoxUrlInquirer;
int mSafariSleepTime;
int mChromeSleepTime;
int mFirefoxSleepTime;
}
@property (nonatomic,copy) NSString * mPageURLSafari;
@property (nonatomic,copy) NSString * mPageURLFirefox;
@property (nonatomic,copy) NSString * mPageURLChrome;
@property (nonatomic, retain) id <PageVisitedDelegate> mPageVisitedDelegate;
@property (nonatomic, assign) AXObserverRef mObserver1;
@property (nonatomic, assign) AXObserverRef mObserver2;
@property (nonatomic, assign) AXObserverRef mObserver3;
@property (nonatomic, assign) CFRunLoopRef mLoop1;
@property (nonatomic, assign) CFRunLoopRef mLoop2;
@property (nonatomic, assign) CFRunLoopRef mLoop3;
@property (nonatomic, assign) AXUIElementRef mProcess1;
@property (nonatomic, assign) AXUIElementRef mProcess2;
@property (nonatomic, assign) AXUIElementRef mProcess3;
-(id)initWithPageVisitedDelegate:(id<PageVisitedDelegate>) aPageVisitedDelegate;
-(void) startNotify;
-(void) stopNotify;
-(void) registerPageEventSafari;
-(void) unRegisterPageEventSafari;
-(void) registerPageEventFirefox;
-(void) unRegisterPageEventFirefox;
-(void) registerPageEventChrome;
-(void) unRegisterPageEventChrome;
-(void) titleChangeCallBack;
-(void) sendUrl:(NSString *)aUrl PageName:(NSString *)aPageName App:(NSString *)aApp ;
@end
| {
"pile_set_name": "Github"
} |
require('../../modules/es6.math.imul');
module.exports = require('../../modules/_core').Math.imul; | {
"pile_set_name": "Github"
} |
delete 030000 170000
| {
"pile_set_name": "Github"
} |
# [TypeScript for Beginner Programmers](https://ts.chibicode.com)
This is the repository for the TypeScript tutorial website called **[TypeScript for Beginner Programmers](https://ycombinator.chibicode.com/)**.
<p>
<a href="https://ts.chibicode.com/"><img src="public/images/og-index.png" width="600" /></a>
</p>
## Article 3: [Your Coding Tutorial Might Need Some Refactoring](https://ts.chibicode.com/refactor)
<p>
<a href="https://ts.chibicode.com/refactor"><img src="public/images/og-refactor-v3.png" width="600" /></a>
</p>
## Article 2: [TypeScript Tutorial for JS Programmers Who Know How to Build a Todo App](https://ts.chibicode.com/todo)
<p>
<a href="https://ts.chibicode.com/todo"><img src="public/images/og-todo-v2.png" width="600" /></a>
</p>
## Article 1: [TypeScript Generics for People Who Gave Up on Understanding Generics](https://ts.chibicode.com/generics)
<p>
<a href="https://ts.chibicode.com/generics"><img src="public/images/og-generics.png" width="600" /></a>
</p>
## License & Credits
- For emojis, I’m using [Twemoji](https://github.com/twitter/twemoji) by Twitter (CC-BY 4.0 license).
- The text for this website is licensed under [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/).
- Everything else is licensed under the [MIT](LICENSE-non-text.txt) license.
## Author
**Shu Uesugi**
- [Website](https://chibicode.com)
- Twitter: [@chibicode](https://twitter.com/chibicode)
- Email: [[email protected]](mailto:[email protected]) | {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun 9 2015 22:53:21).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard.
//
#import <objc/NSObject.h>
#import "CPSConfigurationChangeObserver-Protocol.h"
@class NSString;
@protocol ICPAgentServiceManager, OS_dispatch_queue;
@interface ICPAgentMaintenanceTaskManager : NSObject <CPSConfigurationChangeObserver>
{
NSObject<ICPAgentServiceManager> *_serviceManager;
id _systemLibraryChangeObserver;
NSObject<OS_dispatch_queue> *_workQueue;
}
@property(retain) NSObject<OS_dispatch_queue> *workQueue; // @synthesize workQueue=_workQueue;
@property(retain) id systemLibraryChangeObserver; // @synthesize systemLibraryChangeObserver=_systemLibraryChangeObserver;
@property __weak NSObject<ICPAgentServiceManager> *serviceManager; // @synthesize serviceManager=_serviceManager;
- (void).cxx_destruct;
- (BOOL)serviceManagerIsRunning;
- (void)performServiceStateDependentUpdatesInSystemPhotoLibrary;
- (void)configurationClient:(id)arg1 didChangeStateForServiceIdentifiers:(id)arg2;
- (void)startListeningForServiceStateChanges;
- (void)startListeningForSystemLibraryChanges;
- (void)fetchMPSStateWithCloudServiceStatusInformation:(id)arg1 completion:(CDUnknownBlockType)arg2;
- (void)handleMPSStateWithCompletionHandler:(CDUnknownBlockType)arg1;
- (void)runPeriodicMaintenanceTasksForXPCActivity:(id)arg1;
- (void)checkInWithPeriodicMaintenanceXPCActivity;
- (void)startListeningForEventsTriggeringMaintenance;
- (id)initWithServiceManager:(id)arg1;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.