teleren/devto huggingface dataset:
Sequelize Cheat Sheet
Tags: sequelize, cheatsheet
Published: 2021-05-12 01:53:29

### Reference

* [Sequelize Cheat Sheet](https://cheatsheetmaker.com/sequelize) - [cheatsheetmaker.com](https://cheatsheetmaker.com)

### Build

    item = Project.build({ ... })

    item.title = '...'

    item.save().success (item) ->

    item.updateAttributes({ title: '...' })

    item.destroy().success ->

    item.values

### Finders

    Project.find(123).success (project) ->

    Project.find({ where: {title: 'Hello'} })
    Project.find({ where: {id: [1,3,4]} })
    Project.find({ where: ["id > ?", 25] })

    Project.find(
      where: {title: 'a'}
      attributes: ['id', ['name', 'title']]
    )

    .findOrCreate(...)

    .findAll
    .findAll({ where: ... })
    .findAll({ order: 'title DESC' })
    .findAll({ limit: 10 })
    .findAll({ offset: 10, limit: 2 })

    .count()

### Models

    Project = sequelize.define('Project', {
      title: Sequelize.STRING,
      description: Sequelize.TEXT,
      myDate: { type: Sequelize.DATE, defaultValue: Sequelize.NOW },
      title: { type: Sequelize.STRING, allowNull: false },
      id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
    }, {
      classMethods: { ... },
      instanceMethods: { ... }
    });

    Project.hasMany(Task)

### API

    sequelize.sync().done -> ...
Jasmine Cheat Sheet
Tags: jasmine, cheatsheet
Published: 2021-05-12 01:50:26

### References

* Also see the [Jest cheatsheet](https://cheatsheetmaker.com/jest). Jest uses Jasmine and therefore has a similar API.
* <https://jasmine.github.io>
* [Jasmine Cheat Sheet](https://cheatsheetmaker.com/jasmine)

### [Tests] Event spies

```js
spyOnEvent($('#some_element'), 'click')
$('#some_element').click()
expect('click').toHaveBeenPreventedOn($('#some_element'))
expect('click').toHaveBeenTriggeredOn($('#some_element'))
```

### [Tests] HTML runner

```js
var jasmineEnv = jasmine.getEnv()
jasmineEnv.updateInterval = 250

var htmlReporter = new jasmine.HtmlReporter()
jasmineEnv.addReporter(htmlReporter)

$(function() { jasmineEnv.execute() })
```

Jasmine jQuery
--------------

### [Tests] Async

```js
test('works with promises', () => {
  return new Promise((resolve, reject) => {
    ···
  })
})
```

Make your test return a promise.

### [Tests] Creating spies

```js
stub = jasmine.createSpy('stub')
stub('hello')
```

```js
expect(stub.identity).toEqual('stub')
expect(stub).toHaveBeenCalled()
```

### [Tests] Spies

```js
spyOn(foo, 'setBar')
spyOn(foo, 'setBar').andReturn(123)
spyOn(foo, 'getBar').andCallFake(function() { return 1001; })
foo.setBar(123)
```

```js
expect(foo.setBar).toHaveBeenCalled()
expect(foo.setBar).toHaveBeenCalledWith(123)
expect(foo.setBar.calls.length).toEqual(2)
expect(foo.setBar.calls[0].args[0]).toEqual(123)
```

### [Tests] Pending

```js
xit('this is a pending test', () => {
  ···
})
```

```js
xdescribe('this is a pending block', () => {
  ···
})
```

### [Tests] Hooks

```js
beforeEach(() => {
  ···
})
```

```js
afterEach(() => {
  ···
})
```

### [Tests] Expectations

```js
expect(true).toBe(true)
expect(true).not.toBe(true)
```

```js
expect(a).toEqual(bar)
```

```js
expect(message).toMatch(/bar/)
expect(message).toMatch('bar')
```

```js
expect(a.foo).toBeDefined()
expect(a.foo).toBeUndefined()
expect(a.foo).toBeNull()
```

```js
expect(a.foo).toBeTruthy()
expect(a.foo).toBeFalsy()
```

```js
expect(message).toContain('hello')
```

```js
expect(pi).toBeGreaterThan(3)
expect(pi).toBeLessThan(4)
expect(pi).toBeCloseTo(3.1415, 0.1)
```

```js
expect(func).toThrow()
```

### [Tests] Writing tests

```js
describe('A suite', () => {
  it('works', () => {
    expect(true).toBe(true)
  })
})
```
Saucelabs Cheat Sheet
Tags: saucelabs, cheatsheet
Published: 2021-05-12 01:48:05

### Getting started

Sign up for opensauce:

- http://saucelabs.com/opensauce

Install [zuul](https://npmjs.com/package/zuul):

```
npm i -g zuul
```

Configure zuul:

```yml
# ~/.zuulrc
sauce_username: me
sauce_key: abc12348-e3e2-...
```

Add `.zuul.yml` to your project:

```yml
# .zuul.yml
ui: mocha-bdd
browsers:
  - name: chrome
    version: latest
  - name: ie
    version: 6..latest
  - name: firefox
    version: latest
```

Try to run tests:

```
zuul test/test.js
zuul --local test/test.js
```

### Reference:

* [Saucelabs Cheat Sheet](https://cheatsheetmaker.com/saucelabs)
History of Java And JavaScript names
Tags: java, javascript, programming, python
Published: 2021-05-12 01:46:06

![name history of java and javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eisbvuypwdta34xvah6n.png)

Read the difference between Java & JavaScript
https://buggyprogrammer.com/difference-between-java-and-javascript/
Rspec Cheat Sheet
Tags: rspec, cheatsheet
Published: 2021-05-12 01:43:48

### Spec helpers

```rb
module UserSpecHelper
  def valid_user_attributes
    { :email => "joe@bloggs.com",
      :username => "joebloggs",
      :password => "abcdefg"}
  end
end
```

```rb
describe User do
  include UserSpecHelper

  ...
end
```

### [Doubles] Method stubs

```rb
allow(die).to receive(:roll)
allow(die).to receive(:roll) { 3 }
allow_any_instance_of(Die).to receive(:roll)

expect(die).to receive(:roll)
  .with(1)
  .with(1, true)
  .with(boolean)
  .with(anything)
  .with(any_args)
  .with(1, any_args)
  .with(no_args)
  .with(hash_including(a: 1))
  .with(hash_excluding(a: 1))
  .with(array_including(:a, :b))
  .with(array_excluding(:a, :b))
  .with(instance_of(Fixnum))
  .with(kind_of(Numeric))
  .with(<matcher>)

  .once
  .twice
  .exactly(n).times
  .at_least(:once)
  .at_least(:twice)
  .at_least(n).times
  .at_most(:once)
  .at_most(:twice)
  .at_most(n).times
```

https://relishapp.com/rspec/rspec-mocks/docs

### Doubles

```rb
book = double('book')
book = instance_double('Book', pages: 250)
```
### [Expectations] Change

```rb
expect { thing.approve! }.to \
  change(thing, :status)
  .from(Status::AWAITING_APPROVAL)
  .to(Status::APPROVED)

expect { thing.destroy }.to \
  change(Thing, :count)
  .by(-1)
```

### [Expectations] Enumerables/arrays

```rb
expect(list).to include(<object>)

expect(list).to have(1).things
expect(list).to have_at_least(2).things
expect(list).to have_at_most(3).things

expect(list).to have(2).errors_on(:field)
```

### [Expectations] Control flow

```rb
expect { user.save! }.to raise_error
expect { user.save! }.to raise_error(ExceptionName, /msg/)
expect { user.save! }.to throw :symbol
```

### [Expectations] Objects

```rb
expect(obj).to be_an_instance_of MyClass
expect(obj).to be_a_kind_of MyClass
expect(obj).to respond_to :save!
```

### [Expectations] Predicate

```rb
expect(x).to be_zero    # FixNum#zero?
expect(x).to be_empty   # Array#empty?
expect(x).to have_key   # Hash#has_key?
```

### [Expectations] Comparison

```rb
expect(x).to be value
expect(x).to satisfy { |arg| ... }
expect(x).to match /regexp/
```

### [Expectations] Numeric

```rb
expect(5).to be < 6
expect(5).to == 5
expect(5).to equal value
expect(5).to be_between(1, 10)
expect(5).to be_within(0.05).of value
```

### Reference

* [Rspec Cheat Sheet](https://cheatsheetmaker.com/rspec) - _[cheatsheetmaker.com](https://cheatsheetmaker.com)_
Httpie Cheat Sheet
Tags: httpie, cheatsheet
Published: 2021-05-12 01:40:42

### References

*   <https://github.com/jakubroztocil/httpie>
*   [Httpie Cheat Sheet](https://cheatsheetmaker.com/httpie)

### Options

#### Printing options

```bash
-v, --verbose            # same as --print=HhBb --all
-h, --headers            # same as --print=h
-b, --body               # same as --print=b
    --all                # print intermediate requests
    --print=HhBb         # H: request headers
                         # B: request body
                         # h: response headers
                         # b: response body
    --pretty=none        # all | colors | format
    --json | -j          # Response is serialized as a JSON object.
```

#### Authentication

```bash
    --session NAME
-a, --auth USER:PASS
    --auth-type basic
    --auth-type digest
```

#### Session

```bash
    --session NAME       # store auth and cookies
    --session-read-only NAME
```

#### Downloading

```bash
-d, --download           # like wget
-c, --continue
-o, --output FILE
```

#### Others

```bash
-F, --follow             # follow redirects
    --max-redirects N    # maximum for --follow
    --timeout SECONDS
    --verify no          # skip SSL verification
    --proxy http:http://foo.bar:3128
```

### Raw JSON

```bash
$ echo '{"hello": "world"}' | http POST example.com/post
```
### Forms

```bash
$ http --form POST example.com \
    name="John Smith" \
    cv=@document.txt
```

### Parameters

```bash
$ http POST http://example.com/posts/3 \
    Origin:example.com \  # :   HTTP headers
    name="John Doe" \     # =   string
    q=="search" \         # ==  URL parameters (?q=search)
    age:=29 \             # :=  for non-strings
    list:='[1,3,4]' \     # :=  json
    file@file.bin \       # @   attach file
    token=@token.txt \    # =@  read from file (text)
    user:=@user.json      # :=@ read from file (json)
```

### Introduction

[HTTPie](https://httpie.org/) is a command-line HTTP client.

*   [HTTPie website](https://httpie.org/) _(httpie.org)_
*   [HTTPie documentation](https://httpie.org/docs) _(httpie.org)_
*   [Try it online](https://httpie.org/run) _(httpie.org)_
Why are functions in programming not considered "mathematical" functions?
Published: 2021-05-12 01:19:01

For the sake of interest I was out looking for a discussion of functions in computer science as generalized functions. I started my search by something such as "computer functions as mathematical functions". NO paper discusses functions in computer science in terms of set theory, and they compare (not equate) mathematical functions and functions in programming. Where did I miss the buss? Mathematics need not be done with numbers, although the largest application of mathematics is to numbers.
Create an NLP model without code
Published: 2021-05-12 01:11:47

Hi all,

Today I will introduce a service that creates an NLP model without code. Its name is "Teachable-NLP". To use Teachable-nlp, you only need to prepare the data(txt). 

And if you have a good idea, try the "Teachable NLP Challenge"

Teachable NLP Challenge is free and open to everyone interested in training their own AI. All you need to be prepared for is good ideas and datasets.

When: 05/05/2021 – 05/18/2021 11:59 EDT

How: You just need to submit your AI model link and explanations on your AI (Good example: https://forum.ainetwork.ai/c/ai-showcase/11)

Prizes: Apple Store gift cards, Winners’ interviews will be broadcasted through AI Network Youtube Channel(1.48K subscribers)

To participate, submit your info via https://forms.gle/XfUuNSS2heAn7JtH7. You will receive an invitation email!

Check how Teachable NLP works: https://forum.ainetwork.ai/t/teachable-nlp-how-to-use-teachable-nlp/65Or watch a 1-minute tutorial video: https://youtu.be/hzujZOT1qz8
Fish shell: Customize $PATH
Tags: fish, shell, commandline, path
Published: 2021-05-12 00:59:44

## Summary

This post shows how to customize [`$PATH`](https://fishshell.com/docs/current/tutorial.html#path), an environment variable, in [Fish shell](https://fishshell.com/).

## How-to

Here shows how to add <some-path> to `$PATH`, for example.

### 1. Set Temporarily

All what to do is run this command:

```console
$ set -x PATH <some-path> $PATH
```

Well, [`set`](https://fishshell.com/docs/current/cmds/set.html)'s `-x` (or `--export`) means it "causes the specified shell variable to be exported to child processes (making it an "environment variable")".

### 2. Set Permanently

#### 2-1. config.fish

Fish shell has `$HOME/.config/fish/config.fish` as `.profile` to other shells. Append this line to the bottom of it:

```diff
  ...
+ set PATH <some-path> $PATH
```

#### 2-2. fish_user_paths

There is another and more "fisher" way. Use its `fish_user_paths`, a [universal variable](https://fishshell.com/docs/current/tutorial.html#tut-universal) of Fish shell.
Open your terminal and run this command:

```console
$ set -U fish_user_paths <some-path> $fish_user_paths
```

`-U` (or `--universal`) means it "causes the specified shell variable to be given a universal scope".

Be careful not to write it in `config.fish`, which is called every time Fish shell starts.
Fetch Cheat Sheet
Tags: fetch, cheatsheet
Published: 2021-05-12 00:56:43

### References

*    [https://fetch.spec.whatwg.org/](https://fetch.spec.whatwg.org/)
*    [https://cheatsheetmaker.com/fetch](https://cheatsheetmaker.com/fetch)
*   [https://www.npmjs.com/package/whatwg-fetch](https://www.npmjs.com/package/whatwg-fetch)### Using with node.js

```js
const fetch = require('isomorphic-fetch')
```

See: [isomorphic-fetch](https://npmjs.com/package/isomorphic-fetch) _(npmjs.com)_

### Catching errors

```js
fetch('/data.json')
  .then(checkStatus)
```

```js
function checkStatus (res) {
  if (res.status >= 200 && res.status < 300) {
    return res
  } else {
    let err = new Error(res.statusText)
    err.response = res
    throw err
  }
}
```

Non-2xx responses are still successful requests. Use another function to turn them to errors.

### Request options

```js
fetch('/data.json', {
  method: 'post',
  body: new FormData(form), // post body
  body: JSON.stringify(...),

  headers: {
    'Accept': 'application/json'
  },

  credentials: 'same-origin', // send cookies
  credentials: 'include',     // send cookies, even in CORS

})
```

### Response

```js
fetch('/data.json')
.then(res => {
  res.text()       // response body (=> Promise)
  res.json()       // parse via JSON (=> Promise)
  res.status       //=> 200
  res.statusText   //=> 'OK'
  res.redirected   //=> false
  res.ok           //=> true
  res.url          //=> 'http://site.com/data.json'
  res.type         //=> 'basic'
                   //   ('cors' 'default' 'error'
                   //    'opaque' 'opaqueredirect')

  res.headers.get('Content-Type')
})
```

### Fetch

```
fetch('/data.json')
  .then(response => response.json())
  .then(data => {
    console.log(data)
  })
  .catch(err => ...)﻿
```
Quick Activeadmin Cheat Sheet
Tags: amctiveadmin, cheatsheet
Published: 2021-05-12 00:54:17

### See more:
* [https://activeadmin.info/](https://activeadmin.info/)
* [Activeadmin Cheat Sheet](https://cheatsheetmaker.com/activeadmin)

### Disabling 'new post'

```ruby
ActiveAdmin.register Post do
  actions :index, :edit
  # or: config.clear_action_items!
end
```

### Other helpers

```ruby
status_tag "Done"           # Gray
status_tag "Finished", :ok  # Green
status_tag "You", :warn     # Orange
status_tag "Failed", :error # Red
```

### Columns

```ruby
column :foo
```

```ruby
column :title, sortable: :name do |post|
  strong post.title
end
```

### Custom actions

You can define custom actions for models.
{: .-setup}

```ruby
before_filter only: [:show, :edit, :publish] do
  @post = Post.find(params[:id])
end
```

#### Make the route

```ruby
member_action :publish, method: :put do
  @post.publish!
  redirect_to admin_posts_path, notice: "The post '#{@post}' has been published!"
end
```

#### Link it in the index

```ruby
index do
  column do |post|
    link_to 'Publish', publish_admin_post_path(post), method: :put
  end
end
```

#### And link it in show/edit

```ruby
action_item only: [:edit, :show] do
  @post = Post.find(params[:id])
  link_to 'Publish', publish_admin_post_path(post), method: :put
end
```

### Sidebar filters

```ruby
filter :email
filter :username
```

### Listing scopes

Allows you to filter listings by a certain scope.
{: .-setup}

```ruby
scope :draft
scope :for_approval
```

```ruby
scope :public, if: ->{ current_admin_user.can?(...) }
scope "Unapproved", :pending
scope("Published") { |books| books.where(:published: true) }
```
Quick Sass Cheat Sheet
Tags: sass, style, css, cheatsheet
Published: 2021-05-12 00:50:31

### See also

*   [http://sass-lang.com/documentation/Sass/Script/Functions.html](http://sass-lang.com/documentation/Sass/Script/Functions.html)
*   [http://sass-lang.com/documentation/file.SASS\_REFERENCE.html#sassscript](http://sass-lang.com/documentation/file.SASS_REFERENCE.html#sassscript)
*   [Sass Cheat Sheet](https://cheatsheetmaker.com/sass)

### [Other features] Maps

```scss
$map: (key1: value1, key2: value2, key3: value3);

map-get($map, key1)
```

### [Other features] Lists

```scss
$list: (a b c);

nth($list, 1)  // starts with 1
length($list)

@each $item in $list { ... }
```

### [Other features] Interpolation

```scss
.#{$klass} { ... }      // Class
call($function-name)    // Functions

@media #{$tablet}
font: #{$size}/#{$line-height}
url("#{$background}.jpg")
```

### [Other features] Conditionals

```scss
@if $position == 'left' {
   position: absolute;
   left: 0;
}
@else if $position == 'right' {
   position: absolute;
   right: 0;
}
@else {
   position: static;
}
```

### [Loops] While loops

```scss
$i: 6;
@while $i > 0 {
  .item-#{$i} { width: 2em * $i; }
  $i: $i - 2;
}
```

### [Loops] Each loops (nested)

```scss
$backgrounds: (home, 'home.jpg'), (about, 'about.jpg');

@each $id, $image in $backgrounds {
  .photo-#{$id} {
    background: url($image);
  }
}
```

### [Loops] Each loops (simple)

```scss
$menu-items: home about services contact;

@each $item in $menu-items {
  .photo-#{$item} {
    background: url('images/#{$item}.jpg');
  }
}
```

### [Loops] For loops

```scss
@for $i from 1 through 4 {
  .item-#{$i} { left: 20px * $i; }
}
```

### [Feature checks] Features

* global-variable-shadowing
* extend-selector-pseudoclass
* units-level-3
* at-error
What to use Let or Const?
Published: 2021-05-21 08:42:24

---
title: What to use Let or Const?
published: true
date: 2021-05-12 00:00:00 UTC
tags: 
canonical_url: https://vivekpandey.live/blog/Let-vs-Const/
---

You must have a seen a controversial, sparking conversations on Reddit and Twitter recently. People were debating over usage of Let and Const.

![Let vs Const Thumbnail](https://vivekpandey.live/blog/images/let-vs-const.jpg)

It seems that netizens believe that one should use const wherever possible, only falling back to let where necessary, as can be enforced with the prefer-const **ESLint rule**.

> Let vs Const vs Var: We generally want to use let. If we’re not using the same, we use const. (I’ve have seen codebases which force you to use const when there is only one assignment, same goes for some of the devs out there.)

## Why prefer `const`?

1. 

**Performance Benefits** : There are some claims out there which say using const makes code faster because it knows there won’t be any re-assignment.

2. 

**One Way to Do It** : Sometimes it’s a bias in our head. A rule like “always use const where it works” stop us from thinking about it and can be enforced by a linter nowadays.

3. 

**Reassignments May Cause Bugs** : In the long-run, there can be instances where we may forget about reassignment of the variables. Therefore, const gives you confidence you’ll always “see” the same value and there will be no bug.

4. 

**Learning About Mutation** : When I got started with JavaScript, I got consfused with the const & immutability. It’s important to learn the difference between variable mutation and assignment anyway, and preferring const forces you to confront this distinction early on.

## Why Not prefer `const`?

1. 

**Confusion with Immutability** : In every conversation over const, you’ll find someone who confuses with immutability. This happens because assignment and mutation use the same `'='` operator.

2. 

**Pressure to Avoid Redeclaring** : A const based codebase creates a pressure to not use let for conditionally assigned variables. For example, you might write `const a = condition ? b : c` instead of an if condition, even if both b and c branches are convoluted and giving them explicit names is awkward.

3. 

**Loss of Intent** : If we use const everywhere, we lose the ability to clarify when something is important to not be reassigned.

## What is my Conclusion?

Well I don’t have a opinion on this.

I would use whatever I need as per my situation. If you care, use a linter that automates checking and fixing this issue so that changing let to const doesn’t become a delay in code review.

Finally, remember that linters exist to serve you. Learn from your own mistakes.

Originally posted on: [Vivek's Blog](vivekpandey.live/blog)
Quick C Preprocessor Cheat Sheet
Tags: cpreprocessor, cheatsheet
Published: 2021-05-12 00:47:48

### [Reference] file and line

```
#define LOG(msg) console.log(__FILE__, __LINE__, msg)
#=> console.log("file.txt", 3, "hey")
```

### [Reference] Stringification

```
#define STR(name) #name
char * a = STR(object);   #=> char * a = "object";
```

### [Reference] Token concat

```
#define DST(name) name##_s name##_t
DST(object);   #=> object_s object_t;
```

### [Reference] Macro

```
#define DEG(x) ((x) * 57.29)
```

### [Reference] Error

```
#if VERSION == 2.0
  #error Unsupported
  #warning Not really supported
#endif
```

### [Reference] If

```
#ifdef DEBUG
  console.log('hi');
#elif defined VERBOSE
  ...
#else
  ...
#endif
```

### [Reference] Defines

```
#define FOO
#define FOO "hello"

#undef FOO
```

### [Reference] Includes

```
#include "file"
```

### [Reference] Compiling

```
$ cpp -P file > outfile
```

### Reference

* [C Preprocessor](https://en.wikipedia.org/wiki/C\_preprocessor)
* [C Preprocessor Cheat Sheet](https://cheatsheetmaker.com/c-preprocessor)
An Agile Serenity Prayer
Tags: cicd, continuousdelivery, devops
Published: 2021-05-17 08:22:28

---
title: An Agile Serenity Prayer
published: true
date: 2021-05-12 00:00:00 UTC
tags: cicd,continuousdelivery,devops
canonical_url: https://jhall.io/archive/2021/05/12/an-agile-serenity-prayer/
---

I found this floating around the interwebs:

> AN AGILE SERENITY PRAYER
> 
> God grant me the strength to accept the last-minute changes that get requested a week before a release, the courage to tell the client they can have that neat new feature, but not in this release, and the wisdom not to use velocity as a measure of productivity.

The spirit of it is right: Focus on what matters, and don’t fret what we don’t control.

But one thing jumped out at me as out of place: _a week before a release_.

This concept should be completely foreign to any modern agile team, in the era of continuous delivery/deployment.

If your team isn’t releasing multiple times per day, you should sign up for my free [Lean Continuous Deployment Bootcamp](https://jhall.io/lean-cd-bootcamp/) and get started!

* * *
_If you enjoyed this message, [subscribe](https://jhall.io/daily) to <u>The Daily Commit</u> to get future messages to your inbox._