jeudi 31 août 2023

How to make checkbox in pytelegrammbot, using a data from list

I'm working on a telegramm bot, and during one process, I get a JSON data consisting of several items with 2 fields, and I need to make so, that after pressing button, data converts in checkbox and user can choose, which item do they have, and then I need to process those chosen items to server via POST, but I'm stuck on converting data and showing it to the user. Data is stored in form of list, consisting of dictionary with fields "Name" and "ID"

I've tried this code, but it's 100% incorrect (since it not working), and I'm currently lacking knowledge on this matter, and having trouble with documentation. All this goes after pressing a button, sure that all correct and working before this part

res = requests.get(url=URL3, auth=auth, params={'login': user_login})
data = json.loads(res.content)
results = []  
for item in data["Description"]:
    result = {}
    for key in ["Asset", "InventoryNumber"]:
        result[key] = item[key]
        results.append(result)  
markup = types.InlineKeyboardMarkup(row_width=len(results))
for i, result in enumerate(results):
    checkbox = types.InlineKeyboardButton(f"Name: {result['Asset']}\nID: {result['InventoryNumber']}",
                                          callback_data=f"choice_{i}")
    markup.add(checkbox)
msg = bot.send_message(call.message.chat.id, text='Choose needed assets', reply_markup=markup)
threading.Thread(target=func_del_mess, args=(msg.chat.id, msg.message_id,)).start()




mercredi 30 août 2023

How to modify the following shiny code to obtain row indexes selected by checkbox?

I am interested to have a data table as following in my shiny App. After I select the rows using the check boxes, I would like to continue working on the selected data. The problem now is I don't know how to get the index of the selected rows from this example. Can you please help? Thank you very much!

How do I make persistent checkboxes with DT::datatable in Shiny?

I think it has to do with the callback function. But I couldn't figure it out.




How can I resolve this Error inflating class CheckBox

Due to the fact that import kotlinx.android.synthetic.main is stuck when uploading the sdk to the project, I have been trying to do the migration but I can't get it to work. I have seen the viewbinding examples but I also see that it is in fragments and activities. I don't know if it doesn't work because I am using a :Dialog. What I have done is the following

class FragmentPruebaBinding(var activity: Activity, internal var adapter: AdapterPrueba) : Dialog(activity, R.style.AlertDialogStyle){
   var dialog: Dialog? = null

 override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.fragment_prueba)

        val activity: MainActivity = activity as MainActivity

        val Nombre: TextView = findViewById(R.id.Nombre)
        val check: CheckBox =findViewById(R.id.check)
        val btn_aceptar: Button = findViewById(R.id.btn_aceptar)
        val btn_cancelar: Button = findViewById(R.id.btn_cancelar)
        val nom: String = MainActivity.dataIdentities.activeIdent.name!! + " " + MainActivity.dataIdentities.activeIdent.snam!! + " " + MainActivity.dataIdentities.activeIdent.snam2
        Nombre.text =  nom
        check.setOnClickListener {
            adapter.setEnableAseg(!check.isChecked)
            adapter.notifyDataSetChanged()
        }
. . . 
}

the xml would look like this:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FragmentPruebaBinding">

    <LinearLayout
        android:id="@+id/LinearA"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:orientation="vertical"
        tools:ignore="MissingConstraints">

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="170dp"
            android:fontFamily="@font/roboto"
            app:cardBackgroundColor="@color/color_background_cardview_seleccion_prueba"
            app:cardCornerRadius="18dp"
            app:cardElevation="5dp"
            app:cardPreventCornerOverlap="true"
            app:cardUseCompatPadding="true">

            <TextView
                android:id="@+id/Nombre"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="28dp"
                android:layout_marginTop="20dp"
                android:background="@color/color_background_cardview_seleccion_prueba"
                android:fontFamily="@font/roboto"
                android:textColor="@color/color_nombre"
                android:textSize="22sp"
                app:layout_constraintTop_toBottomOf="@id/header" />

            <TextView
                android:id="@+id/header"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="28dp"
                android:layout_marginTop="60dp"
                android:background="@color/color_background_cardview_seleccion_prueba"
                android:text="@string/header"
                android:textColor="@color/color_nombre"
                android:textSize="15sp" />


            <CheckBox
                android:id="@+id/check"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="20dp"
                android:layout_marginTop="90dp"
                android:fontFamily="@font/roboto"
                android:paddingStart="5dp"
                android:paddingEnd="0dp"
                android:text="@string/check_text"
                android:textColor="@color/color_letra_seleccion_prueba"
                android:textSize="16sp"
                app:buttonTint="@color/color_checkox_checked"
                app:layout_constraintTop_toBottomOf="@id/Nombre" />
        </androidx.cardview.widget.CardView>

    </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/white"
        app:layout_constraintBottom_toTopOf="@+id/btns_pruebas"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/LinearA" />

    <LinearLayout
        android:id="@+id/btns_pruebas"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <Button
            android:id="@+id/btn_cancelar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:backgroundTint="@color/cancel_button"
            android:fontFamily="@font/roboto"
            android:insetTop="0dp"
            android:insetBottom="0dp"
            android:text="@string/cancel"
            android:textSize="14sp"
            app:cornerRadius="0dp"
            app:strokeColor="@color/color_datos_02"
            app:strokeWidth="0.2dp" />

        <Button
            android:id="@+id/btn_aceptar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:backgroundTint="@color/accept_button"
            android:fontFamily="@font/roboto"
            android:insetTop="0dp"
            android:insetBottom="0dp"
            android:text="@string/aceptar"
            android:textSize="14sp"
            app:cornerRadius="0dp"
            app:strokeColor="@color/color_datos_02"
            app:strokeWidth="0.1dp" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

but I get the following error:

 android.view.InflateException: Binary XML file line #64 in ***:layout/fragment_prueba: Binary XML file line #64 in ***:layout/fragment_prueba: Error inflating class CheckBox
                                                                                                    Caused by: android.view.InflateException: Binary XML file line #64 in ***:layout/fragment_prueba: Error inflating class CheckBox
                                                                                                    Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 6: TypedValue{t=0x2/d=0x101009b a=1}, theme={InheritanceMap=[id=0x7f150003***:style/AlertDialogStyle, id=0x7f150127***:style/FioriAlertDialogStyle, id=0x7f1503d1***:style/ThemeOverlay.MaterialComponents.MaterialAlertDialog, id=0x7f150086***:style/Base.ThemeOverlay.MaterialComponents.MaterialAlertDialog, id=0x7f15009a***:style/Base.V14.ThemeOverlay.MaterialComponents.MaterialAlertDialog, id=0x7f150375***:style/ThemeOverlay.AppCompat.Dialog.Alert, id=0x7f15007c***:style/Base.ThemeOverlay.AppCompat.Dialog.Alert, id=0x7f15007b***:style/Base.ThemeOverlay.AppCompat.Dialog, id=0x7f1500a4***:style/Base.V21.ThemeOverlay.AppCompat.Dialog, id=0x7f1500b8***:style/Base.V7.ThemeOverlay.AppCompat.Dialog, id=0x7f150077***:style/Base.ThemeOverlay.AppCompat, id=0x7f1501c1***:style/Platform.ThemeOverlay.AppCompat], Themes=[***:style/AlertDialogStyle, forced, ***:style/AppTheme.NoActionBar, forced, ***:style/Theme.AppCompat.Empty, forced, android:style/Theme.DeviceDefault.Light.DarkActionBar, forced]}
                                                                                                        at android.content.res.TypedArray.getColorStateList(TypedArray.java:600)
                                                                                                        at android.widget.TextView.readTextAppearance(TextView.java:4129)
                                                                                                        at android.widget.TextView.<init>(TextView.java:1128)
                                                                                                        at android.widget.Button.<init>(Button.java:166)
                                                                                                        at android.widget.CompoundButton.<init>(CompoundButton.java:104)
                                                                                                        at android.widget.CheckBox.<init>(CheckBox.java:71)
                                                                                                        at android.widget.CheckBox.<init>(CheckBox.java:67)
                                                                                                        at androidx.appcompat.widget.AppCompatCheckBox.<init>(AppCompatCheckBox.java:79)
                                                                                                        at com.google.android.material.checkbox.MaterialCheckBox.<init>(MaterialCheckBox.java:231)
                                                                                                        at com.google.android.material.checkbox.MaterialCheckBox.<init>(MaterialCheckBox.java:227)
                                                                                                        at com.google.android.material.theme.MaterialComponentsViewInflater.createCheckBox(MaterialComponentsViewInflater.java:49)
                                                                                                        at androidx.appcompat.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:145)
                                                                                                        at androidx.appcompat.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1569)
                                                                                                        at androidx.appcompat.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1620)
                                                                                                        at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1065)
                                                                                                        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1001)
                                                                                                        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:965)
                                                                                                        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1127)
                                                                                                        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1088)
                                                                                                        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1130)
                                                                                                        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1088)
                                                                                                        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1130)
                                                                                                        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1088)
                                                                                                        at android.view.LayoutInflater.inflate(LayoutInflater.java:686)
                                                                                                        at android.view.LayoutInflater.inflate(LayoutInflater.java:538)
                                                                                                        at android.view.LayoutInflater.inflate(LayoutInflater.java:485)
                                                                                                        at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:469)
                                                                                                        at android.app.Dialog.setContentView(Dialog.java:597)
                                                                                                        at ***.FragmentPruebaBinding.onCreate(FragmentPruebaBinding.kt:39)

the line 39 is:

setContentView(R.layout.fragment_aseguradora)

I tried this tutorial but to no avail either. I don't know what I'm missing https://developer.android.com/topic/libraries/view-binding/migration

Thanks for any help.




mardi 29 août 2023

Livewire 3 - Checkbox do not checked

I am doing a website and I'm on the new version of livewire 3, I am trying to do a checkbox All, but the problem is the value is on my tab but the checkbox dont want to checked: Checkbox do not checked

If someone can help me !

The view: first checkbox:

Code of the main checkbox

Both other: Other's checkbox code

Component:

Property

Function

We can see the id's on the array, but the checkbox dont check, and i already try to convert int in string but nothing happen: When i checked the main checkbox And if i checked the 2 down checkbox: When i checked the main and both other's

I guess the problem come from when i checked one of the 2 checkbox the function is called but should not.

If i look in the network, I don't see any update about my selected property: Network screen




lundi 28 août 2023

Extjs 4.2 grid Checkbox column not rendering checked when data from store is true

I have a data grid using Extjs 4.2 that has a checkbox coulmn with a data index = inactive. How can I get the checkbox to render as checked

Here is my data grid: { xtype: 'panel', title: 'Pricing', items: [ { xtype: 'gridpanel', height: 900, id: 'costGrid', title: 'Pricing', columnLines: true, store: 'CostStore', columns: [ { xtype: 'gridcolumn', hidden: true, dataIndex: 'id', text: 'Id' }, { xtype: 'gridcolumn', align: 'center', dataIndex: 'product', text: 'Product' }, { xtype: 'gridcolumn', renderer: function(value, metaData, record, rowIndex, colIndex, store, view) { return '<img src="' + '../' + value + '"width="100" height="100">' + "\n\r" + ' ' + record.data.description + ''; }, width: 371, align: 'center', dataIndex: 'imgSrc', text: 'ImgSrc' }, { xtype: 'gridcolumn', hidden: true, width: 272, dataIndex: 'description', text: 'Description' }, { xtype: 'gridcolumn', width: 154, align: 'center', dataIndex: 'resource', text: 'Resource' }, { xtype: 'gridcolumn', width: 88, align: 'center', dataIndex: 'cost', text: 'Cost', editor: { xtype: 'numberfield', selectOnFocus: true, allowExponential: false } }, { xtype: 'numbercolumn', width: 79, align: 'center', dataIndex: 'mfgCost', text: 'Mfg Cost', editor: { xtype: 'numberfield' } }, { xtype: 'numbercolumn', align: 'center', dataIndex: 'multiplier', text: 'Multiplier', editor: { xtype: 'numberfield' } }, { xtype: 'numbercolumn', align: 'center', dataIndex: 'flatRate', text: 'Flat Rate', editor: { xtype: 'numberfield' } }, { xtype: 'checkcolumn', dataIndex: 'inactive', text: 'Inactive', editor: { xtype: 'checkboxfield' } } ], plugins: [ Ext.create('Ext.grid.plugin.RowEditing', { pluginId: 'costPlugin', clicksToEdit: 1, listeners: { validateedit: { fn: me.onRowEditingValidateedit, scope: me } } }) ], dockedItems: [ { xtype: 'toolbar', dock: 'top', height: 79, width: 776, items: [ { xtype: 'combobox', id: 'productCombo', itemId: 'productCombo', padding: '10 10 10 10', fieldLabel: 'Product', labelWidth: 40, emptyText: '', editable: false, displayField: 'product', store: 'ProductStore', valueField: 'product', listeners: { change: { fn: me.onComboboxChange, scope: me } } }, { xtype: 'combobox', id: 'resourceCombo', itemId: 'resourceCombo', fieldLabel: 'Resource', labelWidth: 50, emptyText: '', editable: false, displayField: 'resource', store: 'ResourceStore', valueField: 'resource', listeners: { change: { fn: me.onResourceComboChange, scope: me } } }, { xtype: 'checkboxfield', padding: 20, width: 200, labelAlign: 'right', boxLabel: 'Check/Uncheck All', boxLabelAlign: 'before', listeners: { change: { fn: me.onCheckboxfieldChange, scope: me } } } ] } ], selModel: Ext.create('Ext.selection.CheckboxModel', { mode: 'SINGLE', showHeaderCheckbox: false }) } ] }

Here is the response from the store get request

[{"id":"1","product":"Casket","imgSrc":"./files/parag/thumb/Princeton_cjb_tn.jpg","description":"Princeton Solid Mahogany","resource":"Paragon","cost":"19500.00","mfgCost":"13000.00","multiplier":"1.50","flatRate":null,"inactive":"1"},

I tried an event change on the checkbox to no avail. Please if someone can send me down the right path I would greatly appreciate it.




samedi 26 août 2023

Add attribute to checkbox so it can fire button click event

I have a button on my page which is a trigger for an update panel. The page does not refresh and all the variables on the page (sender) go into the btncalcsave_click event just fine. Instead of having to check a checkbox and click the button that is wired to the click event, I want to be able to just click the checkbox and btncalcsave_click will fire as when I click the button. How is this achieved?

I tried to add a trigger to the update template (cbbiweekly) which is the id of the checkbox but this doesn't work. Does the checkbox need to have an Onclick attribute added to it in order for this to work? I am unclear how to get this working.

<asp:CheckBox ID="cbbiweekly" runat="server" Text="Bi-Weekly Pmt Schedule" Font-Size="x-Small"  OnClientClick="btncalcsave_Click" />

<asp:UpdatePanel ID="udppmtschedule" runat="server" UpdateMode="Conditional">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="btncalcsave" />
            <asp:AsyncPostBackTrigger ControlID="cbbiweekly" />
        </Triggers>
        <ContentTemplate>
            <table width="450px">



Table with checkboxes losing its checked state on a page scroll (no lazy-loading or virtual scrolling is implemented) in react js

I have a table in react js which has a column of checkboxes. On clicking the table header's checkbox, all of the children / table-row checkboxes gets checked. But when the table or page is scrolled. The checkboxes present in table row gets unchecked automatically, that is, the checked value is turning from true to false. Below is the code:

<table className="table">
 <tbody>
  <tr>
   <td className="cell">
     <span className="select-all">
      <input onChange={selectAllClicked} type="checkbox" value="24">
     <span/>
   <td/>
  <tr/>
  <tr>
   <td className="cell">
     <span className="child-input">
      <input type="checkbox" value="24">
     <span/>
   <td/>
  <tr/>
  <tr>
   <td className="cell">
     <span className="child-input">
      <input type="checkbox" value="24">
     <span/>
   <td/>
  <tr/>
<tbody/>

Below is the event handler used:

function selectAllClicked() {
  $("span.child-input input").prop("checked", $(".select-all input").is(":checked"));
}

It would be really helpful if someone helps me in resolving this issue.




List of checkbox in flutter using bloc [duplicate]

I'm beginner to flutter bloc .

I want to implement list of checkbox in flutter using bloc . I have seen a code snippet of single checkbox implementation. I need list of checkbox.

is there any documentation available?

and how to pass my list to my cubit.

I have seen a code snippet of single checkbox implementation. I need list of checkbox.




vendredi 25 août 2023

JavaFX Box of CheckBox Align Right

I want to align the .box portion of a CheckBox to the right. It is graphic only, so there is no text. Here's a picture where I set the .check-box to have a light blue background, so I can see the entire width of the Control.

CheckBoxScreenshot

No matter what I try, including -fx-alignment: center-right, -fx-text-align: right, or even changing the alignment of the HBox it's contained in to right, will change it.

How can I fix this?




How to keep state of a checkbox?

I have a list of users in 3 different groups(Group A, Group B, and Group C) that I can search by their names. There's a checkbox next to each user. My issue is that even though I click on a checkbox (Example: checkbox next to Alex) and then I start typing Alex I notice my checkbox is no longer checked. I'm guessing it's because React re-renders the component every time I type a character. How can I persist the value of the checkbox? I'm open to using local storage , but what will be the implementation? Thanks in advance!

Here's my LIVE DEMO

<article>
      <h2>
        {post.label}{" "}
        <span onClick={() => setShowGroup(!showGroup)}>
          {showGroup ? "-" : "+"}
        </span>
      </h2>
      {showGroup && (
        <div>
          {post.fields?.map((field: any, idx: number) => {
            return (
              <div key={idx}>
                <input type="checkbox" name="" id="" />
                <span>{field?.name}</span>
                <br />
              </div>
            );
          })}
        </div>
      )}
</article>



jeudi 24 août 2023

Flutter children node checkbox not selectable

I have a treenode implementation i am doing right now ut run into a blocker. When i create parent node and children nodes, i am able to select the parent node checkbox but unable to select the children node checkbox. I want to be able to select the children node checkbox as well so that i can be able to retrieve data from the parent Treenode and store them in supabase. Howver, i don't know what i am doing wrong in the code.

This is the simplified version of the feature code: https://www.dartpad.dev/?id=d644a706f84cb39588a763a767a2e15c

I tried this today again but no success. I have google everything possible, search Stack Overflow yet no solution. I expected to be able to select children node. That is if a parent node have multiple children nodes, i can be able to select a single child node but at the moment i have to select the parent node which in turn select all it children




Add or remove multiple horizontal lines in Shinly ggplot2

I have a shiny app that plots the data from an upload file. I have couple of checkboxInput & couple of corresponding numericInput in the app. Plotting works fine with numericInputs, as in below simple reproducible example. What I want to achieve here is, be able to select or deselect that specific checkbox so that geom_hline is added or removed from the plot.

Users can select or deselect one or multiple at a time based on the requirement.

Thanks in advance

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "H Line Plot Add & Remove"),
  dashboardSidebar(checkboxInput("minthresh", "Mimimun Threshold", T),
                   numericInput("minthreshvalue", "Minimum Threshold Value:", min = 0, max = 9, value = 5),

                   checkboxInput("maxthresh", "Maximun Threshold", T),
                   numericInput("maxthreshvalue", "Maximum Threshold Value:", min = 0, max = 9, value = 6),

                   checkboxInput("optthresh", "Optimal Threshold", T),
                   numericInput("optthreshvalue", "Optimal Threshold Value:", min = 0, max = 9, value = 7)),
  dashboardBody(plotOutput("plot1"))
)

server <- function(input, output) {
  data <- iris

  output$plot1 <- renderPlot({
    ggplot(data, aes(x = Species, y = Sepal.Length)) +
      theme(axis.text.x = element_text(size = 20),
            axis.text.y = element_text(size = 20)) +
      geom_boxplot() +
      geom_hline(aes(yintercept = input$minthreshvalue), color = "red", size = 3) +
      geom_hline(aes(yintercept = input$maxthreshvalue), color = "blue", size = 3) +
      geom_hline(aes(yintercept = input$optthreshvalue), color = "darkgreen", size = 3)
  })
}

shinyApp(ui, server)



mercredi 23 août 2023

Only last item in RecyclerView gets updated when notifyDataSetChanged is called

I want to build a segment wise list with selection feature. For this I have multiple RecyclerViews (for e.g. 5) in my layout file and the data list of each recyclerview is dynamic.As you can see in this image

Now, each item in recyclerview has a checkbox. What I need to do is when user selects any item, only those items of that perticular list should be enabled and other segment's list items should be disabled.

The issue I am facing is when I am trying to update each recyclerview using notifyDataSetChanged, only last item in the list is disabled and rest are enabled. I debugged the app, and process wise everything is working fine but the app doesn't reflect the same.As you can see here

My data model -

data class SelectionModel(
    var channelType: String,
    var channelName: String,
    var devices: ArrayList<SelectiveDevice>?
) {
    data class SelectiveDevice(
        var deviceName: String,
        var deviceType: String,
        var selected: Boolean = false
    )
}

My MainActivity -

class MainActivity : AppCompatActivity(), FiveChannelDeviceAdapter.FiveChannelDeviceCallback, FourChannelDeviceAdapter.FourChannelDeviceCallback, ThreeChannelDeviceAdapter.ThreeChannelDeviceCallback, TwoChannelDeviceAdapter.TwoChannelDeviceCallback, OneChannelDeviceAdapter.OneChannelDeviceCallback {

    lateinit var mBinding: ActivityMainBinding
    private var segments = ArrayList<SelectionModel>()

    private lateinit var fiveChannelDeviceAdapter: FiveChannelDeviceAdapter
    private lateinit var fourChannelDeviceAdapter: FourChannelDeviceAdapter
    private lateinit var threeChannelDeviceAdapter: ThreeChannelDeviceAdapter
    private lateinit var twoChannelDeviceAdapter: TwoChannelDeviceAdapter
    private lateinit var oneChannelDeviceAdapter: OneChannelDeviceAdapter

    var selectedType = ""
    var selectedGroup = ""
    var countChecked = 0
    var devices5ch = ArrayList<SelectionModel.SelectiveDevice>()
    var devices3ch = ArrayList<SelectionModel.SelectiveDevice>()
    var devices1ch = ArrayList<SelectionModel.SelectiveDevice>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        fiveChannelDeviceAdapter = FiveChannelDeviceAdapter(this@MainActivity, this@MainActivity)
        fourChannelDeviceAdapter = FourChannelDeviceAdapter(this@MainActivity, this@MainActivity)
        threeChannelDeviceAdapter = ThreeChannelDeviceAdapter(this@MainActivity, this@MainActivity)
        twoChannelDeviceAdapter = TwoChannelDeviceAdapter(this@MainActivity, this@MainActivity)
        oneChannelDeviceAdapter = OneChannelDeviceAdapter(this@MainActivity, this@MainActivity)

        mBinding.rvFiveCh.adapter = fiveChannelDeviceAdapter
        mBinding.rvFourCh.adapter = fourChannelDeviceAdapter
        mBinding.rvThreeCh.adapter = threeChannelDeviceAdapter
        mBinding.rvTwoCh.adapter = twoChannelDeviceAdapter
        mBinding.rvOneCh.adapter = oneChannelDeviceAdapter

        segments.clear()
        devices5ch.clear()
        devices3ch.clear()
        devices1ch.clear()

        val device1 = SelectionModel.SelectiveDevice("First", "5ch", false)
        val device2 = SelectionModel.SelectiveDevice("Second", "5ch", false)
        val device3 = SelectionModel.SelectiveDevice("Third", "5ch", false)
        val device4 = SelectionModel.SelectiveDevice("Forth", "3ch", false)
        val device5 = SelectionModel.SelectiveDevice("Fifth", "3ch", false)
        val device6 = SelectionModel.SelectiveDevice("Sixth", "1ch", false)

        devices5ch.add(device1)
        devices5ch.add(device2)
        devices5ch.add(device3)

        devices3ch.add(device4)
        devices3ch.add(device5)

        devices1ch.add(device6)

        val segment5ch = SelectionModel("5ch", "Color & CCT Lights", devices5ch)
        val segment3ch = SelectionModel("3ch", "Color Lights", devices3ch)
        val segment1ch = SelectionModel("1ch", "White Lights", devices1ch)

        segments.add(segment5ch)
        segments.add(segment3ch)
        segments.add(segment1ch)

        fiveChannelDeviceAdapter.setAdapterData(segments[0].devices!!, selectedType, selectedGroup, countChecked)
        threeChannelDeviceAdapter.setAdapterData(segments[1].devices!!, selectedType, selectedGroup, countChecked)
        oneChannelDeviceAdapter.setAdapterData(segments[2].devices!!, selectedType, selectedGroup, countChecked)

    }

    override fun resetSelection() {
        selectedType = ""
        selectedGroup = ""
        countChecked = 0

        fiveChannelDeviceAdapter.setAdapterData(segments[0].devices!!, selectedType, selectedGroup, countChecked)
        threeChannelDeviceAdapter.setAdapterData(segments[1].devices!!, selectedType, selectedGroup, countChecked)
        oneChannelDeviceAdapter.setAdapterData(segments[2].devices!!, selectedType, selectedGroup, countChecked)
    }

    override fun setReverseData(
        selectedType: String,
        selectedGroup: String,
        countChecked: Int,
        deviceList: ArrayList<SelectionModel.SelectiveDevice>
    ) {
        this.selectedType = selectedType
        this.selectedGroup = selectedGroup
        this.countChecked = countChecked
        val alteredList = java.util.ArrayList<SelectionModel>()
        alteredList.addAll(segments)

        for (group in alteredList) {
            if (group.channelType.equals(this.selectedType, true)) {
                group.devices = deviceList
            }
        }

        fiveChannelDeviceAdapter.setAdapterData(alteredList[0].devices!!, selectedType, selectedGroup, countChecked)
        threeChannelDeviceAdapter.setAdapterData(alteredList[1].devices!!, selectedType, selectedGroup, countChecked)
        oneChannelDeviceAdapter.setAdapterData(alteredList[2].devices!!, selectedType, selectedGroup, countChecked)

    }
}

One of the Adapter -

class FiveChannelDeviceAdapter(
    private val context: Context,
    private val callback: FiveChannelDeviceCallback
) :
    RecyclerView.Adapter<FiveChannelDeviceAdapter.FiveChannelDeviceViewHolder>() {

    private var mDeviceLists = ArrayList<SelectionModel.SelectiveDevice>()
    private lateinit var channelDevices: LayoutChannelDeviceBinding

    var selectedTypes = ""
    var selectedGroups = ""
    var countCheckeds = 0

    inner class FiveChannelDeviceViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {

        fun setData(position: Int) {
            if (countCheckeds > 0) {
                if (mDeviceLists[position].deviceType == selectedTypes) {
                    Log.d("SegmentSelected", position.toString())
                    channelDevices.selectDeviceCheck.setOnCheckedChangeListener(null)
                    channelDevices.selectDeviceCheck.isEnabled = true
                    channelDevices.selectDeviceCheck.isClickable = true
                    channelDevices.selectDeviceCheck.isChecked = mDeviceLists[position].selected
                    channelDevices.tvDeviceName.text = "Enabled"
                } else {
                    Log.d("SegmentNotSelected", position.toString())
                    channelDevices.selectDeviceCheck.isEnabled = false
                    channelDevices.selectDeviceCheck.isClickable = false
                    channelDevices.tvDeviceName.text = "Disabled"
                }
            } else {
                Log.d("SegmentReset", position.toString())
                channelDevices.selectDeviceCheck.isEnabled = true
                channelDevices.selectDeviceCheck.isClickable = true
                channelDevices.tvDeviceName.text = "Enabled"
            }

            channelDevices.selectDeviceCheck.setOnCheckedChangeListener { compoundButton, checked ->
                if (checked) {
                    countCheckeds += 1
                    mDeviceLists[position].selected = checked
                    selectedTypes = mDeviceLists[position].deviceType
                    selectedGroups = selectedTypes
                    Log.d("DeviceList", mDeviceLists.toString())
                    callback.setReverseData(selectedTypes, selectedGroups, countCheckeds, mDeviceLists)
                } else if (countCheckeds > 0 && !checked) {
                    countCheckeds -= 1
                    mDeviceLists[position].selected = checked
                    if (countCheckeds == 0) {
                        countCheckeds = 0
                        selectedTypes = ""
                        selectedGroups = ""
                        callback.resetSelection()
                    } else {
                        callback.setReverseData(selectedTypes, selectedGroups, countCheckeds, mDeviceLists)
                    }
                } else if (countCheckeds == 0 && !checked) {
                    countCheckeds = 0
                    mDeviceLists[position].selected = checked
                    selectedTypes = ""
                    selectedGroups = ""
                    callback.resetSelection()
                }
            }

        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FiveChannelDeviceViewHolder {
        channelDevices = LayoutChannelDeviceBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return FiveChannelDeviceViewHolder(channelDevices.root)
    }

    override fun onBindViewHolder(holder: FiveChannelDeviceViewHolder, position: Int) {
        holder.setData(position)
    }

    override fun getItemCount(): Int {
        return mDeviceLists.size
    }

    fun setAdapterData(mDeviceList: ArrayList<SelectionModel.SelectiveDevice>, selectedType: String, selectedGroup: String, countChecked: Int) {
        this.mDeviceLists.clear()
        this.mDeviceLists.addAll(mDeviceList)
        this.selectedTypes = selectedType
        this.selectedGroups = selectedGroup
        this.countCheckeds = countChecked
        notifyDataSetChanged()
    }

    interface FiveChannelDeviceCallback {
        fun resetSelection()
        fun setReverseData(selectedType: String, selectedGroup: String, countChecked: Int, deviceList: ArrayList<SelectionModel.SelectiveDevice>)
    }
}



How to change the value of "checkbox" in "DataRow" widget that build on "showModalBottomSheet" in flutter?

I builded this simple screen. After the user clicks on the button, he gets the "showModalBottomSheet" widget that opens on the screen.

In this "showModalBottomSheet" widget, there is a list of data that allows the user to change the value at the "checkbox" to true or false.

The problem is, because of this data inside the "showModalBottomSheet" widget.

When the user changes the value, there is no effect on the screen.

So, how should I refresh the screen to view the changes at the same time the user changes the value?

**Here is my code: **

import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/placeholder.dart';

class showModalBottomSheetTester extends StatefulWidget {
  const showModalBottomSheetTester({super.key});

  @override
  State<showModalBottomSheetTester> createState() =>
      _showModalBottomSheetTesterState();
}

class Welcome {
  final String welcome;
  final String purple;
  final String empty;

  Welcome(this.welcome, this.purple, this.empty);
}

class _showModalBottomSheetTesterState
    extends State<showModalBottomSheetTester> {
  bool _isChecked = false;

  void _updateCheckbox(bool newValue) {
    setState(() {
      _isChecked = newValue;
    });
  }

  List<Welcome> countries = [
    Welcome('Country A', 'purple A', 'empty A'),
    Welcome('Country A', 'purple A', 'empty A'),
    Welcome('Country A', 'purple A', 'empty A'),
  ];
  List<Welcome> seletedCountries = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('showModalBottomSheetTester'),
      ),
      body: ElevatedButton(
          onPressed: () {
            showModalBottomSheet(
                context: context,
                builder: (BuildContext context) {
                  return SizedBox(
                    height: 500,
                    child: Column(
                      children: [
                        const Padding(
                          padding: EdgeInsets.only(top: 30.0),
                          child: Text('Head'),
                        ),
                        DataTable(
                          columns: const [
                            DataColumn(label: Text('Welcome')),
                            DataColumn(label: Text('Purple')),
                            DataColumn(label: Text('Empty')),
                          ],
                          rows: getRows(countries),
                        )
                      ],
                    ),
                  );
                });
          },
          child: const Text('press')),
    );
  }

  List<DataRow> getRows(List<Welcome> countries) => countries
      .map((country) => DataRow(
              selected: seletedCountries.contains(country),
              onSelectChanged: (isSelected) {
                setState(() {
                  if (isSelected != null && isSelected) {
                    seletedCountries.add(country);
                  } else {
                    seletedCountries.remove(country);
                  }
                });
              },
              cells: [
                DataCell(Text(country.welcome)),
                DataCell(Text(country.purple)),
                DataCell(Text(country.empty)),
              ]))
      .toList();
}



mardi 22 août 2023

Adding BackColor Macro to all Checkboxes in an Excel Worksheet

I have an Excel worksheet with a large number of checkboxes. To improve visual clarity, I want the BackColor property of a given checkbox to change when it is checked (and revert back to white when unchecked). This should apply to each checkbox.

Here's my (very basic) macro to achieve this for an individual checkbox:

Private Sub CheckBox1_Click()
    If CheckBox1.Value = True Then
      CheckBox1.BackColor = RGB(255, 0, 0)
    ElseIf CheckBox1.Value = False Then
        CheckBox1.BackColor = RGB(255, 255, 255)
    End If
End Sub

But I cannot get it to work for all checkboxes without painstakingly adding this macro for each individual checkbox. Any help is greatly appreciated (and sorry if this is a very basic question, I'm fairly new to vba)!




overlapping problem with checkboxes in materialize

I have built a website that is a quiz and designed it with "Materialize". Now I have the problem that the texts of the answers overwrite each other. The distance between the checkboxes always stays the same, no matter how long the text is.

Here is my problem

The following is my code

<html><head><title>Coding Project 2</title>

    <!--Import materialize.css-->
    <link rel="stylesheet" href="/materialize/1.0.0/css/materialize.min.css">
    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col s12 form-box">
            <h3 class="center-align">Coding Project 2</h3>
            <form method="post">
                <div class="row">
                    <div class="input-field col s12">
                        <span><b>Question 1:</b> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et</span>
                    </div>
                </div>
                <input type="hidden" id="question" name="question" value="TWO16">
                                    <div class="row">
                        <div class="input-field col s12">
                            <label>
                                <input type="checkbox" name="ans_a" id="ans_a" value="A">
                                <span>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,</span>
                            </label>
                        </div>
                    </div>
                                                        <div class="row">
                        <div class="input-field col s12">
                            <label>
                                <input type="checkbox" name="ans_b" id="ans_b" value="B">
                                <span>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,</span>
                            </label>
                        </div>
                    </div>
                                                        <div class="row">
                        <div class="input-field col s12">
                            <label>
                                <input type="checkbox" name="ans_c" id="ans_c" value="C">
                                <span>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam</span>
                            </label>
                        </div>
                    </div>
                                                                                    <br><br>
                <div class="row">
                    <div class="col s6">
                        <a class="btn red" href="https://example.com/try.php?cancel">Cancel</a>
                    </div>
                    <div class="col s6 right-align">
                        <button class="btn waves-effect waves-light" type="submit" name="submitu" id="submitu">next<i class="material-icons right">send</i>
                        </button>
                    </div>
                </div>
        </form></div>
    </div>    
<!--JavaScript at end of body for optimized loading-->
<script type="text/javascript" src="/materialize/1.0.0/js/materialize.min.js">
</script>
</div></body></html>

Can anyone help me?

I have already tried to change the height manually several times, but I don't want the answers to always be of different lengths.




lundi 21 août 2023

Multiple Checkbox Form Field Kendo React

I have a basic kendo react form, in which one of the field element contains multiple checkboxes. I want to be able to select whichever checkbox i want and get the values in the form of an array in the Field element in submit handler of the kendo form. Currently im able to get only the text() field values .

Custom CheckBox component (<CustomCheckboxInput/>)

 {checkboxList?.map((checkbox, key) => (
                    <span>
                        <Checkbox
                            id={checkbox.id}
                            name="role"
                            label={checkbox.label}
                            checked={checkbox.isChecked || isSuperAdmin}
                            disabled={
                                isSuperAdmin && checkbox.id !== 'superAdmin'
                            }
                            value={checkbox.label}
                            onChange={(e) =>
                                handleRoleChange(e, checkbox.id, key)
                            }
                        />
                    </span>
                ))}

Form Field for Checkbox component

                       <Field
                            id={'role'}
                            label={'Select Role(s)'}
                            value={selectedRoles}
                            defaultValue={selectedRoles.join(',')}
                            component={(props) => (
                                <CustomCheckboxInput
                                    fieldRenderProps={props}
                                    handleRoleChange={handleRoleChange}
                                    isSuperAdmin={isSuperAdmin}
                                    checkboxList={checkboxList}
                                />
                            )}
                            validator={roleValidator}
                        />

This Field element is one of the Field element inside the <FormElement/>, along with other field element which contains Input elements. Im able to get the values of the input field but not the checkbox element.




dimanche 20 août 2023

Angular text field searh pipe eliminates array elements when combined with filter based on checkboxes

Good morning,

I have an angular page where I filter by text and by checkboxes as well.

  • If checkbox A is selected then list all the items starting with A.
  • If chechlox O is selected list all other items
  • If both selected list all
  • and of course at the same time take into account the text box filter as well.

By default both checkboxes are marked and if user types something in the textbox the filter works correctly, when the filter text is removed then i get back the complete list of tasks.

Now, when one of the checkboxes are unmarked i get the correctly filtered list, but when the box is marked again I don't get back the complet list. If the content of the list is visualized on the console then I can see that the content has been reduced to the fitlered values only.

Any idea why the array elements are removed in this second case and not in the first case?

Here is the code of the search pipe and below the html and the component file.

The search-filter.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';
import { TaskService } from './tasks/task.service';

@Pipe({
  name: 'searchFilter'
})
export class SearchFilterPipe implements PipeTransform {

  constructor(private taskService:TaskService){}
  transform(items: any, stringToSearch: string): any {

    console.log(items)
   if (!items) return items;

   return items.filter((s)=>{

     //WE ARE FILTERING HERE BY THE TEXTBOX ONLY. IN THIS CASE ITEMS ARRAY CONTENT IS NOT REDUCED. 
     //DELETING FILTER CONTENT GIVES BACK THE COMPLETE LIST.
      if ((this.taskService.getTitleFilterA() 
          && this.taskService.getTitleFilterO()) ||
      (!this.taskService.getTitleFilterA() 
        && !this.taskService.getTitleFilterO()))
      {

        if (stringToSearch)
        {
          return  s.name.toLowerCase().includes(stringToSearch.toLowerCase());
        }
        else
          return true;
      }

     //WE ARE FILTERING FROM HERE BY CHECKBOXES AS WELL. 
     //IN THIS CASE ITEMS ARRAY CONTENT IS REDUCED EACH TIME A TEXTBOX FILTER IS CLICKED 

      if (this.taskService.getTitleFilterA() 
          && !this.taskService.getTitleFilterO())
      {
        if (stringToSearch)
        return s.name.toLowerCase().startsWith("a") && s.name.toLowerCase().includes(stringToSearch.toLowerCase())
        else
          return s.name.toLowerCase().startsWith("a")
      }
      if (!this.taskService.getTitleFilterA() 
          && this.taskService.getTitleFilterO())
      {
          if (stringToSearch)
         {
            return !s.name.toLowerCase().startsWith("a") && s.name.toLowerCase().includes(stringToSearch.toLowerCase())
         }
        else
        {
          return !s.name.toLowerCase().startsWith("a")
        }
      }
   });
  }
}

The relevant html code from task-list.component.html:

  <input [(ngModel)]="searchText" />
  Zakum wells:
    <input type="checkbox"
      [(ngModel)]="isAChecked"
      (change)="checkBoxAClicked(isAChecked)"/>&nbsp;&nbsp;
  Other wells:
    <input type="checkbox"
    true
      [(ngModel)]="isOChecked"
      (change)="checkBoxOClicked(isOChecked)"
      />
<div class="row">
  <div class="col-xs-12">
    <button
      class="btn btn-success"
      [routerLink]="['new']">New Task</button>
  </div>
</div>
<hr>
<div class="row">
  <div class="col-xs-12">
    <app-task-item
      *ngFor="let taskitem of tasks | searchFilter: searchText; let i = index"
      [task]="taskitem"
      [index]="i">
    </app-task-item>
  </div>
</div>

The complete task-list.component.ts:

import { Component, OnInit } from '@angular/core';
    import { Task } from '../task.model';
    import { TaskService } from '../task.service';
    
    import {SearchFilterPipe} from "../../search-filter.pipe"
    @Component({
      selector: 'app-task-list',
      templateUrl: './task-list.component.html',
      styleUrls: ['./task-list.component.css']
    })
    export class TaskListComponent implements OnInit{
      tasks:Task[];
      searchText:string;
      isAChecked:boolean=true;
      isOChecked:boolean=true;
    
    
      constructor(private taskService:TaskService, private searchFilterPipe:SearchFilterPipe){
      }
    
      ngOnInit(): void {
        this.tasks=this.taskService.getTasks();
      }
    
      checkBoxAClicked(checked:boolean)
      {
       this.taskService.setFilterA(checked);
       this.tasks = this.searchFilterPipe.transform(this.tasks , this.searchText);
      }
    
      checkBoxOClicked(checked:boolean)
      {
       this.taskService.setFilterO(checked);
       this.tasks = this.searchFilterPipe.transform(this.tasks , this.searchText);
      }
    }



Fill textbox based on checkbox choices and prevent doubles

I have the following code to fill a textbox based on checkbox choices on buttonclick.

 If ChkOM.Checked Then
    txtOpp.Text += ChkOM.Text & Environment.NewLine
Else
    txtOpp.Text = ""
End If
If ChkHSM.Checked Then
    txtOpp.Text += ChkHSM.Text & Environment.NewLine
Else
    txtOpp.Text = ""
End If

This code works to an extend, but when i uncheck and later recheck the box it will fill the textbox with 2x the same text. how do i prevent these doubles?




samedi 19 août 2023

How to bypass the agreement checkbox with Python Requests?

I'm trying to bypass the agreement section before scraping this page. I had an idea to injecting PHP Sessions to open the page, but later realized that I must do the checkbox agreement manually before I run the code and get an access to the expected page.

This script below is what I'm doing so far:

import re
import requests
from bs4 import BeautifulSoup

session = requests.session()

#capture PHPSESSID
session.get("https://aviation.bmkg.go.id/web/")
c = str(session.cookies.get_dict())
c = re.sub("{|}|'", "", c).replace(": ","=")

newHeaders = {
    "Content-Type": "application/json",
    "User Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36",
    "Cookie": c
}

page = session.post("https://aviation.bmkg.go.id/web/metar_speci.php?", headers=newHeaders)

print("Status code: ", page.status_code)

print(page.content)

I had some suspicions to do a session.get with another page after doing some inspect elements but seems I can't get past the 400 status code with this route. TIA




vendredi 18 août 2023

yii2 bulk action how to update multiple rows in a dropdown menu using checkboxes

I have created a gridview widget. I can select multiple rows using the class CheckboxColumn::class and I can update those rows using the action in my controller. The gridview, button and js look like this:

<?= Html::a(Yii::t('backend', 'Change selected'), ['update-selected'], [
    'class' => 'btn btn-success mb-1',
    'id' => 'updateSelection',
    'data' => [
        'toggle' => 'modal',
        'target' => '#modal'
    ]
]) ?>

<?= GridView::widget([
    'id' => 'prId',
    'dataProvider' => $prSearch->search(Yii::$app->request->queryParams),
    'filterModel' => $prSearch,
    'filterSelector' => 'filter',
    'columns' => [
        [
            'class' => CheckboxColumn::class,
            'name' => 'CheckBoxSelection',
        ],
        [
            'attribute' => 'name',
        ],
        [
            'attribute' => 'visible'
        ]
    ],
]); ?>
<?php
$this->registerJS(<<<JS
var action = '';

$('#updateSelection').on('click', function(event) {
    event.preventDefault();
    submitForm();
});

function submitForm() {
    var url = $('#updateSelection').attr('href');
    var keys = $('#prId').yiiGridView('getSelectedRows');
    console.log(keys);
    $.ajax({
            type: 'POST',
            url: url,
            data: {keylist: keys}
        });
}
JS
    , View::POS_READY);

And here we have the controller:

    public function actionUpdateSelected()
    {
        $pr = new pR();
        if (Yii::$app->request->isPost && Yii::$app->request->post('keylist')) {
            $pr = pR::find()
                ->where(['IN', 'id', Yii::$app->request->post('keylist')])
                ->all();

            foreach ($pR as $pr) {
                $pr->visibility = 0;
                $pr->save();
            }
        }

        return 1
    }

This makes sure all of the selected rows get a visibility of 0 (there are 4) Now I want the user to be able to open a modal with a dropdownlist so he can choose the visibility himself. So i added this to the controller:

$updateForm = new UpdateForm();

        return $this->renderAjax('UpdateModal', [
            'prId' => new pR(),
            'updateForm' => $updateForm,
        ]);

I created the modal and the form:

//modal
<?php $form = ActiveForm::begin(['id' => 'updateSelectedVisibility', 'type' => ActiveForm::TYPE_HORIZONTAL]);?>
    <div class="modal-body">
        <?= $form->field($updateForm, 'id')->hiddenInput()->label(false); ?>
        <?= $form->field($updateForm, 'visibility')->dropDownList([
            0 => 'none',
            1 => 'some',
            2 => 'much'
            3 => 'yes',
        ], ['id' => 'visibility-dropdown']) ?>

    </div>

And i made a form ofcourse:

class updateForm extends Model
{
    /**
     * @var string
     */
    public $id;

    /**
     * @var string
     */
    public $visibility;

    public function rules()
    {
        return [
            [['id', 'visibility'], 'string'],
            [['visibility'], 'required'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'Id',
            'visibility' => 'Visibility',
        ];
    }
}

Now I've tried calling the keys array into the modal like this: $keys = Yii::$app->request->post('keylist');

although nothing seems to work. Does anybody know how to do this?




jeudi 17 août 2023

Unable to locate and click checkbox ::before using RSelenium

I'm using Rselenium to locate and select the 'All Sites' check box in a drp down box with multiple options. I was able to locate and open the list with all the options in the drop down box but I have not been able to find select the first option 'All Sites' (see below screenshot).

enter image description here

I inspected the the 'All Sites' check box but I can't find an id (see below screenshot),

enter image description here

I tried using name, class name and xpath unsuccessfully. I have also tried some different approaches suggested in this website with no luck.

Does anyone know how to check the 'All Sites' box?

Thanks!




Is it possible to have a multi selection dropdown field in ActiveCampaign?

We would like to give our customers the option to subscribe to our newsletter, however, because we have 5 different products we have 5 newsletters. We would like to give our customers the option to subscribe to 1 or more lists, but also prefer the design of a dropdown field over 5 checkboxes. Is it possible to move the checkboxes into a dropdown list?

I have also tried the multi selection field, however this requires the customer to select multiples using command or control.

I have found a way on here where it is possible, however this way is via building your form from scratch in html. Is it possible to do something like this in the form builder of activecampaign? How to create checkbox inside dropdown?




mercredi 16 août 2023

When I click on a checkbox in ag-grid-vue, all the checkboxes in the row are selected. how to handle each checkbox separately?

I'm working on ag-grid-vue. Currently, I have check box with name 'Checkbox Selection' and I've added a new checkbox colum with name 'Accept Media Pending' (Please look at the attached image). When I'm trying to click on one checkbox, the other checkbox is automatically selected. I want to handle each checkbox separately. How do I do it ?

[![enter image description here][1]][1]

My ag-grid-vue inside template looks like this

<ag-grid-vue :columnDefs="columnDefs"
                 :grid-options="gridOptions"
                 :rowData="rowData"
                 :rowHeight="rowHeight"
                 :showGrid="true"
                 class="ag-theme-alpine"
                 domLayout="autoHeight"
                 :rowClassRules="rowClassRules"
                 style="width:100%"
                 @grid-ready="onGridReady"
                 @row-selected="onRowSelected">
    </ag-grid-vue>

Also, Below is the column Definitions in ag-grid-vue

createColumnDefs() {
            return [
                 {
                    headerName: 'Share Status',
                    field: 'share_status',
                    filter: 'agSetColumnFilter',
                    filterParams: {
                        values: ['Original', 'Shared'],
                        excelMode: 'windows'
                    },
                },
                {
                    headerName: 'Product Type',
                    field: 'product_type_name',
                    filterParams: {
                        newRowsAction: 'keep',
                    }
                },
                {
                    field: 'checkboxSelection',
                    checkboxSelection: true,
                    suppressMenu: true,
                    filter: false,
                    sortable: false,
                    width: 75,
                },
                {
                  field: 'AcceptMediaPending',
                  checkboxSelection: true,
                  showDisabledCheckboxes: true,
                  width: 75,
                }
            ]
        }
   

Could someone please help me ? [1]: https://i.stack.imgur.com/340SZ.png




Create Multi Check box filter for html with jquery

i have multiple articles shown in a div the function will hide all items first i go in each div item in the items and see if its classlist contains the filter to show

the code:

div class="filter">
    <h1>Select products</h1> 
        <div class="checkbox"> <label><input type="checkbox" rel="" onchange="change();" checked="checked" />ALL</label> </div>
        <div class="checkbox"> <label><input type="checkbox" rel="TABLET" onchange="change();" />TABLET</label> </div>
        <div class="checkbox"> <label><input type="checkbox" rel="MEDICAL" onchange="change();" />MEDICAL</label> </div>
        <div class="checkbox">  <label><input type="checkbox" rel="TISANE NATUREL" onchange="change();" />TISANE NATUREL</label> </div>
         </div>

<div id="items">
 <div class="column #MEDICAL# #TABLET#">
        <div class="content">
          <h4>XLS MEDICAL - COMPRIME [FAT REDUCER] {120}</h4>
            <p style="color:blue">Product Ref.: 4384145</p>
            <p style="color:blue">Product Barcode: 5400951001098</p>
        </div>
    </div>

    <div class="column #MEDICAL# #TABLET#">
        <div class="content">
            <h4>XLS MEDICAL - COMPRIME [MAX STRENGTH] {120}</h4>
            <p style="color:blue">Product Ref.: 3214897</p>
            <p style="color:blue">Product Barcode: 5414963013147</p>
         </div>
    </div>

    <div class="column #TISANE NATUREL#">
        <div class="content">
            <h4>XLS MEDICAL - TISANE [FROID] {20}</h4>
            <p style="color:blue">Product Ref.: 3045382</p>
            <p style="color:blue">Product Barcode: 5412141225559</p>
        </div>
    </div>
</div>


<script>
          function change() {
              let results = Array.from(document.querySelectorAll('.row > div')),
                  selectedFilters = document.querySelectorAll('.filter input.models:checked');

              results.forEach(function (result) { result.style.display = 'none'; });

              selectedFilters.forEach(function (filter) { 
                  results.forEach(function (item) {
                      if (Array.inArray(item.classList, filter.getAttribute('rel')) != -1) { item.style.display = 'block'; };
                  });
              });
    }

    change();
</script>

i have tried to change the results to ".row > content" it hides all the item without showing any

my code is not working, thanks for help.




mardi 15 août 2023

How is branching logic coded when dealing with a checkbox answer in RedCAP?

This is my branching logic for the progress bar on one of the questions before we get to the checkbox one: ( this works)

([age]<>"" AND [education]="" AND [relationship_to_child]="" AND [are_you_the_sole_caregiver]="" AND [how_many_dependent_childre]="" AND [language]="" AND [what_is_your_suburb]="" AND [are_you_of_aboriginal_or_t(1)]="" AND [are_you_of_aboriginal_or_t(2)]="" AND [are_you_of_aboriginal_or_t(3)]="" AND [are_you_of_aboriginal_or_t(4)]="" )

However, once I get to the checkbox question, I am a bit stuck.

I have tried the logic below, using OR between each of the checkbox answers, but it doesn’t work.

([age]<>"" AND [education]<>"" AND [relationship_to_child]<>"" AND [are_you_the_sole_caregiver]<>"" AND [how_many_dependent_childre]<>"" AND [language]"" AND [what_is_your_suburb]="" AND ([are_you_of_aboriginal_or_t(1)]<>"" OR [are_you_of_aboriginal_or_t(2)]<>"" OR [are_you_of_aboriginal_or_t(3)]<>"" OR [are_you_of_aboriginal_or_t(4)]<>"" ))




The connection with a cell with logical values is confused

I put checkboxes to all residents, the connection with the cell with logical values is confused, when the "Next" button is pressed

Sub Del_Row()
  Rows(ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row).Delete
  Cells(Cells(Rows.Count, 1).End(xlUp).Row, 11).Activate
 
  n = ActiveSheet.CheckBoxes.Count
  ActiveSheet.CheckBoxes(n).Delete
  ActiveSheet.CheckBoxes(n - 1).Delete
  ActiveSheet.CheckBoxes(n - 2).Delete
  ActiveSheet.CheckBoxes(n - 3).Delete
End Sub
 
 Sub Copy_Row()
   Dim rw As Long
   rw = Cells(Rows.Count, 1).End(xlUp).Row
   Rows(rw).Copy
   Rows(rw + 1).Insert xlDown
   Rows(rw).Cells(1).Resize(2).DataSeries , xlChronological, xlMonth
   Range("K" & rw + 1 & ":AQ" & rw + 1).ClearContents
   n = ActiveSheet.CheckBoxes.Count
    
   ActiveSheet.CheckBoxes(n).LinkedCell = "CW" & rw + 1
   ActiveSheet.CheckBoxes(n - 1).LinkedCell = "CU" & rw + 1
   ActiveSheet.CheckBoxes(n - 2).LinkedCell = "CS" & rw + 1
   ActiveSheet.CheckBoxes(n - 3).LinkedCell = "CQ" & rw + 1
        

   Range("K" & rw + 1).Activate
End Sub

It turned out that the cells are confused




lundi 14 août 2023

How to change a style of disabled and checked checkbox?

I want to change my checked and disabled checkbox to green. I've tried changing background- color, color, accent-color and outline - only the outline changed, so I have the grey checkbox with the green outline. Do you have any idea how to change the checkbox to green or maybe get some ready img like sample checkbox ?

HTML:

                                <label>
                                <input type="checkbox"
                                       ng-model="t.isCorrected"
                                       disabled/>
                                
                            </label>

CSS:

input[type=checkbox][disabled]:checked {
outline:2px solid green;
accent-color: green !important;
background-color: #FA9E57 !important;
}



vendredi 11 août 2023

Multiple Checkboxes with same name insert checked value in database

I am making copy of checkboxes , I want to insert first checkboxes checked values in one row then second checkboxes checked values in second row in database , likewise

This is my form code (same i am making copy of these divs)

   
                  <div class="row">
                      <label class="col-md-2 col-form-label" for="basic-icon-default-fullname">Validation</label>
                      <div class="col-md-10">
                          <div class="form-check mb-2">
                              <input class="form-check-input" type="checkbox" value="required" id="required" class="validation" name="validation[]" checked />
                              <label class="form-check-label" for="required">Required</label>
                          </div>
                          <div class="form-check mb-2">
                              <input class="form-check-input" type="checkbox" value="alpha" id="alpha" class="validation" name="validation[]" />
                              <label class="form-check-label" for="alpha">Alphabets Only</label>
                          </div>
                          <div class="form-check mb-2">
                              <input class="form-check-input" type="checkbox" value="/^[a-zA-Z\s]+$/" id="alphaSpace" class="validation" name="validation[]" />
                              <label class="form-check-label" for="alphaSpace">Alphabets with Space</label>
                          </div>
                          <div class="form-check mb-2">
                              <input class="form-check-input" type="checkbox" value="number" id="number" class="validation" name="validation[]" />
                              <label class="form-check-label" for="number">Number Only</label>
                          </div>
                      </div>
                  </div>

I have tried like this way but it is not working as per my requirement

This is my controller code

$customInputNames = $request->input('customInputName');
        $inputTypes = $request->input('inputType');
        $validationsArrays = $request->input('validation'); // Array of arrays containing checked validation values
        $count = count($customInputNames);

        for ($i = 0; $i < $count; $i++) {
            $customInput = new InputForm();
            $customInput->customInputName = $customInputNames[$i];
            $customInput->inputType = $inputTypes[$i];

            $validationArray = $validationsArrays[$i]; // Get the array of checked validation values for the current input

            // Split the string into an array, remove empty values, and rejoin
            $validationArray = implode(',', array_filter(explode(',', $validationArray)));

            $customInput->validation = $validationArray; // Updated validation string
            $customInput->eventid = $eventId;
            $customInput->save();
        }



jeudi 10 août 2023

Product page custom checkbox enable a percentage discount on WooCommerce cart subtotal

The goal is simple, add a checkbox to the WooCommerce Product Page. If the user checks the checkbox, a 5% discount is applied on cart subtotal.

I have checked and doubled checked the code like ten times, I just cannot figure out why it gives me the "Fatal Error".

This is the code:

add_action( 'woocommerce_after_add_to_cart_button', 'ls_automatic_discount_checbox', 10 );
function ls_automatic_discount_checbox() {
    echo '<p><label><input type="checkbox" name="apply_automatic_discount" value="1"/> Apply 5% discount to your subtotal</label></p>';
}

add_action( 'woocommerce_cart_calculate_fees', 'ls_apply_discount_on_checkbox_check', 10, 7 );
function ls_apply_discount_on_checkbox_check( $cart, $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {

        // makes sure that the checkbox is ticked
        if ( isset( $_POST[ 'apply_automatic_discount' ] ) && $_POST[ 'apply_automatic_discount' ] == 1 ) {        

        // if it is, check what the percentaged discount on the subtotal is
        $percent = 5;

        // if all checks out - give the discount
        if ( isset ( $percent ) && $percent > 0 ) {

        // customer gets a discount of 5% of the SUBTOTAL
        $discount = $cart->cart_contents_total * $percent / 100;
        $cart->add_fee( __('5% OFF', 'woocommerce' ) . " (" . $percent . "%)", -$discount);
    
        }
    }
}



mardi 8 août 2023

Problem in Laravel10 , only the last checked item is saved

This form contains three items. I need the customer to be able to tick the required quantity (mnozstvi) for each item. The problem is that I only ever store the single/last item for which the quantity (mnozstvi) has been ticked in the order_items table. At the same time, I need to add a function that if a person does not check anything for one of the items, that the item is saved in the table as well but with a value of 0 (not interested in this product). Three records must always be stored in the table for an order. I tried checkboxes instead of radio, but it was the same problem. Where am I wrong?

HTML form:

<form class="repeater" method="post" action="" enctype="multipart/form-data">
@csrf

<input type="hidden" name="email" value="">
<div class="mb-3 col-lg-2">
    <label for="provozovna">Objednávka pro provozovnu...</label>
    <select class="form-select" id="provozovna" name="provozovna" required>
        <option disabled selected>Vybrat...</option>
        <option value="1">Praha</option>
        <option value="2">Brno</option>
    </select>
</div>

<hr>

<div class="row">
    <div class="col-md-6">
        <h3>Verze s nikotinem</h3>
        <hr>
        <div data-repeater-list="group-a">
            <div data-repeater-item class="row">
                <div class="mb-3 col-lg-6">
                    <label for="nikotin">Název</label><br>
                    <img src="" class="avatar-xxs rounded-circle" alt="Blueberry">
                    <input type="hidden" name="barva" value="blueberry">
                    Puff House - 800 potáhnutí, Blueberry Ice
                    <input type="hidden" name="order_items[0][nazev]" value="800-blueberry">
                    <input type="hidden" name="order_items[0][nikotin]" value="s nikotinem">
                </div>

                <div class="mb-3 col-lg-4">
                    <div class="container mt-4">
                        <div class="btn-toolbar" role="toolbar">
                            <div class="btn-group" role="group">
                                <input type="radio" class="btn-check" name="order_items[0][mnozstvi]" id="btnBlueberry1" value="12" autocomplete="off">
                                <label class="btn btn-outline-primary" for="btnBlueberry1">x12</label>

                                <input type="radio" class="btn-check" name="order_items[0][mnozstvi]" id="btnBlueberry2" value="24" autocomplete="off">
                                <label class="btn btn-outline-primary" for="btnBlueberry2">x24</label>

                                <input type="radio" class="btn-check" name="order_items[0][mnozstvi]" id="btnBlueberry3" value="36" autocomplete="off">
                                <label class="btn btn-outline-primary" for="btnBlueberry3">x36</label>

                                <input type="radio" class="btn-check" name="order_items[0][mnozstvi]" id="btnBlueberry4" value="48" autocomplete="off">
                                <label class="btn btn-outline-primary" for="btnBlueberry4">x48</label>

                                <input type="radio" class="btn-check" name="order_items[0][mnozstvi]" id="btnBlueberry5" value="60" autocomplete="off">
                                <label class="btn btn-outline-primary" for="btnBlueberry5">x60</label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div data-repeater-item class="row">
                <div class="mb-3 col-lg-6">
                    <img src="" class="avatar-xxs rounded-circle" alt="Fruit Mix">
                    <input type="hidden" name="barva" value="fruitmix">
                    Puff House - 800 potáhnutí, Fruit Mix
                    <input type="hidden" name="order_items[1][nazev]" value="800-fruitmix">
                    <input type="hidden" name="order_items[1][nikotin]" value="s nikotinem">
                </div>

                <div class="mb-3 col-lg-4">
                    <div class="container">
                        <div class="btn-toolbar" role="toolbar">
                            <div class="btn-group" role="group">
                                <input type="radio" class="btn-check" name="order_items[1][mnozstvi]" id="btnFruitmix1" value="12" autocomplete="off">
                                <label class="btn btn-outline-primary" for="btnFruitmix1">x12</label>

                                <input type="radio" class="btn-check" name="order_items[1][mnozstvi]" id="btnFruitmix2" value="24" autocomplete="off">
                                <label class="btn btn-outline-primary" for="btnFruitmix2">x24</label>

                                <input type="radio" class="btn-check" name="order_items[1][mnozstvi]" id="btnFruitmix3" value="36" autocomplete="off">
                                <label class="btn btn-outline-primary" for="btnFruitmix3">x36</label>

                                <input type="radio" class="btn-check" name="order_items[1][mnozstvi]" id="btnFruitmix4" value="48" autocomplete="off">
                                <label class="btn btn-outline-primary" for="btnFruitmix4">x48</label>

                                <input type="radio" class="btn-check" name="order_items[1][mnozstvi]" id="btnFruitmix5" value="60" autocomplete="off">
                                <label class="btn btn-outline-primary" for="btnFruitmix5">x60</label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <div class="col-md-6">
        <h3>Verze bez nikotinu</h3>
        <hr>
        <div data-repeater-list="group-a">
            <div data-repeater-item class="row">
                <div class="mb-3 col-lg-6">
                    <label for="nikotin">Název</label><br>
                    <img src="" class="avatar-xxs rounded-circle" alt="Lychee Ice">
                    <input type="hidden" name="barva" value="lycheeZero">
                    Puff House, Lychee Ice ZERO 800+
                    <input type="hidden" name="order_items[2][nazev]" value="800-lycheeZero">
                    <input type="hidden" name="order_items[2][nikotin]" value="bez nikotinu">
                </div>

                <div class="mb-3 col-lg-4">
                    <div class="container mt-4">
                        <div class="btn-toolbar" role="toolbar">
                            <div class="btn-group" role="group">
                                <input type="radio" class="btn-check" name="order_items[2][mnozstvi]" id="btnLycheeZero1" value="12" autocomplete="off">
                                <label class="btn btn-outline-primary" for="btnLycheeZero1">x12</label>

                                <input type="radio" class="btn-check" name="order_items[2][mnozstvi]" id="btnLycheeZero2" value="24" autocomplete="off">
                                <label class="btn btn-outline-primary" for="btnLycheeZero2">x24</label>

                                <input type="radio" class="btn-check" name="order_items[2][mnozstvi]" id="btnLycheeZero3" value="36" autocomplete="off">
                                <label class="btn btn-outline-primary" for="btnLycheeZero3">x36</label>

                                <input type="radio" class="btn-check" name="order_items[2][mnozstvi]" id="btnLycheeZero4" value="48" autocomplete="off">
                                <label class="btn btn-outline-primary" for="btnLycheeZero4">x48</label>

                                <input type="radio" class="btn-check" name="order_items[2][mnozstvi]" id="btnLycheeZero5" value="60" autocomplete="off">
                                <label class="btn btn-outline-primary" for="btnLycheeZero5">x60</label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>


<div class="d-flex justify-content-end">
    <input type="submit" class="btn btn-primary" value="Odeslat objednávku"/>
</div>

And my controller looks like this:

    <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\OrderItem;

class OrderController extends Controller
{
    public function processForm(Request $request)
    {
        // Zpracování formuláře a uložení do databáze

        $order = new Order();
        $order->provozovna_id = $request->input('provozovna');
        $order->email = $request->input('email');
        $order->save();

        $orderItems = $request->input('order_items');

        foreach ($orderItems as $item) {
            $orderItem = new OrderItem();
            $orderItem->order_id = $order->id;
            $orderItem->nazev = $item['nazev'];
            $orderItem->nikotin = $item['nikotin'];
            $orderItem->mnozstvi = isset($item['mnozstvi']) ? $item['mnozstvi'] : 0;

            $orderItem->save();
        }

        return redirect()->back()->with('success', 'Objednávka byla úspěšně odeslána.');
    }
}



Checkbox checking snag

https://irsa.ipac.caltech.edu/workspace/TMP_8Mcy38_15422/Gator/irsa/19142/tbview.html

I cannot select the checkboxes on this page using selenium webdriver.

This is an excerpt from the code I'm using:

import pandas as pd
import matplotlib.pyplot as plt
import csv
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os
import shutil

     driver_path = 'C:/Windows/chromedriver.exe'
     driver = webdriver.Chrome(executable_path=driver_path)
     driver.get('https://irsa.ipac.caltech.edu/cgi-bin/Gator/nph-scan?mission=irsa&submit=Select&projshort=ZTF')

     driver.find_element_by_xpath("//input[@value='ztf_objects_dr18']").click()
     driver.find_element_by_xpath("//input[@value='Select']").click()

     driver.find_element_by_name('objstr').send_keys(str(177.18609)+' '+str(21.47316))

     driver.find_element_by_xpath("//input[@value='10']").clear()
     driver.find_element_by_xpath("//input[@value='10']").send_keys('2')

     # Generate Text File
     driver.find_element_by_xpath("//input[@value='Run Query']").click()

     # Click on Download Button
    import time
    #print('going to sleep')
    time.sleep(2)
    #print('woke up')
    driver.find_element_by_xpath("//input[@tabindex='-1']").click()

Result on running this

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//input[@tabindex='-1']"}



Tkinter - GUI: checkbox with button that checks for exceptions and closes window

I am creating a GUI that will display the option to the user with a checkbox, and then after pressing the "Enter Data" button the program will check if the user has pressed at least one of the check-boxes. The checked values are being assigned to a dictionary which will be used later down the code. I am trying to make the button only close the window if no exception is raised (i.e. at least one check box is checked).

Right now the program displays the exception message no matter what, even if the user has checked at least 1 checkbox.

import tkinter
from tkinter import *
from tkinter import ttk
from tkinter import messagebox

def enter_data():
    global fatigue_vars

    try:
        if any(fatigue_vars):
            raise Exception("Please select at least one (1) of the given checkboxes!")
            return
    except Exception as ex:
        tkinter.messagebox.showwarning(title="Selection Error!", message=ex)
        return

    window.destroy()

#GUI 

window = tkinter.Tk()
window.title("Dimensions Data Entry")
window.resizable(0,0)

frame = tkinter.Frame(window)
frame.pack()

def disable_event():
    pass
window.protocol("WM_DELETE_WINDOW", disable_event)

#FATIGUE CASE

fatigue_type_frame =tkinter.LabelFrame(frame, text="Fatigue Type")
fatigue_type_frame.grid(row= 0, column=0, padx=20, pady=10)

fatigue_type_option=["Tension", "Compression", "Torsion", "Bending"]

fatigue_vars = {}
for fatigue_type in fatigue_type_option:
    var = StringVar(value="")
    fatigue_vars[fatigue_type] = var
    check_button= Checkbutton(
        fatigue_type_frame,
        text=fatigue_type,
        variable=var,
        onvalue=fatigue_type,
        offvalue="",
        padx=20,
        pady=10
    )

for widget in fatigue_type_frame.winfo_children():
    widget.grid_configure(padx=10, pady=5)

# ENTER DATA BUTTON
button = tkinter.Button(frame, text="Enter Data", command=enter_data)
button.grid(row=2, column=0, sticky="news", padx=20, pady=10)

window.mainloop()



dimanche 6 août 2023

How to remove checkbox border in css

How to remove checkbox border and background color using CSS?

label input[id="cb1"] {
  width: 14px;
  height: 14px;
  border: none;
  border-radius: 0px;
  cursor: pointer;
}

label input[id="cb1"]:checked:after {
  border: none;
}
<label for="cb1"><input type="checkbox" id="cb1"></label>

Demo: https://stackblitz.com/edit/angular-ivy-qq69mq?file=src%2Fapp%2Fapp.component.css




jeudi 3 août 2023

default checkbox with vuetify

I want to set the first checkbox as checked by default, but it's not working. I'm using the option 'value=true', and I also tried with 'v-model=true', but it still doesn't work. Here's the code snippet:

with vuetify.VCard(classes="mb-2"):
            with vuetify.VCardTitle():
                vuetify.VSubheader("Materiaux :", dense=True)
            with vuetify.VCardText():
                with vuetify.VRow():
                    with vuetify.VCol(cols="auto"):
                        vuetify.VCheckbox(label="1", dense=True, value=True)
                    vuetify.VDivider(vertical=True, classes="mx-1")
                    with vuetify.VCol(cols="auto"):
                        vuetify.VCheckbox(label="2", dense=True)
                    vuetify.VDivider(vertical=True, classes="mx-1")
                    with vuetify.VCol(cols="auto"):
                        vuetify.VCheckbox(label="3", dense=True)
                    vuetify.VDivider(vertical=True, classes="mx-1")
                    with vuetify.VCol(cols="auto"):
                        vuetify.VCheckbox(label="4", dense=True)




mercredi 2 août 2023

Angular: Custom checkbox doesn't reflect model but standard checkbox does

I am struggling with my custom checkbox not reflecting changes of ngModel. I've probably read all relevant issues on SO and still can't find a solution that works for me.

export class CheckboxInputComponent extends AbstractInputComponent implements ControlValueAccessor, Validator  {

@Input() public inxs: string;
    @Input() public grouped = true;
    @Input() public checked: boolean;
    @Input() public labeled = true;

    @Input() public name: string;

    @Input() public intermediate = false;

    @ViewChild('cb') public cb: ElementRef;

    @ContentChild('checkBoxLabel') labelTemplate;

    constructor ( protected cdr: ChangeDetectorRef ) {
        super(cdr);
    }

    public toggleCheck(): void {
        if (!this.grouped) {
            this.value = !this.value;
            this.checked = !this.checked;
        }
        this.intermediate = false;
    }

    private checkIntermediate(c: FormControl): void {
        if ( this.cb ) {
            if ( !(c.dirty || c.touched) ) {
                this.cb.nativeElement.intermediate = this.intermediate;
            } else {
                this.cb.nativeElement.intermediate = false;
            }
        }
    }

    protected customValidate( c: FormControl ): unknown | null {
        this.checkIntermediate(c);
        if ( c.dirty || c.touched ) {
            const noValue = this.hasNoValue(c);
            if ( this.required && noValue ) {
                return { 'required': true };
            }
        }
        return null;
    }

    protected normalize ( v: any ): any {
        return v;
    }

    protected hasNoValue(c: FormControl ): boolean {
        return c.value !== true;
    }
}

The abstract class it extends is:

@Directive()
export abstract class AbstractInputComponent implements OnChanges {

    /**
     * inner value
     */
    protected innerValue: unknown = null;
    protected innerErrors: AbstractInputErrors;

    /**
     * field label
     */
    @Input() public label: string;

    /**
     * required boolean
     */
    @Input() public required = false;


    /**
     * read only
     */
    @Input() public isReadOnly = false;

    /**
     * placeholder to show
     */
    @Input() public placeholder: string;

    @Input() public disabled = false;

    /**
     * control reference
     */
    @ViewChild('fieldInput') public fieldInput: NgModel;

    public isFocused = false;

    // infrastructure
    public registerOnChange(fn: any) { this.propagateChange = fn; }
    public registerOnTouched(fn: any) { this.propagateTouch = fn; }

    public propagateChange = (_: any) => { };
    public propagateTouch = (_: any) => { };

    constructor(
        protected cdr: ChangeDetectorRef
        ) { }

    public ngOnChanges(): void {
        if ( this.isReadOnly ) {
            this.propagateChange(this.value);
        }
        this.cdr.detectChanges();
    }

    public onFocus(): void {
        this.isFocused = true;
    }

    public onBlur(): void {
        this.isFocused = false;
        this.propagateTouch(true);
    }

    public get value(): any {
        return this.innerValue;
    };

    @Input() public set value(value: any) {
        if ( value !== undefined ) {
            this.writeValue(value);
            this.propagateChange(this.innerValue);
            this.propagateTouch(true);
        }
    }

    public writeValue(value: any): void {
        if (value !== this.innerValue) {
            this.innerValue = this.normalize(value);
        }
    }

    public setDisabledState(state: boolean): void {
        this.disabled = state;
    }

    public get errors(): AbstractInputErrors {
        return this.innerErrors;
    }

    public set errors( err: AbstractInputErrors ) {
        if ( this.fieldInput ) {
            if ( err ) {
                this.innerErrors = err;
            }
            this.fieldInput.control.setErrors(err);
        }
    }

    public validate(c: FormControl): unknown | null {
        this.innerErrors = (this.isReadOnly) ? null : this.customValidate(c);
        this.errors = this.innerErrors;
        return this.errors;
    }

    protected abstract normalize(value)
    protected abstract customValidate(control)
    protected abstract hasNoValue(value)
}

And the template:

<div class="ultim-checkbox"
    [class.readonly]="isReadOnly"
    [class.checked]="value"
    [class.intermediate]="intermediate"
    (click)="toggleCheck()">
    <input type="checkbox"
        [required]="required"
        [checked]="checked"
        [(ngModel)]="value"
        [attr.intermediate]="intermediate || null"
        #fieldInput="ngModel"
        #cb>
    <span><i class="ico"
            [ngClass]="{
                'i-check-fat': !intermediate,
                'i-minus-fat': intermediate
            }"></i></span>
</div>

Now, in the parent component it goes like this:

                <ultim-checkbox *ngIf="multiEditMode"
                    [(ngModel)]="data.meta.isSelected"
                    (change)="onSelect(data)"></ultim-checkbox>

It only updates the checkbox state if I hover over it. If instead I swap it for the standard input type="checkbox" it works just fine without hovering. Can you spot a problem?




Add a column of checkboxes to a DT table

Building on an earlier question that StackOverflow came to the rescue on... I'm building an app that connects to a database and pulls in a bunch of data, then lets the user "drill down" through a series of selectInput's and then ultimately allows them to download the results a .csv. After the previous question, I can now select which columns are shown in the datatable, as shown in this toy example.

library(shiny)
library(DT)
library(magrittr)

ids <- c(1, 2, 3, 4, 5)
firstNames <- c("Bob", "Jane", "Jim", "Billy", "Siouxsie")
lastNames <- c("Smith", "Jones", "Thomas", "Idol", "Sioux")
FaveColors <- c("Blue", "Green", "Yellow", "Red", "Black")
df <- data.frame(ids, firstNames, lastNames, FaveColors)

# Define UI 
ui <- fluidPage(

    # Application title
    titlePanel("Minimal Example"),

    # Sidebar 
    sidebarLayout(
        sidebarPanel(
            tabPanel("Columns",
                      checkboxGroupInput(inputId = "ColumnsToShow", label = "Output Columns",
                                         choices = names(df)
                      )
            )
        ),

        # Show a table
        mainPanel(
          DT::dataTableOutput("FilteredDataFrame")
        )
    )
)

# Define server logic 
server <- function(input, output) {
  
  filtered_df <- reactive({
    temp_frame <- df %>% select(all_of(input$ColumnsToShow))
    return(temp_frame)
  })

  output$FilteredDataFrame <- DT::renderDT(server=TRUE, {datatable(filtered_df(), extensions = 'Buttons',
                                                                   options = list(scrollx=TRUE,
                                                                                  lengthMenu = c(10,20,30),
                                                                                  paging = TRUE,
                                                                                  searching = TRUE,
                                                                                  fixedColumns = TRUE,
                                                                                  autoWidth = TRUE,
                                                                                  ordering = TRUE,
                                                                                  #dom = 'Bfrtip',
                                                                                  dom = 'tlip',
                                                                                  buttons = c('copy', 
                                                                                              'csv',
                                                                                              'excel')
                                                                   )
  )
  }
  )
}

# Run the application 
shinyApp(ui = ui, server = server)

Now the user has asked me to add a column at the start of the table that contains checkboxes. They would use these to flag entries that may have an error in the data. So ultimately I would gather the checked rows and build an SQL query to push back to a different database creating records for rows that need to be checked.

I've been looking around and most of the solutions I see involve some fairly hefty (for me anyway) javascript programming. Or I also found the shinydust package that has a built in data table with a column of checkboxes, but seems to lack the nice pagination and presentation of DT.

Any pointers on how to achieve this would be most appreciated.




mardi 1 août 2023

In R Shiny, how can I make a table of checkboxes that also has 'select all' checkboxes for individual rows/columns?

Using R Shiny, I want to display a table (e.g. via the "DT" package) with each cell containing a single checkbox. Next to each row and column heading I want to display a 'select all'/'master checkbox', which upon selecting, will select all the checkboxes in the corresponding row or column. As an additional feature, a checkbox in the top-left cell would select all checkboxes in the table. An example:

enter image description here

Attempted js

I found an example of this functionality with a master checkbox for one column here (using some javascript) but couldn't work out how to extend this to my requirements.

An example I've tried

library(shiny)
library(DT)

ui <- fluidPage(
    # Sidebar panel
    sidebarPanel(),
    
    # Main panel with the table
    mainPanel(
        DTOutput("myTable")
    )
)

server <- function(input, output){
    dat <- data.frame(
        vapply(1:6, function(i){
            as.character(
                checkboxInput(paste0("col1-", i), label = NULL, width = "150px")
            )
        }, character(1)),
        vapply(1:6, function(i){
            as.character(
                checkboxInput(paste0("col2-", i), label = NULL, width = "150px")
            )
        }, character(1)),
        vapply(1:6, function(i){
            as.character(
                checkboxInput(paste0("col3-", i), label = NULL, width = "150px")
            )
        }, character(1))
    )
    
    names(dat) <- c(
        as.character(checkboxInput("col1", label = "1", width = "150px")),
        as.character(checkboxInput("col2", label = "2", width = "150px")),
        as.character(checkboxInput("col3", label = "3", width = "150px"))
    )
    
    row_names <- LETTERS[1:6]
    rownames(dat) <- row_names
    
    output$myTable <- renderDT({
        datatable(
            dat, 
            escape = FALSE,
            options = list(
                columnDefs = list(
                    list(targets = c(1, 2, 3), orderable = FALSE, className = "dt-center")
                )
            ),
            callback = JS(
                "$('#col1').on('click', function(){",
                "  var cboxes = $('[id^=col1-]');",
                "  var checked = $('#col1').is(':checked');",
                "  cboxes.each(function(i, cbox) {",
                "    $(cbox).prop('checked', checked);",
                "  });",
                "});",
                "$('#col2').on('click', function(){",
                "  var cboxes = $('[id^=col2-]');",
                "  var checked = $('#col2').is(':checked');",
                "  cboxes.each(function(i, cbox) {",
                "    $(cbox).prop('checked', checked);",
                "  });",
                "});",
                "$('#col3').on('click', function(){",
                "  var cboxes = $('[id^=col3-]');",
                "  var checked = $('#col3').is(':checked');",
                "  cboxes.each(function(i, cbox) {",
                "    $(cbox).prop('checked', checked);",
                "  });",
                "});"
            )
        )
    })
}

shinyApp(ui, server)

This is a start, but I can't work out how to get master checkboxes next to the rows, nor one in the top-left for all boxes. Also, the whole thing is a bit big - would be great to be more compact.