What Chicken Breed To Buy In 2017

With so many chicken breeds on the market, let’s take a few minutes to talk about traits you want before you buy those spring chicks.

Usually starting in late January and going through March, the local farm supply stores will get their spring chicks in.  Please avoid the big-box-marts and buy from the local family owned stores.

Questions To Ask

Have a few questions ready before you go to the store.

Do you want brown or white eggs?  Ideal 236 and Leghorns lay white eggs, while most other breeds lay brown eggs.

Do you live in a cold or hot climate?  Certain chicken breeds deal with hot and cold better than others.

Will the chickens be confined to an enclosed run, have a chicken yard or free range?  Ask which breeds deal with various types of enclosures.

Do you want hens to sit on eggs to hatch out chicks?  This is called going broody or sitting.  If you do not have a rooster, hens sitting on eggs is a waste of time.  While sitting on eggs, hens stop laying.

Breeds that go broody include:

  • Buff Orpington
  • Australorp
  • Dominique, also known as Dominicker
  • Delaware
  • Silkies and Bantam, which are a small breed of chicken.

Egg Production

If all you want are chickens for egg production:

  • White Leghorn
  • Ideal 236
  • Rhode Island Red
  • Barred Rock
  • Silver Laced Wyandotte
  • Production Red

Those chicken breeds rarely go broody. Meaning, they rarely sit on eggs to hatch them out.

Butchering

All the chickens mentioned so far are slow growing heritage breeds.  They will not be full grown until they are around one year old.

If you want a meat chicken that you plan on butchering and want it to grow fast, ask the local farm supply store about “broilers.”  Most broilers are ready to butcher by the time they are two months old.

Broilers are not the kind of chicken you keep around for years.  They are usually heat sensitive and will die when the summer heat kicks in.  Get the broiler, feed them a high protein feed and butcher them when they are around two months old.

Dual Purpose

Most chickens fall under the dual purpose category.  This means they are good egg layers and are good sized for butchering.  If you do not want to butcher a bunch of broilers at one time, then get dual purpose.

Examples of dual purpose breeds:

  • Buff Orpington
  • Jersey Giant
  • New Hampshire Red
  • Barred Rock
  • Rhode Island Red
  • Australorp
  • Wyandottes

Number Of Chicken Breeds

The breeds mentioned so far, is a very small sampling of the number of chicken breeds on the market.  Every spring I learn something new.

Each breed has their own traits, and each chicken has their own personality.  Just because breeds are supposed to act a certain way, does not mean all chickens of that breed are that way.

The post What Chicken Breed To Buy In 2017 appeared first on AllOutdoor.com.

via All Outdoor
What Chicken Breed To Buy In 2017

How Chains are Made

How Chains are Made

Link

Cool factory footage from an old episode of How It’s Made, showing off the process of creating chain from long spools of wire. It’s neat to see how the wire is cut, bent, linked together, and hardened, but the entire time, all we could think of was Rick & Morty anyhow.

The post How Chains are Made appeared first on The Awesomer.

via The Awesomer
How Chains are Made

Working with JSON in MySQL

JFti976TQaVbpi0ZoYIy_scotch-featured-image-guidelines.jpg

SQL databases tend to be rigid.

If you have worked with them, you would agree that database design though it seems easier, is a lot trickier in practice. SQL databases believe in structure, that is why it’s called structured query language.

On the other side of the horizon, we have the NoSQL databases, also called schema-less databases that encourage flexibility. In schema-less databases, there is no imposed structural restriction, only data to be saved.

Though every tool has it’s use case, sometimes things call for a hybrid approach.

What if you could structure some parts of your database and leave others to be flexible?

MySQL version 5.7.8 introduces a JSON data type that allows you to accomplish that.

In this tutorial, you are going to learn.

  1. How to design your database tables using JSON fields.
  2. The various JSON based functions available in MYSQL to create, read, update, and delete rows.
  3. How to work with JSON fields using the Eloquent ORM in Laravel.

Why Use JSON

At this moment, you are probably asking yourself why would you want to use JSON when MySQL has been catering to a wide variety of database needs even before it introduced a JSON data type.

The answer lies in the use-cases where you would probably use a make-shift approach.

Let me explain with an example.

Suppose you are building a web application where you have to save a user’s configuration/preferences in the database.

Generally, you can create a separate database table with the id, user_id, key, and value fields or save it as a formatted string that you can parse at runtime.

However, this works well for a small number of users. If you have about a thousand users and five configuration keys, you are looking at a table with five thousand records that addresses a very small feature of your application.

Or if you are taking the formatted string route, extraneous code that only compounds your server load.

Using a JSON data type field to save a user’s configuration in such a scenario can spare you a database table’s space and bring down the number of records, which were being saved separately, to be the same as the number of users.

And you get the added benefit of not having to write any JSON parsing code, the ORM or the language runtime takes care of it.

The Schema

Before we dive into using all the cool JSON stuff in MySQL, we are going to need a sample database to play with.

So, let’s get our database schema out of the way first.

We are going to consider the use case of an online store that houses multiple brands and a variety of electronics.

Since different electronics have different attributes(compare a Macbook with a Vacuumn Cleaner) that buyers are interested in, typically the Entity–attribute–value model (EAV) pattern is used.

However, since we now have the option to use a JSON data type, we are going to drop EAV.

For a start, our database will be named e_store and has three tables only named, brands, categories, and products respectively.

Our brands and categories tables will be pretty similar, each having an id and a name field.

CREATE DATABASE IF NOT EXISTS `e_store`
DEFAULT CHARACTER SET utf8
DEFAULT COLLATE utf8_general_ci;

SET default_storage_engine = INNODB;

CREATE TABLE `e_store`.`brands`(
    `id` INT UNSIGNED NOT NULL auto_increment ,
    `name` VARCHAR(250) NOT NULL ,
    PRIMARY KEY(`id`)
);

CREATE TABLE `e_store`.`categories`(
    `id` INT UNSIGNED NOT NULL auto_increment ,
    `name` VARCHAR(250) NOT NULL ,
    PRIMARY KEY(`id`)
);

The objective of these two tables will be to house the product categories and the brands that provide these products.

While we are at it, let us go ahead and seed some data into these tables to use later.

/* Brands */
INSERT INTO `e_store`.`brands`(`name`)
VALUES
    ('Samsung');

INSERT INTO `e_store`.`brands`(`name`)
VALUES
    ('Nokia');

INSERT INTO `e_store`.`brands`(`name`)
VALUES
    ('Canon');

/* Types of electronic device */
INSERT INTO `e_store`.`categories`(`name`)
VALUES
    ('Television');

INSERT INTO `e_store`.`categories`(`name`)
VALUES
    ('Mobilephone');

INSERT INTO `e_store`.`categories`(`name`)
VALUES
    ('Camera');

The brands table

The categories table

Next, is the business area of this tutorial.

We are going to create a products table with the id, name, brand_id, category_id, and attributes fields.

CREATE TABLE `e_store`.`products`(
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
    `name` VARCHAR(250) NOT NULL ,
    `brand_id` INT UNSIGNED NOT NULL ,
    `category_id` INT UNSIGNED NOT NULL ,
    `attributes` JSON NOT NULL ,
    PRIMARY KEY(`id`) ,
    INDEX `CATEGORY_ID`(`category_id` ASC) ,
    INDEX `BRAND_ID`(`brand_id` ASC) ,
    CONSTRAINT `brand_id` FOREIGN KEY(`brand_id`) REFERENCES `e_store`.`brands`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE ,
    CONSTRAINT `category_id` FOREIGN KEY(`category_id`) REFERENCES `e_store`.`categories`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE
);

Our table definition specifies foreign key constraints for the brand_id and category_id fields, specifying that they reference the brands and categories table respectively. We have also specified that the referenced rows should not be allowed to delete and if updated, the changes should reflect in the references as well.

The attributes field’s column type has been declared to be JSON which is the native data type now available in MySQL. This allows us to use the various JSON related constructs in MySQL on our attributes field.

Here is an entity relationship diagram of our created database.

The e_store database

Our database design is not the best in terms of efficiency and accuracy. There is no price column in the products table and we could do with putting a product into multiple categories. However, the purpose of this tutorial is not to teach database design but rather how to model objects of different nature in a single table using MySQL’s JSON features.

The CRUD Operations

Let us look at how to create, read, update, and delete data in a JSON field.

Create

Creating a record in the database with a JSON field is pretty simple.

All you need to do is add valid JSON as the field value in your insert statement.

/* Let's sell some televisions */
INSERT INTO `e_store`.`products`(
    `name` ,
    `brand_id` ,
    `category_id` ,
    `attributes`
)
VALUES(
    'Prime' ,
    '1' ,
    '1' ,
    '{"screen": "50 inch", "resolution": "2048 x 1152 pixels", "ports": {"hdmi": 1, "usb": 3}, "speakers": {"left": "10 watt", "right": "10 watt"}}'
);

INSERT INTO `e_store`.`products`(
    `name` ,
    `brand_id` ,
    `category_id` ,
    `attributes`
)
VALUES(
    'Octoview' ,
    '1' ,
    '1' ,
    '{"screen": "40 inch", "resolution": "1920 x 1080 pixels", "ports": {"hdmi": 1, "usb": 2}, "speakers": {"left": "10 watt", "right": "10 watt"}}'
);

INSERT INTO `e_store`.`products`(
    `name` ,
    `brand_id` ,
    `category_id` ,
    `attributes`
)
VALUES(
    'Dreamer' ,
    '1' ,
    '1' ,
    '{"screen": "30 inch", "resolution": "1600 x 900 pixles", "ports": {"hdmi": 1, "usb": 1}, "speakers": {"left": "10 watt", "right": "10 watt"}}'
);

INSERT INTO `e_store`.`products`(
    `name` ,
    `brand_id` ,
    `category_id` ,
    `attributes`
)
VALUES(
    'Bravia' ,
    '1' ,
    '1' ,
    '{"screen": "25 inch", "resolution": "1366 x 768 pixels", "ports": {"hdmi": 1, "usb": 0}, "speakers": {"left": "5 watt", "right": "5 watt"}}'
);

INSERT INTO `e_store`.`products`(
    `name` ,
    `brand_id` ,
    `category_id` ,
    `attributes`
)
VALUES(
    'Proton' ,
    '1' ,
    '1' ,
    '{"screen": "20 inch", "resolution": "1280 x 720 pixels", "ports": {"hdmi": 0, "usb": 0}, "speakers": {"left": "5 watt", "right": "5 watt"}}'
);

The products table after adding televisions

Instead of laying out the JSON object yourself, you can also use the built-in JSON_OBJECT function.

The JSON_OBJECT function accepts a list of key/value pairs in the form JSON_OBJECT(key1, value1, key2, value2, ... key(n), value(n)) and returns a JSON object.

/* Let's sell some mobilephones */
INSERT INTO `e_store`.`products`(
    `name` ,
    `brand_id` ,
    `category_id` ,
    `attributes`
)
VALUES(
    'Desire' ,
    '2' ,
    '2' ,
    JSON_OBJECT(
        "network" ,
        JSON_ARRAY("GSM" , "CDMA" , "HSPA" , "EVDO") ,
        "body" ,
        "5.11 x 2.59 x 0.46 inches" ,
        "weight" ,
        "143 grams" ,
        "sim" ,
        "Micro-SIM" ,
        "display" ,
        "4.5 inches" ,
        "resolution" ,
        "720 x 1280 pixels" ,
        "os" ,
        "Android Jellybean v4.3"
    )
);

INSERT INTO `e_store`.`products`(
    `name` ,
    `brand_id` ,
    `category_id` ,
    `attributes`
)
VALUES(
    'Passion' ,
    '2' ,
    '2' ,
    JSON_OBJECT(
        "network" ,
        JSON_ARRAY("GSM" , "CDMA" , "HSPA") ,
        "body" ,
        "6.11 x 3.59 x 0.46 inches" ,
        "weight" ,
        "145 grams" ,
        "sim" ,
        "Micro-SIM" ,
        "display" ,
        "4.5 inches" ,
        "resolution" ,
        "720 x 1280 pixels" ,
        "os" ,
        "Android Jellybean v4.3"
    )
);

INSERT INTO `e_store`.`products`(
    `name` ,
    `brand_id` ,
    `category_id` ,
    `attributes`
)
VALUES(
    'Emotion' ,
    '2' ,
    '2' ,
    JSON_OBJECT(
        "network" ,
        JSON_ARRAY("GSM" , "CDMA" , "EVDO") ,
        "body" ,
        "5.50 x 2.50 x 0.50 inches" ,
        "weight" ,
        "125 grams" ,
        "sim" ,
        "Micro-SIM" ,
        "display" ,
        "5.00 inches" ,
        "resolution" ,
        "720 x 1280 pixels" ,
        "os" ,
        "Android KitKat v4.3"
    )
);

INSERT INTO `e_store`.`products`(
    `name` ,
    `brand_id` ,
    `category_id` ,
    `attributes`
)
VALUES(
    'Sensation' ,
    '2' ,
    '2' ,
    JSON_OBJECT(
        "network" ,
        JSON_ARRAY("GSM" , "HSPA" , "EVDO") ,
        "body" ,
        "4.00 x 2.00 x 0.75 inches" ,
        "weight" ,
        "150 grams" ,
        "sim" ,
        "Micro-SIM" ,
        "display" ,
        "3.5 inches" ,
        "resolution" ,
        "720 x 1280 pixels" ,
        "os" ,
        "Android Lollypop v4.3"
    )
);

INSERT INTO `e_store`.`products`(
    `name` ,
    `brand_id` ,
    `category_id` ,
    `attributes`
)
VALUES(
    'Joy' ,
    '2' ,
    '2' ,
    JSON_OBJECT(
        "network" ,
        JSON_ARRAY("CDMA" , "HSPA" , "EVDO") ,
        "body" ,
        "7.00 x 3.50 x 0.25 inches" ,
        "weight" ,
        "250 grams" ,
        "sim" ,
        "Micro-SIM" ,
        "display" ,
        "6.5 inches" ,
        "resolution" ,
        "1920 x 1080 pixels" ,
        "os" ,
        "Android Marshmallow v4.3"
    )
);

The products table after adding mobilephones

Notice the JSON_ARRAY function which returns a JSON array when passed a set of values.

If you specify a single key multiple times, only the first key/value pair will be retained. This is called normalizing the JSON in MySQL’s terms. Also, as part of normalization, the object keys are sorted and the extra white-space between key/value pairs is removed.

Another function that we can use to create JSON objects is the JSON_MERGE function.

The JSON_MERGE function takes multiple JSON objects and produces a single, aggregate object.

/* Let's sell some cameras */
INSERT INTO `e_store`.`products`(
    `name` ,
    `brand_id` ,
    `category_id` ,
    `attributes`
)
VALUES(
    'Explorer' ,
    '3' ,
    '3' ,
    JSON_MERGE(
        '{"sensor_type": "CMOS"}' ,
        '{"processor": "Digic DV III"}' ,
        '{"scanning_system": "progressive"}' ,
        '{"mount_type": "PL"}' ,
        '{"monitor_type": "LCD"}'
    )
);

INSERT INTO `e_store`.`products`(
    `name` ,
    `brand_id` ,
    `category_id` ,
    `attributes`
)
VALUES(
    'Runner' ,
    '3' ,
    '3' ,
    JSON_MERGE(
        JSON_OBJECT("sensor_type" , "CMOS") ,
        JSON_OBJECT("processor" , "Digic DV II") ,
        JSON_OBJECT("scanning_system" , "progressive") ,
        JSON_OBJECT("mount_type" , "PL") ,
        JSON_OBJECT("monitor_type" , "LED")
    )
);

INSERT INTO `e_store`.`products`(
    `name` ,
    `brand_id` ,
    `category_id` ,
    `attributes`
)
VALUES(
    'Traveler' ,
    '3' ,
    '3' ,
    JSON_MERGE(
        JSON_OBJECT("sensor_type" , "CMOS") ,
        '{"processor": "Digic DV II"}' ,
        '{"scanning_system": "progressive"}' ,
        '{"mount_type": "PL"}' ,
        '{"monitor_type": "LCD"}'
    )
);

INSERT INTO `e_store`.`products`(
    `name` ,
    `brand_id` ,
    `category_id` ,
    `attributes`
)
VALUES(
    'Walker' ,
    '3' ,
    '3' ,
    JSON_MERGE(
        '{"sensor_type": "CMOS"}' ,
        '{"processor": "Digic DV I"}' ,
        '{"scanning_system": "progressive"}' ,
        '{"mount_type": "PL"}' ,
        '{"monitor_type": "LED"}'
    )
);

INSERT INTO `e_store`.`products`(
    `name` ,
    `brand_id` ,
    `category_id` ,
    `attributes`
)
VALUES(
    'Jumper' ,
    '3' ,
    '3' ,
    JSON_MERGE(
        '{"sensor_type": "CMOS"}' ,
        '{"processor": "Digic DV I"}' ,
        '{"scanning_system": "progressive"}' ,
        '{"mount_type": "PL"}' ,
        '{"monitor_type": "LCD"}'
    )
);

The products table after adding cameras

There is a lot happening in these insert statements and it can get a bit confusing. However, it is pretty simple.

We are only passing objects to the JSON_MERGE function. Some of them have been constructed using the JSON_OBJECT function we saw previously whereas others have been passed as valid JSON strings.

In case of the JSON_MERGE function, if a key is repeated multiple times, it’s value is retained as an array in the output.

A proof of concept is in order I suppose.

/* output: {"network": ["GSM", "CDMA", "HSPA", "EVDO"]} */
SELECT JSON_MERGE(
    '{"network": "GSM"}' ,
    '{"network": "CDMA"}' ,
    '{"network": "HSPA"}' ,
    '{"network": "EVDO"}'
);

We can confirm all our queries were run successfully using the JSON_TYPE function which gives us the field value type.

/* output: OBJECT */
SELECT JSON_TYPE(attributes) FROM `e_store`.`products`;

Add attributes are JSON objects

Read

Right, we have a few products in our database to work with.

For typical MySQL values that are not of type JSON, a where clause is pretty straight-forward. Just specify the column, an operator, and the values you need to work with.

Heuristically, when working with JSON columns, this does not work.

/* It's not that simple */
SELECT
    *
FROM
    `e_store`.`products`
WHERE
    attributes = '{"ports": {"usb": 3, "hdmi": 1}, "screen": "50 inch", "speakers": {"left": "10 watt", "right": "10 watt"}, "resolution": "2048 x 1152 pixels"}';

When you wish to narrow down rows using a JSON field, you should be familiar with the concept of a path expression.

The most simplest definition of a path expression(think JQuery selectors) is it’s used to specify which parts of the JSON document to work with.

The second piece of the puzzle is the JSON_EXTRACT function which accepts a path expression to navigate through JSON.

Let us say we are interested in the range of televisions that have atleast a single USB and HDMI port.

SELECT
    *
FROM
    `e_store`.`products`
WHERE
    `category_id` = 1
AND JSON_EXTRACT(`attributes` , '$.ports.usb') > 0
AND JSON_EXTRACT(`attributes` , '$.ports.hdmi') > 0;

Selecting records by JSON attributes

The first argument to the JSON_EXTRACT function is the JSON to apply the path expression to which is the attributes column. The $ symbol tokenizes the object to work with. The $.ports.usb and $.ports.hdmi path expressions translate to "take the usb key under ports" and "take the hdmi key under ports" respectively.

Once we have extracted the keys we are interested in, it is pretty simple to use the MySQL operators such as > on them.

Also, the JSON_EXTRACT function has the alias -> that you can use to make your queries more readable.

Revising our previous query.

SELECT
    *
FROM
    `e_store`.`products`
WHERE
    `category_id` = 1
AND `attributes` -> '$.ports.usb' > 0
AND `attributes` -> '$.ports.hdmi' > 0;

Update

In order to update JSON values, we are going to use the JSON_INSERT, JSON_REPLACE, and JSON_SET functions. These functions also require a path expression to specify which parts of the JSON object to modify.

The output of these functions is a valid JSON object with the changes applied.

Let us modify all mobilephones to have a chipset property as well.

UPDATE `e_store`.`products`
SET `attributes` = JSON_INSERT(
    `attributes` ,
    '$.chipset' ,
    'Qualcomm'
)
WHERE
    `category_id` = 2;

Updated mobilephones

The $.chipset path expression identifies the position of the chipset property to be at the root of the object.

Let us update the chipset property to be more descriptive using the JSON_REPLACE function.

UPDATE `e_store`.`products`
SET `attributes` = JSON_REPLACE(
    `attributes` ,
    '$.chipset' ,
    'Qualcomm Snapdragon'
)
WHERE
    `category_id` = 2;

Updated mobilephones

Easy peasy!

Lastly, we have the JSON_SET function which we will use to specify our televisions are pretty colorful.

UPDATE `e_store`.`products`
SET `attributes` = JSON_SET(
    `attributes` ,
    '$.body_color' ,
    'red'
)
WHERE
    `category_id` = 1;

Updated televisions

All of these functions seem identical but there is a difference in the way they behave.

The JSON_INSERT function will only add the property to the object if it does not exists already.

The JSON_REPLACE function substitutes the property only if it is found.

The JSON_SET function will add the property if it is not found else replace it.

Delete

There are two parts to deleting that we will look at.

The first is to delete a certain key/value from your JSON columns whereas the second is to delete rows using a JSON column.

Let us say we are no longer providing the mount_type information for cameras and wish to remove it for all cameras.

We will do it using the JSON_REMOVE function which returns the updated JSON after removing the specified key based on the path expression.

UPDATE `e_store`.`products`
SET `attributes` = JSON_REMOVE(`attributes` , '$.mount_type')
WHERE
    `category_id` = 3;

Cameras after removing mount_type property

For the second case, we also do not provide mobilephones anymore that have the Jellybean version of the Android OS.

DELETE FROM `e_store`.`products`
WHERE `category_id` = 2
AND JSON_EXTRACT(`attributes` , '$.os') LIKE '%Jellybean%';

We do not sell Jellybeans anymore!

As stated previously, working with a specific attribute requires the use of the JSON_EXTRACT function so in order to apply the LIKE operator, we have first extracted the os property of mobilephones(with the help of category_id) and deleted all records that contain the string Jellybean.

A Primer for Web Applications

The old days of directly working with a database are way behind us.

These days, frameworks insulate developers from lower-level operations and it almost feels alien for a framework fanatic not to be able to translate his/her database knowledge into an object relational mapper.

For the purpose of not leaving such developers heartbroken and wondering about their existence and purpose in the universe, we are going to look at how to go about the business of JSON columns in the Laravel framework.

We will only be focusing on the parts that overlap with our subject matter which deals with JSON columns. An in-depth tutorial on the Laravel framework is beyond the scope of this piece.

Creating the Migrations

Make sure to configure your Laravel application to use a MySQL database.

We are going to create three migrations for brands, categories, and products respectively.

$ php artisan make:migration create_brands
$ php artisan make:migration create_categories
$ php artisan make:migration create_products

The create_brands and create_categories migrations are pretty similar and and a regulation for Laravel developers.

/* database/migrations/create_brands.php */

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBrands extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('brands', function(Blueprint $table){
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('brands');
    }
}

/* database/migrations/create_categories.php */

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCategories extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function(Blueprint $table){
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('categories');
    }
}

The create_products migration will also have the directives for indexes and foreign keys.

/* database/migrations/create_products */

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProducts extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function(Blueprint $table){
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('name');
            $table->unsignedInteger('brand_id');
            $table->unsignedInteger('category_id');
            $table->json('attributes');
            $table->timestamps();
            // foreign key constraints
            $table->foreign('brand_id')->references('id')->on('brands')->onDelete('cascade')->onUpdate('restrict');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade')->onUpdate('restrict');
            // indexes
            $table->index('brand_id');
            $table->index('category_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('products');
    }
}

Pay attention to the $table->json('attributes'); statement in the migration.

Just like creating any other table field using the appropriate data type named method, we have created a JSON column using the json method with the name attributes.

Also, this only works for database engines that support the JSON data type.

Engines, such as older versions of MySQL will not be able to carry out these migrations.

Creating the Models

Other than associations, there is not much needed to set up our models so let’s run through them quickly.

/* app/Brand.php */

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Brand extends Model
{
    // A brand has many products
    public function products(){
        return $this->hasMany('Product')
    }
}

/* app/Category.php */

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    // A category has many products
    public function products(){
        return $this->hasMany('Product')
    }
}

/* app/Product.php */

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    // Cast attributes JSON to array
    protected $casts = [
        'attributes' => 'array'
    ];

    // Each product has a brand
    public function brand(){
        return $this->belongsTo('Brand');
    }

    // Each product has a category
    public function category(){
        return $this->belongsTo('Category');
    }
}

Again, our Product model needs a special mention.

The $casts array which has the key attributes set to array makes sure whenever a product is fetched from the database, it’s attributes JSON is converted to an associated array.

We will see later in the tutorial how this facilitates us to update records from our controller actions.

Resource Operations

Creating a Product

Speaking of the admin panel, the parameters to create a product maybe coming in through different routes since we have a number of product categories. You may also have different views to create, edit, show, and delete a product.

For example, a form to add a camera requires different input fields than a form to add a mobilephone so they warrant separate views.

Moreoever, once you have the user input data, you will most probabaly run it through a request validator, separate for the camera, and the mobilephone each.

The final step would be to create the product through Eloquent.

We will be focusing on the camera resource for the rest of this tutorial. Other products can be addressed using the code produced in a similar manner.

Assuming we are saving a camera and the form fields are named as the respective camera attributes, here is the controller action.

// creates product in database
// using form fields
public function store(Request $request){
    // create object and set properties
    $camera = new \App\Product();
    $camera->name = $request->name;
    $camera->brand_id = $request->brand_id;
    $camera->category_id = $request->category_id;
    $camera->attributes = json_encode([
        'processor' => $request->processor,
        'sensor_type' => $request->sensor_type,
        'monitor_type' => $request->monitor_type,
        'scanning_system' => $request->scanning_system,
    ]);
    // save to database
    $camera->save();
    // show the created camera
    return view('product.camera.show', ['camera' => $camera]);
}

Fetching Products

Recall the $casts array we declared earlier in the Product model. It will help us read and edit a product by treating attributes as an associative array.

// fetches a single product
// from database
public function show($id){
    $camera = \App\Product::find($id);
    return view('product.camera.show', ['camera' => $camera]);
}

Your view would use the $camera variable in the following manner.

<table>
    <tr>
        <td>Name</td>
        <td></td>
    </tr>
    <tr>
        <td>Brand ID</td>
        <td></td>
    </tr>
    <tr>
        <td>Category ID</td>
        <td></td>
    </tr>
    <tr>
        <td>Processor</td>
        <td></td>
    </tr>
    <tr>
        <td>Sensor Type</td>
        <td></td>
    </tr>
    <tr>
        <td>Monitor Type</td>
        <td></td>
    </tr>
    <tr>
        <td>Scanning System</td>
        <td></td>
    </tr>
</table>

Editing a Product

As shown in the previous section, you can easily fetch a product and pass it to the view, which in this case would be the edit view.

You can use the product variable to pre-populate form fields on the edit page.

Updating the product based on the user input will be pretty similar to the store action we saw earlier, only that instead of creating a new product, you will fetch it first from the database before updating it.

Searching Based on JSON Attributes

The last piece of the puzzle that remains to discuss is querying JSON columns using the Eloquent ORM.

If you have a search page that allows cameras to be searched based on their specifications provided by the user, you can do so with the following code.

// searches cameras by user provided specifications
public function search(Request $request){
    $cameras = \App\Product::where([
        ['attributes->processor', 'like', $request->processor],
        ['attributes->sensor_type', 'like', $request->sensor_type],
        ['attributes->monitor_type', 'like', $request->monitor_type],
        ['attributes->scanning_system', 'like', $request->scanning_system]
    ])->get();
    return view('product.camera.search', ['cameras' => $cameras]);
}

The retrived records will now be available to the product.camera.search view as a $cameras collection.

Deleting a Product

Using a non-JSON column attribute, you can delete products by specifying a where clause and then calling the delete method.

For example, in case of an ID.

\App\Product::where('id', $id)->delete();

For JSON columns, specify a where clause using a single or multiple attributes and then call the delete method.

// deletes all cameras with the sensor_type attribute as CMOS
\App\Product::where('attributes->sensor_type', 'CMOS')->delete();
}

Curtains

We have barely scratched the surface when it comes to using JSON columns in MySQL.

Whenever you need to save data as key/value pairs in a separate table or work with flexible attributes for an entity, you should consider using a JSON data type field instead as it can heavily contribute to compressing your database design.

If you are interested in diving deeper, the MySQL documentation is a great resource to explore JSON concepts futher.

I hope you found this tutorial interesting and knowledgeable. Until my next piece, happy coding!

via Planet MySQL
Working with JSON in MySQL

When You Load or Reload Your AR-15, Do This!

Loading and reloading your AR-15 is a simple and reliable process if you follow these steps. The tip in this video can make a huge difference between a working gun, and one you have to fix.

Dearly departed AR-15 guru Pat Rogers had a special patch he would give out to students who failed to properly seat their AR-15 mags and commenced to shooting, only to watch that loaded but not locked magazine hit the dirt.

Learn to do this folks. It matters.

The post When You Load or Reload Your AR-15, Do This! appeared first on Bearing Arms.

via Bearing Arms
When You Load or Reload Your AR-15, Do This!

Former UFC Champ Rousey Spotted Bearing Instead of Breaking Arms

ronda-rousey

Celebrity gossip site TMZ is reporting the former UFC champion fighter Ronda Rousey and her boyfriend, fellow UFC fighter, #10-ranked heavyweight Travis Browne, were spotted in a Las Vegas gun store over the weekend taking a concealed carry class.

Ronda Rousey has come out of hiding with a bang — surfacing at a Las Vegas gun store where she applied for a concealed carry permit … TMZ Sports has learned.

The UFC superstar and her boyfriend, Travis Browne, hit up The Range 702 gun store on Sunday where our gun enthusiast witnesses at the store say Ronda took a special course required to get a concealed carry permit.

Once Ronda applies for the permit, it usually takes around 90 days before she’ll get her card in the mail.

We’re told Ronda did some shooting at the range — which is also required for the test — using a blue Glock 43 9mm pistol.

It’s not uncommon for athletes—even professional fighters near the top of their game—to obtain firearms and concealed carry permits. Having great hand-to-hand skills is a clear asset in a fight, but professional fighters are wise enough to understand that the kind of fighting that occurs with referees and judges in a ring is completely different than what we see during robberies and home invasions, where no tactics or weapons or off limits. A wiry criminal with a gun and a plan is going to beat an unarmed heavyweight fighter almost every time.

Other professional athletes have firearms at their homes for self defense, for hunting, or merely because they like collecting them.

As people in the public eye, they are acutely aware that some people can become obsessed with celebrities and professional athletes. There have been countless incidents of people stalking celebrities both major and minor, and there have unfortunately been a number of home invasions and murders of celebrities by obsessed fans, such as the murder of The Voice contestant Christina Grimmie in June of 2016 during an autograph session.

I’m glad that Ms. Rousey and Mr. Browne have wisely come to the conclusion that their considerable mixed martial arts talents don’t make them immune to the threat of crime, and that they’re exercising their right to bear arms for self defense.

I’m not so sure about the Glock 43 though.

Blue, Ronda?

The post Former UFC Champ Rousey Spotted Bearing Instead of Breaking Arms appeared first on Bearing Arms.

via Bearing Arms
Former UFC Champ Rousey Spotted Bearing Instead of Breaking Arms

Idea Drop helps organisations generate and capture new ideas

In spite of my aversion to the word “ideation,” I can’t argue against software designed to help an organisation solicit ideas from its people. The best ideas can — and often do — come from anyone, regardless of job title or hierarchy. Enter Idea Drop, a London-headquartered startup that offers what it calls an “idea management” platform.

Consisting of cloud-based software and a mobile app, Idea Drop is designed to help organisations and companies generate and capture new ideas. In addition, it provides features to help decide which of those ideas get put into action.

“For most businesses and organisations, the process of gathering, curating and implementing new ideas is generally costly and time consuming,” says Idea Drop co-founder Owen Hunnam.

“Regardless of size or sector, ideation processes typically happen from the top down, with those highest paid and most senior usually sharing, validating and actioning the most ideas. Where there are existing ideation initiatives in place, such as intranets, suggestion boxes or annual staff surveys, these tend to be siloed and prevent collaborative, transparent and bottom-up innovation unfolding”.

Along with a modern UX and native iOS and Android apps — two things that Hunman says gives Idea Drop the edge over legacy competitors — the software is underpinned by a ranking algorithm that scores every idea in real-time based on “social signals and interactions”.

The idea is to enable the most promising ideas to automatically bubble to the surface for the attention of managers and decision-makers within an organisation.

“Out-of-the-box social tools also make it easy for colleagues to collaborate, enrich and validate ideas,” adds Hunnam. “Other key features include individual innovation scores, challenges, reports, search, analytics and idea cloaking”.

Idea Drop is also disclosing new funding. The startup has raised £1 million from 33 new investors, in addition to all previous backers participating. Also notable is that the company’s 17 person-strong engineering ‘partner’ is based in Kerala, India, and has also invested. Party round, anyone?

via TechCrunch
Idea Drop helps organisations generate and capture new ideas

We’ve Stumbled Across the Most Fascinating Site on the Internet

Astronaut.io is a website with a bizarre function: It scrapes YouTube, finds videos posted in the last week that have zero or close to zero views and undescriptive filenames like "DSC-1234," then shows you a stream of snippets from these videos.

It sounds dull. But it’s completely fascinating.

That’s because Astronaut’s picks are essentially the complete opposite of a Casey Neistat video. Neistat lenses extraordinary footage of curated events and painstakingly edits it into a narrative, garnering millions of views for his artful storytelling. But the unseen videos Astronaut presents are simply random, unedited human activities from all around the world that someone deemed worthy of recording and posting, yet has made no attempt to promote.

The result is an unfiltered and honest look at what human beings do, all day, every day. If an anthropologist clicked onto this website they might never click away.

Some things that I’ve witnessed in a single viewing:

A bunch of high school girls doing a synchronized dance in snow. A tractor idling in a barren field. Men on a beach preparing a hovercraft for launch. A women’s volleyball game. Asian co-workers in an office singing "Happy Birthday" to the birthday woman while clapping. A remote-controlled fighter jet. Someone unboxing a collection of basketball cards. A baby laughing. People dancing at an outdoor festival in what appears to be Africa. Someone failing at a slam dunk in slow motion. A cooking tutorial. A speech at a funeral. A comedy play in Russia. High school students in Vietnam singing karaoke. A tour of a house where all of the surfaces appear to be concrete. A protest march conducted in Arabic. Puppies on carpet.

To be fair, the videos we see do not accurately represent all of humanity, but just the folks that have access to recording technology and a means of uploading footage to the internet. But the global nature of the footage I’ve seen is truly impressive and does not appear dominated by any one region. And I can’t stop watching it.

Try it here.

(Credit where credit is due: The website is the brainchild of data wonks Andrew Wong and James Thompson.)

Via Kottke


via Core77
We’ve Stumbled Across the Most Fascinating Site on the Internet

Lego Batman Explains Why He Got His Own Movie: It’s Because He’s Awesome

In case a movie featuring the Lego versions of Batman and company wasn’t already pushing the envelope for absurdity, we now have a “behind the scenes” video where the Lego figures explain why they made the movie. The fourth wall isn’t so much broken as it is twisted into a Möbius strip.

It’s not just the words that make this video funny—it’s the attention to detail. It’s Batman being credited as “Bruce Wayne’s roommate.” Or Alfred chasing bats around the Batcave in the background of Batman’s interview. Or Harley’s eating habits while the Joker talks. There are layers to this video.

The Lego Batman Movie comes out February 10.

via Gizmodo
Lego Batman Explains Why He Got His Own Movie: It’s Because He’s Awesome

You’ve Been Wrong About Where the Death Star Trench Was for Your Entire Life

Image: Death Star, Lucasfilm

If you were asked to point to the trench that housed the first Death Star’s exhaust port, where would you point? If you pointed at the big obvious seam running along the Death Star’s equator, I am sorry, but you are wrong. But don’t feel too bad—it turns out even the people at Industrial Light & Magic thought that was the answer.

Yesterday, visual effects artist Todd Vaziri posted a story on his blog, FXRants, which he’s been holding in for a year.

Here’s Vaziri remembering how he discovered where the trench that Luke and his fellow X-Wing pilots traversed in A New Hope really was:

Nearly everybody points at the equatorial trench of the Death Star. I asked dozens of die-hard fans, including many co-workers at Industrial Light & Magic, and nearly every single person pointed to the equatorial trench. If you asked me, I would also have said the equatorial trench.

In fact, this came up during ILM “Rogue One” dailies one day. Computer Graphics Supervisor Vick Schutz and Visual Effects Supervisor John Knoll were chatting about the details of our computer graphics version of the Death Star, and Knoll casually remarked that the trench run in “Star Wars” is a longitudinal line on the Death Star (meaning, a north-south trench).

Most of us in the room were dumbfounded. “What did he say?”

As Vaziri himself then goes on to explain, in detail, it makes perfect sense that we’d all assume the big, equatorial line in the middle is where the exhaust port would be, even though it’s clearly much larger than the trench in the trench run and has a bunch of lights that don’t appear there. But that’s where the Death Star’s hangar bays are located, where TIE Fighters launch from, and where the Millennium Falcon was tractor beamed into (which is actually another sign that should make it clear it’s not the trench, as the two look nothing alike).

Instead, as Vaziri points out, the trench runs perpendicular to the equator, which everyone would know if we’d all just paid attention to General Jan Dodonna’s briefing to the Rebel pilots where it is clearly shown:

(Man, no one ever pays attention in meetings. Not even in Star Wars.)

Go read all of Vaziri’s post, if for no other reason than his excellent discourse on why so many of us assumed the wrong thing for so long. And if this is news to you, as it was for so many others, take heart and know that you were in very good company.

[h/t Matt Galvin]

via Gizmodo
You’ve Been Wrong About Where the Death Star Trench Was for Your Entire Life

Airguns, Airguns, And More Airguns

Note: This article was originally posted on NRA Blog: http://bit.ly/2jOFDVX

NRAblog.com
NRAblog.com

USA -(Ammoland.com)- For many, airguns were a rite of passage to the world of firearms.

From hunting, recreational shooting and even competition, airguns have evolved in the shooting sports and the industry is expanding on the demand.

We’ve compiled a list of airguns displayed at this year’s SHOT Show that are bound to be added to your wish list this year.

Crosman Marauder Field & Target Edition Air Rifle
Crosman Marauder Field & Target Edition Air Rifle

Crosman Marauder Field & Target Edition Air Rifle

The beloved PCP air rifle is back with its newest addition to the Marauder line. The Marauder Field & Target edition features an adjustable, quick-change regulator allowing users to simply turn a dial to choose between target and field settings. The barrel is produced through a proprietary precision reaming process with barrel twist rates which optimize each pellet caliber with 3,000 psi. This particular model was presented at SHOT Show 2017 and will be released this spring.

GAMO URBAN PCP .22 Cal Multishot Air Rifle
GAMO URBAN PCP .22 Cal Multishot Air Rifle

The GAMO URBAN PCP .22 Cal Multishot Air Rifle

The Gamo URBAN PCP is a quiet, short, lightweight PCP. 22 caliber with a 10-pellet removable magazine. It features a synthetic stock, 10-shot repeater with bolt-action, and a high-precision, hammer-forged barrel. Accompanied with Whisper Fusion dual integrated sound suppression technology, this extremely quiet pneumatic gun is perfect for hunting.

Umarex Gauntlet Rifle
Umarex Gauntlet Rifle

Umarex Gauntlet Rifle

The Gauntlet is truly in a class of its own. With 70 incredibly consistent shots at 1,000 FPS in .177 caliber, or 60 shots at 900 FPS in .22 caliber, this PCP punches powerful and accurate shots from one fill of its high capacity 13-cu. in. regulated tank. At 8.5 pounds, the Gauntlet is a comfortable air rifle which balances well in the hand and is perfect for hunting, field target competition, or plinking.

 

John Wayne 'Lil Duke BB Rifle
John Wayne ‘Lil Duke BB Rifle

John Wayne ‘Lil Duke BB Rifle

John Wayne was an iconic Hollywood actor who captivated the Silver Screen. Air Venturi presents the officially licensed John Wayne ‘Lil’ Duke .177 caliber lever-action BB rifle, aimed for beginning and young shooters. The rifle is compatible for a scope, making it one of the only lever-action BB repeaters to do so, and is featured with a stained wood stock etched with the signature from the legend himself on the action of the gun. Its large loop cocking mechanism makes for one of the easiest guns to cock and lock, and has a 550 shot capacity launching BBs downrange at speeds up to 350 FPS.

HatsanUSA Semi-Auto BullMaster Air Rifle
HatsanUSA Semi-Auto BullMaster Air Rifle

HatsanUSA Semi-Auto BullMaster Air Rifle

HatsanUSA presented the first-ever semi-automatic air rifle at SHOT Show. Named the BullMaster, this new semi-auto PCP air rifle with a bullpup design is available in .177 and .22 calibers. Featuring a detachable rotary magazine with a 14-shot capacity for the .177 and 12-shot capacity for the .22., the barrel is fully shrouded, precision-rifled and choked, and also comes with three magazines.

ASP Pistol Airguns
ASP Pistol Airguns

SIG Sauer ASP Pistol Airguns

Sig’s popular centerfire pistols are replicated as airguns in their ASP line. From its metal slide to steel-rifled barrel, this air pistol comes with some additional performance advantages – low audible profile, practice space versatility and inexpensive ammunition. The ASP pistol line is ideal for shooters to train for a quick, accurate response and is new to this year’s line.

Beeman SAG Deluxe "CO2" .177 Rifle
Beeman SAG Deluxe “CO2” .177 Rifle

Beeman SAG Deluxe “Co2” .177 Rifle

Anschutz 9015 Competition Air Rifle
Anschutz 9015 Competition Air Rifle

Anschutz 9015 Competition Air Rifle

There’s nothing wrong with a classic, and this SAG Deluxe exudes all the classic elements. The QB Series of the CO2 rifles is perfect for plinking or to modify into the ultimate pellet slinger. Featuring a hardwood stock with blued finish, the single-shot, bolt-action SAG runs on two 12–gram CO2 cartridges with a maximum muzzle velocity of 550 FPS.

Anschutz 9015

The new 9015 barreled action was developed off the 9003 Premium air rifle and is said to replace all former air rifle barreled actions in the future. Its enhanced air pressure control includes a new patented 5065 4K trigger with ball bearings and adaptable trigger blade. The 9015 is also user-friendly with its adjustable butt plate, cheek piece, and pistol grip features.

This post Airguns, Airguns, And More Airguns appeared first on AmmoLand.com Shooting Sports News .

via AmmoLand.com Shooting Sports News
Airguns, Airguns, And More Airguns