Categories
JavaScript

JavaScript tips

A collection of useful JavaScript functions and handy tips / study notes

forEach

                    
// forEach
const x = [1,3,4,66,77];
x.forEach(v => {log (v*2)})

Map

                    
// Map
const x = [1,3,4,5,6,7,87]
let f = x.map(x=>x*2);
log(f);

Filter

                    
// Filter
const ages = [1,3,4,5,6,7,87];
let filteredAges = function(ages){
return (ages > 5);
}
let f = ages.filter(filteredAges);
log(f);

Invoking a class

                    
// Create Animal.js
export default class Animal{
constructor() {
console.log(“i am an animal”);
}
getClassType() {
return “Animal”;
}
}
// In Index.js
// import Animal from ‘./Animal’;
var animal = new Animal();
log(animal.getClassType()

Clickable div – linked to a js function

Use a JavaScript function on a div – (flex)
                    
function klik1() {
document.getElementById(“moo1″).innerHTML=”M”;
}

Use JavaScript to fetch data

Use Stringify to convert JSON to text

API – JS – HTML Demo

We use JavaScript to fetch from an API and create a new element in the html for each character in the API response

                    
const fetchapi = fetch(“https://rickandmortyapi.com/api/character/”)
.then(response => response.json())
.then(characters => showCharacters(characters.results));
//
const showCharacters = characters => {
const charactersDiv = document.querySelector(“#rmc”);
characters.forEach(character => {
const characterElement = document.createElement(‘p’);
characterElement.innerText = `Character Name: ${character.name}`;
charactersDiv.append(characterElement); })};
                    
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<title>Flex</title>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script>
<script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js”></script>
<link rel=”stylesheet” href=”style.css”>
</head>
<body>
<div class=”container-fluid”>
<h1>My API Demo Page</h1>
<script src=”app.js” defer=”true”></script>
<div id=”rmc”></div>
</div>
</body>
</html>
js-api-html-demo
Categories
JavaScript

Callback functions

Javascript callback functions explained.

As well as Python we’ll be adding semi regular tips and case studies of JavaScript code and features. In this article we’ll look at “callback” functions in JavaScript.

Let’s simplify them down to a very basic example which we show here:

                    
    function cbdemo(a, b, callback){
        console.log(callback(a,b));
    };
    var callback = function(a,b){
        return a * b;
    };
    var bx = cbdemo(2,3, callback);

                

The above will print to console.

We have a function calling another function inside itself.

Let’s use the response from the cbdemo function and display on the page

Now we get a nice bold “h2” number 6 viewable in our page in the browser!

Categories
Python Code

Creating a Python Package

Make your own python package and make it installable with pip install.

If you are wanting to create your own Python module for others to use and provide the best way to install it then https://pypi.org/ is the way to go.

Watch how I learned to make a pip package and successfully created it
# __init__.py

# Version of the gimdl package
__version__ = '0.0.2'
__author__ = 'DrPi'
__email__ = 'redandgreencode@email.com'
# setup.py

from setuptools import setup

with open("README.md", "r") as fh:
    long_description = fh.read()

setup(
    name='gimdl',
    version='0.0.12',
    description='Google Image Search Downloader - using API ',
    py_modules=["gimdl"],
    install_requires=['python-dotenv'],
    package_dir={'': 'src'},
    
    classifiers=[
        'Development Status :: 3 - Alpha',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Operating System :: OS Independent',
    ],
    project_urls={  # Optional
        'GitHub': 'https://github.com/RGGH/gimdl',
    },

    keywords='googleimages, images, search', 
    long_description=long_description,
    long_description_content_type="text/markdown"
)
                    

TL;DR

$ python3 bdist_wheel sdist
$ sudo pip install python3-twine
$ twine register dist/gimdl-0.0.1.tar.gz
$ twine upload dist/gimdl-0.0.1.tar.gz
$ pip install gimdl

To upgrade package after change to source code:
$ python3 bdist_wheel sdist
$ twine –skip-existing dist/*

see: https://twine.readthedocs.io/en/latest/


                
See also https://pythonhosted.org/an_example_pypi_project/setuptools.html
Categories
Python Code

Google Image Search

And How To Use Python to automate it!

image-search-google
Step 1 – install Google-Images-Search
instructions-google
Step 2 – follow the installation instructions
env variables
Step 3 – set up the .env file with the API key and CX code you got when you generated your API credentials with Google.
Note : Make sure you enabled image search by setting it to “on”

code:

from google_images_search import GoogleImagesSearch
from dotenv import load_dotenv
import os
# load the API key and CX code from .env file
load_dotenv()

# create an 'ims' sub directory if it doesn't already exists
if not os.path.exists('ims/'):
  os.mkdir('ims/')
pathz = 'ims/'
# Get env variables
DK = os.environ.get('DEVELOPER_KEY')
CX = os.environ.get('CX')

# custom progressbar function
def my_progressbar(url, progress):
    print(url + " " + progress + "%")

# create google images search - object
gis = GoogleImagesSearch(DK, CX, progressbar_fn=my_progressbar)
# using contextual mode (Curses)
with GoogleImagesSearch(DK, CX) as gis:
    # define search params:
    _search_params = {"q": "tree", 
        "num": 3, 
        "safe": "off", 
        "fileType": "png"
        }
    gis.search(search_params=_search_params, path_to_dir=pathz)

print("\nDone\n")
3 images of trees – here is one of them!

Limit Exceeded!

If you see “Error 429 when requesting…” or…

RESOURCE_EXHAUSTED

then you may have exceeded your daily allowance for API calls. So be careful when testing the code not to make too many requests.

quota-reached-google-api
Quota reached!

To install our code you can use pip:

pip install gimdl

https://pypi.org/project/gimdl/

Categories
Python Code

GitHub Support for password authentication

Support for password authentication was removed on August 13, 2021. Please use a personal access token instead.

This article shows you how to fix it!

remote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead.
remote: Please see https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/ for more information.

2 Steps to fix

(base) [rag@pipdem]$ git remote set-url origin git@github.com:RGGH/pipdem.git

replace RGGH with your user (account) name

replace pipdem with your repo name


(base) [rag@pipdem]$ git commit -am "Update"
On branch main
nothing to commit, working tree clean


(base) [rag@pipdem]$ git push --set-upstream origin main


Enumerating objects: 16, done.
Counting objects: 100% (16/16), done.
Delta compression using up to 8 threads
Compressing objects: 100% (12/12), done.
Writing objects: 100% (16/16), 2.40 KiB | 1.20 MiB/s, done.
Total 16 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), done.

                    
$ ls -al ~/.ssh
# Lists the files in your .ssh directory, 
# (if they exist)

# By default, the filenames of the public keys # are one of the following: id_rsa.pub id_ecdsa.pub id_ed25519.pub # If you don’t have an existing public # and private key pair then generate a # new SSH key

Check the GitHub instructions on how to generate a new SSH key:

https://docs.github.com/en/enterprise-server@2.22/github/authenticating-to-github/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent

Categories
Python Code

Remove non printable characters from text

import string

my_str = "htt😆, moon, boo, f🔥re "

def clean_words(my_str):
    for i in my_str.split():
        word = "" if (any([char not in string.printable for char in i])) else i
        print(word)

clean_words(my_str)
-