Khaitan

Khaitan

1563352407

Building Frontend Using Vuetify

Building a friendly application interface with a great user experience is a skill that requires practice and knowledge. While Vuetify won’t make you a skilled UX practitioner overnight, it will help provide a solid start to those who are new in this area.

As a Vue.js developer, there are many fully-featured CSS frameworks specifically developed for Vue that you can take advantage of. One great example is Bootstrap-Vue. I have used it and and it does really make building components easier than just using traditional CSS frameworks. However, you may want to give your apps a Material Design look and feel to make it familiar to new users.

According to the makers of Material Design:

“Material Design isn’t a single style. It’s an adaptable design system inspired by paper and ink. And engineered so you can build beautiful, usable products faster.”
I hope I now have your attention with that powerful statement. Currently, Vuetify is the most complete user interface component library for Vue applications that follows the Google Material Design specs. Let’s quickly dive in and look at how you can get started.

Prerequisites

This guide is written for developers who have intermediate or advanced knowledge of Vue.js. If you have never used Vue.js to build applications

What is Vuetify?

Vuetify is an open source MIT project for building user interfaces for web and mobile applications. It is a project that is backed by sponsors and volunteers from the Vue community. The project is supported by a vibrant Discord community forum where you can ask JavaScript questions — even if they’re not about Vuetify. The development team is committed to fixing bugs and providing enhancements through consistent update cycles. There are also weekly patches to fix issues that the community raises.

Most open-source frontend libraries don’t get this level of attention. So you can be confident that when you start using Vuetify in your projects, you won’t be left hanging without support in the future. Vuetify supports all major browsers out of the box. Older browsers such as IE11 and Safari 9 can work too but will require babel-polyfill. Anything older than that is not supported. Vuetify is built to be semantic. This means that every component and prop name you learn will be easy to remember and re-use without frequently checking the documentation.

Vuetify also comes with free/premium themes and pre-made layouts you can use to quickly theme your application. At the time of writing, Vuetify v1.5.13 is the current version, which utilizes Material Design Spec v1. Version 2.x of Vuetify will utilize Material Design Spec v2 which will soon be made available. Let’s go over to the next section to see a couple of ways we can install Vuetify into our projects.

Installing Vuetify

If you already have an existing Vue project that was created with an older version of Vue CLI tool or some other way, you can simply install Vuetify as follows:

 npm install vuetify 

Update your index.js or main.js and include the following code:

import Vue from "vue"; 
import Vuetify from "vuetify"; 
import "vuetify/dist/vuetify.min.css"; 

Vue.use(Vuetify); 

You’ll also need to install Material Icons, which you can include as a link tag in your index.html file:

<head>
  <link href='https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons' rel="stylesheet">
</head


If you are starting a new project, installing Vuetify is very easy. Just follow these steps:

$ vue create vuetify-demo 
> 
$ cd vuetify-demo 
$ vue add vuetify 
$ ? Choose a preset: (Use arrow keys) 
$ > Default (recommended) 
$ Prototype (rapid development) 
$ Configure (advanced) 

When asked for a preset, just choose Default, which represents the a la carte system. Basically, this means when you build your application for deployment, only the used Vuetify components will get bundled, not the entire Vuetify library. This will help in drastically lowering your build size. You can also use Vue UI to install Vuetify in your project. Now that Vuetify is installed, let’s start using it.

The Basics

Right after adding Vuetify to our project, you will notice quite a number of changes to our project structure and code. Of importance to us now is App.vue.

<template>
  <v-app>
    <v-toolbar app dark class="indigo">
      <v-toolbar-title class="headline text-uppercase">
        <span>Vuetify &nbsp;</span>
        <span class="font-weight-light">MATERIAL DESIGN</span>
      </v-toolbar-title>
      <v-spacer></v-spacer>
      <v-btn
        flat
        href="https://github.com/vuetifyjs/vuetify/releases/latest"
        target="_blank"
      >
        <span class="mr-2">Latest Release</span>
      </v-btn>
    </v-toolbar>

    <v-content>
      <HelloWorld />
    </v-content>
  </v-app>
</template>


If you start the server and open localhost:8080, you should have the following view:

Notice how different the page looks now from the default starter page that is usually created with the Vue CLI create app command. This means Vuetify has been set up correctly. Let’s break down the Vuetify code, starting with this component:

<v-app> 
  <!-- put content here.... --> 
</v-app> 

The v-app component is a mandatory wrapper required for your application to work properly. It is used to determine grid breakpoints for the layout. It can exist anywhere inside the <body>, but must be a parent of all Vuetify components. The v-content component must be a direct descendant of v-app.

The next component that we will discuss is v-toolbar. This can be used as the primary toolbar for your application. You can place icons, menus and other items inside it.

<v-app> 
  <v-toolbar app> 
    <!-- put content here.... --> 
  </v-toolbar> 
</v-app> 

The first prop you’ll come across is app. This simply tells the toolbar to stick to the top when the user starts scrolling down. If you remove the app prop, the toolbar will scroll away with the rest of the page. Try it yourself and see what happens. We can further add more props to customize the appearance of our toolbar.

One thing you’ll come to realize with Vuetify is that you will hardly need to write any CSS code to customize the appearance of your app. However, if you want your application to support multiple themes, then you may need to define multiple stylesheets. Vuetify does provide a theme generator to help you pick a set of colors for your theme.

For now, let’s focus on customizing our app using props. The first one we are going to learn is called dark. Just update your code as follows:

<v-app> 
  <v-toolbar app dark> 
    <!-- put content here.... --> 
  </v-toolbar> 
</v-app> 

Your browser page should update as follows:

The dark prop simply changes the background to black and the text to white. Let’s use another prop called color:

<v-app> 
  <v-toolbar app dark color="red"> 
    <!-- put content here.... --> 
  </v-toolbar> 
</v-app> 

As expected, your browser page should update as follows:

Remove the dark prop and see what happens:

So what just happened? The text went back to the default color black. When you specify the color prop, it overrides the background color that was defined by the dark prop. To make the text white again, you can re-add the dark prop, or you can simply do this:

<v-app> 
  <v-toolbar app color="red white--text"> 
    <!-- put content here.... --> 
  </v-toolbar> 
</v-app> 

Your browser page should update as follows:

The text font color has changed to white, but the button component color has remain unchanged. You can add the prop dark or color="white--text to the button component to make it white. Instead of using the prop color, you can also use class and it will give you the same result. As rule of thumb, any color you specify on its own becomes the background color. To specify the font color, you need to append --text to the color name. Feel free to use any color that is not white or red — try orange, blue, green, etc. Let’s do something cool in the next step. Update the toolbar code as follows:

<v-app> 
  <v-toolbar app dark color="purple pink--text"> 
    <!-- put content here.... --> 
  </v-toolbar> 
</v-app> 

Your browser page should update as follows:

The text is not very legible, is it? One way of fixing that is by using colors that contrast each other. Another way we can fix it is to darken the background and lighten the foreground. Update the code as follows:

<v-app> 
  <v-toolbar app dark color="purple darken-4 pink--text text--lighten-3"> 
    <!-- put content here.... --> 
  </v-toolbar> 
</v-app> 

Your browser page should update as follows:

The text is much more legible now. To darken the background, you can use the values from darken-1 to darken-4. Each level increases the darkness. You can use values from lighten-1 to lighten-4 to lighten the background. If you want to change the text color, add text-- in front of the lighten or darken attributes — e.g. text--lighten-3. We also have accent-1 to accent-4 which seems to control saturation. accent-1 desaturates the color while accent-4 increases saturation and becomes more vivid.

Please note am not pulling these props and values from thin air. Here is the documentation for Vuetify colors.

Do not bother memorizing names of props or classes. Simply visit the Vuetify documentation and you’ll find what you are looking for. Here is the documentation for <a href="https://vuetifyjs.com/en/components/toolbars#api" target="_blank">v-toolbar</a>. Notice there are so many props we haven’t tried out, such as:

  • height
  • light
  • card
  • dense

Feel free to have fun with them all. See what they do. Please note that majority of Vuetify components share the same props such as color. Next, let’s briefly look at the grid system.

The Grid System

Vuetify uses a 12 point grid system to lay out an application’s content. It’s built using the CSS Flexbox Layout Module, which is a system for distributing items in a responsive layout structure without using floats or positions. The grid supports 5 media breakpoints targeting specific screen sizes or orientations.

For a practical demonstration, head over to components/HelloWorld.vue and take a look at the file. Below is a simplified version of the code:

<template>
  <v-container>
    <v-layout text-xs-center wrap>
      <v-flex xs12>
        <v-img
          :src="require('../assets/logo.svg')"
          class="my-3"
          contain
          height="200"
        ></v-img>
      </v-flex>

      <v-flex mb-4>
        <h1 class="display-2 font-weight-bold mb-3">Welcome to Vuetify</h1>
        <p class="subheading font-weight-regular">
          For help and collaboration with other Vuetify developers,
          <br />please join our online
          <a href="https://community.vuetifyjs.com" target="_blank"
            >Discord Community</a
          >
        </p>
      </v-flex>

      <v-flex mb-5 xs12>
        <h2 class="headline font-weight-bold mb-3">What's next?</h2>
        <v-layout justify-center>
          <a href="#" class="subheading mx-3">Explore Components</a>
          <a href="#" class="subheading mx-3">Select a layout</a>
          <a href="#" class="subheading mx-3">F.A.Q</a>
        </v-layout>
      </v-flex>
    </v-layout>
  </v-container>
</template>


The v-container component simply centers your content in the middle of the screen. If you add the fluid prop, your content will occupy the full width of the screen. v-layout is used to group content and align it. There’s a live demo of v-layout that’ll help you understand how it can be used. The v-flex component is basically a box of content that can occupy one or more columns.

We won’t go into detail on the Vuetify grid — it’s a topic that deserves its own article. If you are new to grids, you can check out our article, Introduction to CSS Grid Layout Modules. Otherwise, simply scroll down to the next section and learn how to setup routing and navigation in Vuetify.

Routing and Navigation

During installation, there is an option for installing the router package. If you did this, then you should have some files in the views folder. Confirm that the file router.js exists and has been set up correctly. Vuetify was built with vue-router in mind. Hence you will find that you don’t need to use the router-link component. A number of Vuetify components can act as route links by simply specifying the to prop.

Replace the code in App.vue with the following:

<template>

  <v-app>

    <!-- Start of Navigation -->

    <nav>

      <!-- Start of app toolbar -->

      <v-toolbar app>

        <v-toolbar-side-icon

          @click.stop="drawer = !drawer"

          class="hidden-md-and-up"

        ></v-toolbar-side-icon>

        <v-toolbar-title class="headline text-uppercase"

          >Vuetify Demo</v-toolbar-title

        >

        <v-spacer></v-spacer>

        <v-toolbar-items class="hidden-sm-and-down">

          <v-btn flat to="/" exact>Home</v-btn>

          <v-btn flat to="/about">About</v-btn>

        </v-toolbar-items>

      </v-toolbar>

      <!-- End of app toolbar -->

 

      <!-- Start of mobile side menu -->

      <v-navigation-drawer app v-model="drawer" right>

        <!-- Menu title -->

        <v-toolbar flat>

          <v-list>

            <v-list-tile>

              <v-list-tile-title class="title">Menu</v-list-tile-title>

            </v-list-tile>

          </v-list>

        </v-toolbar>

        <v-divider></v-divider>

        <!-- Menu Links -->

        <v-list>

          <v-list-tile to="/" exact>

            <v-list-tile-action>

              <v-icon>home</v-icon>

            </v-list-tile-action>

            <v-list-tile-content>Home</v-list-tile-content>

          </v-list-tile>

          <v-list-tile to="/about">

            <v-list-tile-action>

              <v-icon>description</v-icon>

            </v-list-tile-action>

            <v-list-tile-content>About</v-list-tile-content>

          </v-list-tile>

        </v-list>

      </v-navigation-drawer>

      <!-- End of mobile side menu -->

    </nav>

    <!-- End of Navigation -->

 

    <v-content>

      <!-- Display view pages here based on route -->

      <router-view></router-view>

    </v-content>

  </v-app>

</template>

 

<script>

  export default {

    name: "App",

    data() {

      return {

        drawer: false // Hide mobile side menu by default

      };

    }

  };

</script>

I’ve put comments in the code so that you can follow along. It would be wise to put menu items into an array data structure. However, for simplicity, I have left the code duplication intact so that you can understand the structure of Vuetify components easily. Below are links to documentations for some of the components we’ve just used:

In case you haven’t noticed, Vuetify automatically added a link to Material Icons in index.html. You can start accessing Material Icons right away. Next, replace the code in views/Home.vue with:

<template>
  <v-container>
    <v-layout>
      <h1>Home page</h1>
    </v-layout>
  </v-container>
</template>

Also, replace the code in views/About.vue with:

<template>
  <v-container>
    <v-layout>
      <v-flex xs12>
        <h1 class="display-1">About Page</h1>
        <p>
          Lorem ipsum dolor, sit amet consectetur adipisicing elit. Excepturi
          obcaecati tempora sunt debitis, minima deleniti ex inventore
          laboriosam at animi praesentium, quaerat corrupti molestiae recusandae
          corporis necessitatibus vitae, nam saepe?
        </p>
      </v-flex>
    </v-layout>
  </v-container>
</template>

After making the above changes, your browser should automatically update. Here’s how the app should look like in full desktop view:

When you resize the browser, the app should switch to the mobile view. This is how it should look with the side menu open:

I think it’s pretty incredible how we’ve built an attractive responsive web app with not many lines of code. Let’s finish up by building a LoginForm component in the next section.

Building the Login Form

Building the Login form is pretty straight forward. Create the file components/Login.vue and copy the following code:

<template>
  <v-layout align-center justify-center>
    <v-flex xs12 sm8 md4>
      <v-card class="elevation-12">
        <v-toolbar dark color="purple">
          <v-toolbar-title>Login Form</v-toolbar-title>
        </v-toolbar>
        <v-card-text>
          <v-form>
            <v-text-field
              prepend-icon="person"
              name="login"
              label="Login"
              id="login"
              type="text"
            ></v-text-field>
            <v-text-field
              prepend-icon="lock"
              name="password"
              label="Password"
              id="password"
              type="password"
            ></v-text-field>
          </v-form>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn dark color="pink">Login</v-btn>
        </v-card-actions>
      </v-card>
    </v-flex>
  </v-layout>
</template> 

I’ve used the following components to build the login screen:

  • <a href="https://vuetifyjs.com/en/components/cards" target="_blank">v-card</a>
  • <a href="https://vuetifyjs.com/en/components/forms#form" target="_blank">v-form</a>
  • <a href="https://vuetifyjs.com/en/components/buttons" target="_blank">v-btn</a>

Do take a look at each component’s documentation to see what else you can customize about them. Next update views/Home.vue as follows:

<template>
  <v-container>
    <v-layout>
      <h1>Home page</h1>
    </v-layout>
    <Login class="mt-5" />
  </v-container>
</template>
 
<script>
  import Login from "../components/Login";
 
  export default {
    components: {
      Login
    }
  };
</script>

If you are wondering what the class mt-5 means, it simply adds a margin-top of 48px. Check out the documentation for spacing to understand how it works in Vuetify. You can easily add preset margins and paddings in any direction on your content by specifying classes. Your home page should now display the following:

Summary

Now that you’ve come to the end of this introductory article, you should know that we’ve only scratched the surface. If you have previous experience using other CSS frameworks such as Bootstrap, you’ll find Vuetify very easy to use. In fact, you’ll find that Vuetify has a many more useful features and components than most popular CSS frameworks. If you are looking to build a web application with a completely custom look, Vuetify may not be right for you. Vuetify is for those who want to rapidly build a web interface using a design that is familiar to most people. Material Design is a popular system that has been implemented in every Android device that doesn’t come with a custom skin installed.

Vuetify can help you save time and money by using a highly researched frontend design. You don’t have to spend a lot time creating your own design language. You don’t even have to write CSS, other than declaring the default colors for your application theme.

I hope you enjoyed learning Vuetify, and that it’lll be your go to UI framework for building Vue.js applications in the future!

#vue-js #javascript #web-development

What is GEEK

Buddha Community

Building Frontend Using Vuetify
Chloe  Butler

Chloe Butler

1667425440

Pdf2gerb: Perl Script Converts PDF Files to Gerber format

pdf2gerb

Perl script converts PDF files to Gerber format

Pdf2Gerb generates Gerber 274X photoplotting and Excellon drill files from PDFs of a PCB. Up to three PDFs are used: the top copper layer, the bottom copper layer (for 2-sided PCBs), and an optional silk screen layer. The PDFs can be created directly from any PDF drawing software, or a PDF print driver can be used to capture the Print output if the drawing software does not directly support output to PDF.

The general workflow is as follows:

  1. Design the PCB using your favorite CAD or drawing software.
  2. Print the top and bottom copper and top silk screen layers to a PDF file.
  3. Run Pdf2Gerb on the PDFs to create Gerber and Excellon files.
  4. Use a Gerber viewer to double-check the output against the original PCB design.
  5. Make adjustments as needed.
  6. Submit the files to a PCB manufacturer.

Please note that Pdf2Gerb does NOT perform DRC (Design Rule Checks), as these will vary according to individual PCB manufacturer conventions and capabilities. Also note that Pdf2Gerb is not perfect, so the output files must always be checked before submitting them. As of version 1.6, Pdf2Gerb supports most PCB elements, such as round and square pads, round holes, traces, SMD pads, ground planes, no-fill areas, and panelization. However, because it interprets the graphical output of a Print function, there are limitations in what it can recognize (or there may be bugs).

See docs/Pdf2Gerb.pdf for install/setup, config, usage, and other info.


pdf2gerb_cfg.pm

#Pdf2Gerb config settings:
#Put this file in same folder/directory as pdf2gerb.pl itself (global settings),
#or copy to another folder/directory with PDFs if you want PCB-specific settings.
#There is only one user of this file, so we don't need a custom package or namespace.
#NOTE: all constants defined in here will be added to main namespace.
#package pdf2gerb_cfg;

use strict; #trap undef vars (easier debug)
use warnings; #other useful info (easier debug)


##############################################################################################
#configurable settings:
#change values here instead of in main pfg2gerb.pl file

use constant WANT_COLORS => ($^O !~ m/Win/); #ANSI colors no worky on Windows? this must be set < first DebugPrint() call

#just a little warning; set realistic expectations:
#DebugPrint("${\(CYAN)}Pdf2Gerb.pl ${\(VERSION)}, $^O O/S\n${\(YELLOW)}${\(BOLD)}${\(ITALIC)}This is EXPERIMENTAL software.  \nGerber files MAY CONTAIN ERRORS.  Please CHECK them before fabrication!${\(RESET)}", 0); #if WANT_DEBUG

use constant METRIC => FALSE; #set to TRUE for metric units (only affect final numbers in output files, not internal arithmetic)
use constant APERTURE_LIMIT => 0; #34; #max #apertures to use; generate warnings if too many apertures are used (0 to not check)
use constant DRILL_FMT => '2.4'; #'2.3'; #'2.4' is the default for PCB fab; change to '2.3' for CNC

use constant WANT_DEBUG => 0; #10; #level of debug wanted; higher == more, lower == less, 0 == none
use constant GERBER_DEBUG => 0; #level of debug to include in Gerber file; DON'T USE FOR FABRICATION
use constant WANT_STREAMS => FALSE; #TRUE; #save decompressed streams to files (for debug)
use constant WANT_ALLINPUT => FALSE; #TRUE; #save entire input stream (for debug ONLY)

#DebugPrint(sprintf("${\(CYAN)}DEBUG: stdout %d, gerber %d, want streams? %d, all input? %d, O/S: $^O, Perl: $]${\(RESET)}\n", WANT_DEBUG, GERBER_DEBUG, WANT_STREAMS, WANT_ALLINPUT), 1);
#DebugPrint(sprintf("max int = %d, min int = %d\n", MAXINT, MININT), 1); 

#define standard trace and pad sizes to reduce scaling or PDF rendering errors:
#This avoids weird aperture settings and replaces them with more standardized values.
#(I'm not sure how photoplotters handle strange sizes).
#Fewer choices here gives more accurate mapping in the final Gerber files.
#units are in inches
use constant TOOL_SIZES => #add more as desired
(
#round or square pads (> 0) and drills (< 0):
    .010, -.001,  #tiny pads for SMD; dummy drill size (too small for practical use, but needed so StandardTool will use this entry)
    .031, -.014,  #used for vias
    .041, -.020,  #smallest non-filled plated hole
    .051, -.025,
    .056, -.029,  #useful for IC pins
    .070, -.033,
    .075, -.040,  #heavier leads
#    .090, -.043,  #NOTE: 600 dpi is not high enough resolution to reliably distinguish between .043" and .046", so choose 1 of the 2 here
    .100, -.046,
    .115, -.052,
    .130, -.061,
    .140, -.067,
    .150, -.079,
    .175, -.088,
    .190, -.093,
    .200, -.100,
    .220, -.110,
    .160, -.125,  #useful for mounting holes
#some additional pad sizes without holes (repeat a previous hole size if you just want the pad size):
    .090, -.040,  #want a .090 pad option, but use dummy hole size
    .065, -.040, #.065 x .065 rect pad
    .035, -.040, #.035 x .065 rect pad
#traces:
    .001,  #too thin for real traces; use only for board outlines
    .006,  #minimum real trace width; mainly used for text
    .008,  #mainly used for mid-sized text, not traces
    .010,  #minimum recommended trace width for low-current signals
    .012,
    .015,  #moderate low-voltage current
    .020,  #heavier trace for power, ground (even if a lighter one is adequate)
    .025,
    .030,  #heavy-current traces; be careful with these ones!
    .040,
    .050,
    .060,
    .080,
    .100,
    .120,
);
#Areas larger than the values below will be filled with parallel lines:
#This cuts down on the number of aperture sizes used.
#Set to 0 to always use an aperture or drill, regardless of size.
use constant { MAX_APERTURE => max((TOOL_SIZES)) + .004, MAX_DRILL => -min((TOOL_SIZES)) + .004 }; #max aperture and drill sizes (plus a little tolerance)
#DebugPrint(sprintf("using %d standard tool sizes: %s, max aper %.3f, max drill %.3f\n", scalar((TOOL_SIZES)), join(", ", (TOOL_SIZES)), MAX_APERTURE, MAX_DRILL), 1);

#NOTE: Compare the PDF to the original CAD file to check the accuracy of the PDF rendering and parsing!
#for example, the CAD software I used generated the following circles for holes:
#CAD hole size:   parsed PDF diameter:      error:
#  .014                .016                +.002
#  .020                .02267              +.00267
#  .025                .026                +.001
#  .029                .03167              +.00267
#  .033                .036                +.003
#  .040                .04267              +.00267
#This was usually ~ .002" - .003" too big compared to the hole as displayed in the CAD software.
#To compensate for PDF rendering errors (either during CAD Print function or PDF parsing logic), adjust the values below as needed.
#units are pixels; for example, a value of 2.4 at 600 dpi = .0004 inch, 2 at 600 dpi = .0033"
use constant
{
    HOLE_ADJUST => -0.004 * 600, #-2.6, #holes seemed to be slightly oversized (by .002" - .004"), so shrink them a little
    RNDPAD_ADJUST => -0.003 * 600, #-2, #-2.4, #round pads seemed to be slightly oversized, so shrink them a little
    SQRPAD_ADJUST => +0.001 * 600, #+.5, #square pads are sometimes too small by .00067, so bump them up a little
    RECTPAD_ADJUST => 0, #(pixels) rectangular pads seem to be okay? (not tested much)
    TRACE_ADJUST => 0, #(pixels) traces seemed to be okay?
    REDUCE_TOLERANCE => .001, #(inches) allow this much variation when reducing circles and rects
};

#Also, my CAD's Print function or the PDF print driver I used was a little off for circles, so define some additional adjustment values here:
#Values are added to X/Y coordinates; units are pixels; for example, a value of 1 at 600 dpi would be ~= .002 inch
use constant
{
    CIRCLE_ADJUST_MINX => 0,
    CIRCLE_ADJUST_MINY => -0.001 * 600, #-1, #circles were a little too high, so nudge them a little lower
    CIRCLE_ADJUST_MAXX => +0.001 * 600, #+1, #circles were a little too far to the left, so nudge them a little to the right
    CIRCLE_ADJUST_MAXY => 0,
    SUBST_CIRCLE_CLIPRECT => FALSE, #generate circle and substitute for clip rects (to compensate for the way some CAD software draws circles)
    WANT_CLIPRECT => TRUE, #FALSE, #AI doesn't need clip rect at all? should be on normally?
    RECT_COMPLETION => FALSE, #TRUE, #fill in 4th side of rect when 3 sides found
};

#allow .012 clearance around pads for solder mask:
#This value effectively adjusts pad sizes in the TOOL_SIZES list above (only for solder mask layers).
use constant SOLDER_MARGIN => +.012; #units are inches

#line join/cap styles:
use constant
{
    CAP_NONE => 0, #butt (none); line is exact length
    CAP_ROUND => 1, #round cap/join; line overhangs by a semi-circle at either end
    CAP_SQUARE => 2, #square cap/join; line overhangs by a half square on either end
    CAP_OVERRIDE => FALSE, #cap style overrides drawing logic
};
    
#number of elements in each shape type:
use constant
{
    RECT_SHAPELEN => 6, #x0, y0, x1, y1, count, "rect" (start, end corners)
    LINE_SHAPELEN => 6, #x0, y0, x1, y1, count, "line" (line seg)
    CURVE_SHAPELEN => 10, #xstart, ystart, x0, y0, x1, y1, xend, yend, count, "curve" (bezier 2 points)
    CIRCLE_SHAPELEN => 5, #x, y, 5, count, "circle" (center + radius)
};
#const my %SHAPELEN =
#Readonly my %SHAPELEN =>
our %SHAPELEN =
(
    rect => RECT_SHAPELEN,
    line => LINE_SHAPELEN,
    curve => CURVE_SHAPELEN,
    circle => CIRCLE_SHAPELEN,
);

#panelization:
#This will repeat the entire body the number of times indicated along the X or Y axes (files grow accordingly).
#Display elements that overhang PCB boundary can be squashed or left as-is (typically text or other silk screen markings).
#Set "overhangs" TRUE to allow overhangs, FALSE to truncate them.
#xpad and ypad allow margins to be added around outer edge of panelized PCB.
use constant PANELIZE => {'x' => 1, 'y' => 1, 'xpad' => 0, 'ypad' => 0, 'overhangs' => TRUE}; #number of times to repeat in X and Y directions

# Set this to 1 if you need TurboCAD support.
#$turboCAD = FALSE; #is this still needed as an option?

#CIRCAD pad generation uses an appropriate aperture, then moves it (stroke) "a little" - we use this to find pads and distinguish them from PCB holes. 
use constant PAD_STROKE => 0.3; #0.0005 * 600; #units are pixels
#convert very short traces to pads or holes:
use constant TRACE_MINLEN => .001; #units are inches
#use constant ALWAYS_XY => TRUE; #FALSE; #force XY even if X or Y doesn't change; NOTE: needs to be TRUE for all pads to show in FlatCAM and ViewPlot
use constant REMOVE_POLARITY => FALSE; #TRUE; #set to remove subtractive (negative) polarity; NOTE: must be FALSE for ground planes

#PDF uses "points", each point = 1/72 inch
#combined with a PDF scale factor of .12, this gives 600 dpi resolution (1/72 * .12 = 600 dpi)
use constant INCHES_PER_POINT => 1/72; #0.0138888889; #multiply point-size by this to get inches

# The precision used when computing a bezier curve. Higher numbers are more precise but slower (and generate larger files).
#$bezierPrecision = 100;
use constant BEZIER_PRECISION => 36; #100; #use const; reduced for faster rendering (mainly used for silk screen and thermal pads)

# Ground planes and silk screen or larger copper rectangles or circles are filled line-by-line using this resolution.
use constant FILL_WIDTH => .01; #fill at most 0.01 inch at a time

# The max number of characters to read into memory
use constant MAX_BYTES => 10 * M; #bumped up to 10 MB, use const

use constant DUP_DRILL1 => TRUE; #FALSE; #kludge: ViewPlot doesn't load drill files that are too small so duplicate first tool

my $runtime = time(); #Time::HiRes::gettimeofday(); #measure my execution time

print STDERR "Loaded config settings from '${\(__FILE__)}'.\n";
1; #last value must be truthful to indicate successful load


#############################################################################################
#junk/experiment:

#use Package::Constants;
#use Exporter qw(import); #https://perldoc.perl.org/Exporter.html

#my $caller = "pdf2gerb::";

#sub cfg
#{
#    my $proto = shift;
#    my $class = ref($proto) || $proto;
#    my $settings =
#    {
#        $WANT_DEBUG => 990, #10; #level of debug wanted; higher == more, lower == less, 0 == none
#    };
#    bless($settings, $class);
#    return $settings;
#}

#use constant HELLO => "hi there2"; #"main::HELLO" => "hi there";
#use constant GOODBYE => 14; #"main::GOODBYE" => 12;

#print STDERR "read cfg file\n";

#our @EXPORT_OK = Package::Constants->list(__PACKAGE__); #https://www.perlmonks.org/?node_id=1072691; NOTE: "_OK" skips short/common names

#print STDERR scalar(@EXPORT_OK) . " consts exported:\n";
#foreach(@EXPORT_OK) { print STDERR "$_\n"; }
#my $val = main::thing("xyz");
#print STDERR "caller gave me $val\n";
#foreach my $arg (@ARGV) { print STDERR "arg $arg\n"; }

Download Details:

Author: swannman
Source Code: https://github.com/swannman/pdf2gerb

License: GPL-3.0 license

#perl 

Why Use WordPress? What Can You Do With WordPress?

Can you use WordPress for anything other than blogging? To your surprise, yes. WordPress is more than just a blogging tool, and it has helped thousands of websites and web applications to thrive. The use of WordPress powers around 40% of online projects, and today in our blog, we would visit some amazing uses of WordPress other than blogging.
What Is The Use Of WordPress?

WordPress is the most popular website platform in the world. It is the first choice of businesses that want to set a feature-rich and dynamic Content Management System. So, if you ask what WordPress is used for, the answer is – everything. It is a super-flexible, feature-rich and secure platform that offers everything to build unique websites and applications. Let’s start knowing them:

1. Multiple Websites Under A Single Installation
WordPress Multisite allows you to develop multiple sites from a single WordPress installation. You can download WordPress and start building websites you want to launch under a single server. Literally speaking, you can handle hundreds of sites from one single dashboard, which now needs applause.
It is a highly efficient platform that allows you to easily run several websites under the same login credentials. One of the best things about WordPress is the themes it has to offer. You can simply download them and plugin for various sites and save space on sites without losing their speed.

2. WordPress Social Network
WordPress can be used for high-end projects such as Social Media Network. If you don’t have the money and patience to hire a coder and invest months in building a feature-rich social media site, go for WordPress. It is one of the most amazing uses of WordPress. Its stunning CMS is unbeatable. And you can build sites as good as Facebook or Reddit etc. It can just make the process a lot easier.
To set up a social media network, you would have to download a WordPress Plugin called BuddyPress. It would allow you to connect a community page with ease and would provide all the necessary features of a community or social media. It has direct messaging, activity stream, user groups, extended profiles, and so much more. You just have to download and configure it.
If BuddyPress doesn’t meet all your needs, don’t give up on your dreams. You can try out WP Symposium or PeepSo. There are also several themes you can use to build a social network.

3. Create A Forum For Your Brand’s Community
Communities are very important for your business. They help you stay in constant connection with your users and consumers. And allow you to turn them into a loyal customer base. Meanwhile, there are many good technologies that can be used for building a community page – the good old WordPress is still the best.
It is the best community development technology. If you want to build your online community, you need to consider all the amazing features you get with WordPress. Plugins such as BB Press is an open-source, template-driven PHP/ MySQL forum software. It is very simple and doesn’t hamper the experience of the website.
Other tools such as wpFoRo and Asgaros Forum are equally good for creating a community blog. They are lightweight tools that are easy to manage and integrate with your WordPress site easily. However, there is only one tiny problem; you need to have some technical knowledge to build a WordPress Community blog page.

4. Shortcodes
Since we gave you a problem in the previous section, we would also give you a perfect solution for it. You might not know to code, but you have shortcodes. Shortcodes help you execute functions without having to code. It is an easy way to build an amazing website, add new features, customize plugins easily. They are short lines of code, and rather than memorizing multiple lines; you can have zero technical knowledge and start building a feature-rich website or application.
There are also plugins like Shortcoder, Shortcodes Ultimate, and the Basics available on WordPress that can be used, and you would not even have to remember the shortcodes.

5. Build Online Stores
If you still think about why to use WordPress, use it to build an online store. You can start selling your goods online and start selling. It is an affordable technology that helps you build a feature-rich eCommerce store with WordPress.
WooCommerce is an extension of WordPress and is one of the most used eCommerce solutions. WooCommerce holds a 28% share of the global market and is one of the best ways to set up an online store. It allows you to build user-friendly and professional online stores and has thousands of free and paid extensions. Moreover as an open-source platform, and you don’t have to pay for the license.
Apart from WooCommerce, there are Easy Digital Downloads, iThemes Exchange, Shopify eCommerce plugin, and so much more available.

6. Security Features
WordPress takes security very seriously. It offers tons of external solutions that help you in safeguarding your WordPress site. While there is no way to ensure 100% security, it provides regular updates with security patches and provides several plugins to help with backups, two-factor authorization, and more.
By choosing hosting providers like WP Engine, you can improve the security of the website. It helps in threat detection, manage patching and updates, and internal security audits for the customers, and so much more.

Read More

#use of wordpress #use wordpress for business website #use wordpress for website #what is use of wordpress #why use wordpress #why use wordpress to build a website

Hire Frontend Developers

Create a new web app or revamp your existing website?

Every existing website or a web application that we see with an interactive and user-friendly interface are from Front-End developers who ensure that all visual effects come into existence. Hence, to build a visually appealing web app front-end development is required.

At HourlyDeveloper.io, you can Hire FrontEnd Developers as we have been actively working on new frontend development as well as frontend re-engineering projects from older technologies to newer.

Consult with experts: https://bit.ly/2YLhmFZ

#hire frontend developers #frontend developers #frontend development company #frontend development services #frontend development #frontend

Using Singular Value Separation in Python and Numpy (linalg.svd)

In this pythonn - Numpy tutorial we will learn about Numpy linalg.svd: Singular Value Decomposition in Python. In mathematics, a singular value decomposition (SVD) of a matrix refers to the factorization of a matrix into three separate matrices. It is a more generalized version of an eigenvalue decomposition of matrices. It is further related to the polar decompositions.

In Python, it is easy to calculate the singular decomposition of a complex or a real matrix using the numerical python or the numpy library. The numpy library consists of various linear algebraic functions including one for calculating the singular value decomposition of a matrix.

In machine learning models, singular value decomposition is widely used to train models and in neural networks. It helps in improving accuracy and in reducing the noise in data. Singular value decomposition transforms one vector into another without them necessarily having the same dimension. Hence, it makes matrix manipulation in vector spaces easier and efficient. It is also used in regression analysis.

Syntax of Numpy linalg.svd() function

The function that calculates the singular value decomposition of a matrix in python belongs to the numpy module, named linalg.svd() .

The syntax of the numpy linalg.svd () is as follows:

numpy.linalg.svd(A, full_matrices=True, compute_uv=True, hermitian=False)

You can customize the true and false boolean values based on your requirements.

The parameters of the function are given below:

  • A->array_like: This is the required matrix whose singular value decomposition is being calculated. It can be real or complex as required. It’s dimension should be >= 2.
  • full_matrices->boolean value(optional): If set to true, then the Hermitian transpose of the given matrix is a square, if it’s false then it isn’t.
  • compute_uv->boolen value(optional): It determines whether the Hermitian transpose is to be calculated or not in addition to the singular value decomposition.
  • hermitian->boolean value(optional): The given matrix is considered hermitian(that is symmetric, with real values) which might provide a more efficient method for computation.

The function returns three types of matrices based on the parameters mentioned above:

  • S->array_like: The vector containing the singular values in the descending order with dimensions same as the original matrix.
  • u->array_like: This is an optional solution that is returned when compute_uv is set to True. It is a set of vectors with singular values.
  • v-> array_like: Set of unitary arrays only returned when compute_uv is set to True.

It raises a LinALgError when the singular values diverse.

Prerequisites for setup

Before we dive into the examples, make sure you have the numpy module installed in your local system. This is required for using linear algebraic functions like the one discussed in this article. Run the following command in your terminal.

pip install numpy

That’s all you need right now, let’s look at how we will implement the code in the next section.

To calculate Singular Value Decomposition (SVD) in Python, use the NumPy library’s linalg.svd() function. Its syntax is numpy.linalg.svd(A, full_matrices=True, compute_uv=True, hermitian=False), where A is the matrix for which SVD is being calculated. It returns three matrices: S, U, and V.

Example 1: Calculating the Singular Value Decomposition of a 3×3 Matrix

In this first example we will take a 3X3 matrix and compute its singular value decomposition in the following way:

#importing the numpy module
import numpy as np
#using the numpy.array() function to create an array
A=np.array([[2,4,6],
       [8,10,12],
       [14,16,18]])
#calculatin all three matrices for the output
#using the numpy linalg.svd function
u,s,v=np.linalg.svd(A, compute_uv=True)
#displaying the result
print("the output is=")
print('s(the singular value) = ',s)
print('u = ',u)
print('v = ',v)

The output will be:

the output is=
s(the singular value) =  [3.36962067e+01 2.13673903e+00 8.83684950e-16]
u =  [[-0.21483724  0.88723069  0.40824829]
 [-0.52058739  0.24964395 -0.81649658]
 [-0.82633754 -0.38794278  0.40824829]]
v =  [[-0.47967118 -0.57236779 -0.66506441]
 [-0.77669099 -0.07568647  0.62531805]
 [-0.40824829  0.81649658 -0.40824829]]

Example 1

Example 1

Example 2: Calculating the Singular Value Decomposition of a Random Matrix

In this example, we will be using the numpy.random.randint() function to create a random matrix. Let’s get into it!

#importing the numpy module
import numpy as np
#using the numpy.array() function to craete an array
A=np.random.randint(5, 200, size=(3,3))
#display the created matrix
print("The input matrix is=",A)
#calculatin all three matrices for the output
#using the numpy linalg.svd function
u,s,v=np.linalg.svd(A, compute_uv=True)
#displaying the result
print("the output is=")
print('s(the singular value) = ',s)
print('u = ',u)
print('v = ',v)

The output will be as follows:

The input matrix is= [[ 36  74 101]
 [104 129 185]
 [139 121 112]]
the output is=
s(the singular value) =  [348.32979681  61.03199722  10.12165841]
u =  [[-0.3635535  -0.48363012 -0.79619769]
 [-0.70916514 -0.41054007  0.57318554]
 [-0.60408084  0.77301925 -0.19372034]]
v =  [[-0.49036384 -0.54970618 -0.67628871]
 [ 0.77570499  0.0784348  -0.62620264]
 [ 0.39727203 -0.83166766  0.38794824]]

Example 2

Example 2

Suggested: Numpy linalg.eigvalsh: A Guide to Eigenvalue Computation.

Wrapping Up

In this article, we explored the concept of singular value decomposition in mathematics and how to calculate it using Python’s numpy module. We used the linalg.svd() function to compute the singular value decomposition of both given and random matrices. Numpy provides an efficient and easy-to-use method for performing linear algebra operations, making it highly valuable in machine learning, neural networks, and regression analysis. Keep exploring other linear algebraic functions in numpy to enhance your mathematical toolset in Python.

Article source at: https://www.askpython.com

#python #numpy 

Разделение единственного числа в Python и Numpy (linalg.svd)

В этом руководстве по pythonn — Numpy мы узнаем о Numpy linalg.svd: разложение по единственному значению в Python. В математике разложение матрицы по сингулярным числам (SVD) относится к разложению матрицы на три отдельные матрицы. Это более обобщенная версия разложения матриц по собственным значениям. Это также связано с полярными разложениями.

В Python легко вычислить сингулярное разложение сложной или вещественной матрицы, используя числовой python или библиотеку numpy. Библиотека numpy состоит из различных линейных алгебраических функций, включая функцию для вычисления разложения матрицы по сингулярным числам.

В моделях машинного обучения разложение по сингулярным числам широко используется для обучения моделей и в нейронных сетях. Это помогает повысить точность и уменьшить шум в данных. Разложение по сингулярным значениям преобразует один вектор в другой, при этом они не обязательно имеют одинаковую размерность. Следовательно, это делает матричные операции в векторных пространствах более простыми и эффективными. Он также используется в регрессионном анализе .

Синтаксис функции Numpy linalg.svd()

Функция, которая вычисляет разложение матрицы по сингулярным числам в python, принадлежит модулю numpy с именем linalg.svd() .

Синтаксис numpy linalg.svd() следующий:

numpy.linalg.svd(A, full_matrices=True, compute_uv=True, hermitian=False)

Вы можете настроить истинные и ложные логические значения в соответствии с вашими требованиями.

Параметры функции приведены ниже:

  • A->array_like: это требуемая матрица, для которой вычисляется разложение по сингулярным числам. Он может быть реальным или сложным по мере необходимости. Его размер должен быть >= 2.
  • full_matrices->boolean value(необязательно): если установлено значение true, то эрмитовское транспонирование данной матрицы является квадратом, если оно false, то это не так.
  • calculate_uv->boolen value (необязательно): определяет, следует ли вычислять эрмитову транспонирование в дополнение к разложению по сингулярным значениям.
  • hermitian->boolean value(необязательно): Данная матрица считается эрмитовой (то есть симметричной, с действительными значениями), что может обеспечить более эффективный метод вычислений.

Функция возвращает три типа матриц на основе указанных выше параметров:

  • S->array_like : вектор, содержащий сингулярные значения в порядке убывания с размерами, такими же, как исходная матрица.
  • u->array_like : это необязательное решение, которое возвращается, когда для параметра calculate_uv установлено значение True. Это набор векторов с сингулярными значениями.
  • v-> array_like : Набор унитарных массивов возвращается только в том случае, если для параметра calculate_uv установлено значение True.

Он вызывает LinALgError , когда сингулярные значения различаются.

Предварительные условия для настройки

Прежде чем мы углубимся в примеры, убедитесь, что в вашей локальной системе установлен модуль numpy. Это необходимо для использования линейных алгебраических функций, подобных той, что обсуждается в этой статье. Запустите следующую команду в своем терминале.

pip install numpy

Это все, что вам нужно прямо сейчас, давайте посмотрим, как мы будем реализовывать код в следующем разделе.

Чтобы вычислить разложение по сингулярным значениям (SVD) в Python, используйте функцию linalg.svd() из библиотеки NumPy. Его синтаксис таков: numpy.linalg.svd(A, full_matrices=True, calculate_uv=True, hermitian=False), где A — матрица, для которой вычисляется SVD. Он возвращает три матрицы: S, U и V.

Пример 1. Вычисление сингулярного разложения матрицы 3×3

В этом первом примере мы возьмем матрицу 3X3 и вычислим ее разложение по сингулярным числам следующим образом:

#importing the numpy module
import numpy as np
#using the numpy.array() function to create an array
A=np.array([[2,4,6],
       [8,10,12],
       [14,16,18]])
#calculatin all three matrices for the output
#using the numpy linalg.svd function
u,s,v=np.linalg.svd(A, compute_uv=True)
#displaying the result
print("the output is=")
print('s(the singular value) = ',s)
print('u = ',u)
print('v = ',v)

Вывод будет:

the output is=
s(the singular value) =  [3.36962067e+01 2.13673903e+00 8.83684950e-16]
u =  [[-0.21483724  0.88723069  0.40824829]
 [-0.52058739  0.24964395 -0.81649658]
 [-0.82633754 -0.38794278  0.40824829]]
v =  [[-0.47967118 -0.57236779 -0.66506441]
 [-0.77669099 -0.07568647  0.62531805]
 [-0.40824829  0.81649658 -0.40824829]]

Пример 1

Пример 1

Пример 2. Вычисление сингулярного разложения случайной матрицы

В этом примере мы будем использовать функцию numpy.random.randint() для создания случайной матрицы. Давайте погрузимся в это!

#importing the numpy module
import numpy as np
#using the numpy.array() function to craete an array
A=np.random.randint(5, 200, size=(3,3))
#display the created matrix
print("The input matrix is=",A)
#calculatin all three matrices for the output
#using the numpy linalg.svd function
u,s,v=np.linalg.svd(A, compute_uv=True)
#displaying the result
print("the output is=")
print('s(the singular value) = ',s)
print('u = ',u)
print('v = ',v)

Вывод будет следующим:

The input matrix is= [[ 36  74 101]
 [104 129 185]
 [139 121 112]]
the output is=
s(the singular value) =  [348.32979681  61.03199722  10.12165841]
u =  [[-0.3635535  -0.48363012 -0.79619769]
 [-0.70916514 -0.41054007  0.57318554]
 [-0.60408084  0.77301925 -0.19372034]]
v =  [[-0.49036384 -0.54970618 -0.67628871]
 [ 0.77570499  0.0784348  -0.62620264]
 [ 0.39727203 -0.83166766  0.38794824]]

Пример 2

Пример 2

Предложено: Numpy linalg.eigvalsh: руководство по вычислению собственных значений .

Подведение итогов

В этой статье мы рассмотрели концепцию разложения по сингулярным числам в математике и способы ее вычисления с помощью модуля Python numpy. Мы использовали функцию linalg.svd() для вычисления разложения по сингулярным числам как заданных, так и случайных матриц. Numpy предоставляет эффективный и простой в использовании метод выполнения операций линейной алгебры, что делает его очень ценным для машинного обучения, нейронных сетей и регрессионного анализа. Продолжайте изучать другие линейные алгебраические функции в numpy, чтобы расширить свой набор математических инструментов в Python.

Источник статьи: https://www.askpython.com

#python #numpy