How to display certain amount to values in Select2

I am using Select2. My code is like below.

var cellEle = $(this);

// Populate select element
cellEle.html(`<select multiple="multiple"></select>`);

// Initialise select2
let selectEle = cellEle.children("select").select2({
    maximumSelectionLength: 3,
    ajax: {
        url: "/wp-admin/admin-ajax.php",
        data: function (params) {
            return {
                action: 'get_data',
                search: params.term,
            };
        },
        processResults: function (data) {                
            var options = [];
            if (data) {
                $.each(data, function (index, text) {
                    var user_data = '<table> 
                        <tr> 
                        <td>Organisation</td> 
                        <td>'+text[2][1]+'</td> 
                        </tr> 
                        <tr> 
                        <td>Age</td> 
                        <td>'+ text[2][0]+'</td> 
                        </tr> 
                    </table>'; 
                    
                    options.push({ id: index, text: text[0], text1: text[1], value: user_data });                
                });
            }
            return {
                results: options,
                more: false
            };
        },
    },
    templateSelection: templateSelection,
    templateResult: resultfucntion,
});

I would like to display 5 values in dropdown list.

How can I do that ?

enter image description here

Display three rows of duplicated data in one row using javascript Filter() function

You can see two data tables in the attached photo. The first data table shows the same data in all three rows. I don’t need the duplicated datas, so I want to remove the duplicated row of datas and make only one row of data. Please tell me what to do. Everyone Please help me.

two data tables images

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script>
<template>
  <v-container class="container-padding">
    <v-breadcrumbs class="px-0 pt-0" large>
      <span class="breadcrumb-line rounded-pill mr-2"></span>
      <v-breadcrumbs-item class="text-h5 mr-5">Timecard</v-breadcrumbs-item>
      <span class="breadcrumb-divider rounded-pill mr-5"></span>
      <v-breadcrumbs-item class="text-h6">View</v-breadcrumbs-item>
    </v-breadcrumbs>

    <v-card>
      <v-container fluid>
        <v-row>
          <v-col cols="1">
            <v-subheader></v-subheader>
          </v-col>
          <v-col cols="2">
            <v-layout row wrap justify-space-around>
              <v-text-field v-model="calendarVal" label="Date" type="date" value="2022-02-05"></v-text-field>
            </v-layout>
          </v-col>
          <v-col cols="1">
            <v-btn @click="fetchWorkerTimeCard">enter</v-btn>
          </v-col>
        </v-row>
      </v-container>
      <v-data-table worker_time_card :headers="headers1" :items="worker_time_card"></v-data-table>
    </v-card>
    <v-card>
      <v-data-table v-if="worker_time_card.length > 0" :headers="headers2" :items="worker_time_card"></v-data-table>
    </v-card>
  </v-container>
</template>
<script>
  export default {
    data() {
      return {
        worker_time_card: [],
        calendarVal: null,
        headers1: [{
            text: 'Start Time',
            value: 'start_time'
          },
          {
            text: 'End time',
            value: 'end_time'
          },
          {
            text: 'Rest time',
            value: 'rest_time'
          },
          {
            text: 'Worked time',
            value: 'worked_time'
          },
        ],
        headers2: [{
            text: 'Project id',
            value: 'project_id'
          },
          {
            text: 'Duration',
            value: 'duration'
          },
          {
            text: 'Work log',
            value: 'work_log'
          }
        ],
      }
    },
    computed: {
      calendarDisp() {
        return this.calendarVal
      },
    },
    mounted() {
      this.calendarVal = this.getDataToday()
      this.fetchWorkerTimeCard()
    },
    methods: {
      getDataToday() {
        return (new Date().toISOString().substr(0, 10))
      },
      submit() {
        console.log(this.calendarVal)
      },
      async fetchWorkerTimeCard() {
        try {
          this.worker_time_card = []
          await this.$axios.$get('/worker_time_card', {
            params: {
              work_date: this.calendarVal
            }
          }).then(data => {
            data.time_cards.forEach(card =>
              this.worker_time_card.push({
                start_time: data.start_time,
                end_time: data.end_time,
                rest_time: data.rest_time,
                worked_time: data.worked_time,
                duration: card.duration,
                work_log: card.work_log,
                project_id: card.project_id,
              })
            )
          })
        } catch (error) {
          console.log(error)
          this.worker_time_card = []
        }
      },
    },
  }
</script>

I’m using “forEach” to duplicate “start_time, end_time, rest_time, worked_time” into 3 rows of data, but I don’t know how to get it back. Maybe using the filter () function will get it back, but it doesn’t work.

    async fetchWorkerTimeCard() {
      try {
        this.worker_time_card = []
        await this.$axios.$get('/worker_time_card', { params: { work_date: this.calendarVal } }).then(data => {
          data.time_cards.forEach(card =>
            this.worker_time_card.push({
              start_time: data.start_time,
              end_time: data.end_time,
              rest_time: data.rest_time,
              worked_time: data.worked_time,
              duration: card.duration,
              work_log: card.work_log,
              project_id: card.project_id,
            })
          )
        })
      } catch (error) {
        console.log(error)
        this.worker_time_card = []
      }
    },

The following JSON data is obtained from the API.

{
  "start_time": "09:00:00",
  "end_time": "18:00:00",
  "rest_time": "01:00:00",
  "worked_time": "08:00:00",
  "is_wfh": true,
  "id": 1,
  "work_day_id": 45,
  "time_cards": [
    {
      "duration": "04:00:00",
      "work_log": "sain",
      "project_id": 1
    },
    {
      "duration": "03:00:00",
      "work_log": "sain02",
      "project_id": 2
    },
    {
      "duration": "01:00:00",
      "work_log": "sain03",
      "project_id": 3
    }
  ]
}

Modal won’t open vanilla javascript any help is appreciated [duplicate]

I’m trying to open the same modal but w different content. Just a little project to explain networking ports. However, the modals won’t open. I keep getting an error: Uncaught TypeError: Cannot read properties of null (reading ‘style’)
at HTMLButtonElement.btn.onclick (script.js:9:39)

Any clue what the issue could be? Thanks

<body>
    <h1>Network Portal</h1>

    <button class='show-modal' data-modal="NTP">NTP</button>
    <button class='show-modal' data-modal="HTTPS">HTTPS</button>
    <button class='show-modal' data-modal="DHCP">DHCP</button>
    <button class='show-modal' data-modal="DNS">DNS</button>
    <button class='show-modal' data-modal="FTP">FTP</button>
    <button class='show-modal' data-modal="SSH">SSH</button>


    <div class="modal" id="ntp">
        <div class="modal-content">
            <div class="'modal-header">NTP PORT 123<button class="icon modal-close"><i class="material-icons">close</i>
            </button></div>
            <div class="modal-body">This port is responsible for</div>
            <div class="modal-footer"><button class="link modal-close">Close Modal</button></div>

        </div>

    </div>
    <div class="modal" id="https">
        <div class="modal-content">
            <div class="'modal-header">HTTPS PORT 443<button class="icon"><i class="material-icons">close</i>
            </button></div>
            <div class="modal-body">This port is responsible for</div>
            <div class="modal-footer"><button class="link modal-close">Close Modal</button></div>

        </div>

    </div>
    <div class="modal" id="dhcp">
        <div class="modal-content">
            <div class="'modal-header">DHCP PORT 67/68<button class="icon"><i class="material-icons">close</i>
            </button></div>
            <div class="modal-body">This port is responsible for</div>
            <div class="modal-footer"><button class="link modal-close">Close Modal</button></div>

        </div>

    </div>
    <div class="modal" id="dns>
        <div class=" modal-content ">
            <div class=" 'modal-header">DNS PORT 53<button class="icon"><i class="material-icons">close</i>
            </button></div>
            <div class="modal-body">This port is responsible for</div>
            <div class="modal-footer"><button class="link modal-close">Close Modal</button></div>

        </div>

    </div>
    <div class="modal" id="ftp">
        <div class="modal-content">
            <div class="'modal-header ">FTP PORT 20/21<button class="icon "><i class="material-icons ">close</i>
            </button></div>
            <div class="modal-body ">This port is responsible for</div>
            <div class="modal-footer "><button class="link modal-close ">Close Modal</button></div>

        </div>

    </div>
    <div class="modal " id="ssh ">
        <div class="modal-content ">
            <div class=" 'modal-header">SSH PORT 22<button class="icon"><i class="material-icons">close</i>
            </button></div>
            <div class="modal-body">This port is responsible for</div>
            <div class="modal-footer"><button class="link modal-close">Close Modal</button></div>

        </div>

    </div>


    <script src="script.js"></script>
</body>

</html>

--CSS--
* {
    margin: 0;
    padding: 0;
    font-family: 'Roboto', sans-serif;
}

.show-modal {
    padding: 8px 16px;
    background: royalblue;
    color: white;
    border-radius: 10px;
    outline: none;
    border: none;
}

.modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 2;
    display: none;
}

.modal-content {
    background: #fff;
    margin-top: 100px;
    width: 50%;
    margin-left: auto;
    margin-right: auto;
    padding: 8px 24px;
    border-radius: 4px;
    z-index: 4;
}

.modal-header {
    font-weight: 500;
    padding: 10px 0;
    font-size: 26px;
}

.modal-header .modal-close {
    float: right;
    font-size: 20px;
    background: #efefef;
    border: 0;
    outline: 0;
    padding: 5px 8px;
    border-radius: 50%;
}

.modal-body {
    color: #7b7b7b;
    padding: 15px 0;
}

.modal-footer {
    padding: 15px 0;
}

.modal-footer .modal-close {
    padding: 8px 16px;
    font-size: 14px;
    border: none;
    outline: none;
    border-radius: 4px;
    color: #1a73e8;
}



--JS--
var modalBtns = document.querySelectorAll(".show-modal");


modalBtns.forEach(function(btn) {
    btn.onclick = function(e) {
        e.preventDefault();
        var modal = btn.getAttribute("data-modal");

        document.getElementById(modal).style.display = "block";
    };
});


var closeBtns = document.querySelectorAll(".modal-close");

closeBtns.forEach(function(btn) {
    btn.onclick = function() {
        var modal = btn.closest(".modal");
        modal.style.display = "none";
    };
});

window.onclick = function(e) {
    if (e.target.className === 'modal') {
        e.target.style.display = "none";
    }
};

How do I combine filtering inside aggregate with project in mongoose?

I am trying to find the document that fits a specific field then take all the results and then project to all of them a rating based on an equation.
I tried first finding the fitting documents with a field then sorting it, however I do not not know how to combine them and use the results from the first query to the second one:

router.get('/questionsfilter',
  body("whichTag").trim().escape(),

  function(req,res,next){
    Question.find({tag: req.body.whichTag}).exec(function(err,results2){
      try{
        let now = new Date();
        const results = await Question.aggregate([
          {$project: {rating: {$add:[
            {$divide: 
              [
                {$divide: [{$arrayElemAt:[{$ifNull:["$views",[0]]}, 0]},  {$subtract:[now, '$dateCreated']}]},
                50
              ]},
            {$subtract: 
              [
                {$multiply: [{$divide: [{$arrayElemAt:[{$ifNull:["$likes",[0]]}, 0]}, {$subtract:[now, '$dateCreated']}]}, 3]},
                {$multiply: [{$divide: [{$arrayElemAt:[{$ifNull:["$dislikes",[0]]}, 0]},  {$subtract:[now, '$dateCreated']}]}, 6]}
              ]
            }
            ]}
          }},
          {$sort: {rating:-1}},
          {$limit: 15}
        ]).exec();
        const questions = await Promise.all(results.map(({_id}) => Question.findOne({_id}).exec()));
        res.render('content', { whichOne: 5, user: req.user, questions:questions, type:'hot', whichTag: req.body.whichTag});
      }
      catch(err){
        next(err);
      }
    })
  }
);

how would I find all the questions’s whose tag field fits the req.body.whichTag then sorting them with first projecting a rating then with map? I cant find out how to combine both and only how to do one!
Thanks!

Open App Store if app isn’t installed IOS 2021

I’m trying to get IOS recognize if my app is not installed when i click in a button on my web. I have everthing that says IOS, apple-app-site-association, in our app everything is set to that, and when the app is already installed, it works! But, if the app is not installed, safary returns an incorrect message, and freeze the next code (i tried to apply the settimeout to do a redirect to the appstore)

I saw multiple cases here on stackoverflow, but none works now…

Why can the first parameter of fetch() be a Request object?

From the API documentation

This defines the resource that you wish to fetch. This can either be:

  • A string or any other object with a stringifier — including a URL object — that provides the URL of the resource you want to fetch.
  • A Request object.

Simple question: “why”? The second parameter is init which seems to have all parameters that will be used to then make a Request object.

So:

  • Why giving the possibility of using EITHER a Request object as first parameter, OR an URL as first parameter and init value of a Request object as second parameter?

  • Is it allowed/spec’d to have BOTH a request object as first parameter, and an init object as second parameter? I assume the answer is “no” since none of the properties of the request object are writable… but in that case, should the documentation above specify that it’s either a request object, or a URL + init parameters?

3 generation referral system in php

I need the source code of 3 generation earn referral system in php, this is how i want it to work.

  1. A user signs up with a fee of 2K.
  2. He makes his first referral which will be his 1st generation, then he earns 50% from the sign up fee which is 1K
  3. Then his 1st generation now went ahead to refer another person which will be his 2nd generation, the 1st generation will then get 50% from the 2nd generation.
  4. when the 2nd generation person refers someone which will be in the 3rd generation now, the 2nd generation will now earn 50% from the 3rd generation also.
    Same thing keeps repeating on and on in the system.

JQuery AJAX returns success undefined + async with loop does not work

getUsers();

function getUsers(){
    console.log('Start');

    $.ajax({
        url: 'https://jsonplaceholder.typicode.com/users',
        method: 'GET',
        //dataType: 'json', // returns success undefined
        dataType: 'application/json',
        success: function (data) {
            if (data.success == true) {
                data.result.forEach(user => {
                    console.log(user.id);
                });                    
            }  else {
                console.log(data.status);
            }
        }
    })
    
    console.log('End');    
}

The above code-example should print the following:
Start
ids

End

However it has the following problems:

  1. It returns success undefined when the dataType is set to json eventhough in debugger data has data.

  2. If I change the dataType to application/json, then success is not undefined anymore, but the data does not get printed to the console. Instead it shows the object as a list.

  3. In both cases the order of printing of the data is wrong. It prints
    Start
    End
    data-object

I know it has to do with async, however I can’t fix the problem. I tryed alot of things like $.When()
Promise
async/await
But none of then helped.

So could you please show how to fix these problems?

Thank you in advance

using setTimeout to render component in React Native

I’m trying to render a component from my screen after 3 seconds, this is due to some time delay when the user changes accounts, I need those 3 seconds so the data can be exactly what the user wants. Before rendering that piece of component, I wanted to load a container with loading in the center. I have inserted the data into the component but I get an error from component exception:
enter image description here

This is how I’m rendering the data:

export function Dashboard({ drawerAnimationStyle}: any) {
    const navigation: any = useNavigation();
    const { firebaseFunctions } = useAuth();

    const [isLoading, setIsLoading] = useState(true);
    const [transactions, setTransactions] = useState<DataListProps[]>([]);
    const [higlightData, setHighlightData] = useState<HighlightDataProps>({} as HighlightDataProps);
    const theme = useTheme();

    async function loadTransaction(): Promise<any> {
        const data = await firebaseFunctions.loadTransaction();

        setTransactions(data.transactionsFormatted);

        setHighlightData(data.higlightData);

        setIsLoading(false);

    }

    useEffect(() => {   
        loadTransaction();
    }, [transactions]);

    return (
        <Animated.View style={{ flex: 1, ...drawerAnimationStyle}}>         
            <Container>
                {
                    isLoading ? 
                    <LoadingContainer>
                        <ActivityIndicator color={theme.colors.blue} size='large'/>
                    </LoadingContainer>
                    :
                    <>
                        <Header>                            
                            <DrawerContainer onPress={() => navigation.openDrawer()}>
                                <Icon name="menu" />
                            </DrawerContainer>
                            <HighLightCards>
                                <HighLightCard type="up" title="Income" amount={higlightData.entries.amount} lastTransaction={higlightData.entries.lastTransaction}/>
                                <HighLightCard type="down"title="Outcome" amount={higlightData.outcome.amount}lastTransaction={higlightData.outcome.lastTransaction}/>
                                <HighLightCard type="total" title="Total" amount={higlightData.total.amount} lastTransaction={higlightData.total.lastTransaction}/>
                            </HighLightCards>
                        </Header>                       

                        {
                            setTimeout(() => {
                                return (
                                    <Transactions>
                                        <Title>Transactions</Title>
                                        {
                                            transactions.length <= 0 ?
                                            <NoTransaction>
                                                <LottieView 
                                                    source={NoTransactionLottie}
                                                    style={{
                                                        width: 100,
                                                        height: 100,                                                                    
                                                    }}
                                                    autoPlay
                                                    loop
                                                    resizeMode='contain'
                                                />
                                            </NoTransaction>
                                            :
                                            <TransactionsList
                                                data={transactions}                     
                                                keyExtractor={(item: { id: any }) => item.id}
                                                renderItem={({ item }: any) => <TransactionCard  data={item}/>}
                                            />
                                        }
                                    </Transactions>
                                );
                            }, 3000)
                        }
                    </>
                }
            </Container>
        </Animated.View>
    );
}

JavaScript `URL`: when to encode when setting `pathname`?

When setting the pathname of a URL, when should you encode the value you are setting it to?

When I say URL I mean this API: https://developer.mozilla.org/en-US/docs/Web/API/URL

When I say “setting the pathname” I mean to do this:

url.pathname = 'some/path/to/a/resource.html';

Based on the MDN documentation, I would think the answer is “you shouldn’t need to”, as there is an example covering this case:

URLs are encoded according to the rules found in RFC 3986. For
instance:

url.pathname = 'démonstration.html';
console.log(url.href); // "http://www.example.com/d%C3%A9monstration.html"

However, I have run into a case where it seems I do need to encode the value I am setting pathname to:

url.pathname = 'atest/New Folder1234/!@#$%^&*().html';
console.log(url.href);

I would expect this to output:
http://example.com/atest/New%20Folder1234/!%40%23%24%25%5E%26*().html

But instead I am getting:
https://example.com/atest/New%20Folder1234/!@%23$%^&*().html

It seems to get what I expect I have to do:

url.pathname = 'atest/New Folder1234/!@#$%^&*()'.split('/').map(encodeURIComponent).join('/')

What is going on here? I cannot find anything on the MDN doc page for either URL or pathname that explains this. I took quick look through RFC 3986, but that just seems to describe the URI syntax. I have run some experiments in an effort to find some sort of pattern to this problem, but nothing is standing out to me.

I don’t know how to handle errors in Multer with Express

I am using Multer to upload a maximum of 3 images to the server and it works fine, but when I upload more than 3 images, Multer tells me the error but it is not manageable to show the user.

I’m working on the route that calls the controller but in the Multer documentation it only shows how to handle errors with the route along with the controller actions.

Route:

router.post('/', upload.array('pictures', 3), 
    newProduct
);

Documentation code for handling Multer errors:

const multer = require('multer')
const upload = multer().single('avatar')

app.post('/profile', function (req, res) {
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      // A Multer error occurred when uploading.
    } else if (err) {
      // An unknown error occurred when uploading.
    }

    // Everything went fine.
  })
})

Error response shown by Multer:

error

In this case how could I do the same documentation but separately to handle Multer errors?

Thank you.