问:
How can I test css properties for a React component using react-testing-library?
The philosophy behind the react-testing-library makes sense to me, but I am struggling to apply it to css properties.

For example, let's say I have a simple toggle component that shows a different background color when clicked:

import React, { useState } from "react";
import "./Toggle.css";

const Toggle = () => {
  const [ selected, setSelected ] = useState(false);
  return (

 setSelected(!selected)}>
      {selected ? "On" : "Off"}

  );
}

export default Toggle;
```

<pre class="lang-css prettyprint-override"><code>.on {
  background-color: green;
}

.off {
  background-color: red;
}
</code>```

How should I test this component? I wrote the following test, which works for inline component styles, but fails when using css classes as shown above.

import React from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import Toggle from "./Toggle";

const backgroundColor = (element) => window.getComputedStyle(element).backgroundColor;

describe("Toggle", () => {
  it("updates the background color when clicked",  () => {
    render(<Toggle />);
    fireEvent.click(screen.getByText("Off"));
    expect(backgroundColor(screen.getByText("On"))).toBe("green");
  });
});
```

答:
For making sure the styling is okay, I prefer snapshot testing. How about firing the event and taking snapshots for both states/cases. Here is what it would look like: </p>

```<code>import React from 'react'
import {render} from '@testing-library/react'

 it('should take a snapshot when button is toggled', () => {
    const { asFragment } = render(<App />)
    // Fire the event
    expect(asFragment(<App />)).toMatchSnapshot()
   })
});
</code>```

Body:
The philosophy behind the react-testing-library makes sense to me, but I am struggling to apply it to css properties.

For example, let's say I have a simple toggle component that shows a different background color when clicked:

import React, { useState } from "react";
import "./Toggle.css";

const Toggle = () => {
  const [ selected, setSelected ] = useState(false);
  return (

 setSelected(!selected)}>
      {selected ? "On" : "Off"}

  );
}

export default Toggle;

.on {
  background-color: green;
}

.off {
  background-color: red;
}

How should I test this component? I wrote the following test, which works for inline component styles, but fails when using css classes as shown above.

import React from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import Toggle from "./Toggle";

const backgroundColor = (element) => window.getComputedStyle(element).backgroundColor;

describe("Toggle", () => {
  it("updates the background color when clicked",  () => {
    render(<Toggle />);
    fireEvent.click(screen.getByText("Off"));
    expect(backgroundColor(screen.getByText("On"))).toBe("green");
  });
});

Body:
For making sure the styling is okay, I prefer snapshot testing. How about firing the event and taking snapshots for both states/cases. Here is what it would look like:

import React from 'react'
import {render} from '@testing-library/react'

 it('should take a snapshot when button is toggled', () => {
    const { asFragment } = render(<App />)
    // Fire the event
    expect(asFragment(<App />)).toMatchSnapshot()
   })
});


来源: stackexchange

问:
How to deserialize MessagePack in Spring Cloud Stream App
I'm trying to create a Kafka streams app using Spring Cloud Stream, but am struggling to deserialize the input messages, whose values have been encoded using MessagePack.

Here's what I've got so far:

```<code>// TransactionApplication.java

@SpringBootApplication
public class TransactionApplication {

  public static void main(String[] args) {
    SpringApplication.run(TransactionApplication.class, args);
  }

  public static class TransactionConsumer {

    @Bean
    public Serde<Transaction> transactionSerde() {
      ObjectMapper mapper = new ObjectMapper(new MessagePackFactory());
      return new JsonSerde<Transaction>(mapper);
    }

    @Bean
    public Consumer<KStream<String, Transaction>> process() {
      return input -> input.foreach((key, value) -> {
        System.out.println("Key: " + key + " Value: " + value);
      });
    }
  }
}
</code>```
```<code>// Transaction.java

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Transaction {
  String item;
  Number amount;
}
</code>```

I'm getting the error:

java.lang.IllegalStateException: No type information in headers and no default type provided.

My application.yml is:

```<code>spring.cloud.stream:
  bindings:
    process-in-0:
      destination: transactions
  kafka:
    streams:
      binder:
        applicationId: transactions-application
        configuration:
          commit.interval.ms: 100

</code>```

After including spring.json.value.default.type: com.example.Transaction underneath the configuration node of my applicaton.yml, I'm getting another error. See below.

```<code>Caused by: org.apache.kafka.common.errors.SerializationException: Can't deserialize data [[123, 34, 105, 116, 101, 109, 34, 58, 32, 34, 112, 114, 105, 118, 97, 116, 101, 32, 106, 101, 116, 34, 44, 32, 34, 97, 109, 111, 117, 110, 116, 34, 58, 32, 53, 48, 50, 125]] from topic [transactions]
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.jackdry.processors.json.Transaction` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (123)
 at [Source: (byte[])"{"item": "private jet", "amount": 502}"; line: -1, column: 0]
</code>```

答:
You need to provide a hint to the deserializer to tell it what object to create from the encoded payload.

If the record was created by the Spring JsonSerializer, the hints are in the headers.

If not, you have to provide the hint in the streams configuration.

You need to show your application.yml/properties.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create a Kafka streams app using Spring Cloud Stream, but am struggling to deserialize the input messages, whose values have been encoded using MessagePack.

Here's what I've got so far:

// TransactionApplication.java

@SpringBootApplication
public class TransactionApplication {

  public static void main(String[] args) {
    SpringApplication.run(TransactionApplication.class, args);
  }

  public static class TransactionConsumer {

    @Bean
    public Serde<Transaction> transactionSerde() {
      ObjectMapper mapper = new ObjectMapper(new MessagePackFactory());
      return new JsonSerde<Transaction>(mapper);
    }

    @Bean
    public Consumer<KStream<String, Transaction>> process() {
      return input -> input.foreach((key, value) -> {
        System.out.println("Key: " + key + " Value: " + value);
      });
    }
  }
}

// Transaction.java

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Transaction {
  String item;
  Number amount;
}

I'm getting the error:

java.lang.IllegalStateException: No type information in headers and no default type provided.

My application.yml is:

spring.cloud.stream:
  bindings:
    process-in-0:
      destination: transactions
  kafka:
    streams:
      binder:
        applicationId: transactions-application
        configuration:
          commit.interval.ms: 100

After including spring.json.value.default.type: com.example.Transaction underneath the configuration node of my applicaton.yml, I'm getting another error. See below.

Caused by: org.apache.kafka.common.errors.SerializationException: Can't deserialize data [[123, 34, 105, 116, 101, 109, 34, 58, 32, 34, 112, 114, 105, 118, 97, 116, 101, 32, 106, 101, 116, 34, 44, 32, 34, 97, 109, 111, 117, 110, 116, 34, 58, 32, 53, 48, 50, 125]] from topic [transactions]
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.jackdry.processors.json.Transaction` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (123)
 at [Source: (byte[])"{"item": "private jet", "amount": 502}"; line: -1, column: 0]


问:
maple code output does not display on the screen
I've just downloaded the  Maple 2020 trial version and I have zero experience on Maple programming. My problem is: when I do simple calculations such as 3+5 or 2*3, the result displays on the screen but, for other functions such as

```<code>   factor(x^2+2x+1);
</code>```

or assigning variables can't be done:

```<code>    n:= 5;
    m:=7;
    m+n;
</code>```

I do not see any results on the  display screen after the enter.

Where am I doing wrong?

答:
It seems like, I need to change some configurations of the Maple. After doing some search online, I found these suggestions in a web site. I have applied the following steps and my problem is solved: (Remember to apply globally not for the session.)

Open a new blank worksheet

On the toolbar, access Tools->Options.

Select the 'Display' tab

Ensure that the first entry is set to 'Maple Notation', and the second entry is set to '2-D Math Notation'

Click 'Apply to session' at the bottom left

On the toolbar, access Tools->Options again

Select the 'Interface' tab

Ensure that the entry 'Default format for new worksheet' is set to 'Worksheet'

Click 'Apply to session' at the bottom left

Now open a new worksheet in the same session. There should be a prompt '>'.

At the prompt, type 'version();' without the single quotes, but with the trailing semi-colon. This ought to return details of the precise Maple version you are running. If it returns something like

```<code>User Interface: 1133417

Kernel: 1133417

Library: 1133417
</code>```

(precise numbers may be different), then you ought to be good to go - so try something simple like 1+1; at the next command prompt, (remember the semicolon).

Body:
I've just downloaded the  Maple 2020 trial version and I have zero experience on Maple programming. My problem is: when I do simple calculations such as 3+5 or 2*3, the result displays on the screen but, for other functions such as

   factor(x^2+2x+1);

or assigning variables can't be done:

    n:= 5;
    m:=7;
    m+n;

I do not see any results on the  display screen after the enter.

Where am I doing wrong?

Body:
It seems like, I need to change some configurations of the Maple. After doing some search online, I found these suggestions in a web site. I have applied the following steps and my problem is solved: (Remember to apply globally not for the session.)

Open a new blank worksheet

On the toolbar, access Tools->Options.

Select the 'Display' tab

Ensure that the first entry is set to 'Maple Notation', and the second entry is set to '2-D Math Notation'

Click 'Apply to session' at the bottom left

On the toolbar, access Tools->Options again

Select the 'Interface' tab

Ensure that the entry 'Default format for new worksheet' is set to 'Worksheet'

Click 'Apply to session' at the bottom left

Now open a new worksheet in the same session. There should be a prompt '>'.

At the prompt, type 'version();' without the single quotes, but with the trailing semi-colon. This ought to return details of the precise Maple version you are running. If it returns something like

User Interface: 1133417

Kernel: 1133417

Library: 1133417

(precise numbers may be different), then you ought to be good to go - so try something simple like 1+1; at the next command prompt, (remember the semicolon).


问:
Why is my smooth scrolling function not working?
I'm creating a website using Django, and I want the link in the navbar (when clicked) to smoothscroll to the element that I want. This is what I have:

base.html

```<code>          <li>
            <a class="nav-item nav-link" href = '' class='scroll-about'>About</a>
          </li>
</code>```

//unrelated elements

```<code> <script>
    // scroll into view
  document.querySelector('.scroll-about').addEventListener('click', function(e) {
    e.preventDefault();
    document.querySelector('.about').scrollIntoView({ behavior: 'smooth' });
  });
</code>```

home.html

```<code>    <div class="about col-12 col-md-6">
  <div class="d-flex flex-column align-items-center py-5 text-uppercase">
    <h3 class="h3-responsive bg-primary text-center text-white rounded font-weight-bold w-50 px-4 py-2 shadow">About</h3>
    <h1 data-easy-reveal = "" class = " h1-reponsive font-weight-bold my-5 ml-3">Our vision is for every business to leave its mark on the digital world</h1>
    <h1 data-easy-reveal = "" class = "down h1-reponsive font-weight-bold ml-3">Our vision is to bring them to the next level </h1>
  </div>
</div>
</code>```

The rest of the code works fine, the Django templating is all fine. I just can't seem to get this scroll function to work. I've tried moving the script around the bottom of the html file, and as well as putting it in the head element of the html file. I've also tried using jQuery smooth scroll and it doesn't work either.

the jQuery code I tried (in this case I put scroll-about and about as the respective IDs):

```<code><script>
$("#scroll-about").click(function() {
    $([document.documentElement, document.body]).animate({
        scrollTop: $("#about").offset().top
    }, 2000);
});
</script>
</code>```

答:
i think that this is what you are trying to do. note that it works just with a tags with href="#something"

$(document).ready(function(){
  // Add smooth scrolling to all links
  $("a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height: 100vh; background: #00ced1">
Go to Section 2
</div>
<div style="height: 100vh; background: red;">
Go to Section 1
</div></code>```

Body:
I'm creating a website using Django, and I want the link in the navbar (when clicked) to smoothscroll to the element that I want. This is what I have:

base.html

            About

//unrelated elements

Body:
i think that this is what you are trying to do. note that it works just with a tags with href="#something"

$(document).ready(function(){
  // Add smooth scrolling to all links
  $("a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height: 100vh; background: #00ced1">
<a id="1" href="#2">Go to Section 2</a>
</div>
<div style="height: 100vh; background: red;">
<a id="2" href="#1">Go to Section 1</a>
</div>


问:
Questions regarding efficiency
So while working through a course on Udemy over C++ one of the challenges was to check a string to see whether it was a palindrome or not. I completed the task successfully but went about it a different way than the instructor. I understand there are a multitude of ways to complete a task but I am wondering which is more efficient and why? It may seem stupid to be wondering about this while reteaching myself coding but I feel this is something I should be keeping in mind.

```<code>//Instructors code//

# include<iostream>
using namespace std;

/*program for reverse a string and check a string is a palidrome

*/
int main()
{
    string str="MADAM";
    string rev="";
    int len=(int)str.length();
    rev.resize(len);
    for(int i=0, j=len-1; i<len; i++, j--)
    {
        rev[i]=str[j];
    }
    rev[len]='\0';
    if(str.compare(rev)==0)
        cout<<"palindrome"<<endl;
    else
        cout<<"not a pallindrome"<<endl;
    return 0;
}
</code>```

My Approach

```<code>#include <iostream>
using namespace std;

int main(){
    string str1="test";
//    cout << "Enter a string to check if it is a Palindrome: ";
//    getline(cin,str1);

    string str2;

    string::reverse_iterator it;
    for(it=str1.rbegin(); it!= str1.rend(); it++)
    {
        str2.push_back(*it);

    }
    if(!str1.compare(str2))
        cout << "\nPalindrome";
    else
        cout << "\nNot a Palindrome";
    return 0;
}
</code>```

Thank you in advance.

答:
In theory the code from your instructor is more efficient, but both examples have issues.

With your instructors code the main issue is the use of

```<code>int len=(int)str.length();
</code>```

In this example, it is okay because we know the size of the string will fit in a int, but if you were getting a string from an outside source, this could be a problem.  A std::string using an unsigned integer type to store the size of the string and that means you can have a string who's size is larger then what can fit in an int.  If that were to happen, then code is not going to work correctly.

With your code you a avoid all that, which is great, but you also leave some performance on the table.  In theory your code of

```<code>for(it=str1.rbegin(); it!= str1.rend(); it++)
{
    str2.push_back(*it);

}
</code>```

is going to cause str2 to have multiple buffer allocations and copies from the old buffer to the new buffer as it grows.  This is a lot of extra work that you don't need to do since you already know how much space you need to allocate.  Having

```<code>str2.reserve(str1.size() + 1);
</code>```

before the loop pre-allocates all the space you need so you don't have those potential performance hits.

Then we come to the fact that both of your examples are using a second string.  You don't need another string to check for a palindrome.  What you can do is just check and see if the first and last characters are the same, and if they are move on to the first+1 and last-1 character and so on until you reach the middle or they don't match.  You can do that using a construct like

```<code>bool is_palindrome = true;
for (auto start = str.begin(), end = str.end() - 1;
     start < end && is_palindrome;
     ++start, --end)
{
    if (*start != *end)
        is_palindrom = false
}
if (is_palindrome)
    std::cout << "palindrome\n";
else
    std::cout << "not a pallindrome\n";
</code>```

Title: Questions regarding efficiency

Body:
So while working through a course on Udemy over C++ one of the challenges was to check a string to see whether it was a palindrome or not. I completed the task successfully but went about it a different way than the instructor. I understand there are a multitude of ways to complete a task but I am wondering which is more efficient and why? It may seem stupid to be wondering about this while reteaching myself coding but I feel this is something I should be keeping in mind.

//Instructors code//

# include<iostream>
using namespace std;

/*program for reverse a string and check a string is a palidrome

*/
int main()
{
    string str="MADAM";
    string rev="";
    int len=(int)str.length();
    rev.resize(len);
    for(int i=0, j=len-1; i<len; i++, j--)
    {
        rev[i]=str[j];
    }
    rev[len]='\0';
    if(str.compare(rev)==0)
        cout<<"palindrome"<<endl;
    else
        cout<<"not a pallindrome"<<endl;
    return 0;
}

My Approach

#include <iostream>
using namespace std;

int main(){
    string str1="test";
//    cout << "Enter a string to check if it is a Palindrome: ";
//    getline(cin,str1);

    string str2;

    string::reverse_iterator it;
    for(it=str1.rbegin(); it!= str1.rend(); it++)
    {
        str2.push_back(*it);

    }
    if(!str1.compare(str2))
        cout << "\nPalindrome";
    else
        cout << "\nNot a Palindrome";
    return 0;
}

Thank you in advance.

Body:
In theory the code from your instructor is more efficient, but both examples have issues.

With your instructors code the main issue is the use of

int len=(int)str.length();

In this example, it is okay because we know the size of the string will fit in a int, but if you were getting a string from an outside source, this could be a problem.  A std::string using an unsigned integer type to store the size of the string and that means you can have a string who's size is larger then what can fit in an int.  If that were to happen, then code is not going to work correctly.

With your code you a avoid all that, which is great, but you also leave some performance on the table.  In theory your code of

for(it=str1.rbegin(); it!= str1.rend(); it++)
{
    str2.push_back(*it);

}

is going to cause str2 to have multiple buffer allocations and copies from the old buffer to the new buffer as it grows.  This is a lot of extra work that you don't need to do since you already know how much space you need to allocate.  Having

str2.reserve(str1.size() + 1);

before the loop pre-allocates all the space you need so you don't have those potential performance hits.

Then we come to the fact that both of your examples are using a second string.  You don't need another string to check for a palindrome.  What you can do is just check and see if the first and last characters are the same, and if they are move on to the first+1 and last-1 character and so on until you reach the middle or they don't match.  You can do that using a construct like

bool is_palindrome = true;
for (auto start = str.begin(), end = str.end() - 1;
     start < end && is_palindrome;
     ++start, --end)
{
    if (*start != *end)
        is_palindrom = false
}
if (is_palindrome)
    std::cout << "palindrome\n";
else
    std::cout << "not a pallindrome\n";


问:
Pulling data from API - GET
I'm trying to pull all planets names via the Star Wars API: https://swapi.dev/

Not sure where my error is in the code below?

```<code>import React, { PureComponent } from 'react'
import axios from "axios";

class Home extends PureComponent {
    constructor(props) {
        super(props)

        this.state = {
            planets: []
        }
    }

    componentDidMount(){
        axios({
            method: "GET",
            url: "https://swapi.dev/api/planets/",
            withCredentials: true
        })
        .then(response => {
            console.log(response)
            let planetslist = response.data;
            this.setState({planets: planetslist})
        })
        .catch(error => {
            console.log("You've made an error with the planets load charles: ",error)
        })
    }

    render() {
        return (
          <div>
            <h1>Star Wars Planets</h1>
              {
                this.state.planets.map(planet =>
                    <div>
                        <p>planet.name</p>
                    </div>
                )
              }
          </div>
        )
    }
}

export default Home
</code>```

答:
The result that api return, contains planet in results field. You can use:

```<code>let planetslist = response.data.results;
</code>```

If you want look at working code, it can be found here:
https://codesandbox.io/s/jovial-stallman-fs012?file=/src/index.js:392-440

Title: Pulling data from API - GET

Body:
I'm trying to pull all planets names via the Star Wars API: https://swapi.dev/

Not sure where my error is in the code below?

import React, { PureComponent } from 'react'
import axios from "axios";

class Home extends PureComponent {
    constructor(props) {
        super(props)

        this.state = {
            planets: []
        }
    }

    componentDidMount(){
        axios({
            method: "GET",
            url: "https://swapi.dev/api/planets/",
            withCredentials: true
        })
        .then(response => {
            console.log(response)
            let planetslist = response.data;
            this.setState({planets: planetslist})
        })
        .catch(error => {
            console.log("You've made an error with the planets load charles: ",error)
        })
    }

    render() {
        return (

Star Wars Planets

              {
                this.state.planets.map(planet =>

planet.name

                )
              }

        )
    }
}

export default Home

Body:
The result that api return, contains planet in results field. You can use:

let planetslist = response.data.results;

If you want look at working code, it can be found here:
https://codesandbox.io/s/jovial-stallman-fs012?file=/src/index.js:392-440


问:
How to fix Perl from anaconda not installing bioperl? `Bailing out the installation for BioPerl-1.007002.`
I am using conda to install several packages. I already installed Perl under conda and is the one working in this machine (running Ubuntu 18.04). Now I am trying to use a script that requires bioperl.

I tried to update conda, install bioperl through conda AND installing bioperl through cpanm as shown below.

I checked to currently used Perl is the anaconda one. The shebang in the perl script is #!/home/evo-slave/anaconda_ete/bin/perl -w

This is the initial error while running the script

```<code>    Can't locate Bio/SeqIO.pm in @INC (you may need to install the
    Bio::SeqIO module) (@INC contains: /home/evo-
    slave/anaconda_ete/lib/site_perl/5.26.2/x86_64-linux-thread-multi
    /home/evo-slave/anaconda_ete/lib/site_perl/5.26.2 /home/evo-
    slave/anaconda_ete/lib/5.26.2/x86_64-linux-thread-multi /home/evo-
    slave/anaconda_ete/lib/5.26.2 .) at ./cortador.pl line 9.
    BEGIN failed--compilation aborted at ./cortador.pl line 9.
</code>```

I don`t know if this is an issue of bioperl not being called/installed by the anaconda perl or during the execution of the script, maybe this lines within the script should indicate something else

```<code>    use File::Basename;
    use Bio::SeqIO;
    use Bio::Seq;
    use Bio::DB::SeqFeature::Store;
    use Bio::SeqFeatureI;
</code>```

When I try to install

```<code>    cpanm Bio::Perl
</code>```

I got this error

```<code>    --> Working on Bio::Perl
    Fetching http://www.cpan.org/authors/id/C/CJ/CJFIELDS/BioPerl-
    1.007002.tar.gz ... OK
    Configuring BioPerl-1.007002 ... OK
    ==> Found dependencies: IO::String, Data::Stag, Test::Most
    --> Working on IO::String
    Fetching http://www.cpan.org/authors/id/G/GA/GAAS/IO-String-

    1.08.tar.gz ... OK
    Configuring IO-String-1.08 ... OK
    Building and testing IO-String-1.08 ... OK
    Successfully installed IO-String-1.08
    --> Working on Data::Stag
    Fetching http://www.cpan.org/authors/id/C/CM/CMUNGALL/Data-Stag-
    0.14.tar.gz ... OK
    Configuring Data-Stag-0.14 ... OK
    ==> Found dependencies: IO::String
    ! Installing the dependencies failed: Module 'IO::String' is not
    installed
    ! Bailing out the installation for Data-Stag-0.14.
    --> Working on Test::Most
    Fetching http://www.cpan.org/authors/id/O/OV/OVID/Test-Most-
    0.35.tar.gz ... OK
    Configuring Test-Most-0.35 ... OK
    ==> Found dependencies: Test::Warn, Test::Deep, Test::Differences,
    Test::Exception, Exception::Class
    --> Working on Test::Warn
    Fetching http://www.cpan.org/authors/id/B/BI/BIGJ/Test-Warn-
    0.36.tar.gz ... OK
    Configuring Test-Warn-0.36 ... OK
    ==> Found dependencies: Sub::Uplevel
    --> Working on Sub::Uplevel
    Fetching http://www.cpan.org/authors/id/D/DA/DAGOLDEN/Sub-Uplevel-
    0.2800.tar.gz ... OK
    Configuring Sub-Uplevel-0.2800 ... OK
    Building and testing Sub-Uplevel-0.2800 ... OK
    Successfully installed Sub-Uplevel-0.2800
    ! Installing the dependencies failed: Module 'Sub::Uplevel' is not
    installed
    ! Bailing out the installation for Test-Warn-0.36.
    --> Working on Test::Deep
    Fetching http://www.cpan.org/authors/id/R/RJ/RJBS/Test-Deep-
    1.128.tar.gz ... OK
    Configuring Test-Deep-1.128 ... OK
    Building and testing Test-Deep-1.128 ... OK
    Successfully installed Test-Deep-1.128
    --> Working on Test::Differences
    Fetching http://www.cpan.org/authors/id/D/DC/DCANTRELL/Test-
    Differences-0.67.tar.gz ... OK
    Configuring Test-Differences-0.67 ... OK
    ==> Found dependencies: Capture::Tiny, Text::Diff
    --> Working on Capture::Tiny
    Fetching http://www.cpan.org/authors/id/D/DA/DAGOLDEN/Capture-
    Tiny-0.48.tar.gz ... OK
    Configuring Capture-Tiny-0.48 ... OK
    Building and testing Capture-Tiny-0.48 ... OK
    Successfully installed Capture-Tiny-0.48
    --> Working on Text::Diff
    Fetching http://www.cpan.org/authors/id/N/NE/NEILB/Text-Diff-
    1.45.tar.gz ... OK
    Configuring Text-Diff-1.45 ... OK
    ==> Found dependencies: Algorithm::Diff
    --> Working on Algorithm::Diff
    Fetching http://www.cpan.org/authors/id/T/TY/TYEMQ/Algorithm-Diff-
    1.1903.tar.gz ... OK
    Configuring Algorithm-Diff-1.1903 ... OK
    Building and testing Algorithm-Diff-1.1903 ... OK
    Successfully installed Algorithm-Diff-1.1903
    ! Installing the dependencies failed: Module 'Algorithm::Diff' is
     not installed
    ! Bailing out the installation for Text-Diff-1.45.
    ! Installing the dependencies failed: Module 'Text::Diff' is not
    installed, Module 'Capture::Tiny' is not installed
    ! Bailing out the installation for Test-Differences-0.67.
    --> Working on Test::Exception
    Fetching http://www.cpan.org/authors/id/E/EX/EXODIST/Test-
    Exception-0.43.tar.gz ... OK
    Configuring Test-Exception-0.43 ... OK
    ==> Found dependencies: Sub::Uplevel
    ! Installing the dependencies failed: Module 'Sub::Uplevel' is not
    installed
    ! Bailing out the installation for Test-Exception-0.43.
    --> Working on Exception::Class
    Fetching http://www.cpan.org/authors/id/D/DR/DROLSKY/Exception-
    Class-1.44.tar.gz ... OK
    Configuring Exception-Class-1.44 ... OK
    ==> Found dependencies: Class::Data::Inheritable
    --> Working on Class::Data::Inheritable
    Fetching http://www.cpan.org/authors/id/T/TM/TMTM/Class-Data-
    Inheritable-0.08.tar.gz ... OK
    Configuring Class-Data-Inheritable-0.08 ... OK
    Building and testing Class-Data-Inheritable-0.08 ... OK
    Successfully installed Class-Data-Inheritable-0.08
    ! Installing the dependencies failed: Module
    'Class::Data::Inheritable' is not installed
    ! Bailing out the installation for Exception-Class-1.44.
    ! Installing the dependencies failed: Module 'Test::Exception' is
    not installed, Module 'Test::Differences' is not installed, Module
    'Exception::Class' is not installed, Module 'Test::Warn' is not
    installed, Module 'Test::Deep' is not installed
    ! Bailing out the installation for Test-Most-0.35.
    ! Installing the dependencies failed: Module 'Test::Most' is not
    installed, Module 'IO::String' is not installed, Module
    'Data::Stag'
    is not installed
    ! Bailing out the installation for BioPerl-1.007002.
    6 distributions installed
</code>```

ETA: It seems something is wrong and the dependencies of the modules that are required are not installed during a simple cpanm
Example of a round trying to install everything that is needed

```<code>
    cpanm Sub::Uplevel

    --> Working on Sub::Uplevel
    Fetching http://www.cpan.org/authors/id/D/DA/DAGOLDEN/Sub-Uplevel-0.2800.tar.gz ... OK
    Configuring Sub-Uplevel-0.2800 ... OK
    Building and testing Sub-Uplevel-0.2800 ... OK
    Successfully installed Sub-Uplevel-0.2800
    1 distribution installed
</code>```

then

```<code>    cpanm Test::Warn

    --> Working on Test::Warn
    Fetching http://www.cpan.org/authors/id/B/BI/BIGJ/Test-Warn-0.36.tar.gz ... OK
    Configuring Test-Warn-0.36 ... OK
    ==> Found dependencies: Sub::Uplevel
    --> Working on Sub::Uplevel
    Fetching http://www.cpan.org/authors/id/D/DA/DAGOLDEN/Sub-Uplevel-0.2800.tar.gz ... OK
    Configuring Sub-Uplevel-0.2800 ... OK
    Building and testing Sub-Uplevel-0.2800 ... OK
    Successfully installed Sub-Uplevel-0.2800
    ! Installing the dependencies failed: Module 'Sub::Uplevel' is not installed
    ! Bailing out the installation for Test-Warn-0.36.
    1 distribution installed
</code>```

Some info to help debugging:

$ set | grep ^PERL
PERL5LIB=:/media/evo-slave/Disco2/ANDRES/DOWNLOADS/GENOME/CAV-POC/GAAS/annotation
PERL_MB_OPT='--install_base "/home/evo-slave/perl5"'
PERL_MM_OPT=INSTALL_BASE=/home/evo-slave/perl5

$ which cpanm
/home/evo-slave/anaconda_ete/bin/cpanm

$ head -n 1 "$( which cpanm )"
#!/home/evo-slave/anaconda_ete/bin/perl
```

答:
UPDATE 2

This problem is coming up again in miniconda3 bioperl installs.

UPDATE

I have not experienced this error for a while with perl packages, so likely some updates occurred on the conda/package side that fixed this. I would recommend trying to update your conda and checking your conda channels before trying this kind of weird kludge.

ORIGINAL ANSWER

I am posting this as an answer not because it's a good idea, but because it provides more information. I am working on Amazon Linux so it's slightly different, but also running into issues with bioperl dependencies installed through conda. In my case I am trying to run VirSorter, which mentions this problem and proposes a solution that does not work for me, but suggests confirming that your PERL5LIB is properly set.

I observed that my perl is 5.26.2:

```<code>$ perl --version

This is perl 5, version 26, subversion 2 (v5.26.2) built for x86_64-linux-thread-multi
</code>```

But conda is for some obscure reason installing my perl dependencies for 5.22.0: /home/ec2-user/anaconda3/envs/virsorter/lib/perl5/site_perl/5.22.0/:

```<code>$ ls /home/ec2-user/anaconda3/envs/virsorter/lib/perl5/site_perl/5.22.0/
Algorithm  Bio  Capture  Class  Data  Devel  Exception  IO  Sub  Test  Text  URI  URI.pm  x86_64-linux-thread-multi
</code>```

I found that I could get VirSorter running, apparently successfully, by simply setting PERL5LIB to the 5.22.0 lib under conda:

```<code>OLD_PER5LIB=$PERL5LIB
export PERL5LIB=/home/ec2-user/anaconda3/envs/virsorter/lib/perl5/site_perl/5.22.0/
# run virsorter
# no errors!
</code>```

I am sure that this throws up a bunch of red flags for the perl people, and I'm sure that it's very fragile if it actually works at all. Perhaps the question is why conda is installing perl modules as the wrong perl version?

Body:
I am using conda to install several packages. I already installed Perl under conda and is the one working in this machine (running Ubuntu 18.04). Now I am trying to use a script that requires bioperl.

I tried to update conda, install bioperl through conda AND installing bioperl through cpanm as shown below.

I checked to currently used Perl is the anaconda one. The shebang in the perl script is #!/home/evo-slave/anaconda_ete/bin/perl -w

This is the initial error while running the script

    Can't locate Bio/SeqIO.pm in @INC (you may need to install the
    Bio::SeqIO module) (@INC contains: /home/evo-
    slave/anaconda_ete/lib/site_perl/5.26.2/x86_64-linux-thread-multi
    /home/evo-slave/anaconda_ete/lib/site_perl/5.26.2 /home/evo-
    slave/anaconda_ete/lib/5.26.2/x86_64-linux-thread-multi /home/evo-
    slave/anaconda_ete/lib/5.26.2 .) at ./cortador.pl line 9.
    BEGIN failed--compilation aborted at ./cortador.pl line 9.

I don`t know if this is an issue of bioperl not being called/installed by the anaconda perl or during the execution of the script, maybe this lines within the script should indicate something else

    use File::Basename;
    use Bio::SeqIO;
    use Bio::Seq;
    use Bio::DB::SeqFeature::Store;
    use Bio::SeqFeatureI;

When I try to install

    cpanm Bio::Perl

I got this error

    --> Working on Bio::Perl
    Fetching http://www.cpan.org/authors/id/C/CJ/CJFIELDS/BioPerl-
    1.007002.tar.gz ... OK
    Configuring BioPerl-1.007002 ... OK
    ==> Found dependencies: IO::String, Data::Stag, Test::Most
    --> Working on IO::String
    Fetching http://www.cpan.org/authors/id/G/GA/GAAS/IO-String-

    1.08.tar.gz ... OK
    Configuring IO-String-1.08 ... OK
    Building and testing IO-String-1.08 ... OK
    Successfully installed IO-String-1.08
    --> Working on Data::Stag
    Fetching http://www.cpan.org/authors/id/C/CM/CMUNGALL/Data-Stag-
    0.14.tar.gz ... OK
    Configuring Data-Stag-0.14 ... OK
    ==> Found dependencies: IO::String
    ! Installing the dependencies failed: Module 'IO::String' is not
    installed
    ! Bailing out the installation for Data-Stag-0.14.
    --> Working on Test::Most
    Fetching http://www.cpan.org/authors/id/O/OV/OVID/Test-Most-
    0.35.tar.gz ... OK
    Configuring Test-Most-0.35 ... OK
    ==> Found dependencies: Test::Warn, Test::Deep, Test::Differences,
    Test::Exception, Exception::Class
    --> Working on Test::Warn
    Fetching http://www.cpan.org/authors/id/B/BI/BIGJ/Test-Warn-
    0.36.tar.gz ... OK
    Configuring Test-Warn-0.36 ... OK
    ==> Found dependencies: Sub::Uplevel
    --> Working on Sub::Uplevel
    Fetching http://www.cpan.org/authors/id/D/DA/DAGOLDEN/Sub-Uplevel-
    0.2800.tar.gz ... OK
    Configuring Sub-Uplevel-0.2800 ... OK
    Building and testing Sub-Uplevel-0.2800 ... OK
    Successfully installed Sub-Uplevel-0.2800
    ! Installing the dependencies failed: Module 'Sub::Uplevel' is not
    installed
    ! Bailing out the installation for Test-Warn-0.36.
    --> Working on Test::Deep
    Fetching http://www.cpan.org/authors/id/R/RJ/RJBS/Test-Deep-
    1.128.tar.gz ... OK
    Configuring Test-Deep-1.128 ... OK
    Building and testing Test-Deep-1.128 ... OK
    Successfully installed Test-Deep-1.128
    --> Working on Test::Differences
    Fetching http://www.cpan.org/authors/id/D/DC/DCANTRELL/Test-
    Differences-0.67.tar.gz ... OK
    Configuring Test-Differences-0.67 ... OK
    ==> Found dependencies: Capture::Tiny, Text::Diff
    --> Working on Capture::Tiny
    Fetching http://www.cpan.org/authors/id/D/DA/DAGOLDEN/Capture-
    Tiny-0.48.tar.gz ... OK
    Configuring Capture-Tiny-0.48 ... OK
    Building and testing Capture-Tiny-0.48 ... OK
    Successfully installed Capture-Tiny-0.48
    --> Working on Text::Diff
    Fetching http://www.cpan.org/authors/id/N/NE/NEILB/Text-Diff-
    1.45.tar.gz ... OK
    Configuring Text-Diff-1.45 ... OK
    ==> Found dependencies: Algorithm::Diff
    --> Working on Algorithm::Diff
    Fetching http://www.cpan.org/authors/id/T/TY/TYEMQ/Algorithm-Diff-
    1.1903.tar.gz ... OK
    Configuring Algorithm-Diff-1.1903 ... OK
    Building and testing Algorithm-Diff-1.1903 ... OK
    Successfully installed Algorithm-Diff-1.1903
    ! Installing the dependencies failed: Module 'Algorithm::Diff' is
     not installed
    ! Bailing out the installation for Text-Diff-1.45.
    ! Installing the dependencies failed: Module 'Text::Diff' is not
    installed, Module 'Capture::Tiny' is not installed
    ! Bailing out the installation for Test-Differences-0.67.
    --> Working on Test::Exception
    Fetching http://www.cpan.org/authors/id/E/EX/EXODIST/Test-
    Exception-0.43.tar.gz ... OK
    Configuring Test-Exception-0.43 ... OK
    ==> Found dependencies: Sub::Uplevel
    ! Installing the dependencies failed: Module 'Sub::Uplevel' is not
    installed
    ! Bailing out the installation for Test-Exception-0.43.
    --> Working on Exception::Class
    Fetching http://www.cpan.org/authors/id/D/DR/DROLSKY/Exception-
    Class-1.44.tar.gz ... OK
    Configuring Exception-Class-1.44 ... OK
    ==> Found dependencies: Class::Data::Inheritable
    --> Working on Class::Data::Inheritable
    Fetching http://www.cpan.org/authors/id/T/TM/TMTM/Class-Data-
    Inheritable-0.08.tar.gz ... OK
    Configuring Class-Data-Inheritable-0.08 ... OK
    Building and testing Class-Data-Inheritable-0.08 ... OK
    Successfully installed Class-Data-Inheritable-0.08
    ! Installing the dependencies failed: Module
    'Class::Data::Inheritable' is not installed
    ! Bailing out the installation for Exception-Class-1.44.
    ! Installing the dependencies failed: Module 'Test::Exception' is
    not installed, Module 'Test::Differences' is not installed, Module
    'Exception::Class' is not installed, Module 'Test::Warn' is not
    installed, Module 'Test::Deep' is not installed
    ! Bailing out the installation for Test-Most-0.35.
    ! Installing the dependencies failed: Module 'Test::Most' is not
    installed, Module 'IO::String' is not installed, Module
    'Data::Stag'
    is not installed
    ! Bailing out the installation for BioPerl-1.007002.
    6 distributions installed

ETA: It seems something is wrong and the dependencies of the modules that are required are not installed during a simple cpanm
Example of a round trying to install everything that is needed

    cpanm Sub::Uplevel

    --> Working on Sub::Uplevel
    Fetching http://www.cpan.org/authors/id/D/DA/DAGOLDEN/Sub-Uplevel-0.2800.tar.gz ... OK
    Configuring Sub-Uplevel-0.2800 ... OK
    Building and testing Sub-Uplevel-0.2800 ... OK
    Successfully installed Sub-Uplevel-0.2800
    1 distribution installed

then

    cpanm Test::Warn

    --> Working on Test::Warn
    Fetching http://www.cpan.org/authors/id/B/BI/BIGJ/Test-Warn-0.36.tar.gz ... OK
    Configuring Test-Warn-0.36 ... OK
    ==> Found dependencies: Sub::Uplevel
    --> Working on Sub::Uplevel
    Fetching http://www.cpan.org/authors/id/D/DA/DAGOLDEN/Sub-Uplevel-0.2800.tar.gz ... OK
    Configuring Sub-Uplevel-0.2800 ... OK
    Building and testing Sub-Uplevel-0.2800 ... OK
    Successfully installed Sub-Uplevel-0.2800
    ! Installing the dependencies failed: Module 'Sub::Uplevel' is not installed
    ! Bailing out the installation for Test-Warn-0.36.
    1 distribution installed

Some info to help debugging:

$ set | grep ^PERL
PERL5LIB=:/media/evo-slave/Disco2/ANDRES/DOWNLOADS/GENOME/CAV-POC/GAAS/annotation
PERL_MB_OPT='--install_base "/home/evo-slave/perl5"'
PERL_MM_OPT=INSTALL_BASE=/home/evo-slave/perl5

$ which cpanm
/home/evo-slave/anaconda_ete/bin/cpanm

$ head -n 1 "$( which cpanm )"
#!/home/evo-slave/anaconda_ete/bin/perl

Body:
UPDATE 2

This problem is coming up again in miniconda3 bioperl installs.

UPDATE

I have not experienced this error for a while with perl packages, so likely some updates occurred on the conda/package side that fixed this. I would recommend trying to update your conda and checking your conda channels before trying this kind of weird kludge.

ORIGINAL ANSWER

I am posting this as an answer not because it's a good idea, but because it provides more information. I am working on Amazon Linux so it's slightly different, but also running into issues with bioperl dependencies installed through conda. In my case I am trying to run VirSorter, which mentions this problem and proposes a solution that does not work for me, but suggests confirming that your PERL5LIB is properly set.

I observed that my perl is 5.26.2:

$ perl --version

This is perl 5, version 26, subversion 2 (v5.26.2) built for x86_64-linux-thread-multi

But conda is for some obscure reason installing my perl dependencies for 5.22.0: /home/ec2-user/anaconda3/envs/virsorter/lib/perl5/site_perl/5.22.0/:

$ ls /home/ec2-user/anaconda3/envs/virsorter/lib/perl5/site_perl/5.22.0/
Algorithm  Bio  Capture  Class  Data  Devel  Exception  IO  Sub  Test  Text  URI  URI.pm  x86_64-linux-thread-multi

I found that I could get VirSorter running, apparently successfully, by simply setting PERL5LIB to the 5.22.0 lib under conda:

OLD_PER5LIB=$PERL5LIB
export PERL5LIB=/home/ec2-user/anaconda3/envs/virsorter/lib/perl5/site_perl/5.22.0/
# run virsorter
# no errors!

I am sure that this throws up a bunch of red flags for the perl people, and I'm sure that it's very fragile if it actually works at all. Perhaps the question is why conda is installing perl modules as the wrong perl version?


问:
How can I modify my <textarea> html value based on user input
I have a html textarea element in my page where user gives comma separate values. for example below.

A-48402,AA,SBAFL,AA+,USD,,

From javascript (which I prefer) I am applying logic to check if the last row value is blank (separated by comma only) then to put a String value 'Y'. Thus I am writing the below

```<code>var data = document.getElementById('txid').value;
rows = data.split('\n');var row1 = rows[0];row1Values=row1 .split(',');
</code>```

Then I am applying logic to verify whether the last value for every row is blank or not, which is actually blank, then adding the below.

```<code>row_values.push('Y');
</code>```

It is reflecting in debugger.

But what I see is the value 'Y' in the Java action class is not reflecting and showing usual 'Y' while the page submit.  How can I add this value 'Y' in every rows end (where there is blank) so that it will be visible in action class?

```<code>String Data = request.getParameter('mbs_inst_data');
</code>```

This data is populated with the same blank values.

答:
If you're only checking for the last row then the only case that would happen is when it's ,,
so you can just do a simple check </p>

```<code>let data = 'A-48402,AA,SBAFL,AA+,USD,,'
data = data.split(',')
let lastRowIsBlank = data[data.length-2] === ""
// we are doing length - 2 because in your situation we have 2 ""
// since you have two commas. If you have only 1 comma we would
// the same steps but with length - 1
if(lastRowIsBlank) data[data.length-2] = "Y"
return data.toString()
</code>```

Body:
I have a html textarea element in my page where user gives comma separate values. for example below.

A-48402,AA,SBAFL,AA+,USD,,

From javascript (which I prefer) I am applying logic to check if the last row value is blank (separated by comma only) then to put a String value 'Y'. Thus I am writing the below

var data = document.getElementById('txid').value;
rows = data.split('\n');var row1 = rows[0];row1Values=row1 .split(',');

Then I am applying logic to verify whether the last value for every row is blank or not, which is actually blank, then adding the below.

row_values.push('Y');

It is reflecting in debugger.

But what I see is the value 'Y' in the Java action class is not reflecting and showing usual 'Y' while the page submit.  How can I add this value 'Y' in every rows end (where there is blank) so that it will be visible in action class?

String Data = request.getParameter('mbs_inst_data');

This data is populated with the same blank values.

Body:
If you're only checking for the last row then the only case that would happen is when it's ,,
so you can just do a simple check

let data = 'A-48402,AA,SBAFL,AA+,USD,,'
data = data.split(',')
let lastRowIsBlank = data[data.length-2] === ""
// we are doing length - 2 because in your situation we have 2 ""
// since you have two commas. If you have only 1 comma we would
// the same steps but with length - 1
if(lastRowIsBlank) data[data.length-2] = "Y"
return data.toString()


问:
Why doesn't this program end? The game goes on forever if i don't input the correct number
I am new to code and I was trying to create a guessing game as one of my first projects. I think i'm nearly done but this program doesn't end. Instead of ending when the there are 0 tries left it just continues the game even with the minus, Ps.(I made the number fixed for now, but will generate a random number when this issue is resolved)

I am new to code and I was trying to create a guessing game as one of my first projects. I think i'm nearly done but this program doesn't end. Instead of ending when the there are 0 tries left it just continues the game even with the minus, Ps.(I made the number fixed for now, but will generate a random number when this issue is resolved)

```<code>print("Welcome to my guessing game can you get the magic number hint, it's between 1 and 100 ")

Magic_number = 7
guess = int(input("Enter your guess:"))
guess_limit = 5
guess_counter = 1
out_of_guesses = False
print("You have", str(guess_limit - guess_counter), "tries left")

while guess != Magic_number and not out_of_guesses:
    while guess < Magic_number:
        print("That number is too small, try again")
        guess = int(input("Enter guess: "))
        guess_counter += 1
        print("You have", str(guess_limit - guess_counter), "tries left")

    while guess > Magic_number:
        print("That number is too high try again")
        guess = int(input("Enter guess: "))
        guess_counter += 1
        print("You have", str(guess_limit - guess_counter), "tries left")

    if guess == Magic_number:
        print("Well done you got it!!")

if out_of_guesses:
    print("Game over, sorry")
</code>```

答:
You dont have to do while guess > Magic_number: or while guess > Magic_number:. You can directly use if while guess > Magic_number: and if guess > Magic_number: instead of them respectively and the program will still keep looping since there's an outer loop.

Your program isn't stopping because you have not checked the condition inside the inner while loops and therefore it keeps looping. The guess_counter will keep increasing inside the inner while loops but you have made no condition to break the loop on basis of guess_counter.

Just replace the inner while loops with if since you don't need them anyway. Hope this solves your problem!

Body:
I am new to code and I was trying to create a guessing game as one of my first projects. I think i'm nearly done but this program doesn't end. Instead of ending when the there are 0 tries left it just continues the game even with the minus, Ps.(I made the number fixed for now, but will generate a random number when this issue is resolved)

I am new to code and I was trying to create a guessing game as one of my first projects. I think i'm nearly done but this program doesn't end. Instead of ending when the there are 0 tries left it just continues the game even with the minus, Ps.(I made the number fixed for now, but will generate a random number when this issue is resolved)

print("Welcome to my guessing game can you get the magic number hint, it's between 1 and 100 ")

Magic_number = 7
guess = int(input("Enter your guess:"))
guess_limit = 5
guess_counter = 1
out_of_guesses = False
print("You have", str(guess_limit - guess_counter), "tries left")

while guess != Magic_number and not out_of_guesses:
    while guess < Magic_number:
        print("That number is too small, try again")
        guess = int(input("Enter guess: "))
        guess_counter += 1
        print("You have", str(guess_limit - guess_counter), "tries left")

    while guess > Magic_number:
        print("That number is too high try again")
        guess = int(input("Enter guess: "))
        guess_counter += 1
        print("You have", str(guess_limit - guess_counter), "tries left")

    if guess == Magic_number:
        print("Well done you got it!!")

if out_of_guesses:
    print("Game over, sorry")


问:
mapView not zooming on second try using didUpdateUserLocation
i am loading a mapviewcontroller when the view map button is pressed from my mainviewcontroller:

```<code>- (IBAction)mapButton:(id)sender {
    MapKitDisplayViewController *mapKitDisplayView = [[MapKitDisplayViewController alloc] init];
    [self presentModalViewController:mapKitDisplayView animated:YES];
    [mapKitDisplayView release]; mapKitDisplayView = nil;
}
</code>```

On startup of this map view this method is called, which correctly zooms to the users location:

```<code>- (void)mapView:(MKMapView *)myMapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    myMapView.showsUserLocation = YES;
    NSLog(@"didUpdateUserLocation = '%@'", userLocation);

    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([userLocation coordinate], 20000, 20000);
    [myMapView setRegion:region animated:YES];
}
</code>```

I have a done button on this screen that dismisses this view:

```<code>- (IBAction)mapDoneButton:(id)sender
{
    [self dismissModalViewControllerAnimated:YES];
}
</code>```

At this stage the user is taken back to the main view controller, however when i press the view map button again, the didUpdateUserLocation method is never called! Hence, the map view is zoomed out to the default one and wont zoom in as before.

How can i get it to be called again?

thanks

答:
What i do is next:

```<code>- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
[[NSNotificationCenter defaultCenter] postNotificationName:@"gotUserLocation" object:self];}
</code>```

then in viewDidLoad check of user location is available. if it is not register view controller as reciever for that notification:

```<code>[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zoomToLocation) name:@"gotUserLocation" object:nil];
</code>```

if user location is available just call zoomToLocation method

ContentLicense: CC BY-SA 3.0

Body:
i am loading a mapviewcontroller when the view map button is pressed from my mainviewcontroller:

- (IBAction)mapButton:(id)sender {
    MapKitDisplayViewController *mapKitDisplayView = [[MapKitDisplayViewController alloc] init];
    [self presentModalViewController:mapKitDisplayView animated:YES];
    [mapKitDisplayView release]; mapKitDisplayView = nil;
}

On startup of this map view this method is called, which correctly zooms to the users location:

- (void)mapView:(MKMapView *)myMapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    myMapView.showsUserLocation = YES;
    NSLog(@"didUpdateUserLocation = '%@'", userLocation);

    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([userLocation coordinate], 20000, 20000);
    [myMapView setRegion:region animated:YES];
}

I have a done button on this screen that dismisses this view:

- (IBAction)mapDoneButton:(id)sender
{
    [self dismissModalViewControllerAnimated:YES];
}

At this stage the user is taken back to the main view controller, however when i press the view map button again, the didUpdateUserLocation method is never called! Hence, the map view is zoomed out to the default one and wont zoom in as before.

How can i get it to be called again?

thanks

Body:
What i do is next:

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
[[NSNotificationCenter defaultCenter] postNotificationName:@"gotUserLocation" object:self];}

then in viewDidLoad check of user location is available. if it is not register view controller as reciever for that notification:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zoomToLocation) name:@"gotUserLocation" object:nil];

if user location is available just call zoomToLocation method


问:
Voxel Cone Tracing in Deferred pipeline?
I am working on a project where I have to implement voxel cone tracing for indirect light in C++/OpenGL. I already have a deferred renderer setup but most of the VCT examples I could find usually draw the scene once for voxelization and once with cone tracing shaders. Is it possible to run cone tracing shaders over a fullscreen quad and sample vertex data from the GBuffer or is that generally a stupid idea? Do I lose accuracy because I only have per pixel vertex data?</p>

答:
Is it possible to run cone tracing shaders over a fullscreen quad and sample vertex data from the GBuffer or is that generally a stupid idea?

Yes, however that's not voxel cone tracing anymore. That's Screen-Space Global Illumination (SSGI) instead. You can think of the voxelized scene in VCT as a 3D GBuffer, which makes all the difference between "screen space" and "full scene".

Do I lose accuracy because I only have per pixel vertex data?

Absolutely. All screen space approximations suffer from the same set of artifacts. They do not account for surfaces that aren't directly visible on the screen (either out of frame or occluded by visible geometry). Most noticeably, when the camera moves and objects enter or exit the frame, the reflections on visible surfaces would also change unrealistically.


问:
How to calculate the Jaccard Index in Python?
I have a data set as I've shown below:

It shows which book is sold by which shop.

```<code>import pandas as pd

books = {'shop': ["A", "B", "C", "D", "E", "A", "B", "C", "D",],
        'book_id': [1, 1, 2, 3, 3, 3, 4, 5, 1,]
        }

df = pd.DataFrame(books, columns = ['shop', 'book_id'])
</code>```

Here is the print:

```<code>  shop  book_id
0    A        1
1    B        1
2    C        2
3    D        3
4    E        3
5    A        3
6    B        4
7    C        5
8    D        1
</code>```

In the data set,

shop A sells 1, 3

shop B sells 1, 4

shop C sells 2, 5

shop D sells 3, 1

shop E sells only 3

So now, I want to calculate the jaccard index here. For instance, let's take shop A and shop B. There are three different books that are sold by A and B (book 1, book 3, book 4). However, only one product is sold by both shops (this is product 1). So, the Jaccard index here should be 33.3% (1/3).

Here is the sample of the desired data:

```<code>result = {'shop_1': ["A", "B", "A", "C", "A", "D", "A", "E",],
          'shop_2': ["B", "A", "C", "A", "D", "A", "E", "A",],
          'jaccard':  [33.3, 33.33, 0, 0, 100, 100, 50, 50,]
        }
desired_df = pd.DataFrame(result, columns = ['shop_1', 'shop_2', 'jaccard'])
</code>```

```<code>Print
  shop_1 shop_2  jaccard
0      A      B    33.30
1      B      A    33.33
2      A      C     0.00
3      C      A     0.00
4      A      D   100.00
5      D      A   100.00
6      A      E    50.00
7      E      A    50.00
.      .      .      .
.      .      .      .
.      .      .      .
</code>```

Can someone help me to do this? Is there any library to implement Jaccard Index?

Body:
I have a data set as I've shown below:

It shows which book is sold by which shop.

import pandas as pd

books = {'shop': ["A", "B", "C", "D", "E", "A", "B", "C", "D",],
        'book_id': [1, 1, 2, 3, 3, 3, 4, 5, 1,]
        }

df = pd.DataFrame(books, columns = ['shop', 'book_id'])

Here is the print:

  shop  book_id
0    A        1
1    B        1
2    C        2
3    D        3
4    E        3
5    A        3
6    B        4
7    C        5
8    D        1

In the data set,

shop A sells 1, 3

shop B sells 1, 4

shop C sells 2, 5

shop D sells 3, 1

shop E sells only 3

So now, I want to calculate the jaccard index here. For instance, let's take shop A and shop B. There are three different books that are sold by A and B (book 1, book 3, book 4). However, only one product is sold by both shops (this is product 1). So, the Jaccard index here should be 33.3% (1/3).

Here is the sample of the desired data:

result = {'shop_1': ["A", "B", "A", "C", "A", "D", "A", "E",],
          'shop_2': ["B", "A", "C", "A", "D", "A", "E", "A",],
          'jaccard':  [33.3, 33.33, 0, 0, 100, 100, 50, 50,]
        }
desired_df = pd.DataFrame(result, columns = ['shop_1', 'shop_2', 'jaccard'])

Print
  shop_1 shop_2  jaccard
0      A      B    33.30
1      B      A    33.33
2      A      C     0.00
3      C      A     0.00
4      A      D   100.00
5      D      A   100.00
6      A      E    50.00
7      E      A    50.00
.      .      .      .
.      .      .      .
.      .      .      .

Can someone help me to do this? Is there any library to implement Jaccard Index?

Body:
If you data is not too big, you can use a broadcasting approach:

books = pd.crosstab(df.shop, df.book_id)

# underlying numpy
arr = books.values

common = (arr[None,...] | arr[:,None,:]).sum(-1)

output = (books @ books.T)/common

Output:

shop         A         B    C         D    E
shop
A     1.000000  0.333333  0.0  1.000000  0.5
B     0.333333  1.000000  0.0  0.333333  0.0
C     0.000000  0.000000  1.0  0.000000  0.0
D     1.000000  0.333333  0.0  1.000000  0.5
E     0.500000  0.000000  0.0  0.500000  1.0

To match your expected output:

output = (output.stack().rename_axis(['shop_1','shop_2'])
                .reset_index(name='jaccard')
                .query('shop_1 != shop_2')
         )

Output:

   shop_1 shop_2   jaccard
1       A      B  0.333333
2       A      C  0.000000
3       A      D  1.000000
4       A      E  0.500000
5       B      A  0.333333
7       B      C  0.000000
8       B      D  0.333333
9       B      E  0.000000
10      C      A  0.000000
11      C      B  0.000000
13      C      D  0.000000
14      C      E  0.000000
15      D      A  1.000000
16      D      B  0.333333
17      D      C  0.000000
19      D      E  0.500000
20      E      A  0.500000
21      E      B  0.000000
22      E      C  0.000000
23      E      D  0.500000


问:
How to set axis ticks in multiples of pi (Python) (matplotlib)
I'd like to make a plot in Python and have x range display ticks in multiples of pi.

Is there a good way to do this, not manually?

I'm thinking of using matplotlib, but other options are fine.

EDIT 3: EL_DON's solution worked for me like this:

```<code>import matplotlib.ticker as tck
import matplotlib.pyplot as plt
import numpy as np

f,ax=plt.subplots(figsize=(20,10))
x=np.linspace(-10*np.pi, 10*np.pi,1000)
y=np.sin(x)

ax.plot(x/np.pi,y)

ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$'))
ax.xaxis.set_major_locator(tck.MultipleLocator(base=1.0))

plt.style.use("ggplot")

plt.show()
</code>```

giving:

EDIT 2 (solved in EDIT 3!): EL_DON's answer doesn't seem to work right for me:

```<code>import matplotlib.ticker as tck
import matplotlib.pyplot as plt
import numpy as np

f,ax=plt.subplots(figsize=(20,10))
x=np.linspace(-10*np.pi, 10*np.pi)
y=np.sin(x)

ax.plot(x/np.pi,y)

ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$'))
ax.xaxis.set_major_locator(tck.MultipleLocator(base=1.0))

plt.style.use("ggplot")

plt.show()
</code>```

gives me

which really doesn't look right

答:
I created a PyPi Package that creates formatter and locator instances like Scott Centoni's answer.</p>
```<code>"""Show a simple example of using MultiplePi."""

import matplotlib.pyplot as plt
import numpy as np

from matplot_fmt_pi import MultiplePi

fig = plt.figure(figsize=(4*np.pi, 2.4))
axes = fig.add_subplot(111)
x = np.linspace(-2*np.pi, 2*np.pi, 512)
axes.plot(x, np.sin(x))

axes.grid(True)
axes.axhline(0, color='black', lw=2)
axes.axvline(0, color='black', lw=2)
axes.set_title("MultiplePi formatting")

pi_manager = MultiplePi(2)
axes.xaxis.set_major_locator(pi_manager.locator())
axes.xaxis.set_major_formatter(pi_manager.formatter())

plt.tight_layout()
plt.savefig("./pi_graph.png", dpi=120)
</code>```

Body:
I'd like to make a plot in Python and have x range display ticks in multiples of pi.

Is there a good way to do this, not manually?

I'm thinking of using matplotlib, but other options are fine.

EDIT 3: EL_DON's solution worked for me like this:

import matplotlib.ticker as tck
import matplotlib.pyplot as plt
import numpy as np

f,ax=plt.subplots(figsize=(20,10))
x=np.linspace(-10*np.pi, 10*np.pi,1000)
y=np.sin(x)

ax.plot(x/np.pi,y)

ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$'))
ax.xaxis.set_major_locator(tck.MultipleLocator(base=1.0))

plt.style.use("ggplot")

plt.show()

giving:

EDIT 2 (solved in EDIT 3!): EL_DON's answer doesn't seem to work right for me:

import matplotlib.ticker as tck
import matplotlib.pyplot as plt
import numpy as np

f,ax=plt.subplots(figsize=(20,10))
x=np.linspace(-10*np.pi, 10*np.pi)
y=np.sin(x)

ax.plot(x/np.pi,y)

ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$'))
ax.xaxis.set_major_locator(tck.MultipleLocator(base=1.0))

plt.style.use("ggplot")

plt.show()

gives me

which really doesn't look right

Body:
I created a PyPi Package that creates formatter and locator instances like Scott Centoni's answer.

"""Show a simple example of using MultiplePi."""

import matplotlib.pyplot as plt
import numpy as np

from matplot_fmt_pi import MultiplePi

fig = plt.figure(figsize=(4*np.pi, 2.4))
axes = fig.add_subplot(111)
x = np.linspace(-2*np.pi, 2*np.pi, 512)
axes.plot(x, np.sin(x))

axes.grid(True)
axes.axhline(0, color='black', lw=2)
axes.axvline(0, color='black', lw=2)
axes.set_title("MultiplePi formatting")

pi_manager = MultiplePi(2)
axes.xaxis.set_major_locator(pi_manager.locator())
axes.xaxis.set_major_formatter(pi_manager.formatter())

plt.tight_layout()
plt.savefig("./pi_graph.png", dpi=120)


问:
Setting maximum number of Columns for ListView
How do we fix the maximum number of columns for a particular ListView control?
Is there any thing like this:</p>

```<code>listViewControl.MaximumColumns = 3;
</code>```

答: If you are talking about the Windows ListView control, the maximum is how many columns you add to it.</p>

OwnerDisplayName: Elroy

ContentLicense: CC BY-SA 2.5

Body:
How do we fix the maximum number of columns for a particular ListView control?
Is there any thing like this:

listViewControl.MaximumColumns = 3;

OwnerDisplayName: Mitch Wheat


问:
How to add a 'X' to the end of every line in C?
I'm trying to append a capital 'X' character at the end of every line of a simple text file (while switching all chars to upper case at the same time) and writing the changes to a new file.

So initially, the file faust.txt contains:

```<code>Besonders aber laßt genug geschehn!
Man kommt zu schaun, man will am liebsten sehn.
Wird vieles vor den Augen abgesponnen,
</code>```

After the call, the file FAUST.txt should contain:

```<code>BESONDERS ABER LAßT GENUG GESCHEHN!X
MAN KOMMT ZU SCHAUN, MAN WILL AM LIEBSTEN SEHN.X
WIRD VIELES VOR DEN AUGEN ABGESPONNEN,X
</code>```

The copying and conversion to upper case seems to work but the appending is unclear to me:

```<code>#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>

int main() {

    // 1)  Open faust source file
    int BUF_SIZE = 1;
    int faust_fh = open("faust.txt", O_RDONLY);
    char src[BUF_SIZE];

    // Destination file.
    int FAUST_fh = open("FAUST.txt", O_CREAT | O_WRONLY);

    int read_bytes = read(faust_fh, &src, BUF_SIZE);
    while (read_bytes > 0) {

        char c = src[0];
        char *C = &c;
        src[0] = toupper(*C);

        if (src[0] == '\n') {
            char *end = &src[0];
            strcat(end, "X");
            src[0] = *end;
        }

        write(FAUST_fh, &src, BUF_SIZE);
        read_bytes = read(faust_fh, src, BUF_SIZE);
    }

    close(FAUST_fh);
    close(faust_fh);
    return 0;
}
</code>```

Note: I should accomplish this with system calls (if possible).

答:
The caveats about strcat et. al. from other responders apply (e.g. you can't guarantee the buffer will have an EOS, so you can't use string functions).

Although it may be easiest to do a read with length 1, it's sometimes more efficient to have a larger buffer size.

Here's a version that works with buffer sizes > 1. I set a size of 10, but it can be whatever size you'd like:

```<code>#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>

int
main(void)
{

    // 1) Open faust source file
#if 0
    int BUF_SIZE = 1;
#else
    int BUF_SIZE = 10;
#endif
    int faust_fh = open("faust.txt", O_RDONLY);
    char src[BUF_SIZE];
    char Xnewline[] = "X\n";

    // Destination file.
    // NOTE/BUG: we need to specify the mode with O_CREAT otherwise the
    // file is created with a semi-random permission mask
#if 0
    int FAUST_fh = open("FAUST.txt", O_CREAT | O_WRONLY);
#else
    int FAUST_fh = open("FAUST.txt", O_CREAT | O_WRONLY, 0644);
#endif

    char *lhs;
    size_t len;
    int read_bytes;

    while (1) {
        lhs = src;

        read_bytes = read(faust_fh, lhs, BUF_SIZE);
        if (read_bytes <= 0)
            break;

        char *end = &lhs[read_bytes];
        char *cur;

        // process/scan all bytes in the buffer
        for (cur = lhs;  cur < end;  ++cur) {
            int c = *cur;

            *cur = toupper(c);

            if (c == '\n') {
                // send all data up to, but not including the newline
                len = cur - lhs;
                if (len > 0)
                    write(FAUST_fh,lhs,len);

                // send X<newline>
                write(FAUST_fh,Xnewline,2);

                // set new left start into current buffer (just _past_ the
                // newline)
                lhs = cur + 1;
            }
        }

        // send the remainder of the current buffer [has _no_ newlines in it]
        len = cur - lhs;
        if (len > 0)
            write(FAUST_fh,lhs,len);
    }

    close(FAUST_fh);
    close(faust_fh);

    return 0;
}
</code>```

Body:
I'm trying to append a capital 'X' character at the end of every line of a simple text file (while switching all chars to upper case at the same time) and writing the changes to a new file.

So initially, the file faust.txt contains:

Besonders aber laßt genug geschehn!
Man kommt zu schaun, man will am liebsten sehn.
Wird vieles vor den Augen abgesponnen,

After the call, the file FAUST.txt should contain:

BESONDERS ABER LAßT GENUG GESCHEHN!X
MAN KOMMT ZU SCHAUN, MAN WILL AM LIEBSTEN SEHN.X
WIRD VIELES VOR DEN AUGEN ABGESPONNEN,X

The copying and conversion to upper case seems to work but the appending is unclear to me:

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>

int main() {

    // 1)  Open faust source file
    int BUF_SIZE = 1;
    int faust_fh = open("faust.txt", O_RDONLY);
    char src[BUF_SIZE];

    // Destination file.
    int FAUST_fh = open("FAUST.txt", O_CREAT | O_WRONLY);

    int read_bytes = read(faust_fh, &src, BUF_SIZE);
    while (read_bytes > 0) {

        char c = src[0];
        char *C = &c;
        src[0] = toupper(*C);

        if (src[0] == '\n') {
            char *end = &src[0];
            strcat(end, "X");
            src[0] = *end;
        }

        write(FAUST_fh, &src, BUF_SIZE);
        read_bytes = read(faust_fh, src, BUF_SIZE);
    }

    close(FAUST_fh);
    close(faust_fh);
    return 0;
}

Note: I should accomplish this with system calls (if possible).

Body:
The caveats about strcat et. al. from other responders apply (e.g. you can't guarantee the buffer will have an EOS, so you can't use string functions).

Although it may be easiest to do a read with length 1, it's sometimes more efficient to have a larger buffer size.

Here's a version that works with buffer sizes > 1. I set a size of 10, but it can be whatever size you'd like:

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>

int
main(void)
{

    // 1) Open faust source file
#if 0
    int BUF_SIZE = 1;
#else
    int BUF_SIZE = 10;
#endif
    int faust_fh = open("faust.txt", O_RDONLY);
    char src[BUF_SIZE];
    char Xnewline[] = "X\n";

    // Destination file.
    // NOTE/BUG: we need to specify the mode with O_CREAT otherwise the
    // file is created with a semi-random permission mask
#if 0
    int FAUST_fh = open("FAUST.txt", O_CREAT | O_WRONLY);
#else
    int FAUST_fh = open("FAUST.txt", O_CREAT | O_WRONLY, 0644);
#endif

    char *lhs;
    size_t len;
    int read_bytes;

    while (1) {
        lhs = src;

        read_bytes = read(faust_fh, lhs, BUF_SIZE);
        if (read_bytes <= 0)
            break;

        char *end = &lhs[read_bytes];
        char *cur;

        // process/scan all bytes in the buffer
        for (cur = lhs;  cur < end;  ++cur) {
            int c = *cur;

            *cur = toupper(c);

            if (c == '\n') {
                // send all data up to, but not including the newline
                len = cur - lhs;
                if (len > 0)
                    write(FAUST_fh,lhs,len);

                // send X<newline>
                write(FAUST_fh,Xnewline,2);

                // set new left start into current buffer (just _past_ the
                // newline)
                lhs = cur + 1;
            }
        }

        // send the remainder of the current buffer [has _no_ newlines in it]
        len = cur - lhs;
        if (len > 0)
            write(FAUST_fh,lhs,len);
    }

    close(FAUST_fh);
    close(faust_fh);

    return 0;
}


问:
How to autocrop video using FFMPEG and powershell
It should be possible to parse the output from ffmpeg's cropdetect command (to remove black borders) ffmpeg -ss 90 -i out.mkv -vframes 10 -vf cropdetect -f null and directly apply given output to the command ffmpeg -i out.mkv -vf "crop=h:w:x:y" YourCroppedMovie.mp4. Parameters are height, width, x start and y start.

How to apply the given result to the second command in PowerShell?

答:
```<code>[string]$STDOUT_FILE = Join-Path -Path $env:TEMP -ChildPath "stdout.txt"
$ArgumentList = "-ss 90 -i out.mkv -vframes 10 -vf cropdetect -f null -"
Start-Process -FilePath ffmpeg -ArgumentList $ArgumentList -Wait -NoNewWindow -RedirectStandardError $STDOUT_FILE
$crop = (((Get-Content -LiteralPath $STDOUT_FILE | Where-Object { $_ -Like '*crop=*' }).Split(" "))[13]).Split("=")[1]

$ArgumentList = '-i out.mkv -vf "crop=' + $crop + '" YourCroppedMovie.mp4'
Start-Process -FilePath ffmpeg -ArgumentList $ArgumentList -Wait -NoNewWindow
</code>```

Each line

1st just sets variable name and the location for the file that ffmpeg's output is captured

2nd was the command line you used in your example

3rd starts ffmpeg with your commands, it waits until ffmpeg is done, it captures ffmpeg's standard error info in file set in line 1

4th Loads the captured file, searches for a line containing "crop=", it then splits that line at every space " ", the 14th segment contains the crop into, it splits that 14th segment at the "=" sign, it then sets the 2nd segment (data after = sign) as $crop

5th sets your command line but adds the crop info ($crop)

6th runs ffmpeg with new command line and waits for it to finish

Body:
[string]$STDOUT_FILE = Join-Path -Path $env:TEMP -ChildPath "stdout.txt"
$ArgumentList = "-ss 90 -i out.mkv -vframes 10 -vf cropdetect -f null -"
Start-Process -FilePath ffmpeg -ArgumentList $ArgumentList -Wait -NoNewWindow -RedirectStandardError $STDOUT_FILE
$crop = (((Get-Content -LiteralPath $STDOUT_FILE | Where-Object { $_ -Like '*crop=*' }).Split(" "))[13]).Split("=")[1]

$ArgumentList = '-i out.mkv -vf "crop=' + $crop + '" YourCroppedMovie.mp4'
Start-Process -FilePath ffmpeg -ArgumentList $ArgumentList -Wait -NoNewWindow

Each line

1st just sets variable name and the location for the file that ffmpeg's output is captured

2nd was the command line you used in your example

3rd starts ffmpeg with your commands, it waits until ffmpeg is done, it captures ffmpeg's standard error info in file set in line 1

4th Loads the captured file, searches for a line containing "crop=", it then splits that line at every space " ", the 14th segment contains the crop into, it splits that 14th segment at the "=" sign, it then sets the 2nd segment (data after = sign) as $crop

5th sets your command line but adds the crop info ($crop)

6th runs ffmpeg with new command line and waits for it to finish


问:
How to filter with wms background maps in Tableau
I created a map with locations plotted in Tableau and have utilized a background map from NOAA to show which locations are being impacted by excessive rainfall. How do I filter the data so only those that fall within the excessive rainfall areas appear on the map? Alternatively how do I get aggregate measures of the locations that fall within the excessive rainfall zone? </p>

答: It's not a perfect solution, but one method that I found success with is creating a filter action and then using the lasso selection tool on the dashboard to select all of the points within the desired area in order to filter the desired values. More info on the filter action can be found here.</p>

Body: It's not a perfect solution, but one method that I found success with is creating a filter action and then using the lasso selection tool on the dashboard to select all of the points within the desired area in order to filter the desired values. More info on the filter action can be found <a href="http://It's%20not%20a%20perfect%20solution,%20but%20one%20method%20that%20I%20found%20success%20with%20is%20creating%20a%20filter%20action%20and%20then%20using%20the%20lasso%20selection%20tool%20on%20the%20dashboard%20to%20select%20all%20of%20the%20points%20within%20the%20desired%20area%20in%20order%20to%20filter%20the%20desired%20values.%20More%20info%20on%20the%20filter%20action%20can%20be%20found%20here:%20https://www.bing.com/videos/search?q=how%20to%20export%20just%20filter%20action%20selected%20data%20in%20tableau&docid=608014042867698243&mid=AD1A8C1C2C4BCC8BB948AD1A8C1C2C4BCC8BB948&view=detail&FORM=VIREHT" rel="nofollow noreferrer">here.


问:
What is the best way to implement a button displayed and hidden in real-time in a specific time?
I have a button that allows the user to join a scheduled meeting in a specific timing (i.e 12:00 PM) and is hidden by default. When the screen having this button is entered, i call a service that returns that timing.
The button is supposed to be displayed starting from the timing and for 15 mins. So if the user is viewing the screen and the button is hidden and the timing is reached the button should appear then after 15 min it disappears.
The returned timing may be a day before!!
How can i implement this in Android? </p>

答:
You can use scedule and LiveData for this.

```<code>Timer().schedule(5000) {
    TODO("Do smth")
}
</code>```

In your case, when service is called and passed via broadcast receiver to MainActivity, you could schedule 2 times and update view.

```<code>// schedule button visibility
Timer().schedule(scheduledTimeInMillisec - currentMillisec){
     livedata.value = true
}

// schedule hiding button
Timer().schedule(scheduledTimeInMillisec - currentMillisec + 1000*60*15){
     livedata.value = false
}
</code>```

Body:
You can use scedule and LiveData for this.

Timer().schedule(5000) {
    TODO("Do smth")
}

In your case, when service is called and passed via broadcast receiver to MainActivity, you could schedule 2 times and update view.

// schedule button visibility
Timer().schedule(scheduledTimeInMillisec - currentMillisec){
     livedata.value = true
}

// schedule hiding button
Timer().schedule(scheduledTimeInMillisec - currentMillisec + 1000*60*15){
     livedata.value = false
}


答:
You did not update out_of_guesses variable, and you may use if and not while for the inner loops to avoid multiplying the place to check out_of_guesses. Then use a break if finds, that allows to put the code to run agin after it and not duplicate it

```<code>while not out_of_guesses:
    if guess < Magic_number:
        print("That number is too small, try again")
    elif guess > Magic_number:
        print("That number is too high try again")
    elif guess == Magic_number:
        print("Well done you got it!!")
        break

    guess = int(input("Enter guess: "))
    guess_counter += 1
    print("You have", str(guess_limit - guess_counter), "tries left")
    out_of_guesses = guess_counter>=guess_limit
</code>```

Title: Why doesn't this program end? The game goes on forever if i don't input the correct number

Body:
You did not update out_of_guesses variable, and you may use if and not while for the inner loops to avoid multiplying the place to check out_of_guesses. Then use a break if finds, that allows to put the code to run agin after it and not duplicate it

while not out_of_guesses:
    if guess < Magic_number:
        print("That number is too small, try again")
    elif guess > Magic_number:
        print("That number is too high try again")
    elif guess == Magic_number:
        print("Well done you got it!!")
        break

    guess = int(input("Enter guess: "))
    guess_counter += 1
    print("You have", str(guess_limit - guess_counter), "tries left")
    out_of_guesses = guess_counter>=guess_limit


问:
Iterating over founded objects with indexes
I get an error : obj.attr is not a function.

```<code>  clone.find(".blockBase").each(function(i, obj) {
     obj.attr("id",newid+"b"+i);
     console.log("Base",i);
  });
</code>```

I can't figure out why ? obj should be a jquery element.

答:
https://api.jquery.com/each/

The second parameter (in your case obj) as well as the context (this) for the .each() function is a DOM element, NOT a jquery object.

Use $(obj).attr() as commented above.

Thus you will construct a jquery object with this DOM element.

Body:
I get an error : obj.attr is not a function.

  clone.find(".blockBase").each(function(i, obj) {
     obj.attr("id",newid+"b"+i);
     console.log("Base",i);
  });

I can't figure out why ? obj should be a jquery element.


问:
What's the usage for convolutional layer that output is the same as the input applied with MaxPool
what's the idea behind when using the following convolutional layers?

especially for nn.Conv2d(16, 16, 3, padding = 1)

```<code>self.conv1 = nn.Conv2d(3, 16, 3, padding = 1 )
self.conv2 = nn.Conv2d(16, 16, 3, padding = 1)
self.conv3 = nn.Conv2d(16, 32, 3, padding = 1)
self.pool = nn.MaxPool2d(2, 2)
</code>```

```<code> x = F.relu(self.conv1(x))
 x = self.pool(F.relu(self.conv2(x)))
 x = F.relu(self.conv3(x))
</code>```

I thought Conv2d always uses a bigger size like
from (16,32) to (32,64) for example.

Is nn.Conv2d(16, 16, 3, padding = 1) merely for reducing the size?

答:
The model architecture all depends on finally what works best for your application, and it's always going to vary.

You are right in saying that usually, you want to make your tensors deeper (in the dimension of your channels) in order to extract richer features, but there is no hard and fast rule about that. Having said that, sometimes you don't want to make your tensors too big, since more the number of channels more the number of trainable parameters making it difficult for your model to train. This again brings me back to the very first line I said - "It all depends".

And as for the line:

```<code>nn.Conv2d(16, 16, 3, padding = 1)  # stride = 1 by default.
</code>```

This will keep the size of the tensor the same as the input in all 3 dimensions (height, width, and number of channels).

I will also add the formula to calculate size of output tensor in a convolution for reference.

```<code>output_size = ( (input_size - filter_size + 2*padding) / stride ) + 1
</code>```

Body:
what's the idea behind when using the following convolutional layers?

especially for nn.Conv2d(16, 16, 3, padding = 1)

self.conv1 = nn.Conv2d(3, 16, 3, padding = 1 )
self.conv2 = nn.Conv2d(16, 16, 3, padding = 1)
self.conv3 = nn.Conv2d(16, 32, 3, padding = 1)
self.pool = nn.MaxPool2d(2, 2)

 x = F.relu(self.conv1(x))
 x = self.pool(F.relu(self.conv2(x)))
 x = F.relu(self.conv3(x))

I thought Conv2d always uses a bigger size like
from (16,32) to (32,64) for example.

Is nn.Conv2d(16, 16, 3, padding = 1) merely for reducing the size?

Body:
The model architecture all depends on finally what works best for your application, and it's always going to vary.

You are right in saying that usually, you want to make your tensors deeper (in the dimension of your channels) in order to extract richer features, but there is no hard and fast rule about that. Having said that, sometimes you don't want to make your tensors too big, since more the number of channels more the number of trainable parameters making it difficult for your model to train. This again brings me back to the very first line I said - "It all depends".

And as for the line:

nn.Conv2d(16, 16, 3, padding = 1)  # stride = 1 by default.

This will keep the size of the tensor the same as the input in all 3 dimensions (height, width, and number of channels).

I will also add the formula to calculate size of output tensor in a convolution for reference.

output_size = ( (input_size - filter_size + 2*padding) / stride ) + 1


问:
Angular | NgRx Check for null field in an object before putting it in a list of dropdown
I have a html dropdown which is sourcing data from an api, the api returns an array of objects [in the component].
The Dropdown uses a field value which is in most objects, but not all.

So it causes, some fields entries to show blank in the dropdown.

```<code><div class="col-sm-5">
                    <label>DropDown<label class="field-importance" style="padding-left: 14rem">Required</label></label>
                    <select formControlName="Entry" placeholder="Select Entry" required>
                        <option value="null" disabled="true" [selected]="true" [hidden]="true">Select Entry</option>
                        <option *ngFor="let e of entry" [value]="e.val">{{e.val}}</option>
                    </select>
</div>
</code>```

Thank you soo much

答:
You could do a *ngIf check for val property before using it. Try the following

  DropDownRequired
  <select formControlName="Entry" placeholder="Select Entry" required>
    <option value="null" disabled="true" [selected]="true" [hidden]="true">Select Entry</option>
    <ng-container *ngFor="let e of entry">
      <ng-container *ngIf="e.val">
        <option [value]="e.val">{{e.val}}</option>
      </ng-container>
    </ng-container>
  </select>

```

Body:
I have a html dropdown which is sourcing data from an api, the api returns an array of objects [in the component].
The Dropdown uses a field value which is in most objects, but not all.

So it causes, some fields entries to show blank in the dropdown.

                    DropDownRequired
                    <select formControlName="Entry" placeholder="Select Entry" required>
                        <option value="null" disabled="true" [selected]="true" [hidden]="true">Select Entry</option>
                        <option *ngFor="let e of entry" [value]="e.val">{{e.val}}</option>
                    </select>

Thank you soo much

Body:
You could do a *ngIf check for val property before using it. Try the following

<div class="col-sm-5">
  <label>DropDown<label class="field-importance" style="padding-left: 14rem">Required</label></label>
  <select formControlName="Entry" placeholder="Select Entry" required>
    <option value="null" disabled="true" [selected]="true" [hidden]="true">Select Entry</option>
    <ng-container *ngFor="let e of entry">
      <ng-container *ngIf="e.val">
        <option [value]="e.val">{{e.val}}</option>
      </ng-container>
    </ng-container>
  </select>
</div>


问:
Print newlines (linebreaks) with Fat Free Framework
I have a textarea which posts and saves a message in MySql
I try to print it in a div with fatfree as
{{@note}} or {{@note | raw}}. Both shows the text as single line. I've checked in phpMyAdmin that the value is saved with linebreaks.
What should I do to print this text as-is with line breaks?</p>

答:
```<code><p style="white-space: pre-line">multi-line text</p>
</code>```

This works! It is not specific to fat free, or PHP.

Body:
<p style="white-space: pre-line">multi-line text</p>

This works! It is not specific to fat free, or PHP.


问:
Dotnet Core - Get the application's launch path
Question - Is there a better/right way to get the application's launch path?

Setup -
I have a console application that runs in a Linux Debian docker image. I am building the application using the --runtime linux-x64 command line switch and have all the runtime identifiers set appropriately. I was expecting the application to behave the same whether launching it by calling dotnet MyApplication.dll or ./MyApplication but they are not.

Culprit Code -
I have deployed files in a folder below the application directory that I reference so I do the following to get what I consider my launch path. I have read various articles saying this is the correct way to get what I want, and it works depending on how I launch it.

```<code>using var processModule = Process.GetCurrentProcess().MainModule;
var basePath = Path.GetDirectoryName(processModule?.FileName);
</code>```

When launching this using the comand dotnet MyApplication.dll the above codes path is /usr/share/dotnet

When launching this using the command ./MyApplication.dll the path is then /app

I understand why using dotnet would be different as it is the process that is running my code, but again it was unexpected.

Any help here to what I should use given the current environment would be appreciated. Ultimately I need the path where the console application started from as gathered by the application when it starts up.

Thanks for your help.

答:
This code should work:  </p>

```<code>public static IConfiguration LoadConfiguration()
{
       var assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
.....

}
</code>```

Body:
Question - Is there a better/right way to get the application's launch path?

Setup -
I have a console application that runs in a Linux Debian docker image. I am building the application using the --runtime linux-x64 command line switch and have all the runtime identifiers set appropriately. I was expecting the application to behave the same whether launching it by calling dotnet MyApplication.dll or ./MyApplication but they are not.

Culprit Code -
I have deployed files in a folder below the application directory that I reference so I do the following to get what I consider my launch path. I have read various articles saying this is the correct way to get what I want, and it works depending on how I launch it.

using var processModule = Process.GetCurrentProcess().MainModule;
var basePath = Path.GetDirectoryName(processModule?.FileName);

When launching this using the comand dotnet MyApplication.dll the above codes path is /usr/share/dotnet

When launching this using the command ./MyApplication.dll the path is then /app

I understand why using dotnet would be different as it is the process that is running my code, but again it was unexpected.

Any help here to what I should use given the current environment would be appreciated. Ultimately I need the path where the console application started from as gathered by the application when it starts up.

Thanks for your help.

Body:
This code should work:

public static IConfiguration LoadConfiguration()
{
       var assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
.....

}


问:
iframe content gets cut off when printing
I have a page with an iframe in it. The iframe's content is a couple of pages long, I've set the iframe's height to match it's content. When I try to print the page, the content of the iframe gets cut off after the first page. I've hidden all other elements/parts on the page while printing with a print stylesheet, except for the iframe. So it's the only element on the page when printed. I've tried setting the iframe's fixed height in a couple of ways:

```<code><iframe src="page.html" style="height: 2100px;" height="2100" scrolling="yes">
</code>```

I've also tried to set the iframe's fixed height in a print only stylesheet, but nothing has worked so far. It does accept other styling like a width or a border, which is visible when printing, but only for the first page.

UPDATE: It seems to be working correctly in Chrome, but it's a known and old (2001) bug in Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=113217
Can't find an exact bug report for IE, but it seems to suffer the same fate as Firefox.

答:
Here is a simple solution using javascript to manipulate the DOM and set the current window to equal the iframe's window, then issue the print command.

```<code><html>
<body>

<iframe id='first_iframe' src="xxx" style="width:718px; height:700px;" frameborder="0"></iframe>

<iframe id='second_iframe' src="yyy" style="width:718px; height:700px;" frameborder="0"></iframe>

</body>
</html>

<script>

 pages =[] // initiate an empty list

function printPage() {

var frame1 = document.getElementById('first_iframe');
// get the first_iframe and
// then push its innerHTML into the list
   pages.push(frame1.contentWindow.document.body.innerHTML);

var frame2 = document.getElementById('second_iframe');
// get the first_iframe and
// then push its innerHTML into the list
   pages.push(frame1.contentWindow.document.body.innerHTML);

if (pages && pages.length) {

// this if statement, just checks to ensure our list is not empty before printing.

// here is the magic, we now set the parent window to be equal to all the concatenated innerHTML
window.content.document.body.innerHTML = pages;
// then we print this new window that contains all the iframes
window.print();
}
else {
// do nothing
}

}
</script>
</code>```

Remember that in your parent page HTML you will have the code below to call the printPage function.

```<code><input type="submit" value="Print All"
  onclick="javascript:printPage()"
 />
</code>```

With this solution you avoid the problem of the iframe being cut off if it exceeds one page. Secondly, you get only one print dialogue box even if you have multiple iframes.

Body:
I have a page with an iframe in it. The iframe's content is a couple of pages long, I've set the iframe's height to match it's content. When I try to print the page, the content of the iframe gets cut off after the first page. I've hidden all other elements/parts on the page while printing with a print stylesheet, except for the iframe. So it's the only element on the page when printed. I've tried setting the iframe's fixed height in a couple of ways:

I've also tried to set the iframe's fixed height in a print only stylesheet, but nothing has worked so far. It does accept other styling like a width or a border, which is visible when printing, but only for the first page.

UPDATE: It seems to be working correctly in Chrome, but it's a known and old (2001) bug in Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=113217
Can't find an exact bug report for IE, but it seems to suffer the same fate as Firefox.

Body:
Here is a simple solution using javascript to manipulate the DOM and set the current window to equal the iframe's window, then issue the print command.

<html>
<body>

<iframe id='first_iframe' src="xxx" style="width:718px; height:700px;" frameborder="0"></iframe>

<iframe id='second_iframe' src="yyy" style="width:718px; height:700px;" frameborder="0"></iframe>

</body>
</html>

<script>

 pages =[] // initiate an empty list

function printPage() {

var frame1 = document.getElementById('first_iframe');
// get the first_iframe and
// then push its innerHTML into the list
   pages.push(frame1.contentWindow.document.body.innerHTML);

var frame2 = document.getElementById('second_iframe');
// get the first_iframe and
// then push its innerHTML into the list
   pages.push(frame1.contentWindow.document.body.innerHTML);

if (pages && pages.length) {

// this if statement, just checks to ensure our list is not empty before printing.

// here is the magic, we now set the parent window to be equal to all the concatenated innerHTML
window.content.document.body.innerHTML = pages;
// then we print this new window that contains all the iframes
window.print();
}
else {
// do nothing
}

}
</script>

Remember that in your parent page HTML you will have the code below to call the printPage function.

<input type="submit" value="Print All"
  onclick="javascript:printPage()"
 />

With this solution you avoid the problem of the iframe being cut off if it exceeds one page. Secondly, you get only one print dialogue box even if you have multiple iframes.