text:
Q: Why is ZXing decoding so poorly? The following program uses ZXing (and PDFBox) to encode a byte array (lengths N=1,2,3,...) as a QR code, which is then embedded into a PDF document, rendered, extracted as a BufferedImage, and decoded. The decoded and encoded byte arrays are compared. Decoding is attempted first without the decoding option PURE_BARCODE, and if this fails, decoding is then attempted with the PURE_BARCODE option.
Decoding starts failing around N=20 (N=28 for the example random seed). Note that until decoding fails, the byte arrays are correctly decoded.
When the decoding fails, the failed QR code is displayed in a dialog box and the payload String printed to the console.
If I point my phone at this dialog box, however, my phone has no problem decoding this QR Code image, and the decoded string matches that on the console.
What mistake am I making?
package zxing;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.Map;
import java.util.PrimitiveIterator;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

public class Problem {

    public static void main(String[] args) throws IOException,
            WriterException,
            NotFoundException,
            ChecksumException,
            FormatException {
        Random r = new Random(12345);

        PrimitiveIterator.OfInt rb = r.ints(-128, 127).iterator();

        for (int N = 1; N < 100; N += 1) { // encode and decode random byte arrays of size N
            System.out.println(N);
            for (int numRuns = 0; numRuns < 10; numRuns++) { // number of tries at size N

                byte[] payload = new byte[N]; // payload to be encoded

                for (int i = 0; i < N; i++) { // payload random initialization
                    payload[i] = rb.next().byteValue();
                }
                final String payloadString = new String(payload, STRING_ENCODING); // encode as string

                // encode using zxing
                final BufferedImage qr = MatrixToImageWriter.toBufferedImage(new QRCodeWriter().encode(payloadString,
                        BarcodeFormat.QR_CODE, 256, 256, ENCODING_HINTS));

                // insert into PDF
                PDDocument pdDocument = new PDDocument();
                PDPage page = new PDPage();
                pdDocument.addPage(page);
                PDPageContentStream pageContent = new PDPageContentStream(pdDocument, page);
                pageContent.drawImage(JPEGFactory.createFromImage(pdDocument, qr), 0, 0, 200, 200);
                pageContent.close();
                // render pdf and extract qr code image
                BufferedImage pageImage = new PDFRenderer(pdDocument).renderImage(0);
                BufferedImage qrcodeImage = pageImage.getSubimage(0, pageImage.getHeight() - 200, 200, 200);
                pdDocument.close();

                byte[] resultPayload;
                try { // try zxing decode qrcodeImage *not* in PURE_BARCODE mode
                    resultPayload = new QRCodeReader().decode(
                            new BinaryBitmap(new HybridBinarizer(new RGBLuminanceSource(qrcodeImage.getWidth(),
                                    qrcodeImage.getHeight(),
                                    qrcodeImage.getRGB(0, 0, qrcodeImage.getWidth(), qrcodeImage.getHeight(), null, 0,
                                            qrcodeImage.getWidth())))), DECODING_HINTS_IMPURE).getText().getBytes(
                                    STRING_ENCODING);
                } catch (Throwable ex) {
                    try { // failed so try zxing decode qrcodeImage in PURE_BARCODE mode
                        resultPayload = new QRCodeReader().decode(
                                new BinaryBitmap(new HybridBinarizer(new RGBLuminanceSource(qrcodeImage.getWidth(),
                                        qrcodeImage.getHeight(),
                                        qrcodeImage.getRGB(0, 0, qrcodeImage.getWidth(), qrcodeImage.getHeight(), null,
                                                0,
                                                qrcodeImage.getWidth())))), DECODING_HINTS_PURE).getText().getBytes(
                                        STRING_ENCODING);
                    } catch (Throwable ex2) { // both decodings failed, display image
                        JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(qrcodeImage)),
                                "N=" + Integer.toString(N),
                                JOptionPane.PLAIN_MESSAGE, null);
                        System.out.println("Encoded=" + payloadString);
                        throw ex2;
                    }
                }

                if (!Arrays.equals(payload, resultPayload)) {
                    throw new RuntimeException("Payload mismatch.");
                }

            }
        }

    }
    private final static String STRING_ENCODING = "ISO-8859-1";
    final private static Map<EncodeHintType, Object> ENCODING_HINTS = new EnumMap<EncodeHintType, Object>(
            EncodeHintType.class);

    static {
        ENCODING_HINTS.put(EncodeHintType.CHARACTER_SET, STRING_ENCODING);
        ENCODING_HINTS.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    }

    final private static Map<DecodeHintType, Object> DECODING_HINTS_IMPURE = new EnumMap<DecodeHintType, Object>(
            DecodeHintType.class);

    static {
        DECODING_HINTS_IMPURE.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
        DECODING_HINTS_IMPURE.put(DecodeHintType.CHARACTER_SET, STRING_ENCODING);
    }

    final private static Map<DecodeHintType, Object> DECODING_HINTS_PURE = new EnumMap<DecodeHintType, Object>(
            DecodeHintType.class);

    static {
        DECODING_HINTS_PURE.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
        DECODING_HINTS_PURE.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
        DECODING_HINTS_PURE.put(DecodeHintType.CHARACTER_SET, STRING_ENCODING);
    }

}

[... ZXing throws a FormatException ...]
[... The ZXing phone application can read the dialog QR Code too ...]

A: The following changes improves the accuracy to about N=64 for high quality error correction and N=100 with no error correction (which suffices for my needs).
Three changes are needed.
Firstly, as suggested by @Tilman Hausherr, use a lossless factory when inserting the QR Code image into the PDF. While this does not make any difference on the code as presented in the OP, it is a necessary co-condition for the other changes to be effective.
Further, render the PDF in binary rather than rgb, and at a higher scale. The default scale (1.0) is only 72dpi.
pageContent.drawImage(LosslessFactory.createFromImage(pdDocument, qr), 0, 0, 200, 200);
...
BufferedImage pageImage = new PDFRenderer(pdDocument)
    .renderImage(0,3.0f,ImageType.BINARY);


text:
Q: MVC5 asp.net Show Validation Error in tooltip when I use dialog form for Edit I try use plugin from
https://bunjeeb.com/2014/06/03/mvc-tooltip-validation-using-jquery-and-bootstrap/
But Validation Error appeared under EditControl first time and once disappeared when I push the button "Save" and then like a tooltip when when I push the button "Save" second time
Please help me
Thanks a lot
1. _Layout.cshtml

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - Moving Pro Services</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    <link href="@Url.Content("~/Content/jquery.validate.mvc.css")" rel="stylesheet" type="text/css"/>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />

        @if (HttpContext.Current.User.Identity.IsAuthenticated)
        {

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                    </button>
                    @Html.ActionLink("Moving Pro Services", "Index", "Home", new {area = ""}, new {@class = "navbar-brand"})

                            Services

@Html.ActionLink("Companies", "Index", "Companies")

@Html.ActionLink("App Versions", "Index", "AppVersions")

                                @if (User.Identity.IsAuthenticated)
                                {
                                    if (User.IsInRole("Administrator"))
                                    {

@Html.ActionLink("Create User", "Register", "Account")

                                    }
                                }

@Html.ActionLink("About", "About", "Home")

@Html.ActionLink("Contact", "Contact", "Home")

                    @Html.Partial("_LoginPartial")

        }

        @RenderBody()

© @DateTime.Now.Year - Moving Pro Services

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

2. View

@model Maintenance.Models.AppVersion

@using (Html.BeginForm())
{

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Edit App Version

        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.AppVersion1)

                    @Html.LabelFor(model => model.AppVersionDescription, htmlAttributes: new { @class = "control-label col-md-4" })

                        @Html.EditorFor(model => model.AppVersionDescription, new { htmlAttributes = new { @class = "form-control", autofocus = "" } })
                        @Html.ValidationMessageFor(model => model.AppVersionDescription)

            <input class="btn btn-primary" type="submit" value="Save changes" id="approve-btn" />
            <button class="btn btn-default" data-dismiss="modal">Close</button>

}

@section Scripts {

    @Scripts.Render("~/bundles/jqueryval")

}

3. Script for create dialog for Edit

$(function () {
    $.ajaxSetup({ cache: false });

    $(document).on("click", ".modal-link", function (e) {
        $('#myModalContent').load(this.href, function () {
            $('#myModal').modal
                (
                {
                    keyboard: true
                }, 'show'
                );

            bindForm(this);
        });
        return false;
    });

    $(document).on("click", "a[data-modal]", function (e)
    {
        $('#myModalContent').load(this.href, function ()
        {
            $('#myModal').modal
            (
                {
                  keyboard: true
                }, 'show'
            );

            bindForm(this);
        });
        return false;
    });

    $(window.document).on('shown.bs.modal', '.modal', function () {
        window.setTimeout(function () {
            $('[autofocus]', this).focus();
        }.bind(this), 100);
    });
});

function bindForm(dialog) {
    $('form', dialog).submit(function () {
        var isValid = true; // assume all OK
        $('form').validate(); // perform validation on the form
        $('input[type="text"]').each(function (index, item) { // could change selector to suit e.g $('input, textarea').each(..
            if (!$(this).valid()) {
                isValid = false; // signal errors
                return false; // break out of loop
            }
        });
        if (!isValid) {
            return false; // exit
        }
        $('#progress').show();
        $.ajax({
            url: this.action,
            modal: true,
            draggable: true,
            resizable: false,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {

                    $('#myModal').modal('hide');
                    $('#progress').hide();
                    //location.reload();
                    alert(result.message);
            }
        });
        return false;
    });
}

4. Model
namespace Maintenance.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;

    public partial class AppVersion
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public AppVersion()
        {
            this.Companies = new HashSet<Company>();
        }

        [StringLength(40)]
        [Display(Name = "App Version")]
        public string AppVersion1 { get; set; }
        [StringLength(40)]
        [Display(Name = "App Version Description")]
        public string AppVersionDescription { get; set; }
        [ReadOnly(true)]
        [Display(Name = "Creating Date")]
        public System.DateTime CreateDate { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Company> Companies { get; set; }
    }
}

5. Plugin to show tooltip

/*
 *  Project: MVC Validation Framework
 *  Description: This plugin will convert client side validation elements to bootstrap tooltips
 *  Author: Ahmad Aqrabawi, Mohamed Aljaber
 *  License: MIT
 */

// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
; (function ($, window, document, undefined) {

    // undefined is used here as the undefined global variable in ECMAScript 3 is
    // mutable (ie. it can be changed by someone else). undefined isn't really being
    // passed in so we can ensure the value of it is truly undefined. In ES5, undefined
    // can no longer be modified.

    // window and document are passed through as local variable rather than global
    // as this (slightly) quickens the resolution process and can be more efficiently
    // minified (especially when both are regularly referenced in your plugin).

    // Create the defaults once
    var pluginName = "tooltipValidation";
    var defaults = {
    };

    // The actual plugin constructor
    function Plugin(element, options) {
        this.element = element;
        // jQuery has an extend method which merges the contents of two or
        // more objects, storing the result in the first object. The first object
        // is generally empty as we don't want to alter the default options for
        // future instances of the plugin
        this.options = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    Plugin.prototype = {

        init: function () {

            // Place initialization logic here
            // You already have access to the DOM element and
            // the options via the instance, e.g. this.element
            // and this.options
            // you can add more functions like the one below and
            // call them like so: this.yourOtherFunction(this.element, this.options).

            var elem = $(this.element),
                name = elem.attr("name"),
                defaultBorderCss = elem.css('border'),
                tooltipPlacement = this.options.placement;

            if (name) {

                var errValElem = $('span[data-valmsg-for="' + name + '"]');
                errValElem.hide();

                function onDOMSubtreeModified(errValElem) {

                    errValElem.bind("DOMSubtreeModified", function () {

                        elem.tooltip("destroy");
                        elem.siblings("div.tooltip").remove();

                        var isTooltipPluginAttached = elem.data("plugin_tooltipValidation");
                        if (!isTooltipPluginAttached) {
                            elem.tooltip({
                                'title': errValElem.text(),
                                'animation': 'true',
                                'placement': tooltipPlacement || 'top',
                                'trigger': 'focus'
                            });
                        }

                        if (errValElem.hasClass("field-validation-error")) {
                            elem.css('border', '1px solid red');
                        }
                        else {
                            elem.css('border', defaultBorderCss);
                            elem.tooltip('destroy');
                            elem.siblings("div.tooltip").remove();
                        }

                    });
                };
                function showTooltipOfError(event) {

                    var inputField = event.currentTarget;
                    if (errValElem.hasClass("field-validation-error") || errValElem.hasClass("field-error")) {

                        $(inputField).siblings("div.tooltip").remove();

                        $(inputField).tooltip({
                            'title': $(errValElem).text(),
                            'animation': 'true',
                            'placement': tooltipPlacement || 'top',
                            'trigger': 'focus'
                        });
                        $(inputField).tooltip('show')
                        $(".tooltip").addClass("error");
                    }
                };

                if (elem.is('select')) { //Handle tooltip on input type = select (DropdownList)
                    elem.on("focus mouseenter", function (event) {
                        showTooltipOfError(event);
                    });
                    elem.on("mouseleave", function (event) {
                        var inputField = event.currentTarget;
                        $(inputField).tooltip('hide');
                    });
                    onDOMSubtreeModified(errValElem);
                }
                else if (elem.attr('type') == 'date') { //Handle if input type = date
                    elem.on("focus mouseenter", function (event) {
                        showTooltipOfError(event);
                    });
                    elem.on("mouseleave", function (event) {
                        var inputField = event.currentTarget;
                        $(inputField).tooltip('hide');
                    });
                    elem.on("change", function (event) {
                        var inputField = event.currentTarget;
                        if ($(inputField).val() != "") {
                            elem.css('border', defaultBorderCss);
                            elem.tooltip('destroy');
                            elem.siblings("div.tooltip").remove();
                        }
                        else
                            elem.css('border', '1px solid red');
                    });
                    onDOMSubtreeModified(errValElem);
                }
                else if (elem.attr('type') == 'file') {
                    elem.on("focus mouseenter", function (event) {
                        showTooltipOfError(event);
                    });
                    elem.on("mouseleave", function (event) {
                        var inputField = event.currentTarget;
                        $(inputField).tooltip('hide');
                    });
                    onDOMSubtreeModified(errValElem);
                }
                else {
                    elem.on("focus", function (event) {
                        showTooltipOfError(event);
                    });
                    onDOMSubtreeModified(errValElem);
                }
            }
        }
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Plugin(this, options));
            }
        });
    };

})(jQuery, window, document);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wifi driver error: Unknown header type 7f Wifi connection is not working with Lenovo Thinkpad. Although ethernet connection is working.
I've already install  Ubuntu 20.04.1:
Linux username-ThinkPad-E490 5.4.0-42-generic #46-Ubuntu SMP Fri Jul 10 00:24:02 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
The notebook is Lenovo Thinkpad E490 (new)
I tried these things:

*

*$ ip address
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback ...
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: enp4s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether ...
3: wlp5s0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default qlen 1000
    link/ether ...

*$ lspci -kv
05:00.0 Network controller: Realtek Semiconductor Co., Ltd. RTL8822BE 802.11a/b/g/n/ac WiFi adapter (rev ff) (prog-if ff)
    !!! Unknown header type 7f
    Kernel driver in use: rtw_pci
    Kernel modules: rtwpci

*$ sudo modprobe 8822be
modprobe: FATAL: Module 8822be not found in directory /lib/modules/5.4.0-42-generic

*$ ls /lib/firmware/rtlwifi | grep rtl8822
rtl8822befw.bin

I don't know what is happens. What means !!! Unknown header type 7f ?
The driver seems to be installed, although the interface is not up.

A: Have the same problem on Lenovo Legion Y530: Ubuntu 18.04 LTE
uname -r
5.4.0-42-generic

$ sudo lspci -v

07:00.0 Network controller: Realtek Semiconductor Co., Ltd. RTL8822BE 802.11a/b/g/n/ac WiFi adapter (rev ff) (prog-if ff)
!!! Unknown header type 7f
Kernel driver in use: r8822be
Kernel modules: rtwpci, r8822be

$ sudo modprobe 8822be

modprobe: FATAL: Module 8822be not found in directory /lib/modules/5.4.0-42-
generic


text:
Q: Validation ignored when cloning a newly created record I have a model UserFile that belongs_to a Folder:
class UserFile < ActiveRecord::Base
  has_attached_file :attachment
  belongs_to :folder

  validates_attachment_presence :attachment
  validates_presence_of :folder_id

  def copy(target_folder)
    new_file = self.clone
    new_file.folder = target_folder
    new_file.save!
  end
end

The following test fails unexpectedly:
test 'cannot copy a file to anything other than a folder' do
  folder = Factory(:folder)
  file1 = UserFile.create(:attachment => File.open("#{Rails.root}/test/fixtures/textfile.txt"), :folder => Folder.root)
  file2 = UserFile.find(file1)

  # Should pass, but fails
  assert_raise(ActiveRecord::RecordInvalid) { file1.copy(nil) }

  # Same record, but this DOES pass
  assert_raise(ActiveRecord::RecordInvalid) { file2.copy(nil) }

  assert file1.copy(folder)
end

The validates_presence_of :folder_id is ignored when using a newly created object, but when I do an ActiveRecord#find it DOES work. I think it has something to do with calling clone in the copy method, but I cannot figure it out. Does anyone know what is going on or how to make the test pass??

A: Mischa,
cloning is a beast.
record.errors is memoized and the @errors instance variable gets cloned too.
file1.errors = new_file.errors

this will be non-nil since create called validations on file1.
now what happens when you clone file1 and say new_file.save!?
Deep inside valid? calls errors.clear on new_file but it still points to the same error object as file1.
Now viciously, the presence validator is implemented like this:
def validate(record)
   record.errors.add_on_blank(attributes, options)
end

which (obviously) can only access errors.base
http://apidock.com/rails/ActiveModel/Errors/add_on_blank
so, although, the validations do run on new_file as the record, the presence validation passes since
new_file.errors.instance_eval { @base } == file1

and for file1.folder_id is NOT blank.
Now, your second test passes because if you read the file entry from the db, file2.errors is nil so when you clone it and call validations on the clone, the errors object is created anew with the correct base (the clone) for which folder_id will be blank because of the line new_file.folder = target_folder.
your problem is solved by simply adding
def copy(target_folder)
    new_file = self.clone
    new_file.instance_eval { @errors = nil } # forces new error object on clone
    new_file.folder = target_folder
    new_file.save!
end

hope this helped


text:
Q: React Table Typescript "Type is not assignable" I've set up my React project with Typescript and React-Table.
I was following the Quick Start Guide from the React-Table website and got an error.
 const data = React.useMemo(
   () => [
     {
       col1: 'Hello',
       col2: 'World',
     },
     {
       col1: 'react-table',
       col2: 'rocks',
     },
     {
       col1: 'whatever',
       col2: 'you want',
     },
   ],
   []
 )

const columns = React.useMemo(
    () => [
      {
        Header: 'Column 1',
        accessor: 'col1', // accessor is the "key" in the data
      },
      {
        Header: 'Column 2',
        accessor: 'col2',
      },
    ],
    []
  )

I get an error when doing const tableInstance = useTable({ columns, data }).

Type '{ Header: string; accessor: string; }[]' is not assignable to type 'readonly Column<{ col1: string; col2: string; }>[]'.
Type '{ Header: string; accessor: string; }' is not assignable to type 'Column<{ col1: string; col2: string; }>'.

I barely just started getting into this so I don't really know what's going on.
Here is a code sandbox with a recreation of the problem: Sandbox

A: Seems that TypeScript fails with type inference, so I gave him the hint by

*

*Introducing new type type Cols = { col1: string; col2: string };

*Explicitly stating type for const columns: Column<Cols>[] = ...
Full working example is here:
import { useTable, TableOptions, Column } from "react-table";
import React from "react";

type Cols = { col1: string; col2: string };

export default function App() {
  const data = React.useMemo(
    (): Cols[] => [
      {
        col1: "Hello",
        col2: "World"
      },
      {
        col1: "react-table",
        col2: "rocks"
      },
      {
        col1: "whatever",
        col2: "you want"
      }
    ],
    []
  );

  const columns: Column<{ col1: string; col2: string }>[] = React.useMemo(
    () => [
      {
        Header: "Column 1",
        accessor: "col1" // accessor is the "key" in the data
      },
      {
        Header: "Column 2",
        accessor: "col2"
      }
    ],
    []
  );

  const options: TableOptions<{ col1: string; col2: string }> = {
    data,
    columns
  };

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = useTable(options);

  return (
    <table {...getTableProps()} style={{ border: "solid 1px blue" }}>
      <thead>
        {headerGroups.map((headerGroup) => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map((column) => (
              <th
                {...column.getHeaderProps()}
                style={{
                  borderBottom: "solid 3px red",
                  background: "aliceblue",
                  color: "black",
                  fontWeight: "bold"
                }}
              >
                {column.render("Header")}
              </th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row) => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map((cell) => {
                return (
                  <td
                    {...cell.getCellProps()}
                    style={{
                      padding: "10px",
                      border: "solid 1px gray",
                      background: "papayawhip"
                    }}
                  >
                    {cell.render("Cell")}
                  </td>
                );
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

A: I was facing the same problem then found this solution, add as 'const' to your columns object like this:
[
  {
    Header: 'Id',
    accessor: 'id' as const,
  },
  {
    Header: 'Column 1',
    accessor: 'column_1' as const,
  },
  {
    Header: 'Column 2',
    accessor: 'column_2' as const,
  },
  {
    Header: 'Column 3',
    accessor: 'column_3' as const,
  },
]

A: It'll work this out for you if you do the following:
https://github.com/tannerlinsley/react-table/issues/2970#issuecomment-756364081
Then you just need to set your columns type to columns[] in your config file
export const headers: Column[] = [
  {
    Header: "ID",
    accessor: "id", // accessor is the "key" in the data
  },
.....

Then in you table consuming component you do
  const columns = useMemo(() => headers, []);
  const data = useMemo(() => people, []);

  const tableInstance = useTable({ columns, data });

Or you can do it all in the one file of course


text:
Q: What is the best way to study graduate level mathematics? I am studying a 400/500 level measure theory math book on my own.
Right now, when I read it I try to read the proposition then the following proof. And then try to do the exercises on my own.
I wonder if I should change it to:-
1. read the proposition
2. try to prove it on my own.
3. If I could not then proceed to read the proof from the book.
4. Do the exercises.
Or should I stick with everything above minus step 2. It can save me some time but I wonder if that is what good mathematics students do?
Any feedback from your experience would be appreciated.
Best,

A: With regards to learning from proofs provided in a textbook, it may be very beneficial to

*

*(step 1) mentally try to guess how a proof is going to substantiate its claim

*(step 2) read the textbook-proof

*(step 3) write a personalized proof while having access to the textbook-proof emphasizing clarity

*(step 4) write a personalized proof while having access to the textbook-proof emphasizing brevity

*(step 5) write a formal proof without having access to the textbook-proof.

Here "formal" means "able to be understood by other mathematicians---most importantly your instructor."


text:
Q: How can I inject css class in Vuejs component with javascript? Sorry for my question. I actually want to inject new css class and its hover attributes which I got from a web service. I'm trying to put it into #style#
 #/style# tags.

A: The official docs for Class and Style Bindings/Binding HTML Classes show several ways. Below are the most common and some useful demos.

Object Syntax
We can pass an object to v-bind:class to dynamically toggle classes:

The above syntax means the presence of the active class will be
determined by the truthiness of the data property isActive.

See demo below:

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    isActive: true
  }
})
.active { background: yellow; }

{{ message }}

My DIV

  <button @click="isActive = !isActive">activate/deactivate</button>

Multiple classes
You can have multiple classes toggled by having more fields in the
object. In addition, the v-bind:class directive can also co-exist with
the plain class attribute. So given the following template:

Demo:

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    isActive: true,
    hasError: false
  }
})
.active { background: yellow }
.text-danger { color: red; font-weight: bold; }

{{ message }}

My DIV

  <button @click="isActive = !isActive">toggle isActive</button>
  <button @click="hasError= !hasError">toggle hasError</button>

Array Syntax
We can pass an array to v-bind:class to apply a list of classes:

data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}

And, of course, you can change that data and the HTML will react. Another demo:

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    activeClass: 'active',
    errorClass: 'text-danger'
  }
})
.active { background: green }
.inactive { background: yellow }
.text-danger { color: red; font-weight: bold; }

{{ message }}

My DIV

  <button @click="activeClass = 'inactive'">activeClass to inactive</button>
  <button @click="activeClass = 'active'">activeClass to active</button>


text:
Q: Match cells in two sheets and copy paste the match content I'm totally new to the vba. I have two excel sheets, and I'm trying to compare and match the cells in one of the columns in two sheets. If matched cells are found, information of the adjacent cells will be copied and paste to another sheet(sheet1).
I have a code that works just fine but incomplete. Because there are repetitive cells in a column, the code once finds a match and copy-paste the info, it skips to the next non-repeated cells. Thus resulting in a lot of blank, missing cell. Any idea to make it fill in the blank?
Image:

Sheet2:

Sub Button2_Click()
Dim lastRw1, lastRw2, nxtRw, m

  lastRw1 = Sheets(1).Range("A" & Rows.Count).End(xlUp).Row
  lastRw2 = Sheets(2).Range("B" & Rows.Count).End(xlUp).Row
'Loop
     For nxtRw = 2 To lastRw2
'Search
        With Sheets(1).Range("A2:A" & lastRw1)
          Set m = .Find(Sheets(2).Range("B" & nxtRw), LookIn:=xlValues, lookat:=xlWhole)
'Copy
            If Not m Is Nothing Then
              Sheets(2).Range("C" & nxtRw & ":D" & nxtRw).Copy _
              Destination:=Sheets(1).Range("J" & m.Row)
            End If
        End With
     Next
End Sub

A: Updated:
I took a small sample of your Sheet2 data set:

I also updated your code as follows (main change - I replaced Find with Match in order to find the matching row number):
Dim lastRw1 As Long, lastRw2 As Long, nxtRw As Long, m As Long

lastRw1 = Sheets(1).Range("A" & Rows.Count).End(xlUp).Row
lastRw2 = Sheets(2).Range("B" & Rows.Count).End(xlUp).Row

'Loop
 For nxtRw = 2 To lastRw1
    'Search
    With Sheets(1)
         m = Application.Match(.Range("A" & nxtRw).Value, _
                Sheets(2).Range("B1:B" & lastRw2), 0)
        'Copy
         If m Then
            Sheets(2).Range("C" & m & ":D" & m).Copy _
            Destination:=.Range("J" & nxtRw)
         End If
    End With
 Next

Final result:


text:
Q: Не подключается jQuery. Не работает jQuery Помогите пожалуйста, не подключается jQuery.
Весь день возился с этой проблемой,
подключал и через папку и через google не помогло.
Буду благодарен вашым ответам.
Заранее Спасибо!

    <meta charset = "utf-8"/>
    <title>Заготовка</title>

    <link href="main.css" rel="stylesheet" />

            Увійти 3 рази

    Увійти


text:
Q: Prove there is no homomorphism from $Z_{16} \oplus Z_2 $ ont $Z_4 \oplus Z_4$
Prove there is no homomorphism from $Z_{16} \oplus Z_2 $ onto $Z_4 \oplus Z_4$

I have no idea at all how to attempt such question. I have read some solutions in which we find the cardinality of $kerm\phi$ for some $\phi mapping $ that is onto using the first theorem of homomorphism.
After that I don't understand anything
Is there a general approach to these questions ?

A: If there were a homomorphism, the kernel would be a subgroup of order $2$, since $Z_4 \oplus Z_4$ has order $16$, and the first isomorphism theorem implies that $Z_{16} \oplus Z_2/ker \phi \cong Z_4 \oplus Z_4$ There is only one subgroup of order $2$ in this group, and its quotient is not isomorphic to $Z_4 \oplus Z_4$.

A: Write $a$ and $b$ for the generators of the $Z_{16}$ and $Z_2$ on the left.
If $\phi$ is a homomorphism from $Z_{16}\oplus Z_2$ to
$Z_{4}\oplus Z_4$ then $\phi(4a)=0$. This means that the kernel of
$\phi$ has size at least $4$. Can $\phi$ be onto with a kernel that  big?


text:
Q: Membership.IsApproved value not saved I have this code:
MembershipUser user = Membership.GetUser(model.UserName);
if (user != null)
    user.IsApproved = false;

The call to user.IsApproved above does set the IsApproved flag to false but when I subsequently do:
MembershipUser user = Membership.GetUser(model.UserName);

and check the IsApproved flag the value is true!
What's wrong?

A: Looking on msdn doing user.IsApproved = false does not update the data store.
If you wish to persist the change you need to call UpdateUser(user)

A: You need to save the change, otherwise you're just setting it to false for the current object. You can use Membership.UpdateUser (http://msdn.microsoft.com/en-us/library/system.web.security.membership.updateuser.aspx).
MembershipUser user = Membership.GetUser(model.UserName);
if (user != null){
    user.IsApproved = false;
    Membership.UpdateUser(user);
}


text:
Q: Is it possible to create a Texture2D_Array off several Texture2D objs in OpenGL? About my intend:
I have an image stack and for several reasons I need them all to be separate 2D-textures. Then for some composed display I need like 5-10 of them to be fused together in one display (perfect for Texture2d_Array). My idea was to take the already uploaded 2D textures and form them into a Texture2d-array. Is that possible with the functions that OpenGL gives me?
Remark: I want to avoid re-loading the image data and for efficientcy reasons the already created mip-maps are very useful and should be retained. Therefore actions like "Get data off Tex2d create new Tex2Darray-layer" are stupid.
If that fails, my fallback would be to have around 10 samplers in my Shader and add/average them together before display.

A: Anything is possible! Well, almost anything...
Depending on the OpenGL version you have available, there are a few options you can consider. This is if you really need to copy the data. Of course by far the best option would be to load the texture data into an array texture in the first place, and avoid the extra copy.
glCopyImageSubData()
The glCopyImageSubData() is a very direct match for the functionality you want. The only downside is that it's only available in OpenGL 4.3 and later.
glCopyTexImage2D()
I'm mentioning this just for completeness sake, in case somebody looks at this answer for a slightly different use case. glCopyTexImage2D() can generally be used to copy texture data by setting up the source texture as an FBO attachment.
But it turns out that it does not support GL_TEXTURE_2D_ARRAY, so it can't be used to copy from a regular texture to an array texture. The other direction would work.
glBlitFramebuffer()
glBlitFramebuffer() is available in OpenGL 3.0 and later, and can be used to copy almost any kind of framebuffer/texture data.
To copy from texture to texture, you create two FBOs. You bind one of them as GL_READ_FRAMEBUFFER, and attach the source texture to it. You bind the second one as GL_DRAW_FRAMEBUFFER, and attach the target texture to it. Then you call glBlitFramebuffer().

A: You might be able to bypass your limitation to have each texture in a separate 2D texture using a combination of the following two techniques:
glTextureView()
Create a single texture array and then use glTextureView() (core in OpenGL 4.3+) to create separate 2D textures which behave exactly as your currently existing ones. The difference compared to the functions outlined by Reto Koradi is that texture views do not duplicate memory on the GPU which might be more efficient depending on your needs.
However, you cannot use this function to map several existing 2D textures together into a new 2D array as you requested. The reason for that is simply because there is not enough control over GPU memory mapping in OpenGL, although this would be possible in theory at least in some cases (given that the size of each slice is dividable by the page size of your GPU's memory controller).
Texture Atlas
You don't necessarily need to create a new texture array with the exact set of 2D texture slices for each of your special use cases, but instead bind the large texture array containing all textures to a single (or multiple) sampler(s) and pass it along with an array of slice indices (selecting only your textures you need) to your shader.
This option is obviously only feasible if you are willing/able to change the shader source code.


text:
Q: Sklearn installation in OSX I have installed sklearn using the following commands (I tried both) but when I include it I receive the following error:
sudo port install py26-scikit-learn
or:
sudo port install py27-scikit-learn

The problem is:
>>> import sklearn
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named sklearn

You know what maybe wrong?
ANSWER: This worked for me:
sudo port select --set python python26

A: Make sure you are using the correct python binary. When you install scikits using macports, it becomes available in the macports version of python - not apple's. Use the port select command to change which python is the default when you simply call "python"


text:
Q: Bundle.putParcelable(String key, Parcelable value) and Intent.putExtra(String name, Parcelable value) Difference I have an object that implements Parcelable interface.
Case 1:
I have an Activity A and B. I would like to pass object from A to B using Intent.putExtra(String name, Parcelable value) so in Activity B when I get object and change some fields and get back to A the field of object remain the same. That mean after pass object via Intent.putExtra(String name, Parcelable value) a new instance of object will be created.
Case 2:
I have an Activity that contains a list of objects, also that activity has ViewPager with fragments. I create fragments and pass to it object Bundle.putParcelable(String key, Parcelable value) so when I get object and change some fields (int Fragment) the object that place in a list(in Activity) also changed. So that mean object hasn't been created just reference has been passed to fragment.
Can someone explain that strange behavior about Bundle.putParcelable(String key, Parcelable value) and Intent.putExtra(String name, Parcelable value)?

A: That's because Intent mechanism and the set/getArguments() of Fragment works differently.
When Activity contains Fragment it has direct reference to the Fragment, and setting a bundle on Fragment is simple set on the Fragment object, that's means that the Bundle object reference but the Activity is the same as the one in the Fragment. Actually you don't necessarily need this mechanism, as you're Activity probably controls the Fragments and knows their type, so you can just pass arguments by exposing a method on your Fragment. the benefit and the similarity to intent is that using provided set/getArguments() is retaining those arguments across fragment destroy and creation, those it uses Bundle and Parcelable, which are data that the system can stored outside your control.
But, Intent and Activity are different, Activity have no object reference to other Activities, and communicating must go through the system, and thus - unlike Activity/Fragment must be done with Parcelable/Bundle data that the system can serailze/deserialze.
When you sent an Intent to a different Activity your Parcelable goes through the system and get serailze/deserialze thus - you have a different Object reference in 2 differnt Activities.  this is not happening when you setArgument on Fragment as Activity/Fragment has no boundaries like different Activities.

A: This difference is not about putParcelable vs. putExtra.
An Activity which accepts an Intent or a Fragment which accepts arguments should not mutate incoming data because it may be passed by reference (as an optimisation), or may be recreated from Parcel (when it's necessary).
If you want to return some data from Activity, use startActivityForResult() and setResult(). If you want to return some data from Fragment, use getActivity() to get a host Activity from a Fragment and communicate with it.


text:
Q: React useReducer async data fetch I'am trying to fetch some data with new react useReducer API and stuck on stage where i need to fetch it async. I just don't know how :/
How to place data fetching in switch statement or it's not a way how it's should be done?
import React from 'react'

const ProfileContext = React.createContext()

const initialState = {
  data: false
}

let reducer = async (state, action) => {
  switch (action.type) {
    case 'unload':
      return initialState
    case 'reload':
      return { data: reloadProfile() } //how to do it???
  }
}

const reloadProfile = async () => {
  try {
    let profileData = await fetch('/profile')
    profileData = await profileData.json()

    return profileData
  } catch (error) {
    console.log(error)
  }
}

function ProfileContextProvider(props) {
  let [profile, profileR] = React.useReducer(reducer, initialState)

  return (
    <ProfileContext.Provider value={{ profile, profileR }}>
      {props.children}
    </ProfileContext.Provider>
  )
}

export { ProfileContext, ProfileContextProvider }

I was trying to do it like this, but it's not working with async ;(
let reducer = async (state, action) => {
  switch (action.type) {
    case 'unload':
      return initialState
    case 'reload': {
      return await { data: 2 }
    }
  }
}

A: This is an interesting case that the useReducer examples don't touch on. I don't think the reducer is the right place to load asynchronously. Coming from a Redux mindset, you would typically load the data elsewhere, either in a thunk, an observable (ex. redux-observable), or just in a lifecycle event like componentDidMount. With the new useReducer we could use the componentDidMount approach using useEffect. Your effect can be something like the following:
function ProfileContextProvider(props) {
  let [profile, profileR] = React.useReducer(reducer, initialState);

  useEffect(() => {
    reloadProfile().then((profileData) => {
      profileR({
        type: "profileReady",
        payload: profileData
      });
    });
  }, []); // The empty array causes this effect to only run on mount

  return (
    <ProfileContext.Provider value={{ profile, profileR }}>
      {props.children}
    </ProfileContext.Provider>
  );
}

Also, working example here: https://codesandbox.io/s/r4ml2x864m.
If you need to pass a prop or state through to your reloadProfile function, you could do so by adjusting the second argument to useEffect (the empty array in the example) so that it runs only when needed. You would need to either check against the previous value or implement some sort of cache to avoid fetching when unnecessary.
Update - Reload from child
If you want to be able to reload from a child component, there are a couple of ways you can do that. The first option is passing a callback to the child component that will trigger the dispatch. This can be done through the context provider or a component prop. Since you are using context provider already, here is an example of that method:
function ProfileContextProvider(props) {
  let [profile, profileR] = React.useReducer(reducer, initialState);

  const onReloadNeeded = useCallback(async () => {
    const profileData = await reloadProfile();
    profileR({
      type: "profileReady",
      payload: profileData
    });
  }, []); // The empty array causes this callback to only be created once per component instance

  useEffect(() => {
    onReloadNeeded();
  }, []); // The empty array causes this effect to only run on mount

  return (
    <ProfileContext.Provider value={{ onReloadNeeded, profile }}>
      {props.children}
    </ProfileContext.Provider>
  );
}

If you really want to use the dispatch function instead of an explicit callback, you can do so by wrapping the dispatch in a higher order function that handles the special actions that would have been handled by middleware in the Redux world. Here is an example of that. Notice that instead of passing profileR directly into the context provider, we pass the custom one that acts like a middleware, intercepting special actions that the reducer doesn't care about.
function ProfileContextProvider(props) {
  let [profile, profileR] = React.useReducer(reducer, initialState);

  const customDispatch= useCallback(async (action) => {
    switch (action.type) {
      case "reload": {
        const profileData = await reloadProfile();
        profileR({
          type: "profileReady",
          payload: profileData
        });
        break;
      }
      default:
        // Not a special case, dispatch the action
        profileR(action);
    }
  }, []); // The empty array causes this callback to only be created once per component instance

  return (
    <ProfileContext.Provider value={{ profile, profileR: customDispatch }}>
      {props.children}
    </ProfileContext.Provider>
  );
}

A: I wrapped the dispatch method with a layer to solve the asynchronous action problem.
Here is initial state. The loading key record the application current loading status, It's convenient when you want to show loading page when the application is fetching data from server.
{
  value: 0,
  loading: false
}

There are four kinds of actions.
function reducer(state, action) {
  switch (action.type) {
    case "click_async":
    case "click_sync":
      return { ...state, value: action.payload };
    case "loading_start":
      return { ...state, loading: true };
    case "loading_end":
      return { ...state, loading: false };
    default:
      throw new Error();
  }
}

function isPromise(obj) {
  return (
    !!obj &&
    (typeof obj === "object" || typeof obj === "function") &&
    typeof obj.then === "function"
  );
}

function wrapperDispatch(dispatch) {
  return function(action) {
    if (isPromise(action.payload)) {
      dispatch({ type: "loading_start" });
      action.payload.then(v => {
        dispatch({ type: action.type, payload: v });
        dispatch({ type: "loading_end" });
      });
    } else {
      dispatch(action);
    }
  };
}

Suppose there is an asynchronous method
async function asyncFetch(p) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(p);
    }, 1000);
  });
}

wrapperDispatch(dispatch)({
  type: "click_async",
  payload: asyncFetch(new Date().getTime())
});

The full example code is here:

https://codesandbox.io/s/13qnv8ml7q

A: It is a good practice to keep reducers pure. It will make useReducer more predictable and ease up testability. Subsequent approaches both combine async operations with pure reducers:
1. Fetch data before dispatch (simple)
Wrap the original dispatch with asyncDispatch and let context pass this function down:
const AppContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initState);
  const asyncDispatch = () => { // adjust args to your needs
    dispatch({ type: "loading" });
    fetchData().then(data => {
      dispatch({ type: "finished", payload: data });
    });
  };

  return (
    <AppContext.Provider value={{ state, dispatch: asyncDispatch }}>
      {children}
    </AppContext.Provider>
  );
  // Note: memoize the context value, if Provider gets re-rendered more often
};

const reducer = (state, { type, payload }) => {
  if (type === "loading") return { status: "loading" };
  if (type === "finished") return { status: "finished", data: payload };
  return state;
};

const initState = {
  status: "idle"
};

const AppContext = React.createContext();

const AppContextProvider = ({ children }) => {
  const [state, dispatch] = React.useReducer(reducer, initState);
  const asyncDispatch = () => { // adjust args to your needs
    dispatch({ type: "loading" });
    fetchData().then(data => {
      dispatch({ type: "finished", payload: data });
    });
  };

  return (
    <AppContext.Provider value={{ state, dispatch: asyncDispatch }}>
      {children}
    </AppContext.Provider>
  );
};

function App() {
  return (
    <AppContextProvider>
      <Child />
    </AppContextProvider>
  );
}

const Child = () => {
  const val = React.useContext(AppContext);
  const {
    state: { status, data },
    dispatch
  } = val;
  return (

Status: {status}

Data: {data || "-"}

      <button onClick={dispatch}>Fetch data</button>

  );
};

function fetchData() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(42);
    }, 2000);
  });
}

ReactDOM.render(<App />, document.getElementById("root"));

2. Use middleware for dispatch (generic)
dispatch might be enhanced with middlewares like redux-thunk, redux-observable, redux-saga for more flexibility and reusability. Or write your own one.
Let's say, we want to 1.) fetch async data with redux-thunk 2.) do some logging 3.) invoke dispatch with the final result. First define middlewares:
import thunk from "redux-thunk";
const middlewares = [thunk, logger]; // logger is our own implementation

Then write a custom useMiddlewareReducer Hook, which you can see here as useReducer bundled with additional middlewares, akin to Redux applyMiddleware:
const [state, dispatch] = useMiddlewareReducer(middlewares, reducer, initState);

Middlewares are passed as first argument, otherwise API is the same as useReducer. For the implementation, we take applyMiddleware source code and carry it over to React Hooks.

const middlewares = [ReduxThunk, logger];

const reducer = (state, { type, payload }) => {
  if (type === "loading") return { ...state, status: "loading" };
  if (type === "finished") return { status: "finished", data: payload };
  return state;
};

const initState = {
  status: "idle"
};

const AppContext = React.createContext();

const AppContextProvider = ({ children }) => {
  const [state, dispatch] = useMiddlewareReducer(
    middlewares,
    reducer,
    initState
  );
  return (
    <AppContext.Provider value={{ state, dispatch }}>
      {children}
    </AppContext.Provider>
  );
};

function App() {
  return (
    <AppContextProvider>
      <Child />
    </AppContextProvider>
  );
}

const Child = () => {
  const val = React.useContext(AppContext);
  const {
    state: { status, data },
    dispatch
  } = val;
  return (

Status: {status}

Data: {data || "-"}

      <button onClick={() => dispatch(fetchData())}>Fetch data</button>

  );
};

function fetchData() {
  return (dispatch, getState) => {
    dispatch({ type: "loading" });
    setTimeout(() => {
      // fake async loading
      dispatch({ type: "finished", payload: (getState().data || 0) + 42 });
    }, 2000);
  };
}

function logger({ getState }) {
  return next => action => {
    console.log("state:", JSON.stringify(getState()), "action:", JSON.stringify(action));
    return next(action);
  };
}

// same API as useReducer, with middlewares as first argument
function useMiddlewareReducer(
  middlewares,
  reducer,
  initState,
  initializer = s => s
) {
  const [state, setState] = React.useState(initializer(initState));
  const stateRef = React.useRef(state); // stores most recent state
  const dispatch = React.useMemo(
    () =>
      enhanceDispatch({
        getState: () => stateRef.current, // access most recent state
        stateDispatch: action => {
          stateRef.current = reducer(stateRef.current, action); // makes getState() possible
          setState(stateRef.current); // trigger re-render
          return action;
        }
      })(...middlewares),
    [middlewares, reducer]
  );

  return [state, dispatch];
}

//                                                         |  dispatch fn  |
// A middleware has type (dispatch, getState) => nextMw => action => action
function enhanceDispatch({ getState, stateDispatch }) {
  return (...middlewares) => {
    let dispatch;
    const middlewareAPI = {
      getState,
      dispatch: action => dispatch(action)
    };
    dispatch = middlewares
      .map(m => m(middlewareAPI))
      .reduceRight((next, mw) => mw(next), stateDispatch);
    return dispatch;
  };
}

ReactDOM.render(<App />, document.getElementById("root"));

Note: we store intermediate state in mutable refs - stateRef.current = reducer(...), so each middleware can access current, most recent state at the time of its invocation with getState.
To have the exact API as useReducer, you can create the Hook dynamically:
const useMiddlewareReducer = createUseMiddlewareReducer(middlewares); //init Hook
const MyComp = () => { // later on in several components
  // ...
  const [state, dispatch] = useMiddlewareReducer(reducer, initState);
}

const middlewares = [ReduxThunk, logger];

const reducer = (state, { type, payload }) => {
  if (type === "loading") return { ...state, status: "loading" };
  if (type === "finished") return { status: "finished", data: payload };
  return state;
};

const initState = {
  status: "idle"
};

const AppContext = React.createContext();

const useMiddlewareReducer = createUseMiddlewareReducer(middlewares);

const AppContextProvider = ({ children }) => {
  const [state, dispatch] = useMiddlewareReducer(
    reducer,
    initState
  );
  return (
    <AppContext.Provider value={{ state, dispatch }}>
      {children}
    </AppContext.Provider>
  );
};

function App() {
  return (
    <AppContextProvider>
      <Child />
    </AppContextProvider>
  );
}

const Child = () => {
  const val = React.useContext(AppContext);
  const {
    state: { status, data },
    dispatch
  } = val;
  return (

Status: {status}

Data: {data || "-"}

      <button onClick={() => dispatch(fetchData())}>Fetch data</button>

  );
};

function fetchData() {
  return (dispatch, getState) => {
    dispatch({ type: "loading" });
    setTimeout(() => {
      // fake async loading
      dispatch({ type: "finished", payload: (getState().data || 0) + 42 });
    }, 2000);
  };
}

function logger({ getState }) {
  return next => action => {
    console.log("state:", JSON.stringify(getState()), "action:", JSON.stringify(action));
    return next(action);
  };
}

function createUseMiddlewareReducer(middlewares) {
  return (reducer, initState, initializer = s => s) => {
    const [state, setState] = React.useState(initializer(initState));
    const stateRef = React.useRef(state); // stores most recent state
    const dispatch = React.useMemo(
      () =>
        enhanceDispatch({
          getState: () => stateRef.current, // access most recent state
          stateDispatch: action => {
            stateRef.current = reducer(stateRef.current, action); // makes getState() possible
            setState(stateRef.current); // trigger re-render
            return action;
          }
        })(...middlewares),
      [middlewares, reducer]
    );
    return [state, dispatch];
  }
}

//                                                         |  dispatch fn  |
// A middleware has type (dispatch, getState) => nextMw => action => action
function enhanceDispatch({ getState, stateDispatch }) {
  return (...middlewares) => {
    let dispatch;
    const middlewareAPI = {
      getState,
      dispatch: action => dispatch(action)
    };
    dispatch = middlewares
      .map(m => m(middlewareAPI))
      .reduceRight((next, mw) => mw(next), stateDispatch);
    return dispatch;
  };
}

ReactDOM.render(<App />, document.getElementById("root"));

More infos - external libraries: react-use, react-hooks-global-state, react-enhanced-reducer-hook

A: I wrote a very detailed explanation of the problem and possible solutions. Dan Abramov suggested Solution 3.
Note: The examples in the gist provide examples with file operations but the same approach could be implemented for data fetching.
https://gist.github.com/astoilkov/013c513e33fe95fa8846348038d8fe42

A: Update:
I've added another comment in the weblink below. It's a custom hook called useAsyncReducer based on the code below that uses the exact same signature as a normal useReducer.
function useAsyncReducer(reducer, initState) {
    const [state, setState] = useState(initState),
        dispatchState = async (action) => setState(await reducer(state, action));
    return [state, dispatchState];
}

async function reducer(state, action) {
    switch (action.type) {
        case 'switch1':
            // Do async code here
            return 'newState';
    }
}

function App() {
    const [state, dispatchState] = useAsyncReducer(reducer, 'initState');
    return <ExampleComponent dispatchState={dispatchState} />;
}

function ExampleComponent({ dispatchState }) {
    return <button onClick={() => dispatchState({ type: 'switch1' })}>button</button>;
}

Old solution:
I just posted this reply here and thought it may be good to post here as well in case it helps anyone.
My solution was to emulate useReducer using useState + an async function:
async function updateFunction(action) {
    switch (action.type) {
        case 'switch1':
            // Do async code here (access current state with 'action.state')
            action.setState('newState');
            break;
    }
}

function App() {
    const [state, setState] = useState(),
        callUpdateFunction = (vars) => updateFunction({ ...vars, state, setState });

    return <ExampleComponent callUpdateFunction={callUpdateFunction} />;
}

function ExampleComponent({ callUpdateFunction }) {
    return <button onClick={() => callUpdateFunction({ type: 'switch1' })} />
}

A: it is very simple
you can change state in useEffect after async Fuction result
define useState for result of fetch
const [resultFetch, setResultFetch] = useState(null);
and useEffect for listen to setResultFetch
after fetch async API call setResultFetch(result of response)
useEffect(() => {
if (resultFetch) {
  const user = resultFetch;
  dispatch({ type: AC_USER_LOGIN, userId: user.ID})

}}, [resultFetch])


text:
Q: Add Toolbar in eclipse rcp application I want to add toolbar in eclipse rcp application, i tried to write the code in fillCoolBar function in ActionBarAdvisor.java and also using extensions. But the extensions provided by other plugins is not aligned properly. My guess is that the names of various toolbarManager inside the toolbar is not proper.
Anyone can tell me how to add all the icons so that the extra icons added by other plugins and added by me are aligned properly?
Every time i restart or open a new work-space the icons spacing changes!
I have attached a image of the problem.

The code in fillCoolBar is as follows:
@Override
protected void fillCoolBar(ICoolBarManager coolBar){
        IToolBarManager fileToolbar1 = new ToolBarManager(SWT.WRAP);
        fileToolbar1.add(new Separator(IWorkbenchActionConstants.NEW_GROUP));
        fileToolbar1.add(newDropDownAction);
        fileToolbar1.add(new GroupMarker(IWorkbenchActionConstants.NEW_EXT));
        fileToolbar1.add(new GroupMarker(IWorkbenchActionConstants.SAVE_GROUP));
        fileToolbar1.add(saveFileAction);
        fileToolbar1.add(saveAllFilesAction);
        fileToolbar1.add(new GroupMarker(IWorkbenchActionConstants.SAVE_EXT));
        fileToolbar1.add(printAction);
        fileToolbar1.add(new GroupMarker(IWorkbenchActionConstants.PRINT_EXT));
        coolBar.add(fileToolbar1);
}

A: Figured it out.
Need to add CSS styling to it.
Take following steps:
1. Open plugin.xml
2. Add extension org.eclipse.e4.ui.css.swt.theme
   2.1 Add Theme to above extension.
      2.1.2 Basestyleurl is relative path to css file, like css/theme.css
      2.1.2 Give a id like plugin.theme [id can be anything]
      2.1.3 Fill rest of the fields
3. In extension org.eclipse.core.runtime.products , the one that has your product
   3.1 Add a property
      3.1.1 name: cssTheme [do not change]
      3.1.2 value: id given in step 2.1.2
   3.2 Add a property
      3.2.1 name: applicationCSSResources
      3.2.2 value: platform:/plugin/plugin.name/images/
[inside plugin i have images folder which has all essential images for my css, you can see images used by eclipse css theme in eclipse\plugins\org.eclipse.platform_4.3.0.v20130605-2000\images and the css used is inside css folder ]

And thats it !
Done :)


text:
Q: The principle amplitude of $\sqrt 2 \left [\cos\frac{5\pi}{3} +i\sin\frac{5\pi}{3}\right ]$ is I know that principe amplitude must lie between $-\pi and \pi$, but should I convert into? My guess was that since it's beyond $\pi$ I should simply subtract $\pi$ from it to get $\frac{2\pi}{3}$, but the answer is $\frac{-\pi}{3}$.

A: We have that by $z=\sqrt 2 \left [\cos\frac{5\pi}{3} +i\sin \frac{5\pi}{3}\right]$
$$|z|^2=z\cdot \bar z=\sqrt 2 \left [\cos\frac{5\pi}{3} +i\sin \frac{5\pi}{3}\right]\cdot \sqrt 2 \left [\cos\frac{5\pi}{3} -i\sin \frac{5\pi}{3}\right]=2$$
and since $\Re(z)>0$
$$\arg (z)=\arctan\left(\frac{\sin \frac{5\pi}{3}}{\cos \frac{5\pi}{3}}\right)=-\frac{\pi}{3}$$
indeed recall that $\arctan(x)$ returns values in the range $(-\pi/2,\pi/2)$.
Note also that since $\frac{5\pi}{3}-2\pi=-\frac{\pi}{3}$ the two values represent the same angle.


text:
Q: How to save current DOM with Ajax, jQuery and PhP? I have edited (appended some of my div's)in my page, now, I need to save all of it, and of course to replace old one.
DOM body example:

Save

111

222

saver.php file example:
<?php
$data = $_GET['data'];
$file = $_SERVER['DOCUMENT_ROOT'];
file_put_contents($file, $data);
echo'Saved!';

Something in this way.
How to save current dom via Ajax, jQuery, PhP?

A: i don't think it's good to save the DOM in DB..
you can post the dom with Ajax by getting the html of the body
$("body").html();
Example
jQuery(document).ready(function($) {
  $(document).on('click', '#save_dom', function(event) {
    $.ajax({
      url: "/saver.php",
      type: "POST",
      data: {
      Dom : $("body").html()
      }, success: function(response) {
      // do things if successed
      }
    });
  });

});

A: You can get the html of current page as a string using this code
$("html").html()

Now pass the string via ajax

The problem will be, this string will contain everything including the javascript, css etc. If you are interested in the html inside body or inside any other element, you can use
data:$("body").html()

OR
data:$("#wrapperElementId").html()


text:
Q: How to keep position of these tagHovers close to tags while scrolling and the tagHover has fixed position? https://plnkr.co/edit/PuP3f71kCjkqgjjMkgNS?p=preview | Also have a stackoverflow snippet below.
Without scrolling the tagHovers will display correctly:
The problem
I think the problem is because I have a fixed position set on the tagHovers tags-modal class. However I need the fixed position on that div so the tagHovers can break outside of the constraints of the .tags-container.
Is there another way to achieve this effect without having to restyle the tagHovers so they have to fit inside the tiny width size of the tags-column?
Correct position without scrolling

Once you scroll, position of the fixed tagHover breaks

However once I started scrolling, the tagHovers lose their relative position to the tag you hovered.

.tags-container which has an overflow-y: auto; To display scrolling.
Each tag has an associated tag-hover directive.
The tagHovers have this styling (So they can be displayed outside of the constraints of the tags-column.)
CSS
https://gist.github.com/leongaban/eb2988a1ff01ada78ea0f663fd0432a8
TagHover.html

Hover for: {{ tghov.tag.term }}

var app = angular.module('plunker', ['ui.bootstrap'])
.component('tagHover', {
//      templateUrl: 'tags_modal.html',
  template: `

Hover for: {{ tghov.tag.term }}

`,
  controllerAs: 'tghov',
  bindings : {
      tag: '<'
  }
})
.controller('TagsHoverController', function(){});

app.controller('MainCtrl', function($scope) {
});

app.component('myComponent', {
  bindings: {},
//  templateUrl: 'tags.html',
  template: `

Tags

{{ tag.term }}

              <tag-hover tag="tag"></tag-hover>

Tags Content

`,
  controllerAs: 'tgs',
  controller: TagsCtrl
});

TagsCtrl.$inject = [
    '$scope',
    '$uibModal'];

function TagsCtrl(
    $scope,
    $uibModal) {
    ///////////////////////////////////

    this.hello = "hello world";

    this.leaveTag = (tag) => tag.hoverDisplay = false;

    this.tagHover = (tag) => tag.hoverDisplay = true;

    this.tags = [
      { id:0, term: 'apple'},
      { id:1, term: 'butter'},
      { id:2, term: 'charlie'},
      { id:3, term: 'duff'},
      { id:4, term: 'edward'},
      { id:5, term: 'freddy'},
      { id:6, term: 'george'},
      { id:7, term: 'henry'},
      { id:8, term: 'ink'},
      { id:9, term: 'joker'},
      { id:10, term: 'kevin'},
      { id:11, term: 'leon'},
      { id:12, term: 'mary'},
      { id:13, term: 'nancy'},
      { id:14, term: 'olivia'},
      { id:15, term: 'preston'},
      { id:16, term: 'quincy'},
      { id:17, term: 'robyn'},
      { id:18, term: 'steven'},
      { id:19, term: 'teddy'},
      { id:17, term: 'ulysses'},
      { id:18, term: 'victor'},
      { id:19, term: 'winston'},
      { id:20, term: 'xavier'},
      { id:20, term: 'yvette'},
      { id:21, term: 'zander'}
    ];
}
/* Put your css in here */

body {
  font-family: Arial, sans-serif;
}

.tags-hover-container {
    float: left;
    position: fixed;
    z-index: 101;
    left: 240px;
    margin-top: 40px;
    width: 200px;
    height: auto;
}

.tags-column {
  z-index: 1;
  float: left;
  position: relative;
  overflow-y: auto;
  margin-top: 70px;
  max-width: 230px;
  min-width: 230px;
  height: calc(100% - 165px);
}

.tags-column li {
  list-style: none;
}

.tags-container {
  overflow-y: auto;
  height: 320px;
}

.tag-container-container { float: left; position: relative; width: 100%; }

.tag-container { float: left; position: relative; }

.tags-content {
  float: left;
  background: #f0f0f0;
}

.tags-box {
  float: left;
  padding: 20px;
  width: 320px;
  height: 640px;
  background: #4169E1;
}

.tags-box h2 {
  color: #fff;
}

.tag {
  margin: 0 10px 10px 0;
  padding: 9px 10px;
  width: auto;
  color: #fff;
  background: #3D3D3D;
  border-radius: 4px;
  cursor: pointer;
  clear: both;
}

.tag:hover {
  background: #656565;
}

.tags-modal {
  float: left;
  position: fixed;
  z-index: 101;
  left: 100px;
  margin-top: -20px;
  padding: 10px;
  width: 200px;
  height: auto;
  color: white;
  background: blue;
  border-radius: 4px;
}

.tags-modal:before {
    position: absolute;
    top: -8px;
    left: 26px;
    z-index: 99;
    content: '';
    display: block;
    height: 0; width: 0;
    border-bottom: 8px solid blue;
    border-left: 8px solid transparent;
    border-right: 8px solid transparent;
}
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>

    <link href="style.css" rel="stylesheet" />

    <my-component></my-component>

A: Finally! Yeah there is no CSS solution to this, I had to figure out the current mouse y position and use ng-style to updated the styling on the fly.
TickersPanelComponent
this.hoverTicker = (event, ticker) => {
    MousePosition.set(event);
    const mouseY = MousePosition.current.y;
    ticker.pos = { top: `${mouseY}px` };
    ticker.hoverDisplay = true;
};

TickersPanel markup (contains tagHover component with ticker passed in)

            {{ ticker.short }}

            {{ ticker.ticker }}

    <ticker-hover ticker="ticker"></ticker-hover>

MousePosition Factory
const set = (e) => {
    current.x = e.pageX;
    current.y = e.pageY;
}

Finally tagHover markup

^ tkhov is the controllerAs this


text:
Q: php code have 2 output in same php interpreter using two different HTTP server I am writing a code in which I have 2 files index.php and register.php.
index.php contains the code for html form which is given below:
<form action="register.php" method="POST">
            <fieldset>
                <legend>Personal Information</legend>

                First Name: <input type="text" name="fname">

                Last Name: <input type="text" name="lname">

                <input type="submit" name="submit" value="Submit">
            </fieldset>
</form>

register.php have the following code:
    <?php

//if(isset($_POST['fname']))
{
    $f_name= $_POST['fname'];
}

//if(isset($_POST['lname']))
{
    $l_name = $_POST['lname'];
}

echo $f_name;
echo "

";
echo $l_name;

?>

I've written the code in PhpStorm and I also have Xampp installed in my windows 10 installed system.
I have set 'htdocs' directory of xampp as 'apache_http_server' in 'D:\' drive of my system and also create PhpStorm project in the sub directory of   'apache_http_server' so that I can run my php project using Xampp and PhpStorm IDE. I also set the php innterpreter supplied with Xampp as the default interpreter of PhpStorm so in both case my code uses same interpreter (PHP Version 7.0.4).
Now the problem is whenever I run this project using Xampp it runs without any kind of error and notice. but if I run the same project using PhpStorm IDE using its inbuilt httpserver on port 63342 its gives me following notice as o/p:
Notice: Undefined index: fname in D:\practice\apache_http_server\my_projects\login_form\register.php on line 5

Notice: Undefined index: lname in D:\practice\apache_http_server\my_projects\login_form\register.php on line 10

I also tried to solve this notice by using if(isset()) as per another answers on stackoverflow but it leads to the undefined variable error.
So why this happens ? where is problem occurs? Am I missed to make change in any configuration file? if yes than what changes need or where?
The o/p screenshots using Xampp server and PhpStorm are as follows:

*

*Using Xampp the final O/p:

*O/P with notice by PhpStorm's http server:

A: you've got different PHP configurations on the two servers,
run phpinfo() on both servers and fix the differences.

A: Try
echo $_SERVER['DOCUMENT_ROOT'];     //check if the root of the website is the same on both servers

if(!$_SERVER['REQUEST_METHOD']) {
    die("Something went REALLY wrong!!!")    //reinstall your server conf.
}
if(!$_SERVER['REQUEST_METHOD'] !== 'POST') {
    die("We're not getting this request from POST. abort");
}

if(!$_POST) {
    die("We're not receiving any data from post.");
} elseif(!$_POST['submit']) {
    die("PHP thinks the form wasn't actually submitted");
} else {
    if($_POST['fname']) {
        //work with your data
    } else {
        echo "
There\'s a problem. We're not getting fname from the form
";
    }
    ...
    ...
}

I don't have any experience with PHPStorm, but perhaps there could be a problem with the include_path of the PHPStorm built-in server? And more importantly. Are you including something from that include_path?

A: It seems that the problem is in configuration in http server. If you have installed Xampp than you can set the apache server of Xampp as the default http server. You can find step by step guide for integrating Xampp with PhpStorm in following link (the link is from official vendor of PhpStorm):
https://confluence.jetbrains.com/display/PhpStorm/Installing+and+Configuring+XAMPP+with+PhpStorm+IDE


text:
Q: JPA equal method: Differences between passing ParameterExpression and Object I've written the following piece of code (being cb a CriteriaBuilder instance):
String someString = "someValue";
Predicate p = cb.equal(
    somePath,
    cb.parameter(String.class, "someParameter"));
// TODO create query, bind someParameter to someString

But the following does the job as well:
String someString = "someValue";
Predicate p = cb.equal(
    somePath,
    someString);

Besides type checking, is there any other difference? When the JPA provider parses the query, is performance the same?

A: Since you are creating both queries dynamically using Criteria there should be little difference.  The best would be to use a name query using JPQL, this will avoid any parsing and prepare costs.


text:
Q: Weird behaviour when removeItemAtPath and copyItemAtPath How to make sure removeItemAtPath is completed before executing the copyItemAtPath function?
if ([[NSFileManager defaultManager] fileExistsAtPath:newDocpath]){
    //removing file
    if (![[NSFileManager defaultManager] removeItemAtPath:newDocpath error:&deleteError]){
        NSLog(@"Could not remove old files. Error:%@",deleteError);
    }
}

[[NSFileManager defaultManager] copyItemAtPath: pathToPDF toPath: newDocpath error: &copyError]

Is there a possibility of items not remove or copied since I'm placing the above-mentioned functions in a for loop?

A: removeItemAtPath works quasi synchronously. From the documentation

Return Value
YES if the item was removed successfully or if URL was nil. Returns NO if an error occurred. If the delegate stops the operation for a file, this method returns YES. However, if the delegate stops the operation for a directory, this method returns NO.

A: Basically removeItemAtPath:error:
**Removes the file or directory at the specified path.
First I start from fileExistsAtPath:isDirectory:

Returns a Boolean value that indicates whether a file or directory
  exists at a specified path. The isDirectory out parameter indicates
  whether the path points to a directory or a regular file.

Returns

YES if a file at the specified path exists, or NO if the file's does
  not exist or its existence could not be determined.

Then
removeItemAtPath:error:

Removes the file or directory at the specified path.

What does it return?

It returns YES if the item was removed successfully or if path was
  nil. Returns NO if an error occurred. If the delegate stops the
  operation for a file, this method returns YES. However, if the
  delegate stops the operation for a directory, this method returns NO.


text:
Q: Java HashMap> losing set elements after they're added The purpose of the following code is to take in a title from one book at a time, split it into keywords (anything separated by a space) and map the resulting keywords into a HashMap containing the keyword as the index and a set of integers (representing the position of the book in an ArrayList arrayOfReferences).
Set<Integer> toAdd = new HashSet<Integer>();
for (String keyword : addTitle.split(" ")) {
    toAdd.clear();
    if (!searchMap.containsKey(keyword.toLowerCase())) {
        if (!toAdd.contains(arrayOfReferences.indexOf(newBook))) {
            toAdd.add(arrayOfReferences.indexOf(newBook));
            searchMap.put(keyword.toLowerCase(), toAdd);
            System.out.println("New flag: " + keyword + " " + searchMap.get(keyword.toLowerCase()));
        }
    }
    else
    {
        for (Integer addNum : searchMap.get(keyword.toLowerCase())) {
            toAdd.add(addNum);
        }

        System.out.println("Before: " + keyword + " " + toAdd);
        if (!toAdd.contains(arrayOfReferences.indexOf(newBook))) {
            toAdd.add(arrayOfReferences.indexOf(newBook));
            searchMap.put(keyword.toLowerCase(), toAdd);
        }
        System.out.println("After: " + keyword + " " + searchMap.get(keyword.toLowerCase()));
    }
}

Currently the code adds the respective indicies to the hashmap, adds the additional positions to the list and then loses the previous values in the list. I'm still very new to Java so the problem could be staring me right in the face, however I need a fresh pair of eyes on it.
Any help is greatly appreaciated!

A: toAdd is a "reference" to some collection (Set) in java heap. Every and each loop you have same reference to same collection - and modify data behind it (replace it). Instead, I believe, you expect to create new references to new java objects in java heap.
To achive it, instead of
- toAdd.clear();

You should
+ toAdd = new HashSet<Integer>();

A: You are defining you Set in line1:
Set<Integer> toAdd = new HashSet<Integer>();

And in each loop you are clearing that set (line2 and 3):
for (String keyword : addTitle.split(" ")) {
    toAdd.clear();

This will modify your already added Set.
I would suggest to create a new Set for each iteration. It's a small change of your code:
for (String keyword : addTitle.split(" ")) { // now the first line of code
    Set<Integer> toAdd = new HashSet<Integer>(); // moved inside the loop
    // toAdd.clear(); - not necessary anymore


text:
Q: Contact syncing is not working for some contacts using iCloud I've verified that at least some of my contacts are not properly syncing between my iPhone running iOS 5.1 and my Mac running OSX 10.7.3 (both the latest OS versions currently available).
Here, you can see that the contact named "Android Standup" is available on my iPhone but not available on my Mac:

I have iCloud set up to sync Contacts on both devices, and both are using the same iCloud account:

The "Android Standup" contact is only available on the phone.  It's not available on iCloud.com or on my mac.
However, I verified that contact sync IS WORKING for some contacts. I just created a new "Test Contact 1" on my phone, and it appeared almost immediately in my Mac's Address Book.
Why are some of my contacts (such as the Android Standup contact) not syncing to iCloud?


text:
Q: Fetch all the id attribute of the form together I have a form and and have 10 input tags in it.Each have different id attributes..I want to fetch and print all the id's at a time..can you please help me to solve this problem

A: This should work for you:
var ids = [];
$('.your-form input').each(function(){
    ids.push(this.id);
});
console.log(ids.join(', '));

Here it is working - http://jsfiddle.net/cy7wA/1/

A: The nicest way to do this is with $.fn.map, $.fn.get and Array.prototype.join:
var ids = $('#form input').map(function() {
    return this.id
}).get().join(', ');

This will get a nice list of ids without any unnecessary commas or what have you.

A: $('#form_id').find('input').each(function(){
    console.log($(this).attr('id'));
});

A: Try like this:
$('#myForm :input').each(function ()
{
   Console.log('ID: ' + $(this).attr('id'));
});

Or
$ids = $('#myform input[id]').map(function() {
  return this.id;
}).get();

A: Please have a look at http://jsfiddle.net/2dJAN/62/
$(':input').each(function(){
  alert($(this).attr('id'));
});

A: Quick answer: you can easily use the jQuery "serialize" function to quickly grab all the elements on the form and put them into a key/value array:
function getVals()
{
    var myform = document.getElementById("formfoo");
    var mydata = myform.serialize();
    var myhtml = "";
    for ( key in mydata )
    {
        myhtml += "KEY IS: " + key + " VAL IS: " + mydata[key] + "<br />";
    }
    document.getElementById("mytestdiv").innerHTML = myhtml;
    return true;
}

It's a bit more code than the other examples, but I like having a single object to work with.


text:
Q: REACT - Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead const [username, setUsername] = useState(null);

useEffect(async () => {
if (user) {
  const ref = doc(db, "users", `${user.uid}`);
  const snap = await getDoc(ref);
  if (snap.exists()) {
    console.log(snap.data() + "---data---");
    setUsername(snap.data().username);
  }
}

I can see the data in console. But in setUsername, its showing the error.
I am using firestore.


text:
Q: Parallel sieve of eratosthenes produces wrong output based on number of threads This is the approach I'm using for parallelization:

*

*p = Process ID, N = total number of processes, n = input size

*Each process is assigned n/N numbers, ranging from index p*n/N to (p+1)*n/N-1.

*When process 0 finds a prime number, all its multiples are marked in parallel.

*Finally, each process counts the number of primes in its assigned range and adds it to the global count.

Using C++/OpenMP for parallelization. Before calling the function, I set the maximum number of threads with omp_set_num_threads().
// p is thread ID, N is total number of threads, n is the array size
#define LOWER_BOUND(p, N, n) p == 0 ? 2 : (p * n / N)
#define UPPER_BOUND(p, N, n) p == (N - 1) ? (n - 1) : (p + 1) * (n / N) - 1

size_t parallel_soe(std::vector<std::atomic<bool>>& A) {
    size_t n = A.size();
    size_t sqrt_n = sqrt(n);
    for (size_t i = 2; i <= sqrt_n; i++) {
        if (A[i] == true) continue;
        #pragma omp parallel
        {
            uint16_t p = omp_get_thread_num();
            uint16_t N = omp_get_num_threads();
            size_t lower_bound = LOWER_BOUND(p, N, n);
            size_t upper_bound = UPPER_BOUND(p, N, n);
            size_t smallest_multiple = std::max(i * i, lower_bound);
            size_t remainder = smallest_multiple % i;
            if (remainder) smallest_multiple += i - remainder;
            for (size_t j = smallest_multiple; j <= upper_bound; j += i)
                A[j] = true;
        }
    }
    // Count number of primes
    size_t prime_count = 0;
    #pragma omp parallel
    {
        uint16_t p = omp_get_thread_num();
        uint16_t N = omp_get_num_threads();
        size_t lower_bound = LOWER_BOUND(p, N, n);
        size_t upper_bound = UPPER_BOUND(p, N, n);
        size_t count = 0;
        for (size_t i = lower_bound; i <= upper_bound; i++)
            if (A[i] == false)
                count++;
        #pragma omp atomic
        prime_count += count;
    }
    return prime_count;
}

The value returned by the function is correct when maximum threads are set to 2, 4, 8, 10, and 16, but not for 6, 12, and 14. I'm running it on a 4 core Intel i5.
This is my output log:
Finding primes under: 10000
================================
[2-parallel]  Found 1229 primes in 542 microseconds
[4-parallel]  Found 1229 primes in 3173 microseconds
[6-parallel]  Found 1228 primes in 2353 microseconds
[8-parallel]  Found 1229 primes in 3600 microseconds
[10-parallel] Found 1229 primes in 3227 microseconds
[12-parallel] Found 1227 primes in 2778 microseconds
[14-parallel] Found 1226 primes in 2248 microseconds
[16-parallel] Found 1229 primes in 2320 microseconds

Finding primes under: 100000
================================
[2-parallel]  Found 9592 primes in 5186 microseconds
[4-parallel]  Found 9592 primes in 10351 microseconds
[6-parallel]  Found 9591 primes in 9859 microseconds
[8-parallel]  Found 9592 primes in 8500 microseconds
[10-parallel] Found 9592 primes in 12294 microseconds
[12-parallel] Found 9591 primes in 8300 microseconds
[14-parallel] Found 9582 primes in 9252 microseconds
[16-parallel] Found 9592 primes in 8557 microseconds

Finding primes under: 1000000
================================
[2-parallel]  Found 78498 primes in 36091 microseconds
[4-parallel]  Found 78498 primes in 43570 microseconds
[6-parallel]  Found 78498 primes in 48176 microseconds
[8-parallel]  Found 78498 primes in 44201 microseconds
[10-parallel] Found 78498 primes in 43645 microseconds
[12-parallel] Found 78498 primes in 49175 microseconds
[14-parallel] Found 78494 primes in 47411 microseconds
[16-parallel] Found 78498 primes in 53602 microseconds

A: I figured it out. It had nothing to do with parallel execution, I just had a calculation error when computing the bounds.
This is the correct formula for computing lower bound:
#define LOWER_BOUND(p, N, n) p == 0 ? 2 : p * (n / N)

Notice the paranthesis around n/n.


text:
Q: User.Identity.Name = "" (anonymous) but Windows auth is enabled? I created an ASP.NET MVC app with the following override via a custom AuthorizeAttribute implementation:
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    return base.AuthorizeCore(httpContext);
}

However, within this method, httpContext.User.Identity.Name is "".  I need to get a handle to the current Identity.Name so I can retrieve some data based on that value. I have the following entries in web.config:
<authentication mode="Windows"  />
<authorization>
    <deny users="?"/>
</authorization>

At minimum, I think that the MVC site should prompt me for credentials with the configuration above, right?

A: I was able to get the network user ID with the following alternate code:
Request.LogonUserIdentity.Name

Are there any implications or impacts of using this code as opposed to:
httpContext.User.Identity.Name


text:
Q: What is wrong with my solution for calculate $\sum_{n=0}^\infty {3n\choose n}\left({2\over27}\right)^{n}$?
problem calculate $\sum_{n=0}^\infty {3n\choose n}\left({2\over27}\right)^{n}$

*firstly, I KNOW that this problem is duplicated. but I want to know what is wrong with my attempt.
my attempt
$$x=\sum_{n=0}^\infty{3n\choose n}{z^{2n+1}\over 2n+1}$$
satisfies $$x^3-x+z=0$$ within the convergence radius $|z|\leq{2\over3\sqrt{3}}$ by Lagrange Inversion theorem.
Thus $${dx\over dz}=\sum_{n=0}^\infty {3n\choose n}z^{2n}={1\over 1-3x^2}$$ and for $z={\sqrt2\over3\sqrt3}$, $x={\sqrt2\over\sqrt3}$ satisfies equation $x^3-x+z=0$.
i.e. $$\sum_{n=0}^\infty {3n\choose n}\left({2\over27}\right)^{n}={1\over 1-3x^2}=-1(???)$$

A: Just to turn @ThomasAndrews's observation into an answer, for the given value of $z$, $x$ may be equal to any of $\sqrt{\frac23},\,-\frac{1}{\sqrt{2}}-\frac{1}{\sqrt{6}},\,\frac{1}{\sqrt{2}}-\frac{1}{\sqrt{6}}$.To avoid a paradox we need $|x|<\frac{1}{\sqrt{3}}$, so we take the third root. In other words, the sum is$$\frac{1}{1-3\left(\frac{1}{\sqrt{2}}-\frac{1}{\sqrt{6}}\right)^2}=\frac{\sqrt{3}+1}{2}\approx1.366.$$


text:
Q: Address data extraction from text via asp.net (vb.net) I have address data that is surrounded by random text. Is there a way to extract this data either with a call to a web service or some vb.net function?
example: 1111 S WILSON ROAD APT B8 CITY STATE 55555 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

A: If your random data is always 0's, try doing a string.Replace to get rid of the 0's and then a Trim() to get rid of extra spaces. You could also use Regex to accomplish the same task to get rid of 0's.
If your random data is truly random, is there a way you can introduce some delimiters in at the beginning and end of your address? For instance, you could have:
#1111 S WILSON ROAD APT B8 CITY STATE 55555# 0 0 0 0 0 0 0 0 0 0 0 0

This way, you could the SubString function to extract just the data you need using those special characters as delimiters.
-D

A: from your example it looks like your data is delimited with 4 numbers in the beginning and 5 numbers in the end so you can use regex as
\d{4}(?<Address>.*)\d{5}

and look for Address group name in match

A: Thanks guys for the responses.. I was not fully informed of the test data (.. of course). What I ended up doing was tossing the text over to the Yahoo PlaceFinder API. If it did not return an exact match, I was alert the user and set the address as best I could. Again thanks for your help.


text:
Q: Error deploying or retrieving source I have newly created a project then created a random LWC page and right click on it and deploy and it is giving me below error

The file or directory that you tried to deploy or retrieve isn't in a
package directory that's specified in your sfdx-project.json file. Add
this location to your "packageDirectories" value, or deploy or
retrieve a different file or directory. For details about
sfdx-project.json, see:
https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_ws_config.htm
You can run SFDX: Deploy Source to Org only on a source file or
directory.

Below is my sfdx-project.json
{
  "packageDirectories": [
    {
      "path": "force-app",
      "default": true
    }
  ],
  "name": "myproject",
  "namespace": "",
  "sfdcLoginUrl": "https://login.salesforce.com",
  "sourceApiVersion": "55.0"
}

A: The issue you are seeing is related to the recently published version v55.4.0 of the Salesforce Extension for VS Code.
Multiple users are impacted by this.You can follow https://github.com/forcedotcom/salesforcedx-vscode/issues/4261 for updates.
The workaround for now, would be to downgrade the "Salesforce CLI Integration" extension version.
I will keep this thread updated as I have more inputs from our concerned Salesforce product development team.
Update:
As a fix, v55.4.1 of the Salesforce Extension for VS Code has been published.  See the release notes here: https://github.com/forcedotcom/salesforcedx-vscode/releases/tag/v55.4.1


text:
Q: What is the pdf of sum of two complex non-zero Gaussian random variable $(x,y)$ and one Gassian mixture random variable $w$? I have three complex random variable $x,y,w$.
The pdf of $x$ is ${f_x} \sim CN({\mu _x},\sigma _x^2)$ with mean ${\mu _x}$ and variance $\sigma _x^2$.
The pdf of $y$ is ${f_y} \sim CN({\mu _y},\sigma _y^2)$ with mean ${\mu _y}$ and variance $\sigma _y^2$.
The random variable $w$ is a mixture of $M$ Gaussian component with corresponding mean  ${{\mu _{w,i}}}$ and variance ${\sigma _{w,i}^2}$ where,
${f_w} \sim \sum\limits_{i = 1}^M {{\varepsilon _i}CN({\mu _{w,i}},\sigma _{w,i}^2)} $
where $\sum\limits_{i = 1}^M {{\varepsilon _i} = 1} $
Now, for a constant $a,b,c\in R$
$z=ax+by+cw$,
What will be the pdf of  $f_z$? How should I express the mean ${\mu _z}$ and variance $\sigma _z^2$? Thank you.


text:
Q: Using Tesseract to OCR matchTemplate Regions of Interest (ROI) This is my very first attempt at using Python. I normally use .NET, but to identify shapes in documents have turned to Python and OpenCV for image processing.
I am using OpenCV TemplateMatching (cv2.matchTemplate) to discover Regions of Interest (ROI) in my documents.
This works well. The template matches the ROI's and rectangles are placed, identifying the matches.
The ROI's in my images contain text which I also need to OCR and extract.  I am trying to do this with Tesseract, but I think I am approaching it wrongly, based upon my results.
My process is this:

*

*Run cv2.matchTemplate

*Loop through matched ROI's

*Add rectangle info. to image

*Pass rectangle info. to Tesseract

*Add text returned from tesseract to image

*Write the final image

In the image below, you can see the matched regions (which are fine), but you can see that the text in the ROI doesn't match the text from tesseract (bottom right of ROI).
Please could someone take a look and advise where I am going wrong?
import cv2
import numpy as np
import pytesseract
import imutils

img_rgb = cv2.imread('images/pd2.png')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)

template = cv2.imread('images/matchMe.png', 0)
w, h = template.shape[::-1]

res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.45
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
    roi = img_rgb[pt, (pt[0] + w, pt[1] + h)]
    config = "-l eng --oem 1 --psm 7"
    text = pytesseract.image_to_string(roi, config=config)
    print(text)
    cv2.putText(img_rgb, text, (pt[0] + w, pt[1] + h),
                cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 255), 3)

cv2.imwrite('images/results.png', img_rgb)

A: There were two issues in your code:
1. You were modifying image (drawing rect) before OCR.
2. roi was not properly constructed.
img_rgb = cv2.imread('tess.png')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)

template = cv2.imread('matchMe.png', 0)
w, h = template.shape[::-1]

res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.45
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
    roi = img_rgb[pt[1]:pt[1] + h, pt[0]: pt[0] + w]
    config = "-l eng --oem 1 --psm 7"
    text = pytesseract.image_to_string(roi, config=config)
    print(text)
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
    cv2.putText(img_rgb, text, (pt[0] + w, pt[1] + h),
                cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 255), 3)

cv2.imwrite('results.png', img_rgb)

You might still have to feed tesseract even properly filtered image for any meaningful recognition. Hope this helps.


text:
Q: Multiple row database into array (dropPin) PROBLEM
As mentioned above. I have an example of code as shown below.
$mapItems = array(
    array("id" => 1, "title" => "map pin 1", "xcoord" => "420", "ycoord" => "120"),
    array("id" => 2, "title" => "map pin 2", "xcoord" => "429", "ycoord" => "129"),
    array("id" => 3, "title" => "map pin 3", "xcoord" => "329", "ycoord" => "329")
);

The problem is, I want to take the data from database and put into an array as shown above. I've tried and I don't know how it works. Below are some of my code:
$mapItems = array();
$qry='SELECT l.loc_x, l.loc_y, m.member_name '.
     'FROM location l '.
     'JOIN member m ON m.member_id = l.member_id '.
     "WHERE l.map_id = '$id'";
$result=mysqli_query($con, $qry);
$tempNo=1;
while($rows=mysqli_fetch_array($result)){
    $mapItems["id"] = $tempNo;
    $mapItems["title"] = $rows['member_name'];
    $mapItems["xcoord"] = $rows['loc_x'];
    $mapItems["ycoord"] = $rows['loc_y'];
    $tempNo++;
}

I want to make my bottom code, looks exactly like the top code but by reading the data from database. Thanks in advance.
SOLUTION
Finally I manage to get solution for my problem.
$qry='SELECT l.loc_x, l.loc_y, m.member_name '.
     'FROM location l '.
     'JOIN member m ON m.member_id = l.member_id '.
     "WHERE l.map_id = '$id'";
$result=mysqli_query($con, $qry);
$i=1;
$mapItems = array();
while($rows=mysqli_fetch_array($result)){
    $loc = array("id"     => $i,
                 "title"  => $rows['member_name'],
                 "xcoord" => $rows['loc_x'],
                 "ycoord" => $rows['loc_y']);
    $mapItems[] = $loc;
    $i++;
}

Reference: dropPin

A: Try this
$i = 0; //array index
while($rows=mysqli_fetch_array($result)){
  $mapItems[$i]["id"] = $tempNo;
  $mapItems[$i]["title"] = $rows['member_name'];
  $mapItems[$i]["xcoord"] = $rows['loc_x'];
  $mapItems[$i]["ycoord"] = $rows['loc_y'];
  $tempNo++;
  $i++;
}

A: i hope this will help you
$qry="SELECT l.loc_x, l.loc_y, m.member_name FROM location l JOIN member m ON m.member_id = l.member_id WHERE l.map_id = '$id'";
$result=mysqli_query($con, $qry);

$mapItems = array();
$tempNo=1;
while($rows=mysqli_fetch_array($result)) {
   $mapItems[] = $row;
}
print_r($mapItems);


text:
Q: Ag Grid headerClass overrides numericColumn type I am trying to set AG Grid header style using headerClass:"ag-grid-total-header" but it overrides type: 'numericColumn' - it shows the header cell value left aligned.
columnDef:
{ headerName: 'Total', field: 'Total', width: 125, sortable: true, type: 'numericColumn', headerClass:"ag-grid-total-header"}

CSS:
.ag-grid-total-header {
  text-align:right; /* It does not work */
  background-color: red; /* This works */
}

Is there any way to apply header style while preserving numericColumn type?
stackblitz:
https://stackblitz.com/edit/angular-ag-grid-angular-huk1fp?file=app/my-grid-application/my-grid-application.component.ts
EDIT:
It works if I add headerComponentParams. However, the sorting does not work if I add headerComponentParams.
headerComponentParams : {
      template:
        '
' +
        '' +
        '
'
      }

A: The header class that is used for a numeric type header is ag-numeric-header. So, apply both your class ag-grid-total-header and ag-numeric-header classes to your column. Change your column definition to:
  {
    headerName: "Price",
    field: "price",
    type: "numericColumn",
    headerClass: ["my-header-class", 'ag-numeric-header']
  },

Demo.