Skip to content

Instantly share code, notes, and snippets.

@caub
caub / sublimetext.md
Last active Apr 12, 2019
VSCode's Format on save for SublimeText
View sublimetext.md

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): 
    if "TypeScript" in view.settings().get("syntax") or "JavaScript" in view.settings().get("syntax"):
      view.run_command("typescript_format_document")
@caub
caub / zendesk-chat.js
Last active Mar 26, 2019
Zendesk Chat API issue
View zendesk-chat.js
const fetch = require('node-fetch');
const cp = require('child_process');
const http = require('http');
// const ZENDESK_KEY = process.env.ZENDESK_KEY || '..........';
const ZENDESK_USER = process.env.ZENDESK_KEY || 'cyril.auburtin@ultimate.ai';
const ZENDESK_PASSWORD = process.env.ZENDESK_PASSWORD || '..........';
// const basicAuth = Buffer.from(`${ZENDESK_USER}/token:${ZENDESK_KEY}`).toString('base64');
const ZENDESK_SUBDOMAIN = process.env.ZENDESK_SUBDOMAIN || 'd3v-ultimateai';
const ZENDESK_OAUTH_CLIENT_ID = process.env.ZENDESK_OAUTH_CLIENT_ID || 'ultimate.ai_zendesk';
View 4.js
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 Oct 15, 2018
https with letsencrypt
View server.js
// 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
Don't use redux-saga
View promise-middleware.js
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) {
View BetterMap.js
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);
View new unicode regex flags.js
// ## 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>...')
View downloadFromFs.js
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
View apollo.js
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
Dataloader knex benchmark
View _output
mapTo: 428.186ms
mapTo2: 319.058ms
ord: 348.390ms
mapToMany: 786.141ms
mapToMany2: 780.661ms
ord agg: 31856.442ms
You can’t perform that action at this time.