问:
Django Server KeyError - Unable to locate my environment variable
I am making a blog using Django and am trying to make it secure by using 2 settings files (prod.py and local.py which both "import *" from a base.py original settings file).

I have two environment variables which are on my local computer and have confirmed they exist: myBlog and SECRET_KEY. myBlog=prod

The error I am receiving is a KeyError:

```<code>(venv) C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog>python manage.py runserver
Traceback (most recent call last):
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog\manage.py", line 22, in <module>
    main()
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line
    utility.execute()
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\core\management\__init__.py", line 386, in execute
    settings.INSTALLED_APPS
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\conf\__init__.py", line 92, in __getattr__
    self._setup(name)
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\conf\__init__.py", line 79, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\conf\__init__.py", line 190, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog\myBlog\settings\__init__.py", line 1, in <module>
    from .base import *
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog\myBlog\settings\base.py", line 28, in <module>
    myBlog = os.environ['myBlog']
  File "C:\Python310\lib\os.py", line 679, in __getitem__
    raise KeyError(key) from None
KeyError: 'myBlog'
</code>```

This is my current init.py file:

```<code>from .base import *
import os

if os.environ['myBlog'] == 'prod':
   from .prod import *
else:
   from .local import *
</code>```

This is my current base.py file:

```<code>"""
Django settings for myBlog project.

Generated by 'django-admin startproject' using Django 4.1.3.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent.parent
TEMPLATES_DIRS = os.path.join(BASE_DIR,'templates')

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']

myBlog = os.environ['myBlog']

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
    'django.contrib.sitemaps',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'myBlog.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATES_DIRS],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'myBlog.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'

STATICFILES_DIRS = ((os.path.join(BASE_DIR, 'static')), )

STATIC_ROOT  = os.path.join(BASE_DIR, 'staticfiles')
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

</code>```

This is my current prod.py file:

```<code>from .base import *
import os

DEBUG = False
ALLOWED_HOSTS = ['mywebsite.co.uk']
</code>```

This is my current local.py file:

```<code>from .base import *
import os

DEBUG = True
ALLOWED_HOSTS = ['localhost']
</code>```

I am unsure of how to solve this issue. I think my environment variables are created properly (have confirmed they exist and have their expected values).

I have edited BASE_DIR to this

```<code>BASE_DIR = Path(__file__).resolve().parent.parent.parent
</code>```

And both of my local.py and prod.py import * from the base.py file.

Any help would be greatly appreciated.

Body:
I am making a blog using Django and am trying to make it secure by using 2 settings files (prod.py and local.py which both "import *" from a base.py original settings file).

I have two environment variables which are on my local computer and have confirmed they exist: myBlog and SECRET_KEY. myBlog=prod

The error I am receiving is a KeyError:

(venv) C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog>python manage.py runserver
Traceback (most recent call last):
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog\manage.py", line 22, in <module>
    main()
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line
    utility.execute()
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\core\management\__init__.py", line 386, in execute
    settings.INSTALLED_APPS
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\conf\__init__.py", line 92, in __getattr__
    self._setup(name)
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\conf\__init__.py", line 79, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\conf\__init__.py", line 190, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog\myBlog\settings\__init__.py", line 1, in <module>
    from .base import *
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog\myBlog\settings\base.py", line 28, in <module>
    myBlog = os.environ['myBlog']
  File "C:\Python310\lib\os.py", line 679, in __getitem__
    raise KeyError(key) from None
KeyError: 'myBlog'

This is my current init.py file:

from .base import *
import os

if os.environ['myBlog'] == 'prod':
   from .prod import *
else:
   from .local import *

This is my current base.py file:

"""
Django settings for myBlog project.

Generated by 'django-admin startproject' using Django 4.1.3.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent.parent
TEMPLATES_DIRS = os.path.join(BASE_DIR,'templates')

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']

myBlog = os.environ['myBlog']

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
    'django.contrib.sitemaps',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'myBlog.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATES_DIRS],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'myBlog.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'

STATICFILES_DIRS = ((os.path.join(BASE_DIR, 'static')), )

STATIC_ROOT  = os.path.join(BASE_DIR, 'staticfiles')
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

This is my current prod.py file:

from .base import *
import os

DEBUG = False
ALLOWED_HOSTS = ['mywebsite.co.uk']

This is my current local.py file:

from .base import *
import os

DEBUG = True
ALLOWED_HOSTS = ['localhost']

I am unsure of how to solve this issue. I think my environment variables are created properly (have confirmed they exist and have their expected values).

I have edited BASE_DIR to this

BASE_DIR = Path(__file__).resolve().parent.parent.parent

And both of my local.py and prod.py import * from the base.py file.

Any help would be greatly appreciated.


来源: stackexchange

问:
Create section for Saving Calendar in Apple Calendar App
Here I am trying to Create a new section in Apple Calendar App.

As you can see in above image we have two sections in Simulator:

ON MY IPHONE

OTHER

And you can in image, I have created Testing1, Testing2, Testing3 Calendar programmatically in Simulator

But in Real Device iPhone we don’t have ON MY IPHONE section so I want to create one in code.

Here is my code:

```<code>func getSections() -> EKSource {
        var source: EKSource?
        source = eventStore.sources.filter { (source: EKSource) -> Bool in
            print("Sources: \(source.description)")
            return (source.sourceType.rawValue == EKSourceType.subscribed.rawValue) // Here I am able to save calendar in Subscription in Real Device but I want to create my own section
        }.first
        print("Source found: \(source?.description)")
        return source ?? EKSource()
    }
</code>```

So Devs, Is there any way to create my own section and save my Calendar here

ContentLicense: CC BY-SA 4.0

Body:
Here I am trying to Create a new section in Apple Calendar App.

As you can see in above image we have two sections in Simulator:

ON MY IPHONE

OTHER

And you can in image, I have created Testing1, Testing2, Testing3 Calendar programmatically in Simulator

But in Real Device iPhone we don’t have ON MY IPHONE section so I want to create one in code.

Here is my code:

func getSections() -> EKSource {
        var source: EKSource?
        source = eventStore.sources.filter { (source: EKSource) -> Bool in
            print("Sources: \(source.description)")
            return (source.sourceType.rawValue == EKSourceType.subscribed.rawValue) // Here I am able to save calendar in Subscription in Real Device but I want to create my own section
        }.first
        print("Source found: \(source?.description)")
        return source ?? EKSource()
    }

So Devs, Is there any way to create my own section and save my Calendar here


问:
Does the Geoda software address generalised linear models questions?
I know the Geoda (https://geodacenter.github.io/) can address spatial regression questions. Can it address the generalized linear regression questions like the spdep and spatialreg packages?

I want to use possion and negative biominal models. Can I use Geoda?


问:
Add an icon on a Flutter Calendar
I'm looking for a way to add a little icon (for example an hamburger icon) on a calendar around the time and date the user had lunch. I'm using the syncfusion calendar package. How do you think i should proceed?
Thank you for your help</p>

Title: Add an icon on a Flutter Calendar


问:
Beginner on VBA looking for help on matching on n products and sending on a new worksheet
I'm a begginer at VBA and I m looking for your help.

My issue is the following.
I have 2 worksheets (ws): one is named "Order", the other is named "Data".

In the Order ws, there are 4 columns: order number, sap code, csc code, and product name with 10 different lines (but the number might rise in the future).

In ther Data ws, i have more columns including  date of stocks (A), sap code (B), csc code (C),  product name (E), line full (I). The "Line full" is a conditional formating check up: if my colonne I = 0 then the line will turn green and i know i ordered the product.

In my code I would like to do the following
(1) Create a new worksheet named B&L
(2) On this new worsheet i want to find the number of items listed on my order list with data from the "Data" ws.
(3) In order to retrieve the correct lines, I need to have a match on sap code (the common key between the two worksheet and only numbers) AND line full = 0, with the date of the row selected on the data ws always being the earliest (ie. if i have a date of 12/12 and 12/13, i want to select first date of the row of 12/12, and so on depending on the number i order).

Note: in the picture you can see my data worksheet.

In the end, if I order 3 items with SAP code XXX and 2 items with SAP code YYYY. I need to find the following on my ws called "B/L"

Date  |SAP Code| CSC Code  |  Product Name
01/02   XXX       1234              XXXX
01/O2   XXX       1835             XXXX
02/02   xxx       1924              XXXX
01/02   yyy       1613             YYYY
03/06   yyyy      1512            YYYY
```
<p>My code is the following but does not work in the loop...</p>
<pre class="lang-vb prettyprint-override"><code>Dim Worksheet As Worksheet
Dim Workbook As Workbook
Dim i As Integer
Dim Lastrow As Long
Dim Cell As Range

With Worksheets("Commande")
        Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With

Sheets.Add.Name = "B&L"
Range("A1").Select
ActiveCell.FormulaR1C1 = "Date"
Range("B1").Select
ActiveCell.FormulaR1C1 = "SAP Code"
Range("C1").Select
ActiveCell.FormulaR1C1 = "CSC Code"
Range("D1").Select
ActiveCell.FormulaR1C1 = "Product Name"

'Here i m looking at finding what data i need to retrieve
Sheets("Order").Select
For i = 2 To Lastrow
    If Not Cells(i, 1) = 0 Then Sheets("Data").Select
'Here i want to get the data in the "Data"Ws and repeat it untill the number of rows of data i copy and past matches the number listed in the order
        Do Until Z = Sheets("Order").Cells(i, 1).Value
            For Each Cell In Range("I:I")
                If Cell.Value = 1 And Range("B").Cell.Value = Sheets("Order").Range("B").Cell.Value Then
                Range("A:C", "E:F").Copy Sheets("B/L").Cells(Rows.Count, 1).End(xlUp)(2)
                End If
            Next Cell
        Loop
Next
</code>```

I have an error at Cell.Value = 1 And Range("B").Cell.Value = Sheets("Commande").Range("B").Cell.Value  and don't understand why.

Thank you in advance

Body:
I'm a begginer at VBA and I m looking for your help.

My issue is the following.
I have 2 worksheets (ws): one is named "Order", the other is named "Data".

In the Order ws, there are 4 columns: order number, sap code, csc code, and product name with 10 different lines (but the number might rise in the future).

In ther Data ws, i have more columns including  date of stocks (A), sap code (B), csc code (C),  product name (E), line full (I). The "Line full" is a conditional formating check up: if my colonne I = 0 then the line will turn green and i know i ordered the product.

In my code I would like to do the following
(1) Create a new worksheet named B&L
(2) On this new worsheet i want to find the number of items listed on my order list with data from the "Data" ws.
(3) In order to retrieve the correct lines, I need to have a match on sap code (the common key between the two worksheet and only numbers) AND line full = 0, with the date of the row selected on the data ws always being the earliest (ie. if i have a date of 12/12 and 12/13, i want to select first date of the row of 12/12, and so on depending on the number i order).

Note: in the picture you can see my data worksheet.

In the end, if I order 3 items with SAP code XXX and 2 items with SAP code YYYY. I need to find the following on my ws called "B/L"

Date  |SAP Code| CSC Code  |  Product Name
01/02   XXX       1234              XXXX
01/O2   XXX       1835             XXXX
02/02   xxx       1924              XXXX
01/02   yyy       1613             YYYY
03/06   yyyy      1512            YYYY

My code is the following but does not work in the loop...

Dim Worksheet As Worksheet
Dim Workbook As Workbook
Dim i As Integer
Dim Lastrow As Long
Dim Cell As Range

With Worksheets("Commande")
        Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With

Sheets.Add.Name = "B&L"
Range("A1").Select
ActiveCell.FormulaR1C1 = "Date"
Range("B1").Select
ActiveCell.FormulaR1C1 = "SAP Code"
Range("C1").Select
ActiveCell.FormulaR1C1 = "CSC Code"
Range("D1").Select
ActiveCell.FormulaR1C1 = "Product Name"

'Here i m looking at finding what data i need to retrieve
Sheets("Order").Select
For i = 2 To Lastrow
    If Not Cells(i, 1) = 0 Then Sheets("Data").Select
'Here i want to get the data in the "Data"Ws and repeat it untill the number of rows of data i copy and past matches the number listed in the order
        Do Until Z = Sheets("Order").Cells(i, 1).Value
            For Each Cell In Range("I:I")
                If Cell.Value = 1 And Range("B").Cell.Value = Sheets("Order").Range("B").Cell.Value Then
                Range("A:C", "E:F").Copy Sheets("B/L").Cells(Rows.Count, 1).End(xlUp)(2)
                End If
            Next Cell
        Loop
Next

I have an error at Cell.Value = 1 And Range("B").Cell.Value = Sheets("Commande").Range("B").Cell.Value  and don't understand why.

Thank you in advance


问:
Problem with infura.io gateway requiring auth posting to IPFS
Before Oct 2022, Infura.io allow users to post using its gateway as follows: No auth is required. My original code is as follows in ipfs.js file.

```<code>const IPFS = require('ipfs-api');
const ipfs = new IPFS({host: 'ipfs.infura.io', port: 5001, protocol: 'https'});
export default ipfs;
</code>```

When auth is needed I included the following:

```<code>const projectId ='ZZZZZZZZZZZZZZz';
const projectSecret='ZXXXZZXXXXXXXXXX';
const auth = 'Bearer ' + (projectId + ':' +projectSecret);

const ipfs = new IPFS({
     host: 'ipfs.infura.io',
     //host: 'nftpatent.infura-ipfs.io/',
     port: 5001,
     protocol: 'https',
     headers: {
     authorization: auth,
     }
});
</code>```

The issue is that i am unable to upload and post/pin to IPFS. My first thought is that I use the wrong host which should be the dedicated 'nftpatent.infura-ipfs.io' as this requires the auth but from what I have read research it seems everything stays the same and we need to provide auth only.

In my App.js, I have this to do the heavy lifting

```<code>        // save document to IPFS,return its hash#, and set hash# to state
        // https://github.com/ipfs/interface-ipfs-core/blob/master/SPEC/FILES.md#add
        //setState by setting ipfsImageHash to ipfsImageHash[0].hash

        if (this.state.myToken.imageBuffer && this.state.myToken.imageBuffer.length > 0) {

            await ipfs.add(this.state.myToken.imageBuffer, (err, ipfsHash) => {
                console.log('IPFS hash: ' + ipfsHash + ', error: ' + err);

                let myMetadata = JSON.parse(JSON.stringify(this.state.myToken.metadataBuffer));
                myMetadata.image = this.state.web3ctx.ipfsGateway + ipfsHash[0].hash;

                this.setState({
                    myToken: {
                        ...this.state.myToken,
                        ipfsImageHash: ipfsHash[0].hash,

                        ipfsImageUrl: myMetadata.image,
                        metadataBuffer: myMetadata,
                        imageBuffer: ''
                    },
                    selectedTab: 'Metadata'
                });
            })
        } else if (this.state.myToken.metadataBuffer && this.state.myToken.metadataBuffer.toString().length > 0) {

            await ipfs.add(Buffer.from(JSON.stringify(this.state.myToken.metadataBuffer)), (err, ipfsHash) => {
                console.log('IPFS hash: ' + ipfsHash + ', error: ' + err);

                this.setState({
                    myToken: {
                        ...this.state.myToken,
                        ipfsMetadataHash: ipfsHash[0].hash,
                        ipfsMetadataUrl: this.state.web3ctx.ipfsGateway + ipfsHash[0].hash
                    },
                    selectedTab: 'Metadata'
                });
            })
        } else {
            console.log('file could not be found: '
                + JSON.stringify(this.state.myToken.metadataBuffer, null, 2));
            return 1;
        }
    };
`
</code>```

And the error is

TypeError: Cannot read properties of undefined (reading '0')
Duplex.
src/App.js:287

myMetadata.image = this.state.web3ctx.ipfsGateway + ipfsHash[0].hash;

enter image description here

Please help as I can't seem to figure out the issues. ``

I tried working the auth and checking whether the host is correctly called. I believe the issue is with "auth" and not with scripts as they were working previously. Thanks in advance.   `

Body:
Before Oct 2022, Infura.io allow users to post using its gateway as follows: No auth is required. My original code is as follows in ipfs.js file.

const IPFS = require('ipfs-api');
const ipfs = new IPFS({host: 'ipfs.infura.io', port: 5001, protocol: 'https'});
export default ipfs;

When auth is needed I included the following:

const projectId ='ZZZZZZZZZZZZZZz';
const projectSecret='ZXXXZZXXXXXXXXXX';
const auth = 'Bearer ' + (projectId + ':' +projectSecret);

const ipfs = new IPFS({
     host: 'ipfs.infura.io',
     //host: 'nftpatent.infura-ipfs.io/',
     port: 5001,
     protocol: 'https',
     headers: {
     authorization: auth,
     }
});

The issue is that i am unable to upload and post/pin to IPFS. My first thought is that I use the wrong host which should be the dedicated 'nftpatent.infura-ipfs.io' as this requires the auth but from what I have read research it seems everything stays the same and we need to provide auth only.

In my App.js, I have this to do the heavy lifting

        // save document to IPFS,return its hash#, and set hash# to state
        // https://github.com/ipfs/interface-ipfs-core/blob/master/SPEC/FILES.md#add
        //setState by setting ipfsImageHash to ipfsImageHash[0].hash

        if (this.state.myToken.imageBuffer && this.state.myToken.imageBuffer.length > 0) {

            await ipfs.add(this.state.myToken.imageBuffer, (err, ipfsHash) => {
                console.log('IPFS hash: ' + ipfsHash + ', error: ' + err);

                let myMetadata = JSON.parse(JSON.stringify(this.state.myToken.metadataBuffer));
                myMetadata.image = this.state.web3ctx.ipfsGateway + ipfsHash[0].hash;

                this.setState({
                    myToken: {
                        ...this.state.myToken,
                        ipfsImageHash: ipfsHash[0].hash,

                        ipfsImageUrl: myMetadata.image,
                        metadataBuffer: myMetadata,
                        imageBuffer: ''
                    },
                    selectedTab: 'Metadata'
                });
            })
        } else if (this.state.myToken.metadataBuffer && this.state.myToken.metadataBuffer.toString().length > 0) {

            await ipfs.add(Buffer.from(JSON.stringify(this.state.myToken.metadataBuffer)), (err, ipfsHash) => {
                console.log('IPFS hash: ' + ipfsHash + ', error: ' + err);

                this.setState({
                    myToken: {
                        ...this.state.myToken,
                        ipfsMetadataHash: ipfsHash[0].hash,
                        ipfsMetadataUrl: this.state.web3ctx.ipfsGateway + ipfsHash[0].hash
                    },
                    selectedTab: 'Metadata'
                });
            })
        } else {
            console.log('file could not be found: '
                + JSON.stringify(this.state.myToken.metadataBuffer, null, 2));
            return 1;
        }
    };
`

And the error is

TypeError: Cannot read properties of undefined (reading '0')
Duplex.
src/App.js:287

myMetadata.image = this.state.web3ctx.ipfsGateway + ipfsHash[0].hash;

enter image description here

Please help as I can't seem to figure out the issues. ``

I tried working the auth and checking whether the host is correctly called. I believe the issue is with "auth" and not with scripts as they were working previously. Thanks in advance.   `


问:
Istio Gatway tlsmode=SIMPLE with combined validation context EnvoyFilter
We are using tlsmode=SIMPLE since our gateway will accept token auth or client cert auth. Also we set caCertificates to validate client cert if has. how we do this in Istio and EnvoyFilter ?
My goal is make it work exactly like VerifyClientCertIfGiven

I create a secret ssl-certificate-cacert with our valid ca cert

Then I apply the following EnvoyFilter but its not working, any advice ?

```<code>apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: add-validation-context-to-simple-mode
  namespace: istio-system
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      context: GATEWAY
      listener:
        portNumber: 443
    patch:
      operation: INSERT_BEFORE
      value:
        transport_socket:
          name: envoy.transport_sockets.tls
          typed_config:
            '@type': type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext
            common_tls_context:
              combined_validation_context:
                default_validation_context: {}
                validation_context_sds_secret_config:
                  name: kubernetes://ssl-certificate-cacert
                  sds_config:
                    ads: {}
                    resource_api_version: V3

</code>```

Body:
We are using tlsmode=SIMPLE since our gateway will accept token auth or client cert auth. Also we set caCertificates to validate client cert if has. how we do this in Istio and EnvoyFilter ?
My goal is make it work exactly like VerifyClientCertIfGiven

I create a secret ssl-certificate-cacert with our valid ca cert

Then I apply the following EnvoyFilter but its not working, any advice ?

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: add-validation-context-to-simple-mode
  namespace: istio-system
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      context: GATEWAY
      listener:
        portNumber: 443
    patch:
      operation: INSERT_BEFORE
      value:
        transport_socket:
          name: envoy.transport_sockets.tls
          typed_config:
            '@type': type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext
            common_tls_context:
              combined_validation_context:
                default_validation_context: {}
                validation_context_sds_secret_config:
                  name: kubernetes://ssl-certificate-cacert
                  sds_config:
                    ads: {}
                    resource_api_version: V3


问:
How to stringify quantities/numbers in different locales grammatically correct in android java
I'm working on a native android app (java) which supports different locales: en, fr, de, es, pt, it, ru, ar

I need to display a number of objects to the user

example: You have 7 days left

what I used to do is provide a double-from translation for the same sentence, One for the singluar form and the other for the plural

private static final String SENTENCE_SINGLE = "You have 1 day left";
private static final String SENTENCE_PLURAL = "You have %d days left";

public String stringify(number) {
  if (number < 0)
    return null;
  if (number == 1)
    return SENTENCE_SINGLE;
  return String.format(Locale.ENGLISH, SENTENCE_PLURAL, number);
}
```
<p>This works fine with <code>English</code> and <code>French</code>. But when I'm dealing with <code>Arabic</code> for example, I have to consider a sentence for the number 2, and another for every first 10 numbers in each 100th. (Kinda complicated, I know)</p>
<p>for refrence</p>
<pre class="lang-java prettyprint-override"><code>// The arabic way
private static final String SENTENCE_SINGLE = "You have 1 day left";
private static final String SENTENCE_DOUBLE = "You have two-days left";
private static final String SENTENCE_PLURAL = "You have %d days left";
private static final String SENTENCE_PLURAL_FIRST_10 = "You have %d special-way-day left";

public String stringify(number) {
  if (number < 0)
    return null;
  if (number == 1)
    return SENTENCE_SINGLE;
  if (number == 2)
    return SENTENCE_DOUBLE;
  if (number % 100 <= 10 && number % 100 >= 2)
    return String.format(Locale.ENGLISH, SENTENCE_PLURAL_FIRST_10, number);
  return String.format(Locale.ENGLISH, SENTENCE_PLURAL, number);
}
</code>```

I should have a unified function for all locales. I still can work with this method, even though I will be using redundant sentences for simple locales like

// for English
private static final String SENTENCE_SINGLE = "You have 1 day left";
private static final String SENTENCE_DOUBLE = "You have 2 days left";
private static final String SENTENCE_PLURAL = "You have %d days left";
private static final String SENTENCE_PLURAL_FIRST_10 = "You have %d days left";
```

The problem is I have no Idea how the grammar in the other languages work (de|German, es|Spanish, pt|Portugese, it|Italian, ru|Russian), I'm mostly working with google translate :)

Is there an existing library I can use, or can someone explain how numbers work in the other languages,

Body:
I'm working on a native android app (java) which supports different locales: en, fr, de, es, pt, it, ru, ar

I need to display a number of objects to the user

example: You have 7 days left

what I used to do is provide a double-from translation for the same sentence, One for the singluar form and the other for the plural

private static final String SENTENCE_SINGLE = "You have 1 day left";
private static final String SENTENCE_PLURAL = "You have %d days left";

public String stringify(number) {
  if (number < 0)
    return null;
  if (number == 1)
    return SENTENCE_SINGLE;
  return String.format(Locale.ENGLISH, SENTENCE_PLURAL, number);
}

This works fine with English and French. But when I'm dealing with Arabic for example, I have to consider a sentence for the number 2, and another for every first 10 numbers in each 100th. (Kinda complicated, I know)

for refrence

// The arabic way
private static final String SENTENCE_SINGLE = "You have 1 day left";
private static final String SENTENCE_DOUBLE = "You have two-days left";
private static final String SENTENCE_PLURAL = "You have %d days left";
private static final String SENTENCE_PLURAL_FIRST_10 = "You have %d special-way-day left";

public String stringify(number) {
  if (number < 0)
    return null;
  if (number == 1)
    return SENTENCE_SINGLE;
  if (number == 2)
    return SENTENCE_DOUBLE;
  if (number % 100 <= 10 && number % 100 >= 2)
    return String.format(Locale.ENGLISH, SENTENCE_PLURAL_FIRST_10, number);
  return String.format(Locale.ENGLISH, SENTENCE_PLURAL, number);
}

I should have a unified function for all locales. I still can work with this method, even though I will be using redundant sentences for simple locales like

// for English
private static final String SENTENCE_SINGLE = "You have 1 day left";
private static final String SENTENCE_DOUBLE = "You have 2 days left";
private static final String SENTENCE_PLURAL = "You have %d days left";
private static final String SENTENCE_PLURAL_FIRST_10 = "You have %d days left";

The problem is I have no Idea how the grammar in the other languages work (de|German, es|Spanish, pt|Portugese, it|Italian, ru|Russian), I'm mostly working with google translate :)

Is there an existing library I can use, or can someone explain how numbers work in the other languages,


问:
Scroll to clicked li on click overflow-x: scroll;
I want to make a made this thumbnail scroll bar for woocommerce But it is not working correct and I can't get it to work. This is for woocommerce product gallery so I can't really make changes to the html thats why there are ol

Is it also possible to have te scrollbar scroll to the item that is clicked?

$(document).ready(function() {
    var scrollTo = 0;
    $('.flex-control-nav').on('click', "img", function() {
      var activeItem = $('li.active');
      var selectedItem = $(this).parent()

      var activeIndex = $('li').index(activeItem);
      var selectedIndex = $('li').index(selectedItem);

      scrollTo = $('.flex-control-nav li').scrollLeft() -selectedItem.position().left + ($('.flex-control-nav').width() / 2) - (selectedItem.width() / 2);

      $('.flex-control-nav').css('transform', 'translateX(' + scrollTo + 'px)');
      activeItem.removeClass('active');
      selectedItem.addClass('active');
    });
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.flex-control-thumbs li {
    display: flex;
    overflow-x: visible;
    flex: 1 0 40%;
}
ol>li {
    padding: 2px;
}
 li {
    width: 50px;
    margin: 0;
    cursor: pointer;
    height: 100px;
}
img{
  background: blue;
}
ol{
  list-style: none;
}
.flex-control-thumbs {
    display: flex;
    flex-wrap: nowrap;
    overflow-x: scroll;
    margin: 0 50px;
}
ul {
    margin: 25px -2px 0;
    max-width: 68%;
 }</code>```

```

Body:
I want to make a made this thumbnail scroll bar for woocommerce But it is not working correct and I can't get it to work. This is for woocommerce product gallery so I can't really make changes to the html thats why there are ol

Is it also possible to have te scrollbar scroll to the item that is clicked?

$(document).ready(function() {
    var scrollTo = 0;
    $('.flex-control-nav').on('click', "img", function() {
      var activeItem = $('li.active');
      var selectedItem = $(this).parent()

      var activeIndex = $('li').index(activeItem);
      var selectedIndex = $('li').index(selectedItem);

      scrollTo = $('.flex-control-nav li').scrollLeft() -selectedItem.position().left + ($('.flex-control-nav').width() / 2) - (selectedItem.width() / 2);

      $('.flex-control-nav').css('transform', 'translateX(' + scrollTo + 'px)');
      activeItem.removeClass('active');
      selectedItem.addClass('active');
    });
 });

.flex-control-thumbs li {
    display: flex;
    overflow-x: visible;
    flex: 1 0 40%;
}
ol>li {
    padding: 2px;
}
 li {
    width: 50px;
    margin: 0;
    cursor: pointer;
    height: 100px;
}
img{
  background: blue;
}
ol{
  list-style: none;
}
.flex-control-thumbs {
    display: flex;
    flex-wrap: nowrap;
    overflow-x: scroll;
    margin: 0 50px;
}
ul {
    margin: 25px -2px 0;
    max-width: 68%;
 }


问:
mysql configuration stops at "starting server 8.0.31" has failed
"MySQL Installer Stuck on "Starting Service"I was installing MySQL installer on my windows 10 machine. During the server configuration process, it gets stuck at "starting server" and doesn't move any further.
The log for the same is :
Beginning configuration step: Writing configuration file

Saving my.ini configuration file...
Saved my.ini configuration file.
Ended configuration step: Writing configuration file

Beginning configuration step: Updating Windows Firewall rules

Adding a Windows Firewall rule for MySQL80 on port 3306.
Attempting to add a Windows Firewall rule with command: netsh.exe advfirewall firewall add rule name="Port 3306" protocol=TCP localport=3306 dir=in action=allow
Ok.

Successfully added the Windows Firewall rule.
Adding a Windows Firewall rule for MySQL80 on port 33060.
Attempting to add a Windows Firewall rule with command: netsh.exe advfirewall firewall add rule name="Port 33060" protocol=TCP localport=33060 dir=in action=allow
Ok.

Successfully added the Windows Firewall rule.
Ended configuration step: Updating Windows Firewall rules

Beginning configuration step: Adjusting Windows service

Attempting to grant the required filesystem permissions to the 'NT AUTHORITY\NetworkService' account.
Granted permissions to the data directory.
Adding new service
New service added
Ended configuration step: Adjusting Windows service

Beginning configuration step: Initializing database (may take a long time)

Attempting to run MySQL Server with --initialize-insecure option...
Starting process for MySQL Server 8.0.31...
Starting process with command: C:\Program Files\MySQL\MySQL Server 8.0\bin\mysqld.exe --defaults-file="C:\ProgramData\MySQL\MySQL Server 8.0\my.ini" --console --initialize-insecure=on --lower-case-table-names=1...
C:\Program Files\MySQL\MySQL Server 8.0\bin\mysqld.exe (mysqld 8.0.31) initializing of server in progress as process 4428
InnoDB initialization has started.
InnoDB initialization has ended.
root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
Process for mysqld, with ID 4428, was run successfully and exited with code 0.
Successfully started process for MySQL Server 8.0.31.
MySQL Server 8.0.31 intialized the database successfully.
Ended configuration step: Initializing database (may take a long time)

Beginning configuration step: Updating permissions for the data folder and related server files

Attempting to update the permissions for the data folder and related server files...
Inherited permissions have been converted to explicit permissions.
Full control permissions granted to: NETWORK SERVICE.
Full control permissions granted to: Administrators.
Full control permissions granted to: CREATOR OWNER.
Full control permissions granted to: SYSTEM.
Access to the data directory is removed for the users group.
Permissions for the data folder and related server files are updated correctly.
Ended configuration step: Updating permissions for the data folder and related server files

Beginning configuration step: Starting the server

Attempting to start service MySQL80....................
A task may only be disposed if it is in a completion state (RanToCompletion, Faulted or Canceled).
Ended configuration step: Starting the server

.
I have already tried the following:-

Un-installed all the programs that were in any way related to MySQL.

Deleted the MySQL folder from C:\Program Files.

Cleared my registry.
and then re-installed the program

go to Start -> Control Panel -> Administrative Tools -> Services -> find MySQL56, right click on it -> Properties -> select Log On Tab AND HERE IS BUG -> Although Local System Account was selected, Somehow "This account: Network Service (with some password) was selected -> Select Log on as: Local System Account, Allow service to interact with desktop -> Apply -> Go back on general tab.

After installing it by mysqld --install. Try this mysqld --initialize. We got the same problem but it's now working.Admin_cmd- mysqld --install, mysqld --initialize


问:
Send message to iframe inside of a promise
I have this promise? How can I postMessage to an iframe from then. Currently i have function with timer that sends info on page load but i want to get more info.

```<code>const socket = io('/')
const videoGrid = document.getElementById('video-grid')
const myPeer = new Peer(undefined, {
  path: '/peerjs',
  host: '/',
  port: '3000'
})
const peers = {}
let myVideoStream;
const myVideo = document.createElement('video')
myVideo.muted = true;

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function brodcastStatus(postMsg) {
  for (let i = 0; i < 10; i++) {
    parent.postMessage(postMsg, "*");
    console.log(postMsg)
    await sleep(1500)
  }
}

if (KIND === 'server'){
  Promise.resolve(navigator.mediaDevices.getUserMedia({
    video: {
      width: 1920,
      height: 1080,
      aspectRatio: { ideal: 1.7777777778 },
      frameRate: { max: 24, }
    },
    audio: true
  })).then(stream => {
    brodcastStatus("server | camera | mic")
    myVideoStream = stream;

    myPeer.on('call', call => {
      call.answer(stream)
      const video = document.createElement('video')
      call.on('stream', userVideoStream => {
        addVideoStream(video, userVideoStream)
      })
    })

    socket.on('user-connected', userId => {
      connectToNewUser(userId, stream)
    })

  }).catch(() => {
    Promise.resolve(navigator.mediaDevices.getUserMedia({
      video: {
        width: 1920,
        height: 1080,
        aspectRatio: { ideal: 1.7777777778 },
        frameRate: { max: 24, }
      },
      audio: false
    })).then(stream => {
      brodcastStatus("server | camera | no mic")
      myVideoStream = stream;

      myPeer.on('call', call => {
        call.answer(stream)
        const video = document.createElement('video')
        call.on('stream', userVideoStream => {
          addVideoStream(video, userVideoStream)
        })
      })

      socket.on('user-connected', userId => {
        connectToNewUser(userId, stream)
      })

    }).catch(() => {
      console.log("nocamera or microphone")
    })
  })
}else if (KIND === 'client'){
  Promise.resolve(navigator.mediaDevices.getUserMedia({
    video: false,
    audio: true
  })).then(stream => {
    brodcastStatus("client | no camera | mic")
    myVideoStream = stream;

    myPeer.on('call', call => {
      call.answer(stream)
      const video = document.createElement('video')
      call.on('stream', userVideoStream => {
        addVideoStream(video, userVideoStream)
      })
    })

    socket.on('user-connected', userId => {
      connectToNewUser(userId, stream)
    })

  }).catch(() => {
    console.log("Client")
    newStream = new MediaStream();
    stream = newStream;
    myVideoStream = stream;
    myPeer.on('call', call => {
      call.answer(stream)
      const video = document.createElement('video')
      call.on('stream', userVideoStream => {
        addVideoStream(video, userVideoStream)
      })
    })

    socket.on('user-connected', userId => {
      connectToNewUser(userId, stream)
    })

  })

}

socket.on('user-disconnected', userId => {
  if (peers[userId]) peers[userId].close()
})

myPeer.on('open', id => {
  socket.emit('join-room', ROOM_ID, id)
})

function connectToNewUser(userId, stream) {
  const call = myPeer.call(userId, stream)
  const video = document.createElement('video')
  call.on('stream', userVideoStream => {
    addVideoStream(video, userVideoStream)
  })
  call.on('close', () => {
    video.remove()
  })

  peers[userId] = call
}

function addVideoStream(video, stream) {
  video.srcObject = stream
  video.setAttribute("style", "object-fit:cover; background: transparent url(/images/New_DACL_Logo.png) no-repeat center center; background-size: auto; overflow: hidden;")
  video.addEventListener('loadedmetadata', () => {
  })
  videoGrid.append(video)
}
</code>```

More context

this app send audio/video to user via webrtc. I using this webpage as an iframe in other application (flask) and i want to get some data about current connected user to lock/unlock other options

Body:
I have this promise? How can I postMessage to an iframe from then. Currently i have function with timer that sends info on page load but i want to get more info.

const socket = io('/')
const videoGrid = document.getElementById('video-grid')
const myPeer = new Peer(undefined, {
  path: '/peerjs',
  host: '/',
  port: '3000'
})
const peers = {}
let myVideoStream;
const myVideo = document.createElement('video')
myVideo.muted = true;

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function brodcastStatus(postMsg) {
  for (let i = 0; i < 10; i++) {
    parent.postMessage(postMsg, "*");
    console.log(postMsg)
    await sleep(1500)
  }
}

if (KIND === 'server'){
  Promise.resolve(navigator.mediaDevices.getUserMedia({
    video: {
      width: 1920,
      height: 1080,
      aspectRatio: { ideal: 1.7777777778 },
      frameRate: { max: 24, }
    },
    audio: true
  })).then(stream => {
    brodcastStatus("server | camera | mic")
    myVideoStream = stream;

    myPeer.on('call', call => {
      call.answer(stream)
      const video = document.createElement('video')
      call.on('stream', userVideoStream => {
        addVideoStream(video, userVideoStream)
      })
    })

    socket.on('user-connected', userId => {
      connectToNewUser(userId, stream)
    })

  }).catch(() => {
    Promise.resolve(navigator.mediaDevices.getUserMedia({
      video: {
        width: 1920,
        height: 1080,
        aspectRatio: { ideal: 1.7777777778 },
        frameRate: { max: 24, }
      },
      audio: false
    })).then(stream => {
      brodcastStatus("server | camera | no mic")
      myVideoStream = stream;

      myPeer.on('call', call => {
        call.answer(stream)
        const video = document.createElement('video')
        call.on('stream', userVideoStream => {
          addVideoStream(video, userVideoStream)
        })
      })

      socket.on('user-connected', userId => {
        connectToNewUser(userId, stream)
      })

    }).catch(() => {
      console.log("nocamera or microphone")
    })
  })
}else if (KIND === 'client'){
  Promise.resolve(navigator.mediaDevices.getUserMedia({
    video: false,
    audio: true
  })).then(stream => {
    brodcastStatus("client | no camera | mic")
    myVideoStream = stream;

    myPeer.on('call', call => {
      call.answer(stream)
      const video = document.createElement('video')
      call.on('stream', userVideoStream => {
        addVideoStream(video, userVideoStream)
      })
    })

    socket.on('user-connected', userId => {
      connectToNewUser(userId, stream)
    })

  }).catch(() => {
    console.log("Client")
    newStream = new MediaStream();
    stream = newStream;
    myVideoStream = stream;
    myPeer.on('call', call => {
      call.answer(stream)
      const video = document.createElement('video')
      call.on('stream', userVideoStream => {
        addVideoStream(video, userVideoStream)
      })
    })

    socket.on('user-connected', userId => {
      connectToNewUser(userId, stream)
    })

  })

}

socket.on('user-disconnected', userId => {
  if (peers[userId]) peers[userId].close()
})

myPeer.on('open', id => {
  socket.emit('join-room', ROOM_ID, id)
})

function connectToNewUser(userId, stream) {
  const call = myPeer.call(userId, stream)
  const video = document.createElement('video')
  call.on('stream', userVideoStream => {
    addVideoStream(video, userVideoStream)
  })
  call.on('close', () => {
    video.remove()
  })

  peers[userId] = call
}

function addVideoStream(video, stream) {
  video.srcObject = stream
  video.setAttribute("style", "object-fit:cover; background: transparent url(/images/New_DACL_Logo.png) no-repeat center center; background-size: auto; overflow: hidden;")
  video.addEventListener('loadedmetadata', () => {
  })
  videoGrid.append(video)
}

More context

this app send audio/video to user via webrtc. I using this webpage as an iframe in other application (flask) and i want to get some data about current connected user to lock/unlock other options


问:
Powershell Exchange Online email counting report
I'm trying to work on some monthly statistics for our company, where I could set a schedule task with powershell to get this data monthly. First of all, I would like to extract the total number of emails (received and sent) over the last 30 days.

I've been looking at the ExchangeOnlineManagement Module, and from what I can see, I would need to use the "Start-HistoricalSearch" to be able to retrieve emails. But I don't want to create a CSV of all emails, I just want as a result the total number of emails, but I can't seem to be able to do something like.

Has anyone had the same need or can help me understand how can I reach this goal?
Thanks


问:
How to store selected items from android multiplechoice list, max number of selected items allowed should be 5?
```<code>final String[] listContent = {"1", "2", "3", "4" ,"5","6", "7", "8", "9", "10" ,"11" };
ListView list;

//adapter
setListAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_multiple_choice, listContent));
    list.setItemsCanFocus(false);
    list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

//on item click method
StringBuilder vota = new StringBuilder();
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    SparseBooleanArray checked = list.getCheckedItemPositions();
    for (int i = 1; i < listContent.length; i++) {

        Log.i("Test", listContent[i] + ": " + checked.get(i));

        if(checked.get(i) == true)
           {
                           count++;
            if(count<=5)
             {
            vota.append(" "+listContent[i]);
            Log.i("vert",vota.toString());
             }
            else
            {
                     //it displays an alert dialogbox
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("You can't select more than 5 items!")
           .setCancelable(false)
           .setPositiveButton("Close", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   dialog.cancel();
               }
             });
        checked.delete(i);
        AlertDialog ert = builder.create();
        ert.show();

           }

             }
    }

}
</code>```

ContentLicense: CC BY-SA 3.0


问:
Not able to assign generated value using IdClass
I have a customer entity whose primary is a composite key. In the composite key one of the field is auto generated value.

```<code>@Entity
@AllArgsConstructor
@Builder
@Setter
@Getter
@IdClass(CustomerId.class)
public class Customer {

  @NotNull
  @Column(name = "account_id", nullable = false)
  private Long accountId;

  @NotNull
  @Column(name = "id", nullable = false)
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Size(max = 255)
  @Column(name = "first_name")
  private String firstName;
</code>```
```<code>@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class CustomerId implements Serializable {
  private static final long serialVersionUID = 8048935613697415032L;
  private Long accountId;

  private Long id;
}
</code>```

When i use below snippet of code to save the customer, i get below error

```<code>@PostMapping
public ResponseEntity create(@RequestBody Customer sc,
                             @RequestParam long account_id) {
  Customer saved = customerRepository.saveAndFlush(sc);
  return ResponseEntity.ok(saved);
}

</code>```

Error
org.springframework.orm.jpa.JpaSystemException: Could not set field value [POST_INSERT_INDICATOR] value by reflection : [class com.demo.service.entity.core.CustomerId.id] setter of com.demo.service.entity.core.CusotmerId.id;

Body:
I have a customer entity whose primary is a composite key. In the composite key one of the field is auto generated value.

@Entity
@AllArgsConstructor
@Builder
@Setter
@Getter
@IdClass(CustomerId.class)
public class Customer {

  @NotNull
  @Column(name = "account_id", nullable = false)
  private Long accountId;

  @NotNull
  @Column(name = "id", nullable = false)
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Size(max = 255)
  @Column(name = "first_name")
  private String firstName;

@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class CustomerId implements Serializable {
  private static final long serialVersionUID = 8048935613697415032L;
  private Long accountId;

  private Long id;
}

When i use below snippet of code to save the customer, i get below error

@PostMapping
public ResponseEntity create(@RequestBody Customer sc,
                             @RequestParam long account_id) {
  Customer saved = customerRepository.saveAndFlush(sc);
  return ResponseEntity.ok(saved);
}

Error
org.springframework.orm.jpa.JpaSystemException: Could not set field value [POST_INSERT_INDICATOR] value by reflection : [class com.demo.service.entity.core.CustomerId.id] setter of com.demo.service.entity.core.CusotmerId.id;


问:
Component not updating page style with prop value
I am unsure about the reason this is happening but the below code is not actually visually showing the image I am passing through, if I have a look into dev tools on chrome I can see the correct image written there however it's not loading through.

```<code>import React from 'react'
import { useState, useEffect } from "react"

export default function Banner(props) {
  const pngname = props.categoryName.replace(" ","").toLowerCase() + "tag"
  return (
    <div className={`bg-cover bg-center bg-[url('/image/${pngname}.png')]`}>
      <div style={{background: props.categoryColour+"59"}} className={`h-[300px] mb-6 flex items-center text-white dark:text-black `}>
        <div className='container mx-auto flex justify-center h-100'>
          <div>
            <span style={{opacity: 1}} className='text-5xl'>{props.categoryName}</span>
          </div>
        </div>
      </div>
    </div>
  )
}
</code>```

One thing I did notice is if I change the props.categoryName to a color such as #E8EAEF

```<code>import React from 'react'
import { useState } from "react"
export default function Banner(props) {
  return (
    <div style={{backgroundImage: props.categoryColour}} className={`h-[300px] mb-6 flex items-center text-white dark:text-black`}>
        <div className='container mx-auto flex justify-center h-100'>
          <div>
            <span className='text-5xl'>{props.categoryName}</span>
            <p className='text-5xl'>{props.categoryColour}</p>
          </div>
        </div>
    </div>
  )
}
</code>```

the above works, however the below doesn't work:

```<code>import React from 'react'
import { useState } from "react"

export default function Banner(props) {
  return (
    <div style={{backgroundImage: `linear-gradient(to right, ${props.categoryColour}, rgba(255,0,0,0));`}} className={`h-[300px] mb-6 flex items-center text-white dark:text-black`}>
        <div className='container mx-auto flex justify-center h-100'>
          <div>
            <span className='text-5xl'>{props.categoryName}</span>
            <p className='text-5xl'>{props.categoryColour}</p>
          </div>
        </div>
    </div>
  )
}
</code>```

Body:
I am unsure about the reason this is happening but the below code is not actually visually showing the image I am passing through, if I have a look into dev tools on chrome I can see the correct image written there however it's not loading through.

import React from 'react'
import { useState, useEffect } from "react"

export default function Banner(props) {
  const pngname = props.categoryName.replace(" ","").toLowerCase() + "tag"
  return (
    <div className={`bg-cover bg-center bg-[url('/image/${pngname}.png')]`}>
      <div style={{background: props.categoryColour+"59"}} className={`h-[300px] mb-6 flex items-center text-white dark:text-black `}>

            {props.categoryName}

  )
}

One thing I did notice is if I change the props.categoryName to a color such as #E8EAEF

import React from 'react'
import { useState } from "react"
export default function Banner(props) {
  return (
    <div style={{backgroundImage: props.categoryColour}} className={`h-[300px] mb-6 flex items-center text-white dark:text-black`}>

            {props.categoryName}

{props.categoryColour}

  )
}

the above works, however the below doesn't work:

import React from 'react'
import { useState } from "react"

export default function Banner(props) {
  return (
    <div style={{backgroundImage: `linear-gradient(to right, ${props.categoryColour}, rgba(255,0,0,0));`}} className={`h-[300px] mb-6 flex items-center text-white dark:text-black`}>

            {props.categoryName}

{props.categoryColour}

  )
}


问:
I want to capturing only icmp packet but getting error only
I am making a packet capture tool using pyshark and python argparse module. so I want to make a feature that only print the imcp when the command -ieth0 -I is used. but I am getting error.

as well the code only show the tcp and udp protocol . it does not show other protocol like imp, arp, etc while capturing the packet.

my code is below.

```<code>import argparse
import pyshark
import time
#import psutil

parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output', help = 'to save the file in pcap format')
parser.add_argument('-c','--count', help = 'to print limited number of packet',type=int)
parser.add_argument('-d','--dns', help = 'to print dns packet', required=False, action='store_ture)
parser.add_argument('-I', '--ICMP', required=False, action='store_true', help = 'to capture icm packet)
parser.add_argument('-t', '--tcp',required=False, action='store_true', help='to capture tcp packet)
parser.add_argument('-u','--udp',required=False, action='store_true', help='to cpature only udp)
parser.add_argument('-v', '--verbose', help='be more specific', default=False, action='store_true)
parser.add_argument('-i', '--interface',metavar="", type=str, required=True, help='network interface)
args = parser.parse_args()

if args.dns:
   print ("-----------------------------DNS packets only---------------------")
   capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='icmp')

#elif args.output:
 #  print ("---------------------------capture and save the packet-----------------")
   #capture = pyshark.LiveCapture(output_file=args.output)

elif args.count:
   capture = pyshark.LiveCapture(interface=args.interface)
   for packet in capture.sniff_continuously(packet_count=args.count):
       if packet == args.count:
          break

elif args.ICMP:
    print ("--------------------------ICMP packets only----------------------------")
    capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='icmp')

elif args.tcp:
    print ("--------------------------TCP packets only-----------------------------")
    capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='tcp')

elif args.udp:
    print ("------------------------UDP Packets only -----------------------------")
    capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='udp port 53')

else:
    capture = pyshark.LiveCapture(interface=args.interface, output_file=args.output)

packet_list =[]
for packet in capture.sniff_continuously():
    packet_list.append(packet)
    localtime = time.asctime(time.localtime(time.time()))
    protocol = packet.transport_layer
    src_addr = packet.ip.src
    src_port = packet[protocol].srcport
    dst_addr = packet.ip.dst
    dst_port = packet[protocol].dstport
    print(localtime,"\t",protocol,"\t", src_addr,"\t", src_port,"\t", dst_addr, "\t", dst_port)
    if args.verbose:
        print (packet.show())

</code>```

output

```<code>--------------------------ICMP packets only----------------------------
Traceback (most recent call last):
  File "/home/kali/help.py", line 54, in <module>
    src_port = packet[protocol].srcport
  File "/home/kali/.local/lib/python3.10/site-packages/pyshark/packet/packet.py", line 50, in __getitem__
    if layer.layer_name == item.lower():
AttributeError: 'NoneType' object has no attribute 'lower'

</code>```

Body:
I am making a packet capture tool using pyshark and python argparse module. so I want to make a feature that only print the imcp when the command -ieth0 -I is used. but I am getting error.

as well the code only show the tcp and udp protocol . it does not show other protocol like imp, arp, etc while capturing the packet.

my code is below.

import argparse
import pyshark
import time
#import psutil

parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output', help = 'to save the file in pcap format')
parser.add_argument('-c','--count', help = 'to print limited number of packet',type=int)
parser.add_argument('-d','--dns', help = 'to print dns packet', required=False, action='store_ture)
parser.add_argument('-I', '--ICMP', required=False, action='store_true', help = 'to capture icm packet)
parser.add_argument('-t', '--tcp',required=False, action='store_true', help='to capture tcp packet)
parser.add_argument('-u','--udp',required=False, action='store_true', help='to cpature only udp)
parser.add_argument('-v', '--verbose', help='be more specific', default=False, action='store_true)
parser.add_argument('-i', '--interface',metavar="", type=str, required=True, help='network interface)
args = parser.parse_args()

if args.dns:
   print ("-----------------------------DNS packets only---------------------")
   capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='icmp')

#elif args.output:
 #  print ("---------------------------capture and save the packet-----------------")
   #capture = pyshark.LiveCapture(output_file=args.output)

elif args.count:
   capture = pyshark.LiveCapture(interface=args.interface)
   for packet in capture.sniff_continuously(packet_count=args.count):
       if packet == args.count:
          break

elif args.ICMP:
    print ("--------------------------ICMP packets only----------------------------")
    capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='icmp')

elif args.tcp:
    print ("--------------------------TCP packets only-----------------------------")
    capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='tcp')

elif args.udp:
    print ("------------------------UDP Packets only -----------------------------")
    capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='udp port 53')

else:
    capture = pyshark.LiveCapture(interface=args.interface, output_file=args.output)

packet_list =[]
for packet in capture.sniff_continuously():
    packet_list.append(packet)
    localtime = time.asctime(time.localtime(time.time()))
    protocol = packet.transport_layer
    src_addr = packet.ip.src
    src_port = packet[protocol].srcport
    dst_addr = packet.ip.dst
    dst_port = packet[protocol].dstport
    print(localtime,"\t",protocol,"\t", src_addr,"\t", src_port,"\t", dst_addr, "\t", dst_port)
    if args.verbose:
        print (packet.show())

output

--------------------------ICMP packets only----------------------------
Traceback (most recent call last):
  File "/home/kali/help.py", line 54, in <module>
    src_port = packet[protocol].srcport
  File "/home/kali/.local/lib/python3.10/site-packages/pyshark/packet/packet.py", line 50, in __getitem__
    if layer.layer_name == item.lower():
AttributeError: 'NoneType' object has no attribute 'lower'


问:
Deploying Nodejs React project to Vercel - react-scripts: command not found
I'm very new to React and I've built a full-stack react application with NodeJS and Express, I'm trying to deploy it on Vercel but it gives me an error.
This is the hierarchy of my folders

```<code>.
backend/
frontend/
package.json
</code>```

package.json contains this script

```<code>"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node backend/index.js"
  },
</code>```

and inside the backend folder, I have another package.json that contains this

```<code>"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node backend/index.js",
    "build": "cd frontend && npm install && npm i react-scripts && npm run build"
  },
</code>```

When I try on vercel, this is what happens

```<code>Running "vercel build"
Vercel CLI 28.10.0
Installing dependencies...
yarn install v1.22.17
info No lockfile found.
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
Done in 4.87s.
sh: react-scripts: command not found
Error: Command "react-scripts build" exited with 127
</code>```

any ideas how to deploy it?

Body:
I'm very new to React and I've built a full-stack react application with NodeJS and Express, I'm trying to deploy it on Vercel but it gives me an error.
This is the hierarchy of my folders

.
backend/
frontend/
package.json

package.json contains this script

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node backend/index.js"
  },

and inside the backend folder, I have another package.json that contains this

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node backend/index.js",
    "build": "cd frontend && npm install && npm i react-scripts && npm run build"
  },

When I try on vercel, this is what happens

Running "vercel build"
Vercel CLI 28.10.0
Installing dependencies...
yarn install v1.22.17
info No lockfile found.
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
Done in 4.87s.
sh: react-scripts: command not found
Error: Command "react-scripts build" exited with 127

any ideas how to deploy it?


问:
What is the difference between Angular Material Theming all-component-colors and all-component-themes?
In this question, the issues were resolved by using all-component-colors instead of all-component-themes.

What is the difference between them and when should we use all-component-themes (this is what the Angular Material Documentation example uses and also this tutorial ...)?


问:
Font becomes blurry in chromium browsers when scrolling after an AJAX call
When calling an Ajax function then manually scrolling to the top of the page some elements become blurry and thicker/darker. Especially noticeable on  tags. Added info: The ajax call in question did not target the affected text in any way, it simple changed the rendered partial in a div further down the page.

Here is before the issue occurs

And after an Ajax call while the title was not on screen, and then scrolling back up

I have verified that no changes to the CSS or markup are occurring, and also confirmed that the various fixes for a previously known issue with hardware acceleration mentioned here do not resolve the issue.


问:
Write request.get response to json file in python
I am using requests.get in python for a URL to get the data as below:

```<code>import requests
username = 'ROAND'
password = dbutils.secrets.get("lab-secrets","ROSecret")
response = requests.get('https://pit.service.com/api/table', auth=(username,password))
</code>```

The count for this is

```<code>print(response.headers)
X-Total-Count': '799434'
</code>```

Im trying to load this into a json file as below:

```<code>data = response.content
with open('/path/file.json', 'wb') as f:
    f.write(data)
</code>```

But the file contains only 1439 records.

The json file content looks like the below image:

Ive tried multiple ways, but not successful.
I just want to exactly bring all my contents from requests.get into a json file.

Kindly help.

Body:
I am using requests.get in python for a URL to get the data as below:

import requests
username = 'ROAND'
password = dbutils.secrets.get("lab-secrets","ROSecret")
response = requests.get('https://pit.service.com/api/table', auth=(username,password))

The count for this is

print(response.headers)
X-Total-Count': '799434'

Im trying to load this into a json file as below:

data = response.content
with open('/path/file.json', 'wb') as f:
    f.write(data)

But the file contains only 1439 records.

The json file content looks like the below image:

Ive tried multiple ways, but not successful.
I just want to exactly bring all my contents from requests.get into a json file.

Kindly help.


问:
Using a sidecar to download artefacts in pod
I am rebuilding a system like gitlab where users can configure pipelines with individual jobs running on AWS ECS (Fargate).

One important functionality is donwloading and uploading of artefacts (files) generated by these jobs.

I want to solve this by running a sidecar with the logic responsible for the artefacts next to the actual code running the logic of the job.

one important requirement: it needs to be assumed that the "main" container runs custom code which i cannot control.

It seems however there is no clean solution in kubernetes for starting a pod with this order of containers:

start a sidecar, trigger download of artefacts

upon completion of artefacts download, start the logic in the main container alongside sidecar and run it to finish

upon finish of main container start upload of new artefacts and end sidecar.

Any suggestion is welcome

Edit:

I found the attribute of container dependencies on AWS ECS and will try it out now: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/example_task_definitions.html#example_task_definition-containerdependency


问:
How to create and update unique slug using typeorm?
I am new in typeorm. I am already complete many part in practice. But Now I am facing confused because I am not getting any docs or blogs about creating and updating an unique slug by title in typeorm. In mongoDB, we get a mongoose-slug-updater to automatically create and update slug. But in typeorm I am not getting anythings like this.

I am using

typeorm (0.3.11)

Postgre (pg- 8.8.0)

Nestjs (9.0.0)

Here is my blog entity-

```<code>@Entity()
export class Blog {
    @PrimaryGeneratedColumn()
    id: number;
    @Column({ type: "text", nullable: false })
    slug: string;
    @Column({ type: "text", nullable: false })
    title: string;
    @Column({ type: "text", nullable: false })
    body: string;
    @CreateDateColumn()
    created_at: Date;
    @UpdateDateColumn()
    updated_at: Date;
}
</code>```

How can I automatically create and update unique slug. Please help me anyone.

Body:
I am new in typeorm. I am already complete many part in practice. But Now I am facing confused because I am not getting any docs or blogs about creating and updating an unique slug by title in typeorm. In mongoDB, we get a mongoose-slug-updater to automatically create and update slug. But in typeorm I am not getting anythings like this.

I am using

typeorm (0.3.11)

Postgre (pg- 8.8.0)

Nestjs (9.0.0)

Here is my blog entity-

@Entity()
export class Blog {
    @PrimaryGeneratedColumn()
    id: number;
    @Column({ type: "text", nullable: false })
    slug: string;
    @Column({ type: "text", nullable: false })
    title: string;
    @Column({ type: "text", nullable: false })
    body: string;
    @CreateDateColumn()
    created_at: Date;
    @UpdateDateColumn()
    updated_at: Date;
}

How can I automatically create and update unique slug. Please help me anyone.


问:
Where is this TS message getting packageId from?
To display the component version in storybook stories I import the version from whatever component's package.json:

import { version } from '@my-foo/abc/package.json';

My IDE complains about this with the following message and I want to know where it is getting packageId from because I could just pull the version from there w/o that import. But, I can't figure out where it is from? Is it like a ts-lint special var and only available in like a ts-lint context or what? Any insight appreciated!


问:
Shopify Plus (Prestige-Theme) - Checkout Form Validation (where can I find it?)
I try to modify the CHECKOUT FORM VALIDATION of a Shopify Plus Store (Prestige-Theme).

But I can't find the file where the validation takes place!?

I want to check the adress field if there is a number included.
If not I want to present an error

Can someone help please...

Thanks


问:
Access to registry key is denied
I'm trying to set the value of a Registry key programmatically :

```<code>string keyname = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render\{ea7039cb-389f-4405-8497-b33ab9ff63d8}\Properties";

//GetValue works - the path is fine
var value = Registry.GetValue(keyname, "{a45c254e-df1c-4efd-8020-67d146a850e0},2", null);

//Access denied exception
Registry.SetValue(keyname, "{a45c254e-df1c-4efd-8020-67d146a850e0},2", "test");
</code>```

I'm starting Visual Studio as Administrator.
I've even added a manifest file to force the execution as Administrator.

When I try to modify the value using Regedit, it works.

Anybody has an idea of what is going on ?

Thanks,

Title: Access to registry key is denied

Body:
I'm trying to set the value of a Registry key programmatically :

string keyname = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render\{ea7039cb-389f-4405-8497-b33ab9ff63d8}\Properties";

//GetValue works - the path is fine
var value = Registry.GetValue(keyname, "{a45c254e-df1c-4efd-8020-67d146a850e0},2", null);

//Access denied exception
Registry.SetValue(keyname, "{a45c254e-df1c-4efd-8020-67d146a850e0},2", "test");

I'm starting Visual Studio as Administrator.
I've even added a manifest file to force the execution as Administrator.

When I try to modify the value using Regedit, it works.

Anybody has an idea of what is going on ?

Thanks,


问:
Homebrew different folder names of libraries
I had an issue building a gem on my Mac. To build a gem I needed to load an SSL library.

I found the answer right here but not quite like it was described. The answer said that I had to look for a folder

The library was built with homebrew and supposedly was in

/opt/homebrew/Cellar/openssl@1.1/1.1.1n/ Notice the weird n at the end?

Another comment said that it almost worked for him except

/opt/homebrew/Cellar/openssl@1.1/1.1.1q/

And in my case it was

/opt/homebrew/Cellar/openssl@1.1/1.1.1q/

It looked pretty weird for me. Is this a kind of internal versioning system from homebrew?


问:
what is assertion error with eigen meaning?
When I compute generalized eigen,I write this following code ,and the part of code :

```<code>Eigen::MatrixXcf get_Generalized_eigen(const Eigen::MatrixXf &A, const Eigen::MatrixXf &B){
    Eigen::GeneralizedEigenSolver<Eigen::MatrixXf> ges;
    ges.compute(A, B);
    // cout << "The (complex) generalzied eigenvalues are (alphas./beta): " << ges.eigenvalues().transpose() << endl;
    cout << ges.eigenvalues().transpose();
}
</code>```

and my err:

```<code>distance_matrix: /usr/include/eigen3/Eigen/src/Eigenvalues/GeneralizedEigenSolver.h:204: Eigen::GeneralizedEigenSolver<_MatrixType>::EigenvalueType Eigen::GeneralizedEigenSolver<_MatrixType>::eigenvalues() const [with _MatrixType = Eigen::Matrix<float, -1, -1>; Eigen::GeneralizedEigenSolver<_MatrixType>::EigenvalueType = Eigen::CwiseBinaryOp<Eigen::internal::scalar_quotient_op<std::complex<float>, float>, Eigen::Matrix<std::complex<float>, -1, 1>, Eigen::Matrix<float, -1, 1> >]: Assertion `m_valuesOkay && "GeneralizedEigenSolver is not initialized."' failed.
./setup.sh: line 6:  3609 Aborted                 ./distance_matrix
</code>```

can anyone help me ? thank a lot!

i am expecting to know why it happen and how to fix it.

Body:
When I compute generalized eigen,I write this following code ,and the part of code :

Eigen::MatrixXcf get_Generalized_eigen(const Eigen::MatrixXf &A, const Eigen::MatrixXf &B){
    Eigen::GeneralizedEigenSolver<Eigen::MatrixXf> ges;
    ges.compute(A, B);
    // cout << "The (complex) generalzied eigenvalues are (alphas./beta): " << ges.eigenvalues().transpose() << endl;
    cout << ges.eigenvalues().transpose();
}

and my err:

distance_matrix: /usr/include/eigen3/Eigen/src/Eigenvalues/GeneralizedEigenSolver.h:204: Eigen::GeneralizedEigenSolver<_MatrixType>::EigenvalueType Eigen::GeneralizedEigenSolver<_MatrixType>::eigenvalues() const [with _MatrixType = Eigen::Matrix<float, -1, -1>; Eigen::GeneralizedEigenSolver<_MatrixType>::EigenvalueType = Eigen::CwiseBinaryOp<Eigen::internal::scalar_quotient_op<std::complex<float>, float>, Eigen::Matrix<std::complex<float>, -1, 1>, Eigen::Matrix<float, -1, 1> >]: Assertion `m_valuesOkay && "GeneralizedEigenSolver is not initialized."' failed.
./setup.sh: line 6:  3609 Aborted                 ./distance_matrix

can anyone help me ? thank a lot!

i am expecting to know why it happen and how to fix it.


问:
Why does QThread freezes Gui Thread while working?
I need to keep updating the table to have up-to-date information. To do this, I created a Thread and implemented an infinite loop in it, which iterates through all the values and compares them, but for some reason the work of this thread affects GUI and as a result, the thread with GUI freezes.

```<code>import random
import sys

import pandas as pd
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import QObject, pyqtSignal, Qt, QThread, QModelIndex
from PyQt5.QtWidgets import QApplication, QMainWindow

class TableModel(QtCore.QAbstractTableModel):

    def __init__(self, header: list):
        super(TableModel, self).__init__()
        self._data = pd.DataFrame(columns=header)

    def data(self, index, role=Qt.DisplayRole):
        if index.isValid():
            if role == Qt.DisplayRole:
                return self._data.values[index.row()][index.column()]
        return None

    def rowCount(self, parent: QModelIndex = ...) -> int:
        return len(self._data.values)

    def columnCount(self, index):
        return self._data.columns.size

    def headerData(self, section, orientation, role):
        # section is the index of the column/row.
        if role == Qt.DisplayRole:
            if orientation == Qt.Horizontal:
                return str(self._data.columns[section])

            if orientation == Qt.Vertical:
                return str(self._data.index[section])

    def setData(self, index, value, role):
        if not index.isValid():
            return False
        row = index.row()
        if row < 0 or row >= len(self._data.values):
            return False
        column = index.column()
        if column < 0 or column >= self._data.columns.size:
            return False
        self._data.iloc[row, column] = value
        self.dataChanged.emit(index, index)
        return True

    def removeRows(self, position, rows, parent=QModelIndex()):
        start, end = position, position + rows - 1
        if 0 <= start <= end < self.rowCount(parent):
            self.beginRemoveRows(parent, start, end)
            for index in range(start, end + 1):
                self._data.drop(index, inplace=True)
            self._data.reset_index(drop=True, inplace=True)
            self.endRemoveRows()
            return True
        return False

    def insertRows(self, position, rows, parent=QModelIndex()):
        start, end = position, position + rows - 1
        if 0 <= start <= end:
            self.beginInsertRows(parent, start, end)
            for index in range(start, end + 1):
                default_row = [[None] for _ in range(self._data.shape[1])]
                new_df = pd.DataFrame(dict(zip(list(self._data.columns), default_row)))
                self._data = pd.concat([self._data, new_df])
            self._data = self._data.reset_index(drop=True)
            self.endInsertRows()
            return True
        return False

    def addRow(self, item):
        self.insertRows(self.rowCount(), 1)

        row = self.rowCount() - 1
        self.setData(self.index(row, 0), item[0], Qt.DisplayRole)
        self.setData(self.index(row, 1), item[1], Qt.DisplayRole)
        self.setData(self.index(row, 2), item[2], Qt.DisplayRole)
        self.setData(self.index(row, 3), item[3], Qt.DisplayRole)
        self.setData(self.index(row, 4), item[4], Qt.DisplayRole)

    def getTable(self):
        return self._data

class Updater(QObject):
    addRow = pyqtSignal(object)

    def __init__(self, table: TableModel):
        super().__init__()
        self.items = []
        for i in range(50):
            item = [
                random.randint(10, 100),
                random.randint(10, 100),
                random.randint(10, 100),
                random.randint(10, 100),
                random.randint(10, 100),
            ]
            self.items.append(item)
        self._table = table
        self._status = False

    def start(self):
        self._status = True

        if self._table.getTable().empty:
            items = self.items
            for item in items:
                self.addRow.emit(item)

        while self._status:
            self.Update(self.items)

    def Update(self, items: list):
        # This function is looking for items in table and changes data if its not up-to-date

        data = self._table.getTable()
        for item in items:
            result = data.loc[
                (data['Col1'] == item[0]) &
                (data['Col2'] == item[1]) &
                (data['Col3'] == item[2])
                ]
            if len(result.values) != 0:
                pass
                # Code ...

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setObjectName("MainWindow")
        self.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(self)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.gridLayout = QtWidgets.QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        self.tableWidget = QtWidgets.QTableView(self.centralwidget)
        self.tableWidget.setObjectName("tableWidget")
        self.gridLayout.addWidget(self.tableWidget, 0, 0, 1, 1)
        self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)
        self.setCentralWidget(self.centralwidget)

        header = ["Col1", "Col2", "Col3", "Col4", "Col5"]

        self.model = TableModel(header)
        self.tableWidget.setModel(self.model)

        self._updater = Updater(self.model)
        self._thread = QThread()
        self._updater.moveToThread(self._thread)

        self._thread.started.connect(self._updater.start)
        self._thread.finished.connect(self._thread.deleteLater)

        self._updater.addRow.connect(self.model.addRow, Qt.QueuedConnection)

        self.show()
        self._thread.start()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())
</code>```

Do not judge strictly. I've only recently started learning pyqt and I don't really understand it yet.Thank you in advance!

Body:
I need to keep updating the table to have up-to-date information. To do this, I created a Thread and implemented an infinite loop in it, which iterates through all the values and compares them, but for some reason the work of this thread affects GUI and as a result, the thread with GUI freezes.

import random
import sys

import pandas as pd
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import QObject, pyqtSignal, Qt, QThread, QModelIndex
from PyQt5.QtWidgets import QApplication, QMainWindow

class TableModel(QtCore.QAbstractTableModel):

    def __init__(self, header: list):
        super(TableModel, self).__init__()
        self._data = pd.DataFrame(columns=header)

    def data(self, index, role=Qt.DisplayRole):
        if index.isValid():
            if role == Qt.DisplayRole:
                return self._data.values[index.row()][index.column()]
        return None

    def rowCount(self, parent: QModelIndex = ...) -> int:
        return len(self._data.values)

    def columnCount(self, index):
        return self._data.columns.size

    def headerData(self, section, orientation, role):
        # section is the index of the column/row.
        if role == Qt.DisplayRole:
            if orientation == Qt.Horizontal:
                return str(self._data.columns[section])

            if orientation == Qt.Vertical:
                return str(self._data.index[section])

    def setData(self, index, value, role):
        if not index.isValid():
            return False
        row = index.row()
        if row < 0 or row >= len(self._data.values):
            return False
        column = index.column()
        if column < 0 or column >= self._data.columns.size:
            return False
        self._data.iloc[row, column] = value
        self.dataChanged.emit(index, index)
        return True

    def removeRows(self, position, rows, parent=QModelIndex()):
        start, end = position, position + rows - 1
        if 0 <= start <= end < self.rowCount(parent):
            self.beginRemoveRows(parent, start, end)
            for index in range(start, end + 1):
                self._data.drop(index, inplace=True)
            self._data.reset_index(drop=True, inplace=True)
            self.endRemoveRows()
            return True
        return False

    def insertRows(self, position, rows, parent=QModelIndex()):
        start, end = position, position + rows - 1
        if 0 <= start <= end:
            self.beginInsertRows(parent, start, end)
            for index in range(start, end + 1):
                default_row = [[None] for _ in range(self._data.shape[1])]
                new_df = pd.DataFrame(dict(zip(list(self._data.columns), default_row)))
                self._data = pd.concat([self._data, new_df])
            self._data = self._data.reset_index(drop=True)
            self.endInsertRows()
            return True
        return False

    def addRow(self, item):
        self.insertRows(self.rowCount(), 1)

        row = self.rowCount() - 1
        self.setData(self.index(row, 0), item[0], Qt.DisplayRole)
        self.setData(self.index(row, 1), item[1], Qt.DisplayRole)
        self.setData(self.index(row, 2), item[2], Qt.DisplayRole)
        self.setData(self.index(row, 3), item[3], Qt.DisplayRole)
        self.setData(self.index(row, 4), item[4], Qt.DisplayRole)

    def getTable(self):
        return self._data

class Updater(QObject):
    addRow = pyqtSignal(object)

    def __init__(self, table: TableModel):
        super().__init__()
        self.items = []
        for i in range(50):
            item = [
                random.randint(10, 100),
                random.randint(10, 100),
                random.randint(10, 100),
                random.randint(10, 100),
                random.randint(10, 100),
            ]
            self.items.append(item)
        self._table = table
        self._status = False

    def start(self):
        self._status = True

        if self._table.getTable().empty:
            items = self.items
            for item in items:
                self.addRow.emit(item)

        while self._status:
            self.Update(self.items)

    def Update(self, items: list):
        # This function is looking for items in table and changes data if its not up-to-date

        data = self._table.getTable()
        for item in items:
            result = data.loc[
                (data['Col1'] == item[0]) &
                (data['Col2'] == item[1]) &
                (data['Col3'] == item[2])
                ]
            if len(result.values) != 0:
                pass
                # Code ...

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setObjectName("MainWindow")
        self.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(self)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.gridLayout = QtWidgets.QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        self.tableWidget = QtWidgets.QTableView(self.centralwidget)
        self.tableWidget.setObjectName("tableWidget")
        self.gridLayout.addWidget(self.tableWidget, 0, 0, 1, 1)
        self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)
        self.setCentralWidget(self.centralwidget)

        header = ["Col1", "Col2", "Col3", "Col4", "Col5"]

        self.model = TableModel(header)
        self.tableWidget.setModel(self.model)

        self._updater = Updater(self.model)
        self._thread = QThread()
        self._updater.moveToThread(self._thread)

        self._thread.started.connect(self._updater.start)
        self._thread.finished.connect(self._thread.deleteLater)

        self._updater.addRow.connect(self.model.addRow, Qt.QueuedConnection)

        self.show()
        self._thread.start()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())

Do not judge strictly. I've only recently started learning pyqt and I don't really understand it yet.Thank you in advance!


问:
how do i align manual and db data when new rows are added in db
I have a Access database that I am getting data from, I added a col right next to the data.I use this col to add some data to it manually. Rows are added to the top of the table and everytime rows are added the manual data col and the Db data get misaligned?

since i am not too techy this is what could come up with

Sub addcells()

x = Worksheets("SaleRates").Range("F:f")
xrows = Application.WorksheetFunction.count(x) + 1
Range("o2") = xrows - Range("O1")
insrow = Range("O2").Value

If Range("O2").Value > 0 Then

Range("Z1:Z" & insrow).Select
Selection.Copy
Range("M2").Select
Selection.Insert Shift:=xlDown

End If

End Sub
```

I just call this sub using a worksheet_change event in the required worksheet. it does not work because it cant insert cells in table. This works if i resize table and remove the manual col from it but it does nto work when data is modified or deleted

Body:
I have a Access database that I am getting data from, I added a col right next to the data.I use this col to add some data to it manually. Rows are added to the top of the table and everytime rows are added the manual data col and the Db data get misaligned?

since i am not too techy this is what could come up with

Sub addcells()

x = Worksheets("SaleRates").Range("F:f")
xrows = Application.WorksheetFunction.count(x) + 1
Range("o2") = xrows - Range("O1")
insrow = Range("O2").Value

If Range("O2").Value > 0 Then

Range("Z1:Z" & insrow).Select
Selection.Copy
Range("M2").Select
Selection.Insert Shift:=xlDown

End If

End Sub

I just call this sub using a worksheet_change event in the required worksheet. it does not work because it cant insert cells in table. This works if i resize table and remove the manual col from it but it does nto work when data is modified or deleted