Make div fill height but not extend it (use scrollbar for overflow)

I have a specific layout that I want to achieve on my web page, namely: 

The layout in the above image is built with the following HTML and bootstrap classes:

        <div className="ContentWrapper d-flex mh-100 flex-row h-100">
            <div className="ContentBody flex-column flex-fill">
                <div className="ContentHeader p-3 w-100">
                    <h2>Header</h2>
                </div>
                <div className="ContentMain w-100">
                    <h2>Scrollable div, should fill height, but not more than that</h2>
                </div>
            </div>
            <div className="Sidebar h-100">
                <h2>Sidebar content</h2>
            </div>
        </div>

Relevant CSS:

.ContentWrapper {
    background-color: red;
}

.ContentBody {
background-color: blue;
}

.ContentHeader {
background-color: yellow;
}

.ContentMain {
background-color: purple;
flex: 1;
}

.Sidebar {
background-color: green;
width: 500px;
}

However, when there is too much content in the purple part, the component starts to increase in height. I wish to prevent that and have a scrollbar in the purple component.

Furthermore, I heard that some flex properties work different in Chrome and Firefox. The idea is that I want my web page to have the same behavior in both browsers.

#html #css #css3 #bootstrap

What is GEEK

Buddha Community

Toby Rogers

1552031594

You can remove h-100 on ContentWrapper and add height: 100vh to it. Make your ContentBody a flexbox by adding `d-flex- class. See demo below with explanations:

.ContentWrapper {
  background-color: red;
  height: 100vh; /* ADDED */
}

.ContentBody {
  background-color: blue;
}

.ContentHeader {
  background-color: yellow;
}

.ContentMain {
  background-color: purple;
  flex: 1;
  overflow-y: auto; /* ADDED */
}

.Sidebar {
  background-color: green;
  width: 500px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<div class="ContentWrapper d-flex mh-100 flex-row"> <!-- removed h-100 class -->
  <div class="ContentBody d-flex flex-column flex-fill"> <!-- added d-flex class -->
    <div class="ContentHeader p-3 w-100">
      <h2>Header</h2>
    </div>
    <div class="ContentMain w-100">
      <h2>Scrollable div, should fill height, but not more than that</h2>
    </div>
  </div>
  <div class="Sidebar h-100">
    <h2>Sidebar content</h2>
  </div>
</div>

Adam Daniels

1552031763

Just find already have an answer there… Whatever put the codepen i just finished, which i think it is a more flexbox way.

<div class="ContentWrapper d-flex mh-100 flex-row h-100">
  <div class="ContentBody flex-column flex-fill d-flex">
    <div class="ContentHeader p-3 w-100">
      <h2>Header</h2>
    </div>
    <div class="ContentMain w-100 flex-fill overflow-auto">
      <h2>Scrollable div
    </h2>
    </div>
  </div>
  <div class="Sidebar h-100 flex-shrink-0">
    <h2>Sidebar content</h2>
  </div>
</div>

https://codepen.io/ramseyfeng/pen/drWNYQ

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 

Как проверить, существует ли имя пользователя с помощью AngularJS

Всегда лучше проверить, существует или нет введенное имя пользователя, если вы разрешаете пользователям выбирать имя пользователя при регистрации и хотите, чтобы оно было уникальным.

При этом пользователь сразу узнает, доступно ли выбранное им имя пользователя или нет.

1. Структура таблицы

Я использую usersтаблицу в учебном примере.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `password` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Конфигурация

Создайте новый config.phpфайл.

Завершенный код

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

3. HTML

Создание базового макета регистрационной формы с тремя элементами ввода и кнопкой.

  • Определена ng-keyupдиректива для поля ввода имени пользователя, которая вызывает checkUsername().
  • Добавьте <div >следующее поле ввода имени пользователя, чтобы показать доступный статус и настроить классы в директиве <div>определения ng-class.

Завершенный код

<body ng-app='myapp'>

 <div class="container" ng-controller='signup'>

  <div id="div_reg">
   <h1>Registration</h1>

   <div>
    <input type="text" class="textbox" id="txt_name" ng-model="name" placeholder="Name"/>
   </div>

   <!-- Username -->
   <div>
    <input type="text" class="textbox" id="txt_uname" ng-model="username" ng-keyup='checkUsername()' placeholder="Username" />
    <div ng-class="addClass(unamestatus)" >{{ unamestatus }}</div>
   </div>

   <div>
    <input type="password" class="textbox" id="txt_pwd" ng-model="password" placeholder="Password"/>
   </div>

   <div>
    <input type="submit" value="Submit" name="but_submit" id="but_submit" />
   </div>

  </div>

 </div>

</body>

4. CSS

/* Container */
.container{
 margin: 0 auto;
 width: 70%;
}

/* Registration */
#div_reg{
 border: 1px solid gray;
 border-radius: 3px;
 width: 470px;
 height: 370px;
 box-shadow: 0px 2px 2px 0px gray;
 margin: 0 auto;
}

#div_reg h1{
 margin-top:0px;
 font-weight: normal;
 padding:10px;
 background-color:cornflowerblue;
 color:white;
 font-family:sans-serif;
}

#div_reg div{
 clear: both;
 margin-top: 10px;
 padding: 5px;
}

#div_reg .textbox{
 width: 96%;
 padding: 7px;
}

#div_reg input[type=submit]{
 padding: 7px;
 width: 100px;
 background-color: lightseagreen;
 border: 0px;
 color: white;
}

/* Response */
.response{
 padding: 6px;
 display: block;
}
.hide{
 display: none;
}
.exists{
 color: green;
}

.not-exists{
 color: red;
}

5. PHP

Создать новый uname_check.php.

Здесь проверьте значение имени пользователя POST в usersтаблице и верните ответ.

Завершенный код

<?php

include 'config.php';

$data = json_decode(file_get_contents("php://input"));

// Username
$uname = $data->username;
 
$resText = '';

if($uname != ''){
 // Check username
 $sel = mysqli_query($con,"select count(*) as allcount from users where username = '".$uname."' ");
 $row = mysqli_fetch_array($sel);

 $resText = "Available";
 if($row['allcount'] > 0){
  $resText = 'Not available';
 }
}

echo $resText;

6. Скрипт

Определены два метода –

  • checkUsername —  отправить $httpзапрос на проверку существования имени пользователя и инициализировать его  $scope.unamestatusс помощью response.data.
  • addClass —  возвращает имена классов в соответствии со  unamestatus значением.

Завершенный код

var fetch = angular.module('myapp', []);

fetch.controller('signup', ['$scope', '$http', function ($scope, $http) {
 
 // Check username 
 $scope.checkUsername = function(){
 
  $http({
   method: 'post',
   url: 'uname_check.php',
   data: {username:$scope.username}
  }).then(function successCallback(response) {
   $scope.unamestatus = response.data;
  });
 }

 // Set class
 $scope.addClass = function(unamestatus){
  if(unamestatus == 'Available'){
   return 'response exists';
  }else if(unamestatus == 'Not available'){
   return 'response not-exists';
  }else{
   return 'hide';
  }
 }

}]);

7. Демо

Посмотреть демо


8. Заключение

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

Всегда обязательно перепроверяйте значение, прежде чем сохранять его в таблице базы данных.

Оригинальный источник статьи: https://makitweb.com/

#angularjs #check #username 

Dylan  Iqbal

Dylan Iqbal

1561523460

Matplotlib Cheat Sheet: Plotting in Python

This Matplotlib cheat sheet introduces you to the basics that you need to plot your data with Python and includes code samples.

Data visualization and storytelling with your data are essential skills that every data scientist needs to communicate insights gained from analyses effectively to any audience out there. 

For most beginners, the first package that they use to get in touch with data visualization and storytelling is, naturally, Matplotlib: it is a Python 2D plotting library that enables users to make publication-quality figures. But, what might be even more convincing is the fact that other packages, such as Pandas, intend to build more plotting integration with Matplotlib as time goes on.

However, what might slow down beginners is the fact that this package is pretty extensive. There is so much that you can do with it and it might be hard to still keep a structure when you're learning how to work with Matplotlib.   

DataCamp has created a Matplotlib cheat sheet for those who might already know how to use the package to their advantage to make beautiful plots in Python, but that still want to keep a one-page reference handy. Of course, for those who don't know how to work with Matplotlib, this might be the extra push be convinced and to finally get started with data visualization in Python. 

You'll see that this cheat sheet presents you with the six basic steps that you can go through to make beautiful plots. 

Check out the infographic by clicking on the button below:

Python Matplotlib cheat sheet

With this handy reference, you'll familiarize yourself in no time with the basics of Matplotlib: you'll learn how you can prepare your data, create a new plot, use some basic plotting routines to your advantage, add customizations to your plots, and save, show and close the plots that you make.

What might have looked difficult before will definitely be more clear once you start using this cheat sheet! Use it in combination with the Matplotlib Gallery, the documentation.

Matplotlib 

Matplotlib is a Python 2D plotting library which produces publication-quality figures in a variety of hardcopy formats and interactive environments across platforms.

Prepare the Data 

1D Data 

>>> import numpy as np
>>> x = np.linspace(0, 10, 100)
>>> y = np.cos(x)
>>> z = np.sin(x)

2D Data or Images 

>>> data = 2 * np.random.random((10, 10))
>>> data2 = 3 * np.random.random((10, 10))
>>> Y, X = np.mgrid[-3:3:100j, -3:3:100j]
>>> U = 1 X** 2 + Y
>>> V = 1 + X Y**2
>>> from matplotlib.cbook import get_sample_data
>>> img = np.load(get_sample_data('axes_grid/bivariate_normal.npy'))

Create Plot

>>> import matplotlib.pyplot as plt

Figure 

>>> fig = plt.figure()
>>> fig2 = plt.figure(figsize=plt.figaspect(2.0))

Axes 

>>> fig.add_axes()
>>> ax1 = fig.add_subplot(221) #row-col-num
>>> ax3 = fig.add_subplot(212)
>>> fig3, axes = plt.subplots(nrows=2,ncols=2)
>>> fig4, axes2 = plt.subplots(ncols=3)

Save Plot 

>>> plt.savefig('foo.png') #Save figures
>>> plt.savefig('foo.png',  transparent=True) #Save transparent figures

Show Plot

>>> plt.show()

Plotting Routines 

1D Data 

>>> fig, ax = plt.subplots()
>>> lines = ax.plot(x,y) #Draw points with lines or markers connecting them
>>> ax.scatter(x,y) #Draw unconnected points, scaled or colored
>>> axes[0,0].bar([1,2,3],[3,4,5]) #Plot vertical rectangles (constant width)
>>> axes[1,0].barh([0.5,1,2.5],[0,1,2]) #Plot horiontal rectangles (constant height)
>>> axes[1,1].axhline(0.45) #Draw a horizontal line across axes
>>> axes[0,1].axvline(0.65) #Draw a vertical line across axes
>>> ax.fill(x,y,color='blue') #Draw filled polygons
>>> ax.fill_between(x,y,color='yellow') #Fill between y values and 0

2D Data 

>>> fig, ax = plt.subplots()
>>> im = ax.imshow(img, #Colormapped or RGB arrays
      cmap= 'gist_earth', 
      interpolation= 'nearest',
      vmin=-2,
      vmax=2)
>>> axes2[0].pcolor(data2) #Pseudocolor plot of 2D array
>>> axes2[0].pcolormesh(data) #Pseudocolor plot of 2D array
>>> CS = plt.contour(Y,X,U) #Plot contours
>>> axes2[2].contourf(data1) #Plot filled contours
>>> axes2[2]= ax.clabel(CS) #Label a contour plot

Vector Fields 

>>> axes[0,1].arrow(0,0,0.5,0.5) #Add an arrow to the axes
>>> axes[1,1].quiver(y,z) #Plot a 2D field of arrows
>>> axes[0,1].streamplot(X,Y,U,V) #Plot a 2D field of arrows

Data Distributions 

>>> ax1.hist(y) #Plot a histogram
>>> ax3.boxplot(y) #Make a box and whisker plot
>>> ax3.violinplot(z)  #Make a violin plot

Plot Anatomy & Workflow 

Plot Anatomy 

 y-axis      

                           x-axis 

Workflow 

The basic steps to creating plots with matplotlib are:

1 Prepare Data
2 Create Plot
3 Plot
4 Customized Plot
5 Save Plot
6 Show Plot

>>> import matplotlib.pyplot as plt
>>> x = [1,2,3,4]  #Step 1
>>> y = [10,20,25,30] 
>>> fig = plt.figure() #Step 2
>>> ax = fig.add_subplot(111) #Step 3
>>> ax.plot(x, y, color= 'lightblue', linewidth=3)  #Step 3, 4
>>> ax.scatter([2,4,6],
          [5,15,25],
          color= 'darkgreen',
          marker= '^' )
>>> ax.set_xlim(1, 6.5)
>>> plt.savefig('foo.png' ) #Step 5
>>> plt.show() #Step 6

Close and Clear 

>>> plt.cla()  #Clear an axis
>>> plt.clf(). #Clear the entire figure
>>> plt.close(). #Close a window

Plotting Customize Plot 

Colors, Color Bars & Color Maps 

>>> plt.plot(x, x, x, x**2, x, x** 3)
>>> ax.plot(x, y, alpha = 0.4)
>>> ax.plot(x, y, c= 'k')
>>> fig.colorbar(im, orientation= 'horizontal')
>>> im = ax.imshow(img,
            cmap= 'seismic' )

Markers 

>>> fig, ax = plt.subplots()
>>> ax.scatter(x,y,marker= ".")
>>> ax.plot(x,y,marker= "o")

Linestyles 

>>> plt.plot(x,y,linewidth=4.0)
>>> plt.plot(x,y,ls= 'solid') 
>>> plt.plot(x,y,ls= '--') 
>>> plt.plot(x,y,'--' ,x**2,y**2,'-.' ) 
>>> plt.setp(lines,color= 'r',linewidth=4.0)

Text & Annotations 

>>> ax.text(1,
           -2.1, 
           'Example Graph', 
            style= 'italic' )
>>> ax.annotate("Sine", 
xy=(8, 0),
xycoords= 'data', 
xytext=(10.5, 0),
textcoords= 'data', 
arrowprops=dict(arrowstyle= "->", 
connectionstyle="arc3"),)

Mathtext 

>>> plt.title(r '$sigma_i=15$', fontsize=20)

Limits, Legends and Layouts 

Limits & Autoscaling 

>>> ax.margins(x=0.0,y=0.1) #Add padding to a plot
>>> ax.axis('equal')  #Set the aspect ratio of the plot to 1
>>> ax.set(xlim=[0,10.5],ylim=[-1.5,1.5])  #Set limits for x-and y-axis
>>> ax.set_xlim(0,10.5) #Set limits for x-axis

Legends 

>>> ax.set(title= 'An Example Axes',  #Set a title and x-and y-axis labels
            ylabel= 'Y-Axis', 
            xlabel= 'X-Axis')
>>> ax.legend(loc= 'best')  #No overlapping plot elements

Ticks 

>>> ax.xaxis.set(ticks=range(1,5),  #Manually set x-ticks
             ticklabels=[3,100, 12,"foo" ])
>>> ax.tick_params(axis= 'y', #Make y-ticks longer and go in and out
             direction= 'inout', 
              length=10)

Subplot Spacing 

>>> fig3.subplots_adjust(wspace=0.5,   #Adjust the spacing between subplots
             hspace=0.3,
             left=0.125,
             right=0.9,
             top=0.9,
             bottom=0.1)
>>> fig.tight_layout() #Fit subplot(s) in to the figure area

Axis Spines 

>>> ax1.spines[ 'top'].set_visible(False) #Make the top axis line for a plot invisible
>>> ax1.spines['bottom' ].set_position(( 'outward',10))  #Move the bottom axis line outward

Have this Cheat Sheet at your fingertips

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

#matplotlib #cheatsheet #python

Bongani  Ngema

Bongani Ngema

1681492440

How to Check If Username Exists with AngularJS

It is always a better idea to check the entered username exists or not if you are allowing the users to choose username while registration and want it to be unique.

With this, the user will instantly know that their chosen username is available or not.

1. Table structure

I am using users table in the tutorial example.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `password` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create a new config.php file.

Completed Code

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

3. HTML

Creating a basic registration form layout that has three input elements and a button.

  • Defined ng-keyup directive on username input field that calls checkUsername().
  • Add a <div > following with username input field to show the available status and to adjust classes on <div> define ng-class directive.

Completed Code

<body ng-app='myapp'>

 <div class="container" ng-controller='signup'>

  <div id="div_reg">
   <h1>Registration</h1>

   <div>
    <input type="text" class="textbox" id="txt_name" ng-model="name" placeholder="Name"/>
   </div>

   <!-- Username -->
   <div>
    <input type="text" class="textbox" id="txt_uname" ng-model="username" ng-keyup='checkUsername()' placeholder="Username" />
    <div ng-class="addClass(unamestatus)" >{{ unamestatus }}</div>
   </div>

   <div>
    <input type="password" class="textbox" id="txt_pwd" ng-model="password" placeholder="Password"/>
   </div>

   <div>
    <input type="submit" value="Submit" name="but_submit" id="but_submit" />
   </div>

  </div>

 </div>

</body>

4. CSS

/* Container */
.container{
 margin: 0 auto;
 width: 70%;
}

/* Registration */
#div_reg{
 border: 1px solid gray;
 border-radius: 3px;
 width: 470px;
 height: 370px;
 box-shadow: 0px 2px 2px 0px gray;
 margin: 0 auto;
}

#div_reg h1{
 margin-top:0px;
 font-weight: normal;
 padding:10px;
 background-color:cornflowerblue;
 color:white;
 font-family:sans-serif;
}

#div_reg div{
 clear: both;
 margin-top: 10px;
 padding: 5px;
}

#div_reg .textbox{
 width: 96%;
 padding: 7px;
}

#div_reg input[type=submit]{
 padding: 7px;
 width: 100px;
 background-color: lightseagreen;
 border: 0px;
 color: white;
}

/* Response */
.response{
 padding: 6px;
 display: block;
}
.hide{
 display: none;
}
.exists{
 color: green;
}

.not-exists{
 color: red;
}

5. PHP

Create new uname_check.php.

Here, check the POST username value in users table and return a response.

Completed Code

<?php

include 'config.php';

$data = json_decode(file_get_contents("php://input"));

// Username
$uname = $data->username;
 
$resText = '';

if($uname != ''){
 // Check username
 $sel = mysqli_query($con,"select count(*) as allcount from users where username = '".$uname."' ");
 $row = mysqli_fetch_array($sel);

 $resText = "Available";
 if($row['allcount'] > 0){
  $resText = 'Not available';
 }
}

echo $resText;

6. Script

Defined two methods –

  • checkUsername – Send $http request to check the username exists or not and initialize $scope.unamestatus with response.data.
  • addClass – Return class names according  to unamestatus value.

Completed Code

var fetch = angular.module('myapp', []);

fetch.controller('signup', ['$scope', '$http', function ($scope, $http) {
 
 // Check username 
 $scope.checkUsername = function(){
 
  $http({
   method: 'post',
   url: 'uname_check.php',
   data: {username:$scope.username}
  }).then(function successCallback(response) {
   $scope.unamestatus = response.data;
  });
 }

 // Set class
 $scope.addClass = function(unamestatus){
  if(unamestatus == 'Available'){
   return 'response exists';
  }else if(unamestatus == 'Not available'){
   return 'response not-exists';
  }else{
   return 'hide';
  }
 }

}]);

7. Demo

View Demo


8. Conclusion

Using the above script you can alert the user whether the username exists or not.

Always make sure to recheck the value before saving it in your Database table.

Original article source at: https://makitweb.com/

#angularjs #check #username 

田辺  桃子

田辺 桃子

1681521480

如何使用 AngularJS 检查用户名是否存在

如果您允许用户在注册时选择用户名并希望它是唯一的,那么检查输入的用户名是否存在总是一个更好的主意。

这样,用户将立即知道他们选择的用户名是否可用

一、表结构

users我在教程示例中使用表格。

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `password` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2.配置

创建一个新config.php文件。

完成代码

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

3.HTML

创建具有三个输入元素和一个按钮的基本注册表单布局。

  • ng-keyup在调用checkUsername().
  • 在用户名输入字段中添加<div >以下内容以显示可用状态并调整<div>defineng-class指令上的类。

完成代码

<body ng-app='myapp'>

 <div class="container" ng-controller='signup'>

  <div id="div_reg">
   <h1>Registration</h1>

   <div>
    <input type="text" class="textbox" id="txt_name" ng-model="name" placeholder="Name"/>
   </div>

   <!-- Username -->
   <div>
    <input type="text" class="textbox" id="txt_uname" ng-model="username" ng-keyup='checkUsername()' placeholder="Username" />
    <div ng-class="addClass(unamestatus)" >{{ unamestatus }}</div>
   </div>

   <div>
    <input type="password" class="textbox" id="txt_pwd" ng-model="password" placeholder="Password"/>
   </div>

   <div>
    <input type="submit" value="Submit" name="but_submit" id="but_submit" />
   </div>

  </div>

 </div>

</body>

4. CSS

/* Container */
.container{
 margin: 0 auto;
 width: 70%;
}

/* Registration */
#div_reg{
 border: 1px solid gray;
 border-radius: 3px;
 width: 470px;
 height: 370px;
 box-shadow: 0px 2px 2px 0px gray;
 margin: 0 auto;
}

#div_reg h1{
 margin-top:0px;
 font-weight: normal;
 padding:10px;
 background-color:cornflowerblue;
 color:white;
 font-family:sans-serif;
}

#div_reg div{
 clear: both;
 margin-top: 10px;
 padding: 5px;
}

#div_reg .textbox{
 width: 96%;
 padding: 7px;
}

#div_reg input[type=submit]{
 padding: 7px;
 width: 100px;
 background-color: lightseagreen;
 border: 0px;
 color: white;
}

/* Response */
.response{
 padding: 6px;
 display: block;
}
.hide{
 display: none;
}
.exists{
 color: green;
}

.not-exists{
 color: red;
}

5. PHP

创建新的uname_check.php.

在这里,检查表中的 POST 用户名值users并返回响应。

完成代码

<?php

include 'config.php';

$data = json_decode(file_get_contents("php://input"));

// Username
$uname = $data->username;
 
$resText = '';

if($uname != ''){
 // Check username
 $sel = mysqli_query($con,"select count(*) as allcount from users where username = '".$uname."' ");
 $row = mysqli_fetch_array($sel);

 $resText = "Available";
 if($row['allcount'] > 0){
  $resText = 'Not available';
 }
}

echo $resText;

6.脚本

定义了两种方法——

  • checkUsername – 发送$http请求以检查用户名是否存在并 $scope.unamestatus使用初始化response.data
  • addClass – 根据 unamestatus 值返回类名。

完成代码

var fetch = angular.module('myapp', []);

fetch.controller('signup', ['$scope', '$http', function ($scope, $http) {
 
 // Check username 
 $scope.checkUsername = function(){
 
  $http({
   method: 'post',
   url: 'uname_check.php',
   data: {username:$scope.username}
  }).then(function successCallback(response) {
   $scope.unamestatus = response.data;
  });
 }

 // Set class
 $scope.addClass = function(unamestatus){
  if(unamestatus == 'Available'){
   return 'response exists';
  }else if(unamestatus == 'Not available'){
   return 'response not-exists';
  }else{
   return 'hide';
  }
 }

}]);

7.演示

查看演示


八、结论

使用上面的脚本,您可以提醒用户用户名是否存在。

始终确保在将值保存到数据库表之前重新检查该值。

文章原文出处:https: //makitweb.com/

#angularjs #check #username