Code  Geek

Code Geek

1664505688

MERN Stack Full Tutorial | MERN Stack Project

MERN Stack Full Tutorial & Project | Complete All-in-One Course | 8 Hours

This MERN Stack Full Tutorial & Project provides a complete all-in-one course with 8 hours of code and instruction to level up your web development skills. Think of this MERN Stack Full Tutorial Course as a full stack video textbook with 13 clearly defined chapters.

(00:00:00) Intro
(00:00:05) Welcome
(00:00:42) Chapter 1: MERN Stack Project
(00:28:13) Chapter 2: Middleware
(00:56:04) Chapter 3: MongoDB
(01:24:59) Chapter 4: Controllers
(02:08:14) Chapter 5: React JS
(02:42:15) Chapter 6: Redux & RTK Query
(03:16:54) Chapter 7: React & Redux Forms
(04:08:36) Chapter 8: Authentication vs Authorization
(04:45:17) Chapter 9: Login Auth
(05:18:49) Chapter 10: JWT Auth
(06:00:59) Chapter 11: Roles & Permissions
(06:44:17) Chapter 12: Refactoring
(07:30:19) Chapter 13: Deployment

All Resources for this MERN Stack Project: https://github.com/gitdagray/mern_stack_course 

Subscribe: https://www.youtube.com/c/DaveGrayTeachesCode/featured 

#mern  #stack  #javascript 

MERN Stack Full Tutorial | MERN Stack Project
Lawrence  Lesch

Lawrence Lesch

1664403360

StackBlur: Fast and Almost Gaussian Blur

StackBlur.js 

StackBlur.js is a fast, almost Gaussian blur created by Mario Klingemann.

Getting Started

Standalone version

To use the standalone version,

download the latest zip from Github or clone the repository

git clone git@github.com:flozz/StackBlur.git

and include the dist/stackblur.js or dist/stackblur.min.js file in your HTML page:

<script src="StackBlur/dist/stackblur.js"></script>

Node

To use the NPM package,

install the package:

npm install --save stackblur-canvas

and require it where needed

const StackBlur = require('stackblur-canvas');

Browsers

If you are only supporting modern browsers, you may use ES6 Modules directly:

import * as StackBlur from
  './node_modules/stackblur-canvas/dist/stackblur-es.min.js';

Or, if you are using Rollup in your own project, use the node-resolve plugin, and import by just referencing the module:

import * as StackBlur from 'stackblur-canvas';

API

See also the docs in docs/jsdoc.

Image as source:

StackBlur.image(sourceImage, targetCanvas, radius, blurAlphaChannel);
  • sourceImage: the HTMLImageElement or its id.
  • targetCanvas: the HTMLCanvasElement or its id.
  • radius: the radius of the blur.
  • blurAlphaChannel: Set it to true if you want to blur a RGBA image (optional, default = false)

RGBA Canvas as source:

StackBlur.canvasRGBA(targetCanvas, top_x, top_y, width, height, radius);
  • targetCanvas: the HTMLCanvasElement.
  • top_x: the horizontal coordinate of the top-left corner of the rectangle to blur.
  • top_y: the vertical coordinate of the top-left corner of the rectangle to blur.
  • width: the width of the rectangle to blur.
  • height: the height of the rectangle to blur.
  • radius: the radius of the blur.

RGB Canvas as source:

StackBlur.canvasRGB(targetCanvas, top_x, top_y, width, height, radius);
  • targetCanvas: the HTMLCanvasElement.
  • top_x: the horizontal coordinate of the top-left corner of the rectangle to blur.
  • top_y: the vertical coordinate of the top-left corner of the rectangle to blur.
  • width: the width of the rectangle to blur.
  • height: the height of the rectangle to blur.
  • radius: the radius of the blur.

RGBA ImageData as source:

StackBlur.imageDataRGBA(imageData, top_x, top_y, width, height, radius);
  • imageData: the canvas' ImageData.
  • top_x: the horizontal coordinate of the top-left corner of the rectangle to blur.
  • top_y: the vertical coordinate of the top-left corner of the rectangle to blur.
  • width: the width of the rectangle to blur.
  • height: the height of the rectangle to blur.
  • radius: the radius of the blur.

RGB ImageData as source:

StackBlur.imageDataRGB(imageData, top_x, top_y, width, height, radius);
  • imageData: the canvas' ImageData.
  • top_x: the horizontal coordinate of the top-left corner of the rectangle to blur.
  • top_y: the vertical coordinate of the top-left corner of the rectangle to blur.
  • width: the width of the rectangle to blur.
  • height: the height of the rectangle to blur.
  • radius: the radius of the blur.

Hacking

Building

This library is built using Rollup. If you change something in the src/ folder, use the following command to re-build the files in the dist/ folder:

npm run rollup


Original source:


Download Details:

Author: Flozz
Source Code: https://github.com/flozz/StackBlur 
License: MIT license

#javascript #stack #blur 

StackBlur: Fast and Almost Gaussian Blur
Rocio  O'Keefe

Rocio O'Keefe

1660622943

Stackdriver_dart: Logging Stackdriver Report

This package report to Google Cloud Error Reporting. It's multi-platform. Http request supported via http and dio package.

Usage

To See /example folder.

Initialize

Future main() async {
  final config = Config(
    projectId: "PROJECT_ID",
    key:"API_KEY",
    service: 'my-app',
    version: "1.0.0");

  final reporter = StackDriverErrorReporter();
  reporter.start(config);

  runZonedGuarded(() async {
    runApp(const MyApp());
  }, (error, trace) {
    reporter.report(err: error, trace: trace);
  });
}

Installing

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add stackdriver_dart

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  stackdriver_dart: ^1.0.7

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:stackdriver_dart/stackdriver_dart.dart';

example/lib/main.dart

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:stackdriver_dart/stackdriver_dart.dart';

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Report Sample",
      supportedLocales: const [
        Locale('ja', 'JP'),
        Locale('en', ''),
      ],
      home: Container(
        child: const Center(
          child: Text(
            "Report Sample",
            style: TextStyle(
              fontFamily: 'NotoSansJP',
              fontSize: 24,
              fontWeight: FontWeight.w200,
              color: Color.fromRGBO(0, 102, 238, 0.08),
            ),
          ),
        ),
      ),
    );
  }
}

Future main() async {
  final config = Config(
      projectId: "PROJECT_ID",
      key:"API_KEY",
      service: 'my-app',
      version: "1.0.0");

  final reporter = StackDriverErrorReporter();
  reporter.start(config);

  runZonedGuarded(() async {
    runApp(const MyApp());
  }, (error, trace) {
    reporter.report(err: error, trace: trace);
  });
}

Download Details:

Author: Ueki-tomohiro
Source Code: https://github.com/ueki-tomohiro/stackdriver_dart 
License: MIT license

#flutter #dart #stack #driver #logging 

Stackdriver_dart: Logging Stackdriver Report
Royce  Reinger

Royce Reinger

1658417340

Botstack: Rapid Chatbot Development with Ruby on Rails

botstack

This is a base project for creating FB Chatbots. It has a state machine and User Management and allows you to add functionality with modules.

Quickstart

Put all your logic into lib/bot. We've already prepared everything for you to kickstart your project.

@msg_meta holds @request_type holds the type of the request. Could be one of the following:

  • DELIVERY (maybe will be removed in the future, to disruptive)
  • OPTIN
  • CALLBACK
  • TEXT
  • IMAGE -> @msg_meta has the url to the image
  • LOCATION-> @msg_meta has the long / lat
  • AUDIO -> @msg_meta has the url to the mp3 file
  • ATTACHMENT_UNKNOWN -> @msg_meta has the url to the ATTACHMENT_UNKNOWN (mostly http links fucked up with fb outbound link system)

@current_user hold infos of your current user (last seen, state machine, user id ...)

botstack grafik-x

Reply Module

This function will reply a message back to the user who sent one. you can use Spintax and Emojs.

 def reply_message(msg, options={})

 def example()
  reply_message "make {:pizza:|:sushi:|:lemon:} great again!"
 end

This function will send an image back to the user who sent a message to your bot.

 def reply_image(img_url)

This function will render HTML and send an image back to the user who sent a message to your bot.

 def reply_html(html)

This function will render a bubble and send it to the user.

 def reply_bubble

This function will return a string along with a set of button options specified in an array.

 def reply_quick_buttons(msg, options=%W(Yes No))

This function will return a string containing the message a user sent to your bot.

 def get_message

Emoji Module

Most of the time you will not need the Emoji Module because it is already integrated into the reply module.

This function will return the UTF-8 representation of the given Emoji Name

 def get_emoji(name)

This function will send a reply message with the UTF-8 representation of the given Emoji Name

 def reply_emoji(name)

This function will be always used with the reply_message function of the repy module. It will search for emoji names surrounded with : and replaces them with the UTF-8 representation of the given [Emoji Name]

 def compute_emojis(content)

This function is the opposite of the function above.

 def parse_emojis(content)

Web Search Module

With the web search module you can transport websites to messengers. Just add two methods to your bot logic. One for handling search requests and one for handling user input on the search results.

search_request_on_website(
    url: "http://www.example.com/",
    form_name: 'search',
    result_css_selector: '.result > a',
    image_css_selector: 'img',
    button_text: 'more infos'
)

handle_search_result(
    url: "http://www.example.com",
    result_css_selector: ".result"
)

State Machine Module

This Module will help you with guiding users through different states of your bot.

Example usage of the State Machine Module:

class BotLogic < BaseBotLogic

    def self.bot_logic
        state_action 0, :greeting
        state_action 1, :turorial
        state_action 2, :bye
    end

    def self.greeting
        reply_message "greeting"
        state_go
    end 

    def self.turorial
        reply_message "turorial"
        state_go
    end 

    def self.bye
        reply_message "bye"
        state_reset
    end 

end

Installation

clone the repo copy config/settings.yml to settings.local.yml and enter your api keys use ngrok or another vpn to tunnel your connection run the following commands

bundle install
rails s

set the webhook to https://tunnel_url/bot and use your token (default: github)

Contributing

  • Fork it!
  • Create your feature branch: git checkout -b my-new-feature
  • Commit your changes: git commit -am 'Useful information about your new features'
  • Push to the branch: git push origin my-new-feature
  • Submit a pull request on the Development branch :D

gems used

Author: Davidmann4
Source Code: https://github.com/davidmann4/botstack 
License: 

#ruby #bot #stack #rails 

Botstack: Rapid Chatbot Development with Ruby on Rails
Hermann  Frami

Hermann Frami

1656863400

Serverless StackStorm Plugin

Serverless StackStorm Plugin

Run ready to use actions from StackStorm Exchange as AWS Lambda with serverless framework. Serverless and Stackstormless.

Prerequisite

  • Serverless framework
  • NodeJS >= 8.4.0
  • Docker - used to build and local-run Lambda on any OS
  • Build tools (build-essentials package on Ubuntu)
  • SSL dev files (libssl-dev package on Ubuntu)

Getting Started

Install serverless dependency globally

npm install -g serverless

Init with package.json:

npm init

Install the plugin:

npm i --save-dev serverless-plugin-stackstorm

Browse StackStorm Exchange to find the integration pack and an action you'd like to use. In the example below we use github.get_issue from GitHub integration pack.

Configure your service to use the plugin by creating serverless.yml file.

service: my-service

provider:
  name: aws
  runtime: python2.7 # StackStorm runners are based on Python 2

functions:
  get_issue:
    stackstorm: # `stackstorm` object replaces `handler`. The rest is the same.
      action: github.get_issue
      config:
        token: ${env:GITHUB_TOKEN}
      input:
        user: "{{ input.pathParameters.user }}"
        repo: "{{ input.pathParameters.repo }}"
        issue_id: "{{ input.pathParameters.issue_id }}"
      output:
        statusCode: 200
        body: "{{ output }}"
    events:
      - http:
          method: GET
          path: issues/{user}/{repo}/{issue_id}

plugins:
  - serverless-plugin-stackstorm

There are few new options inside the function definition (see serverless.example.yml for more options):

  • stackstorm.action allows you to pick up a function you want to turn into a lambda
  • stackstorm.config sets config parameters for the action. Config parameters are pack-wide in stackstorm and are commonly used for authentication tokens and such.
  • stackstorm.input defines how input event parameters should be transformed to match the parameters list stackstorm action expects
  • stackstorm.output defines the transformation that should be applied to the action output to form a result of lambda execution

If you are in doubt on the list of parameters given StackStorm action expects, check action info:

$ sls stackstorm info --action github.get_issue
github.get_issue .............. Retrieve information about a particular Github issue.
Parameters
  issue_id [string] (required)  Issue id
  repo [string] (required) .... Repository name.
  user [string] (required) .... User / organization name.
Config
  base_url [string] (required)  The GitHub URL, for GitHub Enterprise please set enterprise_url.
  deployment_environment [string] (required)  The environment for this StackStorm server.
  enterprise_url [string]  .... GitHub API url (including /api/v3) of your GitHub Enterprise hostname.
  github_type [string] (required)  Default to either github or enterprise.
  password [string]  .......... GitHub Password
  repository_sensor [object]  . Sensor specific settings.
  token [string] (required) ... GitHub oAuth Token
  user [string]  .............. GitHub Username

Then deploy your function to the cloud and invoke it:

sls deploy

sls invoke --function get_issue --log \
--data '{"pathParameters": {"user": "StackStorm", "repo": "st2", "issue_id": "3785"}}'

You can also invoke a function locally for testing. It runs in docker container to ensure compatibility with AWS lambda environment.

sls stackstorm docker run -f get_issue --verbose --passthrough -d '{"pathParameters": {"user": "StackStorm", "repo": "st2", "issue_id": "3785"}}'

Note the options:

  • --passthrough: skips actual invocation - comes handy to ensure the input maps to action parameters right, without invoking the body of the lambda.
  • --verbose: shows the transformation routine that happened for a particular input and output.

Here is an example of a verbose output:

Incoming event ->
{
  "issue_id": "222"
}
-> Parameter transformer ->
{
  "repo": "st2",
  "issue_id": "222",
  "user": "StackStorm"
}
-> Action call ->
{
  "result": {
    "url": "https://github.com/StackStorm/st2/pull/222",
    "created_at": "2014-07-14T19:25:46.000000+00:00",
    ...
  },
  "exit_code": 0,
  "stderr": "",
  "stdout": ""
}
-> Output transformer ->
{
  "result": "2014-07-14T19:25:46.000000+00:00"
}

Commands

The plugin also provides a few optional commands. You don't have to use them as they are all included into sls package, but they still might be handy in some situations.

  • sls stackstorm - Build λ with StackStorm
  • sls stackstorm clean - Clean StackStorm code
  • sls stackstorm docker pull - Pull λ docker image
  • sls stackstorm docker start - Start λ docker container
  • sls stackstorm docker stop - Stop λ docker container
  • sls stackstorm docker exec - Execute a command in λ docker container
  • sls stackstorm docker run - Execute a function in λ docker container
  • sls stackstorm install adapter - Install StackStorm adapter
  • sls stackstorm install deps - Install StackStorm dependencies
  • sls stackstorm install packs - Install a pack
  • sls stackstorm install packDeps - Install dependencies for packs
  • sls stackstorm info - Print information on the action

Exchange

The available packs can be discovered in StackStorm Exchange (https://exchange.stackstorm.com/). At the moment, the collection consist of 6500+ actions spread across 130 packs. We've yet to try them all, though, but the one we did are marked with serverless tag.

Contributing to Exchange

The StackStorm packs this plugin allows you to run on serverless infrastructure are all part of StackStorm Exchange. We encourage community members to contribute to this packs to enrich the entire ecosystem. The most simple way to help us is to try different packs, mark the one that works with serverless keyword and report ones that don't work for some reason. For now, the plugin only supports stackstorm's python runner, but they represent more than 90% of exchange actions.

Author: StackStorm
Source Code: https://github.com/StackStorm/serverless-plugin-stackstorm 
License: Apache-2.0 license

#serverless #stack #plugin #lambda 

Serverless StackStorm Plugin
Hermann  Frami

Hermann Frami

1656855960

Serverless Stack Termination Protection Plugin

Serverless Stack Termination Protection Plugin 

Description

Following deployment, the Serverless Framework does not have the option to enable termination protection for the CloudFormation stack. This plugin will enable the termination protection. It can also disable it by using a command line option. This plugin is designed for the Serverless Framework 1.x and above.

Requirements

  • Serverless Framework 3.x or greater.
  • Node 8.x or greater.
  • NPM 6.x or greater.

Use serverless-stack-termination-protection@1 if you need support for Serverless Framework 2.x or below.

Installation

Installing the Serverless Framework

Visit the Getting Started with the Serverless Framework to get started with the Serverless Framework.

Install with npm:

npm install -g serverless

Installing the Plugin

Install with npm:

npm install --save-dev serverless-stack-termination-protection

And then add the plugin to your serverless.yml file:

plugins:
  - serverless-stack-termination-protection

See the example(s).

Using the Plugin

Automatically Enable Termination Protection After Deployment

This plugin enables termination protection automatically after the deployment. Simply run the deploy:

sls deploy

Automatically Disable Termination Protection After Deployment

This plugin can disable termination protection automatically after the deployment.

Simply run the deploy with the --param option:

sls deploy --param disable-termination-protection

If you are using multiple params, make sure to separate them:

sls deploy --param disable-termination-protection --param some-other-param

Apply Protection to Specified Stages

You may apply protection for specific stages by listing the stages under a serverlessTerminationProtection custom property in the serverless yaml file.

custom:
  serverlessTerminationProtection:
    stages:
      - prod

Notes

Future version will:

  • Delete the stack forceably using sls remove --force.

Please request features or report problems using the issues page.

Author: miguel-a-calles-mba
Source Code: https://github.com/miguel-a-calles-mba/serverless-stack-termination-protection 
License: MIT license

#serverless #stack #cloud 

Serverless Stack Termination Protection Plugin
Hermann  Frami

Hermann Frami

1656848520

Serverless Stack Policy By Resource Type

serverless-stack-policy-by-resource-type

Serverless Framework plugin for automatically populating CloudFormation stack policy statements by resource type.

CloudFormation stack policies allow you to protect a resource from being accidentally replaced or deleted. However, it is easy to forget to update the stack policy when adding new resources that should be protected. This plugin accepts a list of resource types and automatically updates the stack policy upon new resources of that type.

For example, if all DynamoDB tables should be protected from replacement or deleted, you simply have to add

ResourceType:
  - AWS::DynamoDB::Table

to your stack policy statement.

Usage

Install the plugin:

npm install -D serverless-stack-policy-by-resource-type

Register the plugin in serverless.yml:

plugins:
  - serverless-stack-policy-by-resource-type

The following example will prevent CloudFormation from replacing or deleting the DDBTable resource or any S3 buckets except for the LoggingBucket S3 bucket:

provider:
  ...
  stackPolicy:
    - Effect: Allow
      Principal: '*'
      Action: 'Update:*'
      Resource: '*'
    - Effect: Deny
      Principal: '*'
      Action:
        - Update:Replace
        - Update:Delete

      # These resources are included in the stack policy statement.
      Resource:
        - LogicalResourceId/DDBTable

      # These resource types are parsed by this plugin
      # and converted to additional entries in `Resource`.
      ResourceType:
        - AWS::S3::Bucket

      # These resources are excluded from `Resource` after all resources by type are added.
      # This property allows you to intentionally remove a resource.
      ExcludeResource:
        - LogicalResourceId/LoggingBucket

Author: Neverendingqs
Source Code: https://github.com/neverendingqs/serverless-stack-policy-by-resource-type 
License: Apache-2.0 license

#serverless #stack #cloud 

Serverless Stack Policy By Resource Type
Hermann  Frami

Hermann Frami

1656841140

Serverless Plugin Stack Outputs

Serverless-plugin-stack-outputs

Displays stack outputs for your serverless stacks

Installation

Install the package:

npm install serverless-plugin-stack-outputs

Add it to your plugin list in serverless.yml:

plugins:
  - serverless-plugin-stack-outputs

And it will automagically work.

Usage

Whenever you call info or deploy with the --verbose option, the stack outputs will be appended:

sls info --verbose
sls deploy --verbose

You can also get just the stack outputs directly via:

sls info outputs

Example

Example

Author: svdgraaf
Source Code: https://github.com/svdgraaf/serverless-plugin-stack-outputs 
License: MIT license

#serverless #stack #outputs 

Serverless Plugin Stack Outputs
Hermann  Frami

Hermann Frami

1656833700

Serverless Stack Output Plugin

Serverless Stack Output Plugin

A serverless plugin to store output from your AWS CloudFormation Stack in JSON/YAML/TOML files, or to pass the output to a JavaScript function for further processing.

Usage

Install

$ > yarn add serverless-stack-output
$ > npm install serverless-stack-output

Configuration

plugins:
  - serverless-stack-output

custom:
  output:
    handler: scripts/output.handler # Same syntax as you already know
    file: .build/stack.toml # toml, yaml, yml, and json format is available

Handler

Based on the configuration above the plugin will search for a file scripts/output.js with the following content:

function handler (data, serverless, options) {
  console.log('Received Stack Output', data)
}

module.exports = { handler }

File Formats

Just name your file with a .json, .toml, .yaml, or .yml extension, and the plugin will take care of formatting your output. Please make sure the location where you want to save the file exists!

Contribution

You are more than welcome to contribute to this project! 😘 🙆

To make sure you have a pleasant experience, please read the code of conduct. It outlines core values and believes and will make working together a happier experience.

Example

The plugins works fine with serverless functions, as well as when using custom CloudFormation resources. The following example configuration will deploy an AWS Lambda function, API Gateway, SQS Queue, IAM User with AccessKey and SecretKey, and a static value:

Serverless.yml

service: sls-stack-output-example

plugins:
  - serverless-stack-output

package:
  exclude:
    - node_modules/**

custom:
  output:
    handler: scripts/output.handler
    file: .build/stack.toml

provider:
  name: aws
  runtime: nodejs6.10

functions:
  example:
    handler: functions/example.handle
    events:
      - http:
          path: example
          method: get
          cors: true

resources:
  Resources:
    ExampleQueue:
      Type: AWS::SQS::Queue
      Properties:
        QueueName: example-queue
    ExampleUser:
      Type: "AWS::IAM::User"
      Properties:
        UserName: example-user
        Policies:
          - PolicyName: ExampleUserSQSPolicy
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
                - Effect: "Allow"
                  Action:
                    - sqs:SendMessage
                  Resource:
                    - {"Fn::Join": [":", ["arn:aws:sqs:*", {"Ref": "AWS::AccountId"}, "example-queue"]]}
    ExampleUserKey:
      Type: AWS::IAM::AccessKey
      Properties:
        UserName:
          Ref: ExampleUser
  Outputs:
    ExampleUserKey:
      Value:
        Ref: ExampleUserKey
    ExampleUserSecret:
      Value: {"Fn::GetAtt": ["ExampleUserKey", "SecretAccessKey"]}
    ExampleStaticValue:
      Value: example-static-value

Stack Output

TOML

ExampleUserSecret = "YourUserSecretKey"
ExampleUserKey = "YourUserAccessKey"
ExampleLambdaFunctionQualifiedArn = "arn:aws:lambda:us-east-1:AccountID:function:sls-stack-output-example-dev-example:9"
ExampleStaticValue = "example-static-value"
ServiceEndpoint = "https://APIGatewayID.execute-api.us-east-1.amazonaws.com/dev"
ServerlessDeploymentBucketName = "sls-stack-output-example-serverlessdeploymentbuck-BucketID"

YAML

ExampleUserSecret: YourUserSecretKey
ExampleUserKey: YourUserAccessKey
ExampleLambdaFunctionQualifiedArn: 'arn:aws:lambda:us-east-1:AccountID:function:sls-stack-output-example-dev-example:9'
ExampleStaticValue: example-static-value
ServiceEndpoint: 'https://APIGatewayID.execute-api.us-east-1.amazonaws.com/dev'
ServerlessDeploymentBucketName: sls-stack-output-example-serverlessdeploymentbuck-BucketID

JSON

{
  "ExampleUserSecret": "YourUserSecretKey",
  "ExampleUserKey": "YourUserAccessKey",
  "ExampleLambdaFunctionQualifiedArn": "arn:aws:lambda:us-east-1:AccountID:function:sls-stack-output-example-dev-example:9",
  "ExampleStaticValue": "example-static-value",
  "ServiceEndpoint": "https://APIGatewayID.execute-api.us-east-1.amazonaws.com/dev",
  "ServerlessDeploymentBucketName": "sls-stack-output-example-serverlessdeploymentbuck-BucketID"
}

Author: sbstjn
Source Code: https://github.com/sbstjn/serverless-stack-output 
License: MIT license

#serverless #stack #lambda 

Serverless Stack Output Plugin
Hermann  Frami

Hermann Frami

1656826320

Stack Config Plugin for Serverless

Stack Config Plugin for Serverless

A serverless plugin to manage configurations for a micro-service stack.

Features

outputs - This downloads this service's outputs to a file in /PROJECT_ROOT/.serverless/stack-outputs.json and updates the config file in S3.

outputs download - This downloads the existing, combined, stack config file from S3.

Install

npm install --save serverless-plugin-stack-config

Usage

Add the plugin to your serverless.yml like the following:

NOTE: The script and backup properties are optional.

serverless.yml:

provider:
...

plugins:
  - serverless-plugin-stack-config

custom:
  stack-config:
    script: scripts/transform.js
    backup:
      s3:
        key: config/stack-config.json
        bucket: ${self:service}-${opt:env}
        shallow: true

functions:
...
resources:
...

Configure the Stack Output

You can now supply a script that you can use to transform the stack outputs before they are saved to file.

For example you could rename outputs or create new ones from the values received.

// scripts/transform.js

module.exports = async function transform(serverless, stackOutputs) {
  // rename
  stackOutputs.TrackingServiceEndpoint = stackOutputs.ServiceEndpoint;

  // delete
  delete stackOutputs.ServerlessDeploymentBucketName;
  delete stackOutputs.ServiceEndpoint;

  // return updated stack
  return stackOutputs;
}

Example shell commands:

serverless outputs --stage dev --region eu-west-1

serverless outputs download --stage dev --region eu-west-1
# with save directory location
serverless outputs download --stage dev --region eu-west-1 --path .

Limitations

If you are deploying several applications at the same time, there is the possibility that some data loss could occur in the event that multiple stacks are updating the config file in S3.

Author: Rawphp
Source Code: https://github.com/rawphp/serverless-plugin-stack-config 
License: MIT license

#serverless #stack #config 

Stack Config Plugin for Serverless
Hermann  Frami

Hermann Frami

1656796680

Serverless Plugin Split Stacks

serverless-plugin-split-stacks

This plugin migrates CloudFormation resources in to nested stacks in order to work around the 200 resource limit.

There are built-in migration strategies that can be turned on or off as well as defining your own custom migrations. It is a good idea to select the best strategy for your needs from the start because the only reliable method of changing strategy later on is to recreate the deployment from scratch. You configure this in your serverless.yml (defaults shown):

custom:
  splitStacks:
    perFunction: false
    perType: true
    perGroupFunction: false

Migration Strategies

Per Lambda

This splits resources off in to a nested stack dedicated to the associated Lambda function. This defaults to off in 1.x but will switch to enabled by default in 2.x

Per Type

This moves resources in to a nested stack for the given resource type. If Per Lambda is enabled, it takes precedence over Per Type.

Per Lambda Group

This splits resources off in to a nested stack dedicated to a set of Lambda functions and associated resources. If Per Lambda or Per Type is enabled, it takes precedence over Per Lambda Group. In order to control the number of nested stacks, following configurations are needed:

custom:
  splitStacks:
    nestedStackCount: 20 # Controls the number of created nested stacks
    perFunction: false
    perType: false
    perGroupFunction: true

Once set, the nestedStackCount configuration should never be changed because the only reliable method of changing it later on is to recreate the deployment from scratch.

Concurrency

In order to avoid API rate limit errors, it is possible to configure the plugin in 2 different ways:

  • Set nested stacks to depend on each others.
  • Set resources in the nested stack to depend on each others.

This feature comes with a 2 new configurations, stackConcurrency and resourceConcurrency :

custom:
  splitStacks:
    perFunction: true
    perType: false
    perGroupFunction: false
    stackConcurrency: 5 # Controls if enabled and how much stacks are deployed in parallel. Disabled if absent.
    resourceConcurrency: 10 # Controls how much resources are deployed in parallel. Disabled if absent.

Limitations

This plugin is not a substitute for fine-grained services - try to limit the size of your service. This plugin has a hard limit of 200 sub-stacks and does not try to create any kind of tree of nested stacks.

Advanced Usage

If you create a file in the root of your Serverless project called stacks-map.js this plugin will load it.

This file can customize migrations, either by exporting a simple map of resource type to migration, or a function that can have whatever logic you want.

module.exports = {
  'AWS::DynamoDB::Table': { destination: 'Dynamodb' }
}
module.exports = (resource, logicalId) => {
  if (logicalId.startsWith("Foo")) return { destination: 'Foo' };

  // Falls back to default
};

You can also point to your custom splitter from the custom block in your serverless file:

custom:
  splitStacks:
    custom: path/to/your/splitter.js

Be careful when introducing any customizations to default config. Many kind of resources (as e.g. DynamoDB tables) cannot be freely moved between CloudFormation stacks (that can only be achieved via full removal and recreation of the stage)

Force Migration

Custom migrations can specify { force: true } to force the migration of an existing resource in to a new stack. BE CAREFUL. This will cause a resource to be deleted and recreated. It may not even work if CloudFormation tries to create the new one before deleting the old one and they have a name or some other unique property that cannot have two resources existing at the same time. It can also mean a small window of downtime during this period, for example as an AWS::Lambda::Permission is deleted/recreated calls may be denied until IAM sorts things out.

Author: Dougmoscrop
Source Code: https://github.com/dougmoscrop/serverless-plugin-split-stacks 
License: 

#serverless #stack #plugin 

Serverless Plugin Split Stacks
Hermann  Frami

Hermann Frami

1655893860

Serverless Nested Stack

Serverless Nested Stack

Serverless plugin to Workaround for Cloudformation 200 resource limit

Install

Run npm install in your Serverless project.

$ npm install serverless-nested-stack --save-dev

Add the plugin to your serverless.yml file

plugins:
  - serverless-nested-stack

When you deploy using

sls deploy 

nested stack will be created using following structure

Parent-Stack

- LogStack
- ApiStack
  1. Parent-Stack Contains LogStack & ApiStack
  2. LogStack contains LogGroups & Roles
  3. ApiStack Contains Lambda functions and other resource

Note: Currently Tested with Lambda Functions, Api Resources & StepFunctions

Author: Aditmalik-synechron
Source Code: https://github.com/aditmalik-synechron/serverless-nested-stack 
License: 

#serverless #stack 

Serverless Nested Stack
Dixie  Wolff

Dixie Wolff

1655030040

Learn What The Stack Data Structureis, How Is It Implemented?

Stack is a linear collection of items where items are inserted and removed in a particular order. Stack is also called a LIFO Data Structure because it follows the "Last In First Out" principle i.e. the item that is inserted in the last is the one that is taken out first. In this video, we look at what the stack is, how is it implemented, what are the different operations you can perform on a stack, and some of the real-world usages of Stack. After watching this video, you will be able to answer the following questions:

- What is Stack Data Structure?
- What is LIFO principle?
- What are different operations you can perform on a Stack?
- What are some usage examples of Stack?
- How to implement stack in JavaScript?

#stack #datastructure 

Learn What The Stack Data Structureis, How Is It Implemented?
Diego  Elizondo

Diego Elizondo

1652506620

Manténgase Desbloqueado En La Revisión De Código

Acaba de terminar de escribir el nuevo flujo de pago para su aplicación de compras y ahora necesita agregar una función de códigos de promoción. Los códigos de promoción se construyen sobre el flujo de pago, pero te das cuenta de que no puedes construir sobre el flujo de pago porque tu primera solicitud de extracción aún no ha aterrizado, está atascada en la revisión del código. En otras palabras, estás bloqueado.

¿Qué vas a hacer? Tú podrías:

  1. Trabaje en otra cosa : esto no es increíble, tiene todo el código base para los comentarios en su cabeza en este momento, y pasar a otra cosa solo lo ralentizará.
  2. Moleste a su revisor : tampoco es genial, solo los ralentizará.
  3. Dóblalo en el primer PR : No hay nada que le guste más a un desarrollador que una revisión de código de miles de líneas.

O bien, podrías apilar.

¿Qué es apilar?

El apilamiento es el secreto mejor guardado de los desarrolladores de alto rendimiento. El principio es simple: una vez que haya terminado de escribir una función, la asigna a su rama de función, la mueve hacia arriba para revisarla y crea una rama a partir de esa rama de función.

Crédito del diagrama: Xiulung Choy

Espera, estás diciendo que siempre nos ramificamos de main. ¿Por qué me ramificaría de una rama característica?

La respuesta es bastante sencilla. La bifurcación de una rama de función le permite retomar su trabajo donde lo dejó. No es necesario esperar a que aparezca esa característica, simplemente bifurque y listo.

En Graphite, recientemente escribimos sobre cómo construir Wordle usando stacking . A continuación se muestra un edificio de relaciones públicas de Wordle todo a la vez: ‣

Y aquí hay una pila de ocho que hace lo mismo:

  1. Solicitud de extracción n.° 1: usar la aplicación Create React
  2. Solicitud de extracción n.º 2: Agregar entrada de teclado
  3. Solicitud de extracción n.º 3: realice un seguimiento de las conjeturas pasadas
  4. Solicitud de extracción n.º 4: compatibilidad con SCSS
  5. Solicitud de extracción n.º 5: mostrar qué letras son correctas
  6. Solicitud de extracción n.º 6: agregue una condición ganadora y un botón de reinicio
  7. Solicitud de extracción n.º 7: agregue un diccionario real con palabras
  8. Solicitud de extracción n.º 8: implementar scripts

Como revisor, ¿cuál de esos dos fue más fácil de leer? ¿Cuál es probable que revises más rápido? ¿Cuál crees que se fusionará primero? Háganos saber lo que piensa en la sección de comentarios.

Cómo incorporar el apilamiento en un entorno de equipo

Ahora, estoy seguro de que te estás preguntando, ¿esto confundirá a mis compañeros de equipo?

¡Buena pregunta! Y no, esto no confundirá a tus compañeros. Afortunadamente, GitHub tiene soporte básico incorporado para pilas.

Digamos que tiene una pila en marcha: main → checkout → promo_codes. Para crear esa pila, puede crear dos solicitudes de extracción en GitHub:

  • Una rama de fusión promo_codesencheckout
  • Una rama de fusión checkoutenmain

Una rama se fusiona con la rama debajo de ella en la pila y, como resultado, GitHub solo mostrará la diferencia entre esos dos cambios, lo que le permitirá a su revisor comprender la pila en partes pequeñas.

Cuando te fusiones checkoutcon main, volverás a orientar automáticamente la segunda solicitud de extracción para que ahora se fusione con main.

Dos cosas que hemos visto hacer a otros para ayudar a sus compañeros de equipo a comprender su pila:

  1. Mucha gente titula sus solicitudes de extracción con la posición en la pila, es decir, "[1/8] título de relaciones públicas", "[2/8] otro título de relaciones públicas").
  2. Algunos compañeros de equipo especialmente útiles dejan enlaces al resto de su pila en sus descripciones para ayudar a los revisores a navegar por la pila mientras la revisan.

Si esto último suena como una carga, aquí es donde las herramientas automatizadas pueden ayudar, lo cual discutiremos en una sección separada.

¿Por qué no más gente usa esto?

Si bien las herramientas de revisión de código de GitHub tienen soporte básico para el apilamiento , aún no es tan fácil de usar como lo es con Phabricator o Gerrit , donde el apilamiento es común. La mayoría de las personas no apilan porque las herramientas locales no son excelentes: en GitHub, si necesita editar la solicitud de extracción en la base de una pila, reorganizar las de arriba puede ser mucho trabajo.

Afortunadamente, gran parte de ese trabajo se puede automatizar y existen muchas herramientas que ayudan a administrar ese trabajo. Antes de comenzar con Graphite, usamos git-town , ghstack , branchless y otros.

Graphite fue una herramienta diseñada específicamente para llevar este flujo de trabajo a GitHub. Sincroniza sus pilas, agrega comentarios a GitHub para ayudar a orientar a sus revisores y puede comenzar a usarlo hoy, incluso si sus compañeros de trabajo en GitHub no están listos para cambiar sus flujos de trabajo.

¿Cómo apilar en un proyecto existente?

El flujo de trabajo habitual te hace doblar tu código en el primer PR. Con el apilamiento, puede dividir los cambios en varios PR, lo que le permite:

  • Aterriza cada cambio por separado
  • Ejecute CI en su contra
  • Mantenga la carga de trabajo de su revisor ligera, lo que lleva a revisiones más rápidas y exhaustivas.

Además, puede obtener más y más granularidad sobre los lanzamientos de funciones una vez que comience a desglosar sus cambios. Nuestro flujo de pago de ejemplo suena como una característica compleja; al menos, podría dividirse en varias solicitudes de extracción, una para los cambios del servidor y otra para los cambios del cliente.

Conclusión

Independientemente de lo que use, si quiere ser un desarrollador más rápido, simplemente comience a apilar.

Fuente: https://blog.logrocket.com/stay-unblocked-code-review-build-products-faster-with-stacking/

#code #stack 

Manténgase Desbloqueado En La Revisión De Código
高橋  花子

高橋 花子

1652506500

コードレビューでブロックを解除し、スタッキングで製品をより迅速に構築します

ショッピングアプリの新しいチェックアウトフローを書き終えたところで、プロモーションコード機能を追加する必要があります。プロモーションコードはチェックアウトフローの上に構築されますが、最初のプルリクエストがまだ届いていないため、チェックアウトフローの上に構築することはできません。コードレビューでスタックしています。言い換えれば、あなたはブロックされています。

あなたは何をしますか?あなたは出来る:

  1. 他の何かに取り組む:これは素晴らしいことではありません。現在、コメント用のコードベース全体が頭の中にあり、他の何かに移動すると速度が低下します。
  2. レビュアーに迷惑をかける:これも素晴らしいことではありません。速度落とすだけです。
  3. それを最初のPRに折りたたむ:開発者が数千行のコードレビュー以上に受け取るのが好きなものはありません

または、スタックすることもできます。

スタッキングとは何ですか?

スタッキングは、パフォーマンスの高い開発者にとって最もよく守られている秘密です。原則は単純です。機能の記述が完了したら、それを機能ブランチにコミットし、レビューのためにブランチを上に移動して、その機能ブランチからブランチを作成します。

図のクレジット:Xiulung Choy

ちょっと待ってください、あなたが言っているのは—私たちは常にから分岐していmainます。機能ブランチから分岐するのはなぜですか?

答えはかなり簡単です。機能ブランチから分岐すると、中断したところから作業を再開できます。その機能が着陸するのを待つ必要はありません。分岐して移動するだけです。

Graphiteで、最近、スタッキングを使用してWordleを構築する方法について書きました。以下は、Wordleのすべてを一度に構築するPRです。‣

そして、これが同じことをする8つのスタックです。

  1. プルリクエスト#1:CreateReactAppを使用する
  2. プルリクエスト#2:キーボード入力を追加
  3. プルリクエスト#3:過去の推測を追跡する
  4. プルリクエスト#4:SCSSサポート
  5. プルリクエスト#5:正しい文字を表示する
  6. プルリクエスト#6:勝利条件とリセットボタンを追加する
  7. プルリクエスト#7:単語を含む実際の辞書を追加する
  8. プルリクエスト#8:スクリプトをデプロイする

レビューアとして、この2つのうちどちらが読みやすかったですか?どちらを早くレビューする可能性がありますか?どちらが最初にマージされると思いますか?コメント欄でご意見をお聞かせください。

チーム環境にスタッキングを組み込む方法

さて、あなたが尋ねていると確信しています、これは私のチームメートを混乱させますか?

良い質問!いいえ、これでチームメートが混乱することはありません。ありがたいことに、GitHubにはスタックの基本的な組み込みサポートがあります。

スタックが進行中であるとしましょう:main → checkout → promo_codes。そのスタックを作成するには、GitHubで2つのプルリクエストを作成できます。

  • promo_codes1つのマージブランチcheckout
  • checkout1つのマージブランチmain

1つのブランチがスタック内のその下のブランチにマージされ、その結果、GitHubはこれら2つの変更の差分のみを表示し、レビュー担当者がスタックを一口サイズで理解できるようにします。

にマージcheckoutするmainと、2番目のプルリクエストが自動的に再ターゲットされ、にマージされmainます。

チームメイトがスタックを理解するのを助けるために他の人が行うことを私たちが見た2つのこと:

  1. 多くの人は、スタック内の位置でプルリクエストにタイトルを付けます。つまり、「[1/8] PRタイトル」、「[2/8]別のPRタイトル」)
  2. 特に役立つチームメイトの中には、スタックの残りの部分へのリンクを説明に残して、レビュー担当者がスタックをレビューしているときにスタックをナビゲートできるようにするものがあります。

この最後のビットが負担のように聞こえる場合は、自動ツールが役立つ場合があります。これについては、別のセクションで説明します。

なぜもっと多くの人がこれを使わないのですか?

GitHubのコードレビューツールはスタッキングを基本的にサポートしていますが、スタッキングが一般的であるPhabricatorGerritの場合ほど簡単ではありません。ローカルツールが優れていないため、ほとんどの人はスタックしません。GitHubでは、スタックのベースでプルリクエストを編集する必要がある場合、アップスタックのものをリベースするのは大変な作業になる可能性があります。

幸い、その作業の多くは自動化でき、その作業の管理に役立つツールはたくさんあります。Graphiteを開始する前は、git-townghstackbranchlessなどを使用していました。

Graphiteは、このワークフローをGitHubに導入するために設計されたツールでした。スタックを同期し、GitHubにコメントを追加してレビュー担当者の方向付けを支援します。また、GitHubの同僚がワークフローを変更する準備ができていない場合でも、今日から使用を開始できます。

既存のプロジェクトにスタックするにはどうすればよいですか?

通常のワークフローでは、コードを最初のPRに折りたたむ必要があります。スタッキングを使用すると、変更を複数のPRに分割できます。これにより、次のことが可能になります。

  • それぞれの変更を別々に着陸させる
  • それに対してCIを実行します
  • レビュー担当者の作業負荷を軽くして、より迅速で徹底的なレビューにつながる

さらに、変更を分解し始めると、機能リリースについてより詳細に知ることができます。この例のチェックアウトフローは複雑な機能のように聞こえます。少なくとも、サーバーの変更用とクライアントの変更用の複数のプルリクエストに分割できます。

結論

使用するものに関係なく、より高速な開発者になりたい場合は、スタックを開始するだけです。

ソース:https ://blog.logrocket.com/stay-unblocked-code-review-build-products-faster-with-stacking/

#code #stack 

コードレビューでブロックを解除し、スタッキングで製品をより迅速に構築します