问:
How can I combine my constants components with the API request?
I'm still a bit of a newbie in web dev and I've hit on a stumbling block. I'm currently working on a project that fetches API images and I want to attach links to it in my code but it would multiply the number of arrays and this is the problem.

Here is a snapshot of it-

```<code>import React, { useState, useEffect } from 'react';
import '../App.css';
import axios from 'axios';
import  sites  from './Constants';

const Leagues = () => {
  const [data, setData] = useState([]);

  useEffect(()=> {
    axios('https://api-football-standings.azharimm.site/leagues')

    .then(res => {
      console.log(res.data.data);
      setData(res.data.data);
    })
  }, [])

  return <div className='leagues-container'>
    {data.map((data)=> (
      sites.map(({ source })=> (
          <div key={data.id}>
            <a href={source} target='_blank' rel='noreferrer' className='leagues-div'>
              <img src={data.logos.light} />
            </a>
            <h1>{data.name}</h1>
          </div>
        ))))}
    </div>;
};

export default Leagues;
</code>```

I've also created a constants component which has an array of the links that should be appropriate to each image.

Constants-

```<code>const sites = [
  {
    id: 0,
    title: 'Argentinian League',
    source: 'https://www.afa.com.ar/es/'
  },
  {
    id: 1,
    title: 'Australian League',
    source: 'https://www.ultimatealeague.com/'
  },
  {
    id: 2,
    title: 'Brazilian League',
    source: 'https://www.espn.com.au/football/league/_/name/bra.1'
  },
  {
    id: 3,
    title: 'Chinese League',
    source: 'https://www.thecfa.cn/Eindex/index.html'
  },
  {
    id: 4,
    title: 'Dutch League',
    source: 'https://eredivisie.eu/home/'
  },
  {
    id: 5,
    title: 'English League',
    source: 'https://www.premierleague.com/'
  },
  {
    id: 6,
    title: 'French League',
    source: 'https://www.ligue1.com/'
  },
  {
    id: 7,
    title: 'German League',
    source: 'https://www.bundesliga.com/en/bundesliga'
  },
  {
    id: 8,
    title: 'Indonesian League',
    source: 'https://www.espn.com.au/football/league/_/name/idn.1'
  },
  {
    id: 9,
    title: 'Italian League',
    source: 'https://www.legaseriea.it/en'
  },
  {
    id: 10,
    title: 'Japanese League',
    source: 'https://www.jleague.co/'
  },
  {
    id: 11,
    title: 'Malaysian League',
    source: 'https://www.malaysianfootballleague.com/'
  },
  {
    id: 12,
    title: 'Mexican League',
    source: 'https://www.espn.com.au/football/schedule/_/league/mex.1'
  },
  {
    id: 13,
    title: 'Portuguese League',
    source: 'https://www.ligaportugal.pt/en/homepage/'
  },
  {
    id: 14,
    title: 'Russian League',
    source: 'https://eng.premierliga.ru/'
  },
  {
    id: 15,
    title: 'Singaporean League',
    source: 'https://www.spl.sg/'
  },
  {
    id: 16,
    title: 'Spanish League',
    source: 'https://www.laliga.com/en-GB'
  },
  {
    id: 17,
    title: 'Thai League',
    source: 'https://www.thaileague.co.th/131'
  },
  {
    id: 18,
    title: 'Turkish League',
    source: 'https://www.tff.org/Default.aspx?pageID=449'
  },
  {
    id: 19,
    title: 'Ugandan League',
    source: 'https://fufa.co.ug/uganda-premier-league/'
  },

]

export default sites
</code>```

There are 20 items on the array on the API and there are 20 links that I created on the constants component that would link to the corresponding items. I have attached a snapshot of the problem below. On that image I was hovering on the second image that would correspond to the second link on the constant component. The link is correct but the image isn't. As can be seen by the scroll bar, I mistakenly managed to multiply the images by that of the links. Any recommendation is welcomed!

photo of multiplied images

答:
You are doing the map twice which means for each element that is looping on the outer loop there is another internal loop. This is why data is duplicated.

 const findSource =(index) => {
    const site = sites.find((el) => el.id === index)
    return site.source;
  }

  return (

    {data.map((data,index)=> (

{data.name}

       ))}

  );

```

Here I created a function for finding the link from the sites list. According to the way you have defined the sites array, this will only work properly if your API response and the sites array is in the same order. So I recommend to have a common ID for both the sites array and API response. For example you can have id: "arg.1" and so on.

sandbox demo

Body:
I'm still a bit of a newbie in web dev and I've hit on a stumbling block. I'm currently working on a project that fetches API images and I want to attach links to it in my code but it would multiply the number of arrays and this is the problem.

Here is a snapshot of it-

import React, { useState, useEffect } from 'react';
import '../App.css';
import axios from 'axios';
import  sites  from './Constants';

const Leagues = () => {
  const [data, setData] = useState([]);

  useEffect(()=> {
    axios('https://api-football-standings.azharimm.site/leagues')

    .then(res => {
      console.log(res.data.data);
      setData(res.data.data);
    })
  }, [])

  return

    {data.map((data)=> (
      sites.map(({ source })=> (

{data.name}

        ))))}

;
};

export default Leagues;

I've also created a constants component which has an array of the links that should be appropriate to each image.

Constants-

const sites = [
  {
    id: 0,
    title: 'Argentinian League',
    source: 'https://www.afa.com.ar/es/'
  },
  {
    id: 1,
    title: 'Australian League',
    source: 'https://www.ultimatealeague.com/'
  },
  {
    id: 2,
    title: 'Brazilian League',
    source: 'https://www.espn.com.au/football/league/_/name/bra.1'
  },
  {
    id: 3,
    title: 'Chinese League',
    source: 'https://www.thecfa.cn/Eindex/index.html'
  },
  {
    id: 4,
    title: 'Dutch League',
    source: 'https://eredivisie.eu/home/'
  },
  {
    id: 5,
    title: 'English League',
    source: 'https://www.premierleague.com/'
  },
  {
    id: 6,
    title: 'French League',
    source: 'https://www.ligue1.com/'
  },
  {
    id: 7,
    title: 'German League',
    source: 'https://www.bundesliga.com/en/bundesliga'
  },
  {
    id: 8,
    title: 'Indonesian League',
    source: 'https://www.espn.com.au/football/league/_/name/idn.1'
  },
  {
    id: 9,
    title: 'Italian League',
    source: 'https://www.legaseriea.it/en'
  },
  {
    id: 10,
    title: 'Japanese League',
    source: 'https://www.jleague.co/'
  },
  {
    id: 11,
    title: 'Malaysian League',
    source: 'https://www.malaysianfootballleague.com/'
  },
  {
    id: 12,
    title: 'Mexican League',
    source: 'https://www.espn.com.au/football/schedule/_/league/mex.1'
  },
  {
    id: 13,
    title: 'Portuguese League',
    source: 'https://www.ligaportugal.pt/en/homepage/'
  },
  {
    id: 14,
    title: 'Russian League',
    source: 'https://eng.premierliga.ru/'
  },
  {
    id: 15,
    title: 'Singaporean League',
    source: 'https://www.spl.sg/'
  },
  {
    id: 16,
    title: 'Spanish League',
    source: 'https://www.laliga.com/en-GB'
  },
  {
    id: 17,
    title: 'Thai League',
    source: 'https://www.thaileague.co.th/131'
  },
  {
    id: 18,
    title: 'Turkish League',
    source: 'https://www.tff.org/Default.aspx?pageID=449'
  },
  {
    id: 19,
    title: 'Ugandan League',
    source: 'https://fufa.co.ug/uganda-premier-league/'
  },

]

export default sites

There are 20 items on the array on the API and there are 20 links that I created on the constants component that would link to the corresponding items. I have attached a snapshot of the problem below. On that image I was hovering on the second image that would correspond to the second link on the constant component. The link is correct but the image isn't. As can be seen by the scroll bar, I mistakenly managed to multiply the images by that of the links. Any recommendation is welcomed!

photo of multiplied images

Body:
You are doing the map twice which means for each element that is looping on the outer loop there is another internal loop. This is why data is duplicated.

 const findSource =(index) => {
    const site = sites.find((el) => el.id === index)
    return site.source;
  }

  return (
    <div className='leagues-container'>
    {data.map((data,index)=> (
          <div key={data.id}>
            <a href={findSource(index)} target='_blank' rel='noreferrer' className='leagues-div'>
              <img src={data.logos.light} alt={data.name} />
            </a>
            <h1>{data.name}</h1>
          </div>
       ))}
    </div>
  );

Here I created a function for finding the link from the sites list. According to the way you have defined the sites array, this will only work properly if your API response and the sites array is in the same order. So I recommend to have a common ID for both the sites array and API response. For example you can have id: "arg.1" and so on.

sandbox demo


来源: stackexchange

问:
Is it possible to add a elb (cloud provider) to an existing kubernetes cluster running on RHEL8 EC2?
i have a cluster running on aws ec2 and not a managed EKS, i'm trying to add a loadbalancer to the cluster without restarting it or initializing a new node, is that possible ? i've already set the permission and tags related to this post https://blog.heptio.com/setting-up-the-kubernetes-aws-cloud-provider-6f0349b512bd
But the thing is that we must add the flag --cloud-provider=aws  to the Kubelet before adding the node to the cluster.
Is there any other options or other way to do it ?
[kubectl get nodes][1]</p>

答:
You can try using AWS load balancer controller, it works with both managed and self-managed K8s clusters https://kubernetes-sigs.github.io/aws-load-balancer-controller/v2.3/

Zee

ContentLicense: CC BY-SA 4.0


问:
Hazelcast's CacheManager not injected by Spring Boot
I'm trying to setup Hazelcast 4.2.0 with Spring Boot 2.1.18, and those are my dependencies:

<depdendency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-integration</artifactId>
    <version>2.1.18.RELEASE</version>
<depdendency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
    <version>2.1.18.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-autoconfigure</artifactId>
    <version>2.1.18.RELEASE</version>
</dependency>

<dependency>
    <groupId>javax.cache</groupId>
    <artifactId>cache-api</artifactId>
    <version>1.1.1</version>
</dependency>

<dependency>
    <groupId>com.hazelcast</groupId>
    <artifactId>hazelcast-all</artifactId>
    <version>4.2</version>
</dependency>
```
<p>The problem is that I cannot inject my configured cache manager into the application as it is not recognized by Spring. This is my cache manager class</p>
<pre class="lang-java prettyprint-override"><code>@Import(cachingConfig.class)
@Configuration
public class MyCacheManager {

   @Inject
   private CacheManager cacheManager;

   @PostConstruct
   private void postConstruct() {
     MutableConfiguration<String, Account> cacheConfig = new MutableConfiguration<String,
     Account>();
     ...
     cacheManager.createCache("cacheName", cacheConfig);
     ...
   }
}
</code>```

And here is my caching configuration class

@EnableCaching
@Configuration
public class CachingConfig {

      @Bean
      public CacheManager cacheManager() {
        Config config = new Config();
        config.setInstanceName("test");
        HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
        return new HazelcastCacheManager(instance);
      }
    }
```

The error I get is

No qualifying bean of type 'javax.cache.cacheManager' available'

but I don't understand why. It's like the Hazelcast cache manager is not recognized and injected. Can someone help me?

答:
There are two CacheManager classes

Your @Bean returns org.springframework.cache.CacheManager

The @Inject is using javax.cache.CacheManager.

Here's some samples where it is done, maybe easy to copy them,
jcache 1.1
and jcache 1.0

Body:
I'm trying to setup Hazelcast 4.2.0 with Spring Boot 2.1.18, and those are my dependencies:

<depdendency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-integration</artifactId>
    <version>2.1.18.RELEASE</version>
<depdendency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
    <version>2.1.18.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-autoconfigure</artifactId>
    <version>2.1.18.RELEASE</version>
</dependency>

<dependency>
    <groupId>javax.cache</groupId>
    <artifactId>cache-api</artifactId>
    <version>1.1.1</version>
</dependency>

<dependency>
    <groupId>com.hazelcast</groupId>
    <artifactId>hazelcast-all</artifactId>
    <version>4.2</version>
</dependency>

The problem is that I cannot inject my configured cache manager into the application as it is not recognized by Spring. This is my cache manager class

@Import(cachingConfig.class)
@Configuration
public class MyCacheManager {

   @Inject
   private CacheManager cacheManager;

   @PostConstruct
   private void postConstruct() {
     MutableConfiguration<String, Account> cacheConfig = new MutableConfiguration<String,
     Account>();
     ...
     cacheManager.createCache("cacheName", cacheConfig);
     ...
   }
}

And here is my caching configuration class

@EnableCaching
@Configuration
public class CachingConfig {

      @Bean
      public CacheManager cacheManager() {
        Config config = new Config();
        config.setInstanceName("test");
        HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
        return new HazelcastCacheManager(instance);
      }
    }

The error I get is

No qualifying bean of type 'javax.cache.cacheManager' available'

but I don't understand why. It's like the Hazelcast cache manager is not recognized and injected. Can someone help me?


问:
Common way to build and deploy a react web project
I finished a part of my project and bought a webspace with a domain and a database to publish on. So I create a React-Typescript project with followed structure:

API: has my controllers

BLL: the services

Question do I have to create a Build and publish it on the webspace, with the API, BLL... or only the Web component? So that the API, BLL... are on a seperate server and the fetches from the Web-Component are via IP:Port address?

What is the common way here?

答:
The in and outs of web hosting is massively large problem space. And the strategies and approaches number in the thousands. I couldn't hope to do justice to that in a single answer. But in short, you probably want them on the same server, and you want your backend to deliver your front end assets to browsers somehow. And your frontend makes requests without a domain like /api/mydata/ to pull data from the same domain as the frontend. This question will likely get closed now, as it's way too broad to answer.
– Alex Wayne</p>


问:
Connecting to port 21 with Paramiko and got paramiko.ssh_exception.SSHException: Error reading SSH protocol banner
I'm trying to connect to am SFTP server through Paramiko. I don't have a host key. The following code is my attempt and it's giving me an error that says:

paramiko.ssh_exception.SSHException: Error reading SSH protocol banner

I notice that port is usually 22 in other given examples, but the SFTP port I was given is 21. And when I tried 22, it gave me another error saying

Unable to connect to port 22

Thank you in advance for your guidance and insight. Please let me know if I could provide more information.

```<code>from paramiko.client import SSHClient
from paramiko import AutoAddPolicy

client = SSHClient()
client.set_missing_host_key_policy(AutoAddPolicy())

client.connect(hostname="a_private_ip",
               port=21,
               username="user",
               password="xxx")

sftp_handle = client.open_sftp()
</code>```

答:
Paramiko is an SFTP client. The SFTP uses port 22.

If you were given port 21, then it's most likely NOT SFTP. The port 21 is used by FTP. Encrypted variant of FTP, called also FTPS, uses 21 too. And people sometimes mistake it for SFTP.

For FTP use FTP class from ftplib. For FTPS use FTP_TLS class from ftplib.

Body:
I'm trying to connect to am SFTP server through Paramiko. I don't have a host key. The following code is my attempt and it's giving me an error that says:

paramiko.ssh_exception.SSHException: Error reading SSH protocol banner

I notice that port is usually 22 in other given examples, but the SFTP port I was given is 21. And when I tried 22, it gave me another error saying

Unable to connect to port 22

Thank you in advance for your guidance and insight. Please let me know if I could provide more information.

from paramiko.client import SSHClient
from paramiko import AutoAddPolicy

client = SSHClient()
client.set_missing_host_key_policy(AutoAddPolicy())

client.connect(hostname="a_private_ip",
               port=21,
               username="user",
               password="xxx")

sftp_handle = client.open_sftp()


问:
swagger ui topbar plugin react ts
I am using webpack as my bundler. I am trying to integrate the swagger UI for multiple urls. "swagger-ui": "3.51.2".

```<code>import React from "react";
import SwaggerUi, { presets } from "swagger-ui";

// eslint-disable-next-line import/extensions
import SWaggerUiStandalonePreset from "swagger-ui/dist/swagger-ui-standalone-preset.js";

import "swagger-ui/dist/swagger-ui.css";

const Swagger: React.FC = () => {

  React.useEffect(() => {
    SwaggerUi({
      dom_id: "#swaggerContainer",
      urls: [
        {
          url: "http://petstore.swagger.io/v2/swagger.json",
          name: "test1",
        },
        {
          url: `http://petstore.swagger.io/v2/swagger.json`,
          name: "test2",
        },
      ],
      presets: [presets.apis, SWaggerUiStandalonePreset],
      plugins: [SwaggerUi.plugins.Topbar],
    });
  });

  return <div id="swaggerContainer" />;
};

export default Swagger;
</code>```

I am doing something like this and it says, no api definitions found! but if i do just url instead of urls, it works?

How to display something with the topbar plugin?

答: The topbar plug URLs: variable is expecting an array of a url and a name. A potential issue may be that you don't have SwaggerUIBundle.plugins.DownloadUrl in your plugins. This plugin renders the JSON file in the browser.

Title: swagger ui topbar plugin react ts

Body:
I am using webpack as my bundler. I am trying to integrate the swagger UI for multiple urls. "swagger-ui": "3.51.2".

import React from "react";
import SwaggerUi, { presets } from "swagger-ui";

// eslint-disable-next-line import/extensions
import SWaggerUiStandalonePreset from "swagger-ui/dist/swagger-ui-standalone-preset.js";

import "swagger-ui/dist/swagger-ui.css";

const Swagger: React.FC = () => {

  React.useEffect(() => {
    SwaggerUi({
      dom_id: "#swaggerContainer",
      urls: [
        {
          url: "http://petstore.swagger.io/v2/swagger.json",
          name: "test1",
        },
        {
          url: `http://petstore.swagger.io/v2/swagger.json`,
          name: "test2",
        },
      ],
      presets: [presets.apis, SWaggerUiStandalonePreset],
      plugins: [SwaggerUi.plugins.Topbar],
    });
  });

  return
;
};

export default Swagger;

I am doing something like this and it says, no api definitions found! but if i do just url instead of urls, it works?

How to display something with the topbar plugin?


问:
I want to rewrite https://blog/home/post?read=example to https://blog/home/example with .htaccess
I have tried many methods but none has worked.
Blog is the name of the domain, Home is a folder in the domain and post.php is the page getting details from database.
So, in my domain, I have:
home/post.php

```<code>RewriteEngine On    # Turn on the rewriting engine
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([A-Za-z0-9_-]+)$ /post?read=$1 [L]    # Handle page requests
</code>```

Above is the last code I used and it is not working. I'm getting a 404 error.

答:
```<code>RewriteEngine On    # Turn on the rewriting engine
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([A-Za-z0-9_-]+)$ /post?read=$1 [L]    # Handle page requests
</code>```

The .htaccess is located in the root of the folder.

You seem to be ignoring the home subdirectory. (Although you've referred to both home and Home in your question - note that this is case-sensistive.) And if "/post is a PHP file" then you should presumably be rewriting to post.php, not simply post?

Note that Apache does not support line-end comments, as you are using here. (At best they get ignored, at worst they trigger a 500 error.)

If the .htaccess file is located in the document root, as you suggest then you would need to write the rule as follows:

```<code>RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^home/([\w-]+)$ home/post.php?read=$1 [L]
</code>```

The \w shorthand character class is the same as [A-Za-z0-9_].

The RewriteRule pattern matches the URL-path relative to the location of the .htaccess file.

If, on the other hand, the .htaccess file is in the /home subdirectory (ie. at /home/.htaccess) then you would write the rule like this instead:

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)$ post.php?read=$1 [L]
</code>```

Note, there is no slash prefix on the substitution string.

Body:
I have tried many methods but none has worked.
Blog is the name of the domain, Home is a folder in the domain and post.php is the page getting details from database.
So, in my domain, I have:
home/post.php

RewriteEngine On    # Turn on the rewriting engine
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([A-Za-z0-9_-]+)$ /post?read=$1 [L]    # Handle page requests

Above is the last code I used and it is not working. I'm getting a 404 error.

Body:
RewriteEngine On    # Turn on the rewriting engine
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([A-Za-z0-9_-]+)$ /post?read=$1 [L]    # Handle page requests

The .htaccess is located in the root of the folder.

You seem to be ignoring the home subdirectory. (Although you've referred to both home and Home in your question - note that this is case-sensistive.) And if "/post is a PHP file" then you should presumably be rewriting to post.php, not simply post?

Note that Apache does not support line-end comments, as you are using here. (At best they get ignored, at worst they trigger a 500 error.)

If the .htaccess file is located in the document root, as you suggest then you would need to write the rule as follows:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^home/([\w-]+)$ home/post.php?read=$1 [L]

The \w shorthand character class is the same as [A-Za-z0-9_].

The RewriteRule pattern matches the URL-path relative to the location of the .htaccess file.

If, on the other hand, the .htaccess file is in the /home subdirectory (ie. at /home/.htaccess) then you would write the rule like this instead:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)$ post.php?read=$1 [L]

Note, there is no slash prefix on the substitution string.


问:
How to get One Signal unique user id in Mobile?
I am developing a restaurant app. I am using One Signal in my app to send notifications. Here while I place the order I need to send the unique Id of the one signal for a specific user for getting notification of "Your Order is placed successfully... It is in Progress.Please wait". For that I need the user's One Signal user id. How can I get it? I am newbie to One Signal. Please help me.</p>

答:
Use this code to get player id</p>
```<code>public class MainActivity extends Activity implements OSSubscriptionObserver {
  protected void onCreate(Bundle savedInstanceState) {
    OneSignal.addSubscriptionObserver(this);
  }

  public void onOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges) {
    if (!stateChanges.getFrom().getSubscribed() &&
        stateChanges.getTo().getSubscribed()) {
         new AlertDialog.Builder(this)
             .setMessage("You've successfully subscribed to push notifications!")
             .show();
        // get player ID
        stateChanges.getTo().getUserId();
      }

      Log.i("Debug", "onOSSubscriptionChanged: " + stateChanges);
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Use this code to get player id

public class MainActivity extends Activity implements OSSubscriptionObserver {
  protected void onCreate(Bundle savedInstanceState) {
    OneSignal.addSubscriptionObserver(this);
  }

  public void onOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges) {
    if (!stateChanges.getFrom().getSubscribed() &&
        stateChanges.getTo().getSubscribed()) {
         new AlertDialog.Builder(this)
             .setMessage("You've successfully subscribed to push notifications!")
             .show();
        // get player ID
        stateChanges.getTo().getUserId();
      }

      Log.i("Debug", "onOSSubscriptionChanged: " + stateChanges);
  }
}


问:
Blocking SOME but not all endpoints in Wordpress rest api
I am creating a REACT app that uses wordpress as a backend through the rest API. I am using the Simple-JWT-Login plugin to handle the register, login, authentication, and it works perfectly.

I want to block non-logged in users from accessing the /wp/v2/posts endpoint. I know I can do this by doing something like:

```<code>
    add_filter( 'rest_authentication_errors', function( $result ) {
      if ( ! empty( $result ) ) {
        return $result;
      }
      if ( ! is_user_logged_in() ) {
        return new WP_Error( 'rest_not_logged_in', 'You are not currently logged in.', array( 'status' => 401 ) );
      }
      if ( ! current_user_can( 'edit_posts' ) ) {
        return new WP_Error( 'rest_not_admin', 'You are not entitled to view that.', array( 'status' => 401 ) );
      }
      return $result;
    });

</code>```

However that blocks all endpoints, including ?rest_route=/simple-jwt-login/v1/auth and ?rest_route=/simple-jwt-login/v1/users which are the ones from the Simple-JWT-Login plugin used for registering and authenticating users. Therefore users end up in a catch 22 whereby they can't login unless they are already logged in!

Is there a way of modifying the above code to block just the wp/v2/posts/ endpoint, or, alternatively, of effectively whitelisting the registering and authenticating endpoints?

Many thanks for any ideas!

Have searched on here and elsewhere but can't find a solution.

答:
You could always check for the url before showing the error  with $_SERVER['REQUEST_URI'] but that might become a pain to add all your allowed urls in a if check.

I like to use apache_request_headers with preg_match to check for a Bearer Token and if the current request has the correct bearer token, show the results. Otherwise you would throw a error. I can't guarantee its 100% safe or the correct way to do it but it works pretty well for a super basic simple system.

Something like the below code might work for someone:

```<code>add_filter("rest_authentication_errors", function ($result) {

    if (!empty($result)) {
        return $result;
    }

    $headers = apache_request_headers();

    $matches = array();

    $currentToken = "PUT YOUR BEARER TOKEN HERE";
    $pattern = $currentToken."/i";

    preg_match('/Bearer '. $pattern, $headers['Authorization'], $matches);

    if(isset($matches)){

        $token = $matches[0];

        if($token == 'Bearer ' . $currentToken){

            return $result;

        } else {

             return new WP_Error( 'no_auth_found', 'You are not currently logged in.' , array( 'status' => 401));

        }

    }

});
</code>```

Body:
I am creating a REACT app that uses wordpress as a backend through the rest API. I am using the Simple-JWT-Login plugin to handle the register, login, authentication, and it works perfectly.

I want to block non-logged in users from accessing the /wp/v2/posts endpoint. I know I can do this by doing something like:

    add_filter( 'rest_authentication_errors', function( $result ) {
      if ( ! empty( $result ) ) {
        return $result;
      }
      if ( ! is_user_logged_in() ) {
        return new WP_Error( 'rest_not_logged_in', 'You are not currently logged in.', array( 'status' => 401 ) );
      }
      if ( ! current_user_can( 'edit_posts' ) ) {
        return new WP_Error( 'rest_not_admin', 'You are not entitled to view that.', array( 'status' => 401 ) );
      }
      return $result;
    });

However that blocks all endpoints, including ?rest_route=/simple-jwt-login/v1/auth and ?rest_route=/simple-jwt-login/v1/users which are the ones from the Simple-JWT-Login plugin used for registering and authenticating users. Therefore users end up in a catch 22 whereby they can't login unless they are already logged in!

Is there a way of modifying the above code to block just the wp/v2/posts/ endpoint, or, alternatively, of effectively whitelisting the registering and authenticating endpoints?

Many thanks for any ideas!

Have searched on here and elsewhere but can't find a solution.

Body:
You could always check for the url before showing the error  with $_SERVER['REQUEST_URI'] but that might become a pain to add all your allowed urls in a if check.

I like to use apache_request_headers with preg_match to check for a Bearer Token and if the current request has the correct bearer token, show the results. Otherwise you would throw a error. I can't guarantee its 100% safe or the correct way to do it but it works pretty well for a super basic simple system.

Something like the below code might work for someone:

add_filter("rest_authentication_errors", function ($result) {

    if (!empty($result)) {
        return $result;
    }

    $headers = apache_request_headers();

    $matches = array();

    $currentToken = "PUT YOUR BEARER TOKEN HERE";
    $pattern = $currentToken."/i";

    preg_match('/Bearer '. $pattern, $headers['Authorization'], $matches);

    if(isset($matches)){

        $token = $matches[0];

        if($token == 'Bearer ' . $currentToken){

            return $result;

        } else {

             return new WP_Error( 'no_auth_found', 'You are not currently logged in.' , array( 'status' => 401));

        }

    }

});


问:
Defining Observation Space in Open AI Gym
I am working on a deep reinforcement problem, I am new to this. I am writing a snippet of code and errors I am getting.

Broker_Node_Map is a list of values present in different positions in a machine. I don't know how to present these values as integers. This is the state I have as it's changing too accordingly. Please suggest what should I do. Please be kind, I am pretty new and trying to get hold of things.

def __init__(self):
    super(BrokerEnv2, self).__init__()
    reward = 0
    self.action_space = DiscreteActions.get_action_space()
    self.observation_space = DiscreteObservations.get_observation_space()

def reset(self):
    observed_State = self.Broker_Node_Map
    return observed_State
```
<p>While checking env on stable baselines  - <code>check_env(env) **Error** - AssertionError: The observation returned by reset() method must be an int</code></p>
<p><strong>EDIT 1 -</strong>
Very careless of me. Changed the space to box space but now another error emerged.
<strong>AssertionError: The observation returned by the reset() method does not match the given observation space</strong></p>
<p>This is what my reset() is returning -</p>
```<class 'numpy.ndarray'> (46,) [26 33  0 50  0  0 73 26  0 29  0 34 27 67  0  0  0  0 35 60  0  0 24 22
  0  0  0  0 25  0 17  0  0  0 21  0  0 53 68 40 51  0 62  0 56  0]
```
<p>This is how I have defined my observation space -</p>
```self.observation_space = spaces.Box(low=1, high=73, shape=(46,), dtype=np.int64)
```

Please help me out why this error is coming?

答: So I ran into the same problem and the fix for me was to set the bounds of space correctly. For example in your case, the state contains zeros but you've set the low bound to 1.</p>

Body:
I am working on a deep reinforcement problem, I am new to this. I am writing a snippet of code and errors I am getting.

Broker_Node_Map is a list of values present in different positions in a machine. I don't know how to present these values as integers. This is the state I have as it's changing too accordingly. Please suggest what should I do. Please be kind, I am pretty new and trying to get hold of things.

def __init__(self):
    super(BrokerEnv2, self).__init__()
    reward = 0
    self.action_space = DiscreteActions.get_action_space()
    self.observation_space = DiscreteObservations.get_observation_space()

def reset(self):
    observed_State = self.Broker_Node_Map
    return observed_State

While checking env on stable baselines  - check_env(env) **Error** - AssertionError: The observation returned by reset() method must be an int

EDIT 1 -
Very careless of me. Changed the space to box space but now another error emerged.
AssertionError: The observation returned by the reset() method does not match the given observation space

This is what my reset() is returning -

<class 'numpy.ndarray'> (46,) [26 33  0 50  0  0 73 26  0 29  0 34 27 67  0  0  0  0 35 60  0  0 24 22
  0  0  0  0 25  0 17  0  0  0 21  0  0 53 68 40 51  0 62  0 56  0]

This is how I have defined my observation space -

self.observation_space = spaces.Box(low=1, high=73, shape=(46,), dtype=np.int64)

Please help me out why this error is coming?


问:
How to group the list based on count of previous list odd integer?
I need to group the list based  based on (N -count of previous list odd integer)

Example:

Input

```<code>n=5
l=[[45, 20, 40, 26, 32], 10, 20, 13, 16, 5, 10, 8, 5, 4, 2, 1]
</code>```

Initially the input has nested list at 0th index at the size of n.We need to group the other elements based on this condition

```<code>n - count of odd integers
</code>```

l=[[45, 20, 40, 26, 32], 10, 20, 13, 16, 5, 10, 8, 5, 4, 2, 1]

Initially the nested loop has 1 odd integer:
Therefore
n - count of odd integers = 5-1= 4
so i need to group next four elements.

```<code>>>[[45, 20, 40, 26, 32], [10, 20, 13, 16], 5, 10, 8, 5, 4, 2, 1]
</code>```

then the second nested loop has 1 odd integer:

Therefore
n - count of odd integers = 4-1= 3
so I need to group next three elements.

[[45, 20, 40, 26, 32], [10, 20, 13, 16], [5, 10, 8], 5, 4, 2, 1]

then the third nested loop has 1 odd integer:

Therefore
n - count of odd integers = 3-1= 2
so I need to group next 2 elements.

[[45, 20, 40, 26, 32], [10, 20, 13, 16], [5, 10, 8], [5, 4], 2, 1]

...like that I need to do

the final output to be

[[45, 20, 40, 26, 32], [10, 20, 13, 16], [5, 10, 8], [5, 4], [2], 1]

My code:

l1=[l[i:(i+n)] for i in range(0,len(l),n)]

my output:

```<code>[[45, 20, 40, 26, 32], [10, 20, 13, 16, 5], [10, 8, 5, 4, 2], [1]]
</code>```

What changes I need to do???

Body:
I need to group the list based  based on (N -count of previous list odd integer)

Example:

Input

n=5
l=[[45, 20, 40, 26, 32], 10, 20, 13, 16, 5, 10, 8, 5, 4, 2, 1]

Initially the input has nested list at 0th index at the size of n.We need to group the other elements based on this condition

n - count of odd integers

l=[[45, 20, 40, 26, 32], 10, 20, 13, 16, 5, 10, 8, 5, 4, 2, 1]

Initially the nested loop has 1 odd integer:
Therefore
n - count of odd integers = 5-1= 4
so i need to group next four elements.

>>[[45, 20, 40, 26, 32], [10, 20, 13, 16], 5, 10, 8, 5, 4, 2, 1]

then the second nested loop has 1 odd integer:

Therefore
n - count of odd integers = 4-1= 3
so I need to group next three elements.

[[45, 20, 40, 26, 32], [10, 20, 13, 16], [5, 10, 8], 5, 4, 2, 1]

then the third nested loop has 1 odd integer:

Therefore
n - count of odd integers = 3-1= 2
so I need to group next 2 elements.

[[45, 20, 40, 26, 32], [10, 20, 13, 16], [5, 10, 8], [5, 4], 2, 1]

...like that I need to do

the final output to be

[[45, 20, 40, 26, 32], [10, 20, 13, 16], [5, 10, 8], [5, 4], [2], 1]

My code:

l1=[l[i:(i+n)] for i in range(0,len(l),n)]

my output:

[[45, 20, 40, 26, 32], [10, 20, 13, 16, 5], [10, 8, 5, 4, 2], [1]]

What changes I need to do???

Body:
Code commented inline:

l=[[45, 20, 40, 26, 32], 10, 20, 13, 16, 5, 10, 8, 5, 4, 2, 1]
n = 5
a = l[0]
b = l[1:]
result = [a]
while len(b) > 0:
  # find the n-count of odd
  k = n-sum([1 for i in a if i %2 != 0])
  # get next sublist and the remainig elements
  a, b = b[:k], b[k:]
  result.append(a)
  n -= 1

print (result)

output:

[[45, 20, 40, 26, 32], [10, 20, 13, 16], [5, 10, 8], [5, 4], [2], [1]]


问:
what is the reason for this error and how to solve it

add method produce error saya his expression has a type of 'void' so its value can't be used.

```<code> Future addtocart({
    String? productID,
    BuildContext? context,
  }) async {
    List<String>? cartitems = ["gabbage"];
    await _firestore
        .collection("Users")
        .doc(_currentUser!.uid)
        .collection("Cart")
        .doc(_currentUser!.uid)
        .get()
        .then((doc) {
      if (doc.data()!["UserCart"].contains(productID)) {
        Fluttertoast.showToast(
          msg: 'Product is already in the cart',
          gravity: ToastGravity.CENTER,
        );
      } else {
        _firestore
            .collection("Users")
            .doc(_currentUser!.uid)
            .collection("Cart")
            .doc(_currentUser!.uid)
            .update({"UserCart": cartitems.add(productID!)});
      }
    });
  }
}
</code>```

答:
```<code>cartitems.add(productID!);
</code>```

It's not returning anything so how can you assign it to a map

Body:
add method produce error saya his expression has a type of 'void' so its value can't be used.

 Future addtocart({
    String? productID,
    BuildContext? context,
  }) async {
    List<String>? cartitems = ["gabbage"];
    await _firestore
        .collection("Users")
        .doc(_currentUser!.uid)
        .collection("Cart")
        .doc(_currentUser!.uid)
        .get()
        .then((doc) {
      if (doc.data()!["UserCart"].contains(productID)) {
        Fluttertoast.showToast(
          msg: 'Product is already in the cart',
          gravity: ToastGravity.CENTER,
        );
      } else {
        _firestore
            .collection("Users")
            .doc(_currentUser!.uid)
            .collection("Cart")
            .doc(_currentUser!.uid)
            .update({"UserCart": cartitems.add(productID!)});
      }
    });
  }
}

Body:
cartitems.add(productID!);

It's not returning anything so how can you assign it to a map


问:
Is there any way to insert a 3D image of (STL, OBJ, FBX, and DAE formats) in pyqtgraph 3D plot in python?
I am using PyQT5 for building GUI in python. I need to show a 3D object in a 3D pyqtgraph plot. Is there any way to do so? Please provide if there is any documentation available.

Regards,
Kola

答:
You need to address this issue per file format. At least for STL, there is nice library called numpy-stl which can read the STL file and You can export mesh from it. Then You can use GlMeshItem to display it in PyQtGraph.

Here is example code, that You can use to display STL file:

```<code>import sys

import numpy as np
from PyQt5.QtWidgets import QApplication
from pyqtgraph.opengl import GLViewWidget, MeshData, GLMeshItem
from stl import mesh

if __name__ == "__main__":
    app = QApplication(sys.argv)
    view = GLViewWidget()
    # https://ozeki.hu/attachments/116/Eiffel_tower_sample.STL
    stl_mesh = mesh.Mesh.from_file('Eiffel_tower_sample.STL')

    points = stl_mesh.points.reshape(-1, 3)
    faces = np.arange(points.shape[0]).reshape(-1, 3)

    mesh_data = MeshData(vertexes=points, faces=faces)
    mesh = GLMeshItem(meshdata=mesh_data, smooth=True, drawFaces=False, drawEdges=True, edgeColor=(0, 1, 0, 1))
    view.addItem(mesh)

    view.show()
    app.exec()
</code>```

Body:
You need to address this issue per file format. At least for STL, there is nice library called numpy-stl which can read the STL file and You can export mesh from it. Then You can use GlMeshItem to display it in PyQtGraph.

Here is example code, that You can use to display STL file:

import sys

import numpy as np
from PyQt5.QtWidgets import QApplication
from pyqtgraph.opengl import GLViewWidget, MeshData, GLMeshItem
from stl import mesh

if __name__ == "__main__":
    app = QApplication(sys.argv)
    view = GLViewWidget()
    # https://ozeki.hu/attachments/116/Eiffel_tower_sample.STL
    stl_mesh = mesh.Mesh.from_file('Eiffel_tower_sample.STL')

    points = stl_mesh.points.reshape(-1, 3)
    faces = np.arange(points.shape[0]).reshape(-1, 3)

    mesh_data = MeshData(vertexes=points, faces=faces)
    mesh = GLMeshItem(meshdata=mesh_data, smooth=True, drawFaces=False, drawEdges=True, edgeColor=(0, 1, 0, 1))
    view.addItem(mesh)

    view.show()
    app.exec()


问:
Set the height of Details section Crystal Reports
The no of items in my invoice never gets more than 10. When its only one item in invoice(one row in details section) the report footer shows very up.

I want that I should fix 10 rows for the details section, when there are less rows, the remaining rows to make it 10 should be showed as blank lines.

I need the footer to appear at the same place all the time, irrespective of how many items are there in the invoice(never gets more than 10).

Please suggest solution.

答:
Just use Sub Report and Fix the height of the sub report
then you will be able to display fix page. </p>


问:
Allow PRs to be merged even if the commit status fails
I want to set up a tool that updates my commit status of my PRs based on some result.

However, since I want to run this in dry-run mode, I want my PRs to be mergeable even if the status update fails.

Is this possible in GitHub?

答:
I believe this is the default setting in GitHub, as long as you don't enable any Branch Protection Rules on your repository:

If required status checks aren't enabled, collaborators can merge the branch at any time, regardless of whether it is up to date with the base branch. This increases the possibility of incompatible changes.

See the Protected Branches documentation here.


问:
Split up date range into chunks to join back into one table KDB+/Q
I have a table that is being joined like so

```<code>result: select from table where date within (sd;ed)
</code>```

where sd and ed span multiple months (like sd:2021.07.01 ed:2021.09.30). The table that I'm querying from has a break if you take more than a month, so to get the result I need, I have to do something like the following:

```<code>result: uj(uj(select from table where date within (2021.07.01;2021.07.30);select from table where date within (2021.08.01;2021.08.31));select from table where date within (2021.09.01;2021.09.30))
</code>```

How can I make this dynamic for any sd and ed? That is, how can I break up time range into first days of months, last days of months, and join them all into one table cleanly? My initial idea was to divide the days in the range x amount of time, to be input by a user, then add the number of days that results to the sd to get frames, but that got messy.

Body:
I have a table that is being joined like so

result: select from table where date within (sd;ed)

where sd and ed span multiple months (like sd:2021.07.01 ed:2021.09.30). The table that I'm querying from has a break if you take more than a month, so to get the result I need, I have to do something like the following:

result: uj(uj(select from table where date within (2021.07.01;2021.07.30);select from table where date within (2021.08.01;2021.08.31));select from table where date within (2021.09.01;2021.09.30))

How can I make this dynamic for any sd and ed? That is, how can I break up time range into first days of months, last days of months, and join them all into one table cleanly? My initial idea was to divide the days in the range x amount of time, to be input by a user, then add the number of days that results to the sd to get frames, but that got messy.

Body:
One option for converting your start and end dates into an iterable list of dates might be:

f:{0N 2#(x,raze -1 0+/:`date$mx+1+til(`month$y)-mx:`month$x),y}

Where x is start date and y is end date.

f[2021.07.14;2022.02.09]
2021.07.14 2021.07.31
2021.08.01 2021.08.31
2021.09.01 2021.09.30
2021.10.01 2021.10.31
2021.11.01 2021.11.30
2021.12.01 2021.12.31
2022.01.01 2022.01.31
2022.02.01 2022.02.09

Then you could run:

{select from t where date within x} each f[sd;ed]

And join the results using raze or (uj/)


问:
How best to loop over a batch of Results with a C# DbDataReader
I'm executing a number of SQL query's as a batch and then getting all of the result sets back in a batch.  The way that my code is currently put together, the first result set gets skipped.  Now that I know this, I could simply throw in another statement outside of my loop that grabs the first result, however I'm wondering if there is a more elegant solution to this problem.

Here is some sudo code of whats going on:

```<code>DbDataReader reader= /*some stuff that returns a batch of results...*/;

while (reader.NextResult())
{
   while (reader.Read())
   {
       if (!reader.IsDBNull(0))
       {
           //do things with the data....
       }
   }
}
</code>```

Now i would have expected that NextResult() advances you to the first result the first time you call it, which is what Read() seems to do.  However what it actually seems to do is bring you to the second result on the first call.  Am I misunderstanding how you're expected to use this method, or are you really expected to do some like the following:

```<code>DbDataReader reader= /*some stuff that returns a batch of results...*/;

//this deals with the row in the the very first result
while (reader.Read())
{
    if (!reader.IsDBNull(0))
    {
        //do things with the data....
    }
}

//this deals with the rest of the rows...
while (reader.NextResult())
{
   while (reader.Read())
   {
       if (!reader.IsDBNull(0))
       {
           //do exact same things with the data....
           //is this not pretty klugey?
       }
   }
}
</code>```

This strikes me as rotten programming style, but I don't see a way around it.  Does anyone know of a more elegant solution to this?

答:
I usually do this:

```<code>if(reader.HasRows)
    {
      while(reader.Read())
       {

          // Do Stuff
       }
    }
</code>```

Hope it helps

OwnerDisplayName: sweeney

ContentLicense: CC BY-SA 2.5

Body:
I'm executing a number of SQL query's as a batch and then getting all of the result sets back in a batch.  The way that my code is currently put together, the first result set gets skipped.  Now that I know this, I could simply throw in another statement outside of my loop that grabs the first result, however I'm wondering if there is a more elegant solution to this problem.

Here is some sudo code of whats going on:

DbDataReader reader= /*some stuff that returns a batch of results...*/;

while (reader.NextResult())
{
   while (reader.Read())
   {
       if (!reader.IsDBNull(0))
       {
           //do things with the data....
       }
   }
}

Now i would have expected that NextResult() advances you to the first result the first time you call it, which is what Read() seems to do.  However what it actually seems to do is bring you to the second result on the first call.  Am I misunderstanding how you're expected to use this method, or are you really expected to do some like the following:

DbDataReader reader= /*some stuff that returns a batch of results...*/;

//this deals with the row in the the very first result
while (reader.Read())
{
    if (!reader.IsDBNull(0))
    {
        //do things with the data....
    }
}

//this deals with the rest of the rows...
while (reader.NextResult())
{
   while (reader.Read())
   {
       if (!reader.IsDBNull(0))
       {
           //do exact same things with the data....
           //is this not pretty klugey?
       }
   }
}

This strikes me as rotten programming style, but I don't see a way around it.  Does anyone know of a more elegant solution to this?

Body:
I usually do this:

if(reader.HasRows)
    {
      while(reader.Read())
       {

          // Do Stuff
       }
    }

Hope it helps

OwnerDisplayName: MRFerocius


问:
Kotlin Multiplatform Mobile library structure
Some time ago I've created a KMM library from IntelliJ IDEA, using the "Mobile Application" project template. The structure was (with one root build.gradle.kts file):

```<code>libraryProject
- build.gradle.kts
- src
  - androidMain
  - commonMain
  - iosMain
</code>```

Now, that template is missing from the list. There is just a "Library", which creates a jvm/js/common/native structure.

In Android Studio, the KMM plugin generates (for KMM library template):

```<code>libraryProject
- build.gradle.kts
- settings.gradle.kts
- libraryShared (this can be renamed)
  - build.gradle.kts
  - src
    - androidMain
    - commonMain
    - iosMain
</code>```

This is just a KMM application without the actual iOS and Android platform modules.
And, it comes with two build.gradle.kts files (root and shared).

I'm just curious if I missed anything or do I have to configure it manually, somehow.

All IDEs and plugins are up-to-date.

答:
When creating new project in Android Studio, one should be able to choose between two KMM projects(KMM Plugin is required to be installed):

KMM Library which contains only the shared module defined, and is intended to be used when one wants to add this library into existing iOS and Android apps.

KMM Application which creates a complete project with shared multiplatforn library, iOS app with ready integration, and the Android app.

Probably, in this case these two were confused. If you had only one option in the Wizard, please let me know which IDE and Plugin versions were used.

Note: Mobile library and Mobile Application were removed from IDEA by design,please see https://youtrack.jetbrains.com/issue/KTIJ-19232.

Body:
Some time ago I've created a KMM library from IntelliJ IDEA, using the "Mobile Application" project template. The structure was (with one root build.gradle.kts file):

libraryProject
- build.gradle.kts
- src
  - androidMain
  - commonMain
  - iosMain

Now, that template is missing from the list. There is just a "Library", which creates a jvm/js/common/native structure.

In Android Studio, the KMM plugin generates (for KMM library template):

libraryProject
- build.gradle.kts
- settings.gradle.kts
- libraryShared (this can be renamed)
  - build.gradle.kts
  - src
    - androidMain
    - commonMain
    - iosMain

This is just a KMM application without the actual iOS and Android platform modules.
And, it comes with two build.gradle.kts files (root and shared).

I'm just curious if I missed anything or do I have to configure it manually, somehow.

All IDEs and plugins are up-to-date.


问:
JSF / JSP stop working after adding JAX-RS
My web app stop working after I added the following JAX-RS class to the project.

```<code>@Path("/ws")
public class ResourceLocator {

private static final String ACCOUNT_RESOURCE  = "account";

public ResourceLocator() {
}

@Path("/{resource}")
public Object findWebServiceResource(@PathParam("resource") String resource) {

    Object resourceObj = null;
    try {
        resourceObj = getResourceObject(resource);
    }
    catch (Exception ex) {
        Log.category.error("Exception occur when attempting to find Web Service Resource", ex);
        resourceObj = new ResourceLocatorException(ex);
    }

    return resourceObj;
}
. . .
</code>```

The new web-services I added works fine.  But it causes the web site to stop working.  When I access the site, I see this error in the console.

```<code>WARNING: javax.ws.rs.WebApplicationException
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:162)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:91)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:240)
at org.apache.openejb.server.cxf.rs.CxfRsHttpListener.doInvoke(CxfRsHttpListener.java:227)
at org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:94)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241
. . . .
</code>```

The error seems to tell me that the JAX-RS servlet is intercepting request that is supposed to be handled by the MyFaces and JSP servlets.  I think I need to add some servlet mappings in web.xml to correct this, but I'm not sure what to add.  Below is the relevant portion of my web.xml:

```<code><servlet>
    <description>
    </description>
    <display-name>MyFacesServlet</display-name>
    <servlet-name>MyFacesServlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

    <servlet-mapping>
    <servlet-name>MyFacesServlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</code>```

I tried adding below, but it causes both the web-site and the ws to stop working:

```<code><servlet>
    <servlet-name>restServlet</servlet-name>
    <servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
    <init-param>
      <param-name>jaxrs.serviceClasses</param-name>
        <param-value>com.arch.myaccount.ws.ResourceLocator</param-value>
    </init-param>
</servlet>
<servlet-mapping>
   <servlet-name>restServlet</servlet-name>
   <url-pattern>/ws/*</url-pattern>
</servlet-mapping>
</code>```

答:
It works after I removed @Path("/ws") from the ResourceLocator class and add the following to web.xml

```<code><servlet>
    <servlet-name>restServlet</servlet-name>
    <servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
    <init-param>
      <param-name>jaxrs.serviceClasses</param-name>
        <param-value>com.arch.myaccount.ws.ResourceLocator</param-value>
    </init-param>
</servlet>

    <servlet-mapping>
   <servlet-name>restServlet</servlet-name>
   <url-pattern>/ws/*</url-pattern>
</servlet-mapping>
</code>```

My ResourceLocator class now looks like below:

```<code>public class ResourceLocator {

private static final String ACCOUNT_RESOURCE  = "account";

public ResourceLocator() {
}

@Path("/{resource}")
public Object findWebServiceResource(@PathParam("resource") String resource) {

    Object resourceObj = null;
    try {
        resourceObj = getResourceObject(resource);
    }
    catch (Exception ex) {
        Log.category.error("Exception occur when attempting to find Web Service Resource", ex);
        resourceObj = new ResourceLocatorException(ex);
    }

    return resourceObj;
}
</code>```

Body:
My web app stop working after I added the following JAX-RS class to the project.

@Path("/ws")
public class ResourceLocator {

private static final String ACCOUNT_RESOURCE  = "account";

public ResourceLocator() {
}

@Path("/{resource}")
public Object findWebServiceResource(@PathParam("resource") String resource) {

    Object resourceObj = null;
    try {
        resourceObj = getResourceObject(resource);
    }
    catch (Exception ex) {
        Log.category.error("Exception occur when attempting to find Web Service Resource", ex);
        resourceObj = new ResourceLocatorException(ex);
    }

    return resourceObj;
}
. . .

The new web-services I added works fine.  But it causes the web site to stop working.  When I access the site, I see this error in the console.

WARNING: javax.ws.rs.WebApplicationException
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:162)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:91)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:240)
at org.apache.openejb.server.cxf.rs.CxfRsHttpListener.doInvoke(CxfRsHttpListener.java:227)
at org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:94)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241
. . . .

The error seems to tell me that the JAX-RS servlet is intercepting request that is supposed to be handled by the MyFaces and JSP servlets.  I think I need to add some servlet mappings in web.xml to correct this, but I'm not sure what to add.  Below is the relevant portion of my web.xml:

<servlet>
    <description>
    </description>
    <display-name>MyFacesServlet</display-name>
    <servlet-name>MyFacesServlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

    <servlet-mapping>
    <servlet-name>MyFacesServlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>

I tried adding below, but it causes both the web-site and the ws to stop working:

<servlet>
    <servlet-name>restServlet</servlet-name>
    <servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
    <init-param>
      <param-name>jaxrs.serviceClasses</param-name>
        <param-value>com.arch.myaccount.ws.ResourceLocator</param-value>
    </init-param>
</servlet>
<servlet-mapping>
   <servlet-name>restServlet</servlet-name>
   <url-pattern>/ws/*</url-pattern>
</servlet-mapping>

Body:
It works after I removed @Path("/ws") from the ResourceLocator class and add the following to web.xml

<servlet>
    <servlet-name>restServlet</servlet-name>
    <servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
    <init-param>
      <param-name>jaxrs.serviceClasses</param-name>
        <param-value>com.arch.myaccount.ws.ResourceLocator</param-value>
    </init-param>
</servlet>

    <servlet-mapping>
   <servlet-name>restServlet</servlet-name>
   <url-pattern>/ws/*</url-pattern>
</servlet-mapping>

My ResourceLocator class now looks like below:

public class ResourceLocator {

private static final String ACCOUNT_RESOURCE  = "account";

public ResourceLocator() {
}

@Path("/{resource}")
public Object findWebServiceResource(@PathParam("resource") String resource) {

    Object resourceObj = null;
    try {
        resourceObj = getResourceObject(resource);
    }
    catch (Exception ex) {
        Log.category.error("Exception occur when attempting to find Web Service Resource", ex);
        resourceObj = new ResourceLocatorException(ex);
    }

    return resourceObj;
}


问:
How to use apache wicket extensions?
I want to use the AjaxFallbackDefaultDataTable in wicket to view my data but these imports are showing error in eclipse :

```<code>import org.apache.wicket.extensions.ajax.markup.html.repeater.data.table.AjaxFallbackDefaultDataTable;   import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;
</code>```

I guess I should be downloading an extensions jar file from somewhere but I don't know where at, and the Apache wicket website is vague regarding this point.

I am using eclipse with maven plugin and wicket 1.5RC1

答:
I simply added the following lines to the pom.xml file to add the extensions dependency .</p>

```<code><dependency>
    <groupId>org.apache.wicket</groupId>
    <artifactId>wicket-extensions</artifactId>
    <version>1.5-RC1</version>
</dependency>
</code>```

Title: How to use apache wicket extensions?

Body:
I want to use the AjaxFallbackDefaultDataTable in wicket to view my data but these imports are showing error in eclipse :

import org.apache.wicket.extensions.ajax.markup.html.repeater.data.table.AjaxFallbackDefaultDataTable;   import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;

I guess I should be downloading an extensions jar file from somewhere but I don't know where at, and the Apache wicket website is vague regarding this point.

I am using eclipse with maven plugin and wicket 1.5RC1

Body:
I simply added the following lines to the pom.xml file to add the extensions dependency .

<dependency>
    <groupId>org.apache.wicket</groupId>
    <artifactId>wicket-extensions</artifactId>
    <version>1.5-RC1</version>
</dependency>


问:
React Native Navigation drawer partially open
I have a React Native app that I had to upgrade to try and fix an Android issue. I'm now on .67.2. After doing nothing to change the code, my React Navigation Drawer is now stuck partially open on the screen. I don't see any relevant bugs, and I'm not sure how to fix it. Is there any resource to check why this is?

Picture (for context)

答:
Try to change drawer type  to back  instead to be front

<Drawer.Navigator useLegacyImplementation screenOptions={{ drawerType: "back", }} >

```


问:
Multiclass Classification
I have a Multi class classification problem( anonymised features) with 3 classes.Class 1 is being differentiated from other classes but I have a problem separating Class 2 from Class 0.(Most of the Class 2 is being predicted as Class 0).

Since there is a imbalance between these two classes (3:1) .I tried giving weights to Class 2 but then the model just classifies some of the Class 2 correctly but it also predicts Class 0 as Class 2 now, giving me the same accuracy when where was no weights given.

So any ideas on how to separate these two classes? I have tried NN, oneVSrest, also tried a bit of stacking with no significant gain.

答: You can explore the binary logistic regression approach considering one vs rest, u will be getting 3 models. consider max of 3 probabilities and check accuracy. sometimes this approach works well.</p>

Title: Multiclass Classification


问:
Why do we usually use || over |? What is the difference?
I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.

I mean, look at the following:

```<code>if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass
</code>```

```<code>if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass
</code>```

Can we use | instead of ||? Same thing with & and &&.

答:
The only time you would use | or & instead of || or && is when you have very simple boolean expressions and the cost of short cutting (i.e. a branch) is greater than the time you save by not evaluating the later expressions.

However, this is a micro-optimisation which rarely matters except in the most low level code.

Body:
I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.

I mean, look at the following:

if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass

if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass

Can we use | instead of ||? Same thing with & and &&.


问:
How to make flex box with limit 2 elements per row?
I need to make a table which will contain up to 4 divs.
But the divs in that table always should use maximum of avaliable space.
And one one row should contain not more then 2 divs
For instance if table contains 2 divs it should look like this

If table has 3 divs then like this:

And if contains 4 then it should look like that

To achieve it i wrote this code:

```<code><div
  style={{
    height: '58vh', border: '1px solid #d9d9d9',
    borderRadius: '0px 0px 2px 2px',
    display: 'flex',
    flexDirection: 'row',
    flexWrap: 'wrap',
  }}
 >
   <div style={{background:'red', flex: 'auto', margin: '5px'}}
   <div style={{background:'green', flex: 'auto', margin: '5px'}}
   <div style={{background:'blue', flex: 'auto', margin: '5px'}}
   <div style={{background:'pink', flex: 'auto', margin: '5px'}}

 </div>
</code>```

But i missing something here.
For 1 div and for 2 divs it works as planned.
But for more..
This is my result for 3 divs

And for 4 divs

Can anyone advice me please what should i change in this code?

PS. Please don't judge my unevenly drawn squeres :)

答:
What you mean about use Grid for this?

example:

```<code>  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
</code>```

here it's guide for Grid: https://css-tricks.com/snippets/css/complete-guide-grid/

Body:
I need to make a table which will contain up to 4 divs.
But the divs in that table always should use maximum of avaliable space.
And one one row should contain not more then 2 divs
For instance if table contains 2 divs it should look like this

If table has 3 divs then like this:

And if contains 4 then it should look like that

To achieve it i wrote this code:

   <div style={{background:'red', flex: 'auto', margin: '5px'}}
   <div style={{background:'green', flex: 'auto', margin: '5px'}}
   <div style={{background:'blue', flex: 'auto', margin: '5px'}}
   <div style={{background:'pink', flex: 'auto', margin: '5px'}}

But i missing something here.
For 1 div and for 2 divs it works as planned.
But for more..
This is my result for 3 divs

And for 4 divs

Can anyone advice me please what should i change in this code?

PS. Please don't judge my unevenly drawn squeres :)

Body:
What you mean about use Grid for this?

example:

  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;

here it's guide for Grid: https://css-tricks.com/snippets/css/complete-guide-grid/


问:
virtualenv activate does not work
I am trying to create a virtual environment to test an api.

I can create the environment just fine using virtualenv test, then I can cd into it.  When I try to run activate, I get this error:

```<code>PS C:\Users\Bright Bridge\Desktop\autocomplete_demo\Scripts> activate
activate : The term 'activate' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if
a path was included, verify that the path is correct and try again.
At line:1 char:1
+ activate
+ ~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (activate:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Suggestion [3,General]: The command activate was not found, but does exist in the current location. Windows PowerShell does not load commands from the current
 location by default. If you trust this command, instead type: ".\activate". See "get-help about_Command_Precedence" for more details.
</code>```

I recently updated windows, and it replaced the cmd with Windows Powershell.  My virtualenv worked fine with the cmd, so I suspect it may have to do with the way the Powershell does things.

How can I activate the virtualenv?

答:
Execute .\activate instead of activate

That worked for me.

Title: virtualenv activate does not work

Body:
I am trying to create a virtual environment to test an api.

I can create the environment just fine using virtualenv test, then I can cd into it.  When I try to run activate, I get this error:

PS C:\Users\Bright Bridge\Desktop\autocomplete_demo\Scripts> activate
activate : The term 'activate' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if
a path was included, verify that the path is correct and try again.
At line:1 char:1
+ activate
+ ~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (activate:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Suggestion [3,General]: The command activate was not found, but does exist in the current location. Windows PowerShell does not load commands from the current
 location by default. If you trust this command, instead type: ".\activate". See "get-help about_Command_Precedence" for more details.

I recently updated windows, and it replaced the cmd with Windows Powershell.  My virtualenv worked fine with the cmd, so I suspect it may have to do with the way the Powershell does things.

How can I activate the virtualenv?


问:
Accessing fields from a text file
I'm new to python. I need to access fields from a text file which is basically a tweet stream in json format. The text file looks like this:

```<code>{u'favorited': False, u'entities': {u'user_mentions': [{u'indices': [76, 84], u'id': 10228272, u'id_str': u'10228272', u'name': u'YouTube', u'screen_name': u'YouTube'}], u'hashtags': [], u'urls': [{u'indices': [52, 71], u'url': u'http://t.co/iQYW4d3', u'expanded_url': u'http://www.youtube.com/watch?v=-HGfFyqJMrk', u'display_url': u'youtube.com/watch?v=-HGfFy\u2026'}]}, u'contributors': None, u'truncated': False, u'text': u'Long Live Egypt.....A MUST watch..... Freeeeedom... http://t.co/iQYW4d3 via @youtube', u'created_at': u'Sun Feb 06 17:18:21 +0000 2011', u'retweeted': False, u'in_reply_to_status_id_str': None, u'coordinates': None, u'id': 34299873733902336L, u'source': u'<a href="http://twitter.com/tweetbutton" rel="nofollow">Tweet Button</a>', u'in_reply_to_status_id': None, u'id_str': u'34299873733902336', u'in_reply_to_screen_name': None, u'user': {u'follow_request_sent': None, u'profile_use_background_image': True, u'id': 191652149, u'verified': False, u'profile_sidebar_fill_color': u'c9c9c9', u'profile_text_color': u'1c1f23', u'followers_count': 43, u'protected': False, u'location': u'Damascus - Syria', u'profile_background_color': u'07090b', u'listed_count': 3, u'utc_offset': 7200, u'statuses_count': 113, u'description': u'In heaven, all the interesting people are missing ', u'friends_count': 149, u'profile_link_color': u'c34242', u'profile_image_url': u'http://a3.twimg.com/profile_images/1125299662/Untitled_normal.jpg', u'notifications': None, u'show_all_inline_media': False, u'geo_enabled': False, u'id_str': u'191652149', u'profile_background_image_url': u'http://a0.twimg.com/profile_background_images/150071579/x07823fa2328f1ff92c4d900c44bc34d.jpg', u'screen_name': u'NourZoukar', u'lang': u'en', u'following': None, u'profile_background_tile': True, u'favourites_count': 0, u'name': u'M.Nour  Zoukar', u'url': u'http://www.kawngroup.com', u'created_at': u'Fri Sep 17 00:19:26 +0000 2010', u'contributors_enabled': False, u'time_zone': u'Jerusalem', u'profile_sidebar_border_color': u'bfbfbf', u'is_translator': False}, u'place': None, u'retweet_count': 0, u'geo': None, u'in_reply_to_user_id_str': None, u'in_reply_to_user_id': None}
</code>```

I want my output to display the screen name that is 'NourZoukar' in this case.

答:
That looks more like a Python string than json. If you already have that in a string, say s you can convert it into a data native data structure with

```<code>import ast
d = ast.literal_eval(s)
</code>```

To read the string from stream.txt, use something like

```<code>import ast, pprint

with open('stream.txt') as fp:
    stream = fp.read()
    data = ast.literal_eval(stream)

pprint.pprint(data)
</code>```

Title: Accessing fields from a text file

Body:
I'm new to python. I need to access fields from a text file which is basically a tweet stream in json format. The text file looks like this:

{u'favorited': False, u'entities': {u'user_mentions': [{u'indices': [76, 84], u'id': 10228272, u'id_str': u'10228272', u'name': u'YouTube', u'screen_name': u'YouTube'}], u'hashtags': [], u'urls': [{u'indices': [52, 71], u'url': u'http://t.co/iQYW4d3', u'expanded_url': u'http://www.youtube.com/watch?v=-HGfFyqJMrk', u'display_url': u'youtube.com/watch?v=-HGfFy\u2026'}]}, u'contributors': None, u'truncated': False, u'text': u'Long Live Egypt.....A MUST watch..... Freeeeedom... http://t.co/iQYW4d3 via @youtube', u'created_at': u'Sun Feb 06 17:18:21 +0000 2011', u'retweeted': False, u'in_reply_to_status_id_str': None, u'coordinates': None, u'id': 34299873733902336L, u'source': u'Tweet Button', u'in_reply_to_status_id': None, u'id_str': u'34299873733902336', u'in_reply_to_screen_name': None, u'user': {u'follow_request_sent': None, u'profile_use_background_image': True, u'id': 191652149, u'verified': False, u'profile_sidebar_fill_color': u'c9c9c9', u'profile_text_color': u'1c1f23', u'followers_count': 43, u'protected': False, u'location': u'Damascus - Syria', u'profile_background_color': u'07090b', u'listed_count': 3, u'utc_offset': 7200, u'statuses_count': 113, u'description': u'In heaven, all the interesting people are missing ', u'friends_count': 149, u'profile_link_color': u'c34242', u'profile_image_url': u'http://a3.twimg.com/profile_images/1125299662/Untitled_normal.jpg', u'notifications': None, u'show_all_inline_media': False, u'geo_enabled': False, u'id_str': u'191652149', u'profile_background_image_url': u'http://a0.twimg.com/profile_background_images/150071579/x07823fa2328f1ff92c4d900c44bc34d.jpg', u'screen_name': u'NourZoukar', u'lang': u'en', u'following': None, u'profile_background_tile': True, u'favourites_count': 0, u'name': u'M.Nour  Zoukar', u'url': u'http://www.kawngroup.com', u'created_at': u'Fri Sep 17 00:19:26 +0000 2010', u'contributors_enabled': False, u'time_zone': u'Jerusalem', u'profile_sidebar_border_color': u'bfbfbf', u'is_translator': False}, u'place': None, u'retweet_count': 0, u'geo': None, u'in_reply_to_user_id_str': None, u'in_reply_to_user_id': None}

I want my output to display the screen name that is 'NourZoukar' in this case.

Body:
That looks more like a Python string than json. If you already have that in a string, say s you can convert it into a data native data structure with

import ast
d = ast.literal_eval(s)

To read the string from stream.txt, use something like

import ast, pprint

with open('stream.txt') as fp:
    stream = fp.read()
    data = ast.literal_eval(stream)

pprint.pprint(data)


问:
apidata.map is not a function : ReactJS
Can someone please tell me why i am getting this error . I tried fixing it all day, but I could not fix it. So at last i had to come at stackoverflow

This is my code : App.js

```<code>import "./App.css";

function App() {
  const [inputvalue, setInputvalue] = useState(" ");
  const [apidata, setApidata] = useState([]);
  const [finalpoint, setFinalpoint] = useState("");
  useEffect(() => {
    fetch(
      `https://weatherapi-com.p.rapidapi.com/forecast.json?q=+${inputvalue}&days=3`,
      {
        method: "GET",
        headers: {
          "x-rapidapi-host": "weatherapi-com.p.rapidapi.com",
          "x-rapidapi-key":
            "7f89bf16ebmsh9dff0f23f963d34p190691jsn264543e18108",
        },
      }
    )
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        setApidata(data);
      })
      .catch((err) => {
        console.error(err);
      });
  }, [finalpoint]);

  const onchangeinput = (e) => {
    setInputvalue(e.target.value);
  };

  const onsubmithandler = (e) => {
    e.preventDefault();
    setFinalpoint(inputvalue);
  };

  return (
    <div className="App">
      <div className="main">
        <h2>Welcome To weather App </h2>
      </div>

      <form onSubmit={onsubmithandler}>
        <input type="text" value={inputvalue} onChange={onchangeinput} />
        <button type="submit">Search</button>
      </form>
      {apidata.map((data, i) => {
        return <h1>{data.current.feelslike_c}</h1>;
      })}
    </div>
    //Map
  );
}

export default App;
</code>```

This is the error I am getting :
enter image description here

答:
Check if you are receiving undefined here:

```<code>.then((data) => {
   setApidata(data);
 })
</code>```

and overriding the state with undefined.

Title: apidata.map is not a function : ReactJS

Body:
Can someone please tell me why i am getting this error . I tried fixing it all day, but I could not fix it. So at last i had to come at stackoverflow

This is my code : App.js

import "./App.css";

function App() {
  const [inputvalue, setInputvalue] = useState(" ");
  const [apidata, setApidata] = useState([]);
  const [finalpoint, setFinalpoint] = useState("");
  useEffect(() => {
    fetch(
      `https://weatherapi-com.p.rapidapi.com/forecast.json?q=+${inputvalue}&days=3`,
      {
        method: "GET",
        headers: {
          "x-rapidapi-host": "weatherapi-com.p.rapidapi.com",
          "x-rapidapi-key":
            "7f89bf16ebmsh9dff0f23f963d34p190691jsn264543e18108",
        },
      }
    )
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        setApidata(data);
      })
      .catch((err) => {
        console.error(err);
      });
  }, [finalpoint]);

  const onchangeinput = (e) => {
    setInputvalue(e.target.value);
  };

  const onsubmithandler = (e) => {
    e.preventDefault();
    setFinalpoint(inputvalue);
  };

  return (

Welcome To weather App

      <form onSubmit={onsubmithandler}>
        <input type="text" value={inputvalue} onChange={onchangeinput} />
        <button type="submit">Search</button>
      </form>
      {apidata.map((data, i) => {
        return
{data.current.feelslike_c}
;
      })}

    //Map
  );
}

export default App;

This is the error I am getting :
enter image description here

Body:
Check if you are receiving undefined here:

.then((data) => {
   setApidata(data);
 })

and overriding the state with undefined.


问:
Direct inbound internet traffic to Function App through customer firewall that connects to vnet over expressroute
Want to integrate Function App with inbound github webhooks. This inbound internet traffic normally would reach the Function App directly via a microsoft public url/ip. But company wants all inbound internet traffic to go through its firewall and then pass on to azure over expressroute.

If function app is on premium plan, it can be vnet integrated and now has a private ip. But for access to it from the Internet, I don't think I can simply access the app via a NAT using a new public ip address as I think Function App expects the url to use a specific host and domain name. Ideas?

Feels like the wrapper to the service is more complicated than the service itself.

答:
VNet Integration doesn't grant inbound private access to the app from the Virtual Network but gives app access to resources in the same VNet.

If you need to access resources through an ExpressRoute connection, regional vNet Integration feature or an App service Environment is the only way, which runs in your Virtual Network.

But company wants all inbound internet traffic to go through its firewall and then pass on to azure over expressroute.

VNet Integration affects only outbound traffic from your app whereas inbound rules don't apply to your app in an NSG.

To control inbound traffic to your app, use the Access Restrictions feature.

Refer this Microsoft Documentation for more information.


问:
Keyword arguments in python class inheritance
Hello I am recently looking about the metaclass in Python.

I learned about we can attach a metaclass to a class in this way:

class Metaclass(type):
    ...

class MyClass(metaclass=Metaclass):
    ...
```
<ul>
<li>The first question</li>
</ul>
<p>I wonder what's the principle of the keyword argument (<code>metaclass=...</code>) in the above example. There seems no description for that in the doc</p>
<p>I know that there is keyword argument for a function, but I've never seen the form occurred in class inheritance.</p>
<ul>
<li>The second question</li>
</ul>
<p>We know that we can create a class using <code>type()</code> function in this way</p>
<pre class="lang-py prettyprint-override"><code>cls = type(class_name, (base_class,), {func_name: func_ref})
</code>```

Considering the metaclass=... form, how can I pass metaclass when creating class using type() instead of class keyword?

Thanks stackoverflowers!

答:
Yes I've looked this, but it doesn't provide something about principle of keyword argument in class inheritance, I am still confused

metaclass=... is not about inheritance.

Everything in Python is an object. So when you define a class MyClass, not only is MyClass() an object but the class MyClass itself is an object.

MyClass() is an instance of MyClass, simple enough.

But if MyClass is also an object, what class is it an instance of?

If you do nothing, the object (!) MyClass is an instance of the class type.

If you do class MyClass(metaclass=Metaclass) then MyClass is an instance of Metaclass.

Consider

```<code>class Metaclass(type):
    pass

class MyClass1:
    pass

class MyClass2(metaclass=Metaclass):
    pass
</code>```

Both MyClass1 and MyClass2 inherit from object and only object.

```<code>>>> MyClass1.__mro__
(<class '__main__.MyClass1'>, <class 'object'>)
>>> MyClass2.__mro__
(<class '__main__.MyClass2'>, <class 'object'>)
</code>```

But their types differ:

```<code>>>> type(MyClass1)
<class 'type'>
>>> type(MyClass2)
<class '__main__.Metaclass'>
</code>```

When would you need this? Usually, you don't. And when you do, you do the kind of metaprogramming where you already know the why and how.

Body:
Hello I am recently looking about the metaclass in Python.

I learned about we can attach a metaclass to a class in this way:

class Metaclass(type):
    ...

class MyClass(metaclass=Metaclass):
    ...

The first question

I wonder what's the principle of the keyword argument (metaclass=...) in the above example. There seems no description for that in the doc

I know that there is keyword argument for a function, but I've never seen the form occurred in class inheritance.

The second question

We know that we can create a class using type() function in this way

cls = type(class_name, (base_class,), {func_name: func_ref})

Considering the metaclass=... form, how can I pass metaclass when creating class using type() instead of class keyword?

Thanks stackoverflowers!

Body:
Yes I've looked this, but it doesn't provide something about principle of keyword argument in class inheritance, I am still confused

metaclass=... is not about inheritance.

Everything in Python is an object. So when you define a class MyClass, not only is MyClass() an object but the class MyClass itself is an object.

MyClass() is an instance of MyClass, simple enough.

But if MyClass is also an object, what class is it an instance of?

If you do nothing, the object (!) MyClass is an instance of the class type.

If you do class MyClass(metaclass=Metaclass) then MyClass is an instance of Metaclass.

Consider

class Metaclass(type):
    pass

class MyClass1:
    pass

class MyClass2(metaclass=Metaclass):
    pass

Both MyClass1 and MyClass2 inherit from object and only object.

>>> MyClass1.__mro__
(<class '__main__.MyClass1'>, <class 'object'>)
>>> MyClass2.__mro__
(<class '__main__.MyClass2'>, <class 'object'>)

But their types differ:

>>> type(MyClass1)
<class 'type'>
>>> type(MyClass2)
<class '__main__.Metaclass'>

When would you need this? Usually, you don't. And when you do, you do the kind of metaprogramming where you already know the why and how.


问:
PYTHON 3.6.0 & DJANGO 3.5.0 'module' object is not iterable when running django website to the server
So i'm gonna run my Django project with python manage.py runserver but suddenly there comes an error like these:

```<code>Exception in thread django-main-thread:
Traceback (most recent call last):
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\urls\resolvers.py", line 590, in url_patterns
    iter(patterns)
TypeError: 'module' object is not iterable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\management\base.py", line 395, in check
    include_deployment_checks=include_deployment_checks,
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks
    return checks.run_checks(**kwargs)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique
    all_namespaces = _load_all_namespaces(resolver)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces
    url_patterns = getattr(resolver, 'url_patterns', [])
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\urls\resolvers.py", line 597, in url_patterns
    raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'project_settings.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
</code>```

And there is my project.settings.urls

```<code>"""project_settings URL Configuration
"""
from django.contrib import admin
from django.urls import path, include

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('', include('ml_app.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

And here are my ml_app.urls

```<code>        """project_settings URL Configuration """
from django.contrib import admin
from django.urls import path, include
from . import views
from .views import about, index, predict_page,cuda_full

        app_name = 'ml_app' handler404 = views.handler404

        urlpatterns = [
            path('', index, name='home'),
            path('about/', about, name='about'),
            path('predict/', predict_page, name='predict'),
            path('cuda_full/',cuda_full,name='cuda_full'),
    ]
</code>```

Does someone know how to fix that error? It's pretty important for my final test =(

答:
You have some circular imports. It means you have probably used imports from A to B, and then from B to A. You have to check dependencies. Sometime if you use a funtion, that imports model, and later you imports same function to that model, it would import infinitely. Check it in your code. Btw. don't import views and then every View from that views in the same file. It might be confusing

```<code>from django.contrib import admin
from django.urls import path, include
from ml_app.views import about, index, predict_page,cuda_full, handler404
</code>```

Check this article to read more about issue.

Body:
So i'm gonna run my Django project with python manage.py runserver but suddenly there comes an error like these:

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\urls\resolvers.py", line 590, in url_patterns
    iter(patterns)
TypeError: 'module' object is not iterable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\management\base.py", line 395, in check
    include_deployment_checks=include_deployment_checks,
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks
    return checks.run_checks(**kwargs)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique
    all_namespaces = _load_all_namespaces(resolver)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces
    url_patterns = getattr(resolver, 'url_patterns', [])
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\urls\resolvers.py", line 597, in url_patterns
    raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'project_settings.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

And there is my project.settings.urls

"""project_settings URL Configuration
"""
from django.contrib import admin
from django.urls import path, include

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('', include('ml_app.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

And here are my ml_app.urls

        """project_settings URL Configuration """
from django.contrib import admin
from django.urls import path, include
from . import views
from .views import about, index, predict_page,cuda_full

        app_name = 'ml_app' handler404 = views.handler404

        urlpatterns = [
            path('', index, name='home'),
            path('about/', about, name='about'),
            path('predict/', predict_page, name='predict'),
            path('cuda_full/',cuda_full,name='cuda_full'),
    ]

Does someone know how to fix that error? It's pretty important for my final test =(

Body:
You have some circular imports. It means you have probably used imports from A to B, and then from B to A. You have to check dependencies. Sometime if you use a funtion, that imports model, and later you imports same function to that model, it would import infinitely. Check it in your code. Btw. don't import views and then every View from that views in the same file. It might be confusing

from django.contrib import admin
from django.urls import path, include
from ml_app.views import about, index, predict_page,cuda_full, handler404

Check this article to read more about issue.


问:
Chrome Extension I can't get the tab title correctly in my custom extension history
I'm developing a plugin for Chrome and it has History feature in the plugin.  For example, clicking the button creates a new tab and saves the URL address in the history.  So this function works fine.  But I want to get the document.title data of the tab that was opened in the past instead of the URL address.  I tried doing this with tabs[tabs.length-1].title but it didn't get the title of the opened tab.  Instead it got the title of the last tab that was already open.  I guess this is the problem because the tab is not open yet.  How can I solve this?  Can you help me please?

This is my create tab function (If the tab is already open, don't open it again.):

```<code>function openTab(tab_url) {
    var isTabActive = false;
    var tabId = 0;
    var tabTitle = "";
    totalHistoryContent++;
    chrome.tabs.query({}, function(tabs) {
        for(var i=0;i<tabs.length;i++) {
            if(tabs[i].url.toLowerCase().includes(tab_url.toLowerCase()) == true) {
                isTabActive = true;
                tabId = tabs[i].id;
                tabTitle = tabs[i].title; // WORKING NICE
                break;
            }
        }

        if(isTabActive == false) {
            chrome.tabs.create({ url:tab_url });
            tabTitle = tabs[tabs.length - 1].title; // NOT WORKING CORRECTLY
        } else{
            chrome.tabs.update(tabId, {selected: true});
            chrome.tabs.reload(tabId);
        }
        alert(tabTitle);
    });

    if(tab_url !== "chrome-extension://" + chrome.runtime.id + "/popup.html" && tab_url !== "chrome://extensions/?id=" + chrome.runtime.id) {
        setHistory(tabTitle,49); //THIS FUNCTION SAVE TITLE TO HISTORY
    }
}
</code>```

答:
One of the ways that you can handle this problem is sending an ajax request to the page's url

```<code>    var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', 'tab_url', true);
xmlHttp.onreadystatechange = function () {
    if (
        this.readyState == 4 &&
        ((this.status >= 200 && this.status < 300) ||
            this.status == 304)
    ) {
        var data = this.responseText;
        var contentType = this.getResponseHeader("Content-Type"); //no i18n
        if (contentType && contentType.match('text/html')) {
            var doc = new DOMParser().parseFromString(data, "text/html");
            console.log(doc.title);
        }
    }
};
xmlHttp.send();
</code>```

Note: This may throw CORS error at most pages, so don't forget to add "<all_urls>" in permissions in manifest(assuming you are using manifest V2).

```<code>"permissions": [
    "<all_urls>"
],
</code>```

If you are using manifest V3, which is recommended, refer this documentation regarding permission

Other way is to send a message from chrome.tabs.create success callback to content script, if you don't use content script you have to inject code. In message response you can send the document's title using document.title.

Either way both will be asynchronous...

Body:
I'm developing a plugin for Chrome and it has History feature in the plugin.  For example, clicking the button creates a new tab and saves the URL address in the history.  So this function works fine.  But I want to get the document.title data of the tab that was opened in the past instead of the URL address.  I tried doing this with tabs[tabs.length-1].title but it didn't get the title of the opened tab.  Instead it got the title of the last tab that was already open.  I guess this is the problem because the tab is not open yet.  How can I solve this?  Can you help me please?

This is my create tab function (If the tab is already open, don't open it again.):

function openTab(tab_url) {
    var isTabActive = false;
    var tabId = 0;
    var tabTitle = "";
    totalHistoryContent++;
    chrome.tabs.query({}, function(tabs) {
        for(var i=0;i<tabs.length;i++) {
            if(tabs[i].url.toLowerCase().includes(tab_url.toLowerCase()) == true) {
                isTabActive = true;
                tabId = tabs[i].id;
                tabTitle = tabs[i].title; // WORKING NICE
                break;
            }
        }

        if(isTabActive == false) {
            chrome.tabs.create({ url:tab_url });
            tabTitle = tabs[tabs.length - 1].title; // NOT WORKING CORRECTLY
        } else{
            chrome.tabs.update(tabId, {selected: true});
            chrome.tabs.reload(tabId);
        }
        alert(tabTitle);
    });

    if(tab_url !== "chrome-extension://" + chrome.runtime.id + "/popup.html" && tab_url !== "chrome://extensions/?id=" + chrome.runtime.id) {
        setHistory(tabTitle,49); //THIS FUNCTION SAVE TITLE TO HISTORY
    }
}

Body:
One of the ways that you can handle this problem is sending an ajax request to the page's url

    var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', 'tab_url', true);
xmlHttp.onreadystatechange = function () {
    if (
        this.readyState == 4 &&
        ((this.status >= 200 && this.status < 300) ||
            this.status == 304)
    ) {
        var data = this.responseText;
        var contentType = this.getResponseHeader("Content-Type"); //no i18n
        if (contentType && contentType.match('text/html')) {
            var doc = new DOMParser().parseFromString(data, "text/html");
            console.log(doc.title);
        }
    }
};
xmlHttp.send();

Note: This may throw CORS error at most pages, so don't forget to add "<all_urls>" in permissions in manifest(assuming you are using manifest V2).

"permissions": [
    "<all_urls>"
],

If you are using manifest V3, which is recommended, refer this documentation regarding permission

Other way is to send a message from chrome.tabs.create success callback to content script, if you don't use content script you have to inject code. In message response you can send the document's title using document.title.

Either way both will be asynchronous...