问:
Bundle install requiring gem not in gemfile
I've got an application that I'm trying to fix and build. I am having a hard time getting paste this error:

```<code>****$ bundle update
/usr/share/rvm/gems/ruby-2.1.5@global/gems/bundler-1.7.6/lib/bundler.rb:302: warning: Insecure world writable dir /usr/share/rvm in PATH, mode 042777
Updating https://github.com/Compass/compass-rails
Updating https://github.com/DavyJonesLocker/client_side_validations-simple_form
Updating https://github.com/DavyJonesLocker/client_side_validations
Updating https://github.com/seyhunak/twitter-bootstrap-rails.git
Fetching source index from https://rubygems.org/
Resolving dependencies........
Using rake 12.0.0
Using i18n 0.7.0
Using json 1.8.0
Using minitest 5.10.3
Using thread_safe 0.3.6
Using tzinfo 1.2.10 (was 1.2.3)
Using activesupport 4.2.5
Using builder 3.2.4 (was 3.2.3)
Using erubis 2.7.0
Using mini_portile2 2.1.0
Using nokogiri 1.6.8.1
Using rails-deprecated_sanitizer 1.0.4 (was 1.0.3)
Using rails-dom-testing 1.0.9 (was 1.0.8)
Using crass 1.0.6
Using loofah 2.19.1 (was 2.0.3)
Using rails-html-sanitizer 1.4.4 (was 1.0.3)
Using actionview 4.2.5
Using rack 1.6.13 (was 1.6.8)
Using rack-test 0.6.3
Using actionpack 4.2.5
Using globalid 0.4.2 (was 0.3.6)
Using activejob 4.2.5
Using mini_mime 1.1.2

Gem::InstallError: date requires Ruby version >= 2.6.0.
An error occurred while installing date (3.3.3), and Bundler cannot continue.
Make sure that `gem install date -v '3.3.3'` succeeds before bundling.
****$
</code>```

Updates:

I've tried looping through the gems in the file, I cannot find a single gem that requires date.

The gen file has a lot of gems and I used gem dependency {gem} and kept looping through what I found. Nothing, I went through 30 iterations.

I also did gem dependency date --reverse-dependencies again nothing.

```<code>source 'https://rubygems.org'

gem 'rails', '4.2.5'
gem 'concurrent-ruby', '1.0.0'
gem 'minitest', "5.10.3"
gem 'connection_pool', "2.2.0"

#gem for facebook bot
gem 'facebook-messenger' , "0.11.1"
# Bundle edge Rails instead:
# gem 'rails',     :git => 'git://github.com/rails/rails.git'
gem 'mysql2', '0.3.20' #, '~> 0.3.13'
gem 'rack-ssl', '1.3.4', :require => 'rack/ssl'
gem 'execjs', '2.6.0'
#gem 'therubyracer'
#gem 'rack' , '1.4.5'
gem 'json', '1.8.0'
gem 'protected_attributes', '1.1.3'
gem 'gdata_19', '1.1.5'
gem 'foreverb', '0.3.3'
gem 'paper_trail', '3.0.1'
gem 'rack-cors', '0.4.0'
#gem 'exception_notification'
gem 'social-share-button', '0.8.0'
# gem 'contacts', :git => 'git@github.com:eofferma/contacts.git'
# Deploy with Capistrano

gem 'puma', '3.4.0'
gem 'noty-rails', '2.3.8'
#gem 'rvm-capistrano'
gem 'active_model_serializers', '0.9.3'
gem "font-awesome-rails", '4.6.3.0'
gem 'therubyracer', '0.12.2', platforms: :ruby
gem 'sunspot_rails','2.2.0'
gem 'sunspot_solr', '2.2.2'
gem 'capybara', '2.7.1'
gem 'poltergeist', '1.8.1'
gem 'simplecov', '0.8.2', :require => false, :group => :test

gem 'sidekiq', '4.1.1'

group :development do
  gem "better_errors", "2.1.1"
  gem "binding_of_caller", "0.7.2"
  gem 'quiet_assets', '1.1.0'
end

gem 'nokogiri', "1.6.8.1"
gem 'sprockets', "3.5.2"

gem 'sass-rails',"5.0.4"
gem 'compass-rails', git: "https://github.com/Compass/compass-rails", branch: "master"
#gem 'compass-rails', github: "Compass/compass-rails", branch: "master"
gem 'uglifier', "2.7.2"
gem 'compass', "1.0.3"
gem 'compass-h5bp', '0.1.1'

gem 'haml-rails', "0.9.0"  # Optional - to generate haml

gem 'jquery-rails' , "4.1.0" #must be fixed because current version of multiselect widget doesn't work with jquery version >= 1.8.0
gem 'fancybox-rails', "0.3.1"
gem 'jquery-ui-rails', "5.0.5"
gem 'html5-rails', '0.1.0'

# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'

# Use unicorn as the web server
# gem 'unicorn'

# Deploy with Capistrano
# gem 'capistrano'

# To use debugger
# gem 'ruby-debug'
gem 'slim-rails', "3.0.1"
gem 'devise', "4.3.0"
gem 'devise-encryptable', "0.1.2"
#gem 'devise-token_authenticatable'
gem 'coffee-rails', "4.1.0"

gem "omniauth-facebook", "4.0.0"
gem "omniauth-twitter", "1.4.0"
gem "omniauth-google-oauth2", "0.5.2"

gem "koala", "2.2.0"
gem "fb_graph", "2.7.17"
gem 'twitter', "5.15.0"

gem "ancestry", "2.1.0"
gem 'simple_form', "3.2.0"
gem 'client_side_validations-simple_form', git: 'https://github.com/DavyJonesLocker/client_side_validations-simple_form', :ref => 'e6b61d5a82537a4d1d6d5259b8fd07f865ef89c9'
#gem 'client_side_validations-simple_form', github: 'DavyJonesLocker/client_side_validations-simple_form'
gem 'paperclip', '4.2.0'
gem 'aws-sdk', '< 2.0'
#gem 'client_side_validations'
gem 'client_side_validations', git: 'https://github.com/DavyJonesLocker/client_side_validations', :ref => '4f000000a858a46d830a4b2aec1e8d6f41f58685'
#gem 'client_side_validations', github: 'DavyJonesLocker/client_side_validations'

gem 'will_paginate', "3.0.7"
gem 'browser', "1.0.1"
#gem 'twitter-bootstrap-rails', :git => 'git@github.com:seyhunak/twitter-bootstrap-rails.git', :branch => 'bootstrap3'
gem 'twitter-bootstrap-rails', :git => 'https://github.com/seyhunak/twitter-bootstrap-rails.git', :branch => 'bootstrap3'

# gem 'geokit-rails'

gem "recaptcha", '0.5.0', :require => "recaptcha/rails"

gem 'whenever', "0.9.4", :require => false
gem "activemerchant", "1.43.3"
gem "hpricot", "0.8.6"
gem 'money', "6.6.1"
gem 'contacts', "1.2.4"

gem "paypal-sdk-merchant", "1.116.0"
gem 'paypal-sdk-adaptivepayments', "1.117.0"

gem 'fastercsv', "1.5.5"

gem 'cmess', "0.5.0"

gem "grape", "0.13.0"
gem 'wine_bouncer', '0.5.0'

gem 'httparty', "0.13.7"
gem 'delayed_job_active_record', "4.1.0"
gem "daemons", "1.2.3"
gem "rake", "12.0.0"
gem "rake-progressbar", "0.0.5"
gem "httpclient", "2.7.0.1"

gem 'typhoeus', "0.8.0"
gem 'tire', "0.6.2"
gem 'roo', '1.10.3'
# gem 'rubyzip', '< 1.0.0', :require => false
gem 'google_places', "0.32.0"
gem 'foursquare2', "2.0.2"
gem 'twilio-ruby', "4.8.0"
gem 'mechanize', "2.7.3"
gem 'orm_adapter', "0.5.0"

# gem 'capybara'

# gem 'wombat'
# gem 'capybara-webkit'
#gem 'elasticsearch'
gem 'rails3-jquery-autocomplete', "1.0.15"
gem 'selenium-webdriver', '2.53.4'
# gem 'selenium-webdriver'
# gem 'poltergeist'

group :test do
        # gem 'phantomjs', :require => 'phantomjs/poltergeist'
        gem 'database_cleaner', "1.5.1"
        gem 'rspec-rails', "3.4.0"
        # gem 'selenium-webdriver'
        # gem 'poltergeist'
end

group :development, :test do
  gem 'thin', "1.7.0"
  #gem 'machinist'
  gem 'faker', "1.5.0"
  gem 'rails-dev-tweaks', "1.2.0"

  gem 'byebug', "8.2.1"
end

gem "paranoia", "2.1.4"

gem 'rails-observers', "0.1.2"
gem 'activerecord-session_store', "0.1.2"

gem 'useragent', "0.10.0"

gem 'acts_as_commentable', "4.0.2"
gem "iconv", "1.0.4"
gem "rails-erd", "1.4.1"
gem 'zeroclipboard-rails', "0.1.1"

#source 'https://rails-assets.org' do
  #gem 'rails-assets-reveal'
#end
</code>```

Body:
I've got an application that I'm trying to fix and build. I am having a hard time getting paste this error:

****$ bundle update
/usr/share/rvm/gems/ruby-2.1.5@global/gems/bundler-1.7.6/lib/bundler.rb:302: warning: Insecure world writable dir /usr/share/rvm in PATH, mode 042777
Updating https://github.com/Compass/compass-rails
Updating https://github.com/DavyJonesLocker/client_side_validations-simple_form
Updating https://github.com/DavyJonesLocker/client_side_validations
Updating https://github.com/seyhunak/twitter-bootstrap-rails.git
Fetching source index from https://rubygems.org/
Resolving dependencies........
Using rake 12.0.0
Using i18n 0.7.0
Using json 1.8.0
Using minitest 5.10.3
Using thread_safe 0.3.6
Using tzinfo 1.2.10 (was 1.2.3)
Using activesupport 4.2.5
Using builder 3.2.4 (was 3.2.3)
Using erubis 2.7.0
Using mini_portile2 2.1.0
Using nokogiri 1.6.8.1
Using rails-deprecated_sanitizer 1.0.4 (was 1.0.3)
Using rails-dom-testing 1.0.9 (was 1.0.8)
Using crass 1.0.6
Using loofah 2.19.1 (was 2.0.3)
Using rails-html-sanitizer 1.4.4 (was 1.0.3)
Using actionview 4.2.5
Using rack 1.6.13 (was 1.6.8)
Using rack-test 0.6.3
Using actionpack 4.2.5
Using globalid 0.4.2 (was 0.3.6)
Using activejob 4.2.5
Using mini_mime 1.1.2

Gem::InstallError: date requires Ruby version >= 2.6.0.
An error occurred while installing date (3.3.3), and Bundler cannot continue.
Make sure that `gem install date -v '3.3.3'` succeeds before bundling.
****$

Updates:

I've tried looping through the gems in the file, I cannot find a single gem that requires date.

The gen file has a lot of gems and I used gem dependency {gem} and kept looping through what I found. Nothing, I went through 30 iterations.

I also did gem dependency date --reverse-dependencies again nothing.

source 'https://rubygems.org'

gem 'rails', '4.2.5'
gem 'concurrent-ruby', '1.0.0'
gem 'minitest', "5.10.3"
gem 'connection_pool', "2.2.0"

#gem for facebook bot
gem 'facebook-messenger' , "0.11.1"
# Bundle edge Rails instead:
# gem 'rails',     :git => 'git://github.com/rails/rails.git'
gem 'mysql2', '0.3.20' #, '~> 0.3.13'
gem 'rack-ssl', '1.3.4', :require => 'rack/ssl'
gem 'execjs', '2.6.0'
#gem 'therubyracer'
#gem 'rack' , '1.4.5'
gem 'json', '1.8.0'
gem 'protected_attributes', '1.1.3'
gem 'gdata_19', '1.1.5'
gem 'foreverb', '0.3.3'
gem 'paper_trail', '3.0.1'
gem 'rack-cors', '0.4.0'
#gem 'exception_notification'
gem 'social-share-button', '0.8.0'
# gem 'contacts', :git => 'git@github.com:eofferma/contacts.git'
# Deploy with Capistrano

gem 'puma', '3.4.0'
gem 'noty-rails', '2.3.8'
#gem 'rvm-capistrano'
gem 'active_model_serializers', '0.9.3'
gem "font-awesome-rails", '4.6.3.0'
gem 'therubyracer', '0.12.2', platforms: :ruby
gem 'sunspot_rails','2.2.0'
gem 'sunspot_solr', '2.2.2'
gem 'capybara', '2.7.1'
gem 'poltergeist', '1.8.1'
gem 'simplecov', '0.8.2', :require => false, :group => :test

gem 'sidekiq', '4.1.1'

group :development do
  gem "better_errors", "2.1.1"
  gem "binding_of_caller", "0.7.2"
  gem 'quiet_assets', '1.1.0'
end

gem 'nokogiri', "1.6.8.1"
gem 'sprockets', "3.5.2"

gem 'sass-rails',"5.0.4"
gem 'compass-rails', git: "https://github.com/Compass/compass-rails", branch: "master"
#gem 'compass-rails', github: "Compass/compass-rails", branch: "master"
gem 'uglifier', "2.7.2"
gem 'compass', "1.0.3"
gem 'compass-h5bp', '0.1.1'

gem 'haml-rails', "0.9.0"  # Optional - to generate haml

gem 'jquery-rails' , "4.1.0" #must be fixed because current version of multiselect widget doesn't work with jquery version >= 1.8.0
gem 'fancybox-rails', "0.3.1"
gem 'jquery-ui-rails', "5.0.5"
gem 'html5-rails', '0.1.0'

# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'

# Use unicorn as the web server
# gem 'unicorn'

# Deploy with Capistrano
# gem 'capistrano'

# To use debugger
# gem 'ruby-debug'
gem 'slim-rails', "3.0.1"
gem 'devise', "4.3.0"
gem 'devise-encryptable', "0.1.2"
#gem 'devise-token_authenticatable'
gem 'coffee-rails', "4.1.0"

gem "omniauth-facebook", "4.0.0"
gem "omniauth-twitter", "1.4.0"
gem "omniauth-google-oauth2", "0.5.2"

gem "koala", "2.2.0"
gem "fb_graph", "2.7.17"
gem 'twitter', "5.15.0"

gem "ancestry", "2.1.0"
gem 'simple_form', "3.2.0"
gem 'client_side_validations-simple_form', git: 'https://github.com/DavyJonesLocker/client_side_validations-simple_form', :ref => 'e6b61d5a82537a4d1d6d5259b8fd07f865ef89c9'
#gem 'client_side_validations-simple_form', github: 'DavyJonesLocker/client_side_validations-simple_form'
gem 'paperclip', '4.2.0'
gem 'aws-sdk', '< 2.0'
#gem 'client_side_validations'
gem 'client_side_validations', git: 'https://github.com/DavyJonesLocker/client_side_validations', :ref => '4f000000a858a46d830a4b2aec1e8d6f41f58685'
#gem 'client_side_validations', github: 'DavyJonesLocker/client_side_validations'

gem 'will_paginate', "3.0.7"
gem 'browser', "1.0.1"
#gem 'twitter-bootstrap-rails', :git => 'git@github.com:seyhunak/twitter-bootstrap-rails.git', :branch => 'bootstrap3'
gem 'twitter-bootstrap-rails', :git => 'https://github.com/seyhunak/twitter-bootstrap-rails.git', :branch => 'bootstrap3'

# gem 'geokit-rails'

gem "recaptcha", '0.5.0', :require => "recaptcha/rails"

gem 'whenever', "0.9.4", :require => false
gem "activemerchant", "1.43.3"
gem "hpricot", "0.8.6"
gem 'money', "6.6.1"
gem 'contacts', "1.2.4"

gem "paypal-sdk-merchant", "1.116.0"
gem 'paypal-sdk-adaptivepayments', "1.117.0"

gem 'fastercsv', "1.5.5"

gem 'cmess', "0.5.0"

gem "grape", "0.13.0"
gem 'wine_bouncer', '0.5.0'

gem 'httparty', "0.13.7"
gem 'delayed_job_active_record', "4.1.0"
gem "daemons", "1.2.3"
gem "rake", "12.0.0"
gem "rake-progressbar", "0.0.5"
gem "httpclient", "2.7.0.1"

gem 'typhoeus', "0.8.0"
gem 'tire', "0.6.2"
gem 'roo', '1.10.3'
# gem 'rubyzip', '< 1.0.0', :require => false
gem 'google_places', "0.32.0"
gem 'foursquare2', "2.0.2"
gem 'twilio-ruby', "4.8.0"
gem 'mechanize', "2.7.3"
gem 'orm_adapter', "0.5.0"

# gem 'capybara'

# gem 'wombat'
# gem 'capybara-webkit'
#gem 'elasticsearch'
gem 'rails3-jquery-autocomplete', "1.0.15"
gem 'selenium-webdriver', '2.53.4'
# gem 'selenium-webdriver'
# gem 'poltergeist'

group :test do
        # gem 'phantomjs', :require => 'phantomjs/poltergeist'
        gem 'database_cleaner', "1.5.1"
        gem 'rspec-rails', "3.4.0"
        # gem 'selenium-webdriver'
        # gem 'poltergeist'
end

group :development, :test do
  gem 'thin', "1.7.0"
  #gem 'machinist'
  gem 'faker', "1.5.0"
  gem 'rails-dev-tweaks', "1.2.0"

  gem 'byebug', "8.2.1"
end

gem "paranoia", "2.1.4"

gem 'rails-observers', "0.1.2"
gem 'activerecord-session_store', "0.1.2"

gem 'useragent', "0.10.0"

gem 'acts_as_commentable', "4.0.2"
gem "iconv", "1.0.4"
gem "rails-erd", "1.4.1"
gem 'zeroclipboard-rails', "0.1.1"

#source 'https://rails-assets.org' do
  #gem 'rails-assets-reveal'
#end


来源: stackexchange

问:
TripleDES Specified initialization vector (IV) does not match the block size for this algorithm. (Parameter 'rgbIV')
I have next code on .net 6:

```<code>using var algorithm = TripleDES.Create();
var bytes1 = Encoding.UTF8.GetBytes(Keys.CryptKey);
var bytes2 = Encoding.UTF8.GetBytes(Keys.Crypt4);

using var transform = algorithm.CreateEncryptor(bytes1, bytes2);
algorithm.Mode = CipherMode.ECB;
var buffer = Encoding.UTF8.GetBytes(text);
var outBuffer = transform.TransformFinalBlock(buffer, 0, buffer.Length);
return Convert.ToBase64String(outBuffer);
</code>```

It works on .net framework 4.8.

bytes1 and bytes2 are 24 length

When I create an encryptor, I get this error: Specified initialization vector (IV) does not match the block size for this algorithm. (Parameter 'rgbIV')'

I tried to set keys to 8 and 16 length

ContentLicense: CC BY-SA 4.0

Body:
I have next code on .net 6:

using var algorithm = TripleDES.Create();
var bytes1 = Encoding.UTF8.GetBytes(Keys.CryptKey);
var bytes2 = Encoding.UTF8.GetBytes(Keys.Crypt4);

using var transform = algorithm.CreateEncryptor(bytes1, bytes2);
algorithm.Mode = CipherMode.ECB;
var buffer = Encoding.UTF8.GetBytes(text);
var outBuffer = transform.TransformFinalBlock(buffer, 0, buffer.Length);
return Convert.ToBase64String(outBuffer);

It works on .net framework 4.8.

bytes1 and bytes2 are 24 length

When I create an encryptor, I get this error: Specified initialization vector (IV) does not match the block size for this algorithm. (Parameter 'rgbIV')'

I tried to set keys to 8 and 16 length


问:
How to solve ValueError: Expected 2D array, got 1D array instead: array=[]. for encodings?
Earlier i had created a face encodings generation.py.
Then when i want to load the encodings file into my face recognition.py it appeared this error:ValueError: Expected 2D array, got 1D array instead:
array=[].

i had tried to reshape using array.reshape(-1, 1) but still error.
Please help ... tq!!!

Here is my codes.

```<code>#load embeddings of known faces
collected_encodings = pickle.loads(open('face_encoding', "rb").read())
# infile = open('face_encoding','rb')
# #load encodings and name from face_encoding
# data = pickle.load(infile)
# knownEncodings, knownNames = data['encodings'], data['names']
# print(collected_encodings.shape)
#use SVM classifier to classify encodings and name
clf = svm.SVC(gamma="scale", probability=True, tol=0.03)
clf.fit(collected_encodings['encodings'], collected_encodings['names'])
</code>```

Body:
Earlier i had created a face encodings generation.py.
Then when i want to load the encodings file into my face recognition.py it appeared this error:ValueError: Expected 2D array, got 1D array instead:
array=[].

i had tried to reshape using array.reshape(-1, 1) but still error.
Please help ... tq!!!

Here is my codes.

#load embeddings of known faces
collected_encodings = pickle.loads(open('face_encoding', "rb").read())
# infile = open('face_encoding','rb')
# #load encodings and name from face_encoding
# data = pickle.load(infile)
# knownEncodings, knownNames = data['encodings'], data['names']
# print(collected_encodings.shape)
#use SVM classifier to classify encodings and name
clf = svm.SVC(gamma="scale", probability=True, tol=0.03)
clf.fit(collected_encodings['encodings'], collected_encodings['names'])


问:
Error 500 when adding table to confluence page using rest api
I'm trying to add a table to a confluence page using the rest api but it returns error 500. I don't have permissions to check the server log so I'd just like to check if the issue is with my code before i ask the server admin for permissions.

`

```<code>import json
import requests

# Set the base URL for the Confluence REST API
base_url = "https://myconfluence.atlassian.net/wiki"

# Set the content ID
content_id = "30825808261"

# Set the table data
table_data = [
    {
        "type": "tableRow",
        "content": [
            {
                "type": "tableCell",
                "content": [
                    {
                        "type": "paragraph",
                        "text": "Row 1, Cell 1"
                    }
                ]
            },
            {
                "type": "tableCell",
                "content": [
                    {
                        "type": "paragraph",
                        "text": "Row 1, Cell 2"
                    }
                ]
            }
        ]
    },
    {
        "type": "tableRow",
        "content": [
            {
                "type": "tableCell",
                "content": [
                    {
                        "type": "paragraph",
                        "text": "Row 2, Cell 1"
                    }
                ]
            },
            {
                "type": "tableCell",
                "content": [
                    {
                        "type": "paragraph",
                        "text": "Row 2, Cell 2"
                    }
                ]
            }
        ]
    }
]

# Set the updated content, including the table
updated_content = {
    "type": "page",
    "content": [
        {
            "type": "paragraph"
        },
        {
            "type": "table",
            "content": table_data
        }
    ],
    "version": {
        "number": 6
    }
}

# Set the request headers
headers = {
    "Content-Type": "application/json"
}

# Set the authentication credentials
username = 'username'
token = 'token'
auth = (username , token)

# Send the PUT request to update the content
response = requests.put(
    f"{base_url}/rest/api/content/{content_id}",
    headers=headers,
    auth=auth,
    data=json.dumps(updated_content)
)
print(updated_content)
print(response)

print(response.status_code)
# Check the status code of the response
if response.status_code == 200:
    print("Content updated successfully")
else:
    print("Error updating content")

</code>```

`

This is the output i get:
<Response [500]>
500
Error updating content

Body:
I'm trying to add a table to a confluence page using the rest api but it returns error 500. I don't have permissions to check the server log so I'd just like to check if the issue is with my code before i ask the server admin for permissions.

`

import json
import requests

# Set the base URL for the Confluence REST API
base_url = "https://myconfluence.atlassian.net/wiki"

# Set the content ID
content_id = "30825808261"

# Set the table data
table_data = [
    {
        "type": "tableRow",
        "content": [
            {
                "type": "tableCell",
                "content": [
                    {
                        "type": "paragraph",
                        "text": "Row 1, Cell 1"
                    }
                ]
            },
            {
                "type": "tableCell",
                "content": [
                    {
                        "type": "paragraph",
                        "text": "Row 1, Cell 2"
                    }
                ]
            }
        ]
    },
    {
        "type": "tableRow",
        "content": [
            {
                "type": "tableCell",
                "content": [
                    {
                        "type": "paragraph",
                        "text": "Row 2, Cell 1"
                    }
                ]
            },
            {
                "type": "tableCell",
                "content": [
                    {
                        "type": "paragraph",
                        "text": "Row 2, Cell 2"
                    }
                ]
            }
        ]
    }
]

# Set the updated content, including the table
updated_content = {
    "type": "page",
    "content": [
        {
            "type": "paragraph"
        },
        {
            "type": "table",
            "content": table_data
        }
    ],
    "version": {
        "number": 6
    }
}

# Set the request headers
headers = {
    "Content-Type": "application/json"
}

# Set the authentication credentials
username = 'username'
token = 'token'
auth = (username , token)

# Send the PUT request to update the content
response = requests.put(
    f"{base_url}/rest/api/content/{content_id}",
    headers=headers,
    auth=auth,
    data=json.dumps(updated_content)
)
print(updated_content)
print(response)

print(response.status_code)
# Check the status code of the response
if response.status_code == 200:
    print("Content updated successfully")
else:
    print("Error updating content")

`

This is the output i get:
<Response [500]>
500
Error updating content


问:
Why blueimp-load-image fail?
Have this method, it convert HEIC image and send it. I see an error after conversion in the returned image, why?

const uploadImage = async (propsAndFile: UploadImageParams) => {
    try {
        let convertedImage
        let convertedType
        if (propsAndFile?.file?.type == 'image/heic') {
            convertedImage = await new Promise((resolve, reject) => {
                loadImage(
                    propsAndFile.file,
                    resolve,
                    { orientation: true, canvas: true },
                    reject
                )
            })
            convertedType = 'image/jpg'
        }

        try {
            const uploadResponse = await axiosInstance({
                method: 'put',
                url: presignResponse.data,
                data: convertedImage ?? propsAndFile.file ?? propsAndFile.buffer,
                withCredentials: false,
                headers: {
                    'x-amz-acl': 'public-read',
                    'Content-Type':
                        convertedType ??
                        propsAndFile?.contentType ??
                        propsAndFile?.file?.type,
                },
            })
            if (propsAndFile.andThen) {
                return propsAndFile.andThen()
            } else {
                return {
                    presignResponse,
                    uploadResponse,
                }
            }
        } catch (error) {
            console.error(error)

            return {
                presignResponse,
            }
        }
    } catch (error) {
        console.error(error)

        return {}
    }
}
```

Title: Why blueimp-load-image fail?


问:
Unable to set state in .then block after FireBase login with Facebook
I can't seem to figure out what I'm doing incorrectly. Whenever I'm clicking on my Sign In button, my UserContext state does not get set accordingly.
I'm trying to get it to set, and then navigate to the next page.

Any insight on how I can best approach this and why this is happening?

```<code>    import { UserContext } from "../Components/UserContext";
    import { signInWithPopup, FacebookAuthProvider } from "firebase/auth";

    [...]

    let navigate = useNavigate();
    const { user, setUser } = useContext(UserContext);

    //  Login from Firebase
    const signInWithFacebook = () => {
        const provider = new FacebookAuthProvider()
        signInWithPopup(authentication, provider)
            .then((result) => {
                const credential = FacebookAuthProvider.credentialFromResult(result);
                token = credential.accessToken;
                userB = result.user;
                setUser(userB)
                console.log(user) // this equals null
                navigate("../home") // because user state = null, "Home" does not exist in my router, then goes to my 404 page.
            })
    }

[.......]

return (
    [...]
    <button onClick={signInWithFacebook}> Sign In </button>
    [...]
)
</code>```

I've tried await in some portions but it never assigned itself accordingly. Along with that I've also tried to set the setUser in a different function, and called that function. That still didn't work for me.

Body:
I can't seem to figure out what I'm doing incorrectly. Whenever I'm clicking on my Sign In button, my UserContext state does not get set accordingly.
I'm trying to get it to set, and then navigate to the next page.

Any insight on how I can best approach this and why this is happening?

    import { UserContext } from "../Components/UserContext";
    import { signInWithPopup, FacebookAuthProvider } from "firebase/auth";

    [...]

    let navigate = useNavigate();
    const { user, setUser } = useContext(UserContext);

    //  Login from Firebase
    const signInWithFacebook = () => {
        const provider = new FacebookAuthProvider()
        signInWithPopup(authentication, provider)
            .then((result) => {
                const credential = FacebookAuthProvider.credentialFromResult(result);
                token = credential.accessToken;
                userB = result.user;
                setUser(userB)
                console.log(user) // this equals null
                navigate("../home") // because user state = null, "Home" does not exist in my router, then goes to my 404 page.
            })
    }

[.......]

return (
    [...]
    <button onClick={signInWithFacebook}> Sign In </button>
    [...]
)

I've tried await in some portions but it never assigned itself accordingly. Along with that I've also tried to set the setUser in a different function, and called that function. That still didn't work for me.


问:
Prometheus invalid metric type "status=\"available\"} gauge" + 401
Trying to monitor with Prometheus, but cannot get /_admin/metrics/v2/ to work with jwt (I've confirmed the token matches web, tested with postman). So I've enabled the arango-prometheus-exporter service, and can read metrics from the mount point /metrics.

However, Prometheus is now reporting invalid metric type "status=\"available\"} gauge" in the targets list page, and the endpoint is shown as down in red.

I am unsure of 3 things:

Why do I get a 401 not authorized to execute this request when using a valid jwt bearer token,

Why am i getting invalid metric type "status=\"available\"} gauge" for the prometheus target endpoint using the foxx-service mounted at /metrics,

Should i even be using the foxx-service, or the internal admin metrics url?

I am using the latest as of a couple days ago, ArangoDB v3.10.1, Prometheus v2.41.0-rc.0 (and Grafana v9.3.2 (21c1d14e91) but i haven't gotten that far with ArangoDB yet).  All on Ubuntu 20.04.4 LTS.

I am currently successfully monitoring Prometheus, Node exporter and RabbitMQ.

UPDATE: I should be using the ArangoDB metrics rather than Foxx.  More info on issues using built-in metrics:

I have generated a secret from arangodb on command line using arangodb create jwt-secret, then used arangodb auth header --auth.jwt-secret secret.jwt to generate the auth header string.  I copy the token to /etc/prometheus/prometheus.token and update prometheus.yml to:

```<code>  - job_name: "arangodb"
    scrape_interval: 5s
    metrics_path: /_admin/metrics/v2
    bearer_token_file: /etc/prometheus/prometheus.token
    static_configs:
      - targets: ["localhost:8529"]
</code>```

Then i restart prometheus to pick up the changes, and in the Targets tab i see

I tested by running as sudo to generate the secret from ArangoDB, then sudo to generate the Bearer Token, but still the same result.

However, if I copy the token from the jwt key from the Application tab in devtools from the ArangoDB site and paste it into Postman Authorisation section under Bearer Token and make a GET request to http://172.31.245.140:8529/_admin/metrics/v2/ it does work.

So I copied the same token from website login to /etc/prometheus/prometheus.token, restart Prometheus and now its working.  But, it will only last until the web token times out. <- And confirmed, jwt token has timed out and Prometheus is showing "server returned HTTP status 401 Unauthorized" again.

Am I missing something?

UPDATE 2 - I can connect using basic auth in the prometheus config.

So this works:

```<code>  - job_name: "arangodb"
    scrape_interval: 5s
    metrics_path: /_admin/metrics/v2
    #bearer_token_file: /etc/prometheus/prometheus.token
    basic_auth:
      username: root
      password: the_password
    static_configs:
      - targets: ["localhost:8529"]
</code>```

I didn't try password_file instead, but that would at the least remove password from the config file.  I'm ok with this for now since it will be locked down, but i would rather use token auth.

Body:
Trying to monitor with Prometheus, but cannot get /_admin/metrics/v2/ to work with jwt (I've confirmed the token matches web, tested with postman). So I've enabled the arango-prometheus-exporter service, and can read metrics from the mount point /metrics.

However, Prometheus is now reporting invalid metric type "status=\"available\"} gauge" in the targets list page, and the endpoint is shown as down in red.

I am unsure of 3 things:

Why do I get a 401 not authorized to execute this request when using a valid jwt bearer token,

Why am i getting invalid metric type "status=\"available\"} gauge" for the prometheus target endpoint using the foxx-service mounted at /metrics,

Should i even be using the foxx-service, or the internal admin metrics url?

I am using the latest as of a couple days ago, ArangoDB v3.10.1, Prometheus v2.41.0-rc.0 (and Grafana v9.3.2 (21c1d14e91) but i haven't gotten that far with ArangoDB yet).  All on Ubuntu 20.04.4 LTS.

I am currently successfully monitoring Prometheus, Node exporter and RabbitMQ.

UPDATE: I should be using the ArangoDB metrics rather than Foxx.  More info on issues using built-in metrics:

I have generated a secret from arangodb on command line using arangodb create jwt-secret, then used arangodb auth header --auth.jwt-secret secret.jwt to generate the auth header string.  I copy the token to /etc/prometheus/prometheus.token and update prometheus.yml to:

  - job_name: "arangodb"
    scrape_interval: 5s
    metrics_path: /_admin/metrics/v2
    bearer_token_file: /etc/prometheus/prometheus.token
    static_configs:
      - targets: ["localhost:8529"]

Then i restart prometheus to pick up the changes, and in the Targets tab i see

I tested by running as sudo to generate the secret from ArangoDB, then sudo to generate the Bearer Token, but still the same result.

However, if I copy the token from the jwt key from the Application tab in devtools from the ArangoDB site and paste it into Postman Authorisation section under Bearer Token and make a GET request to http://172.31.245.140:8529/_admin/metrics/v2/ it does work.

So I copied the same token from website login to /etc/prometheus/prometheus.token, restart Prometheus and now its working.  But, it will only last until the web token times out. <- And confirmed, jwt token has timed out and Prometheus is showing "server returned HTTP status 401 Unauthorized" again.

Am I missing something?

UPDATE 2 - I can connect using basic auth in the prometheus config.

So this works:

  - job_name: "arangodb"
    scrape_interval: 5s
    metrics_path: /_admin/metrics/v2
    #bearer_token_file: /etc/prometheus/prometheus.token
    basic_auth:
      username: root
      password: the_password
    static_configs:
      - targets: ["localhost:8529"]

I didn't try password_file instead, but that would at the least remove password from the config file.  I'm ok with this for now since it will be locked down, but i would rather use token auth.


问:
creating a shadow jar with a specific gradle task
I have a multi module gradle project of which module 'a' is creating a fat jar using the shadowJar task from johnrengelman. I want to shadow module 'b' but from the output of a specific task in 'b'. How can I do it?

a/build.gradle

```<code>plugins {
    id 'com.github.johnrengelman.shadow' version '7.1.2'
}

dependencies {
    implementation project(':b')
}

shadowJar {
    // shadow with a specific task from module b's?
}
</code>```

currently it seems that gradle is shadowing module b with its default jar task which is expected. Output when creating the fat jar with the shadowJar task:

```<code>> Task :b:compileJava UP-TO-DATE
> Task :b:processResources NO-SOURCE
> Task :b:classes UP-TO-DATE
> Task :b:jar UP-TO-DATE // I want it to use my specific task
> Task :a:compileJava UP-TO-DATE
> Task :a:processResources
> Task :a:classes
> Task :a:jar
</code>```

Body:
I have a multi module gradle project of which module 'a' is creating a fat jar using the shadowJar task from johnrengelman. I want to shadow module 'b' but from the output of a specific task in 'b'. How can I do it?

a/build.gradle

plugins {
    id 'com.github.johnrengelman.shadow' version '7.1.2'
}

dependencies {
    implementation project(':b')
}

shadowJar {
    // shadow with a specific task from module b's?
}

currently it seems that gradle is shadowing module b with its default jar task which is expected. Output when creating the fat jar with the shadowJar task:

> Task :b:compileJava UP-TO-DATE
> Task :b:processResources NO-SOURCE
> Task :b:classes UP-TO-DATE
> Task :b:jar UP-TO-DATE // I want it to use my specific task
> Task :a:compileJava UP-TO-DATE
> Task :a:processResources
> Task :a:classes
> Task :a:jar


问:
How to read an image title with pandas read_html?
I'm trying to use Pandas to import the following wikipedia table as a Dataframe:

https://en.wikipedia.org/wiki/List_of_FIFA_World_Cup_penalty_shoot-outs

```<code>urlcopa = 'https://en.wikipedia.org/wiki/List_of_FIFA_World_Cup_penalty_shoot-outs'
table = pd.read_html(urlcopa, match = 'Takers', flavor='bs4')
</code>```

So far, so good, the table imports properly, although the column titles are a bit wonky but that's easy to fix. However, I also want the info on whether each penalty taker scored or not.

As you can see opening the Wikipedia url, that information is presented with a checkmark next to the taker's name, in the form of an image, and is not imported to python through the read_html pandas function.

I've tried reading the documentation to see if there are any arguments I could use, but I can't find anything that seems to help. Does anyone know a way for me to grab this info? Could be on a different column or maybe as a letter/digit next to the keeper's name in the same column, I don't mind.

Body:
I'm trying to use Pandas to import the following wikipedia table as a Dataframe:

https://en.wikipedia.org/wiki/List_of_FIFA_World_Cup_penalty_shoot-outs

urlcopa = 'https://en.wikipedia.org/wiki/List_of_FIFA_World_Cup_penalty_shoot-outs'
table = pd.read_html(urlcopa, match = 'Takers', flavor='bs4')

So far, so good, the table imports properly, although the column titles are a bit wonky but that's easy to fix. However, I also want the info on whether each penalty taker scored or not.

As you can see opening the Wikipedia url, that information is presented with a checkmark next to the taker's name, in the form of an image, and is not imported to python through the read_html pandas function.

I've tried reading the documentation to see if there are any arguments I could use, but I can't find anything that seems to help. Does anyone know a way for me to grab this info? Could be on a different column or maybe as a letter/digit next to the keeper's name in the same column, I don't mind.


问:
How to autofill the input element that is the child of a label element with a specific aria-label?
```<code>function setInputText() {

  const label = document.querySelector('label[aria-label="Title"]');
  if (!label) {

    console.error('bleh');
    return;
  }

  const input = label.querySelector('input');
  if (!input) {

    console.error('awefawefwe');
    return;
  }

  input.value = 'test';
}

function setInputText() {
  const label = document.querySelector('label[aria-label="Title"]');
  if (!label) {
    console.error('No label element with aria-label="Title" was found');
    return;
  }

  const input = label.nextElementSibling;
  if (!input) {
    console.error('No input element was found as a child of the label element');
    return;
  }

  input.value = 'awefaweafewefaaweawefaefw';
}
</code>```

Trying to autofill a form in Chrome using the aria-label attribute. Can't figure out why this won't work.

Body:
function setInputText() {

  const label = document.querySelector('label[aria-label="Title"]');
  if (!label) {

    console.error('bleh');
    return;
  }

  const input = label.querySelector('input');
  if (!input) {

    console.error('awefawefwe');
    return;
  }

  input.value = 'test';
}

function setInputText() {
  const label = document.querySelector('label[aria-label="Title"]');
  if (!label) {
    console.error('No label element with aria-label="Title" was found');
    return;
  }

  const input = label.nextElementSibling;
  if (!input) {
    console.error('No input element was found as a child of the label element');
    return;
  }

  input.value = 'awefaweafewefaaweawefaefw';
}

Trying to autofill a form in Chrome using the aria-label attribute. Can't figure out why this won't work.


问:
django celery database transaction auto commit
I use celery group feature to group my async tasks, like

```<code>job_flow = group(
            tasks.init_a.si(id, data),
            tasks.init_b.si(id, data)
            )
res = job_flow()
</code>```

In init_a function, I have some code

```<code>def init_a():
    ta = tablea.objects.get(id=id)
    ta.desc = 'done'
    ta.save()
</code>```

Then in init_b(), I will to check the ta.desc is done or not, but I can not get the ta.desc to done.

```<code>def init_b():
    ta = tablea.objects.get(id=id)
    if ta.desc == 'done':
        do_something()
</code>```

But I use ./manage shell to check the ta.desc value is changed to done.

Why I can not in init_b() to get the real ta.desc value?

Django (1.5.6)
celery (3.1.23)

Body:
I use celery group feature to group my async tasks, like

job_flow = group(
            tasks.init_a.si(id, data),
            tasks.init_b.si(id, data)
            )
res = job_flow()

In init_a function, I have some code

def init_a():
    ta = tablea.objects.get(id=id)
    ta.desc = 'done'
    ta.save()

Then in init_b(), I will to check the ta.desc is done or not, but I can not get the ta.desc to done.

def init_b():
    ta = tablea.objects.get(id=id)
    if ta.desc == 'done':
        do_something()

But I use ./manage shell to check the ta.desc value is changed to done.

Why I can not in init_b() to get the real ta.desc value?

Django (1.5.6)
celery (3.1.23)


问:
EF 6 : how to call a stored procedure with multiple output params
I have a .NET 4.8 app that is calling a SQL Server stored procedure using SqlQuery (inside a DbContext). Most of the stored procedures take a couple of input parameters and return a number of rows, with a single output parameter giving the number of rows returned. These work fine.

I have one stored procedure that takes a single input, returns no rows, but has three output parameters. When I call this, I get no data returned and the output parameters appear to be unset (null).

```<code>PROCEDURE GetBob
    @InVal INT,
    @OutVal1 INT OUTPUT,
    @OutVal2 NVARCHAR(30) OUTPUT,
    @OutRows INT OUTPUT
AS
BEGIN
    SELECT @OutVal1 = 1
    SELECT @OutVal2 = "bob"
    SELECT @OutRows = 1
END
</code>```

When I execute this in SQL Server, I get 1, bob and 1 respectively.

```<code>SqlParameter param1 = new SqlParameter() {
    Direction = System.Data.ParameterDirection.Input,
    ParameterName = "@InVal",
    SqlDbType = System.Data.SqlDbType.Int,
    Value = 1
};

SqlParameter param2 = new SqlParameter() {
    Direction = System.Data.ParameterDirection.Output,
    ParameterName = "@OutVal1",
    SqlDbType = System.Data.SqlDbType.Int,
};

// etc. for the last two params.
</code>```

And my call is defined as follows:

```<code>var x = Database.SqlQuery<ab>("GetBob @InVal, @OutVal1, @OutVal2, @OutRows", param1, param2, param3, param4).ToList();
</code>```

For this example, ab is a class that contains a property for each output parameter.

Does anyone have any ideas why it is not picking up the output parameters. I would expect x to be empty as no actual rows are returned, but the output parameters should be populated.

Body:
I have a .NET 4.8 app that is calling a SQL Server stored procedure using SqlQuery (inside a DbContext). Most of the stored procedures take a couple of input parameters and return a number of rows, with a single output parameter giving the number of rows returned. These work fine.

I have one stored procedure that takes a single input, returns no rows, but has three output parameters. When I call this, I get no data returned and the output parameters appear to be unset (null).

PROCEDURE GetBob
    @InVal INT,
    @OutVal1 INT OUTPUT,
    @OutVal2 NVARCHAR(30) OUTPUT,
    @OutRows INT OUTPUT
AS
BEGIN
    SELECT @OutVal1 = 1
    SELECT @OutVal2 = "bob"
    SELECT @OutRows = 1
END

When I execute this in SQL Server, I get 1, bob and 1 respectively.

SqlParameter param1 = new SqlParameter() {
    Direction = System.Data.ParameterDirection.Input,
    ParameterName = "@InVal",
    SqlDbType = System.Data.SqlDbType.Int,
    Value = 1
};

SqlParameter param2 = new SqlParameter() {
    Direction = System.Data.ParameterDirection.Output,
    ParameterName = "@OutVal1",
    SqlDbType = System.Data.SqlDbType.Int,
};

// etc. for the last two params.

And my call is defined as follows:

var x = Database.SqlQuery<ab>("GetBob @InVal, @OutVal1, @OutVal2, @OutRows", param1, param2, param3, param4).ToList();

For this example, ab is a class that contains a property for each output parameter.

Does anyone have any ideas why it is not picking up the output parameters. I would expect x to be empty as no actual rows are returned, but the output parameters should be populated.


问:
non-aws user access S3 through web application
Let say there is a web application with different group of user which upload/ download to S3, in most case the object on S3 only available to the same group. But sometime we may want to share some object to specific user

Create different role in AWS, each role represent a group of user and use sts:assumerole in the web application. For the requirement of sharing file to specific user, is it possible create a role and attach to the user on the fly?

Create only one role, and the remain access right control logic laid in the web application.

1 or 2 is better?


问:
ASP.Net Rowspan first and second column result to messy gridview design
On Data Bound im trying the below code but result is displaying a different gridview
Final gridview of my code
:

```<code>            for (int aa = 0;  aa < ijp_gridview.Rows.Count; aa++)
            {
                for (int bb = 2; bb < ijp_gridview.Columns.Count; bb++)
                {
                    if (ijp_gridview.Rows[aa].Cells[bb].Text == "1st Priority" ||
                        ijp_gridview.Rows[aa].Cells[bb].Text == "2nd Priority" ||
                        ijp_gridview.Rows[aa].Cells[bb].Text == "3rd Priority" ||
                        ijp_gridview.Rows[aa].Cells[bb].Text == "No Priority" ||
                        ijp_gridview.Rows[aa].Cells[bb].Text == "FRESH" ||
                        ijp_gridview.Rows[aa].Cells[bb].Text == "cutted" ||
                        ijp_gridview.Rows[aa].Cells[bb].Text == "Backlog")
                    {
                        ijp_gridview.Rows[aa].Visible = false;
                        break;
                    }
                }
            }

            for (int rowindex = ijp_gridview.Rows.Count - 1; rowindex > 0; rowindex--)
            {
                System.Diagnostics.Debug.WriteLine(rowindex);
                GridViewRow row2 = ijp_gridview.Rows[rowindex];
                GridViewRow previousRow = ijp_gridview.Rows[rowindex - 1];
                for (int cellcount = 0; cellcount < 2; cellcount++)
                {
                    if (row2.Cells[cellcount].Text == previousRow.Cells[cellcount].Text)
                    {
                        if (row2.Cells[cellcount].RowSpan == 0)
                        {
                            previousRow.Cells[cellcount].RowSpan += 2;
                        }
                        else
                        {
                            previousRow.Cells[cellcount].RowSpan = row2.Cells[cellcount].RowSpan + 1;
                        }
                        row2.Cells[cellcount].Visible = false;
                    }
                }
            }
</code>```

It should be look like this but first and second column should rowspan same value. I don't know whats causing the problem I've tried different methods but it ends up distorting the gridview.
Expected gridview layout

Body:
On Data Bound im trying the below code but result is displaying a different gridview
Final gridview of my code
:

            for (int aa = 0;  aa < ijp_gridview.Rows.Count; aa++)
            {
                for (int bb = 2; bb < ijp_gridview.Columns.Count; bb++)
                {
                    if (ijp_gridview.Rows[aa].Cells[bb].Text == "1st Priority" ||
                        ijp_gridview.Rows[aa].Cells[bb].Text == "2nd Priority" ||
                        ijp_gridview.Rows[aa].Cells[bb].Text == "3rd Priority" ||
                        ijp_gridview.Rows[aa].Cells[bb].Text == "No Priority" ||
                        ijp_gridview.Rows[aa].Cells[bb].Text == "FRESH" ||
                        ijp_gridview.Rows[aa].Cells[bb].Text == "cutted" ||
                        ijp_gridview.Rows[aa].Cells[bb].Text == "Backlog")
                    {
                        ijp_gridview.Rows[aa].Visible = false;
                        break;
                    }
                }
            }

            for (int rowindex = ijp_gridview.Rows.Count - 1; rowindex > 0; rowindex--)
            {
                System.Diagnostics.Debug.WriteLine(rowindex);
                GridViewRow row2 = ijp_gridview.Rows[rowindex];
                GridViewRow previousRow = ijp_gridview.Rows[rowindex - 1];
                for (int cellcount = 0; cellcount < 2; cellcount++)
                {
                    if (row2.Cells[cellcount].Text == previousRow.Cells[cellcount].Text)
                    {
                        if (row2.Cells[cellcount].RowSpan == 0)
                        {
                            previousRow.Cells[cellcount].RowSpan += 2;
                        }
                        else
                        {
                            previousRow.Cells[cellcount].RowSpan = row2.Cells[cellcount].RowSpan + 1;
                        }
                        row2.Cells[cellcount].Visible = false;
                    }
                }
            }

It should be look like this but first and second column should rowspan same value. I don't know whats causing the problem I've tried different methods but it ends up distorting the gridview.
Expected gridview layout


问:
ReceivePacketEvent not triggering
I have a mod that is not executing receive packet events when I run

```<code>@Cancelable  public class ReceivePacketEvent extends Event {  public Packet<?> packet;  public ReceivePacketEvent(Packet<?> packet) {  System.out.println("PKT");  this.packet = packet;  }  }
</code>```

Nothing will happen. Other events will work like on render or tick event but packet wont work. for reference I'm using this mod in a server

I get an error seemingly randomly that looks like this and im not sure where it comes from or if it affects the packet event so id say im lost

```<code>[01:22:45] [main/FATAL] (Minecraft) Error executing task
 java.util.concurrent.ExecutionException: java.lang.NullPointerException
    at java.util.concurrent.FutureTask.report(FutureTask.java:122) ~[?:1.8.0_351]
    at java.util.concurrent.FutureTask.get(FutureTask.java:192) ~[?:1.8.0_351]
    at net.minecraft.util.Util.runTask(Util.java:43) [Util.class:?]
    at net.minecraft.client.Minecraft.runGameLoop(Minecraft.java:987) [Minecraft.class:?]
    at net.minecraft.client.Minecraft.run(Minecraft.java:443) [Minecraft.class:?]
    at net.minecraft.client.main.Main.main(Main.java:111) [Main.class:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_351]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_351]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_351]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_351]
    at net.minecraft.launchwrapper.Launch.launch(Launch.java:135) [launchwrapper-1.12.jar:?]
    at net.minecraft.launchwrapper.Launch.main(Launch.java:28) [launchwrapper-1.12.jar:?]
    at net.fabricmc.devlaunchinjector.Main.main(Main.java:86) [dev-launch-injector-0.2.1+build.8.jar:?]
Caused by: java.lang.NullPointerException
    at net.minecraft.scoreboard.Scoreboard.removeTeam(Scoreboard.java:240) ~[Scoreboard.class:?]
    at net.minecraft.client.network.NetHandlerPlayClient.handleTeams(NetHandlerPlayClient.java:1452) ~[NetHandlerPlayClient.class:?]
    at net.minecraft.network.play.server.S3EPacketTeams.processPacket(S3EPacketTeams.java:114) ~[S3EPacketTeams.class:?]
    at net.minecraft.network.play.server.S3EPacketTeams.processPacket(S3EPacketTeams.java:36) ~[S3EPacketTeams.class:?]
    at net.minecraft.network.PacketThreadUtil$1.run(PacketThreadUtil.java:24) ~[PacketThreadUtil$1.class:?]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[?:1.8.0_351]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[?:1.8.0_351]
    at net.minecraft.util.Util.runTask(Util.java:42) ~[Util.class:?]
    ... 10 more
</code>```

Title: ReceivePacketEvent not triggering

Body:
I have a mod that is not executing receive packet events when I run

@Cancelable  public class ReceivePacketEvent extends Event {  public Packet<?> packet;  public ReceivePacketEvent(Packet<?> packet) {  System.out.println("PKT");  this.packet = packet;  }  }

Nothing will happen. Other events will work like on render or tick event but packet wont work. for reference I'm using this mod in a server

I get an error seemingly randomly that looks like this and im not sure where it comes from or if it affects the packet event so id say im lost

[01:22:45] [main/FATAL] (Minecraft) Error executing task
 java.util.concurrent.ExecutionException: java.lang.NullPointerException
    at java.util.concurrent.FutureTask.report(FutureTask.java:122) ~[?:1.8.0_351]
    at java.util.concurrent.FutureTask.get(FutureTask.java:192) ~[?:1.8.0_351]
    at net.minecraft.util.Util.runTask(Util.java:43) [Util.class:?]
    at net.minecraft.client.Minecraft.runGameLoop(Minecraft.java:987) [Minecraft.class:?]
    at net.minecraft.client.Minecraft.run(Minecraft.java:443) [Minecraft.class:?]
    at net.minecraft.client.main.Main.main(Main.java:111) [Main.class:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_351]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_351]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_351]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_351]
    at net.minecraft.launchwrapper.Launch.launch(Launch.java:135) [launchwrapper-1.12.jar:?]
    at net.minecraft.launchwrapper.Launch.main(Launch.java:28) [launchwrapper-1.12.jar:?]
    at net.fabricmc.devlaunchinjector.Main.main(Main.java:86) [dev-launch-injector-0.2.1+build.8.jar:?]
Caused by: java.lang.NullPointerException
    at net.minecraft.scoreboard.Scoreboard.removeTeam(Scoreboard.java:240) ~[Scoreboard.class:?]
    at net.minecraft.client.network.NetHandlerPlayClient.handleTeams(NetHandlerPlayClient.java:1452) ~[NetHandlerPlayClient.class:?]
    at net.minecraft.network.play.server.S3EPacketTeams.processPacket(S3EPacketTeams.java:114) ~[S3EPacketTeams.class:?]
    at net.minecraft.network.play.server.S3EPacketTeams.processPacket(S3EPacketTeams.java:36) ~[S3EPacketTeams.class:?]
    at net.minecraft.network.PacketThreadUtil$1.run(PacketThreadUtil.java:24) ~[PacketThreadUtil$1.class:?]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[?:1.8.0_351]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[?:1.8.0_351]
    at net.minecraft.util.Util.runTask(Util.java:42) ~[Util.class:?]
    ... 10 more


问:
Pandas Data Reader
The code hasn't been changed in a couple of weeks but today when I tried to run it I got an error

TypeError: string indices must be integers
```
<p>I haven't changed the code since it last worked with it working a couple days ago.</p>
<p>Should I update pips? Or perhaps pandas? Or it maybe something else, I'm imagining it to be something simple but I might be wrong.</p>
```import pandas_datareader as pdr
import datetime
print(pdr.get_data_yahoo("GOOG", start = (datetime.datetime.today() - datetime.timedelta(days=7) )  )['Close'])
```
<h3>Error</h3>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    print(pdr.get_data_yahoo("GOOG", start = (datetime.datetime.today() - datetime.timedelta(days=7) ) )['Close'])
  File "C:\Users\Python\Python310\lib\site-packages\pandas_datareader\data.py", line 80, in get_data_yahoo
    return YahooDailyReader(*args, **kwargs).read()
  File "C:\UsersPython\Python310\lib\site-packages\pandas_datareader\base.py", line 253, in read
    df = self._read_one_data(self.url, params=self._get_params(self.symbols))
  File "C:\UsersPython\Python310\lib\site-packages\pandas_datareader\yahoo\daily.py", line 153, in _read_one_data
    data = j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"]
TypeError: string indices must be integers
</code>```

Title: Pandas Data Reader

Body:
The code hasn't been changed in a couple of weeks but today when I tried to run it I got an error

TypeError: string indices must be integers

I haven't changed the code since it last worked with it working a couple days ago.

Should I update pips? Or perhaps pandas? Or it maybe something else, I'm imagining it to be something simple but I might be wrong.

import pandas_datareader as pdr
import datetime
print(pdr.get_data_yahoo("GOOG", start = (datetime.datetime.today() - datetime.timedelta(days=7) )  )['Close'])

Error

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    print(pdr.get_data_yahoo("GOOG", start = (datetime.datetime.today() - datetime.timedelta(days=7) ) )['Close'])
  File "C:\Users\Python\Python310\lib\site-packages\pandas_datareader\data.py", line 80, in get_data_yahoo
    return YahooDailyReader(*args, **kwargs).read()
  File "C:\UsersPython\Python310\lib\site-packages\pandas_datareader\base.py", line 253, in read
    df = self._read_one_data(self.url, params=self._get_params(self.symbols))
  File "C:\UsersPython\Python310\lib\site-packages\pandas_datareader\yahoo\daily.py", line 153, in _read_one_data
    data = j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"]
TypeError: string indices must be integers


问:
Laravel Webpack Build for jQuery, AdminLTE and Bootstrap
Apologies for the long post, I've been trying not to give up on this one, but I've had to admit... I've been out of the game too long (a lot of hospital time), and I'm not winning.

I had an app built on Laravel using Webpack (about four years ago), and everything ran great. Now I'm trying to update. I don't want to use CDNs so I can work offline, but my Webpack build just isn't happening.

JQuery doesn't want to build. However, I've checked the build, and it's there, so I'm doing something wrong.

So for Webpack, I have (a bit of a cut-down version, but this is what I'm trying to build):

```<code>const mix = require('laravel-mix');
let productionSourceMaps = true;

let preCompiled = {
   node: 'node_modules/',
   jquery: 'node_modules/jquery/dist/',
   jquery_ui: 'node_modules/jquery-ui-dist/',
   bootstrap: 'node_modules/bootstrap/dist/',
   app: 'resources/assets/app/',
};

let compiled = {
   app: 'public/assets/app/'
};

// App Pages
mix.js([
    preCompiled.node+'admin-lte/dist/js/adminlte.js',
    preCompiled.jquery+'jquery.js',
    preCompiled.jquery_ui+'jquery-ui.js',
    preCompiled.bootstrap+'js/bootstrap.bundle.js',
], compiled.app+'js/app.js');

mix.copy(preCompiled.node+'admin-lte/dist/img/', compiled.app+'img/');

mix.webpackConfig({
    stats: {
        children: true,
    },
});

mix.version();
</code>```

The problem is I keep getting

TypeError: undefined is not a function (near '...jQuery...')

I've tested with a build including only jQuery, and it's building jQuery in my js/app.js file. I've tried re-ordering the build components but no joy. It's me, and not up to scratch, but I would appreciate any advice.

Body:
Apologies for the long post, I've been trying not to give up on this one, but I've had to admit... I've been out of the game too long (a lot of hospital time), and I'm not winning.

I had an app built on Laravel using Webpack (about four years ago), and everything ran great. Now I'm trying to update. I don't want to use CDNs so I can work offline, but my Webpack build just isn't happening.

JQuery doesn't want to build. However, I've checked the build, and it's there, so I'm doing something wrong.

So for Webpack, I have (a bit of a cut-down version, but this is what I'm trying to build):

const mix = require('laravel-mix');
let productionSourceMaps = true;

let preCompiled = {
   node: 'node_modules/',
   jquery: 'node_modules/jquery/dist/',
   jquery_ui: 'node_modules/jquery-ui-dist/',
   bootstrap: 'node_modules/bootstrap/dist/',
   app: 'resources/assets/app/',
};

let compiled = {
   app: 'public/assets/app/'
};

// App Pages
mix.js([
    preCompiled.node+'admin-lte/dist/js/adminlte.js',
    preCompiled.jquery+'jquery.js',
    preCompiled.jquery_ui+'jquery-ui.js',
    preCompiled.bootstrap+'js/bootstrap.bundle.js',
], compiled.app+'js/app.js');

mix.copy(preCompiled.node+'admin-lte/dist/img/', compiled.app+'img/');

mix.webpackConfig({
    stats: {
        children: true,
    },
});

mix.version();

The problem is I keep getting

TypeError: undefined is not a function (near '...jQuery...')

I've tested with a build including only jQuery, and it's building jQuery in my js/app.js file. I've tried re-ordering the build components but no joy. It's me, and not up to scratch, but I would appreciate any advice.


问:
Is is possible to write own telegram library using MTPROTO API using Python?
I have searched many things in the google and cannot find document. I found MTPROTO API document from telegram official web site but they dont provide any guide to use in python and only explain those APIs. I know telethon can be used.

Is is possible to write own telegram library using MTPROTO API using Python? rather than using 3rd party library.


问:
How to save raw java Map to Redis as Redis Hash by using Spring @Cacheable
How to save raw java Map to Redis as Redis Hash by using Spring @Cacheable.

```<code>@Cacheable(cacheNames = "test:role", key = "#roleId")
public Map<String, String> getRoleName(String roleId) {
    final String rid = "Role" + roleId;
    Map<String, String> map = new HashMap<>();
    map.put(rid + 1, rid + 1);
    map.put(rid + 2, rid + 2);
    return map;
}
</code>```

Actual:

```<code>192.168.0.17:6379> keys *
1) "test:role::1"
2) "test:role::2"
192.168.0.17:6379> type test:role::1
string
192.168.0.17:6379> get test:role::1
"{\"Role11\":\"Role11\",\"Role12\":\"Role12\"}"
</code>```

Expected:

```<code>192.168.0.17:6379> hmset test:role::3 Role11 Role11 Role12 Role12
OK
192.168.0.17:6379> hgetall test:role::3
1) "Role11"
2) "Role11"
3) "Role12"
4) "Role12"
192.168.0.17:6379> hget test:role::3 Role11
"Role11"

</code>```

Any advice will be appreciated, thanks.

Body:
How to save raw java Map to Redis as Redis Hash by using Spring @Cacheable.

@Cacheable(cacheNames = "test:role", key = "#roleId")
public Map<String, String> getRoleName(String roleId) {
    final String rid = "Role" + roleId;
    Map<String, String> map = new HashMap<>();
    map.put(rid + 1, rid + 1);
    map.put(rid + 2, rid + 2);
    return map;
}

Actual:

192.168.0.17:6379> keys *
1) "test:role::1"
2) "test:role::2"
192.168.0.17:6379> type test:role::1
string
192.168.0.17:6379> get test:role::1
"{\"Role11\":\"Role11\",\"Role12\":\"Role12\"}"

Expected:

192.168.0.17:6379> hmset test:role::3 Role11 Role11 Role12 Role12
OK
192.168.0.17:6379> hgetall test:role::3
1) "Role11"
2) "Role11"
3) "Role12"
4) "Role12"
192.168.0.17:6379> hget test:role::3 Role11
"Role11"

Any advice will be appreciated, thanks.


问:
Browser doesn't set cookies an send in header
I have a nest js server that run on localhost 3000 and I use vuejs on http://127.0.0.1 on port 5173

I have a function that authenticated the user in my auth.controller.js

@Post('auth/login')
  async login(
    @Body() payload: { email: string; password: string },
    @Req() req,
    @Res({ passthrough: true }) res,
  ) {

    const user = await this.authService.login(payload.email);

       const ALLOWED_ORIGINS = ['http://127.0.0.1:5173', 'http://postman'];
    if (ALLOWED_ORIGINS.indexOf(req.headers.origin) > -1) {
      res.set('Access-Control-Allow-Origin', req.headers.origin);
      res.set('Access-Control-Allow-Credentials', 'true');
      res.set('Access-Control-Allow-Methods', 'POST, OPTIONS');
    }

    res
      .cookie('sessionId', user.jwtToken, {
        // secure: process.env.NODE_ENV === 'dev' ? false : true, //set true in production
        secure: false,
        httpOnly: true,
        maxAge: 1 * 60 * 60 * 2 * 1000,
        sameSite: 'none', //Should be "strict" in prod
        signed: true,
      })
      .send({
        message: 'Token contenu dans le xsrf',
        xsrfToken: user.token.xsrfToken,
      });
    // console.log(req.cookies);
  }
```
<p>As you can see I return the cookie in the res and I can see the cookie in the network part of the browser</p>
<p><img src="https://i.stack.imgur.com/YAUBe.png" alt="enter image description here" /></p>
<p>But when I make axios request in the front with the option withCredentials set to true, I don't have the cookie inside the header.</p>
<p>There is my request in front</p>
<pre class="lang-js prettyprint-override"><code>const apiClientWithCredential = axios.create({
  withCredentials:true,
  baseURL : "http://localhost:3000"
})
</code>```

getUsers(email: string, password: string) {
    return apiClientWithCredential.post(`/auth/login`, {
      email,
      password
    })
  },
  getProtected() {
    return apiClientWithCredential.get(`http://localhost:3000/protected`, {
      headers: {
        'x-xsrf-token': `${window.sessionStorage['x-xsrf-token']}`
      }
    })
  },
```

In postman I correctly received the cookie d I can it set it automatically in other request.

Any Idea on why the browser cant automatically send the cookie in request header?

Body:
I have a nest js server that run on localhost 3000 and I use vuejs on http://127.0.0.1 on port 5173

I have a function that authenticated the user in my auth.controller.js

@Post('auth/login')
  async login(
    @Body() payload: { email: string; password: string },
    @Req() req,
    @Res({ passthrough: true }) res,
  ) {

    const user = await this.authService.login(payload.email);

       const ALLOWED_ORIGINS = ['http://127.0.0.1:5173', 'http://postman'];
    if (ALLOWED_ORIGINS.indexOf(req.headers.origin) > -1) {
      res.set('Access-Control-Allow-Origin', req.headers.origin);
      res.set('Access-Control-Allow-Credentials', 'true');
      res.set('Access-Control-Allow-Methods', 'POST, OPTIONS');
    }

    res
      .cookie('sessionId', user.jwtToken, {
        // secure: process.env.NODE_ENV === 'dev' ? false : true, //set true in production
        secure: false,
        httpOnly: true,
        maxAge: 1 * 60 * 60 * 2 * 1000,
        sameSite: 'none', //Should be "strict" in prod
        signed: true,
      })
      .send({
        message: 'Token contenu dans le xsrf',
        xsrfToken: user.token.xsrfToken,
      });
    // console.log(req.cookies);
  }

As you can see I return the cookie in the res and I can see the cookie in the network part of the browser

But when I make axios request in the front with the option withCredentials set to true, I don't have the cookie inside the header.

There is my request in front

const apiClientWithCredential = axios.create({
  withCredentials:true,
  baseURL : "http://localhost:3000"
})

getUsers(email: string, password: string) {
    return apiClientWithCredential.post(`/auth/login`, {
      email,
      password
    })
  },
  getProtected() {
    return apiClientWithCredential.get(`http://localhost:3000/protected`, {
      headers: {
        'x-xsrf-token': `${window.sessionStorage['x-xsrf-token']}`
      }
    })
  },

In postman I correctly received the cookie d I can it set it automatically in other request.

Any Idea on why the browser cant automatically send the cookie in request header?


问:
NodeJS multer not being called
I'm experiencing an odd behavior with multer. My route calls the controller method, but for some reason the multer is not working.

Router file:

```<code>const express =  require('express');
const router = express.Router();
var multer  = require('multer');
const FTPStorage = require('multer-ftp');
const FTPClient = require('ftp');

const myController = require('../../controllers/test');

var upload = multer({
  storage: new FTPStorage({
    basepath: '/wwwroot/Files',
    ftp: {
      host: 'myhost.address',
      secure: false, // enables FTPS/FTP with TLS
      user: 'username',
      password: 'password'
    },
    destination: function (req, file, options, callback) {
      console.log(req);  // THIS LOG IS NEVER CALLED
      const body = req.body;
      let path = `/wwwroot/Files/${body.docID}/${body.fileName}`;
      const destination = `/wwwroot/rent/UnitPhotos/${body.docID}`;
      const ftp = new FTPClient();
      ftp.connect({
          host: "myhost.address",
          user: "username",
          password: "password",
      });
      ftp.on('ready', function() {
        ftp.mkdir(destination, function(err) {
            if(err) console.log('Directory: ', err);
            callback(null, path) // custom file destination, file extension is added to the end of the path
            ftp.end();
        });
      });
    }
  })
});

router.post('/uploadFile', upload.single('file'), myController.uploadFile);
</code>```

My test controller has the uploadFile method

```<code>exports.uploadFile = async (req, res, next) => {
    try {
        const data = req.body.data || req.body;

        console.log(data); // THIS WORKS!

        return res.json(0)
    } catch(err) {
        console.log(err
    }
}
</code>```

I'm calling from a React application:

```<code>export const uploadFile = async (data) => {
    let output = 0;

    var formData = new FormData();
    formData.append('docID', data.docID);
    formData.append('file', data.file);
    formData.append('fileName', data.fileName);

    await axios({
        method: "post",
        url: `${URL}/uploadFile`,
        data: formData,
        headers: { "Content-Type": "multipart/form-data" },
      })
        .then(function (res) {
            output = res.data;
        });

    return output;
}
</code>```

Title: NodeJS multer not being called

Body:
I'm experiencing an odd behavior with multer. My route calls the controller method, but for some reason the multer is not working.

Router file:

const express =  require('express');
const router = express.Router();
var multer  = require('multer');
const FTPStorage = require('multer-ftp');
const FTPClient = require('ftp');

const myController = require('../../controllers/test');

var upload = multer({
  storage: new FTPStorage({
    basepath: '/wwwroot/Files',
    ftp: {
      host: 'myhost.address',
      secure: false, // enables FTPS/FTP with TLS
      user: 'username',
      password: 'password'
    },
    destination: function (req, file, options, callback) {
      console.log(req);  // THIS LOG IS NEVER CALLED
      const body = req.body;
      let path = `/wwwroot/Files/${body.docID}/${body.fileName}`;
      const destination = `/wwwroot/rent/UnitPhotos/${body.docID}`;
      const ftp = new FTPClient();
      ftp.connect({
          host: "myhost.address",
          user: "username",
          password: "password",
      });
      ftp.on('ready', function() {
        ftp.mkdir(destination, function(err) {
            if(err) console.log('Directory: ', err);
            callback(null, path) // custom file destination, file extension is added to the end of the path
            ftp.end();
        });
      });
    }
  })
});

router.post('/uploadFile', upload.single('file'), myController.uploadFile);

My test controller has the uploadFile method

exports.uploadFile = async (req, res, next) => {
    try {
        const data = req.body.data || req.body;

        console.log(data); // THIS WORKS!

        return res.json(0)
    } catch(err) {
        console.log(err
    }
}

I'm calling from a React application:

export const uploadFile = async (data) => {
    let output = 0;

    var formData = new FormData();
    formData.append('docID', data.docID);
    formData.append('file', data.file);
    formData.append('fileName', data.fileName);

    await axios({
        method: "post",
        url: `${URL}/uploadFile`,
        data: formData,
        headers: { "Content-Type": "multipart/form-data" },
      })
        .then(function (res) {
            output = res.data;
        });

    return output;
}


问:
Safe key access to a Map inside a class
I would like to create a class that contains a Map who's keys are type safe. I'm guessing I need to somehow change the generics Key and NewKey (below) into string literals somehow.

```<code>class MapWrap<Key extends string> {
    map: Map<Key, any>
    constructor() {
        this.map = new Map();
    }

    set<NewKey extends string>(key: NewKey, value: any) {
        (this as MapWrap<Key | NewKey>).map.set(key, value);
        return this as MapWrap<Key | NewKey>;
    }

    get(key: Key) {
        return this.map.get(key)
    }
}

const myMapWrap = new MapWrap();

// This should show an error that "bob" is not a key.
const bob = myMapWrap.set("hello", 1).set("world", 2).get("bob");

</code>```

I tried using 'as const' in various places with not success.

Title: Safe key access to a Map inside a class

Body:
I would like to create a class that contains a Map who's keys are type safe. I'm guessing I need to somehow change the generics Key and NewKey (below) into string literals somehow.

class MapWrap<Key extends string> {
    map: Map<Key, any>
    constructor() {
        this.map = new Map();
    }

    set<NewKey extends string>(key: NewKey, value: any) {
        (this as MapWrap<Key | NewKey>).map.set(key, value);
        return this as MapWrap<Key | NewKey>;
    }

    get(key: Key) {
        return this.map.get(key)
    }
}

const myMapWrap = new MapWrap();

// This should show an error that "bob" is not a key.
const bob = myMapWrap.set("hello", 1).set("world", 2).get("bob");

I tried using 'as const' in various places with not success.


问:
Why arrow function is different when adding prototype
I just wondered why this code run correctly with normal function and resulted in a different result when using arrow function:

the code:

```<code>String.prototype.addDotAfter = function() {
  return `${this}.`;
}
let ahmed = 'ahmed';

console.log(ahmed.addDotAfter()) // = ahmed.
</code>```

the other code that return strange result:

```<code>String.prototype.addDotAfter = ()=> {
  return `${this}.`;
}
let ahmed = 'ahmed';

console.log(ahmed.addDotAfter()) // = [object Object].
</code>```

I don't know why they are different in result!

Body:
I just wondered why this code run correctly with normal function and resulted in a different result when using arrow function:

the code:

String.prototype.addDotAfter = function() {
  return `${this}.`;
}
let ahmed = 'ahmed';

console.log(ahmed.addDotAfter()) // = ahmed.

the other code that return strange result:

String.prototype.addDotAfter = ()=> {
  return `${this}.`;
}
let ahmed = 'ahmed';

console.log(ahmed.addDotAfter()) // = [object Object].

I don't know why they are different in result!


问:
Pass handler to custom hook
I'm trying to figure out how to pass a state handler to a custom hook. The hook is:

```<code>function useOutsideAlerter(ref, handler) {
  useEffect(() => {
    /**
     * Alert if clicked on outside of element
     */
    function handleClickOutside(event) {
      if (ref.current && !ref.current.contains(event.target)) {
        console.log(handler)
      }
    }
    // Bind the event listener
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      // Unbind the event listener on clean up
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [ref]);
}

/**
 * Component that alerts if you click outside of it
 */
export default function OutsideAlerter(props) {
  const wrapperRef = useRef(null);
  useOutsideAlerter(wrapperRef);

  return <div ref={wrapperRef} handler={props.onClickOutside}>{props.children}</div>;
}
</code>```

I've tried to call the component with:

```<code><OutsideAlerter onClickOutside={handleToggle}><CartBox /></OutsideAlerter>
</code>```

The console log of my supposed passed handler inside useOutsideAlert returns undefined. What is the correct way to accept the handler in the hook?

Title: Pass handler to custom hook

Body:
I'm trying to figure out how to pass a state handler to a custom hook. The hook is:

function useOutsideAlerter(ref, handler) {
  useEffect(() => {
    /**
     * Alert if clicked on outside of element
     */
    function handleClickOutside(event) {
      if (ref.current && !ref.current.contains(event.target)) {
        console.log(handler)
      }
    }
    // Bind the event listener
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      // Unbind the event listener on clean up
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [ref]);
}

/**
 * Component that alerts if you click outside of it
 */
export default function OutsideAlerter(props) {
  const wrapperRef = useRef(null);
  useOutsideAlerter(wrapperRef);

  return
{props.children}
;
}

I've tried to call the component with:

<OutsideAlerter onClickOutside={handleToggle}><CartBox /></OutsideAlerter>

The console log of my supposed passed handler inside useOutsideAlert returns undefined. What is the correct way to accept the handler in the hook?


问:
Is multithreaded large-scale synchronous I/O multiplexing using select() possible?
I know I don't need multiple threads for this, but I like to know if multithreading is possible?

I checked internet and people suggest there is no need for multi threading.


问:
Error with respect to the DBT configuration
My DBT model is not recognizing the dataset and project id despite specifying these inside the profiles.yml file.

The following error seems to persist even after configuring the profiles.yml file in the path /root/.dbt while connecting the dbt model to the existing tables inside the self created dataset of BigQuery within the GCP framework.

```<code>Compilation Error in model file2 (models/example/file2.sql)
  Model 'model.model2.file2' (models/example/file2.sql) depends on a source named 'demo_dataset1.demo_table2' which was not found
</code>```

The dataset name / id and project name / id entered for the same in the profiles.yml conforms to that of the BigQuery inside GCP. However, the error still gets thrown.

I am currently executing this inside the terminal of a Jupyter notebook.

Is there an aspect that I may be overlooking and if so can you please suggest a solution for the same. Thank you.

Body:
My DBT model is not recognizing the dataset and project id despite specifying these inside the profiles.yml file.

The following error seems to persist even after configuring the profiles.yml file in the path /root/.dbt while connecting the dbt model to the existing tables inside the self created dataset of BigQuery within the GCP framework.

Compilation Error in model file2 (models/example/file2.sql)
  Model 'model.model2.file2' (models/example/file2.sql) depends on a source named 'demo_dataset1.demo_table2' which was not found

The dataset name / id and project name / id entered for the same in the profiles.yml conforms to that of the BigQuery inside GCP. However, the error still gets thrown.

I am currently executing this inside the terminal of a Jupyter notebook.

Is there an aspect that I may be overlooking and if so can you please suggest a solution for the same. Thank you.


问:
Custom 404 page with vercel.json
I deployed a landing page with only HTML and CSS and I want to create a custom page for some status codes, for now I'm just going to do the exercise with the 404 page.

In previous years I used Apache servers and it was just adding ErrorDocument 404 /404.html to the .htaccess, now I need to do the same with the vercel.json.

I found this in the Vercel guides, but according to the documentation it is already deprecated, and when I deploy it, Vercel rejects the deployment, so I used the standard redirects property, but I don't know how to update the old solution.

For now I need any request that returns a 404 response to redirect to the page.

My vercel.json:

{
    "cleanUrls": true,
    "redirects": [
        {
            "source": "/(.*)",
            "destination": "/status/404/index.html",
            "statusCode": 404
        }
    ]
}
```

Title: Custom 404 page with vercel.json


问:
Juypter Notebook crashes when I run pandas join
I am trying to join two tables TRAIN and STUDENT with an inner join. For some reason the whole juypter kernal keeps crashing when I run this line:

```<code>X_student = TRAIN.join(STUDENT, on='UserId', how='inner', sort=True)
</code>```

Here are what the tables look like:

NOTE: These tables are pandas dataframes

TRAIN.shape = (15867850, 6)

STUDENT.shape = (118971, 390)

I am trying to join the tables across the UserId. I know every UserId that occers in TRAIN will be in STUDENT and every UserId from STUDENT is used at least once in TRAIN. Note that the UserId is the index for STUDENT.

Running TRAIN.head().join(STUDENT, on='UserId', how='inner', sort=True) yields:

Why is my kernal crashing and how can I fix it?

This is the link to my google colab for the exact code that I am using.

Body:
I am trying to join two tables TRAIN and STUDENT with an inner join. For some reason the whole juypter kernal keeps crashing when I run this line:

X_student = TRAIN.join(STUDENT, on='UserId', how='inner', sort=True)

Here are what the tables look like:

NOTE: These tables are pandas dataframes

TRAIN.shape = (15867850, 6)

STUDENT.shape = (118971, 390)

I am trying to join the tables across the UserId. I know every UserId that occers in TRAIN will be in STUDENT and every UserId from STUDENT is used at least once in TRAIN. Note that the UserId is the index for STUDENT.

Running TRAIN.head().join(STUDENT, on='UserId', how='inner', sort=True) yields:

Why is my kernal crashing and how can I fix it?

This is the link to my google colab for the exact code that I am using.


问:
Type narrowing not working when using Omit
An example setup:

type A = {
  type: 'A';
  foo: string;
  baz: number;
}

type B = {
  type: 'B';
  bar: string;
  baz: number;
}

type Unioned = A | B
```
<p>This works fine:</p>
<pre class="lang-js prettyprint-override"><code>function handle(x:Unioned) {
  if (x.type === 'A') {
    console.log(x.foo)
  }
}
</code>```

However, I get an error with this:

function handle(x:Omit<Unioned, 'baz'>) {
  if (x.type === 'A') {
    console.log(x.foo)
  }
}
```

Specifically, the error I get is: Property 'foo' does not exist on type 'Omit<Unioned, "baz">'.

I would expect that typescript can infer the type of x within the if statement is actually Omit, but it doesn't.

What is it about using Omit that causes this to happen? And how can I make this work as expected?

Body:
An example setup:

type A = {
  type: 'A';
  foo: string;
  baz: number;
}

type B = {
  type: 'B';
  bar: string;
  baz: number;
}

type Unioned = A | B

This works fine:

function handle(x:Unioned) {
  if (x.type === 'A') {
    console.log(x.foo)
  }
}

However, I get an error with this:

function handle(x:Omit<Unioned, 'baz'>) {
  if (x.type === 'A') {
    console.log(x.foo)
  }
}

Specifically, the error I get is: Property 'foo' does not exist on type 'Omit<Unioned, "baz">'.

I would expect that typescript can infer the type of x within the if statement is actually Omit, but it doesn't.

What is it about using Omit that causes this to happen? And how can I make this work as expected?


问:
I want to make three Map in using below JSON response using model classes. Please share
I am a started to learn flutter, i am a beginner, i am stucking one point,I have API response related to checkBox.I want to map the values in to different map.

Here is the API response:

```<code>{
    "sms": {
        "very_low": true,
        "low": true,
        "medium": true,
        "high": false,
        "very_high": true
    },
    "email": {
        "very_low": true,
        "low": true,
        "medium": true,
        "high": true,
        "very_high": true
    },
    "mobile": {
        "very_low": true,
        "low": true,
        "medium": true,
        "high": true,
        "very_high": true
    }
}
</code>```

This is the actual model class,

```<code>class NotifigrationSetup {
  Sms? sms;
  Sms? email;
  Sms? mobile;

  NotifigrationSetup({this.sms, this.email, this.mobile});

  NotifigrationSetup.fromJson(Map<String, dynamic> json) {
    sms = json['sms'] != null ? new Sms.fromJson(json['sms']) : null;
    email = json['email'] != null ? new Sms.fromJson(json['email']) : null;
    mobile = json['mobile'] != null ? new Sms.fromJson(json['mobile']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.sms != null) {
      data['sms'] = this.sms!.toJson();
    }
    if (this.email != null) {
      data['email'] = this.email!.toJson();
    }
    if (this.mobile != null) {
      data['mobile'] = this.mobile!.toJson();
    }
    return data;
  }
}

class Sms {
  bool? veryLow;
  bool? low;
  bool? medium;
  bool? high;
  bool? veryHigh;

  Sms({this.veryLow, this.low, this.medium, this.high, this.veryHigh});

  Sms.fromJson(Map<String, dynamic> json) {
    veryLow = json['very_low'];
    low = json['low'];
    medium = json['medium'];
    high = json['high'];
    veryHigh = json['very_high'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['very_low'] = this.veryLow;
    data['low'] = this.low;
    data['medium'] = this.medium;
    data['high'] = this.high;
    data['very_high'] = this.veryHigh;
    return data;
  }
}
</code>```

So i want make three Map items like, sms,email,mobile, using this model. I am stucking in this section ,kindly request share your ideas

Body:
I am a started to learn flutter, i am a beginner, i am stucking one point,I have API response related to checkBox.I want to map the values in to different map.

Here is the API response:

{
    "sms": {
        "very_low": true,
        "low": true,
        "medium": true,
        "high": false,
        "very_high": true
    },
    "email": {
        "very_low": true,
        "low": true,
        "medium": true,
        "high": true,
        "very_high": true
    },
    "mobile": {
        "very_low": true,
        "low": true,
        "medium": true,
        "high": true,
        "very_high": true
    }
}

This is the actual model class,

class NotifigrationSetup {
  Sms? sms;
  Sms? email;
  Sms? mobile;

  NotifigrationSetup({this.sms, this.email, this.mobile});

  NotifigrationSetup.fromJson(Map<String, dynamic> json) {
    sms = json['sms'] != null ? new Sms.fromJson(json['sms']) : null;
    email = json['email'] != null ? new Sms.fromJson(json['email']) : null;
    mobile = json['mobile'] != null ? new Sms.fromJson(json['mobile']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.sms != null) {
      data['sms'] = this.sms!.toJson();
    }
    if (this.email != null) {
      data['email'] = this.email!.toJson();
    }
    if (this.mobile != null) {
      data['mobile'] = this.mobile!.toJson();
    }
    return data;
  }
}

class Sms {
  bool? veryLow;
  bool? low;
  bool? medium;
  bool? high;
  bool? veryHigh;

  Sms({this.veryLow, this.low, this.medium, this.high, this.veryHigh});

  Sms.fromJson(Map<String, dynamic> json) {
    veryLow = json['very_low'];
    low = json['low'];
    medium = json['medium'];
    high = json['high'];
    veryHigh = json['very_high'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['very_low'] = this.veryLow;
    data['low'] = this.low;
    data['medium'] = this.medium;
    data['high'] = this.high;
    data['very_high'] = this.veryHigh;
    return data;
  }
}

So i want make three Map items like, sms,email,mobile, using this model. I am stucking in this section ,kindly request share your ideas


问:
How to disable gravity and physics in 3d force graph which uses d3.js
I have a 3d graph with nodes, but its floating in the space and rotating on X axis, how can I disable it so nodes alway stay at the exact X Y Z position?

Example - https://imgur.com/a/8uSC7yn

This is my code

```<code>    this.Graph = ForceGraph3D()
      (document.getElementById('gameContainer'))
      .graphData(this.data)
        .width(300)
        .height(300)
        .forceEngine('d3')
        .backgroundColor('#00000000')
        .cameraPosition({
          x: 0,
          y: 15,
          z: 300
        })
        .nodeLabel('label')
        .nodeColor('color')
        // .nodeColor(node => highlightNodes.has(node) ? node === hoverNode ? 'rgb(255,0,0,1)' : 'rgba(255,160,0,0.8)' : 'rgba(0,255,255,0.6)')
        .linkWidth(link => highlightLinks.has(link) ? 4 : 1)
        .linkDirectionalParticles(link => highlightLinks.has(link) ? 4 : 0)
        .linkDirectionalParticleWidth(4)
    }
</code>```

Body:
I have a 3d graph with nodes, but its floating in the space and rotating on X axis, how can I disable it so nodes alway stay at the exact X Y Z position?

Example - https://imgur.com/a/8uSC7yn

This is my code

    this.Graph = ForceGraph3D()
      (document.getElementById('gameContainer'))
      .graphData(this.data)
        .width(300)
        .height(300)
        .forceEngine('d3')
        .backgroundColor('#00000000')
        .cameraPosition({
          x: 0,
          y: 15,
          z: 300
        })
        .nodeLabel('label')
        .nodeColor('color')
        // .nodeColor(node => highlightNodes.has(node) ? node === hoverNode ? 'rgb(255,0,0,1)' : 'rgba(255,160,0,0.8)' : 'rgba(0,255,255,0.6)')
        .linkWidth(link => highlightLinks.has(link) ? 4 : 1)
        .linkDirectionalParticles(link => highlightLinks.has(link) ? 4 : 0)
        .linkDirectionalParticleWidth(4)
    }


问:
how to move move multiple rows wihtin a jqGrid
What I am trying to make is

choose one or multiple rows

move up and down (=change order of the rows), not drag and drop

like the picture below.

I wonder if it's possible and please give me some hint or demo if it exists.


问:
gstream delay problems with udpsrc and tcpserver
I'm using mediasoup create plaintransport then I forward from udpsrc to tcpserversink like this:

```<code>gst-launch-1.0 udpsrc port=57616 caps="application/x-rtp,media=(string)audio,clock-rate=(int)48000,payload=(int)100,encoding-name=(string)OPUS,ssrc=(uint)613744965" ! rtpopusdepay ! opusdec ! tcpserversink port=23333 host=0.0.0.0
</code>```

on Client:

```<code>gst-launch-1.0 tcpclientsrc port=23333 host=11.22.33.44 ! rawaudioparse ! decodebin ! audioconvert ! audioresample ! autoaudiosink
</code>```

the problems is audio stream always delay 2,3 and increase time by time. and I have warning like this

```<code>gstrtpbasedepayload.c(505): gst_rtp_base_depayload_handle_buffer (): /GstPipeline:pipeline0/GstRTPOpusDepay:rtpopusdepay0:
Received invalid RTP payload, dropping
WARNING: from element /GstPipeline:pipeline0/GstRTPOpusDepay:rtpopusdepay0: Could not decode stream.
</code>```

please help me solve this and improve stream delay problems

Body:
I'm using mediasoup create plaintransport then I forward from udpsrc to tcpserversink like this:

gst-launch-1.0 udpsrc port=57616 caps="application/x-rtp,media=(string)audio,clock-rate=(int)48000,payload=(int)100,encoding-name=(string)OPUS,ssrc=(uint)613744965" ! rtpopusdepay ! opusdec ! tcpserversink port=23333 host=0.0.0.0

on Client:

gst-launch-1.0 tcpclientsrc port=23333 host=11.22.33.44 ! rawaudioparse ! decodebin ! audioconvert ! audioresample ! autoaudiosink

the problems is audio stream always delay 2,3 and increase time by time. and I have warning like this

gstrtpbasedepayload.c(505): gst_rtp_base_depayload_handle_buffer (): /GstPipeline:pipeline0/GstRTPOpusDepay:rtpopusdepay0:
Received invalid RTP payload, dropping
WARNING: from element /GstPipeline:pipeline0/GstRTPOpusDepay:rtpopusdepay0: Could not decode stream.

please help me solve this and improve stream delay problems


问:
P2P communication in node.js?
I am trying to make a commandline messaging tool in node.js using websockets. However, I have pretty early on ran into a problem. A while ago I was going to make this in python, but I had complications with it's very linear way of doing things. Javascript is nonblocking and designed for these things, so I thought it would be pretty straightforward. But the issue persists.

I want to get true P2P communication working - that is, without a server. I also would rather not have multiple peices of code to act as a server and client on each machine - they should both have, and be running, the same code. Is this possible?

In python I origionally tried out a multithreaded script, but that was a mess. I think I have a few ideas to solve this, but help would be appreceated.

Title: P2P communication in node.js?


问:
How to add change style sheet of QTButtons and QTLabel in a loop using QSignalMapper and findChild in C++98
I am new in QT using C++ 98.I am setting the stylesheet in QT from of 5 label and 5 button using this class function

Code 1(working)

```<code>void Display::setting_Style()
{
       MyForm::getMyForm()->widget.BTN_FUN1_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));
       MyForm::getMyForm()->widget.BTN_FUN2_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));
       MyForm::getMyForm()->widget.BTN_FUN3_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));
       MyForm::getMyForm()->widget.BTN_FUN4_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));
       MyForm::getMyForm()->widget.BTN_FUN5_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));

       MyForm::getMyForm()->widget.LBL_FUN1_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));
       MyForm::getMyForm()->widget.LBL_FUN2_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));
       MyForm::getMyForm()->widget.LBL_FUN3_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));
       MyForm::getMyForm()->widget.LBL_FUN4_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));
       MyForm::getMyForm()->widget.LBL_FUN5_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));
}
</code>```

I want to replace this muliple statements qt widget for setStyleSheet by QSignalMapper findChid for setting same stylesheet in one line in a loop in C++ like this

Code 2(not working)

```<code>    #include <QMainWindow>
    #include <QSignalMapper>
    #include <QPushButton>
    #include <QLabel>
        void Display::setting_Style()
        {
                   signalMapper = new QSignalMapper(MyForm::getMyForm());
                    for (int i = 1; i <= 5; ++i) {
                        QPushButton* btn = signalMapper->widget->findChild<QPushButton*>("BTN_FUN" +QString::number(i)+"_TEL");
                        btn->setStyleSheet("background-color: rgb(255, 0, 0);border-radius:30px;");
                        signalMapper->setMapping(btn, btn);
//signalMapper->setMapping(this, btn)
                    }

                    for (int i = 1; i <= 5; ++i) {
                        QLabel *btn = widget->findChild<QLabel*>("LBL_FUN" +QString::number(i)+"_TEL");
                        btn->setStyleSheet("background-color: rgb(255, 0, 0);border-radius:30px;");
                        signalMapper->setMapping(btn, btn);
                    }
    }
</code>```

It is giving me this error

The program is crashing ,segmentation fault

How i can resolve this error and make Code 2 work ?

Body:
I am new in QT using C++ 98.I am setting the stylesheet in QT from of 5 label and 5 button using this class function

Code 1(working)

void Display::setting_Style()
{
       MyForm::getMyForm()->widget.BTN_FUN1_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));
       MyForm::getMyForm()->widget.BTN_FUN2_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));
       MyForm::getMyForm()->widget.BTN_FUN3_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));
       MyForm::getMyForm()->widget.BTN_FUN4_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));
       MyForm::getMyForm()->widget.BTN_FUN5_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));

       MyForm::getMyForm()->widget.LBL_FUN1_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));
       MyForm::getMyForm()->widget.LBL_FUN2_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));
       MyForm::getMyForm()->widget.LBL_FUN3_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));
       MyForm::getMyForm()->widget.LBL_FUN4_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));
       MyForm::getMyForm()->widget.LBL_FUN5_TEL->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 0, 0);border-radius:30px;"));
}

I want to replace this muliple statements qt widget for setStyleSheet by QSignalMapper findChid for setting same stylesheet in one line in a loop in C++ like this

Code 2(not working)

    #include <QMainWindow>
    #include <QSignalMapper>
    #include <QPushButton>
    #include <QLabel>
        void Display::setting_Style()
        {
                   signalMapper = new QSignalMapper(MyForm::getMyForm());
                    for (int i = 1; i <= 5; ++i) {
                        QPushButton* btn = signalMapper->widget->findChild<QPushButton*>("BTN_FUN" +QString::number(i)+"_TEL");
                        btn->setStyleSheet("background-color: rgb(255, 0, 0);border-radius:30px;");
                        signalMapper->setMapping(btn, btn);
//signalMapper->setMapping(this, btn)
                    }

                    for (int i = 1; i <= 5; ++i) {
                        QLabel *btn = widget->findChild<QLabel*>("LBL_FUN" +QString::number(i)+"_TEL");
                        btn->setStyleSheet("background-color: rgb(255, 0, 0);border-radius:30px;");
                        signalMapper->setMapping(btn, btn);
                    }
    }

It is giving me this error

The program is crashing ,segmentation fault

How i can resolve this error and make Code 2 work ?