问:
When sharing an image with Intent, it gives an error when converting from byte[] to Uri
I have an application that uses API. I'm using the code below to share the image I got from the API.

```<code>byte[] byte;
final Bitmap[] bitmap = new Bitmap[1];
Glide.with(FilmActivity.this)
      .asBitmap()
      .load(imageLink)
      .into(new CustomTarget<Bitmap>() {
           @Override
           public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                 bitmap[0] = resource;
                 byte = getBytes(bitmap[0]);
            }
           @Override
           public void onLoadCleared(@Nullable Drawable placeholder) {

           }
});
</code>```
```<code>private byte[] getBytes(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
        return stream.toByteArray();
}
</code>```

I am using the following code to share byte[] type data.

```<code>try {
     Intent sendIntent = new Intent(Intent.ACTION_SEND);
     sendIntent.putExtra(Intent.EXTRA_TEXT, name);
     String s = new String(byte, "UTF-8");
     Uri uri = Uri.parse(s);
     sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
     sendIntent.setType("image/*");
     sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
     startActivity(Intent.createChooser(sendIntent, "Share"));
} catch (UnsupportedEncodingException e) {
            e.printStackTrace();
}
</code>```

But it doesn't work. I get the following error.

```<code>java.lang.RuntimeException: Failure from system
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1677)
        at android.app.Activity.startActivityForResult(Activity.java:4586)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
        at android.app.Activity.startActivityForResult(Activity.java:4544)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
        at android.app.Activity.startActivity(Activity.java:4905)
        at android.app.Activity.startActivity(Activity.java:4873)
 at com.example.filmler.activity.FilmActivity$4.onClick(FilmActivity.java:205)
</code>```

答:
Why are converting it to byte and sharing?

Why do you want to convert it? You can just save the bitmap like this:

```<code>String location = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap,new Random().nextInt(), null);
</code>```

And then you can pass it to the intent like this:

```<code>sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(location));
</code>```

Edit

If you do not want to save it on the device, you can do it this way.

Save the bitmap to cache.

```<code>File cacheDir = getBaseContext().getCacheDir();
File f = new File(cacheDir, "pic");

try {
    FileOutputStream out = new FileOutputStream(
            f);
    pic.compress(
            Bitmap.CompressFormat.JPEG,
            100, out);
    out.flush();
    out.close();

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

Get the image and share it.

```<code>File cacheDir = getBaseContext().getCacheDir();
File f = new File(cacheDir, "pic");
</code>```

Add it to intent

```<code>Uri uri = fromFile(f);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
</code>```

Body:
I have an application that uses API. I'm using the code below to share the image I got from the API.

byte[] byte;
final Bitmap[] bitmap = new Bitmap[1];
Glide.with(FilmActivity.this)
      .asBitmap()
      .load(imageLink)
      .into(new CustomTarget<Bitmap>() {
           @Override
           public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                 bitmap[0] = resource;
                 byte = getBytes(bitmap[0]);
            }
           @Override
           public void onLoadCleared(@Nullable Drawable placeholder) {

           }
});

private byte[] getBytes(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
        return stream.toByteArray();
}

I am using the following code to share byte[] type data.

try {
     Intent sendIntent = new Intent(Intent.ACTION_SEND);
     sendIntent.putExtra(Intent.EXTRA_TEXT, name);
     String s = new String(byte, "UTF-8");
     Uri uri = Uri.parse(s);
     sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
     sendIntent.setType("image/*");
     sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
     startActivity(Intent.createChooser(sendIntent, "Share"));
} catch (UnsupportedEncodingException e) {
            e.printStackTrace();
}

But it doesn't work. I get the following error.

java.lang.RuntimeException: Failure from system
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1677)
        at android.app.Activity.startActivityForResult(Activity.java:4586)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
        at android.app.Activity.startActivityForResult(Activity.java:4544)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
        at android.app.Activity.startActivity(Activity.java:4905)
        at android.app.Activity.startActivity(Activity.java:4873)
 at com.example.filmler.activity.FilmActivity$4.onClick(FilmActivity.java:205)

Body:
Why are converting it to byte and sharing?

Why do you want to convert it? You can just save the bitmap like this:

String location = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap,new Random().nextInt(), null);

And then you can pass it to the intent like this:

sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(location));

Edit

If you do not want to save it on the device, you can do it this way.

Save the bitmap to cache.

File cacheDir = getBaseContext().getCacheDir();
File f = new File(cacheDir, "pic");

try {
    FileOutputStream out = new FileOutputStream(
            f);
    pic.compress(
            Bitmap.CompressFormat.JPEG,
            100, out);
    out.flush();
    out.close();

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Get the image and share it.

File cacheDir = getBaseContext().getCacheDir();
File f = new File(cacheDir, "pic");

Add it to intent

Uri uri = fromFile(f);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);


来源: stackexchange

问:
Search multiple column values with one search string
I have this query where I want to return results if the search string provided yields data from the 'FirstName' and 'LastName' column of my database. They each work individually as I can get results for Firstname = 'john' and LastName = 'doe'. I also want to be able to pass in a search string of 'John doe' and get results. How would I implement this using .net/linq

snippet:
var query = _context.Players.Where(p => p.Firstname.Contains(searchString.ToLower().Trim()) || p.Lastname.Contains(searchString.ToLower().Trim()));

答:
use Split function like the following:

```<code>var parts = searchString.Split();
snippet: var query = _context.Players.Where(
     p => p.Firstname.Contains(parts[0].ToLower().Trim())
       || p.Lastname.Contains(parts[1].ToLower().Trim()));
</code>```

Extracted from the official docs:

If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters.

ContentLicense: CC BY-SA 4.0

Body:
use Split function like the following:

var parts = searchString.Split();
snippet: var query = _context.Players.Where(
     p => p.Firstname.Contains(parts[0].ToLower().Trim())
       || p.Lastname.Contains(parts[1].ToLower().Trim()));

Extracted from the official docs:

If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters.


问:
how to create Snapshot & Release Folder for Artifactory using CI pipeline?
I want to create snapshot & release folder in Jfrog Artifactory using CI Pipeline while doing deployment in Gitlab.

Can anybody help me on this?

答:
JFrog Artifactory uses repositories for storing and managing artifacts. One repository usually contains many artifacts. In general, repositories are usually created once, not during a CI run.

Maven repositories can be configured to host releases, snapshots or both. The common practice is to create a local repository for snapshots (e.g. libs-snapshot-local) and a local repository for releases (e.g. libs-release-local). In addition, you can add remote repositories (e.g. for proxying Maven Central). On top of that you can add virtual repositories - to aggregate several repositories.

Please refer to the following links to get more information:

Screencast: Setting Up A Maven Repository With JFrog Artifactory In Less Than One Minute

Official Documentation: Maven Repository

QuickStart Guide: Maven and Gradle


问:
AJAX Using a REST API Without Server Side Framework
I am building a REST based API (Read only) for accessing services of my application. I plan on writing a web application that will leverage these APIs to provide basic information on the status of the application. I plan to use AJAX (using jQuery) to show the information.

Originally I planned on using Grails, Spring MVC, RoR or one of the web frameworks to handle the back end of my application. The REST APIs I will be providing though are already built on a stanalone REST framework so I would only be leveraging the web framework for the core application and not the business logic. In the future, I might need the server side framework to handle other tasks but for now most of the work is done in the REST APIs.

My question is, should I bother with using a web application framework on the server side? I should be able to make all the API calls I need from AJAX directly from the browser. I cannot think of much I would need to do on the server side. Would it make sense to have the application be standard HTML + AJAX + REST?

答:
Its hard to say without actually knowing more about your current setup. This is what your situation sounds like:

You already have an app ready to go with all of the business logic contained. Sounds like its written in Java?

You already have the services written and exposed through a REST api using some other standalone framework. Meaning that if you wanted to, you could access the data right now with the browser without any extra work.

You have not yet built the web application, but when you do, it will get all of its content from the REST api using XHR and jquery. I say that, because otherwise, I would think that you would already be using some kind of framework to generate the other content.

If I am correct in my assumptions, then I would say that you have no need for an additional framework layer. Grails, RoR, SpringMVC my use ajax, and aid in exposing REST services, but the bulk of what they provide is an easy way to make an application that must generate html on the server, deal with form submissions, and handle sessions in a request/response cycle. It doesn't really sound like you'll be doing any of that, and it will likely make your app more complicated.

If you did at some point need the things that rails etc. provides, I would say that you may not need to use rails to expose the rest apis you have now. You could use rails just for what you need, and continue to use what you have for the REST api.

OwnerDisplayName: Chris Dail

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: genericallyloud


问:
How to automate development environment setup?
Every time a new developer joins the team or the computer a developer is using changes, the developer needs to do lots of work to setup the local development environment to make the current project work. As a SCRUM team we are trying to automate everything including deployment and tests so what I am asking is: is there a tool or a practice to make local development environment setup automated?

For example to setup my environment, first I had to install eclipse, then SVN, Apache, Tomcat, MySQL, PHP. After that I populated the DB and I had to do minor changes in the various configuration files etc... Is there a way to reduce this labor to one-click?

答:
I've been thinking about this myself. There are some other technologies that you could throw into the mix. Here's what I'm currently setting up:

PXE based pre-seeded installation images (Debian Squeeze). You can start up a bare-metal machine (or new virtual appliance) and select the image from the PXE boot menu. This has the major advantage of being able to install your environment on physical machines (in addition to virtual appliances).

Someone already mentioned Puppet. I use CFEngine but it's a similar deal. Essentially your configuration is documented and centralized in policy files which are continually enforced by an agent on the client.

if you don't want a rigid environment (i.e. developers may choose a combination of tool-sets) you can roll your own deb packages so new devs can type sudo apt-get install acmecorp-eclipse-env or sudo apt-get install acmecorp-intellij-env, for example.

Slightly off-topic, but if you run a Debian based environment (i.e. Ubuntu), consider installing apt-cacher (package proxy). In addition to saving bandwidth, it will make your installations much faster (since packages are cached on your local network).

ContentLicense: CC BY-SA 3.0


问:
How to use AVCapturePhotoOutput
I have been working on using a custom camera, and I recently upgraded to Xcode 8 beta along with Swift 3. I originally had this:

```<code>var stillImageOutput: AVCaptureStillImageOutput?
</code>```

However, I am now getting the warning:

'AVCaptureStillImageOutput' was deprecated in iOS 10.0: Use AVCapturePhotoOutput instead

As this is fairly new, I have not seen much information on this. Here is my current code:

```<code>var captureSession: AVCaptureSession?
var stillImageOutput: AVCaptureStillImageOutput?
var previewLayer: AVCaptureVideoPreviewLayer?

func clickPicture() {

    if let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo) {

        videoConnection.videoOrientation = .portrait
        stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (sampleBuffer, error) -> Void in

            if sampleBuffer != nil {

                let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
                let dataProvider = CGDataProvider(data: imageData!)
                let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: .defaultIntent)

                let image = UIImage(cgImage: cgImageRef!, scale: 1, orientation: .right)

            }

        })

    }

}
</code>```

I have tried to look at AVCapturePhotoCaptureDelegate, but I am not quite sure how to use it. Does anybody know how to use this? Thanks.

答: Exact same answer as the one given by @productioncoder but I had to change the startCamera() to under viewDidLoad() instead of viewDidAppear().

Title: How to use AVCapturePhotoOutput

Body:
I have been working on using a custom camera, and I recently upgraded to Xcode 8 beta along with Swift 3. I originally had this:

var stillImageOutput: AVCaptureStillImageOutput?

However, I am now getting the warning:

'AVCaptureStillImageOutput' was deprecated in iOS 10.0: Use AVCapturePhotoOutput instead

As this is fairly new, I have not seen much information on this. Here is my current code:

var captureSession: AVCaptureSession?
var stillImageOutput: AVCaptureStillImageOutput?
var previewLayer: AVCaptureVideoPreviewLayer?

func clickPicture() {

    if let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo) {

        videoConnection.videoOrientation = .portrait
        stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (sampleBuffer, error) -> Void in

            if sampleBuffer != nil {

                let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
                let dataProvider = CGDataProvider(data: imageData!)
                let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: .defaultIntent)

                let image = UIImage(cgImage: cgImageRef!, scale: 1, orientation: .right)

            }

        })

    }

}

I have tried to look at AVCapturePhotoCaptureDelegate, but I am not quite sure how to use it. Does anybody know how to use this? Thanks.


问:
Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)
I am having a big problem trying to connect to mysql. When I run:

```<code>/usr/local/mysql/bin/mysql start
</code>```

I have the following error :

```<code>Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)
</code>```

I do have mysql.sock under the /var/mysql directory.

In /etc/my.cnf I have:

```<code>[client]
port=3306
socket=/var/mysql/mysql.sock

[mysqld]
port=3306
socket=/var/mysql/mysql.sock
key_buffer_size=16M
max_allowed_packet=8M
</code>```

and in /etc/php.ini I have :

```<code>; Default socket name for local MySQL connects.  If empty, uses the built-in
; MySQL defaults.
mysql.default_socket = /var/mysql/mysql.sock
</code>```

I have restarted apache using sudo /opt/local/apache2/bin/apachectl restart

But I still have the error.

Otherwise, I don't know if that's relevant but when I do mysql_config --sockets I get

```<code>--socket         [/tmp/mysql.sock]
</code>```

答: When you use localhost to connect to MySQL, the operating system uses the socket connector. However, if you use the 127.0.0.1 IP address, the operating system will use the TCP/IP connector. So, a possible solution when you’re having issues with the socket connector is trying to establish the connection using TCP/IP by specifying the 127.0.0.1 IP address instead of localhost.

Body:
I am having a big problem trying to connect to mysql. When I run:

/usr/local/mysql/bin/mysql start

I have the following error :

Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)

I do have mysql.sock under the /var/mysql directory.

In /etc/my.cnf I have:

[client]
port=3306
socket=/var/mysql/mysql.sock

[mysqld]
port=3306
socket=/var/mysql/mysql.sock
key_buffer_size=16M
max_allowed_packet=8M

and in /etc/php.ini I have :

; Default socket name for local MySQL connects.  If empty, uses the built-in
; MySQL defaults.
mysql.default_socket = /var/mysql/mysql.sock

I have restarted apache using sudo /opt/local/apache2/bin/apachectl restart

But I still have the error.

Otherwise, I don't know if that's relevant but when I do mysql_config --sockets I get

--socket         [/tmp/mysql.sock]


问:
WordPress, nginx proxy and subdirectory: wp-login.php redirects to domain
In my NGINX configuration, a WordPress blog is on a private server. My NGINX public server proxies the private server's content for https://www.example.com/blog/.

```<code>location ^~ /blog/ {    # A "subdirectory", hiding a proxied server

    proxy_pass              http://192.168.0.5:80/;    # The blog resides in the
                                                       # private's web root,
                                                       # not in a subdirectory
    proxy_set_header        Host $host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_redirect          off;
}
</code>```

The blog is perfectly rendered on calling the domain and subdirectory. Bringing up wp-login does not generate a redirect GET field.

https://www.example.com/blog/wp-login.php

My siteurl and my home variables are both set to the domain with subdirectory.

However, after a successful login, I may see the dashboard, but the URL in my browser gets rewritten to https://www.example.com/wp-admin, causing problems on using the dashboard.

How do I configure WP to rewrite the URL to the subdirectory, although the blog is on a proxied private server?

(Do the subdirectories in the servers have to be symmetrical?)

答:
You have to add the following two rewrites to your wp-config.php:

```<code>$_SERVER['REQUEST_URI'] = str_replace("/wp-admin/", "/blog/wp-admin/",  $_SERVER['REQUEST_URI']);
$_SERVER['REQUEST_URI'] = str_replace("/wp-login.php", "/blog/wp-login.php", $_SERVER['REQUEST_URI']);
</code>```

The first one fixes all admin pages. The second one you need for the password reset flow.

I found an open TRAC issue for the password reset flow from 4 years ago, so it seems we'll have to continue doing these workarounds for the foreseeable future. It doesn't seem like running behind a reverse proxy is something Wordpress expects most people to do.

Body:
In my NGINX configuration, a WordPress blog is on a private server. My NGINX public server proxies the private server's content for https://www.example.com/blog/.

location ^~ /blog/ {    # A "subdirectory", hiding a proxied server

    proxy_pass              http://192.168.0.5:80/;    # The blog resides in the
                                                       # private's web root,
                                                       # not in a subdirectory
    proxy_set_header        Host $host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_redirect          off;
}

The blog is perfectly rendered on calling the domain and subdirectory. Bringing up wp-login does not generate a redirect GET field.

https://www.example.com/blog/wp-login.php

My siteurl and my home variables are both set to the domain with subdirectory.

However, after a successful login, I may see the dashboard, but the URL in my browser gets rewritten to https://www.example.com/wp-admin, causing problems on using the dashboard.

How do I configure WP to rewrite the URL to the subdirectory, although the blog is on a proxied private server?

(Do the subdirectories in the servers have to be symmetrical?)

Body:
You have to add the following two rewrites to your wp-config.php:

$_SERVER['REQUEST_URI'] = str_replace("/wp-admin/", "/blog/wp-admin/",  $_SERVER['REQUEST_URI']);
$_SERVER['REQUEST_URI'] = str_replace("/wp-login.php", "/blog/wp-login.php", $_SERVER['REQUEST_URI']);

The first one fixes all admin pages. The second one you need for the password reset flow.

I found an open TRAC issue for the password reset flow from 4 years ago, so it seems we'll have to continue doing these workarounds for the foreseeable future. It doesn't seem like running behind a reverse proxy is something Wordpress expects most people to do.


问:
Rewrite rule doesn't work on joomla htaccess
I need a redirect from http://www.mysite.com/passport/365.html to http://www.mysite.com/passport/365.html?task=view

I try to do it like this
RewriteCond %{HTTP_HOST} ^/passport/365.html$
RewriteRule ^/?$ /passport/365.html?task=view [QSA]

and it doesn't work.

Please help.

答:
I would recommend you use this plugin.

You can simply add the redirect rule to the plugin without modifying .htaccess


问:
Remix.run static asset return 404
I am hitting a brick wall trying to display an image with remix.run.

The documentation on Asset Preloads shows the following:

When I do this I am getting a 404 for the /icons/clipboard.svg.  Do I need to add a route to get static assets to route properly?

Another example is the Jokes tutorial.  I add an assets folder under app with a file heart.svg.  From my jokes.jsx, I add  which 404's, along with "~/assets/heart.svg" or "../assets/heart.svg"

I am thinking there is something glaring me in the face that I am missing here, an additional route, build param, something...

答: Figured it out.  Gotta put the asset folder in the public folder for it to get hit.  Moving it out of the app folder into public resolved my issue.</p>

Title: Remix.run static asset return 404


问:
How to optimize mesh normals calculation?
I am making an application for real time mesh deformation and I need to calculate normals a huge number of times. Now the problem is I found with some profiling this bit of code is taking largest cpu time so how can I possibly optimize this?

```<code>void Mesh::RecalculateNormals()
{
        for (int i = 0; i < indexCount; i += 3)
        {
            const int ia = indices[i];
            const int ib = indices[i + 1];
            const int ic = indices[i + 2];

            const glm::vec3 e1 = glm::vec3(vert[ia].position) - glm::vec3(vert[ib].position);
            const glm::vec3 e2 = glm::vec3(vert[ic].position) - glm::vec3(vert[ib].position);
            const glm::vec3 no = cross(e1, e2);

            vert[ia].normal += glm::vec4(no, 0.0);
            vert[ib].normal += glm::vec4(no, 0.0);
            vert[ic].normal += glm::vec4(no, 0.0);
        }

        for (int i = 0; i < vertexCount; i++)
            vert[i].normal = glm::vec4(glm::normalize(glm::vec3(vert[i].normal)), 0.0f);

}
</code>```

Also before this function is called I must loop through all vertices and clewr the previous normals by setting normals to vec3(0).

How can I speed this up? Could there be a better algorithm? Or is GLM slow?

答:
There is three main ways to optimize this code: using SIMD instructions, using multiple threads and working on the memory access pattern. None of them is a silver-bullet.

Using SIMD instructions is not trivial in your case due to the indices-based indirect data-dependent read in memory in the first loop. That being said, recent SIMD instruction sets like AVX-2/AVX-512 on x86-64 processors and SVE on ARM ones provides instructions to perform gather loads. Once the values are loaded in SIMD registers, you can compute the cross product very quickly. The thing is the last indices-based indirect data-dependent stores in the first loop require scatter store instruction which are only available on very recent processors supporting AVX-512 (x86-64) and SVE (ARM). You can extract the values from SIMD registers so to store them serially but this will certainly quite inefficient. Hopefully, the second loop can be much more easily vectorized but you certainly need to reorder the normal data structure in a way that is more SIMD-friendly (see AoS vs SoA and Data-oriented design). In the end, I expect the SIMD implementation not much faster for the first loop as long as scater instructions are not used, and certainly significantly faster for the second one. Actually, I expect the SIMD implementation of the first loop not to be a lot faster even with gather/scatter instructions since such instructions tend to be quite inefficiently implemented and also because I expect the first loop of your code to cause a lot of cache misses (see the next sections).

Using multiple thread is also not trivial. Indeed, while the first part of the first loop can be trivially parallelized, the second part performing the accumulation of the normal cannot. One solution is to use atomic adds. Another solution is to use a per-thread array of normal vectors. A faster solution is to use partitioning methods so to split the mesh in independent parts (each threads can safely perform the accumulation, except for possibly-shared vect items). Note that efficiently partitioning a mesh so to balance the work between many threads is far from being simple and AFAIK it has been the subject of many past research papers. The best solution is very dependent of the number of threads, the size of the overall vert buffer in memory and your performance/complexity requirements. The second loop can be trivially parallelized. The simplest solution to parallelize the loops is to use OpenMP (few pragma are enough to parallelize the loops although an efficient implementation can be quite complex).

Regarding the input data, the first loop can be very inefficient. Indeed, ia, ib and ic can refer to very different indices causing predictable vert[...] loads/stores in memory. If the structure is big, the loads/stores will cause cache misses. Such cache misses can be very slow is the data structure does not fit in RAM due to the huge latency of the RAM. The best solution to fix this problem is to improve the locality of the memory accesses. Reordering vert items and/or indices can help a lot to improve locality and so performance. Again, partitioning methods can be used to do that. A naive first start is to sort vert so that ia is sorted while updating ib and ic indices so they are still valid. This can be computed using key-value arg-sort. If the mesh is dynamic, the problem becomes very complex to solve efficiently. Octrees and k-D trees could help to improve the locality of the computation without introducing a (too) big overhead.

Note that you may not need to recompute all the normals regarding the previous operations. If so, you can track the one that needs to be recomputed and only perform an incremental update.

Finally, please check compilers optimizations are enabled. Moreover, note that you can use the (unsafe) fash-math flags so to improve the auto-vectorization of your code. You should also check the SIMD instruction set used and that the glm calls are inlined by the compiler.

Body:
I am making an application for real time mesh deformation and I need to calculate normals a huge number of times. Now the problem is I found with some profiling this bit of code is taking largest cpu time so how can I possibly optimize this?

void Mesh::RecalculateNormals()
{
        for (int i = 0; i < indexCount; i += 3)
        {
            const int ia = indices[i];
            const int ib = indices[i + 1];
            const int ic = indices[i + 2];

            const glm::vec3 e1 = glm::vec3(vert[ia].position) - glm::vec3(vert[ib].position);
            const glm::vec3 e2 = glm::vec3(vert[ic].position) - glm::vec3(vert[ib].position);
            const glm::vec3 no = cross(e1, e2);

            vert[ia].normal += glm::vec4(no, 0.0);
            vert[ib].normal += glm::vec4(no, 0.0);
            vert[ic].normal += glm::vec4(no, 0.0);
        }

        for (int i = 0; i < vertexCount; i++)
            vert[i].normal = glm::vec4(glm::normalize(glm::vec3(vert[i].normal)), 0.0f);

}

Also before this function is called I must loop through all vertices and clewr the previous normals by setting normals to vec3(0).

How can I speed this up? Could there be a better algorithm? Or is GLM slow?


问:
How to use len() on Visual Studio Code?
When i'm using len() on the terminal it works but when ı use

it on Visual Studio code it doesn't appear.

```<code>cars = ['bmw', 'audi', 'toyota', 'subaru']
len(cars)
</code>```

答:
you will have to print it out for it to show

```<code>cars = ['bmw', 'audi', 'toyota', 'subaru']
print(len(cars))
</code>```

output:

```<code>4
</code>```

Title: How to use len() on Visual Studio Code?

Body:
When i'm using len() on the terminal it works but when ı use

it on Visual Studio code it doesn't appear.

cars = ['bmw', 'audi', 'toyota', 'subaru']
len(cars)

Body:
you will have to print it out for it to show

cars = ['bmw', 'audi', 'toyota', 'subaru']
print(len(cars))

output:

4


问:
Bot doesn't play music
```<code>@client.event
async def on_ready(pass_context = True):
    print('logged in as {0.user}'.format(client))
    me = client.get_user(str(308330919176175616))
    tchannel = client.get_channel(931274904228233291)
    vchannel = client.get_channel(939513894001578024)
    await vchannel.connect()
    await vchannel.play(discord.FFmpegPCMAudio['музика.mp3'], pass_context = True)
</code>```

AttributeError: 'VoiceChannel' object has no attribute 'play'

UPD:
I have changed the code, so it doesn't show me an error, but there is still no music anyway.
Code:

```<code>@client.event
async def on_ready(pass_context = True):
    print('logged in as {0.user}'.format(client))
    me = client.get_user(str(308330919176175616))
    tchannel = client.get_channel(931274904228233291)
    vchannel = client.get_channel(939513894001578024)
    vc = await vchannel.connect()
    vc.play(discord.FFmpegPCMAudio('s.mp3'))
</code>```

答:
Try this code, instead of mentioning the voice channels before hand let the bot find it! and I have this code which works. So try this!

@client.command()
async def play(ctx):
    voice_state = ctx.author.voice

    if voice_state == None:
        #user isnt in voice channel so it wont connect
        return

    if voice_state != None:
        await ctx.author.voice.channel.connect()

    vc = ctx.voice_client
    vc.play(discord.FFmpegPCMAudio('s.mp3'))
```

Title: Bot doesn't play music

Body:
@client.event
async def on_ready(pass_context = True):
    print('logged in as {0.user}'.format(client))
    me = client.get_user(str(308330919176175616))
    tchannel = client.get_channel(931274904228233291)
    vchannel = client.get_channel(939513894001578024)
    await vchannel.connect()
    await vchannel.play(discord.FFmpegPCMAudio['музика.mp3'], pass_context = True)

AttributeError: 'VoiceChannel' object has no attribute 'play'

UPD:
I have changed the code, so it doesn't show me an error, but there is still no music anyway.
Code:

@client.event
async def on_ready(pass_context = True):
    print('logged in as {0.user}'.format(client))
    me = client.get_user(str(308330919176175616))
    tchannel = client.get_channel(931274904228233291)
    vchannel = client.get_channel(939513894001578024)
    vc = await vchannel.connect()
    vc.play(discord.FFmpegPCMAudio('s.mp3'))


问:
Remove subslists that contains a set of words in Nested List on R
I have a nested list videos inside the sublist there is element "title" I want to filter and remove all the sublists in which x$title has the words like {trailer, highlights, match}. Can some good soul help me in solving this ?

Here is the Nested List in R

Here is the Sublist

(Sorry for my language) Thanks in advance

答:
Making a small sample dataset (See this SO post).

```<code>l <- list(
  list(id = "a", title = "blabla trailer"),
  list(id = "b", title = "keep this one"),
  list(id = "c", title = "remove this match"))
</code>```

To subset list elements based on search patterns we can use some regular expression to find matches those matches. We can use | to search for multiple possibilities.

```<code># base R
l[!sapply(l, function(x){grepl("match|highlight|trailer", x$title)})]
# purrr
library(purrr)
l[!map_lgl(l, ~ grepl("match|highlight|trailer", .x$title))]

[[1]]
[[1]]$id
[1] "b"

[[1]]$title
[1] "keep this one"
</code>```

Body:
Making a small sample dataset (See this SO post).

l <- list(
  list(id = "a", title = "blabla trailer"),
  list(id = "b", title = "keep this one"),
  list(id = "c", title = "remove this match"))

To subset list elements based on search patterns we can use some regular expression to find matches those matches. We can use | to search for multiple possibilities.

# base R
l[!sapply(l, function(x){grepl("match|highlight|trailer", x$title)})]
# purrr
library(purrr)
l[!map_lgl(l, ~ grepl("match|highlight|trailer", .x$title))]

[[1]]
[[1]]$id
[1] "b"

[[1]]$title
[1] "keep this one"


问:
XML update a set of nodes in PHP
I have this PHP code that adds a set of nodes to an XML file. It does most of what it should do, it finds where to make the additions, but then it doesn't make the update.

I have an xml file of this structure.

```<code><COMMUNITIES>
  <COMMUNITY ID="c001">
       <URLS>
           <URL ID="u001">
              <NAME>Google.com</NAME>
              <URL>http://www.google.com</URL>
           </URL>
       </URLS>
  </COMMUNITY>
</COMMUNITIES>
</code>```

The updates are being made to the URLS node.  The user clicks an "Add URL" link and I add the new URL to this node like this.

```<code>       <URL ID="u002">
          <NAME>Yahoo.com</NAME>
          <URL>http://www.yahoo.com</URL>
       </URL>
</code>```

If the URLS node exists, I append the new url node. If the URLS node does not exist, I create it, then append the new url node.

There are no errors, everything seems to work, but the URLS node is empty.  Here is the PHP script.

```<code>function add_url( $nodeid, $urlid, $urlname, $urllink ) {

$dom = new DOMDocument();
$dom->load('communities.xml');

$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;

// get document element

$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//COMMUNITY[@ID='$nodeid']");

if ($nodes->length) {
   $node = $nodes->item(0);

   $xurl = $dom->createElement("URL");
   $xurl->setAttribute("ID", $urlid);

   $xuname     = $dom->createElement("NAME");
   $xunameText = $dom->createTextNode(mysql_escape_mimic($urlname));
   $xuname->appendChild($xunameText);

   $xulink     = $dom->createElement("URL");
   $xulinkText = $dom->createTextNode(mysql_escape_mimic($urllink));
   $xulink->appendChild($xulinkText);

   $xurl->appendChild($xuname);
   $xurl->appendChild($xulink);

   $xurls = $xpath->query("//COMMUNITY[@ID='$nodeid']/URLS");

   if ($xurls->length) {
   }
   else {
      $xurls = $dom->createElement("URLS");
   }

   $xurls->appendChild($xurl);

   /* $node->appendChild($xurls); */

}

$dom->save('communities.xml');
}
</code>```

I thought the problem was that I was appending the URLS node when it already existed.  But I commented out that line.  I am sure the problem is simple, but I am new at this.  I looked on the site and did not find that specific situation.

Edit

Removed return statement before if ($xurls->length).

Fixed function.

答: You are calling return half way down the function, before you have actually saved the changes - so I'd guess what is happening is that you are making the modifications in memory, but not actually writing them to file...

Title: XML update a set of nodes in PHP

Body:
I have this PHP code that adds a set of nodes to an XML file. It does most of what it should do, it finds where to make the additions, but then it doesn't make the update.

I have an xml file of this structure.

<COMMUNITIES>
  <COMMUNITY ID="c001">
       <URLS>
           <URL ID="u001">
              <NAME>Google.com</NAME>
              <URL>http://www.google.com</URL>
           </URL>
       </URLS>
  </COMMUNITY>
</COMMUNITIES>

The updates are being made to the URLS node.  The user clicks an "Add URL" link and I add the new URL to this node like this.

       <URL ID="u002">
          <NAME>Yahoo.com</NAME>
          <URL>http://www.yahoo.com</URL>
       </URL>

If the URLS node exists, I append the new url node. If the URLS node does not exist, I create it, then append the new url node.

There are no errors, everything seems to work, but the URLS node is empty.  Here is the PHP script.

function add_url( $nodeid, $urlid, $urlname, $urllink ) {

$dom = new DOMDocument();
$dom->load('communities.xml');

$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;

// get document element

$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//COMMUNITY[@ID='$nodeid']");

if ($nodes->length) {
   $node = $nodes->item(0);

   $xurl = $dom->createElement("URL");
   $xurl->setAttribute("ID", $urlid);

   $xuname     = $dom->createElement("NAME");
   $xunameText = $dom->createTextNode(mysql_escape_mimic($urlname));
   $xuname->appendChild($xunameText);

   $xulink     = $dom->createElement("URL");
   $xulinkText = $dom->createTextNode(mysql_escape_mimic($urllink));
   $xulink->appendChild($xulinkText);

   $xurl->appendChild($xuname);
   $xurl->appendChild($xulink);

   $xurls = $xpath->query("//COMMUNITY[@ID='$nodeid']/URLS");

   if ($xurls->length) {
   }
   else {
      $xurls = $dom->createElement("URLS");
   }

   $xurls->appendChild($xurl);

   /* $node->appendChild($xurls); */

}

$dom->save('communities.xml');
}

I thought the problem was that I was appending the URLS node when it already existed.  But I commented out that line.  I am sure the problem is simple, but I am new at this.  I looked on the site and did not find that specific situation.

Edit

Removed return statement before if ($xurls->length).

Fixed function.


问:
split a list into groups of n and assign group ID with Python
Given  a list of tuple, with each tuple is a value for a pair of variable.

```<code>[(0.0, 0.0), (0.0, 0.4), (0.0, 0.8), (0.0, 1.2000000000000002), (0.0, 1.6), (0.4, 0.0), (0.4, 0.4)]
</code>```

The objective is to split this list of tuple into N group and append the group ID in each of the tuple.

Currently, the following code answer the objective

```<code>from itertools import product

import numpy as np

def split(a, n):
    k, m = divmod(len(a), n)
    return (a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n))

pair_var=list(product(np.arange(*(0.0,2,0.4)), np.arange(*(0.0,2,0.4))))
ngroup=2
pair_var_gr=list(split(pair_var, ngroup))

new_group=[]
for ndex,ltup in enumerate(pair_var_gr):
  for dtup in ltup:
    m=list(dtup)
    m.append(ndex)
    new_group.append(m)
</code>```

Expected output

```<code>[[0.0, 0.0, 0], [0.0, 0.4, 0], [0.0, 0.8, 0], [0.0, 1.2000000000000002, 0], [0.0, 1.6, 0], [0.4, 0.0, 0], [0.4, 0.4, 0]]
</code>```

However, I wonder whether there is compact or proper ways of achieving the above?

答:
You can use more-itertools to divide a list into N groups.

new_group = [[tuple(pair) + (group_id,) for pair in group_of_pairs]
             for group_id, group_of_pairs in enumerate(more_itertools.divide(ngroup, pair_var))]
```

Or you could also use numpy.array_split or numpy.split.
This is much faster when dealing with large data, but note that this method requires all values to be the same dtype.

Body:
Given  a list of tuple, with each tuple is a value for a pair of variable.

[(0.0, 0.0), (0.0, 0.4), (0.0, 0.8), (0.0, 1.2000000000000002), (0.0, 1.6), (0.4, 0.0), (0.4, 0.4)]

The objective is to split this list of tuple into N group and append the group ID in each of the tuple.

Currently, the following code answer the objective

from itertools import product

import numpy as np

def split(a, n):
    k, m = divmod(len(a), n)
    return (a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n))

pair_var=list(product(np.arange(*(0.0,2,0.4)), np.arange(*(0.0,2,0.4))))
ngroup=2
pair_var_gr=list(split(pair_var, ngroup))

new_group=[]
for ndex,ltup in enumerate(pair_var_gr):
  for dtup in ltup:
    m=list(dtup)
    m.append(ndex)
    new_group.append(m)

Expected output

[[0.0, 0.0, 0], [0.0, 0.4, 0], [0.0, 0.8, 0], [0.0, 1.2000000000000002, 0], [0.0, 1.6, 0], [0.4, 0.0, 0], [0.4, 0.4, 0]]

However, I wonder whether there is compact or proper ways of achieving the above?

Body:
You can use more-itertools to divide a list into N groups.

new_group = [[tuple(pair) + (group_id,) for pair in group_of_pairs]
             for group_id, group_of_pairs in enumerate(more_itertools.divide(ngroup, pair_var))]

Or you could also use numpy.array_split or numpy.split.
This is much faster when dealing with large data, but note that this method requires all values to be the same dtype.


问:
Using redis and node.js issue: why does redis.get return false?
I'm running a simple web app backed by node.js, and I'm trying to use redis to store some key-value pairs. All I do is run "node index.js" on the command line, and here's the first few lines of my index.js:

```<code>var app = require('express').createServer();
var io = require('socket.io').listen(app);

var redis = require('redis');
var redis_client = redis.createClient();
redis_client.set("hello", "world");
console.log(redis_client.get("hello"));
</code>```

However, all I get for redis_client.get("hello") instead of "world" is false. Why is it not returning "world"?

(And I am running the redis-server)

What's weird too is that the example code posted here runs fine, and produces the expected output. Is there something I'm doing incorrectly for simple set and get?

答:
Nowadays, Redis uses a promises API.

const redis = require("redis"); // 4.0.1
const redisClient = redis.createClient();

(async () => {
  await redisClient.connect();
  await redisClient.set("hello", "world");
  console.log(await redisClient.get("hello")); // => world
  await redisClient.quit();
})();
```

Body:
I'm running a simple web app backed by node.js, and I'm trying to use redis to store some key-value pairs. All I do is run "node index.js" on the command line, and here's the first few lines of my index.js:

var app = require('express').createServer();
var io = require('socket.io').listen(app);

var redis = require('redis');
var redis_client = redis.createClient();
redis_client.set("hello", "world");
console.log(redis_client.get("hello"));

However, all I get for redis_client.get("hello") instead of "world" is false. Why is it not returning "world"?

(And I am running the redis-server)

What's weird too is that the example code posted here runs fine, and produces the expected output. Is there something I'm doing incorrectly for simple set and get?


问:
Calculated column based on multiple conditions - comparing rows by category in Power BI Dax
I need to create the calculated column - IsImproved - in the following calculated table - tbl_QOL (screenshot below)

It should compare AvgQOL (another calculated column) by MetricDate for each Client (EHRClientFK)

If - for any particular EHRClientFK AvgQOL value where IsDateMax = 1 is higher than AvgQOL value for IsDateMin = 1, then IsImproved value = 1;  any other cases IsImproved = 0

For example:

EHRClientFK = 2666;  AvgQOL for the (highest(max) date=1) = 3.66;  3.66 value is not higher than 3.83, means IsImproved for EHRClientFK 2666 = 0

EHRClientFK = 3444;  AvgQOL for the (highest(max) date=1) = 3.5;   3.5 value IS HIGHER than 2, means  IsImproved for EHRClientFK 3444 = 1

All shown in the picture below

Applied the following code.
But it doesn't work correctly.
It puts 1 even if AvgQOL for IsDateMax = 1 is less than AvgQOL for IsDateMin = 1, while I expect 0 there - like it is for AvgQOL = 3.66 (for the bigger date - 5/13/2021)

```<code>enter
       IsImproved =
               var _DateRecent = QOL[IsDateMax]
               var _DateLatest = QOL[IsDateMin]

               var _max = calculate(max(QOL[AvgQOL]), FILTER(ALL('QOL'),  _DateRecent=1))
               var _min = calculate(min(QOL[AvgQOL]), FILTER(ALL('QOL'),  _DateLatest=1))
               var _min1 = calculate(max(QOL[AvgQOL]), FILTER(ALL('QOL'),  _DateRecent=0))
               var _min2 = calculate(min(QOL[AvgQOL]), FILTER(ALL('QOL'),  _DateRecent=1))

               return if(_max > _min || _max >_min1 || _max > _min2, 1, 0)
</code>```

I am super new to DAX, plz help!

答:
I'd prefer to use LOOKUPVALUE here:

```<code>VAR ClientFK = tbl_QOL[EHRClientFK]
VAR AvgQOLForMin =
    LOOKUPVALUE (
        tbl_QOL[AvgQOL],
        tbl_QOL[IsDateMin], 1,
        tbl_QOL[EHRClientFK], ClientFK
    )
VAR AvgQOLForMax =
    LOOKUPVALUE (
        tbl_QOL[AvgQOL],
        tbl_QOL[IsDateMax], 1,
        tbl_QOL[EHRClientFK], ClientFK
    )
RETURN
    0 + ( AvgQOLForMax > AvgQOLForMin )
</code>```

Body:
I need to create the calculated column - IsImproved - in the following calculated table - tbl_QOL (screenshot below)

It should compare AvgQOL (another calculated column) by MetricDate for each Client (EHRClientFK)

If - for any particular EHRClientFK AvgQOL value where IsDateMax = 1 is higher than AvgQOL value for IsDateMin = 1, then IsImproved value = 1;  any other cases IsImproved = 0

For example:

EHRClientFK = 2666;  AvgQOL for the (highest(max) date=1) = 3.66;  3.66 value is not higher than 3.83, means IsImproved for EHRClientFK 2666 = 0

EHRClientFK = 3444;  AvgQOL for the (highest(max) date=1) = 3.5;   3.5 value IS HIGHER than 2, means  IsImproved for EHRClientFK 3444 = 1

All shown in the picture below

Applied the following code.
But it doesn't work correctly.
It puts 1 even if AvgQOL for IsDateMax = 1 is less than AvgQOL for IsDateMin = 1, while I expect 0 there - like it is for AvgQOL = 3.66 (for the bigger date - 5/13/2021)

enter
       IsImproved =
               var _DateRecent = QOL[IsDateMax]
               var _DateLatest = QOL[IsDateMin]

               var _max = calculate(max(QOL[AvgQOL]), FILTER(ALL('QOL'),  _DateRecent=1))
               var _min = calculate(min(QOL[AvgQOL]), FILTER(ALL('QOL'),  _DateLatest=1))
               var _min1 = calculate(max(QOL[AvgQOL]), FILTER(ALL('QOL'),  _DateRecent=0))
               var _min2 = calculate(min(QOL[AvgQOL]), FILTER(ALL('QOL'),  _DateRecent=1))

               return if(_max > _min || _max >_min1 || _max > _min2, 1, 0)

I am super new to DAX, plz help!

Body:
I'd prefer to use LOOKUPVALUE here:

VAR ClientFK = tbl_QOL[EHRClientFK]
VAR AvgQOLForMin =
    LOOKUPVALUE (
        tbl_QOL[AvgQOL],
        tbl_QOL[IsDateMin], 1,
        tbl_QOL[EHRClientFK], ClientFK
    )
VAR AvgQOLForMax =
    LOOKUPVALUE (
        tbl_QOL[AvgQOL],
        tbl_QOL[IsDateMax], 1,
        tbl_QOL[EHRClientFK], ClientFK
    )
RETURN
    0 + ( AvgQOLForMax > AvgQOLForMin )


问:
Extract value from jsr223 sampler
enter image description here

enter image description here

How to extract maxValue_max from jsr223 sampler to the next request?
I see that the sampler determines the maximum value, how now to extract and use it?

答:
You don't need to extract, it's part of JMeter variables as you can see in Debug Sampler response

You can use it as ${maxValue_max} expect inside JSR223 script where you should use vars.get("maxValue_max") syntax

See how to reference a variable

Referencing a variable in a test element is done by bracketing the variable name with '${' and '}'.

Title: Extract value from jsr223 sampler


问:
Why is Numpy vstack not working in this function
I have an issue with np.vstack that has been tripping me up.

Initially I used the following block of code repeatedly (and successfully):

```<code>   dev_data_blurred = []

   # Apply kernel to dev_data
   for img in dev_data:
     blurred_img = apply_kernel(img, .5)
     if len(dev_data_blurred) > 0:
       dev_data_blurred = np.vstack([dev_data_blurred, blurred_img])
     else:
       dev_data_blurred.append(blurred_img)
</code>```

I decided to move this functionality to the following function with an example function call:

```<code>def get_blurred_data_struct(image_data, weight):
     data_blurred = []

     for img in image_data:
       blurred_img = apply_kernel(img, .5)
     if len(data_blurred) > 0:
       data_blurred = np.vstack([data_blurred, blurred_img])
     else:
       data_blurred.append(blurred_img)

     return data_blurred

dev_data_blurred = get_blurred_data_struct(dev_data, .5)
</code>```

For some reason the np.vstack does not seem to be working in my function. I have messed with it for a good hour now, and the function  consistently returns a single 1D array, instead of an np.array of shape 1000,784 ( which is what I expect and get if I just perform the top block outside of a function). Any ideas?

答:
It is an indentation issue.

     for img in image_data:
       blurred_img = apply_kernel(img, .5)
```
<p>This always writes apply_kernel(img, .5) into the same variable. Due to your code vstack will never be called. So what you end up with is getting back a list that contains a single image. What you actually want to return I guess is</p>
<pre class="lang-py prettyprint-override"><code>def get_blurred_data_struct(image_data, weight):
    return np.vstack([apply_kernel(img, .5) for img in image_data])
</code>```

Body:
I have an issue with np.vstack that has been tripping me up.

Initially I used the following block of code repeatedly (and successfully):

   dev_data_blurred = []

   # Apply kernel to dev_data
   for img in dev_data:
     blurred_img = apply_kernel(img, .5)
     if len(dev_data_blurred) > 0:
       dev_data_blurred = np.vstack([dev_data_blurred, blurred_img])
     else:
       dev_data_blurred.append(blurred_img)

I decided to move this functionality to the following function with an example function call:

def get_blurred_data_struct(image_data, weight):
     data_blurred = []

     for img in image_data:
       blurred_img = apply_kernel(img, .5)
     if len(data_blurred) > 0:
       data_blurred = np.vstack([data_blurred, blurred_img])
     else:
       data_blurred.append(blurred_img)

     return data_blurred

dev_data_blurred = get_blurred_data_struct(dev_data, .5)

For some reason the np.vstack does not seem to be working in my function. I have messed with it for a good hour now, and the function  consistently returns a single 1D array, instead of an np.array of shape 1000,784 ( which is what I expect and get if I just perform the top block outside of a function). Any ideas?

Body:
It is an indentation issue.

     for img in image_data:
       blurred_img = apply_kernel(img, .5)

This always writes apply_kernel(img, .5) into the same variable. Due to your code vstack will never be called. So what you end up with is getting back a list that contains a single image. What you actually want to return I guess is

def get_blurred_data_struct(image_data, weight):
    return np.vstack([apply_kernel(img, .5) for img in image_data])


问:
Retrieve company name with ticker symbol input, yahoo or google API
Just looking for a simple api return, where I can input a ticker symbol and receive the full company name:

ticker('MSFT')
will return
"Microsoft"

答:
For anyone wondering how to get the stock price of a company using its name rather than its symbol

```<code>import yfinance as yf

def getStock(search_term):
    results = []
    query = requests.get(f'https://yfapi.net/v6/finance/autocomplete?region=IN&lang=en&query={search_term}',
    headers={
        'accept': 'application/json',
        'X-API-KEY': 'API_KEY'
    })
    response = query.json()
    for i in response['ResultSet']['Result']:
        final = i['symbol']
        results.append(final)

    try:
        stock = yf.Ticker(results[0])
        price = stock.info["regularMarketPrice"]
        full_name = stock.info['longName']
        curreny = stock.info["currency"]
    except Exception as e:
        print('Something went wrong')

return f"The stock price of {full_name} is {price} {curreny}"

stock = input("Enter the company's name: ")
final = getStock(stock)
print(final)
</code>```

Output:

```<code>Enter the company's name: Apple
The stock price of Apple Inc. is 172.39 USD
</code>```

Body:
For anyone wondering how to get the stock price of a company using its name rather than its symbol

import yfinance as yf

def getStock(search_term):
    results = []
    query = requests.get(f'https://yfapi.net/v6/finance/autocomplete?region=IN&lang=en&query={search_term}',
    headers={
        'accept': 'application/json',
        'X-API-KEY': 'API_KEY'
    })
    response = query.json()
    for i in response['ResultSet']['Result']:
        final = i['symbol']
        results.append(final)

    try:
        stock = yf.Ticker(results[0])
        price = stock.info["regularMarketPrice"]
        full_name = stock.info['longName']
        curreny = stock.info["currency"]
    except Exception as e:
        print('Something went wrong')

return f"The stock price of {full_name} is {price} {curreny}"

stock = input("Enter the company's name: ")
final = getStock(stock)
print(final)

Output:

Enter the company's name: Apple
The stock price of Apple Inc. is 172.39 USD


问:
Selenium: How to deal with web elements that get hidden when you try to inspect them? Python 3.x related
I'm about to finish developing an automated program on Python and the only thing that's stopping me it's a web element that gets immediately hidden when I try to inspect it from an OpenSea page (can't share the link here since it requires to be connected to my wallet):

So far, I have only managed to get the XPATH and the CSS_SELECTOR of this problematic element (div#tippy-298) which is the following:

```<code>button_problematic_xpath = driver.find_element(By.XPATH, '//*[@id="tippy-298"]')
button_problematic_css = driver.find_element(By.CSS_SELECTOR, '#tippy-298')
</code>```

But what I need is to get the XPATH or CSS_SELECTOR of the Web Elements that button_problematic_css contains, more specifically the "Starting" and "Ending" Textboxes :

Also, just in case, the element that's on top of button_problematic_css is called "Duration", here's its XPATH:

```<code>button_duration = driver.find_element(By.XPATH, '//*[@id="duration"]').click #after clicked it deploys div#tippy-298 element
</code>```

I was wondering if there could be any method to force the visibility of this button_problematic_css using the Chrome Console in the Inspection of Web Elements, or by using an specific method from Selenium on Python3.x to inmediately download all of the web elements this page has right after button_problematic_css is visible.

What I have tried so far is to manually inspect the element, by pressing Ctrl + Shift + C and and then clicking the elements contained in button_problematic_css which just ends up hiding this element before even clicking its content, the same happens when trying to display the contents of this element in the DOM of this page, it just dissapears.

I just wish my program could be capable of editing the dates in the "Starting" and "Ending" Textboxes

答:
I guess you need to click the button to show the element. why did I guess? you need to show the url

or u can also try this code:

```<code>clickmore=WebDriverWait(driver, 2).until(EC.element_to_be_clickable((By.XPATH, 'blabalabla')))
self.driver.execute_script("arguments[0].click();", clickmore)
button_duration = driver.find_element(By.XPATH, '//*[@id="duration"]').click()
</code>```

Body:
I'm about to finish developing an automated program on Python and the only thing that's stopping me it's a web element that gets immediately hidden when I try to inspect it from an OpenSea page (can't share the link here since it requires to be connected to my wallet):

So far, I have only managed to get the XPATH and the CSS_SELECTOR of this problematic element (div#tippy-298) which is the following:

button_problematic_xpath = driver.find_element(By.XPATH, '//*[@id="tippy-298"]')
button_problematic_css = driver.find_element(By.CSS_SELECTOR, '#tippy-298')

But what I need is to get the XPATH or CSS_SELECTOR of the Web Elements that button_problematic_css contains, more specifically the "Starting" and "Ending" Textboxes :

Also, just in case, the element that's on top of button_problematic_css is called "Duration", here's its XPATH:

button_duration = driver.find_element(By.XPATH, '//*[@id="duration"]').click #after clicked it deploys div#tippy-298 element

I was wondering if there could be any method to force the visibility of this button_problematic_css using the Chrome Console in the Inspection of Web Elements, or by using an specific method from Selenium on Python3.x to inmediately download all of the web elements this page has right after button_problematic_css is visible.

What I have tried so far is to manually inspect the element, by pressing Ctrl + Shift + C and and then clicking the elements contained in button_problematic_css which just ends up hiding this element before even clicking its content, the same happens when trying to display the contents of this element in the DOM of this page, it just dissapears.

I just wish my program could be capable of editing the dates in the "Starting" and "Ending" Textboxes

Body:
I guess you need to click the button to show the element. why did I guess? you need to show the url

or u can also try this code:

clickmore=WebDriverWait(driver, 2).until(EC.element_to_be_clickable((By.XPATH, 'blabalabla')))
self.driver.execute_script("arguments[0].click();", clickmore)
button_duration = driver.find_element(By.XPATH, '//*[@id="duration"]').click()


答:
Need an interactive enviroment.

Right-click in the code editor and select Run current file in interactive Window.

Install the necessary package, then you can get the code result instantly as in the terminal.

Title: How to use len() on Visual Studio Code?


问:
https://www.example.com and https://example.com socket.io connection problem
How do I get both https://example.com and https://www.example.com for endpoints to connect?
socket.io connect no problem at htttps://example.com
but not https://www.example.com

my server looks like

```<code>const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "https://www.example.com:3000",
    methods: ["GET", "POST"],
    allowedHeaders: ["my-custom-header"],
    credentials: true
  }});
</code>```

and my client endpoint looks like this

```<code>const ENDPOINT = 'https://example.com/';
</code>```

答:
Configure your DNS to point both example.com and www.example.com to the same host IP address and then support both domains with your cors configuration. Then, either URL will go to the same host.

You can avoid cors entirely if you configure socket.io to start immediately with a webSocket, not with the http polling that it usually starts with.  You can do that in the client by adding the transports: ['websocket'] option to the client connect.

And, your custom header was probably blocking CORs and requiring pre-flight permission. CORs has two levels, simple and not-simple. When you add a custom header, you force CORs into the not-simple route where it requires preflight which is probably more than the built-in socketio cors features will handle.

Body:
How do I get both https://example.com and https://www.example.com for endpoints to connect?
socket.io connect no problem at htttps://example.com
but not https://www.example.com

my server looks like

const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "https://www.example.com:3000",
    methods: ["GET", "POST"],
    allowedHeaders: ["my-custom-header"],
    credentials: true
  }});

and my client endpoint looks like this

const ENDPOINT = 'https://example.com/';


问:
How can I stop React page to re-render?
I am using fetch to get data from API. I am using useEffect for page to stop rerender. But its not working

```<code>  const [load, setLoad] = useState(false);

 if (load) {
    return <h2>Progress</h2>;
  }

  const fetchPicth = async () => {
    setLoad(true);
    const response = await fetch(url);
    const data = await response.json();
    setPicth(data.pink);
  };

  useEffect(() => {
     setLoad(false);
  }, [fetchPicth]);
</code>```

答:
Remove the fetchPicth from the dependency array. If you'd like to set load to false you can do it like this:

```<code>const [load, setLoad] = useState(false);

 if (load) {
    return <h2>Progress</h2>;
  }

  const fetchPicth = async () => {
    setLoad(true);
    const response = await fetch(url);
    const data = await response.json();
    setPicth(data.pink);
    setLoad(false)
  };

  useEffect(() => {
     fetchPicth();
  }, []);
</code>```

Using the code above will only fetch the data from the API only once i.e; when the component is mounted.

Title: How can I stop React page to re-render?

Body:
I am using fetch to get data from API. I am using useEffect for page to stop rerender. But its not working

  const [load, setLoad] = useState(false);

 if (load) {
    return
Progress
;
  }

  const fetchPicth = async () => {
    setLoad(true);
    const response = await fetch(url);
    const data = await response.json();
    setPicth(data.pink);
  };

  useEffect(() => {
     setLoad(false);
  }, [fetchPicth]);

Body:
Remove the fetchPicth from the dependency array. If you'd like to set load to false you can do it like this:

const [load, setLoad] = useState(false);

 if (load) {
    return <h2>Progress</h2>;
  }

  const fetchPicth = async () => {
    setLoad(true);
    const response = await fetch(url);
    const data = await response.json();
    setPicth(data.pink);
    setLoad(false)
  };

  useEffect(() => {
     fetchPicth();
  }, []);

Using the code above will only fetch the data from the API only once i.e; when the component is mounted.


问:
How can I, scrape data from a Javascript Content of a website?
Actually, I am trying to fetch the content from the Product Description from the Nykaa Website.

URL:- https://www.nykaa.com/nykaa-skinshield-matte-foundation/p/460512?productId=460512&pps=1&skuId=460502

This is the URL, and in the section of the Product description, clicking upon the 'Read More' button, at the end there is some text.

The Text which, I want to extract is :

Explore the entire range of Foundation available on Nykaa. Shop more
Nykaa Cosmetics products here.You can browse through the complete
world of Nykaa Cosmetics Foundation . Alternatively, you can also find
many more products from the Nykaa SkinShield Anti-Pollution Matte
Foundation range.

Expiry Date: 15 February 2024

Country of Origin: India

Name of Mfg / Importer / Brand: FSN E-commerce Ventures Pvt Ltd

Address of Mfg / Importer / Brand: 104 Vasan Udyog Bhavan Sun Mill
Compound Senapati Bapat Marg, Lower Parel, Mumbai City Maharashtra -
400013

After inspecting the page, when I, 'disable the javascript' all the content from 'product description' vanishes off. It means the content is loading dynamically with the help of Javascript.

I have used 'selenium' for this purpose. And This, is what I have tried.

```<code>from msilib.schema import Error
from tkinter import ON
from turtle import goto
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import numpy as np
from random import randint
import pandas as pd
import requests
import csv

browser = webdriver.Chrome(
    r'C:\Users\paart\.wdm\drivers\chromedriver\win32\97.0.4692.71\chromedriver.exe')

browser.maximize_window()  # For maximizing window
browser.implicitly_wait(20)  # gives an implicit wait for 20 seconds

browser.get(
    "https://www.nykaa.com/nykaa-skinshield-matte-foundation/p/460512?productId=460512&pps=1&skuId=460502")

# Creates "load more" button object.
browser.implicitly_wait(20)
loadMore = browser.find_element_by_xpath(xpath="/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]")

loadMore.click()
browser.implicitly_wait(20)

desc_data = browser.find_elements_by_class_name('content-details')

for desc in desc_data:
    para_details = browser.find_element_by_xpath(
        './/*[@id="content-details"]/p[1]').text
    extra_details = browser.find_elements_by_xpath(
        './/*[@id="content-details"]/p[2]', './/*[@id="content-details"]/p[3]', './/*[@id="content-details"]/p[4]', './/*[@id="content-details"]/p[5]').text
    print(para_details, extra_details)
</code>```

And this, is the output which is displaying.

```<code>PS E:\Web Scraping - Nykaa> python -u "e:\Web Scraping - Nykaa\scrape_nykaa_final.py"
e:\Web Scraping - Nykaa\scrape_nykaa_final.py:16: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  browser = webdriver.Chrome(

DevTools listening on ws://127.0.0.1:1033/devtools/browser/097c0e11-6f2c-4742-a2b5-cd05bee72661
e:\Web Scraping - Nykaa\scrape_nykaa_final.py:28: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead
  loadMore = browser.find_element_by_xpath(
[9312:4972:0206/110327.883:ERROR:ssl_client_socket_impl.cc(996)] handshake failed; returned -1, SSL error code 1, net_error -101
[9312:4972:0206/110328.019:ERROR:ssl_client_socket_impl.cc(996)] handshake failed; returned -1, SSL error code 1, net_error -101
Traceback (most recent call last):
  File "e:\Web Scraping - Nykaa\scrape_nykaa_final.py", line 28, in <module>
    loadMore = browser.find_element_by_xpath(
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 520, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1244, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]"}
  (Session info: chrome=97.0.4692.99)
Stacktrace:
Backtrace:
        Ordinal0 [0x00FDFDC3+2555331]
        Ordinal0 [0x00F777F1+2127857]
        Ordinal0 [0x00E72E08+1060360]
        Ordinal0 [0x00E9E49E+1238174]
        Ordinal0 [0x00E9E69B+1238683]
        Ordinal0 [0x00EC9252+1413714]
        Ordinal0 [0x00EB7B54+1342292]
        Ordinal0 [0x00EC75FA+1406458]
        Ordinal0 [0x00EB7976+1341814]
        Ordinal0 [0x00E936B6+1193654]
        Ordinal0 [0x00E94546+1197382]
        GetHandleVerifier [0x01179622+1619522]
        GetHandleVerifier [0x0122882C+2336844]
        GetHandleVerifier [0x010723E1+541697]
        GetHandleVerifier [0x01071443+537699]
        Ordinal0 [0x00F7D18E+2150798]
        Ordinal0 [0x00F81518+2168088]
        Ordinal0 [0x00F81660+2168416]
        Ordinal0 [0x00F8B330+2208560]
        BaseThreadInitThunk [0x76C9FA29+25]
        RtlGetAppContainerNamedObjectPath [0x77337A9E+286]
        RtlGetAppContainerNamedObjectPath [0x77337A6E+238]
</code>```

Please, anyone help me getting this issue resolved, or any another specific piece of the code to write, which I am missing to fetch the text content from Product description. It would be a big help.

Thanks .

答:
You can do something like this

```<code>from msilib.schema import Error
from tkinter import ON
from turtle import goto
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import numpy as np
from random import randint
import pandas as pd
import requests
import csv

browser = webdriver.Chrome(
r'C:\Users\paart\.wdm\drivers\chromedriver\win32\97.0.4692.71\chromedriver.exe')

browser.maximize_window()  # For maximizing window
browser.implicitly_wait(20)  # gives an implicit wait for 20 seconds

browser.get(
    "https://www.nykaa.com/nykaa-skinshield-matte-foundation/p/460512?productId=460512&pps=1&skuId=460502")

# Creates "load more" button object.
browser.implicitly_wait(20)
loadMore = browser.find_element_by_xpath("/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]")

loadMore.click()
browser.implicitly_wait(20)

desc_data = browser.find_elements_by_id('content-details')

for desc in desc_data:
    para_details = browser.find_element_by_xpath('//*[@id="content-details"]/p[1]').text
    expiry = browser.find_element_by_xpath('//*[@id="content-details"]/p[2]').text
    country = browser.find_element_by_xpath('//*[@id="content-details"]/p[3]').text
    importer = browser.find_element_by_xpath('//*[@id="content-details"]/p[4]').text
    address = browser.find_element_by_xpath('//*[@id="content-details"]/p[5]').text
    print(para_details, country, importer, address)
</code>```

For the desc_data you were looking for a class name with that string, when there isn't one on the page it is actually an id tag with that string.

inside the for loop you had inserted a bunch of xpaths inside of find_elements_by_xpath() which only takes one xpath to an element.

Body:
Actually, I am trying to fetch the content from the Product Description from the Nykaa Website.

URL:- https://www.nykaa.com/nykaa-skinshield-matte-foundation/p/460512?productId=460512&pps=1&skuId=460502

This is the URL, and in the section of the Product description, clicking upon the 'Read More' button, at the end there is some text.

The Text which, I want to extract is :

Explore the entire range of Foundation available on Nykaa. Shop more
Nykaa Cosmetics products here.You can browse through the complete
world of Nykaa Cosmetics Foundation . Alternatively, you can also find
many more products from the Nykaa SkinShield Anti-Pollution Matte
Foundation range.

Expiry Date: 15 February 2024

Country of Origin: India

Name of Mfg / Importer / Brand: FSN E-commerce Ventures Pvt Ltd

Address of Mfg / Importer / Brand: 104 Vasan Udyog Bhavan Sun Mill
Compound Senapati Bapat Marg, Lower Parel, Mumbai City Maharashtra -
400013

After inspecting the page, when I, 'disable the javascript' all the content from 'product description' vanishes off. It means the content is loading dynamically with the help of Javascript.

I have used 'selenium' for this purpose. And This, is what I have tried.

from msilib.schema import Error
from tkinter import ON
from turtle import goto
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import numpy as np
from random import randint
import pandas as pd
import requests
import csv

browser = webdriver.Chrome(
    r'C:\Users\paart\.wdm\drivers\chromedriver\win32\97.0.4692.71\chromedriver.exe')

browser.maximize_window()  # For maximizing window
browser.implicitly_wait(20)  # gives an implicit wait for 20 seconds

browser.get(
    "https://www.nykaa.com/nykaa-skinshield-matte-foundation/p/460512?productId=460512&pps=1&skuId=460502")

# Creates "load more" button object.
browser.implicitly_wait(20)
loadMore = browser.find_element_by_xpath(xpath="/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]")

loadMore.click()
browser.implicitly_wait(20)

desc_data = browser.find_elements_by_class_name('content-details')

for desc in desc_data:
    para_details = browser.find_element_by_xpath(
        './/*[@id="content-details"]/p[1]').text
    extra_details = browser.find_elements_by_xpath(
        './/*[@id="content-details"]/p[2]', './/*[@id="content-details"]/p[3]', './/*[@id="content-details"]/p[4]', './/*[@id="content-details"]/p[5]').text
    print(para_details, extra_details)

And this, is the output which is displaying.

PS E:\Web Scraping - Nykaa> python -u "e:\Web Scraping - Nykaa\scrape_nykaa_final.py"
e:\Web Scraping - Nykaa\scrape_nykaa_final.py:16: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  browser = webdriver.Chrome(

DevTools listening on ws://127.0.0.1:1033/devtools/browser/097c0e11-6f2c-4742-a2b5-cd05bee72661
e:\Web Scraping - Nykaa\scrape_nykaa_final.py:28: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead
  loadMore = browser.find_element_by_xpath(
[9312:4972:0206/110327.883:ERROR:ssl_client_socket_impl.cc(996)] handshake failed; returned -1, SSL error code 1, net_error -101
[9312:4972:0206/110328.019:ERROR:ssl_client_socket_impl.cc(996)] handshake failed; returned -1, SSL error code 1, net_error -101
Traceback (most recent call last):
  File "e:\Web Scraping - Nykaa\scrape_nykaa_final.py", line 28, in <module>
    loadMore = browser.find_element_by_xpath(
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 520, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1244, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]"}
  (Session info: chrome=97.0.4692.99)
Stacktrace:
Backtrace:
        Ordinal0 [0x00FDFDC3+2555331]
        Ordinal0 [0x00F777F1+2127857]
        Ordinal0 [0x00E72E08+1060360]
        Ordinal0 [0x00E9E49E+1238174]
        Ordinal0 [0x00E9E69B+1238683]
        Ordinal0 [0x00EC9252+1413714]
        Ordinal0 [0x00EB7B54+1342292]
        Ordinal0 [0x00EC75FA+1406458]
        Ordinal0 [0x00EB7976+1341814]
        Ordinal0 [0x00E936B6+1193654]
        Ordinal0 [0x00E94546+1197382]
        GetHandleVerifier [0x01179622+1619522]
        GetHandleVerifier [0x0122882C+2336844]
        GetHandleVerifier [0x010723E1+541697]
        GetHandleVerifier [0x01071443+537699]
        Ordinal0 [0x00F7D18E+2150798]
        Ordinal0 [0x00F81518+2168088]
        Ordinal0 [0x00F81660+2168416]
        Ordinal0 [0x00F8B330+2208560]
        BaseThreadInitThunk [0x76C9FA29+25]
        RtlGetAppContainerNamedObjectPath [0x77337A9E+286]
        RtlGetAppContainerNamedObjectPath [0x77337A6E+238]

Please, anyone help me getting this issue resolved, or any another specific piece of the code to write, which I am missing to fetch the text content from Product description. It would be a big help.

Thanks .

Body:
You can do something like this

from msilib.schema import Error
from tkinter import ON
from turtle import goto
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import numpy as np
from random import randint
import pandas as pd
import requests
import csv

browser = webdriver.Chrome(
r'C:\Users\paart\.wdm\drivers\chromedriver\win32\97.0.4692.71\chromedriver.exe')

browser.maximize_window()  # For maximizing window
browser.implicitly_wait(20)  # gives an implicit wait for 20 seconds

browser.get(
    "https://www.nykaa.com/nykaa-skinshield-matte-foundation/p/460512?productId=460512&pps=1&skuId=460502")

# Creates "load more" button object.
browser.implicitly_wait(20)
loadMore = browser.find_element_by_xpath("/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]")

loadMore.click()
browser.implicitly_wait(20)

desc_data = browser.find_elements_by_id('content-details')

for desc in desc_data:
    para_details = browser.find_element_by_xpath('//*[@id="content-details"]/p[1]').text
    expiry = browser.find_element_by_xpath('//*[@id="content-details"]/p[2]').text
    country = browser.find_element_by_xpath('//*[@id="content-details"]/p[3]').text
    importer = browser.find_element_by_xpath('//*[@id="content-details"]/p[4]').text
    address = browser.find_element_by_xpath('//*[@id="content-details"]/p[5]').text
    print(para_details, country, importer, address)

For the desc_data you were looking for a class name with that string, when there isn't one on the page it is actually an id tag with that string.

inside the for loop you had inserted a bunch of xpaths inside of find_elements_by_xpath() which only takes one xpath to an element.


问:
Locating rows from dataframe with list of words
How can I select rows from a dataframe using a list of words as a reference?

E.g. I have a dataframe, df_business, and each item in the last column is a string containing comma-separated categories, like this:

```<code>categories: "Restaurants, Burgers, Coffee & Tea, Fast Food, Food"
</code>```

I tried this, but it only gives me the rows for the businesses containing ONLY the word coffee in their categories:

```<code>bus_int = df_business.loc[(df_business['categories'].isin(['Coffee']))]
</code>```

How can I get the businesses containing my word even when it's present among others, as shown above?

答:
Just use - .isin(List_name/the string you want)

Example -

```<code>list = ['apple', 'mango', 'banana'] #creating a list

df[df['Fruits_name'].isin(list)]
# this will find all the rows with this 3 fruit name
</code>```

Body:
How can I select rows from a dataframe using a list of words as a reference?

E.g. I have a dataframe, df_business, and each item in the last column is a string containing comma-separated categories, like this:

categories: "Restaurants, Burgers, Coffee & Tea, Fast Food, Food"

I tried this, but it only gives me the rows for the businesses containing ONLY the word coffee in their categories:

bus_int = df_business.loc[(df_business['categories'].isin(['Coffee']))]

How can I get the businesses containing my word even when it's present among others, as shown above?

Body:
Just use - .isin(List_name/the string you want)

Example -

list = ['apple', 'mango', 'banana'] #creating a list

df[df['Fruits_name'].isin(list)]
# this will find all the rows with this 3 fruit name


问:
Python List scraping
I have a txt file containing professors', names, ids, where they work, and titles, separated by a comma. I only want to get the names and discard the rest. Is it possible?

for example:

```<code>12717, PROFESÖR, ABDULLAH ERYAVUZ, AFYON KOCATEPE ÜNİVERSİTESİ/VETERİNER FAKÜLTESİ/VETERİNER HEKİMLİĞİ TEMEL BİLİMLERİ BÖLÜMÜ/VETERİNERLİK FİZYOLOJİSİ ANABİLİM DALI/, Sağlık Bilimleri Temel Alanı, Veterinerlik Fizyolojisi, 1E246277D3E01142
106459, PROFESÖR, ABDULLAH KESKİN, AFYON KOCATEPE ÜNİVERSİTESİ/İKTİSADİ VE İDARİ BİLİMLER FAKÜLTESİ/İKTİSAT BÖLÜMÜ/İKTİSAT TEORİSİ ANABİLİM DALI/, Sosyal-Beşeri ve İdari Bilimler Temel Alanı, Makro İktisat, Gelişme Ekonomisi - Makro ; Büyüme ; Para-Banka, akeskin[at]aku.edu.tr, C771324515A1023A
53410, PROFESÖR, ABDURRAHMAN KARABULUT, AFYON KOCATEPE ÜNİVERSİTESİ/TEKNOLOJİ FAKÜLTESİ/MAKİNE MÜHENDİSLİĞİ BÖLÜMÜ/MAKİNE MÜHENDİSLİĞİ ANABİLİM DALI/, Mühendislik Temel Alanı, Makine Mühendisliği, Makine Teorisi ve Dinamiği ; Makine Tasarımı ve Makine Elemanları ; Mekanik Titretişimler ve Gürültü, akarabulut[at]aku.edu.tr, C4DEB0A8828D1E78
57393, PROFESÖR, ABDURRAHMAN FATİH FİDAN, AFYON KOCATEPE ÜNİVERSİTESİ/VETERİNER FAKÜLTESİ/VETERİNER HEKİMLİĞİ TEMEL BİLİMLERİ BÖLÜMÜ/VETERİNERLİK BİYOKİMYASI ANABİLİM DALI/, Sağlık Bilimleri Temel Alanı, Veterinerlik Biyokimyası, ffidan[at]aku.edu.tr, FB9466184DC835D3
</code>```

答:
As You said, you have a txt file containing professors info. 1st we opened that txt file. then getting every lines from txt file as list. then we used a for loop to fetch every item from that list. then we use if condition to ignore blank lines. the continue used in for and while loop to bypass current loop and continue next one. then we converting that data into list separated with a comma and a space and storing that into a variable. the name is in 3rd index of the list, but in programming language, number starts from 0. so it will be index no 2. and lastly printing that name

Try this code:

```<code>with open('test.txt', 'r') as file: # Opening File
    lines=file.readlines() # Getting data from per lines
    for data in lines: # Getting Name from that data
        if data=='\n':
            continue # if any lines are empty, ignore them
        name=data.split(', ')[2] # Converting that data into list (Every info separated with a comma and space ", ")
        print(name) # Printing that Name
    file.close()
</code>```

The Output:

```<code>ABDULLAH ERYAVUZ
ABDULLAH KESKÄ°N
ABDURRAHMAN KARABULUT
ABDURRAHMAN FATÄ°H FÄ°DAN
</code>```

Title: Python List scraping

Body:
I have a txt file containing professors', names, ids, where they work, and titles, separated by a comma. I only want to get the names and discard the rest. Is it possible?

for example:

12717, PROFESÖR, ABDULLAH ERYAVUZ, AFYON KOCATEPE ÜNİVERSİTESİ/VETERİNER FAKÜLTESİ/VETERİNER HEKİMLİĞİ TEMEL BİLİMLERİ BÖLÜMÜ/VETERİNERLİK FİZYOLOJİSİ ANABİLİM DALI/, Sağlık Bilimleri Temel Alanı, Veterinerlik Fizyolojisi, 1E246277D3E01142
106459, PROFESÖR, ABDULLAH KESKİN, AFYON KOCATEPE ÜNİVERSİTESİ/İKTİSADİ VE İDARİ BİLİMLER FAKÜLTESİ/İKTİSAT BÖLÜMÜ/İKTİSAT TEORİSİ ANABİLİM DALI/, Sosyal-Beşeri ve İdari Bilimler Temel Alanı, Makro İktisat, Gelişme Ekonomisi - Makro ; Büyüme ; Para-Banka, akeskin[at]aku.edu.tr, C771324515A1023A
53410, PROFESÖR, ABDURRAHMAN KARABULUT, AFYON KOCATEPE ÜNİVERSİTESİ/TEKNOLOJİ FAKÜLTESİ/MAKİNE MÜHENDİSLİĞİ BÖLÜMÜ/MAKİNE MÜHENDİSLİĞİ ANABİLİM DALI/, Mühendislik Temel Alanı, Makine Mühendisliği, Makine Teorisi ve Dinamiği ; Makine Tasarımı ve Makine Elemanları ; Mekanik Titretişimler ve Gürültü, akarabulut[at]aku.edu.tr, C4DEB0A8828D1E78
57393, PROFESÖR, ABDURRAHMAN FATİH FİDAN, AFYON KOCATEPE ÜNİVERSİTESİ/VETERİNER FAKÜLTESİ/VETERİNER HEKİMLİĞİ TEMEL BİLİMLERİ BÖLÜMÜ/VETERİNERLİK BİYOKİMYASI ANABİLİM DALI/, Sağlık Bilimleri Temel Alanı, Veterinerlik Biyokimyası, ffidan[at]aku.edu.tr, FB9466184DC835D3

Body:
As You said, you have a txt file containing professors info. 1st we opened that txt file. then getting every lines from txt file as list. then we used a for loop to fetch every item from that list. then we use if condition to ignore blank lines. the continue used in for and while loop to bypass current loop and continue next one. then we converting that data into list separated with a comma and a space and storing that into a variable. the name is in 3rd index of the list, but in programming language, number starts from 0. so it will be index no 2. and lastly printing that name

Try this code:

with open('test.txt', 'r') as file: # Opening File
    lines=file.readlines() # Getting data from per lines
    for data in lines: # Getting Name from that data
        if data=='\n':
            continue # if any lines are empty, ignore them
        name=data.split(', ')[2] # Converting that data into list (Every info separated with a comma and space ", ")
        print(name) # Printing that Name
    file.close()

The Output:

ABDULLAH ERYAVUZ
ABDULLAH KESKÄ°N
ABDURRAHMAN KARABULUT
ABDURRAHMAN FATÄ°H FÄ°DAN


问:
Why is @typescript-eslint/parser including files outside of those configured in my tsconfig.json?
I am getting the error: -

```<code>Parsing error: "parserOptions.project" has been set for u/typescript-eslint/parser.

The file does not match your project config: .eslintrc.js.

The file must be included in at least one of the projects provided.
</code>```

IDE - WebStorm 20.1.1

Project structure: -

```<code>node_modules

src

--- testfile.js

.eslintrc.js

.prettierrc.js

baseeslint.js

package.json

tsconfig.json
</code>```

.eslintrc.js: -

```<code>module.exports = {
extends: ['./baseeslint'],
parserOptions: {
project: './tsconfig.json'
},
rules: {}
}
</code>```

baseeslint.js: -

```<code>module.exports = {

parser: '@typescript-eslint/parser'

}
</code>```

tsconfig.json: -

```<code>{

"include": [

"/src/**/*.ts",

"/src/**/*.tsx"

],

"exclude": ["node_modules"],

"compilerOptions": {

"outDir": "./lib",

"types": ["styled-components", "react", "@types/react-router-dom", "reactstrap"]

}

}
</code>```

I have absolutely no idea why this is happening? I would assume it would ignore files in the root, especially with include specified in my tsconfg.json?

Any help would be greatly appreciated.

EDIT: -

My solution, should it help others...

I added the ignorePatterns configuration to my .eslintrc.js file: -

```<code>module.exports = {
  extends: ["mycustom/eslint-config"],
  parserOptions: {
    project: './tsconfig.json'
  },
  ignorePatterns: ["/*.*"],
  rules: {}
}
</code>```

This can also be done via .eslintignore (see Anton Bessonov's response below).

Another thing relating to this which maybe of use to others here is the VScode config I used (I switched from WebStorm to VSCode after posting the original question). I am a big fan of running eslint fix on save but I do not want it attempting to do this with all files. My project files (and only my project files) are all .ts/.tsx. The options below in settings.json allow fix on save without it including every file in my repo: -

```<code>{
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
    },
    "eslint.probe": [
        "typescript",
        "typescriptreact"
    ],
}
</code>```

If eslint.probe is not specified, it defaults to: -

["javascript", "javascriptreact", "typescript", "typescriptreact", "html", "vue"]

More about the VSCode ESLint extension settings can be found here.

答:
Just to build off the accepted answer, something I found helpful for me was that, by default, hidden files aren't captured by globs.

To fix this, you could do some combination of this (depending on what your shell environment supports):

"include": [
    "./**/*", // All non-hidden files at any directory level
    "./**/.*", // Hidden dotfiles like .eslintrc.js at any level
    "./**/.*.[tj]s?(x)" // All hidden TS/JS dotfiles
]
```

Body:
I am getting the error: -

Parsing error: "parserOptions.project" has been set for u/typescript-eslint/parser.

The file does not match your project config: .eslintrc.js.

The file must be included in at least one of the projects provided.

IDE - WebStorm 20.1.1

Project structure: -

node_modules

src

--- testfile.js

.eslintrc.js

.prettierrc.js

baseeslint.js

package.json

tsconfig.json

.eslintrc.js: -

module.exports = {
extends: ['./baseeslint'],
parserOptions: {
project: './tsconfig.json'
},
rules: {}
}

baseeslint.js: -

module.exports = {

parser: '@typescript-eslint/parser'

}

tsconfig.json: -

{

"include": [

"/src/**/*.ts",

"/src/**/*.tsx"

],

"exclude": ["node_modules"],

"compilerOptions": {

"outDir": "./lib",

"types": ["styled-components", "react", "@types/react-router-dom", "reactstrap"]

}

}

I have absolutely no idea why this is happening? I would assume it would ignore files in the root, especially with include specified in my tsconfg.json?

Any help would be greatly appreciated.

EDIT: -

My solution, should it help others...

I added the ignorePatterns configuration to my .eslintrc.js file: -

module.exports = {
  extends: ["mycustom/eslint-config"],
  parserOptions: {
    project: './tsconfig.json'
  },
  ignorePatterns: ["/*.*"],
  rules: {}
}

This can also be done via .eslintignore (see Anton Bessonov's response below).

Another thing relating to this which maybe of use to others here is the VScode config I used (I switched from WebStorm to VSCode after posting the original question). I am a big fan of running eslint fix on save but I do not want it attempting to do this with all files. My project files (and only my project files) are all .ts/.tsx. The options below in settings.json allow fix on save without it including every file in my repo: -

{
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
    },
    "eslint.probe": [
        "typescript",
        "typescriptreact"
    ],
}

If eslint.probe is not specified, it defaults to: -

["javascript", "javascriptreact", "typescript", "typescriptreact", "html", "vue"]

More about the VSCode ESLint extension settings can be found here.


问:
How can you get the return value of a Windows thread?
I was just wondering if it is possible (and if so, how) to get the return value of a thread in C++ (Windows). I have several threads, and I use WaitForMultipleObjects(...) on them. This waits until a thread is done, and returns the index of said thread, and all is well. However, I want to be able to obtain the return value of the thread that finished using its handle.

For example:

```<code>DWORD WINAPI Thread1(void *parameter){
    ...
    if(...) return 0;
    else return -1;
}

DWORD WINAPI Thread2(void *parameter){
    ...
    if(...) return 1;
    else return 0;
}

int main(){
    HANDLE t1 = CreateThread(0, 0, Thread1, NULL, 0, 0);
    HANDLE t2 = CreateThread(0, 0, Thread2, NULL, 0, 0);
    HANDLE *threads = new HANDLE[2];
    threads[0] = t1;
    threads[1] = t2;
    int result = WaitForMultipleObjects(2, threads, false, INFINITE);
    if(result == 0){
        //get the threads value here:
        int retVal = SomeFunction(t1); //What is SomeFunction?
    }
    ...
}
</code>```

I have tried to use GetExitCodeThread(thread) but I'm assuming this returns a system exit code, as it always gives me a very strange integer. Does anyone know a way, or a workaround?

答: you need to check for STILL_ACTIVE for the values one of these threads may still be active</p>

Body:
I was just wondering if it is possible (and if so, how) to get the return value of a thread in C++ (Windows). I have several threads, and I use WaitForMultipleObjects(...) on them. This waits until a thread is done, and returns the index of said thread, and all is well. However, I want to be able to obtain the return value of the thread that finished using its handle.

For example:

DWORD WINAPI Thread1(void *parameter){
    ...
    if(...) return 0;
    else return -1;
}

DWORD WINAPI Thread2(void *parameter){
    ...
    if(...) return 1;
    else return 0;
}

int main(){
    HANDLE t1 = CreateThread(0, 0, Thread1, NULL, 0, 0);
    HANDLE t2 = CreateThread(0, 0, Thread2, NULL, 0, 0);
    HANDLE *threads = new HANDLE[2];
    threads[0] = t1;
    threads[1] = t2;
    int result = WaitForMultipleObjects(2, threads, false, INFINITE);
    if(result == 0){
        //get the threads value here:
        int retVal = SomeFunction(t1); //What is SomeFunction?
    }
    ...
}

I have tried to use GetExitCodeThread(thread) but I'm assuming this returns a system exit code, as it always gives me a very strange integer. Does anyone know a way, or a workaround?


问:
Can't add right_action_items to KivyMD Toolbar
I'm trying to add 2 buttons to my MDToolbar, which would normally use the property right_action_items. My toolbar code looks like this:

```<code>        self.main_toolbar = MDToolbar(
        title = "Home",
        right_action_items = [["import", lambda args: print("import pressed")],["export", lambda args: print("export pressed")]],
        pos_hint = {"top": 1}
    )z

    self.smain.add_widget(self.main_toolbar)
</code>```

self.smain is my screen variable.

The error I'm getting says there is a KeyError with "right_actions" somewhere in the kivymd module. There isn't any reference to my code in the error except it saying that the error was from my MDToolbar

Minimal reproduceable sample:

```<code>from kivymd.app import MDApp
from kivymd.uix.screen import MDScreen
from kivymd.uix.toolbar import MDToolbar

class MyApp(MDApp):
    def build(self):
        screen = MDScreen()

        screen.add_widget(MDToolbar(
            title = "Placeholder",
            right_action_items = [["import", lambda x: print("import clicked")], ["export", lambda x: print("export clicked")]]
        ))

        return screen

MyApp().run()
</code>```

答:
Actually you have a little thing to do with this problem (the problem is infact there in the source code of MDToolbar that works quite well in kvlang but not in python).

Here, you can use attr. right_action_items like a class attr. rather than a instance attr. as,

from kivymd.app import MDApp
from kivymd.uix.screen import MDScreen
from kivymd.uix.toolbar import MDToolbar

class MyApp(MDApp):
    def build(self):
        screen = MDScreen()

        self.tb = MDToolbar(
            title = "Placeholder",
        )
        self.tb.right_action_items = [["import", lambda x: print("import clicked")], ["export", lambda x: print("export clicked")]]
        screen.add_widget(self.tb)

        return screen

MyApp().run()
```

Body:
I'm trying to add 2 buttons to my MDToolbar, which would normally use the property right_action_items. My toolbar code looks like this:

        self.main_toolbar = MDToolbar(
        title = "Home",
        right_action_items = [["import", lambda args: print("import pressed")],["export", lambda args: print("export pressed")]],
        pos_hint = {"top": 1}
    )z

    self.smain.add_widget(self.main_toolbar)

self.smain is my screen variable.

The error I'm getting says there is a KeyError with "right_actions" somewhere in the kivymd module. There isn't any reference to my code in the error except it saying that the error was from my MDToolbar

Minimal reproduceable sample:

from kivymd.app import MDApp
from kivymd.uix.screen import MDScreen
from kivymd.uix.toolbar import MDToolbar

class MyApp(MDApp):
    def build(self):
        screen = MDScreen()

        screen.add_widget(MDToolbar(
            title = "Placeholder",
            right_action_items = [["import", lambda x: print("import clicked")], ["export", lambda x: print("export clicked")]]
        ))

        return screen

MyApp().run()


问:
is there anyway to convert from Double to BigInteger?
Is there anyway to convert from double value to BigInteger?

```<code>double doubleValue = 64654679846513164.2;
BigInteger bigInteger = (BigInteger) doubleValue;
</code>```

I try to cast it but it didn't work.

答:
The process of converting a Double -> BigDecimal -> BigInteger is intensive. I propose the below: (about 500% faster)

```<code>BigInteger m = DoubleToBigInteger(doublevalue);

static BigInteger DoubleToBigInteger(double testVal) {
    long bits = Double.doubleToLongBits(testVal);
    int exp = ((int)(bits >> 52) & 0x7ff) - 1075;
    BigInteger m = BigInteger.valueOf((bits & ((1L << 52)) - 1) | (1L << 52)).shiftLeft(exp);
    return  (bits >= 0)? m : m.negate();
}
</code>```

Body:
Is there anyway to convert from double value to BigInteger?

double doubleValue = 64654679846513164.2;
BigInteger bigInteger = (BigInteger) doubleValue;

I try to cast it but it didn't work.

Body:
The process of converting a Double -> BigDecimal -> BigInteger is intensive. I propose the below: (about 500% faster)

BigInteger m = DoubleToBigInteger(doublevalue);

static BigInteger DoubleToBigInteger(double testVal) {
    long bits = Double.doubleToLongBits(testVal);
    int exp = ((int)(bits >> 52) & 0x7ff) - 1075;
    BigInteger m = BigInteger.valueOf((bits & ((1L << 52)) - 1) | (1L << 52)).shiftLeft(exp);
    return  (bits >= 0)? m : m.negate();
}