Blog

  • puppet-mackerel_agent

    Puppet module for mackerel-agent

    Puppet Forge Dependency Status Build Status

    Table of Contents

    1. Overview – What is the mackerel_agent module?
    2. Setup – The basics of getting started
    3. Usage – How to use the module
    4. Limitations – OS compatibility, etc.
    5. Development – Guide for contributing to the module

    Overview

    This Puppet module install and configure mackerel-agent.

    Setup

    Install via Puppet Forge:

    $ puppet module install tomohiro-mackerel_agent

    Usage

    class { 'mackerel_agent':
      apikey              => 'Your API Key',
      roles               => ['service:web', 'service:database'],
      host_status         => {
        on_start => 'working',
        on_stop  => 'poweroff'
      },
      ignore_filesystems  => '/dev/ram.*',
      use_metrics_plugins => true,
      use_check_plugins   => true,
      metrics_plugins     => {
        apache2     => '/usr/local/bin/mackerel-plugin-apache2',
        php-opcache => '/usr/local/bin/mackerel-plugin-php-opcache'
      },
      check_plugins       => {
        access_log => '/usr/local/bin/check-log --file /var/log/access.log --pattern FATAL',
        check_cron => '/usr/local/bin/check-procs -p crond'
        check_ssh  => {
          command               => 'ruby /path/to/check-ssh.rb',
          notification_interval => '60',
          max_check_attempts    => '3',
          check_interval        => '5'
        }
      }
    }

    Hiera

    mackerel_agent::apikey: 'Your API Key'
    mackerel_agent::roles:
      - 'service:web'
      - 'service:database'
    mackerel_agent::host_status:
      on_start: working
      on_stop: poweroff
    mackerel_agent::ignore_filesystems: '/dev/ram.*'
    mackerel_agent::use_metrics_plugins: true
    mackerel_agent::use_check_plugins: true
    mackerel_agent::metrics_plugins:
      apache2: '/usr/local/bin/mackerel-plugin-apache2'
      php-opcache: '/usr/local/bin/mackerel-plugin-php-opcache'
    mackerel_agent::check_plugins:
      access_log: '/usr/local/bin/check-log --file /var/log/access.log --pattern FATAL'
      check_cron: '/usr/local/bin/check-procs -p crond'
      ssh:
        command: 'ruby /path/to/check-ssh.rb'
        notification_interval: '60'
        max_check_attempts: '3'
        check_interval: '5'

    Limitations

    These operation systems are supported.

    • RHEL 6
    • CentOS 6
    • Debian 7
    • Ubuntu 14.04

    The person who want to add an operating system to supported list should implement it himself.

    Development

    Requirements

    • Puppet 3.7 or later
    • librarian-puppet

    Setup development environments

    Install dependencies:

    $ bundle install --path vendor/bundle
    $ bundle exec librarian-puppet install

    You can run smoke tests:

    $ export MACKEREL_API_KEY="your api key" # Export a your mackerel API key
    $ vagrant up
    $ vagrant provision

    Testing

    Unit tests:

    $ bundle exec rake spec

    Acceptance tests:

    $ export DOCKER_HOST=tcp://your-docker-host-ip:port
    $ BEAKER_set=centos-6-x64 bundle exec rake beaker

    Contributing

    See CONTRIBUTING guideline.

    LICENSE

    © 2014 – 2016 Tomohiro TAIRA.

    This project is licensed under the Apache License, Version 2.0. See LICENSE for details.

    Visit original content creator repository https://github.com/tomohiro/puppet-mackerel_agent
  • yii2-imgcache

    Image effect, thumb and cache extension for Yii2

    Latest Stable Version Total Downloads License

    About

    The lireincore/imgcache integration for Yii2 framework.

    Install

    Add the "lireincore/yii2-imgcache": "^0.6" package to your require section in the composer.json file

    or

    $ php composer.phar require lireincore/yii2-imgcache

    Usage

    To use this extension, you need to create the imgcache.php file in your config folder and add this code:

    <?php
    
    return [
        'srcdir' => '@app/files/images',
        'destdir' => '@webroot/thumbs',
        'webdir' => '@webroot',
        'baseurl' => '@web',
        //....
        'presets' => [
            'origin' => [
                'effects' => [
                    //add the effects you need
                    //....
                ],
            ],
        ],
    ];

    See lireincore/imgcache README.md for more information about the available effects and other config options.

    Also add the following code in your Yii2 application configuration:

    $config = [
        //....
        'container' => [
            //....
            'singletons'  => [
                //....
                LireinCore\Yii2ImgCache\ImgCache::class => [
                    ['class' => LireinCore\Yii2ImgCache\ImgCache::class],
                    [
                        require(__DIR__ . '/imgcache.php'),
                    ]
                ],
            ]
        ],
    ];

    Use in your code:

    use LireinCore\Yii2ImgCache\ImgCache;
    
    $imgCache = Yii::$container->get(ImgCache::class);
    
    // get thumb url for image '{srcdir}/blog/image.jpg' (preset 'origin')
    $url = $imgcache->url('blog/image.jpg', 'origin');
    
    
    // get thumb url for image '{srcdir}/blog/image.jpg' (preset 'origin')
    $url = \Yii::$app->imgcache->url('blog/image.jpg', 'origin');

    See lireincore/imgcache README.md for more information about the available functions.

    License

    This project is licensed under the MIT License – see the License File file for details

    Visit original content creator repository https://github.com/lireincore/yii2-imgcache
  • SingletonBundle-CSharp

    GodotParadiseSingletonBundle-CSharp logo

    Godot Paradise SingletonBundle-CSharp

    LastCommit Stars Total downloads License PRs Welcome Kofi

    es


    This plugin offers a collection of singletons that encompass global resources and functionalities that can enhance your game’s utility and accessibility.

    Requirements

    📢 We don’t currently give support to Godot 3+ as we focus on future stable versions from version 4 onwards

    • Godot 4+

    ✨Installation

    Automatic (Recommended)

    You can download this plugin from the official Godot asset library using the AssetLib tab in your godot editor. Once installed, you’re ready to get started

    Manual

    To manually install the plugin, create an “addons” folder at the root of your Godot project and then download the contents from the “addons” folder of this repository

    GDScript version

    This plugin has also been written in GDscript and you can find it on SingletonBundle

    Getting Started

    Each singleton is separated by a class name that defines its utility. This classes are autoloaded by Godot and added to the root scene make them globally available in all scenes of your project.

    🧙‍♂️ Vector Wizard

    A set of useful vector utilities that you are likely to use in your day-to-day work as a game developer. The functions that are marked as v2 means that applies to Vector2 and v3 that applies to Vector3. If v3 functions have no description, it means that they do exactly the same thing but applied in a 3-dimensional space.

    Vector2 NormalizeVector(Vector2 value)

    Normalize the vector only if it’s not normalized and also changes if it’s diagonal vector and do the proper normalization. Returns the vector GodotParadiseVectorWizard.NormalizeVector(Vector2(30, -40)) # returns Vector2(1, -1)

    Vector2 NormalizeDiagonalVector(Vector2 direction)

    A diagonal vector requires additional treatment, which can be applied using this function. GodotParadiseVectorWizard.NormalizeDiagonalVector(Vector2(-0.7444, 0.7444))

    bool IsDiagonalDirection(Vector2 direction)

    Performs a basic check and returns whether the direction passed as a parameter is diagonal. This function is used internally by the normalize_diagonal_vector function. GodotParadiseVectorWizard.is_diagonal_direction(Vector2(1, -1))

    Vector2 GenerateRandomDirection()

    Simple random Vector2 direction generator, use this function if you need a random direction in some behaviour of your game. The result is normalized

    GenerateRandomAngle(float minAngleRange = 0.0f, float maxAngleRange = 360.0f)

    Generate a random angle between a range provided, the unit is on degrees

    # Between 90º and 120º
    GodotParadiseVectorWizard.generate_random_angle(90, 120) # 117º

    GenerateRandomDirectionsOnAngleRange(Vector2 origin, float minAngleRange = 0.0f, float maxAngleRange = 360.0f, int numDirections = 10)

    This function generate a n random directions in a Array[Vector2] format from an starting vector point defining the min and max angles:

    # 5 Random directions from Vector down (0, 1) between 90º and 180º
    GodotParadiseVectorWizard.GenerateRandomDirectionsOnAngleRange(Vector2.Down, 90.0f, 180.0f, 5)
    
    # 25 random directions from the actual player global position between 0 and 360º
    GodotParadiseVectorWizard.GenerateRandomDirectionsOnAngleRange(player.GlobalPosition, 0.0f, 360.0f, 25)

    Vector2 TranslateXAxisToVector(float axis)

    Translate a value that usually comes from Input.GetAxis into a direction Vector2. Vector2 horizontalDirection = GodotParadiseVectorWizard.TranslateXAxisToVector(Input.GetAxis("ui_left", "ui_right"))

    float DistanceManhattanV2(Vector2 a, Vector2 b)

    Also known as the “city distance” or “L1 distance”. It measures the distance between two points as the sum of the absolute differences of their coordinates in each dimension.

    Examples on where can be useful:

    Path of a character in a maze: In a maze game, you can use the Manhattan distance to calculate the distance between a character’s current position and a potential exit. This will help you determine the direction in which the character should move to reach the exit with the least amount of moves, as it only allows moves in straight lines, such as up, down, left and right.

    Sliding puzzle: In puzzle games where you must move pieces to solve a puzzle, the Manhattan distance is used to calculate how far a piece is from its target position. The closer a piece is to its correct position, the more it will “fit” into the puzzle.

    float DistanceChebysevV2(Vector2 a, Vector2 b)

    Also known as the “chess distance” or “L∞ distance”. It measures the distance between two points as the greater of the absolute differences of their coordinates in each dimension.

    Examples on where can be useful:

    Movement of a king in chess: In a game of chess, the king moves in any direction (horizontally, vertically or diagonally). The Chebyshev distance is used to determine how many moves it takes for the king to move from its current position to a target square, since the king can move in any of these directions.

    Movement in a turn-based strategy game: In a turn-based strategy game, such as Civilization, where units can move in several directions, the Chebyshev distance can be used to calculate the distance between two locations on the map and determine how many turns it would take to get from one to the other.

    float LengthManhattanV2(Vector2 a)

    The LengthManhattanV2 function calculates the length or magnitude of a two-dimensional vector a using the Manhattan distance. Manhattan distance is determined by summing the absolute differences of the x and y coordinates of the vector. The result is a scalar value that represents the total distance traveled in terms of vertical and horizontal movements, which is useful in situations where movements occur in straight lines along orthogonal axes.

    float LengthChebysevV2(Vector2 a, Vector2 b)

    The LengthChebysevV2 function calculates the length or magnitude of a two-dimensional vector a using the Chebyshev distance. Chebyshev distance is determined by taking the maximum of the absolute differences between the x and y coordinates of the vector. The result is a scalar value that represents the maximum distance traveled in terms of movements in any direction, whether vertical, horizontal, or diagonal. This metric is useful in situations where movements can occur in multiple directions.

    Vector2 ClosestPointOnLineClampedV2(Vector2 a, Vector2 b, Vector2 c)

    This function is specifically designed to find the closest point on a line segment, ensuring that the result lies within the boundaries of the segment. It’s particularly useful in scenarios where it’s essential to constrain the closest point to the line.

    For example, in a drawing application, you can employ this function to accurately snap a point to the nearest position on a line when creating freehand drawings.

    Vector2 ClosestPointOnLineV2(Vector2 a, Vector2 b, Vector2 c)

    In contrast to the ClosestPointOnLineClampedV2 function, this variant is intended to identify the closest point on a line segment without imposing any restrictions on its location within or outside the segment. This makes it versatile in situations where you need to find the nearest point on a line but don’t require it to be confined to the segment.

    For instance, in a CAD application, you might use this function to locate the closest point on a sketch line to a user-defined point.

    float DistanceManhattanV3(Vector3 a, Vector3 b)

    float DistanceChebysevV3(Vector3 a, Vector3 b)

    float LengthManhattanV3(Vector3 a)

    float LengthChebysevV3(Vector3 a, Vector3 b)

    Vector3 ClosestPointOnLineClampedV3(Vector3 a, Vector3 b, Vector3 c)

    Vector3 ClosestPointOnLineV3(Vector3 a, Vector3 b, Vector3 c)

    float ClosestPointOnLineNormalizedV3(Vector3 a, Vector3 b, Vector3 c)

    🕶️ General utilities

    Utilities that do not have a particular location and belong to a more global scope.

    string GenerateRandomString(int length, string characters = “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789”)

    You can use this function to generate a random string with a specified length and character list. For instance, you can utilize this function to create invitation codes for your multiplayer rooms:

    string invitationCode = GodotParadiseUtilities.GenerateRandomString(4, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") # returns YMZ2

    bool IsValidUrl(string url)

    As the String class from Godot lack this validation you can use the following one:

    GodotParadiseUtilities.IsValidUrl("https://example.com") # true

    async void StartFrameFreeze(double timeScale, double duration)

    To achieve a slow-motion effect you can use this function that receives the time scale (as time goes by frame by frame) and the duration of the freeze in seconds.

    # Time scale 0.05
    # Duration 0.5 sec
    GodotParadiseUtilities.StartFrameFreeze(0.05, 0.5)

    Here you can see an example that trigger a frame freeze when a character jumps:

    public void handleJump():
    	if (Input.IsActionJustPressed("jump")) {
    		player.Jump();
    		GodotParadiseUtilities.StartFrameFreeze(0.05, 1);
    	}

    FrameFreezed signal is emitted when the effect starts in case you want to listen to it to perform other actions such as triggering animations. Here you can see a basic example:

    public override _Ready():
       GodotParadiseUtilities.StartFrameFreeze += OnFrameFreezed;
    
    private void OnFrameFreezed():
       AnimatedSprite.Play("juicy_hurt")
        //...

    ⚙️ Environment variables

    To keep environment variables secure, avoid hard-coding sensitive information into your source code. By utilizing environment variables, you can ensure that such information remains protected.

    Environment variables provide a standardized and crucial method for effectively managing sensitive information within your software projects. These variables serve as a secure repository for storing a wide range of confidential data, including but not limited to API keys, access tokens, database credentials, and configuration settings.

    You can access all features by using the GodotParadiseEnvironment class in any part of your code. This class provides extra functionality while maintaining compatibility with OS.GetEnvironment() and OS.SetEnvironment() for runtime variable management. By default, this class looks for .env files in the root of your project res:// To modify this path, you can use:

    GodotParadiseEnvironment.EnvironmentFilesPath = "res://project"

    or set the value on the Project settings -> GodotEnv -> Root directory: godotenv_settings

    Variable tracker

    For internal execution convenience, the plugin tracks active variables without storing their values in array, as storing sensitive content in this array can risk data leaks or unauthorized access. This approach allows you to verify which variables have been read and loaded into memory without exposing their values:

    GodotParadiseEnvironment.EnvironmentVariableTracker # could return ["ADDRESS", "PORT", "SERVER_ID]

    Example of use

    // .env file
    ADDRESS=127.0.0.1
    PORT=9492
    
    SERVER_ID=1919
    
    // random_script.cs
    GodotParadiseEnvironment.LoadEnvFile(".env")
    
    GodotParadiseEnvironment.GetVar("PORT") // Returns an empty string if does not exists
    // or
    GodotParadiseEnvironment.GetVarOrNull("PORT") // Returns null instead

    You only need to load your environment variables once, and there’s no need to load them in every _Ready() function in your nodes. If you have duplicate variables, the value used will be the one from the last occurrence. Therefore, it’s important to review your files carefully to avoid unintentional overwriting.

    ADDRESS=127.0.0.1
    ADDRESS=192.168.1.55 # This is the one that will be assigned as it overwrites the previous one

    Loading variables from other files

    This class supports reading multiple environment files. For production, it’s highly advisable to refrain from including the .env file in your source code repository. Instead, consider providing on the repository an .env.example file with blank values for the keys used. This strategy enables you to duplicate the file and input the values in your local environment, thereby averting the inadvertent exposure of sensitive information.

    // .env.example
    ADDRESS=
    PORT=
    SERVER_NAME=
    
    // random_script.cs
    GodotParadiseEnvironment.LoadEnvFile(".env.example")
    GodotParadiseEnvironment.LoadEnvFile(".env.dev")
    GodotParadiseEnvironment.LoadEnvFile(".env.staging")
    // ...

    Signals

    VariableAdded(string key)
    VariableRemoved(string key)
    VariableReplaced(string key)
    EnvFileLoaded(string filename)

    string GetVar(string key)

    This is an alternative to OS.GetEnvironment(key) :

    GodotParadiseEnvironment.GetVar("SERVER_PORT")

    string GetVarOrNull(string key)

    Retrieve the value of an environment variable by its key or null it if it doesn’t:

    GodotParadiseEnvironment.GetVarOrNull("SERVER_PORT")

    void SetVar(string key, string value = “”)

    Set a environment variable on the runtime process, this is an alternative to OS.SetEnvironment(key, value):

    GodotParadiseEnvironment.SetVar("API_KEY", "991918291921")

    void RemoveVar(string key)

    Remove a variable from the runtime process

    GodotParadiseEnvironment.RemoveVar("API_KEY")

    void CreateEnvironmentFile(string filename = “.env”, bool overwrite = false)

    Create an environment file with the specified filename. If it already exists, it can be overwritten

    GodotParadiseEnvironment.CreateEnvironmentFile(".env")
    GodotParadiseEnvironment.AddVarToFile("env", "PORT", 3000)
    GodotParadiseEnvironment.AddVarToFile("env", "ENCRYPTION_ALGORITHM", 'SHA256')

    LoadEnvFile(filename: String = “.env”) -> void

    Read an .env file and set the valid environment variables to be accessible in the code: GodotParadiseEnvironment.LoadEnvFile(".env.example")

    void FlushEnvironmentVariables(string filename = “.env”, Array except = null)

    Remove environment variables from the current process runtime. You can add the keys that you do not want to be deleted in this process as second parameter:

    GodotParadiseEnvironment.FlushEnvironmentVariables(".env")
    GodotParadiseEnvironment.FlushEnvironmentVariables(".env", ["IP_ADDRESS", "COUNTRY"])

    void AddVarToFile(string filename, string key, string value = “”)

    Add a key-value pair to an environment file and set the environment variable

    GodotParadiseEnvironment.AddVarToFile("env", "PORT", 4500)
    GodotParadiseEnvironment.AddVarToFile("env", "APP_NAME", 'FightingTournament')

    🎬 Scene transitioner

    This handler facilitates seamless transitions between scenes, offering the option to include a loading screen, particularly useful for larger scenes.

    The singleton can be accessed through GodotParadiseSceneTransitioner. This manager utilizes the foundational class GodotParadiseSceneTransition to manage scene transitions.

    To effectively utilize this system, you are required to create your transition scenes by extending the foundational class GodotParadiseSceneTransition.

    These transition scenes should incorporate the essential signals and parameters necessary for seamless integration with the singleton.

    The GodotParadiseSceneTransition primarily functions as a container for managing additional parameters and emitting the appropriate signals. For example, consider a real use case, such as a fade scene where you can specify the animation name to choose between different types of fades (e.g., ‘fade_in’ or ‘fade_out’).

    // This is your transition_scene
    
    public partial class YourTransitionScene : GodotParadiseSceneTransition {
    
    	public AnimationPlayer animationPlayer;
    
    	public override _Ready() {
    		animationPlayer = GetNode<AnimationPlayer>("AnimationPlayer");
    		animationPlayer.Play(data["animation"])
    
    		animationPlayer.AnimationFinished += OnAnimationFinished;
    	}
    
    	private void OnAnimationFinished(string name) {
    		if(AnimationPlayer.GetAnimationList().Contains(name)) {
    			EmitSignal(SignalName.FinishedTransition, data);
    			QueueFree();
    		}
    	}
    }

    This is an example on how to use the transitioner, the TargetScene parameter can be provided as either a PackedScene or the file path to the desired scene:

    PackedScene TargetScene = ResourceLoader.Load<PackedScene>("res://example.tscn") # or raw string "res://example.tscn"
    PackedScene yourTransitionScene = ResourceLoader.Load<PackedScene>("res://transitions/fade.tscn")
    
    GodotParadiseSceneTransitioner.TransitionTo(target_scene, yourTransitionScene, new(){{"animation", "fade_in"}})

    It’s important to note that the FinishedTransition signal must be manually emitted. This design choice provides flexibility in determining precisely when a transition is considered complete.

    Transition with loading screen

    This class offers a function designed for working with a loading screen as a transition. To utilize this functionality, your custom loading scene must also extend from GodotParadiseSceneTransition to receive progression data.

    In this case, the FinishedTransition signal is emitted after the progress value reachs 1 when the scene load is completed.

    This feature is particularly beneficial for large scenes where loading times may be longer. When providing the scene, it should be passed as a file path since our class internally leverages the ResourceLoader

    PackedScene TargetScene = ResourceLoader.Load<PackedScene>("res://large_scene_example.tscn") # or raw string "res://example.tscn"
    PackedScene loadingScene = ResourceLoader.Load<PackedScene>("res://transitions/loading.tscn")
    
    GodotParadiseSceneTransitioner.TransitionToWithLoading(target_scene, loading)

    In the loading scene, you gain access to progress and load status data retrieved from the ResourceLoader, which you can utilize to display relevant information. Below is a basic example to demonstrate this functionality. To ensure proper functionality, it’s essential to call the parent base._Process() function; failing to do so will result in the information not being updated:

    // res://transitions/loading.tscn
    public partial class YourLoadingTransitionScene : GodotParadiseSceneTransition {
    	ProgressBar progressBar;
    
    	public override _Ready() {
    		progressBar = GetNode<ProgressBar>("CenterContainer/ProgressBar");
    	}
    
    	public override void _Process(double delta) {
    		base._Process(delta);
    		progressBar.Value = progress[0];
    	}
    }

    GodotParadiseSceneTransicioner

    TransitionTo(string scene, string transition, TransitionData data)

    The primary function responsible for initiating the transition to the target scene is the TransitionTo function. Any data passed to this function will be accessible within the transition scene, enabling the incorporation of external parameters as needed. It is focused on transitioning pre-loaded scenes.

    The Scene parameter can be received as PackedScene or String file path.

    It’s worth noting that the transition scene is added to the viewport, not the scene tree. This approach ensures that the transition will execute even if nodes in the main tree are freed

    void TransitionToWithLoading(string scene, string loadingScene, TransitionData data)

    It behaves identically to TransitionTo, but with one key distinction: the scene parameter must be provided as a file path string. This requirement is due to the transitioner’s utilization of the ResourceLoader for scene loading

    GodotParadiseSceneTransition

    Variables

    • public TransitionData Data;
    • public Array Progress;
    • public ResourceLoader.ThreadLoadStatus LoadStatus
    enum  ThreadLoadStatus:
    
    ● THREAD_LOAD_INVALID_RESOURCE = 0
    #The resource is invalid, or has not been loaded with load_threaded_request().THREAD_LOAD_IN_PROGRESS = 1
    # The resource is still being loaded.THREAD_LOAD_FAILED = 2
    # Some error occurred during loading and it failed.THREAD_LOAD_LOADED = 3
    # The resource was loaded successfully and can be accessed via load_threaded_get().

    TransitionData is a custom class that transport specific parameters for the transition:

    public record TransitionData
    {
        public string ScenePath { get; set; } = string.Empty;
        public string TargetScene { get; set; } = string.Empty;
        public bool IsLoadingScreen { get; set; } = false;
    
        public TransitionData(string scenePath, string targetScene, bool isLoadingScreen = false)
        {
            ScenePath = scenePath;
            TargetScene = targetScene;
            IsLoadingScreen = isLoadingScreen;
        }
    
        public Dictionary ToDictionary()
        {
            return new() {
                { "scenePath", ScenePath },
                { "targetScene", TargetScene },
                { "isLoadingScreen", IsLoadingScreen }
             };
        }
    }

    Signals

    • StartedTransition(Dictionary data)
    • FinishedTransition(Dictionary data, PackedScene nextScene) NextScene it’s only provided on TransitionToWithLoading

    🎵 Audio

    Several helper functions for managing the volume levels of various buses in your game.

    Accessible normal variables

    • public Array AvailableBuses

    Here is an array list of the available buses set up in your project, for example:

    GodotParadiseAudioManager.AvailableBuses # returns ["Master", "Music", "SFX"]

    void ChangeVolume(dynamic bus, float value)

    Change the volume of selected BusIndex if it exists. Can receive the bus parameter as name or index.

    GodotParadiseAudioManager.ChangeVolume(1, 0.5f)
    # or
    GodotParadiseAudioManager.ChangeVolume("Music", 0.5f)

    float GetActualVolumeDBFromBusName(string name)

    Retrieve the current volume value for the selected bus by its name. If the BusName does not exist in your project, it will raise an error and return a value of 0.0.

    GodotParadiseAudioManager.GetActualVolumeDBFromBusName("Music")

    float GetActualVolumeDBFromBusIndex(int busIndex)

    Retrieve the current volume value for the selected bus by its index.

    GodotParadiseAudioManager.GetActualVolumeDBFromBusIndex(1)
    # or
    GodotParadiseAudioManager.GetActualVolumeDBFromBusIndex(AudioServer.GetBusIndex("Music"))

    Functional Example:

    Let’s demonstrate how these functions can assist us in audio management within our game:

    public partial class YourUIScene : Control {
    	HSlider Music;
    	HSlider SFX;
    
    	public override _Ready() {
    		Music = GetNode<HSlider>("Parameters/VBoxContainer/HorizontalContainer/Sliders/Music");
    
    		SFX = GetNode<HSlider>("Parameters/VBoxContainer/HorizontalContainer/Sliders/SFX");
    
    		Music.Value = GodotParadiseAudioManager.GetActualVolumeDBFromBusName("Music")
    		SFX.Value = GodotParadiseAudioManager.GetActualVolumeDBFromBusName("SFX")
    	}
    
    	private void OnMusicValueChanged(float value) {
    		GodotParadiseAudioManager.ChangeVolume("Music", value)
    	}
    
    	private void OnMusicValueChanged(float value) {
    		GodotParadiseAudioManager.ChangeVolume("SFX", value)
    	}
    }

    ✌️You are welcome to

    GodotParadise is available for free.

    If you’re grateful for what we’re doing, please consider a donation. Developing GodotParadise requires massive amount of time and knowledge, especially when it comes to Godot. Even $1 is highly appreciated and shows that you care. Thank you!


    🤝Contribution guidelines

    Thank you for your interest in Godot Paradise!

    To ensure a smooth and collaborative contribution process, please review our contribution guidelines before getting started. These guidelines outline the standards and expectations we uphold in this project.

    📓Code of Conduct: We strictly adhere to the Godot code of conduct in this project. As a contributor, it is important to respect and follow this code to maintain a positive and inclusive community.


    📇Contact us

    If you have built a project, demo, script or example with this plugin let us know and we can publish it here in the repository to help us to improve and to know that what we do is useful.

    Visit original content creator repository https://github.com/BananaHolograma/SingletonBundle-CSharp
  • dagota

    Dynomite on OpenShift as Statefulset

    Dynomite (https://github.com/Netflix/dynomite) is a distributed dynamo layer for redis and memcached hight availability. It is use to replicate each service with data and that’s mainly what we need with OpenShift statefulsets.

    Note: memcached is not tested at this time.

    The project includes 2 docker images:

    Both images are based on openshift/base-centos7 image to be able to start without any user rights problem on OpenShift.

    Also, this images should be coupled with a Redis container that listens on 22122 port (invert of memcached port 11211).

    So that Pod has got 3 containers, one for dagota (to send detected peers to dynoite), dynomite that is used as redis proxy, and redis that is the service to use internally. You should make a service to bind on dynomite port (6379) and not on 22122, keep in mind that dynomite is the entrypoint.

    You can try example at https://raw.githubusercontent.com/Smile-SA/dagota/master/dynomite.statefulset.test.yml:

    oc create -f https://raw.githubusercontent.com/Smile-SA/dagota/master/dynomite.statefulset.persistent.yml
    # or, without storage
    oc create -f https://raw.githubusercontent.com/Smile-SA/dagota/master/dynomite.statefulset.yml

    Important You must use “dynomite:6379” (Service) from other pods to connect redis ! Don’t connect to redis (22122).

    Now you can try to SET/GET values:

    $ oc run -it --name=redis-cli --image=redis --restart=Never -- bash
    > redis-cli -h dynomite set foo "bar"
    OK
    > redis-cli -h dynomite get foo
    "bar"
    > exit
    
    # then remove that pod
    oc delete pod redis-cli --now
    

    Notes to not break your init

    • Be sure that serviceName and SERVICE env var in statefulset are the same value as the Service name
    • Be sure that clusterIP in service is set to None
    • Check that redis is listening on 22122

    TODO

    • Better dagota go code
    • Test memcached
    • Check why centos/redis-32-centos7 fails some connection while library/redis is ok
    • livenessProbe and readinessProbe
    • Volumes templates for redis

    Visit original content creator repository
    https://github.com/Smile-SA/dagota

  • Grocery_helper

    Grocery_helper


    Description

    A webapp that keeps track of your groceries list and shopping cart items.

    Languages, Libraries & Frameworks

    • React
    • JavaScript
    • CSS
    • HTML

    Setup

    1. Clone the repository to a local directory
    2. cd into the directory and run npm start to run the app in development mode
    3. run npm run build or yarn build to build the app for production

    Screenshots

    alt text

    Live Demo

    https://hungry-jennings-92ae10.netlify.app

    Usage & Details

    The goal of this webapp is to facilitate doing the groceries by keeping track of your grocery list as well as tracking the items in your shopping cart.

    • To add a new grocery item, fill the item’s name in the ‘grocery list’ top bar and press ‘+’
    • To add an item to your ‘shopping cart’, tap on the desired grocery list item
    • To add multiple items to your cart, tap the desired number of times on the desired grocery list item
    • To empty your cart, tap on the ’empty cart’ button in the cart’s top bar

    Issues/ Missing Features

    • As a user i’d like to be able to edit and remove items from grocery list and shopping cart
    • As a user i’d like the possibility to manually enter item quantities
    • As a user i’d like an item added to cart to automatically or manually be grayed out from my grocery list
    Visit original content creator repository https://github.com/NTielman/Grocery_helper
  • Grocery_helper

    Grocery_helper


    Description

    A webapp that keeps track of your groceries list and shopping cart items.

    Languages, Libraries & Frameworks

    • React
    • JavaScript
    • CSS
    • HTML

    Setup

    1. Clone the repository to a local directory
    2. cd into the directory and run npm start to run the app in development mode
    3. run npm run build or yarn build to build the app for production

    Screenshots

    alt text

    Live Demo

    https://hungry-jennings-92ae10.netlify.app

    Usage & Details

    The goal of this webapp is to facilitate doing the groceries by keeping track of your grocery list as well as tracking the items in your shopping cart.

    • To add a new grocery item, fill the item’s name in the ‘grocery list’ top bar and press ‘+’
    • To add an item to your ‘shopping cart’, tap on the desired grocery list item
    • To add multiple items to your cart, tap the desired number of times on the desired grocery list item
    • To empty your cart, tap on the ’empty cart’ button in the cart’s top bar

    Issues/ Missing Features

    • As a user i’d like to be able to edit and remove items from grocery list and shopping cart
    • As a user i’d like the possibility to manually enter item quantities
    • As a user i’d like an item added to cart to automatically or manually be grayed out from my grocery list
    Visit original content creator repository https://github.com/NTielman/Grocery_helper
  • react-base-cisa

    Template de Desenvolvimento Web

    Este é um template para desenvolvimento web utilizando React, Vite, TypeScript, SWC (Speedy Web Compiler), ESLint, ESLint Stylistic, Zustand, AWS Sandbox (SDK, Lambda, API Gateway) e ++.

    Pré-requisitos

    Certifique-se de ter os seguintes itens instalados:

    • Node.js (versão 14 ou superior)
    • npm (versão 6 ou superior) ou yarn

    Como inicializar o projeto

    1. Clone o repositório

    git clone https://github.com/cisaitemm/react-base-cisa.git

    2. Instale as dependências

    npm install

    Scripts disponíveis

    Aqui estão os principais scripts definidos no package.json para gerenciar e construir o projeto:

    npm run dev

    • Inicializa o servidor de desenvolvimento usando o Vite.
    • Uso: Durante o desenvolvimento, para visualizar as alterações em tempo real.

    npm run build

    • Compila o projeto em TypeScript e gera os arquivos otimizados para produção.
    • Uso: Quando o projeto está pronto para ser implantado em um ambiente de produção.

    npm run preview

    • Executa uma prévia da versão de produção do projeto gerada pelo build.
    • Uso: Para verificar como o projeto será exibido em produção.

    npm run lint

    • Analisa o código em busca de problemas de formatação e boas práticas, usando o ESLint.
    • Uso: Antes de commits ou PRs, para garantir que o código está de acordo com os padrões definidos.

    npm run fix

    • Corrige automaticamente problemas detectados pelo ESLint sempre que possível.
    • Uso: Após rodar o npm run lint, para ajustar erros de formatação ou pequenos problemas. Ou para uso direto caso deseje realizar as correções de maneira direta.

    Estruturação do Projeto

    1. Estrutura de Pastas

    A estrutura do projeto é organizada para facilitar o desenvolvimento, manutenção e escalabilidade. Abaixo está uma proposta básica:

    src/
    ├── assets/  	                  # Arquivos estáticos como imagens, fontes, etc.
    ├── components/                  # Componentes reutilizáveis da interface
    │   ├── Button/
    │   │   ├── Button.tsx
    │   │   ├── Button.test.tsx
    │   │   └── Button.module.css
    ├── hooks/                       # Custom Hooks
    ├── pages/                       # Páginas do projeto (rotas principais)
    │   ├── Home/
    │   │   ├── index.tsx
    │   │   ├── Home.test.tsx
    │   │   └── Home.module.css
    │   ├── About/
    │       ├── index.tsx
    │       ├── About.test.tsx
    │       └── About.module.css
    ├── services/    	             # Configurações de APIs e AWS SDK
    ├── utils/           
    │   ├── state/ # Configuração do Zustand (gerenciamento de estado)
    │                   # Funções utilitárias e helpers
    ├── App.tsx                      # Arquivo principal do React (root onde serão aplicados Authenticators, contexts e routes)
    ├── main.tsx                     # Arquivo de inicialização com ReactDOM
    └── vite-env.d.ts                # Tipos específicos do Vite
    
    public/
    ├── index.html                   # Template principal
    ├── favicon.ico                  # Favicon do site
    
    .vscode/
    ├── extensions.json              # Extensões recomendadas para o desenvolvimento
    ├── settings.json                # Configurações padrões para a utilização correta do estlint e testes estáticos
    
    
    

    2. Tecnologias Utilizadas

    • React: Biblioteca popular para criar interfaces de usuário reutilizáveis e baseadas em componentes.
    • Vite: Build tool moderno e super-rápido para desenvolvimento web.
    • TypeScript: Adiciona tipagem estática ao JavaScript, garantindo código mais seguro e escalável.
    • SWC (Speedy Web Compiler): Compilador rápido para transpilar código TypeScript e JavaScript, melhorando o desempenho.
    • ESLint + Stylistic: Ferramentas para garantir a qualidade do código e consistência no estilo (Testes estáticos).
    • Vitest: Framework de testes (“Vite Native Test Runner”) responsável por organizar e executar o ambiente de testes.
    • React Testing Library: Testing library, Jest serve como o ambiente que executa e organiza os testes, enquanto a Testing Library ajuda a interagir com o DOM durante os testes.
    • Zustand: Biblioteca leve para gerenciamento de estado global, oferecendo simplicidade e flexibilidade.
    • AWS SDK: Para integração com serviços AWS como Lambda e API Gateway.
    • AWS Lambda e API Gateway: Estrutura para construir e expor APIs serverless de forma escalável.
    • Material UI: Biblioteca de componentes react que implementa o “Google’s Material Design”.

    3. Como Contribuir

    Para contribuir com este projeto:

    1. Faça um fork do repositório.
    2. Clone o projeto para sua máquina local:
      git clone https://github.com/seu-usuario/nome-repositorio.git
    3. Instale as dependências:
      npm install
    4. Crie uma branch para suas alterações:
      git checkout -b minha-feature
    5. Após as alterações, faça commit e push:

      git commit -m "Descrição da feature"
      git push origin minha-feature
    6. Abra um Pull Request detalhando as mudanças.

    4. To-Do List

    • Configuração inicial do projeto com Vite.
    • Integração do SWC para compilação.
    • Linter configurado com ESLint e Stylistic.
    • Configuração de rotas com react-router-dom.
    • implementar vitest
    • Configuração do Zustand para gerenciamento de estado.
    • Implementação de exemplo básico de AWS Lambda e API Gateway.
    • Testes unitários e integração com CI/CD.

    5. Deploy

    O deploy preferencial será realizado na AWS:

    • Pipeline Sugerido:
      1. Build do projeto com vite build.
      2. Upload dos arquivos estáticos no S3 para servir como frontend.
      3. Configuração de APIs utilizando AWS Lambda e API Gateway.
      4. Gerenciamento de permissões e autenticação via IAM ou Cognito.

    Comandos úteis:

    # Deploy de funções Lambda
    aws lambda update-function-code --function-name sua-funcao --zip-file fileb://funcao.zip
    
    # Configuração do API Gateway
    aws apigateway import-rest-api --body 'api-config.json'

    adicionado jest com ts-jest para funcionamento do jest em vite, excluindo a possibilidade não implementada de testes nos
    recursos:

    • import.meta:
      O Jest não compreende import.meta nativamente porque ele é baseado em CJS por padrão, enquanto import.meta é específico de ESM.

    • Transformações .vue
      O Jest precisa de transformadores específicos para entender e processar os arquivos .vue. Sem isso, ele trata os arquivos como texto bruto, gerando erros.

    Conclusão

    Esses recursos foram projetados para melhorar a experiência de desenvolvimento e a performance no Vite. Eles facilitam o trabalho com módulos dinâmicos e o desenvolvimento em frameworks como Vue.js. Se você está usando o Jest, precisará configurar transformadores adicionais (como o vite-jest) para que esses recursos sejam corretamente interpretados.

    eslint-plugin-jest

    Esse trecho da documentação explica como configurar o ESLint para evitar erros ao usar Jest nos arquivos de teste. O problema principal que ele aborda é que o ESLint, por padrão, não conhece os globais do Jest (como describe, it, expect, etc.), o que pode gerar erros como no-undef. A seguir, explicarei cada solução apresentada:

    Correção

    Para corrigir os dois erros acima, utilizaremos a mudança para o ViTest, que é o “tester runner” nativo do vite que tem uma performance muito melhor que a do jest e é mais bem integrável com o vite

    “This is Vitest, a next generation testing framework powered by Vite.”

    Visit original content creator repository
    https://github.com/AntonioMori/react-base-cisa

  • JustBar

    JustBar

    Download

    Grab via Gradle:

    implementation 'com.irozon.justbar:justbar:1.0.1'
    

    Usage

        <com.irozon.justbar.JustBar
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
            <com.irozon.justbar.BarItem
                android:layout_width="0dp"
                android:layout_height="0dp"
                app:icon="@drawable/ic_search"
                app:radius="25dp" />
            .
            .
            .
    
        </com.irozon.justbar.JustBar>

    BarItem – Child for JustBar:

    Optional attributes for BarItem

        <com.irozon.justbar.BarItem
                android:id="@+id/barItem"
                android:layout_width="0dp"
                android:layout_height="0dp"
                app:selectedColor="@color/colorSelected"
                app:unSelectedColor="@color/colorUnselected"
                app:selectedIconColor="@color/colorIconSelected"
                app:unSelectedIconColor="@color/colorIconUnselected"
                app:selected="false"
                app:icon="@drawable/ic_search"
                app:radius="25dp" />
    Attribute Desription
    selectedColor Selected state color for the BarItem
    unSelectedColor Unselected state color for the BarItem
    selectedIconColor Selected state color for the icon
    unSelectedIconColor Unselected state color for the icon
    selected Initial selected or unselected state for BarItem`
    icon Icon for BarItem
    radius Radius for the BarItem

    Action for BarItem:

        justBar.setOnBarItemClickListener(new OnBarItemClickListener() {
                   @Override
                   public void onBarItemClick(BarItem barItem, int position) {
                        // Your code here
                   }
               });

    Apps using JustBar

    If you are using JustBar in your app and would like to be listed here, please let me know by email or opening a new issue!

    Authors

    Contribution

    Pull requests are welcome! Feel free to browse through open issues to look for things that need work. If you have a feature request or bug, please open a new issue so i can track it.

    Acknowledgments

    Licence

    Copyright 2018 Irozon, Inc.
    
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
    
       http://www.apache.org/licenses/LICENSE-2.0
    
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
    
    Visit original content creator repository https://github.com/Hamadakram/JustBar
  • treafik_nxtcloud

    Nextcloud served on Traefik and Docker

    Preface

    Becoming interested in Docker and Microservices I decided to give it a shot and replace my classic Nginx/Nextcloud installation by something containerized.

    In my research I came across traefik. It acts not only as a HTTP reverse proxy, and as a load balancer. It can also dynamically detect running microservices and create routes to them. One of my personal favourites is also, that it can automatically install Let’s Encrypt certificates and route all traffic through https.

    As a starter I studied the excellent DigitalOcean tutorial on a traefic/WordPress setup:

    https://www.digitalocean.com/community/tutorials/how-to-use-traefik-as-a-reverse-proxy-for-docker-containers-on-ubuntu-16-04

    (Kudos at this point for DigitalOcean, for maintaining an excellent source of information with this blog)

    I departed from this tutorial, to finally come up with a traefic/Nextcloud setup, including the MySQL database and an adminer container.

    Prerequisites

    Installation

    First of all create a project folder and go inside.

    mkdir traefik
    cd traefik
    

    traefik configuration

    Before traefik is installed a passord hash needs to be generated, which will serve as the admin password for traefik.

    sudo apt-get install apache2-utils
    htpasswd -nb admin secure_password
    

    Replace secure_password with your password you want to use for traefik. Copy the output, which you will use inside your traefic configuration.

    Traefik is configured by a traefik.toml file
    . Create it and edit it with

    nano traefik.toml
    

    The contents are:

    defaultEntryPoints = ["http", "https"]
    [web]
    address = ":8080"
      [web.auth.basic]
      users = ["admin:passwordhash"]
    [entryPoints]
      [entryPoints.http]
      address = ":80"
        [entryPoints.http.redirect]
          entryPoint = "https"
      [entryPoints.https]
      address = ":443"
        [entryPoints.https.tls]
    [acme]
    email = "your@email.address"
    storage = "acme.json"
    entryPoint = "https"
    onHostRule = true
    onDemand = false

    Replace passwordhash with the output you copied in the previous step, and enter your email address, which will be used for the Let’s encrypt certificate generation.

    The ssl certificate information will be stored inside acme.json. Therefore we need to create it:

    touch acme.json
    chmod 600 acme.json
    

    docker-composer configuration

    Docker-composer will take care of starting up the docker containers in the right order with the right configuration.

    First a docker network named proxy is created which will serve internally for the docker containers:

    docker network create proxy

    Then docker-composer is configured using a docker-compose.yml file:

    nano docker-compose.yml
    

    Its contents are:

    version: "3"
    
    networks:
      proxy:
        external: true
      internal:
        external: false
    
    volumes:
      nextcloud:
      apps:
      data:
      config:
      mysqldir:
    
    services:
      traefik:
        image: traefik:1.4.4-alpine
        command: --docker
        container_name: traefik
        hostname: traefik
        labels:
          - traefik.frontend.rule=Host:monitor.mydomain.com
          - traefik.port=8080
        restart: always
        volumes:
          - /var/run/docker.sock:/var/run/docker.sock
          - /path/to/traefik/traefik.toml:/traefik.toml
          - /path/to/traefik/acme.json:/acme.json
        networks:
          - proxy
        ports:
          - 80:80
          - 443:443
    
      nextcloud:
        image: nextcloud
        environment:
          - MYSQL_DATABASE=nextcloud
          - MYSQL_USER=root
        links:
          - mysql
        restart: always
        volumes:
          - nextcloud:/var/www/html
          - apps:/var/www/html/custom_apps
          - data:/var/www/html/data
          - config:/var/www/html/config
        labels:
          - traefik.backend=nextcloud
          - traefik.frontend.rule=Host:nextcloud.mydomain.com
          - traefik.docker.network=proxy
          - traefik.port=80
        networks:
          - internal
          - proxy
        depends_on:
          - mysql
    
      mysql:
        image: mariadb:latest
        environment:
          MYSQL_ROOT_PASSWORD:
        restart: always
        volumes:
          - mysqldir:/var/lib/mysql
        networks:
          - internal
        labels:
          - traefik.enable=false
     
      adminer:
        image: adminer:4.3.1-standalone
        labels:
          - traefik.backend=adminer
          - traefik.frontend.rule=Host:db-admin.mydomain.com
          - traefik.docker.network=proxy
          - traefik.port=8080
        networks:
          - internal
          - proxy
        depends_on:
          - mysql
    

    Replace all three mydomain.com occurences with your domain, and adjust the /path/to/ in the traefik volumes.

    As you can see, traefik itself is coming as a docker container 🙂

    Unlike in the DigitalOcean tutorial, I included the traefik container inside the docker-composer configuration file. Like that the whole setup can comfortably be started with one single command.

    Next important step before starting, is to set the MYSQL_ROOT_PASSWORD variable with:

    export MYSQL_ROOT_PASSWORD=secure_database_password

    Of course with replacing secure_database_password with your secure password. This password will be used to login to MySQL using adminer.

    Starting

    Time to run it.

    docker-compose up -d

    This should install and start all the containers specified in the docker-compose.yml. If there are problems it can be useful to run just docker-compose up which will give output on the console.

    Now open up

    https://monitor.mydomain.com

    (This might take a while, since traefik is going to install the Let’s Encrypt certificates after the first start.)

    You should be asked to enter your traefik credentials. Don’t enter your hashed password, but your plain password here 😉

    You should see now the admin panel of traefik.

    Generate database

    Open adminer:

    https://db-admin.mydomain.com

    Here enter your root user credentials and use the mysql server. Inside create a nextcloud database.

    Setup Nextcloud

    Finally to setup Nextcloud open

    https://nextcloud.mydomain.com

    Choose MySQL as the database. In the database fields enter your root user credentials, and for the server use mysql:3306. If everything goes well, Nextcloud will generate your user and a MySQL user, and you should see soon the Nextcloud welcome screen.

    Stopping

    If you want to stop the system a

    docker-compose stop

    will do.

    Links

    Useful Links were

    Visit original content creator repository
    https://github.com/pagnotta/treafik_nxtcloud

  • valo-elo


    A website to check you ELO rating in Valorant

    This website is not affiliated with Riot Games, this was made by Abishake inspired from RumbleMike’s ValorStreamOverlay

    About

    Hi y’all, this website was built after being inspired from RumbleMike’s ValorStreamOverlay. I felt the installation process involved was too complex for a gamer and hence made this website. This website fetches your Rank Points from RIOT Servers(unofficially) and calculates your ELO and recent ELO changes. The site requires your username and password to fetch and display the required data (Would love to hear if you’ve found other alternatives). Check out RumbleMikes app if you’re a streamer: ValorStreamOverlay.

    Notes

    Neither username nor password are logged/stored in the server. The autofilling of username and password from second usage is stored locally in your browser. You can check the source code here (frontend) and here (backend). However, the backend is hosted in heroku (third-party hosting service). Hence, I highly recommend you to change your password to something that you’re not using in other services like email, social media etc., so that in the event of highly unlikely data leak, the other services do not get affected.

    If you still feel uncomfortable using the site, you can setup the site locally (frontend and backend), which is completely safe or use RumbleMike’s ValorStreamOverlay.

    How to use the site

    Just enter username, password and region and click submit -> Voila!

    Credits and tech used

    • valorant.js – A nice API wrapper for valorant with oauth; Used a customised version of the same to handle requests to RIOT servers.

    • ValorStreamOverlay – A wonderful stream overlay from RumbleMike; The RP and ELO calculations are based on the algorithm used in this repo.

    • Svelte – Used to build the frontend.

    • Nodejs and Express – Used to build the backend.

    Message For Riot

    Hey Riot, as explained above, this site just fetches data from the RIOT API and does not affect the game in any way. If this website is not something you approve of, please message me by creating an issue here.

    Visit original content creator repository https://github.com/shakeabi/valo-elo