react post from wp-admin editor text tab


/**
 *  File: App.js
 *  "React State Example-1: Update state using 2 select elements."
 *  by Joe Dorocak (JoeCodeswell.com) 
 *  Demonstrates changing state with 2 select elements 
 * 
 *  Source Code Link: https://joecodeswell.wordpress.com/2018/09/25/react-state-example-1-update-state-using-2-select-elements/
 * 
 * MIT License
 * 
 * Copyright (c) [2018] [Joseph P. Dorocak]
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * 
 *  https://en.forums.wordpress.com/topic/posting-javascript-markdown-does-not-show/
 * 
 *  
 */

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

let programmerList =  ["Admiral Grace Hopper","Ada Lovelace","Donald Knuth","James Gosling","Guido van Rossum","Linus Torvalds"];

class App extends Component {
  constructor() {
    super();
    this.state = {
      counter: 0,
      programmer_list: programmerList,
      fmSelFrom: programmerList[0],
      fmSelTo:programmerList[0]
    };
  }
  handleFromChange = (event) => {
    this.setState({ 
      fmSelFrom: event.target.value     
    });
  }
  handleToChange = (event) => {
    this.setState({ 
      fmSelTo: event.target.value    
    });
  }
  render() {
    // inside class App -> render(){ before return(
    return (

      /* begin out of the box jsx */
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
        {/* end out of the box jsx */}
        {/* begin non out of the box jsx */}
        <div id="show-programmer-list">
          <p>Programmer List</p>
            {this.state.programmer_list.map(  (itm,ix) => <p key={ix} value={itm} >ix:{ix}->itm:{itm}</p> )   }          
        </div>

        <div id="select-programmer-from-to">
        <label>
            Pick your FROM Programmer:        
            <select id="select-from"  value={this.value} onChange={this.handleFromChange} >
              {this.state.programmer_list.map(  (itm,ix) => <option key={ix} value={ix+":"+itm} >{itm}</option> )   }  
            </select>
        </label>
        <label>
          Pick your TO Programmer:         
          <select id="select-to" value={this.key} onChange={this.handleToChange} >
            {this.state.programmer_list.map(  (itm,ix) => <option key={ix} value={itm} >{itm}</option> )   }
          </select>
        </label>

        <p>this.state.fmSelFrom: {this.state.fmSelFrom}</p>
        <p>this.state.fmSelTo: {this.state.fmSelTo}</p>

        </div>
        {/* end non out of the box jsx */}
     
      </div> 
      /* end of <div className="App"> */

      // inside class App -> render(){ ->return( -> after <div className="App"></div>

    ); // end render -> return
  } // end render () code
}

export default App;
App.js.txt
Displaying App.js.txt.
Advertisements

Help with publishing code on WordPress.com

Here is a link to a WordPress.com support request of mine regarding publishing code on WordPress.com, posting “` javascript markdown DOES NOT show ”.

The folks were a GREAT HELP.

Thanks again to  @melancholia.

Love and peace,

Joe

React State Example-1: Update state using 2 select elements.

Based on Out of the box src for create-react-app -V 1.5.2


/**
 *  File: App.js
 *  "React State Example-1: Update state using 2 select elements."
 *  by Joe Dorocak (JoeCodeswell.com) 
 *  Demonstrates changing state with 2 select elements 
 * 
 *  Source Code Link: https://joecodeswell.wordpress.com/2018/09/25/react-state-example-1-update-state-using-2-select-elements/
 * 
 * MIT License
 * 
 * Copyright (c) [2018] [Joseph P. Dorocak]
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * 
 *  https://en.forums.wordpress.com/topic/posting-javascript-markdown-does-not-show/
 * 
 *  
 */

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

let programmerList =  ["Admiral Grace Hopper","Ada Lovelace","Donald Knuth","James Gosling","Guido van Rossum","Linus Torvalds"];

class App extends Component {
  constructor() {
    super();
    this.state = {
      counter: 0,
      programmer_list: programmerList,
      fmSelFrom: programmerList[0],
      fmSelTo:programmerList[0]
    };
  }
  handleFromChange = (event) => {
    this.setState({ 
      fmSelFrom: event.target.value     
    });
  }
  handleToChange = (event) => {
    this.setState({ 
      fmSelTo: event.target.value    
    });
  }
  render() {
    // inside class App -> render(){ before return(
    return (

      /* begin out of the box jsx */
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
        {/* end out of the box jsx */}
        {/* begin non out of the box jsx */}
        <div id="show-programmer-list">
          <p>Programmer List</p>
            {this.state.programmer_list.map(  (itm,ix) => <p key={ix} value={itm} >ix:{ix}->itm:{itm}</p> )   }          
        </div>

        <div id="select-programmer-from-to">
        <label>
            Pick your FROM Programmer:        
            <select id="select-from"  value={this.value} onChange={this.handleFromChange} >
              {this.state.programmer_list.map(  (itm,ix) => <option key={ix} value={ix+":"+itm} >{itm}</option> )   }  
            </select>
        </label>
        <label>
          Pick your TO Programmer:         
          <select id="select-to" value={this.key} onChange={this.handleToChange} >
            {this.state.programmer_list.map(  (itm,ix) => <option key={ix} value={itm} >{itm}</option> )   }
          </select>
        </label>

        <p>this.state.fmSelFrom: {this.state.fmSelFrom}</p>
        <p>this.state.fmSelTo: {this.state.fmSelTo}</p>

        </div>
        {/* end non out of the box jsx */}
     
      </div> 
      /* end of <div className="App"> */

      // inside class App -> render(){ ->return( -> after <div className="App"></div>

    ); // end render -> return
  } // end render () code
}

// App.js.txt
// Displaying App.js.txt.

export default App;

Out of the box src for create-react-app -V 1.5.2

App.js out of the box

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      <div>
        <header>
          <img src="{logo}" alt="logo" />
          <h1>Welcome to React</h1>
        </header>

          To get started, edit <code>src/App.js</code> and save to reload.

      </div>
    );
  }
}

export default App;

App.css out of the box

.App {
  text-align: center;
}

.App-logo {
  animation: App-logo-spin infinite 20s linear;
  height: 80px;
}

.App-header {
  background-color: #222;
  height: 150px;
  padding: 20px;
  color: white;
}

.App-title {
  font-size: 1.5em;
}

.App-intro {
  font-size: large;
}

@keyframes App-logo-spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

App.test.js out of the box

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
  ReactDOM.unmountComponentAtNode(div);
});

index.css out of the box

body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
}

index.js out of the box

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

registerServiceWorker.js out of the box

<br />// In production, we register a service worker to serve assets from local cache.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.

// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.

const isLocalhost = Boolean(
  window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 127.0.0.1/8 is considered localhost for IPv4.
    window.location.hostname.match(
      /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);

export default function register() {
  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
    // The URL constructor is available in all browsers that support SW.
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
    if (publicUrl.origin !== window.location.origin) {
      // Our service worker won't work if PUBLIC_URL is on a different origin
      // from what our page is served on. This might happen if a CDN is used to
      // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
      return;
    }

    window.addEventListener('load', () => {
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

      if (isLocalhost) {
        // This is running on localhost. Lets check if a service worker still exists or not.
        checkValidServiceWorker(swUrl);

        // Add some additional logging to localhost, pointing developers to the
        // service worker/PWA documentation.
        navigator.serviceWorker.ready.then(() => {
          console.log(
            'This web app is being served cache-first by a service ' +
              'worker. To learn more, visit https://goo.gl/SC7cgQ'
          );
        });
      } else {
        // Is not local host. Just register service worker
        registerValidSW(swUrl);
      }
    });
  }
}

function registerValidSW(swUrl) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              // At this point, the old content will have been purged and
              // the fresh content will have been added to the cache.
              // It's the perfect time to display a "New content is
              // available; please refresh." message in your web app.
              console.log('New content is available; please refresh.');
            } else {
              // At this point, everything has been precached.
              // It's the perfect time to display a
              // "Content is cached for offline use." message.
              console.log('Content is cached for offline use.');
            }
          }
        };
      };
    })
    .catch(error => {
      console.error('Error during service worker registration:', error);
    });
}

function checkValidServiceWorker(swUrl) {
  // Check if the service worker can be found. If it can't reload the page.
  fetch(swUrl)
    .then(response => {
      // Ensure service worker exists, and that we really are getting a JS file.
      if (
        response.status === 404 ||
        response.headers.get('content-type').indexOf('javascript') === -1
      ) {
        // No service worker found. Probably a different app. Reload the page.
        navigator.serviceWorker.ready.then(registration => {
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        // Service worker found. Proceed as normal.
        registerValidSW(swUrl);
      }
    })
    .catch(() => {
      console.log(
        'No internet connection found. App is running in offline mode.'
      );
    });
}

export function unregister() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then(registration => {
      registration.unregister();
    });
  }
}

logo.svg out of the box

NOT shown due to WordPress.com markdown limitations!

#222

gDocInsertDateTime Google Docs add-on

For my own use & that of others, I just wrote gDocInsertDateTime. It is a Google Docs add-on that inserts a date-time stamp at the position of the cursor.

Please use the comments below for feedback. Thanks.

Shortlink: https://wp.me/p1zI3Z-uZ

I just installed P2 and…

FINALLY, I AM HAPPY! 🙂

My Travails

BUMMER: I just installed P2 and the links to my pages (menu?) at the top of the site disappeared! I am going to go back to Truly Minimal theme and see if they HOPEFULLY re appear!

ANOTHER BUMMER: wordpress says you can’t revert to an old theme.

ANOTHER BIG BIG BUMMER: Markdown gets replaced by [X]HTML in posts. Find Markdown onP2 by Automattic

ANOTHER BUMMER: STILL can’t get P2 to display links to my pages.
See P2 User Guide

Fixing Menu to Pages

  1. My sites > JoeCodeswell > Themes [Customize button]
  2. Menus Tab
  3. Create New Menu [Named “Pages” N.B. name does not show]
  4. Menu Location: Where do you want this menu to appear? (If you plan to use a menu widget (opens in a new window), skip this step.) [X] Primary Menu (Current: Pages) N.B. I clicked [X] on this item.
  5. Click “+ Add Items” button RESULT Menu of links appears on right. Including as JSON: [Search menu items…, Pages: [Home,ES6 Notes, Django Notes, Python Notes, Web2py Notes, My Resume (SCROLL DOWN TO SEE!)], Posts, Categories, Tags, Format ]
  6. I clicked + on all the Page Items to add them to the menu

RESULT: Pages Menu APPEARS ACROSS TOP WITHOUT “Pages” title. Thanks be to God. Amen.

Python code creates a database from .csv

Content

  1. Documentation
  2. Code

1. Documentation

csv2sqliteDB.py:
1. Creates an sqlite Database (from SQLITE_FILEPATH) then
2. Creates and Loads TABLE_NAME (adding id INTEGER PRIMARY KEY )
FROM CSV_FILEPATH (with header, NO id field necessary)
INTO DATABASE_FILEPATH
CREATING DATABASE_FILEPATH if it doesn’t exist.

Usage:   csv2sqliteDB.py TABLE_NAME CSV_FILEPATH  SQLITE_FILEPATH
Example: csv2sqliteDB.py contacts   contacts2.csv contactsDB2id.db

2. Code


#!/usr/bin/python
#! python3
#! python2
# -*- coding: utf-8 -*-
"""csv2sqliteDB.py Creates and Loads TABLE_NAME (adding id INTEGER PRIMARY KEY )
      from CSV_FILEPATH (with header, NO id field necessary)
      into DATABASE_FILEPATH
          creating DATABASE_FILEPATH if it doesn't exist

Usage:   csv2sqliteDB.py TABLE_NAME CSV_FILEPATH  SQLITE_FILEPATH
Example: csv2sqliteDB.py contacts   contacts2.csv contactsDB2id.db
"""

# see:
    # Importing a CSV file into a sqlite3 - http://stackoverflow.com/a/2888042/601770
    # csv file using python with headers intact - http://stackoverflow.com/a/3428633/601770

import os, sys, csv, sqlite3

def csv2sqliteDB(table_name, csv_filepath, database_filepath):
    conn, cursor = createDatabaseIfNotExist(database_filepath)
    nlines = sum(1 for line in open(csv_filepath)) # http://stackoverflow.com/a/36973958/601770
    with open(csv_filepath, 'r') as f:
        reader = csv.reader(f)
        headerL = reader.__next__()

        createTable(table_name, conn, cursor, headerL)

        loadTable(table_name, conn, cursor, headerL, reader, nlines)
    conn.close()

def createDatabaseIfNotExist(database_filepath):
    # if we error, we rollback automatically, else commit!
    with sqlite3.connect(database_filepath) as conn:
        cursor = conn.cursor()
        cursor.execute('SELECT SQLITE_VERSION()')
        data = cursor.fetchone()
        print('SQLite version:', data)
        return conn, cursor

def createTable(table_name, conn, cursor,  headerL):
    """
    :param table_name:
    :param conn:
    :param cursor:
    :param header:
    :return:
    """
    # http://stackoverflow.com/a/12432311/601770
    # http: // stackoverflow.com / a / 19730169 / 601770

    textL = len(headerL)*'TEXT'.split()
    def_str = ', '.join( ['id INTEGER PRIMARY KEY'] + [i[0]+' '+i[1] for i in list(zip(headerL, textL))] )
    script_str = """DROP TABLE IF EXISTS %s;
        CREATE TABLE %s (%s);
    """%(table_name, table_name, def_str) # checks to see if table exists and makes a fresh table.

    cursor.executescript(script_str)


def loadTable(table_name, conn, cursor, headerL, reader, nlines):
    insert_str_model = "INSERT INTO {table_name} ({col_names}) VALUES({q_marks});"
    col_names = ','.join(headerL)
    q_marks = ','.join(len(headerL)*'?'.split())

    insert_str = insert_str_model.format(table_name=table_name, col_names=col_names, q_marks=q_marks)

    # DO THE INSERTS
    line_count = 0
    for row in reader:
        line_count += 1
        if line_count%10 == 1: print('line %s of %s'%(line_count, nlines))
        cursor.execute(insert_str, row)
        conn.commit()


NUM_ARGS = 3
def main():
    args = sys.argv[1:]
    if len(args) != NUM_ARGS or "-h" in args or "--help" in args:
        print (__doc__)
        sys.exit(2)
    csv2sqliteDB(args[0], args[1], args[2])

if __name__ == '__main__':
    main()

#code, #csv, #database, #python, #sqlite