Skip to content

Instantly share code, notes, and snippets.

@TobiObeck
Last active November 3, 2022 13:08
Show Gist options
  • Save TobiObeck/f764eaaa635d43e29456f153e3ba9065 to your computer and use it in GitHub Desktop.
Save TobiObeck/f764eaaa635d43e29456f153e3ba9065 to your computer and use it in GitHub Desktop.
Cheat Sheets

JavaScript (JS) Snippets

//noticeable console logs
console.log('%c onFormLoad', 'background: #222; color: #bada55');
//iterating over js object
for (const key in obj) {
  let value = obj[key];
  
  //optional check for properties from prototype chain 
  if (obj.hasOwnProperty(key)) {
    //no a property from prototype chain     
  }
  //not needed else{//property from protytpe chain  }
}

create filled array for functional functions like forEach(), map(), filter(), reduce()

const arr = Array(100); // Wrong way! Results in arr of type object:
{
  //no index keys!
  length: 100
}

// Good way! to prevent this use this:
Array.from({length: 100}, (_, i) => i);
Array(100).fill(null).map((_, i) => i)

Terminal Commands

Terminal commands for windows/unix

Windows

# new folder
mkdir 
# clearing the terminal
cls
clear

Powershell

Record powershell session and save into output.txt file

$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
Start-Transcript -path "C:\Users\path\to\output.txt" -append
# Do some stuff that is printed into the terminal and is therefore written into the output file
Stop-Transcript

Environment Variables

display all (powershell) gci env:

sorted: gci env:* | sort-object name

set an environment variable:

  • powershell: PS C:\path\to\app> $env:FLASK_APP = "hello.py"
  • cmd set FLASK_APP=hello.py
  • UNIX export FLASK_APP=hello.py

npm

npm

npm init // creates a new package.json file -f for force

npm install --save nodemon eslint

inside of package.json: "scripts": { ... } "versions": "echo == git == && git --version && echo == node == && node --version" scripts can be run by: npm run [command]

npm install -g node nodemon

project setup

git clone [URL]
cd [REPONAME]
globally install vue cli tool
npm install -g vue-cli
vue list //lists possible project templates
vue init [template-name] [project-name]
vue init webpack "client"
wizards asks for unit testsing (y/n), linting (y/n)...
and creates "client" folder with config files etc.
cd client
npm install (or if using yarn: yarn) //installs local dependencies and devDependencies in node_modules folder
npm run lint -- --fix (or for yarn: yarn run lint --fix)
npm run dev

.vscode\settings.json

{
    "editor.formatOnSave": true,
    "vetur.format.defaultFormatter.ts": "prettier",
    "vetur.format.options.tabSize": 2,
    "vetur.format.defaultFormatterOptions": {
        "prettier": {
            // Prettier option here
            "semi": true,
            "singleQuote": true,
            "trailingComma": "none",
        }
    }
}

How to Import CSS!

`@import` is CSS/SASS syntax to include other files.
`import` is modern ES6 syntax to include modules.
`require` is AMD/CMD syntax currently used by Node.
in main.js / main.ts
main.js:
require('../node_modules/bootstrap/dist/css/bootstrap.min.css')
require('./assets/layout3/css/layout.min.css')
import "leaflet/dist/leaflet.css";

or

in App.vue in a SCSS style block:
<style lang="scss">
@import 'src/assets/css/mycss_lib.css';
</style>
You'll need the scss loader and node-sass for this.

or

webpack /static folder vuejs-templates/webpack#604

or the best option

For Single File Components (with Vue.js v2) : <style src="./my-component.css"></style>

<!-- my-component.vue -->
<template>
  <div>This will be pre-compiled</div>
</template>
<script src="./my-component.js"></script>
<style src="./my-component.css"></style>

https://vuejs.org/v2/guide/single-file-components.html#What-About-Separation-of-Concerns

Tips for Using Axios with Vue

You need to provide your own Promise polyfill when using Axios, if your target environments do not natively support Promises.
If you’d like to access this.$http like in vue-resource, you can just set Vue.prototype.$http = axios.

Axios download/upload progress

{
Axios.get('some/url',
        onDownloadProgress: (progressEvent) => {
          const totalLength = progressEvent.lengthComputable ? progressEvent.total : progressEvent.target.getResponseHeader('content-length') || progressEvent.target.getResponseHeader('x-decompressed-content-length');
          console.log("PROGRESS onDownloadProgress", totalLength);
          if (totalLength !== null) {
            const length = Math.round((progressEvent.loaded * 100) / totalLength);
            console.log("PROGRESS " + length);
          }
        }
      }).then(...)

Environment Variables with VUE CLI

.env.localdev

NODE_ENV=development
VUE_APP_LOCALDEV=TRUE

in code

if(process.env.NODE_ENV === 'devolpment'){
    // do stuff    
}

if(Boolean(process.env.VUE_APP_LOCALDEV)){
    // use mock data / mock api endpoint
}

Visual Studio Code (VS Code)

.vscode/settings.json or user settings.json
// Platzieren Sie Ihre Einstellungen in dieser Datei, um die Standardeinstellungen zu überschreiben.
{
    "window.menuBarVisibility": "default",
    "team.showWelcomeMessage": false,
    "window.zoomLevel": 0,
    "workbench.activityBar.visible": true,
    "workbench.statusBar.visible": true,
    "git.ignoreMissingGitWarning": true,    
    "textmarker.useHighlightColorOnRuler": true,
    //"jslint.version": "es6"
    "jshint.options": {
        "sub": true
        /*jshint sub:true*/
        /*jshint -W069 */
        /*Disable Warning Justification:
            Using bracket notation so Google Closure Compiler 
            ADVANCED_OPTIMIZATIONS will keep the original property names. */
        
        /*jshint +W069 */
    },
    //BEGIN leerzeichen for function ()
    "javascript.format.insertSpaceBeforeFunctionParenthesis": false,    
    "javascript.format.insertSpaceAfterKeywordsInControlFlowStatements": false,
    "javascript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": false,
    //"javascript.format.insertSpaceBeforeAndAfterBinaryOperators": true,
    "editor.formatOnType": true,
    //END leerzeichen for function ()

    "workbench.colorTheme": "Monokai",
    "textmarker.highlightColors": [
        "darkgoldenrod",
        "darkmagenta",
        "darkolivegreen",
        "darkslateblue",
        "darkslategray",
        "darkviolet",
        "darkblue",
        "darkturquoise",
        "darkgray",
        "darkkhaki",
        "darkorange",
        "darksalmon",
        "darkseagreen"
    ],
    "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\tf.exe",
    "tfvc.restrictWorkspace": true,
    "terminal.integrated.env.windows": {
        "PATH": "C:\\git\\Tools\\ImportExporter\\WebResourceImportExporter\\bin\\Debug;${env:PATH}"
    },    
    "terminal.integrated.shell.windows": "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
    "todohighlight.isEnable": false,
    "better-comments.tags": [
        {
          "tag": "!",
          "color": "#FF2D00",
          "strikethrough": false,
          "backgroundColor": "transparent"
        },
        {
          "tag": "?",
          "color": "#3498DB",
          "strikethrough": false,
          "backgroundColor": "transparent"
        },
        {
          "tag": "//",
          "color": "#474747",
          "strikethrough": true,
          "backgroundColor": "transparent"
        },
        {
          "tag": "todo",
          "color": "#FF8C00",
          "strikethrough": false,
          "backgroundColor": "transparent"
        },
        {
          "tag": "*",
          "color": "#98C379",
          "strikethrough": false,
          "backgroundColor": "transparent"
        },
        {
          "tag": "fixme",
          "color": "#FF8C00",
          "strikethrough": false,
          "backgroundColor": "#00000020"
        },
        ],
        "editor.minimap.enabled": true,
        "editor.formatOnType": true,
        "editor.fontSize": 13,
        //"[javascript]": {
        //  "editor.formatOnSave": true
        //}
        "javascript.preferences.quoteStyle": "single",
        "[typescript]": {
        "editor.defaultFormatter": "vscode.typescript-language-features"
        //  "editor.defaultFormatter": "esbenp.prettier-vscode",
        //  "editor.formatOnSave": true
        }
}

Global gitconfig file

path on windows: C:\Program Files\Git\mingw64\etc

[color "status"]
    changed = red bold
    untracked = red bold
    added = green bold

[color "branch"]
	current = yellow reverse
	local = cyan
	remote = normal

[color "decorate"]
    HEAD = cyan
    branch = green
    tag = blue bold    
    
[color "diff"]
	context = white
	meta = white
	frag = white
	commit = white
	new = cyan
	old = red

Increment Selection albymor.increment-selection

Multiple cursor selections are auto incremented/auto numbering/counted/indexed

https://github.com/albymor/Increment-Selection

https://marketplace.visualstudio.com/items?itemName=albymor.increment-selection


Multiple cursor case preserve cardinal90.multi-cursor-case-preserve

Preserves Casing when renaming via multiple cursor selections

https://github.com/Cardinal90/multi-cursor-case-preserve


Auto Close Tag formulahendry.auto-close-tag

Auto Rename Tag formulahendry.auto-rename-tag


Lorem Picsum huang-an-sheng.lorem-picsum-photos-snippets

Lorem Picsum photos snippets


Live Server ritwickdey.liveserver

https://github.com/ritwickdey/vscode-live-server


Bracket Pair Colorizer coenraads.bracket-pair-colorizer

https://github.com/CoenraadS/BracketPair


Highlight Bad Chars wengerk.highlight-bad-chars

https://github.com/WengerK/vscode-highlight-bad-chars

https://marketplace.visualstudio.com/items?itemName=wengerk.highlight-bad-chars

  "highlight-bad-chars.additionalUnicodeChars": [
    "\uFFFD", // questionmark  Replacement Character �
  ],

Regions With Colors argiolasriccardo90.regions-with-colors

https://marketplace.visualstudio.com/items?itemName=argiolasriccardo90.regions-with-colors

"regionsWithColors.color": "rgba(0, 0, 0, 0.1)"


Text Marker (Highlighter) ryu1kn.text-marker

https://marketplace.visualstudio.com/items?itemName=ryu1kn.text-marker

"textmarker.useHighlightColorOnRuler": true,

"textmarker.highlightColors": [
    "darkgoldenrod",
    "darkmagenta",
    "darkolivegreen",
    "darkslateblue",
    "darkslategray",
    "darkviolet",
    "darkblue",
    "darkturquoise",
    "darkgray",
    "darkkhaki",
    "darkorange",
    "darksalmon",
    "darkseagreen"
],

SynthWave '84


CodeMetrics kisstkondoros.vscode-codemetrics

https://github.com/kisstkondoros/codemetrics

  // settings for switch case and...

.vscode/extensions.json

{
    "recommendations": [
        "albymor.increment-selection",
        "cardinal90.multi-cursor-case-preserve",
        "huang-an-sheng.lorem-picsum-photos-snippets",
        "ritwickdey.liveserver",
        "coenraads.bracket-pair-colorizer",
        "wengerk.highlight-bad-chars",
        "argiolasriccardo90.regions-with-colors",
        "kisstkondoros.vscode-codemetrics",
        "ryu1kn.text-marker",
        "AykutSarac.jsoncrack-vscode",
        "statelyai.stately-vscode", // xstate
        "stateful.runme",
        "	phobal.vscode-collapse-node-modules" // cmd + shift + p -> select the Collapse: collapse node_modules folder
        // deprecated I think "mattpocock.xstate-vscode"
    ]
}

maybe

        "formulahendry.auto-close-tag",
        "formulahendry.auto-rename-tag",
        

Additional extensions

Carbon Code Screenshot ericadamski.carbon-now-sh Polacode pnp.polacode

Better screenshotthan polacode with customization via VS Code settings:

CodeSnap adpyke.codesnap

https://marketplace.visualstudio.com/items?itemName=adpyke.codesnap


JSON Crack AykutSarac.jsoncrack-vscode

https://marketplace.visualstudio.com/items?itemName=AykutSarac.jsoncrack-vscode


CodeSnap settings:

{
    "codesnap.backgroundColor": "#abb8c3",
    "codesnap.showWindowControls": false,
    "codesnap.boxShadow": "rgba(0, 0, 0, 0.55) 0px 5px 5px",
    "codesnap.containerPadding": "1em",
    "codesnap.showWindowTitle": true,
    "codesnap.showLineNumbers": true,
    "codesnap.realLineNumbers": false,
    "codesnap.transparentBackground": true,
    "editor.formatOnSave": true,
}

Marky Dynamic robole.marky-dynamic

https://marketplace.visualstudio.com/items?itemName=robole.marky-dynamic

Generate markdown Table of Contents (ToC)

© 0169
 0160 fake leerzeichen.
█ 987
­ 0173 manchmal unsichtbares sonderzeichen, dass keinen Platz einnimmt

https://github.com/typescript-eslint/typescript-eslint microsoft/TypeScript#30553 https://blog.matterhorn.dev/posts/learn-typescript-linting-part-1/

npm run lint -- --fix

WIP

{
    // "vetur.format.defaultFormatter.ts": "prettier",
    // "vetur.format.options.tabSize": 2,
    // "vetur.format.defaultFormatterOptions": {
    //     "prettier": {
    //         // Prettier option here
    //         "semi": true,
    //         "singleQuote": true,
    //         "trailingComma": "none",
    //         "quote-props": [
    //             "error",
    //             "always"
    //         ],
    //         "printWidth": 100
    //     }
    // }
    //"tslint.typeCheck": true,
    //"tslint.autoFixOnSave": true,
    //
    
    //"prettier.tslintIntegration": true,
    "vetur.format.defaultFormatter.ts": "prettier-tslint",    
    "[vue]": {
        "editor.formatOnSave": true,
    },
    "[typescript]": {
        "editor.codeActionsOnSave": {
            "source.fixAll": true,
            //"source.organizeImports": true
        },
        "editor.formatOnSave": true,
        "editor.defaultFormatter": "ms-vscode.vscode-typescript-tslint-plugin"
    }
}

Regular Expressions / Regex

Every line except word is occurring

Select every line where given word is not present

^((?!ihatethisword|{|}).)*$

matches

{ //skipped
this line
another line
skips ihatethisword asdf
matches this line
} //also skipped

Match all code blocks with triple backtick fences in markdown document:

```javascript[a-z]*\n[\s\S]*?\n[\s\S]*?```

Matches only the content of a string without the single or double quotes (e.g. for replacing strings across mutliple files) Lookbehind some_string Lookahead https://javascript.info/regexp-lookahead-lookbehind

(?<=('|"))some_string(?=('|"))
"    <attribute name='some_string' />" +
'    <attribute name="some_string" />' +
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment