Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add completely untested multitasking code
taskswapHandler : pop ecx ; pop eip into ecx pusha mov ebx, [currentTaskNum] ; get the current task imul ebx, TASK_OBJ_SIZE add ebx, RunningTaskList mov [ebx+Task_eip], ecx mov [ebx+Task_stackLoc], esp ; store the relevent things ; get the next Task object into ebx taskswapHandler.goLoop : add ebx, TASK_OBJ_SIZE cmp ebx, RunningTaskListEnd jge taskswapHandler.doneZeroing mov ebx, RunningTaskList taskswapHandler.doneZeroing : cmp dword [ebx+Task_id], 0 je taskswapHandler.goLoop taskswapHandler.noloopback : mov esp, [ebx+Task_stackLoc] popa push dword [ebx+Task_eip] iret currentTaskNum : dd 0x0 RunningTaskList : times 32*TASK_OBJ_SIZE db 0x0 ; 32 tasks max atm RunningTaskListEnd : Task_id equ 0x0 Task_stackLoc equ 0x4 Task_eip equ 0x8 TASK_OBJ_SIZE equ 0xC registerTask : ; eip in ecx pusha mov ebx, RunningTaskList registerTask.loop : cmp dword [ebx+Task_id], 0 je registerTask.foundTask add ebx, TASK_OBJ_SIZE jmp registerTask.loop registerTask.foundTask : mov eax, [currentTaskId] mov [ebx+Task_id], eax mov [ebx+Task_eip], ecx add eax, 1 mov [currentTaskId], eax mov edx, ebx sub eax, 1 mov ebx, TASK_STACK_SIZE call Guppy.malloc add ebx, TASK_STACK_SIZE*0x200 mov [edx+Task_stackLoc], ebx popa ret unregisterTask : ; ID in ecx pusha mov ebx, RunningTaskList unregisterTask.loop : cmp dword [ebx+Task_id], ecx je unregisterTask.foundTask unregisterTask.foundTask : xor ecx, ecx mov [ebx+Task_id], ecx popa ret currentTaskId : dd 0x0 TASK_STACK_SIZE equ 2
Add PoR patch to fix bonus STR not affecting martial art
.nds .relativeinclude on .erroronwarning on ; In vanilla PoR Martial Art does not take bonus STR (e.g. from STR Boost) into account when calculating its damage. ; This patch causes it to take bonus STR into account. .open "ftc/overlay9_0", 021CDF60h .org 0x022176CC ldrsh r1, [r4, 18h] ; Load bonus STR from 02111FEC add r0, r0, r1 ; Add base STR (already in r0) to bonus STR mov r0, r0, lsl 1h ; Double the strength value to get the damage martial art should do (same as in vanilla, except in vanilla it used float multiplication instead of shifting) nop nop .close
Return 0 for no items
; Based on http://codekata.com/kata/kata09-back-to-the-checkout/ org 8000h include src/zx-spec.asm spec_init describe 'price' it 'Returns 0 for no items' ld a,$FF call price assert_a_equal 0 spec_end price proc ret endp end 8000h
; Based on http://codekata.com/kata/kata09-back-to-the-checkout/ org 8000h include src/zx-spec.asm spec_init describe 'price' it 'Returns 0 for no items' ld a,$FF call price assert_a_equal 0 spec_end price proc ld a,0 ret endp end 8000h
Add patch to make wygol unlocked from the start in OoE
.nds .relativeinclude on .erroronwarning on .open "ftc/overlay9_22", 02223E00h ; Shanoa mode: Makes Ecclesia and Wygol be unlocked from the start. .org 0x0223B7F4 ; Code that would normally set Ecclesia as the default unlocked area. ldr r14, =021003CCh ldr r0, [r14] mov r1, 0x0000003C ; Sets both bits for Ecclesia and Wygol orr r0, r0, r1 str r0, [r14] b 0223B840h .pool .close
Write to 0x70 instead 46
LLB R1, 70 #Address LHB R1, 0xCC LLB R2, 59 LLB R12, 34 LLB R13, 45 LLB R14, 78 SW R1, R1, 0 SW R12, R1, 1 SW R13, R1, 2 SW R14, R1, 3 LW R3, R1, 0 ADD R4, R2, R2 LW R7, R1, 1 ADD R4, R4, R4 LW R8, R1, 2 ADD R4, R4, R4 LW R9, R1, 3 ADD R4, R4, R4 SW R2, R1, 0 LW R5, R1, 1 LW R6, R1, 3 HLT
LLB R1, 0x70 #Address LHB R1, 0xCC LLB R2, 59 LLB R12, 34 LLB R13, 45 LLB R14, 78 SW R1, R1, 0 SW R12, R1, 1 SW R13, R1, 2 SW R14, R1, 3 LW R3, R1, 0 ADD R4, R2, R2 LW R7, R1, 1 ADD R4, R4, R4 LW R8, R1, 2 ADD R4, R4, R4 LW R9, R1, 3 ADD R4, R4, R4 SW R2, R1, 0 LW R5, R1, 1 LW R6, R1, 3 HLT
Add test for BR 3187743
;Testname=unoptimized; Arguments=-O0 -fbin -obr3187743.bin; Files=stdout stderr br3187743.bin ;Testname=optimized; Arguments=-Ox -fbin -obr3187743.bin; Files=stdout stderr br3187743.bin bits 64 vlddqu xmm0,[edi] vlddqu ymm0,[edi]
Include upper 32-bits of tsc.
; ; Copyright Mehdi Sotoodeh. All rights reserved. ; <mehdisotoodeh@gmail.com> ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that source code retains the ; above copyright notice and following disclaimer. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ; include defines.inc PUBPROC readTSC rdtscp shl rdx,32 xchg eax,edx xchg rdx,rax ret ENDPROC readTSC END
; ; Copyright Mehdi Sotoodeh. All rights reserved. ; <mehdisotoodeh@gmail.com> ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that source code retains the ; above copyright notice and following disclaimer. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ; include defines.inc PUBPROC readTSC rdtscp shl rdx,32 add rax,rdx ret ENDPROC readTSC END
Add patch to prevent overlapping events in first room of DoS
.nds .relativeinclude on .erroronwarning on ; This patch fixes issues that could happen in the first room of the castle if the player got one of the bad endings before seeing the cutscene with Hammer in that first room. ; The cutscene with Hammer would play at the same time as the bad ending cutscene, and could allow skipping the cutscene to get out of the room, escaping from the bad ending. @Overlay41Start equ 0x02308920 @FreeSpace equ @Overlay41Start + 0x1DC .open "ftc/overlay9_0", 0219E3E0h .org 0x021C84DC ; In Object5ECreate (cutscene in the first room of the castle with Hammer) bne @CheckInBadEnding .close .open "ftc/overlay9_41", @Overlay41Start .org @FreeSpace @CheckInBadEnding: ldr r1, =020F7188h ; Bitfield of event flags ldr r1, [r1] ands r1, r1, 24000h ; Check the two bad ending flags beq 0x021C84F4 ; If neither are set, continue on with this event code b 0x021C84E0 ; Otherwise, delete this event .pool .close
Add patch for boss orbs to reload some boss rooms in OoE
.nds .relativeinclude on .erroronwarning on ; This patch makes it so getting a boss orb in Mystery Manor or Ecclesia will reload the room. ; This is because the cutscene after beating Albus/Barlowe won't play until the room is reloaded. ; Albus/Barlowe normally reload the room on defeat, but in boss randomizer something else needs to do it. @Overlay86Start equ 0x022EB1A0 @FreeSpace equ 0x022EB1A0 + 0x48 .open "ftc/arm9.bin", 02000000h .org 0x02061254 ; At the end of the function for the boss orb being picked up b @BossOrbCheckReloadRoom .close .open "ftc/overlay9_86", @Overlay86Start ; Free space overlay .org @FreeSpace @BossOrbCheckReloadRoom: ldr r0, =02100790h ldrb r0, [r0] ; Read the current game mode cmp r0, 0h ; Shanoa mode bne @BossOrbCheckReloadRoomEnd ldr r0, =020FFCB9h ldrb r0, [r0] ; Read the current area index cmp r0, 0Eh ; Mystery Manor beq @BossOrbReloadRoomMysteryManor cmp r0, 2h ; Ecclesia bne @BossOrbCheckReloadRoomEnd @BossOrbReloadRoomEcclesia: mov r0, 2h ; Area, Ecclesia mov r1, 0h ; Sector mov r2, 6h ; Room b @BossOrbReloadRoom @BossOrbReloadRoomMysteryManor: mov r0, 0Eh ; Area, Mystery Manor mov r1, 0h ; Sector mov r2, 9h ; Room @BossOrbReloadRoom: mov r3, 0C0h ; X pos mov r4, 0B0h ; Y pos str r3, [r13] bl 0203AFD0h ; TeleportPlayer bl 0203B014h ; TriggerRoomTransition @BossOrbCheckReloadRoomEnd: ; Return to the normal boss orb code add r13, r13, 34h ; Replace line overwritten to jump here b 2061258h .pool .close
Test of immediate handling on 64-bit mode
bits 64 mov rax,1234567890abcdefh mov eax,1234567890abcdefh mov rax,dword 1234567890abcdefh mov rax,qword 1234567890abcdefh mov dword [rsi],1234567890abcdefh mov qword [rsi],1234567890abcdefh mov dword [rsi],dword 1234567890abcdefh mov qword [rsi],dword 1234567890abcdefh ; mov qword [rsi],qword 1234567890abcdefh ; Error ; mov [rsi],qword 1234567890abcdefh ; Error mov [rsi],dword 1234567890abcdefh
Add patch to remove Shanoa back glow
.nds .relativeinclude on .erroronwarning on ; This patch makes the color at index 2 in Shanoa's palette (the glyph on her back) not glow and switch between colors automatically. .open "ftc/arm9.bin", 02000000h .org 0x0208C990 nop .close
Remove any space between chars
;;----------------------------------------------------------------------------;; ;; Reduce the font space ;; Copyright 2015 Benito Palacios (aka pleonex) ;; ;; 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. ;;----------------------------------------------------------------------------;; .arm .org 020C64E0h .area 4h MOV R1, #8 - 4 .endarea
;;----------------------------------------------------------------------------;; ;; Reduce the font space ;; Copyright 2015 Benito Palacios (aka pleonex) ;; ;; 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. ;;----------------------------------------------------------------------------;; .arm .org 020C64E0h .area 4h MOV R1, #8 - 8 .endarea
Fix familiar money give number position
;;----------------------------------------------------------------------------;; ;; Align the position of the textbox in familiars menu ;; Copyright 2014 Benito Palacios (aka pleonex) ;; ;; 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. ;;----------------------------------------------------------------------------;; ;; # FAMILIAR DESCRIPTION # .org 020B6770h MOV r4, #0x9A ; Y Position: original 0x97 .org 020B677Ch MOV r1, #8 ; X Position: original 0x08 ;; # FAMILIAR OBJECTS # .org 020B6604h MOV r1, #0x73 ; X Position: Original 0x74 ADD r2, r2, #0x6B ; Y Position: Original 0x6B
;;----------------------------------------------------------------------------;; ;; Align the position of the textbox in familiars menu ;; Copyright 2014 Benito Palacios (aka pleonex) ;; ;; 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. ;;----------------------------------------------------------------------------;; .arm ;; # FAMILIAR DESCRIPTION # .org 020B6770h MOV r4, #0x9A ; Y Position: original 0x97 .org 020B677Ch MOV r1, #8 ; X Position: original 0x08 ;; # FAMILIAR OBJECTS # .org 020B6604h MOV r1, #0x73 ; X Position: Original 0x74 ADD r2, r2, #0x6B ; Y Position: Original 0x6B ;; # MONEY GIVEN # .org 020B671Ch MOV R1, #0xCD + 9 ; X Position
Test for various ELF64 GOT references
;Testname=noerr; Arguments=-felf64 -ogotoff64.o; Files=stdout stderr gotoff64.o ;Testname=err; Arguments=-DERROR -felf64 -ogotoff64.o; Files=stdout stderr gotoff64.o bits 64 default rel extern foo mov r15,[foo wrt ..got] lea r12,[foo wrt ..got] %ifdef ERROR lea rax,[foo wrt ..gotoff] mov rax,[foo wrt ..gotoff] %endif default abs mov r15,[foo wrt ..got] lea r12,[foo wrt ..got] mov rax,[qword foo wrt ..got] %ifdef ERROR lea rax,[foo wrt ..gotoff] mov rax,[foo wrt ..gotoff] %endif mov rax,[qword foo wrt ..gotoff]
Move health state in team menu
;;----------------------------------------------------------------------------;; ;; Align the position of the textbox in team menu ;; Copyright 2015 Benito Palacios (aka pleonex) ;; ;; 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. ;;----------------------------------------------------------------------------;; .arm ;; Character face icon .org 0x02130478 ADD R2, R2, #0x19 - 1 ; Y position
;;----------------------------------------------------------------------------;; ;; Align the position of the textbox in team menu ;; Copyright 2015 Benito Palacios (aka pleonex) ;; ;; 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. ;;----------------------------------------------------------------------------;; .arm ;; Character face icon .org 0x02130478 ADD R2, R2, #0x19 - 1 ; Y position ;; Health state .org 0x02130A08 MOV R2, #0x2A + 1 ; Y position
Set the stack-less kernel stack to a safe value
.file "context.asm" .text .align 2 .global kernel_enter .type kernel_enter, %function kernel_enter: mov r2, lr mrs r3, spsr msr cpsr, #0x9F /* system */ stmfd sp!, {r0, r2-r12, lr} mov r2, sp msr cpsr, #0x93 /* supervisor */ ldmfd sp!, {r4-r12, lr} /* mov sp, #0x1000 */ b syscall_handle (PLT) .size kernel_enter, .-kernel_enter .align 2 .global kernel_exit .type kernel_exit, %function kernel_exit: @ r0 holds address of user stack stmfd sp!, {r4-r12, lr} msr cpsr, #0x9F /* System */ mov sp, r0 ldmfd sp!, {r0, r2-r12, lr} msr cpsr, #0x93 /* Supervisor */ msr spsr, r3 movs pc, r2 .size kernel_exit, .-kernel_exit
.file "context.asm" .text .align 2 .global kernel_enter .type kernel_enter, %function kernel_enter: mov r2, lr mrs r3, spsr msr cpsr, #0x9F /* system */ stmfd sp!, {r0, r2-r12, lr} mov r2, sp msr cpsr, #0x93 /* supervisor */ ldmfd sp!, {r4-r12, lr} /* mov sp, #0x100000 */ b syscall_handle (PLT) .size kernel_enter, .-kernel_enter .align 2 .global kernel_exit .type kernel_exit, %function kernel_exit: @ r0 holds address of user stack stmfd sp!, {r4-r12, lr} msr cpsr, #0x9F /* System */ mov sp, r0 ldmfd sp!, {r0, r2-r12, lr} msr cpsr, #0x93 /* Supervisor */ msr spsr, r3 movs pc, r2 .size kernel_exit, .-kernel_exit
Make work with new BSPL ABI reqs
x0 = 0 ra = 1 dsp = 2 rsp = 3 gp = 4 gvp = 5 x16 = 16 x17 = 17 x18 = 18 include "sdtest.asm" ; exit the emulator. emu_exit: andi x16, x16, 255 slli x16, x16, 8 addi rsp, rsp, -8 sd x16, 0(rsp) csrrw x0, rsp, $780 jal x0, * ; Initialize the BSPL runtime environment. ; Then, kick off our tests. _cold: addi rsp, x0, $400 add dsp, rsp, rsp add gvp, dsp, dsp jal x0, _ ; CPU cold boots here. adv $FFF00, $CC jal x0, _cold
zero = 0 ra = 1 dsp = 2 ; Data stack pointer. rsp = 3 ; Return stack pointer. gvp = 4 ; Global variables pointer. gp = 13 dr16 = 5 dr17 = 6 dr18 = 7 dr19 = 8 dr20 = 9 dr21 = 10 dr22 = 11 dr23 = 12 x0 = 0 x16 = 16 x17 = 17 x18 = 18 include "sdtest.asm" ; exit the emulator. emu_exit: andi x16, x16, 255 slli x16, x16, 8 addi rsp, rsp, -8 sd x16, 0(rsp) csrrw x0, rsp, $780 jal x0, * ; Initialize the BSPL runtime environment. ; Then, kick off our tests. _cold: addi rsp, x0, $400 add dsp, rsp, rsp add gvp, dsp, dsp jal x0, _ ; CPU cold boots here. adv $FFF00, $CC jal x0, _cold
Implement yes in NASM for Mac OS X 64-bit
global _main global _start extern _puts section .text _main: add rsi, 8 _start: push rdi push rsi comp: sub rsp, 8 cmp rdi, 1 jg nz je zero nz: mov rdi, [rsi] jmp loop zero: mov rdi, y loop: call _puts add rsp, 8 pop rsi pop rdi jmp _start ret section .data y: db 'y'
Move slot color in item menu
;;----------------------------------------------------------------------------;; ;; Align the position of the textbox in the effect of items ;; Copyright 2014 Benito Palacios (aka pleonex) ;; ;; 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. ;;----------------------------------------------------------------------------;; .thumb .org 0x02117D4E MOV R1, #0x60 ; X POS -> Original 0x62
;;----------------------------------------------------------------------------;; ;; Align the position of the textbox in the effect of items ;; Copyright 2014 Benito Palacios (aka pleonex) ;; ;; 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. ;;----------------------------------------------------------------------------;; .thumb ;; Item effect .org 0x02117D4E MOV R1, #0x60 ; X POS -> Original 0x62 ;; Slot color .org 0x021170DE MOV R1, #0x9E - 4 ; X POS
Fix BR 1490407: size of the second operand of LAR/LSL
bits 64 lar ax,bx lar ax,[rsi] lar ax,word [rsi] lar eax,bx lar eax,[rsi] lar eax,word [rsi] lar rax,bx lar rax,[rsi] lar rax,word [rsi] lsl ax,bx lsl ax,[rsi] lsl ax,word [rsi] lsl eax,bx lsl eax,[rsi] lsl eax,word [rsi] lsl rax,bx lsl rax,[rsi] lsl rax,word [rsi]
Add armips patch to fix the vanilla PoR death softlock
.nds .relativeinclude on .erroronwarning on ; Fixes a vanilla bug where skipping the cutscene after you kill Death too quickly will prevent Death's boss death flag from being set. ; As a result of that bug the boss doors would relock after you exit the room, though Death himself wouldn't ever be fightable again. .open "ftc/overlay9_64", 022D7900h .org 0x022D8B18 nop .close
Add patch to always show drop percentages in PoR
.nds .relativeinclude on .erroronwarning on ; This patch causes you to always have the Gambler Glasses effect of showing percentages instead of star ratings for enemy drops. .open "ftc/arm9.bin", 02000000h .org 0x02053074 ; Checks if you have Gambler Glasses equipped to see if it should hide the stars. mov r0, 2h ; Head armor 2, Gambler Glasses .org 0x02053790 ; Checks if you have Gambler Glasses equipped to see if it should show the percentages. mov r0, 2h ; Head armor 2, Gambler Glasses .close
Add ARMIPS patch to disable sliding puzzle
.nds .relativeinclude on .erroronwarning on ; Disables the special doors of the sliding puzzle in Demon Guest House. .open "ftc/arm9.bin", 02000000h .org 0x0202738C ; This is where, upon going through any door, the game would start checking your current sector/room indexes to see if the door you went through was a sliding puzzle door. ; The original code here had a return that was conditional and only ran if your sector index is not 1 (Demon Guest House). ; We change it to an unconditional return so the special behavior of the sliding puzzle doors never activates. mov r0, 0h pop r4-r8,r14 bx r14 .close
Fix last position offset on colorwasher fx
//============================================================ // color washer routine //============================================================ colwash: lda color+$00 // load the current first color from table sta color+$28 // store in in last position of table to reset the cycle ldx #$00 // init X with zero cycle1: lda color+1,x // Start cycle by fetching next color in the table... sta color,x // ...and store it in the current active position. sta $d990,x // put into Color Ram inx // increment X-Register cpx #$28 // have we done 40 iterations yet? bne cycle1 // if no, continue colwash2: lda color2+$28 // load current last color from second table sta color2+$00 // store in in first position of table to reset the cycle ldx #$28 cycle2: lda color2-1,x // Start cycle by fetching previous color in the table... sta color2,x // ...and store it in the current active position. sta $d9df,x // put into Color Ram dex // decrease iterator bne cycle2 // if x not zero yet, continue rts // return from subroutine
//============================================================ // color washer routine //============================================================ colwash: lda color+$00 // load the current first color from table sta color+$27 // store in in last position of table to reset the cycle ldx #$00 // init X with zero cycle1: lda color+1,x // Start cycle by fetching next color in the table... sta color,x // ...and store it in the current active position. sta $d990,x // put into Color Ram inx // increment X-Register cpx #$28 // have we done 40 iterations yet? bne cycle1 // if no, continue colwash2: lda color2+$27 // load current last color from second table sta color2+$00 // store in in first position of table to reset the cycle ldx #$28 cycle2: lda color2-1,x // Start cycle by fetching previous color in the table... sta color2,x // ...and store it in the current active position. sta $d9df,x // put into Color Ram dex // decrease iterator bne cycle2 // if x not zero yet, continue rts // return from subroutine
Use rsp as stack pointer, not esp
[BITS 64] %include "src/asm_routines/constants.asm" global start extern rust_main section .entry start: ; update segments mov dx, gdt_selector_data ; data selector mov ss, dx ; stack segment mov ds, dx ; data segment mov es, dx ; extra segment mov fs, dx ; f-segment mov gs, dx ; g-segment ; set up stack mov esp, stack_top ; get to kernel call rust_main ; rust main returned, print `OS returned!` mov rax, 0x4f724f204f534f4f mov [0xb8000], rax mov rax, 0x4f724f754f744f65 mov [0xb8008], rax mov rax, 0x4f214f644f654f6e mov [0xb8010], rax hlt ; reserve space for stack section .bss stack_bottom: resb 4096 stack_top:
[BITS 64] %include "src/asm_routines/constants.asm" global start extern rust_main section .entry start: ; update segments mov dx, gdt_selector_data ; data selector mov ss, dx ; stack segment mov ds, dx ; data segment mov es, dx ; extra segment mov fs, dx ; f-segment mov gs, dx ; g-segment ; set up stack mov rsp, stack_top ; get to kernel call rust_main ; rust main returned, print `OS returned!` mov rax, 0x4f724f204f534f4f mov [0xb8000], rax mov rax, 0x4f724f754f744f65 mov [0xb8008], rax mov rax, 0x4f214f644f654f6e mov [0xb8010], rax hlt ; reserve space for stack section .bss stack_bottom: resb 4096 stack_top:
Print "===" to the screen
; JUMP.ASM ; Make a jump and then hang ; Tell the compiler that this is offset 0. ; It isn't offset 0, but it will be after the jump. [ORG 0] jmp 07C0h:start ; Goto segment 07C0 start: ; Update the segment registers mov ax, cs mov ds, ax mov es, ax hang: ; Hang! jmp hang times 510-($-$$) db 0 dw 0AA55h
; 1.ASM ; Print "====" on the screen and hang ; Tell the compiler that this is offset 0. ; It isn't offset 0, but it will be after the jump. [ORG 0] jmp 07C0h:start ; Goto segment 07C0 start: ; Update the segment registers mov ax, cs mov ds, ax mov es, ax mov ah, 9 ; Print "====" mov al, '=' ; mov bx, 7 ; mov cx, 4 ; int 10h ; hang: ; Hang! jmp hang times 510-($-$$) db 0 dw 0AA55h
Add a test for various 32- and 64-bit relocations
bits 64 extern foo mov eax,[foo] mov rax,[foo] mov rax,[qword foo] mov eax,foo mov rax,dword foo mov rax,qword foo dd foo dq foo
Change name of entry function
bits 32 section .text align 4 dd 0x1BADB002 dd 0x00 dd - (0x1BADB002 + 0x00) global start extern main start: cli mov esp, kstack call main hlt section .bss resb 8192 kstack:
bits 32 section .text align 4 dd 0x1BADB002 dd 0x00 dd - (0x1BADB002 + 0x00) global start extern entry start: cli mov esp, kstack call entry hlt section .bss resb 8192 kstack:
Update patch to break balore blocks
.nds .relativeinclude on .erroronwarning on .open "ftc/overlay9_0", 0219E3E0h ; This makes it so that all melee weapons can break balore blocks, not just Julius's whip. .org 0x02212AB0 ; Branch of a switch statement taken for all melee weapons except Julius's whip. b 02212D64h ; Instead take the branch taken for Julius's whip. .close
.nds .relativeinclude on .erroronwarning on .open "ftc/overlay9_0", 0219E3E0h ; This makes it so that all melee weapons can break balore blocks, not just Julius's whip. .org 0x02212AB0 ; Branch of a switch statement taken for all melee weapons except Julius's whip. b 02212D64h ; Instead take the branch taken for Julius's whip. ; Next we need to make sure the player has Balore's soul. .org 0x02212E94 ; Line in the whip code that would normally call 021D5210 to break the blocks. b @CheckDestroyBaloreBlocks ; Instead jump to our own code to check if the player has Balore's soul. .close .open "ftc/arm9.bin", 02000000h .org 0x020C0290 ; Free space @CheckDestroyBaloreBlocks: mov r5, r14 mov r0, 0h bl 0220F81Ch cmp r0, 1h ; Check if Balore soul is active. beq @DestroyBaloreBlocks ; Destroy blocks if it is. ldr r0,=020F740Eh ldrb r0, [r0] cmp r0, 1h ; Otherwise check if the current player character is Julius. beq @DestroyBaloreBlocks ; Destroy blocks if it is. b 02212E98h ; Didn't meet either condition, so return without destroying them. @DestroyBaloreBlocks: mov r0, r5 mov r1, r12 mov r2, r4 bl 021D5210h ; Call function to destroy blocks. b 02212E98h ; Return .pool .close
Remove the branch for clarity
add $t0, $t1, $t2 sub $s0, $t0, $v0 exit beq $3, $8, 3 nop nop
add $t0, $t1, $t2 sub $s0, $t0, $v0 exit add $t0, $t1, $t2 nop nop
Fix changing starting room in PoR not changing Old Axe Armor mode's starting room
.nds .relativeinclude on .erroronwarning on .open "ftc/arm9.bin", 02000000h .org 0x02051F90 ; Where the original game's code for loading area/sector/room indexes is. b 020BFC00h ; Jump to some free space, where we will put our own code for loading the area/sector/room indexes. .org 0x020BFC00 ; Free space. mov r5,0h ; Load the area index into r5. strb r5,[r0,515h] ; Store the area index to the ram address where r0 will read it later. (0x02111785) mov r5,0h ; Load the sector index into r5. mov r4,0h ; Load the room index into r4. b 02051F94h ; Return to where we came from. .close
.nds .relativeinclude on .erroronwarning on .open "ftc/arm9.bin", 02000000h .org 0x02051F90 ; Where the original game's code for loading area/sector/room indexes is. b 020BFC00h ; Jump to some free space, where we will put our own code for loading the area/sector/room indexes. .org 0x020BFC00 ; Free space. mov r5,0h ; Load the area index into r5. strb r5,[r0,515h] ; Store the area index to the ram address where r0 will read it later. (0x02111785) mov r5,0h ; Load the sector index into r5. mov r4,0h ; Load the room index into r4. b 02051F94h ; Return to where we came from. .org 0x02051F80 ; The case statement for Old Axe Armor mode's starting room initialization. b 0x02051F88 ; Change it to take the same branch as the other three modes. .close
Increase items name textbox size
;;----------------------------------------------------------------------------;; ;; Align the position of the textbox in the effect of items ;; Copyright 2014 Benito Palacios (aka pleonex) ;; ;; 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. ;;----------------------------------------------------------------------------;; .thumb ;; Item effect .org 0x02117D4E MOV R1, #0x60 ; X POS -> Original 0x62 ;; Slot color .org 0x021170DE MOV R1, #0x9E - 4 ; X POS .thumb ;; Increase the size of the item name textbox .org 0x02116E90 MOV R0, #0x14 + 1 ; Width / 8
;;----------------------------------------------------------------------------;; ;; Align the position of the textbox in the effect of items ;; Copyright 2014 Benito Palacios (aka pleonex) ;; ;; 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. ;;----------------------------------------------------------------------------;; .thumb ;; Item effect .org 0x02117D4E MOV R1, #0x60 ; X POS -> Original 0x62 ;; Slot color .org 0x021170DE MOV R1, #0x9E - 4 ; X POS .thumb ;; Increase the size of the item name textbox .org 0x02116E90 MOV R0, #0x14 + 2 ; Width / 8
Test for mov [mem], sreg
global _start section .data align 16 mydword: dd 0 %include "header.inc" ; 32-bit register move should set higher bits to zero mov eax, -1 mov eax, ss and eax, 0xffff0000 ; 32-bit memory move should preserver higher bits mov dword [mydword], 0xdeadbeef mov [mydword], ss mov ebx, [mydword] and ebx, 0xffff0000 %include "footer.inc"
Add patch to reveal whole map from the start for DoS
.nds .relativeinclude on .erroronwarning on ; Makes the entire map visible but greyed out from the start. .open "ftc/arm9.bin", 02000000h .org 0x020220C4 ; Make the game not care if you have the map items and just always draw unvisited tiles. mov r1, r8 nop .org 0x02024BE8 ; Makes rooms never be counted as secret rooms, since secret rooms don't show up even if the game thinks you have the map for that area. mvn r0, 0h bx r14 .close
Rewrite the 16bit print routine.
; ============================================================================= ; Copyright (C) 2015 Manolis Fragkiskos Ragkousis -- see LICENSE.TXT ; ============================================================================= ;;; Print routine ;;; I push all the register to the stack. ;;; Set the bios routine for printing in the screen ;;; Move to al the data that bx points ;;; Generate the interrupt. ;;; Pop all registers from the stack ;;; Return to where the pc pointed to before getting in here. ;;; bx contains routine argument %ifndef PRINT_STRING_16BIT %define PRINT_STRING_16BIT print_string: pusha mov ah, 0x0e compare: cmp byte [bx], 0 je exit jmp print print: mov al, [bx] int 0x10 add bx, 1 jmp compare exit: popa ret %endif
; ============================================================================= ; Copyright (C) 2015 Manolis Fragkiskos Ragkousis -- see LICENSE.TXT ; ============================================================================= ;;; Print routine ;;; I push all the register to the stack. ;;; Set the bios routine for printing in the screen ;;; Move to al the data that bx points ;;; Generate the interrupt. ;;; Pop all registers from the stack ;;; Return to where the pc pointed to before getting in here. ;;; bx contains routine argument %ifndef PRINT_STRING_16BIT %define PRINT_STRING_16BIT [bits 16] print_string: pusha mov ah, 0x0e print_loop: mov al, [bx] cmp al, 0 je print_exit int 0x10 inc bx jmp print_loop print_exit: popa ret %endif
Fix srg mapping in hook (round 2)
list n_IItemRenderer GETSTATIC net/minecraft/client/renderer/tileentity/TileEntityItemStackRenderer.instance : Lnet/minecraft/client/renderer/tileentity/TileEntityItemStackRenderer; ALOAD 1 INVOKEVIRTUAL net/minecraft/client/renderer/tileentity/TileEntityItemStackRenderer.renderByItem (Lnet/minecraft/item/ItemStack;)V GOTO LEND #end of if statement list IItemRenderer ALOAD 2 INSTANCEOF codechicken/lib/render/IItemRenderer IFEQ LELSE ALOAD 2 ALOAD 1 INVOKEINTERFACE codechicken/lib/render/IItemRenderer.renderItem (Lnet/minecraft/item/ItemStack;)V GOTO LEND LELSE
list n_IItemRenderer GETSTATIC net/minecraft/client/renderer/tileentity/TileEntityItemStackRenderer.field_147719_a : Lnet/minecraft/client/renderer/tileentity/TileEntityItemStackRenderer; ALOAD 1 INVOKEVIRTUAL net/minecraft/client/renderer/tileentity/TileEntityItemStackRenderer.func_179022_a (Lnet/minecraft/item/ItemStack;)V GOTO LEND #end of if statement list IItemRenderer ALOAD 2 INSTANCEOF codechicken/lib/render/IItemRenderer IFEQ LELSE ALOAD 2 ALOAD 1 INVOKEINTERFACE codechicken/lib/render/IItemRenderer.renderItem (Lnet/minecraft/item/ItemStack;)V GOTO LEND LELSE
Add patch to fix DoS tower boss in boss rando
.nds .relativeinclude on .erroronwarning on ; This patch for the boss randomizer prevents the boss in Gergoth's tower from being loaded in until the player enters the top floor of the tower. ; In order for the patch to work correctly, the boss entity should be at index 1 and the tower floors entity should be at index 0 (reversed from how they are in vanilla). @Overlay41Start equ 0x02308920 @FreeSpace equ @Overlay41Start + 0x288 .open "ftc/overlay9_0", 0219E3E0h .org 0x0219F08C ; Near the end of the create function for object 18 (tower floors) b @LoadOrUnloadTowerBoss .close .open "ftc/overlay9_41", @Overlay41Start .org @FreeSpace @LoadOrUnloadTowerBoss: ldr r1, =020F70CCh ; Pointer to the current room's entity list ldr r1, [r1] add r1, r1, 11h ; Add 0x11 (0xC + 0x5) to the start of the entity list to get a pointer to the type byte of the second entity in the list, which is the boss entity. ; The last check done before the custom code was checking if r0 is equal to 0. If it is it means the player is on the top floor of the tower, so the boss should be loaded. beq @AllowTowerBossToBeLoaded @DoNotAllowTowerBossToBeLoaded: mov r0, 0h ; Set the type of the boss entity to 0, so it's doesn't load any entity in. b @FinishLoadingOrUnloadingTowerBoss @AllowTowerBossToBeLoaded: mov r0, 1h ; Set the type of the boss entity to 0, so it works properly as an enemy. @FinishLoadingOrUnloadingTowerBoss: strb r0, [r1] ; Store the type to the entity list. ; Replace the code we overwrote to jump here. beq 0x0219F0AC ; Return from function if on the top floor. b 0x0219F098 ; If not on the top floor, do some other stuff before returning. .pool .close
Add basic background cycler example that is confirmed to work with 6502.Net.
.cpu "6502" .target "flat" * = $F000 BackgroundColor = $80 VSYNC = $00 VBLANK = $01 WSYNC = $02 COLUBK = $09 TIM64T = $296 INTIM = $284 Start SEI CLD LDX #$FF TXS LDA #0 ClearMem STA 0,X DEX BNE ClearMem MainLoop LDA #%00000010 STA VSYNC STA WSYNC STA WSYNC STA WSYNC LDA #43 STA TIM64T LDA #0 STA VSYNC INC BackgroundColor LDA BackgroundColor STA COLUBK WaitForVBlankEnd LDA INTIM BNE WaitForVBlankEnd STA WSYNC STA VBLANK LDY #192 ScanLoop STA WSYNC DEY BNE ScanLoop LDA #2 STA WSYNC STA VBLANK LDY #30 OverScanWait STA WSYNC DEY BNE OverScanWait JMP MainLoop // Special memory locations. Tells the 6502 where to go. * = $FFFC .word Start .word Start
Test of some addressing modes in 64-bit mode.
bits 64 mov rdx,[rax] mov eax,[byte rsp+0x01] mov eax,[byte rsp-0x01] mov eax,[byte rsp+0xFF] mov eax,[byte rsp-0xFF] mov eax,[rsp+0x08] mov eax,[rsp-0x01] mov eax,[rsp+0xFF] mov eax,[rsp-0xFF] mov rax,[rsp+56] mov [rsi],dl mov byte [rsi],'-' mov [rsi],al mov byte [rsi],' '
Add test for problematic floats
;; Known problematic floating-point numbers and their proper ;; encoding... dd 1.1e10 dd 0x5023e9ac ; Should be... dd 50.40e9 dd 0x513bc130 ; Should be... dq 1.4e23 dq 0x44bda56a4b0835c0 dq 50.48e21 dq 0x44a5610d7502feae dt 1.2e28 dq 0x9b18ab5df7180b6c dw 0x405c dt 50.46e25 dq 0xd0b29a67e95dcb60 dw 0x4057
Add test cases for IP-relative addressing
bits 64 ; extern foo mov rax,[foo] mov rax,[123456789abcdef0h] mov rbx,[foo] mov rax,[dword foo] mov rbx,[dword foo] mov rax,[qword foo] mov rax,[rel foo] mov rbx,[rel foo] mov rax,[rel dword foo] mov rax,[rel qword foo] mov rax,[es:foo] mov rax,[es:123456789abcdef0h] mov rbx,[es:foo] mov rax,[dword es:foo] mov rbx,[dword es:foo] mov rax,[qword es:foo] mov rax,[rel es:foo] mov rbx,[rel es:foo] mov rax,[rel dword es:foo] mov rax,[rel qword es:foo] mov rax,[fs:foo] mov rax,[fs:123456789abcdef0h] mov rbx,[fs:foo] mov rax,[dword fs:foo] mov rbx,[dword fs:foo] mov rax,[qword fs:foo] mov rax,[rel fs:foo] mov rbx,[rel fs:foo] mov rax,[rel dword fs:foo] mov rax,[rel qword fs:foo] section .data foo equ $
Switch dos stub processor spec to 386.
; Copyright 2011 Google Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; .286 .MODEL TINY, C .CODE PUBLIC end_dos_stub begin_dos_stub PROC ; Fold the code and data segments, as our data is in this function. ; Note that begin_dos_stub is implicitly the start of the data segment. push cs pop ds ; Compute the distance to the string through this subtraction instead ; of e.g. a lea instruction to avoid the need for relocation entries mov dx, message - begin_dos_stub ; Print the message to the console mov ah, 09h int 21h ; Terminate the program mov ah, 00h int 21h message DB 'This is a Windows program, you cannot run it in DOS.\r\n$' ; Expose the end of the DOS stub as a function to make it easy to ; calculate its length. end_dos_stub LABEL PROC begin_dos_stub ENDP END
; Copyright 2012 Google Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; .386 .MODEL TINY, C .CODE PUBLIC end_dos_stub begin_dos_stub PROC ; Fold the code and data segments, as our data is in this function. ; Note that begin_dos_stub is implicitly the start of the data segment. push cs pop ds ; Compute the distance to the string through this subtraction instead ; of e.g. a lea instruction to avoid the need for relocation entries mov dx, message - begin_dos_stub ; Print the message to the console mov ah, 09h int 21h ; Terminate the program mov ah, 00h int 21h message DB 'This is a Windows program, you cannot run it in DOS.\r\n$' ; Expose the end of the DOS stub as a function to make it easy to ; calculate its length. end_dos_stub LABEL PROC begin_dos_stub ENDP END
Add dependent types into EEPROM API
%{# #include <avr/eeprom.h> %} fun eeprom_read_byte (address: int): uint8 = "mac#" fun eeprom_write_byte (address: int, value: uint8): void = "mac#"
%{# #include <avr/eeprom.h> %} fun eeprom_read_byte {n:nat} (address: int n): uint8 = "mac#" fun eeprom_write_byte {n:nat} (address: int n, value: uint8): void = "mac#"
Include C raw source code
implement main0 () = ()
%{^ #include "LPC17xx.h" %} %{ volatile int g_LoopDummy; void c_blink(void) { LPC_GPIO1->FIODIR |= 1 << 18; // P1.18 connected to LED1 while(1) { int i; LPC_GPIO1->FIOPIN ^= 1 << 18; // Toggle P1.18 for (i = 0 ; i < 5000000 && !g_LoopDummy ; i++) { } } } %} extern fun c_blink (): void = "mac#" implement main0 () = c_blink ()
Add type to mbed interface
%{^ #include "mbed_interface.h" %} typedef char_p = cPtr0(char) fun mbed_mac_address: (char_p) -> void = "mac#"
Allow Creation of Hostname When File is Missing
(* Module: Hostname Parses /etc/hostname and /etc/mailname Author: Raphael Pinson <raphink@gmail.com> About: License This file is licenced under the LGPL v2+, like the rest of Augeas. *) module Hostname = autoload xfm (* View: lns *) let lns = [ label "hostname" . store Rx.word . Util.eol ] (* View: filter *) let filter = incl "/etc/hostname" . incl "/etc/mailname" let xfm = transform lns filter
(* Module: Hostname Parses /etc/hostname and /etc/mailname Author: Raphael Pinson <raphink@gmail.com> About: License This file is licenced under the LGPL v2+, like the rest of Augeas. *) module Hostname = autoload xfm (* View: lns *) let lns = [ label "hostname" . store Rx.word . Util.eol ] | Util.empty (* View: filter *) let filter = incl "/etc/hostname" . incl "/etc/mailname" let xfm = transform lns filter
Remove bogus reset of 'record' counter
# Parsing /etc/inittab #map # grammar inittab # include '/etc/inittab' '/system/config/inittab' #end grammar inittab token SEP ':' token EOL '\n' file: ( comment | record ) * comment: ( /#.*?\n/ | /[ \t]*\n/ ) record: counter 'record' . [ seq 'record' . [ label 'id' . store ..? ] . SEP . [ label 'runlevels' . store ..? ] . SEP . [ label 'action' . store ..? ] . SEP . [ label 'process' . store ..? ] . EOL ] end
# Parsing /etc/inittab map grammar inittab include '/etc/inittab' '/system/config/inittab' end grammar inittab token SEP ':' token EOL '\n' file: ( comment | record ) * comment: ( /#.*?\n/ | /[ \t]*\n/ ) record: [ seq 'record' . [ label 'id' . store ..? ] . SEP . [ label 'runlevels' . store ..? ] . SEP . [ label 'action' . store ..? ] . SEP . [ label 'process' . store ..? ] . EOL ] end
Remove trailing white spaces from puppet test
(* Tests for the PuppetFileserver module *) module Test_puppetfileserver = let fileserver = "# This a comment [mount1] # Mount1 options path /etc/puppet/files/%h allow host.domain1.com allow *.domain2.com deny badhost.domain2.com [mount2] allow * deny *.evil.example.com deny badhost.domain2.com [mount3] allow * # Puppet #6026: same line comment # And trailing whitespace allow * " test PuppetFileserver.lns get fileserver = { "#comment" = "This a comment" } { } { "mount1" { "#comment" = "Mount1 options" } { "path" = "/etc/puppet/files/%h" } { "allow" = "host.domain1.com" } { "allow" = "*.domain2.com" } { "deny" = "badhost.domain2.com" } } { "mount2" { "allow" = "*" } { "deny" = "*.evil.example.com" } { "deny" = "badhost.domain2.com" } } { "mount3" { "allow" = "*" { "#comment" = "Puppet #6026: same line comment" } } { "#comment" = "And trailing whitespace" } { "allow" = "*" } }
(* Tests for the PuppetFileserver module *) module Test_puppetfileserver = let fileserver = "# This a comment [mount1] # Mount1 options path /etc/puppet/files/%h allow host.domain1.com allow *.domain2.com deny badhost.domain2.com [mount2] allow * deny *.evil.example.com deny badhost.domain2.com [mount3] allow * # Puppet #6026: same line comment # And trailing whitespace allow * " test PuppetFileserver.lns get fileserver = { "#comment" = "This a comment" } { } { "mount1" { "#comment" = "Mount1 options" } { "path" = "/etc/puppet/files/%h" } { "allow" = "host.domain1.com" } { "allow" = "*.domain2.com" } { "deny" = "badhost.domain2.com" } } { "mount2" { "allow" = "*" } { "deny" = "*.evil.example.com" } { "deny" = "badhost.domain2.com" } } { "mount3" { "allow" = "*" { "#comment" = "Puppet #6026: same line comment" } } { "#comment" = "And trailing whitespace" } { "allow" = "*" } }
Add Sep.equal, used in nrpe.aug
(* Module: Sep Generic separators to build lenses Author: Raphael Pinson <raphink@gmail.com> About: License This file is licensed under the LGPLv2+, like the rest of Augeas. *) module Sep = let colon = Util.del_str ":" let comma = Util.del_str "," let space = del Rx.space " " let tab = del Rx.space "\t" let opt_space = del Rx.opt_space "" let opt_tab = del Rx.opt_space "\t"
(* Module: Sep Generic separators to build lenses Author: Raphael Pinson <raphink@gmail.com> About: License This file is licensed under the LGPLv2+, like the rest of Augeas. *) module Sep = let colon = Util.del_str ":" let comma = Util.del_str "," let equal = Util.del_str "=" let space = del Rx.space " " let tab = del Rx.space "\t" let opt_space = del Rx.opt_space "" let opt_tab = del Rx.opt_space "\t"
Fix syntax error in test
module Fail_union_atype = (* This is illegal, otherwise we don't know which alternative *) (* to take for a tree { "a" = "?" } *) let del_str (s:string) = del s s let lns = [ key /a/ . store /b/ . del_str " (l)" | [ key /a/ . store /c/ . del_str " (r)" ] (* To make this a passing test, make sure that this also works: *) (* test lns put "ac (r)" after set "a" "b" = "ab (l)" *) (* Local Variables: *) (* mode: caml *) (* End: *)
module Fail_union_atype = (* This is illegal, otherwise we don't know which alternative *) (* to take for a tree { "a" = "?" } *) let del_str (s:string) = del s s let lns = [ key /a/ . store /b/ . del_str " (l)" ] | [ key /a/ . store /c/ . del_str " (r)" ] (* To make this a passing test, make sure that this also works: *) (* test lns put "ac (r)" after set "a" "b" = "ab (l)" *) (* Local Variables: *) (* mode: caml *) (* End: *)
Fix put test - it was checking for hte wrong result
module Pass_subtree_growth = (* Make sure that a subtree that is not the lowest one does indeed *) (* grow the tree, instead of just setting the label of an enclosed *) (* subtree. This is only a problem if the enclosed subtree does *) (* not have a label *) let lns = [ label "outer" . [ store /a/ ] ] (* The improper result is { "outer" = "a" } *) test lns get "a" = { "outer" { = "a" } } test lns put "a" after set "outer" "b" = "b" (* Local Variables: *) (* mode: caml *) (* End: *)
module Pass_subtree_growth = (* Make sure that a subtree that is not the lowest one does indeed *) (* grow the tree, instead of just setting the label of an enclosed *) (* subtree. This is only a problem if the enclosed subtree does *) (* not have a label *) let lns = [ label "outer" . [ store /a/ ] ] (* The improper result is { "outer" = "a" } *) test lns get "a" = { "outer" { = "a" } } (* This produces a tree { "outer" = "b" { = "a" } } *) (* but the value for "outer" is never used in put *) (* (That should probably be flagged as an error separately) *) test lns put "a" after set "outer" "b" = "a" (* Local Variables: *) (* mode: caml *) (* End: *)
Add more recent nagios lens
(* Module: NagiosConfig Parses /etc/{nagios{3,},icinga/*.cfg Authors: Sebastien Aperghis-Tramoni <sebastien@aperghis.net> Raphaël Pinson <raphink@gmail.com> About: License This file is licenced under the LGPL v2+, like the rest of Augeas. About: Lens Usage To be documented About: Configuration files This lens applies to /etc/{nagios{3,},icinga/*.cfg. See <filter>. *) module NagiosCfg = autoload xfm (************************************************************************ * Group: Utility variables/functions ************************************************************************) (* View: param_def define a field *) let param_def = let space_in = /[^ \t\n][^\n=]*[^ \t\n]|[^ \t\n]/ in key /[A-Za-z0-9_]+/ . Sep.space_equal . store space_in (* View: macro_def Macro line, as used in resource.cfg *) let macro_def = let macro = /\$[A-Za-z0-9]+\$/ in let macro_decl = Rx.word | Rx.fspath in key macro . Sep.space_equal . store macro_decl (************************************************************************ * Group: Entries ************************************************************************) (* View: param Params can have sub params *) let param = [ Util.indent . param_def . [ Sep.space . param_def ]* . Util.eol ] (* View: macro *) let macro = [ Util.indent . macro_def . Util.eol ] (************************************************************************ * Group: Lens ************************************************************************) (* View: entry Define the accepted entries, such as param for regular configuration files, and macro for resources.cfg .*) let entry = param | macro (* View: lns main structure *) let lns = ( Util.empty | Util.comment | entry )* (* View: filter *) let filter = incl "/etc/nagios3/*.cfg" . incl "/etc/nagios/*.cfg" . incl "/etc/icinga/*.cfg" . excl "/etc/nagios3/commands.cfg" . excl "/etc/nagios/commands.cfg" . excl "/etc/nagios/nrpe.cfg" . incl "/etc/icinga/commands.cfg" let xfm = transform lns filter
Add test for radicale lens
module Test_radicale = let conf = " [server] [encoding] [well-known] [auth] [git] [rights] [storage] [logging] [headers] " test Radicale.lns get conf = {} { "server" {} } { "encoding" {} } { "well-known" {} } { "auth" {} } { "git" {} } { "rights" {} } { "storage" {} } { "logging" {} } { "headers" {} } test Radicale.lns put conf after set "server/hosts" "127.0.0.1:5232, [::1]:5232"; set "server/base_prefix" "/radicale/"; set "well-known/caldav" "/radicale/%(user)s/caldav/"; set "well-known/cardav" "/radicale/%(user)s/carddav/"; set "auth/type" "remote_user"; set "rights/type" "owner_only" = " [server] hosts=127.0.0.1:5232, [::1]:5232 base_prefix=/radicale/ [encoding] [well-known] caldav=/radicale/%(user)s/caldav/ cardav=/radicale/%(user)s/carddav/ [auth] type=remote_user [git] [rights] type=owner_only [storage] [logging] [headers] "
Add basic EPSG augeas lens
module EPSG = let proj = [ key /[^\/= \t\n]+/ . (Sep.equal . store Rx.no_spaces)? ] let entry = [ Util.del_str "<" . key Rx.integer . Util.del_str ">" . Sep.space . Build.opt_list proj Sep.space . Sep.space . Util.del_str "<>" . Util.eol ] let lns = (Util.empty | Util.comment | entry)*
Add /etc/mtab to known files
(* Parsing /etc/fstab *) module Fstab = autoload xfm let sep_tab = Sep.tab let sep_spc = Sep.space let comma = Sep.comma let eol = Util.eol let comment = Util.comment let empty = Util.empty let word = Rx.neg1 let spec = /[^,# \n\t][^ \n\t]*/ let comma_sep_list (l:string) = let lns = [ label l . store word ] in Build.opt_list lns comma let record = [ seq "mntent" . [ label "spec" . store spec ] . sep_tab . [ label "file" . store word ] . sep_tab . comma_sep_list "vfstype" . sep_tab . comma_sep_list "opt" . (sep_tab . [ label "dump" . store /[0-9]+/ ] . ( sep_spc . [ label "passno" . store /[0-9]+/ ])? )? . eol ] let lns = ( empty | comment | record ) * let xfm = transform lns (incl "/etc/fstab") (* Local Variables: *) (* mode: caml *) (* End: *)
(* Parsing /etc/fstab *) module Fstab = autoload xfm let sep_tab = Sep.tab let sep_spc = Sep.space let comma = Sep.comma let eol = Util.eol let comment = Util.comment let empty = Util.empty let word = Rx.neg1 let spec = /[^,# \n\t][^ \n\t]*/ let comma_sep_list (l:string) = let lns = [ label l . store word ] in Build.opt_list lns comma let record = [ seq "mntent" . [ label "spec" . store spec ] . sep_tab . [ label "file" . store word ] . sep_tab . comma_sep_list "vfstype" . sep_tab . comma_sep_list "opt" . (sep_tab . [ label "dump" . store /[0-9]+/ ] . ( sep_spc . [ label "passno" . store /[0-9]+/ ])? )? . eol ] let lns = ( empty | comment | record ) * let filter = (incl "/etc/fstab") . (incl "/etc/mtab") let xfm = transform lns filter (* Local Variables: *) (* mode: caml *) (* End: *)
Store comments in subtrees so they are restored properly
# Parsing /etc/inittab map grammar pam # We really need to be able to exclude some files, like # backup files and .rpmsave files include '/etc/pam.d/*' '/system/config/pam' $basename end grammar pam token SEP /[ \t]+/ = '\t' token EOL '\n' token CONTROL /(\[[^\]]*\]|[^ \t]+)/ = 'none' token POUND_TO_EOL /#.*\n/ = '# ' file: ( comment | record ) * comment: ( /#.*?\n/ | /[ \t]*\n/ ) record: [ seq 'record' . [ label 'type' . store ... ] . SEP . [ label 'control' . store CONTROL] . SEP . [ label 'module' . store ... ] . ( [ SEP . label 'opts' . store ... ] )? . EOL ] end
# Parsing /etc/inittab map grammar pam # We really need to be able to exclude some files, like # backup files and .rpmsave files include '/etc/pam.d/*' '/system/config/pam' $basename end grammar pam token SEP /[ \t]+/ = '\t' token EOL '\n' token CONTROL /(\[[^\]]*\]|[^ \t]+)/ = 'none' token POUND_TO_EOL /#.*\n/ = '# ' file: ( comment | record ) * comment: [ ( /#.*?\n/ | /[ \t]*\n/ ) ] record: [ seq 'record' . [ label 'type' . store ... ] . SEP . [ label 'control' . store CONTROL] . SEP . [ label 'module' . store ... ] . ( [ SEP . label 'opts' . store ... ] )? . EOL ] end
Check that let expressions work
(* Test let expressions *) module Pass_let_exp = (* This definition is insanely roundabout; it's written that way *) (* since we want to exercise LET expressions *) let lns = let lbl = "a" in let spc = " " in let del_spaces (s:string) = del spc+ s in let del_str (s:string) = del s s in let store_delim (ldelim:string) (rdelim:string) (val:regexp) = del_str ldelim . store val . del_str rdelim in [ label lbl . del_spaces " " . store_delim "(" ")" /[a-z]+/ ] test lns get " (abc)" = { "a" = "abc" } (* Local Variables: *) (* mode: caml *) (* End: *)
Add another shortcut for Listary
#NoTrayIcon #Persistent #SingleInstance force #NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases. ; #Warn ; Enable warnings to assist with detecting common errors. SendMode Input ; Recommended for new scripts due to its superior speed and reliability. SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory. ;;******************************************************* ; CUSTOM SHORTCUTS ;******************************************************* ;------------------------------------------------------- ; Keep window on top ;------------------------------------------------------- !+^T:: Winset, Alwaysontop, , A ;------------------------------------------------------- ;------------------------------------------------------- ; Replace default calculator ;------------------------------------------------------- ^NumpadEnter::Run "C:\Program Files (x86)\Moffsoft FreeCalc\MoffFreeCalc.exe" ;------------------------------------------------------- ;------------------------------------------------------- ; Call Listary ;------------------------------------------------------- ; With Alt + Space !Space::Send !+^{=} ; With the down button of the mouse XButton1::Send !+^{)} ;------------------------------------------------------- ;------------------------------------------------------- ; Switch between the desktops ;------------------------------------------------------- ; With the up button of the mouse ^XButton1:: switchDesktop() ; XButton2:: switchDesktop() ; ; Function to switch between the desktops switchedDesktop := false switchDesktop() { global switchedDesktop if switchedDesktop { SendEvent ^#{Right} switchedDesktop := false } else { SendEvent ^#{Left} switchedDesktop := true } } ;-------------------------------------------------------
#NoTrayIcon #Persistent #SingleInstance force #NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases. ; #Warn ; Enable warnings to assist with detecting common errors. SendMode Input ; Recommended for new scripts due to its superior speed and reliability. SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory. ;;******************************************************* ; CUSTOM SHORTCUTS ;******************************************************* ;------------------------------------------------------- ; Keep window on top ;------------------------------------------------------- !+^T:: Winset, Alwaysontop, , A ;------------------------------------------------------- ;------------------------------------------------------- ; Replace default calculator ;------------------------------------------------------- ^NumpadEnter::Run "C:\Program Files (x86)\Moffsoft FreeCalc\MoffFreeCalc.exe" ;------------------------------------------------------- ;------------------------------------------------------- ; Call Listary ;------------------------------------------------------- ; With Alt + Space !Space::Send !+^{=} ; With the down button of the mouse XButton1::Send !+^{)} ^RButton::Send !+^{)} ;------------------------------------------------------- ;------------------------------------------------------- ; Switch between the desktops ;------------------------------------------------------- ; With the up button of the mouse ^XButton1:: switchDesktop() ; XButton2:: switchDesktop() ; ; Function to switch between the desktops switchedDesktop := false switchDesktop() { global switchedDesktop if switchedDesktop { SendEvent ^#{Right} switchedDesktop := false } else { SendEvent ^#{Left} switchedDesktop := true } } ;-------------------------------------------------------
Update for new bnet title scheme
email = %1% passwrd = %2% Checkd() { WinWait Blizzard App Login, ,3 WinMove 0, 0 WinActivate IfWinNotActive { Checkd() } if ErrorLevel { MsgBox unable to find Battle.net login window. Please record trying to login and report it at j20.pw/bnethelp exit } } Checkd() Sleep 2000 Checkd() WinActivate Checkd() ClickFromTopRight(42,200) Send ^a Send {BS} send %email% sleep 20 Sleep 100 ClickFromTopRight(42,250) Sleep 20 ClickFromTopRight(42,250) Send ^a Send {BS} send %passwrd% Send {Enter} exit ClickFromTopRight(_X,_Y){ CoordMode, mouse, Relative WinGetActiveStats, Title, width, height, x,y _X := width - _X Click %_X%, %_Y% }
email = %1% passwrd = %2% Checkd() { WinWait Blizzard Battle.net Login, ,3 WinMove 0, 0 WinActivate IfWinNotActive { Checkd() } if ErrorLevel { MsgBox unable to find Battle.net login window. Please record trying to login and report it at j20.pw/bnethelp exit } } Checkd() Sleep 2000 Checkd() WinActivate Checkd() ClickFromTopRight(42,200) Send ^a Send {BS} send %email% sleep 20 Sleep 100 ClickFromTopRight(42,250) Sleep 20 ClickFromTopRight(42,250) Send ^a Send {BS} send %passwrd% Send {Enter} exit ClickFromTopRight(_X,_Y){ CoordMode, mouse, Relative WinGetActiveStats, Title, width, height, x,y _X := width - _X Click %_X%, %_Y% }
Add hotkeys for changing keyboard language.
; ahk_class PotPlayer #SC01F::Send {Media_Play_Pause} $+1::Send {!} $+2::Send {@} $+3::Send {#} $+4::Send {$} $+5::Send {`%} $+6::Send {^} ;$+7::Send {&} $+8::Send {*}
#InstallKeybdHook #SingleInstance Force ; ahk_class PotPlayer #SC01F::Send {Media_Play_Pause} $+1::Send {!} $+2::Send {@} $+3::Send {#} $+4::Send {$} $+5::Send {`%} $+6::Send {^} ;$+7::Send {&} $+8::Send {*} GetKeyboardLayout() { HKL := DllCall("GetKeyboardLayout", "UInt", 0, "Ptr") Return HKL } GetKeyboardLayoutName() { VarSetCapacity(Str, 1000) DllCall("GetKeyboardLayoutName", "Str", Str, "Int") Return Str } ActivateKeyboardLayout(HKL) ; This does not work. { ; For initialization, necessary to run only once. DllCall("Ole32.dll\OleInitialize", "Ptr", 0, "Int") DllCall("LoadKeyboardLayout", "Str", "00020409", "Int") T := DllCall("ActivateKeyboardLayout", "UInt", HKL, "UInt", 0x00000000, "PTR") If (!T) { MsgBox, Error } } Capslock:: SetCapsLockState, Off If (Lang = 0) { PostMessage, 0x50, 0, 0xF0020409,, A Lang := 1 } Else { PostMessage, 0x50, 0, 0xF03A0429,, A Lang := 0 } Return <^Capslock:: SetCapsLockState, Off PostMessage, 0x50, 0, 0xF01A0409,, A Return >^Capslock:: SetCapsLockState, Off PostMessage, 0x50, 0, 0xF01B0409,, A Return !Capslock:: T := GetKeyboardLayout() H := Format("{1:X}", T) MsgBox, %T% %H% Return Temp() { ;^1:: ; This line is commented out. T := GetKeyboardLayout() H := Format("{1:X}", T) MsgBox, %T% %H% Return ;^2:: ; This line is commented out. ;ActivateKeyboardLayout(0xF0020409) PostMessage, 0x50, 0, 0xF0020409,, A MsgBox, Done. Return }
Add special characters for Persian keyboard.
; ahk_class PotPlayer #SC01F::Send {Media_Play_Pause}
; ahk_class PotPlayer #SC01F::Send {Media_Play_Pause} $+1::Send {!} $+2::Send {@} $+3::Send {#} $+4::Send {$} $+5::Send {`%} $+6::Send {^} ;$+7::Send {&} $+8::Send {*}
Add reliable setup in conjunction with SharpKeys
FileEncoding, UTF-8 ; This file needs to be saved/encoded with "UTF-8 with BOM" ; Use Swedish characters on US-English keyboard ![:: Send, å !+{:: Send, Å !':: Send, ä !+':: Send, Ä !;:: Send, ö !+;:: Send, Ö ; does not work ; HHKB settings to mimic macOS behavior on Windows ; Lwin = <^ LWin::LCtrl <^Right:: Send, {End} <^Left:: Send, {Home} <^Up:: Send, {PgUp} <^Down:: Send, {PgDn} <^Tab::Send {LWin down}{Tab}{LWin up}
FileEncoding, UTF-8 ; This file needs to be saved/encoded with "UTF-8 with BOM" ; Use Swedish characters on US-English keyboard ![:: Send, å !+{:: Send, Å !':: Send, ä !+':: Send, Ä !;:: Send, ö !+;:: Send, Ö ; does not work ; HHKB settings to mimic macOS behavior on Windows LWin::LCtrl ; this one is better to use SharpKeys for, as it is unreliable here <^Right:: Send, {End} <^Left:: Send, {Home} <^Up:: Send, {PgUp} <^Down:: Send, {PgDn} <+^Up:: Send, {LShift down}{PgUp}{LShift up} <+^Down:: Send, {LShift down}{PgDn}{LShift up} <^Tab::Send {LWin down}{Tab}{LWin up}
Add path onto which to store this file
FileEncoding, UTF-8 ; This file needs to be saved/encoded with "UTF-8 with BOM" ; Use Swedish characters on US-English keyboard ![:: Send, å !+{:: Send, Å !':: Send, ä !+':: Send, Ä !;:: Send, ö !+;:: Send, Ö ; HHKB settings to mimic macOS behavior on Windows LWin::LCtrl ; this one is better to use SharpKeys for, as it is unreliable here <^Right:: Send, {End} <^Left:: Send, {Home} <^Up:: Send, {PgUp} <^Down:: Send, {PgDn} <+^Right:: Send, {LShift down}{End}{LShift up} <+^Left:: Send, {LShift down}{Home}{LShift up} <+^Up:: Send, {LShift down}{PgUp}{LShift up} <+^Down:: Send, {LShift down}{PgDn}{LShift up} ; Windows laptop AppsKey:: Send, {RWin}
; Put this file in ; %APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup FileEncoding, UTF-8 ; This file needs to be saved/encoded with "UTF-8 with BOM" ; Use Swedish characters on US-English keyboard ![:: Send, å !+{:: Send, Å !':: Send, ä !+':: Send, Ä !;:: Send, ö !+;:: Send, Ö ; HHKB settings to mimic macOS behavior on Windows LWin::LCtrl ; this one is better to use SharpKeys for, as it is unreliable here <^Right:: Send, {End} <^Left:: Send, {Home} <^Up:: Send, {PgUp} <^Down:: Send, {PgDn} <+^Right:: Send, {LShift down}{End}{LShift up} <+^Left:: Send, {LShift down}{Home}{LShift up} <+^Up:: Send, {LShift down}{PgUp}{LShift up} <+^Down:: Send, {LShift down}{PgDn}{LShift up} ; Windows laptop AppsKey:: Send, {RWin}
Add ahk-script to duplicate window width (useful with vertical monitors)
+#Up:: WinGetActiveTitle, Title WinRestore, %Title% SysGet, X1, 76 SysGet, Y1, 77 SysGet, Width, 78 SysGet, Height, 79 WinMove, %Title%,, X1, Y1, Width, Height return
Add simple AHK script to test mouse wheel jumping
~WheelDown:: GoingDown := True if GoingUp { MsgBox, , Problem, Mouse wheel is jumping VarSetCapacity(GoingDown,0) } return ~WheelUp:: GoingUp := True if GoingDown { MsgBox, , Problem, Mouse wheel is jumping VarSetCapacity(GoingUp,0) } return
Update for new login window
email = %1% passwrd = %2% Checkd() { WinWait Blizzard App Login, ,3 WinMove 0, 0 WinActivate IfWinNotActive { Checkd() } if ErrorLevel { MsgBox unable to find Battle.net login window. Please record trying to login and report it at j20.pw/bnethelp exit } } Checkd() Sleep 2000 Checkd() WinActivate Checkd() ClickFromTopRight(42,200) Send ^a Send {BS} send %email% sleep 20 Sleep 100 ClickFromTopRight(42,250) Sleep 20 ClickFromTopRight(42,250) Send ^a Send {BS} send %passwrd% Send {Enter} exit ClickFromTopRight(_X,_Y){ CoordMode, mouse, Relative WinGetActiveStats, Title, width, height, x,y _X := width - _X Click %_X%, %_Y% }
Add AHK for leftover debug dialog at completion of install/uninstall
#NoEnv SendMode Input SetWorkingDir %A_ScriptDir% SetTitleMatchMode, 1 ;matches if title begins with string DetectHiddenText, off ;will not search hidden window text DetectHiddenWindows, off ;will not detect hidden windows WinWait, Sandboxie ahk_class #32770, DONE, 120 WinActivate Send,{Enter} ExitApp
Add a script to launch the 'keep window on top' from other programs
#NoTrayIcon #Persistent #SingleInstance force #NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases. ; #Warn ; Enable warnings to assist with detecting common errors. SendMode Input ; Recommended for new scripts due to its superior speed and reliability. SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory. Send !+^{T}
Add AHK script to reset cursor position for all pages in a section
#NoEnv #NoTrayIcon #SingleInstance force #Warn SendMode Input SetTitleMatchMode, 3 SetWorkingDir, %A_ScriptDir% procName := "ONENOTE.EXE" ; Set cursor to page title for all pages in the current section !q:: IfWinActive, ahk_exe %ProcName% { Send !{Home} Loop, 31 { Send ^+T Send {Home} Send ^{PgDn} } }
Add AutoHotkey configuration for np2
; Muhenkan (PC98 NFER key) LWin::Send {vk1D} ; Henkan (PC98 XFER key) ;RWin::Send {vk1C} ;^RWin::Send {vk1C} AppsKey::Send {vk1C} ^AppsKey::Send ^{vk1C} ;Muhenkan / 無変換 -> {vk1D} ;Henkan / 変換 -> {vk1C} ;Kana / かな -> {vkF2} ;IME ON/OF -> {vkF3}, {vkF4}
Add small windows autohotkey script.
Capslock::Ctrl ; Window management #h::SendEvent #{Left} #l::SendEvent #{Right} #j::SendEvent #{Down} #k::SendEvent #{Up} ; Windows Explorer Navigation #IfWinActive, ahk_class CabinetWClass ^h:: ControlGet renamestatus,Visible,,Edit1,A ControlGetFocus focussed, A if(renamestatus!=1&&(focussed=DirectUIHWND3?||focussed=SysTreeView321)) { SendInput {Alt Left} }else{ Send {Backspace} } #IfWinActive
Add new prefixes: feature, refactor and update
#!/usr/bin/awk -f BEGIN { # Determines whether to print 'Unreleased' banner at top UNRELEASED_COMMITS = 1 # Prefixes that determine whether a commit will be printed CHANGELOG_REGEX = "^(changelog|fix|docs|chore|feat): " FS="|" while ("git log --pretty='%D|%s|%H'" | getline) { IS_GIT_TAG = length($1) && match($1, /tag:/) if (IS_GIT_TAG) { UNRELEASED_COMMITS = 0 # Cut out text up to tag sub(/.*tag: /, "", $1) # Cut out text after tag sub(/,.*/, "", $1) print $1 } else { if ( UNRELEASED_COMMITS ) { print "Unreleased" UNRELEASED_COMMITS = 0 } if ( match($2, CHANGELOG_REGEX) ) { sub(CHANGELOG_REGEX, "", $2) printf("\t- %s\n", $2) } } } }
#!/usr/bin/awk -f BEGIN { # Determines whether to print 'Unreleased' banner at top UNRELEASED_COMMITS = 1 # Prefixes that determine whether a commit will be printed CHANGELOG_REGEX = "^(changelog|fix|docs|chore|feat|feature|refactor|update): " FS="|" while ("git log --pretty='%D|%s|%H'" | getline) { IS_GIT_TAG = length($1) && match($1, /tag:/) if (IS_GIT_TAG) { UNRELEASED_COMMITS = 0 # Cut out text up to tag sub(/.*tag: /, "", $1) # Cut out text after tag sub(/,.*/, "", $1) print $1 } else { if ( UNRELEASED_COMMITS ) { print "Unreleased" UNRELEASED_COMMITS = 0 } if ( match($2, CHANGELOG_REGEX) ) { sub(CHANGELOG_REGEX, "", $2) printf("\t- %s\n", $2) } } } }
Make sure newline at end of file
# Print lines from a WebScraper csv file after joining extra newlines # INVOCATION: # awk -f fixExtraLinesFrom-webscraper.awk BritBoxPrograms.csv { if (/^"/) printf ("\n" $0) else printf }
# Print lines from a WebScraper csv file after joining extra newlines # INVOCATION: # awk -f fixExtraLinesFrom-webscraper.awk BritBoxPrograms.csv { if (/^"/) printf ("\n" $0) else printf } END { printf ("\n") }
Update to output in markdown format
#!/usr/bin/awk -f BEGIN { # Determines whether to print 'Unreleased' banner at top UNRELEASED_COMMITS = 1 # Prefixes that determine whether a commit will be printed CHANGELOG_REGEX = "^(changelog|fix|docs|chore|feat|feature|refactor|update): " FS="|" while ("git log --pretty='%D|%s|%H'" | getline) { IS_GIT_TAG = length($1) && match($1, /tag:/) if (IS_GIT_TAG) { UNRELEASED_COMMITS = 0 # Cut out text up to tag sub(/.*tag: /, "", $1) # Cut out text after tag sub(/,.*/, "", $1) print $1 } else { if ( UNRELEASED_COMMITS ) { print "Unreleased" UNRELEASED_COMMITS = 0 } if ( match($2, CHANGELOG_REGEX) ) { sub(CHANGELOG_REGEX, "", $2) printf("\t- %s\n", $2) } } } }
#!/usr/bin/awk -f BEGIN { REPO_URL = getRepoURL() # Prefixes that determine whether a commit will be printed CHANGELOG_REGEX = "^(changelog|fix|docs|chore|feat|feature|refactor|update): " FS="|" # %D: tags # %s: commit message # %H: long hash # %h: short hash while ("git log --pretty='%D|%s|%H|%h'" | getline) { IS_GIT_TAG = length($1) && match($1, /tag:/) if (IS_GIT_TAG) { printTag($1) } else { printCommit($2, $3, $4) } } } function printTag(input) { # Cut out text up to tag sub(/.*tag: /, "", input) # Cut out text after tag sub(/,.*/, "", input) printf("## %s\n", input) } function printCommit(input, longHash, shortHash) { if ( match(input, CHANGELOG_REGEX) ) { sub(CHANGELOG_REGEX, "", input) printf("- %s (%s)\n", input, makeCommitLink(REPO_URL, shortHash, longHash) ) } } function makeCommitLink(repoUrl, shortHash, longHash) { return ("[" shortHash "](" repoUrl "/commit/" longHash ")") } # Get Git repo URL function getRepoURL() { "git config --get remote.upstream.url || git config --get remote.origin.url || git config --get remote.dev.url" | getline REPO_URL sub(/:/, "/", REPO_URL) sub(/git@/, "https://", REPO_URL) sub(/\.git/, "", REPO_URL) return REPO_URL }
Clarify that input must be sorted
#!/usr/bin/env awk -f # # Computes the median. # # Usage: median # # Input: # - a column of numbers # # Output: # - median value BEGIN { i = 0 } { a[i++] = $1 } END { j = i/2 if ( i%2 == 1 ) { median = a[int(j)] } else { median = (a[j] + a[j-1])/2 } print median }
#!/usr/bin/env awk -f # # Computes the median. # # Usage: median # # Input: # - a sorted column of numbers # # Output: # - median value BEGIN { i = 0 } { a[i++] = $1 } END { j = i/2 if ( i%2 == 1 ) { median = a[int(j)] } else { median = (a[j] + a[j-1])/2 } print median }
Exclude any target with "Test" in the name
BEGIN { FS = "\n"; } /Targets:/ { while (getline && $0 != "") { if ($0 ~ /Tests/) continue; sub(/^ +/, ""); print; } }
BEGIN { FS = "\n"; } /Targets:/ { while (getline && $0 != "") { if ($0 ~ /Test/) continue; sub(/^ +/, ""); print; } }
Make this link against gtk+-3.24.4
#!/usr/bin/awk # # Patch the generated wrapper Swift code to handle special cases # BEGIN { depr_init = 0 } /open .* ColorSelection/ { depr_init = 1 } /public .* ColorSelection/ { depr_init = 1 } /public .* HSV/ { depr_init = 1 } /open .* HSV/ { depr_init = 1 } / init.. {/ { if (depr_init) { printf("@available(*, deprecated) ") depr_init = 0 } } / init. title:/ { if (depr_init) { printf("@available(*, deprecated) ") depr_init = 0 } } // { print }
#!/usr/bin/awk # # Patch the generated wrapper Swift code to handle special cases # BEGIN { depr_init = 0 ; comment = 0 } /open .* ColorSelection/ { depr_init = 1 } /public .* ColorSelection/ { depr_init = 1 } /public .* HSV/ { depr_init = 1 } /open .* HSV/ { depr_init = 1 } /open .* HSV/ { depr_init = 1 } /func getColumnHeaderCells/ { comment = 1 } /func getRowHeaderCells/ { comment = 1 } / init.. {/ { if (depr_init) { printf("@available(*, deprecated) ") depr_init = 0 } } / init. title:/ { if (depr_init) { printf("@available(*, deprecated) ") depr_init = 0 } } // { if (comment) { printf("// ") } print } /^ }$/ { comment = 0 }
Revert "Fix bracket expression matches a character at gawk"
BEGIN { print "V1.0 {"; print " global:"; } { # Remove the CR character in case the sources are mapped from # a Windows share and contain CRLF line endings gsub(/\r/,"", $0); # Skip empty lines and comment lines starting with semicolon if (NF && !match($0, /^[[:space:]]*;/)) { print " " $0 ";"; } } END { print " local: *;" print "};"; }
BEGIN { print "V1.0 {"; print " global:"; } { # Remove the CR character in case the sources are mapped from # a Windows share and contain CRLF line endings gsub(/\r/,"", $0); # Skip empty lines and comment lines starting with semicolon if (NF && !match($0, /^[:space:]*;/)) { print " " $0 ";"; } } END { print " local: *;" print "};"; }
Include header files whose path begins with ../ .
#!/bin/awk # # $Id$ { if (NR == 1) { print } else { for (i = 1; i <= NF; i++) { if ($i ~ /^include\// || $i ~ /^src\// || $i ~ /^obj\// || $i == "\\") printf " " $i } print "" } }
#!/bin/awk # # $Id$ { if (NR == 1) { print } else { for (i = 1; i <= NF; i++) { if ($i ~ /^include\// || $i ~ /^src\// || $i ~ /^obj\// || $i ~ /^\.\.\// || $i == "\\") printf " " $i } print "" } }
Fix an output formatting bug in the rewriter script.
BEGIN{ now = systime() format = "%Y/%m/%d %H:%M:%S" } { split($1, DATE, "/") split($2, TIME, ":") $1 = "" $2 = "" t = mktime(DATE[1] " " DATE[2] " " DATE[3] " " TIME[1] " " TIME[2] " " TIME[3]) if (delta == "") { delta = now - t } print strftime(format, t + delta) $0 }
BEGIN{ now = systime() format = "%Y/%m/%d %H:%M:%S" } { split($1, DATE, "/") split($2, TIME, ":") t = mktime(DATE[1] " " DATE[2] " " DATE[3] " " TIME[1] " " TIME[2] " " TIME[3]) if (delta == "") { delta = now - t } out = strftime(format, t + delta) for (i = 3; i <= NF; i++) { out = out OFS $i } print out }
Fix awk script to work with cairo generated postscript
BEGIN{doit = 0} { if (doit) print $0 } $0 == "%%EndSetup" { doit = 1 }
BEGIN{doit = 0} { if (doit) print $0 } $0 = /%%End.*Setup/ { doit = 1 }
Add year differentation into monthly report
#!/usr/bin/awk -f BEGIN { FS = "," } $1 == "pld" { p += $2 } $1 == "val" { v += $2 } { "date -d "$3" +%B" | getline month monthly[month][$1] += $2 categorically[$1][$4] += $2 } END { print "Val spent "v"€" print "PLD spent "p"€" if ( p < v ) print "PLD owe "v - p"€ to val." else if ( p > v ) print "Val owe "p - v"€ to PLD." else print "Accounts are balanced." print "" if ( verbose == 1 ) { print "Here's the detail:" print " Spendings per month:" for ( month in monthly ) { print " In "month":" for ( who in monthly[month] ) { print " "who" spent "monthly[month][who]"€." } } print " Spendings by category:" for ( who in categorically ) { print " By "who":" for ( category in categorically[who] ) { print " "categorically[who][category]"€ in "category"." } } } }
#!/usr/bin/awk -f BEGIN { FS = "," } $1 == "pld" { p += $2 } $1 == "val" { v += $2 } { "date -d "$3" '+%B %Y'" | getline month_and_year monthly[month_and_year][$1] += $2 categorically[$1][$4] += $2 } END { print "Val spent "v"€" print "PLD spent "p"€" if ( p < v ) print "PLD owe "v - p"€ to val." else if ( p > v ) print "Val owe "p - v"€ to PLD." else print "Accounts are balanced." print "" if ( verbose == 1 ) { print "Here's the detail:" print " Spendings per month:" for ( month_and_year in monthly ) { print " In "month_and_year":" total_for_month = 0 for ( who in monthly[month_and_year] ) { spent = monthly[month_and_year][who] print " "who" spent "spent"€." total_for_month += spent } print " Total: "total_for_month"€." } print " Spendings by category:" for ( who in categorically ) { print " By "who":" for ( category in categorically[who] ) { print " "categorically[who][category]"€ in "category"." } } } }
Support also different version of Hadoop (=Fedora).
# # Parsing output of: # # hdfs dfs -du -s '/user/*' # function dbstr(s) { if (s) { return "'" s "'" } else { return "NULL" } } function dbi(i) { if (i >= 0) { return i } else { return "NULL" } } BEGIN { FS="[ \t/]+" print "INSERT INTO measure (name) VALUES ('quota');"; } { used=$1 user=$4 print "INSERT INTO quota (id_measure, user, used) VALUES (last_insert_id(), " dbstr(user) ", " dbi(used) ");" }
# # Parsing output of: # # hdfs dfs -du -s '/user/*' # function dbstr(s) { if (s) { return "'" s "'" } else { return "NULL" } } function dbi(i) { if (i >= 0) { return i } else { return "NULL" } } BEGIN { FS="[ \t/]+" print "INSERT INTO measure (name) VALUES ('quota');"; } /^[0-9]+[ ]+[0-9]+[ ]+\/.*/ { used=$1 user=$4 print "INSERT INTO quota (id_measure, user, used) VALUES (last_insert_id(), " dbstr(user) ", " dbi(used) ");" } /^[0-9]+[ ]+\/.*/ { used=$1 user=$3 print "INSERT INTO quota (id_measure, user, used) VALUES (last_insert_id(), " dbstr(user) ", " dbi(used) ");" }
Add identifier KEY so we can see where we are in -v script
{ title = $0 if (match (title, /, The"$/)) { sub (/^"/,"\"The ", title) sub (/, The"$/,"\"", title) } printf ("echo ==\\> %3d: %s\n",NR,title) >> TITLES_SCRIPT printf ("./getIMDbInfoFrom-titles.py %s\n",title) >> TITLES_SCRIPT printf ("echo \n\n") >> TITLES_SCRIPT printf ("echo ==\\> %3d: %s\n",NR,title) >> ID_SCRIPT printf ("./getIMDb_IDsFrom-titles.py %s | head -7\n",title) >> ID_SCRIPT printf ("echo \n\n") >> ID_SCRIPT }
{ title = $0 if (match (title, /, The"$/)) { sub (/^"/,"\"The ", title) sub (/, The"$/,"\"", title) } if (FILENAME ~ /Acorn/) KEY = "A" if (FILENAME ~ /BBox/) KEY = "B" if (FILENAME ~ /MHz/) KEY = "M" if (FILENAME ~ /Watched/) KEY = "W" printf ("echo ==\\> %sT %3d: %s\n", KEY, NR, title) >> TITLES_SCRIPT printf ("./getIMDbInfoFrom-titles.py %s\n",title) >> TITLES_SCRIPT printf ("echo \n\n") >> TITLES_SCRIPT printf ("echo ==\\> %sI %3d: %s\n", KEY, NR, title) >> ID_SCRIPT printf ("./getIMDb_IDsFrom-titles.py %s | head -7\n",title) >> ID_SCRIPT printf ("echo \n\n") >> ID_SCRIPT }
Add a close command to avoid too many files opened problems (encountered with large libpcap file)
BEGIN { session_count = 0; FS="|" OFS="|" } { if ($3 ~ "[0-9]+") { # See if the current line is already in the table frame_file = destDir "/frames/Frame"$3".html" session_line = "" "grep -i \"" session_token "\" " frame_file | getline session_line if (session_line == "" ) { $6 = "{0}" print $0 } else { found = 0; split(session_line, array, " ") session = array[2] for (i=0; i < session_count; i++) { if (sessions[i] == session) { found = 1 $6 = "{" i+1 "}" print $0 break } } if (found == 0) { $6 = "{" session_count+1 "}" sessions[session_count++] = session print $0 s = sprintf("echo '%2d: new session in frame %4s: %s' >&2", session_count, $3, session) system(s) } } } else { # Comment line, line starting with "#". # Requires no processing, just print it print $0 } }
BEGIN { session_count = 0; FS="|" OFS="|" } { if ($3 ~ "[0-9]+") { # See if the current line is already in the table frame_file = destDir "/frames/Frame"$3".html" session_line = "" "grep -i \"" session_token "\" " frame_file | getline session_line close(grep) if (session_line == "" ) { $6 = "{0}" print $0 } else { found = 0; split(session_line, array, " ") session = array[2] for (i=0; i < session_count; i++) { if (sessions[i] == session) { found = 1 $6 = "{" i+1 "}" print $0 break } } if (found == 0) { $6 = "{" session_count+1 "}" sessions[session_count++] = session print $0 s = sprintf("echo '%2d: new session in frame %4s: %s' >&2", session_count, $3, session) system(s) } } } else { # Comment line, line starting with "#". # Requires no processing, just print it print $0 } }
Define KEY_MAX for Python. (dm)
############################################################################### # BRLTTY - A background process providing access to the console screen (when in # text mode) for a blind person using a refreshable braille display. # # Copyright (C) 1995-2006 by The BRLTTY Developers. # # BRLTTY comes with ABSOLUTELY NO WARRANTY. # # This is free software, placed under the terms of the # GNU General Public License, as published by the Free Software # Foundation. Please see the file COPYING for details. # # Web Page: http://mielke.cc/brltty/ # # This software is maintained by Dave Mielke <dave@mielke.cc>. ############################################################################### /#define[ \t]*BRLAPI_KEY_[A-Z_]+_MASK/ { apiMask(substr($2, 12), $2, getDefineValue(), "") next } /#define[ \t]*BRLAPI_KEY_[A-Z_]+_SHIFT/ { apiShift(substr($2, 12), $2, getDefineValue(), "") next } /#define[ \t]*BRLAPI_KEY_TYPE_/ { apiType(substr($2, 17), $2, getDefineValue(), "") next } /#define[ \t]*BRLAPI_KEY_SYM_/ { apiKey(substr($2, 16), $2, getDefineValue(), "") next }
############################################################################### # BRLTTY - A background process providing access to the console screen (when in # text mode) for a blind person using a refreshable braille display. # # Copyright (C) 1995-2006 by The BRLTTY Developers. # # BRLTTY comes with ABSOLUTELY NO WARRANTY. # # This is free software, placed under the terms of the # GNU General Public License, as published by the Free Software # Foundation. Please see the file COPYING for details. # # Web Page: http://mielke.cc/brltty/ # # This software is maintained by Dave Mielke <dave@mielke.cc>. ############################################################################### /#define[ \t]*BRLAPI_KEY_MAX/ { apiMask(substr($2, 12), $2, getDefineValue(), "") next } /#define[ \t]*BRLAPI_KEY_[A-Z_]+_MASK/ { apiMask(substr($2, 12), $2, getDefineValue(), "") next } /#define[ \t]*BRLAPI_KEY_[A-Z_]+_SHIFT/ { apiShift(substr($2, 12), $2, getDefineValue(), "") next } /#define[ \t]*BRLAPI_KEY_TYPE_/ { apiType(substr($2, 17), $2, getDefineValue(), "") next } /#define[ \t]*BRLAPI_KEY_SYM_/ { apiKey(substr($2, 16), $2, getDefineValue(), "") next }
Use a file name prefix for generated labels
#!/usr/bin/awk -f # # Adds github compatible labels to level 1 and 2 markdown headings # in underline style. # # # Substitute github references with doxygen references. # /\(#[_a-z0-9-]*\)/ { gsub(/\(#[_a-z0-9-]*\)/, "<__REF__&__REF__>") gsub(/<__REF__\(#/, "(@ref ") gsub(/\)__REF__>/, ")") } # # If this line is underlining a heading, add a label to the previous # line. # line && (/^===*$/ || /^---*$/) { id = tolower(line) gsub(/[^_a-z0-9]+/, "-", id) line = line " {#" id "}" } # # Print the previous line, after a label might have been added. # {print line} # # Remember this line when scanning the next one for underlining. # {line = $0} # # Print the last line. # END { print }
#!/usr/bin/awk -f # # Adds github compatible labels to level 1 and 2 markdown headings # in underline style. # # # Get file name prefix for references. # filename != FILENAME { filename = FILENAME # strip path "pwd" | getline path path = path "/" prefix = substr(filename, 1, length(path)) == path \ ? substr(filename, length(path) + 1) \ : filename sub(/\.[^.]*$/, "", prefix) gsub(/[^_a-z0-9]+/, "-", prefix) prefix = "md_" prefix "_" } # # Substitute github references with doxygen references. # /\(#[_a-z0-9-]*\)/ { gsub(/\(#[_a-z0-9-]*\)/, "<__REF__&__REF__>") gsub(/<__REF__\(#/, "(@ref " prefix) gsub(/\)__REF__>/, ")") } # # If this line is underlining a heading, add a label to the previous # line. # line && (/^===*$/ || /^---*$/) { id = tolower(line) gsub(/[^_a-z0-9]+/, "-", id) line = line " {#" prefix id "}" } # # Print the previous line, after a label might have been added. # {print line} # # Remember this line when scanning the next one for underlining. # {line = $0} # # Print the last line. # END { print }
Fix an awk script that doesn't seem to be very portable
BEGIN { } function extension(str){ n = split(str, parts, ".") if (n == 1){ return "<NO EXTENSION>" } else { return parts[n] } } $2 != "total" { by_type[extension($2)] += $1 } $2 ~ "CMakeLists.txt" { #cmake should not count as text by_type["txt"] -= $1 by_type["cmake"] += $1 } $2 ~ "test" { by_type[extension($2)] -= $1 by_type["TEST"] += $1 } END { # join up cpp types by_type["cpp"] += by_type["hpp"] delete by_type["hpp"] #get rid of some filetypes I dont care about delete by_type["gitignore"] delete by_type["jpg"] delete by_type["png"] delete by_type["ttf"] delete by_type["pdf"] #print each extension, collect the total total=0 for (x in by_type) { if (by_type[x] > 0) { total += by_type[x] print (x, by_type[x]) } } print("Total:", total) }
BEGIN { } function getExtension(str){ n = split(str, parts, ".") if (n == 1){ return "<NO EXTENSION>" } else { return parts[n] } } $2 != "total" { by_type[getExtension($2)] += $1 } $2 ~ "CMakeLists.txt" { #cmake should not count as text by_type["txt"] -= $1 by_type["cmake"] += $1 } $2 ~ "test" { by_type[getExtension($2)] -= $1 by_type["TEST"] += $1 } END { # join up cpp types by_type["cpp"] += by_type["hpp"] delete by_type["hpp"] #get rid of some filetypes I dont care about delete by_type["gitignore"] delete by_type["jpg"] delete by_type["png"] delete by_type["ttf"] delete by_type["pdf"] #print each getExtension, collect the total total=0 for (x in by_type) { if (by_type[x] > 0) { total += by_type[x] print (x, by_type[x]) } } print("Total:", total) }
Fix the modules path in the xpi chrome.manifests
{ content = $1 ~ /^(content|skin|locale)$/ } content && $NF ~ /^[a-z]/ { $NF = "/" name "/" $NF } content { sub(/^\.\./, "", $NF); $NF = "jar:chrome/" name ".jar!" $NF } { sub("^\\.\\./liberator/", "", $NF) print }
{ content = $1 ~ /^(content|skin|locale)$/ } content && $NF ~ /^[a-z]/ { $NF = "/" name "/" $NF } content { sub(/^\.\./, "", $NF); $NF = "jar:chrome/" name ".jar!" $NF } { sub("^\\.\\./common/", "", $NF) print }
Print last two lines in Avg
# Generate MHz_TV_Shows_minutes.csv by processing SHORT_SPREADSHEET to figure # average episode length # BEGIN { FS = "\t" } /^Title/ { printf ("%s\t%s\t%s\t%s\tAvg Len\t%s\t%s\t%s\t%s\t%s\n", $1,$2,$3,$4,$5,$6,$7,$8,$9) } /=HYPERLINK/ { dur=$4 sub (/h/,"",dur) sub (/m/,"",dur) split (dur,fld," ") eplen = (fld[1]*60+fld[2])/$3 printf ("%s\t%s\t%s\t%s\t%d\t%s\t%s\t%s\t%s\t%s\n", $1,$2,$3,$4,eplen,$5,$6,$7,$8,$9) }
# Generate MHz_TV_Shows_minutes.csv by processing SHORT_SPREADSHEET to figure # average episode length # BEGIN { FS = "\t" } /^Title/ { printf ("%s\t%s\t%s\t%s\tAvg Len\t%s\t%s\t%s\t%s\t%s\n", $1,$2,$3,$4,$5,$6,$7,$8,$9) } /=HYPERLINK/ { dur=$4 sub (/h/,"",dur) sub (/m/,"",dur) split (dur,fld," ") eplen = (fld[1]*60+fld[2])/$3 printf ("%s\t%s\t%s\t%s\t%d\t%s\t%s\t%s\t%s\t%s\n", $1,$2,$3,$4,eplen,$5,$6,$7,$8,$9) } /^Non-blank values/ || /^Total seasons & episodes/ { print }
Handle mscorwks_unixexports.src with better regexp operator for compatibility
BEGIN { print "V1.0 {"; print " global:"; } { # Remove the CR character in case the sources are mapped from # a Windows share and contain CRLF line endings gsub(/\r/,"", $0); # Skip empty lines and comment lines starting with semicolon if (NF && !match($0, /^[:space:]*;/)) { print " " $0 ";"; } } END { print " local: *;" print "};"; }
BEGIN { print "V1.0 {"; print " global:"; } { # Remove the CR character in case the sources are mapped from # a Windows share and contain CRLF line endings gsub(/\r/,"", $0); # Skip empty lines and comment lines starting with semicolon if (NF && !match($0, /^[ \t]*;/)) { print " " $0 ";"; } } END { print " local: *;" print "};"; }
Fix for symbol table demangled names with spaces
# # Converts the output of 'nm' into a C source containing an array of symbols # that correspond to functions (t and T in terms of 'nm'). # # Usage: # nm -n image | awk -f nm2c.awk # # Date: Aug 28, 2012 # Author: Eldar Abusalimov # BEGIN { print "/* Auto-generated file. Do not edit. */"; print ""; print "#include <debug/symbol.h>"; print "#include <stddef.h>"; print ""; print "const struct symbol __symbol_table[] = {"; } /^[0-9a-fA-F]* [tT]/ { printf "\t{ (void *) 0x%s, \"%s\" },\n", $1, $3; } END { print "};"; print "const size_t __symbol_table_size ="; print "\tsizeof(__symbol_table) / sizeof(__symbol_table[0]);"; print ""; }
# # Converts the output of 'nm' into a C source containing an array of symbols # that correspond to functions (t and T in terms of 'nm'). # # Usage: # nm -n image | awk -f nm2c.awk # # Date: Aug 28, 2012 # Author: Eldar Abusalimov # BEGIN { print "/* Auto-generated file. Do not edit. */"; print ""; print "#include <debug/symbol.h>"; print "#include <stddef.h>"; print ""; print "const struct symbol __symbol_table[] = {"; } /^[0-9a-fA-F]* [tT]/ { split($0,a," [tT] "); printf "\t{ (void *) 0x%s, \"%s\" },\n", $1, a[2]; } END { print "};"; print "const size_t __symbol_table_size ="; print "\tsizeof(__symbol_table) / sizeof(__symbol_table[0]);"; print ""; }
Fix the pair generation and also speed up the sorting
#!/usr/bin/awk -f BEGIN { FS = OFS = "\t"; } { len = split($3, words, ", "); if (length(N) > 0 && len >= N) next; for (i = 1; i <= len - 1; i++) { for (j = i + 1; j <= len; j++) { print words[i], words[j], ORS, words[j], words[i] | "sort --parallel=$(nproc) -us"; } } }
#!/usr/bin/awk -f BEGIN { FS = "\t"; OFS = ""; } { len = split($3, words, ", "); if (length(N) > 0 && len >= N) next; for (i = 1; i <= len - 1; i++) { for (j = i + 1; j <= len; j++) { print words[i], FS, words[j], ORS, words[j], FS, words[i] | "sort --parallel=$(nproc) -S1G -us"; } } }
Handle cases where system time is adjusted backwards (e.g. by NTP).
{ if (1==NR) { startTimestamp = substr($1, 2, length($1) - 2) printf(";$FILEVERSION=1.3\n") printf(";$STARTTIME=%u.%u\n", mktime(strftime("%Y %m %d 0 0 0", startTimestamp)) / 86400 + 25569, \ 10000000000 / 86400 * (mktime(strftime("%Y %m %d %H %M %S", startTimestamp)) - mktime(strftime("%Y %m %d 0 0 0", startTimestamp)))) } printf("%u) %.3f 1 Rx %s - %s", NR, (substr($1, 2, length($1) - 2) - startTimestamp) * 1000, $3, substr($4, 2, length($4) - 2)) if (5<=NF) { for(i=5;i<=NF;i++) { printf " "$i } } printf "\n" }
{ if (1==NR) { startTimestamp = substr($1, 2, length($1) - 2) printf(";$FILEVERSION=1.3\n") printf(";$STARTTIME=%u.%u\n", mktime(strftime("%Y %m %d 0 0 0", startTimestamp)) / 86400 + 25569, \ 10000000000 / 86400 * (mktime(strftime("%Y %m %d %H %M %S", startTimestamp)) - mktime(strftime("%Y %m %d 0 0 0", startTimestamp)))) currentTimeOffset = 0.0 } else { previousTimeOffset = currentTimeOffset currentTimestamp = substr($1, 2, length($1) - 2) currentTimeOffset = currentTimestamp - startTimestamp if (currentTimeOffset < 0) { startTimestamp = currentTimestamp + currentTimeOffset currentTimeOffset = previousTimeOffset } } printf("%u) %.3f 1 Rx %s - %s", NR, currentTimeOffset * 1000, $3, substr($4, 2, length($4) - 2)) if (5<=NF) { for(i=5;i<=NF;i++) { printf " "$i } } printf "\n" }
Mark CVaListPointer array generators as unavailable on Linux
#!/usr/bin/awk # # Patch the generated wrapper Swift code to handle special cases # BEGIN { etpInit = 0 } /public convenience init.T: ErrorTypeProtocol./ { etpInit = 1 print " /// Convenience copy constructor, creating a unique copy" print " /// of the passed in Error. Needs to be freed using free()" print " /// (automatically done in deinit if you use ErrorType)." } /self.init.other.ptr./ { if (etpInit) { print " self.init(g_error_copy(other.ptr))" etpInit = 0 next } } /no reference counting for GError, cannot ref/ { next } /no reference counting for GError, cannot unref/ { print " g_error_free(error_ptr)" next } / -> GIConv {/, /^}/ { sub(/GIConv {/,"GIConv? {") sub(/return rv/,"return rv == unsafeBitCast(-1, to: GIConv.self) ? nil : rv") } // { print }
#!/usr/bin/awk # # Patch the generated wrapper Swift code to handle special cases # BEGIN { etpInit = 0 ; vaptrptr = 0 } /public convenience init.T: ErrorTypeProtocol./ { etpInit = 1 print " /// Convenience copy constructor, creating a unique copy" print " /// of the passed in Error. Needs to be freed using free()" print " /// (automatically done in deinit if you use ErrorType)." } /self.init.other.ptr./ { if (etpInit) { print " self.init(g_error_copy(other.ptr))" etpInit = 0 next } } /no reference counting for GError, cannot ref/ { next } /no reference counting for GError, cannot unref/ { print " g_error_free(error_ptr)" next } / -> GIConv {/, /^}/ { sub(/GIConv {/,"GIConv? {") sub(/return rv/,"return rv == unsafeBitCast(-1, to: GIConv.self) ? nil : rv") } /UnsafeMutablePointer.CVaListPointer/ { vaptrptr = 1 print "#if !os(Linux)" } /^$/ { if (vaptrptr) { print "#endif" vaptrptr = 0 } } /\/\/\// { if (vaptrptr) { print "#endif" vaptrptr = 0 } } // { print }
Check named_enable rather than just named_flags. PR: 3893 (sort of)
# $Id: ndcedit.awk,v 1.4 1997/02/22 16:08:19 peter Exp $ NR == 3 { print "#" print "# This file is generated automatically, do not edit it here!" print "# Please change src/usr.sbin/ndc/ndcedit.awk instead" print "#" print "" print "# If there is a global system configuration file, suck it in." print "if [ -f /etc/rc.conf ]; then" print "\t. /etc/rc.conf" print "fi\n" } { if ($1 == "named") { printf "\t\t# $namedflags is imported from /etc/rc.conf\n" printf "\t\tif [ \"X${named_flags}\" != X\"NO\" ]; then\n" printf "\t\t\tnamed ${named_flags} && {\n" getline printf "\t%s\n", $0 getline printf "\t%s\n", $0 getline printf "\t%s\n", $0 printf "\t\tfi\n" } else { if (/PATH=/) { gsub(":/usr/ucb:", ":", $0); if (!/export/) { $0=$0"\nexport PATH"; } } print; } }
# $Id: ndcedit.awk,v 1.5 1997/05/27 07:19:57 jkh Exp $ NR == 3 { print "#" print "# This file is generated automatically, do not edit it here!" print "# Please change src/usr.sbin/ndc/ndcedit.awk instead" print "#" print "" print "# If there is a global system configuration file, suck it in." print "if [ -f /etc/rc.conf ]; then" print "\t. /etc/rc.conf" print "fi\n" } { if ($1 == "named") { printf "\t\t# $named_flags is imported from /etc/rc.conf\n" printf "\t\tif [ \"X${named_enable}\" = X\"YES\" ]; then\n" printf "\t\t\tnamed ${named_flags} && {\n" getline printf "\t%s\n", $0 getline printf "\t%s\n", $0 getline printf "\t%s\n", $0 printf "\t\tfi\n" } else { if (/PATH=/) { gsub(":/usr/ucb:", ":", $0); if (!/export/) { $0=$0"\nexport PATH"; } } print; } }
Fix extra comma in json file
BEGIN { FS = "\"" } /\/us\/movie\// { numMovies += 1 shortURL = $6 printf ("%s \"https://www.britbox.com%s\"", trailingComma, shortURL) >> EPISODES_JSON_FILE trailingComma = ",\n" } /\/us\/show\// { numShows += 1 shortURL = $6 printf ("%s \"https://www.britbox.com%s\"", trailingComma, shortURL) >> EPISODES_JSON_FILE printf ("%s \"https://www.britbox.com%s\"", trailingComma, shortURL) >> SEASONS_JSON_FILE trailingComma = ",\n" } END { print "" >> EPISODES_JSON_FILE print "" >> SEASONS_JSON_FILE print "==> Found " numMovies " movies" print "==> Found " numShows " shows" }
BEGIN { FS = "\"" } /\/us\/movie\// { numMovies += 1 shortURL = $6 printf ("%s \"https://www.britbox.com%s\"", trailingEpisodesComma, shortURL) \ >> EPISODES_JSON_FILE trailingEpisodesComma = ",\n" } /\/us\/show\// { numShows += 1 shortURL = $6 printf ("%s \"https://www.britbox.com%s\"", trailingEpisodesComma, shortURL) \ >> EPISODES_JSON_FILE trailingEpisodesComma = ",\n" printf ("%s \"https://www.britbox.com%s\"", trailingSeasonsComma, shortURL) \ >> SEASONS_JSON_FILE trailingSeasonsComma = ",\n" } END { print "" >> EPISODES_JSON_FILE print "" >> SEASONS_JSON_FILE print "==> Found " numMovies " movies" print "==> Found " numShows " shows" }
Add script for generating vendor header include lines
# Usage: awk -f <this_script> vendor/MKxxxx.h vendor/MKxxyy.h vendor/MKzzz.h ... /Processor[s]?:/ { i=0; if (FNR == NR) { printf "#if"; } else { printf "#elif"; } while(match($0, /MK.*/)) { if (i>0) { printf " || \\\n "; } printf " defined(CPU_MODEL_%s)", substr($0, RSTART, RLENGTH); getline; i++; } printf("\n#include \"%s\"\n", FILENAME); nextfile; } END { print "#endif" }
Add new script for gln testing report
#!/usr/bin/awk -f # cat *.tdb | tdbout -t publisher,plugin,publisher:info[tester],status BEGIN { FS="\t" pn = 0 } { nn = split($2,na,/\./) lp2 = na[nn] if (!(($1,lp2) in b)) { p[pn] = $1 n[pn] = lp2 # n[pn] = $2 r[pn] = $3 pn++ } b[$1,lp2]++ c[$1,lp2,$4]++ x[$4]++ tt++ } END { s[0] = "expected" s[1] = "exists" s[2] = "manifest" s[3] = "wanted" s[4] = "crawling" s[5] = "testing" s[6] = "notReady" s[7] = "released" s[8] = "down" s[9] = "superseded" s[10] = "zapped" sn = 11 sc[0] = "expe" sc[1] = "exis" sc[2] = "mani" sc[3] = "want" sc[4] = "craw" sc[5] = "test" sc[6] = "notR" sc[7] = "rele" sc[8] = "down" sc[9] = "supe" sc[10] = "zapp" scn = 11 #print out header printf "Publisher\tPlugin\tT\tTotal" for (j = 0 ; j < scn ; j++) { if (x[s[j]] > 0) { printf "\t%s", sc[j] } } printf "\n" #print out publisher, plugin, tester, total aus for (i = 0 ; i < pn ; i++) { printf "%s\t%s\t%s\t%d", p[i], n[i], r[i], b[p[i],n[i]] for (j = 0 ; j < sn ; j++) { if (x[s[j]] > 0){ if (c[p[i],n[i],s[j]] == 0) { printf "\t.." } else { printf "\t%d", c[p[i],n[i],s[j]] } } } printf "\n" } #print out bottom line sums printf "Publisher\tPlugin\tT\t%d", tt for (j = 0 ; j < sn ; j++) { if (x[s[j]] > 0) { printf "\t%d", x[s[j]] } } printf "\n" }
Add AWK script to generate a frequency table from a column of numbers
#!/usr/bin/env awk -f # # Generates a frequency table. # # Usage: frequency_table # # Input: # - a column of numbers # # Output: # - frequency table { total += 1 table[$1] += 1 } END { for (v in table) { count = table[v] print v OFS count OFS count/total } }