Lawrence  Lesch

Lawrence Lesch

1662433080

Hotel: A Simple Process Manager for Developers

hotel

Start apps from your browser and use local domains/https automatically

Tip: if you don't enable local domains, hotel can still be used as a catalog of local servers.

Hotel works great on any OS (macOS, Linux, Windows) and with all servers ❤️

  • Node (Express, Webpack)
  • PHP (Laravel, Symfony)
  • Ruby (Rails, Sinatra, Jekyll)
  • Python (Django)
  • Docker
  • Go
  • Apache, Nginx
  • ...

To all the amazing people who have answered the Hotel survey, thanks so much <3 !

v0.8.0 upgrade

.localhost replaces .dev local domain and is the new default. See https://ma.ttias.be/chrome-force-dev-domains-https-via-preloaded-hsts/ for context.

If you're upgrading, please be sure to:

  1. Remove "tld": "dev" from your ~/.hotel/conf.json file
  2. Run hotel stop && hotel start
  3. Refresh your network settings

Support

If you are benefiting from hotel, you can support its development on Patreon.

You can view the list of Supporters here https://thanks.typicode.com.

Video

Features

  • Local domains - http://project.localhost
  • HTTPS via local self-signed SSL certificate - https://project.localhost
  • Wildcard subdomains - http://*.project.localhost
  • Works everywhere - macOS, Linux and Windows
  • Works with any server - Node, Ruby, PHP, ...
  • Proxy - Map local domains to remote servers
  • System-friendly - No messing with port 80, /etc/hosts, sudo or additional software
  • Fallback URL - http://localhost:2000/project
  • Servers are only started when you access them
  • Plays nice with other servers (Apache, Nginx, ...)
  • Random or fixed ports

Install

npm install -g hotel && hotel start

Hotel requires Node to be installed, if you don't have it, you can simply install it using one of the following method:

You can also visit https://nodejs.org.

Quick start

Local domains (optional)

To use local .localhost domains, you need to configure your network or browser to use hotel's proxy auto-config file or you can skip this step for the moment and go directly to http://localhost:2000

See instructions here.

Add your servers

# Add your server to hotel
~/projects/one$ hotel add 'npm start'
# Or start your server in the terminal as usual and get a temporary local domain
~/projects/two$ hotel run 'npm start' 

Visit localhost:2000 or http(s)://hotel.localhost.

Alternatively you can directly go to

http://localhost:2000/one
http://localhost:2000/two
http(s)://one.localhost
http(s)://two.localhost 

Popular servers examples

Using other servers? Here are some examples to get you started :)

hotel add 'ember server'                               # Ember
hotel add 'jekyll serve --port $PORT'                  # Jekyll
hotel add 'rails server -p $PORT -b 127.0.0.1'         # Rails
hotel add 'python -m SimpleHTTPServer $PORT'           # static file server (Python)
hotel add 'php -S 127.0.0.1:$PORT'                     # PHP
hotel add 'docker-compose up'                          # docker-compose
hotel add 'python manage.py runserver 127.0.0.1:$PORT' # Django
# ...

On Windows use "%PORT%" instead of '$PORT'

See a Docker example here..

Proxy requests to remote servers

Add your remote servers

~$ hotel add http://192.168.1.12:1337 --name aliased-address
~$ hotel add http://google.com --name aliased-domain 

You can now access them using

http://aliased-address.localhost # will proxy requests to http://192.168.1.12:1337
http://aliased-domain.localhost # will proxy requests to http://google.com

CLI usage and options

hotel add <cmd|url> [opts]
hotel run <cmd> [opts]

# Examples

hotel add 'nodemon app.js' --out dev.log  # Set output file (default: none)
hotel add 'nodemon app.js' --name name    # Set custom name (default: current dir name)
hotel add 'nodemon app.js' --port 3000    # Set a fixed port (default: random port)
hotel add 'nodemon app.js' --env PATH     # Store PATH environment variable in server config
hotel add http://192.168.1.10 --name app  # map local domain to URL

hotel run 'nodemon app.js'                # Run server and get a temporary local domain

# Other commands

hotel ls     # List servers
hotel rm     # Remove server
hotel start  # Start hotel daemon
hotel stop   # Stop hotel daemon

To get help

hotel --help
hotel --help <cmd>

Port

For hotel to work, your servers need to listen on the PORT environment variable. Here are some examples showing how you can do it from your code or the command-line:

var port = process.env.PORT || 3000
server.listen(port)
hotel add 'cmd -p $PORT'  # OS X, Linux
hotel add "cmd -p %PORT%" # Windows

Fallback URL

If you're offline or can't configure your browser to use .localhost domains, you can always access your local servers by going to localhost:2000.

Configurations, logs and self-signed SSL certificate

You can find hotel related files in ~/.hotel :

~/.hotel/conf.json
~/.hotel/daemon.log
~/.hotel/daemon.pid
~/.hotel/key.pem
~/.hotel/cert.pem
~/.hotel/servers/<app-name>.json

By default, hotel uses the following configuration values:

{
  "port": 2000,
  "host": '127.0.0.1',
  
  // Timeout when proxying requests to local domains
  "timeout": 5000,
  
  // Change this if you want to use another tld than .localhost
  "tld": 'localhost', 
  
  // If you're behind a corporate proxy, replace this with your network proxy IP (example: "1.2.3.4:5000")
  "proxy": false
}

To override a value, simply add it to ~/.hotel/conf.json and run hotel stop && hotel start

Third-party tools

FAQ

Setting a fixed port

hotel add --port 3000 'server-cmd $PORT' 

Adding X-Forwarded-* headers to requests

hotel add --xfwd 'server-cmd'

Setting HTTP_PROXY env

Use --http-proxy-env flag when adding your server or edit your server configuration in ~/.hotel/servers

hotel add --http-proxy-env 'server-cmd'

Proxying requests to a remote https server

hotel add --change-origin 'https://jsonplaceholder.typicode.com'

When proxying to a https server, you may get an error because your .localhost domain doesn't match the host defined in the server certificate. With this flag, host header is changed to match the target URL.

ENOSPC and EACCES errors

If you're seeing one of these errors in ~/.hotel/daemon.log, this usually means that there's some permissions issues. hotel daemon should be started without sudo and ~/.hotel should belong to $USER.

# to fix permissions
sudo chown -R $USER: $HOME/.hotel

See also, https://docs.npmjs.com/getting-started/fixing-npm-permissions

Configuring a network proxy IP

If you're behind a corporate proxy, replace "proxy" with your network proxy IP in ~/.hotel/conf.json. For example:

{
  "proxy": "1.2.3.4:5000"
}

Download Details:

Author: Typicode
Source Code: https://github.com/typicode/hotel 
License: MIT license

#javascript #front #local #https #proxy 

Hotel: A Simple Process Manager for Developers
Mike  Kozey

Mike Kozey

1661950320

Localizely SDK for Flutter Enables Over-the-air Translations Update

Localizely SDK

This package provides Over-the-Air translation updates and In-Context Editing from the Localizely platform.

Platform Support

AndroidiOSWebMacOSLinuxWindows

Prerequisites

As of version 2.4.0, an update of min platform versions is required:

Android: Require Android SDK 21 or newer

iOS: Require iOS 11 or newer

Over-the-Air translation updates

Update translations for your Flutter applications over the air. Learn more

Setup

Update pubspec.yaml file

dependencies:
  ...
  localizely_sdk: ^2.4.0

flutter_intl:
  ...
  localizely:
    ota_enabled: true # Required for Over-the-Air translation updates

Trigger localization files generation by Flutter Intl IDE plugin or by intl_utils library

Initialize Localizely SDK (e.g. main.dart file)

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:localizely_sdk/localizely_sdk.dart'; // Import sdk package
import 'generated/l10n.dart';

void main() {
  Localizely.init('<SDK_TOKEN>', '<DISTRIBUTION_ID>'); // Init sdk 
  Localizely.setPreRelease(true); // Add this only if you want to use prereleases
  Localizely.setAppVersion('<APP_VERSION>'); // Add this only if you want to explicitly set the application version, or in cases when automatic detection is not possible (e.g. Flutter web apps)

  runApp(MaterialApp(
      onGenerateTitle: (context) => S.of(context).appTitle,
      localizationsDelegates: [
        S.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: S.delegate.supportedLocales,
      home: HomePage()));
}

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();

    Localizely.updateTranslations().then( // Call 'updateTranslations' after localization delegates initialization
        (response) => setState(() {
              _isLoading = false;
            }),
        onError: (error) => setState(() {
              _isLoading = false;
            }));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text(S.of(context).pageHomeTitle)),
        body: Center(
            child: _isLoading ? CircularProgressIndicator() : Column(children: <Widget>[Text(S.of(context).welcome)])));
  }
}

In-Context Editing

Instantly see how your translations fit on a real device without unnecessary app builds. Learn more. Works with projects that use Flutter's gen_l10n approach for internationalization, and with projects that use Flutter Intl IDE plugin / intl_utils.

Setup for gen_l10n

Update pubspec.yaml file

dependencies:
  ...
  localizely_sdk: ^2.4.0

Generate localization files

flutter pub run localizely_sdk:generate

Update localizationsDelegates and supportedLocales props of the MaterialApp widget.

import 'package:flutter_gen/gen_l10n/localizely_localizations.dart';

class MyApp extends StatelessWidget {
  ...

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      ...
      localizationsDelegates: LocalizelyLocalizations.localizationsDelegates,
      supportedLocales: LocalizelyLocalizations.supportedLocales,
      ...
    );
  }
}

Wrap the root of the app (e.g. main.dart file)

import 'package:localizely_sdk/localizely_sdk.dart'; // Import sdk package

void main() {
  runApp(
    LocalizelyInContextEditing(
      enabled: true, // set to false to disable In-Context Editing for production app builds
      child: MyApp(),
    ),
  );
}

Connect to Localizely

Run Flutter app on a real device and connect with Localizely by scanning the QR code (for web & desktop apps paste the token).

Setup for Flutter Intl

Update pubspec.yaml file

dependencies:
  ...
  localizely_sdk: ^2.4.0

flutter_intl:
  ...
  localizely:
    ota_enabled: true # Required for In-Context Editing

Trigger localization files generation by Flutter Intl IDE plugin or by intl_utils library

Wrap the root of the app (e.g. main.dart file)

import 'package:localizely_sdk/localizely_sdk.dart'; // Import sdk package

void main() {
  runApp(
    LocalizelyInContextEditing(
      enabled: true, // set to false to disable In-Context Editing for production app builds
      child: MyApp(),
    ),
  );
}

Connect to Localizely

Run Flutter app on a real device and connect with Localizely by scanning the QR code (for web & desktop apps paste the token).

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add localizely_sdk

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

dependencies:
  localizely_sdk: ^2.4.0

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:localizely_sdk/localizely_sdk.dart';

Want to learn more?

Complete Over-the-Air documentation

Sample app with Over-the-Air translation updates

Complete In-Context Editing documentation

Sample app with In-Context Editing

Original article source at: https://pub.dev/packages/localizely_sdk 

#flutter #dart #sdk #local 

Localizely SDK for Flutter Enables Over-the-air Translations Update
Mike  Kozey

Mike Kozey

1661938320

A Simple Abstraction to Persist Data in The Local File System

Local_value

A simple abstraction to persist data in the local file system

Quickstart

//locally save a singleton:
final localCounterValue = LocalSingleton<int>(id: 'counter_val');
await localCounterValue.write(5);
print(await localCounterValue.read()); //5

//or save multiple related objects:
final localUserScores = LocalValue<int>(basePath: ['user_scores']);

await localUserScores.write('user_1', 15); 
await localUserScores.write('user_2', 24)

print(await localUserScores.read('user_1')); //prints 15
print(await localUserScores.read('user_2')); //prints 24

Features

helps save / load / delete singletons to local storage.

you can specify if the document is a application document, temporary document, support document, or shared prefrence. The distinction can be found here.

In short:

  • DocumentType.document: data that is user generated and cannot be recreated. (ex. my high score in a local-only game)
  • DocumentType.support: data that is NOT user generated and cannot be recreated. (ex. automatically set config files)
  • DocumentType.temporary: data that can be cleared at any time. (ex. caching a downloaded json)
  • DocumentType.secure: data that must be stored securely. (ex. a users API keys)
  • DocumentType.prefs: user preference (ex. should the app open in light mode)

NOTE: Web uses shared_preferences on the backend instead of real files. this is because on web, there is no notion of files.

Use cases

Saving the logged in user:

class CurrentUser {
    final int id;
    final String name;
    final Color favoriteColor;

    // insert toJson here
    // insert fromJson here
}

final locallyPersistedUser = localSingleton<CurrentUser>(
      id: 'current_user',
      fromJson: CurrentUser.fromJson,
      toJson: (currentUser) => currentUser.toJson());


//save and load the user to memory like this:
CurrentUser? myCurrentUser = await locallyPersistedUser.read();
await locallyPersistedUser.write(someUser);

Caching many things to memory to avoid redundant network calls:

final localUsers = LocalValue<User>(toJson: ..., fromJson: ...);

await localUsers.read(userOneId);
await localUsers.write(userTwoId, userTwo);

Strongly typed way to save things to shared preference:

final isDarkMode = LocalSingleton<User>(documentType: DocumentType.prefs, id: 'isDarkMode');
await isDarkMode.write(true);
final darkMode = await isDarkMode.read() ?? false;

LocalValue vs LocalSingleton

This package exposes LocalValue and LocalSingleton. both share a very similar API, but one key difference: LocalSingleton always saves to the same file - this is beneficial for use cases where you only need to store one value - something like the current user's data.

If you have to store data on many users, consider LocalValue, which requires an id for read, write, and delete

Usage


//preface: import it!
import 'package:local_value/local_value.dart';

//first, create some sort of data model you want to save to local storage.
//can be a primative (just use LocalValue<int> or similar)
class CounterObj {
    int value;

    CounterObj(this.value);
}


//localSingleton is used for singletons,
final counterFile = localSingleton<CounterObj>(
      documentType: DocumentType.document, //optional, defaults to document
      id: 'counter', //required to be unique

      //from and to json are required for primatives
      fromJson: (counterJson) => CounterObj(counterJson['value'] as int), 
      toJson: (counterObj) => {'value': counterObj.value}
    );



//read from it
CounterObj? myCurrentCounter = await counterStorage.read();

//write to it
await counterStorage.write(myCurrentCounter ?? CounterObj(8));

//clear it
await counterStorage.clear();

Additional information

If you find an issue, please post it on the github.

I am actively maintaining this package and am open to feature requests. Please leave an issue on the github for anything.

This package's inital development is complete (fully unit test covered, all initally planned features are complete) but feature requests are welcome. Since this is built as an abstraction over two very well tested packages (shared_preferences and path_provder), this package is stable.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add local_value

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

dependencies:
  local_value: ^1.1.2

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:local_value/local_value.dart';

example/lib/main.dart

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

class CounterObj {
  int value;

  CounterObj(this.value);
}

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final counterStorage = LocalSingleton<int>(id: 'counter');

  MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Local Data Manager Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      floatingActionButton: Builder(
          builder: (context) => Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  FloatingActionButton(
                    onPressed: () => widget.counterStorage.read().then((value) {
                      if (value == null) {
                        ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(
                                content: Text('no local data saved')));
                        return;
                      }

                      setState(() {
                        _counter = value;
                      });
                    }),
                    backgroundColor: Colors.orange,
                    child: const Icon(Icons.replay),
                  ),
                  FloatingActionButton(
                    onPressed: () =>
                        widget.counterStorage.write(_counter).then((_) {
                      ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('saved!')));
                    }),
                    backgroundColor: Colors.green,
                    child: const Icon(Icons.save),
                  ),
                  FloatingActionButton(
                    onPressed: _incrementCounter,
                    child: const Icon(Icons.add),
                  ),
                ],
              )),
    );
  }
}

Download Details:

Author: Antholeole
Source Code: https://github.com/antholeole/ants_packages/ 
License: MIT

#flutter #dart #local #value 

A Simple Abstraction to Persist Data in The Local File System
Reid  Rohan

Reid Rohan

1661785097

Localtunnel: Expose Yourself

localtunnel

localtunnel exposes your localhost to the world for easy testing and sharing! No need to mess with DNS or deploy just to have others test out your changes.

Great for working with browser testing tools like browserling or external api callback services like twilio which require a public url for callbacks.

Quickstart

npx localtunnel --port 8000

Installation

Globally

npm install -g localtunnel

As a dependency in your project

yarn add localtunnel

CLI usage

When localtunnel is installed globally, just use the lt command to start the tunnel.

lt --port 8000

Thats it! It will connect to the tunnel server, setup the tunnel, and tell you what url to use for your testing. This url will remain active for the duration of your session; so feel free to share it with others for happy fun time!

You can restart your local server all you want, lt is smart enough to detect this and reconnect once it is back.

Arguments

Below are some common arguments. See lt --help for additional arguments

  • --subdomain request a named subdomain on the localtunnel server (default is random characters)
  • --local-host proxy to a hostname other than localhost

You may also specify arguments via env variables. E.x.

PORT=3000 lt

API

The localtunnel client is also usable through an API (for test integration, automation, etc)

localtunnel(port [,options][,callback])

Creates a new localtunnel to the specified local port. Will return a Promise that resolves once you have been assigned a public localtunnel url. options can be used to request a specific subdomain. A callback function can be passed, in which case it won't return a Promise. This exists for backwards compatibility with the old Node-style callback API. You may also pass a single options object with port as a property.

const localtunnel = require('localtunnel');

(async () => {
  const tunnel = await localtunnel({ port: 3000 });

  // the assigned public url for your tunnel
  // i.e. https://abcdefgjhij.localtunnel.me
  tunnel.url;

  tunnel.on('close', () => {
    // tunnels are closed
  });
})();

options

  • port (number) [required] The local port number to expose through localtunnel.
  • subdomain (string) Request a specific subdomain on the proxy server. Note You may not actually receive this name depending on availability.
  • host (string) URL for the upstream proxy server. Defaults to https://localtunnel.me.
  • local_host (string) Proxy to this hostname instead of localhost. This will also cause the Host header to be re-written to this value in proxied requests.
  • local_https (boolean) Enable tunneling to local HTTPS server.
  • local_cert (string) Path to certificate PEM file for local HTTPS server.
  • local_key (string) Path to certificate key file for local HTTPS server.
  • local_ca (string) Path to certificate authority file for self-signed certificates.
  • allow_invalid_cert (boolean) Disable certificate checks for your local HTTPS server (ignore cert/key/ca options).

Refer to tls.createSecureContext for details on the certificate options.

Tunnel

The tunnel instance returned to your callback emits the following events

eventargsdescription
requestinfofires when a request is processed by the tunnel, contains method and path fields
errorerrfires when an error happens on the tunnel
close fires when the tunnel has closed

The tunnel instance has the following methods

methodargsdescription
close close the tunnel

other clients

Clients in other languages

go gotunnelme

go go-localtunnel

C#/.NET localtunnel-client

Rust rlt

server

See localtunnel/server for details on the server that powers localtunnel.

Download Details:

Author: localtunnel
Source Code: https://github.com/localtunnel/localtunnel 
License: MIT license

#javascript #local #expose 

Localtunnel: Expose Yourself
Monty  Boehm

Monty Boehm

1660296240

A Julia Package to Fold All Local & Long-range RNA Duplexes

EvoDuplexes.jl 

RNA suffix array traversal through chromosomal multiple alignment files (MAF format) to fold and score (with both free-energy models and phylogenetic likelihood) all local and long-range RNA duplexes while allowing bulges and mismatches.

Full documentation is coming soon (Requires Julia v0.6.4), however comprehensive examples of API usage for EvoDuplexes package can be found in test/runtests.jl.

Executable can be run using evo-duplex.jl in /bin:

$ julia evo-duplex.jl -h
usage: evo-duplex.jl --tree TREE [--cons-regions CONS-REGIONS]
                     --gene-regions GENE-REGIONS --maf MAF
                     [--model-load MODEL-LOAD]
                     [--model-data MODEL-DATA] [--model-train]
                     [-o OUTPUT] [--cons-branch CONS-BRANCH]
                     [--sig-ratio SIG-RATIO] [--output-all]
                     [--max-distance MAX-DISTANCE]
                     [--max-duplex-length MAX-DUPLEX-LENGTH]
                     [--max-bulges MAX-BULGES]
                     [--max-mismatches MAX-MISMATCHES]
                     [--max-deltag MAX-DELTAG] [-h]

optional arguments:
  --tree TREE           Phylogenetic tree with neutral branch lengths
                        (in newick format)
  --cons-regions CONS-REGIONS
                        BED file containing conserved regions
  --gene-regions GENE-REGIONS
                        BED file containing gene units to allow
                        long-range folding within
  --maf MAF             Directory with MAF files named by chromosome
                        (chr1.maf.gz...) (default: "../maf")
  --model-load MODEL-LOAD
                        Load pre-trained IsolationForest models,
                        .evt.jls
  --model-data MODEL-DATA
                        Load training data from `.jlt` file, output
                        `.evt.jls` file
  --model-train         Train the IsolationForest models from scratch
                        using input regions, output `.evt.jls` file
  -o, --output OUTPUT   Output prefix (default: "evoduplex")
  --cons-branch CONS-BRANCH
                        When conserved regions are given, use this
                        branch length multiplier (type: Float64,
                        default: 0.33)
  --sig-ratio SIG-RATIO
                        Output the top fraction of outliers (type:
                        Float64, default: 0.05)
  --output-all          Output all folds regardless of prediction
                        status
  --max-distance MAX-DISTANCE
                        Set a limit on the maximum distance between a
                        left/right arm of a duplex (type: Int64,
                        default: 2000)
  --max-duplex-length MAX-DUPLEX-LENGTH
                        Set the maximum duplex length that will be
                        accessible from the suffix array (type: Int64,
                        default: 50)
  --max-bulges MAX-BULGES
                        Set the maximum number of bulges to allow for
                        a duplex (type: Int64, default: 3)
  --max-mismatches MAX-MISMATCHES
                        Set the maximum number of mismatches to allow
                        for a duplex (type: Int64, default: 3)
  --max-deltag MAX-DELTAG
                        Set the maximum allowable deltaG value (type:
                        Float64, default: -8.0)
  -h, --help            show this help message and exit

Download Details:

Author: Timbitz
Source Code: https://github.com/timbitz/EvoDuplexes.jl 
License: MIT license

#julia #local #array 

A Julia Package to Fold All Local & Long-range RNA Duplexes
Mike  Kozey

Mike Kozey

1659318180

A JSON File-based Storage Package Provides A Persistent Repository

Localstore

Between SQL or NoSQL, there's no one best database, there's the right database for your specific project. Localstore is a JSON file-based storage package (localstorage) provides a persistent repository for simple NoSQL database.

 Localstore (NoSQL)SQLite (SQL)
Data formatFile path (collection)Table
Data itemJSON Document (doc)Record / Row
ScalabilityHorizontalLimited vertical
OrganizationSchema-lessFixed schema

Demo Screenshot

Getting Started

Calling WidgetsFlutterBinding.ensureInitialized(); in main() before calling runApp():

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

Import import 'package:localstore/localstore.dart';

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

Creates an instance using the default Localstore

final db = Localstore.instance;

or using anywhere in your project.

Creates new item

// gets new id
final id = db.collection('todos').doc().id;

// save the item
db.collection('todos').doc(id).set({
  'title': 'Todo title',
  'done': false
});

Gets item by id

final data = await db.collection('todos').doc(id).get();

Delete item by id

db.collection('todos').doc(id).delete();

Fetch the documents for the collection

final items = await db.collection('todos').get();

Using stream

final stream = db.collection('todos').stream;

Installing

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add localstore

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

dependencies:
  localstore: ^1.2.3

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:localstore/localstore.dart';

example/lib/main.dart

import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:localstore/localstore.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Localstore Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Localstore Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, this.title}) : super(key: key);

  final String? title;

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

class _MyHomePageState extends State<MyHomePage> {
  final _db = Localstore.instance;
  final _items = <String, Todo>{};
  StreamSubscription<Map<String, dynamic>>? _subscription;

  @override
  void initState() {
    /*
    _db.collection('todos').get().then((value) {
      setState(() {
        value?.entries.forEach((element) {
          final item = Todo.fromMap(element.value);
          _items.putIfAbsent(item.id, () => item);
        });
      });
    });
    */
    _subscription = _db.collection('todos').stream.listen((event) {
      setState(() {
        final item = Todo.fromMap(event);
        _items.putIfAbsent(item.id, () => item);
      });
    });
    if (kIsWeb) _db.collection('todos').stream.asBroadcastStream();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title!)),
      body: ListView.builder(
        itemCount: _items.keys.length,
        itemBuilder: (context, index) {
          final key = _items.keys.elementAt(index);
          final item = _items[key]!;
          return Card(
            child: CheckboxListTile(
              value: item.done,
              title: Text(item.title),
              onChanged: (value) {
                item.done = value!;
                item.save();
              },
              secondary: IconButton(
                icon: const Icon(Icons.delete),
                onPressed: () {
                  setState(() {
                    item.delete();
                    _items.remove(item.id);
                  });
                },
              ),
            ),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          final id = Localstore.instance.collection('todos').doc().id;
          final now = DateTime.now();
          final item = Todo(
            id: id,
            title: now.toIso8601String(),
            time: now,
            done: false,
          );
          item.save();
          _items.putIfAbsent(item.id, () => item);
        },
        tooltip: 'add',
        child: const Icon(Icons.add),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
    );
  }

  @override
  void dispose() {
    if (_subscription != null) _subscription?.cancel();
    super.dispose();
  }
}

/// Data Model
class Todo {
  final String id;
  String title;
  DateTime time;
  bool done;
  Todo({
    required this.id,
    required this.title,
    required this.time,
    required this.done,
  });

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'title': title,
      'time': time.millisecondsSinceEpoch,
      'done': done,
    };
  }

  factory Todo.fromMap(Map<String, dynamic> map) {
    return Todo(
      id: map['id'],
      title: map['title'],
      time: DateTime.fromMillisecondsSinceEpoch(map['time']),
      done: map['done'],
    );
  }
}

extension ExtTodo on Todo {
  Future save() async {
    final _db = Localstore.instance;
    return _db.collection('todos').doc(id).set(toMap());
  }

  Future delete() async {
    final _db = Localstore.instance;
    return _db.collection('todos').doc(id).delete();
  }
}

Features and bugs

Please file feature requests and bugs at the issue tracker.

Author: Chuyentt
Source Code: https://github.com/chuyentt/localstore 
License: MIT license

#flutter #dart #local #json 

A JSON File-based Storage Package Provides A Persistent Repository
Mike  Kozey

Mike Kozey

1658698620

tlfs: The Local First SDK for Dart

The Local-First SDK

Philosophy

There is no cloud, it's just someone else's computer.

The Local-First SDK offers a stack to write applications as productively as when using state-of-the-art cloud-based architectures, while providing the Seven Ideals for Local-First Software 0 -- basically for free:

  • Software can respond near-instantaneously to user input. (No waiting on server round-trips, no spinners.)
  • Cross-device synchronization. (Pick up work on your mobile device just where you left off with your laptop.)
  • "Offline-First" as a subset of Local-First. (Connectivity is irrelevant when interacting with the application>0
  • Seamless collaboration with other peers. (Edit and sync shared data without fear of conflicts.)
  • Full data agency. (Do what you want with your data, it's yours only.)
  • Secure and private data management. (Everything is encrypted, only you have the keys.)
  • Full ownership and control over the application's data. (No one can take away a service from you.)

Components

The Local-First SDK comprises the following components:

  1. User and Access Control: ... (key management, acl)
  2. Multi-Device Support and Collaboration: ... (device auth, p2p, peer discovery (mdns and via cloud peer))
  3. Data Persistence ... (cloud peer or self-hosted)
  4. Multi device support and interoperability ... (browser, native, android/ios?)

Artifacts

The Local-First SDK comes in three flavours:

  1. An opinionated Javascript package (with Typescript bindings) to write Local-First applications targeting the browser.
  2. A library which can be embedded into other applications, either as a rust library or a C-compatible FFI.
  3. A native, permanent process shepherding the user's data. Applications can interface with this daemon via HTTP.

The Local-First Javascript SDK

As the browser's API guarantees are weak, its environment has to be considered ephemeral[^1]. This is why the optional Cloud-Peer supplemental services complement the browser environment very well (data persistence, peer discovery).

As of now, the SDK is just offered as an ES module, requiring asynchronous import:

import * as localFirst from 'local-first';

await localFirst.init();

[..]

[^1]: Most notably this is about persistence of user data (key material and application data). However, it's easy to lose one's browsing data by switching to another browser profile/container, etc.


Under the hood

Rust, libp2p, crdts, cambria, .. --> INSERT AWESOMENESS HERE <--


Installing

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add tlfs

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

dependencies:
  tlfs: ^0.1.0+10

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:tlfs/tlfs.dart';

Author: cloudpeers
Source Code: https://github.com/cloudpeers/tlfs 
License: MIT license

#flutter #dart #sdk #local 

tlfs: The Local First SDK for Dart
Nat  Grady

Nat Grady

1658309580

Add Keyboard Shortcuts Locally to A BrowserWindow instance

electron-localshortcut

A module to register/unregister a keyboard shortcut locally to a BrowserWindow instance, without using a Menu.

This is built to circumvent this Electron issue.   

Installation

npm install --save electron-localshortcut

Usage

    const electronLocalshortcut = require('electron-localshortcut');
    const BrowserWindow = require('electron').BrowserWindow;

    const win = new BrowserWindow();
    win.loadUrl('https://github.com');
    win.show();

    electronLocalshortcut.register(win, 'Ctrl+A', () => {
        console.log('You pressed ctrl & A');
    });

    electronLocalshortcut.register(win, 'Ctrl+B', () => {
        console.log('You pressed ctrl & B');
    });

    electronLocalshortcut.register(win, ['Ctrl+R', 'F5'], () => {
        console.log('You pressed ctrl & R or F5');
    });

    console.log(
        electronLocalshortcut.isRegistered(win, 'Ctrl+A')
    );      // true

    electronLocalshortcut.unregister(win, 'Ctrl+A');
    electronLocalshortcut.unregisterAll(win);

App shortcuts.

If you omit the window argument of isRegistered, unregisterAll, unregister and register methods, the shortcut is registered as an app shortcut. It is active when any window of the app is focused.

They differ from native global-shortcuts because they doesn't interfere with other apps running on the same machine.

Shortcut behaviour.

If you register a shortcut for a window, this module unregister the shortcut when the window is hidden, unfocused or minimized, and automatically restore it when the window is restored and focused again.

If you register an app shortcut, this module unregister the shortcut when all windows of your app are hidden, unfocused or minimized, and automatically restore it when any window of your app is restored and focused again.

API

disableAll

Disable all of the shortcuts registered on the BrowserWindow instance. Registered shortcuts no more works on the window instance, but the module keep a reference on them. You can reactivate them later by calling enableAll method on the same window instance.

Parameters

  • win BrowserWindow BrowserWindow instance

Returns Undefined

enableAll

Enable all of the shortcuts registered on the BrowserWindow instance that you had previously disabled calling disableAll method.

Parameters

  • win BrowserWindow BrowserWindow instance

Returns Undefined

unregisterAll

Unregisters all of the shortcuts registered on any focused BrowserWindow instance. This method does not unregister any shortcut you registered on a particular window instance.

Parameters

  • win BrowserWindow BrowserWindow instance

Returns Undefined

register

Registers the shortcut acceleratoron the BrowserWindow instance.

Parameters

  • win BrowserWindow BrowserWindow instance to register. This argument could be omitted, in this case the function register the shortcut on all app windows.
  • accelerator (String | Array<String>) the shortcut to register
  • callback Function This function is called when the shortcut is pressed and the window is focused and not minimized.

Returns Undefined

unregister

Unregisters the shortcut of accelerator registered on the BrowserWindow instance.

Parameters

  • win BrowserWindow BrowserWindow instance to unregister. This argument could be omitted, in this case the function unregister the shortcut on all app windows. If you registered the shortcut on a particular window instance, it will do nothing.
  • accelerator (String | Array<String>) the shortcut to unregister

Returns Undefined

isRegistered

Returns true or false depending on whether the shortcut accelerator is registered on window.

Parameters

  • win BrowserWindow BrowserWindow instance to check. This argument could be omitted, in this case the function returns whether the shortcut accelerator is registered on all app windows. If you registered the shortcut on a particular window instance, it return false.
  • accelerator String the shortcut to check

Returns Boolean if the shortcut accelerator is registered on window.

Author: Parro-it
Source Code: https://github.com/parro-it/electron-localshortcut 
License: MIT license

#electron #local #windows #browser 

Add Keyboard Shortcuts Locally to A BrowserWindow instance
Gordon  Taylor

Gordon Taylor

1657086300

An Abstract-leveldown Compliant Store using Localforage As Its Backend

localforagedown  

This is an abstract-leveldown compliant store that uses localforage as it backend.

Install

yarn add localforagedown
# or npm
npm install localforagedown

API

Please refrence LevelDOWN for API. If you want a easier experience, use it with LevelUP.

Author: Shanoaice 
Source Code: https://github.com/shanoaice/localforagedown 
License: MIT license

#javascript #local 

An Abstract-leveldown Compliant Store using Localforage As Its Backend
Hermann  Frami

Hermann Frami

1656592140

Serverless S3 Local

serverless-s3-local

serverless-s3-local is a Serverless plugin to run S3 clone in local. This is aimed to accelerate development of AWS Lambda functions by local testing. I think it is good to collaborate with serverless-offline.

Installation

Use npm

npm install serverless-s3-local --save-dev

Use serverless plugin install

sls plugin install --name serverless-s3-local

Example

serverless.yaml

service: serverless-s3-local-example
provider:
  name: aws
  runtime: nodejs12.x
plugins:
  - serverless-s3-local
  - serverless-offline
custom:
# Uncomment only if you want to collaborate with serverless-plugin-additional-stacks
# additionalStacks:
#    permanent:
#      Resources:
#        S3BucketData:
#            Type: AWS::S3::Bucket
#            Properties:
#                BucketName: ${self:service}-data
  s3:
    host: localhost
    directory: /tmp
resources:
  Resources:
    NewResource:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: local-bucket
functions:
  webhook:
    handler: handler.webhook
    events:
      - http:
        method: GET
        path: /
  s3hook:
    handler: handler.s3hook
    events:
      - s3: local-bucket
        event: s3:*

handler.js (AWS SDK v2)

const AWS = require("aws-sdk");

module.exports.webhook = (event, context, callback) => {
  const S3 = new AWS.S3({
    s3ForcePathStyle: true,
    accessKeyId: "S3RVER", // This specific key is required when working offline
    secretAccessKey: "S3RVER",
    endpoint: new AWS.Endpoint("http://localhost:4569"),
  });
  S3.putObject({
    Bucket: "local-bucket",
    Key: "1234",
    Body: new Buffer("abcd")
  }, () => callback(null, "ok"));
};

module.exports.s3hook = (event, context) => {
  console.log(JSON.stringify(event));
  console.log(JSON.stringify(context));
  console.log(JSON.stringify(process.env));
};

handler.js (AWS SDK v3)

const { S3Client, PutObjectCommand } = require("@aws-sdk/client-s3");

module.exports.webhook = (event, context, callback) => {
  const client = new S3Client({
    forcePathStyle: true,
    credentials: {
      accessKeyId: "S3RVER", // This specific key is required when working offline
      secretAccessKey: "S3RVER",
    },
    endpoint: "http://localhost:4569",
  });
  client
    .send(
      new PutObjectCommand({
        Bucket: "local-bucket",
        Key: "1234",
        Body: Buffer.from("abcd"),
      })
    )
    .then(() => callback(null, "ok"));
};

module.exports.s3hook = (event, context) => {
  console.log(JSON.stringify(event));
  console.log(JSON.stringify(context));
  console.log(JSON.stringify(process.env));
};

Configuration options

Configuration options can be defined in multiple ways. They will be parsed with the following priority:

  • custom.s3 in serverless.yml
  • custom.serverless-offline in serverless.yml
  • Default values (see table below)
OptionDescriptionTypeDefault value
addressThe host/IP to bind the S3 server tostring'localhost'
hostThe host where internal S3 calls are made. Should be the same as addressstring 
portThe port that S3 server will listen tonumber4569
directoryThe location where the S3 files will be created. The directory must exist, it won't be createdstring'./buckets'
accessKeyIdThe Access Key Id to authenticate requestsstring'S3RVER'
secretAccessKeyThe Secret Access Key to authenticate requestsstring'S3RVER'
corsThe S3 CORS configuration XML. See AWS docsstring | Buffer 
websiteThe S3 Website configuration XML. See AWS docsstring | Buffer 
noStartSet to true if you already have an S3rver instance runningbooleanfalse
allowMismatchedSignaturesPrevent SignatureDoesNotMatch errors for all well-formed signaturesbooleanfalse
silentSuppress S3rver log messagesbooleanfalse
serviceEndpointOverride the AWS service root for subdomain-style accessstringamazonaws.com
httpsProtocolTo enable HTTPS, specify directory (relative to your cwd, typically your project dir) for both cert.pem and key.pem files.string 
vhostBucketsDisable vhost-style access for all bucketsbooleantrue
bucketsExtra bucket names will be created after starting S3 localstring 

Feature

  • Start local S3 server with specified root directory and port.
  • Create buckets at launching.
  • Support serverless-plugin-additional-stacks
  • Support serverless-webpack
  • Support serverless-plugin-existing-s3
  • Support S3 events.

Working with IaC tools

If your want to work with IaC tools such as terraform, you have to manage creating bucket process. In this case, please follow the below steps.

  1. Comment out configurations about S3 Bucket from resources section in serverless.yml.
#resources:
#  Resources:
#    NewResource:
#      Type: AWS::S3::Bucket
#      Properties:
#        BucketName: local-bucket
  1. Create bucket directory in s3rver working directory.
$ mkdir /tmp/local-bucket

Triggering AWS Events offline

This plugin will create a temporary directory to store mock S3 info. You must use the AWS cli to trigger events locally. First, using aws configure set up a new profile, i.e. aws configure --profile s3local. The default creds are

aws_access_key_id = S3RVER
aws_secret_access_key = S3RVER

You can now use this profile to trigger events. e.g. to trigger a put-object on a file at ~/tmp/userdata.csv in a local bucket run: aws --endpoint http://localhost:4569 s3 cp ~/tmp/data.csv s3://local-bucket/userdata.csv --profile s3local

You should see the event trigger in the serverless offline console: info: PUT /local-bucket/user-data.csv 200 16ms 0b and a new object with metadata will appear in your local bucket.

See also

Author: ar90n
Source Code: https://github.com/ar90n/serverless-s3-local 
License: MIT license

#serverless #s3 #lambda #local 

Serverless S3 Local
Hermann  Frami

Hermann Frami

1656024000

Serverless Offline Local Authorizers Plugin

serverless-offline-local-authorizers-plugin

Serverless plugin for adding authorizers when developing and testing functions locally with serverless-offline

This plugin allows you to add local authorizer functions to your serverless projects. These authorizers are added dynamically in a way they can be called by serverless-offline but don't interfer with your deployment and your shared authorizer functions. This helps when you have shared API Gateway authorizers and developing and testing locally with serverless-offline.

Installation

Installing using npm:

npm i serverless-offline-local-authorizers-plugin --save-dev

Usage

Step 1: Define your authorizer functions in a file called local-authorizers.js and put it into your project root (that's where your serverless.yml lives).

If you want the local function to call your deployed shared authorizer it could look something like this:

const AWS = require("aws-sdk");
const mylocalAuthProxyFn = async (event, context) => {

  const lambda = new AWS.Lambda();
  const result = await lambda.invoke({
    FunctionName: "my-shared-lambda-authorizer",
    InvocationType: "RequestResponse",
    Payload: JSON.stringify(event),
  }).promise();

  if (result.StatusCode === 200) {
    return JSON.parse(result.Payload);
  }

  throw Error("Authorizer error");
};

module.exports = { mylocalAuthProxyFn };

Of course you could also just return a mocked response, call Cognito to mock your Cognito Authorizer or whatever suits your needs. You can also define multiple authorizer functions if you need to.

Step 2: In your serverless.yml, add the localAuthorizer property to your http events. This will not interfere with your "real" authorizers and will be ignored upon deployment.

functions:
  myFunction:
    handler: myFunction.handler
    events:
      - http:
          path: /my/api/path
          method: GET
          authorizer:
            type: CUSTOM
            authorizerId: abcjfk
          localAuthorizer:
            name: "mylocalAuthProxyFn"
            type: "request"

Step 3: Add the plugin to the plugins sections in serverless.yml:

plugins:
  - serverless-offline-local-authorizers-plugin
  - serverless-offline

Step 4: Fire up serverless offline with the local-authorizers option:

$ sls offline local-authorizers --stage dev --region eu-central-1

⚠️ If you are using this plugin and get schema validation errors: Please check indentation of localAuthorizer: config property! See example below...

Author: nlang
Source Code: https://github.com/nlang/serverless-offline-local-authorizers-plugin 
License: MIT license

#serverless #local #plugin 

Serverless Offline Local Authorizers Plugin
Hunter  Krajcik

Hunter Krajcik

1655617620

LocalRegex: Collection of regex patterns commonly used in Zimbabwe

LocalRegex

This plugin allows developers to check if an input matches common regex patterns in Zimbabwe and other countries. This plugin works for all Flutter supported platforms i.e. Android, iOS, Web and Desktop (Linux, Windows & MacOS).

Developed by Ngonidzashe Mangudya. Special shoutout to Kudakwashe Kuzvindiwana for pushing this package the most.

Usage

Add dependency

dependencies:
  localregex: ^3.0.3

Or

flutter pub add localregex

Import package

  import 'package:localregex/localregex.dart';

Note that declaration and initialization is no longer necessary

Check if a mobile number matches patterns for Econet, Netone or Telecel numbers

LocalRegex.isNetone('mobile_number');
LocalRegex.isEconet('mobile_number');
LocalRegex.isTelecel('mobile_number');

Check if a mobile number matches any of the patterns for Econet, Netone or Telecel

LocalRegex.isValidZimMobile('mobile_number');

Check if mobile number is valid (recommended for numbers not from Zimbabwe)

LocalRegex.isValidMobile('mobile_number');

Check if a supplied email matches proper email patterns

localregex.isEmail('email_address');

Check if a supplied national id matches the pattern for Zimbabwean national id

localregex.isValidZimID('national_id');

Check passport number

localregex.isValidZimPassport('passport_number');

Check number plate

localregex.isValidZimVehicleNumberPlate('number_plate');

Check driver's license

localregex.isValidZimDriversLicence('drivers_license');

Check mobile number and returns mobile number in required format (for use with Zim numbers only)

String? number = LocalRegex.formatNumber(
  value: '+263777213388',
  type: FormatTypes.regular,
);

Check if password is valid (minimum of 8 characters, at least 1 special character, 1 capital letter, 1 numeric character)

LocalRegex.isValidPassword('your_password');

Mobile Number Format Types

Regular

This is the general format of mobile numbers e.g. 0777213388

FormatTypes.regular

Common

This is the mobile number format with country code but no + sign e.g. 263777213388

FormatTypes.common

Common Plus

This is the mobile number format with country code and + sign e.g. +263777213388

FormatTypes.commonPlus

PasswordTextFormField

This a custom text form field that validates the password. It is recommended to use this field instead of the default text form field. It has the option to show which requirements have been met and which have not. The default password validation section can also be overwritten by supplying a function that returns a Widget.

Usage:

PasswordTextFormField(
  controller: passwordController,
  overrideValidationRow: true,
  customValidationSection: customValidationSection,
  decoration: InputDecoration(
    border: InputBorder.none,
  ),
  autovalidateMode: AutovalidateMode.onUserInteraction,
  showValidationRow: true,
)

Override Custom Validation Section

Supply a function that returns a Widget that will be displayed in the validation section.

Structure Of The Function

Widget customValidationSection({
  required bool hasEightCharacters,
  required bool hasCapitalLetter,
  required bool hasSmallCapsLetter,
  required bool hasADigit,
  required bool hasASpecialCharacter,
}) {
  return Container(
    height: 50,
    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        Row(
          children: [
            Text(
              "🔠",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
            Text(
              hasCapitalLetter ? "✅" : "❌",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
          ],
        ),
        Row(
          children: [
            Text(
              "🔡",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
            Text(
              hasSmallCapsLetter ? "✅" : "❌",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
          ],
        ),
        Row(
          children: [
            Text(
              "🔢",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
            Text(
              hasADigit ? "✅" : "❌",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
          ],
        ),
        Row(
          children: [
            Text(
              "🔣",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
            Text(
              hasASpecialCharacter ? "✅" : "❌",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
          ],
        ),
        Row(
          children: [
            Text(
              "8️⃣ chars",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
            Text(
              hasCapitalLetter ? "✅" : "❌",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
          ],
        ),
      ],
    ),
  );
}

Screenshot

DefaultUsing The Override Option

Installing

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add localregex

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

dependencies:
  localregex: ^3.0.3

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:localregex/localregex.dart';

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:localregex/localregex.dart';
import 'package:localregex/password_validation/password_text_form_field.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Example(),
    );
  }
}

class Example extends StatefulWidget {
  @override
  _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
  bool _isMobile = false;
  final _formKey = GlobalKey<FormState>();
  final TextEditingController passwordController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text("LocalRegex usage example"),
        ),
        body: Container(
          height: MediaQuery.of(context).size.height * 0.9,
          width: MediaQuery.of(context).size.width,
          color: Colors.white,
          child: Form(
            key: _formKey,
            child: Column(
              children: [
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: TextFormField(
                    decoration: InputDecoration(
                      labelText: "Mobile Number",
                    ),
                    autovalidateMode: AutovalidateMode.onUserInteraction,
                    // ignore: missing_return
                    validator: (String? value) {
                      if (!LocalRegex.isValidZimMobile(value!)) {
                        return "Not a valid Zimbabwean mobile number";
                      }
                    },
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Container(
                    color: Colors.blue,
                    width: MediaQuery.of(context).size.width * 0.9,
                    child: MaterialButton(
                      onPressed: () {
                        if (_formKey.currentState!.validate()) {
                          setState(() {
                            _isMobile = true;
                          });
                        } else {
                          setState(() {
                            _isMobile = false;
                          });
                        }
                      },
                      child: Text(
                        "VERIFY",
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(
                    _isMobile ? "Verified" : "Not verified",
                    style: TextStyle(
                      color: _isMobile ? Colors.green : Colors.red,
                    ),
                  ),
                ),
                SizedBox(
                  height: 100,
                ),
                PasswordTextFormField(
                  controller: passwordController,
                  overrideValidationRow: true,
                  customValidationSection: customValidationSection,
                  autovalidateMode: AutovalidateMode.onUserInteraction,
                  showValidationRow: true,
                  debugPrintLoud: true,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Widget customValidationSection({
  required bool hasEightCharacters,
  required bool hasCapitalLetter,
  required bool hasSmallCapsLetter,
  required bool hasADigit,
  required bool hasASpecialCharacter,
}) {
  return Container(
    height: 50,
    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        Row(
          children: [
            Text(
              "🔠",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
            Text(
              hasCapitalLetter ? "✅" : "❌",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
          ],
        ),
        Row(
          children: [
            Text(
              "🔡",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
            Text(
              hasSmallCapsLetter ? "✅" : "❌",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
          ],
        ),
        Row(
          children: [
            Text(
              "🔢",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
            Text(
              hasADigit ? "✅" : "❌",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
          ],
        ),
        Row(
          children: [
            Text(
              "🔣",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
            Text(
              hasASpecialCharacter ? "✅" : "❌",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
          ],
        ),
        Row(
          children: [
            Text(
              "8️⃣ chars",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
            Text(
              hasEightCharacters ? "✅" : "❌",
              style: TextStyle(
                fontSize: 20,
              ),
            ),
          ],
        ),
      ],
    ),
  );
}

Original article source at: https://pub.dev/packages/localregex 

#flutter #dart #local

LocalRegex: Collection of regex patterns commonly used in Zimbabwe
Hermann  Frami

Hermann Frami

1655441400

Serverless MongoDB Local Plugin

serverless-mongodb-local 

Serverless MongoDB local plugin

Features

  • Automatically starts/stops a local MongoDB instance
  • Automatically downloads MongoDB binaries on first use
  • Can be used as a local equivalent to DocumentDB/CosmosDB

Install

npm i -D serverless-mongodb-local

Usage

In serverless.yaml

plugins:
  - serverless-mongodb-local

custom:
  mongodb:
    stages: # If you only want to use MongoDB Local in particular stages, declare them here as a string or regex
      - dev
      - 'dev-\d+'
    instance: # MongoMemoryServer() options and defaults https://github.com/nodkz/mongodb-memory-server#available-options-for-mongomemoryserver
      port: 1234
      dbName: MyDB
      dbPath: ./db
      storageEngine: wiredTiger # Set with `dbPath` to persists the database between instantiations
    seed:
      auto: true
      dataPath: ./test/data

In your handlers

const { MongoClient } = require('mongodb');

const client = await MongoClient.connect(
  process.env.SLS_MONGODB_URI,  // Provided as a convenience when using the plugin
  { useUnifiedTopology: true }
);

Seeding data

By setting a mongodb.seed.dataPath any .json files in the folder will be imported as collections. The name of file being the name of the collection. The file should be an array of documents to load into the collection.

Using with serverless-offline plugin

plugins:
  - serverless-mongodb-local
  - serverless-offline

Make sure that serverless-mongodb-local is above serverless-offline so it will be loaded earlier.

Now your local MongoDB database will be automatically started before running serverless-offline, when using the command sls offline start.

Usage on the command line

# Start the db
sls mongodb start

# Seed the db
sls mongodb seed

Credit

Development

Run

npm start

Build

npm test

Publish

npm version patch|minor|major
git push --follow-tags

Author: Bealearts
Source Code: https://github.com/bealearts/serverless-mongodb-local 
License: MIT license

#serverless #mongodb #local 

Serverless MongoDB Local Plugin
Hermann  Frami

Hermann Frami

1655329740

LocalStack Serverless Plugin

LocalStack Serverless Plugin

Serverless Plugin to support running against Localstack.

This plugin allows Serverless applications to be deployed and tested on your local machine. Any requests to AWS to be redirected to a running LocalStack instance.

Pre-requisites:

  • LocalStack

Installation

The easiest way to get started is to install via npm.

npm install -g serverless
npm install --save-dev serverless-localstack

Configuring

There are two ways to configure the plugin, via a JSON file or via serverless.yml. There are two supported methods for configuring the endpoints, globally via the host property, or individually. These properties may be mixed, allowing for global override support while also override specific endpoints.

A host or individual endpoints must be configured or this plugin will be deactivated.

Configuration via serverless.yml

Please refer to the example configuration template below. (Please note that most configurations in the sample are optional and need not be specified.)

service: myService

plugins:
  - serverless-localstack

custom:
  localstack:
    stages:
      # list of stages for which the plugin should be enabled
      - local
    host: http://localhost  # optional - LocalStack host to connect to
    edgePort: 4566  # optional - LocalStack edge port to connect to
    autostart: true  # optional - Start LocalStack in Docker on Serverless deploy
    networks: #optional - attaches the list of networks to the localstack docker container after startup
      - host
      - overlay
      - my_custom_network
    lambda:
      # Enable this flag to improve performance
      mountCode: True
    docker:
      # Enable this flag to run "docker ..." commands as sudo
      sudo: False
  stages:
    local:
      ...

Activating the plugin for certain stages

Note the stages attribute in the config above. The serverless-localstack plugin gets activated if either:

  1. the serverless stage (explicitly defined or default stage "dev") is included in the stages config; or
  2. serverless is invoked without a --stage flag (default stage "dev") and no stages config is provided

Mounting Lambda code for better performance

Note that the localstack.lambda.mountCode flag above will mount the local directory into the Docker container that runs the Lambda code in LocalStack. If you remove this flag, your Lambda code is deployed in the traditional way which is more in line with how things work in AWS, but also comes with a performance penalty: packaging the code, uploading it to the local S3 service, downloading it in the local Lambda API, extracting it, and finally copying/mounting it into a Docker container to run the Lambda. Mounting code from multiple projects is not supported with simple configuration, and you must use the autostart feature, as your code will be mounted in docker at start up. If you do need to mount code from multiple serverless projects, manually launch localstack with volumes specified. For example:

localstack start --docker -d \
  -v /path/to/project-a:/path/to/project-a \
  -v /path/to/project-b:/path/to/project-b

If you use either serverless-webpack or serverless-plugin-typescript, serverless-localstack will detect it and modify the mount paths to point to your output directory. You will need to invoke the build command in order for the mounted code to be updated. (eg: serverless webpack). There is no --watch support for this out of the box, but could be accomplished using nodemon:

npm i --save-dev nodemon

package.json:

  "scripts": {
    "build": "serverless webpack --stage local",
    "deploy": "serverless deploy --stage local",
    "watch": "nodemon -w src -e '.*' -x 'npm run build'",
    "start": "npm run deploy && npm run watch"
  },
npm run start

A note on using webpack

serverless-webpack is supported, with code mounting. However, there are some assumptions and configuration requirements. First, your output directory must be .webpack. Second, you must retain your output directory contents. You can do this by modifying the custom > webpack portion of your serverless configuration file.

custom:
  webpack:
    webpackConfig: webpack.config.js
    includeModules: true
    keepOutputDirectory: true
  localstack:
    stages:
      - local
    lambda:
      mountCode: true
    autostart: true

Environment Configurations

  • LAMBDA_MOUNT_CWD: Allow users to define a custom working directory for Lambda mounts. For example, when deploying a Serverless app in a Linux VM (that runs Docker) on a Windows host where the -v <local_dir>:<cont_dir> flag to docker run requires us to specify a local_dir relative to the Windows host file system that is mounted into the VM (e.g., "c:/users/guest/...").
  • LAMBDA_EXECUTOR: Executor type to use for running Lambda functions (default docker) - see LocalStack repo
  • LAMBDA_REMOTE_DOCKER: Whether to assume that we're running Lambda containers against a remote Docker daemon (default false) - see LocalStack repo

Only enable serverless-localstack for the listed stages

  • serverless deploy --stage local would deploy to LocalStack.
  • serverless deploy --stage production would deploy to aws.
service: myService

plugins:
  - serverless-localstack

custom:
  localstack:
    stages:
      - local
      - dev
    endpointFile: path/to/file.json

LocalStack

For full documentation, please refer to https://github.com/localstack/localstack

Contributing

Setting up a development environment is easy using Serverless' plugin framework.

Clone the Repo

git clone https://github.com/localstack/serverless-localstack

Setup your project

cd /path/to/serverless-localstack
npm link

cd myproject
npm link serverless-localstack

Optional Debug Flag

An optional debug flag is supported via serverless.yml that will enable additional debug logs.

custom:
  localstack:
    debug: true

Change Log

  • v0.4.36: Add patch to avoid "TypeError" in AwsDeploy plugin on Serverless v3.4.0+
  • v0.4.35: Add config option to connect to additional Docker networks
  • v0.4.33: Fix parsing StepFunctions endpoint if the endpointInfo isn't defined
  • v0.4.32: Add endpoint to AWS credentials for compatibility with serverless-domain-manager plugin
  • v0.4.31: Fix format of API GW endpoints printed in stack output
  • v0.4.30: Fix plugin for use with Serverless version 2.30+
  • v0.4.29: Add missing service endpoints to config
  • v0.4.28: Fix plugin activation for variable refs in profile names
  • v0.4.27: Fix loading of endpoints file with variable references to be resolved
  • v0.4.26: Fix resolution of template variables during plugin initialization
  • v0.4.25: Use single edge port instead of deprecated service-specific ports
  • v0.4.24: Fix resolving of stage/profiles via variable expansion
  • v0.4.23: Fix config loading to enable file imports; fix output of API endpoints if plugin is not activated; enable SSM and CF output refs by performing early plugin loading
  • v0.4.21: Fix integration with serverless-plugin-typescript when mountCode is enabled
  • v0.4.20: Use LAMBDA_EXECUTOR/LAMBDA_REMOTE_DOCKER configurations from environment
  • v0.4.19: Fix populating local test credentials in AWS provider
  • v0.4.18: Fix output of API Gateway endpoints; add port mappings; fix config init code
  • v0.4.17: Enable configuration of $START_WEB
  • v0.4.16: Add option for running Docker as sudo; add fix for downloadPackageArtifacts
  • v0.4.15: Enable plugin on aws:common:validate events
  • v0.4.14: Initialize LocalStack using hooks for each "before:" event
  • v0.4.13: Add endpoint for SSM; patch serverless-secrets plugin; allow customizing $DOCKER_FLAGS
  • v0.4.12: Fix Lambda packaging for mountCode:false
  • v0.4.11: Add polling loop for starting LocalStack in Docker
  • v0.4.8: Auto-create deployment bucket; autostart LocalStack in Docker
  • v0.4.7: Set S3 path addressing; add eslint to CI config
  • v0.4.6: Fix port mapping for service endpoints
  • v0.4.5: Fix config to activate or deactivate the plugin for certain stages
  • v0.4.4: Add LAMBDA_MOUNT_CWD configuration for customizing Lambda mount dir
  • v0.4.3: Support local mounting of Lambda code to improve performance
  • v0.4.0: Add support for local STS

Author: LocalStack
Source Code: https://github.com/LocalStack/serverless-localstack 
License: 

#serverless #local #aws 

LocalStack Serverless Plugin
Hermann  Frami

Hermann Frami

1655322360

Serverless Local Schedule

Serverless Local Schedule

This plugin allows you to specify a timezone on your lambdas triggered by AWS CloudWatch Events.


Install

sls plugin install -n serverless-local-schedule

For example:

functions:
  hello:
    handler: handler.hello
    events:
      - schedule:
          rate: cron(0 10 * * ? *)
          timezone: America/New_York

It works by converting that into 6 different schedules, effectively the same as having the following configuration:

functions:
  hello:
    handler: handler.hello
    events:
      - schedule:
          rate: cron(0 15 * 1-2,12 ? *) # full non-DST months
      - schedule:
          rate: cron(0 15 1-10 3 ? *) # non-DST portion of March
      - schedule:
          rate: cron(0 14 11-31 3 ? *) # DST portion of March
      - schedule:
          rate: cron(0 14 * 4-10 ? *) # full DST months
      - schedule:
          rate: cron(0 14 1-3 11 ? *) # DST portion of November
      - schedule:
          rate: cron(0 15 4-31 11 ? *) # non-DST portion of November

NOTE: The - schedule: cron(* * * * ? *) short syntax isn't supported.

NOTE: Unfortunately you cannot specify day of the week in the cron expression i.e. cron(0 7 ? * MON-FRI *). This is because to support the split months (March & November in the US), the plugin has to specify a day of month (EG: November 1-3 in 2018), so you cannot specify a DOW other than ? unfortunately. Recommended workaround for this is to move the day of week check into your code so it's just a no-op on non weekdays for instance.


Originally developed by Capital One, now maintained in scope of Serverless, Inc

Capital One considers itself the bank a technology company would build. It's delivering best-in-class innovation so that its millions of customers can manage their finances with ease. Capital One is all-in on the cloud and is a leader in the adoption of open source, RESTful APIs, microservices and containers. We build our own products and release them with a speed and agility that allows us to get new customer experiences to market quickly. Our engineers use artificial intelligence and machine learning to transform real-time data, software and algorithms into the future of finance, reimagined.


Author: Serverless
Source Code: https://github.com/serverless/serverless-local-schedule 
License: MIT license

#serverless #local #aws 

Serverless Local Schedule