React Native: How do I change the scroll position of a ScrollView when the element is not visible?

I have a horizontal FlatList which renders a list of vertical ScrollView cards.

When I scroll the FlatList, I would like the ScrollView cards to reset their scroll position to the top. I do not want to reset the scroll position of the larger FlatList, instead, on each FlatList scroll, I want each individual ScrollView to scrollToStart if that ScrollView is not visible on the screen. In descriptive skeleton code it would be something like…

const onFlatlistScroll = { (scrollViewCard) => {
  if (scrollViewCard.visible !== true && scrollViewCard.scrollPositionY !== 0) {
    scrollViewCard.scrollTo({'x': 0, 'y': 0})
  }
}}

I tried using the FlatList’s onViewableItemsChanged and viewabilityConfig properties to tell if an individual scrollViewCard was not visible, however, I have an accessibility feature that changes the fontFamily and fontSize properties of Text elements with an onPress to make text easier to read and this onPress event throws an error with onViewableItemsChanged for ‘on the fly changes not supported’.

Is there new technology to push data from DB update to client [closed]

I built a live auction platform primarily in php/JQuery/JS/MySQL many years ago. It basically had a back end where i would poll the DB for any bids, if there was/were i would push the data to all users via PubNub mechanism. If there were no bids after 5 seconds, i would close that lot off and move onto the next one and update all users via the same PubNub mechanism.

I am now redesigning the platform to be fully automated. I am looking to implement web sockets as the connection method. I want to implement a trigger which fires when a new bid comes in then pushes the info to all users. I also want to create a stored procedure which automatically checks if news bids have come in in the last 5 seconds, if not, close the active lot and set new active lot to n+1. This would be wrapped in an event which fires every second. That seems pretty straight forward.

My question is, once the stored procedure has determined that its time to move onto a new lot OR a new bid has come in, how can i push that information to the user?

Most of the solutions out there seem to be 6-8 years old, and i was wondering if there is any new technology i can look into?

The obvious and somewhat antiquated way for me is to constantly poll from the users end, but this does not seem to be a scalable solution, or take advantage of new technology out there. Or is/does it?

I have looked at UDF/sys_exec() as a solution but a) a lot of people says its bad practise and its not designed to do that, and b) if i do execute a secondary .php script would there be a way to push the data to the user via the same websocket connection already established?

PS. I am also open to other options/opinions in terms of how the platform is logically designed/implemented.

Thanks.

Adding an Iframe into a button using HTML

I am trying to make a website using Glitch. I was confused when I saw this problem, I came across of wondering how I could add multiple I-frames on different buttons and open them in new windows! How would I do that? Also, I was wondering how I could make it look nicer (clean ui) than it originally was

Here is the code:

<html>
 
  <head>
  </head>
 <title>Hello World</title>
  <body>
    <button>Test</button>
    <script>
      
      var urlObj = new window.URL(window.location.href);
      var url = "LINK NOT SET YET";
      if (url) {
        var win;
 
        document.querySelector('button').onclick = function() {
          if (win) {
            win.focus();
          } else {
            win = window.open();
            win.document.body.style.margin = '0';
            win.document.body.style.height = '100vh';
            var iframe = win.document.createElement('iframe');
            iframe.style.border = 'none';
            iframe.style.width = '100%';
            iframe.style.height = '100%';
            iframe.style.margin = '0';
            iframe.src = url;
            win.document.body.appendChild(iframe);
          }
          document.querySelector('button').style.bacground = 'grey';
          document.querySelector('button').innerHTML = "REFRESH TO USE";
        };
      }
 
    </script>
  </body>
 
</html>
 

Best Regards,
Quacked
w

Trying to design HTML site, and when I was making I-frames, I tried copying and pasting the code over and over. Nothing…

Using a loop to increment each slot of an array by 1. The size of the array is the argument passed into a function

i am trying to solve a code challenge that asks me to fill an array with the value passed as an argument in a function.

For example = fizzBuzz(10)

should return an Array with 10 slots and for each slot increment 1

[0, 1, 2, 3 ,4, 5, 6, 7, 8, 9, 10]

i have tried with a loop and with the fill method but i am having difficulties on this.

This is the first step of the algorithm. Can someone help me ?

Here is my last attempt:

function fizzbuzz(n) {
  // Write your code here
  const array = new Array(n)
    for(let i = 0; i < n; i++) {
    array.fill(0, n))
    }
  return array
}

This wont work cause the fill method is only called once for every slot i guess. Can someone help me ?

I have tried with the forEach method, fill method and with a loop, but i am unable to solve the first step of this algorithm.

I need nelp solving the first step of this algorithm.

Mock Chrome Storage API to test extension popup

I am building a chrome extension. For this I use the Chrome Storage API in a script that runs when the popup is opened (popup.js):

chrome.storage.sync.get(...);

However, it’s much easier to develop and test the popup if I open it directly in the browser as its own web page instead of just testing it as an actual popup, since I then also have Inspect element and similar tools.
The only problem is that the Storage API is meant for extensions and any uses of it in my code will directly result in an error when I open the popup as a web page. So I thought it would be useful to just mock the API calls. Then I could simulate storage data as well. To do this, so far I’m using something like the following at the top of popup.js:

let chrome = {
    storage: {
        sync: {
            get: function (a, b) {console.log("[Mock] get-Function"); },
        }
    },
}

(Of course, to really simulate storage data this would need more than an empty function)

The problem is, however, that I only want to use the mocking for testing the popup, of course, and not for testing the addon or in production. For production I already have my own build process with webpack, which bundles the whole thing for me.
Is it possible that I create a similar build process (possibly also with webpack) that I can then run from the command line and that actively includes mocking in the code, for example by adding it as a dependency.
Or what is basically the best approach if you want to use a piece of code for some special test processes and never otherwise?

So far, I’ve tried creating my own file that overrides the Chrome API with empty functions and exports that. popup.js should then check if this file exists and if so import the overridden functions. This would work in itself, if webpack didn’t also always bundle the mock file with the production build. It was not possible for me to get webpack to ignore dependencies completely by any settings.

Is there a way to have 2 separate sprites in canvas, one mirrored, one not?

So I’m making a game in javascript canvas. I’m using the context.scale(-1, 1) function, called within a method of my Sprite class that updates the image every frame to draw the mirrored image. I’m setting the scale back to (1,1) when I draw the non-flipped sprite. The problem is, the spirite that’s supposed to be flipped is not getting mirrored and it’s constantly flashing, any ideas?

I tried using save() and restore() methods of the context object. Not succesful, same result.

Button have different URL based on condition

I’m beginner in Code. I want to create button that have different url based on condition that user choose.

So for example the button called “Book Now”
I have to package using span: Standard and Premium

My plan is, if user choose “standard” the button will be have “html://blablabla.com/standard
and if user choose “premium” the url will be “html://blablabla.com/premium

I was wondering how it can be possible in html and javascript?

Vue 2 and Vuelidate 2 – Validating a child component from a custom npm component library

I’ve been searching the vuelidate-next (and vuelidate 0.x) documentation, github vuelidate repo (issues), and stackoverflow, but haven’t really found a solution for this issue that I currently have.

Main issue:

  • Vuelidate is not collecting all validation $errors and $silentErrors when used with a child component from a custom npm component library.

Context behind this issue:

  • I am currently building a Vue 2 component library (using the Options API), and using it in another Vue 2 (Options API) project (Parent Vue Project).
  • When the component library is being tested in Jest and or StoryBook, the v$ setup object appears in the Vue inspector tool, and supplies all the usual information as normal (examples posted below).
  • However, when the components are packaged for release via npm, then imported into another vue 2 project; the v$ setup object only returns information for vue 2 project instance, and completely ignores the validation for the library components.
  • All the library components have $autoDirty: true (code example below).
  • The components from the npm library render and function correctly within the Parent Vue Project, except for the validations through Vuelidate.
  • The component library has functioning validation as far as I have tested (Validation works perfectly with both Jest and StoryBook).
  • The components must have the validation rules within the custom npm library, and be validated in a parent wrapper within another project (client has specified this as a requirement, the examples posted below are a simplified representation of the actual code).

The Parent Vue Project code (not component library) looks like this:

<template>
    <div>
        <custom-input-component v-model="textValue"/>
            <span v-if="v$.value.$error" class="field validation-error">
              This field is required
            </span>
    </div>
</template>

<script>
    import { useVuelidate } from '@vuelidate/core';
    import { CustomInputComponent } from '@custom-components-library';
    
    export default{
        props:{...},
        data(){...},
        
          setup () {
            return {
              v$: useVuelidate()
            }
          },
        
        computed:{...}
        methods:{...}
    }
</script>

The npm component library package code looks like this:

<template>
    <div>
        <label for="name">Name: </label>
        <input type="text" :value="value">
    </div>
</template>

<script>
    import { useVuelidate } from '@vuelidate/core';
    import { required } from '@vuelidate/validators';

    export default{
        props:{
            value: {
                type: String,
                default: '',
            }
        },
        setup() {
            return {
              v$: useVuelidate({ $autoDirty: true }),
            };
        },
    
        validations() {
            return {
              value: {required},
            };
        }
  ...
  }
  </script>

v$ validation object in component library ( using Storybook with Vue 2)

v$:Object (Computed)
    $anyDirty:true
    $clearExternalResults:function $clearExternalResults()
    $commit:function $commit()
    $dirty:true
    $error:false
    $errors:Array[0]
    ...
    value:
        $anyDirty:true
        $commit:function $commit()
        $dirty:true
        $error:true
        $errors:Array[1]
        $externalResults:Array[0]
        $invalid:true
        ...
        required:Object

v$ validation object in Parent Vue Project (using Vue 2)

v$:Object (Computed)
    $anyDirty:true
    $clearExternalResults:function
    $clearExternalResults()
    $commit:function $commit()
    $dirty:true
    $error:false
    $errors:Array[0]
    ...

Web browser console errors:

[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading '$error')" 

Component library build config:

{
    "compilerOptions": {
    "target": "es5",
    "module": "esnext"
  }
}

Questions:

  • How can I get the child component to validate in the Parent Vue Project?
  • My suspicion is that there are potentially two vuelidate instances, and the parent vuelidate object doesn’t know about the v$ validation rules in child components?
  • Is there any way to overcome this, and be able to set validation rules within the npm library based components, and validate them within a parent wrapper within another project?

How can I re-declare the same var six times at JavaScript DOM? [closed]

I am trying to select six divs from my HTML and render a chart from https://apexcharts.com/javascript-chart-demos/radialbar-charts/basic/ which uses javascript

let options = {
  series: [70],
  chart: {
    height: 350,
    type: "radialBar",
  },
  plotOptions: {
    radialBar: {
      hollow: {
        size: "70%"
      }
    }
  },
  labels: ["Cricket"]
};

let charts = document.querySelectorAll(".chart");
charts.forEach((chart) => {
  let chartInstance = new ApexCharts(chart, options);
  chartInstance.render();
});
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<div class="chart"></div>
<div class="chart"></div>
<div class="chart"></div>
<div class="chart"></div>
<div class="chart"></div>
<div class="chart"></div>

However, only my first div receives this chart, the other five do not receive and I get it in my console:

Uncaught SyntaxError: Identifier ‘options’ has already been declared (at (index):641:36)

While I hide my password in react-native password freezes to the beginning

const [password, setPassword] = useState('')
const [passwordVisibility, setPasswordVisibility] = useState(false);
<View style={styles.inputContainer}>
          <TextInput
            name="password"
            style={styles.inputField}
            autoCapitalize='none'
            value={password}
            autoCorrect={false}
            textContentType="newPassword"
            onChangeText={onChangeText}
            placeholder="Password"
            enablesReturnKeyAutomatically
            secureTextEntry={passwordVisibility}
          />
          <Pressable onPress={()=>{setPasswordVisibility(!passwordVisibility) , console.log(password)}}>
          <Icon name={passwordVisibility == true ? 'eye' : 'eye-off' } size={23} color='purple' />
          </Pressable>
          
        </View>

Here is my code .While I hide my password in react-native password freezes to the beginning . How can I fix this

Why req.params answers 2 id?

it’s my first Express and MongoDb project and i encountered an issue today.
When i ask req.params it answers 2 id so i can’t search data in mongo db
idk if i made myself clear but here is the code

articleController.js

exports.articlepage = async(req, res) => {
    try {
        let artId = req.params
        console.log(artId)

        res.render('page', { title: `p` } );
    } catch (error) {
        console.log(error)
    }
}

articleRoutes.js

router.get('/article/:id', articleController.articlepage);

and the console answers
{ id: ‘638d07c63bec27224511c7af’ }
{ id: ‘jquery-2.1.1.min.js’ }

hope someone can help, thank you in advance and if you need more of my code you can ask me

I’ve searched about this but wasn’t able to find something truly helpful

TypeError: Cannot read properties of undefined (reading ‘input’), Vue

I’m trying to access a using my API, which works when I try using Postman, from VUE, but for some reason I’m getting the error “TypeError: Cannot read properties of undefined (reading ‘input’)”.

The body when sending the post would be something like this:

POST: http://localhost:8080/api/vendedor/login

{
  "correo": "[email protected]",
  "password": "123456"
}

And the answer from the POST would be a JSON with:

{
  "idvendedor": 5,
  "nombre": "Leonardo",
  "apellido": "Andrade",
  "correo": "[email protected]",
  "password": "123456",
  "lugartrabajo": "Casino Los Notros"
}

The HTML from the login would be like this:

<form class="w-96 mx-auto rounded-md">
            <div class="input">
                <label for="email" class="text-xl font-medium text- flex justify-left py-1">Correo</label>
                <input type="text" name="email" v-model="input.email" placeholder="[email protected]" class="border-2 p-1 w-96 border-violet-700 rounded-full">
            </div>
            <div class="input">
                <label for="password" class="text-xl font-medium text- flex justify-left py-1">Contraseña</label>
                <input type="password" name="password" v-model="input.password" placeholder="***************************" class="border-2 p-1 w-96 border-violet-700 rounded-full">
            </div>
            <div class="pb-5"></div>
            <button type="submit" id="botonlogin" v-on:click.prevent="login()" class="ml-28 h-8 w-36 mx-auto bg-gradient-to-r from-indigo-500 to-indigo-700 rounded-full hover:from-indigo-400 hover:to-indigo-600">
                <span class="text-center text-white font-medium">Iniciar Sesión</span>
            </button>
        </form>

And this is the script in the login:

<script>
import axios from 'axios';

  export default {
    name: 'Login',
    data() {
      return {
        input: {
          email: "",
          password: ""
        },
        vendedor: {
          idvendedor: "",
          nombre: "",
          apellido: "",
          correo: "",
          password: "",
          lugartrabajo: ""
        },
      }
    },
    methods: {
      async login() {
        try{
          let res = await axios.post('http://localhost:8080/api/vendedor/login', this.data.input);
          console.log(res);
          if(this.input.email == this.vendedor.correo && this.input.password == this.vendedor.password){
            this.$router.push('/vendedor/homeVender');
          }
        }catch (e){
          console.log(e)
        }
        
          
      }
    }
  }
</script>

I expected to get the JSON from axios, so that i could make an “if” for the login, but I’m getting the error “TypeError: Cannot read properties of undefined (reading ‘input’)”

Add SuperScript only if fragment id is present in GraphQL query

I am working on a AEM component to dynamically add superscripts based on a graphQL query and I need some help.

Currently the component will add a superscript to any element that has the data-id attribute.

The future state that I am looking to achieve is having the component only add the superscript if the fragment id is present in the graphQL query.

Below is the full code of the component:


document.addEventListener("DOMContentLoaded", function(){
    var myHeaders = new Headers();
        myHeaders.append("Content-Type", "application/json");
        myHeaders.append("Authorization", "Basic YWRtaW46YWRtaW4=");
        myHeaders.append("Cookie", "cq-authoring-mode=TOUCH");

    var requestOptions = {
        method: 'GET',
        headers: myHeaders,
        redirect: 'follow'
    };

    var query = {
        protocol: document.location.protocol,
        host: document.location.host,
        path: "graphql/execute.json/dot-pnc-aem-caas",
        name: "disclosure-by-id",
        paramName: "fragmentId"
    };

    let disclosureDiv = document.getElementById('disclosureComponent'),
        disclosureElement = document.querySelectorAll('span[data-id]'),
        orderedList = document.createElement("ol"),
        disclosureArray = [],
        queryValue,
        footnoteNumber = 1,
        footnoteObject = {},
        supNum,
        url = query.protocol +"//"+ query.host +"/"+ query.path +"/"+ query.name +"%3B"+ query.paramName +"%3D{"_logOp"%3A"OR"%2C"_expressions"%3A[";

    function createDisclosureArray(){    
        for (let i = 0, max=disclosureElement.length; i < max; i++) {
            let fragmentId = disclosureElement[i].dataset.id;
            if(!footnoteObject.hasOwnProperty(fragmentId)){
                footnoteObject[fragmentId] = footnoteNumber;
            }
            supNum = footnoteObject[fragmentId];
            disclosureArray.push({
                fragmentId: fragmentId,
                anchorId: fragmentId,
                superScript: supNum
            });
            anchorTag = document.createElement('a');
            anchorTag.setAttribute('href', '#'+disclosureArray[i].anchorId);
            anchorTag.setAttribute('class', 'disclosureAnchor');
            sup = document.createElement('sup');
            const fragment = document.createDocumentFragment();
            const superScript = fragment
                .appendChild(anchorTag)
                .appendChild(sup);
            superScript.textContent = '['+disclosureArray[i].superScript+']';
            disclosureElement[i].append(fragment);
            footnoteNumber++;
        }
        queryValue = disclosureArray.map(({fragmentId}) => '{"value"%3A"'+fragmentId+'"}').join('%2C');
        url += queryValue + "]}";
        return disclosureArray;
    }

    async function getDisclosures(){
        try{
            let result = await fetch(url, requestOptions);
            if (!result.ok) {
                const message = `An error has occured: ${result.status} - ${result.statusText}`;
                throw new Error(message);
            }
            return await result.json();
        } catch (error){
            console.log(error.message);
            disclosureDiv.append('No disclosures were found.');
        }
    }

    async function updateLegalAccordion(){
        let disclosure = await getDisclosures();
        let disclosureNum = disclosure.data.disclosureList.items;
        for (let i = 0, max = disclosureNum.length; i < max; i++ ){
            let listItem = document.createElement('li');
            listItem.innerHTML = `${disclosureNum[i].copy.html}`;
            listItem.setAttribute('id', disclosureArray[i].anchorId);
            orderedList.appendChild(listItem);
            disclosureDiv.appendChild(orderedList);
        }
    }

    createDisclosureArray();
    updateLegalAccordion();


});  

I have tried creating a new graphQL query in Postman to check if the fragmentId exists so I could base the superscript off that query but I was getting errors in Postman