Home / Cheat sheets / MAD2
Code patterns and facts collected automatically from the lessons. Print it, or read it the night before an exam or viva.
typeof null -> "object"; typeof NaN -> "number"; Array.isArray(x)false 0 -0 0n "" null undefined NaN"5" + 3 -> "53"; "5" - 3 -> 2; 1 + 2 + "3" -> "33"for (const v of arr) values; for (const k in obj) keys (strings)arr.reduce((acc, x) => acc + x, 0); arr.map(f); arr.filter(f)const { a, b: { c } } = obj; const [x, y] = arr; { ...obj, k: v } [...arr, v]JSON.stringify(obj) / JSON.parse(text)document.querySelector("#id"), el.addEventListener("click", fn), el.textContentconst make = () => { let c = 0; return () => ++c; };f.call(obj, a), f.apply(obj, [a]), const g = f.bind(obj)class B extends A { constructor(x) { super(x); } }export const x = 1; export default fn; import fn, { x } from "./m.js";try { } catch (e) { } finally { }; a?.b, a ?? bthen, after await), tasks (setTimeout)Promise.all([..]), Promise.race([..]), Promise.allSettled([..])const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(obj) }); if (!res.ok) throw new Error(res.status); const data = await res.json();localStorage.setItem(k, v), getItem(k) (null if missing), removeItem(k), clear(); sessionStorage has the same APIJSON.stringify(obj) before storing, JSON.parse(str) after readingnpm install, npm run serve (dev, hot reload), npm run build (to dist/)^2.6.14 = same major, newer minor and patch allowed<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>; new Vue({ el: "#app", data: {} })navigator.serviceWorker.register("/sw.js"); manifest = name, icons, start_url, display<meta name="viewport" content="width=device-width, initial-scale=1"><script src="https://cdn.jsdelivr.net/npm/vue@2"></script>new Vue({ el: "#app", data: {...}, methods: {...}, computed: {...}, watch: {...} }):attr="x" is v-bind:attr; @click="f" is v-on:click; @submit.prevent, @click.stop, @click.once, @keyup.enterv-model.trim, v-model.number, v-model.lazyv-for="(item, i) in list", (value, key, i) in obj, n in 5; always :key:class="{ active: isOn }", :class="[a, { b: flag }]", :style="{ color: c }"Vue.set(obj, key, val), this.$set(arr, i, val), arr.splice(i, 1, val)this.$nextTick(fn), this.$refs.namecreateApp, Proxy reactivity, beforeUnmount and unmountedconst res = await fetch(url); if (!res.ok) throw new Error(res.status); const data = await res.json();fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(obj) })const { data } = await axios.get(url), axios.post(url, obj), errors in err.response.statusCORS(app) or CORS(app, resources={r"/api/*": {"origins": "http://localhost:8080"}})return jsonify(obj), 201, return "", 204, return jsonify({"error": "..."}), 404vue.config.js): devServer: { proxy: { "/api": { target: "http://localhost:5000", changeOrigin: true } } }Flask(__name__, static_folder="dist", static_url_path="") and send_from_directory(app.static_folder, "index.html")loading = true; try { ... } catch (e) { error = e.message } finally { loading = false }Vue.component("my-comp", { props: [...], data() { return {...}; }, template: "..." })components: { MyComp } (use <my-comp>)props: { n: { type: Number, required: true, default: 0 } }; pass :n="5"this.$emit("name", payload); parent @name="handler"value, event input<slot name="x">fallback</slot>; <template v-slot:x> (or #x); scoped <slot :item="i"> with v-slot:default="sp"<component :is="name">, <keep-alive>new VueRouter({ mode: "history", routes: [...] }), { path: "/u/:id", name: "user", component: U, props: true, children: [...] }this.$route.params.id, this.$route.query.q; go: this.$router.push({ name: "user", params: { id: 1 } }), .replace(), .go(-1)router.beforeEach((to, from, next) => { ... next() }); catch-all { path: "*", component: NotFound }component: () => import("./views/About.vue")vue create app, npm run serve, npm run build; Vue 3 router: createRouter, createWebHistorynew Vuex.Store({ state, getters, mutations, actions, modules, strict })(state, payload); getter (state, getters); action (context, payload) with { commit, dispatch, state, getters }this.$store.state.x, this.$store.getters.x, this.$store.commit('m', p), this.$store.dispatch('a', p)...mapState(['x']), ...mapGetters(['g']) in computed; ...mapMutations(['m']), ...mapActions(['a']) in methodscommit('cart/add', x), getters['cart/count'], mapState('cart', ['items'])sessionStorage.setItem(k, v), getItem(k), removeItem(k); same API on localStorage; strings onlyVue.set(obj, 'key', val), arr.splice(i, 1, val)Authorization: Bearer <token> or Authentication-Token: <token>jwt.encode(payload, key, algorithm="HS256"), jwt.decode(token, key, algorithms=["HS256"])create_access_token(identity=str(id)), @jwt_required(), get_jwt_identity(), get_jwt()CORS(app, origins=["http://localhost:8080"])resp.set_cookie(name, val, httponly=True, secure=True, samesite="Strict", max_age=3600)credentials: 'include', server needs Access-Control-Allow-Credentials: truecelery = Celery("tasks", broker="redis://localhost:6379/0", backend="redis://localhost:6379/1")@celery.task / @celery.task(bind=True, max_retries=3); raise self.retry(exc=exc, countdown=30)t.delay(a, b) is t.apply_async(args=(a, b)); options countdown=, eta=, expires=res = AsyncResult(task_id, app=celery); res.state (PENDING, STARTED, RETRY, SUCCESS, FAILURE); res.get(timeout=5)celery -A app.celery worker -l info, celery -A app.celery beat -l info, celery -A app.celery flowercrontab(hour=18, minute=0); crontab(minute='*/10'); crontab(hour=8, minute=0, day_of_month=1); crontab(hour=7, minute=30, day_of_week='mon')SET, GET, EXPIRE k 60, TTL k, INCR, LPUSH, RPUSH, LRANGE q 0 -1, SADD, SMEMBERS, HSET, HGETALL, ZADD, ZRANGE; redis-cli ping gives PONGdocker run -p 6379:6379 redis or Redis inside WSLrequests.post(URL, json={"text": "hi"}, timeout=5)hmac.new(SECRET, body, hashlib.sha256).hexdigest() and hmac.compare_digest(a, b)Response(gen(), mimetype="text/event-stream"); frame = "data: text\n\n"new EventSource(url), es.onmessage = e => ..., es.close()r.publish("ch", msg), p = r.pubsub(); p.subscribe("ch")Message(subject, recipients=[...], body=..., html=...), mail.send(msg)http://localhost:8025crontab(hour=18, minute=0); monthly crontab(day_of_month=1, hour=8, minute=0)Content-Disposition: attachment; filename=export.csvab -n 100 -c 10 URL (requests, concurrency)Cache-Control: max-age=60, no-store, no-cache, public, private; ETag plus If-None-Match gives 304CACHE_TYPE="RedisCache", CACHE_REDIS_URL="redis://localhost:6379/1", CACHE_DEFAULT_TIMEOUT=300@cache.cached(timeout=60); @cache.cached(timeout=60, key_prefix="k"); @cache.memoize(timeout=60)cache.delete("key"), cache.delete_memoized(fn, *args), cache.clear()select(Author).options(selectinload(Author.books))db.Column(db.Integer, index=True)db.paginate(select(Book).order_by(Book.id), page=2, per_page=20)component: () => import("./views/X.vue")Authorization: Bearer <token>; 401 = no or bad token, 403 = not allowed, 409 = conflict, 202 = accepted for background workcreate_access_token(identity=..., additional_claims={"role": ...}), @jwt_required(), get_jwt()router.beforeEach((to, from, next) => { ... next("/login") })state, mutations (sync), actions (async), commit, dispatchCORS(app, resources={r"/api/*": {"origins": ["http://localhost:8080"]}})crontab(hour=18, minute=0), crontab(day_of_month=1, hour=8, minute=0)celery -A app.celery worker -l info -P solo; beat: celery -A app.celery beat -l infohttp://localhost:8025pip freeze > requirements.txt; keep secrets in .env, never in Git