lundi 31 janvier 2022

Display a list of names based on checked boxes in other page - Xamarin Forms

I have a view with a lot of labels and checkboxes, it is basically a list of questions for the user and if the user answers yes, they check the checkbox, otherwise they don't. I have another view that is related to this first view in which it should get and display which check boxes were checked. For example:

<Label Text="You have fever?" />
<CheckBox x:Name="fever" />

<Label Text="You have a running nose?" />
<CheckBox x:Name="running_nose" />

<Label Text="You are feeling dizzy?" />
<CheckBox x:Name="dizzy" />

And on the other page I want to display the values that were checked in a entry field. Let's say the user checked fever and dizzy. On the other page it would display something like this:

"You marked *fever*, *dizzy*. Is that right?"

How can I do this? I know I can use data binding. But not sure how to. In my actual app, I have around 10 fields of those and I need to display on the other page the was that were marked. I was also thinking in instead of displaying an entry with these values, I would created a card for each one of the checked boxes (my app is much more complex, the symptoms are just an example).




dimanche 30 janvier 2022

React JS - filtering based on multiple checkbox values

I have a simple react application which looks like this:

import { useState } from "react";

const initialState = [
  { id: 1, language: "javascript" },
  { id: 2, language: "java" },
  { id: 3, language: "python" },
  { id: 4, language: "python" },
  { id: 5, language: "javascript" },
  { id: 6, language: "javascript" },
];

function App() {
  const [items, setItems] = useState(initialState);

  const [languages, setLanguages] = useState({
    javascript: false,
    java: false,
    python: false,
  });

  const onChange = (e) => {
    setLanguages({ ...languages, [e.target.value]: e.target.checked });
  };

  return (
    <>
      <div>
        <label>
          <input
            type="checkbox"
            value="javascript"
            name="language"
            checked={languages.javascript}
            onChange={onChange}
          />
          javascript
        </label>

        <label>
          <input
            type="checkbox"
            value="java"
            name="language"
            checked={languages.java}
            onChange={onChange}
          />
          java
        </label>

        <label>
          <input
            type="checkbox"
            value="python"
            name="language"
            checked={languages.python}
            onChange={onChange}
          />
          python
        </label>
      </div>

      <ul>
        {items.map((item) => (
          <li key={item.id}>{item.language}</li>
        ))}
      </ul>
    </>
  );
}

export default App;

I'm now trying to implement filtering but haven't succeeded yet. How can I make displayed items to be filtered and rendered based on all the checked values so each time checkbox values change list items get updated? Please see expected behavior below.

Example 1

State:

const [languages, setLanguages] = useState({
  javascript: true,
  java: false,
  python: false,
});

Output:

<ul>
  <li>javascript</li>
  <li>javascript</li>
  <li>javascript</li>
</ul>

Example 2

State:

const [languages, setLanguages] = useState({
  javascript: true,
  java: false,
  python: true,
});

Output:

<ul>
  <li>javascript</li>
  <li>python</li>
  <li>python</li>
  <li>javascript</li>
  <li>javascript</li>
</ul>



Remove multiple rows with checkbox

soy nuevo en spring y necesito poder eliminar las filas seleccionadas por medio de un checkbox, esta es mi tabla .html

<div class="col-md-12">
                        <table class="table" id="tableImport">
                            <thead>
                                <tr>
                                    <th scope="col">Remove</th>
                                    <th scope="col">Debt Age Rule</th>
                                    <th scope="col">Reminder</th>
                                    <th scope="col">Frequency</th>
                                    <th scope="col">Reorder</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr th:each="configCampaign:${listConfigCampaigns}">
                                    <td>
                                        <input type="checkbox" name="my-checkbox">
                                    </td>
                                    <td th:text="${configCampaign.debtagerule}"></td>
                                    <td th:text="${configCampaign.remindebttype}"></td>
                                    <td th:text="'Every '+${configCampaign.every} + ' ' + ${configCampaign.unit}"></td>
                                    <td></td>
                                </tr>
                            </tbody>
                        </table>
                        <div class="col-md-12" style="text-align: center">
                            <input class="btn btn-primary" type="button" value="- Remove Selected Action(s)"/>
                        </div>
                    </div>

This table shows me data from an arrayList in memory, nothing with a database, I need to remove those selected objects from the array. At the moment I have my controller like this enter image description here

private int configid;
private String debtagerule;
private String remindebttype;
private int every;
private String unit;
private boolean selected;
//getters and setters



samedi 29 janvier 2022

how to toggle all checkbox by clicking header checkbox react js

is there anyone to help that how can i implement functionality in toggleCheckboxes() to select all checkboxes. In my code there is a map method. it controls the number of checkbox input's. In table Data, every checkbox type input is shown after mapping an item from manageOrder. i tried with using useState, setAttribute but can't to solve this problem.

import React, { useEffect, useState, useRef } from 'react';
import { Container, Spinner } from 'react-bootstrap';
import './ManageAllOrder.css';

const ManageAllOrder = () => {
    const [manageOrder, setManageOrder] = useState([]);
    useEffect(() => {
        fetch('https://ghostly-blood-77078.herokuapp.com/orders')
        .then(res => res.json())
        .then(data => setManageOrder(data))
    }, [])
    //change status after click
    const changeStatus= (e) => {
        e.target.innerText = 'active'
    }
    //toggle checkbox
    const rowCheckbox = useRef('')
    const toggleCheckboxes = () => {
        


    }

    return (
        <Container>
            <div>
                <h3 className='my-4' style=>Order Management</h3>
                <div>
                {!manageOrder.length ? 
                      <Spinner animation="grow" variant="warning" /> :

                    //table to show data
                    <table className="table">
                        <thead className='table-warning'>
                            <tr>
                                <th><input id='header-checkbox' type='checkbox' onClick={toggleCheckboxes()} /></th>
                                <th>OrderID</th>
                                <th>Date</th>
                                <th>Customer</th>
                                <th>Order</th>
                                <th>Place</th>
                                <th>Price</th>
                                <th>Status</th>
                                <th>Delete</th>
                            </tr>
                        </thead>
                        <tbody>
                    {manageOrder.map(order =>
                            <tr>
                                <td><p><input type='checkbox' ref={rowCheckbox}/></p></td>
                                <td><p>{order._id}</p></td>
                                <td><p>{order.date}</p></td>
                                <td><p>{order.displayName}</p></td>
                                <td><p>{order.name}</p></td>
                                <td><p>{order.place}</p></td>
                                <td><p>{order.amount}</p></td>
                                <td><p onClick={(e) => changeStatus(e)}>pending...</p></td>
                            </tr>
                        )}
                        </tbody>
                    </table>
                }
                </div>
            </div>
        </Container>
    );
};

export default ManageAllOrder;```


[i want to toggle all checkboxes after clicking the checkbox top left corner, i tried a few ways to implement that but i can't because of map method. ][1]
  [1]: https://i.stack.imgur.com/SfbSJ.png



Problem collecting all checkbox values from Shiny DT assembled from different sources

I apologize that the reproducible example is not quite minimal.

I have a large shiny app, the example here is just an excerpt. I am trying to produce a DT table with checkboxes. The application has DT of available values on the left and three DT on the right where selected values can be moved with buttons. The input of the checkbox table below is a reactive object with all unique combinations of the values from the three reactiveValues' objects with selected values which are displayed in the other three DT tables of selected values from above. It all works fine when I render the table with the checkboxes. However, when I click on the checkboxes, not all are actually selected and displayed in the last DT output. There is some patterns of the unwanted behavior:

  1. If there are names only in the first (or the second, or the third) DT on the right, all works fine, clicking on the checkbox produces the desired result.
  2. When there are selected values in the first and the second DTs then clicking on the first checkbox has no effect.
  3. If there are values in all three DTs on the right, then clicking on the first few checkboxes does not have any effect, but it works for the subsequent.

Different other scenarios are possible, depending on the number of selected values in the three DT outputs on the right. I can't reach any explanation why not all of the checkbox values are collected. When the checkboxes are generated with the shinyInput function, their number matches the number of all possible pairs. However, the shinyValue function collects just part of them.

Here is the code:

library(shiny)
library(DT)
library(data.table)

mydt <- data.table(Variables = c("IDCNTRY", "ASBG01", "ASBG03", "ASBG04", "ASBG05A", "ASBG05B", "ASBG05C", "ASBG05D", "ASBG05E", "ASBG05F", "ASBG05G", "ASBG05H", "ASBG06", "ASBG07A", "ASBG07B", "ASBG08", "ASBG09A", "ASBG09B", "ASBG09C", "ASBG10A", "ASBG10B"), Variable_Labels = c("COUNTRY ID", "SEX OF STUDENT", "OFTEN SPEAK <LANG OF TEST> AT HOME", "AMOUNT OF BOOKS IN YOUR HOME", "HOME POSSESS/COMPUTER OR TABLET", "HOME POSSESS/STUDY DESK", "HOME POSSESS/OWN ROOM", "HOME POSSESS/INTERNET CONNECTION", "HOME POSSESS/<COUNTRY SPECIFIC>", "HOME POSSESS/<COUNTRY SPECIFIC>", "HOME POSSESS/<COUNTRY SPECIFIC>", "HOME POSSESS/<COUNTRY SPECIFIC>", "ABOUT HOW OFTEN ABSENT FROM SCHOOL", "HOW OFTEN FEEL THIS WAY/TIRED", "HOW OFTEN FEEL THIS WAY/HUNGRY", "HOW OFTEN BREAKFAST ON SCHOOL DAYS", "USE COMPUTER TABLET/HOME", "USE COMPUTER TABLET/SCHOOL", "USE COMPUTER TABLET/OTHER", "USE COMPUTER TABLET SCHOOLWORK/READING", "USE COMPUTER TABLET SCHOOLWORK/PREPARING"), order_col = 1:21)

shinyApp(
  ui <- fluidPage(
    fluidRow(
      column(width = 6, align = "center",
             DTOutput(outputId = "allAvailableVars"),
      ),
      
      column(width = 6,
             fluidRow(
               column(width = 2, align = "center",
                      br(), br(),  br(),
                      uiOutput(outputId = "arrowSelGroup1VarsRight"),
                      uiOutput(outputId = "arrowSelGroup1VarsLeft")
               ),
               column(width = 10,
                      DTOutput(outputId = "group1Vars")
               )
             ),
             
             fluidRow(
               column(width = 2, align = "center",
                      br(), br(),  br(),
                      uiOutput(outputId = "arrowSelGroup2VarsRight"),
                      uiOutput(outputId = "arrowSelGroup2VarsLeft")
               ),
               column(width = 10,
                      DTOutput(outputId = "group2Vars"),
               ),
               br()
             ),
             
             fluidRow(
               column(width = 2, align = "center",
                      br(), br(),  br(),
                      uiOutput(outputId = "arrowSelGroup3Right"),
                      uiOutput(outputId = "arrowSelGroup3Left")
               ),
               
               column(width = 10,
                      DTOutput(outputId = "group3Vars"),
               )
             )
      )
    ),
    
    fluidRow(
      column(width = 6,
             DTOutput(outputId = "checkBoxTable")
      ),
      column(width = 6,
             DTOutput(outputId = "selectedCheckBoxTable")
      )
    )
  ),
  
  
  server <- function(input, output, session) {
    
    observe({
      
      # Create initial values for the available and selected variables.
      initial.available.vars <- mydt
      initial.selected.split.vars <- data.table(Variables = as.character(), Variable_Labels = as.character(), order_col = as.numeric())
      initial.selected.bckg.vars <- data.table(Variables = as.character(), Variable_Labels = as.character(), order_col = as.numeric())
      initial.selected.PV.vars <- data.table(Variables = as.character(), Variable_Labels = as.character(), order_col = as.numeric())
      initial.checkboxes <- data.table(Variable1 = as.character(), Check = as.character(), Variable2 = as.character())
      
      allVars <- reactiveValues(availVars = initial.available.vars, selectedGroup1Vars = initial.selected.split.vars, selectedGroup2Vars = initial.selected.bckg.vars, selectedGroup3Vars = initial.selected.PV.vars)
      
      output$arrowSelGroup1VarsRight <- renderUI({
        actionButton(inputId = "arrowSelGroup1VarsRight", label = NULL, icon("angle-right"), width = "50px")
      })
      
      output$arrowSelGroup1VarsLeft <- renderUI({
        actionButton(inputId = "arrowSelGroup1VarsLeft", label = NULL, icon("angle-left"), width = "50px")
      })
      
      output$arrowSelGroup2VarsRight <- renderUI({
        actionButton(inputId = "arrowSelGroup2VarsRight", label = NULL, icon("angle-right"), width = "50px")
      })
      
      output$arrowSelGroup2VarsLeft <- renderUI({
        actionButton(inputId = "arrowSelGroup2VarsLeft", label = NULL, icon("angle-left"), width = "50px")
      })
      
      output$arrowSelGroup3Right <- renderUI({
        actionButton(inputId = "arrowSelGroup3Right", label = NULL, icon("angle-right"), width = "50px")
      })
      
      output$arrowSelGroup3Left <- renderUI({
        actionButton(inputId = "arrowSelGroup3Left", label = NULL, icon("angle-left"), width = "50px")
      })
      
      observeEvent(input$arrowSelGroup1VarsRight, {
        req(input$allAvailableVars_rows_selected)
        allVars$selectedGroup1Vars <- rbind(isolate(allVars$selectedGroup1Vars), allVars$availVars[input$allAvailableVars_rows_selected, , drop = FALSE])
        allVars$selectedGroup1Vars <- allVars$selectedGroup1Vars[complete.cases(allVars$selectedGroup1Vars[ , "Variables"]), , drop = FALSE]
        allVars$availVars <- isolate(allVars$availVars[-input$allAvailableVars_rows_selected, , drop = FALSE])
      })
      
      observeEvent(input$arrowSelGroup1VarsLeft, {
        req(input$group1Vars_rows_selected)
        allVars$availVars <- rbind(isolate(allVars$availVars), allVars$selectedGroup1Vars[input$group1Vars_rows_selected, , drop = FALSE])
        allVars$availVars <- allVars$availVars[complete.cases(allVars$availVars[ , "Variables"]), , drop = FALSE]
        allVars$selectedGroup1Vars <- isolate(allVars$selectedGroup1Vars[-input$group1Vars_rows_selected, , drop = FALSE])
      })
      
      observeEvent(input$arrowSelGroup2VarsRight, {
        req(input$allAvailableVars_rows_selected)
        allVars$selectedGroup2Vars <- rbind(isolate(allVars$selectedGroup2Vars), allVars$availVars[input$allAvailableVars_rows_selected, , drop = FALSE])
        allVars$selectedGroup2Vars <- allVars$selectedGroup2Vars[complete.cases(allVars$selectedGroup2Vars[ , "Variables"]), , drop = FALSE]
        allVars$availVars <- isolate(allVars$availVars[-input$allAvailableVars_rows_selected, , drop = FALSE])
      })
      
      observeEvent(input$arrowSelGroup2VarsLeft, {
        req(input$group2Vars_rows_selected)
        allVars$availVars <- rbind(isolate(allVars$availVars), allVars$selectedGroup2Vars[input$group2Vars_rows_selected, , drop = FALSE])
        allVars$availVars <- allVars$availVars[complete.cases(allVars$availVars[ , "Variables"]), , drop = FALSE]
        allVars$selectedGroup2Vars <- isolate(allVars$selectedGroup2Vars[-input$group2Vars_rows_selected, , drop = FALSE])
      })
      
      observeEvent(input$arrowSelGroup3Right, {
        req(input$allAvailableVars_rows_selected)
        allVars$selectedGroup3Vars <- rbind(isolate(allVars$selectedGroup3Vars), allVars$availVars[input$allAvailableVars_rows_selected, , drop = FALSE])
        allVars$selectedGroup3Vars <- allVars$selectedGroup3Vars[complete.cases(allVars$selectedGroup3Vars[ , "Variables"]), , drop = FALSE]
        allVars$availVars <- isolate(allVars$availVars[-input$allAvailableVars_rows_selected, , drop = FALSE])
      })
      
      observeEvent(input$arrowSelGroup3Left, {
        req(input$group3Vars_rows_selected)
        allVars$availVars <- rbind(isolate(allVars$availVars), allVars$selectedGroup3Vars[input$group3Vars_rows_selected, , drop = FALSE])
        allVars$availVars <- allVars$availVars[complete.cases(allVars$availVars[ , "Variables"]), , drop = FALSE]
        allVars$selectedGroup3Vars <- isolate(allVars$selectedGroup3Vars[-input$group3Vars_rows_selected, , drop = FALSE])
      })
      
      output$allAvailableVars <- renderDT({
        setkeyv(x = allVars$availVars, cols = "order_col")
      },
      rownames = FALSE, colnames = c("Names", "Labels", "sortingcol"), extensions = list("Scroller"),
      options = list(dom = "ti", ordering = FALSE, autoWidth = TRUE, pageLength = 5000, deferRender = TRUE, scrollY = 455, scroller = TRUE))
      
      output$group1Vars <- renderDT({
        allVars$selectedGroup1Vars
      },
      rownames = FALSE, colnames = c("Names", "Labels", "sortingcol"), extensions = list("Scroller"),
      options = list(dom = "ti", ordering = FALSE, pageLength = 5000, autoWidth = TRUE, deferRender = TRUE, scrollY = 100, scroller = TRUE))
      
      output$group2Vars <- renderDT({
        allVars$selectedGroup2Vars
      },
      rownames = FALSE, class = "cell-border stripe;compact cell-border;", extensions = list("Scroller"),
      options = list(dom = "ti", ordering = FALSE, pageLength = 5000, autoWidth = TRUE, deferRender = TRUE, scrollY = 100, scroller = TRUE))
      
      output$group3Vars <- renderDT({
        allVars$selectedGroup3Vars
      },
      rownames = FALSE, class = "cell-border stripe;compact cell-border;", extensions = list("Scroller"),
      options = list(dom = "ti", ordering = FALSE, pageLength = 5000, autoWidth = TRUE, rowCallback = JS("function(r,d) {$(r).attr('height', '40px')}"), deferRender = TRUE, scrollY = 100, scroller = TRUE))
      
      # Define a function to generate the checkboxes in the table.
      shinyInput = function(FUN, len, id, ...) {
        inputs <- character(len)
        lapply(seq_len(len), function(i) {
          inputs[i] <- as.character(FUN(paste0(id, i), label = NULL, ...))
        })
      }
      
      # Define a function to read back the input from the checkboxes.
      shinyValue <- function(id, len) {
        sapply(seq_len(len), function(i) {
          value <- input[[paste0(id, i)]]
          if(is.null(value)) {
            NA
          } else {
            value
          }
        })
      }
      
      # Combine a data.table with the unique combinations of the selected variables.
      possibleCheckboxes <- reactive({
        if(nrow(rbindlist(l = list(allVars$selectedGroup1Vars, allVars$selectedGroup2Vars, allVars$selectedGroup3Vars))) > 1) {
          selected.vars <- c(allVars$selectedGroup1Vars[ , Variables], allVars$selectedGroup2Vars[ , Variables], allVars$selectedGroup3Vars[ , Variables])
          tmp <- transpose(as.data.table(combn(x = selected.vars, m = 2)))
          data.table(Variable1 = tmp[ , V1], Check = shinyInput(FUN = checkboxInput, len = nrow(tmp), id = "cbox_", width = "5px"), Variable2 = tmp[ , V2])
        } else {
          initial.checkboxes
        }
      })
      
      # Render the data table for the checkboxes.
      output$checkBoxTable <- renderDT({
        possibleCheckboxes()
      },
      server = FALSE, escape = FALSE, rownames = FALSE, colnames = c("Variable 1", "", "Variable 2"), extensions = list("Scroller"), selection="none",
      options = list(dom = "ti", ordering = FALSE, autoWidth = TRUE, preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'), drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } '), deferRender = TRUE, scrollY = 450, scroller = TRUE))
      
      selectedCheckboxes <- reactive({
        if(nrow(possibleCheckboxes()) > 0) {
          possibleCheckboxes()[shinyValue(id = "cbox_", len = nrow(possibleCheckboxes())) == TRUE]
        } else {
          initial.checkboxes
        }
      })
      
      output$selectedCheckBoxTable <- renderDT({
        selectedCheckboxes()[ , mget(c("Variable1", "Variable2"))]
      },
      server = FALSE, escape = FALSE, rownames = FALSE, colnames = c("Variable 1", "Variable 2"), extensions = list("Scroller"), selection="none",
      options = list(dom = "ti",
                     ordering = FALSE,
                     autoWidth = TRUE,
                     preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
                     drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } '),
                     deferRender = TRUE, scrollY = 450, scroller = TRUE
      ))
    })
  }
)

Here is a screenshot in the final outputs:

enter image description here

Can someone help with this?




Using Checkboxes on Google Sheets

I have a Google sheet (Main) with a lot of data. I want to import data from Main sheet to another sheet (A) using Checkboxes (or any other filtering method).

Once the data is imported to sheet (A), I want to be able to make changes to it and those changes should reflect in the Main data/sheet.

Can this be done? Please help/advise.

Regards.




vendredi 28 janvier 2022

I need help figuring out how to move a row in google sheets to another sheet if there are multiple checkboxes in the same row

I have a workbook in google sheets. With multiple columns and rows, more rows will be added. I am trying to figure out how to expand to copy the entire row if there is a check in one or more of the column checkboxes to a new sheet (which there will be several).




Angular 12 Upgrade to typescript 4.3.2 Kendo-grid checkbox issue

I have upgraded my Angular project from Angular 6 to Angular 12 and as a result typescript to 4.3.2. The following code which was working before is not working anymore. onSelectAllChange event, which is fired when all checkboxes are selected is working fine as before. However, onSelectedKeysChange, is not not having the value of mySelection. I’m trying to retrieve the value of this.mySelection[i].RequestNumber in ApproveProjects() where it throws error:

TypeError: Cannot read properties of undefined (reading 'RequestNumber')

Here is my telerik Kendo-grid with checkbox:

<kendo-grid [data]="view" [style.maxHeight.px]="650"
                        [pageSize]="gridState.take"
                        [skip]="gridState.skip"
                        [sort]="gridState.sort"
                        [sortable]="{ mode: 'multiple' }"
                        (sortChange)="sortChange($event)"
                        [filter]="gridState.filter"
                        (dataStateChange)="dataStateChange($event)"
                        [selectable]="{ checkboxOnly: false,mode: 'multiple'}"
                        [kendoGridSelectBy]="mySelectionKey"
                        [selectedKeys]="mySelection"
                        (selectedKeysChange)="onSelectedKeysChange($event)"
                        [pageable]="true"
                        (pageChange)="pageChange($event)"
                        style="height:50vh"
                        filterable="menue"
                        [navigable]="true"
                        [resizable]="true"
                        [reorderable]="true">
                <ng-template kendoGridToolbarTemplate>
                    <label style="font-size:medium">Select Projects to Approve/Reject:</label>
                </ng-template>
                <kendo-grid-checkbox-column width="25">
                    <ng-template kendoGridHeaderTemplate>
                        <input class="k-checkbox" id="selectAllCheckboxId" kendoGridSelectAllCheckbox
                               [state]="selectAllState"
                               (selectAllChange)="onSelectAllChange($event)">
                        <label class="k-checkbox-label" for="selectAllCheckboxId"></label>
                    </ng-template>

                </kendo-grid-checkbox-column>

                <kendo-grid-column field='RequestNumber' title='Project Request#' width='175'>
                </kendo-grid-column>
            //other columns
            </kendo-grid>

Component code:

//this is working fine
public onSelectAllChange(checkedState: SelectAllCheckboxState) {
        if (checkedState === 'checked') {
            this.mySelection = this.localData.map((item) => item);

            this.selectAllState = 'checked';
        } else {
            this.mySelection = [];
            this.selectAllState = 'unchecked';
        }
        this.CallResetSession();
    }
    public mySelectionKey(context: RowArgs): any {
        return context.dataItem;
    }
    public onSelectedKeysChange(e) {
       // const len = this.mySelection.length;
        const len = e.length;
        this.mySelection.length = e.length;

        if (len === 0) {
            this.selectAllState = 'unchecked';
        } else if (len > 0 && len < this.localData.length) {
            this.selectAllState = 'indeterminate';
        } else {
            this.selectAllState = 'checked';
        }
    }
ApproveProjects() {

        if (this.mySelection.length > 0) {
            if (confirm("Are you sure to approve these " + this.mySelection.length + " Project requests?")) {

                for (var i = 0; i < this.mySelection.length; i++) {
                    this.ToApproveProjReqsDelimitedList.push(this.mySelection[i].RequestNumber);
                }
        //rest of the processing
            }
        }
        else {
            alert("Please select at least one item to Approve!");
        }
    }

Please guide




Getting the error "DataTables warning: table id=datatable - Cannot reinitialise DataTable"

DataTables warning: table id=datatable - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3

I'm trying to hide last three columns by default and display when checked again...

Checkbox filter -

<div class="show-hide-wrap">
Columns <input type="checkbox" id="title" name="title" value="title" class="toggle-vis" data-column="0" checked disabled="disabled"> <label for="title"> Title</label>
<input type="checkbox" id="status" name="status" value="title" class="toggle-vis" data-column="1" checked> <label for="Status"> Status</label>
<input type="checkbox" id="url" name="url" value="url" class="toggle-vis" data-column="2"  checked> <label for="url"> URL</label>
<input type="checkbox" id="version" name="version" value="version" class="toggle-vis" data-column="3" checked > <label for="version"> Version</label>
<input type="checkbox" id="System" name="System" value="System" class="toggle-vis" data-column="4"  checked> <label for="System"> System</label>
<input type="checkbox" id="Target" name="Target" value="Target" class="toggle-vis" data-column="5"  checked > <label for="Target"> Target</label>
<input type="checkbox" id="date" name="date" value="date" class="toggle-vis" data-column="6"> <label for="date"> Deployed On</label>
<input type="checkbox" id="security" name="security" value="security" class="toggle-vis" data-column="7"> <label for="security"> Security</label>
<input type="checkbox" id="links" name="links" value="links" class="toggle-vis" data-column="8"> <label for="links"> Links</label>
</div>

JS Code -

(function ($) 
{ 'use strict';
jQuery(document).ready(function() {
var table = $('#datatable').DataTable({
    columns: [
        {data: 'title'},
        {data: 'status'},
        {data: 'url'},
        {data: 'version'},
        {data: 'System'},
        {data: 'Target'},
        {data: 'date',visible:false},
        {data: 'security',visible:false},
        {data: 'links',visible:false}
    ]
});
 
    $('input.toggle-vis').on( 'change', function (e) {
        e.preventDefault();
 
        /* Get the column API object */
        var column = table.column( $(this).attr('data-column') );
 
        /* Toggle the visibility */
        column.visible( ! column.visible() );
    } );
} );
 })(jQuery, Drupal);



jeudi 27 janvier 2022

how to make similar widget list with addition Flutter

how can i make a similar list of checkboxes(buttons), with the ability to add a new element Here are design examples

Main screen

Add screen




Center check boxes with css in cfml page

I'm having a really basic issue with css. It won't let me centre my checkboxes in the middle of the page. The checkboxes are actually coldfusion, but should work the same.

myform.cfml:

.myform {
  position: relative;
  padding: 2rem;
  margin-left: auto;
  margin-right: auto;
}

.checkboxes {
  background-color: aquamarine;
}
<div class="myform">
  <cfform action="landing.cfml" method="post">

    <div class="checkboxes">
      <cfoutput query="toolIds">

        <input type="checkbox" name="myDataList" value="#toolid#" <cfif listFind(selectedTools, toolid)></cfif>> #toolname# <br />
      </cfoutput>
    </div>

    <cfinput type="Submit" name="SubmitForm" value="Submit">
  </cfform>
</div>

I coloured the background of the checkboxes aquamarine to see how it lies. It spreads across the whole screen. margin: auto; or margin: 0 auto; make no difference. It also doesn't matter if the margin: auto; is in the .myform or the .checkboxes, it still doesn't work. If I change it to margin-left: 30rem; margin-right:30rem; it moves, but I can't have an absolute positioning.

Everything I have read says to use margin: auto; and it should position the div in the centre horizontally.




mercredi 26 janvier 2022

How to add all checked boxes into separate LI tags

I want to separate all checked items into LI tags but right now it is adding them all to a single LI tag. What am I doing wrong? It's probably simple and I'm just dumb :(


let ul = document.querySelector('.ul')
let li = document.createElement('li')


getSelectedToys() {
        let { selectedToys } = this;
        const checked =  document.querySelectorAll('input[type=checkbox]:checked')


        for (var i = 0; i < checked.length; i++) {
            selectedToys.push(checked[i].value)
            console.log(selectedToys[i])           
        }

        selectedToys.forEach(function(item) {
            ul.appendChild(li)
            let text = document.createTextNode(item);
            li.appendChild(text)
       })



React - CheckboxTree filter

So i am using this package "react-checkbox-tree" to make a checkbox, but since this is made on classes components and i need to do it with functions and hooks, this is being a bit tricky to my actual skills.

//Checkbox Tree
  const [checkedTree, setCheckedTree] = useState([]);
  const [expandedTree, setExpandedTree] = useState(["1"]);
  const [filterText, setFilterText] = useState("");
  const [nodesFiltered, setNodesFiltered] = useState();

  ///FILTER LOGIC /////
  const onFilterChange = (e) => {
    setFilterText(e.target.value);
    if (e.target.value) {
      filterTree();
    }
  };

  const filterTree = () => {
    // Reset nodes back to unfiltered state
    if (!filterText || filterText === "" || filterText.length === 0) {
      setNodesFiltered(nodes);
      return;
    }

    const nodesFiltered = (nodes) => {
      return nodes.reduce(filterNodes, []);
    };

    setNodesFiltered(nodesFiltered);
  };

  const filterNodes = (filtered, node) => {
    const children = (node.children || []).reduce(filterNodes, []);
    if (
      // Node's label matches the search string
      node.label.toLocaleLowerCase().indexOf(filterText.toLocaleLowerCase()) >
        -1 ||
      // Or a children has a matching node
      children.length
    ) {
      filtered.push({ ...node, ...(children.length && { children }) });
    }
    return filtered;
  };
  //
  • My first problem is that when i search for the parent, i only get the last children of the array for some reason.

  • The Second is that when i use the backspace button, the filter stops working until i clean every char.

I made a codesandbox to help you guys to understand the problems: https://codesandbox.io/s/checkboxtree-6gu60

This is the example on with classes: https://github.com/jakezatecky/react-checkbox-tree/blob/master/examples/src/js/FilterExample.js

Tks in advance!




React dynamic table with dynamic checkboxes

So basically I want to dynamically generate a table with checkboxes where I can give user rights to users. The thing is this has to be dynamic which in this case means that I get all available user rights via an API call and all Users with their already given rights via an API. But I don't really know how I start with this. My first thought would be something like just a dynamic table and checkbox but I don't really know how I could like match the checkbox with the user right and the user. I added an example table made with excel where the X replaces the checkboxes

example picture




Copy data to new sheet in next blank row when checkbox is ticked

I’m trying to copy data (D:AG) from sheet “orders” to the next blank row in sheet “Del to book” when a checkbox is ticked in column AB on the “orders” sheet.

I’m no expert but managed to use a simple formula to copy the data across: =FILTER(ORDERS!D:AG,ORDERS!AB:AB=TRUE)

However, this only copies the data in the order it appears on the “orders sheet. I need it so that the data appears on the “Del 2 book” sheet in the order it is ticked on the “orders” sheet.

Hope that makes sense. Unfortunately, some of this data is sensitive so I cannot provide an example but hopefully someone can help form my explanation above.

Thanks

** EDIT **

I’ve stripped out all the sensitive info and left a few examples of what I’m working with:

https://docs.google.com/spreadsheets/d/1L3r_0i8Q8D82W_lyJRb6a1ll2iAzeoTKv67GPiamxZ4/edit?usp=sharing

You’ll see my current formula copies all of the data from “orders” to cells AC:BF on the “Del/Fab 2 Book” sheet and I’ve then created more formulas (on row 3, which is hidden) to filter the information out to what is required on this sheet.

Please let me know if you have any questions.

Hope you can help.

Thanks Jack




mardi 25 janvier 2022

Multiple Checkbox Filter is giving me duplicate results

I have a checkbox filter for a product page I'm working on, and it works, but I'm getting duplicate results if an item matches multiple criteria. For example, if I check both 'Size 1' and 'Nike', the resulting product card displays twice. I would like it to only display once. Here's what I have:

let show_sizes_array = []; //Where the filtered sizes get stored

$(document).ready(function() {
  showAllItems(); //Display all items with no filter applied

  $(".size-filter-check").click(function() {
    //When a checkbox is clicked
    let size_clicked = $(this).attr("data-size"); //The certain size checkbox clicked

    if ($(this).is(":checked")) {
      show_sizes_array.push(size_clicked); //Was not checked so add to filter array
      showItemsFiltered(); //Show items grid with filters
    } else {
      //Unchecked so remove from the array
      show_sizes_array = show_sizes_array.filter(function(elem) {
        return elem !== size_clicked;
      });
      showItemsFiltered(); //Show items grid with new filters
    }

    if (!$("input[type=checkbox]").is(":checked")) {
      //No checkboxes are checked
      show_sizes_array = []; //Clear size filter array
      showAllItems(); //Show all items with NO filters applied
    }
  });
});



//Mock API data:
let category_items = [{
    id: 1,
    category_id: 8,
    price: 39.42,
    title: "Shoes with id #1",
    thumbnail: "https://www.transparentpng.com/download/adidas-shoes/a4xO3G-adidas-shoes-adidas-shoe-kids-superstar-daddy-grade.png",
    sizes: ["Size1"],
    brand: ["Nike"]
  },
  {
    id: 2,
    category_id: 8,
    price: 31.93,
    title: "Shoes with id #2",
    thumbnail: "https://www.transparentpng.com/download/adidas-shoes/a4xO3G-adidas-shoes-adidas-shoe-kids-superstar-daddy-grade.png",
    sizes: ["Size2"],
    brand: ["Adidas"]
  },
  {
    id: 3,
    category_id: 8,
    price: 49.44,
    title: "Shoes with id #3",
    thumbnail: "https://www.transparentpng.com/download/adidas-shoes/a4xO3G-adidas-shoes-adidas-shoe-kids-superstar-daddy-grade.png",
    sizes: ["Size3"],
    brand: ["Nike"]
  },
  {
    id: 4,
    category_id: 8,
    price: 65.38,
    title: "Shoes with id #4",
    thumbnail: "https://www.transparentpng.com/download/adidas-shoes/a4xO3G-adidas-shoes-adidas-shoe-kids-superstar-daddy-grade.png",
    sizes: ["Size4"],
    brand: ["Other"]
  },
];

function showAllItems() {
  //Default grid to show all items on page load in
  $("#display-items-div").empty();
  for (let i = 0; i < category_items.length; i++) {
    let item_content =
      '<div class="product-card" data-available-sizes="' +
      category_items[i]["sizes"] +
      '"><b>' +
      category_items[i]["title"] +
      '</b><br><img src="' +
      category_items[i]["thumbnail"] +
      '" height="64" width="64" alt="shoe thumbnail"><p>$' +
      category_items[i]["price"] +
      "</p></div>";
    $("#display-items-div").append(item_content);
  }
}

function showItemsFiltered() {
  //Default grid to show all items on page load in
  $("#display-items-div").empty();
  for (let i = 0; i < category_items.length; i++) {
    //Go through the items but only show items that have size from show_sizes_array
    if (show_sizes_array.some((v) => category_items[i]["sizes"].includes(v))) {
      let item_content =
        '<div class="product-card" data-available-sizes="' +
        category_items[i]["sizes"] +
        '"><b>' +
        category_items[i]["title"] +
        '</b><br><img src="' +
        category_items[i]["thumbnail"] +
        '" height="64" width="64" alt="shoe thumbnail"><p>$' +
        category_items[i]["price"] +
        "</p></div>";
      $("#display-items-div").append(item_content); //Display in grid
    }

    //Test filter for speeds//
    if (show_sizes_array.some((v) => category_items[i]["brand"].includes(v))) {
      let item_content =
        '<div class="product-card" data-available-speed="' +
        category_items[i]["sizes"] +
        '"><b>' +
        category_items[i]["title"] +
        '</b><br><img src="' +
        category_items[i]["thumbnail"] +
        '" height="64" width="64" alt="shoe thumbnail"><p>$' +
        category_items[i]["price"] +
        "</p></div>";
      $("#display-items-div").append(item_content); //Display in grid
    }
    //end test filter//

  }
}
.product-page-wrapper {
  display: flex;
  padding: 20px;
}

.filter-wrapper {
  border: 1px solid #eee;
  width: 20%;
}

.items-wrapper {
  width: 80%
}

.items {
  padding: 20px;
}

.product-card {
  width: 23%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="product-page-wrapper">
  <!--Product Filter-->
  <div class="filter-wrapper">
    <h2>Filter by</h2>
    <hr>
    <h3>Size:</h3>
    <form id="size-form">
      <div class="form-check">
        <input class="form-check-input size-filter-check" type="checkbox" value="" id="size-check" data-size="Size1">
        <label class="form-check-label" for="size-check">Size 1</label>
      </div>
      <div class="form-check">
        <input class="form-check-input size-filter-check" type="checkbox" value="" id="size-check" data-size="Size2">
        <label class="form-check-label" for="size-check">Size 2</label>
      </div>
      <div class="form-check">
        <input class="form-check-input size-filter-check" type="checkbox" value="" id="size-check" data-size="Size3r">
        <label class="form-check-label" for="size-check">Size 3</label>
      </div>
      <div class="form-check">
        <input class="form-check-input size-filter-check" type="checkbox" value="" id="size-check" data-size="Size4">
        <label class="form-check-label" for="size-check">Size 4</label>
      </div>
    </form>

    <h3>Brand:</h3>
    <form id="brand-form">
      <div class="form-check">
        <input class="form-check-input size-filter-check" type="checkbox" value="" id="brand-check" data-size="Other">
        <label class="form-check-label" for="size-check">Other</label>
      </div>
      <div class="form-check">
        <input class="form-check-input size-filter-check" type="checkbox" value="" id="brand-check" data-size="Nike">
        <label class="form-check-label" for="size-check">Nike</label>
      </div>
      <div class="form-check">
        <input class="form-check-input size-filter-check" type="checkbox" value="" id="brand-check" data-size="Adidas">
        <label class="form-check-label" for="size-check">Adidas</label>
      </div>
      <div class="form-check">
        <input class="form-check-input size-filter-check" type="checkbox" value="" id="brand-check" data-size="Sketchers">
        <label class="form-check-label" for="size-check">Sketchers</label>
      </div>

    </form>
  </div>

  <!--Display Items-->
  <div class="items-wrapper">
    <div class="items" id="display-items-div"></div>
  </div>

</div>

I'm still rather new to JS, so I'm pleased that I've come as far as I have. Any help is appreciated, or if I'm using bad practices, please correct me now.




lundi 24 janvier 2022

Custom ThreeState CheckBox not working with Click trigger event

I made my own MyCheckBox control by overriding the default CheckBox control. Reason being I wanted to change order of it's states when it's ThreeState property is set to true.

The Default order is

UnChecked -> Checked -> Indeterminate -> Unchecked -> ..... (Repeats)

I wanted the order to be like

UnChecked -> Indeterminate -> Checked -> Unchecked -> ..... (Repeats)

So following is the code which made it happen.

    public class MyCheckBox : CheckBox
    {
        protected override void OnClick(EventArgs e)
        {
            if (AutoCheck)
            {
                if (CheckState == CheckState.Indeterminate)
                {
                    CheckState = CheckState.Checked;
                }
                else if (CheckState == CheckState.Checked)
                {
                    CheckState = CheckState.Unchecked;
                }
                else
                {
                    CheckState = ThreeState ? CheckState.Indeterminate : CheckState.Checked;
                }
            }
        }
    }

All worked fine until here and the problem began when I enabled it's Click trigger event.

enter image description here

The Click event is not firing.

I went back to the CheckBox OnClick() to see if I am missing something. This is the code that is there which I overridden with the above mentioned code.

        protected override void OnClick(EventArgs e)
        {
            if (autoCheck)
            {
                switch (CheckState)
                {
                    case CheckState.Unchecked:
                        CheckState = CheckState.Checked;
                        break;
                    case CheckState.Checked:
                        if (threeState)
                        {
                            CheckState = CheckState.Indeterminate;
                            if (AccObjDoDefaultAction)
                            {
                                AccessibilityNotifyClients(AccessibleEvents.StateChange, -1);
                            }
                        }
                        else
                        {
                            CheckState = CheckState.Unchecked;
                        }

                        break;
                    default:
                        CheckState = CheckState.Unchecked;
                        break;
                }
            }

            base.OnClick(e);
        }

I missed the base.OnClick(e) method of course but as soon as I add this method to my MyCheckBox OnClick(), now the Click event is firing okay but the CheckState of MyCheckBox is stuck at Unchecked. No matter how many times I click it's stuck on Unchecked and doesn't change.

I spent hours figuring out what is happening but with no luck.

Upon further debugging I found out that the CheckState does change (Can see it if I pause the program just before the Click trigger event fires) but after it's Click event ends the CheckState reverts back to UnChecked.

Can anyone figure this out? I give up.

I am on .net winforms.




How to get checkbox values in android studio with onCheckboxClicked

private CheckBox ch;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    register = findViewById(R.id.btn_register);
    ch = findViewById(R.id.checkboxCh);

    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            JSONObject jsonObject = new JSONObject();
            RequestQueue requestQueue = Volley.newRequestQueue(RegisterActivity.this);

            try{
                jsonObject.put("ch", ch);
            }catch (JSONException exception){
                exception.printStackTrace();
            }

            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, REGISTER_URL, jsonObject, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    System.out.println(response);
                    Toast.makeText(RegisterActivity.this, "You have registered", Toast.LENGTH_LONG).show();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                    Toast.makeText(RegisterActivity.this, "An error occurred", Toast.LENGTH_SHORT).show();
                }
            });

            //add request to the requestQueue
            requestQueue.add(jsonObjectRequest);
        }
    });

}

public void onCheckboxClicked(View view){
    //Is the view now checked?
    Boolean checked = ((CheckBox) view).isChecked();

    //Check if checkbox is selected or not
    if(ch.isChecked()){
        //checked=true;
    }else{
        //checked=false;
    }
}

I am trying to send the true or false answer from boolean onCheckBoxClicked using JSONObject to my database. But whatever code I tried in if statement was wrong. Do you have any suggestions? I would apreciate it. Thank you!




dimanche 23 janvier 2022

How do I set my checkbox checked by default after a certain action is performed in Android Studio?

everyone! Please help with finding a solution to this problem. I would very much appreciate it! I have an activity with a list of checkboxes. A checkbox and after clicking it, the next action is called, performed, and completed. Afterward, the action is completed, the app returns to the action with a list of checkboxes and now I want the used checkbox to be checked by default and unable to be clicked again. Please help!

This is what I tried to do but was not successful checkbox becomes unchecked when I return to the action:

P2106.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked){
                Intent move = new Intent(GeneralRoute.this, ScanTest.class);
                startActivity(move);
                P2106.setChecked(true);
            }
        }
    });



Dynamic Javascript String Generator w/ Checkboxes

My web page allows users to generate strings/phrases by selecting a combination of two radio buttons from two different groups: mode and category. Mode determines the order that the generator runs through the array, while category determines which array the function is pulling the strings from. After selecting their choice of buttons, they click the 'Push' button and a string pops up. See the snippet below:

class modes {
    constructor(items) {
        this.items = items;
        this.randomUnused = [...items];
        this.forwardIndex = 0;
        this.reverseIndex = items.length - 1;
    }
    forwardItem() {
        return this.items[this.forwardIndex++ % (this.items.length)];
    }
    randomItem() {
        if (!this.randomUnused.length) {
          this.randomUnused.push(...this.items);
        }
        const index = Math.floor(Math.random() * this.randomUnused.length);
        return this.randomUnused.splice(index, 1);
    }
    reverseItem() {
        if (this.reverseIndex < 0) {
          this.reverseIndex = this.items.length - 1;
        }
        return this.items[this.reverseIndex--];
    }
}
const categ = {
    A: new modes([
        "A example 1",
        "A example 2",
        "A example 3",
        "A example 4",
    ]),
    B: new modes([
        "B example 1",
        "B example 2",
        "B example 3",
        "B example 4",
    ]),
    C: new modes([
        "C example 1",
        "C example 2",
        "C example 3",
        "C example 4",
    ]),
    D: new modes([
        "D example 1",
        "D example 2",
        "D example 3",
        "D example 4",
    ])
};
function main() {
    const output = document.querySelector("output");
    if(!(document.forms.thingSelection2.type.value in categ)) {
        return false;
    }
    const list = categ[document.forms.thingSelection2.type.value];
    const method = document.forms.thingSelection1.mode.value + "Item";
    const item = list[method]();
    output.innerHTML = item;
}
const abutton = document.getElementById("abutton");
if(abutton) {
    abutton.addEventListener("click", main);
}
<output></output>

<button id="abutton">Push</button>

<form name="thingSelection1">
    Forwards<input type="radio" name="mode" value="forward">
    Random<input type="radio" name="mode" value="random">
    Backwards<input type="radio" name="mode" value="reverse">
</form>

<form name="thingSelection2">
    <li><input type="radio" name="type" value="A">Choice A</li>
    <li><input type="radio" name="type" value="B">Choice B</li>
    <li><input type="radio" name="type" value="C">Choice C</li>
    <li><input type="radio" name="type" value="D">Choice D</li>
</form>

Each category is currently represented by a radio button and has its own separate array, so only one may be selected at a time. My goal is to allow the user to select multiple categories and combine them into a new array, then cycle through them.

Problem 1: Changing the category radio buttons into checkboxes causes the function to break. The snippet below illustrates this. I figure this is due to the fact that checkboxes have 3 possible states (checked, unchecked, indeterminate) while radio buttons can only be true or false. I am unsure what changes to make to the function to allow the checkboxes to work. I could use some assistance. I'm fairly new to javascript, so please be patient.

class modes {
    constructor(items) {
        this.items = items;
        this.randomUnused = [...items];
        this.forwardIndex = 0;
        this.reverseIndex = items.length - 1;
    }
    forwardItem() {
        return this.items[this.forwardIndex++ % (this.items.length)];
    }
    randomItem() {
        if (!this.randomUnused.length) {
          this.randomUnused.push(...this.items);
        }
        const index = Math.floor(Math.random() * this.randomUnused.length);
        return this.randomUnused.splice(index, 1);
    }
    reverseItem() {
        if (this.reverseIndex < 0) {
          this.reverseIndex = this.items.length - 1;
        }
        return this.items[this.reverseIndex--];
    }
}
const categ = {
    A: new modes([
        "A example 1",
        "A example 2",
        "A example 3",
        "A example 4",
    ]),
    B: new modes([
        "B example 1",
        "B example 2",
        "B example 3",
        "B example 4",
    ]),
    C: new modes([
        "C example 1",
        "C example 2",
        "C example 3",
        "C example 4",
    ]),
    D: new modes([
        "D example 1",
        "D example 2",
        "D example 3",
        "D example 4",
    ])
};
function main() {
    const output = document.querySelector("output");
    if(!(document.forms.thingSelection2.type.value in categ)) {
        return false;
    }
    const list = categ[document.forms.thingSelection2.type.value];
    const method = document.forms.thingSelection1.mode.value + "Item";
    const item = list[method]();
    output.innerHTML = item;
}
const abutton = document.getElementById("abutton");
if(abutton) {
    abutton.addEventListener("click", main);
}
<output></output>

<button id="abutton">Push</button>

<form name="thingSelection1">
    Forwards<input type="radio" name="mode" value="forward">
    Random<input type="radio" name="mode" value="random">
    Backwards<input type="radio" name="mode" value="reverse">
</form>

<form name="thingSelection2">
    <li><input type="checkbox" name="type" value="A">Choice A</li>
    <li><input type="checkbox" name="type" value="B">Choice B</li>
    <li><input type="checkbox" name="type" value="C">Choice C</li>
    <li><input type="checkbox" name="type" value="D">Choice D</li>
</form>

Problem 2: Constructing the custom array in a specific order. While internet searches provide many ways to combine multiple arrays into one, like concat, none of them explain how to organize the strings in a custom order.

Example of what im looking for: ["A example 1", "B example 1", "C example 1", "D example 1", "A example 2", "B example 2"...]

Rather than simply stacking the array contents on top of each other, like concat and every other method of combining arrays: ["A example 1", "A example 2", "A example 3", "A example 4", "B example 1", "B example 2"...]

I'm unaware of any method to achieve this. No external libraries please.




R shiny - Checkbox and conditional panels issues

I have 2 separate issues here. First, the conditional panels for my data frame output are not working properly. Regardless of which checkbox you click on, I would like the data frame to output at the same location all the time. Currently, only the "efficient frontier" checkbox outputs at the right location. The "Monte Carlo" checkbox and the combination of both checkboxes shifts the data frame to the right for some reason..

The second issue I have has to do with "isolating" my checkboxes. Currently, if you change the checkboxes after outputting the results using the "Go" button, the graph will come and go. I would like for the graph output to only be modified when you click on the "Go" button.

Here is a snippet of my code. Everything after line 165 is just functions so don't waste any time looking at that.

Thank you for your help! :D

library(shiny)
library(quantmod)                            
library(PerformanceAnalytics)
library(zoo)
library(xts)
library(plyr)
library(ggplot2)
library(RiskPortfolios)
library(quadprog)
library(rvest)
library(purrr)
library(dplyr)

ui <- shinyUI(navbarPage("Analysis",
                         
     tabPanel(
         "Performance",
         
         titlePanel("Performance"),
         br(),
         
         sidebarLayout(
             sidebarPanel(
             ),
             mainPanel(
             )
         )),
     
     tabPanel(
         "Construction",
         
         titlePanel("Construction"),
         br(),
         
         sidebarLayout(
             sidebarPanel(
                 textInput("Stockw","Ticker (Yahoo)"),
                 numericInput("Sharesw","Number of Shares",0, min = 0, step = 1),
                 selectInput("Countryw","Country",choices = c("Canada","United States")),
                 
                 column(12,
                        splitLayout(cellWidths = c("70%", "30%"),
                                    actionButton("actionw", "Add",icon("dollar-sign"),  
                                                 style="color: #fff; background-color: #337ab7; border-color: #2e6da4"),
                                    actionButton("resetw", "Reset",icon("trash"),  
                                                 style="color: #fff; background-color: #337ab7; border-color: #2e6da4"))),
                 
                 br(),
                 br(),
                 checkboxInput("EF", "Efficient Frontier"),
                 checkboxInput("MonteCarlo", "Monte Carlo Simulation"),
                 
                 fluidRow(
                     align = "center",
                     p("____________________________________"),
                     p("Ready to launch?", style = "font-size: 14px; font-weight: bold"),
                     actionButton("Gow", "Go!", style="color: #fff; background-color: #337ab7; border-color: #2e6da4; margin: auto")),
                 
             ),
             
             mainPanel(
                 column(12,
                        tableOutput("tablew"), 
                        style = "height:185px; overflow-y: scroll; border: 1px solid #e3e3e3; border-radius: 8px; background-color: #f7f7f7;text-align: left; overflow-x: hidden"),
                 column(12,
                        br(),
                        align = "left",
                        splitLayout(cellWidths = c("70%", "30%"),
                                    plotOutput("Graphw"),
                                    conditionalPanel(condition = "input.EF == true && input.MonteCarlo == false", tableOutput("EFWeightsTable")),
                                    conditionalPanel(condition = "input.MonteCarlo == true && input.EF == false", tableOutput("MCWeightsTable")),
                                    conditionalPanel(condition = "input.MonteCarlo == true && input.EF == true", tableOutput("EFMCWeightsTable")))),
                 column(12,
                        align = "center",
                        conditionalPanel(condition = "input.EF == true && input.MonteCarlo == false", plotOutput("GraphEF")),
                        conditionalPanel(condition = "input.MonteCarlo == true && input.EF == false", plotOutput("GraphMC")),
                        conditionalPanel(condition = "input.MonteCarlo == true && input.EF == true", plotOutput("GraphEFMC"))
                 )
             )
         )
     )
))


#Server
server <- shinyServer(function(input, output) {
    
    
    #CONSTRUCTION
    
    #Store Initial Tickers/Number of Shares/Countries From User Inputs (In Vectors and Data Frame)
    valuesDFw <- reactiveValues() #Initialize Data Frame
    valuesDFw$dfw <- data.frame("Ticker" = numeric(0), "Shares" = numeric(0), "Country" = numeric(0)) 
    valuesVECw <- reactiveValues(tickersw = NULL, SharesVecw = NULL, CountryVecw = NULL) #Initialize Vectors
    
    observeEvent(input$actionw, {
        isolate(valuesDFw$dfw[nrow(valuesDFw$dfw) + 1,] <- c(input$Stockw, input$Sharesw, input$Countryw)) #Store Data frame
        valuesVECw$tickersw <- c(valuesVECw$tickersw,input$Stockw)  #Store Vectors
        valuesVECw$SharesVecw <- c(valuesVECw$SharesVecw,input$Sharesw)
        valuesVECw$CountryVecw <- c(valuesVECw$CountryVecw, input$Countryw)
    })
    
    #Reset Initial Tickers/Number of Shares/Countries From User Inputs (In Vectors and Data Frame)
    observeEvent(input$resetw, {
        valuesVECw$tickersw <- valuesVECw$tickersw[-1:-(length(valuesVECw$tickersw))] #Reset Vectors
        valuesVECw$SharesVecw <- valuesVECw$SharesVecw[-1:-(length(valuesVECw$SharesVecw))]
        valuesVECw$CountryVecw <- valuesVECw$CountryVecw[-1:-(length(valuesVECw$CountryVecw))]
        valuesDFw$dfw <- valuesDFw$dfw[0,] #Reset Data Frame
    })
    
    #Call Function (Defined Bellow)
    OPw <- reactiveValues()
    observeEvent(input$Gow, {
        
        OPw$PC <- Run(valuesVECw$tickersw,valuesVECw$SharesVecw,valuesVECw$CountryVecw)
        
        if(input$EF == TRUE && input$MonteCarlo == FALSE){
            showModal(modalDialog("Loading... Please Wait", footer=NULL)) #Creates Loading Pop-up Message
            OPw$LIST1 <- Run2(valuesVECw$tickersw,valuesVECw$SharesVecw,valuesVECw$CountryVecw)
        }
        removeModal() #Removes Loading Pop-up Message
        
        if(input$MonteCarlo == TRUE && input$EF == FALSE){
            showModal(modalDialog("Loading... Please Wait", footer=NULL)) #Creates Loading Pop-up Message
            OPw$LIST2 <- Run3(valuesVECw$tickersw,valuesVECw$SharesVecw,valuesVECw$CountryVecw)
        }
        removeModal() #Removes Loading Pop-up Message
        
        if(input$MonteCarlo == TRUE && input$EF == TRUE){
            showModal(modalDialog("Loading... Please Wait", footer=NULL)) #Creates Loading Pop-up Message
            OPw$LIST3 <- Run4(valuesVECw$tickersw,valuesVECw$SharesVecw,valuesVECw$CountryVecw)
        }
        removeModal() #Removes Loading Pop-up Message
    })
    
    #Output Variables
    output$tablew <- renderTable({valuesDFw$dfw}) #Initial Holdings Data Frame
    output$Graphw <- renderPlot({ #Pie Chart
        OPw$PC}, height = 400, width = 400)
    
    output$GraphEF <- renderPlot({ #Graph EF
        OPw$LIST1[[1]]
    },height = 550, width = 700)
    
    output$EFWeightsTable <- renderTable({ #Efficient Portfolio Weights Data Frame
        OPw$LIST1[[2]]}, colnames = TRUE
    )
    
    output$GraphMC <- renderPlot({ #Graph MC
        OPw$LIST2[[1]]
    },height = 550, width = 700)
    
    output$MCWeightsTable <- renderTable({ #Efficient Portfolio Weights Data Frame
        OPw$LIST2[[2]]}, colnames = TRUE
    )
    
    output$GraphEFMC <- renderPlot({ #Graph EFMC
        OPw$LIST3[[1]]
    },height = 550, width = 700)
    
    output$EFMCWeightsTable <- renderTable({ #Efficient Portfolio Weights Data Frame
        OPw$LIST3[[2]]}, colnames = TRUE
    )
    
    #Weights Function
    Run <- function(tickersw, SharesVecw, CountryVecw){
        
        USDtoCAD <- getQuote("CAD=X", src = "yahoo")[2] #Convert USD to CAD
        USDtoCAD <- USDtoCAD[[1]] #List to Numeric
        
        #Select Last Prices (From Tickers)
        PortfolioPricesw <- NULL 
        tickersw <- toupper(tickersw) #CAPS
        for (i in tickersw){
            PortfolioPricesw <- cbind(PortfolioPricesw, getQuote(i, src = "yahoo")[,2])          
        }  
        
        #Convert USD Denominated Assets to CAD
        for (i in 1:length(PortfolioPricesw)){
            if(CountryVecw[i] == "United States"){
                PortfolioPricesw[i] <- USDtoCAD*PortfolioPricesw[i]
            }
        }
        
        #Find Weights
        MarketValuew <- SharesVecw*PortfolioPricesw
        Weightsw <- MarketValuew/sum(MarketValuew)*100
        colnames(Weightsw) <- tickersw
        
        #Create Pie Chart 
        tickersw <- tickersw[order(Weightsw)]; Weightsw <- sort(Weightsw)
        Percent <- factor(paste(tickersw, scales::percent(Weightsw/100, accuracy = 0.1)), paste(tickersw, scales::percent(Weightsw/100, accuracy = 0.1)))
        
        Plot <- ggplot() + theme_bw() +
            geom_bar(aes(x = "", y = Weightsw, fill = Percent),
                     stat = "identity", color = "white") + 
            coord_polar("y", start = 0) +
            ggtitle("My Portfolio") +
            theme(axis.title = element_blank(),
                  plot.title = element_text(size=14, face="bold.italic", hjust = 0.5),
                  axis.text = element_blank(),
                  axis.ticks = element_blank(),
                  panel.grid = element_blank(),
                  panel.border = element_blank()) +
            guides(fill = guide_legend(reverse = TRUE)) + 
            theme(legend.text = element_text(size = 12),
                  legend.title = element_blank(),
                  legend.key.size = unit(0.8,"cm")) 
        
        #Output
        return(Plot)
    }
    
    #Efficient Frontier Function
    Run2 <- function(tickersw, SharesVecw, CountryVecw){
        
        AdjustedPrices <- NULL
        TargetPrice <- NULL
        CurrentPrice <- NULL
        yret <- NULL
        wret <- NULL
        ReturnsVec <- NULL
        
        get_summary_table <- function(symbol){
            
            url <- paste0("https://finance.yahoo.com/quote/",symbol)
            df <- url %>%
                read_html() %>%
                html_table(header = FALSE) %>%
                map_df(bind_cols) %>%
                as_tibble()
            
            names(df) <- c("name", "value")
            df["stock"] <- symbol
            
            df
        }
        
        for (i in tickersw){
            AdjustedPrices <- cbind(AdjustedPrices, 
                                    getSymbols.yahoo(i, from = "2019-01-01", to = Sys.Date(),             
                                                     periodicity = "weekly", auto.assign = F)[,6])  
            TargetPrice <- as.numeric(gsub(",","",unlist(get_summary_table(i)[16,2])))
            CurrentPrice <- as.numeric(gsub(",","",unlist(get_summary_table(i)[1,2])))
            yret <- (TargetPrice-CurrentPrice)/CurrentPrice 
            wret <- (1+yret)^(1/52) - 1
            ReturnsVec <- c(ReturnsVec, wret)
        }   
        
        Returnsw <- Return.calculate(AdjustedPrices, method = "discrete")
        Returnsw <- Returnsw[-1,] #Removes NA
        
        #Minimum Variance Portfolio
        sigma <- cov(Returnsw)
        weights_mv <- optimalPortfolio(Sigma = sigma, 
                                       control = list(type = "minvol", constraint = "lo"))
        
        #Efficient Frontier
        ret_min <- sum(ReturnsVec*weights_mv)
        ret_max <- max(ReturnsVec)
        ret_range <- seq(from = ret_min, to = ret_max, length.out = 30)
        
        vol <- rep(NA, 30)
        mu <- rep(NA,30)
        eweights <- matrix(NA, nrow = length(tickersw), ncol = 30)
        
        #Min Weights
        eweights[,1] <- weights_mv
        vol[1] <- sqrt(tcrossprod(crossprod(weights_mv, sigma), weights_mv))
        mu[1] <- ret_min
        
        #Max Weights
        max_ret_idx <- which(ReturnsVec == ret_max)
        w_maxret <- rep(0,length(tickersw))
        w_maxret[max_ret_idx] <- 1
        
        eweights[,30] <- w_maxret
        vol[30] <- apply(Returnsw,2,sd)[max_ret_idx]
        mu[30] <- ReturnsVec[max_ret_idx]
        
        #Rest of Weights
        for (i in 2:29){
            res <- solve.QP(Dmat = sigma, dvec = rep(0,length(tickersw)), Amat = cbind(matrix(rep(1,length(tickersw)), ncol=1), diag(length(tickersw)), matrix(ReturnsVec, ncol=1)), bvec = c(1,rep(0,length(tickersw)), ret_range[i]), meq = 1)
            w <- res$solution
            
            eweights[,i] <- w
            vol[i] <- sqrt(tcrossprod(crossprod(w,sigma),w))
            mu[i] <- sum(ReturnsVec*w)
        }
        
        #My Weights
        USDtoCAD <- getQuote("CAD=X", src = "yahoo")[2] #Convert USD to CAD
        USDtoCAD <- USDtoCAD[[1]] #List to Numeric
        
        #Select Last Prices (From Tickers)
        PortfolioPricesw <- NULL 
        tickersw <- toupper(tickersw) #CAPS
        for (i in tickersw){
            PortfolioPricesw <- cbind(PortfolioPricesw, getQuote(i, src = "yahoo")[,2])          
        }  
        
        #Convert USD Denominated Assets to CAD
        for (i in 1:length(PortfolioPricesw)){
            if(CountryVecw[i] == "United States"){
                PortfolioPricesw[i] <- USDtoCAD*PortfolioPricesw[i]
            }
        }
        
        #Find Weights
        MarketValuew <- SharesVecw*PortfolioPricesw
        Weightsw <- MarketValuew/sum(MarketValuew)
        Weightsw <- as.vector(Weightsw)
        
        MyMu <- sum(ReturnsVec*Weightsw)
        MyVol <- as.numeric(sqrt(tcrossprod(crossprod(Weightsw,sigma),Weightsw)))
        
        eweights <- round(eweights,2)
        eweights <- t(eweights)
        colnames(eweights) <- gsub(".Adjusted", "", colnames(sigma))
        eweights <- abs(eweights[c(1,5,8,12,16,19,23,26,30),])
        
        MYPLOT <- ggplot(as.data.frame(cbind(vol,mu)), aes(vol, mu)) +
            geom_line() +
            geom_point(aes(MyVol,MyMu, colour = "My Portfolio"), 
                       shape = 18, 
                       size = 3) +
            ggtitle("Efficient Frontier") +
            xlab("Volatility (Weekly)") +
            ylab("Expected Returns (Weekly)") +
            theme(plot.title = element_text(size=14, face="bold.italic", hjust = 0.5, margin=margin(0,0,15,0)),
                  axis.title.x = element_text(size = 10, margin=margin(15,0,0,0)),
                  axis.title.y = element_text(size = 10, margin=margin(0,15,0,0)),
                  panel.border = element_rect(colour = "black", fill=NA, size=1),
                  legend.position = c(0.92,0.06),
                  legend.title = element_blank(),
                  legend.text = element_text(size=8),
                  legend.background = element_rect(color = "black"),
                  legend.key=element_blank())
        
        return(list(MYPLOT, eweights))
    }
    
    #Monte Carlo Function
    Run3 <- function(tickersw, SharesVecw, CountryVecw){
        
        AdjustedPrices <- NULL
        TargetPrice <- NULL
        CurrentPrice <- NULL
        yret <- NULL
        wret <- NULL
        ReturnsVec <- NULL
        
        get_summary_table <- function(symbol){
            
            url <- paste0("https://finance.yahoo.com/quote/",symbol)
            df <- url %>%
                read_html() %>%
                html_table(header = FALSE) %>%
                map_df(bind_cols) %>%
                as_tibble()
            
            names(df) <- c("name", "value")
            df["stock"] <- symbol
            
            df
        }
        
        for (i in tickersw){
            AdjustedPrices <- cbind(AdjustedPrices, 
                                    getSymbols.yahoo(i, from = "2019-01-01", to = Sys.Date(),             
                                                     periodicity = "weekly", auto.assign = F)[,6])  
            TargetPrice <- as.numeric(gsub(",","",unlist(get_summary_table(i)[16,2])))
            CurrentPrice <- as.numeric(gsub(",","",unlist(get_summary_table(i)[1,2])))
            yret <- (TargetPrice-CurrentPrice)/CurrentPrice 
            wret <- (1+yret)^(1/52) - 1
            ReturnsVec <- c(ReturnsVec, wret)
        }   
        
        Returnsw <- Return.calculate(AdjustedPrices, method = "discrete")
        Returnsw <- Returnsw[-1,] #Removes NA
        
        #Minimum Variance Portfolio
        sigma <- cov(Returnsw)
        weights_mv <- optimalPortfolio(Sigma = sigma, 
                                       control = list(type = "minvol", constraint = "lo"))
        
        #Efficient Frontier
        ret_min <- sum(ReturnsVec*weights_mv)
        ret_max <- max(ReturnsVec)
        ret_range <- seq(from = ret_min, to = ret_max, length.out = 30)
        
        vol <- rep(NA, 30)
        mu <- rep(NA,30)
        eweights <- matrix(NA, nrow = length(tickersw), ncol = 30)
        
        #Min Weights
        eweights[,1] <- weights_mv
        vol[1] <- sqrt(tcrossprod(crossprod(weights_mv, sigma), weights_mv))
        mu[1] <- ret_min
        
        #Max Weights
        max_ret_idx <- which(ReturnsVec == ret_max)
        w_maxret <- rep(0,length(tickersw))
        w_maxret[max_ret_idx] <- 1
        
        eweights[,30] <- w_maxret
        vol[30] <- apply(Returnsw,2,sd)[max_ret_idx]
        mu[30] <- ReturnsVec[max_ret_idx]
        
        #Rest of Weights
        for (i in 2:29){
            res <- solve.QP(Dmat = sigma, dvec = rep(0,length(tickersw)), Amat = cbind(matrix(rep(1,length(tickersw)), ncol=1), diag(length(tickersw)), matrix(ReturnsVec, ncol=1)), bvec = c(1,rep(0,length(tickersw)), ret_range[i]), meq = 1)
            w <- res$solution
            
            eweights[,i] <- w
            vol[i] <- sqrt(tcrossprod(crossprod(w,sigma),w))
            mu[i] <- sum(ReturnsVec*w)
        }
        
        #Monte Carlo
        W_Vec <- matrix(NA, nrow = length(tickersw), ncol = 1000)
        VOL <- rep(NA, 1000)
        MU <- rep(NA,1000)
        
        for (i in 1:1000){
            W_Vec[,i] <- runif(length(tickersw)) #Generate 4 random numbers [0,1]
            W_Vec[,i] <- W_Vec[,i]/sum(W_Vec[,i]) #Sum of Weights = 1
            MU[i] <- sum(ReturnsVec*W_Vec[,i])
            VOL[i] <- sqrt(tcrossprod(crossprod(W_Vec[,i],sigma),W_Vec[,i]))
        }
        
        #My Weights
        USDtoCAD <- getQuote("CAD=X", src = "yahoo")[2] #Convert USD to CAD
        USDtoCAD <- USDtoCAD[[1]] #List to Numeric
        
        #Select Last Prices (From Tickers)
        PortfolioPricesw <- NULL 
        tickersw <- toupper(tickersw) #CAPS
        for (i in tickersw){
            PortfolioPricesw <- cbind(PortfolioPricesw, getQuote(i, src = "yahoo")[,2])          
        }  
        
        #Convert USD Denominated Assets to CAD
        for (i in 1:length(PortfolioPricesw)){
            if(CountryVecw[i] == "United States"){
                PortfolioPricesw[i] <- USDtoCAD*PortfolioPricesw[i]
            }
        }
        
        #Find Weights
        MarketValuew <- SharesVecw*PortfolioPricesw
        Weightsw <- MarketValuew/sum(MarketValuew)
        Weightsw <- as.vector(Weightsw)
        
        MyMu <- sum(ReturnsVec*Weightsw)
        MyVol <- as.numeric(sqrt(tcrossprod(crossprod(Weightsw,sigma),Weightsw)))
        
        eweights <- round(eweights,2)
        eweights <- t(eweights)
        colnames(eweights) <- gsub(".Adjusted", "", colnames(sigma))
        eweights <- abs(eweights[c(1,5,8,12,16,19,23,26,30),])
        
        MYPLOT <- ggplot(as.data.frame(cbind(VOL,MU)), aes(VOL, MU)) +
            geom_point(shape = 1) +
            geom_point(aes(MyVol,MyMu, colour = "My Portfolio"), 
                       shape = 18, 
                       size = 3) +
            geom_line(data=data.frame(vol,mu), mapping=aes(vol, mu)) +
            ggtitle("Efficient Frontier") +
            xlab("Volatility (Weekly)") +
            ylab("Expected Returns (Weekly)") +
            theme(plot.title = element_text(size=14, face="bold.italic", hjust = 0.5, margin=margin(0,0,15,0)),
                  axis.title.x = element_text(size = 10, margin=margin(15,0,0,0)),
                  axis.title.y = element_text(size = 10, margin=margin(0,15,0,0)),
                  panel.border = element_rect(colour = "black", fill=NA, size=1),
                  legend.position = c(0.92,0.06),
                  legend.title = element_blank(),
                  legend.text = element_text(size=8),
                  legend.background = element_rect(color = "black"),
                  legend.key=element_blank())
        
        return(list(MYPLOT, eweights))
    }
    
    #Monte Carlo and EF Function
    Run4 <- function(tickersw, SharesVecw, CountryVecw){
        Run3(tickersw, SharesVecw, CountryVecw)
    }
})

shinyApp (ui = ui, server = server)



filtering using checkboxes in react typescript using react hooks

I am trying to filter the data I created by specific string word. I am making an event based app and want to filter data using checkbox based on location. Location is either "Online" or specific place (random name).

My if function goes directly to "else" statement (I get console.log test2). It also only gives me that console log if I click on "Online" checkbox. When I click on "Onsite" checkbox nothing registers at all. I am not sure what am I doing wrong.

I am also not sure what condition to use to get onsite data filtered since all places have different names.

This is first time I am encountering with React TypeScript combination and I am getting a lot of hiccups along the way.

Here is the code from ResultFilter.ts file:

import { useState } from 'react'
import '../App.css'
//import { EventActivity } from '../model/Event'

/* 
interface Props {
    activity: EventActivity
  } */

const ResultFilter = (EventActivity: { location: string }) => {

    // const [filtered, setFiltered] = useState(String)

    const [Checked, setChecked] = useState<any[]>([])

    const handleCheckboxChange = () => {
        console.log('test');
        
        const PATTERN = 'Online'

         if (EventActivity.location === PATTERN) {

             const filteredData = Checked.filter((str)=>{
                 return str.toLowerCase().includes(PATTERN)
             });
             console.log(filteredData);
             console.log('filtered data')
             
            setChecked(filteredData)

        } else  {
            console.log('test2');            
            
        }
    }

    return (
        <div className="filter-container">
            <div className="filter-wrapper">
                <div className="checkbox">
                    <label>
                        <input
                            type="checkbox"                             
                            onChange={()=>handleCheckboxChange}
                            
                        />
                        <span>Onsite</span>
                    </label>

                    <label>
                        <input
                            type="checkbox"
                        /* checked={checked} */
                        onChange={handleCheckboxChange}
                        />
                        <span>Online</span>
                    </label>
                </div>

            </div>
        </div>
    )
}
export default ResultFilter

This is model Event.tsx:

export interface EventActivity {
    id: number
    title: string 
    description: string
    imgUrl: string 
    date: string
    location: string     
  }

This is CardGrid.tsx file which displays all events where ResultFilter.tsx is displayed:

import FrontCard from "./FrontCard"
import { EventActivity } from '../model/Event'
import ResultFilter from "./ResultFilter"

const data: EventActivity[] = [
  {
    id: 1,
    title: 'Yoga',
    description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.',
    imgUrl: 'https://images.unsplash.com/photo-1588286840104-8957b019727f?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80',
    date: "Mon,FEB 1 @1:00 AM CET",
    location: 'Kellers Park'
  },
  {
    id: 2,
    title: 'Hiking',
    description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.',
    imgUrl: 'https://images.unsplash.com/photo-1551632811-561732d1e306?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80',
    date: "Wed,MAR 5 @12:00 AM CET",
    location: 'Delsjön'
  },
  {
    id: 3,
    title: 'Photography',
    description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.',
    imgUrl: 'https://images.unsplash.com/photo-1554048612-b6a482bc67e5?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80',
    date: "Mon,FEB 12 @9:00 AM CET",
    location: 'Brunnsparken'
  },
  {
    id: 4,
    title: 'Connect!',
    description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.',
    imgUrl: 'https://images.unsplash.com/photo-1539635278303-d4002c07eae3?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80',
    date: "Fri,APR 3 @5:00 PM CET",
    location: 'Gothenburg'
  },
  {
    id: 5,
    title: 'Gamers unite!',
    description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.',
    imgUrl: 'https://images.unsplash.com/photo-1544652478-6653e09f18a2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80',
    date: "Mon,DEC 1 @1:00 AM CET",
    location: 'Online'
  },
  {
    id: 6,
    title: 'Book Club',
    description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.',
    imgUrl: 'https://images.unsplash.com/photo-1513475382585-d06e58bcb0e0?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80',
    date: "Sun,NOV 1 @2:00 PM CET",
    location: 'Online'
  },
]

interface Props {
  searchString: string
}

const CardGrid = ({ searchString }: Props) => {
  const filteredData = data.filter(activity => activity.title.toLowerCase().includes(searchString.toLowerCase()))

  return (

    <>
      <h4 className="events-title" >Events</h4>


      <section data-testid="filter-events" className="filter-events">
        
          <ResultFilter location={""} />
        
    </section>


      <section data-testid="all-events" className="card-grid">
        {filteredData.map(activity => (
          <FrontCard key={activity.id} activity={activity} />
        ))}
      </section>
    </>
  )
}

export default CardGrid



samedi 22 janvier 2022

How to activate the checkboxes saved in the database when I close and reopen the window?

I have a code where if you select/activate a checkbox, its value will be saved in the database as active or inactive (0 or 1). If you close and reopen the window, all active/selected checkboxes are shown even when they shouldn't.

enter image description here

PROBLEM: The problem lies in the upload function. It is wrong. The very logic of the code is wrong. It is useless to identify errors, it should be rewritten from scratch. I have no idea how to write it. For example, if I activate / select only one checkbox and save, then if I close and reopen the window, all checkboxes will be automatically activated.

WHAT DO I WANT? I would like that when I close and open the window, only the checkboxes that I have previously selected/activated are activated. For example, if I activate only Checkbox 1 and then I save, then subsequently when I close and open the window I would like to see only checkbox1 activated (not both).

import sqlite3
import tkinter as tk
from tkinter import ttk
from tkinter import *
from tkinter import messagebox
import tkinter.messagebox

root = tk.Tk()
root.geometry("200x200")
root.configure(bg='white')

Checkbutton1 = IntVar() 
Checkbutton2 = IntVar() 
         
Button1 = Checkbutton(root, text = "Checkbutton1", variable = Checkbutton1, onvalue = 1, offvalue = 0, height = 1,
                            bg="white", foreground='black', activebackground="white")
Button1.place(x=10, y=26)
            
Button2 = Checkbutton(root, text = "Checkbutton2", variable = Checkbutton2, onvalue = 1, offvalue = 0, height = 1, 
                            bg="white", foreground='black', activebackground="white")
Button2.place(x=10, y=46)
                        
def save():
    value_Button1 = Checkbutton1.get()
    value_Button2 = Checkbutton2.get()

    conn = sqlite3.connect("...")
    c = conn.cursor()
    c.execute('SELECT button1 button2 FROM example WHERE id=1')
    rec = c.fetchall()

    if rec:
        c.execute("UPDATE example SET Button1=?, Button2=? WHERE id=1;", ((value_Button1), (value_Button2),))
    else:
        c.execute("INSERT INTO example VALUES (1,?,?);", ((value_Button1), (value_Button2),))
                    
        conn.commit()
        conn.close()
                
        messagebox.showinfo("Saved successfully","Saved successfully")
  
def load():
    conn = sqlite3.connect("...")
    c = conn.cursor()
    c.execute("SELECT * FROM example")
    val = c.fetchone()[0]
    conn.close()

    Checkbutton1.set(val)
    Checkbutton2.set(val)


load()
                    

save = Button(root, text="save", bg='#b40909', foreground='white', command= save)
save.pack()
save.place(x=10, y=90)

root.mainloop()

Example database

CREATE TABLE "example" (
    "id"    INTEGER,
    "Button1"   INTEGER,
    "Button2"   INTEGER,
    PRIMARY KEY("id" AUTOINCREMENT)
);



How to view saved checkboxes? They are all displayed as selected, i cannot choose them individually (executable example)

I have code with executable example where the selection (0 or 1) of a combobox is saved in the database. If I open and close the window, the checkboxes are displayed as all selected, but I would like to display only those selected individually previously.

For example on 2 checkboxes, I would like to select only 1. Later when I close and open the window, I would like to see only 1 checkbox selected and not all. How can I solve?

import sqlite3
import tkinter as tk
from tkinter import ttk
from tkinter import *
from tkinter import messagebox
import tkinter.messagebox

root = tk.Tk()
root.geometry("200x200")
root.configure(bg='white')

Checkbutton1 = IntVar() 
Checkbutton2 = IntVar() 
Checkbutton3 = IntVar() 

            
Button1 = Checkbutton(root, text = "Checkbutton1", variable = Checkbutton1, onvalue = 1, offvalue = 0, height = 1,
                            bg="white", foreground='black', activebackground="white")
Button1.place(x=10, y=26)
            
Button2 = Checkbutton(root, text = "Checkbutton2", variable = Checkbutton2, onvalue = 1, offvalue = 0, height = 1, 
                            bg="white", foreground='black', activebackground="white")
Button2.place(x=10, y=46)
                        
def save():
    value_Button1 = Checkbutton1.get()
    value_Button2 = Checkbutton2.get()

    conn = sqlite3.connect("...")
    c = conn.cursor()
    c.execute('SELECT button1 button2 FROM example WHERE id=1')
    rec = c.fetchall()

    if rec:
        c.execute("UPDATE example SET Button1=?, Button2=? WHERE id=1;", ((value_Button1), (value_Button1),))
    else:
        c.execute("INSERT INTO example VALUES (1,?,?);", ((value_Button1), (value_Button1),))
                    
        conn.commit()
        conn.close()
                
        messagebox.showinfo("Saved successfully","Saved successfully")



def load():
    conn = sqlite3.connect("...")
    c = conn.cursor()
    c.execute("SELECT button1 FROM example")
    val = c.fetchone()[0]
    conn.close()

    Checkbutton1.set(val)
    Checkbutton2.set(val)


load()
                    

save = Button(root, text="save", bg='#b40909', foreground='white', command= save)
save.pack()
save.place(x=10, y=90)

root.mainloop()

Example database

CREATE TABLE "example" (
    "id"    INTEGER,
    "Button1"   INTEGER,
    "Button2"   INTEGER,
    PRIMARY KEY("id" AUTOINCREMENT)
);



In Google Sheets, how can I copy a row based on a specific column value into a new tab, and then append checkboxes to the row?

I'm trying to write a script which would allow me to copy a row into a new tab based on a specific cell value. In this case, it is a checkbox of being set to TRUE.

I have no issue with copying the row to a new sheet based on the cell value, but now I'm unsure as to how I can use insertCheckboxes to append 5 checkboxes to the copied row in the new sheet.

This is the code I have at the moment:

function onEdit(event) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = event.source.getActiveSheet();
  var r = event.source.getActiveRange();

  if(s.getName() == "Client Database" && r.getColumn() == 9 && r.getValue() == true) {
    var row = r.getRow();
    var numColumns = s.getLastColumn();
    var targetSheet = ss.getSheetByName("Referrals");
    var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
    s.getRange(row, 1, 1, numColumns).copyTo(target);
}
}

Column 9 contains checkboxes which when set to true, copies the row from "Client Database" into my new tab ("Referrals").

I'm scratching my head over two things:

  • What do I need to change in the code to only copy columns 1 and 4 from the original sheet? (as it is currently copying all columns from the row).
  • Unless there is an easier workaround, how can I append checkboxes into the adjacent columns within the new sheet using insertCheckboxes? (Illustration below). This is simply to avoid having to manually insert the boxes each time (as I will not be the one using the sheet)

Any advice is greatly appreciated.

Illustration




Not able to reatain the position of CheckBox state in Viusalforce Page

Please Review my Code:: I have Created a Custom Component In which I have Created Check-boxes in from from each record and Now I want to retain there position but it is not happening as well my wrapper is fine can anybody please tell me what is the mistake.

.................................................

public class PaginationCompController {
public List<String> selectedFields{get;set;}
public String selectedObject{get;set;}
public String query{get;set;}
Public ApexPages.StandardSetController ssc{get;set;} 
public List<sObject> allRecords{get;set;}
public Integer Size{get;set;}
public Integer pageNumber{get;set;}
public ID recId{get;set;}
public List<WrapperClass> listOfWrapper{get;set;}
//This method will called only once autmatically by the actionfuntion component and Initialize the ssc by the query
public void show(){
    //get the query in the form of the String     
        //automatically Called By Action
        allRecords();
    
}
 

//This method will return the list of all Records
public List<sObject> allRecords(){
    allRecords = ssc.getRecords();
    System.debug('this called' + allrecords);
    pageNumber = ssc.getPageNumber();
    recordsInWrapper();
    return allRecords;      
}

/*============================================    Methods for Pagination   =============================================*/
public void first(){
    ssc.first();
    allRecords();
}
public void next(){
   
    ssc.next();
    allRecords(); 
}

public void previous(){
    ssc.previous();
    allRecords();
}
public void last(){
    ssc.last();
    allRecords();
}

public void pageSize(){
    ssc.setPageSize(size);
    allRecords();
}

public void finalPageNumber(){
    ssc.setPageNumber(pageNumber);
    allRecords();
}


/*==============================================MAINTAIN THE CHECKBOXES ===============================================*/
public Map<Id,sObject> mapOfSelectedRecords;
public void selectedRecords(){   
    mapOfSelectedRecords = new Map<Id,sObject>();
    if(listOfWrapper!=null){
        for(WrapperClass ob : listOfWrapper){
            if(ob.isSelected == true){
                //putting all the checked records to the Map
                mapOfSelectedRecords.put(ob.obj.id, ob.obj);
            }
            else{
                //Remove funtion is used to remove the all the Records which first selected and later deselected
                mapOfSelectedRecords.remove(ob.obj.id);
            }
        }
    }
    System.debug('The map of selected records is ' + mapOfSelectedRecords);
}
/*============================================================= WRAPPPER CLASS =============================================================================*/    
public class WrapperClass{
    public Boolean isSelected {get;set;}
    public sObject obj {get;set;}  
    public WrapperClass(sObject obj,Boolean isSelected)
    { 
        this.isSelected = isSelected;
        this.obj = obj;
    }
}

public List<WrapperClass> recordsInWrapper(){
    selectedRecords();
    System.debug('Inside the records in Wrapper Methods The Map of selected Records is : ' + mapOfSelectedRecords);
    listOfWrapper = new List<WrapperClass>();
    System.debug('The wrapper data is ' +listOfWrapper );
    System.debug('The all Records are ::::: ' + allRecords);
    for(sObject sObj : allRecords){
        if(mapOfSelectedRecords.containsKey(sobj.id)){
            System.debug('Key is Present');
            listOfWrapper.add(new WrapperClass(sObj,true));
        }
        else{
             System.debug('Key is Not Present');
        listOfWrapper.add(new WrapperClass(sObj,false));
        }
    }
    System.debug('The wrapper data is ' +listOfWrapper );
    // System.debug('The Checked wrapper data is ' +asRecordsList );
    return listOfWrapper;
}  

}