问:
Ordering a complex unordered list with javascript
I am looking for a way to sort a fairly complicated html unordered list using either standard javascript or jQuery.

Please view the HTML, the order needs to be alphabetical and based on the HTML found inside the ".keywordType span value" but needs to construct the order of the top level li (with the unique keyword_xxx). I've just pasted 2 of the list items out of dozens.

```<code><ul class="keywords">
    <li id="keyword_185">
        <div class="icon_keyword"></div>
        <input type="hidden" class="keywordLabel" value="More opening hours">
        <div class="data-wrapper">
            <div class="keywordType">
                <span class="oh">Payment methods</span>
            </div>
            <div class="keywordValue">
                <span id="keyword_185" class="oh">Credit Card, PayPal</span>
            </div>
        </div>
        <a class="edit" title="Edit keywords"></a>
        <a class="delete" title="Delete keywords"></a>
    </li>
    <li id="keyword_192">
        <div class="icon_keyword"></div>
        <input type="hidden" class="keywordLabel" value="Monday to Friday: 8:30am to 6:30pm Saturday: 9pm to 6:30pm Sunday: 10 - 4pm">
        <div class="data-wrapper">
            <div class="keywordType">
                <span class="oh">Opening Hours</span>
            </div>
            <div class="keywordValue">
                <span id="keyword_192" class="oh">Monday to Friday: 8:30am to 6:30pm<br>Saturday: 9pm to 6:30pm<br>Sunday: 10 - 4pm</span>
            </div>
        </div>
        <a class="edit" title="Edit keywords"></a>
        <a class="delete" title="Delete keywords"></a>
    </li>
</ul>
</code>```

Thanks

答:
Take a look at this, it exactly matches your requirement.

http://james.padolsey.com/javascript/sorting-elements-with-jquery/

Body:
I am looking for a way to sort a fairly complicated html unordered list using either standard javascript or jQuery.

Please view the HTML, the order needs to be alphabetical and based on the HTML found inside the ".keywordType span value" but needs to construct the order of the top level li (with the unique keyword_xxx). I've just pasted 2 of the list items out of dozens.

        <input type="hidden" class="keywordLabel" value="More opening hours">

                Payment methods

                Credit Card, PayPal

        <input type="hidden" class="keywordLabel" value="Monday to Friday: 8:30am to 6:30pm Saturday: 9pm to 6:30pm Sunday: 10 - 4pm">

                Opening Hours

                Monday to Friday: 8:30am to 6:30pm
Saturday: 9pm to 6:30pm
Sunday: 10 - 4pm

Thanks


来源: stackexchange

问:
Unable to connect to h2 database
I have been trying to integrate h2 DB with spring boot application and I am getting the following error when trying to connect from the h2-console

```<code>Database "mem:testdb" not found, either pre-create it or allow remote database creation (not recommended in secure environments) [90149-200] 90149/90149 (Help)
org.h2.jdbc.JdbcSQLNonTransientConnectionException: Database "mem:testdb" not found, either pre-create it or allow remote database creation (not recommended in secure environments) [90149-200]
</code>```

I tried adding the following properties to the application.properties file:

```<code>spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create
</code>```

It still does not seem to work.

This is how my build.gradle file looks like

```<code>plugins {
    id 'org.springframework.boot' version '2.6.3'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.data:spring-data-jpa'

    runtimeOnly 'com.h2database:h2'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
    useJUnitPlatform()
}
</code>```

答:
It works as expected if you replace the line

```<code>implementation 'org.springframework.data:spring-data-jpa'
</code>```

with

```<code>implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
</code>```

in build.gradle if you make sure that the field JDBC URL in the login mask has the value jdbc:h2:mem:testdb.

You get the correct build.gradle if you use the Spring Initializr and add

Lombok

Spring Data JPA

H2 Database

Spring Web

If you want to add dependencies to a project that was originally created with the Spring Initializr, it's usually a good idea to go back to https://start.spring.io/, add all dependencies, hit the Explore button, and copy & paste the generated build.gradle into the existing project.

ContentLicense: CC BY-SA 4.0

Title: Unable to connect to h2 database

Body:
I have been trying to integrate h2 DB with spring boot application and I am getting the following error when trying to connect from the h2-console

Database "mem:testdb" not found, either pre-create it or allow remote database creation (not recommended in secure environments) [90149-200] 90149/90149 (Help)
org.h2.jdbc.JdbcSQLNonTransientConnectionException: Database "mem:testdb" not found, either pre-create it or allow remote database creation (not recommended in secure environments) [90149-200]

I tried adding the following properties to the application.properties file:

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create

It still does not seem to work.

This is how my build.gradle file looks like

plugins {
    id 'org.springframework.boot' version '2.6.3'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.data:spring-data-jpa'

    runtimeOnly 'com.h2database:h2'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

Body:
It works as expected if you replace the line

implementation 'org.springframework.data:spring-data-jpa'

with

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

in build.gradle if you make sure that the field JDBC URL in the login mask has the value jdbc:h2:mem:testdb.

You get the correct build.gradle if you use the Spring Initializr and add

Lombok

Spring Data JPA

H2 Database

Spring Web

If you want to add dependencies to a project that was originally created with the Spring Initializr, it's usually a good idea to go back to https://start.spring.io/, add all dependencies, hit the Explore button, and copy & paste the generated build.gradle into the existing project.


问:
Switch methods in object using protoype
I have a piece of code that switches the processing used on an object, a, outside of a function test. The function, test, uses properties of a and a.b and a.c:

```<code>let a;
let fB = {method: function(o){o.b.count++;return o.b.value}};
let fC = {method: function(o){o.c.count++;return o.c.value}};
a = new class A {value='Method:'; b={value:'B',count:0}; c={value:'C',count:0}};
function test (a,f) {
    console.log(a.value+f.method(a));
}
test(a,fB); // method:B
test(a,fC); // method:C
console.log('Counts:',a.b.count,a.c.count) // Counts: 1 1
</code>```

I want to write it in a more OO way, something like :

```<code>function test (a) {
    console.log(a.value+a.method());
}
class B {
    constructor(){this.val='B';this.count=0}
    method (){this.count++;return this.val}
}
class C {
    constructor(){this.val='C';this.count=0}
    method (){this.count++;return this.val}
}
class A {
    value='Method:';
}

a = new A();
Object.setPrototypeOf(a,new B());
test(a); // method:B
Object.setPrototypeOf(a,new C());
test(a); // method:C
console.log('Counts:',a.b.count,a.c.count) // a.b is undefined
</code>```

The best I could come up with was :

```<code>class B {
    constructor(){this.value='B';this.count=0}
    method (){this.count++;return this.value}
}
class C {
    constructor(){this.value='C';this.count=0}
    method (){this.count++;return this.value}
}
class A {
    value='Method:';
    b=new B();
    c=new C();
    x=this.b;

    switchToB(){this.x = this.b}
    switchToC(){this.x = this.c}
    method(){return this.x.method()}
}

a = new A();

function test (a) {
    console.log(a.value+a.method());
}
test(a); // method:B
a.switchToC();
test(a); // method:C
console.log('Counts:',a.b.count,a.c.count) // Counts: 1 1
</code>```

I don't much like this, nor an alternative :

```<code>class B {
    constructor(a){this.value=a.value;this.val='B';this.count=0}
    method (){this.count++;return this.val}
}
class C {
    constructor(a){this.value=a.value;this.val='C';this.count=0}
    method (){this.count++;return this.val}
}
class A {
    value='Method:';
    b=new BB(this);
    c=new CC(this);
}

a = new A();
test(a.b); // method:B
test(a.c); // method:C
console.log('Counts:',a.b.count,a.c.count) // Counts: 1 1
</code>```

Is there a better way to do this in JS ?

答:
Looking at the first OO attempt that you provided, there are these observations:

No b or c properties are created on a, yet the testing code needs them.

Also the switching mechanism should work with a reference to these b and c properties

B and C are look-alikes so that could be generalised to one Counter class whose constructor takes an argument that distinguishes them (determining the value property).

We could also think of a more lazy initialisation, where a counter object is only created when a switches to it.

There seems to be a relationship between the name "b" and the output "B". Similar between "c" and "C". So one could be derived from the other.

This leads to the following implementation:

class Counter {
    constructor(value) {
        this.value = value.toUpperCase();
        this.count = 0;
    }
    method() {
        this.count++;
        return this.value;
    }
}

class A {
    constructor() {
        this.value = 'Method:';
    }
    activateCounter(name) {
        // Create a new counter if not used before
        this[name] ??= new Counter(name);
        // Redirect the method to use this counter's method
        this.method = () => this[name].method();
    }
}

function test(a) {
    console.log(a.value + a.method());
}

let a = new A();
a.activateCounter("b");
test(a); // method:B
a.activateCounter("c");
test(a); // method:C
console.log('Counts:', a.b.count, a.c.count) // Counts: 1 1```

Here a.method() should only be called after a counter was activated with a call of a.activateCounter. This is because the latter will (re)define the method method on a.

Title: Switch methods in object using protoype

Body:
I have a piece of code that switches the processing used on an object, a, outside of a function test. The function, test, uses properties of a and a.b and a.c:

let a;
let fB = {method: function(o){o.b.count++;return o.b.value}};
let fC = {method: function(o){o.c.count++;return o.c.value}};
a = new class A {value='Method:'; b={value:'B',count:0}; c={value:'C',count:0}};
function test (a,f) {
    console.log(a.value+f.method(a));
}
test(a,fB); // method:B
test(a,fC); // method:C
console.log('Counts:',a.b.count,a.c.count) // Counts: 1 1

I want to write it in a more OO way, something like :

function test (a) {
    console.log(a.value+a.method());
}
class B {
    constructor(){this.val='B';this.count=0}
    method (){this.count++;return this.val}
}
class C {
    constructor(){this.val='C';this.count=0}
    method (){this.count++;return this.val}
}
class A {
    value='Method:';
}

a = new A();
Object.setPrototypeOf(a,new B());
test(a); // method:B
Object.setPrototypeOf(a,new C());
test(a); // method:C
console.log('Counts:',a.b.count,a.c.count) // a.b is undefined

The best I could come up with was :

class B {
    constructor(){this.value='B';this.count=0}
    method (){this.count++;return this.value}
}
class C {
    constructor(){this.value='C';this.count=0}
    method (){this.count++;return this.value}
}
class A {
    value='Method:';
    b=new B();
    c=new C();
    x=this.b;

    switchToB(){this.x = this.b}
    switchToC(){this.x = this.c}
    method(){return this.x.method()}
}

a = new A();

function test (a) {
    console.log(a.value+a.method());
}
test(a); // method:B
a.switchToC();
test(a); // method:C
console.log('Counts:',a.b.count,a.c.count) // Counts: 1 1

I don't much like this, nor an alternative :

class B {
    constructor(a){this.value=a.value;this.val='B';this.count=0}
    method (){this.count++;return this.val}
}
class C {
    constructor(a){this.value=a.value;this.val='C';this.count=0}
    method (){this.count++;return this.val}
}
class A {
    value='Method:';
    b=new BB(this);
    c=new CC(this);
}

a = new A();
test(a.b); // method:B
test(a.c); // method:C
console.log('Counts:',a.b.count,a.c.count) // Counts: 1 1

Is there a better way to do this in JS ?

Body:
Looking at the first OO attempt that you provided, there are these observations:

No b or c properties are created on a, yet the testing code needs them.

Also the switching mechanism should work with a reference to these b and c properties

B and C are look-alikes so that could be generalised to one Counter class whose constructor takes an argument that distinguishes them (determining the value property).

We could also think of a more lazy initialisation, where a counter object is only created when a switches to it.

There seems to be a relationship between the name "b" and the output "B". Similar between "c" and "C". So one could be derived from the other.

This leads to the following implementation:

class Counter {
    constructor(value) {
        this.value = value.toUpperCase();
        this.count = 0;
    }
    method() {
        this.count++;
        return this.value;
    }
}

class A {
    constructor() {
        this.value = 'Method:';
    }
    activateCounter(name) {
        // Create a new counter if not used before
        this[name] ??= new Counter(name);
        // Redirect the method to use this counter's method
        this.method = () => this[name].method();
    }
}

function test(a) {
    console.log(a.value + a.method());
}

let a = new A();
a.activateCounter("b");
test(a); // method:B
a.activateCounter("c");
test(a); // method:C
console.log('Counts:', a.b.count, a.c.count) // Counts: 1 1

Here a.method() should only be called after a counter was activated with a call of a.activateCounter. This is because the latter will (re)define the method method on a.


问:
Script Debugging Not Working (VS 2008)
I recently installed VS 6.0 after installing VS 2008 and overwrite JIT settings .. when i started VS 2008 option dialog .. it said another debugger has taken over VS 2008 debugger and I asked me to reset .. so I did ..

Now everything works fine except javascript debugging. I am unable to debug javascript .. I can set breakpoint .. but in debug mode when I hover the breakpoint it says "The breakpoint will not currently be hit. The document is not loaded" ..

How can I solve this issue? Can I reset JIT Settings?

答:
Make sure in internet explorer -> Tools -> Internet Options -> Advanced tab the "Disable script debugging" checkbox is unchecked.

This is the classic Disable script debugging checkbox checked after MS so called Security Patch update / revert back to original setting solution.

OwnerDisplayName: ZuhaibZ

ContentLicense: CC BY-SA 2.5

Title: Script Debugging Not Working (VS 2008)

LastEditorDisplayName: Kent Fredric

ContentLicense: CC BY-SA 3.0


问:
How to organise different kinds of tests in Java project?
We have a Java project where we have placed all the tests for the source code in one place at this path: src/test/java/com/temp. At this path we have placed all kinds of tests which includes unit tests, integration tests, smoke tests etc.

And I would like to get some idea on how we can organise it in a better way, such that it will help in organising future tests written for the project. Another motivation is that we can easily distinguish where exactly particular type of tests reside in the project.

I found this stack overflow answer: How do you organize tests in a modular Java project?

But in the above link, there was no mention of organising different kinds of tests

答:
It is good idea to have all the tests under src/tests folder. Within src/tests folder, I generally created one folder for each kind of tests. So something like this -
src/tests/integration

src/tests/unit

src/tests/smoke

In our current project, due to some dependencies, we have kept integration tests directly under src directory. I guess it all works fine if you have all the similar kind of tests organized under a folder with that name (integration for example).


问:
Alternating lines with Nested Loops
This is the exercise I need to complete:
Using nested loops, write some code that outputs the following:

```<code>##########
**********
##########
**********
##########
</code>```

Following is all the code I have so far. I assume I need to combine these two loop functions to one but I'm struggling with it. I'm early on in my first class and any help with this would be appreciated!

```<code>for a in range (0, 5, 2):
    for b in range(10):
        print("#", end = "")
    print("")
for a in range (1, 5, 2):
    for b in range(10):
        print("*", end = "")
    print("")
</code>```

答:
You can use this to get the result that you want</p>
```<code>for i in range(0,5):
     print("*"*10)
     print("#"*10)
</code>```

Title: Alternating lines with Nested Loops

Body:
This is the exercise I need to complete:
Using nested loops, write some code that outputs the following:

##########
**********
##########
**********
##########

Following is all the code I have so far. I assume I need to combine these two loop functions to one but I'm struggling with it. I'm early on in my first class and any help with this would be appreciated!

for a in range (0, 5, 2):
    for b in range(10):
        print("#", end = "")
    print("")
for a in range (1, 5, 2):
    for b in range(10):
        print("*", end = "")
    print("")

Body:
You can use this to get the result that you want

for i in range(0,5):
     print("*"*10)
     print("#"*10)


答:
I would suggest to simply base the symbol on the row index, even or odd

```<code>nb_lines = 5
line_size = 10

for i in range(nb_lines):
    for _ in range(line_size):
        if i % 2 == 0:
            print("#", end="")
        else:
            print("*", end="")
    print()
</code>```

But no need of nested loops

```<code>nb_lines = 5
line_size = 10

for i in range(nb_lines):
    if i % 2 == 0:
        print("#" * line_size)
    else:
        print("*" * line_size)
</code>```

Title: Alternating lines with Nested Loops

Body:
I would suggest to simply base the symbol on the row index, even or odd

nb_lines = 5
line_size = 10

for i in range(nb_lines):
    for _ in range(line_size):
        if i % 2 == 0:
            print("#", end="")
        else:
            print("*", end="")
    print()

But no need of nested loops

nb_lines = 5
line_size = 10

for i in range(nb_lines):
    if i % 2 == 0:
        print("#" * line_size)
    else:
        print("*" * line_size)


问:
Server Response Not matching model (no records) in Swift
sorry if the question is vague but I am trying to be as expressive as possible.

I have the following model:

```<code>struct Posts: Codable, Identifiable {
    let id: String
    let title: String
    let content: String

    enum CodingKeys: String, CodingKey {
        case id = "_id"
        case title
        case content
    }
}
</code>```

the server response if a post is found would be the same model no issues because the JSON matches the model .

but if the server returns an error post not found, this would be the response JSON:

```<code>{
"error": "No records found"
}
</code>```

I receive the following when this happens:

keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "id", intValue: nil) ("id").", underlyingError: nil))

what would be the best approach to handle this issue?

UPDATE:

Thank you jnpdx!

So, I did a ErrorResponse Struct, and it did catch the error response like so:

```<code>
struct ErrorResponse: Codable {
    let error: String

    enum CodingKeys: String, CodingKey {
        case error
    }
}

</code>```

So in my APIServices file, how do I handle this?

```<code>// this is what gets the Post data

let decodedData = try JSONDecoder().decode(Post?.self, from: data)

//Do I need another JSONDecoder to also catch the error below the above line like this?

let decodedDataError = try JSONDecoder().decode(ErrorResponse?.self, from: data)

</code>```

答:
In the comments, we discussed creating a struct to model the error, which it looks like you've done. To address your followup, no, you don't need a separate JSONDecoder. You also probably should not be decoding optionals.

There's not just a single way to do this correctly, but your function might look something like this:

```<code>let decoder = JSONDecoder()
do {
  let post = try decoder.decode(Post.self, from: data)
  //handle the post
} catch {
  //try to decode an error
  if let error = try? decoder.decode(ErrorResponse.self, from: data) {
    //handle an API error
  }
  //handle an unknown error
}
</code>```

Body:
sorry if the question is vague but I am trying to be as expressive as possible.

I have the following model:

struct Posts: Codable, Identifiable {
    let id: String
    let title: String
    let content: String

    enum CodingKeys: String, CodingKey {
        case id = "_id"
        case title
        case content
    }
}

the server response if a post is found would be the same model no issues because the JSON matches the model .

but if the server returns an error post not found, this would be the response JSON:

{
"error": "No records found"
}

I receive the following when this happens:

keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "id", intValue: nil) ("id").", underlyingError: nil))

what would be the best approach to handle this issue?

UPDATE:

Thank you jnpdx!

So, I did a ErrorResponse Struct, and it did catch the error response like so:

struct ErrorResponse: Codable {
    let error: String

    enum CodingKeys: String, CodingKey {
        case error
    }
}

So in my APIServices file, how do I handle this?

// this is what gets the Post data

let decodedData = try JSONDecoder().decode(Post?.self, from: data)

//Do I need another JSONDecoder to also catch the error below the above line like this?

let decodedDataError = try JSONDecoder().decode(ErrorResponse?.self, from: data)

Body:
In the comments, we discussed creating a struct to model the error, which it looks like you've done. To address your followup, no, you don't need a separate JSONDecoder. You also probably should not be decoding optionals.

There's not just a single way to do this correctly, but your function might look something like this:

let decoder = JSONDecoder()
do {
  let post = try decoder.decode(Post.self, from: data)
  //handle the post
} catch {
  //try to decode an error
  if let error = try? decoder.decode(ErrorResponse.self, from: data) {
    //handle an API error
  }
  //handle an unknown error
}


问:
Run a Script within Autocad from Excel
I have an excel workbook that creates an runs several calculations to create a new sheet.

From this new sheet it plots an array of commands for Autocad once it's exported to an AutoCAD script.

The script is saved to a predifined location ("C:\Autocad\Drawing To Drop In****.SCR"), what im try to achieve is from within Excel can it automate the manual dropping of the script into the AuutoCAD.

答:
It's possible to start AutoCAD and call a script from a Vbnet app using WinForms.

It should be possible to do something similar with VBA.

To write a Vba app in AutoCAD, type 'vbaman' on the AutoCAD command line.

Here's a repo with a sample Vbnet app that can launch AutoCAD and call a script.

There probably is away to launch this Vbnet app directly from excel I would imagine.

https://github.com/cadwiki/cadwiki-free-solutions

Title: Run a Script within Autocad from Excel


问:
Best algorithm for efficient collision detection between objects
I'm confused.  Well not confused, so much as not wanting to do 6 test programs to see which algorithm is the best. So I thought I'd ask my expert friends here at SO to give me the benefit of their experience.

The scenario is a 3d scene with potentially quite a large area compared to the sizes of the objects inside it.  There are potentially thousands of objects in the scene.  Objects vary in size from tenths of a unit to up to around 10 units, but no bigger (or smaller).  The objects tend to be clustered together, but those clusters can potentially appear anywhere in the scene.  All objects are dynamic and moving.  Clusters tend to move together, but when they do their velocities might not be the same all the time.  There's also static geometry to consider.  Although there are large numbers of dynamic objects, there's also some static objects in the scene (the static objects tend to be one or two orders of magnitude larger than the dynamic objects).

Now, what I want is a spatial data structure for efficiently performing collision detection for all items in the scene.  It would be great if the algorithm also supported visibility query too, for the rendering pipeline.  For the sake of simplicity, assume that collision detection here is broad-phase (i.e. all dynamic objects are just perfect spheres).

So, in my research I can use one of:

(1) Octree
(2) Loose Octree
(3) Linear Octree (+ loose)
(4) KD Tree
(5) BSP Tree
(6) Hashing

So far (6) is the only one I've tried.  It's actually totally superb in terms of speed (8192 items collision checked in under 1ms on my system) if objects in the scene are on average evenly spread out.  It's not such a good algorithm if all objects get couped up into a smaller area, which I suppose is possible.

Does anyone have some insight as to which one to use, or any tricks I can employ to speed things up?  I'm thinking that whatever happens I can just use a separate BSP tree for the static geometry.  I suppose the dynamic "spheres" are what concern me most here.  Note: no CUDA, this is CPU only :p.

Thanks

EDIT: Ok, thanks to Floris, I found more information about AABB Trees.  There's an old discussion on GameDev here: http://www.gamedev.net/topic/308665-aabb-tree---wheres-the-poly-o_o/.  Looks like a good compromise.

Final EDIT:  Decided not to reinvent the wheel.  It's possible the bullet physics library will do all of this for me (it has AABB tree in it, probably very well optimised too).

答:
Many physics engines use an AABBTree (Axis aligned Bounding Box Tree), It subdivides an object to smaller and smaller pieces. You can get very good collision detection by using this algo. This tree looks somewhat like an Octree.

An OOBBTree (Orientated Bounding Box) would be it's better counter part.


问:
Find rows that have different value on a column in MySQL
I want to get all the user_id that are having different user_ip_address on user_device table using a MySQL query.

```<code>Table: user_device

id    user_id    user_ip_address
-----------------------------------
1        1        1.1.1.1
2        1        1.1.1.1
3        2        2.2.2.2
4        3        3.3.3.3
5        1        10.10.10.10
6        4        4.4.4.4
7        2        20.20.20.20
8        3        3.3.3.3
</code>```

In this data, user_id 1 and user_id 2 have different user_ip_address.
It should output 1 and 2

I tried:

```<code>SELECT user_ip_address AS c
FROM user_device WHERE user_ip_address IN (SELECT user_id
FROM user_device group by user_id having user_ip_address!=c)
</code>```

答:
Use:

```<code>select  user_id
from user_device
group by user_id
having count(distinct user_ip_address) >1;
</code>```

Result:

```<code>user_id
1
2
</code>```

Demo

Body:
I want to get all the user_id that are having different user_ip_address on user_device table using a MySQL query.

Table: user_device

id    user_id    user_ip_address
-----------------------------------
1        1        1.1.1.1
2        1        1.1.1.1
3        2        2.2.2.2
4        3        3.3.3.3
5        1        10.10.10.10
6        4        4.4.4.4
7        2        20.20.20.20
8        3        3.3.3.3

In this data, user_id 1 and user_id 2 have different user_ip_address.
It should output 1 and 2

I tried:

SELECT user_ip_address AS c
FROM user_device WHERE user_ip_address IN (SELECT user_id
FROM user_device group by user_id having user_ip_address!=c)

Body:
Use:

select  user_id
from user_device
group by user_id
having count(distinct user_ip_address) >1;

Result:

user_id
1
2

Demo


问:
Binary Search Tree, one test does not go through
I have written a code of Binary Search tree that extends comparable and implements an interface. The code for leaves and the helper method countLeaves (included down here), makes sure that all of the test goes through except for one, heightIsLogOfNumLeavesTreeIsPerfect().

// TODO: Look at the Leaves and the helper method to leaves and see how I should change it so that this test goes through aswell.

//EDIT: I have added the whole tree class

```<code>java.lang.AssertionError:
Expected: <2>
     but: was <0>
Expected :<2>
Actual   :<0>
</code>```
```<code>import org.junit.Test;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.Timeout;
import static org.junit.Assert.*;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import java.util.Arrays;
import java.util.stream.IntStream;
/**
 * Test class for a tree.
 */
public class TreeTest{
    @Rule public Timeout globalTimeout = Timeout.seconds(5);

    Tree<Integer> tree;
    int[] elementsInTree;
    int[] elementsNotInTree;

    @Before
    public void setUp() {
        /**
         * This tree should look like this:
         *
         *               8
         *             /  \
         *            3   10
         *           / \    \
         *          1   6    14
         *             / \   /
         *            4   7 13
         */
        tree = new Tree<>();
        elementsInTree = new int[] {8, 10, 14, 13, 3, 1, 6, 4, 7};
        for (int elem : elementsInTree) {
            tree.insert(elem);
        }
        elementsNotInTree = new int[] {34, -3, -10, 12, 74, 5};
    }

    @Test
    public void heightIsLogOfNumLeavesTreeIsPerfect() {
        // For a perfect tree, tree.height() == log2(tree.leaves()

        // Arrange
        Tree<Integer> tree = new Tree<>();
        int[] elements = new int[] {8, 3, 10, 1, 6, 9, 14};
        int numLeaves = 4;
        int logNumLeaves = (int) Math.round(Math.log(numLeaves) / Math.log(2));
        for (int elem : elements) {
            tree.insert(elem);
        }

        // Act
        int height = tree.height();
        // Assert
        assertThat(height, equalTo(logNumLeaves));
    }
}
</code>```
```<code>**
 * An interface describing a generic Comparable
 */

public interface BSTInterface <T>{

    boolean search(T elem);

    boolean insert(T elem);

        int size();

    int height();

    int leaves();
}
</code>```
```<code>/**
 * An Binary Search tree implementation of the comparable interface.
 * @param <T>
 */
public class Tree <T extends Comparable <T>> implements BSTInterface <T>{
    private int size;
    private Node root;
    public class Node{
        private Node Left;
        private Node Right;
        private T data;

        public Node(T data){
            this.data = data;
        }
        public Node getRight(){
            return Right;
        }

        public Node getLeft() {
            return Left;
        }

        public T getData() {
            return data;
        }
    }
    public Tree (){
        size = 0;
        root = null;
    }

    /**
     * Test for presence of a value.
     * @param elem
     * @return true/false
     */
    @Override
    public boolean search(T elem) {
        if(root == null ||elem == null){
        return false;
        }
        Node node = root;
        while(true){
            if(node.data.compareTo(elem) > 0){
                if(node.Right == null){
                    return false;
                } else{
                    node = node.Right;
                }
            } else if(node.data.compareTo(elem) == 0){
                break;
            } else{
                if(node.Left== null){
                    return false;
                }
                else{
                    node = node.Left;
                }
            }
        }
        return true;
    }

    /**
     * Add value to tree; duplicates are not allowed.
     * Return true if the element is not already present (and is thus inserted),
     * false otherwise.
     *
     * @param elem
     * @return true/false
     */
    @Override
    public boolean insert(T elem) {
        if (elem == null){
            return false;
        }
        if (root == null){
            root = new Node(elem);
            size++;
            return true;
        }
        Node node = root;
        while (true){
            if (node.data.compareTo(elem) > 0) {
                if (node.Right == null){
                    node.Right = new Node(elem);
                    size++;
                    break;
                } else {
                    node = node.Right;
                }

            } else if (node.data.compareTo(elem) == 0) {
                return false;
            } else {
                if (node.Left == null){
                    node.Left = new Node(elem);
                    size++;
                    break;
                } else {
                    node = node.Left;
                }
            }
        }
        return true;
    }

    /**
     * the number of elements in the tree
     * @return size.
     */
    @Override
    public int size() {
        return size;
    }

    /**
     * The height of the tree.
     * The empty tree and the tree with only the root node both have height 0.
     * @return the height of the tree.
     */
    @Override
    public int height() {
        return countHeight(root);
    }
    /**
     * Helper method for height
     */
    private int countHeight(Node node){
        if(node == null) {
            return 0;
        }
        return Math.max(countHeight(node.Left), countHeight(node.Right));
    }

    /**
     * The number of leaves in the tree.
     * @return the amount of leaves the tree have.
     */
    @Override
    public int leaves() {
        return countLeaves(root);
    }
    /**
     * Helper method for leaves
     */
    private int countLeaves(Node node) {
        if (node == null) {
            return 0;
        }
        if (node.Left == null && node.Right == null) {
            return 1;
        }
        return countLeaves(node.Left) + countLeaves(node.Right);
    }

    /**
     * A string describing the tree
     * @return
     */
    public String toString(){
        String str = "[" + helpToString(root);
        if (str.length() > 1) {
            str = str.substring(0, str.length() - 2);
        } return str + "]";
    }

    /**
     * Helper method for toString
     */
    private String helpToString(Node node) {
        String str = "";
        if (node != null) {
            str += helpToString(node.Right);
            str += node.data + ", ";
            str += helpToString(node.Left);
        }
        return str;
      }
}

</code>```

答:
Your countHeight method can return either zero or a maximum of two returns, and there are no other operations in it. You can't get a value greater of zero out of zeros just by using max function.

You should return -1 for an empty tree and max(height(left) + 1, height(right) + 1) otherwise. Each +1 accounts for length of corresponding parent-child edge.

(Mathematically speaking, height of an "empty" tree is usually undefined, but defining it as -1 in this case helps a lot so let's stick to that.)

Body:
I have written a code of Binary Search tree that extends comparable and implements an interface. The code for leaves and the helper method countLeaves (included down here), makes sure that all of the test goes through except for one, heightIsLogOfNumLeavesTreeIsPerfect().

// TODO: Look at the Leaves and the helper method to leaves and see how I should change it so that this test goes through aswell.

//EDIT: I have added the whole tree class

java.lang.AssertionError:
Expected: <2>
     but: was <0>
Expected :<2>
Actual   :<0>

import org.junit.Test;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.Timeout;
import static org.junit.Assert.*;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import java.util.Arrays;
import java.util.stream.IntStream;
/**
 * Test class for a tree.
 */
public class TreeTest{
    @Rule public Timeout globalTimeout = Timeout.seconds(5);

    Tree<Integer> tree;
    int[] elementsInTree;
    int[] elementsNotInTree;

    @Before
    public void setUp() {
        /**
         * This tree should look like this:
         *
         *               8
         *             /  \
         *            3   10
         *           / \    \
         *          1   6    14
         *             / \   /
         *            4   7 13
         */
        tree = new Tree<>();
        elementsInTree = new int[] {8, 10, 14, 13, 3, 1, 6, 4, 7};
        for (int elem : elementsInTree) {
            tree.insert(elem);
        }
        elementsNotInTree = new int[] {34, -3, -10, 12, 74, 5};
    }

    @Test
    public void heightIsLogOfNumLeavesTreeIsPerfect() {
        // For a perfect tree, tree.height() == log2(tree.leaves()

        // Arrange
        Tree<Integer> tree = new Tree<>();
        int[] elements = new int[] {8, 3, 10, 1, 6, 9, 14};
        int numLeaves = 4;
        int logNumLeaves = (int) Math.round(Math.log(numLeaves) / Math.log(2));
        for (int elem : elements) {
            tree.insert(elem);
        }

        // Act
        int height = tree.height();
        // Assert
        assertThat(height, equalTo(logNumLeaves));
    }
}

**
 * An interface describing a generic Comparable
 */

public interface BSTInterface <T>{

    boolean search(T elem);

    boolean insert(T elem);

        int size();

    int height();

    int leaves();
}

/**
 * An Binary Search tree implementation of the comparable interface.
 * @param <T>
 */
public class Tree <T extends Comparable <T>> implements BSTInterface <T>{
    private int size;
    private Node root;
    public class Node{
        private Node Left;
        private Node Right;
        private T data;

        public Node(T data){
            this.data = data;
        }
        public Node getRight(){
            return Right;
        }

        public Node getLeft() {
            return Left;
        }

        public T getData() {
            return data;
        }
    }
    public Tree (){
        size = 0;
        root = null;
    }

    /**
     * Test for presence of a value.
     * @param elem
     * @return true/false
     */
    @Override
    public boolean search(T elem) {
        if(root == null ||elem == null){
        return false;
        }
        Node node = root;
        while(true){
            if(node.data.compareTo(elem) > 0){
                if(node.Right == null){
                    return false;
                } else{
                    node = node.Right;
                }
            } else if(node.data.compareTo(elem) == 0){
                break;
            } else{
                if(node.Left== null){
                    return false;
                }
                else{
                    node = node.Left;
                }
            }
        }
        return true;
    }

    /**
     * Add value to tree; duplicates are not allowed.
     * Return true if the element is not already present (and is thus inserted),
     * false otherwise.
     *
     * @param elem
     * @return true/false
     */
    @Override
    public boolean insert(T elem) {
        if (elem == null){
            return false;
        }
        if (root == null){
            root = new Node(elem);
            size++;
            return true;
        }
        Node node = root;
        while (true){
            if (node.data.compareTo(elem) > 0) {
                if (node.Right == null){
                    node.Right = new Node(elem);
                    size++;
                    break;
                } else {
                    node = node.Right;
                }

            } else if (node.data.compareTo(elem) == 0) {
                return false;
            } else {
                if (node.Left == null){
                    node.Left = new Node(elem);
                    size++;
                    break;
                } else {
                    node = node.Left;
                }
            }
        }
        return true;
    }

    /**
     * the number of elements in the tree
     * @return size.
     */
    @Override
    public int size() {
        return size;
    }

    /**
     * The height of the tree.
     * The empty tree and the tree with only the root node both have height 0.
     * @return the height of the tree.
     */
    @Override
    public int height() {
        return countHeight(root);
    }
    /**
     * Helper method for height
     */
    private int countHeight(Node node){
        if(node == null) {
            return 0;
        }
        return Math.max(countHeight(node.Left), countHeight(node.Right));
    }

    /**
     * The number of leaves in the tree.
     * @return the amount of leaves the tree have.
     */
    @Override
    public int leaves() {
        return countLeaves(root);
    }
    /**
     * Helper method for leaves
     */
    private int countLeaves(Node node) {
        if (node == null) {
            return 0;
        }
        if (node.Left == null && node.Right == null) {
            return 1;
        }
        return countLeaves(node.Left) + countLeaves(node.Right);
    }

    /**
     * A string describing the tree
     * @return
     */
    public String toString(){
        String str = "[" + helpToString(root);
        if (str.length() > 1) {
            str = str.substring(0, str.length() - 2);
        } return str + "]";
    }

    /**
     * Helper method for toString
     */
    private String helpToString(Node node) {
        String str = "";
        if (node != null) {
            str += helpToString(node.Right);
            str += node.data + ", ";
            str += helpToString(node.Left);
        }
        return str;
      }
}


问:
Mobile Menu Not Closing Upon Selection
I have a mobile menu that appears on smaller devices, everything is working correctly except when a selection is made the mobile menu still displays even though my code should hide it.

Thank you for your time

Below is the js code I'm using for my mobile menu

```<code>const menu = document.querySelector("#mobile-menu");
const menuLinks = document.querySelector(".navbar__menu");
const navLogo = document.querySelector("#navbar__logo");

// Display Mobile Menu
const mobileMenu = () => {
  menu.classList.toggle("is-active");
  menuLinks.classList.toggle("active");
};

menu.addEventListener("click", mobileMenu);

//  Close mobile Menu when clicking on a menu item
const hideMobileMenu = () => {
  const menuBars = document.querySelector(".is-active");
  if (window.innerWidth <= 768 && menuBars) {
    menu.classList.toggle("is-active");
    menuLinks.classList.remove("active");
  }
};

menuLinks.addEventListener("click", hideMobileMenu);
navLogo.addEventListener("click", hideMobileMenu);
</code>```

Here is the mobile menu html

```<code>    <!-- Navbar Section -->
    <nav class="navbar">
      <div class="navbar__container">
        <a href="#home" id="navbar__logo">TEST</a>
        <div class="navbar__toggle" id="mobile-menu">
          <span class="bar"></span>
          <span class="bar"></span>
          <span class="bar"></span>
        </div>
        <ul class="navbar__menu">
          <li class="navbar__item">
            <a href="#home" class="navbar__links" id="home-page">Home</a>
          </li>
          <li class="navbar__item">
            <a href="#about" class="navbar__links" id="about-page">About</a>
          </li>
          <li class="navbar__item">
            <a href="#practices" class="navbar__links" id="practices-page"
              >Practice</a
            >
          </li>
          <li class="navbar__btn">
            <a href="#contact" class="button" id="contact-page">Contact</a>
          </li>
        </ul>
      </div>
    </nav>
</code>```

答:
Created this snippet to attempt to reproduce the issue and I don't see or understand the problem?

User can click on mobile nav icon (3 bars) and have it display the "nav"

User can click on a nav item.

When user clicks on nav item it closes mobile nav.

If there are some other circumstances, or I didn't understand the question, please feel free to insert this code snippet into your question and add more details. Also not sure why window.innerWidth has to be less than 768 in that one conditional.

Also, you can probably just run the mobileMenu() function instead of essentially re-writing it inside that if clause:

```<code> if (window.innerWidth <= 768 && menuBars) {
    menu.classList.toggle("is-active");
    menuLinks.classList.remove("active");
  }
</code>```

can turn into:

```<code>  if (window.innerWidth <= 768 && menuBars) {
    mobileMenu();
  }
</code>```

const menu = document.querySelector("#mobile-menu");
const menuLinks = document.querySelector(".navbar__menu");
const navLogo = document.querySelector("#navbar__logo");

// Display Mobile Menu
const mobileMenu = () => {
  menu.classList.toggle("is-active");
  menuLinks.classList.toggle("active");
};

menu.addEventListener("click", mobileMenu);

//  Close mobile Menu when clicking on a menu item
const hideMobileMenu = () => {
  const menuBars = document.querySelector(".is-active");
  if (window.innerWidth <= 768 && menuBars) {
    menu.classList.toggle("is-active");
    menuLinks.classList.remove("active");
  }
};

menuLinks.addEventListener("click", hideMobileMenu);
navLogo.addEventListener("click", hideMobileMenu);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.navbar__menu {
display: none;
}
.navbar__menu.active {
display: flex;
}
.navbar__toggle {
  height: 1rem;
}
.navbar__toggle .bar {
  background: green;
  height: 5px;
  width: 5px;
  padding: 3px;
  display: block;
  border: 1px solid black;
  content: 'x';
}
#mobile-menu {
display: flex;
}
#mobile-menu.is-active {
  background: green;
}</code>```

        TEST

            Home

            About

            Practice

            href="#contact" class="button" id="contact-page">Contact

    ```

Title: Mobile Menu Not Closing Upon Selection

Body:
I have a mobile menu that appears on smaller devices, everything is working correctly except when a selection is made the mobile menu still displays even though my code should hide it.

Thank you for your time

Below is the js code I'm using for my mobile menu

const menu = document.querySelector("#mobile-menu");
const menuLinks = document.querySelector(".navbar__menu");
const navLogo = document.querySelector("#navbar__logo");

// Display Mobile Menu
const mobileMenu = () => {
  menu.classList.toggle("is-active");
  menuLinks.classList.toggle("active");
};

menu.addEventListener("click", mobileMenu);

//  Close mobile Menu when clicking on a menu item
const hideMobileMenu = () => {
  const menuBars = document.querySelector(".is-active");
  if (window.innerWidth <= 768 && menuBars) {
    menu.classList.toggle("is-active");
    menuLinks.classList.remove("active");
  }
};

menuLinks.addEventListener("click", hideMobileMenu);
navLogo.addEventListener("click", hideMobileMenu);

Here is the mobile menu html

        TEST

            Home

            About

            Practice

            Contact

Body:
Created this snippet to attempt to reproduce the issue and I don't see or understand the problem?

User can click on mobile nav icon (3 bars) and have it display the "nav"

User can click on a nav item.

When user clicks on nav item it closes mobile nav.

If there are some other circumstances, or I didn't understand the question, please feel free to insert this code snippet into your question and add more details. Also not sure why window.innerWidth has to be less than 768 in that one conditional.

Also, you can probably just run the mobileMenu() function instead of essentially re-writing it inside that if clause:

 if (window.innerWidth <= 768 && menuBars) {
    menu.classList.toggle("is-active");
    menuLinks.classList.remove("active");
  }

can turn into:

  if (window.innerWidth <= 768 && menuBars) {
    mobileMenu();
  }

const menu = document.querySelector("#mobile-menu");
const menuLinks = document.querySelector(".navbar__menu");
const navLogo = document.querySelector("#navbar__logo");

// Display Mobile Menu
const mobileMenu = () => {
  menu.classList.toggle("is-active");
  menuLinks.classList.toggle("active");
};

menu.addEventListener("click", mobileMenu);

//  Close mobile Menu when clicking on a menu item
const hideMobileMenu = () => {
  const menuBars = document.querySelector(".is-active");
  if (window.innerWidth <= 768 && menuBars) {
    menu.classList.toggle("is-active");
    menuLinks.classList.remove("active");
  }
};

menuLinks.addEventListener("click", hideMobileMenu);
navLogo.addEventListener("click", hideMobileMenu);

.navbar__menu {
display: none;
}
.navbar__menu.active {
display: flex;
}
.navbar__toggle {
  height: 1rem;
}
.navbar__toggle .bar {
  background: green;
  height: 5px;
  width: 5px;
  padding: 3px;
  display: block;
  border: 1px solid black;
  content: 'x';
}
#mobile-menu {
display: flex;
}
#mobile-menu.is-active {
  background: green;
}

<!-- Navbar Section -->
    <nav class="navbar">
      <div class="navbar__container">
        <a href="#home" id="navbar__logo">TEST</a>
        <div class="navbar__toggle" id="mobile-menu">
          <span class="bar"></span>
          <span class="bar"></span>
          <span class="bar"></span>
        </div>
        <ul class="navbar__menu">
          <li class="navbar__item">
            <a href="#home" class="navbar__links" id="home-page">Home</a>
          </li>
          <li class="navbar__item">
            <a href="#about" class="navbar__links" id="about-page">About</a>
          </li>
          <li class="navbar__item">
            <a href="#practices" class="navbar__links" id="practices-page"
              >Practice</a
            >
          </li>
          <li class="navbar__btn">
            <a href="#contact" class="button" id="contact-page">Contact</a>
          </li>
        </ul>
      </div>
    </nav>


答:
Count the number of different addresses each user has:</p>
```<code>SELECT user_id
FROM user_device
GROUP BY user_id
HAVING COUNT(DISTINCT user_ip_address) > 1
</code>```

Title: Find rows that have different value on a column in MySQL

Body:
Count the number of different addresses each user has:

SELECT user_id
FROM user_device
GROUP BY user_id
HAVING COUNT(DISTINCT user_ip_address) > 1


问:
PyInstaller FATAL FIPS SELFTEST FAILURE
I have used PyInstaller to package up a python application. When I run the application I receive this error:

crypto/fips/fips.c:154: OpenSSL internal error: FATAL FIPS SELFTEST FAILURE
Abort (core dumped)

If I run the script via "python3 scriptname.py" it runs fine. I do not use OpenSSL in my python scripts. I believe PyInstaller is using something that is not FIPS compliant.

With FIPS disabled I am able to successfully run the PyInstaller packaged application.

How can I debug this error? Is there a way to patch PyInstaller to make it FIPS compliant?

答:
This usually happens, if you installed python with FIPS enabled/disabled or if Python is consuming a module/library/something, where Python/ or that particular library/python pyInstaller may be consuming an artifact (that was built on some machine previously, with FIPS Disabled); then, using such executables (built with FIPS disabled) on another machine(where FIPS is actually enabled) i.e. where FIPS setting doesn't match with the machine, where you built the app in python or that particular library, then, you'll get such errors.

Ex: Let's say a package manager ex: yum / zypper installed python without openssl (which is a pre-install/pre-requisite for python app, which needs Openssl functionality). If python is installed without Openssl first already installed, then any Python app, which needs openssl processing, Python won't work, even if you install openssl later on the machine; Python will still spit out bunch of gnarly openssl errors :--) big grin.

Similarly, if something was installed/packaged/built using FIPS disabled (on some machine), it can be an app or any library that you are consuming... then later, if you try to run an app or an app(consuming that  library/package) on a machine, where FIPS = 1 (enabled) then you'll see this error.

In my case, cmake was failing for running simple cmake --version and all I did was used a cmake .tar bundle which may have been compiled on a machine, where source and target machine's FIPS settings were same i.e. in my case, cmake tar bundle came from a FIPS enabled machine, and when I used it on this other new machine where FIPS was enabled, it worked!

MISC Info on OpenSSL errors:

The effects of self-test failures in the Module differ depending on the type of self-test that failed.

The FIPS_mode_set() function verifies the integrity of the runtime executable using a HMAC SHA-256 digest,
which is computed at build time. If this computed HMAC SHA-256 digest matches the stored, known digest, then
the power-up self-test (consisting of the algorithm-specific Pairwise Consistency and Known Answer tests) is
performed.

Non-fatal self-test errors transition the module into an error state. The application must be restarted to recover
from these errors. The non-fatal self-test errors are:

FIPS_R_FINGERPRINT_DOES_NOT_MATCH - The integrity verification check failed

FIPS_R_FIPS_SELFTEST_FAILED - a known answer test failed

FIPS_R_SELFTEST_FAILED - a known answer test failed

FIPS_R_TEST_FAILURE – a known answer test failed (RSA); pairwise consistency test failed (DSA)

FIPS_R_PAIRWISE_TEST_FAILED – a pairwise consistency test during DSA or RSA key generation failed

FIPS_R_FIPS_MODE_ALREADY_SET - the application initializes the FIPS mode when it is already initialized

These errors are reported through the regular ERR interface of the shared libraries and can be queried by
functions such as ERR_get_error(). See the OpenSSL Module manual page for the function description.

A fatal error occurs only when the module is in the error state (a self-test has failed) and the application calls a
crypto function of the module that cannot return an error in normal circumstances (void return functions). The
error message: 'FATAL FIPS SELFTEST FAILURE' is printed to stderr and the application is terminated with the
abort() call.

The only way to recover from a fatal error is to restart the application. If failures persist, you must reinstall the Module. If you downloaded the software, verify the package hash to confirm a proper download.

IMPORTANT NOTE:

If you installed a newer version of OpenSSL x.y.z (rpm/etc) and didn't reboot/restart your machine, some of the libraries which consume openssl will be vulnerable / error out too with similar errors.

You can test this by running:

uptime command to see how long your server/machine has been UP n running.

sudo lsof | grep libssl.so or to Find processes running with deleted OpenSSL libraries, run:

sudo lsof | grep DEL.*libssl

So, try rebooting your machine and see if the errors goes away and check the output of the above commands.

For more info, refer this link: https://raymii.org/s/snippets/Find_all_services_using_libssl_to_restart_after_an_OpenSSL_update.html

Title: PyInstaller FATAL FIPS SELFTEST FAILURE


问:
permutation & combinations interview
This is a good one because it's so counter-intuitive:

Imagine an urn filled with balls, two-thirds of which are of one color and one-third of which are of another. One individual has drawn 5 balls from the urn and found that 4 are red and 1 is white. Another individual has drawn 20 balls and found that 12 are red and 8 are white. Which of the two individuals should feel more confident that the urn contains two-thirds red balls and one-third white balls, rather than vice-versa? What odds should each individual give?

I know the right answer, but maybe I don't quite get the odds calculation. Can anyone explain?

答:
Hehe. May be I am totally wrong but isnt it intuitive that answer should be second  guy ?

One sees a ratio : 4:1  4/5 : 1/5

Two sees a ratio 3:1   3/4 : 1/4

So simple question is who is closer to  2/3 : 1/3  ?  Hence the answer is Obs. Two.

May be I have done two mistakes and am getting simple answer to something complex, but pardon my patience to go through long explanation for what I thought was actually intuitive.

OwnerDisplayName: Nick

Title: permutation & combinations interview

LastEditorDisplayName: A. Rex


问:
How to stop a for loop inside an ExecutorService?
I've tried looking on other threads and I can't seem to find a proper answer,

When using executorService.shutdownNow() almost all tasks stop immediately as intended except ones with for loops in them.
I have no idea why it happens, but the most I've seen from other threads is that you should be using Thread.currentThread().isInterrupted() to check if it is interrupted, but adding a

```<code>if(Thread.currentThread().isInterrupted())
    {return;}
</code>```

Doesn't actually stop it all.  I'm calling executor shutdownNow when a UI button is toggled off.

Code example:

```<code>executorService.submit(() -> {
            ctx.batzUtils.keyEvent(KeyEvent.KEY_PRESSED, VK_SHIFT);
            //Shit keeps going if you call ShutdownNow Todo
            for (Rectangle rect : rects)
            {
                ctx.batzUtils.click(rect);
                try
                {
                    Thread.sleep(minDelayBetween, maxDelayBetween);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
            ctx.batzUtils.keyEvent(KeyEvent.KEY_RELEASED, VK_SHIFT);
            ctx.batzUtils.keyEvent(KeyEvent.KEY_TYPED, VK_SHIFT);
        });
</code>```

Any ideas as to why or solutions would be greatly appreciated

答:
When using executorService.shutdownNow() almost all tasks stop immediately as intended except ones with for loops in them.

This is a misleading statement. executorService.shutdownNow() cancels any jobs that have not run yet and interrupts all of the threads that are currently running.  The reason why some of your threads aren't being interrupted is because you are catching InterruptedException in your for loop.  Whenever InterruptedException is thrown, the interrupt bit of the running thread is cleared.

Whenever you catch InterruptedException, you should immediately re-interrupt the running thread so that the caller will know that the interrupt has been set.  Your bug is a good example of why this pattern is necessary.

```<code>try {
   Thread.sleep(minDelayBetween, maxDelayBetween);
} catch (InterruptedException e) {
   // when InterruptedException is thrown it clears the interrupt bit so
   // we need to re-interrupt the thread whenever we catch it
   Thread.currentThread().interrupt();
   // you should handle the interrupt appropriately and not just print it
   return;
}
</code>```

Here's a good tutorial on the subject of Java thread interrupts.

Body:
I've tried looking on other threads and I can't seem to find a proper answer,

When using executorService.shutdownNow() almost all tasks stop immediately as intended except ones with for loops in them.
I have no idea why it happens, but the most I've seen from other threads is that you should be using Thread.currentThread().isInterrupted() to check if it is interrupted, but adding a

if(Thread.currentThread().isInterrupted())
    {return;}

Doesn't actually stop it all.  I'm calling executor shutdownNow when a UI button is toggled off.

Code example:

executorService.submit(() -> {
            ctx.batzUtils.keyEvent(KeyEvent.KEY_PRESSED, VK_SHIFT);
            //Shit keeps going if you call ShutdownNow Todo
            for (Rectangle rect : rects)
            {
                ctx.batzUtils.click(rect);
                try
                {
                    Thread.sleep(minDelayBetween, maxDelayBetween);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
            ctx.batzUtils.keyEvent(KeyEvent.KEY_RELEASED, VK_SHIFT);
            ctx.batzUtils.keyEvent(KeyEvent.KEY_TYPED, VK_SHIFT);
        });

Any ideas as to why or solutions would be greatly appreciated

Body:
When using executorService.shutdownNow() almost all tasks stop immediately as intended except ones with for loops in them.

This is a misleading statement. executorService.shutdownNow() cancels any jobs that have not run yet and interrupts all of the threads that are currently running.  The reason why some of your threads aren't being interrupted is because you are catching InterruptedException in your for loop.  Whenever InterruptedException is thrown, the interrupt bit of the running thread is cleared.

Whenever you catch InterruptedException, you should immediately re-interrupt the running thread so that the caller will know that the interrupt has been set.  Your bug is a good example of why this pattern is necessary.

try {
   Thread.sleep(minDelayBetween, maxDelayBetween);
} catch (InterruptedException e) {
   // when InterruptedException is thrown it clears the interrupt bit so
   // we need to re-interrupt the thread whenever we catch it
   Thread.currentThread().interrupt();
   // you should handle the interrupt appropriately and not just print it
   return;
}

Here's a good tutorial on the subject of Java thread interrupts.


问:
TypeError: arguments did not match any overloaded call
I'm a beginner with QT Python and I'm trying to run a small program to display a table view with a push button beside each row. I've tried the code shown below but I'm getting the following errors:

```<code>Traceback (most recent call last):
  File "/Users/Programs/bottone.py", line 42, in <module>
    mainwindow = MainWindow()
  File "/Users/Programs/bottone.py", line 29, in __init__
    self.btn_sell = IndexedButtonWidget('Edit')
  File "/Users/Programs/bottone.py", line 8, in __init__
    super(QPushButton, self).__init__(parent=parent)
TypeError: arguments did not match any overloaded call:
  QPushButton(parent: QWidget = None): argument 'parent' has unexpected type 'str'
  QPushButton(str, parent: QWidget = None): not enough arguments
  QPushButton(QIcon, str, parent: QWidget = None): not enough arguments
</code>```

Code:

```<code>class IndexedButtonWidget(QPushButton):
    def __init__(self, parent=None):
        super(QPushButton, self).__init__(parent=parent)
        self.button_row = 0
        self.button_column = 0

    class MainWindow(QtWidgets.QMainWindow):
        def __init__(self, parent=None):
            QtWidgets.QMainWindow.__init__(self,parent)
            self.table = QtWidgets.QTableWidget()
            self.table.setColumnCount(3)
            self.setCentralWidget(self.table)
            data1 = ['row1','row2','row3','row4']
            data2 = ['1','2.0','3.00000001','3.9999999']

            self.table.setRowCount(4)

            for index in range(4):
                item1 = QtWidgets.QTableWidgetItem(data1[index])
                self.table.setItem(index,0,item1)
                item2 = QtWidgets.QTableWidgetItem(data2[index])
                self.table.setItem(index,1,item2)
                self.btn_sell = IndexedButtonWidget('Edit')
                self.btn_sell.button_row = index
                self.btn_sell.button_column = 2
                self.btn_sell.clicked.connect(self.handleButtonClicked)
                self.table.setCellWidget(index,2,self.btn_sell)

        def handleButtonClicked(self):
            button = self.sender()
            print(button.button_row)
            print(button.button_column)
</code>```

Do you have any clue about which is the problem?

答:
The IndexedButtonWidget is instantiated with one argument: 'Edit'

self.btn_sell = IndexedButtonWidget('Edit')
```
<p>The documentation shows that there is only one <code>QPushButton.__init__()</code> which takes one argument: <code>QPushButton(self, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None</code>. So the code ends up passing <code>'Edit'</code> as <code>parent</code>, hence the <code>TypeError</code>.</p>
<pre class="lang-py prettyprint-override"><code>help(QPushButton)
</code>```
```
Help on class QPushButton in module PySide6.QtWidgets:

class QPushButton(QAbstractButton)
 |  QPushButton(self, icon: Union[PySide6.QtGui.QIcon, PySide6.QtGui.QPixmap], text: str, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None
 |  QPushButton(self, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None
 |  QPushButton(self, text: str, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None
 |
 |  Method resolution order:
 |      QPushButton
 |      QAbstractButton
 |      QWidget
 |      PySide6.QtCore.QObject
 |      PySide6.QtGui.QPaintDevice
 |      Shiboken.Object
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __delattr__(self, name, /)
 |      Implement delattr(self, name).
 |
 |  __init__(...)
 |      __init__(self, icon: Union[PySide6.QtGui.QIcon, PySide6.QtGui.QPixmap], text: str, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None
 |      __init__(self, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None
 |      __init__(self, text: str, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None
 |
 |      Initialize self.  See help(type(self)) for accurate signature.
```

This error can be solved by updating IndexedButtonWidget.__init__().

class IndexedButtonWidget(QPushButton):
    def __init__(self, text='', parent=None):
        super(QPushButton, self).__init__(text, parent=parent)
        self.button_row = 0
        self.button_column = 0
```

There are other ways to write __init__() so that the TypeError doesn't occur, but this solves the specific error in the question.

Body:
I'm a beginner with QT Python and I'm trying to run a small program to display a table view with a push button beside each row. I've tried the code shown below but I'm getting the following errors:

Traceback (most recent call last):
  File "/Users/Programs/bottone.py", line 42, in <module>
    mainwindow = MainWindow()
  File "/Users/Programs/bottone.py", line 29, in __init__
    self.btn_sell = IndexedButtonWidget('Edit')
  File "/Users/Programs/bottone.py", line 8, in __init__
    super(QPushButton, self).__init__(parent=parent)
TypeError: arguments did not match any overloaded call:
  QPushButton(parent: QWidget = None): argument 'parent' has unexpected type 'str'
  QPushButton(str, parent: QWidget = None): not enough arguments
  QPushButton(QIcon, str, parent: QWidget = None): not enough arguments

Code:

class IndexedButtonWidget(QPushButton):
    def __init__(self, parent=None):
        super(QPushButton, self).__init__(parent=parent)
        self.button_row = 0
        self.button_column = 0

    class MainWindow(QtWidgets.QMainWindow):
        def __init__(self, parent=None):
            QtWidgets.QMainWindow.__init__(self,parent)
            self.table = QtWidgets.QTableWidget()
            self.table.setColumnCount(3)
            self.setCentralWidget(self.table)
            data1 = ['row1','row2','row3','row4']
            data2 = ['1','2.0','3.00000001','3.9999999']

            self.table.setRowCount(4)

            for index in range(4):
                item1 = QtWidgets.QTableWidgetItem(data1[index])
                self.table.setItem(index,0,item1)
                item2 = QtWidgets.QTableWidgetItem(data2[index])
                self.table.setItem(index,1,item2)
                self.btn_sell = IndexedButtonWidget('Edit')
                self.btn_sell.button_row = index
                self.btn_sell.button_column = 2
                self.btn_sell.clicked.connect(self.handleButtonClicked)
                self.table.setCellWidget(index,2,self.btn_sell)

        def handleButtonClicked(self):
            button = self.sender()
            print(button.button_row)
            print(button.button_column)

Do you have any clue about which is the problem?

Body:
The IndexedButtonWidget is instantiated with one argument: 'Edit'

self.btn_sell = IndexedButtonWidget('Edit')

The documentation shows that there is only one QPushButton.__init__() which takes one argument: QPushButton(self, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None. So the code ends up passing 'Edit' as parent, hence the TypeError.

help(QPushButton)

Help on class QPushButton in module PySide6.QtWidgets:

class QPushButton(QAbstractButton)
 |  QPushButton(self, icon: Union[PySide6.QtGui.QIcon, PySide6.QtGui.QPixmap], text: str, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None
 |  QPushButton(self, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None
 |  QPushButton(self, text: str, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None
 |
 |  Method resolution order:
 |      QPushButton
 |      QAbstractButton
 |      QWidget
 |      PySide6.QtCore.QObject
 |      PySide6.QtGui.QPaintDevice
 |      Shiboken.Object
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __delattr__(self, name, /)
 |      Implement delattr(self, name).
 |
 |  __init__(...)
 |      __init__(self, icon: Union[PySide6.QtGui.QIcon, PySide6.QtGui.QPixmap], text: str, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None
 |      __init__(self, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None
 |      __init__(self, text: str, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None
 |
 |      Initialize self.  See help(type(self)) for accurate signature.

This error can be solved by updating IndexedButtonWidget.__init__().

class IndexedButtonWidget(QPushButton):
    def __init__(self, text='', parent=None):
        super(QPushButton, self).__init__(text, parent=parent)
        self.button_row = 0
        self.button_column = 0

There are other ways to write __init__() so that the TypeError doesn't occur, but this solves the specific error in the question.


问:
Cannot autheticate gcloud
I am trying to authenticate my gcloud. I can run gcloud init and everything goes smoothly but the terminal does not proceed beyond giving me the link to open the authentication browser link.

I run:

```<code>gcloud init
</code>```

and, I get

```<code>Welcome! This command will take you through the configuration of gcloud.

Your current configuration has been set to: [default]

You can skip diagnostics next time by using the following flag:
  gcloud init --skip-diagnostics

Network diagnostic detects and fixes local network connection issues.
Checking network connection...done.
Reachability Check passed.
Network diagnostic passed (1/1 checks passed).

You must log in to continue. Would you like to log in (Y/n)?  Y
</code>```

I proceed with Y and it automatically opens the browser tab and asks me to log in to my google account. meanwhile the terminal has reached

```<code>Your browser has been opened to visit:

    https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=32555940559.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8085%2F&scope=openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fappengine.admin+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcompute+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Faccounts.reauth&state=nAOd8W8sIVuPPQyBtbdolPPSAUctM67&access_type=offline&code_challenge=pBvvLeTf4D1x7AuhvuOkCsv8Yxq6-ldWOKs5AP3YPn0&code_challenge_method=S256
</code>```

I successfully log in to my google account and it gives me

```<code>You are now authenticated with the gcloud CLI!
</code>```

But, the terminal remains stuck at the screen and nothing happens. I forcibly quit it with ctrl+c

I run

```<code>gclouds projects list

</code>```

and I get

```<code>ERROR: (gcloud.projects.list) You do not currently have an active account selected.
Please run:

  $ gcloud auth login

to obtain new credentials.

If you have already logged in with a different account:

    $ gcloud config set account ACCOUNT

to select an already authenticated account to use.
</code>```

--no-browser or --no-console options do not help as well as nothing happens post pasting the key in my terminal. And I have to forcibly quit the browser and then I find out that gcloud has not been authenticated.

How to get my gcloud authenticated?

答:
This may be a permission problem in the user profile; just see where it fails to write:</p>
```<code>strace -e trace=open,close,read,write gcloud init
</code>```

Title: Cannot autheticate gcloud

Body:
I am trying to authenticate my gcloud. I can run gcloud init and everything goes smoothly but the terminal does not proceed beyond giving me the link to open the authentication browser link.

I run:

gcloud init

and, I get

Welcome! This command will take you through the configuration of gcloud.

Your current configuration has been set to: [default]

You can skip diagnostics next time by using the following flag:
  gcloud init --skip-diagnostics

Network diagnostic detects and fixes local network connection issues.
Checking network connection...done.
Reachability Check passed.
Network diagnostic passed (1/1 checks passed).

You must log in to continue. Would you like to log in (Y/n)?  Y

I proceed with Y and it automatically opens the browser tab and asks me to log in to my google account. meanwhile the terminal has reached

Your browser has been opened to visit:

    https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=32555940559.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8085%2F&scope=openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fappengine.admin+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcompute+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Faccounts.reauth&state=nAOd8W8sIVuPPQyBtbdolPPSAUctM67&access_type=offline&code_challenge=pBvvLeTf4D1x7AuhvuOkCsv8Yxq6-ldWOKs5AP3YPn0&code_challenge_method=S256

I successfully log in to my google account and it gives me

You are now authenticated with the gcloud CLI!

But, the terminal remains stuck at the screen and nothing happens. I forcibly quit it with ctrl+c

I run

gclouds projects list

and I get

ERROR: (gcloud.projects.list) You do not currently have an active account selected.
Please run:

  $ gcloud auth login

to obtain new credentials.

If you have already logged in with a different account:

    $ gcloud config set account ACCOUNT

to select an already authenticated account to use.

--no-browser or --no-console options do not help as well as nothing happens post pasting the key in my terminal. And I have to forcibly quit the browser and then I find out that gcloud has not been authenticated.

How to get my gcloud authenticated?

Body:
This may be a permission problem in the user profile; just see where it fails to write:

strace -e trace=open,close,read,write gcloud init


问:
Compare Matrix Multiplication Execution Time in Different Sizes in C
I need to calculate and compare execution time of multiplication of 2 matrices in 3 different sizes (100 * 100 , 1000 * 1000 and 10000 * 10000) in C programming language. I wrote the following simple code to do that for 1000 * 1000 and I got the execution time

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int r1 = 1000, c1 = 1000, r2 = 1000, c2 = 1000, i, j, k;

    // Dynamic allocation.
    double(*a)[r1][c1] = malloc(sizeof *a);
    double(*b)[r2][c2] = malloc(sizeof *b);
    double(*result)[r1][c2] = malloc(sizeof *result);

    // Storing elements of first matrix.
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c1; ++j)
        {
            (*a)[i][j] = rand() / RAND_MAX;
        }
    }

    // Storing elements of second matrix.
    for (i = 0; i < r2; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*b)[i][j] = rand() / RAND_MAX;
        }
    }

    // Initializing all elements of result matrix to 0
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*result)[i][j] = 0;
        }
    }

    clock_t begin1 = clock();
    // Multiplying matrices a and b and
    // storing result in result matrix
    for (i = 0; i < r1; ++i)
        for (j = 0; j < c2; ++j)
            for (k = 0; k < c1; ++k)
            {
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];
            }

    clock_t end1 = clock();
    double time_taken = (double)(end1 - begin1) / CLOCKS_PER_SEC;
    printf("\n function took %f seconds to execute \n", time_taken);
    return 0;
}
</code>```

And now I want to repeat this part for two other sizes and get the result like this at the end of my program with one run:

```<code>the execution time for 100 * 100 is 1 second
the execution time for 1000 * 1000 is 2 seconds
the execution time for 10000 * 10000 is 3 seconds
</code>```

What is the best solution for that? When I repeat this part for 10000 * 10000 after 1000 * 1000 I got the segmentation fault error.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int r1 = 1000, c1 = 1000, r2 = 1000, c2 = 1000, i, j, k;

    // Dynamic allocation.
    double(*a)[r1][c1] = malloc(sizeof *a);
    double(*b)[r2][c2] = malloc(sizeof *b);
    double(*result)[r1][c2] = malloc(sizeof *result);

    // Storing elements of first matrix.
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c1; ++j)
        {
            (*a)[i][j] = rand() / RAND_MAX;
        }
    }

    // Storing elements of second matrix.
    for (i = 0; i < r2; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*b)[i][j] = rand() / RAND_MAX;
        }
    }

    // Initializing all elements of result matrix to 0
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*result)[i][j] = 0;
        }
    }

    clock_t begin1 = clock();
    // Multiplying matrices a and b and
    // storing result in result matrix
    for (i = 0; i < r1; ++i)
        for (j = 0; j < c2; ++j)
            for (k = 0; k < c1; ++k)
            {
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];
            }

    clock_t end1 = clock();
    double time_taken = (double)(end1 - begin1) / CLOCKS_PER_SEC;
    printf("\n \nfunction took %f seconds to execute \n",
           time_taken);
    free(a);
    free(b);
    free(result);

    r1 = 10000, c1 = 10000, r2 = 10000, c2 = 10000;
printf("\n run second one for %d \n",r1);
    // Storing elements of first matrix.
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c1; ++j)
        {
            (*a)[i][j] = rand() / RAND_MAX;
        }
    }

    // Storing elements of second matrix.
    for (i = 0; i < r2; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*b)[i][j] = rand() / RAND_MAX;
        }
    }

    // Initializing all elements of result matrix to 0
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*result)[i][j] = 0;
        }
    }

    begin1 = clock();
    // Multiplying matrices a and b and
    // storing result in result matrix
    for (i = 0; i < r1; ++i)
        for (j = 0; j < c2; ++j)
            for (k = 0; k < c1; ++k)
            {
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];
            }

    end1 = clock();
    time_taken = (double)(end1 - begin1) / CLOCKS_PER_SEC;
    printf("\n second function took %f seconds to execute \n",
           time_taken);
    free(a);
    free(b);
    free(result);

    return 0;
}
</code>```

答:
A simplified version of your program:

```<code>...
int main()
{

    int r1 = 1000, c1 = 1000, r2 = 1000, c2 = 1000, i, j, k;

    // Dynamic allocation.

    double(*a)[r1][c1] = malloc(sizeof *a);
    double(*b)[r2][c2] = malloc(sizeof *b);
    double(*result)[r1][c2] = malloc(sizeof *result);

    ...

    free(a);
    free(b);
    free(result);

    r1 = 10000, c1 = 10000, r2 = 10000, c2 = 10000;
    for (i = 0; i < r1; ++i)
        for (j = 0; j < c1; ++j)
            (*a)[i][j] = rand() /RAND_MAX; // KABOOM !
...
}
</code>```

A quick but crucial information about about VLA arrays. Name "variable" in "variable-length-array" means that the size is stored in a variable, not that the size is variable. This variable is hidden and can be only read via sizeof operator.

The size of array is bound to it's type, not to its value. Therefore the dimensions of VLA type (and object) cannot change, no matter if the object is dynamic or automatic.

The line:

```<code>double(*a)[r1][c1] = malloc(sizeof *a);
</code>```

it interpreted as:

```<code>typedef double __hidden_type[r1][c1];
__hidden_type* a = malloc(sizeof *a);

... changes of r1 or c1 do not affect sizeof(__hidden_type)
</code>```

The sizes are bound to the types when the types are defined. After that the types are immutable.

Therefore changing the r1 does not change the size of *a. You need to create a new a (or rather its type) and allocate memory for this new *a.

I suggest moving the whole test to a function that takes r1, r2, c1 and c2 as parameters. The arrays would be local to the function.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void bench(int r1, int c1, int r2, int c2) {
    int i, j, k;

    // Dynamic allocation.

    double(*a)[r1][c1] = malloc(sizeof *a);
    double(*b)[r2][c2] = malloc(sizeof *b);
    double(*result)[r1][c2] = malloc(sizeof *result);

    // Storing elements of first matrix.
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c1; ++j)
        {
            (*a)[i][j] = rand() /RAND_MAX;
        }
    }

    // Storing elements of second matrix.

    for (i = 0; i < r2; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*b)[i][j] = rand()/ RAND_MAX;
        }
    }
    // Initializing all elements of result matrix to 0
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*result)[i][j] = 0;
        }
    }
     clock_t begin1 = clock();
    // Multiplying matrices a and b and
    // storing result in result matrix
    for (i = 0; i < r1; ++i)
        for (j = 0; j < c2; ++j)
            for (k = 0; k < c1; ++k)
            {
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];
            }

    clock_t end1 = clock();
    double time_taken = (double)(end1 - begin1) / CLOCKS_PER_SEC;
   printf("\n \nfunction took %f seconds to execute \n", time_taken);
    free(a);
    free(b);
    free(result);
}

int main()
{
    bench(1000, 1000, 1000, 1000);
    bench(2000, 2000, 2000, 2000);
}
</code>```

I've reduced the size from 10000 to 2000 to get results in reasonable time.
On my machine I got:

```<code>function took 1.966788 seconds to execute
function took 37.370633 seconds to execute
</code>```

Note that the function is very cache unfriendly.

```<code>    for (i = 0; i < r1; ++i)
        for (j = 0; j < c2; ++j)
            for (k = 0; k < c1; ++k)
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];
</code>```

On every iteration of k you get a cache miss when accessing (*b)[k][j]. Try swapping the j and k  loops:

```<code>    for (i = 0; i < r1; ++i)
      for (k = 0; k < c1; ++k)
        for (j = 0; j < c2; ++j)
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];
</code>```

Now when increasing j then (*result)[i][j] and (*b)[k][j] are likely in cache.
On my machine this trivial change gave 10x speedup:

```<code>function took 0.319594 seconds to execute
function took 3.829459 seconds to execute
</code>```

Body:
I need to calculate and compare execution time of multiplication of 2 matrices in 3 different sizes (100 * 100 , 1000 * 1000 and 10000 * 10000) in C programming language. I wrote the following simple code to do that for 1000 * 1000 and I got the execution time

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int r1 = 1000, c1 = 1000, r2 = 1000, c2 = 1000, i, j, k;

    // Dynamic allocation.
    double(*a)[r1][c1] = malloc(sizeof *a);
    double(*b)[r2][c2] = malloc(sizeof *b);
    double(*result)[r1][c2] = malloc(sizeof *result);

    // Storing elements of first matrix.
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c1; ++j)
        {
            (*a)[i][j] = rand() / RAND_MAX;
        }
    }

    // Storing elements of second matrix.
    for (i = 0; i < r2; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*b)[i][j] = rand() / RAND_MAX;
        }
    }

    // Initializing all elements of result matrix to 0
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*result)[i][j] = 0;
        }
    }

    clock_t begin1 = clock();
    // Multiplying matrices a and b and
    // storing result in result matrix
    for (i = 0; i < r1; ++i)
        for (j = 0; j < c2; ++j)
            for (k = 0; k < c1; ++k)
            {
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];
            }

    clock_t end1 = clock();
    double time_taken = (double)(end1 - begin1) / CLOCKS_PER_SEC;
    printf("\n function took %f seconds to execute \n", time_taken);
    return 0;
}

And now I want to repeat this part for two other sizes and get the result like this at the end of my program with one run:

the execution time for 100 * 100 is 1 second
the execution time for 1000 * 1000 is 2 seconds
the execution time for 10000 * 10000 is 3 seconds

What is the best solution for that? When I repeat this part for 10000 * 10000 after 1000 * 1000 I got the segmentation fault error.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int r1 = 1000, c1 = 1000, r2 = 1000, c2 = 1000, i, j, k;

    // Dynamic allocation.
    double(*a)[r1][c1] = malloc(sizeof *a);
    double(*b)[r2][c2] = malloc(sizeof *b);
    double(*result)[r1][c2] = malloc(sizeof *result);

    // Storing elements of first matrix.
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c1; ++j)
        {
            (*a)[i][j] = rand() / RAND_MAX;
        }
    }

    // Storing elements of second matrix.
    for (i = 0; i < r2; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*b)[i][j] = rand() / RAND_MAX;
        }
    }

    // Initializing all elements of result matrix to 0
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*result)[i][j] = 0;
        }
    }

    clock_t begin1 = clock();
    // Multiplying matrices a and b and
    // storing result in result matrix
    for (i = 0; i < r1; ++i)
        for (j = 0; j < c2; ++j)
            for (k = 0; k < c1; ++k)
            {
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];
            }

    clock_t end1 = clock();
    double time_taken = (double)(end1 - begin1) / CLOCKS_PER_SEC;
    printf("\n \nfunction took %f seconds to execute \n",
           time_taken);
    free(a);
    free(b);
    free(result);

    r1 = 10000, c1 = 10000, r2 = 10000, c2 = 10000;
printf("\n run second one for %d \n",r1);
    // Storing elements of first matrix.
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c1; ++j)
        {
            (*a)[i][j] = rand() / RAND_MAX;
        }
    }

    // Storing elements of second matrix.
    for (i = 0; i < r2; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*b)[i][j] = rand() / RAND_MAX;
        }
    }

    // Initializing all elements of result matrix to 0
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*result)[i][j] = 0;
        }
    }

    begin1 = clock();
    // Multiplying matrices a and b and
    // storing result in result matrix
    for (i = 0; i < r1; ++i)
        for (j = 0; j < c2; ++j)
            for (k = 0; k < c1; ++k)
            {
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];
            }

    end1 = clock();
    time_taken = (double)(end1 - begin1) / CLOCKS_PER_SEC;
    printf("\n second function took %f seconds to execute \n",
           time_taken);
    free(a);
    free(b);
    free(result);

    return 0;
}

Body:
A simplified version of your program:

...
int main()
{

    int r1 = 1000, c1 = 1000, r2 = 1000, c2 = 1000, i, j, k;

    // Dynamic allocation.

    double(*a)[r1][c1] = malloc(sizeof *a);
    double(*b)[r2][c2] = malloc(sizeof *b);
    double(*result)[r1][c2] = malloc(sizeof *result);

    ...

    free(a);
    free(b);
    free(result);

    r1 = 10000, c1 = 10000, r2 = 10000, c2 = 10000;
    for (i = 0; i < r1; ++i)
        for (j = 0; j < c1; ++j)
            (*a)[i][j] = rand() /RAND_MAX; // KABOOM !
...
}

A quick but crucial information about about VLA arrays. Name "variable" in "variable-length-array" means that the size is stored in a variable, not that the size is variable. This variable is hidden and can be only read via sizeof operator.

The size of array is bound to it's type, not to its value. Therefore the dimensions of VLA type (and object) cannot change, no matter if the object is dynamic or automatic.

The line:

double(*a)[r1][c1] = malloc(sizeof *a);

it interpreted as:

typedef double __hidden_type[r1][c1];
__hidden_type* a = malloc(sizeof *a);

... changes of r1 or c1 do not affect sizeof(__hidden_type)

The sizes are bound to the types when the types are defined. After that the types are immutable.

Therefore changing the r1 does not change the size of *a. You need to create a new a (or rather its type) and allocate memory for this new *a.

I suggest moving the whole test to a function that takes r1, r2, c1 and c2 as parameters. The arrays would be local to the function.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void bench(int r1, int c1, int r2, int c2) {
    int i, j, k;

    // Dynamic allocation.

    double(*a)[r1][c1] = malloc(sizeof *a);
    double(*b)[r2][c2] = malloc(sizeof *b);
    double(*result)[r1][c2] = malloc(sizeof *result);

    // Storing elements of first matrix.
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c1; ++j)
        {
            (*a)[i][j] = rand() /RAND_MAX;
        }
    }

    // Storing elements of second matrix.

    for (i = 0; i < r2; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*b)[i][j] = rand()/ RAND_MAX;
        }
    }
    // Initializing all elements of result matrix to 0
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*result)[i][j] = 0;
        }
    }
     clock_t begin1 = clock();
    // Multiplying matrices a and b and
    // storing result in result matrix
    for (i = 0; i < r1; ++i)
        for (j = 0; j < c2; ++j)
            for (k = 0; k < c1; ++k)
            {
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];
            }

    clock_t end1 = clock();
    double time_taken = (double)(end1 - begin1) / CLOCKS_PER_SEC;
   printf("\n \nfunction took %f seconds to execute \n", time_taken);
    free(a);
    free(b);
    free(result);
}

int main()
{
    bench(1000, 1000, 1000, 1000);
    bench(2000, 2000, 2000, 2000);
}

I've reduced the size from 10000 to 2000 to get results in reasonable time.
On my machine I got:

function took 1.966788 seconds to execute
function took 37.370633 seconds to execute

Note that the function is very cache unfriendly.

    for (i = 0; i < r1; ++i)
        for (j = 0; j < c2; ++j)
            for (k = 0; k < c1; ++k)
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];

On every iteration of k you get a cache miss when accessing (*b)[k][j]. Try swapping the j and k  loops:

    for (i = 0; i < r1; ++i)
      for (k = 0; k < c1; ++k)
        for (j = 0; j < c2; ++j)
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];

Now when increasing j then (*result)[i][j] and (*b)[k][j] are likely in cache.
On my machine this trivial change gave 10x speedup:

function took 0.319594 seconds to execute
function took 3.829459 seconds to execute


问:
How do I add text to the side of an image in HTML
I'm trying to add text to the side of an image (more of an oval) in HTML, does anyone know how?

答:
If you put text inside a  element it will be on the same line (inline).

```<code><div>
    <img src="img.png" />
    <span>your text here</span>
<div>
</code>```

If you'd like to center your text to the left, a simple CSS flex box solution would be:

```<code>div {
  display: flex;
  align-items: center;
}

   span {
  padding: 15px;
}
</code>```

Body:
If you put text inside a  element it will be on the same line (inline).

<div>
    <img src="img.png" />
    <span>your text here</span>
<div>

If you'd like to center your text to the left, a simple CSS flex box solution would be:

div {
  display: flex;
  align-items: center;
}

   span {
  padding: 15px;
}


问:
Primeng v11 progress spinner does not change color
I'm using primeng version 11, and I'm trying to change the color of the spinner bar, I tried copying the code form primeng but it did not work for me.

html:

css:

```<code>@keyframes custom-progress-spinner-color {
    100%,
    0% {
        stroke: #16697A;
    }
    40% {
        stroke: #489FB5;
    }
    66% {
        stroke: #82C0CC;
    }
    80%,
    90% {
        stroke: #FFA62B;
    }
}
</code>```

module is imported and checked everything.

答:
You can just use the same class name, no need for a new one:

```<code>@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styles: [`
    @keyframes p-progress-spinner-color {
        from {
            stroke: #yourColor;
        }

        to {
            stroke: #yourColor;
        }
    }
`]
</code>```

})

Even you can use 'from' and 'to' which are equivalent to percentages... cheers!!!
See the doc for reference

Body:
I'm using primeng version 11, and I'm trying to change the color of the spinner bar, I tried copying the code form primeng but it did not work for me.

html:

css:

@keyframes custom-progress-spinner-color {
    100%,
    0% {
        stroke: #16697A;
    }
    40% {
        stroke: #489FB5;
    }
    66% {
        stroke: #82C0CC;
    }
    80%,
    90% {
        stroke: #FFA62B;
    }
}

module is imported and checked everything.

Body:
You can just use the same class name, no need for a new one:

@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styles: [`
    @keyframes p-progress-spinner-color {
        from {
            stroke: #yourColor;
        }

        to {
            stroke: #yourColor;
        }
    }
`]

})

Even you can use 'from' and 'to' which are equivalent to percentages... cheers!!!
See the doc for reference


问:
pyfinance dividends and documentation
I'm trying to use pyfinance to pull data, I have run into issues with the dividends. Below is the code, the error I et is:

```<code>    import yfinance as yf

print('Enter Ticker:')
symbol = input()
symbol = yf.Ticker(symbol)
print('Forward PE:')
print(symbol.info['forwardPE'])
print('Dividends:')

info = yf.Ticker(symbol).info
div = info.get('trailingAnnualDividendYield')
print(div)
</code>```

Does anyone have documentation for pyfinance? What I have been able to find is slim, how can I view the modules/classes/etc

Error from python interpreter:

```<code>    Enter Ticker:
c
Forward PE:
8.224477
Dividends:
Traceback (most recent call last):
  File "/home/user/Desktop/test.py", line 10, in <module>
    info = yf.Ticker(symbol).info
  File "/home/user/.local/lib/python3.9/site-packages/yfinance/base.py", line 49, in __init__
    self.ticker = ticker.upper()
AttributeError: 'Ticker' object has no attribute 'upper'
</code>```

答:
You assign symbol = yf.Ticker(symbol), so symbol is yfinance.Ticker object now, not a string. And then you call yf.Ticker(symbol).info (which is not needed) that leads to an error. Don't save on variables names.

```<code>import yfinance as yf

print('Enter Ticker:')
symbol = input()
s = yf.Ticker(symbol)
print('Forward PE:')
print(s.info['forwardPE'])
print('Dividends:')

div = s.info.get('trailingAnnualDividendYield')
print(div)
</code>```

And the results:

```<code>Enter Ticker:
ibm
Forward PE:
12.553453
Dividends:
0.049131215
</code>```

Title: pyfinance dividends and documentation

Body:
I'm trying to use pyfinance to pull data, I have run into issues with the dividends. Below is the code, the error I et is:

    import yfinance as yf

print('Enter Ticker:')
symbol = input()
symbol = yf.Ticker(symbol)
print('Forward PE:')
print(symbol.info['forwardPE'])
print('Dividends:')

info = yf.Ticker(symbol).info
div = info.get('trailingAnnualDividendYield')
print(div)

Does anyone have documentation for pyfinance? What I have been able to find is slim, how can I view the modules/classes/etc

Error from python interpreter:

    Enter Ticker:
c
Forward PE:
8.224477
Dividends:
Traceback (most recent call last):
  File "/home/user/Desktop/test.py", line 10, in <module>
    info = yf.Ticker(symbol).info
  File "/home/user/.local/lib/python3.9/site-packages/yfinance/base.py", line 49, in __init__
    self.ticker = ticker.upper()
AttributeError: 'Ticker' object has no attribute 'upper'

Body:
You assign symbol = yf.Ticker(symbol), so symbol is yfinance.Ticker object now, not a string. And then you call yf.Ticker(symbol).info (which is not needed) that leads to an error. Don't save on variables names.

import yfinance as yf

print('Enter Ticker:')
symbol = input()
s = yf.Ticker(symbol)
print('Forward PE:')
print(s.info['forwardPE'])
print('Dividends:')

div = s.info.get('trailingAnnualDividendYield')
print(div)

And the results:

Enter Ticker:
ibm
Forward PE:
12.553453
Dividends:
0.049131215