DOD Recommends Private Gun Registration, Centralized Storage & Min Age-to-Buy On Bases

https://www.ammoland.com/wp-content/uploads/2019/11/USA-flag-wooden-door-locked-padlock-border-wall-immigration-iStock-fermate-641331942-500×294.jpg

USA flag wooden door locked padlock border wall immigration IMG iStock/fermate 641331942
iStock/fermate 641331942

USA –

“Finding ‘common ground’ with the thinking of evil men is a fool’s errand” ~ Herschel Smith

As we witness our Armed Forces recruitment efforts repeatedly falling drastically short of even minimum maintenance goals, DOD in its infinite wisdom, now cynically manufactures yet another significant reason for young Americans not to enlist!

Under the laughable pretext of “lethal-means reduction,” a new DOD report, “Preventing Suicide in the U.S. Military: Recommendations from the Suicide Prevention and Response Independent Review Committee” [embedded below], consists of a demand for active-duty troops to “register” all privately-owned guns, even those troopers who are in possession of valid, state-issued CCW permits.

This will, of course, immediately bring about a demand on the part of “woke” base commanders that all privately-owned guns (now “registered”) be subsequently removed from homes (on-base or off) of troopers, including officers and NCOs, and locked-up “for safe-keeping” within a base armory.

Of course, rightful owners will never see their guns again!

Another part of this impending new policy is that “twenty-five” is to become the new minimum age for any Soldier, Sailor, Airman, or Marine to privately own any kind of gun, again, even when the trooper already has a valid CCW permit!

So, we put into the hands of eighteen-year-olds automatic weapons that we don’t teach them to use (because they’re all too busy attending “transgender sensitivity” classes), and then prohibit them from obtaining, nor training with, their own weapons.

Even when troopers reach the age of twenty-five (in the unlikely event they’re still around), guns that they do privately own they can’t keep with them, as all guns must be locked-up and under the control of the base commander.

At this rate, few you recruits will be joining up. Fewer still will re-enlist.

It makes one wonder whom DOD is really working for!

“Where there is trust, no proof is necessary. Where there is none, no proof is possible.”

/John

Preventing Suicide in the U.S. Military: Recommendations from the Suicide Prevention and Response Independe..


About John Farnam & Defense Training International, Inc

As a defensive weapons and tactics instructor, John Farnam will urge you, based on your beliefs, to make up your mind about what you would do when faced with an imminent lethal threat. You should, of course, also decide what preparations you should make in advance if any. Defense Training International wants to ensure that its students fully understand the physical, legal, psychological, and societal consequences of their actions or in-actions.

It is our duty to make you aware of certain unpleasant physical realities intrinsic to Planet Earth. Mr. Farnam is happy to be your counselor and advisor. Visit: www.defense-training.com

John Farnam
John Farnam

AmmoLand Shooting Sports News

Let’s build a ChatGPT Plugin with Laravel

https://barreto.jp/assets/images/chatgpt-plugin-with-laravel/7-local-plugin-ip.png

Starting last week (May 12), OpenAI rolled out the plugins for ChatGPT plus users. This means that we can not only use the plugins from their store but also create our own plugins.

In this article, we will go through the process of creating a plugin for ChatGPT using Laravel.
The plugin will be a very simple web browser that will fetch the HTML content of a given URL, but this concept can be applied to any other use case.

Why a browser? Because it’s a simple example.

TL;DR: The code is available at github.com/juampi92/chatgpt-plugin-in-laravel.

Step 0 – Setup

Start by creating a new laravel project

composer create-project laravel/laravel chatgpt-browse-plugin
composer require guzzlehttp/guzzle

We will need the guzzlehttp/guzzle package to make HTTP requests using the Laravel HTTP Client.

Step 1 – Plugin configuration

ChatGPT requires us to have a plugin manifesto. This file is a JSON file that contains information about the plugin, such as the name, description, logo, etc.
We will need to locate it in the following URL localhost:8000/.well-known/ai-plugin.json.

For reasons that will be explained later, we will create the file inside resources/ instead of public.

mkdir resources/.well-known
touch resources/.well-known/ai-plugin.json
{
    "schema_version": "v1",
    "name_for_human": "My Local Web Browser Plugin",
    "name_for_model": "MyLocalWebBrowser",
    "description_for_human": "Plugin for browsing the web locally in the name of ChatGPT.",
    "description_for_model": "Plugin for browsing websites locally and getting their content.",
    "auth": {
        "type": "none"
    },
    "api": {
        "type": "openapi",
        "url": "http://localhost:8000/openapi.yaml",
        "is_user_authenticated": false
    },
    "logo_url": "http://localhost:8000/logo.png",
    "contact_email": "support@example.com",
    "legal_info_url": "http://www.example.com/legal"
}

Notes:

  • If you decide to use a different port, make sure to update the url fields (api.url and logo_url).
  • Also, if you decide to use a different name, make sure name_for_model doesn’t have any spaces.

To make the file available to the public, we need to do two things:

  1. Update the routes in routes/web.php:
Route::get('.well-known/ai-plugin.json', fn () =>
    File::get(resource_path('.well-known/ai-plugin.json')));
  1. Update config/cors.php to have 'paths' => ['*'],.

The reason why we can’t use the /public directory is because
the plugin will be hosted on a different domain and the browser
will block the request due to CORS.
If you intend to host the plugin on a server, you can use
the /public directory and configure apache/nginx to allow
CORS on static files.

Step 2 – Making it browse

Now we need to create the API that will be used by ChatGPT to browse the web.

Let’s create a new controller:

php artisan make:controller BrowseController

And the content of the controller should look something like this:

use Illuminate\Support\Facades\Http;

public function __invoke(Request $request): JsonResponse
{
    ['url' => $url] = $request->validate([
        'url' => 'required|url',
    ]);

    $response = Http::withHeaders([
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36',
        ])
            ->get($url);

    return new JsonResponse([
        'response' => $response->body(),
    ]);
}

Add the controller to routes/api.php:

Route::get('/browse', BrowseController::class);

Step 3 – API Documentation

In order for ChatGPT to understand how to use our plugin,
we need to generate an OpenAPI specification.
GPT will read the specification and decide when and how to use your endpoints,
so it’s important that the API is clear.

To generate the actual yaml file, we will use the zircote/swagger-php package.

composer require zircote/swagger-php --dev

Now we need to update the Controller using the OpenApi Annotations:

/**
 * @OA\Info(title="MyLocalWebBrowserAPI", version="0.1")
 */
class BrowseController extends Controller
{
    /**
     * @OA\Get(
     *     path="/api/browse",
     *     summary="Get HTML content of an URL",
     *     @OA\Parameter(
     *         name="url",
     *         in="query",
     *         description="URL to fetch the HTML from",
     *         required=true,
     *         @OA\Schema(
     *             type="string",
     *             example="http://example.com"
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="HTML content of the URL",
     *         @OA\JsonContent(
     *            type="object",
     *            required={"response"},
     *            @OA\Property(
     *              property="response",
     *              type="string",
     *              description="Raw HTML content of the URL"
     *           )
     *         )
     *     )
     * )
     */

To generate our OpenAPI specification, we run the following:

./vendor/bin/openapi app -o resources/openapi.yaml

And, for the same reasons mentioned before, add
the following route to routes/web.php:

Route::get('openapi.yaml', fn () =>
    File::get(resource_path('openapi.yaml')));

Step 4 – Serving

To run our plugin, simply call

php artisan serve --port=8000

Step 5 – Installing the plugin

Now that we have our plugin ready, we need to install it in ChatGPT.
When creating a new GPT-4 chat, you can click on the “Plugins” button and then go to the Plugin store.

GPT-4

From there, we go to the Plugin Store, and at the bottom, we click on Develop your own plugin.

Plugin Store

Here we are presented with a form to fill in the domain of our plugin. We input localhost:8000 (if you changed the port, make sure to use the correct one).

Enter Website Domain

If everything went well, you will see the following screen:

Found Plugin

New Plugin Selected

Step 6 – Using the plugin

Now that we have our plugin installed, we can use it in our chat.

ChatGPT will decide when to use your plugin depending on your description and OpenAPI specification,
so in the case of our browser plugin, simply giving a URL will do.

You might be wondering: why not just use WebPilot, the plugin that comes with ChatGPT?

The truth is that you can use WebPilot. The only difference is that
WebPilot uses a hosted server to browse. A server that can be rate-limited by websites, and you can’t customize.

This is an example using WebPilot:
WebPilot IP

And here is with our plugin:

WebPilot IP

Conclusion

In this simple article, we saw how to create a plugin for ChatGPT using Laravel.

If you would like to see the whole code, you can find it here: juampi92/chatgpt-plugin-in-laravel. I added a few more features, like transforming the content into markdown, so there is less content to send to ChatGPT, and so hitting the characters limit less often.

Laravel News Links

Bungie revives ‘Marathon’ as a multiplayer shooter

http://img.youtube.com/vi/6y-e2krA3uE/0.jpg

What do you think Bungie would do for its first non-Destiny game in over a decade? A return to the franchise that helped make it a gaming giant, of course. The developer has unveiledMarathon, a follow-up to the classic first-person shooter series for Macs. This isn’t a sequel or remake, mind you. Instead, it’s a multiplayer "extraction shooter" that has mercenary Runners exploring a lost colony.

While there’s no single-player component, game director Chris Barrett says this will still "feel" like a Bungie game between the mechanics and rich universe. Player actions will also influence the plot — you might find an artifact that unlocks an area for all players. There are persistent zones and seasons, although we wouldn’t expect a repeat of similar elements in Destiny.

Marathon is in development for PC, PS5 and Xbox Series X/S. While there isn’t much more to share at this point, Bungie says the next update will be "much closer to launch" and include gameplay. It’s safe to say there’s a lot riding on this title. It’s proof that Bungie isn’t content to iterate on Destiny forever, and will show what the company can do with a multiplayer-only experience. And for old-time fans, this is a chance to return to a beloved franchise 27 years later.

This article originally appeared on Engadget at https://www.engadget.com/bungie-revives-marathon-as-a-multiplayer-shooter-212630605.html?src=rssEngadget

Making $65 per Hour on Upwork with Pandas

https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPJcJGWP8WH4%2F0.jpg

4/5 – (1 vote)

Pandas, an open-source data analysis and manipulation library for Python, is a tool of choice for many professionals in data science. Its advanced features and capabilities enable users to manipulate, analyze, and visualize data efficiently.

????‍???? Recommended: 10 Minutes to Pandas (in 5 Minutes)

YouTube Video

In the above video “Making $65 per Hour on Upwork with Pandas” ????, the highlighted strategy is centered on mastering this versatile tool and effectively communicating its benefits to potential clients. A key fact to remember is that Pandas is highly valued in various industries, including finance, retail, healthcare, and technology, where data is abundant and insights are critical.

For a freelancer, proficiency in Pandas can command an hourly rate of $65 or more, even if it’s just a side business to add an additional and independent income stream.

But it’s not just about the tool; it’s about showcasing your ability to drive business value.

???? Recommended: Python Freelancer Course – How to Create a Thriving Coding Business Online

Highlighting case studies where you’ve used Pandas to extract meaningful insights or solve complex business problems can significantly boost your profile’s appeal.

As for project bidding, understanding the client‘s requirements and tailoring your proposal to highlight how your Pandas expertise can meet those needs is vital. Negotiation, too, plays a critical role in securing a lucrative rate.

Mastering Pandas and marketing this skill effectively can unlock high-paying opportunities on platforms like Upwork, as demonstrated by the impressive $65 per hour rate (for a freelancer with very little practical experience). This reinforces the importance of specialized skills in enhancing your freelancing career.

???? Recommended: What’s the Average Python Developer Salary in the US? Six Figures!

Be on the Right Side of Change

Laravel 10 Eloquent Mutators and Accessors

https://coderadvise.com/wp-content/uploads/2023/05/Laravel-10-Eloquent-Mutators-and-Accessors.jpg

Laravel 10 Eloquent Mutators and Accessors

The mutator modifies the value before inserting it into the database, while the accessor modifies the value after fetching it from the database. Mutator and accessor can be defined in the same method.

Let’s suppose, the customer’s name should be stored in lowercase and displayed in Pascal case (with space) even if the customer puts a name with capitalized letters. To do that, we will need to use a mutator and accessor in the Model. The mutator will be converting the customer name into lowercase before inserting it in the database and the accessor will be converting it into Pascal case before displaying it.

You can define a mutator and accessor in the Model file in the app/Models directory. We added two additional columns first_name and last_name into the users table through migration. By default, Laravel creates a name column in the users table.

Mutator

The Mutator allows you to modify the value before inserting it into the database. For example, if you want, the first and last should always be stored in lowercase in the database then mutator is the best way to do it.

Define Mutator:

To define a mutator it is necessary to create a method using the column’s name written in the camel case. Let’s take an example: if the column name is first_name then the method name should be firstName().

In the earlier versions of Laravel, it is required to add a set at the beginning of the method and an attribute keyword at the end of the method. But in Laravel versions 9 and 10 it is no longer required.

Let’s create a mutator for the first_name column in the User model class from app/Models directory.

Before adding the above mutator method in the model class make sure the Attribute class is imported. You can import the attribute class through the below namespace

use Illuminate\Database\Eloquent\Casts\Attribute;

protected function firstName(): Attribute
{
    return Attribute::make(
        set: fn (string $value) => strtolower($value),
    );
}

The above mutator method will be converting the value of the first_name column into lowercase before inserting it into the database.

In this method, we used the make() method of the Attribute class that takes two optional parameters get and set. We passed a callback function to the set parameter that takes a string and converts it into lowercase through PHP built-in function strtolower().

Now look at the below profile update form where the first name is in capitalized letters that should be inserted in the lowercase through the mutator.

Let’s check the inserted row in the database.

In the above screenshot of the users table the first_name value is inserted in lowercase.

Accessor

The accessor allows you to modify the value before being accessed. To define an accessor, similar to a mutator, it is essential to create a method using the column’s name in the camelcase.

Define Accessor:

Let’s create an accessor for the first_name column that should capitalize the first letter of each word.

protected function firstName(): Attribute
{
    return Attribute::make(
        get: fn (string $value) => ucwords($value),
    );
}

In the above accessor method, we used the make() method from the attribute class in which we passed a callback function to the get parameter. The callback function takes the value and converts capitalize the first letter of each word through the PHP built-in function ucwords().

To check if the accessor is working, we can print the first_name column’s value in the controller.

echo $request->user()->first_name;
// Output: Emily

As you can see the first_name value “Emily” is stored in the lowercase through the mutator, but in the controller accessor capitalized the first letter.

Accessor and mutator can be defined in the same method. Look at the below method in which we defined the accessor and mutator together.

protected function firstName(): Attribute
{
    return Attribute::make(
        get: fn (string $value) => ucwords($value),
        set: fn (string $value) => strtolower($value),
    );
}

Related Posts

Laravel News Links

Family hit with $3,100 App Store bill after kid goes on Roblox spending spree

https://photos5.appleinsider.com/gallery/54528-110174-53631-107774-Roblox-xl-xl.jpg

Roblox in the App Store


A 10-year-old child spent over $3000 on Roblox via the family iPad, charges applied after the child changed the account password.

Stories of excessive spending in a game by a child regularly surface, with parents complaining about the seemingly unjust charges. In the latest iteration, a 10-year-old managed to run up a bill of more than 2,500 pounds ($3,115) on the game Roblox, without her mother’s knowledge.

Georgina Munday of Dyserth, Denbighshire, UK, had allowed her autistic daughter to play on an iPad for long periods, due to struggling in school, reports BBC News. Soon after, she started to see the transactions, and initially believed that the account had been hacked.

“We’d just seen hundreds of transactions, these payment confirmations, so then the panic set in – oh my gosh, whose card is this on?” the mother told the report.

Munday spent a week going between Tesco Bank and Apple to try and get a refund, but both sides refused.

“I rang up Tesco Bank and they said, because it was my daughter, they couldn’t do anything about it,” Minday said. “So I tried Apple again – they just read me their terms and conditions.”

After contacting the BBC, Tesco Bank said she would receive a refund. The bank said there was a “further review” of the case that prompted the refund, and added an additional payment as a gesture of goodwill on top of an apology.

In responding to the story, Apple reiterated previous advice that accounts can have alerts set up so parents could be warned before a purchase could be made. Also, they said that parents should not disclose passwords, avoid adding their child to Face ID and Touch ID, enable Ask to Buy, and to use Screen Time.

Roblox said it “has a robust policy for processing refund requests where there may have been unauthorized payments from a person’s account.” Parents also have access to parental controls that can limit spending and to issue spend notifications for “increased visibility.

Munday is not keen on allowing her daughter to play the game in future, but admitted while she knew what she was doing in changing the password, “I don’t think she understood the enormity of it.” The mother asked parents to “be vigilant” and to take note of what children do on their devices.

AppleInsider News

Use This ‘Tears of the Kingdom’ Inventory Glitch for Unlimited Items

https://i.kinja-img.com/gawker-media/image/upload/c_fill,f_auto,fl_progressive,g_center,h_675,pg_1,q_80,w_1200/38be1fcd35f47d0fde3d749153567df9.jpg

The Legend of Zelda: Tears of the Kingdom features a lot of items. It carries over staples from Breath of the Wild like food and monster parts, and adds plenty of new options from bomb flowers to Zonai devices. You really can’t have enough items in this game, which makes this item duplication glitch so useful.

The glitch, as outlined by IGN, isn’t necessarily hard to pull off, but it does require precision. My advice is to read through the instructions first, then give it a shot. If you don’t get it right away, be patient and give it another go.

How to glitch your way to unlimited items in Tears of the Kingdom

To start, make sure you have a bow equipped. Draw your arrow by tapping R2, then attach the item you’re looking to duplicate by holding the up button. Personally, I’m not going to choose any brightbloom seeds because I have so many, but I could use more bomb flowers, so I went with that.

With your item equipped, wait a beat, press +, then head over to the Bows and Arrows section of the menu. Select the bow you have equipped, then Drop it. Without leaving the menu, equip a new bow, then press + two times as quickly as possible. You want to make it back to the menu without the bow falling to the ground. Now, drop the newly equipped bow, and finally exit the menu for good.

If done correctly, the two bows should be stacked on top of each other. Pick them both up, then check your items. You should have one extra item than you started with.

IGN details two other item duplication efforts—one for duplicating equipment in your inventory and another for copying equipment you haven’t come across before. But these methods are more complicated, and actually risk losing items in the process. For safe item duplication, stick to the first glitch.

There were fears that this glitch would be patched in the latest update, version 1.1.1., but that doesn’t appear to be the case. Even after installing the update, the game still lets you copy your items, which means Nintendo is either unaware of the glitch or feels it low priority enough not to fix yet. Hopefully they never fix it and allows the fun glitch to be among the very few bugs in a remarkably polished game.

Lifehacker

How to Build a Microservice in Python

https://static1.makeuseofimages.com/wordpress/wp-content/uploads/2023/01/add-video-player-in-react-js.jpg

Software design is an essential phase in software development. The design approach can affect the entire project and how you handle different requirements.

Developers have often used a monolithic architecture, bundling up all the software components into a single module. However, this approach can prove inefficient, particularly for larger applications.

MAKEUSEOF VIDEO OF THE DAYSCROLL TO CONTINUE WITH CONTENT

Microservices aim to address these limitations. A microservice is a small, modular application that performs specific functions. Unlike monolithic applications, microservices allow for independent deployment and scaling. As a result, they are more flexible and easier to maintain.

The Microservice Architecture

The microservice architecture is a software design approach that breaks down a large application into independent services, with each service designed to address a specific business requirement.

These services run on dedicated resources, including separate database instances and computing power. Unlike monolithic systems, microservice applications are loosely coupled allowing for greater flexibility.

In a distributed system, server nodes deploy and execute microservice applications as separate processes—communicating with each other using communication protocols such as HTTP or via message brokers like RabbitMQ.

Essentially, this architectural approach enables the services to maintain their independence from one another while effectively operating within the software system.

In this tutorial, we’ll guide you through implementing a simple user microservice that manages user data using Flask and PostgreSQL

Set Up a PostgreSQL Database

To get started, install PostgreSQL. If you don’t have PostgreSQL installed, you can find out how to install PostgreSQL on Windows or how to install PostgreSQL on macOS.

Alternatively, you can configure a remote PostgreSQL database instance.

This guide will use Render’s free tier to set up a PostgreSQL database. Follow these to spin up a PostgreSQL database instance on Render:

  1. Head over to Render’s website, sign up for an account, and log in to your dashboard page.
  2. On your dashboard page, from the list of services displayed, select the PostgreSQL service.
  3. On the database settings page, fill in the required details and make sure to select the free tier, and finally click Create database.

Create a Flask Microservice

  1. In your terminal, make a new directory and change into it:
     mkdir flask-microservice
    cd flask-microservice
  2. Next, install virtualenv, to create an isolated virtual development environment.
     pip install virtualenv 
  3. Create a virtual environment in your project:
     virtualenv venv 
  4. Finally, activate the virtual environment.
     # Windows: 
    .\venv\Scripts\activate
    # Unix or MacOS:
    source venv/bin/activate

Install the Required Packages

  1. Create a new requirements.txt file in the root directory and add these packages:
     flask
    psycopg2-binary
    sqlalchemy
  2. Next, install the packages.
     pip install -r requirements.txt 

Create a Flask Server

In the root directory, create a new file: service.py, and the following code:

  1. Make the following imports:
     from flask import Flask, request, jsonify
    from sqlalchemy import create_engine, Column, Integer, String
    from sqlalchemy.orm import sessionmaker
    from sqlalchemy.ext.declarative import declarative_base
    import psycopg2
  2. Create the Flask instance and configure the database connection.
     app = Flask(__name__)

    engine = create_engine("postgresql+psycopg2://flask_service_fe0v_user:4785MhjfkdjfhjfjyUx67O2Nuzjchb2MQIP@dpg-chffjfjdkgfk54d6mb7860-a.oregon-postgres.render.com/flask_service_fe0v")

    Copy the external database URL on Render’s database settings page. We’ll use the SQLAlchemy create_engine method and Psycopg2 to configure the database connection. Make sure to update and replace the database URL in the above code with the URL of your own PostgreSQL instance that matches the format specified above. If the URL format is incorrect, the code will throw an error.

  3. Create an SQLAlchemy model for the database.
     Base = declarative_base()
    class User(Base):
        __tablename__ = 'users'
        id = Column(Integer, primary_key=True)
        name = Column(String(50))
    Base.metadata.create_all(engine)
    print("Table 'users' created successfully.")
    Session = sessionmaker(engine)

    The code defines a data model for the users’ table. After defining the model, it creates the table using the SQLAlchemy create_all method which takes the database connection engine object as a parameter. Finally, it creates an instance of the session maker using the same engine object to enable interactions with the database.

  4. Lastly, define the API routes for the microservice.
     @app.route("/api/user", methods=["POST"])
    def create_user():
        data = request.get_json()
        name = data["name"]
        try:
            session = Session()
            new_user = User(name=name)
            session.add(new_user)
            session.commit()
            return {"id": new_user.id, "name": new_user.name, "message": f"User {name} created."}, 201
        except Exception as e:
            print(f"The error '{e}' occurred.")
            return {"error": "An error occurred while creating the user."}, 500
    @app.route("/api/user", methods=["GET"])
    def get_all_users():
        try:
            session = Session()
            users = session.query(User).all()
            if users:
                result = []
                for user in users:
                    result.append({"id": user.id, "name": user.name})
                return jsonify(result)
            else:
                return jsonify({"error": f"Users not found."}), 404
        except Exception as e:
            print(f"The error '{e}' occurred.")
            return {"error": "An error occurred while getting all users."}, 500
    if __name__ == "__main__":
        app.run(debug=True, host="0.0.0.0")

Test the Microservice

The above code demonstrates a simple user data microservice that adds and fetches data from a PostgreSQL database. Ideally, microservices mirror the REST API architecture since it allows for a flexible approach to building web services—this architecture fits well with the design pattern of microservices.

However, it’s important to note that microservices can use other types of design approaches and communication protocols as well, depending on the specific needs of the system.

To test the service, spin up the development server and head over to Postman to make HTTP requests to the defined endpoints.

 flask --app service run 

In Postman, make a POST request to add user data.

Containerizing Microservices With Docker

Docker bundles applications and their dependencies in containers. This approach streamlines the development, deployment, and management of microservices in a production environment since each service can operate independently and communicate with other services using the configured communication protocol.

Before you get started, you need to first install Docker by following the steps on the Docker website. Then, build a Docker image from a Dockerfile that contains the necessary instructions for setting up the required dependencies to run the application in a container.

  1. Create a Dockerfile in your project folder’s root directory and add these instructions:
     FROM python:3.9-alpine
    WORKDIR /app
    COPY requirements.txt ./
    RUN pip install -r requirements.txt
    COPY . .
    EXPOSE 5000
    CMD ["python", "./service.py"]
  2. Run, the command below to build the Docker image.
      docker build -t flask-microservice . 
  3. Finally, run the Docker container.
     docker run -p 5000:5000 flask-microservice 

This will start a Docker container running the Flask microservice and expose port 5000 on the container to port 8000 on the host machine, allowing you to make HTTP requests from your web browser or Postman using the URL http://localhost:5000.

Adopting the Microservice Architecture

Microservices architecture has become a popular approach for developing scalable and robust software applications. By dividing the application into small, independently deployable services, microservices architecture makes it easier to maintain and scale the system.

While this architecture has potential benefits, it’s not suitable not for all use cases. In any case, the specific business requirements of the project should primarily influence the adopted design approach.

MakeUseOf

Concealed Carriers Guide to Using .22 LR for Self-Defense

https://www.pewpewtactical.com/wp-content/uploads/2020/08/10.-Popular-.22LR-Ammo-1024×699.jpg

Let’s bring up a rather controversial subject in the concealed carry community. Who would choose to carry a .22 LR for self-defense?

Popular .22LR Ammo
Popular .22LR Ammo

I occasionally carry a .22 LR handgun for self-defense. My typical concealed carry handgun is a Sig Sauer P365, and sometimes a P365 with an XL slide and red dot.

The P365 is already a fairly small gun, but there are times when even it’s too big.

P365XL Stronghand Grip
P365XL…it works, but it’s a little big.

That’s when I turn to a super small, easily concealed weapon…a tiny .22 LR goes a long way and allows for consistent concealed carry.

So let’s dive into .22 LR, talk about what it can do for you concealment-wise, and run you through the best ways to carry rimfire!

Table of Contents

Loading…

Why .22 LR?

I’ve covered my reasons and bet others would target the same thing. Sometimes a certain style of dress, especially formal wear for women, makes concealment difficult, and other times to avoid detection.

This might leave you asking, why not carry a micro .380 ACP?

Womens CCW Dress
Sig Sauer P238 carried in a thigh holster under a dress.

It’s true that .380 ACP is ballistically superior to .22 LR, and my favorite .22 LR is the LCP II, which is the same size as the .380 ACP version. I prefer the .22 LR because I can’t shoot the .380 ACP very well.

Those guns are very snappy, with a fair bit of recoil. It’s true that it works well, but I hate shooting it and never shot it very well.

Sinterfire .380 ACP 75 grain HP Frangibles and a Ruger LCP II. If you like .380 ACP you really should check out Sinterfire’s frangibles
.380 ACP might not work for everyone…

The LCP in .380 ACP is often described as a belly pistol, and I tend to agree. With a micro-sized .22 LR, I outshoot any micro .380 and can do so at ranges between 10 yards.

Micro .22 LR pistols lack recoil and tend to have a decent capacity. The LCP II holds 11 rounds total, and that’s a nice change.

.22LR Round
.22 LR Round

Even revolvers can often hold eight rounds of .22 LR. A higher capacity and lower recoil make these little guns a bit more competent.

Plus, the ammo is so much cheaper. It’s cheaper than .380 ACP, and you can train for very little dinero.

.22LR Ammo In Stock

Deal
Grain
Cost Per Round
Notes
40gr
$0.06
40gr
$0.09
40gr
$0.08
40gr
$0.09

Getting out to the range once a week isn’t prohibitively expensive. Even without much practice, I already shoot the LCP 2 in 22 LR better than I shoot the .380 ACP version, and I’ll get better with more practice.

This is especially true in compromising situations where I might use a single hand. With a .22 LR, this is fairly easy.

Downsides of .22 LR for CCW

The subject of .22 LR for concealed carry is already a bit controversial, and the controversy comes from the downsides tied to the .22 LR.

There are quite a few you need to recognize before strapping on the old rimfire round.

22LR Rat Shot
.22 LR

Rimfire rounds have reliability issues and are less reliable than centerfire rounds. With that said, their quality has improved, especially with premium rounds from companies like CCI and Federal.

Penetration and expansion are not the highest with a .22 LR, especially from a short barrel.

Less penetration means some rounds may have trouble reaching the FBI standard of 12 inches of penetration to help guarantee proper depth to stop a threat.

PPTGel2
The FBI’s standard for penetration is 12 inches

Semi-auto .22 LRs can also be a little picky. They tend to prefer certain rounds and certain velocities to function properly.

You will have to properly vet your carry ammo and ensure your gun can chew through it before you trust it.

Picking the Right Ammo

If you carry a .22 LR for self-defense, then you need to educate yourself on ammo.

A lot of the standard ammunition knowledge goes out the window. You usually wanted a jacketed hollow point, which isn’t the case now.

FMJ vs Hollowpoints (9mm and .45 ACP)
FMJ vs Hollowpoints (9mm and .45 ACP)

A good hollow point .22 LR is great for hunting, but the expansion factor tends to slow the round down and prevent adequate penetration. Expansion is one of those things that you sacrifice with .22 LR for defensive purposes.

When a 9mm round grows to .60 inches in gel is great, but we can’t get that with .22 LR. You are going to need to focus on penetration. Small holes can do big damage if you put them in important places.

For practice, you can use really any ammo your gun operates with, but for defensive carry, it’s smart to be picky. This is especially true because our focus is on guns with fairly short barrels.

SW22 with Federal .22LR
All rounds are not created equal

Luckily a few rounds have been shown to function well from short barrels and do a good job reaching the FBI minimum standards.

One round that stands out exceptionally well for short-barreled defensive weapons is the CCI Velocitor.

This semi-hollow point round is a hefty 40-grain round with a reported velocity of 1,435 feet per second. It does a great job of penetrating from a short-barreled gun.

9

at Kygunco

Prices accurate at time of writing

Prices accurate at time of writing

Available Coupons

The Federal Personal Defense Punch round is another good round that comes in at a close second. It’s a newer round designed from the ground up for self-defense.

It is a decent penetrator and is nickel plated.

10

at Federal

Prices accurate at time of writing

Prices accurate at time of writing

Available Coupons

Nickel plating helps protect the round from corrosion, which sweat can cause. Your small gun is more likely carried in a deep, concealed manner, often exposing it to more sweat.

These aren’t the only rounds on the market, but they are the two I have experience with and I’d trust. Do your own testing, research, and review before deciding.

Choosing a Defensive .22 LR Pistol

When choosing a defensive firearm in .22 LR, we have to go back to the revolver versus semi-automatic. In the realm of .22 LRs, they seem to have their strengths and weaknesses.

Small automatics tend to be more size efficient. They may not be bigger than a small revolver, but they tend to pack more barrel length for their size.

FN502 Shooting
FN 502

The Ruger LCP features a 2.75-inch barrel, and the LCR packs a 1.87-inch barrel.

A little extra barrel goes a long way with increasing velocity, aiding penetration.

Revolvers have a serious advantage in .22 LR in terms of reliability issues. A rimfire round isn’t as reliable as a centerfire, and if it fails to fire, fixing the issue isn’t as hard with a revolver.

Rimfire vs Centerfire Primer Strike
Rimfire vs Centerfire Primer Strike

If you pull the trigger and it goes click, just pull the trigger again. Also, revolvers aren’t picky about the round’s velocity to ensure the weapon cycles.

Purchasing a .22 LR defensive pistol is like purchasing any other. You need to find a reliable handgun that’s made to last, accurate, and easy to shoot. There are tons of small .22 LR handguns out there, but a good number of them suck.

Ruger Mark IV

Avoid guns from companies like Jennings or Jimenez. They tend to be poorly made, albeit very cheap, and often very small.

Ruger LCP II

The LCP 2 in .22 LR is one of my favorite defensive .22 LR pistols. It’s a one-for-one clone of the .380 ACP version of the gun but is chambered in .22 LR. The small little gun packs 11 rounds of .22 LR and is a very nice shooter.

Ruger LCP and LCP II
Ruger LCP and LCP II

The Literack design makes utilizing the weapon easy for shooters with hand strength issues. Shooters get an ultra-small, thin firearm that’s easy to carry IWB, pocket, ankle, or wherever.

Best Semi-Auto .22 LR
314

at Guns.com

Prices accurate at time of writing

Prices accurate at time of writing

Available Coupons

In my experience, this little gun is super fun to shoot and fairly accurate with decent sights. The gun has barely any recoil and is reliable with most .22 LR I’ve used.

One of the few things I don’t like is the silly safety. Ruger should ditch it as they did on the standard LCP II.

Other than that, the LCP II in .22 LR might be the most modern and one of the most affordable .22 LR Defensive pistols.

Ruger LCR

Another option from Ruger is the LCR. This wheelgun option gives you eight rounds of .22 LR in a standard snub nose package. It’s lightweight with a partial polymer frame and weighs 14.9 ounces.

Ruger LCR 9mm
Ruger LCR (9mm version, but you get the idea)

While the snub nose is a bit larger than the LCP II, the LCR does pocket carry very well. It’s light, and the curves and design of a revolver make it a natural choice for pocket carry. The popularity of the LCR in bigger calibers has created a ton of holsters for the gun, making it easy to carry.

Ruger’s LCR is a very reliable and modern option. It tends to strike reliably, but if it doesn’t, it’s not tough to remedy the situation. The LCR is one of the few .22 LR revolvers made for carry purposes.

Best .22 LR Pocket Revolver
499

at Guns.com

Prices accurate at time of writing

Prices accurate at time of writing

Available Coupons

My one complaint is the trigger.

The LCR trigger is famously awesome, but the .22 LR version lacks. It’s noticeably heavier and likely a means to ensure consistent rimfire engagement and reliability.

While it’s not as good as a standard LR trigger, it is still not bad.

Beretta 21A

Finally, let’s go back in time a little bit. The Beretta 21A is a super small little gun that’s also known as the Bobcat.

This little .22 LR came to be in 1984, but it is still a fairly viable gun. It is super small, smaller than the LCP 2.

Beretta 21A

It only holds seven rounds, but the small size can make up for that. This gun uses a tip-up barrel system, allowing the user to load the chamber without manipulating the slide.

The gun also uses a DA/SA design, so you can attempt to fire the cartridge in the chamber if it fails to fire.

419

at Guns.com

Prices accurate at time of writing

Prices accurate at time of writing

Available Coupons

The gun is all metal, which does make it a few ounces heavier than the LCP II. There is a suppressor-ready model if you want to move beyond concealed carry and have fun.

The biggest downside will be the puny little sights. If you can deal with that, you have one of the coolest guns in your pocket.

Deep Concealment Carry

The main strength of these little rimfires is their ability to be concealed in nearly any style of dress and situation.

With that in mind, we need to examine some functional holsters for those tasks.

Pocket Carry

This style of carry is one of the easier ways to carry a handgun concealed, and it’s often fairly convenient in any style of dress.

With that in mind, the Desantis Nemesis is one of the best pocket holsters.

21

at Amazon

Prices accurate at time of writing

Prices accurate at time of writing

Available Coupons

This pocket piece is affordable and made in various sizes to accommodate the Beretta 21A and LCP II, among many more.

This textured holster keeps things locked in place when you draw and ensures the holsters remain locked in place when your weapon is drawn.

IWB Carry

Inside the Waistband is a standard means of concealed carry. This hides the weapon inside of pants and allows nothing more than a t-shirt to conceal it.

Womens Concealed Carry IWB
IWB

For these little .22 LR pistols, I’d suggest two holsters, one for semi-automatics and one for revolvers.

The Desantis Slim Tuck is a solid, affordable hr for most common semi-auto ls. It’s a minimalist holster that conceals easily and offers adjustable cant and height on top of great comfort and concealment.

30

at Amazon

Prices accurate at time of writing

Prices accurate at time of writing

Available Coupons

It’s also tuckable, allowing you to dress more formally for events.

For snub nose .22 LR revolvers, the PHLster City Special likely has you covered.

This modern polymer holster brings PHLster’s expertise front and center. This creates an easily concealable revolver in a modern, modular, and adjustable holster.

79

at Brownells

Prices accurate at time of writing

Prices accurate at time of writing

Available Coupons

It’ll make your LCR disappear without issue.

.22 LR Drills: Practice Makes Perfect

If you’re packing a .22 LR for concealed carry, you better train with it. Here are a few good drills you can do to maximize your time at the range.

10-10-10 Drill

The classic 10-10-10 is a great yardstick for concealed carry competency. It’s shot with a B8, and traditionally the shooter shoots 10 rounds, in 10 seconds, at 10 yards. Every shot should be in the black of the B8.

Low Round Count Drill B8 Target
B8 Target

Since a lot of .22 LR handguns don’t hold 10 rounds, you might modify it to the 10-10-7 or 10-10-8 and fire however many rounds you can.

Super Snubby Test

If you are rocking the snub nose, try Hard Wired Tactical Super Snubby Test. It only requires 15 rounds. Grab a shot timer and a B8 as well.

Stage one begins at 10 yards. Start from the low ready and fire five rounds with both hands in eight seconds.

Pocket Pro II Shot Timer
You’ll need one of these. Don’t have one? See our recommendations for best shot timers.

Stage two moves you to the 5-yard line. Start in the low ready and fire five rounds in five seconds.

At stage three, you are at 3 yards. You will only use your strong hand and start in the low ready. At the beep, fire five rounds in 3.5 seconds.

Aim to land all of your shots in the black.

Draw and Failure to Stop

Being able to quickly draw and engage a threat with effective fire is crucial to concealed carry.

When carrying a small gun in a deep concealment design, you should get competent at drawing your pistol. If you use a tucked-in shirt, practice with a tucked-in shirt. If you use a pocket holster, then practice with that pocket holster.

Ferro Bison Belt Concealed Carry
Gotta practice that draw

For this drill, you’ll need a man-sized target. At the beep, you’ll draw from your concealment drill and fire a failure drill.

A failure drill is two shots to the torso and one to the head. Start at three yards and aim to complete the drill in at least five seconds as you get faster, lower the par time, and increase the distance.

Failure to Fire Drills

To help counteract any issues with reliability, get some practice in with clearing malfunctions.

Armed & Ready, Malfunctions
Malfunctions happen

Get some snap caps, set up some malfunctions, and practice with the old tap rack bang and clearing complicated malfunctions.

Final Thoughts

A .22 LR handgun can be a proper defensive tool. It has some inherent weaknesses, and you should do what’s necessary to mitigate them when possible.

Smith & Wesson SW22 Victory Resized
Smith & Wesson SW22 Victory

If you pick a good gun, quality ammo, a good holster, and practice, then you’ll be ready to roll.

Would you carry a .22 LR for self-defense? Let us know in the comments below. For more rimfire, check out the Best .22 LR Pistols/Handguns!

The post Concealed Carriers Guide to Using .22 LR for Self-Defense appeared first on Pew Pew Tactical.

Pew Pew Tactical

Python Get All TXT Files in a Folder

https://s.w.org/images/core/emoji/14.0.0/72×72/1f91d.png

5/5 – (1 vote)

Imagine you have a project that requires you to process tons of text files, and these files are scattered throughout your folder hierarchy. By the time you finish reading this article, you’ll be equipped with the knowledge to efficiently fetch all the .txt files in any folder using Python.

Method 1: The Os Module

The os module can be used to interact effectively with the file system. The method os.listdir() lists all files and directories in your target folder. You’ll use this method along with a for loop and the endswith() method to filter .txt files specifically.

Here’s the code snippet:

import os

directory = './your_folder/'
txt_files = []

for file in os.listdir(directory):
    if file.endswith('.txt'):
        txt_files.append(file)

print(txt_files)

This code imports the os module, sets the target directory, and initializes an empty list.

The for loop iterates through all the files and checks for the .txt extension using the endswith() method. Matching files are added to the list, which is printed at the end.

Method 2: The Glob Module (My Fav ????)

Another solution involves using the glob module, which allows you to find all the file paths in a directory that match a specific pattern. You can use the glob.glob() function to list all .txt files.

Here’s how you can do it:

import glob

directory = './your_folder/'
txt_files = glob.glob(f'{directory}*.txt')

print(txt_files)

This method imports the glob module, sets the target directory, and retrieves the list of text files using the glob.glob() function that filters file paths based on the given pattern (*.txt). The list of .txt files is then printed.

Method 3: os.listdir() and List Comprehension

The os.listdir() is a simple method to use when listing all files in a directory. You can iterate over all files obtain with this method using a simple list comprehension statement such as [file for file in os.listdir(dir_path) if file.endswith(".txt")].

See this example:

import os

dir_path = "your_directory_path"
all_files = os.listdir(dir_path)
txt_files = [file for file in all_files if file.endswith(".txt")]

print(txt_files)

This code will list all the text files in the specified directory using os.listdir function.????

Method 4: Using os.scandir()

The os.scandir() method can provide more information about each file. Extracting the files from this more information-rich representation is a bit less concise but works just fine in this list comprehension [entry.name for entry in os.scandir(dir_path) if entry.name.endswith(".txt") and entry.is_file()].

For instance, use the following code:

import os

dir_path = "your_directory_path"
txt_files = [entry.name for entry in os.scandir(dir_path) if entry.name.endswith(".txt") and entry.is_file()]

print(txt_files)

Method 5: Using glob.glob()

For a more concise solution, try the glob.glob() function from the glob library. Here’s the code snippet to list text files:

import glob

dir_path = "your_directory_path"
txt_files = glob.glob(f"{dir_path}/*.txt")

print(txt_files)

The glob.glob() function returns a list of all text files with the specified pattern (in this case, *.txt).✨

Method 6: Using pathlib.Path.iterdir()

Finally, the pathlib.Path.iterdir method offers another way to list text files in a directory. To use this method, simply import the pathlib library and write the following code:

from pathlib import Path

dir_path = Path("your_directory_path")
txt_files = [file.name for file in dir_path.iterdir() if file.is_file() and file.name.endswith(".txt")]

print(txt_files)

In this code, pathlib.Path.iterdir is iterator over the files in the directory and, when combined with list comprehensions, can efficiently list all text files.????

Iterating Through Directories

In this section, you’ll learn how to iterate through directories using Python and get all the .txt files in a folder.

We’ll cover three methods: using the for loop method, working with the os.walk() function, and recursively traversing directories with a custom recursive function. ????

Using the For Loop Method

To get started, we’ll use the os.listdir() function with a for loop. This approach allows you to iterate over all files in a directory and filter by their extension.

This code lists all the .txt files in the specified directory using a simple for loop. ????

import os

directory = 'your_directory_path'
for filename in os.listdir(directory):
    if filename.endswith('.txt'):
        print(os.path.join(directory, filename))

Working with the os.walk() Function

The os.walk() function is another powerful tool for iterating over files in directories. It enables you to traverse a directory tree and retrieve all files with a specific extension:

import os

root_dir = 'your_directory_path'
for root, dirs, files in os.walk(root_dir):
    for file in files:
        if file.endswith('.txt'):
            print(os.path.join(root, file))

This code explores the entire directory tree, including subdirectories, and prints out the full paths of .txt files. ????

In fact, we have written a detailed article with a video on the function, feel free to check it out! ????

YouTube Video

????‍???? Recommended: Python os.walk() – A Simple Illustrated Guide

Recursively Traversing Directories with a Recursive Function

Lastly, you could create a custom recursive function to traverse directories and collect .txt files. This method is particularly useful when working with different operating systems, like Windows and Unix:

from pathlib import Path

def find_txt_files(path: Path):
    txt_files = []
    for item in path.iterdir():
        if item.is_dir():
            txt_files.extend(find_txt_files(item))
        elif item.name.endswith('.txt'):
            txt_files.append(item)
    return txt_files

directory = Path('your_directory_path')
txt_files = find_txt_files(directory)
print(txt_files)

This recursive function explores directories and subdirectories and returns a list of .txt files. This approach is more versatile as it leverages Python 3’s pathlib module. ????

Filtering Based on File Extension and Size

To get all the .txt files in a folder, you can use the glob module in Python, which provides an easy way to find files matching a specific pattern.

Here’s a simple code snippet to get started:

import glob

txt_files = glob.glob('path/to/your/folder/*.txt')
print(txt_files)

This code will provide the absolute paths of all the .txt files within the specified folder. ????

Now that you have the .txt files, you might want to filter them based on their size. To achieve this, you can use the os module.

Here’s an example of how to filter .txt files by size:

import os
import glob

min_size = 1000  # Replace with your desired minimum file size in bytes

txt_files = glob.glob('path/to/your/folder/*.txt')
filtered_files = [file for file in txt_files if os.path.getsize(file) >= min_size]

print(filtered_files)

In this code, min_size represents the minimum file size in bytes that you wish to retrieve. By using a list comprehension with a condition, you can filter out the files that don’t meet your size requirements. ????

If you want to find .txt files not only in the target folder but also within its subdirectories, you can use the ** pattern along with the recursive parameter:

txt_files = glob.glob('path/to/your/folder/**/*.txt', recursive=True)

Using this approach, you can easily tailor your search to retrieve specific .txt files based on their size and location. With these tools at hand, you should be able to efficiently filter files in your Python projects. ????

Operating System Compatibility

Python works well across different operating systems, including Unix and Windows. Thanks to its compatibility ????, you can consistently use your code on different platforms. For this task, both the os and glob libraries are compatible with Unix and Windows systems, so you don’t have to worry about your text file retrieval code failing on either OS.

To get all the text files in a folder using Python, you can use the os and glob libraries. This works for all operating systems, i.e., Linux, Windows, Ubuntu, macOS.

Here’s a code snippet to achieve this:

import os
import glob

os.chdir("your_directory_path")
txt_files = glob.glob('*.txt')
print(txt_files)

Replace “your_directory_path” with the path of your folder containing the txt files.

Recommended Video

YouTube Video

Be on the Right Side of Change