Brook  Hudson

Brook Hudson

1659359100

Tmuxinator: Create and Manage Complex Tmux Sessions Easily Of Ruby

Tmuxinator   

Create and manage tmux sessions easily.

Screenshot

Installation

RubyGems

gem install tmuxinator

Homebrew

brew install tmuxinator

Some users have reported issues when installing via Homebrew, so the RubyGems installation is preferred until these are resolved.

tmuxinator aims to be compatible with the currently maintained versions of Ruby.

Some operating systems may provide an unsupported version of Ruby as their "system ruby". In these cases, users should use RVM or rbenv to install a supported Ruby version and use that version's gem binary to install tmuxinator.

Editor and Shell

tmuxinator uses your shell's default editor for opening files. If you're not sure what that is type:

echo $EDITOR

For me that produces "vim". If you want to change your default editor simply put a line in ~/.bashrc that changes it. Mine looks like this:

export EDITOR='vim'

tmux

The recommended version of tmux to use is 1.8 or later, with the exception of 2.5, which is not supported (see issue 536 for details). Your mileage may vary for earlier versions. Refer to the FAQ for any odd behaviour.

Completion

Your distribution's package manager may install the completion files in the appropriate location for the completion to load automatically on startup. But, if you installed tmuxinator via Ruby's gem, you'll need to run the following commands to put the completion files where they'll be loaded by your shell.

bash

# wget https://raw.githubusercontent.com/tmuxinator/tmuxinator/master/completion/tmuxinator.bash -O /etc/bash_completion.d/tmuxinator.bash

zsh

# wget https://raw.githubusercontent.com/tmuxinator/tmuxinator/master/completion/tmuxinator.zsh -O /usr/local/share/zsh/site-functions/_tmuxinator

Note: ZSH's completion files can be put in other locations in your $fpath. Please refer to the manual for more details.

fish

$ wget https://raw.githubusercontent.com/tmuxinator/tmuxinator/master/completion/tmuxinator.fish ~/.config/fish/completions/

Usage

A working knowledge of tmux is assumed. You should understand what windows and panes are in tmux. If not please consult the man pages for tmux.

Create a project

Create or edit your projects with:

tmuxinator new [project]

Create or edit a local project where the config file will be stored in the current working directory (in .tmuxinator.yml) instead of the default project configuration file location (e.g. ~/.config/tmuxinator):

tmuxinator new --local [project]

For editing you can also use tmuxinator open [project]. new is aliased to n,open to o, and edit to e. Please note that dots can't be used in project names as tmux uses them internally to delimit between windows and panes. Your default editor ($EDITOR) is used to open the file. If this is a new project you will see this default config:

# ~/.tmuxinator/sample.yml

name: sample
root: ~/

# Optional tmux socket
# socket_name: foo

# Note that the pre and post options have been deprecated and will be replaced by
# project hooks.

# Project hooks

# Runs on project start, always
# on_project_start: command

# Run on project start, the first time
# on_project_first_start: command

# Run on project start, after the first time
# on_project_restart: command

# Run on project exit ( detaching from tmux session )
# on_project_exit: command

# Run on project stop
# on_project_stop: command

# Runs in each window and pane before window/pane specific commands. Useful for setting up interpreter versions.
# pre_window: rbenv shell 2.0.0-p247

# Pass command line options to tmux. Useful for specifying a different tmux.conf.
# tmux_options: -f ~/.tmux.mac.conf

# Change the command to call tmux.  This can be used by derivatives/wrappers like byobu.
# tmux_command: byobu

# Specifies (by name or index) which window will be selected on project startup. If not set, the first window is used.
# startup_window: editor

# Specifies (by index) which pane of the specified window will be selected on project startup. If not set, the first pane is used.
# startup_pane: 1

# Controls whether the tmux session should be attached to automatically. Defaults to true.
# attach: false

windows:
  - editor:
      layout: main-vertical
      # Synchronize all panes of this window, can be enabled before or after the pane commands run.
      # 'before' represents legacy functionality and will be deprecated in a future release, in favour of 'after'
      # synchronize: after
      panes:
        - vim
        - guard
  - server: bundle exec rails s
  - logs: tail -f log/development.log

Windows

The windows option allows the specification of any number of tmux windows. Each window is denoted by a YAML array entry, followed by a name* and command to be run.

*Users may optionally provide a null YAML value (e.g. null or ~) in place of a named window key, which will cause the window to use its default name (usually the name of their shell).

windows:
  - editor: vim

Window specific root

An optional root option can be specified per window:

name: test
root: ~/projects/company

windows:
  - small_project:
      root: ~/projects/company/small_project
      panes:
        - start this
        - start that

This takes precedence over the main root option.

Panes

Note that if you wish to use panes, make sure that you do not have . in your project name. tmux uses . to delimit between window and pane indices, and tmuxinator uses the project name in combination with these indices to target the correct pane or window.

Panes are optional and are children of window entries, but unlike windows, they do not need a name. In the following example, the editor window has 2 panes, one running vim, the other guard.

windows:
  - editor:
      layout: main-vertical
      panes:
        - vim
        - guard

The layout setting gets handed down to tmux directly, so you can choose from one of the five standard layouts or specify your own.

Please note the indentation here is deliberate. YAML's indentation rules can be confusing, so if your config isn't working as expected, please check the indentation. For a more detailed explanation of why YAML behaves this way, see this Stack Overflow question.

Note: If you're noticing inconsistencies when using a custom layout it may be due #651. See this comment for a workaround.

Interpreter Managers & Environment Variables

To use tmuxinator with rbenv, RVM, NVM etc, use the pre_window option.

pre_window: rbenv shell 2.0.0-p247

These command(s) will run before any subsequent commands in all panes and windows.

Custom session attachment

You can set tmuxinator to skip auto-attaching to the session by using the attach option.

attach: false

If you want to attach to tmux in a non-standard way (e.g. for a program that makes use of tmux control mode like iTerm2), you can run arbitrary commands by using a project hook:

on_project_exit: tmux -CC attach

Passing directly to send-keys

tmuxinator passes commands directly to send keys. This differs from simply chaining commands together using && or ;, in that tmux will directly send the commands to a shell as if you typed them in. This allows commands to be executed on a remote server over SSH for example.

To support this both the window and pane options can take an array as an argument:

name: sample
root: ~/

windows:
  - stats:
    - ssh stats@example.com
    - tail -f /var/log/stats.log
  - logs:
      layout: main-vertical
      panes:
        - logs:
          - ssh logs@example.com
          - cd /var/logs
          - tail -f development.log

ERB

Project files support ERB for reusability across environments. Eg:

root: <%= ENV["MY_CUSTOM_DIR"] %>

You can also pass arguments to your projects, and access them with ERB. Simple arguments are available in an array named @args.

Eg:

$ tmuxinator start project foo
# ~/.tmuxinator/project.yml

name: project
root: ~/<%= @args[0] %>

...

You can also pass key-value pairs using the format key=value. These will be available in a hash named @settings.

Eg:

$ tmuxinator start project workspace=~/workspace/todo
# ~/.tmuxinator/project.yml

name: project
root: ~/<%= @settings["workspace"] %>

...

Starting a session

This will fire up tmux with all the tabs and panes you configured, start is aliased to s.

tmuxinator start [project] -n [name] -p [project-config]

If you use the optional [name] argument, it will start a new tmux session with the custom name provided. This is to enable reuse of a project without tmux session name collision.

If there is a ./.tmuxinator.yml file in the current working directory but not a named project file in ~/.tmuxinator, tmuxinator will use the local file. This is primarily intended to be used for sharing tmux configurations in complex development environments.

You can provide tmuxinator with a project config file using the optional [project-config] argument (e.g. --project-config=path/to/my-project.yaml or -p path/to/my-project.yaml). This option will override a [project] name (if provided) and a local tmuxinator file (if present).

Shorthand

The shell completion files also include a shorthand alias for tmuxinator that can be used in place of the full name*.

mux [command]

*The mux alias has been removed from the Zsh completion script because it was resulting in unexpected behavior in some setups. Including aliases in completion scripts is not standard practice and the Bash and Fish aliases may be removed in a future release. Going forward, users should create their own aliases in their shell's RC file (e.g. alias mux=tmuxinator).

Other Commands

Copy an existing project. Aliased to c and cp

tmuxinator copy [existing] [new]

List all the projects you have configured. Aliased to l and ls

tmuxinator list

Remove a project. Aliased to rm

tmuxinator delete [project]

Remove all tmuxinator configs, aliases and scripts. Aliased to i

tmuxinator implode

Examines your environment and identifies problems with your configuration

tmuxinator doctor

Shows tmuxinator's help. Aliased to h

tmuxinator help

Shows the shell commands that get executed for a project

tmuxinator debug [project]

Shows tmuxinator's version.

tmuxinator version

Project Configuration Location

Using environment variables, it's possible to define which directory tmuxinator will use when creating or searching for project config files. (See PR #511.)

Tmuxinator will attempt to use the following locations (in this order) when creating or searching for existing project configuration files:

  • $TMUXINATOR_CONFIG
  • $XDG_CONFIG_HOME/tmuxinator
  • ~/.tmuxinator

FAQ

Window names are not displaying properly?

Add export DISABLE_AUTO_TITLE=true to your .zshrc or .bashrc

Contributing

To contribute, please read the contributing guide.

Copyright

Copyright (c) 2010-2020 Allen Bargi, Christopher Chow. See LICENSE for further details.


Author:  tmuxinator
Source code: https://github.com/tmuxinator/tmuxinator
License: MIT license

#ruby #ruby-on-rails 

What is GEEK

Buddha Community

Tmuxinator: Create and Manage Complex Tmux Sessions Easily Of Ruby
Easter  Deckow

Easter Deckow

1655630160

PyTumblr: A Python Tumblr API v2 Client

PyTumblr

Installation

Install via pip:

$ pip install pytumblr

Install from source:

$ git clone https://github.com/tumblr/pytumblr.git
$ cd pytumblr
$ python setup.py install

Usage

Create a client

A pytumblr.TumblrRestClient is the object you'll make all of your calls to the Tumblr API through. Creating one is this easy:

client = pytumblr.TumblrRestClient(
    '<consumer_key>',
    '<consumer_secret>',
    '<oauth_token>',
    '<oauth_secret>',
)

client.info() # Grabs the current user information

Two easy ways to get your credentials to are:

  1. The built-in interactive_console.py tool (if you already have a consumer key & secret)
  2. The Tumblr API console at https://api.tumblr.com/console
  3. Get sample login code at https://api.tumblr.com/console/calls/user/info

Supported Methods

User Methods

client.info() # get information about the authenticating user
client.dashboard() # get the dashboard for the authenticating user
client.likes() # get the likes for the authenticating user
client.following() # get the blogs followed by the authenticating user

client.follow('codingjester.tumblr.com') # follow a blog
client.unfollow('codingjester.tumblr.com') # unfollow a blog

client.like(id, reblogkey) # like a post
client.unlike(id, reblogkey) # unlike a post

Blog Methods

client.blog_info(blogName) # get information about a blog
client.posts(blogName, **params) # get posts for a blog
client.avatar(blogName) # get the avatar for a blog
client.blog_likes(blogName) # get the likes on a blog
client.followers(blogName) # get the followers of a blog
client.blog_following(blogName) # get the publicly exposed blogs that [blogName] follows
client.queue(blogName) # get the queue for a given blog
client.submission(blogName) # get the submissions for a given blog

Post Methods

Creating posts

PyTumblr lets you create all of the various types that Tumblr supports. When using these types there are a few defaults that are able to be used with any post type.

The default supported types are described below.

  • state - a string, the state of the post. Supported types are published, draft, queue, private
  • tags - a list, a list of strings that you want tagged on the post. eg: ["testing", "magic", "1"]
  • tweet - a string, the string of the customized tweet you want. eg: "Man I love my mega awesome post!"
  • date - a string, the customized GMT that you want
  • format - a string, the format that your post is in. Support types are html or markdown
  • slug - a string, the slug for the url of the post you want

We'll show examples throughout of these default examples while showcasing all the specific post types.

Creating a photo post

Creating a photo post supports a bunch of different options plus the described default options * caption - a string, the user supplied caption * link - a string, the "click-through" url for the photo * source - a string, the url for the photo you want to use (use this or the data parameter) * data - a list or string, a list of filepaths or a single file path for multipart file upload

#Creates a photo post using a source URL
client.create_photo(blogName, state="published", tags=["testing", "ok"],
                    source="https://68.media.tumblr.com/b965fbb2e501610a29d80ffb6fb3e1ad/tumblr_n55vdeTse11rn1906o1_500.jpg")

#Creates a photo post using a local filepath
client.create_photo(blogName, state="queue", tags=["testing", "ok"],
                    tweet="Woah this is an incredible sweet post [URL]",
                    data="/Users/johnb/path/to/my/image.jpg")

#Creates a photoset post using several local filepaths
client.create_photo(blogName, state="draft", tags=["jb is cool"], format="markdown",
                    data=["/Users/johnb/path/to/my/image.jpg", "/Users/johnb/Pictures/kittens.jpg"],
                    caption="## Mega sweet kittens")

Creating a text post

Creating a text post supports the same options as default and just a two other parameters * title - a string, the optional title for the post. Supports markdown or html * body - a string, the body of the of the post. Supports markdown or html

#Creating a text post
client.create_text(blogName, state="published", slug="testing-text-posts", title="Testing", body="testing1 2 3 4")

Creating a quote post

Creating a quote post supports the same options as default and two other parameter * quote - a string, the full text of the qote. Supports markdown or html * source - a string, the cited source. HTML supported

#Creating a quote post
client.create_quote(blogName, state="queue", quote="I am the Walrus", source="Ringo")

Creating a link post

  • title - a string, the title of post that you want. Supports HTML entities.
  • url - a string, the url that you want to create a link post for.
  • description - a string, the desciption of the link that you have
#Create a link post
client.create_link(blogName, title="I like to search things, you should too.", url="https://duckduckgo.com",
                   description="Search is pretty cool when a duck does it.")

Creating a chat post

Creating a chat post supports the same options as default and two other parameters * title - a string, the title of the chat post * conversation - a string, the text of the conversation/chat, with diablog labels (no html)

#Create a chat post
chat = """John: Testing can be fun!
Renee: Testing is tedious and so are you.
John: Aw.
"""
client.create_chat(blogName, title="Renee just doesn't understand.", conversation=chat, tags=["renee", "testing"])

Creating an audio post

Creating an audio post allows for all default options and a has 3 other parameters. The only thing to keep in mind while dealing with audio posts is to make sure that you use the external_url parameter or data. You cannot use both at the same time. * caption - a string, the caption for your post * external_url - a string, the url of the site that hosts the audio file * data - a string, the filepath of the audio file you want to upload to Tumblr

#Creating an audio file
client.create_audio(blogName, caption="Rock out.", data="/Users/johnb/Music/my/new/sweet/album.mp3")

#lets use soundcloud!
client.create_audio(blogName, caption="Mega rock out.", external_url="https://soundcloud.com/skrillex/sets/recess")

Creating a video post

Creating a video post allows for all default options and has three other options. Like the other post types, it has some restrictions. You cannot use the embed and data parameters at the same time. * caption - a string, the caption for your post * embed - a string, the HTML embed code for the video * data - a string, the path of the file you want to upload

#Creating an upload from YouTube
client.create_video(blogName, caption="Jon Snow. Mega ridiculous sword.",
                    embed="http://www.youtube.com/watch?v=40pUYLacrj4")

#Creating a video post from local file
client.create_video(blogName, caption="testing", data="/Users/johnb/testing/ok/blah.mov")

Editing a post

Updating a post requires you knowing what type a post you're updating. You'll be able to supply to the post any of the options given above for updates.

client.edit_post(blogName, id=post_id, type="text", title="Updated")
client.edit_post(blogName, id=post_id, type="photo", data="/Users/johnb/mega/awesome.jpg")

Reblogging a Post

Reblogging a post just requires knowing the post id and the reblog key, which is supplied in the JSON of any post object.

client.reblog(blogName, id=125356, reblog_key="reblog_key")

Deleting a post

Deleting just requires that you own the post and have the post id

client.delete_post(blogName, 123456) # Deletes your post :(

A note on tags: When passing tags, as params, please pass them as a list (not a comma-separated string):

client.create_text(blogName, tags=['hello', 'world'], ...)

Getting notes for a post

In order to get the notes for a post, you need to have the post id and the blog that it is on.

data = client.notes(blogName, id='123456')

The results include a timestamp you can use to make future calls.

data = client.notes(blogName, id='123456', before_timestamp=data["_links"]["next"]["query_params"]["before_timestamp"])

Tagged Methods

# get posts with a given tag
client.tagged(tag, **params)

Using the interactive console

This client comes with a nice interactive console to run you through the OAuth process, grab your tokens (and store them for future use).

You'll need pyyaml installed to run it, but then it's just:

$ python interactive-console.py

and away you go! Tokens are stored in ~/.tumblr and are also shared by other Tumblr API clients like the Ruby client.

Running tests

The tests (and coverage reports) are run with nose, like this:

python setup.py test

Author: tumblr
Source Code: https://github.com/tumblr/pytumblr
License: Apache-2.0 license

#python #api 

Brook  Hudson

Brook Hudson

1659396000

Humidifier: A Ruby tool for Managing AWS CloudFormation Stacks

Humidifier 

Humidifier is a ruby tool for managing AWS CloudFormation stacks. You can use it to build and manage stacks programmatically or you can use it as a command line tool to manage stacks through configuration files.

Installation

Add this line to your application's Gemfile:

gem 'humidifier'

And then execute:

$ bundle

Or install it yourself as:

$ gem install humidifier

Getting started

Stacks are represented by the Humidifier::Stack class. You can set any of the top-level JSON attributes (such as name and description) through the initializer.

Resources are represented by an exact mapping from AWS resource names to Humidifier resources names (e.g. AWS::EC2::Instance becomes Humidifier::EC2::Instance). Resources have accessors for each JSON attribute. Each attribute can also be set through the initialize, update, and update_attribute methods.

Example usage

The below example will create a stack with two resources, a loader balancer and an auto scaling group. It then deploys the new stack and pauses execution until the stack is finished being created.

stack = Humidifier::Stack.new(name: 'Example-Stack')

stack.add(
  'LoaderBalancer',
  Humidifier::ElasticLoadBalancing::LoadBalancer.new(
    scheme: 'internal',
    listeners: [
      {
        load_balancer_port: 80,
        protocol: 'http',
        instance_port: 80,
        instance_protocol: 'http'
      }
    ]
  )
)

stack.add(
  'AutoScalingGroup',
  Humidifier::AutoScaling::AutoScalingGroup.new(
    min_size: '1',
    max_size: '20',
    availability_zones: ['us-east-1a'],
    load_balancer_names: [Humidifier.ref('LoadBalancer')]
  )
)

stack.deploy_and_wait

Interfacing with AWS

Once stacks have the appropriate resources, you can query AWS to handle all stack CRUD operations. The operations themselves are intuitively named (i.e. #create, #update, #delete). There are also convenience methods for validating a stack body (#valid?), checking the existence of a stack (#exists?), and creating or updating based on existence (#deploy).

There are additionally four functions on Humidifier::Stack that support waiting for execution in AWS to finish. They all have non-blocking corollaries, and are named after them. They are: #create_and_wait, #update_and_wait, #delete_and_wait, and #deploy_and_wait.

CloudFormation functions

You can use CFN intrinsic functions and references using Humidifier.fn.[name] and Humidifier.ref. They will build appropriate structures that know how to be dumped to CFN syntax.

Change Sets

Instead of immediately pushing your changes to CloudFormation, Humidifier also supports change sets. Change sets are a powerful feature that allow you to see the changes that will be made before you make them. To read more about change sets see the announcement article. To use them in Humidifier, Humidifier::Stack has the #create_change_set and #deploy_change_set methods. The #create_change_set method will create a change set on the stack. The #deploy_change_set method will create a change set if the stack currently exists, and otherwise will create the stack.

Introspection

To see the template body, you can check the #to_cf method on stacks, resources, fns, and refs. All of them will output a hash of what will be uploaded (except the stack, which will output a string representation).

Humidifier itself contains a registry of all possible resources that it supports. You can access it with Humidifier::registry which is a hash of AWS resource name pointing to the class.

Resources have an ::aws_name method to see how AWS references them. They also contain a ::props method that contains a hash of the name that Humidifier uses to reference the prop pointing to the appropriate prop object.

Large templates

When templates are especially large (larger than 51,200 bytes), they cannot be uploaded directly through the AWS SDK. You can configure Humidifier to seamlessly upload the templates to S3 and reference them using an S3 URL instead by:

Humidifier.configure do |config|
  config.s3_bucket = 'my.s3.bucket'
  config.s3_prefix = 'my-prefix/' # optional
end

Forcing uploading

You can force a stack to upload its template to S3 regardless of the size of the template. This is a useful option if you're going to be deploying multiple copies of a template or if you want a backup. You can set this option on a per-stack basis:

stack.deploy(force_upload: true)

or globally, by setting the configuration option:

Humidifier.configure do |config|
  config.force_upload = true
end

CLI

Humidifier can also be used as a CLI for managing resources through configuration files. For a step-by-step guide, read on, but if you'd like to see a working example, check out the example directory.

To get started, build a ruby script (for example humidifier) that executes the Humidifier::CLI class, like so:

#!/usr/bin/env ruby
require 'humidifier'

Humidifier.configure do |config|
  # optional, defaults to the current working directory, so that all of the
  # directories from the location that you run the CLI are assumed to contain
  # resource specifications
  config.stack_path = 'stacks'

  # optional, a default prefix to use before deploying to AWS
  config.stack_prefix = 'humidifier-'

  # specifies that `users.yml` files contain specifications for `AWS::IAM::User`
  # resources
  config.map :users, to: 'IAM::User'
end

Humidifier::CLI.start(ARGV)

Resource files

Inside of the stacks directory configured above, create a subdirectory for each CloudFormation stack that you want to deploy. With the above configuration, we can create YAML files in the form of users.yml for each stack, which will specify IAM users to create. The file format looks like the below:

EngUser:
  path: /humidifier/
  user_name: EngUser
  groups:
  - Engineering
  - Testing
  - Deployment

AdminUser:
  path: /humidifier/
  user_name: AdminUser
  groups:
  - Management
  - Administration

The top-level keys are the logical resource names that will be displayed in the CloudFormation screen. They point to a map of key/value pairs that will be passed on to humidifier. Any humidifier (and therefore any CloudFormation) attribute may be specified. For more information on CloudFormation templates and which attributes may be specified, see both the humidifier docs and the CloudFormation docs.

Mappers

Oftentimes, specifying these attributes can become repetitive, e.g., each user should automatically receive the same "path" attribute. Other times, you may want custom logic to execute depending on which AWS environment you're running in. Finally, you may want to reference resources in the same or other stacks.

Humidifier's solution for this is to allow customized "mapper" classes to take the user-provided attributes and transform them into the attributes that CloudFormation expects. Consider the following example for mapping a user:

class UserMapper < Humidifier::Config::Mapper
  GROUPS = {
    'eng' => %w[Engineering Testing Deployment],
    'admin' => %w[Management Administration]
  }

  defaults do |logical_name|
    { path: '/humidifier/', user_name: logical_name }
  end

  attribute :group do |group|
    groups = GROUPS[group]
    groups.any? ? { groups: GROUPS[group] } : {}
  end
end

Humidifier.configure do |config|
  config.map :users, to: 'IAM::User', using: UserMapper
end

This means that by default, all entries in the users.yml files will get a /humidifier/ path, the user_name attribute will be set based on the logical name that was provided for the resource, and you can additionally specify a group attribute, even though it is not native to CloudFormation. With this group attribute, it will actually map to the groups attribute that CloudFormation expects.

With this new mapper in place, we can simplify our YAML file to:

EngUser:
  group: eng

AdminUser:
  group: admin

Using the CLI

Now that you've configured your CLI, your resources, and your mappers, you can use the CLI to display, validate, and deploy your infrastructure to CloudFormation. Run your script without any arguments to get the help message and explanations for each command.

Each command has an --aws-profile (or -p) option for specifying which profile to authenticate against when querying AWS. You should ensure that this profile has the correct permissions for creating whatever resources are going to part of your stack. You can also rely on the AWS_* environment variables, or the EC2 instance profile if you're deploying from an instance. For more information, see the AWS docs under the "Configuration" section.

Below are the list of commands and some of their options.

change [?stack]

Creates a change set for either the specified stack or all stacks in the repo. The change set represents the changes between what is currently deployed versus the resources represented by the configuration.

deploy [?stack] [*parameters]

Creates or updates (depending on if the stack already exists) one or all stacks in the repo.

The deploy command also allows a --prefix command line argument that will override the default prefix (if one is configured) for the stack that is being deployed. This is especially useful when you're deploying multiple copies of the same stack (for instance, multiple autoscaling groups) that have different purposes or semantically mean newer versions of resources.

display [stack] [?pattern]

Displays the specified stack in JSON format on the command line. If you optionally pass a pattern argument, it will filter the resources down to just ones whose names match the given pattern.

stacks

Displays the names of all of the stacks that humidifier is managing.

upgrade

Downloads the latest CloudFormation resource specification. Periodically AWS will update the file that humidifier is based on, in which case the attributes of the resources that were changed could change. This gem usually stays relatively in sync, but if you need to use the latest specs and this gem has not yet released a new version containing them, then you can run this command to download the latest specs onto your system.

upload [?stack]

Upload one or all stacks in the repo to S3 for reference later. Note that this must be combined with the humidifier s3_bucket configuration option.

validate [?stack]

Validate that one or all stacks in the repo are properly configured and using values that CloudFormation understands.

version

Output the version of Humidifier as well as the version of the CloudFormation resource specification that you are using.

Parameters

CloudFormation template parameters can be specified by having a special parameters.yml file in your stack directory. This file should contain a YAML-encoded object whose keys are the names of the parameters and whose values are the parameter configuration (using the same underscore paradigm as humidifier resources for specifying configuration).

You can pass values to the CLI deploy command after the stack name on the command line as in:

humidifier deploy foobar Param1=Foo Param2=Bar

Those parameters will get passed in as values when the stack is deployed.

Shortcuts

A couple of convenient shortcuts are built into humidifier so that writing templates and mappers both can be more concise.

Automatic id properties

There are a lot of properties in the AWS CloudFormation resource specification that are simply pointers to other entities within the AWS ecosystem. For example, an AWS::EC2::VPCGatewayAttachment entity has a VpcId property that represents the ID of the associated AWS::EC2::VPC.

Because this pattern is so common, humidifier detects all properties ending in Id and allows you to specify them without the suffix. If you choose to use this format, humidifier will automatically turn that value into a CloudFormation resource reference.

Anonymous mappers

A lot of the time, mappers that you create will not be overly complicated, especially if you're using automatic id properties. So, the config.map method optionally takes a block, and allows you to specify the mapper inline. This is recommended for mappers that aren't too complicated as to warrant their own class (for instance, for testing purposes). An example of this using the UserMapper from above is below:

Humidifier.configure do |config|
  config.map :users, to: 'IAM::User' do
    GROUPS = {
      'eng' => %w[Engineering Testing Deployment],
      'admin' => %w[Management Administration]
    }

    defaults do |logical_name|
      { path: '/humidifier/', user_name: logical_name }
    end

    attribute :group do |group|
      groups = GROUPS[group]
      groups.any? ? { groups: GROUPS[group] } : {}
    end
  end
end

Cross-stack references

AWS allows cross-stack references through the intrinsic Fn::ImportValue function. You can take advantage of this with humidifier by using the export: true option on resources in your stacks. For instance, if in one stack you have a subnet that you need to reference in another, you could (stacks/vpc/subnets.yml):

ProductionPrivateSubnet2a:
  vpc: ProductionVPC
  cidr_block: 10.0.0.0/19
  availability_zone: us-west-2a
  export: true

ProductionPrivateSubnet2b:
  vpc: ProductionVPC
  cidr_block: 10.0.64.0/19
  availability_zone: us-west-2b
  export: true

ProductionPrivateSubnet2c:
  vpc: ProductionVPC
  cidr_block: 10.0.128.0/19
  availability_zone: us-west-2c
  export: true

And then in another stack, you could reference those values (stacks/rds/db_subnets_groups.yml):

ProductionDBSubnetGroup:
  db_subnet_group_description: Production DB private subnet group
  subnets:
  - ProductionPrivateSubnet2a
  - ProductionPrivateSubnet2b
  - ProductionPrivateSubnet2c

Within the configuration, you would specify to use the Fn::ImportValue function like so:

Humidifier.configure do |config|
  config.stack_path = 'stacks'

  config.map :subnets, to: 'EC2::Subnet'

  config.map :db_subnet_groups, to: 'RDS::DBSubnetGroup' do
    attribute :subnets do |subnet_names|
      subnet_ids =
        subnet_names.map do |subnet_name|
          Humidifier.fn.import_value(subnet_name)
        end

      { subnet_ids: subnet_ids }
    end
  end
end

If you specify export: true it will by default export a reference to the resource listed in the stack. You can also choose to export a different attribute by specifying the attribute as the value to export. For example, if we were creating instance profiles and wanted to export the Arn so that it could be referenced by an instance later, we could:

APIRoleInstanceProfile:
  depends_on: APIRole
  roles:
  - APIRole
  export: Arn

Development

To get started, ensure you have ruby installed, version 2.4 or later. From there, install the bundler gem: gem install bundler and then bundle install in the root of the repository.

Testing

The default rake task runs the tests. Styling is governed by rubocop. The docs are generated with yard. To run all three of these, run:

$ bundle exec rake
$ bundle exec rubocop
$ bundle exec rake yard

Specs

The specs pulled from the CFN docs is saved to CloudFormationResourceSpecification.json. You can update it by running bundle exec rake specs. This script will pull down the latest resource specification to be used with Humidifier.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/kddnewton/humidifier.

License

The gem is available as open source under the terms of the MIT License.


Author: kddnewton
Source code: https://github.com/kddnewton/humidifier
License: MIT license

#ruby  #ruby-on-rails 

Tamale  Moses

Tamale Moses

1669003576

Exploring Mutable and Immutable in Python

In this Python article, let's learn about Mutable and Immutable in Python. 

Mutable and Immutable in Python

Mutable is a fancy way of saying that the internal state of the object is changed/mutated. So, the simplest definition is: An object whose internal state can be changed is mutable. On the other hand, immutable doesn’t allow any change in the object once it has been created.

Both of these states are integral to Python data structure. If you want to become more knowledgeable in the entire Python Data Structure, take this free course which covers multiple data structures in Python including tuple data structure which is immutable. You will also receive a certificate on completion which is sure to add value to your portfolio.

Mutable Definition

Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’ is the ability of objects to change their values. These are often the objects that store a collection of data.

Immutable Definition

Immutable is the when no change is possible over time. In Python, if the value of an object cannot be changed over time, then it is known as immutable. Once created, the value of these objects is permanent.

List of Mutable and Immutable objects

Objects of built-in type that are mutable are:

  • Lists
  • Sets
  • Dictionaries
  • User-Defined Classes (It purely depends upon the user to define the characteristics) 

Objects of built-in type that are immutable are:

  • Numbers (Integer, Rational, Float, Decimal, Complex & Booleans)
  • Strings
  • Tuples
  • Frozen Sets
  • User-Defined Classes (It purely depends upon the user to define the characteristics)

Object mutability is one of the characteristics that makes Python a dynamically typed language. Though Mutable and Immutable in Python is a very basic concept, it can at times be a little confusing due to the intransitive nature of immutability.

Objects in Python

In Python, everything is treated as an object. Every object has these three attributes:

  • Identity – This refers to the address that the object refers to in the computer’s memory.
  • Type – This refers to the kind of object that is created. For example- integer, list, string etc. 
  • Value – This refers to the value stored by the object. For example – List=[1,2,3] would hold the numbers 1,2 and 3

While ID and Type cannot be changed once it’s created, values can be changed for Mutable objects.

Check out this free python certificate course to get started with Python.

Mutable Objects in Python

I believe, rather than diving deep into the theory aspects of mutable and immutable in Python, a simple code would be the best way to depict what it means in Python. Hence, let us discuss the below code step-by-step:

#Creating a list which contains name of Indian cities  

cities = [‘Delhi’, ‘Mumbai’, ‘Kolkata’]

# Printing the elements from the list cities, separated by a comma & space

for city in cities:
		print(city, end=’, ’)

Output [1]: Delhi, Mumbai, Kolkata

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(cities)))

Output [2]: 0x1691d7de8c8

#Adding a new city to the list cities

cities.append(‘Chennai’)

#Printing the elements from the list cities, separated by a comma & space 

for city in cities:
	print(city, end=’, ’)

Output [3]: Delhi, Mumbai, Kolkata, Chennai

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(cities)))

Output [4]: 0x1691d7de8c8

The above example shows us that we were able to change the internal state of the object ‘cities’ by adding one more city ‘Chennai’ to it, yet, the memory address of the object did not change. This confirms that we did not create a new object, rather, the same object was changed or mutated. Hence, we can say that the object which is a type of list with reference variable name ‘cities’ is a MUTABLE OBJECT.

Let us now discuss the term IMMUTABLE. Considering that we understood what mutable stands for, it is obvious that the definition of immutable will have ‘NOT’ included in it. Here is the simplest definition of immutable– An object whose internal state can NOT be changed is IMMUTABLE.

Again, if you try and concentrate on different error messages, you have encountered, thrown by the respective IDE; you use you would be able to identify the immutable objects in Python. For instance, consider the below code & associated error message with it, while trying to change the value of a Tuple at index 0. 

#Creating a Tuple with variable name ‘foo’

foo = (1, 2)

#Changing the index[0] value from 1 to 3

foo[0] = 3
	
TypeError: 'tuple' object does not support item assignment 

Immutable Objects in Python

Once again, a simple code would be the best way to depict what immutable stands for. Hence, let us discuss the below code step-by-step:

#Creating a Tuple which contains English name of weekdays

weekdays = ‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’

# Printing the elements of tuple weekdays

print(weekdays)

Output [1]:  (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’)

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(weekdays)))

Output [2]: 0x1691cc35090

#tuples are immutable, so you cannot add new elements, hence, using merge of tuples with the # + operator to add a new imaginary day in the tuple ‘weekdays’

weekdays  +=  ‘Pythonday’,

#Printing the elements of tuple weekdays

print(weekdays)

Output [3]: (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’, ‘Pythonday’)

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(weekdays)))

Output [4]: 0x1691cc8ad68

This above example shows that we were able to use the same variable name that is referencing an object which is a type of tuple with seven elements in it. However, the ID or the memory location of the old & new tuple is not the same. We were not able to change the internal state of the object ‘weekdays’. The Python program manager created a new object in the memory address and the variable name ‘weekdays’ started referencing the new object with eight elements in it.  Hence, we can say that the object which is a type of tuple with reference variable name ‘weekdays’ is an IMMUTABLE OBJECT.

Also Read: Understanding the Exploratory Data Analysis (EDA) in Python

Where can you use mutable and immutable objects:

Mutable objects can be used where you want to allow for any updates. For example, you have a list of employee names in your organizations, and that needs to be updated every time a new member is hired. You can create a mutable list, and it can be updated easily.

Immutability offers a lot of useful applications to different sensitive tasks we do in a network centred environment where we allow for parallel processing. By creating immutable objects, you seal the values and ensure that no threads can invoke overwrite/update to your data. This is also useful in situations where you would like to write a piece of code that cannot be modified. For example, a debug code that attempts to find the value of an immutable object.

Watch outs:  Non transitive nature of Immutability:

OK! Now we do understand what mutable & immutable objects in Python are. Let’s go ahead and discuss the combination of these two and explore the possibilities. Let’s discuss, as to how will it behave if you have an immutable object which contains the mutable object(s)? Or vice versa? Let us again use a code to understand this behaviour–

#creating a tuple (immutable object) which contains 2 lists(mutable) as it’s elements

#The elements (lists) contains the name, age & gender 

person = (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the tuple

print(person)

Output [1]: (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(person)))

Output [2]: 0x1691ef47f88

#Changing the age for the 1st element. Selecting 1st element of tuple by using indexing [0] then 2nd element of the list by using indexing [1] and assigning a new value for age as 4

person[0][1] = 4

#printing the updated tuple

print(person)

Output [3]: (['Ayaan', 4, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(person)))

Output [4]: 0x1691ef47f88

In the above code, you can see that the object ‘person’ is immutable since it is a type of tuple. However, it has two lists as it’s elements, and we can change the state of lists (lists being mutable). So, here we did not change the object reference inside the Tuple, but the referenced object was mutated.

Also Read: Real-Time Object Detection Using TensorFlow

Same way, let’s explore how it will behave if you have a mutable object which contains an immutable object? Let us again use a code to understand the behaviour–

#creating a list (mutable object) which contains tuples(immutable) as it’s elements

list1 = [(1, 2, 3), (4, 5, 6)]

#printing the list

print(list1)

Output [1]: [(1, 2, 3), (4, 5, 6)]

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(list1)))

Output [2]: 0x1691d5b13c8	

#changing object reference at index 0

list1[0] = (7, 8, 9)

#printing the list

Output [3]: [(7, 8, 9), (4, 5, 6)]

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(list1)))

Output [4]: 0x1691d5b13c8

As an individual, it completely depends upon you and your requirements as to what kind of data structure you would like to create with a combination of mutable & immutable objects. I hope that this information will help you while deciding the type of object you would like to select going forward.

Before I end our discussion on IMMUTABILITY, allow me to use the word ‘CAVITE’ when we discuss the String and Integers. There is an exception, and you may see some surprising results while checking the truthiness for immutability. For instance:
#creating an object of integer type with value 10 and reference variable name ‘x’ 

x = 10
 

#printing the value of ‘x’

print(x)

Output [1]: 10

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(x)))

Output [2]: 0x538fb560

#creating an object of integer type with value 10 and reference variable name ‘y’

y = 10

#printing the value of ‘y’

print(y)

Output [3]: 10

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(y)))

Output [4]: 0x538fb560

As per our discussion and understanding, so far, the memory address for x & y should have been different, since, 10 is an instance of Integer class which is immutable. However, as shown in the above code, it has the same memory address. This is not something that we expected. It seems that what we have understood and discussed, has an exception as well.

Quick checkPython Data Structures

Immutability of Tuple

Tuples are immutable and hence cannot have any changes in them once they are created in Python. This is because they support the same sequence operations as strings. We all know that strings are immutable. The index operator will select an element from a tuple just like in a string. Hence, they are immutable.

Exceptions in immutability

Like all, there are exceptions in the immutability in python too. Not all immutable objects are really mutable. This will lead to a lot of doubts in your mind. Let us just take an example to understand this.

Consider a tuple ‘tup’.

Now, if we consider tuple tup = (‘GreatLearning’,[4,3,1,2]) ;

We see that the tuple has elements of different data types. The first element here is a string which as we all know is immutable in nature. The second element is a list which we all know is mutable. Now, we all know that the tuple itself is an immutable data type. It cannot change its contents. But, the list inside it can change its contents. So, the value of the Immutable objects cannot be changed but its constituent objects can. change its value.

FAQs

1. Difference between mutable vs immutable in Python?

Mutable ObjectImmutable Object
State of the object can be modified after it is created.State of the object can’t be modified once it is created.
They are not thread safe.They are thread safe
Mutable classes are not final.It is important to make the class final before creating an immutable object.

2. What are the mutable and immutable data types in Python?

  • Some mutable data types in Python are:

list, dictionary, set, user-defined classes.

  • Some immutable data types are: 

int, float, decimal, bool, string, tuple, range.

3. Are lists mutable in Python?

Lists in Python are mutable data types as the elements of the list can be modified, individual elements can be replaced, and the order of elements can be changed even after the list has been created.
(Examples related to lists have been discussed earlier in this blog.)

4. Why are tuples called immutable types?

Tuple and list data structures are very similar, but one big difference between the data types is that lists are mutable, whereas tuples are immutable. The reason for the tuple’s immutability is that once the elements are added to the tuple and the tuple has been created; it remains unchanged.

A programmer would always prefer building a code that can be reused instead of making the whole data object again. Still, even though tuples are immutable, like lists, they can contain any Python object, including mutable objects.

5. Are sets mutable in Python?

A set is an iterable unordered collection of data type which can be used to perform mathematical operations (like union, intersection, difference etc.). Every element in a set is unique and immutable, i.e. no duplicate values should be there, and the values can’t be changed. However, we can add or remove items from the set as the set itself is mutable.

6. Are strings mutable in Python?

Strings are not mutable in Python. Strings are a immutable data types which means that its value cannot be updated.

Join Great Learning Academy’s free online courses and upgrade your skills today.


Original article source at: https://www.mygreatlearning.com

#python 

Brook  Hudson

Brook Hudson

1659359100

Tmuxinator: Create and Manage Complex Tmux Sessions Easily Of Ruby

Tmuxinator   

Create and manage tmux sessions easily.

Screenshot

Installation

RubyGems

gem install tmuxinator

Homebrew

brew install tmuxinator

Some users have reported issues when installing via Homebrew, so the RubyGems installation is preferred until these are resolved.

tmuxinator aims to be compatible with the currently maintained versions of Ruby.

Some operating systems may provide an unsupported version of Ruby as their "system ruby". In these cases, users should use RVM or rbenv to install a supported Ruby version and use that version's gem binary to install tmuxinator.

Editor and Shell

tmuxinator uses your shell's default editor for opening files. If you're not sure what that is type:

echo $EDITOR

For me that produces "vim". If you want to change your default editor simply put a line in ~/.bashrc that changes it. Mine looks like this:

export EDITOR='vim'

tmux

The recommended version of tmux to use is 1.8 or later, with the exception of 2.5, which is not supported (see issue 536 for details). Your mileage may vary for earlier versions. Refer to the FAQ for any odd behaviour.

Completion

Your distribution's package manager may install the completion files in the appropriate location for the completion to load automatically on startup. But, if you installed tmuxinator via Ruby's gem, you'll need to run the following commands to put the completion files where they'll be loaded by your shell.

bash

# wget https://raw.githubusercontent.com/tmuxinator/tmuxinator/master/completion/tmuxinator.bash -O /etc/bash_completion.d/tmuxinator.bash

zsh

# wget https://raw.githubusercontent.com/tmuxinator/tmuxinator/master/completion/tmuxinator.zsh -O /usr/local/share/zsh/site-functions/_tmuxinator

Note: ZSH's completion files can be put in other locations in your $fpath. Please refer to the manual for more details.

fish

$ wget https://raw.githubusercontent.com/tmuxinator/tmuxinator/master/completion/tmuxinator.fish ~/.config/fish/completions/

Usage

A working knowledge of tmux is assumed. You should understand what windows and panes are in tmux. If not please consult the man pages for tmux.

Create a project

Create or edit your projects with:

tmuxinator new [project]

Create or edit a local project where the config file will be stored in the current working directory (in .tmuxinator.yml) instead of the default project configuration file location (e.g. ~/.config/tmuxinator):

tmuxinator new --local [project]

For editing you can also use tmuxinator open [project]. new is aliased to n,open to o, and edit to e. Please note that dots can't be used in project names as tmux uses them internally to delimit between windows and panes. Your default editor ($EDITOR) is used to open the file. If this is a new project you will see this default config:

# ~/.tmuxinator/sample.yml

name: sample
root: ~/

# Optional tmux socket
# socket_name: foo

# Note that the pre and post options have been deprecated and will be replaced by
# project hooks.

# Project hooks

# Runs on project start, always
# on_project_start: command

# Run on project start, the first time
# on_project_first_start: command

# Run on project start, after the first time
# on_project_restart: command

# Run on project exit ( detaching from tmux session )
# on_project_exit: command

# Run on project stop
# on_project_stop: command

# Runs in each window and pane before window/pane specific commands. Useful for setting up interpreter versions.
# pre_window: rbenv shell 2.0.0-p247

# Pass command line options to tmux. Useful for specifying a different tmux.conf.
# tmux_options: -f ~/.tmux.mac.conf

# Change the command to call tmux.  This can be used by derivatives/wrappers like byobu.
# tmux_command: byobu

# Specifies (by name or index) which window will be selected on project startup. If not set, the first window is used.
# startup_window: editor

# Specifies (by index) which pane of the specified window will be selected on project startup. If not set, the first pane is used.
# startup_pane: 1

# Controls whether the tmux session should be attached to automatically. Defaults to true.
# attach: false

windows:
  - editor:
      layout: main-vertical
      # Synchronize all panes of this window, can be enabled before or after the pane commands run.
      # 'before' represents legacy functionality and will be deprecated in a future release, in favour of 'after'
      # synchronize: after
      panes:
        - vim
        - guard
  - server: bundle exec rails s
  - logs: tail -f log/development.log

Windows

The windows option allows the specification of any number of tmux windows. Each window is denoted by a YAML array entry, followed by a name* and command to be run.

*Users may optionally provide a null YAML value (e.g. null or ~) in place of a named window key, which will cause the window to use its default name (usually the name of their shell).

windows:
  - editor: vim

Window specific root

An optional root option can be specified per window:

name: test
root: ~/projects/company

windows:
  - small_project:
      root: ~/projects/company/small_project
      panes:
        - start this
        - start that

This takes precedence over the main root option.

Panes

Note that if you wish to use panes, make sure that you do not have . in your project name. tmux uses . to delimit between window and pane indices, and tmuxinator uses the project name in combination with these indices to target the correct pane or window.

Panes are optional and are children of window entries, but unlike windows, they do not need a name. In the following example, the editor window has 2 panes, one running vim, the other guard.

windows:
  - editor:
      layout: main-vertical
      panes:
        - vim
        - guard

The layout setting gets handed down to tmux directly, so you can choose from one of the five standard layouts or specify your own.

Please note the indentation here is deliberate. YAML's indentation rules can be confusing, so if your config isn't working as expected, please check the indentation. For a more detailed explanation of why YAML behaves this way, see this Stack Overflow question.

Note: If you're noticing inconsistencies when using a custom layout it may be due #651. See this comment for a workaround.

Interpreter Managers & Environment Variables

To use tmuxinator with rbenv, RVM, NVM etc, use the pre_window option.

pre_window: rbenv shell 2.0.0-p247

These command(s) will run before any subsequent commands in all panes and windows.

Custom session attachment

You can set tmuxinator to skip auto-attaching to the session by using the attach option.

attach: false

If you want to attach to tmux in a non-standard way (e.g. for a program that makes use of tmux control mode like iTerm2), you can run arbitrary commands by using a project hook:

on_project_exit: tmux -CC attach

Passing directly to send-keys

tmuxinator passes commands directly to send keys. This differs from simply chaining commands together using && or ;, in that tmux will directly send the commands to a shell as if you typed them in. This allows commands to be executed on a remote server over SSH for example.

To support this both the window and pane options can take an array as an argument:

name: sample
root: ~/

windows:
  - stats:
    - ssh stats@example.com
    - tail -f /var/log/stats.log
  - logs:
      layout: main-vertical
      panes:
        - logs:
          - ssh logs@example.com
          - cd /var/logs
          - tail -f development.log

ERB

Project files support ERB for reusability across environments. Eg:

root: <%= ENV["MY_CUSTOM_DIR"] %>

You can also pass arguments to your projects, and access them with ERB. Simple arguments are available in an array named @args.

Eg:

$ tmuxinator start project foo
# ~/.tmuxinator/project.yml

name: project
root: ~/<%= @args[0] %>

...

You can also pass key-value pairs using the format key=value. These will be available in a hash named @settings.

Eg:

$ tmuxinator start project workspace=~/workspace/todo
# ~/.tmuxinator/project.yml

name: project
root: ~/<%= @settings["workspace"] %>

...

Starting a session

This will fire up tmux with all the tabs and panes you configured, start is aliased to s.

tmuxinator start [project] -n [name] -p [project-config]

If you use the optional [name] argument, it will start a new tmux session with the custom name provided. This is to enable reuse of a project without tmux session name collision.

If there is a ./.tmuxinator.yml file in the current working directory but not a named project file in ~/.tmuxinator, tmuxinator will use the local file. This is primarily intended to be used for sharing tmux configurations in complex development environments.

You can provide tmuxinator with a project config file using the optional [project-config] argument (e.g. --project-config=path/to/my-project.yaml or -p path/to/my-project.yaml). This option will override a [project] name (if provided) and a local tmuxinator file (if present).

Shorthand

The shell completion files also include a shorthand alias for tmuxinator that can be used in place of the full name*.

mux [command]

*The mux alias has been removed from the Zsh completion script because it was resulting in unexpected behavior in some setups. Including aliases in completion scripts is not standard practice and the Bash and Fish aliases may be removed in a future release. Going forward, users should create their own aliases in their shell's RC file (e.g. alias mux=tmuxinator).

Other Commands

Copy an existing project. Aliased to c and cp

tmuxinator copy [existing] [new]

List all the projects you have configured. Aliased to l and ls

tmuxinator list

Remove a project. Aliased to rm

tmuxinator delete [project]

Remove all tmuxinator configs, aliases and scripts. Aliased to i

tmuxinator implode

Examines your environment and identifies problems with your configuration

tmuxinator doctor

Shows tmuxinator's help. Aliased to h

tmuxinator help

Shows the shell commands that get executed for a project

tmuxinator debug [project]

Shows tmuxinator's version.

tmuxinator version

Project Configuration Location

Using environment variables, it's possible to define which directory tmuxinator will use when creating or searching for project config files. (See PR #511.)

Tmuxinator will attempt to use the following locations (in this order) when creating or searching for existing project configuration files:

  • $TMUXINATOR_CONFIG
  • $XDG_CONFIG_HOME/tmuxinator
  • ~/.tmuxinator

FAQ

Window names are not displaying properly?

Add export DISABLE_AUTO_TITLE=true to your .zshrc or .bashrc

Contributing

To contribute, please read the contributing guide.

Copyright

Copyright (c) 2010-2020 Allen Bargi, Christopher Chow. See LICENSE for further details.


Author:  tmuxinator
Source code: https://github.com/tmuxinator/tmuxinator
License: MIT license

#ruby #ruby-on-rails 

Royce  Reinger

Royce Reinger

1658899080

MediaWiki API: A Library for interacting with MediaWiki API From Ruby

MediaWiki API

A library for interacting with MediaWiki API from Ruby. Uses adapter-agnostic Faraday gem to talk to the API.

Installation

Add this line to your application's Gemfile:

gem "mediawiki_api"

And then execute:

$ bundle

Or install it yourself as:

$ gem install mediawiki_api

Usage

Assuming you have MediaWiki installed via MediaWiki-Vagrant.

require "mediawiki_api"

client = MediawikiApi::Client.new "http://127.0.0.1:8080/w/api.php"
client.log_in "username", "password" # default Vagrant username and password are "Admin", "vagrant"
client.create_account "username", "password" # will not work on wikis that require CAPTCHA, like Wikipedia
client.create_page "title", "content"
client.get_wikitext "title"
client.protect_page "title", "reason", "protections" #  protections are optional, default is "edit=sysop|move=sysop"
client.delete_page "title", "reason"
client.upload_image "filename", "path", "comment", "ignorewarnings"
client.watch_page "title"
client.unwatch_page "title"
client.meta :siteinfo, siprop: "extensions"
client.prop :info, titles: "Some page"
client.query titles: ["Some page", "Some other page"]

Advanced Usage

Any API action can be requested using #action. See the MediaWiki API documentation for supported actions and parameters.

By default, the client will attempt to get a csrf token before attempting the action. For actions that do not require a token, you can specify token_type: false to avoid requesting the unnecessary token before the real request. For example:

client.action :parse, page: 'Main Page', token_type: false

Links

MediaWiki API gem at: Gerrit, GitHub, RubyGems, Code Climate.

Contributing

See https://www.mediawiki.org/wiki/Gerrit

Release notes

0.7.1 2017-01-31

  • Add text param to MediawikiApi::Client#upload_image

0.7.0 2016-08-03

  • Automatically follow redirects for all API requests.

0.6.0 2016-05-25

  • Update account creation code for AuthManager. This change updates the gem to test which API flavor is in use, then send requests accordingly.

0.5.0 2015-09-04

  • Client cookies can now be read and modified via MediawikiApi::Client#cookies.
  • Logging in will recurse upon a NeedToken API error only once to avoid infinite recursion in cases where authentication is repeatedly unsuccessful.

0.4.1 2015-06-17

  • Allow for response-less ApiError exceptions to make mocking in tests easier

0.4.0 2015-06-16

  • Use action=query&meta=tokens to fetch tokens, instead of deprecated action=tokens

0.3.1 2015-01-06

  • Actions now automatically refresh token and re-submit action if first attempt returns 'badtoken'.

0.3.0 2014-10-14

  • HTTP 400 and 500 responses now result in an HttpError exception.
  • Edit failures now result in an EditError exception.

0.2.1 2014-08-26

  • Fix error handling for token requests

0.2.0 2014-08-06

  • Automatic response parsing.
  • Handling of API error responses.
  • Watch/unwatch support.
  • Query support.
  • Public MediawikiApi::Client#action method for advanced API use.

0.1.4 2014-07-18

  • Added MediawikiApi::Client#protect_page.
  • Updated documentation.

0.1.3 2014-06-28

  • Added MediawikiApi::Client#upload_image.

0.1.2 2014-04-11

  • Added MediawikiApi::Client#get_wikitext.

0.1.1 2014-04-01

  • Updated documentation.

0.1.0 2014-03-13

  • Complete refactoring.
  • Removed MediawikiApi#create_article, #create_user and #delete_article.
  • Added MediawikiApi::Client#new, #log_in, #create_page, #delete_page, #create_account.
  • Added unit tests.

0.0.2 2014-02-11

  • Added MediawikiApi#delete_article.

0.0.1 2014-02-07

  • Added MediawikiApi#create_article and #create_user.

Author: Wikimedia
Source Code: https://github.com/wikimedia/mediawiki-ruby-api 
License: View license

#ruby #api #media