Monday, October 12, 2020

Flutter Widgets Style

Normal application tree
1) MaterialApp [title,theme,home]
2) Scaffold [appBar,body]
3) SingleChildScrollView [child]
4) Column [children]
5) Container [child]
6) Card [child]


MaterialApp

class MyApp1 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Personal Expenses',
theme: ThemeData(
primarySwatch: Colors.purple,
accentColor: Colors.amber,
),
home: MyHomePage(),
);
}
}

Column

Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('test1' ),
Text('test2' ),
],
)
 

Container

Container(
margin: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
decoration: BoxDecoration(border: Border.all(color: Colors.purple, width: 2) ),
padding: EdgeInsets.all(10),
child: Text('test' ),
)

Text

Text('\$${tx.amount}',
style: TextStyle( fontWeight: FontWeight.bold, fontSize: 20, color: Colors.purple)
)

TextField   (For Data Entry)
final titleController = TextEditingController();
TextField(
decoration: InputDecoration(labelText: 'Title'),
controller: titleController,
  keyboardType: TextInputType.number,
),

OR

String titleInput;
TextField(
decoration: InputDecoration(labelText: 'Title'),
onChanged: (val) {
titleInput = val;
},
),

TextField keyboardType: 
- TextInputType.number
- TextInputType.datetime
- TextInputType.emailAddress
- TextInputType.multiline
- TextInputType.phone
- TextInputType.url
- TextInputType.visiblePassword

FlatButton
FlatButton(
child: Text('Submit'),
textColor: Colors.purple,
onPressed: () {
print(titleController.text);
    print(titleInput);
},
),

Card
Card(
      elevation: 5,    //drop shadow
      child: Text('Test' )
)

Scroll: To avoid widgets overflow, surround all widgets with scrollbar
SingleChildScrollView()

ListView: it is column with scroll
ListView(
children: <Widget>[
Text('test1' ),
Text('test2' ),
],
)

ListView.builder: it is column with scroll but render only the visible items not all items
ListView.builder(
itemBuilder: (ctx, index) {
return Text('test2'+ index);
  },
itemCount:
5,
)


Titlebar icon and FloatingActionButton

To add icon on AppBar use Actions: iconButton
To add float icon on footer use floatActionButton
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter App'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () => { },
),
],
),

floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () => { } ,
),
);
}

Popup Modal
    showModalBottomSheet(
      context: buildContext,
      builder: (_) {
        return GestureDetector(
          onTap: () {},
          child: null,
          behavior: HitTestBehavior.opaque,
        );
      },
    );



Expanded(child:null),

FractionallySizedBox(heightFactor: 0.7, child:null), 

SizedBox(height: 4),

Padding(padding: EdgeInsets.all(10), child:null),

FittedBox(child:null),

Container( height: 200, child: Image.asset('assets/images/waiting.png', fit: BoxFit.cover)),

CircleAvatar(radius: 30, child:null),

IconButton( icon: Icon(Icons.delete),
color: Theme.of(context).errorColor,
onPressed: () {}
),

ListTile(
leading: null,
title: null,
subtitle: null,
trailing:null,
),

showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2019),
lastDate: DateTime.now(),
).then((pickedDate) {
if (pickedDate == null) {
return;
}
setState(() {
_selectedDate = pickedDate;
});
});

Sunday, October 11, 2020

Validate URLs using Python

 

We have two DB tables

files Table with two columns (id, URL)
Validation Table with two column (id, Status)

Python Application will loop through "files" DB Table and check if the URL are exists and record validation status to another Table


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# -*- coding: utf-8 -*-
#!/usr/bin/python
from __future__ import print_function
import MySQLdb    #sudo apt-get install python-mysqldb
import sys
import re
import requests

reload(sys)
sys.setdefaultencoding('utf8')

my_db = MySQLdb.connect(host="IP",    # your host, usually localhost
                     user="user",         # your username
                     passwd="Password",   # your password
                     db="DB",             # name of the data base
                     charset='utf8')


my_db.autocommit(True)
my_cur = my_db.cursor(MySQLdb.cursors.DictCursor)
my_cur.execute("SET session group_concat_max_len=30000;")

my_cur.execute("""
                    SELECT id,url FROM `files` where url like 'http%' order by id
                   """
                   ) 

try:
    MarcRecords=my_cur.fetchall()
    for row in MarcRecords:
        r = requests.get(str(row["url"]))
        my_cur.execute("insert into `Validation` (id,Status) values("+str(row["id"])+",'"+str(r.status_code)+"')")
        if(r.status_code != 200):
            print('Error: '+str(row["BibID"]))
        else:
            print('Success: '+str(row["BibID"]))

            

except Exception as e:
    print ("Fail!")
    print (str(e))


my_cur.close()
my_db.close()

print ("============= END ====================")

Friday, October 9, 2020

User Latest DB2 11.5.4 on Docker


Prerequisites: Docker engine

1) Get Docker Image
docker pull ibmcom/db2


2) Start Docker image
DB Name: testdb
UserName: db2inst1
Password: P@ssw0rd
Map default DB2 port 50000 to 60000
Map HD : C:\DB2\TestDockerDB


docker run -it --name mydb2 --privileged=true -p 60000:50000 -e LICENSE=accept -e DB2INST1_PASSWORD=P@ssw0rd -e DBNAME=testdb -v C:\DB2\TestDockerDB:/database ibmcom/db2

3) To Login to Docker image

docker exec -it mydb2 bash



For More Configuration Check

https://hub.docker.com/r/ibmcom/db2






Saturday, October 3, 2020

Complete Flutter Project for Online Exam

 












import 'package:flutter/material.dart';


void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _MyAppState();
}
}

class _MyAppState extends State<MyApp> {
final _questions = const [
{
'questionText': 'What\'s your favorite color?',
'answers': [
{'text': 'Black', 'score': 10},
{'text': 'Red', 'score': 5},
{'text': 'Green', 'score': 3},
{'text': 'White', 'score': 1},
],
},
{
'questionText': 'What\'s your favorite animal?',
'answers': [
{'text': 'Rabbit', 'score': 3},
{'text': 'Snake', 'score': 11},
{'text': 'Elephant', 'score': 5},
{'text': 'Lion', 'score': 9},
],
},
{
'questionText': 'Who\'s your favorite instructor?',
'answers': [
{'text': 'Max', 'score': 1},
{'text': 'Max', 'score': 1},
{'text': 'Max', 'score': 1},
{'text': 'Max', 'score': 1},
],
},
];
var _questionIndex = 0;
var _totalScore = 0;

void _resetQuiz() {
setState(() {
_questionIndex = 0;
_totalScore = 0;
});
}

void _answerQuestion(int score) {
_totalScore += score;

setState(() {
_questionIndex = _questionIndex + 1;
});
print(_questionIndex);
if (_questionIndex < _questions.length) {
print('We have more questions!');
} else {
print('No more questions!');
}
}

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My First App'),
),
body: _questionIndex < _questions.length
? QuizWidget( answerQuestion: _answerQuestion, questionIndex: _questionIndex, questions: _questions )
: ResultWidget(_totalScore, _resetQuiz),
),
);
}
}


class QuizWidget extends StatelessWidget {
final List<Map<String, Object>> questions;
final int questionIndex;
final Function answerQuestion;

QuizWidget({ @required this.questions, @required this.answerQuestion, @required this.questionIndex });

@override
Widget build(BuildContext context) {
return Column(
children: [
QuestionWidget(
questions[questionIndex]['questionText'],
),
...(questions[questionIndex]['answers'] as List).map((_answer) {
return AnswerWidget(() => answerQuestion(_answer['score']), _answer['text']);
}).toList()
],
);
}
}


class QuestionWidget extends StatelessWidget {
final String questionText;

QuestionWidget(this.questionText);

@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
margin: EdgeInsets.all(10),
child: Text(
questionText,
style: TextStyle(fontSize: 28),
textAlign: TextAlign.center,
),
);
}
}


class AnswerWidget extends StatelessWidget {
final Function selectHandler;
final String answerText;

AnswerWidget(this.selectHandler, this.answerText);

@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: RaisedButton(
color: Colors.blue,
textColor: Colors.white,
child: Text(answerText),
onPressed: selectHandler,
),
);
}
}


class ResultWidget extends StatelessWidget {
final int resultScore;
final Function resetHandler;

ResultWidget(this.resultScore, this.resetHandler);

String get resultPhrase {
String resultText;
if (resultScore <= 8) {
resultText = 'You are awesome and innocent!';
} else if (resultScore <= 12) {
resultText = 'Pretty likeable!';
} else if (resultScore <= 16) {
resultText = 'You are ... strange?!';
} else {
resultText = 'You are so bad!';
}
return resultText;
}

@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: <Widget>[
Text(
resultPhrase,
style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
FlatButton(
child: Text(
'Restart Quiz!',
),
textColor: Colors.blue,
onPressed: resetHandler,
),
],
),
);
}
}

Understand Map on DART/Flutter

Example 1 : Using a given json extract items and loop through subitems

var questions=[

{

'question':'What is your nationality?',

'answers':['Egyptians','USA','KSA']

},

{

'question':'What is your nationality?',

'answers':['Egyptians','USA','KSA']

},

];


To access first question: questions[0]['question']

To access first question answers list questions[0]['answers']

To Loop through first question answers list and extract them to a given list

MyList =[
    ...(questions[i]['answers'] as List<String>).map((answer){return(answer);}).toList()
];






Example 2 in Dart






Example 3 in Flutter

Step1: Define Class Object
class Transaction {
final String id;
final String title;
final double amount;
final DateTime date;
Transaction({@required this.id, @required this.title, @required this.amount, @required this.date});
}

Step2: Fill Cass Object List with data
final List<Transaction> transactions = [
Transaction( id: 't1', title: 'New Shoes', amount: 69.99, date: DateTime.now()),
Transaction( id: 't2', title: 'New Maps', amount: 69.99, date: DateTime.now()),
];

Step3: Loop Through List using MAP
body: Column(
children:
transactions.map((tx) { return Text( tx.title ); }).toList(),
)

The Complete working code