text
stringlengths
1
1.05M
<gh_stars>100-1000 //index.js //获取应用实例 var app = getApp() Page({ data: { motto: '预约会议', currentDate: new Date(), meetingRooms: ['会议室1', '会议室2'] }, //事件处理函数 formSubmit: function() { var that = this; // 获取天气信息 wx.request({ url: 'https://liuanchen.com/w/meeting', method: 'POST', header: { 'content-type': 'application/json' }, data: { meetingDate: that.getData('meetingDate'), meetingTime: that.getData('meetingTime'), meetingRoorm: that.getData('meetingRoom'), title: that.getData('title'), content: that.getData('content') }, success: function(res) { wx.navigateTo({ url: '../detail/detail' }) }, fail: function(error) { that.setData({ errMsg: error.errMsg }) } }) }, onLoad: function () { } })
<reponame>rpsubc8/esp32gameboy #include <stdio.h> #include "mem.h" #include "rom.h" #include "interrupt.h" #include "gbConfig.h" #define set_HL(x) do {unsigned int macro = (x); c.L = macro&0xFF; c.H = macro>>8;} while(0) #define set_BC(x) do {unsigned int macro = (x); c.C = macro&0xFF; c.B = macro>>8;} while(0) #define set_DE(x) do {unsigned int macro = (x); c.E = macro&0xFF; c.D = macro>>8;} while(0) #define set_AF(x) do {unsigned int macro = (x); c.F = macro&0xFF; c.A = macro>>8;} while(0) #define get_AF() ((c.A<<8) | c.F) #define get_BC() ((c.B<<8) | c.C) #define get_DE() ((c.D<<8) | c.E) #define get_HL() ((c.H<<8) | c.L) /* Flags */ #define set_Z(x) c.F = ((c.F&0x7F) | ((x)<<7)) #define set_N(x) c.F = ((c.F&0xBF) | ((x)<<6)) #define set_H(x) c.F = ((c.F&0xDF) | ((x)<<5)) #define set_C(x) c.F = ((c.F&0xEF) | ((x)<<4)) #define flag_Z !!((c.F & 0x80)) #define flag_N !!((c.F & 0x40)) #define flag_H !!((c.F & 0x20)) #define flag_C !!((c.F & 0x10)) struct CPU { unsigned char H; unsigned char L; unsigned char D; unsigned char E; unsigned char B; unsigned char C; unsigned char A; unsigned char F; unsigned short SP; unsigned short PC; unsigned int cycles; }; static struct CPU c; static int is_debugged; static int halted; //**************************** int CPUIncCycle(int aux) {//Incrementamos ciclos c.cycles += aux; } //**************************** void cpu_init(void) { set_AF(0x01B0); set_BC(0x0013); set_DE(0x00D8); set_HL(0x014D); c.SP = 0xFFFE; c.PC = 0x0100; c.cycles = 0; ResetDMAPending(); } static void RLC(unsigned char reg) { unsigned char t, old; switch(reg) { case 0: /* B */ old = !!(c.B&0x80); c.B = (c.B << 1) | old; set_C(old); set_Z(!c.B); break; case 1: /* C */ old = !!(c.C&0x80); set_C(old); c.C = c.C<<1 | old; set_Z(!c.C); break; case 2: /* D */ old = !!(c.D&0x80); set_C(old); c.D = c.D<<1 | old; set_Z(!c.D); break; case 3: /* E */ old = !!(c.E&0x80); set_C(old); c.E = c.E<<1 | old; set_Z(!c.E); break; case 4: /* H */ old = !!(c.H&0x80); set_C(old); c.H = c.H<<1 | old; set_Z(!c.H); break; case 5: /* L */ old = !!(c.L&0x80); set_C(old); c.L = c.L<<1 | old; set_Z(!c.L); break; case 6: /* (HL) */ t = mem_get_byte(get_HL()); old = !!(t&0x80); set_C(old); t = t<<1 | old; mem_write_byte(get_HL(), t); set_Z(!t); break; case 7: /* A */ old = !!(c.A&0x80); c.A = (c.A<<1) | old; set_C(old); set_Z(!c.A); break; } set_N(0); set_H(0); } static void RRC(unsigned char reg) { unsigned char t, old; switch(reg) { case 0: /* B */ old = c.B&1; set_C(old); c.B = c.B>>1 | old<<7; set_Z(!c.B); break; case 1: /* C */ old = c.C&1; set_C(old); c.C = c.C>>1 | old<<7; set_Z(!c.C); break; case 2: /* D */ old = c.D&1; set_C(old); c.D = c.D>>1 | old<<7; set_Z(!c.D); break; case 3: /* E */ old = c.E&1; set_C(old); c.E = c.E>>1 | old<<7; set_Z(!c.E); break; case 4: /* H */ old = c.H&1; set_C(old); c.H = c.H>>1 | old<<7; set_Z(!c.H); break; case 5: /* L */ old = c.L&1; set_C(old); c.L = c.L>>1 | old<<7; set_Z(!c.L); break; case 6: /* (HL) */ t = mem_get_byte(get_HL()); old = t; set_C(old); t = t>>1 | old<<7; c.cycles += 2; mem_write_byte(get_HL(), t); set_Z(!t); break; case 7: /* A */ old = c.A&1; set_C(old); c.A = c.A>>1 | old<<7; set_Z(!c.A); break; } set_N(0); set_H(0); } static void RL(unsigned char reg) { unsigned char t, t2; switch(reg) { case 0: /* B */ t2 = flag_C; set_C(!!(c.B&0x80)); c.B = (c.B << 1) | !!(t2); set_Z(!c.B); break; case 1: /* C */ t2 = flag_C; set_C(!!(c.C&0x80)); c.C = (c.C << 1) | !!(t2); set_Z(!c.C); break; case 2: /* D */ t2 = flag_C; set_C(!!(c.D&0x80)); c.D = (c.D << 1) | !!(t2); set_Z(!c.D); break; case 3: /* E */ t2 = flag_C; set_C(!!(c.E&0x80)); c.E = (c.E << 1) | !!(t2); set_Z(!c.E); break; case 4: /* H */ t2 = flag_C; set_C(!!(c.H&0x80)); c.H = (c.H << 1) | !!(t2); set_Z(!c.H); break; case 5: /* L */ t2 = flag_C; set_C(!!(c.L&0x80)); c.L = (c.L << 1) | !!(t2); set_Z(!c.L); break; case 6: /* (HL) */ t = mem_get_byte(get_HL()); t2 = flag_C; set_C(!!(t&0x80)); t = (t << 1) | !!(t2); mem_write_byte(get_HL(), t); set_Z(!t); c.cycles += 2; break; case 7: /* A */ t2 = flag_C; set_C(!!(c.A&0x80)); c.A = (c.A << 1) | t2; set_Z(!c.A); break; } set_N(0); set_H(0); } static void RR(unsigned char reg) { unsigned char t, t2; switch(reg) { case 0: /* B */ t2 = flag_C; set_C(c.B&1); c.B = (c.B >> 1) | t2<<7; set_Z(!c.B); break; case 1: /* C */ t2 = flag_C; set_C(c.C&1); c.C = (c.C >> 1) | t2<<7; set_Z(!c.C); break; case 2: /* D */ t2 = flag_C; set_C(c.D&1); c.D = (c.D >> 1) | t2<<7; set_Z(!c.D); break; case 3: /* E */ t2 = flag_C; set_C(c.E&1); c.E = (c.E >> 1) | t2<<7; set_Z(!c.E); break; case 4: /* H */ t2 = flag_C; set_C(c.H&1); c.H = (c.H >> 1) | t2<<7; set_Z(!c.H); break; case 5: /* L */ t2 = flag_C; set_C(c.L&1); c.L = (c.L >> 1) | t2<<7; set_Z(!c.L); break; case 6: /* (HL) */ t = mem_get_byte(get_HL()); t2 = flag_C; set_C(t&1); t = (t >> 1) | t2<<7; set_Z(!t); mem_write_byte(get_HL(), t); c.cycles += 2; break; case 7: /* A */ t2 = flag_C; set_C(c.A&1); c.A = (c.A >> 1) | (t2<<7); set_Z(!c.A); break; } set_N(0); set_H(0); } static void SLA(unsigned char reg) { unsigned char t; switch(reg) { case 0: /* B */ set_C(!!(c.B & 0x80)); c.B = c.B << 1; set_Z(!c.B); break; case 1: /* C */ set_C(!!(c.C & 0x80)); c.C = c.C << 1; set_Z(!c.C); break; case 2: /* D */ set_C(!!(c.D & 0x80)); c.D = c.D << 1; set_Z(!c.D); break; case 3: /* E */ set_C(!!(c.E & 0x80)); c.E = c.E << 1; set_Z(!c.E); break; case 4: /* H */ set_C(!!(c.H & 0x80)); c.H = c.H << 1; set_Z(!c.H); break; case 5: /* L */ set_C(!!(c.L & 0x80)); c.L = c.L << 1; set_Z(!c.L); break; case 6: /* (HL) */ t = mem_get_byte(get_HL()); set_C(!!(t & 0x80)); t = t << 1; mem_write_byte(get_HL(), t); set_Z(!t); c.cycles += 2; break; case 7: /* A */ set_C(!!(c.A & 0x80)); c.A = c.A << 1; set_Z(!c.A); break; } set_H(0); set_N(0); } static void SRA(unsigned char reg) { unsigned char old, t; switch(reg) { case 0: /* B */ set_C(c.B&1); old = c.B&0x80; c.B = c.B >> 1 | old; set_Z(!c.B); break; case 1: /* C */ set_C(c.C&1); old = c.C&0x80; c.C = c.C >> 1 | old; set_Z(!c.C); break; case 2: /* D */ set_C(c.D&1); old = c.D&0x80; c.D = c.D >> 1 | old; set_Z(!c.D); break; case 3: /* E */ set_C(c.E&1); old = c.E&0x80; c.E = c.E >> 1 | old; set_Z(!c.E); break; case 4: /* H */ set_C(c.H&1); old = c.H&0x80; c.H = c.H >> 1 | old; set_Z(!c.H); break; case 5: /* L */ set_C(c.L&1); old = c.L&0x80; c.L = c.L >> 1 | old; set_Z(!c.L); break; case 6: /* (HL) */ t = mem_get_byte(get_HL()); set_C(t&1); old = t&0x80; t = t >> 1 | old; mem_write_byte(get_HL(), t); set_Z(!t); break; case 7: /* A */ set_C(c.A&1); old = c.A&0x80; c.A = c.A >> 1 | old; set_Z(!c.A); break; } set_H(0); set_N(0); } static void SRL(unsigned char reg) { unsigned char t; switch(reg) { case 0: /* B */ set_C(c.B & 1); c.B = c.B >> 1; set_Z(!c.B); break; case 1: /* C */ set_C(c.C & 1); c.C = c.C >> 1; set_Z(!c.C); break; case 2: /* D */ set_C(c.D & 1); c.D = c.D >> 1; set_Z(!c.D); break; case 3: /* E */ set_C(c.E & 1); c.E = c.E >> 1; set_Z(!c.E); break; case 4: /* H */ set_C(c.H & 1); c.H = c.H >> 1; set_Z(!c.H); break; case 5: /* L */ set_C(c.L & 1); c.L = c.L >> 1; set_Z(!c.L); break; case 6: /* (HL) */ t = mem_get_byte(get_HL()); set_C(t & 1); t = t >> 1; mem_write_byte(get_HL(), t); set_Z(!t); c.cycles += 2; break; case 7: /* A */ set_C(c.A & 1); c.A = c.A >> 1; set_Z(!c.A); break; } set_H(0); set_N(0); } static void SWAP(unsigned char reg) { unsigned char t; switch(reg) { case 0: /* B */ c.B = ((c.B&0xF)<<4) | ((c.B&0xF0)>>4); c.F = (!c.B)<<7; break; case 1: /* C */ c.C = ((c.C&0xF)<<4) | ((c.C&0xF0)>>4); c.F = (!c.C)<<7; break; case 2: /* D */ c.D = ((c.D&0xF)<<4) | ((c.D&0xF0)>>4); c.F = (!c.D)<<7; break; case 3: /* E */ c.E = ((c.E&0xF)<<4) | ((c.E&0xF0)>>4); c.F = (!c.E)<<7; break; case 4: /* H */ c.H = ((c.H&0xF)<<4) | ((c.H&0xF0)>>4); c.F = (!c.H)<<7; break; case 5: /* L */ c.L = ((c.L&0xF)<<4) | ((c.L&0xF0)>>4); c.F = (!c.L)<<7; break; case 6: /* (HL) */ t = mem_get_byte(get_HL()); t = ((t&0xF)<<4) | ((t&0xF0)>>4); mem_write_byte(get_HL(), t); c.F = (!t)<<7; c.cycles += 2; break; case 7: /* A */ c.A = ((c.A&0xF)<<4) | ((c.A&0xF0)>>4); c.F = (!c.A)<<7; break; } } static void BIT(unsigned char bit, unsigned char reg) { unsigned char t, f = 0 /* Make GCC happy */; switch(reg) { case 0: /* B */ f = !(c.B & bit); break; case 1: /* C */ f = !(c.C & bit); break; case 2: /* D */ f = !(c.D & bit); break; case 3: /* E */ f = !(c.E & bit); break; case 4: /* H */ f = !(c.H & bit); break; case 5: /* L */ f = !(c.L & bit); break; case 6: /* (HL) */ t = mem_get_byte(get_HL()); f = !(t & bit); c.cycles += 1; break; case 7: /* A */ f = !(c.A & bit); break; } set_Z(f); set_N(0); set_H(1); } static void RES(unsigned char bit, unsigned char reg) { unsigned char t; switch(reg) { case 0: /* B */ c.B &= ~bit; break; case 1: /* C */ c.C &= ~bit; break; case 2: /* D */ c.D &= ~bit; break; case 3: /* E */ c.E &= ~bit; break; case 4: /* H */ c.H &= ~bit; break; case 5: /* L */ c.L &= ~bit; break; case 6: /* (HL) */ t = mem_get_byte(get_HL()); t &= ~bit; mem_write_byte(get_HL(), t); c.cycles += 2; break; case 7: /* A */ c.A &= ~bit; break; } } static void SET(unsigned char bit, unsigned char reg) { unsigned char t; switch(reg) { case 0: /* B */ c.B |= bit; break; case 1: /* C */ c.C |= bit; break; case 2: /* D */ c.D |= bit; break; case 3: /* E */ c.E |= bit; break; case 4: /* H */ c.H |= bit; break; case 5: /* L */ c.L |= bit; break; case 6: /* (HL) */ t = mem_get_byte(get_HL()); t |= bit; mem_write_byte(get_HL(), t); c.cycles += 2; break; case 7: /* A */ c.A |= bit; break; } } /* 00000xxx = RLC xxx 00001xxx = RRC xxx 00010xxx = RL xxx 00011xxx = RR xxx 00100xxx = SLA xxx 00101xxx = SRA xxx 00110xxx = SWAP xxx 00111xxx = SRL xxx 01yyyxxx = BIT yyy, xxx 10yyyxxx = RES yyy, xxx 11yyyxxx = SET yyy, xxx */ static void decode_CB(unsigned char t) { unsigned char reg, opcode, bit; void (*f[])(unsigned char) = {RLC, RRC, RL, RR, SLA, SRA, SWAP, SRL}; void (*f2[])(unsigned char, unsigned char) = {BIT, RES, SET}; reg = t&7; opcode = t>>3; if(opcode < 8) { f[opcode](reg); return; } bit = opcode&7; opcode >>= 3; f2[opcode-1](1<<bit, reg); } void cpu_interrupt(unsigned short vector) { halted = 0; c.SP -= 2; mem_write_word(c.SP, c.PC); c.PC = vector; interrupt_disable(); } unsigned int cpu_get_cycles(void) { return c.cycles; } void cpu_print_debug(void) { #ifdef use_lib_log_serial printf("%04X: %02X\n", c.PC, mem_get_byte(c.PC)); printf("\tAF: %02X%02X, BC: %02X%02X, DE: %02X%02X, HL: %02X%02X SP: %04X, cycles %d\n", c.A, c.F, c.B, c.C, c.D, c.E, c.H, c.L, c.SP, c.cycles); #endif } int cpu_cycle(void) { unsigned char b, t; unsigned short s; unsigned int i; if(halted) { c.cycles += 1; return 1; } if(interrupt_flush()) { halted = 0; } b = mem_get_byte(c.PC); #ifdef EBUG // if(c.PC == 0x2F38 && c.cycles > 10000000) // if(c.PC == 0xff87 && c.cycles > 14000000) // is_debugged = 0; #endif if(is_debugged) { cpu_print_debug(); } switch(b) { case 0x00: /* NOP */ c.PC++; c.cycles += 1; break; case 0x01: /* LD BC, imm16 */ s = mem_get_word(c.PC+1); set_BC(s); c.PC += 3; c.cycles += 3; break; case 0x02: /* LD (BC), A */ mem_write_byte(get_BC(), c.A); c.PC += 1; c.cycles += 2; break; case 0x03: /* INC BC */ set_BC(get_BC()+1); c.PC += 1; c.cycles += 2; break; case 0x04: /* INC B */ set_H((c.B&0xF) == 0xF); c.B++; set_Z(!c.B); set_N(0); c.PC += 1; c.cycles += 1; break; case 0x05: /* DEC B */ c.B--; set_Z(!c.B); set_N(1); set_H((c.B & 0xF) == 0xF); c.PC += 1; c.cycles += 1; break; case 0x06: /* LD B, imm8 */ c.B = mem_get_byte(c.PC+1); c.PC += 2; c.cycles += 2; break; case 0x07: /* RLCA */ RLC(7); set_Z(0); c.PC += 1; c.cycles += 1; break; case 0x08: /* LD (imm16), SP */ mem_write_word(mem_get_word(c.PC+1), c.SP); c.PC += 3; c.cycles += 5; break; case 0x09: /* ADD HL, BC */ i = get_HL() + get_BC(); set_N(0); set_C(i >= 0x10000); set_H((i&0xFFF) < (get_HL()&0xFFF)); set_HL(i&0xFFFF); c.PC += 1; c.cycles += 2; break; case 0x0A: /* LD A, (BC) */ c.A = mem_get_byte(get_BC()); c.PC += 1; c.cycles += 2; break; case 0x0B: /* DEC BC */ s = get_BC(); s--; set_BC(s); c.PC += 1; c.cycles += 2; break; case 0x0C: /* INC C */ set_H((c.C&0xF) == 0xF); c.C++; set_Z(!c.C); set_N(0); c.PC += 1; c.cycles += 1; break; case 0x0D: /* DEC C */ set_H((c.C&0xF) == 0); c.C--; set_Z(!c.C); set_N(1); c.PC += 1; c.cycles += 1; break; case 0x0E: /* LD C, imm8 */ c.C = mem_get_byte(c.PC+1); c.PC += 2; c.cycles += 2; break; case 0x0F: /* RRCA */ RRC(7); set_Z(0); c.PC += 1; c.cycles += 1; break; case 0x11: /* LD DE, imm16 */ s = mem_get_word(c.PC+1); set_DE(s); c.PC += 3; c.cycles += 3; break; case 0x12: /* LD (DE), A */ mem_write_byte(get_DE(), c.A); c.PC += 1; c.cycles += 2; break; case 0x13: /* INC DE */ s = get_DE(); s++; set_DE(s); c.PC += 1; c.cycles += 2; break; case 0x14: /* INC D */ set_H((c.D&0xF) == 0xF); c.D++; set_Z(!c.D); set_N(0); c.PC += 1; c.cycles += 1; break; case 0x15: /* DEC D */ c.D--; set_Z(!c.D); set_N(1); set_H((c.D & 0xF) == 0xF); c.PC += 1; c.cycles += 1; break; case 0x16: /* LD D, imm8 */ c.D = mem_get_byte(c.PC+1); c.PC += 2; c.cycles += 2; break; case 0x17: /* RLA */ RL(7); set_Z(0); c.PC += 1; c.cycles += 1; break; case 0x18: /* JR rel8 */ c.PC += (signed char)mem_get_byte(c.PC+1) + 2; c.cycles += 3; break; case 0x19: /* ADD HL, DE */ i = get_HL() + get_DE(); set_H((i&0xFFF) < (get_HL()&0xFFF)); set_HL(i); set_N(0); set_C(i > 0xFFFF); c.PC += 1; c.cycles += 3; break; case 0x1A: /* LD A, (DE) */ c.A = mem_get_byte(get_DE()); c.PC += 1; c.cycles += 2; break; case 0x1B: /* DEC DE */ s = get_DE(); s--; set_DE(s); c.PC += 1; c.cycles += 2; break; case 0x1C: /* INC E */ set_H((c.E&0xF) == 0xF); c.E++; set_Z(!c.E); set_N(0); c.PC += 1; c.cycles += 1; break; case 0x1D: /* DEC E */ c.E--; set_Z(!c.E); set_N(1); set_H((c.E & 0xF) == 0xF); c.PC += 1; c.cycles += 1; break; case 0x1E: /* LD E, imm8 */ c.E = mem_get_byte(c.PC+1); c.PC += 2; c.cycles += 2; break; case 0x1F: /* RR A */ RR(7); set_Z(0); c.PC += 1; c.cycles += 1; break; case 0x20: /* JR NZ, rel8 */ if(flag_Z == 0) { c.PC += (signed char)mem_get_byte(c.PC+1) + 2; c.cycles += 3; } else { c.PC += 2; c.cycles += 2; } break; case 0x21: /* LD HL, imm16 */ s = mem_get_word(c.PC+1); set_HL(s); c.PC += 3; c.cycles += 3; break; case 0x22: /* LDI (HL), A */ i = get_HL(); mem_write_byte(i, c.A); i++; set_HL(i); c.PC += 1; c.cycles += 2; break; case 0x23: /* INC HL */ s = get_HL(); s++; set_HL(s); c.PC += 1; c.cycles += 2; break; case 0x24: /* INC H */ c.H++; set_Z(!c.H); set_H((c.H&0xF) == 0); set_N(0); c.PC += 1; c.cycles += 1; break; case 0x25: /* DEC H */ c.H--; set_Z(!c.H); set_N(1); set_H((c.H & 0xF) == 0xF); c.PC += 1; c.cycles += 1; break; case 0x26: /* LD H, imm8 */ c.H = mem_get_byte(c.PC+1); c.PC += 2; c.cycles += 2; break; case 0x27: /* DAA */ s = c.A; if(flag_N) { if(flag_H) s = (s - 0x06)&0xFF; if(flag_C) s -= 0x60; } else { if(flag_H || (s & 0xF) > 9) s += 0x06; if(flag_C || s > 0x9F) s += 0x60; } c.A = s; set_H(0); set_Z(!c.A); if(s >= 0x100) set_C(1); c.PC += 1; c.cycles += 1; break; case 0x28: /* JR Z, rel8 */ if(flag_Z == 1) { c.PC += (signed char)mem_get_byte(c.PC+1) + 2; c.cycles += 3; } else { c.PC += 2; c.cycles += 2; } break; case 0x29: /* ADD HL, HL */ i = get_HL()*2; set_H((i&0x7FF) < (get_HL()&0x7FF)); set_C(i > 0xFFFF); set_HL(i); set_N(0); c.PC += 1; c.cycles += 2; break; case 0x2A: /* LDI A, (HL) */ s = get_HL(); c.A = mem_get_byte(s); set_HL(s+1); c.PC += 1; c.cycles += 2; break; case 0x2B: /* DEC HL */ set_HL(get_HL()-1); c.PC += 1; c.cycles += 2; break; case 0x2C: /* INC L */ c.L++; set_Z(!c.L); set_N(0); set_H((c.L & 0xF) == 0x00); c.PC += 1; c.cycles += 1; break; case 0x2D: /* DEC L */ c.L--; set_Z(!c.L); set_N(1); set_H((c.L & 0xF) == 0xF); c.PC += 1; c.cycles += 1; break; case 0x2E: /* LD L, imm8 */ c.L = mem_get_byte(c.PC+1); c.PC += 2; c.cycles += 2; break; case 0x2F: /* CPL */ c.A = ~c.A; set_N(1); set_H(1); c.PC += 1; c.cycles += 1; break; case 0x30: /* JR NC, rel8 */ if(flag_C == 0) { c.PC += (signed char)mem_get_byte(c.PC+1) + 2; c.cycles += 3; } else { c.PC += 2; c.cycles += 2; } break; case 0x31: /* LD SP, imm16 */ c.SP = mem_get_word(c.PC+1); c.PC += 3; c.cycles += 3; break; case 0x32: /* LDD (HL), A */ i = get_HL(); mem_write_byte(i, c.A); set_HL(i-1); c.PC += 1; c.cycles += 2; break; case 0x33: /* INC SP */ c.SP++; c.PC += 1; c.cycles += 2; break; case 0x34: /* INC (HL) */ t = mem_get_byte(get_HL()); t++; mem_write_byte(get_HL(), t); set_Z(!t); set_N(0); set_H((t & 0xF) == 0); c.PC += 1; c.cycles += 1; break; case 0x35: /* DEC (HL) */ t = mem_get_byte(get_HL()); t--; mem_write_byte(get_HL(), t); set_Z(!t); set_N(1); set_H((t & 0xF) == 0xF); c.PC += 1; c.cycles += 1; break; case 0x36: /* LD (HL), imm8 */ t = mem_get_byte(c.PC+1); mem_write_byte(get_HL(), t); c.PC += 2; c.cycles += 3; break; case 0x37: /* SCF */ set_N(0); set_H(0); set_C(1); c.PC += 1; c.cycles += 1; break; case 0x38: /* JR C, rel8 */ if(flag_C == 1) { c.PC += (signed char)mem_get_byte(c.PC+1) + 2; c.cycles += 3; } else { c.PC += 2; c.cycles += 2; } break; case 0x39: /* ADD HL, SP */ i = get_HL() + c.SP; set_H((i&0x7FF) < (get_HL()&0x7FF)); set_C(i > 0xFFFF); set_N(0); set_HL(i); c.PC += 1; c.cycles += 2; break; case 0x3A: /* LDD A, (HL) */ c.A = mem_get_byte(get_HL()); set_HL(get_HL()-1); c.PC += 1; c.cycles += 2; break; case 0x3B: /* DEC SP */ c.SP--; c.PC += 1; c.cycles += 2; break; case 0x3C: /* INC A */ c.A++; set_Z(!c.A); set_H((c.A&0xF) == 0); set_N(0); c.PC += 1; c.cycles += 1; break; case 0x3D: /* DEC A */ c.A--; set_Z(!c.A); set_N(1); set_H((c.A & 0xF) == 0xF); c.PC += 1; c.cycles += 1; break; case 0x3E: /* LD A, imm8 */ c.A = mem_get_byte(c.PC+1); c.PC += 2; c.cycles += 2; break; case 0x3F: /* CCF */ set_N(0); set_H(0); set_C(!flag_C); c.PC += 1; c.cycles += 1; break; case 0x40: /* LD B, B */ c.B = c.B; c.PC += 1; c.cycles += 1; break; case 0x41: /* LD B, C */ c.B = c.C; c.PC += 1; c.cycles += 1; break; case 0x42: /* LD B, D */ c.B = c.D; c.PC += 1; c.cycles += 1; break; case 0x43: /* LD B, E */ c.B = c.E; c.PC += 1; c.cycles += 1; break; case 0x44: /* LD B, H */ c.B = c.H; c.PC += 1; c.cycles += 1; break; case 0x45: /* LD B, L */ c.B = c.L; c.PC += 1; c.cycles += 1; break; case 0x46: /* LD B, (HL) */ c.B = mem_get_byte(get_HL()); c.PC += 1; c.cycles += 2; break; case 0x47: /* LD B, A */ c.B = c.A; c.PC += 1; c.cycles += 1; break; case 0x48: /* LD C, B */ c.C = c.B; c.PC += 1; c.cycles += 1; break; case 0x49: /* LD C, C */ c.C = c.C; c.PC += 1; c.cycles += 1; break; case 0x4A: /* LD C, D */ c.C = c.D; c.PC += 1; c.cycles += 1; break; case 0x4B: /* LD C, E */ c.C = c.E; c.PC += 1; c.cycles += 1; break; case 0x4C: /* LD C, H */ c.C = c.H; c.PC += 1; c.cycles += 1; break; case 0x4D: /* LD C, L */ c.C = c.L; c.PC += 1; c.cycles += 1; break; case 0x4E: /* LD C, (HL) */ c.C = mem_get_byte(get_HL()); c.PC += 1; c.cycles += 2; break; case 0x4F: /* LD C, A */ c.C = c.A; c.PC += 1; c.cycles += 1; break; case 0x50: /* LD D, B */ c.D = c.B; c.PC += 1; c.cycles += 1; break; case 0x51: /* LD D, C */ c.D = c.C; c.PC += 1; c.cycles += 1; break; case 0x52: /* LD D, D */ c.D = c.D; c.PC += 1; c.cycles += 1; break; case 0x53: /* LD D, E */ c.D = c.E; c.PC += 1; c.cycles += 1; break; case 0x54: /* LD D, H */ c.D = c.H; c.PC += 1; c.cycles += 1; break; case 0x55: /* LD D, L */ c.D = c.L; c.PC += 1; c.cycles += 1; break; case 0x56: /* LD D, (HL) */ c.D = mem_get_byte(get_HL()); c.PC += 1; c.cycles += 2; break; case 0x57: /* LD D, A */ c.D = c.A; c.PC += 1; c.cycles += 1; break; case 0x58: /* LD E, B */ c.E = c.B; c.PC += 1; c.cycles += 1; break; case 0x59: /* LD E, C */ c.E = c.C; c.PC += 1; c.cycles += 1; break; case 0x5A: /* LD E, D */ c.E = c.D; c.PC += 1; c.cycles += 1; break; case 0x5B: /* LD E, E */ c.E = c.E; c.PC += 1; c.cycles += 1; break; case 0x5C: /* LD E, H */ c.E = c.H; c.PC += 1; c.cycles += 1; break; case 0x5D: /* LD E, L */ c.E = c.L; c.PC += 1; c.cycles += 1; break; case 0x5E: /* LD E, (HL) */ c.E = mem_get_byte(get_HL()); c.PC += 1; c.cycles += 2; break; case 0x5F: /* LD E, A */ c.E = c.A; c.PC += 1; c.cycles += 1; break; case 0x60: /* LD H, B */ c.H = c.B; c.PC += 1; c.cycles += 1; break; case 0x61: /* LD H, C */ c.H = c.C; c.PC += 1; c.cycles += 1; break; case 0x62: /* LD H, D */ c.H = c.D; c.PC += 1; c.cycles += 1; break; case 0x63: /* LD H, E */ c.H = c.E; c.PC += 1; c.cycles += 1; break; case 0x64: /* LD H, H */ c.H = c.H; c.PC += 1; c.cycles += 1; break; case 0x65: /* LD H, L */ c.H = c.L; c.PC += 1; c.cycles += 1; break; case 0x66: /* LD H, (HL) */ c.H = mem_get_byte(get_HL()); c.PC += 1; c.cycles += 2; break; case 0x67: /* LD H, A */ c.H = c.A; c.PC += 1; c.cycles += 1; break; case 0x68: /* LD L, B */ c.L = c.B; c.PC += 1; c.cycles += 1; break; case 0x69: /* LD L, C */ c.L = c.C; c.PC += 1; c.cycles += 1; break; case 0x6A: /* LD L, D */ c.L = c.D; c.PC += 1; c.cycles += 1; break; case 0x6B: /* LD L, E */ c.L = c.E; c.PC += 1; c.cycles += 1; break; case 0x6C: /* LD L, H */ c.L = c.H; c.PC += 1; c.cycles += 1; break; case 0x6D: /* LD L, L */ c.L = c.L; c.PC += 1; c.cycles += 1; break; case 0x6E: /* LD L, (HL) */ c.L = mem_get_byte(get_HL()); c.PC += 1; c.cycles += 2; break; case 0x6F: /* LD L, A */ c.L = c.A; c.PC += 1; c.cycles += 1; break; case 0x70: /* LD (HL), B */ mem_write_byte(get_HL(), c.B); c.PC += 1; c.cycles += 2; break; case 0x71: /* LD (HL), C */ mem_write_byte(get_HL(), c.C); c.PC += 1; c.cycles += 2; break; case 0x72: /* LD (HL), D */ mem_write_byte(get_HL(), c.D); c.PC += 1; c.cycles += 2; break; case 0x73: /* LD (HL), E */ mem_write_byte(get_HL(), c.E); c.PC += 1; c.cycles += 2; break; case 0x74: /* LD (HL), H */ mem_write_byte(get_HL(), c.H); c.PC += 1; c.cycles += 2; break; case 0x75: /* LD (HL), L */ mem_write_byte(get_HL(), c.L); c.PC += 1; c.cycles += 2; break; case 0x76: /* HALT */ halted = 1; c.PC += 1; c.cycles += 1; break; case 0x77: /* LD (HL), A */ mem_write_byte(get_HL(), c.A); c.PC += 1; c.cycles += 2; break; case 0x78: /* LD A, B */ c.A = c.B; c.PC += 1; c.cycles += 1; break; case 0x79: /* LD A, C */ c.A = c.C; c.PC += 1; c.cycles += 1; break; case 0x7A: /* LD A, D */ c.A = c.D; c.PC += 1; c.cycles += 1; break; case 0x7B: /* LD A, E */ c.A = c.E; c.PC += 1; c.cycles += 1; break; case 0x7C: /* LD A, H */ c.A = c.H; c.PC += 1; c.cycles += 1; break; case 0x7D: /* LD A, L */ c.A = c.L; c.PC += 1; c.cycles += 1; break; case 0x7E: /* LD A, (HL) */ c.A = mem_get_byte(get_HL()); c.PC += 1; c.cycles += 2; break; case 0x7F: /* LD A, A */ c.A = c.A; c.PC += 1; c.cycles += 1; break; case 0x80: /* ADD B */ i = c.A + c.B; set_H((c.A&0xF)+(c.B&0xF) > 0xF); set_C(i > 0xFF); set_N(0); c.A = i; set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x81: /* ADD C */ i = c.A + c.C; set_H((c.A&0xF)+(c.C&0xF) > 0xF); set_C(i > 0xFF); set_N(0); c.A = i; set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x82: /* ADD D */ i = c.A + c.D; set_H((c.A&0xF)+(c.D&0xF) > 0xF); set_C(i > 0xFF); set_N(0); c.A = i; set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x83: /* ADD E */ i = c.A + c.E; set_H((c.A&0xF)+(c.E&0xF) > 0xF); set_C(i > 0xFF); set_N(0); c.A = i; set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x84: /* ADD H */ i = c.A + c.H; set_H((c.A&0xF)+(c.H&0xF) > 0xF); set_C(i > 0xFF); set_N(0); c.A = i; set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x85: /* ADD L */ i = c.A + c.L; set_H((c.A&0xF)+(c.L&0xF) > 0xF); set_C(i > 0xFF); set_N(0); c.A = i; set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x86: /* ADD (HL) */ i = c.A + mem_get_byte(get_HL()); set_H((i&0xF) < (c.A&0xF)); set_C(i > 0xFF); set_N(0); c.A = i; set_Z(!c.A); c.PC += 1; c.cycles += 2; break; case 0x87: /* ADD A */ i = c.A + c.A; set_H((c.A&0xF)+(c.A&0xF) > 0xF); set_C(i > 0xFF); set_N(0); c.A = i; set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x88: /* ADC B */ i = c.A + c.B + flag_C >= 0x100; set_N(0); set_H(((c.A&0xF) + (c.B&0xF) + flag_C) >= 0x10); c.A = c.A + c.B + flag_C; set_C(i); set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x89: /* ADC C */ i = c.A + c.C + flag_C >= 0x100; set_N(0); set_H(((c.A&0xF) + (c.C&0xF) + flag_C) >= 0x10); c.A = c.A + c.C + flag_C; set_C(i); set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x8A: /* ADC D */ i = c.A + c.D + flag_C >= 0x100; set_N(0); set_H(((c.A&0xF) + (c.D&0xF) + flag_C) >= 0x10); c.A = c.A + c.D + flag_C; set_C(i); set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x8B: /* ADC E */ i = c.A + c.E + flag_C >= 0x100; set_N(0); set_H(((c.A&0xF) + (c.E&0xF) + flag_C) >= 0x10); c.A = c.A + c.E + flag_C; set_C(i); set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x8C: /* ADC H */ i = c.A + c.H + flag_C >= 0x100; set_N(0); set_H(((c.A&0xF) + (c.H&0xF) + flag_C) >= 0x10); c.A = c.A + c.H + flag_C; set_C(i); set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x8D: /* ADC L */ i = c.A + c.L + flag_C >= 0x100; set_N(0); set_H(((c.A&0xF) + (c.L&0xF) + flag_C) >= 0x10); c.A = c.A + c.L + flag_C; set_C(i); set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x8E: /* ADC (HL) */ t = mem_get_byte(get_HL()); i = c.A + t + flag_C >= 0x100; set_N(0); set_H(((c.A&0xF) + (t&0xF) + flag_C) >= 0x10); c.A = c.A + t + flag_C; set_C(i); set_Z(!c.A); c.PC += 1; c.cycles += 2; break; case 0x8F: /* ADC A */ i = c.A + c.A + flag_C >= 0x100; set_N(0); set_H(((c.A&0xF) + (c.A&0xF) + flag_C) >= 0x10); c.A = c.A + c.A + flag_C; set_C(i); set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x90: /* SUB B */ set_C((c.A - c.B) < 0); set_H(((c.A - c.B)&0xF) > (c.A&0xF)); c.A -= c.B; set_Z(!c.A); set_N(1); c.PC += 1; c.cycles += 1; break; case 0x91: /* SUB C */ set_C((c.A - c.C) < 0); set_H(((c.A - c.C)&0xF) > (c.A&0xF)); c.A -= c.C; set_Z(!c.A); set_N(1); c.PC += 1; c.cycles += 1; break; case 0x92: /* SUB D */ set_C((c.A - c.D) < 0); set_H(((c.A - c.D)&0xF) > (c.A&0xF)); c.A -= c.D; set_Z(!c.A); set_N(1); c.PC += 1; c.cycles += 1; break; case 0x93: /* SUB E */ set_C((c.A - c.E) < 0); set_H(((c.A - c.E)&0xF) > (c.A&0xF)); c.A -= c.E; set_Z(!c.A); set_N(1); c.PC += 1; c.cycles += 1; break; case 0x94: /* SUB H */ set_C((c.A - c.H) < 0); set_H(((c.A - c.H)&0xF) > (c.A&0xF)); c.A -= c.H; set_Z(!c.A); set_N(1); c.PC += 1; c.cycles += 1; break; case 0x95: /* SUB L */ set_C((c.A - c.L) < 0); set_H(((c.A - c.L)&0xF) > (c.A&0xF)); c.A -= c.L; set_Z(!c.A); set_N(1); c.PC += 1; c.cycles += 1; break; case 0x96: /* SUB (HL) */ t = mem_get_byte(get_HL()); set_C((c.A - t) < 0); set_H(((c.A - t)&0xF) > (c.A&0xF)); c.A -= t; set_Z(!c.A); set_N(1); c.PC += 1; c.cycles += 2; break; case 0x97: /* SUB A */ set_C(0); set_H(0); c.A = 0; set_Z(1); set_N(1); c.PC += 1; c.cycles += 1; break; case 0x98: /* SBC B */ t = flag_C + c.B; set_H(((c.A&0xF) - (c.B&0xF) - flag_C) < 0); set_C((c.A - c.B - flag_C) < 0); set_N(1); c.A -= t; set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x99: /* SBC C */ t = flag_C + c.C; set_H(((c.A&0xF) - (c.C&0xF) - flag_C) < 0); set_C((c.A - c.C - flag_C) < 0); set_N(1); c.A -= t; set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x9A: /* SBC D */ t = flag_C + c.D; set_H(((c.A&0xF) - (c.D&0xF) - flag_C) < 0); set_C((c.A - c.D - flag_C) < 0); set_N(1); c.A -= t; set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x9B: /* SBC E */ t = flag_C + c.E; set_H(((c.A&0xF) - (c.E&0xF) - flag_C) < 0); set_C((c.A - c.E - flag_C) < 0); set_N(1); c.A -= t; set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x9C: /* SBC H */ t = flag_C + c.H; set_H(((c.A&0xF) - (c.H&0xF) - flag_C) < 0); set_C((c.A - c.H - flag_C) < 0); set_N(1); c.A -= t; set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x9D: /* SBC L */ t = flag_C + c.L; set_H(((c.A&0xF) - (c.L&0xF) - flag_C) < 0); set_C((c.A - c.L - flag_C) < 0); set_N(1); c.A -= t; set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0x9E: /* SBC (HL) */ t = mem_get_byte(get_HL()); b = flag_C + t; set_H(((c.A&0xF) - (t&0xF) - flag_C) < 0); set_C((c.A - t - flag_C) < 0); set_N(1); c.A -= b; set_Z(!c.A); c.PC += 1; c.cycles += 2; break; case 0x9F: /* SBC A */ t = flag_C + c.A; set_H(((c.A&0xF) - (c.A&0xF) - flag_C) < 0); set_C((c.A - c.A - flag_C) < 0); set_N(1); c.A -= t; set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0xA0: /* AND B */ c.A &= c.B; set_Z(!c.A); set_H(1); set_N(0); set_C(0); c.PC += 1; c.cycles += 1; break; case 0xA1: /* AND C */ c.A &= c.C; set_Z(!c.A); set_H(1); set_N(0); set_C(0); c.PC += 1; c.cycles += 1; break; case 0xA2: /* AND D */ c.A &= c.D; set_Z(!c.A); set_H(1); set_N(0); set_C(0); c.PC += 1; c.cycles += 1; break; case 0xA3: /* AND E */ c.A &= c.E; set_Z(!c.A); set_H(1); set_N(0); set_C(0); c.PC += 1; c.cycles += 1; break; case 0xA4: /* AND H */ c.A &= c.H; set_Z(!c.A); set_H(1); set_N(0); set_C(0); c.PC += 1; c.cycles += 1; break; case 0xA5: /* AND L */ c.A &= c.L; set_Z(!c.A); set_H(1); set_N(0); set_C(0); c.PC += 1; c.cycles += 1; break; case 0xA6: /* AND (HL) */ c.A &= mem_get_byte(get_HL()); set_Z(!c.A); set_H(1); set_N(0); set_C(0); c.PC += 1; c.cycles += 1; break; case 0xA7: /* AND A */ set_H(1); set_N(0); set_C(0); set_Z(!c.A); c.PC += 1; c.cycles += 1; break; case 0xA8: /* XOR B */ c.A ^= c.B; c.F = (!c.A)<<7; c.PC += 1; c.cycles += 1; break; case 0xA9: /* XOR C */ c.A ^= c.C; c.F = (!c.A)<<7; c.PC += 1; c.cycles += 1; break; case 0xAA: /* XOR D */ c.A ^= c.D; c.F = (!c.A)<<7; c.PC += 1; c.cycles += 1; break; case 0xAB: /* XOR E */ c.A ^= c.E; c.F = (!c.A)<<7; c.PC += 1; c.cycles += 1; break; case 0xAC: /* XOR H */ c.A ^= c.H; c.F = (!c.A)<<7; c.PC += 1; c.cycles += 1; break; case 0xAD: /* XOR L */ c.A ^= c.L; c.F = (!c.A)<<7; c.PC += 1; c.cycles += 1; break; case 0xAE: /* XOR (HL) */ c.A ^= mem_get_byte(get_HL()); c.F = (!c.A)<<7; c.PC += 1; c.cycles += 1; break; case 0xAF: /* XOR A */ c.A = 0; c.F = 0x80; c.PC += 1; c.cycles += 1; break; case 0xB0: /* OR B */ c.A |= c.B; c.F = (!c.A)<<7; c.PC += 1; c.cycles += 1; break; case 0xB1: /* OR C */ c.A |= c.C; c.F = (!c.A)<<7; c.PC += 1; c.cycles += 1; break; case 0xB2: /* OR D */ c.A |= c.D; c.F = (!c.A)<<7; c.PC += 1; c.cycles += 1; break; case 0xB3: /* OR E */ c.A |= c.E; c.F = (!c.A)<<7; c.PC += 1; c.cycles += 1; break; case 0xB4: /* OR H */ c.A |= c.H; c.F = (!c.A)<<7; c.PC += 1; c.cycles += 1; break; case 0xB5: /* OR L */ c.A |= c.L; c.F = (!c.A)<<7; c.PC += 1; c.cycles += 1; break; case 0xB6: /* OR (HL) */ c.A |= mem_get_byte(get_HL()); c.F = (!c.A)<<7; c.PC += 1; c.cycles += 2; break; case 0xB7: /* OR A */ c.F = (!c.A)<<7; c.PC += 1; c.cycles += 1; break; case 0xB8: /* CP B */ set_C((c.A - c.B) < 0); set_H(((c.A - c.B)&0xF) > (c.A&0xF)); set_Z(c.A == c.B); set_N(1); c.PC += 1; c.cycles += 1; break; case 0xB9: /* CP C */ set_Z(c.A == c.C); set_H(((c.A - c.C)&0xF) > (c.A&0xF)); set_N(1); set_C((c.A - c.C) < 0); c.PC += 1; c.cycles += 1; break; case 0xBA: /* CP D */ set_Z(c.A == c.D); set_H(((c.A - c.D)&0xF) > (c.A&0xF)); set_N(1); set_C((c.A - c.D) < 0); c.PC += 1; c.cycles += 1; break; case 0xBB: /* CP E */ set_Z(c.A == c.E); set_H(((c.A - c.E)&0xF) > (c.A&0xF)); set_N(1); set_C((c.A - c.E) < 0); c.PC += 1; c.cycles += 1; break; case 0xBC: /* CP H */ set_Z(c.A == c.H); set_H(((c.A - c.H)&0xF) > (c.A&0xF)); set_N(1); set_C((c.A - c.H) < 0); c.PC += 1; c.cycles += 1; break; case 0xBD: /* CP L */ set_Z(c.A == c.L); set_H(((c.A - c.L)&0xF) > (c.A&0xF)); set_N(1); set_C((c.A - c.L) < 0); c.PC += 1; c.cycles += 1; break; case 0xBE: /* CP (HL) */ t = mem_get_byte(get_HL()); set_Z(c.A == t); set_H(((c.A - t)&0xF) > (c.A&0xF)); set_N(1); set_C((c.A - t) < 0); c.PC += 1; c.cycles += 1; break; case 0xBF: /* CP A */ set_Z(1); set_H(0); set_N(1); set_C(0); c.PC += 1; c.cycles += 1; break; case 0xC0: /* RET NZ */ if(!flag_Z) { c.PC = mem_get_word(c.SP); c.SP += 2; c.cycles += 3; } else { c.PC += 1; c.cycles += 1; } break; case 0xC1: /* POP BC */ s = mem_get_word(c.SP); set_BC(s); c.SP += 2; c.PC += 1; c.cycles += 3; break; case 0xC2: /* JP NZ, mem16 */ if(flag_Z == 0) { c.PC = mem_get_word(c.PC+1); } else { c.PC += 3; } c.cycles += 3; break; case 0xC3: /* JP imm16 */ c.PC = mem_get_word(c.PC+1); c.cycles += 4; break; case 0xC4: /* CALL NZ, imm16 */ if(flag_Z == 0) { c.SP -= 2; mem_write_word(c.SP, c.PC+3); c.PC = mem_get_word(c.PC+1); c.cycles += 6; } else { c.PC += 3; c.cycles += 3; } break; case 0xC5: /* PUSH BC */ c.SP -= 2; mem_write_word(c.SP, get_BC()); c.PC += 1; c.cycles += 3; break; case 0xC6: /* ADD A, imm8 */ t = mem_get_byte(c.PC+1); set_C((c.A + t) >= 0x100); set_H(((c.A + t)&0xF) < (c.A&0xF)); c.A += t; set_N(0); set_Z(!c.A); c.PC += 2; c.cycles += 2; break; case 0xC7: /* RST 00 */ c.SP -= 2; mem_write_word(c.SP, c.PC+1); c.PC = 0; c.cycles += 3; break; case 0xC8: /* RET Z */ if(flag_Z == 1) { c.PC = mem_get_word(c.SP); c.SP += 2; c.cycles += 3; } else { c.PC += 1; c.cycles += 1; } break; case 0xC9: /* RET */ c.PC = mem_get_word(c.SP); c.SP += 2; c.cycles += 3; break; case 0xCA: /* JP z, mem16 */ if(flag_Z == 1) { c.PC = mem_get_word(c.PC+1); } else { c.PC += 3; } c.cycles += 3; break; case 0xCB: /* RLC/RRC/RL/RR/SLA/SRA/SWAP/SRL/BIT/RES/SET */ decode_CB(mem_get_byte(c.PC+1)); c.PC += 2; c.cycles += 2; break; case 0xCC: /* CALL Z, imm16 */ if(flag_Z == 1) { c.SP -= 2; mem_write_word(c.SP, c.PC+3); c.PC = mem_get_word(c.PC+1); c.cycles += 6; } else { c.PC += 3; c.cycles += 3; } break; case 0xCD: /* call imm16 */ c.SP -= 2; mem_write_word(c.SP, c.PC+3); c.PC = mem_get_word(c.PC+1); c.cycles += 6; break; case 0xCE: /* ADC a, imm8 */ t = mem_get_byte(c.PC+1); i = c.A + t + flag_C >= 0x100; set_N(0); set_H(((c.A&0xF) + (t&0xF) + flag_C) >= 0x10); c.A = c.A + t + flag_C; set_C(i); set_Z(!c.A); c.PC += 2; c.cycles += 2; break; case 0xCF: /* RST 08 */ c.SP -= 2; mem_write_word(c.SP, c.PC+1); c.PC = 0x0008; c.cycles += 4; break; case 0xD0: /* RET NC */ if(flag_C == 0) { c.PC = mem_get_word(c.SP); c.SP += 2; c.cycles += 3; } else { c.PC += 1; c.cycles += 1; } break; case 0xD1: /* POP DE */ s = mem_get_word(c.SP); set_DE(s); c.SP += 2; c.PC += 1; c.cycles += 3; break; case 0xD2: /* JP NC, mem16 */ if(flag_C == 0) { c.PC = mem_get_word(c.PC+1); } else { c.PC += 3; } c.cycles += 3; break; case 0xD4: /* CALL NC, mem16 */ if(flag_C == 0) { c.SP -= 2; mem_write_word(c.SP, c.PC+3); c.PC = mem_get_word(c.PC+1); c.cycles += 6; } else { c.PC += 3; c.cycles += 3; } break; case 0xD5: /* PUSH DE */ c.SP -= 2; mem_write_word(c.SP, get_DE()); c.PC += 1; c.cycles += 3; break; case 0xD6: /* SUB A, imm8 */ t = mem_get_byte(c.PC+1); set_C((c.A - t) < 0); set_H(((c.A - t)&0xF) > (c.A&0xF)); c.A -= t; set_N(1); set_Z(!c.A); c.PC += 2; c.cycles += 2; break; case 0xD7: /* RST 10 */ c.SP -= 2; mem_write_word(c.SP, c.PC+1); c.PC = 0x0010; c.cycles += 4; break; case 0xD8: /* RET C */ if(flag_C == 1) { c.PC = mem_get_word(c.SP); c.SP += 2; c.cycles += 3; } else { c.PC += 1; c.cycles += 1; } break; case 0xDA: /* JP C, mem16 */ if(flag_C) { c.PC = mem_get_word(c.PC+1); } else { c.PC += 3; } c.cycles += 3; break; case 0xDC: /* CALL C, mem16 */ if(flag_C == 1) { c.SP -= 2; mem_write_word(c.SP, c.PC+3); c.PC = mem_get_word(c.PC+1); c.cycles += 6; } else { c.PC += 3; c.cycles += 3; } break; case 0xD9: /* RETI */ c.PC = mem_get_word(c.SP); c.SP += 2; c.cycles += 4; interrupt_enable(); break; case 0xDE: /* SBC A, imm8 */ t = mem_get_byte(c.PC+1); b = flag_C; set_H(((t&0xF) + flag_C) > (c.A&0xF)); set_C(t + flag_C > c.A); set_N(1); c.A -= (b + t); set_Z(!c.A); c.PC += 2; c.cycles += 2; break; case 0xDF: /* RST 18 */ c.SP -= 2; mem_write_word(c.SP, c.PC+1); c.PC = 0x0018; c.cycles += 3; break; case 0xE0: /* LD (FF00 + imm8), A */ t = mem_get_byte(c.PC+1); mem_write_byte(0xFF00 + t, c.A); c.PC += 2; c.cycles += 3; break; case 0xE1: /* POP HL */ i = mem_get_word(c.SP); set_HL(i); c.SP += 2; c.PC += 1; c.cycles += 3; break; case 0xE2: /* LD (FF00 + C), A */ s = 0xFF00 + c.C; mem_write_byte(s, c.A); c.PC += 1; c.cycles += 2; break; case 0xE5: /* PUSH HL */ c.SP -= 2; mem_write_word(c.SP, get_HL()); c.PC += 1; c.cycles += 3; break; case 0xE6: /* AND A, imm8 */ t = mem_get_byte(c.PC+1); set_N(0); set_H(1); set_C(0); c.A = t & c.A; set_Z(!c.A); c.PC += 2; c.cycles += 2; break; case 0xE7: /* RST 20 */ c.SP -= 2; mem_write_word(c.SP, c.PC+1); c.PC = 0x20; c.cycles += 4; break; case 0xE8: /* ADD SP, imm8 */ i = mem_get_byte(c.PC+1); set_Z(0); set_N(0); set_C(((c.SP+i)&0xFF) < (c.SP&0xFF)); set_H(((c.SP+i)&0xF) < (c.SP&0xF)); c.SP = c.SP + (signed char)i; c.PC += 2; c.cycles += 4; break; case 0xE9: /* JP HL */ c.PC = get_HL(); c.cycles += 1; break; case 0xEA: /* LD (mem16), a */ s = mem_get_word(c.PC+1); mem_write_byte(s, c.A); c.PC += 3; c.cycles += 4; break; case 0xEE: /* XOR A, imm8 */ c.A ^= mem_get_byte(c.PC+1); c.F = (!c.A)<<7; c.PC += 2; c.cycles += 2; break; case 0xEF: /* RST 28 */ c.SP -= 2; mem_write_word(c.SP, c.PC+1); c.PC = 0x28; c.cycles += 4; break; case 0xF0: /* LD A, (FF00 + imm8) */ t = mem_get_byte(c.PC+1); c.A = mem_get_byte(0xFF00 + t); c.PC += 2; c.cycles += 3; break; case 0xF1: /* POP AF */ s = mem_get_word(c.SP); set_AF(s&0xFFF0); c.SP += 2; c.PC += 1; c.cycles += 3; break; case 0xF2: /* LD A, (FF00 + c) */ c.A = mem_get_byte(0xFF00 + c.C); c.PC += 1; c.cycles += 2; break; case 0xF3: /* DI */ c.PC += 1; c.cycles += 1; interrupt_disable(); break; case 0xF5: /* PUSH AF */ c.SP -= 2; mem_write_word(c.SP, get_AF()); c.PC += 1; c.cycles += 3; break; case 0xF6: /* OR A, imm8 */ c.A |= mem_get_byte(c.PC+1); c.F = (!c.A)<<7; c.PC += 2; c.cycles += 2; break; case 0xF7: /* RST 30 */ c.SP -= 2; mem_write_word(c.SP, c.PC+1); c.PC = 0x30; c.cycles += 4; break; case 0xF8: /* LD HL, SP + imm8 */ i = mem_get_byte(c.PC+1); set_N(0); set_Z(0); set_C(((c.SP+i)&0xFF) < (c.SP&0xFF)); set_H(((c.SP+i)&0xF) < (c.SP&0xF)); set_HL(c.SP + (signed char)i); c.PC += 2; c.cycles += 3; break; case 0xF9: /* LD SP, HL */ c.SP = get_HL(); c.PC += 1; c.cycles += 2; break; case 0xFA: /* LD A, (mem16) */ s = mem_get_word(c.PC+1); c.A = mem_get_byte(s); c.PC += 3; c.cycles += 4; break; case 0xFB: /* EI */ interrupt_enable(); //JJ DEBIG printf("Interrupts enabled, IE: %02x\n", interrupt_get_mask()); c.PC += 1; c.cycles += 1; break; case 0xFE: /* CP a, imm8 */ t = mem_get_byte(c.PC+1); set_Z(c.A == t); set_N(1); set_H(((c.A - t)&0xF) > (c.A&0xF)); set_C(c.A < t); c.PC += 2; c.cycles += 2; break; case 0xFF: /* RST 38 */ c.SP -= 2; mem_write_word(c.SP, c.PC+1); c.PC = 0x0038; c.cycles += 4; break; default: #ifdef use_lib_log_serial printf("Unhandled opcode %02X at %04X\n", b, c.PC); printf("cycles: %d\n", c.cycles); #endif return 0; break; } return 1; }
import { InjectionKey } from 'vue' import { NotifyInterface } from './Notify' export const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol' export const PolySymbol = (name: string) => hasSymbol ? Symbol(name) : ('_N_') + name export const notifyStoreKey = /*#__PURE__*/ PolySymbol('NS') as InjectionKey<NotifyInterface>
<reponame>sahilduhan/codeforces #include <bits/stdc++.h> using namespace std; class Solution { public: string defangIPaddr(string address) { string result; for (int i = 0; i < address.length(); i++) { if (address[i] == '.') result += "[.]"; else result += address[i]; } return result; } }; int main() { return 0; }
<filename>frontend/src/js/query-upload-concept-list-modal/actions.ts import { ActionType, createAction } from "typesafe-actions"; import { TreesT } from "../concept-trees/reducer"; export type QueryUploadConceptListModalActions = ActionType< | typeof openQueryUploadConceptListModal | typeof closeQueryUploadConceptListModal | typeof acceptQueryUploadConceptListModal >; export const openQueryUploadConceptListModal = createAction( "query-upload-concept-list-modal/OPEN", )<{ andIdx: number | null; }>(); export const closeQueryUploadConceptListModal = createAction( "query-upload-concept-list-modal/CLOSE", )(); export const acceptQueryUploadConceptListModal = createAction( "query-upload-concept-list-modal/ACCEPT", )<{ andIdx: number | null; label: string; rootConcepts: TreesT; resolvedConcepts: string[]; }>();
#Calculate average of array arr <- c(1.1, 2.2, 3.3, 4.4) average <- mean(arr) print(average)
<gh_stars>0 import axios from 'axios'; const KEY = '<KEY>' export default axios.create({ baseURL : "https://www.googleapis.com/youtube/v3", params: { part : 'snippet', maxResults : 5, key : KEY } });
<filename>pinax/apps/tasks/tests/tasks_urls.py from django.conf.urls.defaults import * urlpatterns = patterns("", url(r"^tasks/", include("pinax.apps.tasks.urls")), url(r"^notices/", include("notification.urls")), url(r"^tagging_utils/", include("pinax.apps.tagging_utils.urls")), url(r"^comments/", include("threadedcomments.urls")), )
let i = 0; for (i; i <= 10; i += 1) { console.log(i); }
// deno-lint-ignore-file no-explicit-any import { Body, Controller, ControllerName, Get, Ip, MethodName, Post, Query, Res, Response, UploadedFile, UseGuards, } from "../../../mod.ts"; import type { Context } from "../../../mod.ts"; import { BadRequestException, mockjs } from "../../deps.ts"; import { AuthGuard } from "../../guards/auth.guard.ts"; import { AuthGuard2 } from "../../guards/auth2.guard.ts"; import { AuthGuard3, SSOGuard } from "../../guards/auth3.guard.ts"; import { RoleAction, Roles } from "../../decorators/roles.ts"; import { LogTime } from "../../decorators/time.ts"; import { LoggerService } from "../services/logger.service.ts"; @UseGuards(AuthGuard, SSOGuard) @Controller("/user") export class UserController { constructor(private readonly loggerService: LoggerService) { this.loggerService.info("user"); } @UseGuards(AuthGuard2, AuthGuard3) @Get("/info") info( @MethodName() methodName: string, @ControllerName() controllerName: string, context: Context, ) { console.log("methodName", methodName, "controllerName", controllerName); context.response.body = mockjs.mock({ name: "@name", "age|1-100": 50, "val|0-2": 1, }); } @Get("/info2") @UseGuards(AuthGuard2, AuthGuard3) info2(@Res() res: Response, @Query() params: any) { res.body = mockjs.mock({ name: "@name", "age|1-100": 50, "val|0-2": 1, params, }); } @Get("/test") testResultIsUndefined(@Ip() ip: string) { console.log(ip); return; } @Get("/err") err() { throw new BadRequestException("bad request"); } @UseGuards(AuthGuard2, AuthGuard3) @Get("list") @Roles(RoleAction.read) list(context: Context) { this.testInnerCall(); context.response.body = mockjs.mock({ "citys|100": [{ name: "@city", "value|1-100": 50, "type|0-2": 1 }], }); } testInnerCall() { console.log("---testInnerCall---"); } @Post("citys") @Roles(RoleAction.read, RoleAction.write) @LogTime() getCitys(ctx: Context, @Body() params: any) { console.log("----citys---", params); const result = mockjs.mock({ "citys|100": [{ name: "@city", "value|1-100": 50, "type|0-2": 1 }], }); // console.log(result); ctx.response.body = result; } @Post("upload") async upload(ctx: Context) { const data = ctx.request.body({ type: "form-data", }); const result = await data.value.read({ maxFileSize: 10 * 1024 * 1024 * 1024, }); console.log("---upload----", result); ctx.response.body = "test ok"; } @Post("upload2") upload2( @UploadedFile({ maxFileSize: 10 * 1024 * 1024 * 1024, }) result: any, @Res() res: Response, ) { console.log("---upload----", result); res.body = result; } }
import angular from 'angular'; import MapHelper from "./map-helper.service"; let mapHelperModule = angular.module('mapHelper', [ "geoserver" ]) .service('MapHelperService', MapHelper) .name; export default mapHelperModule;
#!/bin/bash -e die(){ echo $1; exit; } pushd master git fetch --all -p git checkout master git reset --hard origin/master popd for a in REL* do pushd $a git checkout $a git reset --hard origin/$a popd done pushd master git diff-index --quiet HEAD || die "Skip updating dirty master" u="$(git ls-files --exclude-standard --others)" && test -z "$u" || die "Skip unpdating dirty (untracked) master" git checkout master git rebase origin/master popd
s script will add the "public" versions of the Cadre repos # As `public` remotes for all applicable repos for repo in Cerveau Viseur Joueur.cpp Joueur.cs Joueur.java Joueur.js Joueur.lua Joueur.py Joueur.ts do cd $repo echo " -> adding MMAI-dev branch for $repo" git remote add mmai-dev git@github.com:siggame/$repo-MegaMinerAI-Dev.git git fetch --all cd .. done
package com.learn.controller; import com.alibaba.csp.sentinel.Entry; import com.alibaba.csp.sentinel.EntryType; import com.alibaba.csp.sentinel.SphU; import com.alibaba.csp.sentinel.context.ContextUtil; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.alibaba.csp.sentinel.slots.block.RuleConstant; import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; /** * <p> * OrderController * </p> * * @author Yuhaoran * @since 2021/12/31 */ @RestController @RequestMapping("/order") public class OrderController { @RequestMapping("/testFunc") public String testFunc(String application,long id){ initFlowRules(); //ContextUtil.enter("user-center",application); Entry entry = null; try { entry = SphU.entry("testFunc", EntryType.IN); /*您的业务逻辑 - 开始*/ System.out.println("hello world"); return getOrderName(id); /*您的业务逻辑 - 结束*/ } catch (BlockException e1) { /*流控逻辑处理 - 开始*/ System.out.println("block!"); throw new RuntimeException("系统繁忙"); /*流控逻辑处理 - 结束*/ } finally { if (entry != null) { entry.exit(); } } } public String getOrderName(long id){ Entry entry = null; try { entry = SphU.entry("getOrderName"); /*您的业务逻辑 - 开始*/ return "BuySomething"; /*您的业务逻辑 - 结束*/ } catch (BlockException e1) { /*流控逻辑处理 - 开始*/ return null; /*流控逻辑处理 - 结束*/ } finally { if (entry != null) { entry.exit(); } } } private static void initFlowRules(){ List<FlowRule> rules = new ArrayList<>(); FlowRule rule = new FlowRule(); rule.setResource("testFunc"); rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // Set limit QPS to 20. rule.setCount(20); rules.add(rule); FlowRuleManager.loadRules(rules); } }
<filename>lang/py/cookbook/v2/source/cb2_2_13_exm_2.py print>>somewhere, "The average of %d and %d is %f\n" % (1, 3, (1+3)/2)
def classify_dataset(data): """Function to classify a given dataset into two different classes""" #Initialize result list result = [] #Loop over the data for item in data: #Check the label of each item and append the corresponding class to result if item['label'] == 0: result.append('class1') elif item['label'] == 1: result.append('class2') return result
#!/bin/bash set -m mongodb_cmd="mongod --storageEngine $STORAGE_ENGINE" cmd="$mongodb_cmd --replSet rs0" if [ "$AUTH" == "yes" ]; then cmd="$cmd --auth" fi if [ "$JOURNALING" == "no" ]; then cmd="$cmd --nojournal" fi if [ "$OPLOG_SIZE" != "" ]; then cmd="$cmd --oplogSize $OPLOG_SIZE" fi $cmd & ./init-replica-set.sh if [ ! -f /data/db/.mongodb_password_set ]; then /set_mongodb_password.sh fi fg
const todo = (state, action) => { switch (action.type) { case 'ADD_TODO': return { id:action.id, text:action.text, completed:false }; case 'TOGGLE_TODO': if(state.id !== action.id) { return state; } return { ...state, completed: !state.completed } default: return state; } } const todos = (state = [], action) => { switch(action.type){ case 'ADD_TODO': return [ ...state, todo(undefined, action) ]; case 'TOGGLE_TODO': return state.map(t => todo(t, action)); default: return state; } }; const visibilityFilter = ( state = 'SHOW_ALL', action ) => { switch (action.type) { case 'SET_VISIBILITY_FILTER': return action.filter; default: return state; } }; const combineReducers = (reducers) => { return (state ={}, action) => { return Object.keys(reducers).reduce( (nextState, key) => { nextState[key] = reducers[key]( state[key], action ); return nextState; }, {} ); }; }; //const { combineReducers } = Redux; const todoApp = combineReducers({ todos, visibilityFilter }); /*const todoApp = (state = {}, action) => { return { todos: todos( state.todos, action ), visibilityFilter: visibilityFilter( state.visibilityFilter, action ) }; };*/ const { createStore } = Redux; const store = createStore(todoApp); const { Component } = React; let nextTodoId = 0; class TodoApp extends Component { render() { return ( <div> <input ref={node => { this.input = node }} /> <button onClick={() => { store.dispatch({ type: 'ADD_TODO', text: this.input.value, id: nextTodoId++ }); this.input.value = ''; } } >Add Todo</button> <ul> {this.props.todos.map(todo => <li key={todo.id}> {todo.text} </li> )} </ul> </div> ); } } const render = () => { ReactDOM.render( <TodoApp todos={store.getState().todos} />, document.querySelector("#root") ); }; store.subscribe(render); render();
#!/bin/sh . "${TEST_INIT:-./test-init.sh}" if [ "$1" = 'actual' ]; then mkdir .calcurse || exit 1 cp "$DATA_DIR/conf" .calcurse || exit 1 "$CALCURSE" -D "$PWD/.calcurse" -i "$DATA_DIR/ical-004.ical" "$CALCURSE" -D "$PWD/.calcurse" -s01/01/1980 -r2 "$CALCURSE" -D "$PWD/.calcurse" -t rm -rf .calcurse || exit 1 elif [ "$1" = 'expected' ]; then cat <<EOD Import process report: 0017 lines read 1 app / 0 events / 1 todo / 0 skipped 01/01/80: - 00:01 -> ..:.. Calibrator's 01/02/80: - ..:.. -> 09:18 Calibrator's to do: 1. Nary parabled Louvre's fleetest mered EOD else ./run-test "$0" fi
<filename>unmangler/src/unmangler.h #ifndef UNMANGLER_H #define UNMANGLER_H #include <ngrest/common/Service.h> class unmangler: public ngrest::Service { public: // *method: GET std::string unmangle(std::string mangled); }; #endif // UNMANGLER_H
import { Express, Request, Response } from "express"; import { createBlockChainNodeHandler, getBlockChainHandler, deleteBlockChainHandler, getBlockChainNodeHandler, getHopBlockChainHandler, createBlockChainHandler, removeBlockChainHandler } from "./controller/blockchain.controller"; import { createBlockChainNodeSchema, createBlockChainSchema, getBlockChainSchema, deleteBlockChainSchema, getBlockChainNodeSchema, emptyBlockChainSchema } from "./schema/blockchain.schema"; import validateResource from "./middleware/validateResource"; function routes(app: Express) { app.post( "/api/blockchain", [validateResource(createBlockChainSchema)], createBlockChainHandler ); app.get( "/api/blockchain", validateResource(getBlockChainSchema), getBlockChainHandler ); app.get( "/api/blockchain/:origin/:hops", validateResource(getBlockChainSchema), getHopBlockChainHandler ); app.post( "/api/blockchain/node", [validateResource(createBlockChainNodeSchema)], createBlockChainNodeHandler ); app.get( "/api/blockchain/node/:tx_hash", validateResource(getBlockChainNodeSchema), getBlockChainNodeHandler ); app.delete( "/api/blockchain/node/:tx_hash", [validateResource(deleteBlockChainSchema)], deleteBlockChainHandler ); app.delete( "/api/blockchain/remove", [validateResource(emptyBlockChainSchema)], removeBlockChainHandler ); } export default routes;
#!/bin/bash #SBATCH --job-name=/data/unibas/boittier/test-neighbours2 #SBATCH --nodes=1 #SBATCH --ntasks=1 #SBATCH --partition=short #SBATCH --output=/data/unibas/boittier/test-neighbours2_%A-%a.out hostname # Path to scripts and executables cubefit=/home/unibas/boittier/fdcm_project/mdcm_bin/cubefit.x fdcm=/home/unibas/boittier/fdcm_project/fdcm.x ars=/home/unibas/boittier/fdcm_project/ARS.py # Variables for the job n_steps=2 n_charges=24 scan_name=frame_ suffix=.chk cubes_dir=/data/unibas/boittier/fdcm/amide_graph output_dir=/data/unibas/boittier/test-neighbours2 frames=/home/unibas/boittier/fdcm_project/mdcms/amide/model1/frames.txt initial_fit=/home/unibas/boittier/fdcm_project/mdcms/amide/model1/24_charges_refined.xyz initial_fit_cube=/home/unibas/boittier/fdcm_project/mdcms/amide/model1/amide1.pdb.chk prev_frame=0 start_frame=18 next_frame=47 acd=/home/unibas/boittier/fdcm_project/0_fit.xyz.acd start=$start_frame next=$next_frame dir='frame_'$next output_name=$output_dir/$dir/$dir'-'$start'-'$next'.xyz' initial_fit=$output_dir/"frame_"$start/"frame_"$start'-'$prev_frame'-'$start'.xyz' # Go to the output directory mkdir -p $output_dir cd $output_dir mkdir -p $dir cd $dir # Do Initial Fit # for initial fit esp1=$cubes_dir/$scan_name$start$suffix'.p.cube' dens1=$cubes_dir/$scan_name$start$suffix'.d.cube' esp=$cubes_dir/$scan_name$next$suffix'.p.cube' dens=$cubes_dir/$scan_name$next$suffix'.d.cube' # adjust reference frame python $ars -charges $initial_fit -pcube $dens1 -pcube2 $dens -frames $frames -output $output_name -acd $acd > $output_name.ARS.log # do gradient descent fit $fdcm -xyz $output_name.global -dens $dens -esp $esp -stepsize 0.2 -n_steps $n_steps -learning_rate 0.5 -output $output_name > $output_name.GD.log # adjust reference frame python $ars -charges $output_name -pcube $esp -pcube2 $esp -frames $frames -output $output_name -acd $acd > $output_name.ARS-2.log # make a cube file for the fit $cubefit -v -generate -esp $esp -dens $dens -xyz refined.xyz > $output_name.cubemaking.log # do analysis $cubefit -v -analysis -esp $esp -esp2 $n_charges'charges.cube' -dens $dens > $output_name.analysis.log echo $PWD sbatch /home/unibas/boittier/fdcm_project/job_files/test-neighbours2/frame_18_(18, 5).sh sbatch /home/unibas/boittier/fdcm_project/job_files/test-neighbours2/frame_18_(18, 22).sh sbatch /home/unibas/boittier/fdcm_project/job_files/test-neighbours2/frame_18_(18, 24).sh sbatch /home/unibas/boittier/fdcm_project/job_files/test-neighbours2/frame_18_(18, 44).sh sbatch /home/unibas/boittier/fdcm_project/job_files/test-neighbours2/frame_18_(18, 68).sh sbatch /home/unibas/boittier/fdcm_project/job_files/test-neighbours2/frame_18_(18, 78).sh sbatch /home/unibas/boittier/fdcm_project/job_files/test-neighbours2/frame_18_(18, 88).sh
<gh_stars>0 import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HomeComponent } from './home.component'; import { HomeRoutingModule } from './home-routing.module'; import { FindCourierComponent } from '../find-courier/find-courier.component'; import { FindMedicineComponent } from '../find-medicine/find-medicine.component'; import { FindPatientComponent } from '../find-patient/find-patient.component'; import { FindUserComponent } from '../find-user/find-user.component'; import { NewCourierComponent } from '../new-courier/new-courier.component'; import { NewMedicineComponent } from '../new-medicine/new-medicine.component'; import { NewPatientComponent } from '../new-patient/new-patient.component'; import { NewUserComponent } from '../new-user/new-user.component'; import { SchedulingComponent } from '../scheduling/scheduling.component'; import { StatusChangeComponent } from '../status-change/status-change.component'; import { StubsListComponent } from '../stubs-list/stubs-list.component'; import { MenuComponent } from 'src/app/shared/components/menu/menu.component'; import { MatSidenavModule, MatIconModule, MatSelectModule, } from '@angular/material'; // import { FormModule } from '../../shared/components/forms/form.module'; import { MatCardModule, MatListModule, MatButtonModule, MatExpansionModule, } from '@angular/material'; import { ComponentsModule } from '../../shared/components/components.module'; import { EditMedicineComponent } from '../find-patient/edit-medicine/edit-medicine.component'; @NgModule({ declarations: [ HomeComponent, MenuComponent, FindCourierComponent, FindMedicineComponent, FindPatientComponent, FindUserComponent, EditMedicineComponent, NewCourierComponent, NewMedicineComponent, NewPatientComponent, NewUserComponent, SchedulingComponent, StatusChangeComponent, StubsListComponent, ], imports: [ CommonModule, HomeRoutingModule, MatSidenavModule, ComponentsModule, MatCardModule, MatIconModule, MatListModule, MatButtonModule, MatExpansionModule, MatSelectModule, ], }) export class HomeModule {}
require 'securerandom' module HasSalt DEFAULT_LENGTH = 64 module ClassMethods INFINITY = 1.0 / 0.0 def has_salt(only: nil, column: nil, length: nil, size: nil) only ||= -> { true } column ||= :salt # Size override fail ArgumentError, "don't pass both :size and :length" if size && length length ||= size # Allow passing in strings column = column.to_sym plural_column = column.to_s.pluralize # Handle `only: :predicate?` argument. # With correct binding via function invocation. only = ->(symbol) { -> { send(symbol) } }.(only) if only.is_a?(Symbol) generate_salt = -> (length) do raw = SecureRandom.base64((length * 0.75) + 1) raw[0...length] end # Gets the restricted range based on AR validations validation_salt_length = ->(column) do minmax = [0.0, INFINITY] length_validators = validators_on(column).select do |v| v.is_a?(ActiveModel::Validations::LengthValidator) end length_validators.each do |validator| options = validator.options # Explicitly set? Done. minmax = ([options[:is].to_f] * 2) and break if options[:is] # Adjust bounds. minmax = [ [minmax[0], options[:minimum] || 0].max.to_f, [minmax[1], options[:maximum] || INFINITY].min.to_f ] end minmax end schema_salt_length = ->(column) do [0.0, (columns_hash[column.to_s].limit || INFINITY).to_f] end calculated_salt_length = ->(column) do # Explicitly passed length return length unless length.nil? # Result from validations with :is from_validations = validation_salt_length.(column) return from_validations.first.to_i if from_validations.uniq.size == 1 # Result from schema with :limit from_schema = schema_salt_length.(column) return from_schema.first.to_i if from_schema.uniq.size == 1 minmax = [[from_validations[0], from_schema[0]].max, [from_validations[1], from_schema[1]].min ] # OK, now let's be reasonable: length = DEFAULT_LENGTH length = minmax[0] if length < minmax[0] length = minmax[1] if length > minmax[1] length end # Updates regardless define_method("generate_#{column}!") do send("#{column}=", generate_salt.(calculated_salt_length.(column))) end # Updates if changed. define_method("generate_#{column}") do if send(column).blank? && instance_exec(&only) send("generate_#{column}!") end end before_validation "generate_#{column}".to_sym end end def self.included(cls) cls.send(:extend, ClassMethods) end end if defined?(ActiveRecord::Base) class << ActiveRecord::Base def has_salt(*args, **kw) include HasSalt has_salt(*args, **kw) end end end
<filename>src/main/java/org/stellar/sdk/responses/operations/RevokeSponsorshipOperationResponse.java package org.stellar.sdk.responses.operations; import com.google.common.base.Optional; import com.google.gson.annotations.SerializedName; /** * Represents RevokeSponsorship operation response. * @see org.stellar.sdk.requests.OperationsRequestBuilder * @see org.stellar.sdk.Server#operations() */ public class RevokeSponsorshipOperationResponse extends OperationResponse { @SerializedName("account_id") private final String accountId; @SerializedName("claimable_balance_id") private final String claimableBalanceId; @SerializedName("data_account_id") private final String dataAccountId; @SerializedName("data_name") private final String dataName; @SerializedName("offer_id") private final Long offerId; @SerializedName("trustline_account_id") private final String trustlineAccountId; @SerializedName("trustline_asset") private final String trustlineAsset; @SerializedName("signer_account_id") private final String signerAccountId; @SerializedName("signer_key") private final String signerKey; public RevokeSponsorshipOperationResponse(String accountId, String claimableBalanceId, String dataAccountId, String dataName, Long offerId, String trustlineAccountId, String trustlineAsset, String signerAccountId, String signerKey) { this.accountId = accountId; this.claimableBalanceId = claimableBalanceId; this.dataAccountId = dataAccountId; this.dataName = dataName; this.offerId = offerId; this.trustlineAccountId = trustlineAccountId; this.trustlineAsset = trustlineAsset; this.signerAccountId = signerAccountId; this.signerKey = signerKey; } public Optional<String> getAccountId() { return Optional.fromNullable(accountId); } public Optional<String> getClaimableBalanceId() { return Optional.fromNullable(claimableBalanceId); } public Optional<String> getDataAccountId() { return Optional.fromNullable(dataAccountId); } public Optional<String> getDataName() { return Optional.fromNullable(dataName); } public Optional<Long> getOfferId() { return Optional.fromNullable(offerId); } public Optional<String> getTrustlineAccountId() { return Optional.fromNullable(trustlineAccountId); } public Optional<String> getTrustlineAsset() { return Optional.fromNullable(trustlineAsset); } public Optional<String> getSignerAccountId() { return Optional.fromNullable(signerAccountId); } public Optional<String> getSignerKey() { return Optional.fromNullable(signerKey); } }
/** * Copyright 2015 IBM Corp. * * 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.ibm.bluelistproxy.internal; import java.util.Map; import java.util.logging.Logger; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import com.cloudant.client.api.Database; import com.cloudant.client.api.model.DbInfo; /** * BlueList proxy utility class. The utilities are related to sending requests and * writing responses. */ public class BlueListProxyUtils { private static final String CLASS_NAME = BlueListProxyUtils.class.getName(); private static final Logger logger = Logger.getLogger(CLASS_NAME); /** * Determines whether the current database already exists. * This is done my making a request that involves the database. * * @param databaseName The name of the database. * @return True if it exists, false otherwise. */ public static boolean dbExists(String databaseName) { final String METHOD_NAME = "dbExists"; logger.entering(CLASS_NAME, METHOD_NAME, databaseName); boolean dbExists = false; try { Database db = KeyPassManager.getInstance().getAdminCloudantClient().database(databaseName, false); DbInfo dbInfo = db.info(); dbExists = ( dbInfo != null ); } catch(Exception e) {} logger.exiting(CLASS_NAME, METHOD_NAME, dbExists); return dbExists; } /** * Determines whether the current database document already exists. * * @param databaseName The name of the database. * @param documentName The name of the database document. * @return True if it exists, false otherwise. */ public static boolean dbDocExists(String databaseName, String documentName) { final String METHOD_NAME = "dbDocExists"; logger.entering(CLASS_NAME, METHOD_NAME, new Object[] {databaseName, documentName}); boolean dbDocExists = false; try { Database db = KeyPassManager.getInstance().getAdminCloudantClient().database(databaseName, false); dbDocExists = db.contains(documentName); } catch(Exception e) {} logger.exiting(CLASS_NAME, METHOD_NAME, dbDocExists); return dbDocExists; } /** * Create a JAX-rs response from the given json response. * * @param jsonResponse The json response to write. * @return The JAX-rs response. */ public static Response writeResponse(JSONResponse jsonResponse) { final String METHOD_NAME = "writeResponse"; logger.entering(CLASS_NAME, METHOD_NAME, jsonResponse); // Create response builder and set http status code int statusCode = jsonResponse.getStatusCode(); ResponseBuilder rb = Response.status(statusCode); // Add response headers (copied from Cloudant response) Map<String,String> hdrs = jsonResponse.getHeaders(); if (hdrs != null) { for (Map.Entry<String,String> hdr : hdrs.entrySet()) { rb.header(hdr.getKey(), hdr.getValue()); } } // Copy payload Response response = rb.entity(jsonResponse.getResult()).type(jsonResponse.getContentType()).build(); logger.exiting(CLASS_NAME, METHOD_NAME, response); return response; } }
filter_result = list(filter(lambda x: x["department"] == criteria["department"] and x["salary"] >= criteria["min_salary"], data)) print(filter_result) ## Output [ { "id": "3", "name": "Albert", "department": "IT", "salary": 70000 } ]
<reponame>neggas/blog import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { SubscriptionController } from './Subscription.controller'; import { Subscription } from './Subscription.entity'; import { SubscriptionService } from './Subscription.service'; @Module({ imports: [TypeOrmModule.forFeature([Subscription])], providers: [SubscriptionService], exports: [SubscriptionService], controllers: [SubscriptionController], }) export class SubscriptionModule {}
<html> <head> <title>Table Sample</title> </head> <body> <table> <tr> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> <tr> <td>John</td> <td>Doe</td> <td>30</td> </tr> <tr> <td>Jane</td> <td>Doe</td> <td>25</td> </tr> </table> </body> </html>
<gh_stars>1-10 /* * Copyright 2013 <NAME> * * 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 org.apache.maven.classpath.munger.parse.pom; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.maven.classpath.munger.Dependency; import org.apache.maven.classpath.munger.Repository; import org.apache.maven.classpath.munger.logging.Log; import org.apache.maven.classpath.munger.parse.AbstractDependeciesLoader; import org.apache.maven.classpath.munger.util.properties.NamedPropertySource; import org.apache.maven.classpath.munger.util.properties.PropertiesUtil; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * @author <NAME>. * @since Dec 24, 2013 12:44:08 PM */ public class PomDependenciesLoader extends AbstractDependeciesLoader { private NamedPropertySource properties; private List<Dependency> dependencies; private List<Repository> repos; private Set<String> propsNames; public PomDependenciesLoader() { super(); } public PomDependenciesLoader(Log log) { super(log); } public PomDependenciesLoader(InputStream inputStream) throws IOException { load(inputStream); } @Override public NamedPropertySource getProperties() { return properties; } @Override public Set<String> getDefinedPropertiesNames() { return propsNames; } @Override public List<Dependency> getDependencies() { return dependencies; } @Override public List<Repository> getRepositories() { return repos; } @Override public void load(InputStream inputStream) throws IOException { InputSource source=new InputSource(inputStream); PomDependenciesParser parser=new PomDependenciesParser(logger); SAXParserFactory factory=SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); try { SAXParser saxParser=factory.newSAXParser(); saxParser.parse(source, parser); } catch(SAXException e) { logger.error("Failed (" + e.getClass().getSimpleName() + ") to load: " + e.getMessage(), e); throw new IOException(e); } catch(ParserConfigurationException e) { logger.error("Failed (" + e.getClass().getSimpleName() + ") to instantiate parser: " + e.getMessage(), e); throw new IOException(e); } Map<String,String> propsMap=parser.getProperties(); propsNames = Collections.unmodifiableSet(new TreeSet<String>(propsMap.keySet())); properties = PropertiesUtil.asPropertySource(propsMap); dependencies = Collections.unmodifiableList(parser.getDependencies()); repos = Collections.unmodifiableList(parser.getRepositories()); } }
<reponame>shadman2000/ftc_app<filename>Team8201/src/main/java/org/firstinspires/ftc/team8201/robot8201.java package org.firstinspires.ftc.team8201; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.TouchSensor; @TeleOp(name = "robot8201", group = "Testing") public class robot8201 extends LinearOpMode { //Creating an instance of HardwareK9bot as "robot" HardwareK9bot robot = new HardwareK9bot(); @Override public void runOpMode() { //Declare the variables //Motor(s) double leftWheelPowerFront = 0.0; double leftWheelPowerBack = 0.0; double rightWheelPowerFront = 0.0; double rightWheelPowerBack = 0.0; double suckInWheelRight = 0.0; double suckInWheelLeft = 0.0; double elevatorPower = 0.0; //servo(s) double rightCollectorPower = 0.0; double leftCollectorPower = 0.0; double leftPlatform = 0.0; double rightPlatform = 1.0; //Initializing the hardwareK9bot file robot.init(hardwareMap); //Sensor(s) TouchSensor groundTouch; TouchSensor cubeTouch; cubeTouch = hardwareMap.get(TouchSensor.class,"cubeTouch"); groundTouch = hardwareMap.get(TouchSensor.class, "groundTouch"); //Ready message telemetry.addData("Say ", "8201 robot is ready"); telemetry.update(); //Wait for play waitForStart(); //opMode code that will run in a loop while we are in opMode while (opModeIsActive()) { //Acceleration of both wheels on right trigger if(gamepad1.right_trigger > 0) { //Redefining the power of both wheel according to the position of the trigger leftWheelPowerFront = -gamepad1.right_trigger; leftWheelPowerBack = -gamepad1.right_trigger; rightWheelPowerFront = -gamepad1.right_trigger; rightWheelPowerBack = -gamepad1.right_trigger; //Setting wheelPowers for turning if (gamepad1.left_stick_x > 0) { rightWheelPowerFront = gamepad1.right_trigger; rightWheelPowerBack = gamepad1.right_trigger; } else if (gamepad1.left_stick_x < 0) { leftWheelPowerFront = gamepad1.right_trigger; leftWheelPowerBack = gamepad1.right_trigger; } } //Deceleration of both wheels on left trigger if(gamepad1.left_trigger > 0) { //Redefining the power of both wheel according to the position of the trigger leftWheelPowerFront = gamepad1.left_trigger; leftWheelPowerBack = gamepad1.left_trigger; rightWheelPowerFront = gamepad1.left_trigger; rightWheelPowerBack = gamepad1.left_trigger; //Setting wheelPowers for turning if (gamepad1.left_stick_x > 0) { rightWheelPowerFront = -gamepad1.left_trigger; rightWheelPowerBack = -gamepad1.left_trigger; } else if (gamepad1.left_stick_x < 0) { leftWheelPowerFront = -gamepad1.left_trigger; leftWheelPowerBack = -gamepad1.left_trigger; } } // //Mecanum Wheel // //Forward and turn // if(gamepad1.right_trigger > 0) { // //Redefining the power of both wheel according to the position of the trigger // leftWheelPowerFront = -gamepad1.right_trigger; // leftWheelPowerBack = -gamepad1.right_trigger; // rightWheelPowerFront = -gamepad1.right_trigger; // rightWheelPowerBack = -gamepad1.right_trigger; // //Setting wheelPowers for turning // if (gamepad1.left_stick_x > 0) { // rightWheelPowerFront = gamepad1.right_trigger; // rightWheelPowerBack = gamepad1.right_trigger; // } // if (gamepad1.left_stick_x < 0) { // leftWheelPowerFront = gamepad1.right_trigger; // rightWheelPowerBack = gamepad1.right_trigger; // } // } // //Backward and turn // if(gamepad1.left_trigger > 0){ // //Redefining the power of both wheel according to the position of the trigger // rightWheelPowerBack = gamepad1.left_trigger; // rightWheelPowerFront = gamepad1.left_trigger; // leftWheelPowerBack = gamepad1.left_trigger; // leftWheelPowerFront = gamepad1.left_trigger; // //Setting wheelPowers for turning // if(gamepad1.left_stick_x > 0){ // rightWheelPowerFront = -gamepad1.left_trigger; // rightWheelPowerBack = -gamepad1.right_trigger; // } // if(gamepad1.right_stick_x < 0){ // leftWheelPowerBack = -gamepad1.left_trigger; // rightWheelPowerFront = -gamepad1.left_trigger; // } // } // //Going right // if(gamepad1.right_stick_x > 0){ // rightWheelPowerFront = -gamepad1.right_stick_x; // rightWheelPowerBack = gamepad1.right_stick_x; // leftWheelPowerFront = gamepad1.right_stick_x; // leftWheelPowerBack = -gamepad1.right_stick_x; // } // //Going Left // if(gamepad1.right_stick_x < 0){ // leftWheelPowerBack = gamepad1.right_stick_x; // leftWheelPowerFront = -gamepad1.right_stick_x; // rightWheelPowerFront = gamepad1.right_stick_x; // rightWheelPowerBack = -gamepad1.right_stick_x; // } //setting all motor (driving wheel) power to 0 if nothing is pressed if(gamepad1.right_trigger <= 0 && gamepad1.left_trigger <= 0) { //DO NOT USE AN ELSE!!!!!!!!!!!!!!!!! rightWheelPowerFront = 0; rightWheelPowerBack = 0; leftWheelPowerFront = 0; leftWheelPowerBack = 0; } //The suck-in wheels //Need to be tested which way the wheel rotates if(gamepad2.right_trigger > 0){ //Redefining the power of both wheel (suck-in) according to the position of the trigger suckInWheelLeft = gamepad2.right_trigger; suckInWheelRight = gamepad2.right_trigger; } //The wheels of the suck-in will both rotate outwards with left_trigger if (gamepad2.left_trigger > 0) { //Redefining the power of both wheel (suck-in) according to the position of the trigger suckInWheelLeft = -gamepad2.left_trigger; suckInWheelRight = -gamepad2.left_trigger; } if(gamepad2.a == true){ suckInWheelLeft = 1; suckInWheelRight = -1; } // if(gamepad2.a == false){ // suckInWheelLeft = 0; // suckInWheelRight = 0; // } //Stopping the wheel when none is pressed if(gamepad2.left_trigger <= 0 && gamepad2.right_trigger <= 0 && gamepad2.a == false){ suckInWheelLeft = 0; suckInWheelRight = 0; } //The elevator //The motors will go both up and down according to the y_axis of gamepad2 rightstick //Motor power goes up so as the elevator elevatorPower = -gamepad2.right_stick_y; //Stoping the elevator when touches the ground if (groundTouch.isPressed() == true && elevatorPower < 0) { elevatorPower = 0; } //Stopping the elevator when a cube is touched if(cubeTouch.isPressed() == true && elevatorPower < 0){ elevatorPower = 0; } //The gem arm //drop if(gamepad2.dpad_down){ robot.gemArm.setPosition(0.8); //Need to test accoring to the initial } //up if(gamepad2.dpad_up){ robot.gemArm.setPosition(0.3); //Need to test according to the initial } //The cube collector //Limiting the power(s) of servo //TESTED if(rightCollectorPower >= 0.38){ rightCollectorPower = 0.38; } if(rightCollectorPower <= 0.15){ rightCollectorPower = 0.30; } if(leftCollectorPower >= 0.15){ leftCollectorPower = 0.51; } if(leftCollectorPower <= 0.36){ leftCollectorPower = 0.36; } //Gamepad 2 right bumper holder movement if(gamepad2.right_bumper){ //Increasing Servo power rightCollectorPower-=0.1; //Right from the front leftCollectorPower+=0.1; //Left from the front //Sending the powers to the servo robot.cubeHolderLeft.setPosition(leftCollectorPower); robot.cubeHolderRight.setPosition(rightCollectorPower); } //Gamepad 2 left bumper holder movement if(gamepad2.left_bumper){ //Increasing Servo power rightCollectorPower+=0.1; leftCollectorPower-=0.1; //Sending the powers to the servo robot.cubeHolderLeft.setPosition(leftCollectorPower); robot.cubeHolderRight.setPosition(rightCollectorPower); } //The platform if(gamepad1.dpad_down == true){ leftPlatform = 1.0; rightPlatform = 0.0; } if(gamepad1.dpad_up == true){ leftPlatform = 0.0; rightPlatform = 1.0; } //Sending the powers as motor Power robot.leftWheelFront.setPower(leftWheelPowerFront * 0.6); robot.leftWheelBack.setPower(leftWheelPowerBack * 0.6); robot.rightWheelBack.setPower(rightWheelPowerFront * 0.6); robot.rightWheelFront.setPower(rightWheelPowerBack * 0.6); robot.suckInWheelleft.setPower(suckInWheelLeft); robot.suckInWheelright.setPower(suckInWheelRight); robot.leftPservo.setPosition(leftPlatform); robot.rightPservo.setPosition(rightPlatform); robot.elevator.setPower(elevatorPower * 0.3); //Testing messages telemetry.addData("leftServo" , leftCollectorPower); telemetry.addData("rightServo" , rightCollectorPower); telemetry.addData("Left Collector Wheel" , leftCollectorPower); telemetry.addData("right Collector Wheel" , rightCollectorPower); telemetry.addData("elevator" , elevatorPower); telemetry.addData("groundTouch" , groundTouch.isPressed()); telemetry.addData("cubeTouch" , cubeTouch.isPressed()); telemetry.update(); } } }
<filename>os/yapio.h /************************************************************************* * * * YAP Prolog %W% %G% * * * Yap Prolog was developed at NCCUP - Universidade do Porto * * * * Copyright L.Damas, V.S.Costa and Universidade do Porto 1985-2003 * * * ************************************************************************** * * * File: yapio.h * Last *rev: 22/1/03 * mods: ** comments: Input/Output information * * * *************************************************************************/ #ifndef YAPIO_H #define YAPIO_H 1 #ifdef SIMICS #undef HAVE_LIBREADLINE #endif #include <stdio.h> #include <wchar.h> #include "YapIOConfig.h" #include "YapUTF8.h" #include <VFS.h> #include <Yatom.h> #define WRITE_DEFS() \ PAR("module", isatom, WRITE_MODULE) \ , PAR("attributes", isatom, WRITE_ATTRIBUTES), \ PAR("cycles", booleanFlag, WRITE_CYCLES), \ PAR("quoted", booleanFlag, WRITE_QUOTED), \ PAR("ignore_ops", booleanFlag, WRITE_IGNORE_OPS), \ PAR("max_depth", nat, WRITE_MAX_DEPTH), \ PAR("numbervars", booleanFlag, WRITE_NUMBERVARS), \ PAR("singletons", booleanFlag, WRITE_SINGLETONS), \ PAR("portrayed", booleanFlag, WRITE_PORTRAYED), \ PAR("portray", booleanFlag, WRITE_PORTRAY), \ PAR("priority", nat, WRITE_PRIORITY), \ PAR("character_escapes", booleanFlag, WRITE_CHARACTER_ESCAPES), \ PAR("backquotes", booleanFlag, WRITE_BACKQUOTES), \ PAR("brace_terms", booleanFlag, WRITE_BRACE_TERMS), \ PAR("fullstop", booleanFlag, WRITE_FULLSTOP), \ PAR("nl", booleanFlag, WRITE_NL), \ PAR("variable_names", ok, WRITE_VARIABLE_NAMES), \ PAR(NULL, ok, WRITE_END) #define PAR(x, y, z) z typedef enum write_enum_choices { WRITE_DEFS() } write_choices_t; #ifdef BEAM int beam_write(USES_REGS1) { Yap_StartSlots(); Yap_plwrite(ARG1, GLOBAL_Stream + LOCAL_c_output_stream, LOCAL_max_depth, 0, NULL); Yap_CloseSlots(); Yap_RaiseException(); return (TRUE); } #endif #ifndef _PL_WRITE_ #define EOFCHAR EOF #endif /* info on aliases */ typedef struct AliasDescS { Atom name; int alias_stream; } * AliasDesc; #define MAX_ISO_LATIN1 255 typedef struct scanner_extra_params { Term tposINPUT, tposOUTPUT; Term backquotes, singlequotes, doublequotes; bool ce, vprefix, vn_asfl; Term tcomms; /// Access to comments Term cmod; /// Access to commen bool store_comments; // bool get_eot_blank; } scanner_params; /** * * @return a new VFS that will support /assets */ extern struct vfs *Yap_InitAssetManager(void); /* routines in parser.c */ extern VarEntry *Yap_LookupVar(const char *); extern Term Yap_VarNames(VarEntry *, Term); extern Term Yap_Variables(VarEntry *, Term); extern Term Yap_Singletons(VarEntry *, Term); /* routines in scanner.c */ extern void Yap_clean_tokenizer(void); extern char *Yap_AllocScannerMemory(unsigned int); /* routines in iopreds.c */ extern FILE *Yap_FileDescriptorFromStream(Term); extern Int Yap_FirstLineInParse(void); extern int Yap_CheckIOStream(Term, char *); #if defined(YAPOR) || defined(THREADS) extern void Yap_LockStream(void *); extern void Yap_UnLockStream(void *); #else #define Yap_LockStream(X) #define Yap_UnLockStream(X) #endif extern Int Yap_GetStreamFd(int); extern void Yap_CloseStreams(void); extern void Yap_CloseTemporaryStreams(int minstream); extern int Yap_FirstFreeStreamD(); extern void Yap_FlushStreams(void); extern void Yap_ReleaseStream(int); extern int Yap_PlGetchar(void); extern int Yap_PlGetWchar(void); extern int Yap_PlFGetchar(void); extern int Yap_GetCharForSIGINT(void); extern Int Yap_StreamToFileNo(Term); int Yap_OpenStream(Term tin, const char* io_mode, YAP_Term user_name, encoding_t enc); extern int Yap_FileStream(FILE *, Atom, Term, int, VFS_t *); extern char *Yap_TermToBuffer(Term t, int flags); extern char *Yap_HandleToString(yhandle_t l, size_t sz, size_t *length, encoding_t *encoding, int flags); extern int Yap_GetFreeStreamD(void); extern int Yap_GetFreeStreamDForReading(void); extern Term Yap_BufferToTerm(const char *s, Term opts); extern Term Yap_UBufferToTerm(const unsigned char *s, Term opts); extern Term Yap_WStringToList(wchar_t *); extern Term Yap_WStringToListOfAtoms(wchar_t *); extern Atom Yap_LookupWideAtom(const wchar_t *); typedef enum mem_buf_source { MEM_BUF_MALLOC = 1, MEM_BUF_USER = 2 } memBufSource; extern char *Yap_MemStreamBuf(int sno); extern char *Yap_StrPrefix(const char *buf, size_t n); extern Term Yap_StringToNumberTerm(const char *s, encoding_t *encp, bool error_on); extern int Yap_FormatFloat(Float f, char **s, size_t sz); extern int Yap_open_buf_read_stream(void *st, const char *buf, size_t nchars, encoding_t *encp, memBufSource src, Atom name, Term uname); extern int Yap_open_buf_write_stream(encoding_t enc, memBufSource src); extern Term Yap_BufferToTerm(const char *s, Term opts); extern X_API Term Yap_BufferToTermWithPrioBindings(const char *s, Term opts, Term bindings, size_t sz, int prio); extern FILE *Yap_GetInputStream(Term t, const char *m); extern FILE *Yap_GetOutputStream(Term t, const char *m); extern Atom Yap_guessFileName( int sno, Atom n, Term un, size_t max); extern int Yap_CheckSocketStream(Term stream, const char *error); extern void Yap_init_socks(char *host, long interface_port); extern bool Yap_flush(int sno); extern uint64_t HashFunction(const unsigned char *); extern uint64_t WideHashFunction(wchar_t *); extern void Yap_InitAbsfPreds(void); inline static Term MkCharTerm(Int c) { unsigned char cs[8]; if (c==EOF) return TermEof; size_t n = put_xutf8(cs, c); if (n<0) n = 0; cs[n] = 0; return MkAtomTerm(Yap_ULookupAtom(cs)); } extern char *GLOBAL_cwd; extern char *Yap_VF(const char *path); extern char *Yap_VFAlloc(const char *path); /// UT when yap started extern uint64_t Yap_StartOfWTimes; extern bool Yap_HandleSIGINT(void); #endif
export const PORTFOLIO_ITEM_NULLABLE = [ 'name', 'description', 'long_description', 'distributor', 'documentation_url', 'support_url' ]; export const PORTFOLIO_NULLABLE = ['description'];
class GroceryStore: def __init__(self, name, products, location): self.name = name self.products = products self.location = location def get_all_products(self): return self.products def get_location(self): return self.location
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package fieldpath import ( "testing" "sigs.k8s.io/structured-merge-diff/v2/value" ) func TestPathElementValueMap(t *testing.T) { m := PathElementValueMap{} if _, ok := m.Get(PathElement{FieldName: strptr("onion")}); ok { t.Fatal("Unexpected path-element found in empty map") } m.Insert(PathElement{FieldName: strptr("carrot")}, value.NewValueInterface("knife")) m.Insert(PathElement{FieldName: strptr("chive")}, value.NewValueInterface(2)) if _, ok := m.Get(PathElement{FieldName: strptr("onion")}); ok { t.Fatal("Unexpected path-element in map") } if val, ok := m.Get(PathElement{FieldName: strptr("carrot")}); !ok { t.Fatal("Missing path-element in map") } else if !value.Equals(val, value.NewValueInterface("knife")) { t.Fatalf("Unexpected value found: %#v", val) } if val, ok := m.Get(PathElement{FieldName: strptr("chive")}); !ok { t.Fatal("Missing path-element in map") } else if !value.Equals(val, value.NewValueInterface(2)) { t.Fatalf("Unexpected value found: %#v", val) } }
#!/bin/bash mkdir -p $CASSANDRA_HOME/logs java -Xmx128M -Xms128M -XX:MaxDirectMemorySize=256M -jar $CASSANDRA_HOME/mate/cassandra-mate.jar >>$CASSANDRA_HOME/logs/cassandra_mate.stdout.log 2>>$CASSANDRA_HOME/logs/cassandra_mate.stderr.log
#!/bin/sh # # Vivado(TM) # runme.sh: a Vivado-generated Runs Script for UNIX # Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. # echo "This script was generated under a different operating system." echo "Please update the PATH and LD_LIBRARY_PATH variables below, before executing this script" exit if [ -z "$PATH" ]; then PATH=C:/APPZ/Xilinx/Vivado/2020.1/ids_lite/ISE/bin/nt64;C:/APPZ/Xilinx/Vivado/2020.1/ids_lite/ISE/lib/nt64:C:/APPZ/Xilinx/Vivado/2020.1/bin else PATH=C:/APPZ/Xilinx/Vivado/2020.1/ids_lite/ISE/bin/nt64;C:/APPZ/Xilinx/Vivado/2020.1/ids_lite/ISE/lib/nt64:C:/APPZ/Xilinx/Vivado/2020.1/bin:$PATH fi export PATH if [ -z "$LD_LIBRARY_PATH" ]; then LD_LIBRARY_PATH= else LD_LIBRARY_PATH=:$LD_LIBRARY_PATH fi export LD_LIBRARY_PATH HD_PWD='D:/Documents/xkaspa46/digital-electronics-1/labs/07-display_driver/display_driver/display_driver.runs/synth_1' cd "$HD_PWD" HD_LOG=runme.log /bin/touch $HD_LOG ISEStep="./ISEWrap.sh" EAStep() { $ISEStep $HD_LOG "$@" >> $HD_LOG 2>&1 if [ $? -ne 0 ] then exit fi } EAStep vivado -log top.vds -m64 -product Vivado -mode batch -messageDb vivado.pb -notrace -source top.tcl
//Question: https://www.hackerrank.com/challenges/js10-try-catch-and-finally/problem Solution /* * Complete the reverseString function * Use console.log() to print to stdout. */ function reverseString(s) { try{ // Can be chained, but it damages readability console.log(s.split("").reverse().join("")) } catch(e){ console.log(e.message); // Use .message, or you'll get more than expected. console.log(s); } }
#!/usr/bin/env bash sudo gu remove bc && cd ./component/ && sudo gu -L install ./bc-component.jar && cd ..
<reponame>go-generalize/volcago<filename>generator/generator.go<gh_stars>1-10 package generator import ( "strings" "github.com/go-generalize/go-easyparser" "github.com/go-generalize/go-easyparser/types" "golang.org/x/xerrors" ) // Generator generates firestore CRUD functions type Generator struct { dir string types map[string]types.Type AppVersion string } func NewGenerator(dir string) (*Generator, error) { psr, err := easyparser.NewParser(dir, func(fo *easyparser.FilterOpt) bool { return fo.BasePackage }) if err != nil { return nil, xerrors.Errorf("failed to initialize parser: %w", err) } psr.Replacer = replacer types, err := psr.Parse() if err != nil { return nil, xerrors.Errorf("failed to parse: %w", err) } return &Generator{ dir: dir, types: types, AppVersion: "devel", }, nil } // GenerateOption is a parameter to generate repository type GenerateOption struct { OutputDir string PackageName string CollectionName string MockGenPath string MockOutputPath string DisableMetaFieldsDetection bool Subcollection bool } // NewDefaultGenerateOption returns a default GenerateOption func NewDefaultGenerateOption() GenerateOption { return GenerateOption{ OutputDir: ".", MockGenPath: "mockgen", MockOutputPath: "mock/mock_{{ .GeneratedFileName }}/mock_{{ .GeneratedFileName }}.go", DisableMetaFieldsDetection: false, } } func (g *Generator) Generate(structName string, opt GenerateOption) error { var typ *types.Object for k, v := range g.types { split := strings.Split(k, ".") t := split[len(split)-1] if t == structName { t, ok := v.(*types.Object) if !ok { return xerrors.Errorf("Only struct is allowed") } typ = t } } if typ == nil { return xerrors.Errorf("struct not found: %s", structName) } gen, err := newStructGenerator(typ, structName, g.AppVersion, opt) if err != nil { return xerrors.Errorf("failed to initialize generator: %w", err) } if err := gen.parseType(); err != nil { return xerrors.Errorf("failed to parse type: %w", err) } if err := gen.generate(); err != nil { return xerrors.Errorf("failed to generate files: %w", err) } return nil }
#!/bin/sh # # Copyright (c) 2007 Junio C Hamano # test_description='Quoting paths in diff output. ' . ./test-lib.sh P0='pathname' P1='pathname with HT' P2='pathname with SP' P3='pathname with LF' if : 2>/dev/null >"$P1" && test -f "$P1" && rm -f "$P1" then test_set_prereq TABS_IN_FILENAMES else say 'Your filesystem does not allow tabs in filenames' fi test_expect_success TABS_IN_FILENAMES setup ' echo P0.0 >"$P0.0" && echo P0.1 >"$P0.1" && echo P0.2 >"$P0.2" && echo P0.3 >"$P0.3" && echo P1.0 >"$P1.0" && echo P1.2 >"$P1.2" && echo P1.3 >"$P1.3" && git add . && git commit -m initial && git mv "$P0.0" "R$P0.0" && git mv "$P0.1" "R$P1.0" && git mv "$P0.2" "R$P2.0" && git mv "$P0.3" "R$P3.0" && git mv "$P1.0" "R$P0.1" && git mv "$P1.2" "R$P2.1" && git mv "$P1.3" "R$P3.1" && : ' test_expect_success TABS_IN_FILENAMES 'setup expected files' ' cat >expect <<\EOF rename pathname.1 => "Rpathname\twith HT.0" (100%) rename pathname.3 => "Rpathname\nwith LF.0" (100%) rename "pathname\twith HT.3" => "Rpathname\nwith LF.1" (100%) rename pathname.2 => Rpathname with SP.0 (100%) rename "pathname\twith HT.2" => Rpathname with SP.1 (100%) rename pathname.0 => Rpathname.0 (100%) rename "pathname\twith HT.0" => Rpathname.1 (100%) EOF ' test_expect_success TABS_IN_FILENAMES 'git diff --summary -M HEAD' ' git diff --summary -M HEAD >actual && test_cmp expect actual ' test_expect_success TABS_IN_FILENAMES 'setup expected files' ' cat >expect <<\EOF pathname.1 => "Rpathname\twith HT.0" | 0 pathname.3 => "Rpathname\nwith LF.0" | 0 "pathname\twith HT.3" => "Rpathname\nwith LF.1" | 0 pathname.2 => Rpathname with SP.0 | 0 "pathname\twith HT.2" => Rpathname with SP.1 | 0 pathname.0 => Rpathname.0 | 0 "pathname\twith HT.0" => Rpathname.1 | 0 7 files changed, 0 insertions(+), 0 deletions(-) EOF ' test_expect_success TABS_IN_FILENAMES 'git diff --stat -M HEAD' ' git diff --stat -M HEAD >actual && test_cmp expect actual ' test_done
<reponame>glameyzhou/training<filename>distribute/src/main/java/org/glamey/training/demo/easy/RemoveElement.java package org.glamey.training.demo.easy; /**给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。 示例 1: 给定 nums = [3,2,2,3], val = 3, 函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。 你不需要考虑数组中超出新长度后面的元素。 示例 2: 给定 nums = [0,1,2,2,3,0,4,2], val = 2, 函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。 注意这五个元素可为任意顺序。 你不需要考虑数组中超出新长度后面的元素。 说明: 为什么返回数值是整数,但输出的答案是数组呢? 请注意,输入数组是以“引用”方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。 你可以想象内部操作如下: // nums 是以“引用”方式传递的。也就是说,不对实参作任何拷贝 int len = removeElement(nums, val); // 在函数里修改输入数组对于调用者是可见的。 // 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。 for (int i = 0; i < len; i++) {     print(nums[i]); } 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/remove-element 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * @author yang.zhou 2020.01.31.21 */ public class RemoveElement { public static void main(String[] args) { int[] nums = new int[]{3,2,2,3}; System.out.println(new RemoveElement().removeElement(nums, 3)); } public int removeElement(int[] nums, int val) { int index = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != val) { nums[index] = nums[i]; index ++; } } return index; } }
<reponame>KaydenMiller/screeps import { Uuid } from "./uuid"; export const MAX_CREEPS = 5; export const MAX_HARVESTERS = 3; export const MIN_HARVESTERS = 1; export const MIN_UPGRADERS = 1; export const MAX_UPGRADERS = 1; export const MIN_BUILDERS = 1; export const MAX_BUILDERS = 1; export class CreepFactory { constructor(private spawnerName: string) { } public create(type: "builder" | "upgrader" | "harvester" | "big-harvester"): any { switch (type) { case "harvester": Game.spawns[this.spawnerName].spawnCreep([WORK, CARRY, MOVE], `Harvester-${Uuid.create("v4")}`, { memory: { room: "none", role: "harvester", working: false } }); break; case "upgrader": Game.spawns[this.spawnerName].spawnCreep([WORK, CARRY, MOVE], `Upgrader-${Uuid.create("v4")}`, { memory: { room: "none", role: "upgrader", working: false } }); break; case "builder": Game.spawns[this.spawnerName].spawnCreep([WORK, CARRY, MOVE], `Builder-${Uuid.create("v4")}`, { memory: { room: "none", role: "builder", working: false } }); break; case "big-harvester": Game.spawns[this.spawnerName].spawnCreep([WORK, WORK, WORK, WORK, CARRY, MOVE, MOVE], `HarvesterBig-${Uuid.create("v4")}`, { memory: { room: "none", role: "harvester", working: false } }); break; } } }
// Define the enum representing mouse events enum MouseEvent { Press(u8, i32, i32), Release(i32, i32), Hold(i32, i32), } // Function to obtain the representation of a mouse button fn repr_mouse_button(b: u8) -> Option<String> { // Implementation of repr_mouse_button function is not provided // Assume it returns Some(String) if the button has a representation, otherwise None unimplemented!() } // Function to process the mouse event and return the formatted string fn process_mouse_event(mev: MouseEvent) -> Option<String> { match mev { MouseEvent::Press(b, x, y) => repr_mouse_button(b).map(|s| format!("Press:{},{},{}", s, x, y)), MouseEvent::Release(x, y) => Some(format!("Release:{},{}", x, y)), MouseEvent::Hold(x, y) => Some(format!("Hold:{},{}", x, y)), } } // Example usage fn main() { let press_event = MouseEvent::Press(1, 100, 200); let release_event = MouseEvent::Release(150, 250); let hold_event = MouseEvent::Hold(300, 400); println!("{:?}", process_mouse_event(press_event)); // Output: Some("Press:Left,100,200") println!("{:?}", process_mouse_event(release_event)); // Output: Some("Release:150,250") println!("{:?}", process_mouse_event(hold_event)); // Output: Some("Hold:300,400") }
<reponame>NAVEENRH/FULL_STACK_TRAINING import React from "react"; import Column from "./components/Column"; type State = { no: number; count: number }; class Demo extends React.Component<{}, State> { state: State = { no: 0, count: 0 }; shouldComponentUpdate(nextProps: {}, nextState: State) { console.log("SHOULD COMPONENT UPDATE"); console.log("PROPS", this.props, nextProps); console.log("STATE", this.state, nextState); return this.state.no !== nextState.no || nextState.count === 7; } render() { console.log("RENDER CALLED", this.state); const name = "Mike"; return ( <div className="row"> <Column size={12}> <h1>Demo Component</h1> <p>Some html content</p> {this.state.count > 6 ? <p>Hello from {name.toUpperCase()}</p> : null} <p>{7 + 3}</p> <button onClick={() => this.setState({ no: 1 })} className="btn btn-sm btn-primary mx-2" > Change state to 1 </button> <button onClick={() => this.setState({ no: 0 })} className="btn btn-sm btn-primary mx-2" > Change state to 0 </button> <button className="btn btn-sm btn-primary mx-2" onClick={() => this.setState((prevState) => ({ count: prevState.count + 1 })) } > Increment count </button> </Column> </div> ); } } export default Demo;
document.addEventListener("click", e => { if(e.target.className=='swal2-close' && e.target.id=="swal-minimize") { e.stopPropagation(); e.preventDefault(); $('#swal-minimized-text').html($("#swal2-title")[0].outerHTML); swal_minimize(); } }, true); export_styles(); $('#swal-minimized').on('click', ev => { const e = ev.originalEvent; if(e.target.id !== "deminify-btn"){ swal_maximize(); }else{ $('#swal-minimized').css('display', 'none'); Swal.fire('Alert closed', 'Bye!', 'success'); $('#swal-minimized-text').html(''); } }); function swal_minimize () { $('.swal2-container.swal2-center.swal2-backdrop-show').hide(); $('#swal-minimized').css('display', 'flex'); } function swal_maximize () { $('#swal-minimized').css('display', 'none'); $('.swal2-container.swal2-center.swal2-backdrop-show').show(); $('#swal-minimized-text').html(''); } function export_styles() { const Styles = ` #swal-minimized { display: none; height:40px; position: absolute; border-radius:10px; filter: brightness(110%); bottom: 5px; left: 10px; z-index: 990; background-color: #c4c7ca; cursor:pointer; } #swal-minimized:hover { filter: brightness(100%); } #swal-minimized:active { filter: brightness(95%); } #swal-minimize { display: flex; position: relative; right:25px; } `; const style = document.createElement('style'); style.textContent = Styles; document.head.append(style); }
#!/bin/bash # This expects the device to be in zedboot mode, with a zedboot that is # is compatible with the Fuchsia system image provided. # # The first and only parameter should be the path to the Fuchsia system image # tarball, e.g. `./fuchsia-test.sh generic-x64.tgz`. # # This script expects `pm`, `dev_finder`, and `fuchsia_ctl` to all be in the # same directory as the script, as well as the `flutter_aot_runner-0.far` and # the `flutter_runner_tests-0.far`. It is written to be run from its own # directory, and will fail if run from other directories or via sym-links. set -Ee # The nodes are named blah-blah--four-word-fuchsia-id device_name=${SWARMING_BOT_ID#*--} if [ -z "$device_name" ] then echo "No device found. Aborting." exit 1 else echo "Connecting to device $device_name" fi reboot() { # note: this will set an exit code of 255, which we can ignore. ./fuchsia_ctl -d $device_name ssh -c "dm reboot-recovery" || true } trap reboot EXIT ./fuchsia_ctl -d $device_name pave -i $1 # TODO(gw280): Enable tests using JIT runner ./fuchsia_ctl -d $device_name test \ -f flutter_aot_runner-0.far \ -f flutter_runner_tests-0.far \ -t flutter_runner_tests
import requests import json def get_latest_news(): """Get latest news from Google news API. Returns ------- List[dict] List of dictionaries containing the latest news. """ url = 'http://newsapi.org/v2/everything?sources=google-news&apiKey=<YOUR_API_KEY>' response = requests.get(url) data = json.loads(response.text) return data['articles']
# pairgenerator.py class PairDataGenerator: def generate_pairs(self): # Implementation to generate pairs of data pass # classify_trainer.py def train_classifier(pairs): # Implementation to train a classifier using the pairs of data pass def train_zaco_classifier(pairs): # Implementation to train a ZACO classifier using the pairs of data pass # tflite_model.py class TFLiteModel: def create_tflite_model(self): # Implementation to create a TFLite model for deployment on edge devices pass
# $Id$ inittest extract-nonexistent tc/extract-nonexistent extshar ${TESTDIR} extshar ${RLTDIR} runcmd "${AR} xv valid.a nonexistent" work true rundiff true
<gh_stars>1-10 import { withIcon } from "../withIcon"; import { ReactComponent as Icon } from "./gift-sign.svg"; export const IconGiftSign = withIcon(Icon);
<filename>doc/html/search/pages_8.js var searchData= [ ['performance',['Performance',['../performace.html',1,'']]] ];
<reponame>rajatariya21/airbyte require_relative './airbyte_protocol.rb' require_relative './airbyte_logger.rb' require 'json' class MongodbState def initialize(state_file:) @state = if state_file JSON.parse(File.read(state_file)) else {} end AirbyteLogger.log("Initialized with state:\n#{JSON.pretty_generate(@state)}") end def get(stream_name:, cursor_field:) @state.dig(stream_name, cursor_field) end def set(stream_name:, cursor_field:, cursor:) @state[stream_name] ||= {} @state[stream_name][cursor_field] = cursor end def dump_state! json = @state.to_json AirbyteLogger.log("Saving state:\n#{JSON.pretty_generate(@state)}") asm = AirbyteStateMessage.from_dynamic!({ 'data' => @state, }) message = AirbyteMessage.from_dynamic!({ 'type' => Type::State, 'state' => asm.to_dynamic, }) puts message.to_json end end
function glb-to-draco-gltf() { if [ $# -eq 0 ]; then echo "usage: $0 glb filename (without '.glb' at the end)" return fi gltf-pipeline -i ${1}.glb -o ${1}.gltf gltf-pipeline -i ${1}.gltf -o ${1}.draco.gltf -d }
<reponame>ArtursKuzmiks/SpringTest package com.example.Tests.Example2.Dao; import com.example.Tests.Example2.ApplicationConfig.Customer; import java.util.List; /** * @author <NAME> on 18.29.5 */ public interface CustomerDao { void addCustomer(Customer customer); void editCustomer(Customer customer, Long customerId); void deleteCustomer(int customerId); List<Customer> debtors(); Customer find(long customerId); List<Customer> findAll(); }
#include "ItemManager.h" #include <Info/Info/Database.h> #include "../GameStateDatabase.h" #include "../State/States.h" #include <Core/DeltaTimer.h> #include "../LogicDB/LogicDB.h" using namespace Lunia::XRated::Database; namespace Lunia { namespace XRated { namespace Logic { const float Item::TIMELIMIT = 30.0f; //const float Item::CREATETIME = 2.0f; const float Item::CREATETIME = 0.5f; const float Item::DURATION = 120.0f; const float Item::TRYINTERVAL = 1.0f; const float Item::DICETIME = 10.0f; Item::Item(IGameStateDatabase& db, Serial serial, Info::ItemInfo* i, float3 pos) : Object(Constants::ObjectType::Item) , info(i), owner(serial), elapsedTimeFromCreation(0) , itemData(objectData), bTried(false), triedTime(0) { objectData.Name = info->Id; objectData.NameHash = info->Hash; objectData.Radius = 6.0f; objectData.Position = pos; switch ( i->ItemType ) { case Info::ItemInfo::Type::PVPITEM : //Pvp item �� �Դµ� ���� �����̰� ����. if ( owner ) itemState = ItemState::OwnerShip; else itemState = ItemState::Opened; break; default : itemState = ItemState::CreateDelay; } Object::Initialize(&db); } //Item::Item(Item& p) // : Object(Constants::ObjectType::Item) // , info(p.info), owner(p.objectData.GameObjectSerial), elapsedTimeFromCreation(0) // , itemData(objectData), bTried(false), triedTime(0) //{ // Lunia_WARNING((L"Logic::Item(Item&) - Owner: {}", owner )); // stageData = p.stageData; // objectData.GameObjectSerial = p.objectData.GameObjectSerial; // objectData.Name = p.objectData.Name; // objectData.NameHash = p.objectData.NameHash; // objectData.Type = p.objectData.Type; // objectData.Radius = p.objectData.Radius; // objectData.Position = p.objectData.Position; // objectData.Direction = p.objectData.Direction; //} Item::~Item() { } bool Item::Get(Player* player, IGameStateDatabase* db) { if ( player->GetPlayTimePenalty() & XRated::Constants::PlayTimePenalty::Item ) { //�����ߵ������ý��� ������ bTried = true; return false; } switch ( info->ItemType ) { case Info::ItemInfo::Type::INSTANT : LogicDBInstance().stateDB.AddItemState(info->Hash, player); // StateBudle�� �ִٸ� ���ǿ� ���� ��� bundle�� ����������. { Database::Info::StateBundleInfo::ConditionList::iterator i = info->StateBundleConditions.begin(); for ( ; i != info->StateBundleConditions.end() ; ++i) { player->ProcessStateBundle(*i); } } return true; case Info::ItemInfo::Type::PVPITEM : //pvp�����濡�� ���̴� ������. ��������ó���� �־�� �ϰα�����. if ( player->AcquireItem(info) ) { db->AcquirePvpItem(player, info->Hash); return true; } break; default : //�ν���Ʈ�� �ƴϸ� �ϴ��� ������ if ( db->AcquireItem(player, info->Hash, GetSerial(), itemData.StackCount, itemData.InstanceEx) ) { return true; } else { //�κ��� ������ ��������. bTried = true; } } return false; } bool Item::Update(float dt, IGameStateDatabase* db) { elapsedTimeFromCreation += dt; switch ( itemState ) { case ItemState::CreateDelay : //�����Ǽ� ���� ���� �� ���� ���� if (elapsedTimeFromCreation > CREATETIME) { if ( !(info->Attributes.Attr & Info::ItemInfo::ATTRIBUTES::ACQUIREBYDICE) ) { if ( owner ) itemState = ItemState::OwnerShip; else itemState = ItemState::Opened; } else if( elapsedTimeFromCreation > DICETIME ) //Ŭ�󿡼� �ֻ��������� ���⵿�� ���� �� ���� �Ѵ�. { if ( owner ) itemState = ItemState::OwnerShip; else itemState = ItemState::Opened; } } break; case ItemState::OwnerShip : //�������� �����ϴ� ���� { Player* player = db->RetrievePlayer(owner); //if ( owner == NULL || player == NULL ) //{ // Lunia_WARNING((L"Logic::Update() - OwnerShip State : Onwer:{} / PlayerPtr: 0x%p", owner , player)); //} if (player && !player->CheckState(Database::Info::StateInfo::Type::GHOST) && Lunia::Math::Length<float>(player->GetPosition()-objectData.Position) <= objectData.Radius) { if (bTried) //�������� �̹� �õ� �߾���. �̷��� ������ ���� ��ٸ��� return false; if ( Get( player, db ) ) return true; } else { bTried = false; //������ �������� �õ��ߴ��� ���θ� ��Ÿ���� flag�� �ʱ�ȭ�Ѵ�. �ƹ��� ������ ���� ���� ���� } if (!itemData.PrivateItem && elapsedTimeFromCreation > TIMELIMIT) { //privateItem�� ������� �ʴ´�! �ֳı�? Opened�� ���°� �ȹٲ�ϱ� -__-!! itemState = ItemState::Opened; itemData.OwnerId = L""; } } break; case ItemState::Opened : { if ( triedTime <= 0 ) { std::vector<Player*> l; Player* player; db->GetAreaObject(objectData.Position, objectData.Radius, Constants::AllianceType::AnyObjects, 0, this, l); if (!l.empty()) { int cnt = (int)l.size(); while(cnt) { --cnt; player = l[cnt]; if ( !player->CheckState(Database::Info::StateInfo::Type::GHOST) ) { if ( Get( player, db) ) return true; } } triedTime = TRYINTERVAL; } else { bTried = false; } } else { triedTime -= dt; if (triedTime > TRYINTERVAL) Logger::GetInstance().Warn(L"Item::Update() - TriedTime Error: {0}", triedTime); } } if (elapsedTimeFromCreation > DURATION) return true; break; default : return true; } return Object::Update(dt, db); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ItemManager ItemManager::ItemManager() : currentOwner(GameStateDatabase::PCSerialBase), tick(0) { } void ItemManager::Init() { std::map<Serial, Item*>::iterator i = itemList.begin(), end = itemList.end(); for (; i != end ; ++i) delete (*i).second; itemList.clear(); } const wchar_t* ItemManager::NextOwner(IGameStateDatabase& db) { Player* player = db.NextPlayer(currentOwner); if (!player) return NULL;//����ڰ� �ƹ��� ����. std::set<XRated::Serial> itemNotNomalGainUsers; while(player->IsGainNormal() == false) { // �ѹ��� ������ if(itemNotNomalGainUsers.insert(player->GetSerial()).second == false) return NULL; player = db.NextPlayer(player->GetSerial()); } currentOwner = player->GetSerial(); return player->GetName().c_str(); } const wchar_t* ItemManager::GetRandomPlayer(IGameStateDatabase& db, Serial& owner) { Player* player = db.GetRandomPlayer(); if (!player) return NULL;//����ڰ� �ƹ��� ����. owner = player->GetSerial(); return player->GetName().c_str(); } uint8 ItemManager::GetValidStackCount(const Database::Info::ItemInfo* info, uint8 curStackCount) { if (curStackCount == 1) return curStackCount; ///< stackCount Validation if (!info) return 1; if (info->MaxCnt <= 1) return 1; if (info->ItemType == Info::ItemInfo::Type::INSTANT) return 1; ///< ��ùߵ��������� 1�� return curStackCount; } void ItemManager::CreateItem(IGameStateDatabase& db, uint32 name, float3 position, float3 direction, Serial serial, uint16 stackCount, InstanceEx instance, bool isPrivateItem) { if ( position.x < 0 || position.z < 0 ) { //���� �ۿ� �������� �����Ƿ� �ߴ�. Logger::GetInstance().Warn( L"[ItemManager::CreateItem] Wrong position." ); return; } if ( itemList.find(serial) != itemList.end() ) { // serial �� �ߺ��Ǹ� �ȵ���. Logger::GetInstance().Info( L"[ItemManager::CreateItem] item �����ÿ� serial�� �ߺ��Ǿ����ϴ�." ); return; } position.y = 0; Info::ItemInfo* info = DatabaseInstance().InfoCollections.Items.Retrieve(name); if (!info) { Logger::GetInstance().Info( L"[ItemManager::CreateItem] item [{}] info not founded in database.", name ); return; } Item* item; stackCount = GetValidStackCount(info, stackCount); if ( (info->Attributes.Attr & Info::ItemInfo::ATTRIBUTES::ACQUIREBYTURN) || (info->Attributes.Attr & Info::ItemInfo::ATTRIBUTES::ACQUIREBYDICE) ) { const wchar_t* ownerName; Serial randomOwner; if( info->Attributes.Attr & Info::ItemInfo::ATTRIBUTES::ACQUIREBYDICE ) { isPrivateItem = true; ownerName = GetRandomPlayer(db, randomOwner); }else { ownerName = NextOwner(db); } if (ownerName) { if( info->Attributes.Attr & Info::ItemInfo::ATTRIBUTES::ACQUIREBYDICE ) { item = new Item(db, randomOwner, info, position); } else { item = new Item(db, currentOwner, info, position); } item->SetSerial(serial); item->SetDirection(direction); item->SetOwnerName(ownerName); item->SetPrivateItem(isPrivateItem); item->SetStackCount(stackCount); item->SetInstance(instance); itemList[serial] = item; db.ItemCreated(item->GetObjectData(), ownerName, 0, stackCount, isPrivateItem); } else { item = new Item(db, 0, info, position); item->SetSerial(serial); item->SetDirection(direction); item->SetOwnerName(L""); item->SetPrivateItem(isPrivateItem); item->SetStackCount(stackCount); item->SetInstance(instance); itemList[serial] = item; db.ItemCreated(item->GetObjectData(), L"", 0, stackCount, isPrivateItem); } } else { item = new Item(db, 0, info, position); item->SetSerial(serial); item->SetDirection(direction); item->SetOwnerName(L""); item->SetPrivateItem(isPrivateItem); item->SetStackCount(stackCount); item->SetInstance(instance); itemList[serial] = item; db.ItemCreated(item->GetObjectData(), L"", 0, stackCount, isPrivateItem); } //�������� ���͸� �������ش�. { float2 pos( position.x, position.z ); Sector* sector = db.GetSmallSector().GetSector( pos ); item->SetSmallSector(sector); sector = db.GetBigSector().GetSector( pos ); item->SetBigSector(sector); } } void ItemManager::CreateItem(IGameStateDatabase& db, uint32 name, float3 position, float3 direction, Serial serial, uint32 userSerial, uint16 stackCount, InstanceEx instance, bool isPrivateItem) { if ( itemList.find(serial) != itemList.end() ) { Logger::GetInstance().Info( L"[ItemManager::CreateItem] item �����ÿ� serial�� �ߺ��Ǿ����ϴ�." ); return; } Info::ItemInfo* info = DatabaseInstance().InfoCollections.Items.Retrieve(name); if (!info) { Logger::GetInstance().Info( L"[ItemManager::CreateItem] item [{0}] info not founded in database.", name); return; } Player* player = db.RetrievePlayer( userSerial ); if ( !player ) return; if ( position.x < 0 || position.z < 0 ) { Logger::GetInstance().Warn( L"[ItemManager::CreateItem] Wrong position."); return; } if(info->Attributes.Attr & Info::ItemInfo::ATTRIBUTES::ACQUIREBYDICE) isPrivateItem = true; position.y = 0; Item* item; stackCount = GetValidStackCount(info, stackCount); item = new Item(db, player->GetSerial(), info, position); item->SetSerial(serial); item->SetDirection(direction); item->SetOwnerName(player->GetName().c_str()); item->SetPrivateItem(isPrivateItem); item->SetStackCount(stackCount); item->SetInstance(instance); itemList[serial] = item; db.ItemCreated(item->GetObjectData(), player->GetName(), 0, stackCount, isPrivateItem); //�������� ���͸� �������ش�. { float2 pos( position.x, position.z ); Sector* sector = db.GetSmallSector().GetSector( pos ); item->SetSmallSector(sector); sector = db.GetBigSector().GetSector( pos ); item->SetBigSector(sector); } } void ItemManager::Update(float dt, IGameStateDatabase* db) { tick += dt; if (tick >= 0.2f) { tick -= 0.2f; } else return; std::map<Serial, Item*>::iterator i = itemList.begin(), end = itemList.end(); for (; i != end ;) { if ( (*i).second->Update(0.2f, db) ) { ObjectData& data = (*i).second->GetObjectData(); db->ObjectDestroyed((*i).second, data.Type); delete (*i).second; i = itemList.erase(i); } else ++i; } } Object* ItemManager::Retrieve(Serial serial) { std::map<Serial, Item*>::iterator i = itemList.find(serial); if (i != itemList.end() ) return itemList[serial]; return NULL; } void ItemManager::GetObjectList(std::vector<ItemData*>& l) { std::map<Serial, Item*>::iterator i = itemList.begin(), end = itemList.end(); for (; i != end ;++i) { ItemData& data = (*i).second->GetItemData(); l.push_back(&data); } } void ItemManager::ClearItem(IGameStateDatabase* db) { std::map<Serial, Item*>::iterator i = itemList.begin(), end = itemList.end(); for (; i != end ; ++i) { ObjectData& data = (*i).second->GetObjectData(); db->ObjectDestroyed((*i).second, data.Type); delete (*i).second; } itemList.clear(); } } } }
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from peewee import fn def test_returns_instance(employee_class): """ :type employee_class: pydrill_dsl.resource.Resource """ item = employee_class.select().get() assert item.first_name != '' def test_returned_instace_has_methods(employee_class): """ :type employee_class: pydrill_dsl.resource.Resource """ item = employee_class.select().get() assert item.salary_with_name() != '' def test_select_count(employee_class): """ :type employee_class: pydrill_dsl.resource.Resource """ count = employee_class.select().count() assert count == ('EXPR$0', '1155') def test_alias_count(employee_class): """ :type employee_class: pydrill_dsl.resource.Resource """ count = employee_class.select(fn.Count('*').alias('count_employee')).scalar(as_tuple=True) assert count == [('count_employee', '1155')] def test_predicate_order_by(employee_class): """ :type employee_class: pydrill_dsl.resource.Resource """ salary_gte_17K = (employee_class.salary >= 17000) salary_lte_25K = (employee_class.salary <= 25000) result = employee_class.select().where(salary_gte_17K & salary_lte_25K).order_by(+employee_class.salary) # ASC results = list(result) lowest, highest = results[0], results[-1] assert isinstance(lowest, employee_class) assert lowest.salary < highest.salary @pytest.mark.parametrize('filter,expected_count', [ ({'first_name__eq': 'Sheri'}, 1), ({'first_name__ne': 'Sheri'}, 1154), ({'salary__gte': 17000}, 17), ]) def test_django_style_lookup(employee_class, filter, expected_count): """ :type employee_class: pydrill_dsl.resource.Resource """ result = employee_class.select().filter(**filter) assert len(result) == expected_count def test_raw_query(employee_class): """ :type employee_class: pydrill_dsl.resource.Resource """ result = list(employee_class.raw('SELECT salary FROM `cp`.`employee.json` ORDER BY salary LIMIT 1')) assert isinstance(result[0], employee_class) assert result[0].salary == '20.0'
<filename>src/types/replacements.schema.ts<gh_stars>0 /* tslint:disable */ /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export type Files = string[]; export type ReplacementValue = string; export type Search = string[]; export interface Replacements { [k: string]: Replacement; } export interface Replacement { innerText?: InnerTextReplacement; orgWideEmailAddress?: OrgWideEmailAddressReplacement; } export interface InnerTextReplacement { files: Files; replacement: ReplacementValue; search: Search; } export interface OrgWideEmailAddressReplacement { files: Files; replacement: ReplacementValue; }
<reponame>famura/Rcs /******************************************************************************* Copyright (c) 2017, Honda Research Institute Europe GmbH 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 the copyright holder 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 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. *******************************************************************************/ #include "RcsViewer.h" #include "Rcs_graphicsUtils.h" #include <Rcs_macros.h> #include <Rcs_timer.h> #include <KeyCatcherBase.h> #include <Rcs_Vec3d.h> #include <Rcs_VecNd.h> #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osgViewer/ViewerEventHandlers> #include <osgUtil/Optimizer> #include <osg/StateSet> #include <osg/PolygonMode> #include <osgShadow/ShadowMap> #include <osgFX/Cartoon> #include <osgGA/TrackballManipulator> #include <iostream> #if !defined (_MSC_VER) #include <sys/wait.h> #include <unistd.h> static pid_t forkProcess(const char* command) { pid_t pid = fork(); if (pid == 0) { execl("/bin/bash", "bash", "-c", command, NULL); perror("execl"); exit(1); } return pid; } #endif static const std::string defaultBgColor = "LIGHT_GRAYISH_GREEN"; namespace Rcs { /******************************************************************************* * Keyboard handler for default keys. The default manipulator is extended so * that the default space behavior (default camera pose) is disabled, and that * the mouse does not move the tracker once Shift-L is pressed. This allows to * implement a mouse spring. ******************************************************************************/ class RcsManipulator : public osgGA::TrackballManipulator { public: RcsManipulator() : osgGA::TrackballManipulator(), leftShiftPressed(false) { } ~RcsManipulator() { } virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { bool spacePressed = false; switch (ea.getEventType()) { case (osgGA::GUIEventAdapter::KEYDOWN): { if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Shift_L) { this->leftShiftPressed = true; } else if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Space) { spacePressed = true; } break; } case (osgGA::GUIEventAdapter::KEYUP): { if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Shift_L) { this->leftShiftPressed = false; } break; } default: { } } // switch(...) if ((this->leftShiftPressed==true) || (spacePressed==true)) { return false; } return osgGA::TrackballManipulator::handle(ea, aa); } bool leftShiftPressed; }; /******************************************************************************* * User event data structure for custom events. ******************************************************************************/ struct ViewerEventData : public osg::Referenced { enum EventType { AddNode = 0, AddChildNode, AddEventHandler, RemoveNode, RemoveNamedNode, RemoveChildNode, RemoveAllNodes, SetCameraTransform, SetCameraHomePose, SetCameraHomePoseEyeCenterUp, SetTitle, ResetView, SetBackgroundColor, SetShadowEnabled, SetWireframeEnabled, SetCartoonEnabled, SetTrackballCenter, None }; ViewerEventData(EventType type) : eType(type), flag(false) { init(type, "No arguments"); } ViewerEventData(osg::ref_ptr<osg::Node> node_, EventType type) : node(node_), eType(type), flag(false) { init(type, node->getName()); } ViewerEventData(const HTr* transform, EventType type) : eType(type), flag(false) { HTr_copy(&trf, transform); init(type, "Transform"); } ViewerEventData(std::string nodeName, EventType type) : childName(nodeName), eType(type), flag(false) { init(type, nodeName); } ViewerEventData(osg::ref_ptr<osg::Group> parent_, osg::ref_ptr<osg::Node> node_, EventType type) : parent(parent_), node(node_), eType(type), flag(false) { init(type, node->getName()); } ViewerEventData(osg::ref_ptr<osgGA::GUIEventHandler> eHandler, EventType type) : eventHandler(eHandler), eType(type), flag(false) { init(type, "osgGA::GUIEventHandler"); } ViewerEventData(osg::Group* parent_, std::string childName_, EventType type) : parent(parent_), childName(childName_), eType(type), flag(false) { init(type, "osgGA::GUIEventHandler"); } ViewerEventData(EventType type, bool enable) : eType(type), flag(enable) { init(type, "No arguments"); } void init(EventType type, std::string comment) { this->eType = type; RLOG(5, "Creating ViewerEventData %d: %s", userEventCount, comment.c_str()); userEventCount++; } ~ViewerEventData() { userEventCount--; RLOG(5, "Deleting ViewerEventData - now %d events", userEventCount); } osg::ref_ptr<osg::Group> parent; osg::ref_ptr<osg::Node> node; std::string childName; osg::ref_ptr<osgGA::GUIEventHandler> eventHandler; EventType eType; HTr trf; bool flag; static int userEventCount; }; int Rcs::ViewerEventData::userEventCount = 0; /******************************************************************************* * Keyboard handler for default keys. ******************************************************************************/ class KeyHandler : public osgGA::GUIEventHandler { public: KeyHandler(Rcs::Viewer* viewer) : _viewer(viewer), _video_capture_process(-1) { RCHECK(_viewer); KeyCatcherBase::registerKey("0-9", "Set Rcs debug level", "Viewer"); KeyCatcherBase::registerKey("w", "Toggle wireframe mode", "Viewer"); KeyCatcherBase::registerKey("s", "Cycle between shadow modes", "Viewer"); KeyCatcherBase::registerKey("R", "Toggle cartoon mode", "Viewer"); #if !defined(_MSC_VER) KeyCatcherBase::registerKey("M", "Toggle video capture", "Viewer"); #endif KeyCatcherBase::registerKey("F11", "Print camera transform", "Viewer"); } ~KeyHandler() { if (_video_capture_process >= 0) { toggleVideoCapture(); } } virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { return _viewer->handle(ea, aa); } bool toggleVideoCapture() { bool captureRunning = false; #if !defined(_MSC_VER) if (_video_capture_process >= 0) { // Stop video taking kill(_video_capture_process, SIGINT); waitpid(_video_capture_process, NULL, 0); _video_capture_process = -1; } else { // movie taken using avconv x11grab // get the first window osgViewer::ViewerBase::Windows windows; _viewer->viewer->getWindows(windows, true); if (!windows.empty()) { int x = 0; int y = 0; int w = 0; int h = 0; windows[0]->getWindowRectangle(x, y, w, h); static unsigned int movie_number = 1; RMSG("Start capturing: (%d, %d) %dx%d", x, y, w, h); std::stringstream cmd; cmd << "ffmpeg -y -f x11grab -r 25 -s " << w << "x" << h << " -i " << getenv("DISPLAY") << "+" << x << "," << y << " -crf 20 -r 25 -c:v libx264 -c:a n" << " /tmp/movie_" << movie_number++ << ".mp4"; // cmd << "avconv -y -f x11grab -r 25 -s " // << w << "x" << h // << " -i " << getenv("DISPLAY") << "+" // << x << "," << y // << " -crf 20 -r 25 -c:v libx264 -c:a n" // << " /tmp/movie_" << movie_number++ << ".mp4"; _video_capture_process = forkProcess(cmd.str().c_str()); captureRunning = true; } } #endif return captureRunning; } private: Rcs::Viewer* _viewer; pid_t _video_capture_process; }; /******************************************************************************* * Viewer class. ******************************************************************************/ Viewer::Viewer() : fps(0.0), mouseX(0.0), mouseY(0.0), normalizedMouseX(0.0), normalizedMouseY(0.0), mtxFrameUpdate(NULL), threadRunning(false), updateFreq(25.0), initialized(false), wireFrame(false), shadowsEnabled(false), llx(0), lly(0), sizeX(640), sizeY(480), cartoonEnabled(false), threadStopped(true), leftMouseButtonPressed(false), rightMouseButtonPressed(false) { // Check if logged in remotely const char* sshClient = getenv("SSH_CLIENT"); bool fancy = true; if (sshClient != NULL) { if (strlen(sshClient) > 0) { RLOGS(4, "Remote login detected - simple viewer settings"); fancy = false; } } create(fancy, fancy); RLOG(5, "Done constructor of viewer"); } /******************************************************************************* * Viewer class. ******************************************************************************/ Viewer::Viewer(bool fancy, bool startupWithShadow) : fps(0.0), mouseX(0.0), mouseY(0.0), normalizedMouseX(0.0), normalizedMouseY(0.0), mtxFrameUpdate(NULL), threadRunning(false), updateFreq(25.0), initialized(false), wireFrame(false), shadowsEnabled(false), llx(0), lly(0), sizeX(640), sizeY(480), cartoonEnabled(false), threadStopped(true), leftMouseButtonPressed(false), rightMouseButtonPressed(false) { create(fancy, startupWithShadow); RLOG(5, "Done constructor of viewer"); } /******************************************************************************* * Destructor. ******************************************************************************/ Viewer::~Viewer() { stopUpdateThread(); } /******************************************************************************* * Initlalization method. ******************************************************************************/ void Viewer::create(bool fancy, bool startupWithShadow) { #if defined(_MSC_VER) llx = 12; lly = 31; #endif const char* forceSimple = getenv("RCSVIEWER_SIMPLEGRAPHICS"); if (forceSimple) { fancy = false; startupWithShadow = false; } this->shadowsEnabled = startupWithShadow; // Rotate loaded file nodes to standard coordinate conventions // (z: up, x: forward) osg::ref_ptr<osgDB::ReaderWriter::Options> options; options = new osgDB::ReaderWriter::Options; options->setOptionString("noRotation"); osgDB::Registry::instance()->setOptions(options.get()); this->viewer = new osgViewer::Viewer(); // Mouse manipulator (needs to go before event handler) osg::ref_ptr<osgGA::TrackballManipulator> trackball = new RcsManipulator(); viewer->setCameraManipulator(trackball.get()); // Handle some default keys (see handler above) this->keyHandler = new KeyHandler(this); viewer->addEventHandler(this->keyHandler.get()); // Root node (instead of a Group we create an Cartoon node for optional // cell shading) if (fancy) { this->rootnode = new osgFX::Cartoon; dynamic_cast<osgFX::Effect*>(rootnode.get())->setEnabled(false); } else { this->rootnode = new osg::Group; } rootnode->setName("rootnode"); // Light grayish green universe this->clearNode = new osg::ClearNode; this->clearNode->setClearColor(colorFromString("LIGHT_GRAYISH_GREEN")); this->rootnode->addChild(this->clearNode.get()); // Light model: We switch off the default viewer light, and configure two // light sources. The sunlight shines down from 10m. Another light source // moves with the camera, so that there are no dark spots whereever // the mouse manipulator moves to. // Disable default light rootnode->getOrCreateStateSet()->setMode(GL_LIGHT0, osg::StateAttribute::OFF); // Light source that moves with the camera this->cameraLight = new osg::LightSource; cameraLight->getLight()->setLightNum(1); cameraLight->getLight()->setPosition(osg::Vec4(0.0, 0.0, 10.0, 1.0)); cameraLight->getLight()->setSpecular(osg::Vec4(1.0, 1.0, 1.0, 1.0)); rootnode->addChild(cameraLight.get()); rootnode->getOrCreateStateSet()->setMode(GL_LIGHT1, osg::StateAttribute::ON); // Light source that shines down osg::ref_ptr<osg::LightSource> sunlight = new osg::LightSource; sunlight->getLight()->setLightNum(2); sunlight->getLight()->setPosition(osg::Vec4(0.0, 0.0, 10.0, 1.0)); rootnode->addChild(sunlight.get()); rootnode->getOrCreateStateSet()->setMode(GL_LIGHT2, osg::StateAttribute::ON); // Shadow map scene. We use the sunlight to case shadows. this->shadowScene = new osgShadow::ShadowedScene; osg::ref_ptr<osgShadow::ShadowMap> sm = new osgShadow::ShadowMap; sm->setTextureSize(osg::Vec2s(2048, 2048)); sm->setLight(sunlight->getLight()); sm->setPolygonOffset(osg::Vec2(-0.7, 0.0)); sm->setAmbientBias(osg::Vec2(0.7, 0.3)); // values need to sum up to 1.0 shadowScene->setShadowTechnique(sm.get()); shadowScene->addChild(rootnode.get()); shadowScene->setReceivesShadowTraversalMask(ReceivesShadowTraversalMask); shadowScene->setCastsShadowTraversalMask(CastsShadowTraversalMask); // Change the threading model. The default threading model is // osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext. if (forceSimple) { viewer->setThreadingModel(osgViewer::Viewer::SingleThreaded); } else { viewer->setThreadingModel(osgViewer::Viewer::CullDrawThreadPerContext); } // Create viewer in a window if (fancy == false) { viewer->setSceneData(rootnode.get()); } else { // Set anti-aliasing osg::ref_ptr<osg::DisplaySettings> ds = new osg::DisplaySettings; ds->setNumMultiSamples(4); viewer->setDisplaySettings(ds.get()); viewer->setSceneData(startupWithShadow?shadowScene.get():rootnode.get()); } // Disable small feature culling to avoid problems with drawing single points // as they have zero bounding box size viewer->getCamera()->setCullingMode(viewer->getCamera()->getCullingMode() & ~osg::CullSettings::SMALL_FEATURE_CULLING); viewer->getCameraManipulator()->setHomePosition(osg::Vec3d(4.0, 3.5, 3.0), osg::Vec3d(0.0, -0.2, 0.8), osg::Vec3d(0.0, 0.05, 1.0)); viewer->home(); KeyCatcherBase::registerKey("F10", "Toggle full screen", "Viewer"); osg::ref_ptr<osgViewer::WindowSizeHandler> wsh; wsh = new osgViewer::WindowSizeHandler; wsh->setKeyEventToggleFullscreen(osgGA::GUIEventAdapter::KEY_F10); viewer->addEventHandler(wsh.get()); KeyCatcherBase::registerKey("F9", "Toggle continuous screenshots", "Viewer"); KeyCatcherBase::registerKey("F8", "Take screenshot(s)", "Viewer"); osg::ref_ptr<osgViewer::ScreenCaptureHandler::WriteToFile> scrw; scrw = new osgViewer::ScreenCaptureHandler::WriteToFile("screenshot", "png"); osg::ref_ptr<osgViewer::ScreenCaptureHandler> capture; capture = new osgViewer::ScreenCaptureHandler(scrw.get()); capture->setKeyEventToggleContinuousCapture(osgGA::GUIEventAdapter::KEY_F9); capture->setKeyEventTakeScreenShot(osgGA::GUIEventAdapter::KEY_F8); viewer->addEventHandler(capture.get()); KeyCatcherBase::registerKey("z", "Toggle on-screen stats", "Viewer"); KeyCatcherBase::registerKey("Z", "Print viewer stats to console", "Viewer"); osg::ref_ptr<osgViewer::StatsHandler> stats = new osgViewer::StatsHandler; stats->setKeyEventTogglesOnScreenStats('z'); stats->setKeyEventPrintsOutStats('Z'); viewer->addEventHandler(stats.get()); setTitle("RcsViewer"); } /******************************************************************************* * Add a node to the root node. ******************************************************************************/ bool Viewer::setWindowSize(unsigned int llx_, // lower left x unsigned int lly_, // lower left y unsigned int sizeX_, // size in x-direction unsigned int sizeY_) { if (isInitialized() == true) { RLOG(1, "The window size can't be changed after launching the viewer " "window"); return false; } this->llx = llx_; this->lly = lly_; this->sizeX = sizeX_; this->sizeY = sizeY_; return true; } /******************************************************************************* * \ţodo: In case the viewer is about to be realized, we might get into the * realized==false branch. If it then gets realized, we get a * concurrency problem. Can this ever happen? Does it make sense to * handle this? ******************************************************************************/ void Viewer::add(osgGA::GUIEventHandler* eventHandler) { RLOG(5, "Adding event handler"); addUserEvent(new ViewerEventData(eventHandler, ViewerEventData::AddEventHandler)); } /******************************************************************************* * Add a node to the root node. ******************************************************************************/ void Viewer::add(osg::Node* node) { RLOG(5, "Adding node %s to eventqueue", node->getName().c_str()); osg::ref_ptr<osg::Node> refNode(node); addUserEvent(new ViewerEventData(refNode, ViewerEventData::AddNode)); } /******************************************************************************* * Add a node to the root node. ******************************************************************************/ bool Viewer::addInternal(osg::Node* node) { osg::Camera* newHud = dynamic_cast<osg::Camera*>(node); // If it's a camera, it needs a graphics context. This doesn't exist right // after construction, therefore in that case we ignore it. This shouldn't // happen here, since this function gets called from within the viewer's // frame traversals. if (newHud) { osgViewer::Viewer::Windows windows; viewer->getWindows(windows); if (windows.empty()) { RLOG(1, "Failed to add HUD - window not created"); } else { newHud->setGraphicsContext(windows[0]); newHud->setViewport(0, 0, windows[0]->getTraits()->width, windows[0]->getTraits()->height); viewer->addSlave(newHud, false); } return true; } bool success = false; if (node != NULL) { success = this->rootnode->addChild(node); } else { RLOG(1, "Failed to add osg::Node - node is NULL!"); } return success; } /******************************************************************************* * Add a node to the parent node. ******************************************************************************/ void Viewer::add(osg::Group* parent, osg::Node* child) { addUserEvent(new ViewerEventData(parent, child, ViewerEventData::AddChildNode)); } /******************************************************************************* * Add a node to the parent node. ******************************************************************************/ bool Viewer::addInternal(osg::Group* parent, osg::Node* child) { parent->addChild(child); return true; } /******************************************************************************* * Removes a node from the scene graph. ******************************************************************************/ void Viewer::removeNode(osg::Node* node) { addUserEvent(new ViewerEventData(node, ViewerEventData::RemoveNode)); } /******************************************************************************* * Removes a node from the scene graph. ******************************************************************************/ void Viewer::removeNode(std::string nodeName) { RLOG_CPP(5, "Removing node " << nodeName); addUserEvent(new ViewerEventData(nodeName, ViewerEventData::RemoveNamedNode)); } /******************************************************************************* * Removes all nodes with a given name from a parent node. ******************************************************************************/ void Viewer::removeNode(osg::Group* parent, std::string child) { RLOG_CPP(5, "Removing node " << child << " of parent " << parent->getName()); addUserEvent(new ViewerEventData(parent, child, ViewerEventData::RemoveChildNode)); } /******************************************************************************* * ******************************************************************************/ void Viewer::removeNodes() { addUserEvent(new ViewerEventData(ViewerEventData::RemoveAllNodes)); } /******************************************************************************* * ******************************************************************************/ void Viewer::setCameraTransform(const HTr* A_CI) { addUserEvent(new ViewerEventData(A_CI, ViewerEventData::SetCameraTransform)); } /******************************************************************************* * ******************************************************************************/ void Viewer::setCameraTransform(double x, double y, double z, double thx, double thy, double thz) { HTr A_CI; double x6[6]; VecNd_set6(x6, x, y, z, thx, thy, thz); HTr_from6DVector(&A_CI, x6); setCameraTransform(&A_CI); } /******************************************************************************* * Removes all nodes with the given name from the rootNode ******************************************************************************/ int Viewer::removeInternal(std::string nodeName) { int nnd = 0; osg::Node* ndi; do { ndi = getNode(nodeName); if (ndi) { bool success = removeInternal(ndi); if (success) { nnd++; } else { RLOG(4, "Failed to remove node %s at iteration %d", nodeName.c_str(), nnd); } } } while (ndi); RLOG(5, "Removed %d nodes with name %s from the viewer", nnd, nodeName.c_str()); return nnd; } /******************************************************************************* * Removes a node from the scene graph. ******************************************************************************/ bool Viewer::removeInternal(osg::Node* node) { if (node == NULL) { RLOG(1, "Node is NULL - can't be deleted"); return false; } osg::Camera* hud = dynamic_cast<osg::Camera*>(node); if (hud != NULL) { osg::View::Slave* slave = viewer->findSlaveForCamera(hud); if (slave != NULL) { RLOG(4, "Hud can't be deleted - is not part of the scene graph"); return false; } // We are a bit pedantic and check that the camera is not the // viewer's camera. unsigned int si = viewer->findSlaveIndexForCamera(hud); unsigned int ci = viewer->findSlaveIndexForCamera(viewer->getCamera()); if (ci != si) { viewer->removeSlave(si); RLOG(5, "Hud successully deleted"); } else { RLOG(1, "Cannot remove the viewer's camera"); return false; } return true; } osg::Node::ParentList parents = node->getParents(); size_t nDeleted = 0; for (size_t i=0; i<parents.size(); ++i) { nDeleted++; parents[i]->removeChild(node); } if (nDeleted == 0) { RLOG(1, "Node can't be deleted - is not part of the scene graph"); return false; } return true; } /******************************************************************************* * Search through the parent node. We do this in a while loop to remove all * nodes with the same name ******************************************************************************/ int Viewer::removeInternal(osg::Node* parent, std::string nodeName) { osg::Node* toRemove = findNamedNodeRecursive(parent, nodeName); int nnd = 0; while (toRemove) { removeInternal(toRemove); toRemove = findNamedNodeRecursive(parent, nodeName); nnd++; } return nnd; } /******************************************************************************* * ******************************************************************************/ int Viewer::removeAllNodesInternal() { int nDeleted = rootnode->getNumChildren(); rootnode->removeChildren(0, nDeleted); this->rootnode->addChild(this->clearNode.get()); RLOG_CPP(5, "Removing all " << nDeleted << " nodes"); return nDeleted; } /******************************************************************************* * Sets the update frequency in [Hz]. ******************************************************************************/ void Viewer::setUpdateFrequency(double Hz) { this->updateFreq = Hz; } /******************************************************************************* * Returns the update frequency in [Hz]. ******************************************************************************/ double Viewer::updateFrequency() const { return this->updateFreq; } /******************************************************************************* * ******************************************************************************/ void Viewer::resetView() { addUserEvent(new ViewerEventData(ViewerEventData::ResetView)); } /******************************************************************************* * Sets the camera position and viewing direction * First vector is where camera is, Second vector is where the * camera points to, the up vector is set internally to always stay upright ******************************************************************************/ void Viewer::setCameraHomePosition(const HTr* A_CI) { addUserEvent(new ViewerEventData(A_CI, ViewerEventData::SetCameraHomePose)); } /******************************************************************************* * Sets the camera position and viewing direction * First vector is where camera is, Second vector is where the * camera points to, the up vector is set internally to always stay upright. * The eye, center and up vectors are stored in the rows of the transform's * rotation matrix. ******************************************************************************/ void Viewer::setCameraHomePosition(const osg::Vec3d& eye, const osg::Vec3d& center, const osg::Vec3d& up) { HTr ecu; Vec3d_setZero(ecu.org); Vec3d_set(ecu.rot[0], eye[0], eye[1], eye[2]); Vec3d_set(ecu.rot[1], center[0], center[1], center[2]); Vec3d_set(ecu.rot[2], up[0], up[1], up[2]); addUserEvent(new ViewerEventData(&ecu, ViewerEventData::SetCameraHomePoseEyeCenterUp)); } /******************************************************************************* * ******************************************************************************/ void Viewer::getCameraTransform(HTr* A_CI) const { osg::Matrix matrix = viewer->getCamera()->getViewMatrix(); HTr_fromViewMatrix(matrix, A_CI); } /******************************************************************************* * ******************************************************************************/ osg::Node* Viewer::getNodeUnderMouse(double I_mouseCoords[3]) { return Rcs::getNodeUnderMouse<osg::Node*>(*this->viewer.get(), mouseX, mouseY, I_mouseCoords); } /******************************************************************************* * ******************************************************************************/ osg::Node* Viewer::getNode(std::string nodeName) { return findNamedNodeRecursive(rootnode, nodeName); } /******************************************************************************* * aspectRatio = width/height * OSG returns field of view in [degrees]. We convert it to SI units ******************************************************************************/ void Viewer::getFieldOfView(double& width, double& height) const { double aspectRatio, zNear, zFar; viewer->getCamera()->getProjectionMatrixAsPerspective(width, aspectRatio, zNear, zFar); width = RCS_DEG2RAD(width); height = width/aspectRatio; } /******************************************************************************* * OSG returns field of view in [degrees]. We convert it to SI units ******************************************************************************/ double Viewer::getFieldOfView() const { double fovy, aspectRatio, zNear, zFar; viewer->getCamera()->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar); return RCS_DEG2RAD(fovy); } /******************************************************************************* * ******************************************************************************/ void Viewer::setFieldOfView(double fovy) { double fovyOld, aspectRatio, zNear, zFar; fovy = RCS_RAD2DEG(fovy); viewer->getCamera()->getProjectionMatrixAsPerspective(fovyOld, aspectRatio, zNear, zFar); viewer->getCamera()->setProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar); } /******************************************************************************* * Defaults are: * fov_org = 29.148431 aspectRatio_org = 1.333333 * znear=1.869018 zfar=10.042613 ******************************************************************************/ void Viewer::setFieldOfView(double fovWidth, double fovHeight) { double fovyOld, aspectRatio, zNear, zFar; fovWidth = RCS_RAD2DEG(fovWidth); fovHeight = RCS_RAD2DEG(fovHeight); viewer->getCamera()->getProjectionMatrixAsPerspective(fovyOld, aspectRatio, zNear, zFar); viewer->getCamera()->setProjectionMatrixAsPerspective(fovWidth, fovWidth/fovHeight, zNear, zFar); } /******************************************************************************* * Runs the viewer in its own thread. ******************************************************************************/ void* Viewer::ViewerThread(void* arg) { Rcs::Viewer* viewer = static_cast<Rcs::Viewer*>(arg); if (viewer->isThreadRunning() == true) { RLOG(1, "Viewer thread is already running"); return NULL; } viewer->lock(); viewer->init(); viewer->threadRunning = true; viewer->unlock(); while (viewer->isThreadRunning() == true) { viewer->frame(); unsigned long dt = (unsigned long)(1.0e6/viewer->updateFrequency()); Timer_usleep(dt); } return NULL; } /******************************************************************************* * ******************************************************************************/ void Viewer::runInThread(pthread_mutex_t* mutex) { this->mtxFrameUpdate = mutex; threadStopped = false; pthread_create(&frameThread, NULL, ViewerThread, (void*) this); // Wait until the class has been initialized while (!isInitialized()) { Timer_usleep(10000); } // ... and realized while (!isRealized()) { Timer_usleep(10000); } } /******************************************************************************* * For true, displays all nodes in wireframe, otherwise in solid ******************************************************************************/ void Viewer::displayWireframe(bool wf) { addUserEvent(new ViewerEventData(ViewerEventData::SetWireframeEnabled, wf)); } /******************************************************************************* * Toggles between solid and wireframe display ******************************************************************************/ void Viewer::toggleWireframe() { displayWireframe(!this->wireFrame); } /******************************************************************************* * Switches between shadow casting modes. ******************************************************************************/ void Viewer::setShadowEnabled(bool enable) { addUserEvent(new ViewerEventData(ViewerEventData::SetShadowEnabled, enable)); } /******************************************************************************* * Renders the scene in cartoon mode. ******************************************************************************/ void Viewer::setCartoonEnabled(bool enable) { addUserEvent(new ViewerEventData(ViewerEventData::SetCartoonEnabled, enable)); } /******************************************************************************* * ******************************************************************************/ void Viewer::setBackgroundColor(const std::string& color) { addUserEvent(new ViewerEventData(color, ViewerEventData::SetBackgroundColor)); } /******************************************************************************* * ******************************************************************************/ void Viewer::frame() { if (isInitialized() == false) { init(); } double dtFrame = Timer_getSystemTime(); // Publish all queued events before the frame() call userEventMtx.lock(); for (size_t i=0; i<userEventStack.size(); ++i) { getOsgViewer()->getEventQueue()->userEvent(userEventStack[i].get()); } userEventStack.clear(); userEventMtx.unlock(); lock(); viewer->frame(); unlock(); dtFrame = Timer_getSystemTime() - dtFrame; this->fps = 0.9*this->fps + 0.1*(1.0/dtFrame); } /******************************************************************************* This initialization function needs to be called from the thread that also calls the osg update traversals. That's why it is separated from the constructor. Otherwise, it leads to problems under msvc. *******************************************************************************/ void Viewer::init() { if (isInitialized() == true) { return; } viewer->setUpViewInWindow(llx, lly, sizeX, sizeY); // Stop listening to ESC key, cause it doesn't end RCS properly viewer->setKeyEventSetsDone(0); viewer->realize(); this->startView = viewer->getCamera()->getProjectionMatrix(); this->initialized = true; } /******************************************************************************* * ******************************************************************************/ void Viewer::optimize() { osgUtil::Optimizer optimizer; optimizer.optimize(rootnode); } /******************************************************************************* * ******************************************************************************/ void Viewer::setSceneData(osg::Node* node) { viewer->setSceneData(node); } /******************************************************************************* * ******************************************************************************/ bool Viewer::isRealized() const { return viewer->isRealized(); } /******************************************************************************* * ******************************************************************************/ bool Viewer::isInitialized() const { return this->initialized; } /******************************************************************************* * ******************************************************************************/ bool Viewer::isThreadRunning() const { return this->threadRunning; } /******************************************************************************* * ******************************************************************************/ void Viewer::stopUpdateThread() { if (threadRunning == false) { return; } this->threadRunning = false; pthread_join(frameThread, NULL); threadStopped = true; this->initialized = false; } /******************************************************************************* * ******************************************************************************/ osg::ref_ptr<osgViewer::Viewer> Viewer::getOsgViewer() const { return this->viewer; } /******************************************************************************* * ******************************************************************************/ bool Viewer::lock() const { if (this->mtxFrameUpdate!=NULL) { pthread_mutex_lock(this->mtxFrameUpdate); return true; } return false; } /******************************************************************************* * ******************************************************************************/ bool Viewer::unlock() const { if (this->mtxFrameUpdate!=NULL) { pthread_mutex_unlock(this->mtxFrameUpdate); return true; } return false; } /******************************************************************************* * ******************************************************************************/ bool Viewer::toggleVideoRecording() { return keyHandler->toggleVideoCapture(); } /******************************************************************************* * ******************************************************************************/ void Viewer::getMouseTip(double tip[3]) const { osg::Matrix vm = viewer->getCamera()->getViewMatrix(); osg::Matrix pm = viewer->getCamera()->getProjectionMatrix(); HTr A_CamI; getCameraTransform(&A_CamI); double planePt[3]; Vec3d_add(planePt, A_CamI.org, A_CamI.rot[0]); Rcs::getMouseTip(vm, pm, normalizedMouseX, normalizedMouseY, planePt, tip); } /******************************************************************************* * ******************************************************************************/ void Viewer::handleUserEvents(const osg::Referenced* userEvent) { RLOG(5, "Received user event"); const ViewerEventData* ev = dynamic_cast<const ViewerEventData*>(userEvent); if (!ev) { RLOG(5, "User event not of type ViewerEventData - skipping"); return; } switch (ev->eType) { case ViewerEventData::AddNode: if (ev->node.valid()) { RLOG(5, "Adding node \"%s\"", ev->node->getName().c_str()); addInternal(ev->node.get()); } else { RLOG(5, "ViewerEventData::AddNode: Found invalid node"); } break; case ViewerEventData::AddChildNode: RCHECK(ev->parent.valid()); RCHECK(ev->node.valid()); RLOG(5, "Adding node \"%s\"", ev->node->getName().c_str()); addInternal(ev->parent.get(), ev->node.get()); break; case ViewerEventData::RemoveNode: RCHECK(ev->node.valid()); RLOG(5, "Removing node \"%s\"", ev->node->getName().c_str()); removeInternal(ev->node.get()); break; case ViewerEventData::RemoveNamedNode: RLOG(5, "Removing all nodes with name \"%s\"", ev->childName.c_str()); removeInternal(ev->childName); break; case ViewerEventData::RemoveChildNode: RCHECK(ev->parent.valid()); RLOG(5, "Removing child node \"%s\" from parent %s", ev->childName.c_str(), ev->parent->getName().c_str()); removeInternal(ev->parent.get(), ev->childName); break; case ViewerEventData::RemoveAllNodes: removeAllNodesInternal(); break; case ViewerEventData::AddEventHandler: RCHECK(ev->eventHandler.valid()); RLOG(5, "Adding handler \"%s\"", ev->eventHandler->getName().c_str()); viewer->addEventHandler(ev->eventHandler.get()); break; case ViewerEventData::SetCameraTransform: RLOG(5, "Setting camera transform"); viewer->getCameraManipulator()->setByInverseMatrix(viewMatrixFromHTr(&ev->trf)); break; case ViewerEventData::SetCameraHomePose: { RLOG(5, "Setting camera home pose"); const HTr* A_CI = &ev->trf; osg::Vec3d eye(A_CI->org[0], A_CI->org[1], A_CI->org[2]); osg::Vec3d center(A_CI->org[0] + A_CI->rot[2][0], A_CI->org[1] + A_CI->rot[2][1], A_CI->org[2] + A_CI->rot[2][2]); osg::Vec3d up(-A_CI->rot[1][0], -A_CI->rot[1][1], -A_CI->rot[1][2]); viewer->getCameraManipulator()->setHomePosition(eye, center, up); viewer->home(); } break; // The eye, center and up vectors are stored in the rows of the transform's // rotation matrix. case ViewerEventData::SetCameraHomePoseEyeCenterUp: { RLOG(5, "Setting camera home pose from eye, center and up"); const HTr* A_CI = &ev->trf; osg::Vec3d eye(A_CI->rot[0][0], A_CI->rot[0][1], A_CI->rot[0][2]); osg::Vec3d center(A_CI->rot[1][0], A_CI->rot[1][1], A_CI->rot[1][2]); osg::Vec3d up(A_CI->rot[2][0], A_CI->rot[2][1], A_CI->rot[2][2]); viewer->getCameraManipulator()->setHomePosition(eye, center, up); viewer->home(); } break; // Sets the title of the viewer windows. We set the title for all windows, // but only one window should be created anyways case ViewerEventData::SetTitle: { RLOG_CPP(5, "Setting window title to" << ev->childName); osgViewer::ViewerBase::Windows windows; this->viewer->getWindows(windows); osgViewer::ViewerBase::Windows::iterator window; for (window = windows.begin(); window != windows.end(); window++) { (*window)->setWindowName(ev->childName); } } break; case ViewerEventData::ResetView: RLOG(5, "Resetting view"); viewer->getCamera()->setProjectionMatrix(this->startView); break; case ViewerEventData::SetBackgroundColor: RLOG_CPP(5, "Setting background color to" << ev->childName); this->clearNode->setClearColor(colorFromString(ev->childName.c_str())); break; case ViewerEventData::SetShadowEnabled: { RLOG(5, "Setting shadows to %s", ev->flag ? "TRUE" : "FALSE"); osg::Matrix lastViewMatrix = viewer->getCameraManipulator()->getMatrix(); if (ev->flag==false) { RLOG(3, "Shadows off"); if (this->shadowsEnabled == true) { viewer->setSceneData(rootnode.get()); } this->shadowsEnabled = false; } else { RLOG(3, "Shadows on"); if (this->shadowsEnabled == false) { viewer->setSceneData(shadowScene.get()); } this->shadowsEnabled = true; } viewer->getCameraManipulator()->setByMatrix(lastViewMatrix); } break; case ViewerEventData::SetWireframeEnabled: { RLOG(5, "Setting wireframe to %s", ev->flag ? "TRUE" : "FALSE"); this->wireFrame = ev->flag; osg::ref_ptr<osg::StateSet> sSet = rootnode->getOrCreateStateSet(); if (ev->flag == true) { sSet->setAttribute(new osg::PolygonMode (osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::LINE)); } else { sSet->setAttribute(new osg::PolygonMode (osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::FILL)); } } break; case ViewerEventData::SetCartoonEnabled: { RLOG(5, "Setting cartoon mode to %s", ev->flag ? "TRUE" : "FALSE"); osgFX::Effect* cartoon = dynamic_cast<osgFX::Effect*>(rootnode.get()); if (!cartoon) { return; } // Disable shadows when switching to cartoon mode if ((ev->flag==true) && (this->shadowsEnabled==true)) { viewer->setSceneData(rootnode.get()); this->shadowsEnabled = false; } cartoon->setEnabled(ev->flag); } break; case ViewerEventData::SetTrackballCenter: { RLOG(5, "Setting trackball center to %f %f %f", ev->trf.org[0], ev->trf.org[1], ev->trf.org[2]); osgGA::TrackballManipulator* trackball = dynamic_cast<osgGA::TrackballManipulator*>(viewer->getCameraManipulator()); if (trackball) { const double* cntr = ev->trf.org; trackball->setCenter(osg::Vec3(cntr[0], cntr[1], cntr[2])); } } break; default: RLOG(1, "Unknown event type %d", (int) ev->eType); break; } } /******************************************************************************* * ******************************************************************************/ bool Viewer::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { switch (ea.getEventType()) { ///////////////////////////////////////////////////////////////// // User events triggered through classes API ///////////////////////////////////////////////////////////////// case osgGA::GUIEventAdapter::USER: { handleUserEvents(ea.getUserData()); break; } ///////////////////////////////////////////////////////////////// // Gets called once viewer window is closed. We then leave the // viewer's thread so that no more rendering is performed. ///////////////////////////////////////////////////////////////// case (osgGA::GUIEventAdapter::CLOSE_WINDOW): { stopUpdateThread(); break; } ///////////////////////////////////////////////////////////////// // Frame update event ///////////////////////////////////////////////////////////////// case (osgGA::GUIEventAdapter::FRAME): { this->mouseX = ea.getX(); this->mouseY = ea.getY(); this->normalizedMouseX = ea.getXnormalized(); this->normalizedMouseY = ea.getYnormalized(); if (cameraLight.valid()) { HTr A_CI; getCameraTransform(&A_CI); osg::Vec4 lightpos; lightpos.set(A_CI.org[0], A_CI.org[1], A_CI.org[2] + 0 * 2.0, 1.0f); cameraLight->getLight()->setPosition(lightpos); } break; } ///////////////////////////////////////////////////////////////// // Mouse button pressed events. ///////////////////////////////////////////////////////////////// case (osgGA::GUIEventAdapter::PUSH): { // Left mouse button pressed if (ea.getButton() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON) { this->leftMouseButtonPressed = true; if (this->rightMouseButtonPressed) { double center[3] = {0.0, 0.0, 0.0};; osg::Node* click = getNodeUnderMouse(center); if (click) { setTrackballCenter(center[0], center[1], center[2]); } } } // Right mouse button pressed else if (ea.getButton() == osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON) { this->rightMouseButtonPressed = true; } break; } ///////////////////////////////////////////////////////////////// // Mouse button released events. ///////////////////////////////////////////////////////////////// case (osgGA::GUIEventAdapter::RELEASE): { // Left mouse button released. if (ea.getButton() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON) { this->leftMouseButtonPressed = false; } // Right mouse button released. if (ea.getButton() == osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON) { this->rightMouseButtonPressed = false; } break; } ///////////////////////////////////////////////////////////////// // Key pressed events ///////////////////////////////////////////////////////////////// case (osgGA::GUIEventAdapter::KEYDOWN): { // key '0' is ASCII code 48, then running up to 57 for '9' if ((ea.getKey() >= 48) && (ea.getKey() <= 57)) { unsigned int dLev = ea.getKey() - 48; if (dLev<9) { RcsLogLevel = dLev; } else { RcsLogLevel = -1; } RMSG("Setting debug level to %u", dLev); return false; } else if (ea.getKey() == osgGA::GUIEventAdapter::KEY_F11) { HTr A_CI; double x[6]; this->getCameraTransform(&A_CI); HTr_to6DVector(x, &A_CI); RMSGS("Camera pose is %f %f %f %f %f %f (degrees: %.3f %.3f %.3f)", x[0], x[1], x[2], x[3], x[4], x[5], RCS_RAD2DEG(x[3]), RCS_RAD2DEG(x[4]), RCS_RAD2DEG(x[5])); } // // Toggle wireframe // else if (ea.getKey() == 'w') { toggleWireframe(); return false; } // // Toggle shadows // else if (ea.getKey() == 's') { setShadowEnabled(!this->shadowsEnabled); return false; } // // Toggle cartoon mode // else if (ea.getKey() == 'R') { this->cartoonEnabled = !this->cartoonEnabled; setCartoonEnabled(this->cartoonEnabled); return false; } else if (ea.getKey() == 'M') { keyHandler->toggleVideoCapture(); return false; } break; } // case(osgGA::GUIEventAdapter::KEYDOWN): default: break; } // switch(ea.getEventType()) return false; } /******************************************************************************* * ******************************************************************************/ void Viewer::setTrackballCenter(double x, double y, double z) { HTr cntr; HTr_setIdentity(&cntr); Vec3d_set(cntr.org, x, y, z); addUserEvent(new ViewerEventData(&cntr, ViewerEventData::SetTrackballCenter)); } /******************************************************************************* * ******************************************************************************/ bool Viewer::getTrackballCenter(double pos[3]) const { osgGA::TrackballManipulator* trackball = dynamic_cast<osgGA::TrackballManipulator*>(viewer->getCameraManipulator()); if (trackball) { osg::Vec3d tbCenter = trackball->getCenter(); Vec3d_set(pos, tbCenter.x(), tbCenter.y(), tbCenter.z()); return true; } return false; } /******************************************************************************* * ******************************************************************************/ bool Viewer::isThreadStopped() const { return this->threadStopped; } /******************************************************************************* * ******************************************************************************/ double Viewer::getFPS() const { return this->fps; } /******************************************************************************* * ******************************************************************************/ std::string Viewer::getDefaultBackgroundColor() const { return defaultBgColor; } /******************************************************************************* * Add a node to the root node. ******************************************************************************/ void Viewer::setTitle(const std::string& title) { addUserEvent(new ViewerEventData(title, ViewerEventData::SetTitle)); } /******************************************************************************* * This might run concurrent with the frame's appending of events to the event * queue. ******************************************************************************/ void Viewer::addUserEvent(osg::Referenced* userEvent) { osg::ref_ptr<osg::Referenced> ev(userEvent); userEventMtx.lock(); userEventStack.push_back(ev); userEventMtx.unlock(); } } // namespace Rcs
package db import ( "errors" "github.com/gueradevelopment/team-context/models" ) // TaskDB - Task model database accessor type TaskDB struct{} var ( items = make(map[string]models.Task) ) // Get - retrieves a single resource func (db *TaskDB) Get(id string, c chan Result) { defer close(c) result := Result{} item, ok := checklistItems[id] if ok { result.Result = item result.Err = nil } else { result.Err = errors.New("No result") } c <- result } // GetAll - retrieves all resources func (db *TaskDB) GetAll(c chan ResultArray, resources map[string][]string) { defer close(c) result := ResultArray{} var arr = []Model{} var boardID string if resources["boardId"] != nil { boardID = resources["boardId"][0] } var checklistID string if resources["checklistId"] != nil { checklistID = resources["checklistId"][0] } for _, v := range items { if checklistID != "" && v.ChecklistID == checklistID { arr = append(arr, v) } if checklistID == "" { if boardID != "" && v.BoardID == boardID { arr = append(arr, v) } if boardID == "" { arr = append(arr, v) } } } result.Result = arr c <- result } // Add - creates a resource func (db *TaskDB) Add(item models.Task, c chan Result) { defer close(c) result := Result{} if items[item.ID] == (models.Task{}) { items[item.ID] = item result.Result = item } else { result.Err = errors.New("Duplicated ID") } c <- result } // Edit - updates a resource func (db *TaskDB) Edit(item models.Task, c chan Result) { defer close(c) result := Result{} if items[item.ID] == (models.Task{}) { result.Err = errors.New("No such ID") } else { items[item.ID] = item result.Result = item } c <- result } // Delete - deletes a resource func (db *TaskDB) Delete(id string, c chan Result) { defer close(c) result := Result{} item := items[id] if item == (models.Task{}) { result.Err = errors.New("No such ID") } else { result.Result = item delete(items, id) } c <- result }
import * as vs from "../../../../domain/validation" import { ChannelCommandRepository, ChannelQueryRepository, MessageCommandRepository, MessageQueryRepository, TransactionRepository, UserCommandRepository, UserQueryRepository, } from "../../../repositories" import { DeleteMessageApplication, ErrorCodes } from "../../../../application/message/DeleteMessage" import { InternalErrorSpec, InvalidAuth, UnexpectedErrorSpec, raise } from "../../error" import { MethodFacts, defineArguments, defineErrors, defineMethod } from "../../define" import { ApplicationError } from "../../../../application/ApplicationError" import { AuthenticationMethods } from "../../facts/authentication_method" import { ChannelGroupTimelineCommandRepository } from "../../../../infrastructure/prisma/repository" import { ContentTypes } from "../../facts/content_type" import { HttpMethods } from "../../facts/http_method" import { MethodIdentifiers } from "../../identifier" export const argumentSpecs = defineArguments(["id"] as const, { id: { description: ["削除するメッセージのID"], examples: ["99999"], required: true, validator: vs.messageId(), }, }) export const expectedErrorSpecs = defineErrors( [ErrorCodes.DoNotHavePermission, "invalid_auth", "internal_error", "unexpected_error"] as const, argumentSpecs, { do_not_have_permission: { description: ["メッセージを削除する権限がありません"], hint: ["信用レベルを上げると削除できるようになります"], code: "do_not_have_permission", }, invalid_auth: new InvalidAuth(), internal_error: new InternalErrorSpec(), unexpected_error: new UnexpectedErrorSpec(), } ) export const facts: MethodFacts = { url: MethodIdentifiers.DeleteMessage, httpMethod: HttpMethods.POST, rateLimiting: {}, acceptedContentTypes: [ContentTypes.ApplicationJson], authenticationRequired: true, private: false, acceptedAuthenticationMethods: [ AuthenticationMethods.OAuth, AuthenticationMethods.AccessToken, AuthenticationMethods.Cookie, ], acceptedScopes: {}, description: ["チャンネルまたはスレッドに投稿します"], } type ReturnType = Promise<boolean> export default defineMethod(facts, argumentSpecs, expectedErrorSpecs, async (args, errors, authUser): ReturnType => { const transaction = await TransactionRepository.new<ReturnType>() if (authUser == null) { raise(errors["invalid_auth"]) } try { return await transaction.$transaction(async (transactionSession) => { return await new DeleteMessageApplication( new UserQueryRepository(transactionSession), new UserCommandRepository(transactionSession), new ChannelQueryRepository(transactionSession), new ChannelCommandRepository(transactionSession), new MessageQueryRepository(transactionSession), new MessageCommandRepository(transactionSession), new ChannelGroupTimelineCommandRepository(transactionSession) ).delete({ messageId: args.id, requestUserId: authUser.id, }) }) } catch (error) { if (error instanceof ApplicationError) { if (error.code === ErrorCodes.DoNotHavePermission) { raise(errors["do_not_have_permission"], error) } else { raise(errors["internal_error"], error) } } else if (error instanceof Error) { raise(errors["unexpected_error"], error) } else { raise(errors["unexpected_error"], new Error("unexpected_error")) } } })
#!/bin/bash # This does not work, you have to type this in manually unfortunately source venv/bin/activate
<gh_stars>0 package q13_test import ( "testing" "puzzle/quizzes/q13" ) func Test_cards(t *testing.T) { cards := q13.Cards([]int{1, 2, 3, 4}) b2 := []q13.ICards{} for _, v := range cards.Before() { t.Logf("n=1, %v", v.Values()) b2 = append(b2, v) } b3 := []q13.ICards{} for _, v := range b2 { b3 = append(b3, v.Before()...) } for _, v := range b3 { t.Logf("n=2 %v\n", v) } b4 := []q13.ICards{} for _, v := range b3 { b4 = append(b4, v.Before()...) } for _, v := range b4 { t.Logf("n=3 %v\n", v) } }
def create_url_mapping(url_patterns): url_mapping = {} for pattern, view_function in url_patterns: if view_function in url_mapping: url_mapping[view_function].append(pattern) else: url_mapping[view_function] = [pattern] return url_mapping
#!/usr/bin/env bash set -eux # yq sudo add-apt-repository -y ppa:rmescandon/yq sudo apt update sudo apt install -y yq # jq sudo apt install -y jq # sponge sudo apt install -y moreutils # promtool mkdir -p build cd build prom_version=2.3.2 prom_file="prometheus-${prom_version}.linux-amd64.tar.gz" curl -LO https://github.com/prometheus/prometheus/releases/download/v${prom_version}/${prom_file} echo "351931fe9bb252849b7d37183099047fbe6d7b79dcba013fb6ae19cc1bbd8552 $prom_file" | sha256sum --check tar xzvf $prom_file sudo cp prometheus-${prom_version}.linux-amd64/promtool /usr/local/bin/ # install helm curl https://raw.githubusercontent.com/kubernetes/helm/master/scripts/get > get_helm.sh chmod 777 get_helm.sh sudo ./get_helm.sh helm init -c # socat is needed for helm init --wait to work sudo apt-get install -y socat
#!/bin/bash set -x export DASHROOT=`pwd` export SHA=`git log --pretty=format:'%h' -n 1` set +x if [[ "$DOCKER_IMAGE" == "fedora" ]]; then source /usr/share/Modules/init/bash module load mpi fi source `pwd`/../tci/bin/activate set -x export PATH=.:${PATH} export PYTHONPATH=${DASHROOT}/build/lib export LD_LIBRARY_PATH=${DASHROOT}/build/lib export MPLBACKEND=Agg mkdir build ctest -S ${DASHROOT}/test/travis_ci/ctest_linux.cmake -V --timeout 180
package com.hongbog.view; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.PixelFormat; import android.graphics.PorterDuff; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import com.hongbog.dto.SensorDTO; import com.hongbog.util.Dlog; import com.tzutalin.quality.R; import static com.hongbog.view.SensorListener.ACEL_MSG; /** * Created by taein on 2018-07-12. */ public class BallSurFaceView extends SurfaceView implements SurfaceHolder.Callback { private SurfaceHolder mHolder; private DrawThread mThread; private final int BALL_SIZE = 0; private Handler mHandler; private Bitmap mBitmap; public BallSurFaceView(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); mBitmap = BitmapFactory.decodeResource( getResources(), R.drawable.ball); mHolder = getHolder(); mHolder.setFormat(PixelFormat.TRANSLUCENT); mHolder.addCallback(this); mHolder.setFixedSize(getWidth(), getHeight()); setFocusable(true); setZOrderOnTop(true); mHandler = new SensorChangeHandler(); SensorListener.setBallSurfaceHandler(mHandler); } @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { mThread = new DrawThread(); mThread.start(); } @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) { if(mThread != null){ mThread.setSize(width, height); } } @Override public void surfaceDestroyed(SurfaceHolder paramSurfaceHolder) { boolean retry = true; mThread.setExit(true); while (retry) { try { mThread.join(); retry = false; } catch (InterruptedException e) { Dlog.e("InterruptedException Message : " + e.getMessage()); return; } } } private class DrawThread extends Thread{ private boolean bExit; private int dspWidth, dspHeight; private int ballSize; private SurfaceHolder mHolder; private float acelX; private float acelZ; private Ball ball; DrawThread(){ mHolder = getHolder(); bExit = false; ball = new Ball(); } public void setExit(boolean exit){ bExit = exit; } public void setAcel(float x, float z){ acelX = x; acelZ = z; } public void setSize(int width, int height) { dspWidth = width; dspHeight = height; ballSize = (dspWidth / (16 - BALL_SIZE) / 2); } public void run(){ while(bExit == false){ Canvas canvas = null; try { canvas = mHolder.lockCanvas(); ball.calcBall(acelX, acelZ, dspWidth, dspHeight, ballSize); synchronized (mHolder) { if (canvas == null) break; canvas.drawColor(0, PorterDuff.Mode.CLEAR); canvas.drawBitmap(mBitmap, ball.getBallSrc(), ball.getBallDst(), null); } }catch(IllegalArgumentException ex){ Dlog.e("IllegalArgumentException Message : " + ex.getMessage()); mThread.setExit(true); return; }finally { if(canvas != null){ mHolder.unlockCanvasAndPost(canvas); } } } } } public class SensorChangeHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what){ case ACEL_MSG: SensorDTO sensorDTO = (SensorDTO)msg.obj; if(mThread != null && mThread.isAlive()){ mThread.setAcel(sensorDTO.getAccelX(), sensorDTO.getAccelZ()); } break; } } } }
#!/bin/bash # ========== Experiment Seq. Idx. 1017 / 50.7.3 / N. 63/1/3 - _S=50.7.3 D1_N=63 a=-1 b=1 c=1 d=1 e=1 f=1 D3_N=1 g=-1 h=-1 i=1 D4_N=3 j=3 ========== set -u # Prints header echo -e '\n\n========== Experiment Seq. Idx. 1017 / 50.7.3 / N. 63/1/3 - _S=50.7.3 D1_N=63 a=-1 b=1 c=1 d=1 e=1 f=1 D3_N=1 g=-1 h=-1 i=1 D4_N=3 j=3 ==========\n\n' if [[ "No" == "Yes" ]]; then echo 'FATAL: This treatment included an SVM layer.'>&2 echo ' Something very wrong happened!'>&2 exit 161 fi # Prepares all environment variables JBHI_DIR="$HOME/jbhi-special-issue" DATASET_DIR="$JBHI_DIR/data/edra-dermoscopic-seg.598.tfr" MODEL_DIR="$JBHI_DIR/models/deep.63" RESULTS_DIR="$JBHI_DIR/results" RESULTS_PREFIX="$RESULTS_DIR/deep.63.layer.1.test.3.index.2637.nosvm" RESULTS_PATH="$RESULTS_PREFIX.results.txt" # ...variables expected by jbhi-checks.include.sh and jbhi-footer.include.sh SOURCES_GIT_DIR="$JBHI_DIR/jbhi-special-issue" LIST_OF_INPUTS="$DATASET_DIR/finish.txt:$MODEL_DIR/finish.txt" START_PATH="$RESULTS_PREFIX.start.txt" FINISH_PATH="$RESULTS_PREFIX.finish.txt" LOCK_PATH="$RESULTS_PREFIX.running.lock" LAST_OUTPUT="$RESULTS_PATH" # EXPERIMENT_STATUS=1 # STARTED_BEFORE=No mkdir -p "$RESULTS_DIR" # # Assumes that the following environment variables where initialized # SOURCES_GIT_DIR="$JBHI_DIR/jbhi-special-issue" # LIST_OF_INPUTS="$DATASET_DIR/finish.txt:$MODELS_DIR/finish.txt:" # START_PATH="$OUTPUT_DIR/start.txt" # FINISH_PATH="$OUTPUT_DIR/finish.txt" # LOCK_PATH="$OUTPUT_DIR/running.lock" # LAST_OUTPUT="$MODEL_DIR/[[[:D1_MAX_NUMBER_OF_STEPS:]]].meta" EXPERIMENT_STATUS=1 STARTED_BEFORE=No # Checks if code is stable, otherwise alerts scheduler pushd "$SOURCES_GIT_DIR" >/dev/null GIT_STATUS=$(git status --porcelain) GIT_COMMIT=$(git log | head -n 1) popd >/dev/null if [ "$GIT_STATUS" != "" ]; then echo 'FATAL: there are uncommitted changes in your git sources file' >&2 echo ' for reproducibility, experiments only run on committed changes' >&2 echo >&2 echo ' Git status returned:'>&2 echo "$GIT_STATUS" >&2 exit 162 fi # The experiment is already finished - exits with special code so scheduler won't retry if [[ "$FINISH_PATH" != "-" ]]; then if [[ -e "$FINISH_PATH" ]]; then echo 'INFO: this experiment has already finished' >&2 exit 163 fi fi # The experiment is not ready to run due to dependencies - alerts scheduler if [[ "$LIST_OF_INPUTS" != "" ]]; then IFS=':' tokens_of_input=( $LIST_OF_INPUTS ) input_missing=No for input_to_check in ${tokens_of_input[*]}; do if [[ ! -e "$input_to_check" ]]; then echo "ERROR: input $input_to_check missing for this experiment" >&2 input_missing=Yes fi done if [[ "$input_missing" != No ]]; then exit 164 fi fi # Sets trap to return error code if script is interrupted before successful finish LOCK_SUCCESS=No FINISH_STATUS=161 function finish_trap { if [[ "$LOCK_SUCCESS" == "Yes" ]]; then rmdir "$LOCK_PATH" &> /dev/null fi if [[ "$FINISH_STATUS" == "165" ]]; then echo 'WARNING: experiment discontinued because other process holds its lock' >&2 else if [[ "$FINISH_STATUS" == "160" ]]; then echo 'INFO: experiment finished successfully' >&2 else [[ "$FINISH_PATH" != "-" ]] && rm -f "$FINISH_PATH" echo 'ERROR: an error occurred while executing the experiment' >&2 fi fi exit "$FINISH_STATUS" } trap finish_trap EXIT # While running, locks experiment so other parallel threads won't attempt to run it too if mkdir "$LOCK_PATH" --mode=u=rwx,g=rx,o=rx &>/dev/null; then LOCK_SUCCESS=Yes else echo 'WARNING: this experiment is already being executed elsewhere' >&2 FINISH_STATUS="165" exit fi # If the experiment was started before, do any cleanup necessary if [[ "$START_PATH" != "-" ]]; then if [[ -e "$START_PATH" ]]; then echo 'WARNING: this experiment is being restarted' >&2 STARTED_BEFORE=Yes fi #...marks start date -u >> "$START_PATH" echo GIT "$GIT_COMMIT" >> "$START_PATH" fi # If the experiment was started before, do any cleanup necessary if [[ "$STARTED_BEFORE" == "Yes" ]]; then echo -n fi #...gets closest checkpoint file MODEL_CHECKPOINT=$(ls "$MODEL_DIR/"model.ckpt-*.index | \ sed 's/.*ckpt-\([0-9]*\)\..*/\1/' | \ sort -n | \ awk -v c=1 -v t=15000 \ 'NR==1{d=$c-t;d=d<0?-d:d;v=$c;next}{m=$c-t;m=m<0?-m:m}m<d{d=m;v=$c}END{print v}') MODEL_PATH="$MODEL_DIR/model.ckpt-$MODEL_CHECKPOINT" echo "$MODEL_PATH" >> "$START_PATH" #...performs prediction echo Testing on "$MODEL_PATH" python \ "$SOURCES_GIT_DIR/predict_image_classifier.py" \ --model_name="resnet_v2_101_seg" \ --checkpoint_path="$MODEL_PATH" \ --dataset_name=skin_lesions \ --task_name=label \ --dataset_split_name=test \ --preprocessing_name=dermatologic \ --aggressive_augmentation="True" \ --add_rotations="True" \ --minimum_area_to_crop="0.20" \ --normalize_per_image="1" \ --batch_size=1 \ --id_field_name=id \ --pool_scores=avg \ --eval_replicas="50" \ --output_file="$RESULTS_PATH" \ --dataset_dir="$DATASET_DIR" # Tip: leave last the arguments that make the command fail if they're absent, # so if there's a typo or forgotten \ the entire thing fails EXPERIMENT_STATUS="$?" # #...starts training if [[ "$EXPERIMENT_STATUS" == "0" ]]; then if [[ "$LAST_OUTPUT" == "" || -e "$LAST_OUTPUT" ]]; then if [[ "$FINISH_PATH" != "-" ]]; then date -u >> "$FINISH_PATH" echo GIT "$GIT_COMMIT" >> "$FINISH_PATH" fi FINISH_STATUS="160" fi fi
def generate_report(repo_list): total_stars = sum(stars for _, stars in repo_list) highest_star_repo = max(repo_list, key=lambda x: x[1]) lowest_star_repo = min(repo_list, key=lambda x: x[1]) return { "total_stars": total_stars, "highest_star_repo": highest_star_repo, "lowest_star_repo": lowest_star_repo }
TERMUX_PKG_HOMEPAGE=https://wiki.termux.com/wiki/Termux:API TERMUX_PKG_DESCRIPTION="Termux API - static commands (install also the Termux:API app)" TERMUX_PKG_LICENSE="MIT" TERMUX_PKG_VERSION=0.5 TERMUX_PKG_SHA256=c4e793ab6402213efd88138486d23038e29692df3f36ddb5c590d9adc358d702 TERMUX_PKG_SRCURL=https://github.com/am0n666/termux-api/raw/master/termux-api-package-0.46.tar.gz TERMUX_PKG_BUILD_IN_SRC=true TERMUX_PKG_DEPENDS="bash"
#!/bin/bash if [ "$EUID" -ne 0 ] then echo "Please run as root" exit fi before_reboot(){ apt update -y apt upgrade -y apt install ufw iptables } after_reboot(){ ufw allow 9001 ufw allow 9030 ufw allow 22 ufw allow 222 ufw allow 80 ufw allow 53 ufw enable } if [ -f /var/run/rebooting-for-updates ]; then after_reboot rm /var/run/rebooting-for-updates update-rc.d myupdate remove else before_reboot touch /var/run/rebooting-for-updates update-rc.d myupdate defaults reboot now fi
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. DOWNLOAD=$1 for FOLDER in 'img_db' 'txt_db' 'pretrained' 'finetune'; do if [ ! -d $DOWNLOAD/$FOLDER ] ; then mkdir -p $DOWNLOAD/$FOLDER fi done BLOB='https://acvrpublicycchen.blob.core.windows.net/uniter' # image dbs for SPLIT in 'train2014' 'val2014'; do if [ ! -d $DOWNLOAD/img_db/coco_$SPLIT ] ; then wget $BLOB/img_db/coco_$SPLIT.tar -P $DOWNLOAD/img_db/ tar -xvf $DOWNLOAD/img_db/coco_$SPLIT.tar -C $DOWNLOAD/img_db fi done if [ ! -d $DOWNLOAD/img_db/flickr30k ] ; then wget $BLOB/img_db/flickr30k.tar -P $DOWNLOAD/img_db/ tar -xvf $DOWNLOAD/img_db/flickr30k.tar -C $DOWNLOAD/img_db fi # text dbs for SPLIT in 'train' 'restval' 'val' 'test'; do wget $BLOB/txt_db/itm_coco_$SPLIT.db.tar -P $DOWNLOAD/txt_db/ tar -xvf $DOWNLOAD/txt_db/itm_coco_$SPLIT.db.tar -C $DOWNLOAD/txt_db done for SPLIT in 'train' 'val' 'test'; do wget $BLOB/txt_db/itm_flickr30k_$SPLIT.db.tar -P $DOWNLOAD/txt_db/ tar -xvf $DOWNLOAD/txt_db/itm_flickr30k_$SPLIT.db.tar -C $DOWNLOAD/txt_db done if [ ! -f $DOWNLOAD/pretrained/uniter-base.pt ] ; then wget $BLOB/pretrained/uniter-base.pt -P $DOWNLOAD/pretrained/ fi
package org.insightcentre.nlp.saffron.data.connections; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * * @author <NAME> &lt;<EMAIL>&gt; */ @JsonIgnoreProperties(ignoreUnknown = true) public class AuthorTerm { private String authorId; private String termId; private int matches; private int occurrences; private int paperCount; // Number of papers for researcher that term occurs in. private double tfIrf; // Like TFIDF but with researchers instead of documents. // See "Domain adaptive extraction of topical hierarchies // for Expertise Mining" (Georgeta Bordea (2013)) for // evaluations of different methods. private double score; // tfirf * term score private double researcherScore; // score for researcher's ranking for this particular term public String getAuthorId() { return authorId; } public void setAuthorId(String authorId) { this.authorId = authorId; } public String getTermId() { return termId; } public void setTermId(String termId) { this.termId = termId; } public int getMatches() { return matches; } public void setMatches(int matches) { this.matches = matches; } public int getOccurrences() { return occurrences; } public void setOccurrences(int occurrences) { this.occurrences = occurrences; } public int getPaperCount() { return paperCount; } public void setPaperCount(int paperCount) { this.paperCount = paperCount; } public double getTfIrf() { return tfIrf; } public void setTfIrf(double tfIrf) { this.tfIrf = tfIrf; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } public double getResearcherScore() { return researcherScore; } public void setResearcherScore(double researcherScore) { this.researcherScore = researcherScore; } @Override public int hashCode() { int hash = 7; hash = 43 * hash + Objects.hashCode(this.authorId); hash = 43 * hash + Objects.hashCode(this.termId); hash = 43 * hash + this.matches; hash = 43 * hash + this.occurrences; hash = 43 * hash + this.paperCount; hash = 43 * hash + (int) (Double.doubleToLongBits(this.tfIrf) ^ (Double.doubleToLongBits(this.tfIrf) >>> 32)); hash = 43 * hash + (int) (Double.doubleToLongBits(this.score) ^ (Double.doubleToLongBits(this.score) >>> 32)); hash = 43 * hash + (int) (Double.doubleToLongBits(this.researcherScore) ^ (Double.doubleToLongBits(this.researcherScore) >>> 32)); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final AuthorTerm other = (AuthorTerm) obj; if (!Objects.equals(this.authorId, other.authorId)) { return false; } if (!Objects.equals(this.termId, other.termId)) { return false; } if (this.matches != other.matches) { return false; } if (this.occurrences != other.occurrences) { return false; } if (this.paperCount != other.paperCount) { return false; } if (Double.doubleToLongBits(this.tfIrf) != Double.doubleToLongBits(other.tfIrf)) { return false; } if (Double.doubleToLongBits(this.score) != Double.doubleToLongBits(other.score)) { return false; } if (Double.doubleToLongBits(this.researcherScore) != Double.doubleToLongBits(other.researcherScore)) { return false; } return true; } @Override public String toString() { return "AuthorTerm [authorId=" + authorId + ", termId=" + termId + ", matches=" + matches + ", occurrences=" + occurrences + ", paperCount=" + paperCount + ", tfIrf=" + tfIrf + ", score=" + score + ", researcherScore=" + researcherScore + "]"; } }
<filename>src/widgets/settingspages/IgnoresPage.hpp<gh_stars>1-10 #pragma once #include "widgets/settingspages/SettingsPage.hpp" #include <QStringListModel> class QVBoxLayout; namespace chatterino { class IgnoresPage : public SettingsPage { public: IgnoresPage(); void onShow() final; private: QStringListModel userListModel_; }; } // namespace chatterino
<gh_stars>1-10 /** * 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.smartloli.kafka.eagle.core.factory; import com.alibaba.fastjson.JSONObject; /** * ZkService operate comand and get metadata from zookeeper interface. * * @author smartloli. * * Created by Jan 18, 2017. * * Update by hexiang 20170216 */ public interface ZkService { /** Zookeeper delete command. */ public String delete(String clusterAlias, String cmd); /** Find zookeeper leader node. */ public String findZkLeader(String clusterAlias); /** Zookeeper get command. */ public String get(String clusterAlias, String cmd); /** Zookeeper ls command. */ public String ls(String clusterAlias, String cmd); /** Get zookeeper health status. */ public String status(String host, String port); /** Get zookeeper cluster information. */ public String zkCluster(String clusterAlias); /** Judge whether the zkcli is active. */ public JSONObject zkCliStatus(String clusterAlias); }
python lab-09_numbers_and_missing_data.py
#!/bin/bash FROM="go1.8.3" TO="go1.10.2" PKGS=( "ast" "constant" "doc" "format" "internal/format" "internal/testenv" "parser" "printer" "scanner" "token" "types" ) SGOSRC=`pwd` function last-commit { git log | head -n 1 | awk '{print $2}' } function checkout-go { echo "Checking out $1." cd /usr/local/go git checkout $1 for dir in ${PKGS[@]}; do cp -r ./src/go/$dir/ $SGOSRC/sgo/$dir done cd $SGOSRC git add ./sgo git commit -m "[upgrade-go-version.sh] Checkout $1." } checkout-go $FROM FROMCOMMIT=`last-commit` echo "Getting commit with SGo changes on top of $FROM." git revert --no-edit HEAD git commit --amend -m "[upgrade-go-version.sh] Apply SGo changes on top of $FROM." SGOCOMMIT=`last-commit` git reset --hard $FROMCOMMIT checkout-go $TO echo "Cherry-picking SGo changes from $FROM on top of $TO." git cherry-pick $SGOCOMMIT echo "Fix conflcits, then squash everything, then ????, then profit!"
xt_main -f examples/default_cases/muzero_breakout.yaml
<gh_stars>1-10 #!/usr/bin/env python # Copyright 2014 IIJ Innovation Institute 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: # * 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 IIJ INNOVATION INSTITUTE 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 IIJ INNOVATION INSTITUTE 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. # Copyright 2014 <NAME>. 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 AUTHOR ``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 AUTHOR 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. '''A Python class to access TSL2561 based light-to-digital convertor provided by Switch-Science as a part no. SFE-SEN-12055. The smbus module is required. Example: import smbus import tsl2561 bus = smbus.SMBus(1) sensor = tsl2561.Tsl2561(bus) print sensor.lux ''' import sensorbase import time # Default I2C address _DEFAULT_ADDRESS = 0x39 # Commands _CMD = 0x80 _CMD_CLEAR = 0x40 _CMD_WORD = 0x20 _CMD_BLOCK = 0x10 # Registers _REG_CONTROL = 0x00 _REG_TIMING = 0x01 _REG_ID = 0x0A _REG_BLOCKREAD = 0x0B _REG_DATA0 = 0x0C _REG_DATA1 = 0x0E # Control parameters _POWER_UP = 0x03 _POWER_DOWN = 0x00 # Timing parameters _GAIN_LOW = 0b00000000 _GAIN_HIGH = 0b00010000 _INTEGRATION_START = 0b00001000 _INTEGRATION_STOP = 0b00000000 _INTEGRATE_13 = 0b00000000 _INTEGRATE_101 = 0b00000001 _INTEGRATE_402 = 0b00000010 _INTEGRATE_DEFAULT = _INTEGRATE_402 _INTEGRATE_NA = 0b00000011 class Tsl2561(sensorbase.SensorBase): def __init__(self, bus = None, addr = _DEFAULT_ADDRESS): '''Initializes the sensor with some default values. bus: The SMBus descriptor on which this sensor is attached. addr: The I2C bus address (default is 0x39). ''' assert(bus is not None) assert(addr > 0b000111 and addr < 0b1111000) super(Tsl2561, self).__init__( update_callback = self._update_sensor_data) self._bus = bus self._addr = addr self._gain = _GAIN_LOW self._manual = _INTEGRATION_STOP self._integ = _INTEGRATE_DEFAULT self._channel0 = None self._channel1 = None self._lux = None self._control(_POWER_UP) self._reconfigure() @property def lux(self): ''' Returns a lux value. Returns None if no valid value is set yet. ''' self._update() return (self._lux) def _update_sensor_data(self, **kwargs): cmd = _CMD | _CMD_WORD | _REG_DATA0 vals = self._bus.read_i2c_block_data(self._addr, cmd, 2) self._channel0 = vals[1] << 8 | vals[0] cmd = _CMD | _CMD_WORD | _REG_DATA1 vals = self._bus.read_i2c_block_data(self._addr, cmd, 2) self._channel1 = vals[1] << 8 | vals[0] # If either sensor is satulated, no acculate lux value # can be achieved. if (self._channel0 == 0xffff or self._channel1 == 0xffff): lux = None return # The following lux value calculation code is taken from # the SparkFun's example code. # # https://github.com/sparkfun/ # TSL2561_Luminosity_Sensor_BOB/blob/master/ # Libraries/SFE_TSL2561/SFE_TSL2561.cpp d0 = float(self._channel0) d1 = float(self._channel1) if (d0 == 0): # Sometimes, the channel0 returns 0 when dark... lux = 0.0 return ratio = d1 / d0 integ_scale = 1 if (self._integ == _INTEGRATE_13): integ_scale = 402.0 / 13.7 elif (self._integ == _INTEGRATE_101): integ_scale = 402.0 / 101.0 elif (self._integ == _INTEGRATE_NA): integ_scale = 402.0 / kwargs['integration_time'] d0 = d0 * integ_scale d1 = d1 * integ_scale if (self._gain == _GAIN_HIGH): d0 = d0 / 16 d1 = d1 / 16 if (ratio < 0.5): self._lux = 0.0304 * d0 - 0.062 * d0 * (ratio ** 1.4) elif (ratio < 0.61): self._lux = 0.0224 * d0 - 0.031 * d1 elif (ratio < 0.80): self._lux = 0.0128 * d0 - 0.0153 * d1 elif (ratio < 1.30): self._lux = 0.00146 * d0 - 0.00112 * d1 else: self._lux = 0.0 return def _control(self, params): cmd = _CMD | _REG_CONTROL self._bus.write_byte_data(self._addr, cmd, params) # Wait for 400ms to be power up. time.sleep(0.4) def _reconfigure(self): cmd = _CMD | _REG_TIMING timing = (self._gain | self._manual | self._integ) self._bus.write_byte_data(self._addr, cmd, timing) # Wait for 400ms to complete initial A/D conversion. time.sleep(0.4) if __name__ == '__main__': import smbus bus = smbus.SMBus(1) sensor = Tsl2561(bus) for cache in [0, 5]: print '**********' print 'Cache lifetime is %d' % cache sensor.cache_lifetime = cache for c in range(10): print sensor.lux
<reponame>vollmerr/state-template-starter<filename>src/components/App/routes.js import Home from '../Home'; import Help from '../Help'; import Form from '../Form'; // order here determines order in navigation menu export const routesByKey = { home: { key: 'home', name: 'Home', path: '/', exact: true, icon: 'ca-gov-icon-home', component: Home, }, form: { key: 'form', name: 'Form', path: '/form', exact: true, icon: 'ca-gov-icon-pencil-edit', component: Form, }, help: { key: 'help', name: 'Help', path: '/help', exact: true, icon: 'ca-gov-icon-question-line', component: Help, }, }; export default Object.values(routesByKey);
TERMUX_PKG_HOMEPAGE=http://premake.github.io/ TERMUX_PKG_DESCRIPTION="Build script generator" TERMUX_PKG_VERSION=4.4-beta5 TERMUX_PKG_SRCURL=http://downloads.sourceforge.net/project/premake/Premake/4.4/premake-${TERMUX_PKG_VERSION}-src.zip # TERMUX_PKG_DEPENDS="pcre, openssl, libuuid" # TERMUX_PKG_EXTRA_CONFIGURE_ARGS="--with-ssl=openssl" termux_step_pre_configure() { TERMUX_PKG_BUILDDIR=$TERMUX_PKG_SRCDIR/build/gmake.unix }
#!/bin/sh echo "Setting up your Mac..." # Check for Homebrew and install if we don't have it if test ! $(which brew); then /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" fi # Update Homebrew recipes brew update # Install all our dependencies with bundle (See Brewfile) brew tap homebrew/bundle brew bundle # Make ZSH the default shell environment chsh -s $(which zsh) # Install global Composer packages /usr/local/bin/composer global require hirak/prestissimo laravel/installer laravel/valet # Install Laravel Valet $HOME/.composer/vendor/bin/valet install # Create a Sites directory # This is a default directory for macOS user accounts but doesn't comes pre-installed mkdir $HOME/Sites # Removes .zshrc from $HOME (if it exists) and symlinks the .zshrc file from the .dotfiles rm -rf $HOME/.zshrc ln -s $HOME/.dotfiles/.zshrc $HOME/.zshrc # Symlink the Mackup config file to the home directory ln -s $HOME/.dotfiles/.mackup.cfg $HOME/.mackup.cfg # Set macOS preferences # We will run this last because this will reload the shell source .macos
#!/usr/bin/env bash mkdir -p certs docker pull docker.pkg.github.com/eventstore/es-gencert-cli/es-gencert-cli:1.0.1 docker run --rm --volume $PWD/certs:/tmp --user $(id -u):$(id -g) docker.pkg.github.com/eventstore/es-gencert-cli/es-gencert-cli:1.0.1 create-ca -out /tmp/ca docker run --rm --volume $PWD/certs:/tmp --user $(id -u):$(id -g) docker.pkg.github.com/eventstore/es-gencert-cli/es-gencert-cli:1.0.1 create-node -ca-certificate /tmp/ca/ca.crt -ca-key /tmp/ca/ca.key -out /tmp/node -ip-addresses 127.0.0.1 chmod 0755 -R ./certs
import AppScreen from './AppScreen'; import {locatorStrategy} from '../helpers/utils'; class BiometricsScreen extends AppScreen { constructor() { super(locatorStrategy('biometrics screen')); } private get biometricsSwitch() { return $(locatorStrategy('biometrics switch')); } async enableBiometrics() { const switchValue = await this.biometricsSwitch.getText(); const isDisabled = switchValue === (driver.isIOS ? '0' : 'OFF'); if (isDisabled) { await this.biometricsSwitch.click(); } } } export default new BiometricsScreen();
import {useDispatch} from "react-redux" import React from "react" import ErrorFactory from "../models/ErrorFactory" import Link from "./common/Link" import LoadFilesInput from "ppl/import/LoadFilesInput" import Notice from "../state/Notice" import errors from "../errors" import ingestFiles from "../flows/ingestFiles" import refreshSpaceNames from "../flows/refreshSpaceNames" import {AppDispatch} from "../state/types" import {popNotice} from "./PopNotice" export default function TabImport() { const dispatch = useDispatch<AppDispatch>() function onChange(_e, files) { if (!files.length) return dispatch(ingestFiles(files)) .then(() => { popNotice("Import complete.") }) .catch((e) => { const regex = /(Failed to fetch)|(network error)/ regex.test(e.cause.message) ? dispatch(Notice.set(errors.importInterrupt())) : dispatch(Notice.set(ErrorFactory.create(e.cause))) dispatch(refreshSpaceNames()) console.error(e.message) }) } return ( <div className="input-methods"> <section> <h2>Import Files</h2> <LoadFilesInput onChange={onChange} /> <footer> <p> <b>Accepted formats:</b> .pcap, .pcapng,{" "} <Link href="https://github.com/brimsec/zq/blob/master/zng/docs/spec.md"> .zng </Link> , and{" "} <Link href="https://docs.zeek.org/en/current/scripts/base/frameworks/logging/writers/ascii.zeek.html"> Zeek ASCII/JSON </Link> . </p> <p> <b>Note:</b> Multiple zng and Zeek log files may be imported, but only one pcap. </p> </footer> </section> </div> ) }
<filename>scripts/services/reddit.txt.js /**   deps: ['https://cdn.jsdelivr.net/npm/arquero@latest', 'https://cdn.jsdelivr.net/npm/hal9-utils@latest/dist/hal9-utils.min.js'] cache: true params: - name: type label: Type value: - control: select value: submissions values: - name: submissions label: Submissions - name: comments label: Comments - name: sub label: Subreddit value: - control: 'textbox' value: wallstreetbets - name: query label: Query value: - control: 'textbox' value: GME - name: before label: Before value: - control: 'textbox' value: 1 Jan 2021 - name: after label: After value: - control: 'textbox' value: 1 Jan 2020 **/ aft = new Date(after).getTime() / 1000; bfr = new Date(before).getTime() / 1000; const baseUrl = 'https://api.pushshift.io/'; if (type == 'submissions') {   endPoint = '/reddit/search/submission/'; } else {   endPoint = '/reddit/search/comment/'; } url = baseUrl + endPoint + '?q=' + query +'&size=1000&fields=author,created_utc,full_link,selftext,body,title,num_comments,score&sort=asc'; if (sub) {   url = url+ '&subreddit=' + sub; } if (bfr) {   url = url + '&before='+bfr; } if (aft) {   url = url + '&after='+aft; } const res = await fetch(url); data = await res.json(); data = data.data; data = await hal9.utils.toArquero(data); time_arr = data.array('created_utc') last_entry = time_arr[time_arr.length - 1] while (last_entry < before) {      aft = last_entry - 1;     bfr = bfr;     if (type == 'submissions') {       endPoint = '/reddit/search/submission/';     } else {       endPoint = '/reddit/search/comment/';     }       url = baseUrl + endPoint + '?q=' + query +'&size=500&fields=author,created_utc,full_link,selftext,body,title,num_comments,score&sort=asc';     if (sub) {    url = url+ '&subreddit=' + sub; }     if (bfr) {       url = url + '&before='+bfr;     }     if (aft) {         url = url + '&after='+aft;     }   const res = await fetch(url);   newData = await res.json();   newData = newData.data; console.log(data.size)   newData = await hal9.utils.toArquero(newData);     data = data.concat(newData); console.log(data.size)   time_arr = data.array('created_utc');   last_entry = time_arr[time_arr.length - 1];   if (newData.size <100){ break; }   await new Promise(r => setTimeout(r, 1000)); } data = data.dedupe();
#! /usr/bin/env sh DIR=$(dirname "$0") cd "$DIR" . ../scripts/functions.sh SOURCE="$(realpath -m .)" DESTINATION="$(realpath -m ~)" info "Configuring git..." find . -name ".git*" | while read fn; do fn=$(basename $fn) symlink "$SOURCE/$fn" "$DESTINATION/$fn" done success "Finished configuring git."
<reponame>aloygupta/DsAlgoImpl package list.implementation; import list.List; public class LinkedListWithTail<T> implements List<T> { private class Node{ public T value; public Node next; public Node(T value, Node next) { this.value = value; this.next = next; } } private Node head; private Node tail; private int size; public LinkedListWithTail() { this.head = null; this.tail = null; this.size = 0; } @Override public int size() { return size; } @Override public boolean empty() { return (size == 0); } @Override public T valueAt(int index) { if(index < 0 || index >= size ) throw new IndexOutOfBoundsException("Can not fetch "+index+"th index value from start"); if(index == (size-1)) return tail.value; Node currentNode = head; for(int i=0 ;i<index;i++) { currentNode = currentNode.next; } return currentNode.value; } @Override public void pushFront(T value) { Node newFrontNode; if(head == null) { // empty linked list newFrontNode = new Node(value, null); tail = newFrontNode; } else { // at least one node is there, no need to change tail newFrontNode = new Node(value, head); } //point head to newFrontNode; head = newFrontNode; ++size; } @Override public T popFront()throws Exception { if(head == null) throw new Exception("Empty Linked List"); Node headNode = head; //redirect head to next node if(head.next == null) { // only 1 node, so tail has to be made null tail = null; } // no need to modify tail head = head.next; //isolate the node, not really required though. //headNode should get GC when this function finishes. headNode.next = null; --size; return headNode.value; } @Override public void pushBack(T value) { Node newlastNode = new Node(value, null); if(head == null) { //empty linked list head = tail = newlastNode; } else { // go to the last node /*Node currentNode = head; while(currentNode.next != null) { currentNode = currentNode.next; } currentNode.next = newlastNode; */ tail.next = newlastNode; tail = newlastNode; } ++size; } @Override public T popBack() throws Exception { if(head == null) throw new Exception("Empty Linked List"); if(head.next == null) { //only 1 item in list T valueOfHead = head.value; //make head and tail null, GC will collect it head = tail = null; --size; return valueOfHead; } else { Node currentNode = head; while(currentNode.next.next != null) { currentNode = currentNode.next; } //currentNode now points to 2nd last node T lastNodeValue = currentNode.next.value; tail = currentNode; //make 2nd last node point to null, thus allowing GC to collect last node currentNode.next = null; --size; return lastNodeValue; } } @Override public T front()throws Exception { if(head == null) throw new Exception("Empty Linked List"); return head.value; } @Override public T back() throws Exception { if(head == null) throw new Exception("Empty Linked List"); else { /*Node current = head; while(current.next != null) { current = current.next; } return current.value;*/ return tail.value; } } @Override public void insert(int index, T value) { if(index < 0 || index >= size) throw new IndexOutOfBoundsException("Can not insert at index: "+index); if(index == 0) { pushFront(value); } else { Node current = head; //navigate to just before the index for(int i = 1; i<index; i++) { current = current.next; } Node insertedNode = new Node(value, current.next); current.next = insertedNode; ++size; } } @Override public void erase(int index) throws Exception { if(index < 0 || index >= size) throw new IndexOutOfBoundsException("Can not erase at index: "+index); if(index == 0) { popFront(); } else { Node current = head; for(int i = 1; i<index; i++) { current = current.next; } //point pre-target node's next pointer to post-target node current.next = current.next.next; if(index == (size-1)) { // last node has been removed, so modify tail to point to current, whose next is null tail = current; } --size; } } @Override public T valueNFromEnd(int n) { if(n < 0 || n >= size ) throw new IndexOutOfBoundsException("Can not fetch value at "+n+"th index from end"); if(n == 0) return tail.value; if(n == (size -1)) return head.value; int nFromFront = size -1 -n; Node current = head; for(int i= 0; i < nFromFront; i++) { current = current.next; } return current.value; } @Override public void reverse() throws Exception { if(head == null) throw new Exception("Empty Linked List"); if(head.next == null) // only 1 node in list return; Node previousNode = null; Node currentNode = head; Node nextNode = currentNode.next; while(currentNode != null) { currentNode.next = previousNode; previousNode = currentNode; currentNode = nextNode; // at one point currentNode will reach null, signifying end of list prevent NPE of nextNode if(currentNode != null) nextNode = currentNode.next; } //previously what was head node, is now tail this.tail = this.head; //since currentNode is now null after exit from while loop, previousNode is the head of the reversed list this.head = previousNode; } @Override public void removeValue(T value) throws Exception { if(head == null) throw new Exception("Empty Linked List"); boolean nodeFound = false; Node previousNode = null; Node currentNode = head; while(currentNode != null) { if(currentNode.value.equals(value)) { if(previousNode == null) { //firstNode is matched head = head.next; if(head == null) // only one node was there, that too has been removed tail = null; } else { if(currentNode.next == null) { // check whether currentNode is last node, if yes, have to update tail pointer tail = previousNode; } previousNode.next = currentNode.next; currentNode.next = null; currentNode = null; } nodeFound = true; --size; break; } previousNode = currentNode; currentNode = currentNode.next; } if(nodeFound == false) throw new Exception("Node with value "+value+" not present"); } @Override public String toString() { String desc = "["; if(size != 0) { desc = "[ "+head.value; } Node currentNode = head; for(int i=1;i<size;i++) { desc= desc +" , "+currentNode.next.value; currentNode = currentNode.next; } desc += " ]"; //desc += " Head: "+head.value+" , Tail: "+tail.value; return desc; } }
<filename>conn.go package nfs import ( "bufio" "bytes" "context" "encoding/binary" "errors" "fmt" "io" "io/ioutil" "log" "net" xdr2 "github.com/rasky/go-xdr/xdr2" "github.com/willscott/go-nfs-client/nfs/rpc" "github.com/willscott/go-nfs-client/nfs/xdr" ) var ( // ErrInputInvalid is returned when input cannot be parsed ErrInputInvalid = errors.New("invalid input") // ErrAlreadySent is returned when writing a header/status multiple times ErrAlreadySent = errors.New("response already started") ) // ResponseCode is a combination of accept_stat and reject_stat. type ResponseCode uint32 // ResponseCode Codes const ( ResponseCodeSuccess ResponseCode = iota ResponseCodeProgUnavailable ResponseCodeProcUnavailable ResponseCodeGarbageArgs ResponseCodeSystemErr ResponseCodeRPCMismatch ResponseCodeAuthError ) type conn struct { *Server writeSerializer chan []byte net.Conn } func (c *conn) serve(ctx context.Context) { connCtx, cancel := context.WithCancel(ctx) defer cancel() c.writeSerializer = make(chan []byte, 1) go c.serializeWrites(connCtx) bio := bufio.NewReader(c.Conn) for { w, err := c.readRequestHeader(connCtx, bio) if err != nil { if err == io.EOF { // Clean close. c.Close() return } return } //log.Printf("request: %v", w.req) err = c.handle(connCtx, w) respErr := w.finish(connCtx) if err != nil { log.Printf("error handling req: %v", err) // failure to handle at a level needing to close the connection. c.Close() return } if respErr != nil { log.Printf("error sending response: %v", respErr) c.Close() return } } } func (c *conn) serializeWrites(ctx context.Context) { // todo: maybe don't need the extra buffer writer := bufio.NewWriter(c.Conn) var fragmentBuf [4]byte var fragmentInt uint32 for { select { case <-ctx.Done(): return case msg, ok := <-c.writeSerializer: if !ok { return } // prepend the fragmentation header fragmentInt = uint32(len(msg)) fragmentInt |= (1 << 31) binary.BigEndian.PutUint32(fragmentBuf[:], fragmentInt) n, err := writer.Write(fragmentBuf[:]) if n < 4 || err != nil { return } n, err = writer.Write(msg) if err != nil { return } if n < len(msg) { panic("todo: ensure writes complete fully.") } if err = writer.Flush(); err != nil { return } } } } // Handle a request. errors from this method indicate a failure to read or // write on the network stream, and trigger a disconnection of the connection. func (c *conn) handle(ctx context.Context, w *response) error { handler := c.Server.handlerFor(w.req.Header.Prog, w.req.Header.Proc) if handler == nil { log.Printf("No handler for %d.%d", w.req.Header.Prog, w.req.Header.Proc) if err := w.drain(ctx); err != nil { return err } return c.err(ctx, w, &ResponseCodeProcUnavailableError{}) } appError := handler(ctx, w, c.Server.Handler) if drainErr := w.drain(ctx); drainErr != nil { return drainErr } if appError != nil && !w.responded { log.Printf("call to %+v failed: %v", handler, appError) if err := c.err(ctx, w, appError); err != nil { return err } } if !w.responded { log.Printf("Handler did not indicate response status via writing or erroring") if err := c.err(ctx, w, &ResponseCodeSystemError{}); err != nil { return err } } return nil } func (c *conn) err(ctx context.Context, w *response, err error) error { select { case <-ctx.Done(): return nil default: } if w.err == nil { w.err = err } if w.responded { return nil } rpcErr := w.errorFmt(err) if writeErr := w.writeHeader(rpcErr.Code()); writeErr != nil { return writeErr } body, _ := rpcErr.MarshalBinary() return w.Write(body) } type request struct { xid uint32 rpc.Header Body io.Reader } func (r *request) String() string { if r.Header.Prog == nfsServiceID { return fmt.Sprintf("RPC #%d (nfs.%s)", r.xid, NFSProcedure(r.Header.Proc)) } else if r.Header.Prog == mountServiceID { return fmt.Sprintf("RPC #%d (mount.%s)", r.xid, MountProcedure(r.Header.Proc)) } return fmt.Sprintf("RPC #%d (%d.%d)", r.xid, r.Header.Prog, r.Header.Proc) } type response struct { *conn writer *bytes.Buffer responded bool err error errorFmt func(error) RPCError req *request } func (w *response) writeXdrHeader() error { err := xdr.Write(w.writer, &w.req.xid) if err != nil { return err } respType := uint32(1) err = xdr.Write(w.writer, &respType) if err != nil { return err } return nil } func (w *response) writeHeader(code ResponseCode) error { if w.responded { return ErrAlreadySent } w.responded = true if err := w.writeXdrHeader(); err != nil { return err } status := rpc.MsgAccepted if code == ResponseCodeAuthError || code == ResponseCodeRPCMismatch { status = rpc.MsgDenied } err := xdr.Write(w.writer, &status) if err != nil { return err } if status == rpc.MsgAccepted { // Write opaque_auth header. err = xdr.Write(w.writer, &rpc.AuthNull) if err != nil { return err } } return xdr.Write(w.writer, &code) } // Write a response to an xdr message func (w *response) Write(dat []byte) error { if !w.responded { if err := w.writeHeader(ResponseCodeSuccess); err != nil { return err } } acc := 0 for acc < len(dat) { n, err := w.writer.Write(dat[acc:]) if err != nil { return err } acc += n } return nil } // drain reads the rest of the request frame if not consumed by the handler. func (w *response) drain(ctx context.Context) error { if reader, ok := w.req.Body.(*io.LimitedReader); ok { if reader.N == 0 { return nil } // todo: wrap body in a context reader. _, err := io.CopyN(ioutil.Discard, w.req.Body, reader.N) if err == nil || err == io.EOF { return nil } return err } return io.ErrUnexpectedEOF } func (w *response) finish(ctx context.Context) error { select { case w.conn.writeSerializer <- w.writer.Bytes(): return nil case <-ctx.Done(): return ctx.Err() } } func (c *conn) readRequestHeader(ctx context.Context, reader *bufio.Reader) (w *response, err error) { fragment, err := xdr.ReadUint32(reader) if err != nil { if xdrErr, ok := err.(*xdr2.UnmarshalError); ok { if xdrErr.Err == io.EOF { return nil, io.EOF } } return nil, err } if fragment&(1<<31) == 0 { log.Printf("Warning: haven't implemented fragment reconstruction.\n") return nil, ErrInputInvalid } reqLen := fragment - uint32(1<<31) if reqLen < 40 { return nil, ErrInputInvalid } r := io.LimitedReader{R: reader, N: int64(reqLen)} xid, err := xdr.ReadUint32(&r) if err != nil { return nil, err } reqType, err := xdr.ReadUint32(&r) if err != nil { return nil, err } if reqType != 0 { // 0 = request, 1 = response return nil, ErrInputInvalid } req := request{ xid, rpc.Header{}, &r, } if err = xdr.Read(&r, &req.Header); err != nil { return nil, err } w = &response{ conn: c, req: &req, errorFmt: basicErrorFormatter, // TODO: use a pool for these. writer: bytes.NewBuffer([]byte{}), } return w, nil }
#include "Camera.h" #include <cstdlib> Vec3 random_in_unit_disk() { float x, y; do { x = 2 * drand48() - 1; y = 2 * drand48() - 1; } while (x * x + y * y > 1); return Vec3(x, y, 0); } Camera::Camera(Vec3 from, Vec3 at, Vec3 up, float fov, float aspect, float aperture) { Vec3 view = from - at; lens_radius = aperture / 2; origin = from; float theta = fov * M_PI / 180; // radians float height = 2 * tan(theta / 2); float width = aspect * height; float focus = view.length(); w = unit_vector(view); u = unit_vector(cross(up, w)); v = cross(w, u); // cross 2 unit vectors is a unit vector lower_left_corner = origin - (width / 2) * focus * u - (height / 2) * focus * v - focus * w; horizontal = width * focus * u; vertical = height * focus * v; } Ray Camera::get_ray(float s, float t) { Vec3 rd = lens_radius * random_in_unit_disk(); Vec3 offset_origin = origin + u * rd.x + v * rd.y; return Ray(offset_origin, lower_left_corner + s * horizontal + t * vertical - offset_origin); }
# remote compute worker export WORKER=takos export SYNC_ROOT=~/jobs ## create and download backup bkup() { local SHOST=root@$WORKER ssh $SHOST -- bkup/bkup scp $SHOST:backup.tar.gz.age . ssh $SHOST -- rm backup.tar.gz.age } alias sak="ssh-add -K" # tmux alias sls="tmux ls" ## prefer attach if exists s() { local list=$(tmux ls) if [[ "$list" =~ "no server" || -z "$list" ]]; then tmux new -s0 else tmux attach -t $(echo $list | peco --select-1 | awk -F: '{printf $1}') fi } ## force new session sn() { local sessName=${1:-$(basename $PWD)} tmux new -As $sessName } sp() { ssh ${1:-$WORKER} } mp() { mosh ${1:-$WORKER} -- tmux new -As0 } forward() { ssh -L ${1}:localhost:${1} -N ${2} } alias forward-vnc="forward 5900" alias forward-jupyter="forward 18888" sk() { echo 🚀 Syncing to $WORKER #rsync -C --filter=":- .gitignore" --exclude=".git*" -avz . "${WORKER}:${SYNC_ROOT}/$(basename $PWD)" rsync -C --exclude=".git*" -avz . "${WORKER}:${SYNC_ROOT}/$(basename $PWD)" } receive() { rsync -C --exclude=".git*" -avz "${WORKER}:${SYNC_ROOT}/$(basename $PWD)/$1" "./$1" echo "📞 Receiving \"$1\" on $WORKER" } run() { ssh -t $WORKER "cd \"${SYNC_ROOT}/$(basename $PWD)\"; zsh -ic \"$@\"" 2>/dev/null echo "🏃 Running \"$@\" on $WORKER" } skrun() { sk && echo '' && run $@ } dive() { ssh -t $WORKER "cd \"${SYNC_ROOT}/$(basename $PWD)\"; zsh" echo "🎯 Dive into ${SYNC_ROOT}/$(basename "$PWD") on $WORKER" } sshrun() { local param=("${(@s/:/)1}") local server=$param[1] local baseDir=${param[2]:-.} local commands=${@:2} ssh -t $server "cd \"${baseDir}\"; zsh -ic \"${commands}\"" 2>/dev/null }
<gh_stars>1-10 import {extend} from "flarum/extend"; import app from "flarum/app"; import PermissionGrid from "flarum/components/PermissionGrid"; import addUploadPane from "./addUploadPane"; app.initializers.add('flagrow-upload', app => { // add the admin pane addUploadPane(); // add the permission option to the relative pane extend(PermissionGrid.prototype, 'startItems', items => { items.add('upload', { icon: 'far fa-file', label: app.translator.trans('flagrow-upload.admin.permissions.upload_label'), permission: 'flagrow.upload' }); }); // add the permission option to the relative pane extend(PermissionGrid.prototype, 'viewItems', items => { items.add('download', { icon: 'fas fa-download', label: app.translator.trans('flagrow-upload.admin.permissions.download_label'), permission: 'flagrow.upload.download', allowGuest: true }); }); });
#!/bin/bash set -eu define(){ eval ${1:?}=\"\${*\:2}\"; } array (){ eval ${1:?}=\(\"\${@\:2}\"\); } function init_brew(){ echo ' ################# # brew install # ################# ' echo "## Install Xcode (Depend) Testing" echo "! Please Include Xcode packs select !" echo "! And Xcode boot up + Additional pack Install !" xcode-select --install || true echo "sleeping... Please push any key" read aksjfiefe sudo xcodebuild -license accept echo "## install brew basesystem" /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" echo "" echo "## Install brew extra" echo "" brew tap caskroom/cask brew install argon/mas/mas #brew install rcmdnk/file/brew-file } function install_brewpacks(){ # brew list init array brewlist # cask list init array casklist #AquaSKK array casklist+ aquaskk #Screen brew tap rcmdnk/rcmdnkpac array brewlist+ screenutf8 #google array casklist+ google-backup-and-sync array casklist+ google-chrome #slack array casklist+ slack #vm array casklist+ docker array casklist+ virtualbox #entertain array casklist+ gimp #depend brew cask install xquartz array casklist+ inkscape array casklist+ blender #report #array casklist+ skim array casklist+ libreoffice #sshfs array casklist+ osxfuse array brewlist+ sshfs #istat_menus #array casklist+ istat-menus #ranger(file manager) array brewlist+ ranger #dropbox array casklist+ dropbox #Install brew update brew install macvim --with-override-system-vim brew install ${brewlist[*]} brew cask install ${casklist[*]} } function install_maspacks(){ #appstore-files # BoxySVG #mas install 611658502 # OneDrive mas install 823766827 # Xcode #mas install 497799835 } function install_go(){ mkdir ~/go brew install go #echo "export GOPATH=~/env/go" >> ~/.bashrc #echo "export PATH=$PATH:/$GOPATH/bin" >> ~/.bashrc } function install_pips(){ sudo easy_install pip #sudo pip install tensorflow # or gpu # pip install tensorflow-gpu pip install virtualenv pip install pyenv } function install_texlive(){ # Heavy Package brew cask install mactex brew install pandoc # additional # https://snap.textfile.org/20151006085255/ } function backup_maspacks(){ mas list > brew_appstore-`date '+%Y%m%d'` } function do_yourself(){ echo' before: Download this files Install Xcode After: Open Google/One Drive Set GOPATH/PATH for go Terminal Setting Google Chrome setting Docker startup+Docker mem&cpu setting change reboot for complete to aquqskk init sudo tlmgr update --self --all change setting : skim : autoreload(kannkou settei) 透明度の設定/バーを黒くする設定 ' } if [ "$1" = "init" ] then init_brew install_maspacks install_brewpacks install_texlive # !testing #install_go #install_pips echo ' ################ # Init OK # ################ ' exit fi if [ "$1" = "restart" ] then install_brewpacks install_texlive # !testing #install_go #install_pips echo ' ################ # Init OK # ################ ' exit fi
#!/bin/bash set -euox pipefail export GOPATH="$(pwd)/go" export PATH="$PATH:$GOPATH/bin" go get -u golang.org/x/mobile/cmd/gomobile || true go get golang.org/x/tools/go/packages || true go install golang.org/x/mobile/cmd/gobind go get golang.org/x/mobile || true go get -u github.com/ProtonMail/gopenpgp || true PACKAGE_PATH="github.com/ProtonMail/gopenpgp" GOPENPGP_REVISION="136c0a54956e0241ff1b0c31aa34f2042588f843" ( cd "$GOPATH/src/$PACKAGE_PATH" && git checkout "$GOPENPGP_REVISION" && GO111MODULE=on go mod vendor ) patch -p0 < $GOPATH/crypto.patch OUTPUT_PATH="$GOPATH/dist" mkdir -p "$OUTPUT_PATH" chmod -R u+w "$GOPATH/pkg/mod" "$GOPATH/bin/gomobile" bind -v -ldflags="-s -w" -target ios -o "${OUTPUT_PATH}/Crypto.framework" \ "$PACKAGE_PATH"/{crypto,armor,constants,models,subtle}
<gh_stars>0 /* * 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 brooklyn.location.geo; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.Test; import com.google.common.collect.Sets; public class LocalhostExternalIpLoaderIntegrationTest { private static final Logger LOG = LoggerFactory.getLogger(LocalhostExternalIpLoaderIntegrationTest.class); @Test(groups = "Integration") public void testHostsAgreeOnExternalIp() { Set<String> ips = Sets.newHashSet(); for (String url : LocalhostExternalIpLoader.getIpAddressWebsites()) { String ip = LocalhostExternalIpLoader.getIpAddressFrom(url); LOG.debug("IP from {}: {}", url, ip); ips.add(ip); } assertEquals(ips.size(), 1, "Expected all IP suppliers to agree on the external IP address of Brooklyn. " + "Check logs for source responses. ips=" + ips); } @Test(groups = "Integration") public void testLoadExternalIp() { assertNotNull(LocalhostExternalIpLoader.getLocalhostIpWaiting()); } }
<reponame>bxyoung89/xorberax-visualizer<gh_stars>1-10 import mintyScale from './scales/minty-scale.js'; import mintyGradient from './helpers/minty-gradient.js'; import makeFragShaderFromGradient from './helpers/make-frag-shader-from-gradient.js'; import makeBackgroundShaderFromGradient from './helpers/make-background-shader-from-gradient.js'; export default { name: 'Minty', luminosityFunction: (luminosity) => { return mintyScale(luminosity); }, shader: makeFragShaderFromGradient('mintyGradient', mintyGradient), backgroundShader: makeBackgroundShaderFromGradient('mintyGradient', mintyGradient), };
/////////////////////////////////////////////////////////////////////////////// // Name: src/gtk/mnemonics.cpp // Purpose: implementation of GTK mnemonics conversion functions // Author: <NAME> // Created: 2007-11-12 // Copyright: (c) 2007 <NAME> <<EMAIL>> // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // for compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #include "wx/log.h" #include "wx/gtk1/private/mnemonics.h" namespace { // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- // Names of the standard XML entities. const char *const entitiesNames[] = { "&amp;", "&lt;", "&gt;", "&apos;", "&quot;" }; } // anonymous namespace // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // internal helper: apply the operation indicated by flag // ---------------------------------------------------------------------------- enum MnemonicsFlag { MNEMONICS_REMOVE, MNEMONICS_CONVERT, MNEMONICS_CONVERT_MARKUP }; static wxString GTKProcessMnemonics(const wxString& label, MnemonicsFlag flag) { wxString labelGTK; labelGTK.reserve(label.length()); for ( wxString::const_iterator i = label.begin(); i != label.end(); ++i ) { wxChar ch = *i; switch ( ch ) { case wxT('&'): if ( i + 1 == label.end() ) { // "&" at the end of string is an error wxLogDebug(wxT("Invalid label \"%s\"."), label); break; } if ( flag == MNEMONICS_CONVERT_MARKUP ) { bool isMnemonic = true; size_t distanceFromEnd = label.end() - i; // is this ampersand introducing a mnemonic or rather an entity? for (size_t j=0; j < WXSIZEOF(entitiesNames); j++) { const char *entity = entitiesNames[j]; size_t entityLen = wxStrlen(entity); if (distanceFromEnd >= entityLen && wxString(i, i + entityLen) == entity) { labelGTK << entity; i += entityLen - 1; // the -1 is because main for() // loop already increments i isMnemonic = false; break; } } if (!isMnemonic) continue; } ch = *(++i); // skip '&' itself switch ( ch ) { case wxT('&'): // special case: "&&" is not a mnemonic at all but just // an escaped "&" if ( flag == MNEMONICS_CONVERT_MARKUP ) labelGTK += wxT("&amp;"); else labelGTK += wxT('&'); break; case wxT('_'): if ( flag != MNEMONICS_REMOVE ) { // '_' can't be a GTK mnemonic apparently so // replace it with something similar labelGTK += wxT("_-"); break; } //else: fall through default: if ( flag != MNEMONICS_REMOVE ) labelGTK += wxT('_'); labelGTK += ch; } break; case wxT('_'): if ( flag != MNEMONICS_REMOVE ) { // escape any existing underlines in the string so that // they don't become mnemonics accidentally labelGTK += wxT("__"); break; } //else: fall through default: labelGTK += ch; } } return labelGTK; } // ---------------------------------------------------------------------------- // public functions // ---------------------------------------------------------------------------- wxString wxGTKRemoveMnemonics(const wxString& label) { return GTKProcessMnemonics(label, MNEMONICS_REMOVE); } wxString wxConvertMnemonicsToGTK(const wxString& label) { return GTKProcessMnemonics(label, MNEMONICS_CONVERT); } wxString wxConvertMnemonicsToGTKMarkup(const wxString& label) { return GTKProcessMnemonics(label, MNEMONICS_CONVERT_MARKUP); } wxString wxConvertMnemonicsFromGTK(const wxString& gtkLabel) { wxString label; for ( const wxChar *pc = gtkLabel.c_str(); *pc; pc++ ) { // '_' is the escape character for GTK+. if ( *pc == wxT('_') && *(pc+1) == wxT('_')) { // An underscore was escaped. label += wxT('_'); pc++; } else if ( *pc == wxT('_') ) { // Convert GTK+ hotkey symbol to wxWidgets/Windows standard label += wxT('&'); } else if ( *pc == wxT('&') ) { // Double the ampersand to escape it as far as wxWidgets is concerned label += wxT("&&"); } else { // don't remove ampersands '&' since if we have them in the menu title // it means that they were doubled to indicate "&" instead of accelerator label += *pc; } } return label; }
<gh_stars>1-10 /** * Created by <NAME> on 14.02.2017. */ import {BaseUtils} from '../base/BaseUtils'; import {IValueTypeDesc, ValueTypeUtils} from '../data/valuetype'; import {IAtom, IAtomDataDescription, IAtomValue, IInlinedAtomDataDescription, AtomUtils} from './IAtom'; import {LocalIDAssigner} from '../idtype'; import {AAtom} from './AAtom'; import {Range} from '../range'; const noValue: IAtomValue<any> = { id: -1, name: '', value: null }; export class Atom<T,D extends IValueTypeDesc> extends AAtom<T,D> implements IAtom<T,D> { constructor(desc: IAtomDataDescription<D>, private readonly loaded: IAtomValue<T>) { super(desc); } id() { return Promise.resolve(Range.list(this.loaded.id)); } name() { return Promise.resolve(this.loaded.name); } data() { return Promise.resolve(this.loaded.value); } static create<T, D extends IValueTypeDesc>(desc: IAtomDataDescription<D>|IInlinedAtomDataDescription<T,D>): IAtom<T,D> { if (typeof((<any>desc).data) !== undefined) { return new Atom(desc, <IAtomValue<T>>(<any>desc).data); } return new Atom(desc, noValue); } static asAtom<T>(name: string, value: T, options: IAsAtomOptions = {}) { const desc = BaseUtils.mixin(AtomUtils.createDefaultAtomDesc(), { value: ValueTypeUtils.guessValueTypeDesc([value]) }, options); const rowAssigner = options.rowassigner || LocalIDAssigner.create(); const atom = { name, value, id: rowAssigner([name]).first }; return new Atom(desc, atom); } } export interface IAsAtomOptions { name?: string; idtype?: string; rowassigner?(ids: string[]): Range; }
# Assign the value of x x <- 10 # Calculate Y Y <- (4 * x - 8 / 2 * x + 3)^2 # Print the Output print(Y) # output 143.0
#!/bin/bash username=${ESP_USERNAME:-"please"} password=${ESP_PASSWORD:-"installme!"} hostname=${ESP_HOSTNAME:-192.168.4.1} function doUpload() { target=$1 file=$2 curl --digest --user ${username}:${password} \ -o /dev/null -F "file=@${file}" \ "http://${hostname}/upload/${target}" } function doFlash() { curl --digest --user ${username}:${password} \ "http://${hostname}/flash/${target}" && echo "OK" || echo "Error" }