text:
Q: P/Invoke offreg.dll functions - Access violation on subsequent calls it is my first question here so if I violate some written or unwritten rules, please bear with me.
I am trying to P/Invoke functions from the offreg.dll in C#. To get a feel of how they work, I wrote this very basic console application:
using System.Text;
using System.Runtime.InteropServices;

namespace ConsoleApp2
{

    class Program
    {
        [DllImport("C:\\TEMP\\offreg-x64.dll", EntryPoint = "ORGetVersion", CharSet = CharSet.Unicode)]
        public static extern void ORGetVersion(out uint MajorVersion, out uint MinorVersion);

        [DllImport("C:\\TEMP\\offreg-x64.dll", EntryPoint = "OROpenHive", CharSet = CharSet.Unicode)]
        public static extern int OROpenHive(string HivePath, out IntPtr rootKeyHandle);

        [DllImport("C:\\TEMP\\offreg-x64.dll", EntryPoint = "OROpenKey", CharSet = CharSet.Unicode)]
        public static extern int OROpenKey(IntPtr KeyHandle, string SubKeyName, out IntPtr SubKeyHandle);

        [DllImport("C:\\TEMP\\offreg-x64.dll", EntryPoint = "ORCloseKey", CharSet = CharSet.Unicode)]
        public static extern int ORCloseKey(IntPtr KeyHandle);

        [DllImport("C:\\TEMP\\offreg-x64.dll", EntryPoint = "OREnumKey", CharSet = CharSet.Unicode)]
        public static extern int OREnumKey( IntPtr KeyHandle,
                                            uint Index,
                                            [MarshalAs(UnmanagedType.LPWStr)]
                                            StringBuilder SubKeyName,
                                            ref uint SubKeyLen,
                                            [MarshalAs(UnmanagedType.LPWStr)]
                                            StringBuilder ClassName,
                                            ref uint ClassLen,
                                            out uint LastWriteTime
            );

        [DllImport("C:\\TEMP\\offreg-x64.dll", EntryPoint = "ORQueryInfoKey", CharSet = CharSet.Unicode)]
        public static extern int ORQueryInfoKey(IntPtr KeyHandle,
                                            [MarshalAs(UnmanagedType.LPWStr)]
                                            StringBuilder ClassName,
                                            ref uint ClassLen,
                                            out uint NumKeys,
                                            out uint MaxKeyLen,
                                            out uint NumVals,
                                            out uint MaxValLen,
                                            out IntPtr SecDesc,
                                            out uint LastWrite
            );

        [DllImport("C:\\TEMP\\offreg-x64.dll", EntryPoint = "ORCloseHive", CharSet = CharSet.Unicode)]
        public static extern int ORCloseHive(IntPtr rootKeyHandle);

        static void Main(string[] args)
        {
            Console.WriteLine("Hello World");
            int res = 0;    // result of every OR function call
            IntPtr h;       // hive (or root key) handle

            // Get DLL version
            uint ver1 = 0;
            uint ver2 = 0;
            Program.ORGetVersion(out ver1, out ver2);
            Console.WriteLine("Library Version: " + ver1.ToString() + "." + ver2.ToString());
            // end get version

            // Open hive
            res = Program.OROpenHive(@"C:\TEMP\NTUSER.DAT", out h);
            Console.WriteLine("Open Result: " + res.ToString());
            Console.WriteLine("Open Handle: " + h.ToString());
            // end oppen hive

            // prepare variables for key operations
            StringBuilder ClassName = new StringBuilder(256);
            uint ClassLen = 256;
            StringBuilder SubKeyName = new StringBuilder(256);
            uint SubKeyLen = 256;
            uint NKeys = 0;
            uint maxKeyLen = 0;
            uint NVals = 0;
            uint maxValLen = 0;
            IntPtr SecDesc = IntPtr.Zero;
            uint LastWrite = 0;
            uint SubKeyIndex = 0;   // we are asking for the first subkey
            // end prepare variables

            // Query root key information
            res = Program.ORQueryInfoKey(h, ClassName, ref ClassLen, out NKeys, out maxKeyLen, out NVals, out maxValLen, out SecDesc, out LastWrite);
            Console.WriteLine("Query Result: " + res.ToString());
            Console.WriteLine("Query Class Name: " + ClassName.ToString());
            Console.WriteLine("Query Class Length: " + ClassLen.ToString());
            Console.WriteLine("Query Num Subkeys: " + NKeys.ToString());
            Console.WriteLine("Query Max Subkey Len: " + maxKeyLen.ToString());
            Console.WriteLine("Query Num Values: " + NVals.ToString());
            Console.WriteLine("Query Max Value Len: " + maxValLen.ToString());
            Console.WriteLine("Query Last Write: " + LastWrite.ToString());
            // end query root key information

            // enum first subkey
            res = Program.OREnumKey(h, SubKeyIndex, SubKeyName, ref SubKeyLen, ClassName, ref ClassLen, out LastWrite);
            Console.WriteLine("Enum Result: " + res.ToString());
            Console.WriteLine("Enum Builder: " + SubKeyName.ToString());
            Console.WriteLine("Enum Length: " + SubKeyLen.ToString());
            Console.WriteLine("Enum Capacity: " + SubKeyName.Capacity.ToString());
            // end enum first subkey

            // close hive
            res = Program.ORCloseHive(h);
            Console.WriteLine("Close Result: " + res.ToString());
            // end close hive

            // sayonara
            Console.WriteLine("Press [ENTER] to exit");
            Console.ReadLine();
        }
    }
}

When I run this code as shown above, it will run the ORQueryInfoKey block but give me an Access Violation on attempt to call OREnumKey.
If I comment out the call to ORQueryInfoKey, it runs OK and returns correct info on the first subkey (but I obviously don't get the info about the number of subkeys and values, or their length).
If I comment out the call to OREnumKey, the Access Violation still happens on ORCloseHive.
If I swap the ORQueryInfoKey block and the OREnumKey block, it doesn't throw any exception but the Query call returns 234 (MORE_DATA_AVAILABLE) which means the ClassLen is too short.
If I swap the ORQueryInfoKey block and the OREnumKey block and set ClassLen to 1 before the second call, it runs OK, returns correct data but throws an Access Violation on ORCloseHive.
So to summarize this, after a successfull call to ORQueryInfoKey it appears that the next call using the handle h will produce an Access Violation.
What am I missing?
Any insight is greatly appreciated!

A: The ORQueryInfoKey was missing a lot of parameters, FILETIME is equivalent to a .NET long (64-bit, and DateTime has a built-in function to convert it), and you must call the API with strings twice: first you pass a null pointer and the API will give you the length, then you allocate the length, call the API again (and convert the allocated pointer back to a string, free the buffer), something like this (I've added a loop so you can see how it works in a loop):
[DllImport(@"C:\Program Files (x86)\Windows Kits\10\Redist\offreg\x64\offreg.dll", CharSet = CharSet.Unicode)]
public static extern int OREnumKey(IntPtr Handle,
                                    int dwIndex,
                                    IntPtr lpName,
                                    ref int lpcName,
                                    IntPtr lpClass,
                                    ref int lpcClass,
                                    out long lpftLastWriteTime);

[DllImport(@"C:\Program Files (x86)\Windows Kits\10\Redist\offreg\x64\offreg.dll", CharSet = CharSet.Unicode)]
public static extern int ORQueryInfoKey(
                            IntPtr Handle,
                            IntPtr lpClass,
                            ref int lpcClass,
                            out int lpcSubKeys,
                            out int lpcMaxSubKeyLen,
                            out int lpcMaxClassLen,
                            out int lpcValues,
                            out int lpcMaxValueNameLen,
                            out int lpcMaxValueLen,
                            out int lpcbSecurityDescriptor,
                            out long lpftLastWriteTime);

static void Main()
{
    const int ERROR_MORE_DATA = 234;
    const int ERROR_NO_MORE_ITEMS = 259;

    var res = OROpenHive(@"c:\TEMP\NTUSER.DAT", out var h);
    if (res != 0)
        throw new Win32Exception(res);

    try
    {
        var clsLen = 0;
        var clsPtr = IntPtr.Zero;
        res = ORQueryInfoKey(h, IntPtr.Zero, ref clsLen, out var subKeys, out var maxSubKeyLen, out var maxClassLen, out var values, out var maxValueNameLen, out var maxValueLen, out var securityDescriptor, out var lastWriteTime);
        if (res == ERROR_MORE_DATA)
        {
            clsPtr = Marshal.AllocHGlobal(clsLen);
            try
            {
                res = ORQueryInfoKey(h, clsPtr, ref clsLen, out subKeys, out maxSubKeyLen, out maxClassLen, out values, out maxValueNameLen, out maxValueLen, out securityDescriptor, out lastWriteTime);
                if (res == 0)
                {
                    var cls = Marshal.PtrToStringUni(clsPtr);
                    Console.WriteLine("Class: " + cls);
                }
            }
            finally
            {
                Marshal.FreeHGlobal(clsPtr);
            }
        }

        if (res != 0)
            throw new Win32Exception(res);

        var nameLen = 0;
        var i = 0;
        var namePtr = IntPtr.Zero;

        do
        {
            clsLen = 0;
            nameLen = 0;
            res = OREnumKey(h, i, IntPtr.Zero, ref nameLen, IntPtr.Zero, ref clsLen, out lastWriteTime);
            if (res == ERROR_NO_MORE_ITEMS)
                break;

            if (res == ERROR_MORE_DATA)
            {
                if (nameLen > 0)
                {
                    namePtr = Marshal.AllocHGlobal(nameLen);
                }

                if (clsLen > 0)
                {
                    clsPtr = Marshal.AllocHGlobal(clsLen);
                }

                try
                {
                    res = OREnumKey(h, i, namePtr, ref nameLen, clsPtr, ref clsLen, out lastWriteTime);
                    if (res == 0)
                    {
                        Console.WriteLine("LastWriteTime: " + DateTime.FromFileTime(lastWriteTime));

                        if (namePtr != IntPtr.Zero)
                        {
                            var name = Marshal.PtrToStringUni(namePtr);
                            Console.WriteLine("Name: " + name);
                        }

                        if (clsPtr != IntPtr.Zero)
                        {
                            var cls = Marshal.PtrToStringUni(clsPtr);
                            Console.WriteLine("Class: " + cls);
                        }
                    }
                }
                finally
                {
                    if (namePtr != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(namePtr);
                        namePtr = IntPtr.Zero;
                    }

                    if (clsPtr != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(clsPtr);
                        clsPtr = IntPtr.Zero;
                    }
                }
            }

            if (res != 0)
                throw new Win32Exception(res);

            i++;
        }
        while (true);
    }
    finally
    {
        ORCloseHive(h);
    }
}


text:
Q: html in mail doesn't shows up. Inline images does I wrote following piece of code:
[SOLVED]
I've tried everything and this piece of code seems fine for me.
Regards,
Andy

A: Many email clients ignore background colors specified in the  tag.
Use a container table instead:

            hello world!

            footer

Yes, it's a lot of extra HTML code. Building HTML emails that perform well in the majority of email clients can be painful.
Some helpful references:

*

*http://www.campaignmonitor.com/resources/will-it-work/guidelines/

*http://www.campaignmonitor.com/css/

A: rgb(0, 0, 0) is not supported in older email clients use instead regular background colors.
Also, for email clients is better to use tables instead of div tags.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL N-M relationship gets the most producible products with the least material I create a difficult scenario to increase my troubleshooting skills.
In my example I want to make as many different products as possible with the same (as little different) materials.
I create the Table like this:
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Table_test](
    [ID] [int] NOT NULL,
    [REFProduct] [int] NOT NULL,
    [REFMaterial] [int] NOT NULL,
 CONSTRAINT [PK_Table_test] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

I filled it with Random Data while REFProduct and REFMaterial 0< int <30
I managed to determine the SQL to get the Products with the fewest Materials:
SELECT COUNT(REFMaterial) AS ProductMaterials
FROM Table_test
GROUP BY REFProduct
ORDER BY ProductMaterials

Sample Datas:
|ID|REFMaterial|REFProdukt|
|--|-----------|----------|
|1 |6          |13        |
|--|-----------|----------|
|2 |5          |28        |
|--|-----------|----------|
|3 |2          |24        |
|--|-----------|----------|
|4 |29         |14        |
|--|-----------|----------|
|5 |18         |15        |
|--|-----------|----------|
|6 |8          |16        |
|--|-----------|----------|
|7 |2          |26        |
|--|-----------|----------|
|8 |11         |23        |
|--|-----------|----------|
|9 |3          |25        |
|--|-----------|----------|
|10|7          |27        |
|--|-----------|----------|
|11|4          |4         |
|--|-----------|----------|
|12|2          |25        |
|--|-----------|----------|
|13|12         |4         |
|--|-----------|----------|
|14|8          |11        |
|--|-----------|----------|
|15|5          |27        |
|--|-----------|----------|
|16|26         |22        |
|--|-----------|----------|
|17|16         |26        |
|--|-----------|----------|
|18|29         |19        |
|--|-----------|----------|
|19|4          |1         |
|--|-----------|----------|
|20|9          |26        |

Now I struggle to create a corresponding SQL command or to determine the next steps.
I use SQL Server but every other SQL database or Excel would be fine to solve it.
Edit:
Expected Result:
list of n materials, where as many material lists of the products as possible are completely covered . The material list of each product is the Table_test table
n= variable input
If I want to make as many different products as possible from 3 materials, I give as input the number 3 and as output i get the 3 materials , with which I make a maximum of different products
With these materials from the result i can determine the Products in a second SQL as parameter, like this :
SELECT REFProduct FROM Table_test where REFMaterialin ([ResultList of materials])

Edit 2
Excepted Output:
|REFMaterial|
|-----------|
|6          |
|-----------|
|5          |
|-----------|
|24         |
|-----------|


text:
Q: MongoDb Schema Structure I have a collection named 'Category' with this structure:
{
 "CategoryID" : 1,
 "ParentID" : 0,
"Name" : "Sample Cat"
}

And another collection which will be using this category
{
 "DocumentID" : 1,
 "CategoryID" : 1,
 "DocumentName" : "Doc XPXSAX"
}

The problem with this design is that when is that I cannot use it to make a live search which will show me the document as
Doc XPXSAX found in Sample Cat"(along with category name without using join)
Also I cannot embed the documents inside the Category collection (as an array in one of the fields) as I am expecting the number of documents to go up to 50k.
What alternate schema design will enable me to incorporate an efficient search functionality without using hacks imitating joins ?
Thanks.

A: If you dislike an application-level join, why not embed the categories inside the document documents?
{
    "DocumentID" : 1,
    "category" : {
        "ID" : 1,
        "Name" : "Sample Cat",
        "ParentID" : 0
    },
    "DocumentName" : "Doc XPXSAX"
}

Keep the category information you need for display in the document document. Information you need more rarely can live in the category document and be found with a second query or application-level join.


text:
Q: Edit column data at SQL I am trying to update my retrieved data as described below:
  UPDATE vw_public_task_priority
  SET task_state = REPLACE(task_state, 'NULL', 'DONE')

After I execute it I get the next error:

Msg 4406, Level 16, State 1, Line 41
Update or insert of view or function 'vw_public_task_priority'
  failed because it contains a derived or constant field.

Can you please advice to me what I'm doing wrong + there is a possibility to update the results at new column instead of edit "task_state" data?
Thanks!

A: Try this
UPDATE vw_public_task_priority SET task_state = 'DONE' where task_state is null


text:
Q: How to enable QCA6390 Bluetooth firmware in Linux kernel? Context
I'm having difficulty getting the kernel to load the necessary Bluetooth firmware for my XPS 9310. My model has the AX500 connectivity chip, which uses the QCA6390.
Users of both Ubuntu and Arch have reported Bluetooth working with this model, however, I'm having difficulty finding the right kernel configuration necessary to get this working on NixOS.
My Configuration
I have enabled the following kernel configuration params with the following patch added to boot.kernelPatches in my nix configuration:
    # Extra config required for Bluetooth.
    {
      name = "enable-qca6390-bluetooth";
      patch = null;
      extraConfig = ''
        BT_QCA m
        BT_HCIBTUSB m
        BT_HCIBTUSB_AUTOSUSPEND y
        BT_HCIUART m
        BT_HCIUART_QCA y
      '';
    }

I'm loading the related modules like so:
  boot.kernelModules = [ "bluetooth" "btqca" "btusb" "hci_qca" "hci_uart" ];

It should go without saying that I have:
  hardware.bluetooth.enable = true;

I also have:
  hardware.enableRedistributableFirmware = true;

which, enables the firmwareLinuxNonfree package, which in turn adds the firmware from the linux-firmware repo, which in turn includes the necessary QCA firmware.
The Problem
This firmware can be observed being loaded in the dmesg output of two separate Ubuntu users here and here, both of which report working Bluetooth. However, I am unable to observe it being loaded in mine.
For reference, here is the dmesg output from a user with working Bluetooth:
[ 2.349008] Bluetooth: Core ver 2.22
[ 2.349019] Bluetooth: HCI device and connection manager initialized
[ 2.349023] Bluetooth: HCI socket layer initialized
[ 2.349024] Bluetooth: L2CAP socket layer initialized
[ 2.349028] Bluetooth: SCO socket layer initialized
[ 2.394642] Bluetooth: HCI UART driver ver 2.3
[ 2.394644] Bluetooth: HCI UART protocol H4 registered
[ 2.394645] Bluetooth: HCI UART protocol BCSP registered
[ 2.394654] Bluetooth: HCI UART protocol LL registered
[ 2.394655] Bluetooth: HCI UART protocol ATH3K registered
[ 2.394660] Bluetooth: HCI UART protocol Three-wire (H5) registered
[ 2.394702] Bluetooth: HCI UART protocol Intel registered
[ 2.394734] Bluetooth: HCI UART protocol Broadcom registered
[ 2.394742] Bluetooth: HCI UART protocol QCA registered
[ 2.394743] Bluetooth: HCI UART protocol AG6XX registered
[ 2.394748] Bluetooth: HCI UART protocol Marvell registered
[ 2.416321] Bluetooth: hci0: setting up ROME/QCA6390
[ 2.420348] Bluetooth: hci0: Frame reassembly failed (-84)
[ 2.444937] Modules linked in: snd_pcm qrtr ns snd_seq_midi snd_seq_midi_event ath11k_pci(+) mhi snd_rawmidi ath11k hci_uart qmi_helpers btqca i915(+) snd_seq btrtl uvcvideo mac80211 snd_seq_device btbcm btintel snd_timer videobuf2_vmalloc dell_wmi drm_kms_helper input_leds videobuf2_memops dell_smbios videobuf2_v4l2 cec dcdbas snd efi_pstore serio_raw rc_core videobuf2_common hid_sensor_als i2c_algo_bit hid_sensor_trigger ucsi_acpi(+) cfg80211 fb_sys_fops industrialio_triggered_buffer processor_thermal_device typec_ucsi dell_wmi_descriptor kfifo_buf hid_sensor_iio_common intel_rapl_common soundcore industrialio wmi_bmof videodev mei_me libarc4 syscopyarea cros_ec_ishtp 8250_dw mc hid_multitouch sysfillrect mei cros_ec sysimgblt intel_soc_dts_iosf typec mac_hid bluetooth ecdh_generic ecc int3403_thermal int340x_thermal_zone acpi_pad intel_hid acpi_tad int3400_thermal acpi_thermal_rel sparse_keymap sch_fq_codel parport_pc ppdev drm lp parport ip_tables x_tables autofs4 hid_sensor_hub
[ 2.756645] Bluetooth: hci0: QCA Product ID :0x00000010
[ 2.756647] Bluetooth: hci0: QCA SOC Version :0x400a0200
[ 2.756647] Bluetooth: hci0: QCA ROM Version :0x00000200
[ 2.756648] Bluetooth: hci0: QCA Patch Version:0x00000d2b
[ 2.756650] Bluetooth: hci0: QCA controller version 0x02000200
[ 2.756651] Bluetooth: hci0: QCA Downloading qca/htbtfw20.tlv
[ 3.584055] Bluetooth: hci0: QCA Downloading qca/htnv20.bin
[ 3.777754] Bluetooth: hci0: QCA setup on UART is completed
[ 3.998318] Bluetooth: BNEP (Ethernet Emulation) ver 1.3
[ 3.998319] Bluetooth: BNEP filters: protocol multicast
[ 3.998321] Bluetooth: BNEP socket layer initialized
[ 14.108234] Bluetooth: RFCOMM TTY layer initialized
[ 14.108238] Bluetooth: RFCOMM socket layer initialized
[ 14.108242] Bluetooth: RFCOMM ver 1.11

And here is the output of dmesg | grep -i blue on my machine:
[    4.363188] Bluetooth: Core ver 2.22
[    4.363199] Bluetooth: HCI device and connection manager initialized
[    4.363201] Bluetooth: HCI socket layer initialized
[    4.363203] Bluetooth: L2CAP socket layer initialized
[    4.363205] Bluetooth: SCO socket layer initialized
[    4.379230] Bluetooth: HCI UART driver ver 2.3
[    4.379231] Bluetooth: HCI UART protocol H4 registered
[    4.379232] Bluetooth: HCI UART protocol BCSP registered
[    4.379238] Bluetooth: HCI UART protocol LL registered
[    4.379256] Bluetooth: HCI UART protocol Intel registered
[    4.379260] Bluetooth: HCI UART protocol QCA registered
[   20.090546] Bluetooth: BNEP (Ethernet Emulation) ver 1.3
[   20.090553] Bluetooth: BNEP socket layer initialized

As you can see, my Bluetooth setup never performs this step or any of the following hci0 steps:
[ 2.416321] Bluetooth: hci0: setting up ROME/QCA6390

Unsurprisingly, as a result, I'm unable to enable Bluetooth in my GNOME settings GUI, and bluetoothctl shows nothing:
$ bluetoothctl list

$ bluetoothctl devices
No default controller available

Questions
From my understanding, the firmware should be automatically loaded in the case that BT_QCA is enabled and the firmware exists, both of which should be happening as a result of my aforementioned nix configuration.
Is this assumption correct?
Am I missing a necessary step required to trigger the hci0 lines shown above?
Any advice or ideas on how to progress would be greatly appreciated!
System info
$ nix-shell -p nix-info --run "nix-info -m"
 - system: `"x86_64-linux"`
 - host os: `Linux 5.10.2, NixOS, 21.03pre259798.84917aa00bf (Okapi)`
 - multi-user?: `yes`
 - sandbox: `yes`
 - version: `nix-env (Nix) 2.3.10`
 - channels(root): `"nixos-21.03pre259798.84917aa00bf, home-manager-20.09"`
 - nixpkgs: `/nix/var/nix/profiles/per-user/root/channels/nixos`

$ lsmod | grep -i bt
btusb                  57344  0
btrtl                  24576  1 btusb
btbcm                  20480  1 btusb
btintel                28672  2 hci_uart,btusb
btqca                  20480  1 hci_uart
bluetooth             589824  13 btrtl,btqca,btintel,hci_uart,btbcm,bnep,btusb
usbcore               270336  5 xhci_hcd,usbhid,uvcvideo,btusb,xhci_pci

$ lspci
00:00.0 Host bridge: Intel Corporation 11th Gen Core Processor Host Bridge/DRAM Registers (rev 01)
00:02.0 VGA compatible controller: Intel Corporation UHD Graphics (rev 01)
00:04.0 Signal processing controller: Intel Corporation Device 9a03 (rev 01)
00:06.0 PCI bridge: Intel Corporation 11th Gen Core Processor PCIe Controller (rev 01)
00:07.0 PCI bridge: Intel Corporation Tiger Lake-LP Thunderbolt PCI Express Root Port #0 (rev 01)
00:07.2 PCI bridge: Intel Corporation Tiger Lake-LP Thunderbolt PCI Express Root Port #2 (rev 01)
00:0a.0 Signal processing controller: Intel Corporation Device 9a0d (rev 01)
00:0d.0 USB controller: Intel Corporation Tiger Lake-LP Thunderbolt USB Controller (rev 01)
00:0d.2 USB controller: Intel Corporation Tiger Lake-LP Thunderbolt NHI #0 (rev 01)
00:0d.3 USB controller: Intel Corporation Tiger Lake-LP Thunderbolt NHI #1 (rev 01)
00:12.0 Serial controller: Intel Corporation Tiger Lake-LP Integrated Sensor Hub (rev 20)
00:14.0 USB controller: Intel Corporation Tiger Lake-LP USB 3.2 Gen 2x1 xHCI Host Controller (rev 20)
00:14.2 RAM memory: Intel Corporation Tiger Lake-LP Shared SRAM (rev 20)
00:15.0 Serial bus controller [0c80]: Intel Corporation Tiger Lake-LP Serial IO I2C Controller #0 (rev 20)
00:15.1 Serial bus controller [0c80]: Intel Corporation Tiger Lake-LP Serial IO I2C Controller #1 (rev 20)
00:16.0 Communication controller: Intel Corporation Tiger Lake-LP Management Engine Interface (rev 20)
00:19.0 Serial bus controller [0c80]: Intel Corporation Tiger Lake-LP Serial IO I2C Controller #4 (rev 20)
00:19.1 Serial bus controller [0c80]: Intel Corporation Tiger Lake-LP Serial IO I2C Controller #5 (rev 20)
00:1c.0 PCI bridge: Intel Corporation Device a0b8 (rev 20)
00:1d.0 PCI bridge: Intel Corporation Device a0b3 (rev 20)
00:1e.0 Communication controller: Intel Corporation Tiger Lake-LP Serial IO UART Controller #0 (rev 20)
00:1f.0 ISA bridge: Intel Corporation Tiger Lake-LP LPC Controller (rev 20)
00:1f.3 Multimedia audio controller: Intel Corporation Tiger Lake-LP Smart Sound Technology Audio Controller (rev 20)
00:1f.4 SMBus: Intel Corporation Tiger Lake-LP SMBus Controller (rev 20)
00:1f.5 Serial bus controller [0c80]: Intel Corporation Tiger Lake-LP SPI Controller (rev 20)
01:00.0 Non-Volatile memory controller: Toshiba Corporation Device 011a
56:00.0 Unassigned class [ff00]: Qualcomm Device 1101
57:00.0 Unassigned class [ff00]: Realtek Semiconductor Co., Ltd. RTS5260 PCI Express Card Reader (rev 01)

$ lsusb
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 003: ID 0c45:672a Microdia Integrated_Webcam_HD
Bus 003 Device 002: ID 27c6:533c Shenzhen Goodix Technology Co.,Ltd. FingerPrint
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Further Reference
In case they help as a reference, here are the links to the default kernel configurations for NixOS, Debian and Arch.
Here is my WIP PR aimed at adding support for the XPS 9310 to NixOS that will include this work.
Here is my previous post to the NixOS discourse forum asking for help with this issue, yet to receive a response as of writing this.

SOLVED
We have since solved this in the nixos/nixos-hardware github repo and upstreamed the necessary kernel config patches to nixpkgs itself. Use the module in the nixos-hardware repo here to get up and running with nixos on the xps 9310 easily.

A: Have a look into the BIOS. In the main menu click Connection. There's a section called Wireless Device Enable. Make sure the Bluetooth checkbox is checked. Sometimes it's the obvious stuff ¯\_(ツ)_/¯.
I have a Dell XPS 15 9500 with the same Bluetooth hardware (Qualcomm  QCA6390 / AX500-DBS).
I had the exact same symptom as you describe and was 'sure' that I did not disable BT via BIOS. Until I looked, to verify. To my surprise I actually did disable it.
With BT being disabled in the BIOS I found the dmesg | grep -i blue output to match yours (precisely!). I was missing for example these two critical log lines:
Bluetooth: hci0: QCA Downloading qca/htbtfw20.tlv
Bluetooth: hci0: QCA Downloading qca/htnv20.bin

bluetoothctl devices was showing No default controller available. Which is how I found your question here.


text:
Q: jQuery Event when all selects inside a div have changed If a have several selects how can i run a jquery function when all selects have changed and not just the first i choose?
I have this html:

<select name="talla1" class="talla1">
    <option value="none">Select</option>
    <option value="S">S</option>
    <option value="M">M</option>
    <option value="L">L</option>
    <option value="XL">XL</option>
    <option value="XXL">XXL</option>
</select>

<select name="talla2" class="talla1">
    <option value="none">Select</option>
    <option value="S">S</option>
    <option value="M">M</option>
    <option value="L">L</option>
    <option value="XL">XL</option>
    <option value="XXL">XXL</option>
</select>

<select name="talla3" class="talla1">
    <option value="none">Select</option>
    <option value="S">S</option>
    <option value="M">M</option>
    <option value="L">L</option>
    <option value="XL">XL</option>
    <option value="XXL">XXL</option>
</select>

With this jQuery function:
$('.container select').change(function() {
    alert('changed');
});

but this fires the alert only when change the first select and i want to do it once all selects inside the container have changed its value and i when return to default in any select run other function, was i clear enough?
thanks in advance

A: You can keep a record of changes on each select and use that value to see if all 3 are changed.

var eventArray = [];
$('.container select').on('change',function(){
    indexOfSelect = $('.container select').index( $(this) );
    if($.inArray(indexOfSelect, eventArray) == -1)
        eventArray.push( '' + indexOfSelect + '' );
    if(eventArray.length == $('.container select').length)
        alert('All changed');
});

  <select name="talla1" class="talla1">
    <option value="none">Select</option>
    <option value="S">S</option>
    <option value="M">M</option>
    <option value="L">L</option>
    <option value="XL">XL</option>
    <option value="XXL">XXL</option>
  </select>

  <select name="talla2" class="talla1">
    <option value="none">Select</option>
    <option value="S">S</option>
    <option value="M">M</option>
    <option value="L">L</option>
    <option value="XL">XL</option>
    <option value="XXL">XXL</option>
  </select>

  <select name="talla3" class="talla1">
    <option value="none">Select</option>
    <option value="S">S</option>
    <option value="M">M</option>
    <option value="L">L</option>
    <option value="XL">XL</option>
    <option value="XXL">XXL</option>
  </select>

A: when a class is added to multiple elements its event is binded to every element and the class works for all. simply give a common class to all your select on which you want to fire a event

this works for all the select which has class talla1

A: Change your jquery code to this :
$(".talla1").each(function(){
   $(this).change(function(){
     //alert('called');
    $(this).addClass('active');
    if($(".container").find('.active').length == $(".talla1").length){
            alert('finish');
       }
   });

});

Here is the working fiddle.
Do tell if it worked.
Happy Coding.


text:
Q: как переделать  в JPA аннотации из хибернейт конфигурации У меня есть такая xml-конфигурация
        <map name="inbound" table="env_inbound" lazy="true">
            <key>
                <column name="environment_id" sql-type="bigint"/>
            </key>
            <map-key-many-to-many class="com.core.model.jpa.system.System">
                <column name="systems" sql-type="bigint"/>
            </map-key-many-to-many>
            <many-to-many class="com.core.model.jpa.server.ServerHB" lazy="proxy">
                <column name="servers" sql-type="bigint"/>
            </many-to-many>
        </map>

Подскажите как переделать данный фрагмент на JPA аннотации. Пробовал делать вот так
    @JsonSerialize(using = ExportMapSerializer.class)
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "env_inbound",
            joinColumns = @JoinColumn(name = "systems", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "servers", referencedColumnName = "id"))
    @MapKey(name = "environment_id")
    private Map<System, Server> inbound = Maps.newHashMapWithExpectedSize(10);

но в итоге лишь ошибки о том что нет поля в родительском классе класса ServerHB - Server помещенного в аннотацию @MapKey (его там быть точно не должно). Сам текст ошибки:
Map key property not found: com.core.model.jpa.server.Server.environment_id


text:
Q: An issue with PyTorch's Event I am using the following github code and it is initiating this error
class musterModel(nn.Module):
    def __init__(self, args):
        super(musterModel, self).__init__()

        self.model = pedMondel(args.frames, vel=args.velocity, seg=args.seg, h3d=args.H3D, n_clss=3)
        ckpt = torch.load(args.ckpt, map_location=args.device)
        #ckpt = torch.load(args.ckpt, map_location=torch.device('cpu'))
        self.model.load_state_dict(ckpt)
        self.model = self.model.to(args.device)
        #self.model = self.model.to(torch.device('cuda:0'))
        self.model.eval()

str_t = torch.cuda.Event(enable_timing=True)
end_t = torch.cuda.Event(enable_timing=True)

  str_t.record()
        if args.last2:
            x = x[:, :, -(args.lastn+30):] if args.forecast else x[:, :, -args.lastn:]
            pred = model(x.contiguous().half(), f.half(), v.half())
        else:
            pred = model(x.half(), f.half(), v.half())

        end_t.record()

        torch.cuda.synchronize()
        timimg.append(str_t.elapsed_time(end_t))

Error:
Traceback (most recent call last):
  File "/home/lambda-quad2/H line 308, in <module>
    main(args)
  File "/home/lambda-quad2/H.py", line 166, in main
    str_t = torch.cuda.Event(enable_timing=True)
  File "/home/lambda-quad2/anaconda3/lib/python3.9/site-packages/torch/cuda/streams.py", line 164, in __new__
    return super(Event, cls).__new__(
TypeError: object.__new__() takes exactly one argument (the type to instantiate)

Any help what to do in this case? The str_t and end_t are defined in the above code


text:
Q: Run code for x amount of time To preface, I am on a Unix (linux) system using gcc.
What I am stuck on is how to accurately implement a way to run a section of code for a certain amount of time.
Here is an example of something I have been working with:
struct timeb start, check;
int64_t duration = 10000;
int64_t elapsed = 0;

ftime(&start);

while ( elapsed < duration ) {
    // do a set of tasks
    ftime(&check);
    elapsed += ((check.time - start.time) * 1000)  + (check.millitm - start.millitm);
}

I was thinking this would have carried on for 10000ms or 10 seconds, but it didn't, almost instantly.  I was basing this off other questions such as How to get the time elapsed in C in milliseconds? (Windows) . But then I thought that if upon the first call of ftime, the struct is time = 1, millitm = 999 and on the second call time = 2, millitm = 01 it would be calculating the elapsed time as being 1002 milliseconds.  Is there something I am missing?
Also the suggestions in the various stackoverflow questions, ftime() and gettimeofday(), are listed as deprecated or legacy.
I believe I could convert the start time into milliseconds, and the check time into millseconds, then subtract start from check. But milliseconds since the epoch requires 42 bits and I'm trying to keep everything in the loop as efficient as possible.
What approach could I take towards this?

A: Code is incorrect calculating elapsed time.
// elapsed += ((check.time - start.time) * 1000)  + (check.millitm - start.millitm);
elapsed = ((check.time - start.time) * (int64_t)1000)  + (check.millitm - start.millitm);

There is some concern about check.millitm - start.millitm.  On systems with struct timeb *tp, it can be expected that the millitm will be promoted to int before subtraction occurs.  So the difference will be in the range [-1000 ... 1000].
       struct timeb {
           time_t         time;
           unsigned short millitm;
           short          timezone;
           short          dstflag;
       };

IMO, more robust code would handle ms conversion in a separate helper function.  This matches OP's "I believe I could convert the start time into milliseconds, and the check time into millseconds, then subtract start from check."
int64_t timeb_to_ms(struct timeb *t) {
  return (int64_t)t->time * 1000 + t->millitm;
}

struct timeb start, check;
ftime(&start);
int64_t start_ms = timeb_to_ms(&start);

int64_t duration = 10000 /* ms */;
int64_t elapsed = 0;

while (elapsed < duration) {
  // do a set of tasks
  struct timeb check;
  ftime(&check);
  elapsed = timeb_to_ms(&check) - start_ms;
}

A: If you want efficiency, let the system send you a signal when a timer expires.
Traditionally, you can set a timer with a resolution in seconds with the alarm(2) syscall.
The system then sends you a SIGALRM when the timer expires. The default disposition of that signal is to terminate.
If you handle the signal, you can longjmp(2) from the handler to another place.
I don't think it gets much more efficient than SIGALRM + longjmp (with an asynchronous timer, your code basically runs undisturbed without having to do any extra checks or calls).
Below is an example for you:
#define _XOPEN_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <setjmp.h>

static jmp_buf jmpbuf;

void hndlr();
void loop();
int main(){

    /*sisv_signal handlers get reset after a signal is caught and handled*/
    if(SIG_ERR==sysv_signal(SIGALRM,hndlr)){
        perror("couldn't set SIGALRM handler");
        return 1;
    }

    /*the handler will jump you back here*/
    setjmp(jmpbuf);

    if(0>alarm(3/*seconds*/)){
        perror("couldn't set alarm");
        return 1;
    }

    loop();

    return 0;
}

void hndlr(){
    puts("Caught SIGALRM");
    puts("RESET");
    longjmp(jmpbuf,1);
}

void loop(){
    int i;
    for(i=0;  ; i++){
        //print each 100-milionth iteration
        if(0==i%100000000){
            printf("%d\n", i);
        }
    }
}

If alarm(2) isn't enough, you can use timer_create(2) as EOF suggests.


text:
Q: MySQL: is a TRIGGER ON DELETE triggered by DROP PARTITION? In my MySQL base, with engine=innodb and 1 file by partition, I have:

*

*Table 1 partitioned by date

*Table 2 that counts the entries of table 1 by date

Table 1 is filled by a software, and Table 2 is filled by triggers on Table 1, as below:
CREATE TRIGGER tgi_table1 AFTER INSERT ON table1 FOR EACH ROW INSERT INTO table2 values ( NEW.date, 1 ) ON DUPLICATE KEY UPDATE count = count+1;
CREATE TRIGGER tgd_table1 AFTER DELETE ON table1 FOR EACH ROW UPDATE table2 SET count = count-1;

Also, there is a script that runs periodically and execute DROP PARTITION on the old partitions of table1.
My question is: will these DROP PARTITION activate the trigger tgd_table1?
Thank you.

A: No, it wont use DELETE query for deleting records. It is dropping the data in a different way. Here is the explanation from mysql docs:

DELETE: The trigger activates whenever a row is deleted from the table; for example, through DELETE and REPLACE statements. DROP TABLE and TRUNCATE TABLE statements on the table do not activate this trigger, because they do not use DELETE. Dropping a partition does not activate DELETE triggers, either.


text:
Q: "No database Selected" after website migration to snow leopard server I'm migrating a website from a windows server to a snow leopard server (OSX 10.6.8 to be exact) and I'm running into several compatibility issues with my mysql queries. Every query returns a "No database selected" error and I can't make heads or tales of it. I've done some research on it and wasn't able to find the answer I was looking for. Here are some indicators that may be useful in solving my issues.
Here is my connect file include:
$link = mysql_connect("localhost", "username", "password") or die("Invalid query: " . mysql_error());
mysql_select_db("tradeport", $link) or die("Database Connection Error: ".mysql_error());

Here is one of my queries:
$sSQL="SELECT mainPhone FROM admins";
$result21=mysql_query($sSQL) or die ("MySQL err: ".mysql_error()."
".$sSQL);

if($row21 = mysql_fetch_array($result21))
{$phoneMain = $row21['mainPhone'];}

Another note I would like to add is that when I began migration on this site all of the php was showing in the page source. I had to replace all php brackets with the more formal ones as shown here:
<? //before

<?php //after

I'm currently running PHP version 5.3.8 and MySQL version 5.0.92.
Any information would be greatly apreciated.

A: Try adding the db name to the query
"SELECT mainPhone FROM tradeport.admins"

A: It is always good habit to reference your db connection in your mysql_* or mysqli_* (which you should be using) function calls.
Try:
$result21=mysql_query($sSQL, $link) or die ("MySQL err: ".mysql_error()."
".$sSQL);

A: You say your are seeing the error message, "No database selected", which makes me wonder if you are actually executing the mysql_select_db line of code because its error message is "Database Connection Error:", followed by the mysql error code.
Also, where is the include file getting the values for username and password? You just have quoted literal strings, which at first I assumed was for security purposes.
I think the code snippets you provided don't show us the whole picture.

A:
I've tried that and it gives me this error in return: SELECT command
  denied to user ''@'localhost' for table – Trig3rz 20 mins ago

Check that the database user is setup with the correct permissions
GRANT SELECT ON db.* TO user@'localhost' IDENTIFIED BY 'pass';
You might want to check the php.ini file on the original server to see what differences there are.
<? is php short tags and it is enabled in the php ini file with this line:
short_open_tag=On


text:
Q: Using tree Command in C++ on C:// I want to use the Windows CMD tree command in my C++ console application. My code:
system("cd c:/");
system("tree");

The problem is that the command tree will execute on the folder path where the program is running and not on C://. Is there a way to fix this?

A: Why not :
system("tree c:\");

?
TREE [drive:][path] [/F] [/A]

   /F   Display the names of the files in each folder.
   /A   Use ASCII instead of extended characters.

A: You can use SetCurrentDirectory from windows.h. This page has a demonstration:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa363806%28v=vs.85%29.aspx

A: Your problem is that the system("cd c:/") is executed in a shell, and then the shell exits. [It's also wrong, because you use the wrong kind of slash, it should be "cd c:\\" - the double backslash is needed to make one backslash in the output, assuming we're talking about a Windows system].
There are a couple of different ways to do this:

*

*Use chdir() (or SetCurrentDirectory) function call to change the main processes current working directory, and then call system("..."). This is the simplest solution.

*Generate all your commands into a batch file, then pass the batch file to system.

*Open a command shell with something like _popen() and pass commands into the pipe that you get from that.

*Manually create pipes and connect them to the standard in and standard out of a process that runs the command prompt.

A: Just for programs in Windows, include "windows.h", then
SetCurrentDirectory("c:/");
system("pwd");

A: While I'm still curious why would you want to do this, you can try to run all commands in one system() call:
system("cd c: && c: && tree");

Second c: is needed to change drive letter, in case if you're not currently on drive c: (because cd doesn't do it).


text:
Q: Show that the graph of the function $z(x,y) = x\tan(y)$ is a minimal surface
Show that the graph of the function $z(x,y) = x\tan(y)$ is a minimal surface

I'm really lost on how to do this question. I know we have to use the Euler equation to show this, but other than that I'm a bit lost because it's two different variables without a constraint.


text:
Q: Capturing content in server side from nicEdit when form is submitted in asp.net website I am using nicedit in my asp page. I am developing a website using asp.net. I managed to get the nicedit work, but how can I get the value of the textarea, I want to store the value in the DB when submit button is clicked. Actually I am trying to get the textarea value in my server side code(c#).
<script type="text/javascript" src="js/nicEdit.js"></script>
<script type="text/javascript">
   //<![CDATA[
    bkLib.onDomLoaded(function () {
        try {
            new nicEditor({ fullPanel: true }).panelInstance('bee');
        }
        catch (ex)
      { }
    });
   //]]>
</script>

 <textarea id="bee" runat="server"></textarea>

A: To get the results of the entered data, you need to pass the ID of the textarea.
See below:
data = new nicEditors.findEditor('bee'); // bee is the ID of the textarea
d = data.getContent(); // return the content

A: You can get the value of the textarea by the Value property
string val = bee.Value


text:
Q: opencv cli app crashes on windows 10 I'm working on a visual studio project(CLI app) that does some image processing over frames captured using opencv's videocapture class.
The project works fine on my Windows 7 computer, but when I try to deploy it on Windows 10 the program crashes and the following is being thrown to the output:
0x0B37A1C9 (0x0E5C9020 0x0E94E880 0x0E65F020 0x00000500), DllGetClassObject() + 0x4D8B9 bytes(s)
0x0B2D2299 (0x00000280 0x0E94E880 0x00000018 0x00000500)
0x0B30C409 (0x0EA30000 0x00000280 0xFFFFFE20 0x00000500)

Any ideas as to where's it coming from? I'm not even sure that opencv is causing it..
This is the code that handles capturing the frame(from inside a loop):
    cv::Mat mIn;
    int camW = 640;
    int camH = 480;
    int w, h, nc, nI;
    size_t nbytesI, numberOfValues, sizeOfBuffers, sizeOfBuffersO;
    float *h_in;
    cv::VideoCapture camera;

    while (!g_quit)
    {
        reload_parameters(&demo, &oclobjects);
        g_paramsChanged = false;

        if (g_camera)
        {
            if (!g_cameraOpen)
            {
                camera.open(0); // open the default camera
                if (!camera.isOpened())  // check if we succeeded
                {
                    cerr << "Couldn't open camera" << endl;
                    return -1;
                }
                camera.set(CV_CAP_PROP_FRAME_WIDTH, camW);
                camera.set(CV_CAP_PROP_FRAME_HEIGHT, camH);
                g_cameraOpen = true;
            }
            // read in first frame to get the dimensions
            while (true)
            {
                camera >> mIn;
                if (!mIn.empty()) break;
            }
        }
...

I am using opencv 3.0.0 and visual studio 2013.
I would also be very happy simply for pointers as to what does this output mean.


text:
Q: Dajaxice with Class Based View Is there a way to user dajaxice with django class based views?
I'm trying this, but not having much success:
class FavoriteEnroledTrainee(SessionMixin, View):

    def get(self, request, *args, **kwargs):
        print 'here'

    @method_decorator(dajaxice_register(method='GET', name='company.favorite'))
    def dispatch(self, *args, **kwargs):
        return super(FavoriteEnroledTrainee, self).dispatch(*args, **kwargs)

I can see the dajaxice is able to fetch the view but nothing gets printed.

A: You cannot register the dispatch method, because it's not the view entry point. Dajaxice will try to call dispatch directly, but this won't work because it's not a fully functionnal view.
You should register the result of the *as_view* call :
class FavoriteEnroledTrainee(SessionMixin, View):
    def get(self, request, *args, **kwargs):
        print 'here'
favorite_enroled_trainee = dajaxice_register(method='GET', name='company.favorite')(FavoriteEnroledTrainee.as_view())


text:
Q: Typescript getters and setters I am working on a typescript assignment, and wondering if someone could help me, please :)
I have a file called HomePage.ts. Here is the code:
import * as $ from "jquery";
import * as AssetEvent from "../events/AssetEvent";
import * as img from "../data/ImageData";
import * as ts from "../data/TextStyles";
import { applyTextStyle } from "../utils/TextStyleUtils";
import { AssetManager } from "../managers/AssetManager";
import { HorizontalDivide } from "../containers/HorizontalDivide";
import { Margin } from "../utils/Margin";
import "createjs";

/*****************************************************************************/
export class FrontPage extends createjs.Container {

    //===== VARIABLES ======================================//
    private logo: createjs.Bitmap;
    private headline: createjs.Text;
    private body: createjs.Text;
    private div: HorizontalDivide;
    private bucketImage: createjs.Bitmap;
    private bucketHeading: createjs.Text;
    private bucketBody: createjs.Text;
    private stars: createjs.Bitmap;

    private _width: number;
    private _height: number;

    //===== CONSTRUCTOR ====================================//
    constructor() {
        super();

        this._width = -1;
        this._height = -1;

        $("[name=stars]").on("change", (e: Event) => this.onNumStarsChange(e));

        this.addElements();
        this.putDefaultContent();
    }

    //===== FUNCTIONS ======================================//
    /**
     * Instantiate elements and add them to the container.
     */
    addElements(): void {

        // Logo
        this.logo = new createjs.Bitmap(this.am.getAsset(img.LOGO.id));
        this.addChild(this.logo);

        // Headline
        this.headline = new createjs.Text();
        applyTextStyle(this.headline, ts.HEADLINE);
        this.addChild(this.headline);

        // Body
        this.body = new createjs.Text();
        applyTextStyle(this.body, ts.BODY);
        this.addChild(this.body);

        // Divide
        this.div = new HorizontalDivide();
        this.addChild(this.div);

        // Bucket Image
        this.bucketImage = new createjs.Bitmap(this.am.getAsset(img.IMAGE_0.id));
        this.addChild(this.bucketImage);

        // Bucket Header
        this.bucketHeading = new createjs.Text();
        applyTextStyle(this.bucketHeading, ts.BUCKET_HEADLINE);
        this.addChild(this.bucketHeading);

        // Bucket Body
        this.bucketBody = new createjs.Text();
        applyTextStyle(this.bucketBody, ts.BUCKET_BODY);
        this.addChild(this.bucketBody);

        //Stars
        for(let i = 0; i <= 4; i++) {
            this.stars = new createjs.Bitmap(this.am.getAsset(img.STAR.id));
            this.addChild(this.stars[i]);
        }

    }

    /**
     * Set default content for elements.
     */
    putDefaultContent(): void {

        // Headline
        this.headline.text = "Creating Lasting Partnerships";

        // Body
        this.body.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere est sodales est lobortis interdum. Cras a turpis ullamcorper elit dignissim mattis. Mauris dignissim aliquet est, vel vestibulum nisi fermentum vel. Fusce sit amet dolor eu tellus tincidunt pellentesque et vitae mauris. Praesent convallis magna sem. Sed vel mi nunc. In porta justo urna, ac tristique mauris lobortis et. Nam imperdiet lacinia augue eu vehicula. Duis nec consequat libero. Aenean et sapien volutpat, ultricies ante sit amet, ornare leo. Proin orci felis, lacinia ac commodo vitae, suscipit eget ipsum. Sed egestas justo non dolor molestie, eu iaculis enim lobortis. Suspendisse id ipsum vel lectus luctus viverra. Donec quam neque, fringilla quis justo sagittis, malesuada vestibulum leo. Nam eget lorem at elit vestibulum molestie nec quis est.";

        // Bucket
        this.bucketImage.image = this.am.getAsset(img.IMAGE_0.id);
        this.bucketHeading.text = "CONSULTING";
        this.bucketBody.text = "Nunc posuere nibh sed urna posuere rutrum. Ut eu turpis id arcu consequat sagittis. Pellentesque at purus velit. Suspendisse sit amet massa augue. In sit amet arcu ac quam sagittis ornare sit amet ac elit. Donec tempus eu nulla ac pretium. Vivamus laoreet finibus leo. Donec ut massa aliquam, tincidunt nulla ut, mollis nibh.";

    }

    /**
     * Size and position elements and update the CreateJS stage.
     * This should be called whenever the layout changes.
     */
    updateSizeProperties(): void {

        // Margin
        const m: Margin = new Margin(48, 36, 60, 36);

        // Logo
        const logoWidth: number = 76;
        const logoScale: number = logoWidth / img.LOGO.width;

        this.logo.x = this.width - logoWidth - 80;
        this.logo.y = 48;
        this.logo.scaleX = logoScale;
        this.logo.scaleY = logoScale;

        // Headline
        this.headline.x = m.left;
        this.headline.y = 113;
        this.headline.lineWidth = this.width - m.horizontal;

        // Body
        this.body.x = m.left;
        this.body.y = 162;
        this.body.lineWidth = this.width - m.horizontal;

        // Divide
        this.div.x = (this._width / 2) - (this._width / 4);
        this.div.y = this._height / 2 - 90;
        this.div.width = this._width / 2 - m.top;
        this.div.thickness = 1.5;

        // Image
        const bucketWidth: number = 190;
        const imageData: img.IImageData | null = img.getImageDataById(img.IMAGE_0.id);
        const imageScale: number = (imageData) ? bucketWidth / imageData.width : 1;

        this.bucketImage.x = m.left;
        this.bucketImage.y = 432;
        this.bucketImage.scaleX = imageScale;
        this.bucketImage.scaleY = imageScale;

        // Header
        this.bucketHeading.x = m.left;
        this.bucketHeading.y = this.bucketImage.y + 146;
        this.bucketHeading.lineWidth = bucketWidth;

        // Body
        this.bucketBody.x = m.left;
        this.bucketBody.y = this.bucketImage.y + 175;
        this.bucketBody.lineWidth = bucketWidth;

        // Stars
        this.stars.y = m.bottom + 125;

        // Update Stage
        if (this.stage)
            this.stage.update();
    }

    //===== EVENT LISTENERS ================================//
    private onNumStarsChange(e: Event = null) {

        // Update stage display
        this.updateSizeProperties();
    }

    //===== GETTERS / SETTERS ==============================//
    get width(): number {
        return this._width;
    }
    set width(value: number) {
        this._width = value;
        this.updateSizeProperties();
    }

    get height(): number {
        return this._height;
    }
    set height(value: number) {
        this._height = value;
        this.updateSizeProperties();
    }

    //===== CONVENIENCE ====================================//
    private get am(): AssetManager {
        return AssetManager.instance;
    }
}

What I want to do is to create a class that extends createjs container, and move the bucket image, heading and body display object into that class from the page.
The class should be reusable, so that I could easily add two more buckets.
Is there a way to use getters and setters to achieve this?


text:
Q: Testing application with self signed cert - works with ubuntu 20.04 but not 18.04 Using the below conf file to generate a self signed cert for testing purposes. I added the generated cert and pem as a tls certificate in the ingress and everything works perfectly with ubuntu 20.04 when running this command curl --cacert key.crt https://<redacted>.com When using ubuntu 18.04 with the same curl command, I get curl: (60) SSL certificate problem: unable to get local issuer certificate. Doesn't matter if it's u18 vm or docker image, same result. What am I missing?
openssl req -x509 -nodes -days 730 -newkey rsa:2048 -keyout key.pem -out key.crt -config req.conf -extensions 'v3_req'

[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = <redacted>
ST = <redacted>
L = <redacted>
O = <redacted>
OU = <redacted>
CN = *.<redacted>.com
[v3_req]
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
basicConstraints = CA:TRUE
subjectAltName = @alt_names
[alt_names]
DNS.1 = <redacted>.com
DNS.2 = <redacted>.com


text:
Q: Triggering a True Keyboard Press in Javascript/Jquery I have seen multiple solutions and have tried them all, but none of them seem to be working for what I am trying to do.
Here is how I'm sending the key-presses right now:
$("#choice").autotype(text + "{{enter}}", {delay: 100});

It works (as in, it shows the letters in the textbox) but I still need to press enter manually, despite it being part of the line of code above.
I have also attempted using the code I found from another stackoverflow answer:
e = jQuery.Event("keypress")
e.which = 13 //choose the one you want
    $("#test").keypress(function(){
     alert('keypress triggered')
    }).trigger(e)

(That's the raw version, I changed it a bit to fit my needs but it basically was the same).
I've done a lot of research on this but I can't figure out how to make a true keystroke... is it even possible?
For reference, the keystroke that I'm trying to automate is the enter (return) key.
Thanks.


text:
Q: The action of the longest element on weights I am doing some computations related to some work I do in Lie theory and I need to compute the result of the action
$$w_0 \omega_{i},$$
where $w_0$ denotes the longest element in the Weyl group $W$ of a semisimple simply-connected complex algebraic group $G$ and the $\omega_i$'s denote the fundamental weights. I know I can express $w_0$ as a product of reflections $s_j$ and consider the action of each $s_j$ one by one, but this takes me a quite a lot of time and effort. Is there a shortcut (or a program) to compute this?

A: Following what @JyrkiLahtonen mentioned, we have $-w_0 \varpi_i = \varpi_{\sigma(i)}$ for some automorphism $\sigma$ of the Dynkin diagram, so all we need to know is which Dynkin diagram automorphism $\sigma$ is. I'll also note that depending on what tools you have on hand, it might be easier to calculate $\sigma$ as the permutation of simple generators induced by conjugation-by-the-longest-element in the Weyl group: $w_0 s_i w_0^{-1} = s_{\sigma(i)}$.
Here I state without proof the automorphism $\sigma$ in each type:

*

*Type $A_n$: For $n \geq 2$ there is a unique non-identity automorphism (path reversal), which is $\sigma$.

*Type $B_n, C_n$ for $n \geq 2$: The only Dynkin automorphism is the identity, so $\sigma$ is the identity.

*Type $D_n$ for $n \geq 4$: If $n$ is even then $\sigma$ is the identity. If $n$ is odd, then $\sigma$ is the unique non-identity automorphism which interchanges the two interchangable leaves.

*Type $E_6$: $\sigma$ is the unique non-identity automorphism (reversal of the longest path).

*Types $E_7, E_8, F_4, G_2$: The only Dynkin automorphism is the identity.


text:
Q: How properly set line scaling in ms visio I trying to create scallable shapes in Visio
I manage to set scaling for text, but when it comes to lines i cant make it work:
Here i have shape

I setup linewidth as described here http://visguy.com/vgforum/index.php?topic=5261.0
Now i set scale for a page to metric 1:5

I have a ethernet switch shape and need that scale so it fit on page.
So, when i did it, i get this:

So it did not scale lines at all.
How to fix it?

A: It's pretty simple actually, you need use advanced formula from - http://visguy.com/vgforum/index.php?topic=5261.0
You need add User Cells:
User.Width_LineWeight = 2 in
User.Height_LineWeight = 1 in
User.AntiScale = ThePage!PageScale/ThePage!DrawingScale

now just set formula
LineWeight  = SETATREFEXPR(1 pt) * (Width / SETATREF(User.Width_LineWeight, SETATREFEVAL(Width)) + Height / SETATREF(User.Height_LineWeight, SETATREFEVAL(Height))) / 2  *  User.AntiScale

For my example i have 1 rectangle shape and line shape
For rectangle you need this settings
User.Width_LineWeight = set rect real width
User.Height_LineWeight = set rect real height

In formula set first number as line width
LineWeight  = SETATREFEXPR(2.5 pt)...

For line
User.Width_LineWeight = set line width in pt
User.Height_LineWeight = set to 1

That all. Well it seems not 100% accurate, but on scaling to smaller sizes it so far looks just fine.

A: For this I just use copy paste a simple script that affects all shapes on the current page
Private Declare Function GetUserDefaultLCID% Lib "kernel32" ()
Private Declare Function GetLocaleInfoA Lib "kernel32" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String, ByVal cchData As Long) As Long
Private Declare Function SetLocaleInfoA Lib "kernel32" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String) As Boolean
'Used for Localization compability

Public Function loopShapes(ByRef shapes) As Long
Debug.Print "loopShapes called:"
Dim shapeCount As Long
shapeCount = 0

For Each shape In shapes
Call WriteCell(shape)
shapeCount = shapeCount + loopShapes(shape.shapes)
Debug.Print shape
Next
Debug.Print "count:"
Debug.Print shapeCount
countShapes = shapeCount + 1
End Function

Public Sub ResizeWeightWith()

'Declare object variables as Visio object types.
Dim vsoPage As Visio.Page
Dim vsoDocument As Visio.Document
Dim vsoDocuments As Visio.Documents
Dim vsoPages As Visio.Pages
Dim a As Visio.shapes

' record the settings in the variable LocalSettingsDecimal
Dim LocalSettingsDecimal As String
Dim Buffer As String
Buffer = String(256, 0)
Dim le As Integer
le = GetLocaleInfoA(GetUserDefaultLCID(), 14, Buffer, Len(Buffer))
LocalSettingsDecimal = Left(Buffer, le - 1)

' force decimal settings to '.'
Call SetLocaleInfoA(GetUserDefaultLCID(), 14, ".")

'Iterate through all open documents.
Set vsoDocuments = Application.Documents
Set a = Application.Documents.Item(1).Pages.Item(1).shapes
Debug.Print loopShapes(Application.Documents.Item(1).Pages.Item(1).shapes)

Call SetLocaleInfoA(GetUserDefaultLCID(), 14, LocalSettingsDecimal)

End Sub

Sub WriteCell(ByRef shape)

   On Error Resume Next
   Dim l As String

l = shape.CellsSRC(visSectionObject, visRowLine, visLineWeight) / (10 * shape.CellsSRC(visSectionObject, visRowXFormOut, visXFormHeight) * shape.CellsSRC(visSectionObject, visRowXFormOut, visXFormHeight)) & "*Width*Height"
  Debug.Print l
shape.CellsSRC(visSectionObject, visRowLine, visLineWeight).FormulaU = l

End Sub

A: I wanted to add some thoughts - not meant as criticisms, just food for thought for those who land here in the future, or those who want to try some other things out.
We should probably question why you want to change the line scale in the first place.
A lot of "antiscaling" formulas for Visio compare the original height of a shape to the current height of the shape (often for resizing text), but I don't think that is your case. This would result in different lineweights for shapes of differing sizes, but you still want all shapes on the page to have consistent lineweights.
You just need to reduce the lineweights when drawing scales cross various threshholds, and the other answers seem to have figured this out. A few details that I worry about:

*

*Shapes are often grouped, so you need to dig into sub shapes and set their lineweights.

*If you are going to change the scale again in the future, will your code be able to properly change the lineweights again? Think about ways that you can adjust the lineweights up or down such that you can get back to where you started :)

*You may be able to edit a single style attribute and save yourself a lot of trouble. If you have only one page in your drawing file, or if all of the pages in your drawing have the same scale, then you might try editing the Normal style. You can use the Drawing Explorer window to get at the Normal style. Right-click and Show ShapeSheet. Then edit the Lineweight for the style - divide it by, say, 3 or 4. All of the shapes will change (except where you have explicitly applied distinct lineweights already) Visio has some sort of inheritance hierarchy for formatting styles that you can take advantage of.

*Consider NOT changing the drawing scale at all! Just make the page bigger. Explore the Page Setup dialog's tabs. You can make the page bigger and bigger to fit your shapes. When you go to print, just make sure to "fit to 1 page across by 1 page down". Then the printing process will handle the scaling, and you can avoid this whole fight!


text:
Q: Fix the dice value based on user count I have a dice rolling game. I want the dice values from 6 to 12 to fall less frequently and the dice values from 2 to 5 to fall more frequently.
The dice value should fall like the below table

*

*If UserCount is 600or1200or1800... then the dice value should be 6

*If UserCount is 700or1400or2100... then the dice value should be 7

*If UserCount is 800or1600or2400... then the dice value should be 8

*If UserCount is 900or1800or2700... then the dice value should be 9

*If UserCount is 1000or2000or3000... then the dice value should be 10

*If UserCount is 1100or2200or3300... then the dice value should be 11

*If UserCount is 1200or2400or3600... then the dice value should be 12
So its like If the case is 600or1200 => 6 and 1200 => 12 then the dice value should be 6 If it is 1600or2400 => 8 and 1200or2400 =>12 then the dice value should be 8
For rest of the usercount the dice values should fall from 2 to 5 randomly.
I roll 2 dice at a time and each one is 6 sided. When i roll the dice if it falls between 2 to 5 then i will display the same value to the user. But if it is greater than 5 then i will check for the user count and have to fix the value as specified in the question
I maintain the user count in a table. This is an windows application.
Kindly Help.
I have come up with below code
public static String Roll(Int32 numberOfDice, Int32 numberOfSides, Int32 diceRolled)
        {

            if (numberOfDice <= 0)
            {
                throw new ApplicationException("Number of die must be greater than zero.");
            }

            if (numberOfSides <= 0)
            {
                throw new ApplicationException("Number of sides must be greater than zero.");
            }

            Random rnd = new Random((Int32)DateTime.Now.Ticks);
            StringBuilder result = new StringBuilder();
            Int32 total = 0;

            for (Int32 i = 1; i < numberOfDice; i++)
            {

                Int32 roll = rnd.Next(2, numberOfSides);
                total += roll;

                if (total > 5)
                {
                    if (diceRolled % 6 == 0)
                    {
                        total = 6;
                    }
                    else if (diceRolled % 7 == 0)
                    {
                        total = 7;
                    }
                    else if (diceRolled % 8 == 0)
                    {
                        total = 8;
                    }
                    else if (diceRolled % 9 == 0)
                    {
                        total = 9;
                    }
                    else if (diceRolled % 10 == 0)
                    {
                        total = 10;
                    }
                    else if (diceRolled % 11 == 0)
                    {
                        total = 11;
                    }
                    else if (diceRolled % 12 == 0)
                    {
                        total = 12;
                    }
                    else
                    {
                        Dice.Roll(2, 12, diceRolled);
                    }
                }

            }

            Console.WriteLine("Total{0}", Convert.ToString(total));

            return Convert.ToString(total);
        }

Kindly suggest any improvements.

A: I think this should do it:
    public static int RollDice(int userCount)
    {
        //Reduce the user count ex: 600 => 6
        var reducedValue = userCount/100;

        //Process numbers 6-12
        for (int i = 6; i <= 12; i++)
        {
            //Create a trials list
            var trials = new[]
                         {
                             reducedValue/i,
                             reducedValue/(i*2),
                             reducedValue/(i*3),
                         };

            //If any of the trials for this iteration passed
            //i.e. divided evenly, then return our index
            if (trials.Any(t => t == 1))
            {
                return i;
            }
        }

        //Ok, just return a random number from 2 to 5
        var r = new Random();
        return  r.Next(2, 5);
    }


text:
Q: Is there not one decent email client for Mac? When I started looking for an alternative to Mail I had no idea it would become a quest. So my criteria have become...

*

*One-off purchase (no monthly/annual billing)

*Pleasant UI

*Doesn't force me to use an intermediate proxy server

*Doesn't mine my emails or usage for data

*Has a solid search

*Doesn't sporadically lose my recent emails or reset read flags, etc

*Compatible with Protonmail (should be...just SMTP)

*I guess should have an iphone version too but I'm willing to be flexible on that

*Bonus: copy/pastes nicely from places like Notes

Failed contenders:
Spark: Free so I presume mines my data. intermediate server? monthly fee above 5GB
Edison: Mines you for data
Newton: 50/yr and I presume an intermediate server?
Outlook: Ugly
Canary: Reviewer says it suffers the same issues as Mail and has an equally lousy search
Airmail: Is a fairly cheap subscription and one-off for business purchases. People are complaining about the search though
Anyone have an other suggestions? Is there anything genuinely better than Mail? Are my standards too high??

A: Answer: Postbox
It misses #8 (no mobile version) and #9 is so-so (loses some formatting but I'm thinking it's Notes that's the problem)...but it is very stylish, snappy, and seems to have a lot of nice UX innovations (e.g. quick replies below every email, sort emails into folders with pre-defined keystrokes, themes...)

A: No, email is a remnant of a more civilized time when text was text and email didn't have to include such things as a JavaScript engine and image rendering and a security apparatus.

*

*elm / pine / lynx used to be enough for email and web browsing but now you've got requirements that are at odds with plain text display. (And we're all in the same boat as you - your ask is reasonable on the surface but unlikely to be met in a substantial way.)

On a practical level, I have had better success with choosing a mail client to match the mail provider and choosing a mail provider that makes Apple's first party client work better by better managing the content that gets to my device in the first place.

*

*Work is Microsoft, so outlook it is. (warts and opinions on beauty are assuaged by a paycheck.)

*Fastmail has provided sanity to me for mail I manage. It works well
with the native client and it's own app / web app are well designed
to my eye. I can afford it, and their business model adds value to me. Not everyone wants to fund a service that makes their mail work with native clients, though.

*Hey + Basecamp seemed promising but I can't seem to navigate the pain that burning bridges to the past would entail to make a run at using Hey for my email.

Just like security software, email changes constantly and how you fund the salaries of people skilled enough to care about optimizing your time with decent software may be at odds with paying them once for software you expect to work in a month or need support in 6 months.
Just like dozens of companies before it, I wish Postbox (and all newcomers to the space) well, but lifetime support on a fixed price purchase is hard to see as anything but a Ponzi scheme. Whether a company is VC funded or bootstrapping it, developing a popular mail client that do a better job than Apple' first party client is a money-losing operation for the foreseeable future. Until enough people want to pay substantial money regularly, I don't see a business model for the innovation you seek in this space.
As a postscript, if you don't buy into mail and standards as the cause of this mess - have a read on how we can't even agree what a valid email address might be. With that one header field still up in the air for implementation in a standard manner, a proper email client surely can't be made today to a common standard of use.

*

*https://www.netmeister.org/blog/email.html
I look forward to other people's solutions to a gnarly problem and some requirements I can't see being met in the next 4 years or so in a manner that was possible in past decades.


text: Q: my sql workbech no me toma las comas ni los punto y coma al finalizar un codigo lo que sucede es que el programa no toma los puntos y comas para realizar correctamente un codigo o una consulta. Es decir si yo hago un Query sin ; el programa me arroja error, y a mi no me envia ningun error y no se porque. aqui muestro en la siguiente imagen


text:
Q: Plugin for average distance from node to polyline in QGIS? Is there a plugin available that will calculate this?
EDIT 1:
The red polyline is the average distance of the point to the black polyline. The red polyline is what I want to display. Alternatively, is there something which would calculate the radius of the circle so I can use a buffer?

A: Using QGIS and GRASS, this should be doable:

*

*Split the line using v.segment

*Add the point you want to calculate avg distance for

*Use QGIS "Distance Matrix"

*The last column in the matrix should contain all distances. You just need to calculate the mean.

I'm sure there is a GRASS alternative to distance matrix (v.distance?). As far as I know, there is no equivalent to v.segment in QGIS yet.

A: It's unlikely QGIS (or any software) has implemented the exact formulas provided in the antecedent thread, but one could sample a polyline at regular intervals, compute the distances between the sample points and the "node," and average them: these are common operations available in many GISes.  (This is a Riemann Sum, or rectangular, approximation to the integral. Improved approximations, such as with the Trapezoidal Rule or Simpson's Rule, can be implemented similarly.  Correct application of Simpson's Rule would require estimating the average distances separately over each segment of the polyline and then forming the segment-length-weighted average of those results.)
Example

This screenshot (using ArcView 3, an old simple GIS :-) illustrates the procedure.  A 10 km feature in a road layer (barely visible in black) has been sampled at 100 m intervals  (shown in darker cyan) beginning at a random location.  Another point layer containing a single point (shown as a cross) has been spatially joined to the sample points.  One result of the join is to compute a [distance] value to each of the sample points, shown in the table at left.  A statistics dialog displays the mean distance (of 3503 meters), shown highlighted.  A circle of that radius (red) was manually added based on that information.


text:
Q: How can I schedule one(!) reboot? Say I want my machine to reboot tomorrow at 02:00 am. And not again later, just that one time tomorrow morning. How can I do this?

A: Use shutdown -r with TIME option:
$ shutdown -r 02:00
Shutdown scheduled for Fri 2022-04-22 02:00:00 CEST, use 'shutdown -c' to cancel.

From man shutdown:
SYNOPSIS
  shutdown [OPTIONS...] [TIME] [WALL...]

DESCRIPTION
  [...]
  The time string may either be in the format "hh:mm" [...] specified in 24h clock format.
  Alternatively it may be in the syntax "+m" referring to the specified number of minutes m from now.

OPTIONS
  [...]
  -r, --reboot
          Reboot the machine

Alternatively you can use at to schedule a program execution:
$ echo "reboot -f" | at 02:00
warning: commands will be executed using /bin/sh
job 1 at Fri Apr 22 02:00:00 2022

See list of scheduled commands along with its id using atq, remove from list with atrm <id>.
(may need to install sudo apt install at).

Note: at has the benefit that the schedule survives reboots, while the scheduled shutdown will be canceled when rebooting before 02:00.


text:
Q: How to define a version of createSelector typed for my app? In redux-toolkit docs they suggest you to create the following definition to have proper types when you use useSelector hook:
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

This will save you of having to type all the selectors with the root state.
However, when it's time to define memoized selector with createSelector there are no instructions about how to do a similar thing.
Is there any shortcut for this or I have to manually type every memoized selector?

A: I was working on a app that I wanted to do the same. For my needs, I just wanted a simple selector, so I did this:
// store.ts

// …omitted store configuration

export type RootState = ReturnType<typeof store.getState>;

// create a generic type called AppSelector
export type AppSelector<Return> = (state: RootState) => Return
// create a custom `createSelector` that uses the type above
export const createAppSelector = <R>(selector: AppSelector<R>): AppSelector<R> => selector

With the types above, we can do the following:
const selectTitle: AppSelector<string> = (state) => state.title;
// Note that using the AppSelector type requires you to always pass the return type argument
// It's much easier to use the createAppSelector function
// selectTitle and selectTitle2 accomplish the same thing
const selectTitle2 = createAppSelector((state) => state.title);

When inside createAppSelector, state will correctly have the RootState type.
The limitation of this form is that, unlike createSelector, createAppSelector only allows you to create a single selector and doesn't allow you to combine or mutate the selections.
Hopefully someday we'll have a way to const createAppSelector: TypedCreateSelector<RootState> = createSelector;


text:
Q: Is there an API to get e-mail smtp information (for GMail) I want to send an e-mail using gmail API.
I want to know if the email was received successfully. And if not, what the problem. (Such as SMTP Log)
I can use Google Admin G-Suite if need.
How can I do it?
Thank you.

A: What you are looking for is Request read receipt after an email is sent.  This would notify the sender when the recipient reads the email.
This is not something that is currently available in the gmail api.   you may want to consider submitting a feature request here


text:
Q: Set Detailed Bluetooth Audio Codec preferences in macOS Monterey TL;DR
Preferences set in ~root/Library/Preferences/bluetoothaudiod.plist don't seem to have any effect any more. "Bluetooth Explorer" and defaults(1) commands that messed with these don't seem to work either. Does anyone know how to go about doing these things in Monterey?

Historically, we pedants and audiophiles on macOS have been able to tweak bluetoothaudiod.plist to our own fancy. We were essentially restricted to setting AAC bitrates, toggling AptX (not AptX HD, mind you), and packet buffer limits and stuff, but it was still something.
The way to go about this in GUI was to use "Bluetooth Explorer", an Xcode "extra" that is last known to have been distributed with Xcode 11.
Of course, one could always use defaults(1) as well.

As GianpaoloPascasi points out in a post below, tweaking BT-audio codecs can sometimes be a necessity.
How does one tweak the stuff that Bluetooth Explorer and bluetoothaudiod.plist managed, in Monterey?

A: I confirm! Bluetooth explorer and the terminal commands (sudo defaults write bluetoothaudiod) are not working, giving no errors.
I saw that in /Library/Preferences/ there is an empty plist file "com.apple.Bluetooth.plist"...
P.S.
I started searching because i have a brand new pair of Xiaomi Earbuds Basic 2 and they often loss connection, they sound very weird when using their microphone and sometimes the sound playing even "jumps". All of this on a Macbook Pro 13" 2020. I'd like to go back to BigSur and try out the Bluetooth explorer...
Obviusly, they work good on my Windows laptop and on my phone.
The worst thing is that a lot of tutorials cover old methods (putting the keyword "Monterey" SUCH WOW) no longer working. Thanks Apple for this st_pid sh_t.


text:
Q: Accessing AWS Secrets Manager in Alpine Linux I am accessing AWS Secrets Manager in Alpine Linux, though I can't see a way to get a value only from secret string without installing jq resource in Linux.
I know the below command will solve but jq is not a standard utility:
aws secretsmanager get-secret-value --secret-id secrets| jq --raw-output '.SecretString' | jq -r .<KeyName>

I'm stuck at checking the below command but it would return JSON format with 3 key-value pairs:
aws secretsmanager get-secret-value --secret-id secrets --query SecretString --output text

Also one option is to use Systems Manager Parameter Store which is possible but I don't like to create them 1-by-1 like in Secrets Manager you can store username, password, URL in one secret string.

A: It looks like are correct using jq, since the AWS CLI cannot interpret that field.
This is because the SecretString field on a secret is a string, which is not interpreted by the AWS CLI as a JSON object:
{
    "ARN": "arn:aws:secretsmanager:ap-southeast-2:...:secret:foo-GZPisx",
    "Name": "foo",
    "VersionId": "...",
    "SecretString": "{\"my-key\":\"my-value\"}",      <-- This is a string
    "VersionStages": [
        "AWSCURRENT"
    ],
    "CreatedDate": 1601860373.721
}


text:
Q: Shrink unused space in raw image I have a raw image that includes my Windows disk, including 87Gb of C: ; 80 Gb of unallocated space ; 3 Mo of D: ; 147Gb of unallocated space.
How can I delete the unallocated space from my hypervisor disk loosing as few performance as possible?
My hypervisor is kvm, my system is CentOS 7.5.

A: I think you need to convert your raw image to qcow2 using qemu-img. The qcow2 image will only allocate disk as it is needed (sparse).
For example:
$ qemu-img convert -O qcow2 myimage.raw myimage.qcow2

And then replace the disk image in your VM definition with the qcow2 one.

A: The standard utility to deal with this situation is virt-sparsify. RAW files do not support sparseness, so you'll need to switch to qcow2 of course.
@tonioc has a more manual approach, but it will definitely also work.


text:
Q: React Bootstrap container different sizing to regular HTML Bootstrap Why does the Bootstrap container component size differently than a regular HTML Bootstrap, not sure if I am missing a prop or not?
This is what I get the output I get for both:
(the white space in the sides are from the container margin)

React code:
<Container>
  <Row className="row">
    <Col className="col-lg-3 col-md-4">

    </Col>

  </Row>
</Container>

Regular HTML code:

Can someone help with the correct styling/fix for the React version to match the regular one please?


text:
Q: Cannot create property 'validator' on string 'documents' i created a dynamic array form so i can add unlimited amount of items
.html file
'

                Number of videos
                <select formControlName="numberofVideo" class="form-control" (change)="onChangeVideo($event)">
                <option value=""></option>
                <option *ngFor="let i of [1,2,3,4,5,6,7,8,9,10]">{{i}}</option>
                </select>

Video {{i+1}}

                            Select Video: <input (change)="postVideo($event)" formControlName="uploadVideo" type="file" id="uploadVideo" name="uploadVideo">

                                {{ progressVideo | async }}% Complete

                Number of Document
                <select formControlName="numberofDoc" class="form-control " (change)="onChangeDoc($event)">
                <option value=""></option>
                <option *ngFor="let i of [1,2,3,4,5,6,7,8,9,10]">{{i}}</option>
                </select>

Document {{i+1}}

                            Select Document: <input (change)="postDoc($event)" formControlName="uploadDocument" type="file" id="uploadDocument" name="uploadDocument">

                                {{ progressDoc | async }}% Complete

'
.ts file
'
ngOnInit() {
    this.uploadForm = this.formBuilder.group({
      uploadName: ['',Validators.required],
      uploadPrice: ['',Validators.required],
      uploadAuthor: ['',Validators.required],
      uploadDes: ['',Validators.required],
      uploadImage: ['',Validators.required],
      numberofVideo: [''],
      videos: new FormArray([]),
      numberofDoc: [''],
      documents: new FormArray([])
    })
  }

get f(){
    return this.uploadForm.controls;
  }
  get t(){
    return this.f.videos as FormArray;
  }
  get x(){
    return this.f.documents as FormArray;
  }

  onChangeVideo(e){
    const numberOfVideo = e.target.value || 0;
    if(this.t.length < numberOfVideo){
      for(let i=this.t.length;i<numberOfVideo;i++){
        this.t.push(this.formBuilder.group({
          uploadVideo: new FormControl('')
        }));
      }
    }else{
      for(let i = this.t.length; i >= numberOfVideo;i--){
        this.t.removeAt(i)
      }
    }
  }

  onChangeDoc(e){
    const numberOfDoc = e.target.value || 0;
    if(this.x.length < numberOfDoc){
      for(let i=this.x.length;i<numberOfDoc;i++){
        this.x.push(this.formBuilder.group({
          uploadDocument:new FormControl('')
        }));
      }
    }else{
      for(let i = this.x.length; i >= numberOfDoc;i--){
        this.x.removeAt(i)
      }
    }
  }

'
error
AdminComponent.html:46 ERROR Error: Cannot find control with path: 'videos -> uploadVideo'
AdminComponent.html:66 ERROR TypeError: Cannot create property 'validator' on string 'documents'
AdminComponent.html:66 ERROR TypeError: this.form.get is not a function


text:
Q: Get row which has max version value but isn't active I do have a table where changes are always inserted. For this purposes, a version number is increased on each insert but one version is always set manually to be the active one. I would now like to retrieve all rows where the row with the highest version does not have 'active'=true.
| UID | Version | Active | Name  |
----------------------------------
| 001 |       1 | _      | Peter |
| 001 |       2 | X      | Paul  |
| 001 |       3 | _      | Petra |
| 002 |       1 | _      | Walt  |
| 002 |       2 | X      | Jan   |
| 003 |       1 | X      | Brad  |

The result of the query should only return uid 001 as there is a max version of 3 which is not active.
I assume that I need some kind of self-join?
Thanks for any help on this!

A: You could use subquery  and inner join
select uid, version
from my_table m
inner join  (
  select  uid, max(version) max_version
  from my_table
  group by uid
) t ON t.uid = m.uid and t.max_version = m.version
where active ='-'


text:
Q: VHDL- Pseudo Random Number Generating with Seed using linear equation? I'm having trouble writing a random number sequence generator in VHDL.
I tried to use a linear equation to do so, but the Xilinx compiler keeps complaining about the syntax.
The code uses a clock input and the board has 7 switches that will be used to enter the seed. From there, it's all algebra. Or so I hoped.
The code I have is the following:
entity RandNumSeqGen is
    Port ( clk : in  STD_LOGIC;
           switches: in STD_LOGIC_VECTOR (6 downto 0);
           num : out  STD_LOGIC_VECTOR (0 to 3));
end RandNumSeqGen;

architecture Behavioral of RandNumSeqGen is
constant M : integer := 278200;
constant A : integer := 6521;
constant B : integer := 88977;
variable rand_f: real :=0.0;
variable rand_d: integer :=0;
variable seed: integer :=0;
seed <= to_integer(signed(switches));

begin
if (clk'event and clk='1') then
    Seed := (seed*A+B) mod M;
    rand_f:=seed/real(M);
    rand_f:=rand_f*1000;
    rand_d:=integer(rand_f) mod 12;
    num<= rand_d;
end if;

end Behavioral;

The code would ideally keep on making a new random number between 0 and 11 and write it in the num output.
The error report has, well, a lot to say.
Maybe there is a problem with how I declared the variables?
If you know what needs fixing, please let me know. I want to learn to do better.
Line 47: Syntax error near "seed".
Line 50: Syntax error near "then".
Line 51: Syntax error near "mod".
Line 52: Syntax error near ":=".
Line 53: Syntax error near ":=".
Line 54: Syntax error near "mod".
Line 56: Syntax error near "if".
ERROR:ProjectMgmt - 7 error(s) found while parsing design hierarchy.

Sorry for the noob question, I've just gotten started with VHDL numeric variables. Up until now I've only used C and Python

A: Your code should probably be
library ieee;
use ieee.std_logic_1164.all;

entity RandNumSeqGen is
    Port (
        clk : in  STD_LOGIC;
        switches: in STD_LOGIC_VECTOR (6 downto 0);
        num : out  STD_LOGIC_VECTOR (0 to 3)
    );
end entity;

architecture Behavioral of RandNumSeqGen is
    use ieee.numeric_std.all;
    constant M : integer := 278200;
    constant A : integer := 6521;
    constant B : integer := 88977;
begin
    gen_rand_out: process(clk)
        variable rand_f: real := 0.0;
        variable rand_d: integer := 0;
        variable seed: integer := 0;
    begin
        if rising_edge(clk) then
            -- seed := to_integer(signed(switches)); -- I don't get what you want to do here
            seed := (seed*A+B) mod M;
            rand_f := real(seed)/real(M);
            rand_f := rand_f*1000.0;
            rand_d := integer(rand_f) mod 12;
            num <= std_logic_vector(to_unsigned(rand_d, num'length));
        end if;
    end process;
end architecture;

But this will of course not synthesize...


text:
Q: Weird icon (OS X El Capitan) This icon appeared on my Mac Pro with El Capitan.

It cannot be clicked, nor I can see a name.
Any ideas what it might be? I have the same applications on my Mac Mini and never seen the icon.

A: I believe it is "Checking for updates" icon for LibreOffice. It goes away whenever you close it, and whenever you click the icon with LibreOffice open, it brings up the "Check for updates" dialog.
I accidentally discovered that while trying to find out what it was!

A: Downward arrow indicates a download, typically. Are you downloading content without realizing it? Some app that is pulling down data in the background?
Check Activity Monitor (vs your Mini) and see what shows up on your system that is not running on the Mini. Kill it. See if the icon disappears. If it does, you found your culprit.


text:
Q: Adding Items to a string array I need a way to prepend items on to an existing string array, such that:
string[] dirParams = null;

if (Request.Params["locationDirection_0"] != "")
{
    dirParams = Request.Params["locationDirection_0"].Split(',');
}

if (Request.Params["locationDirection_1"] != "")
{
    dirParams = Request.Params["locationDirection_1"].Split(',');
}

if (Request.Params["locationDirection_2"] != "")
{
    dirParams = Request.Params["locationDirection_2"].Split(',');
}

if (Request.Params["locationDirection_3"] != "")
{
    dirParams = Request.Params["locationDirection_3"].Split(',');
}

will give me a string array of about 4 items (assuming none of the requests coming in are empty)
whats the easiest way to do this, I thought of using a list and or a dictonary, neither will work for what I want to do, string array is all I want.

A: Use a list instead:
        List<string> dirParams = new List<string>();

        if (Request.Params["locationDirection_0"] != "")
        {
            dirParams.AddRange(Request.Params["locationDirection_0"].Split(','));
        }

        if (Request.Params["locationDirection_1"] != "")
        {
            dirParams.AddRange(Request.Params["locationDirection_1"].Split(','));
        }

        if (Request.Params["locationDirection_2"] != "")
        {
            dirParams.AddRange(Request.Params["locationDirection_2"].Split(','));
        }

        if (Request.Params["locationDirection_3"] != "")
        {
            dirParams.AddRange(Request.Params["locationDirection_3"].Split(','));
        }

A: Use a List<string> and then the ToArray() method to convert it into a string[].

A: Build your items in a List<string> then use LINQ's .ToArray () to convert it into an array.

A: How about using Linq?
var dirParam = Enumerable.Range(0, 4)
              .Select(i => Request.Params["locationDirection_" + i])
              .Where(s => !String.IsNullOrEmpty(s))
              .SelectMany(s => s.Split(','))
              .ToArray();


text:
Q: nodemon stuck at ''restarting due to changes..." for some reason nodemon doesn't restart after any changes I do. currently, there is no difference between nodemon and node command
console.log('one')

if I use nodemon command and change 'one' to 'two' i get  "restarting due to changes..." and nothing happens after that
this is my package.json file
{
 "name": "weather_app",
 "version": "1.0.0",
 "description": "",
 "main": "app.js",
 "scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"connect-livereload": "^0.6.1",
"handlebars": "^4.7.7",
"hbs": "^4.1.2",
"livereload": "^0.9.3",
"nodemon": "^2.0.12"
}
}

this problem started after I formatted my pc but, I don't think that's the reason
if you could help me I would be very grateful

A: I just fixed this problem by downgrading nodemon to 2.0.2
you can do that by uninstalling the package and installing it again
npm uninstall nodemon

then
npm i nodemon@2.0.2

A: Oh my god, I am gonna kill myself.
After installing nodemon I was trying to run this
npm start

And it is actually should be
nodemon index.js


text:
Q: AngularJS : Isolated Scope in directive with Compile in directive I am struggling to get access to an isolated scope from some html I am building in the compile function of a directive. I have a SIMPLE example, the one I am working with is much more complex. Essentially I can't access properties on the isolated scope. Here is the code.
http://plnkr.co/edit/ETIRs4j3EwZ4DFN5XkPc?p=preview
It's odd to me because the in the console the scope looks great, from the post function.
Notice how the html is set up in the compile function:
tElement.append(angular.element('
{{name}}
{{value}}Hello'))
Also notice the second directive, Here with an inherited scope everything works fine.
Edit: I updated the first directive(The directive that isn't working) to set a property in the html so I could look for it in the console when I log the scope. It turns out it is on the $parent scope (The property is named "wat"). But why? It makes sense why it wouldn't work, but I don't understand why that html doesn't have access to the same isolated scope? Is there a way to force the html I am inserting to use the isolated scope instead?
Edit 2: Ok so a lot of questions about why I am trying to do this, the best description could be found here. https://github.com/angular/angular.js/issues/7874. Essentially we wanted to ng-repeat some transcluded content, and expose the item from ng-repeat to the transcluded content, but you can't do that in angular, because the transcluded content only has access to the parent scope.
The goal is to get the first directive to work like the second, in that the value of the two properties (value, and name) work from appending html in the compile function, with an isolated scope.

A: This is how I would go about what ( I think ) you are trying to achieve
http://plnkr.co/edit/mL7h7Hf8TkkpfsPNoL6g?p=preview
By using a template with transclude: true and a link function you can achieve the desired result as you replace the element with your template while interpreting the angular expressions
You could use replace: true to further customise your directive
app.directive('widget',function(){
  return {
    restrict:'E',
    transclude: true,
    template: '
{{name}}
{{value}} There',
    scope:{
      name:'@',
      value:'='
    },
    link:function($scope, tElement){
    }
  }
});


text:
Q: Geolocation Push Notifications I'm using phonegap/cordova for both my iOS and Android applications. I'm looking for geolocation push notifications, so I can do a push message for both my east coast and west coast customers. Is there a third party platform that would allow me to integrate this ability and let me do one-time push notifications?

A: We recently did the same thing.
Initially:
We tried to capture all the user push ids and store them, then set our own system up. Which was a pain in the...
Then:
A better option is to set up native push notifications with http://parse.com/
They have a few API options. So its easy to set up the users.

*

*When you add the user

*also add a [channel]

*Call the channel ["east_coast"] or ["west_coast"]

Then push a notification out to the channels that include ["east_coast"]
Easy.


text:
Q: How do I get horizontal scroll history navigation to work in browsers in Ubuntu 18.04? I can't seem to get horizontal scroll-based navigation (back/forward) to work in any browser under Ubuntu 18.04. For example, in Chromium, the setting to control this can be found by pasting the following in your address bar: chrome://flags/#overscroll-history-navigation. However, modifying this setting appears to do nothing.
Horizontal scrolling works for moving the view on a wide page in the browser, so my touchpad doesn't have any issues.