Google Apps Script: Save Gmail attachment to SHARED Google Drive

Goal:
Update code below to save attachments to a “Test” folder within “Shared drive”

So far I’ve been successful in saving attachments to “My Drive” using the gmail2gdrive script found on https://github.com/ahochsteger/gmail2gdrive

This script uses DriveApp.getRootFolder() to find the root folder, but does not look at shared drives.
I have the “Drive” Advanced Service set up and am able to at least view up to 10 folders in the Shared Drive using getSharedDrives(), but have been unsuccessful updating the code to transfer files to a shared drives.

PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR On Certain Hour

I have a problem about connecting to MySQL. After 8 PM (My local time), the connection is lost. So I modified my code, whenever mysql throw PROTOCOL_CONNECTION_LOST, it will try to reconnect to the mysql. The error for PROTOCOL_CONNECTION_LOST is gone, but it give new error code PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR when trying to connect to the server.
This is my code to create connection to MySQL.

const dbConn = mysql.createConnection({
    host        : 'localhost',
    user        : 'xxxx',
    password    : 'xxxx',
    database    : 'test'
});

function handleDisconnect() {

  dbConn.connect(function(err, connection) {             
    if(err) {                                     
      console.log('error when connecting to db:', err);
      setTimeout(handleDisconnect, 2000); 
    }       
  });                                     
   
  dbConn.on('error', function(err) {
    console.log('db error', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') { 
      handleDisconnect();                         
    } else {                                     
      throw(err)                       
    }
  });
}

handleDisconnect();
module.exports = dbConn;

This is my error stack

0|index    | error when connecting to db: Error: Cannot enqueue Handshake after fatal error.
0|index    |     at Protocol._validateEnqueue (/home/mydev/SOBATku/node_modules/mysql/lib/protocol/Protocol.js:212:16)
0|index    |     at Protocol._enqueue (/home/mydev/SOBATku/node_modules/mysql/lib/protocol/Protocol.js:138:13)
0|index    |     at Protocol.handshake (/home/mydev/SOBATku/node_modules/mysql/lib/protocol/Protocol.js:51:23)
0|index    |     at Connection.connect (/home/mydev/SOBATku/node_modules/mysql/lib/Connection.js:116:18)
0|index    |     at handleDisconnect (/home/mydev/SOBATku/config/db.config.js:34:10)
0|index    |     at Connection.<anonymous> (/home/mydev/SOBATku/config/db.config.js:45:7)
0|index    |     at Connection.emit (node:events:390:28)
0|index    |     at Connection._handleProtocolError (/home/mydev/SOBATku/node_modules/mysql/lib/Connection.js:423:8)
0|index    |     at Protocol.emit (node:events:390:28)
0|index    |     at Protocol._delegateError (/home/mydev/SOBATku/node_modules/mysql/lib/protocol/Protocol.js:398:10) {
0|index    |   code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR',
0|index    |   fatal: false
0|index    | }

It can reconnect when I do some command like pm2 logs or other command with pm2 (I use pm2 for the node run command). Planning to use cron function to restart my server every 8PM, but if it can solved without restart the server, it will be very helpful. Thank you.

why does Echoing php into JavaScript not work

I am trying to echo a multidimensional array from PHP to js, but it is giving me an error saying that “<” is an unexpected token.

js

var products = <?php echo json_encode( $products ) ?>;

Php

<?php
    // PHP array
    $products = array(
        // product abbreviation, product name, unit price
        array('choc_cake', 'Chocolate Cake', 15),
        array('carrot_cake', 'Carrot Cake', 12),
        array('cheese_cake', 'Cheese Cake', 20),
        array('banana_bread', 'Banana Bread', 14)
    );
?>

Implementing a nested mutation based on a relationship between two GraphQL types

I want to create a form that allows me to create a value from a nested field. Root values in the same mutation work ok, but when I want to create the nested value, I cannot. Take for instance the below mutation.

export const createPremise = (newPremiseEntry) => {
  const mutation = gql`
    mutation CreatePremise($input: PremiseInput!) {
      createPremise(data: $input) {
        _id
        _ts
        content
      
        createdAt
      }
    }
  `
  return graphQLClient.request(mutation, { input: newPremiseEntry })
}

I want to create a premise with the root value content on my form, so, on my frontend I have:

const ENTRIES_PATH = '/api/entries/allPremises'

    const putPremiseEntry = (payload) =>
        fetch(ENTRIES_PATH, {
            method: 'POST',
            body: JSON.stringify(payload),
            headers: {
                'Content-Type': 'application/json',
            },
        }).then((res) => (res.ok ? res.json() : Promise.reject(res)))

Then I do this:

const useEntriesFlow = () => {
    const onSubmit = async (payload) => {
        await putPremiseEntry(payload)
        await mutate(ENTRIES_PATH)
    }
    return {
        onSubmit,
    }
}

const EntryPremiseForm = ({ onSubmit: onSubmitProp }, storyId) => {
    const [show, setShow] = useState(false);

    const handleClose = () => setShow(false);
    const handleShow = () => setShow(true);
    const initial = {
        content: '', // My premise has a field called content, which I want to input, remember this, i'll come back to it.

    }
    const [values, setValues] = useState(initial)
    const [formState, setFormState] = useState('initial')
    const isSubmitting = formState === 'submitting'

    const onSubmit = (ev) => {
        ev.preventDefault()
        setFormState('submitting')
        onSubmitProp(values)
            .then(() => {
                setValues(initial)
                setFormState('submitted')
            })
            .catch(() => {
                setFormState('failed')
            })
    }
    const makeOnChange =
        (fieldName) =>
            ({ target: { value } }) =>
                setValues({
                    ...values,
                    [fieldName]: value,
                })
    return (
        <>
                <form className="" onSubmit={onSubmit}>
                        <input  //this is my input for creating the premise
                            required
                            className={cn(inputClasses, '')}
                            aria-label="premise"
                            placeholder="Premise"
                            value={values.content}
                            onChange={makeOnChange('content')} // On my form, I add the `content` value which goes into my premise object, creating the premise.
                        />
                        <Button type="submit" disabled={isSubmitting}>
                            {isSubmitting ? <LoadingSpinner /> : 'Create Story'}
                        </Button>
                </form>
                {{
                    failed: () => <ErrorMessage>Something went wrong. :(</ErrorMessage>,
                    submitted: () => ( <SuccessMessage>Thanks for signing the guestbook.</SuccessMessage>
                    ),
                }[formState]?.()}
        </>
    )
}

This is all fine, It works.

THE PROBLEM

The problem comes when I need to do the same thing, but with an extra field that is nested. This type Premise belongs to another object called Story

type Story {
  name: String!
  createdAt: Time!
  premises: [Premise] @relation
}

type Premise {
  content: String!
  belongs: Story!
  createdAt: Time!
}

belongs is how faunadb creates the relation

The mutation looks like this:

export const createPremise = (newPremiseEntry) => {
  const mutation = gql`
    mutation CreatePremise($input: PremiseInput!) {
      createPremise(data: $input) {
        _id
        _ts
        content
        belongs{name}  //nested relationship, not sure if syntax is correct.
        createdAt
      }
    }
  `
  return graphQLClient.request(mutation, { input: newPremiseEntry })
}

The difference being:

belongs{name}

name being the name of the story it belongs to. found on the type Story

FIRST PROBLEM

How do I represent this in my POST?

export default async function handler(req, res) {
  const handlers = {

    POST: async () => {
      const {
        body: { 
        content, 
        belongs{name} // ?? WHAT DO I PUT HERE? HOW DO I REPRESENT BELONGS.NAME AS SEEN IN TYPE PREMISE?
        },
      } = req
      const createdPremise = await createPremise({
        content, belongs{name}, //???
        createdAt: new Date(),
      })
      res.json(createdPremise)
    },
  }

  if (!handlers[req.method]) {
    return res.status(405).end()
  }

  await handlers[req.method]()
}

SECOND PROBLEM

In my const EntryPremiseForm above how do I represent that belongs.name

const handleClose = () => setShow(false);
    const handleShow = () => setShow(true);
    const initial = {
        content: '',
        belongs.name: '', //??? How do I set the inital state for this nested relationship field. remember, content works fine
    }

When I have that, I can then do this

<input  
      required
      className={cn(inputClasses, '')}
      aria-label="premise"
      placeholder="Premise"
      value={values.belongs.name} // ??? HOW DO I REPRESENT THAT HERE
      onChange={makeOnChange('values.belongs.name')} //???
/>

Any help is greatly apreciated.

db.collection(“articles”).add results in “.default.collection is not a function”

Essentially I want to add a collection called “articles” with the following actors and store it in firebase.

I followed the doc for uploading files to firebase. I was reading the doc for adding data to firebase but it was a bit confusing and not sure how to implement it.

index.js (to view the other top half, here)

...
() => {
   getDownloadURL(upload.snapshot.ref).then((downloadURL) => {
    db.collection("articles").add({
      actor: {
        description: payload.user.email,
        title: payload.user.displayName,
        date: payload.timestamp,
        image: payload.user.photoURL,
        },
        video: payload.video,
        sharedImg: downloadURL,
        comments: 0,
        description: payload.description,
       });
   });
}

However, whenever I run this code, I get “Unhandled Rejection (TypeError): firebase__WEBPACK_IMPORTED_MODULE_0_.default.collection is not a function.”

firebase.js

import { initializeApp } from 'firebase/app';
import { getAuth, GoogleAuthProvider } from 'firebase/auth';
import { getStorage } from "firebase/storage";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
...
}

const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
const auth = getAuth();
const provider = new GoogleAuthProvider();
const storage = getStorage(firebaseApp);
  
export { auth, provider, storage };
export default db;

Any advise as to what is going wrong? Thanks!

How to make white shadows in Tailwind CSS

I’m currently in the process of making a portfolio website with a light and dark mode. In light mode, the cards on the site have a shadow to create a sense of distance from the background. I want to make that same effect in dark mode, but I can’t figure out how to make a white shadow in tailwind. I have looked up on the documentation, other questions on similar topics, and still no luck. You can find the full code here.

Here’s what I’ve tried so far:

  1. I’ve tried defining my own custom shadow in tailwind.config.js using
theme: {
    extend: {
      boxShadow: {
        'dark-sm': '0 1px 2px 0 rgba(255, 255, 255, 0.05)',
      },
    },
  },
  1. I’ve also tried using the shadows keyword instead of boxShadow:
theme: {
    extend: {
      shadows: {
        'red': 'rgba(255, 0, 0, 0.1)',
      }
    },
  },

when I call

<div className = "dark:shadow-dark-sm"></div>

or

<div className = "dark:shadow-red"></div>

nothing happens, even if I try it with a different color and not in dark mode.

There was one time when I was able to change the color using the boxShadow method, but it doesn’t work any more and I have no idea why. Any help would be appreciated!

I can’t run the slider function in react

I am trying to make a simple component. The component can also be dragged. When I run it I don’t get any error but it doesn’t work.When I make some changes, it gives the error “TypeError: slider.addEventListener is not a function”. How can I make these codes work?

export class SliderComp extends Component {
  render() {
     function SliderComp( ) {
    let slider = document.querySelectorAll("items");
     let isDown = false;
    let startX;
    let scrollLeft;

    slider.addEventListener("mousedown", (e) => {
      isDown = true;
      slider.classList.add("active");
      startX = e.pageX - slider.offsetLeft;
      scrollLeft = slider.scrollLeft;
    });
    slider.addEventListener("mouseleave", () => {
      isDown = false;
      slider.classList.remove("active");
    });
    slider.addEventListener("mouseup", () => {
      isDown = false;
      slider.classList.remove("active");
    });
    slider.addEventListener("mousemove", (e) => {
      if (!isDown) return;
      e.preventDefault();
      const x = e.pageX - slider.offsetLeft;
      const walk = (x - startX) * 3;
      slider.scrollLeft = scrollLeft - walk;  
    });
  }
    return (
      <div>        
        <div class="grid-container">
          <main class="grid-item main">
            <div class="items">
              <div class="item item1"></div>
              <div class="item item2"></div>
            </div>
          </main>
        </div>
      </div>
    );   
  }
}

I want to pick 6 random id’s [duplicate]

I’m trying to pick 6 random ids from a api. So far I’m printing all of them.


function makeCatLi(cat){
    
    const newLi = document.createElement("LI"); 
    for (let i = 0; i < 6; i++) {
      let randomIndex = Math.floor(Math.random() * cat.id);
      newLi.innerText = randomIndex;
      body.append(newLi);
    }
}

I appreciate any help. And I only want to use vanilla JS.

How do i change the the like button to 1 like when a user is loged in?

My question is once the user is logged in I need to be able to set a like and remove it as well, such as instagram. I´ll leave you with my two components. Very much appreciated. What i was thinking was to share through props the handleclick and then pass it on the Onclick of the like button, but i had troubles with that.

function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const handleChangeEmail = (e) => {
    setEmail(e.target.value);
  };

  const handleChangePassword = (e) => {
    setPassword(e.target.value);
  };

  const handleClickLogin = () => {
    const storage = localStorage.getItem("values");

    if (
      JSON.parse(storage).email === email &&
      JSON.parse(storage).password === password
    ) {
      console.log("user loged");
    } else {
      console.log("user isn´t loged");
    }
  };

  return (
    <div className="container">
      <div className="icon">
        <div className="cion_class">
          <PersonAdd fontSize="large" />
        </div>
        <div className="text">Log In</div>
      </div>

      <div className="row m-2">
        <TextField
          id="email"
          className="p-2"
          onChange={handleChangeEmail}
          type="text"
          variant="outlined"
          label="Enter email"
          fullWith
        />
        <TextField
          id="password"
          className="p-2"
          onChange={handleChangePassword}
          type="text"
          variant="outlined"
          label="Enter Password"
          fullWith
        />
        <FormControlLabel
          control={
            <Checkbox
              icon={<CheckBoxOutlineBlank fontSize="small" />}
              checkedIcon={<CheckBox fontSize="small" />}
              name="checked"
            />
          }
          label="Remember me"
        />
        <Button
          variant="contained"
          color="primary"
          fullWidth
          onClick={() => handleClickLogin()}
        >
          Log In
        </Button>
      </div>
      <Divider variant="middle" />
      <Link to="sign-up">
        <h5 className="text-center">Create Account</h5>
      </Link>
    </div>
  );
}

export default Login;

function Like() {
  const [heartColor, setHeartColor] = useState(false);

  return (
    <>
      <button className="insta-heart">
        <i
          className={heartColor ? "fas fa-heart heart-red" : "far fa-heart"}
          onClick={() => {
            setHeartColor(!heartColor);
          }}
        ></i>
      </button>
    </>
  );
}

export default Like;

When props data to child component my items is not displayed ? React

When I props the data on child component do not appear propertly data to me.

First check my parent compnent:

  selectFile = (event) => { // on select file and upload
    let addedFiles = []; 
    event.target.files.forEach((element) => {
      addedFiles.push(element);
    });  
    this.setState({
      tempFiles: addedFiles,
      modalTempFiles: this.state.old.concat(addedFiles),
      old: this.state.old.concat(addedFiles)
    }); 
  };


  componentDidMount() { 
    //  I NEED TO USE SETTIMEOUT BECAUSE MY PROPS DATA IS NULL ON MOUNT
    setTimeout(() => { 
      this.setState({
        tempFiles: this.props.files.exFiles,
        modalTempFiles: this.props.files.exFiles,
        old: this.props.files.exFiles
      });
    }, 1500);
  }

HTML: (check only FileUploadContainer component )

  render() {
    const {
      intl,
      onHideAttachmentsModal,
      files,
      show,
      onHideErrorModal,
      showErrorModal
    } = this.props;
    const { modalTempFiles } = this.state;
    return (
      <>
        <Modal
          show={show} 
          title={intl.formatMessage(messages.attachments)} 
          primaryButtonTitle="Upload attachment(s)"
        > 
           //RIGHT NOW JUST THIS COMPONENT IS IMPORTANT -> FileUploadContainer
          <FileUploadContainer
            stopPropagation={this.stopPropagation}
            onFileDrop={this.onFileDrop}
            selectFile={this.selectFile}
            files={this.props.files?.exFiles}
          />

          {modalTempFiles.length > 0 && (
            <FileContainer
              files={modalTempFiles}
              onClickHandler={this.removeFile}
            />
          )}
        </Modal> 

      </>
    );
  }

My state is :

this.state = {
  tempFiles: [],
  modalTempFiles: [],
  old: []
};

Now I’m props some data in my children’s component. To my FileUploadContainer component.

This is my child component:

const FilesContainer = ({ intl, files, onClickHandler, fullWidth }) => {
  console.log("files", files);
  return (   
        {files.map((file, index) => (
          <File
            key={index}
            name={file.name}
            size={file.size}
            onClickHandler={() => onClickHandler(file, index, true)}
          />
        ))} 
  );
};

Don’t show me names and sizes… I see three items printed in loop but name and size is empty…

One of the interesting things is that my console.log (‘files’, files) is printed more than 4-5 times..

What’s the problem here? Why I am shown 3 items (as many as I need) but with empty values.
What I example see:

  1. Name : EMPTY , Size: EMPTY,
  2. Name : EMPTY , Size: EMPTY,
  3. Name : EMPTY , Size: EMPTY

BUT THREE TIMES LOOPED AS IT SHOULD BE because i have three items…

Having problems making a post request using the Ckeditor

How do I push the data from my text editor into the formData object, in the content section? inside the CkEditor tag I need to be able to make name={content} and value={content} similar to how they are set in the input tags

import { useState } from 'react';
import { CKEditor } from '@ckeditor/ckeditor5-react'
import ClassicEditor from '@ckeditor/ckeditor5-build-classic'
import { createPost } from '../../services/Posts.js'
import { useHistory } from 'react-router';


function CreatePosts(props) {
  const { currentUser } = props;
  const history = useHistory()
 const [formData, setFormData] = useState({
    image: '',
    category: '',
    title: '',
    subtitle: '',
    content: '',
  });
  const { image, category, title, subtitle, content } = formData;
  const [body, setBody] = useState('')

  const handleChange = (e, editor) => {
    const { value, name } = e.target;
    setFormData({
      ...formData,
      [name]: value
    });
  };

  return (
    <div>
      <img class="explore-image" src="https://res.cloudinary.com/tylerwashington98/image/upload/v1638051076/Meta-Minds/decentraland_naqec7.jpg" alt="banner image"></img>
      <div class="latest-and-all-posts-main-divs">
        <form class="create-post-form"
          onSubmit={(e) => {
            e.preventDefault();
            createPost(formData);
            history.push(`/user-posts/${currentUser?.id}`)
          }}
        >  <h1 class="create-post-header-text">Create Post</h1>
          <label class="create-post-label-and-input-div">
            <div class="create-post-input-text">Image URL</div>
            <input
              class="create-post-user-input-box"
              type='text'
              name={'image'}
              value={image}
              onChange={handleChange} />
          </label>
          <br />
          <label class="create-post-label-and-input-div">
            <div class="create-post-input-text">Category</div>
            <input
              class="create-post-user-input-box"
              type='text'
              value={category}
              name={'category'}
              onChange={handleChange} />
          </label>
          <br />
          <label class="create-post-label-and-input-div">
            <div class="create-post-input-text">Title</div>
            <input
              class="create-post-user-input-box"
              type='text'
              value={title}
              name={'title'}
              onChange={handleChange} />
          </label>
          <br />
          <label class="create-post-label-and-input-div">
            <div class="create-post-input-text">Subtitle</div>
            <input
              class="create-post-user-input-box"
              type='text'
              value={subtitle}
              name={'subtitle'}
              onChange={handleChange} />
          </label>
          <br />
          <label class="create-post-label-and-input-div">
            <div class="create-post-input-text">Content</div>
            <div className="edits">
              <CKEditor
                editor={ClassicEditor}
                onChange={(event, editor) => {
                  const data = editor.getData()
                  setBody(data)
                }}
              />
            </div>
          </label>
          <button>Submit</button>
        </form>
      </div>
    </div >
  );
}

export default CreatePosts

How do I push the data from my text editor into the formData object, in the content section? inside the CkEditor tag I need to be able to make name={content} and value={content} similar to how they are set in the input tags

How to store values such as name and mobile when create user with email and password Firebase? React Native

can somebody explain and give example on how to store extra data when crate user with firebase9? I can only create user with email and password. But how to add data such as name, image, etc? There is a function add data? but this is in firebase database which is separate from authentication. It gets different document id, and thus, I can not linked it to a specific user?
Please some clarification how to save additional data when creating a user with firebase 9 and where and how to read that data?

Slider issue – html css

thank you for looking into my issue.

I am creating a small website: http://testgod0312.000webhostapp.com/
I have an issue with my slider.

#1 I cant position the p below the image. There is a problem with the height currently absolute from top of section. More importantly, I struggle to align the p in the middle of the screen

#2 There is a weird item at the end of each p and i dont know how to remove it…

#3 I struggle to position the arrows, I would like them on the border of the image, not border of the screen

my p and img are absolute positions, because I have to overlap them. Then with a js script, an image becomes active and the other non_active

The html is:

 <div class="slider">
    <h2><span class="red">The Hierarchy</span></h2>
    <img src="assets/img/Slider/img1.jpg" alt="img1" class="img__slider active" />
    <img src="assets/img/Slider/img2.jpg" alt="img2" class="img__slider" />
    <img src="assets/img/Slider/img3.jpg" alt="img3" class="img__slider" />
    <p class="p__slider active"> test 1 blqblqbqbl blqblqbqbl blqblqbqbl blqblqbqbl </p>
    <p class="p__slider"> test 2</p>
    <p class="p__slider"> test sdaa</p>
    <div class="suivant">
        <i class="fas fa-chevron-circle-right"></i>
    </div>
    <div class="precedent">
        <i class="fas fa-chevron-circle-left"></i>
    </div>
</div>

The CSS is here (also slider.css in the asset folder on site):

.slider {
    height: 62vh;
    position: relative;
    margin: auto;
    background: var(--color1);
    justify-content: center;
    text-align: center;
}

.slider h2 {
    margin-bottom: 1rem;
    font-size: 2rem;
    text-align: center;
}

.slider img {
    object-fit: cover;
    max-width: 1200px;
    height: 50vh;
    width: 90%;
    position: absolute;
    opacity: 0;
    transition: opacity .5s;
    transform: translateX(-50%);
}

.slider img.active {
    opacity: 1;
}

.slider p {
    margin: auto;
    font-size: 1.5rem;
    position: absolute;
    top: 57vh;
    opacity: 0;
    transition: opacity .5s;
    color: var(--color2);
    max-width: 1200px;
    width: 1200px;
}

.slider p.active {
    opacity: 1;
}

.suivant, .precedent {
    color: #fff;
    font-size: 2.5rem;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    cursor: pointer;
}

.suivant {
    right: 1rem;
}

.precedent {
    left: 1rem;
}

To note, suivant refers to the next arrow and precedent to the previous arrow

Thank you for your help guys!!