Thursday, 24 November 2022

Parenting tips to inculcate learning habits in your kid

Parenting tips to inculcate learning habits in your kid


Tip #1)

Children do not learn things, they emitate. So, try to do things by yourself, your child will follow you.
Let us see how can we lure a kid into learning Mathematics.

Take a paper and pen or pencil.
Do some simple mathematical problem.
After solving the problem, show happiness on your face.
This way kid will think that this thing is joyful and will follow you.

Saturday, 20 August 2022

Write Smart code in PHP arrays using in built functions.

We have a requirement to fetch data from database and display user names and their salaries.

Output required:

Morgan's salary: 6000, Jermy's salary: 5500, Phil's salary: 5500, Anthony's salary: 5500, John's salary: 5500, Norman's salary: 5500

There are 2 ways of doing this that generate the same result.

<?php

$databseArray = [];

$databseArray[] = [1, 'Morgan', 6000];

$databseArray[] = [2, 'Jermy', 5500];

$databseArray[] = [3, 'Phil', 5500];

$databseArray[] = [4, 'Anthony', 5500];

$databseArray[] = [5, 'John', 5500];

$databseArray[] = [6, 'Norman', 5500];


echo 'Approach 1';

echo '<br/>';

if (! empty($databseArray)) {

 $str = '';

 $cntr = 0;

 $len = count($databseArray);

 foreach ($databseArray as $databseRow) {

  $str .= ' '.$databseRow[1] ."'s". ' salary: '.$databseRow[2];

  if ($cntr < ($len-1))

  $str .= ', ';

  ++$cntr;

 }

}

echo $str;

echo '<br/>--------------------------------------------------------------<br/>';

echo 'Approach 2';

echo '<br/>';

$outputArr = [];

if (! empty($databseArray)) {

 foreach ($databseArray as $databseRow) {

  $outputArr[] = ' '.$databseRow[1] ."'s". ' salary: '.$databseRow[2];

 }

}

echo implode(', ', $outputArr);

Friday, 19 August 2022

Design Pattern in PHP

<?php

class Booklibrary {

 private $bookName = '';

 private $bookAuthor = '';

 const BR = '<br/>';

 public function __construct($name = '', $author = '') {

  $this->bookName = $name;

  $this->bookAuthor = $author;

 }

 public function getNameAndAuthor() {

  return $this->bookName . ' - ' . $this->bookAuthor . self::BR;

 }

}

class BooklibraryFactory {

 public static function create($name, $author) {

  return new Booklibrary($name, $author);

 }

}

$bookOne = BooklibraryFactory::create('Shiv Khera', 'You can win');

$bookTwo = BooklibraryFactory::create('Norman Vincent Peale', 'The Power Of Positive Thinking.');


echo $bookOne->getNameAndAuthor();

echo $bookTwo->getNameAndAuthor();

Monday, 15 August 2022

ReactJS useState() method explained

 The ReactJS useState() method is used to save and set state variables in the React Components.

For this to use, we need to import useState() from React.

The useState() method returns an array.

It has two parameters:

1) state variable

2) function to change state variable.


For example:


const [count, setCount] = useState(0);

Here we are destructing the useState() array with two variables.

the count is variable and setCount is a method.

// Import useState from React

import {useState} from 'react';


function App() {

 const [count, setCount] = useState(0);

}


We can set the count using setCount() method.

Tuesday, 5 July 2022

My First Component to Toggle Color and Color Name

 import { Fragment, useState, useReducer } from 'react';

function reducer(state, action) {
  console.log(state);
  console.log(action);
  switch (action.type) {
    case 'Green':
      return action.type;
      break;
    case 'Red':
      return action.type;
      break;
    case 'Yellow':
      return action.type;
      break;
    case 'Pink':
      return action.type;
      break;
  }
  return state;
}
function Toggle() {
  //const [state, setState] = useState('pink');
  const [state, dispatch] = useReducer(reducer, 'Pink');
  return (
    <Fragment>
      The color is{' '}
      <span style={{ backgroundColor: state, padding: '5px' }}> {state} </span>
      <button
        onClick={() => {
          dispatch({ type: 'Green' });
        }}
      >
        Green
      </button>
      <button
        onClick={() => {
          dispatch({ type: 'Red' });
        }}
      >
        Red
      </button>
      <button
        onClick={() => {
          dispatch({ type: 'Yellow' });
        }}
      >
        Yellow
      </button>
      <button
        onClick={() => {
          dispatch({ type: 'Pink' });
        }}
      >
        Pink
      </button>
    </Fragment>
  );
}
export default Toggle;






Tuesday, 17 May 2022

Drupal 8 programmatically get list of themes installed

 To get list of themes on a Drupal site programmatically, please use following code:


  $modulesList = \Drupal::service('extension.list.theme')->reset()->getList();
  if (! empty($modulesList)) {
    echo "<strong>Themes List:</strong>";
    echo "<br/>";
    foreach ($modulesList as $moduleName => $moduleObj) {
      echo "<br/>";
      echo '<strong>Machine Name: </strong>' . $moduleName;
      echo "<br/>";
      echo '<strong>Humand Readable Name: </strong>' . $moduleObj->info['name'];
      echo "<br/>";
      echo '<strong>Description: </strong>' . $moduleObj->info['description'];
      echo "<br/>";
      echo '<strong>Package: </strong>' . $moduleObj->info['package'];
      echo "<br/>";
      echo "-----------------------------------------------------------------";
    }
  }


Output:


Themes List:

Machine Name: bartik
Humand Readable Name: Bartik
Description: A flexible, recolorable theme with many regions and a responsive, mobile-first layout.
Package: Core
-----------------------------------------------------------------
Machine Name: claro
Humand Readable Name: Claro
Description: A clean, accessible, and powerful Drupal administration theme.
Package: Core
-----------------------------------------------------------------
Machine Name: classy
Humand Readable Name: Classy
Description: A base theme with sensible default CSS classes added. Learn how to use Classy as a base theme in the Drupal 8 Theming Guide.
Package: Core
-----------------------------------------------------------------
Machine Name: seven
Humand Readable Name: Seven
Description: The default administration theme for Drupal 8 was designed with clean lines, simple blocks, and sans-serif font to emphasize the tools and tasks at hand.
Package: Core
-----------------------------------------------------------------
Machine Name: stable
Humand Readable Name: Stable
Description: A default base theme using Drupal 8.0.0's core markup and CSS.
Package: Core
-----------------------------------------------------------------

Drupal 8 get List of modules programmatically.

To get list of modules programmatically, please use following code:


  $modulesList = \Drupal::service('extension.list.module')->reset()->getList();
  if (! empty($modulesList)) {
    echo "<strong>Modules List:</strong>";
    echo "<br/>";
    foreach ($modulesList as $moduleName => $moduleObj) {
      echo "<br/>";
      echo '<strong>Machine Name: </strong>' . $moduleName;
      echo "<br/>";
      echo '<strong>Humand Readable Name: </strong>' . $moduleObj->info['name'];
      echo "<br/>";
      echo '<strong>Description: </strong>' . $moduleObj->info['description'];
      echo "<br/>";
      echo '<strong>Package: </strong>' . $moduleObj->info['package'];
      echo "<br/>";
      echo "-----------------------------------------------------------------";
    }
  }

Output:

Modules List:

Machine Name: action
Humand Readable Name: Actions
Description: Perform tasks on specific events triggered within the system.
Package: Core
-----------------------------------------------------------------
Machine Name: aggregator
Humand Readable Name: Aggregator
Description: Aggregates syndicated content (RSS, RDF, and Atom feeds) from external sources.
Package: Core
-----------------------------------------------------------------
Machine Name: automated_cron
Humand Readable Name: Automated Cron
Description: Provides an automated way to run cron jobs, by executing them at the end of a server response.
Package: Core
-----------------------------------------------------------------
Machine Name: ban
Humand Readable Name: Ban
Description: Enables banning of IP addresses.
Package: Core
-----------------------------------------------------------------
Machine Name: basic_auth
Humand Readable Name: HTTP Basic Authentication
Description: Provides the HTTP Basic authentication provider
Package: Web services
-----------------------------------------------------------------
......

Monday, 25 April 2022

Drush command line get Drupal 8 Version

 We can get Drupal 8 version using Drush also.


drush st as a shortcut (alias) for 


drush status

Output:

 drush st

 Drupal version   : 8.8.0

 Site URI         : http://default

 DB driver        : pgsql

 DB hostname      : localhost

 DB port          : 5432

 DB username      : postgres

 DB name          : prod

 Database         : Connected

 Drupal bootstrap : Successful

 Default theme    : wealth

 Admin theme      : seven

 PHP binary       : E:\wamp64\bin\php\php7.3.21\php.exe

 PHP config       : E:\wamp64\bin\php\php7.3.21\php.ini

 PHP OS           : WINNT

 Drush script     : C:\Users\USERNAME\drush9\vendor\drush\drush\drush

 Drush version    : 9.7.2

 Drush temp       : C:\Users\AMOLBH~1\AppData\Local\Temp

 Drush configs    : C:/Users/Amol

                    Bhavsar/drush9/vendor/drush/drush/drush.yml

 Install profile  : minimal

 Drupal root      : E:\wamp64\www\drupal_installation

 Site path        : sites/default

 Files, Public    : sites/default/files

 Files, Private   : private

 Files, Temp      : /tmp


Wednesday, 16 February 2022

Windows 10: How to open a program on start up?

To open a program(Google Chrome, Outlook) on start up, please follow these steps:

  1. Click on Window button, you will see Outlook icon.
  2. Right click on Outlook, mouse over on More, click on Open File Location.
  3. A folder will be opened with the shortcut to it.
  4. Copy the shortcut icon.
  5. Keyboard: Press Window + R
  6. In the textbox, type shell:startup
  7. A folder will be opened
  8. Paste the Outlook shortcut icon here.
  9. Restart the machine.
  10. Now, Outlook will be opened whenever we start the machine.

Wednesday, 17 March 2021

How to make a text unreadable using CSS?

Imagine you are working on a page where you want to blur a text to make it unreadable for Anonymous users.

Please see the example below in the image:


This is achievable using CSS:

.class-name {

 text-shadow: 7px 7px 7px #0000;

 color: transparent;

}

That's it. All elements with class class-name will blur to become unreadable.

Drupal 8 Blocks: Visibility Hide/Show for certain Roles.

 In Drupal 8, while showing any block, there are visibility settings where, we can select which pages the block can be visible.

The same form has an underlying functionality to hide the block for the selected list or URLs.

Unfortunately, the same is not the case of Roles.

You can select which roles you want to display the block, but, you cannot select which Roles you want to hide the block.

Following code adds a Negate condition to Roles Visibility:


/* Negate the condition to decide visibility of which user roles to show/hide. */

function YOUR_MODULE_form_block_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

$form['visibility']['user_role']['negate'] = [

'#type' => 'radios',

                '#title' => '',

'#default_value' => 0,

'#options' => [

t('Show for selected Roles'),

t('Hide for selected Roles'),

],

];

}

This adds two radio buttons under the form: Roles.

Following is the screen shot for the same:



Thursday, 4 March 2021

Attention GitHub users: Git will add Token Authentication on August 13, 2021, only Username and Password authentication will not work.

Recently, Github has added strict measures to proivde additional security to its users.

As a major step in this, github is making a Token based authentication mandatory for all Github users from August 13, 2021.

So, mere Username and Password authentication will not work.

Tokens will be generated either for devices or session.

Read in details here

Thursday, 30 May 2019

How to restrict a menu in Drupal 7

Sometimes, we need to restrict a user from accessing a certain page.

You can do it through: hook_menu_alter()

So, if your module name is hello_world, the function should be:

function hello_world_menu_alter(&$items) {
 $items['user/%/edit']['access callback'] = FALSE;
}

Here, we have restricted user from editing profile.

Thursday, 28 March 2019

How to flip font awesome icons

Recently came across a problem with font awesome icons.

We are required to show unlock icon. So, we showed it with:

<i class="fa fa-unlock"></i>

And it showed like:





But, we are supposed to show like:



That is, we need to flip the unlock icon.

So, after some research, found solution.

Add class fa-flip-horizontal to <i>

<i class="fa fa-unlock fa-flip-horizontal"></i>

And the unlock icon is flipped.

Tuesday, 19 March 2019

Drupal 8 uninstall a module programmatically

Drupal 8 does not allow to enable/disable modules like previous versions.

You have to completely uninstall a module to get rid of it.

You can install the module be:

<?php
  
\Drupal::service('module_installer')->install(['admin_toolbar']);?>



You can uninstall the module by:

<?php
  
\Drupal::service('module_installer')->uninstall(['admin_toolbar']);?>

Monday, 18 March 2019

Drupal 8: Get User Profile Field Allowed values list


Say, you have a user profile field: field_phone_brand

And you have options:

iPhone|iPhone
Samsung|Samsung
MI|MI
Oppo|Oppo
Vivo|Vivo

And you want to get the allowed values list in a custom module/theme,

$entityManager = \Drupal::service('entity_field.manager');
$fields = $entityManager->getFieldStorageDefinitions('user', 'profile');
$options options_allowed_values($fields[$fieldName]);

If you print:

echo '<pre>';
print_r($options);
echo '</pre>';

You will get:

Array
(
    [iPhone] => iPhone
    [Samsung] => Samsung
    [MI] => MI
    [Oppo] => Oppo
    [Vivo] => Vivo
)

Thursday, 28 February 2019

How to add a class to body Drupal adding a class to “body”

You can use hook_preprocess_html() in your theme's yourtheme.theme file.

Following code will add a body class bdyCls to <body> if certain condition matches.

/**
 * Implement hook_preprocess_html
 */
function yourtheme_preprocess_html(&$html) {
 if ($condition) {
  $html['body_class'] .= 'your-custom-css-class';
 }
}

Wednesday, 27 February 2019

Drupal 8 login a user programatically

Question: How to login a user programmatically in Drupal 8?

Steps:

In your module, create a menu call back

example.externallogin:
  path: '/external/login/{token}'
  defaults:
    _controller: '\Drupal\example\Controller\ExamplesController::externallogin'
    _title: 'Offers'
  requirements:
    _access: 'TRUE'


in your controller,

modules/example/src/Controller/ExamplesController.php,

use Drupal\user\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;

public function externallogin($token = NULL) {
$uid = 111; // Can be any valid Drupal's user id.
if(isset($uid)) {
  $user = User::load($uid);
  user_login_finalize($user);
}
return ['#type' => 'markup', '#markup' => $this->t('You are logged in')];
}

And user is logged into Drupal.

Monday, 25 February 2019

Drupal 8 prevent caching of programmatically created block.

I was working on creating a custom block programmatically.

The requirement was to show the file uploaded to a specific node.

The problem was block was caching and showing same value for each node page.

After a lot of Google search for module hooks, theme hooks, I found that there is an inbuilt function in the block definition itself.

getCacheMaxAge()

This function can set cache age to 0 hence disabling to cache the block.

Final code:

<?php
/**
 * @file
 * Contains \Drupal\sample\Plugin\Block\XaiBlock.
 */
namespace Drupal\sample\Plugin\Block;
use Drupal\Core\Block\BlockBase;
//use GuzzleHttp\json_decode;
/**
 * Provides a 'article' block.
 *
 * @Block(
 *   id = "article_block",
 *   admin_label = @Translation("Article"),
 *   category = @Translation("Custom article block sample")
 * )
 */
class ArticleBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
public function build() {
$nid = NULL;
$content = NULL;
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
// You can get nid and anything else you need from the node object.
$nid = $node->id();
}
if (! empty($nid)) {
$node = \Drupal\node\Entity\Node::load($nid);
$changedVal = $node->get('changed')->getValue();
$changedVal = ! empty($changedVal[0]['value']) ? $changedVal[0]['value'] : '';
if ($changedVal) {
$changedVal = date('d F Y', $changedVal);
}
$content .= '<p class="txt">Last updated ' . $changedVal . '</p>';
}
return array(
'#type' => 'markup',
'#markup' => $content
);
}
/**
     * {@inheritdoc}
     */
    public function getCacheMaxAge() { // <- This function disables block caching.
return 0;
    }
}

Tuesday, 29 January 2019

Great Example of passion about programming

Who is a great example of a very passionate software engineer?

I’m sure a lot of you already know what this Dutch legend is famous for.
In case you don’t - he is the creator of Python.


He now works at Dropbox. He started working there under the condition that he would work simply as a software engineernot a lead or even a manager.
In his own words:


“I think it was because I enjoy doing actual engineering work, and I don’t enjoy as much the formal aspect of management. In the past, I was thrown into such a role for a small team, and it never really worked out. I never really felt comfortable in that type of role. I was always much more comfortable just writing code. Over time, that has included technical leadership, but I like to be part of the work and not just tell people what to do or how to do it.”

Reference: a Quora Answer 

Parenting tips to inculcate learning habits in your kid

Parenting tips to inculcate learning habits in your kid Tip #1) Children do not learn things, they emitate. So, try to do things by yours...