Skip to content

Instantly share code, notes, and snippets.

@caub
caub / sublimetext.md
Last active April 15, 2021 19:31
VSCode's Format on save for SublimeText

requirement: TypeScript package should be installed

Step 1: Create a new plugin (Tools > Developer > new plugin) with the following, save it as format-on-save.py for example:

import sublime
import sublime_plugin

class FormatTypescriptOnSave(sublime_plugin.EventListener):
  def on_pre_save(self, view): 
@caub
caub / zendesk-chat.js
Last active November 15, 2021 17:23
Zendesk Chat API
const http = require('http');
const fetch = require('node-fetch');
const getToken = () => new Promise((resolve, reject) => {
const server = http.createServer(async (req, res) => {
res.end();
const params = new URLSearchParams(req.url.slice(1));
console.log('rec', req.url, params);
if (params.has('code')) {
resolve(params.get('code'));
var formatDate = d=>`${d.getFullYear()}-${`${d.getMonth()+1}`.padStart(2,0)}-${`${d.getDate()}`.padStart(2,0)}`
var es=document.body.textContent.trim().split('\n').map(l => {let [,d,s]=l.split(/\[|\] /g); return {d: new Date(d), s}}).sort((a,b)=>a.d-b.d)
var xs=es.map(({d,s}) => { let m=d.getMinutes(); if (d.getHours()===23){d.setDate(d.getDate()+1);m=0;} return {date: formatDate(d), m,d,s}} )
var days=xs.reduce((o,{date,m,s})=>{const slots=o[date]&&o[date].slots||Array.from({length:60},()=>0); let g=s.match(/#\d+/); if (s.startsWith('falls')){for(let i=m;i<slots.length;i++)slots[i]=1} if (s.startsWith('wakes')){for(let i=m;i<slots.length;i++)slots[i]=0} return {...o,[date]:{...o[date],slots,...g&&{guard:g[0]}}} }, {})
var guards=Object.values(days).reduce((o, {slots,guard}) => {let name=guard.slice(1); const sleeptime=o[name]||0; return {...o,[name]:sleeptime+slots.reduce((a,b)=>a+b)};}, {})
var ds = Object.entries(days).filter(([date, o]) => o.guard==='#2593').map(([date, {slots}]) => slots)
Math.max(...ds.
@caub
caub / server.js
Last active October 15, 2018 06:41
https with letsencrypt
// d run -d --name=ok -p 443:6100 -p 80:6000 --workdir=/home/node -v /etc/letsencrypt/:/etc/letsencrypt/:ro -v $PWD/server.js:/home/node/server.js node node server
var https = require("https");
var http = require("http");
var fs = require("fs");
var p="/etc/letsencrypt/live/ulti.pw/";
var hs=https.createServer({
key: fs.readFileSync(p+"privkey.pem")+"",
@caub
caub / promise-middleware.js
Created May 22, 2018 17:58
Don't use redux-saga
const promiseMiddleware = store => next => action => {
if (typeof action.then === 'function') {
return Promise.resolve(action).then(next);
} else if (action.value && typeof action.value.then === 'function') {
return Promise.resolve(action.value).then(value => next({ type: action.type, value }));
}
// else, not a promise
try {
return next(action);
} catch (e) {
export default class BetterMap {
constructor(data) {
this.m = new Map(Array.isArray(data) || data instanceof Map ? data : Object.entries(data));
}
set(k, v) { // return BetterMap
this.m.set(k, v);
return new SortableMap(this.m);
}
delete(k) { // return BetterMap
this.m.delete(k, v);
// ## like \1 but named:
/(?<fruit>apple|fig)==\k<fruit>/u.test('fig==fig')
// true
// ## named group captures:
'we can'.replace(/(?<subject>\w+) (?<verb>\w+)/u, '$<subject>...$<verb>')
//"we...can"
'yes, we can'.replace(/(?<w>\w+)[,\s]+/gu, '$<w>...')
const DIR = os.homedir() + '/.foo';
// adapted from https://stackoverflow.com/a/24977085/3183756
const downloadFromFs = (req, res) => {
const { name } = req.params;
const filePath = path.join(DIR, name);
fs.stat(filePath, (err, stats) => {
if (err) {
if (err.code === 'ENOENT') {
// 404 Error if file not found
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
const TodoApp = ({ loading, error, data: { todos, refetch }, ...props }) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return (
<div {...props}>
<button onClick={() => refetch()}>Refresh</button>
<ul>{todos && todos.map(todo => <li key={todo.id}>{todo.text}</li>)}</ul>
@caub
caub / _output
Last active May 16, 2018 18:11
Dataloader knex benchmark
mapTo: 428.186ms
mapTo2: 319.058ms
ord: 348.390ms
mapToMany: 786.141ms
mapToMany2: 780.661ms
ord agg: 31856.442ms