QWebChannel python function returned values is always same

I am trying to get data from localStoragePy package for python and sending it to the QtWebEngineView’s js but whenever I try to get data from localStoragePy in js I always get the same output even though the actual data in the storage is different.

Code:
html

<body>
   <script src="qrc:///qtwebchannel/qwebchannel.js"></script>
   <script>
      window.onload = () => {
         new QWebChannel(qt.webChannelTransport, async (channel) => {
            window.backend = await channel.objects.backend;
            getServerStat = async () => {
               await window.backend.getValuesFromDatabaseBool("serverGo", (data) => {
                 if (data == true) {
                   emitter.emit("serverGo-true");
               } else {
                   emitter.emit('serverGo-false');
               }
               console.log(`Server Status = ${data}`);
               return Boolean(data);
            });
            };
         })
      }
   </script>
</body>

py:

import sys,os,requests,sqlite3
from jellyfin_apiclient_python import JellyfinClient
from localStoragePy import localStoragePy
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtCore import QUrl, QFileInfo, Slot, QObject
from PySide6.QtGui import QIcon
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtWebEngineCore import QWebEngineSettings
from PySide6.QtWebChannel import QWebChannel
app = QApplication(sys.argv)
os.environ['QTWEBENGINE_REMOTE_DEBUGGING'] = "9000"

storagea = localStoragePy('prayag.jellyplayer.app', 'sqlite')
storagea.setItem("App_Version", "0.1.0")

class Backend(QObject):
    @Slot(str, result=bool)
    def saveServer(self, data):
        ping = requests.get(f"{data}/System/Ping")
        if ping.content == b'"Jellyfin Server"':
            storagea.setItem('server', data)
            storagea.setItem("serverGo", True)
            return True
        else:
            storagea.setItem("serverGo", False)
            return False

    @Slot(str, result=bool)
    def getValuesFromDatabaseBool(self, object):
        print(f"Object: {object}")
        item = storagea.getItem(object)
        if item == True:
            return True
        elif item == False:
            return False
    
    @Slot(str, result=str)
    def getValuesFromDatabaseStr(self, object):
        item = storagea.getItem(object)
        return item
    
class LoginWin(QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.dir = os.path.dirname(os.path.abspath(__file__))
        self.view= QWebEngineView(self)
        self.setCentralWidget(self.view)
        # self.setWindowIcon()
        
        self.view.settings().setAttribute(QWebEngineSettings.JavascriptEnabled, True)
        self.view.settings().setAttribute(QWebEngineSettings.PluginsEnabled, True)
        
           self.view.settings().setAttribute(QWebEngineSettings.LocalContentCanAccessRemoteUrls, True)
        
        self.view.setWindowTitle('JellyPlayer App')
        self.view.setWindowIcon(QIcon(f"{self.dir}/assests/icon.png"))
        self.setWindowIcon(QIcon(f"{self.dir}/assests/icon.png"))
        self.view.load(QUrl.fromLocalFile(f"{self.dir}\renderer\html\main.html"))
        self.view.loadFinished.connect(self.handleLoaded)
        
        self.inspector = QWebEngineView()
        self.inspector.setWindowTitle("Inspector")
        self.inspector.load(QUrl("http://127.0.0.1:9000"))
        
        self.backend = Backend()
        self.channel = QWebChannel()
        self.channel.registerObject('backend', self.backend)
        self.view.page().setWebChannel(self.channel)
        
    def handleLoaded(self, ok):
        if ok:
            self.view.page().setDevToolsPage(self.inspector.page())
            self.inspector.show()

window = LoginWin()
window.showMaximized()
sys.exit(app.exec())

I am using PySide6, the emitter fire is received in another part of the code, I did try to debug this by trying to print the values in the database at the time of sending the data but the print just shows the actual value whereas the value received by the JS function is old value

Constructor Function explanation [duplicate]

I am new to JavaScript and coding in general.
I am doing an assignment and I got the question correct but don’t understand exactly why.

Here is my code:

function Person(firstName,lastName){
            this.firstName = firstName
            this.lastName = lastName
        };
  1. When invoked without the new key word Person should return undefined.

  2. When invoked with the new key word, Person should return an object with firstName and lastName.

I spent so much time tyring to answer this. I found some information on MDN that led me to the right answer but I don’t know what exactly is going on. Any explanation would be awesome. Thanks!

Async function returning twice

When I’m calling getRefreshedAccessToken().then(resolve => { return resolve } ), my mutations and queries get called twice. Even when I’m simply calling return authState.access, it works accordingly, but my query on-page fires twice?

async function getRefreshedAccessToken() {
    try {
        const authState = store.getState().auth
        const { data } = await clientAuth.mutate({
            mutation: REFRESH,
            variables: {
                input: {
                    refreshToken: authState.refresh
                }
            }
        })
        if (data && data.refreshTokens) {
            authActions.authUser(data.refreshTokens)
            return data.refreshTokens.access
        }
    } catch (error) {
        authActions.logoutUser()
        console.log(error)
        return null
    }
}

export function getAccessToken() {
    const authState = store.getState().auth
    const accessExp = authState.payload.exp <= time
    const refreshExp = authState.refreshExpires <= time

    if (authState && authState.access && authState.payload) {

        if (time + 1 * 60 <= authState.payload.exp) {
            if (time + 3 * 60 >= authState.payload.exp) {
                getRefreshedAccessToken().then(resolve => { return resolve } )
            }


        } else if (accessExp == true && refreshExp == false) {
            getRefreshedAccessToken().then(resolve => { return resolve } )
        }

        else if (accessExp == true && refreshExp == true) {
            authActions.logoutUser()
            return null
        } 

        return authState.access
    }
}

export const linkTokenHeader = setContext(async (_, { headers }) => {
  var accessToken = getAccessToken()
  return {
    headers: {
      ...headers,
      Authorization: accessToken ? `${accessToken}` : ''
    }
  }
})

Test page:

const PRIVATE = gql`
  query Private {
    privateInfo
  }
`

function Test() {
    const isAuth = useIsAuth()
    const { data } = useQuery(PRIVATE, { skip: !isAuth });
    const globalState = useSelector((state) => state)
    return (
        <>
            <pre>
                {JSON.stringify(globalState, null, 2)}
            </pre>

            {isAuth ? (
                <>
                    {data ? data.privateInfo : 'unauthorized'}

                    <button onClick={() => authActions.logoutUser()}>
                        Logout
                    </button>
                </>

            ) : (
                <Link href={"/login"}>
                    <button>
                        Authenticate
                    </button>
                </Link>
            )}
        </>
    );
}

This is the code I’m referring to and trying to rewrite to work for me:

async function getRefreshedAccessTokenPromise() {
  try {
    const { data } = await apolloClientAuth.mutate({ mutation: REFRESH })
    if (data && data.refreshToken) authTokenActions.setAuthToken(data.refreshToken)
    return data.refreshToken.token
  } catch (error) {
    authTokenActions.logOut()
    console.log(error)
    return error
  }
}

let pendingAccessTokenPromise = null

export function getAccessTokenPromise() {
  const authTokenState = reduxStoreMain.getState().authToken
  const currentNumericDate = Math.round(Date.now() / 1000)

  if (authTokenState && authTokenState.token && authTokenState.payload && currentNumericDate + 1 * 60 <= authTokenState.payload.exp) {
    if (currentNumericDate + 3 * 60 >= authTokenState.payload.exp) getRefreshedAccessTokenPromise()
    return new Promise(resolve => resolve(authTokenState.token))
  }

  if (!pendingAccessTokenPromise) pendingAccessTokenPromise = getRefreshedAccessTokenPromise().finally(() => (pendingAccessTokenPromise = null))

  return pendingAccessTokenPromise
}

I can’t seem to write this properly and would REALLY appreciate any insight on making this work. I had a comment on my last question that wasn’t answered that said: "For the "unauthorized" question, my guess is that the function getAccessToken calls to the async getRefreshedAccessToken in some cases but does not wait for the function to finish but return immediately. So there are cases where the api call is still happening in getRefreshedAccessToken, but getAccessToken has already returned, and is used for query." but can’t make sense of it.

Is it just how my react page is writen

are these vue.js bootstrap links okay. my code isn’t executing

I am trying to run the sample code from php mysql vue.js sample code

I put a file named index.html in abyss webserver doc directory with 2 php files model.php and create.php with the rest of the code from index.html. It is not executing. I am wondering if the bootstrap code is not working right.

Any cool tips are greatly appreciated!

thanks

<script  src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-vue/2.21.2/bootstrap-vue.min.js" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-vue/2.21.2/bootstrap-vue.min.js" />
<script
  src="https://cdn.jsdelivr.net/npm/[email protected]"
  integrity=""
  crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.26.1/axios.js"/>
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-vue/2.21.2/bootstrap-vue.min.css" />

… rest of code for index.html here….

Add timer to ejs file

I am working on a personal project and in this personal project, I am trying to implement a countdown timer. However, it seems that this is impossible with Node and an ejs file type. If anyone knows how to include a countdown timer into an ejs file, any help would be nice. I would like to know the basics so that way I can implement this into other projects if need be. Please note that I am using node js, express, MySQL, and passport for the project.

Thank you for your time and patience in advance!

Octal literals should not be used on JavaScript Date objects

When I use JavaScript Date objects I got two errors:

The first one from ESlint:

Octal literals should not be used.

The second one from TypeScript:

Octal literals are not available when targeting ECMAScript 5 and higher.

Example of the code:

new Date( 2025, 06, 08 )

If the month or the day starts with 0 I got the errors.

How can solve this issue without the need to remove the 0?

How to auto-scroll to specific element using JavaScript

I’m creating simple quiz plugin, but now I’m in dilemma, because don’t have an idea how to make options to auto-scroll to the top of the Explanation Box after visitor choose an answer (right or wrong, explanation box is same with same content. Note – explainer box is hidden until visitor clicks with mouse on checkbox of any offered answer.

Below is JavaScript code I have so far:

var wpvqgr = wpvqgr || {};

(function($) 
{
    $(document).ready(function() 
    {
        wpvqgr.selectAnswer = function($question, question_id, $answer, answer_id)
        {
            // Don't let the user play twice the same question!
            if ($answer.hasClass('wpvqgr-disabled-answer') && !wpvqgr.vars.quiz.settings.trivia_hiderightwrong) {
                return;
            }

            // Right or wrong?
            var rightAnswers    =  wpvqgr.getRightAnswers(question_id);
            var isRight         =  (rightAnswers.indexOf(answer_id) > -1);

            // Store data
            var _answers = wpvqgr.getStore('answers') || { 'questions' : [] };
            _answers.questions[question_id] = { 
                'answer_id'     : answer_id,
                'isRight'       : isRight,
                'rightAnswers'  : rightAnswers,
            };
            wpvqgr.setStore('answers', _answers);

            // Display Right or Wrong answers
            if (wpvqgr.vars.quiz.settings.trivia_hiderightwrong != 'yes')
            {
                // First, disable every answers
                $question.find('.wpvqgr-answer').removeClass('wpvqgr-selected-answer').addClass('wpvqgr-disabled-answer');

                // Add explanation
                var $explanation = $question.find('div.wpvqgr-explanation');
                $explanation.find('div.wpvqgr-explanation-content').html(wpvqgr.vars.quiz.questions[question_id].wpvqgr_quiz_questions_explanation);

                if (isRight) 
                {
                    $explanation.find('h3.wpvqgr-thats-right').show();
                    $answer.addClass('wpvqgr-right-answer');
                } 
                else 
                {
                    $explanation.find('h3.wpvqgr-thats-wrong').show();
                    $answer.addClass('wpvqgr-wrong-answer');
                    $.each(rightAnswers, function(index, answer_id){
                        $question.find('.wpvqgr-answer[data-id=' + answer_id + ']').addClass('wpvqgr-right-answer');
                    });
                }

                $explanation.show();
            }
            else
            {
                $question.find('.wpvqgr-answer').removeClass('wpvqgr-selected-answer');
                $answer.addClass('wpvqgr-selected-answer');
            }

            // Update visual checkbox
            $question.find('div.wpvqgr-checkbox-picture').removeClass('wpvqgr-checkbox-checked-picture');
            $answer.find('div.wpvqgr-checkbox-picture').addClass('wpvqgr-checkbox-checked-picture');

            // Not a visual class, just marked as
            $answer.addClass('wpvqgr-is-selected-answer');
        };

        wpvqgr.computeResults = function()
        {
            var answers     =  wpvqgr.getStore('answers') || { 'questions' : [] };
            var finalScore  =  0;

            // Score
            $.each(answers.questions, function (q_id, answer_data) {
                if (answer_data.isRight) {
                    finalScore++;
                }
            });

            // Appreciation
            var appreciation = wpvqgr.getAppreciation(finalScore);

            // Store global data for Facebook, page refresh and other stuff
            wpvqgr.setStore('finalScore', finalScore);
            wpvqgr.setStore('appreciation', appreciation);
        };
        
            //Autoscroll
            
            
            
        /**
         * Integrate results in view
         * @return {[type]} [description]
         */
        wpvqgr.integrateResults = function ()
        {
            wpvqgr.parseResults('quizname', wpvqgr.vars.quiz.general.name);
            wpvqgr.parseResults('score', wpvqgr.getStore('finalScore'));
            wpvqgr.parseResults('total', wpvqgr.getStore('answers').questions.length);
            wpvqgr.parseResults('description', wpvqgr.getStore('appreciation').content);
        }

        wpvqgr.getAppreciation = function(score)
        {
            var finalAppreciationId = -1;
            var finalAppreciationScoreStep = 9999;

            $.each(wpvqgr.vars.quiz.appreciations, function (ap_id, data) 
            {
                var app_score = parseInt(data.score);
                if (score <= app_score && finalAppreciationScoreStep > app_score) 
                {
                    finalAppreciationScoreStep  =  app_score;
                    finalAppreciationId         =  ap_id;
                }
            });

            // No appreciation found!
            if (finalAppreciationId == -1) {
                return { 'content':'', 'redirect':'', 'picture':'', 'score':-1 }
            } else {
                return wpvqgr.vars.quiz.appreciations[finalAppreciationId];
            }
        };

        wpvqgr.getRightAnswers = function(question_id)
        {
            var rightAnswers = [];

            var answers = wpvqgr.vars.quiz.questions[question_id]['wpvqgr_quiz_questions_answers'];
            $.each(answers, function(id, data) {
                if (data['wpvqgr_quiz_questions_answers_right']) {
                    rightAnswers.push(id);
                }
            });

            return rightAnswers;
        };

        wpvqgr.getFinalScore = function()
        {
            return wpvqgr.getStore('finalScore');
        };
    });

})(jQuery);

/**
 * Store
 *
 * questions[$id] = $answer_id
 *
 *
 * 
 */
<?php global $wpvqgr_quiz, $wpvqgr_quiz_columns, $wpvqgr_resources_dir_url, $wpvqgr_skin_dir_url; ?>

<!-- Load CSS Skin Theme -->
<style> @import url('<?php echo $wpvqgr_resources_dir_url . 'css/bootstrap-wrapper.css'; ?>'); </style>
<style> @import url('<?php echo $wpvqgr_resources_dir_url . 'icons/fa/css/font-awesome.min.css'; ?>'); </style>
<style> @import url('<?php echo $wpvqgr_resources_dir_url . 'css/fo-style.css'; ?>'); </style>
<style> @import url('<?php echo $wpvqgr_skin_dir_url . 'style.css'; ?>'); </style>

<!-- Custom style -->
<style>
    <?php if ($wpvqgr_quiz->getSetting('progessbarcolor') != ''): ?>
        .wpvqgr-wrapper button.wpvqgr-button.wpvqgr-playagain,
        .wpvqgr-wrapper button.wpvqgr-button.wpvqgr-start-button,
        .wpvqgr-wrapper div.wpvqgr-continue button.wpvqgr-button,
        .wpvqgr-wrapper button.wpvqgr-button.wpvqgr-askinfo-submit,
        .wpvqgr-progress .progress-bar {
            background-color:<?php echo $wpvqgr_quiz->getSetting('progessbarcolor'); ?>;
        }
    <?php endif; ?>

    <?php echo $wpvqgr_quiz->getSetting('global_custom_css'); ?>
</style>

<!-- Facebook SDK -->
<script type="text/javascript">
    (function(d, s, id){
         var js, fjs = d.getElementsByTagName(s)[0];
         if (d.getElementById(id)) {return;}
         js = d.createElement(s); js.id = id;
         js.src = "//connect.facebook.net/en_US/sdk.js";
         fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
</script>
<!-- / Prepare sharing options -->
    
<?php echo apply_filters('wpvqgr_public_version', "<!--  Quiz Created with WP Viral Quiz (v".WPVQGR_VERSION.") - https://www.ohmyquiz.io/discover -->"); ?>

<a name="wpvqgr"></a>

<div class="wpvqgr-wrapper">
    <div class="container-fluid">

        <?php if ($wpvqgr_quiz->getSetting('startbutton') && !$wpvqgr_resultsOnly): ?>
            <div class="wpvqgr-intro">
                <?php if ($wpvqgr_quiz->getSetting('startbuttonintro')): ?>
                    <p><?php echo $wpvqgr_quiz->getSetting('startbuttonintro'); ?></p>
                <?php endif ?>
                <button class="wpvqgr-start-button wpvqgr-button"><?php echo $wpvqgr_quiz->getSetting('customlabel_startbutton'); ?></button>
            </div>
        <?php endif ?>

        <div id="wpvqgr-<?php echo $wpvqgr_quiz->getId(); ?>" class="wpvqgr <?php echo $wpvqgr_quiz->getType(); ?>">

            <div class="wpvqgr-a-d-s">
                <?php echo do_shortcode($wpvqgr_quiz->getSetting('global_ads_before')); ?>
                <?php echo do_shortcode($wpvqgr_quiz->getSetting('ads_before')); ?>
            </div>

            <?php if ($wpvqgr_quiz->getPageCounter() > 1 && in_array('top', $wpvqgr_quiz->getSetting('progessbar'))): ?>
                <!-- Progress bar -->
                <div class="wpvqgr-progress wpvqgr-progress-top progress">
                    <div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                </div>
            <?php endif ?>

            <?php if (!$wpvqgr_resultsOnly): ?>
                <a href="" id="wpvqgrquestion"></a>
                <div class="wpvqgr-page-0 wpvqgr-page" data-id="0">

                    <?php   
                        $wpvqgr_questions = $wpvqgr_quiz->getQuestionsAndBlocks();
                        $q_real_id = -1;
                        foreach($wpvqgr_questions as $q_id => $question):

                            // Type and content
                            $q_type             =  $question['_type'];
                            $q_content          =  ($q_type == 'wpvqgr_quiz_htmlblocks') ? $question['wpvqgr_quiz_htmlblocks_content'] : $question['wpvqgr_quiz_questions_content'];

                            // Real ID (ignore HTML blocks)
                            if ($q_type == 'wpvqgr_quiz_questions') {
                                $q_real_id++;
                            }

                            // Pagination
                            $q_isTherePage      =  ($question['wpvqgr_quiz_questions_addpage'] && isset($wpvqgr_questions[$q_id+1]));
                            $currentPage_id     =  (!isset($currentPage_id)) ? 0 : $currentPage_id;

                            // Picture
                            if ($q_type == 'wpvqgr_quiz_questions') {
                                $q_picture_id       =  $question['wpvqgr_quiz_questions_picture'];
                                $q_picture_info     =  WPVQGR_Snippets::wpGetAttachment($q_picture_id);
                                $q_picture_url      =  wp_get_attachment_url($q_picture_id);
                            }
                    ?>

                        <div class="row">
                            <div class="col-sm-12">

                                <!-- Global ads between questions -->
                                <?php if ( $q_real_id > 0 && $wpvqgr_quiz->getSetting('global_ads_between_count') > 0 && ($q_real_id % $wpvqgr_quiz->getSetting('global_ads_between_count') == 0) ): ?>
                                    <?php echo $wpvqgr_quiz->getSetting('global_ads_between_content'); ?>
                                <?php endif; ?>
                                
                                <!-- HTML Blocks -->
                                <?php if ($q_type == 'wpvqgr_quiz_htmlblocks'): ?>
                                    <div class="wpvqgr-htmlblock">
                                        <?php echo do_shortcode($q_content); ?>
                                    </div>
                                <?php else: ?>
                                <!-- Regular question -->
                                
                                    <div class="wpvqgr-question" data-id="<?php echo $q_real_id; ?>">
                                        <div class="wpvqgr-question-label"><?php echo do_shortcode(nl2br($q_content)); ?></div>
                                        
                                        <?php if (is_numeric($q_picture_id)): ?>
                                            <div class="wpvqgr-question-picture">
                                                <figure class="figure">
                                                    <img src="<?php echo $q_picture_url; ?>" class="figure-img img-fluid" alt="<?php echo htmlentities($q_picture_info['alt']); ?>" />
                                                    <?php if ($q_picture_info['caption'] != ''): ?>
                                                        <figcaption class="figure-caption"><?php echo $q_picture_info['caption']; ?></figcaption>
                                                    <?php endif; ?>
                                                </figure>
                                                <?php if (function_exists ('adinserter')) echo adinserter (1); ?> <!-- / First Add Code -->
                                            </div>
                                        <?php endif ?>
                                
                                        <div class="row">
                                            <?php 
                                                $smartColumns = WPVQGR_Snippets::getSmartColumnsSize($question, $wpvqgr_quiz_columns);
                                                foreach ($question['wpvqgr_quiz_questions_answers'] as $a_id => $answer):
                                                    // Answer
                                                    $a_label            =  $answer['wpvqgr_quiz_questions_answers_answer'];

                                                    // Picture
                                                    if ($smartColumns['displayPicture'])
                                                    {
                                                        $a_picture_id    =  $answer['wpvqgr_quiz_questions_answers_picture'];
                                                        if ($a_picture_id == 0) {
                                                            $a_picture_info  =  array('alt' => '', 'caption' => '');
                                                            $a_picture_url   =  WPVQGR_PLUGIN_URL . '/resources/images/picture-placeholder.jpg';
                                                        } else {
                                                            $a_picture_info  =  WPVQGR_Snippets::wpGetAttachment($a_picture_id);
                                                            $a_picture_url   =  wp_get_attachment_image_src($a_picture_id, 'wpvqgr-square-answer');
                                                            $a_picture_url   =  $a_picture_url[0];
                                                        }
                                                    }
                                            ?>
                                                    <div class="wpvqgr-answer-col col-xs-<?php echo $smartColumns['xs-size']; ?> col-md-<?php echo $smartColumns['md-size']; ?>">
                                                        <div class="wpvqgr-answer" data-id="<?php echo $a_id; ?>">

                                                            <?php if ($wpvqgr_quiz->getType() == 'wpvqgr_quiz_perso'): ?>
                                                                <!-- Multipliers -->
                                                                <?php foreach ($answer['wpvqgr_quiz_questions_answers_multipliers'] as $p_id => $value): ?>
                                                                    <input type="hidden" name="wpvqgr_answer_multipliers[]" data-pid="<?php echo (int)$p_id; ?>" value="<?php echo (int)$value; ?>" />
                                                                <?php endforeach ?>
                                                            <?php endif; ?>

                                                            <?php if ($smartColumns['displayPicture']): ?>
                                                                <div class="wpvqgr-answer-picture">
                                                                    <figure class="figure">
                                                                        <img src="<?php echo $a_picture_url; ?>" class="figure-img img-fluid" alt="<?php echo htmlentities($a_picture_info['alt']); ?>" />
                                                                        <?php if ($a_picture_info['caption'] != ''): ?>
                                                                            <figcaption class="figure-caption"><?php echo $a_picture_info['caption']; ?></figcaption>
                                                                        <?php endif; ?>
                                                                    </figure>
                                                                </div>
                                                            <?php endif ?>
                                                            
                                                            <?php if ($a_label != ''): ?>
                                                                <div class="wpvqgr-checkbox">
                                                                    <div class="wpvqgr-checkbox-picture wpvqgr-checkbox-unchecked-picture"></div>
                                                                    <span class="wpvqgr-answer-label"><?php echo do_shortcode(stripslashes($a_label)); ?></span>
                                                                    <hr class="wpvqgr-clear" />
                                                                </div>
                                                            <?php endif ?>
                                                        </div>
                                                    </div>
                                            <?php endforeach; ?>
                                        </div>
                                        <div class="row"><div class="col-sm-12">
                                                <div class="wpvqgr-explanation">
                                                    <center><h6>⇩ SCROLL DOWN TO CONTINUE ⇩</h6></center>
                                                    <h3 class="wpvqgr-thats-right"><?php echo $wpvqgr_quiz->getSetting('customlabel_right'); ?></h3>
                                                    <h3 class="wpvqgr-thats-wrong"><?php echo $wpvqgr_quiz->getSetting('customlabel_wrong'); ?></h3>
                                                    <div class="wpvqgr-explanation-content"></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div> <!-- .question -->
                                <?php endif; ?>
                            </div> <!-- / col -->
                        </div> <!-- / row -->
                        <div class="autoscroll>">
                        </div>
                        <div class="wpvqgr-continue">
                            <?php if (function_exists ('adinserter')) echo adinserter (2); ?> <!-- / Second Add Code -->
                            <button class="wpvqgr-button" style="background:<?php echo $wpvqgr_quiz->getSetting('progessbarcolor'); ?>;">
                                <?php echo $wpvqgr_quiz->getSetting('customlabel_continuebutton'); ?>
                            </button>
                        </div>
                    
                        <?php 
                            if ($q_isTherePage): $currentPage_id++; 
                        ?>
                            </div> <!-- close previous page -->
                            <div class="wpvqgr-page-<?php echo $currentPage_id; ?> wpvqgr-page" data-id="<?php echo $currentPage_id; ?>">
                        <?php endif ?>
                    <?php endforeach; ?>
                </div> <!-- Final page close -->
            <?php endif; ?>

            <a id="wpvqgr-resultarea"></a>

            <!-- Force to share -->
            <div class="row">
                <div class="col-xs-12 col-md-10 offset-md-1">
                    <div class="wpvqgr-forcetoshare">
                        <h3><?php echo __("Share the quiz to show your results !", 'wpvq'); ?></h3>
                        <button class="wpvqgr-button wpvqgr-social-facebook wpvqgr-force-share" data-title="<?php echo $wpvqgr_quiz->getSetting('global_template_facebook_title'); ?>" data-description="<?php echo $wpvqgr_quiz->getSetting('global_template_facebook_description'); ?>"><i class="fa fa-facebook-square" aria-hidden="true"></i>&nbsp; <?php echo __('Share on Facebook', 'wpvq'); ?></button>
                    </div>
                </div>
            </div>

            <!-- Force to give some informations -->
            <div class="row">
                <div class="col-xs-12 col-md-10 offset-md-1">
                    <div class="wpvqgr-askinfo">
                        <h3><?php echo $wpvqgr_quiz->getSetting('customlabel_askinfotitle'); ?></h3>
                        <form action="" method="GET">
                            <?php foreach($wpvqgr_quiz->getSetting('askinfo_fields') as $field): ?>
                                <?php 
                                    $field_slug         =  WPVQGR_Snippets::slugify($field['wpvqgr_settings_askinfo_fields_field_label']); 
                                    $is_required_field  =  ($field['wpvqgr_settings_askinfo_fields_field_optional'] != 'yes');
                                ?>
                                <div class="form-group">
                                    <label for="wpvqgr-<?php echo $field_slug; ?>"><?php echo $field['wpvqgr_settings_askinfo_fields_field_label']; ?></label>
                                    <input type="<?php echo $field['wpvqgr_settings_askinfo_fields_field_type']; ?>" class="form-control" name="<?php echo $field_slug; ?>" id="wpvqgr-<?php echo $field_slug; ?>" <?php if($is_required_field): ?>required="true"<?php endif; ?>/>
                                </div>
                            <?php endforeach; ?>

                            <?php if ($wpvqgr_quiz->getSetting('global_gdpr_enabled') == 1): ?>
                                <div class="form-check gdpr-area">
                                    <label class="form-check-label">
                                        <input type="checkbox" class="form-check-input" name="wpvq_gpdr" id="wpvq_gpdr_checkbox" required="true" />
                                        <?php echo $wpvqgr_quiz->getSetting('global_gdpr_message'); ?>
                                    </label>
                                </div>
                            <?php endif ?>

                            <div class="form-group" style="text-align:center;">
                                <button type="submit" class="wpvqgr-button wpvqgr-askinfo-submit"><?php echo $wpvqgr_quiz->getSetting('customlabel_askinfobutton'); ?></button>
                            </div>
                        </form>
                        
                        <?php if ($wpvqgr_quiz->getSetting('askinfo_ignore')): ?>
                            <p class="wpvqgr-askinfo-ignore"><?php echo $wpvqgr_quiz->getSetting('customlabel_askinfoignore'); ?></p>
                        <?php endif ?>
                    </div>
                </div>
            </div>

            <!-- Show results -->
            <div class="row">
                <div class="col-sm-12">
                    <div class="wpvqgr-results">

                        <div class="wpvqgr-a-d-s">
                            <?php echo do_shortcode($wpvqgr_quiz->getSetting('global_ads_aboveresults')); ?>
                            <?php echo do_shortcode($wpvqgr_quiz->getSetting('ads_aboveresults')); ?>
                        </div>

                        <div class="wpvqgr-results-box <?php echo $wpvqgr_quiz->getType(); ?>">
                        
                            <div class="wpvqgr-top-result">
                                <div class="wpvqgr-quiz-name"><?php echo stripslashes($wpvqgr_quiz->getName()); ?></div>
                                <h3><?php echo $wpvqgr_quiz->getSetting('global_template_result'); ?></h3>
                                <div class="wpvqgr-result-description">%%description%%</div>
                            </div>

                            <div class="wpvqgr-additional-results">
                                <div class="wpvqgr-additional-results-template">
                                    <h3><?php echo $wpvqgr_quiz->getSetting('global_template_additional_results'); ?></h3>
                                    <div class="wpvqgr-result-description">%%description%%</div>
                                </div>
                            </div>

                            <div class="wpvqgr-a-d-s">
                                <?php echo do_shortcode($wpvqgr_quiz->getSetting('global_ads_afterresults')); ?>
                                <?php echo do_shortcode($wpvqgr_quiz->getSetting('ads_afterresults')); ?>
                            </div>

                            <?php if ($wpvqgr_quiz->getSetting('displaysharing')): ?>
                                <div class="wpvqgr-sharing">
                                    <?php if (!in_array('facebook', $wpvqgr_quiz->getSetting('global_socialmedia_hide'))): ?>
                                        <button class="wpvqgr-button wpvqgr-social-facebook" data-title="<?php echo $wpvqgr_quiz->getSetting('global_template_facebook_title'); ?>" data-description="<?php echo $wpvqgr_quiz->getSetting('global_template_facebook_description'); ?>"><i class="fa fa-facebook-square" aria-hidden="true"></i>&nbsp; <?php echo __('Share on Facebook', 'wpvq'); ?></button>
                                    <?php endif; ?>
                                     
                                    <!-- Twitter -->
                                    <?php if (!in_array('twitter', $wpvqgr_quiz->getSetting('global_socialmedia_hide'))): ?>
                                        <button class="wpvqgr-button wpvqgr-social-twitter" data-tweet="<?php echo $wpvqgr_quiz->getSetting('global_template_twitter'); ?>" data-mention="<?php echo $wpvqgr_quiz->getSetting('twittermention'); ?>" data-hashtag="<?php echo $wpvqgr_quiz->getSetting('twitterhashtag'); ?>"><i class="fa fa-twitter-square" aria-hidden="true"></i>&nbsp; <?php echo __('Share on Twitter', 'wpvq'); ?></button>
                                    <?php endif ?>

                                    <!-- VK -->
                                    <?php if (!in_array('vk', $wpvqgr_quiz->getSetting('global_socialmedia_hide'))): ?>
                                        <button class="wpvqgr-button wpvqgr-social-vk" data-title="<?php echo $wpvqgr_quiz->getSetting('global_template_vk_title'); ?>" data-description="<?php echo $wpvqgr_quiz->getSetting('global_template_vk_description'); ?>"><i class="fa fa-vk" aria-hidden="true"></i>&nbsp; <?php echo __('Share on VK', 'wpvq'); ?></button>
                                    <?php endif ?>
                                </div>
                            <?php endif; ?>
                        </div>

                        <?php if ($wpvqgr_quiz->getSetting('playagain')): ?>
                            <button class="wpvqgr-button wpvqgr-playagain"><?php echo $wpvqgr_quiz->getSetting('customlabel_playagainbutton'); ?></button>
                        <?php endif; ?>

                    </div>
                </div>
            </div>

            <?php if ($wpvqgr_quiz->getPageCounter() > 1 && in_array('bottom', $wpvqgr_quiz->getSetting('progessbar'))): ?>
                <!-- Progress bar -->
                <div class="wpvqgr-progress wpvqgr-progress-bottom progress">
                    <div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                </div>
            <?php endif ?>

            <div class="wpvqgr-a-d-s">
                <?php echo do_shortcode($wpvqgr_quiz->getSetting('global_ads_after')); ?>
                <?php echo do_shortcode($wpvqgr_quiz->getSetting('ads_after')); ?>
            </div>

            <?php if ($wpvqgr_quiz->getSetting('promote')): ?>
                <div class="wpvqgr-promote">
                    <p>
                        <?php _e("This quiz has been created with", 'wpvq'); ?> <a href="https://www.ohmyquiz.io/discover" target="_blank">WordPress Viral Quiz</a>
                    </p>
                </div>
            <?php endif; ?>
        </div> <!-- / #wpvqgr -->
    </div> <!-- / container -->

    <!-- Loading -->
    <div class="row">
        <div class="wpvqgr-loader">
            <p>
                <i class="fa fa-spinner fa-spin fa-3x fa-fw"></i>
                <span class="sr-only"><?php _e("Loading...", 'wpvq'); ?></span>
            </p>
        </div>
    </div>
</div> <!-- / Bootstrap wrapper -->

I tried with dummy DIV element, but without success (to have it as an anchor, because explainer element is invisible).

Code samples I tried so far are:

$('wpvqgr-answer').click(function() {
         $('html,body').animate({scrollTop: ('#autoscroll').offset().top - staticHeaderHeight}, 'slow');
         return true;
         });

And:

$('.wpvqgr-answer').click(function () {
         $("html, body").animate({ scrollTop: $(el).closest(':visible').offset().top}, 400);
         return true;
        });

And, this was desperate act of self destruction:

 $('.wpvqgr-answer').click(() => {
      $('.wpvqgr-explanation').toggle('smooth', () => {
      $('.wpvqgr-explanation').get(0).scrollIntoView();
       });
   });

I hope you have some kind of overview now, even in basic sense. Any guidance appreciated. Thank you

Problems receiving value from a select and displaying in a table

I’m having trouble rendering data I get from my database.
I created a computed activity to try to display data in a table. However, when receiving this data, one of them ends up being returned in a numeric value.

email: “[email protected]” id: 1 name: “Antonio” profession: “Dev” role:
“1”

This role is related to my list of activities:

export const AvailableUserRoles: Array<UserRoleOptions> = [
      {
        label: 'Administrator',
        value: 1
      },  
      {
        label: 'Counter',
        value: 2
      },
      {
        label: 'Tester',
        value: 5
      },
      {
        label: 'employees',
        value: 6
      }

]

On my computed property I tried doing the following function but it didn’t work well:

  const roleName = computed(() => {      
      return (item: unknown) => {
        return AvailableUserRoles.map((option) => {
          if(item == option.value){
            return option.label
          }else{
            return item
          }
        })
      }
   })

My table row:

<template #body-cell-role="{ col, row }">
  <q-td :class="col.__tdClass">
     {{roleName(row.role)}}
  </q-td>
</template> 

Fetch patch not found error for plural route

I’ve been having an issue with the PATCH function for fetch where I want to increment a deep value in a JSON file. I’ve seen a similar answer on here about plural routes to patch nested values but whenever I do i get a 404 error saying PATCH at the URL is not found. Here is my JSON data and my fetch function. Please let me know what you think, I’m very new to fetch and have tried many things to fix this.

//let capContainer = document.getElementById("fundsDisplayed");
const increaseValue = () => {
    //  capContainer.value ++;
    fetch("http://localhost:3001/trustRoutes/1", {
        method: "GET", 
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(
            {
                "capitalAllocation": 100000//capContainer.value
            }
        )
    })
    .then(response => response.json())

    .then(data => {
        capContainer.innerText = `${data.trusts.capitalAllocation} capitalAllocation`;
    })

}
{    
    "trusts":[
        {
            "id": 1,
            "trustName": "Orkney",
            "capitalAllocation": 64272000,
            "peopleServed": 21349,
            "staff": 565,
            "trustMembers": [
                    {
                    
                            "member": {
                                "name": "Meghan McEwen",
                                "position": "chair",
                                "funds": "100 000"    
                            }
                        
                    
                    }
               ]
           }
       ]
}

By the way, my backend json is using a express rest api and I have tried adding cors middleware and headers which i think fixed those error

By the way, my backend json is using a express rest api and I have tried adding cors middleware and headers which i think fixed those error. When using GET methods before I had no issue but I’m not sure of any alterative way to patch values deeper inside other than using pluralroutes. Also, looking at other answers, I can’t seem to find anything exactly similar as this value should exist.

Navbar does not work for mobile devices in Nextjs Project

I am working on creating a personal website, and I just realized that the navbar I am using does not work on mobile. The navbar button appears, but the content doesn’t appear after clicking it. The link to said webpage is ezrajohnson.me, so you can see the difference between the computer and mobile renderings. I saw someone else had a similar problem two years ago on here, but somehow their solution didn’t work for me.

This is the navbar file:

import React from 'react'
import { Nav, Button } from 'react-bootstrap';
import Link from 'next/link'

export default function Navbar() {
  return (
    <Nav className="navbar defaultExpanded navbar-expand-lg navbar-dark bg-dark">
      <div className="container-fluid">
        <Link href="/">
          <a className="navbar-brand">Ezra Johnson</a>
        </Link>
        <Button className="navbar-toggler" type="button" data-toggle="collapse" data-target="navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
          <span className="navbar-toggler-icon"></span>
        </Button>

        <div className="collapse navbar-collapse" id="navbarNav">
          <ul className="navbar-nav mr-auto">
            <li className="nav-item active">
              <Link href="/">
                <a className="nav-link">Home </a>
              </Link>
            </li>
            <li className="nav-item">
              <Link href="/projects">
                <a className="nav-link">Projects</a>
              </Link>
            </li>
            <li className="nav-item">
              <Link href="/experience">
                <a className="nav-link">Experience</a>
              </Link>
            </li>
          </ul>
        </div>
      </div>
    </Nav>
  )
}

Thanks 🙂

I tried using react-bootstrap instead of bootstrap, but that didn’t work. Neither did using the code solutions I found here on StackOverflow for the button.

Click and drag to select and move points on a SVG

With a SVG with lines and points like this:

svg line { stroke: black; stroke-width: 2px; }
<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" id="svg">
<circle id="1a" cx="20" cy="20" r="3"></circle><circle id="1b" cx="20" cy="120" r="3"></circle><line id="1c" x1="20" y1="20" x2="20" y2="120"></line>
<circle id="2a" cx="20" cy="120" r="3"></circle><circle id="2b" cx="60" cy="80" r="3"></circle><line id="2c" x1="20" y1="120" x2="60" y2="80"></line>
<circle id="3a" cx="60" cy="80" r="3"></circle><circle id="3b" cx="100" cy="120" r="3"></circle><line id="3c" x1="60" y1="80" x2="100" y2="120"></line>
<circle id="4a" cx="100" cy="120" r="3"></circle><circle id="4b" cx="140" cy="100" r="3"></circle><line id="4c" x1="100" y1="120" x2="140" y2="100"></line>
<circle id="5a" cx="140" cy="100" r="3"></circle><circle id="5b" cx="100" cy="20" r="3"></circle><line id="5c" x1="140" y1="100" x2="100" y2="20"></line>
</svg>

is there a way with a HTML <svg> to be able to click and drag to select points? So that we can then mouse drag to move these points?

Before re-inventing the wheel, are there ways to do this directly with a <svg>?

enter image description here

Javascript reduce and map on nested array of objects

i have an array of objects in

[
  {
    "country": "USA",
    "payment": [
      {
        "paymentType": "Visa",
        "count": 1000
      },
      {
        "paymentType": "MasterCard",
        "count": 1000
      }
    ]
  },
  {
    "country": "CANADA",
    "payment": [
      {
        "paymentType": "Visa",
        "count": 1000
      },
      {
        "paymentType": "MasterCard",
        "count": 1000
      }
    ]
  },
  {...}
]

I want to transform it into

[
["USA" , "VISA" , 10000 ], 
["USA","Mastercard",1000],
[countryName2, paymentType,count] , ...
]

Can someone help me>?

I tried doing :

const data2 = data.map(function(elem) {
  return [
    elem.country,
    elem.payment.map(b=> b.paymentType),
    elem.payment.map(c=>c.count),
  ]
})

but the output i get is not what i want, if someone could show how to do it,

Font in Next.js / Tailwind CSS app initially bold but then unintentionally reverts

I’m working on a pretty bare bones Next app using Tailwind and I just installed a custom variable-weight font Raleway (downloaded the family in .ttf format and converted it to .woff2) but for some reason am unable to change the font weight via the font-bold, font-extrabold, etc custom classes… at least permanently. The Raleway font is successfully showing at all to begin with.

Shown below, a refresh makes the page immediately flash with what’s seemingly the correct style but then reverts to something else.

The ephemeral, initially-present bold text upon refreshing.

Could it have something to do with the font block period transitioning to the font swap period? Below is my styles/globals.css:

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
    @font-face {
        font-family: 'Raleway';
        src: url('/fonts/Raleway-Thin.woff2') format('woff2');
        font-weight: 400;
        font-display: swap;
        font-style: normal;
    }
}

And here’s my tailwind.config.js:

module.exports = {
  content: [
    './pages/**/*.{js,ts,jsx,tsx}',
    './components/**/*.{js,ts,jsx,tsx}',
  ],
  theme: {
    extend: {
      fontFamily: {
        raleway: ['Raleway', 'sans-serif'],
      },
    },
  },
  plugins: [],
}