问:
Count the minimum number of jumps required for a frog to get to the other side of a river
I work with a Codility problem provided below,

The Fibonacci sequence is defined using the following recursive formula:

```<code>F(0) = 0
F(1) = 1
F(M) = F(M - 1) + F(M - 2) if M >= 2
</code>```

A small frog wants to get to the other side of a river. The frog is initially located at one bank of the river (position −1) and wants to get to the other bank (position N). The frog can jump over any distance F(K), where F(K) is the K-th Fibonacci number. Luckily, there are many leaves on the river, and the frog can jump between the leaves, but only in the direction of the bank at position N.

The leaves on the river are represented in an array A consisting of N integers. Consecutive elements of array A represent consecutive positions from 0 to N − 1 on the river. Array A contains only 0s and/or 1s:

0 represents a position without a leaf;
1 represents a position containing a leaf.
The goal is to count the minimum number of jumps in which the frog can get to the other side of the river (from position −1 to position N). The frog can jump between positions −1 and N (the banks of the river) and every position containing a leaf.

For example, consider array A such that:

```<code>A[0] = 0
A[1] = 0
A[2] = 0
A[3] = 1
A[4] = 1
A[5] = 0
A[6] = 1
A[7] = 0
A[8] = 0
A[9] = 0
A[10] = 0
</code>```

The frog can make three jumps of length F(5) = 5, F(3) = 2 and F(5) = 5.

Write a function:

```<code>class Solution { public int solution(int[] A); }
</code>```

that, given an array A consisting of N integers, returns the minimum number of jumps by which the frog can get to the other side of the river. If the frog cannot reach the other side of the river, the function should return −1.

For example, given:

```<code>A[0] = 0
A[1] = 0
A[2] = 0
A[3] = 1
A[4] = 1
A[5] = 0
A[6] = 1
A[7] = 0
A[8] = 0
A[9] = 0
A[10] = 0
</code>```

the function should return 3, as explained above.

Assume that:

N is an integer within the range [0..100,000];
each element of array A is an integer that can have one of the following values: 0, 1.
Complexity:

expected worst-case time complexity is O(N*log(N));
expected worst-case space complexity is O(N) (not counting the storage required for input arguments).

I wrote the following solution,

```<code>class Solution {
    private class Jump {
        int position;
        int number;

        public int getPosition() {
            return position;
        }

        public int getNumber() {
            return number;
        }

        public Jump(int pos, int number) {
            this.position = pos;
            this.number = number;
        }
    }

    public int solution(int[] A) {

        int N = A.length;

        List<Integer> fibs = getFibonacciNumbers(N + 1);

        Stack<Jump> jumps = new Stack<>();
        jumps.push(new Jump(-1, 0));

        boolean[] visited = new boolean[N];

        while (!jumps.isEmpty()) {

            Jump jump = jumps.pop();

            int position = jump.getPosition();
            int number = jump.getNumber();

            for (int fib : fibs) {

                if (position + fib > N) {
                    break;
                } else if (position + fib == N) {
                    return number + 1;
                } else if (!visited[position + fib] && A[position + fib] == 1) {

                    visited[position + fib] = true;
                    jumps.add(new Jump(position + fib, number + 1));
                }
            }
        }

        return -1;
    }

    private List<Integer> getFibonacciNumbers(int N) {

        List<Integer> list = new ArrayList<>();

        for (int i = 0; i < 2; i++) {
            list.add(i);
        }

        int i = 2;

        while (list.get(list.size() - 1) <= N) {

            list.add(i, (list.get(i - 1) + list.get(i - 2)));
            i++;
        }

        for (i = 0; i < 2; i++) {
            list.remove(i);
        }

        return list;
    }

    public static void main(String[] args) {

    int[] A = new int[11];

    A[0] = 0;
    A[1] = 0;
    A[2] = 0;
    A[3] = 1;
    A[4] = 1;
    A[5] = 0;
    A[6] = 1;
    A[7] = 0;
    A[8] = 0;
    A[9] = 0;
    A[10] = 0;

    System.out.println(solution(A));
   }
}
</code>```

However, while the correctness seems good, the performance is not high enough.  Is there a bug in the code and how do I improve the performance?

答:
JavaScript with 100%.
Inspired from here.</p>

```<code>function solution(A) {
  const createFibs = n => {
    const fibs = Array(n + 2).fill(null)
    fibs[1] = 1
    for (let i = 2; i < n + 1; i++) {
      fibs[i] = fibs[i - 1] + fibs[i - 2]
    }
    return fibs
  }
  const createJumps = (A, fibs) => {
    const jumps = Array(A.length + 1).fill(null)
    let prev = null
    for (i = 2; i < fibs.length; i++) {
      const j = -1 + fibs[i]
      if (j > A.length) break
      if (j === A.length || A[j] === 1) {
        jumps[j] = 1
        if (prev === null) prev = j
      }
    }
    if (prev === null) {
      jumps[A.length] = -1
      return jumps
    }
    while (prev < A.length) {
      for (let i = 2; i < fibs.length; i++) {
        const j = prev + fibs[i]
        if (j > A.length) break
        if (j === A.length || A[j] === 1) {
          const x = jumps[prev] + 1
          const y = jumps[j]
          jumps[j] = y === null ? x : Math.min(y, x)
        }
      }
      prev++
      while (prev < A.length) {
        if (jumps[prev] !== null) break
        prev++
      }
    }
    if (jumps[A.length] === null) jumps[A.length] = -1
    return jumps
  }
  const fibs = createFibs(26)
  const jumps = createJumps(A, fibs)
  return jumps[A.length]
}

const A = [0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0]
console.log(A)
const s = solution(A)
console.log(s)
</code>```

Body:
I work with a Codility problem provided below,

The Fibonacci sequence is defined using the following recursive formula:

F(0) = 0
F(1) = 1
F(M) = F(M - 1) + F(M - 2) if M >= 2

A small frog wants to get to the other side of a river. The frog is initially located at one bank of the river (position −1) and wants to get to the other bank (position N). The frog can jump over any distance F(K), where F(K) is the K-th Fibonacci number. Luckily, there are many leaves on the river, and the frog can jump between the leaves, but only in the direction of the bank at position N.

The leaves on the river are represented in an array A consisting of N integers. Consecutive elements of array A represent consecutive positions from 0 to N − 1 on the river. Array A contains only 0s and/or 1s:

0 represents a position without a leaf;
1 represents a position containing a leaf.
The goal is to count the minimum number of jumps in which the frog can get to the other side of the river (from position −1 to position N). The frog can jump between positions −1 and N (the banks of the river) and every position containing a leaf.

For example, consider array A such that:

A[0] = 0
A[1] = 0
A[2] = 0
A[3] = 1
A[4] = 1
A[5] = 0
A[6] = 1
A[7] = 0
A[8] = 0
A[9] = 0
A[10] = 0

The frog can make three jumps of length F(5) = 5, F(3) = 2 and F(5) = 5.

Write a function:

class Solution { public int solution(int[] A); }

that, given an array A consisting of N integers, returns the minimum number of jumps by which the frog can get to the other side of the river. If the frog cannot reach the other side of the river, the function should return −1.

For example, given:

A[0] = 0
A[1] = 0
A[2] = 0
A[3] = 1
A[4] = 1
A[5] = 0
A[6] = 1
A[7] = 0
A[8] = 0
A[9] = 0
A[10] = 0

the function should return 3, as explained above.

Assume that:

N is an integer within the range [0..100,000];
each element of array A is an integer that can have one of the following values: 0, 1.
Complexity:

expected worst-case time complexity is O(N*log(N));
expected worst-case space complexity is O(N) (not counting the storage required for input arguments).

I wrote the following solution,

class Solution {
    private class Jump {
        int position;
        int number;

        public int getPosition() {
            return position;
        }

        public int getNumber() {
            return number;
        }

        public Jump(int pos, int number) {
            this.position = pos;
            this.number = number;
        }
    }

    public int solution(int[] A) {

        int N = A.length;

        List<Integer> fibs = getFibonacciNumbers(N + 1);

        Stack<Jump> jumps = new Stack<>();
        jumps.push(new Jump(-1, 0));

        boolean[] visited = new boolean[N];

        while (!jumps.isEmpty()) {

            Jump jump = jumps.pop();

            int position = jump.getPosition();
            int number = jump.getNumber();

            for (int fib : fibs) {

                if (position + fib > N) {
                    break;
                } else if (position + fib == N) {
                    return number + 1;
                } else if (!visited[position + fib] && A[position + fib] == 1) {

                    visited[position + fib] = true;
                    jumps.add(new Jump(position + fib, number + 1));
                }
            }
        }

        return -1;
    }

    private List<Integer> getFibonacciNumbers(int N) {

        List<Integer> list = new ArrayList<>();

        for (int i = 0; i < 2; i++) {
            list.add(i);
        }

        int i = 2;

        while (list.get(list.size() - 1) <= N) {

            list.add(i, (list.get(i - 1) + list.get(i - 2)));
            i++;
        }

        for (i = 0; i < 2; i++) {
            list.remove(i);
        }

        return list;
    }

    public static void main(String[] args) {

    int[] A = new int[11];

    A[0] = 0;
    A[1] = 0;
    A[2] = 0;
    A[3] = 1;
    A[4] = 1;
    A[5] = 0;
    A[6] = 1;
    A[7] = 0;
    A[8] = 0;
    A[9] = 0;
    A[10] = 0;

    System.out.println(solution(A));
   }
}

However, while the correctness seems good, the performance is not high enough.  Is there a bug in the code and how do I improve the performance?

Body:
JavaScript with 100%.
Inspired from here.

function solution(A) {
  const createFibs = n => {
    const fibs = Array(n + 2).fill(null)
    fibs[1] = 1
    for (let i = 2; i < n + 1; i++) {
      fibs[i] = fibs[i - 1] + fibs[i - 2]
    }
    return fibs
  }
  const createJumps = (A, fibs) => {
    const jumps = Array(A.length + 1).fill(null)
    let prev = null
    for (i = 2; i < fibs.length; i++) {
      const j = -1 + fibs[i]
      if (j > A.length) break
      if (j === A.length || A[j] === 1) {
        jumps[j] = 1
        if (prev === null) prev = j
      }
    }
    if (prev === null) {
      jumps[A.length] = -1
      return jumps
    }
    while (prev < A.length) {
      for (let i = 2; i < fibs.length; i++) {
        const j = prev + fibs[i]
        if (j > A.length) break
        if (j === A.length || A[j] === 1) {
          const x = jumps[prev] + 1
          const y = jumps[j]
          jumps[j] = y === null ? x : Math.min(y, x)
        }
      }
      prev++
      while (prev < A.length) {
        if (jumps[prev] !== null) break
        prev++
      }
    }
    if (jumps[A.length] === null) jumps[A.length] = -1
    return jumps
  }
  const fibs = createFibs(26)
  const jumps = createJumps(A, fibs)
  return jumps[A.length]
}

const A = [0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0]
console.log(A)
const s = solution(A)
console.log(s)


来源: stackexchange

问:
What is the purpose of "remove unused references"
I have read that removing unused references makes no difference to the compiler as it ignores assemblies that are not being referenced in the code itself.

But I find it hard to believe because then, what is the real purpose of Removing unused references? It doesn't have any noticeable effect on the size of the generated assembly or otherwise. Or is this smart behaviour limited to the C# compiler (csc.exe) and not inherent to vbc.exe?

If this functionality is so useless, why does ReSharper offer it as a feature? Why is it provided within the Visual Studio Project Configuration dialog?

The only activity I can think of where this would be useful is during Deployment. References (used or unused) would still be copied by the installer. But for assemblies that reside in the GAC (for instance, BCL assemblies), this would not be a problem either.

答: Apart from the source files being smaller, I think it is just better to have a clean source file that has no unused code or references.</p>

OwnerDisplayName: Cerebrus

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Cerebrus

OwnerDisplayName: Christophe Herreman


问:
View schema of resultset in SQL Server Management Studio
Is there any way in Sql Server Management Studio (2008) whereby I can view the data types of each field in the result of a query?

In this case, I am running a stored procedure which returns a result set, and I would like to know the lengths of the nvarchar columns and precision of decimals.

In the past, I have created a view which contains the underlying query in the stored procedure, and then viewed the column list, but the query within the procedure is much too complex to do so in this case.

Any ideas?

答:
Quick and dirty snippet, requires all the fields in the result set are named or aliased;</p>

```<code>select * into #T
from
  openrowset('SQLNCLI', 'Server=.;Trusted_Connection=yes;', 'exec thedb.dbo.sp_whatever')
exec('use tempdb exec sp_columns #T drop table #T')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Quick and dirty snippet, requires all the fields in the result set are named or aliased;

select * into #T
from
  openrowset('SQLNCLI', 'Server=.;Trusted_Connection=yes;', 'exec thedb.dbo.sp_whatever')
exec('use tempdb exec sp_columns #T drop table #T')


问:
Xcode/iOS App freezing, how to track such errors
I have sometimes app freezing I do not know what is the source of problem.
It happens rarely but happens. I consider how to track such issue
I have crashlytics from firebase but there is no errors as freezing is I suppose something with threads maybe some deadlocks or infinite loops.

Is there way to track such things?
What maybe reasons of app freezing and being inactive (it is SwiftUI app) ?
Are there possibilities to track/profile apps installed on devices (not connected via Xcode) and send informations such that are available in Instrument to something like firebase console or other 3rd party tools.

Update

I think I do not indicated important fact.
It freezes UI definitely not for a few seconds but app need do be killed and restarted again.

答: I have experienced some of these weird behaviours before. And mostly the reason behind it was a task that is blocking the main thread making it unresponsive. Pause the app and check the stack trace. Also make sure all your UI operations are done on the main thread. Hope this helps! </p>

ContentLicense: CC BY-SA 4.0


问:
FIWARE lab - My dockerhub image is created empty
I want to generate an image in FIWARE lab from Docker Hub.

I have tried different options and fiware lab does not give me an error, but it generates an empty image that cannot be instanced.

Modal to create my own image

Could you please give me an example of the url you use to create your own images from the docker hub?

答:
Currently FIWARE Lab only supports Virtual Machine images. There are no Docker images.

Maybe you can create you image and configure docker to run inside the Virtual Machine created from your image.

However, you can look at how a new image could be created using Openstack APIs and some qemu/libvirt tools here: https://github.com/jicarretero/FiwareImageTweak

The example there shows how to create a new image with docker and some dockers which will run when a new instance is created from an image generated this way.


问:
How to get value from selected icon dropdown?
I have 3 icons. i.e icon-star, icon-check, icon-info. if icon-start selected, then i want to store the value of the selected icon into database. for example:

icon-start with value="star"

icon-check with value="complete"

icon-info with value="important"

So, the value stored into database is "star" because i choose icon-star.

Where i must put the value? and how?

Here my modal:

```<code><form autocomplete="off" novalidate action="<?= base_url('app/admin/to-do-add')?>" method="POST">
    <input type="hidden" name="<?=$this->security->get_csrf_token_name();?>" value="<?=$this->security->get_csrf_hash();?>">
    <div class="btn-group dropup dropdown-icon-wrapper mr-1 mb-1" style="float:right">
        <button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" name="status">
            <i class="feather icon-star dropdown-icon"></i>
        </button>
        <div class="dropdown-menu">
            <span class="dropdown-item">
                <i class="feather icon-star" data-toggle="tooltip" data-placement="left" title="Starred" value="star"></i>
            </span>
            <span class="dropdown-item">
                <i class="feather icon-info" data-toggle="tooltip" data-placement="left" title="Important" value="important"></i>
            </span>
            <span class="dropdown-item">
                <i class="feather icon-check" data-toggle="tooltip" data-placement="left" title="Completed" value="complete"></i>
            </span>
        </div>
    </div>
    <br>
    <br>
    <div class="form-group">
        <label>To</label>
        <div class="controls">
            <select class="select2 form-control" name="to">
                <option value="<?php echo $dataLogin->MEmployee_ID;?>">-SELECT-</option>
                <?php foreach ($data1 as $row){ ?>
                <option value=" <?php echo $row->MEmployee_ID ?>">
                    <?php echo $row->EmployeeName?>
                </option>
                <?php } ?>
            </select>
        </div>
    </div>
    <div class=" modal-footer">
        <button type="submit" class="btn btn-primary"><?= $this->lang->line('add');?></button>
    </div>
</form>
</code>```

Here my controller :

```<code>public function addTask(){
    var_dump($this->input->post('status')); die(); //i tried to var_dump, the value is NULL
    $dataLogin = $this->employee_model->checkUserData($this->session->userdata('islogin'))->row();
    $data = [
        "MEmployee_ID" => $this->input->post('to'),
        "status" => $this->input->post('status') //here the value of selected icon
    ];
}
</code>```

答:
I think you should use a "select" instead of a "dropdown" because a dropdown is not an input. And according to ww3school
(https://www.w3schools.com/html/html_form_elements.asp)

The select element defines a drop-down list.

The option elements defines an option that can be selected.

I suggest you try this code:

```<code><?php echo form_open('app/admin/to-do-add'); ?>
    <input type="hidden" name="<?=$this->security->get_csrf_token_name();?>" value="<?=$this->security->get_csrf_hash();?>">

    <select class="custom-select mb-3" name="status">
        <option selected disabled>-- Status--</option>
        <option value="star"><i class="feather icon-star" data-toggle="tooltip" data-placement="left" title="Starred" ></i></option>
        <option value="important"><i class="feather icon-info" data-toggle="tooltip" data-placement="left" title="Important"></i></option>
        <option value="complete"><i class="feather icon-check" data-toggle="tooltip" data-placement="left" title="Completed"></i></option>
    </select>

    <div class="form-group">
        <label>To</label>
        <div class="controls">
            <select class="select2 form-control" name="to">
                <option value="<?php echo $dataLogin->MEmployee_ID;?>">-SELECT-</option>
                <?php foreach ($data1 as $row){ ?>
                <option value=" <?php echo $row->MEmployee_ID ?>"><?php echo $row->EmployeeName?></option>
                <?php } ?>
            </select>
        </div>
    </div>

    <div class=" modal-footer">
        <button type="submit" class="btn btn-primary"><?= $this->lang->line('add');?></button>
    </div>
<?php echo form_close(); ?>
</code>```

Body:
I have 3 icons. i.e icon-star, icon-check, icon-info. if icon-start selected, then i want to store the value of the selected icon into database. for example:

icon-start with value="star"

icon-check with value="complete"

icon-info with value="important"

So, the value stored into database is "star" because i choose icon-star.

Where i must put the value? and how?

Here my modal:

<form autocomplete="off" novalidate action="<?= base_url('app/admin/to-do-add')?>" method="POST">
    <input type="hidden" name="<?=$this->security->get_csrf_token_name();?>" value="<?=$this->security->get_csrf_hash();?>">

        <button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" name="status">

        </button>

        To

            <select class="select2 form-control" name="to">
                <option value="<?php echo $dataLogin->MEmployee_ID;?>">-SELECT-</option>
                <?php foreach ($data1 as $row){ ?>
                <option value=" <?php echo $row->MEmployee_ID ?>">
                    <?php echo $row->EmployeeName?>
                </option>
                <?php } ?>
            </select>

        <button type="submit" class="btn btn-primary"><?= $this->lang->line('add');?></button>

</form>

Here my controller :

public function addTask(){
    var_dump($this->input->post('status')); die(); //i tried to var_dump, the value is NULL
    $dataLogin = $this->employee_model->checkUserData($this->session->userdata('islogin'))->row();
    $data = [
        "MEmployee_ID" => $this->input->post('to'),
        "status" => $this->input->post('status') //here the value of selected icon
    ];
}

Body:
I think you should use a "select" instead of a "dropdown" because a dropdown is not an input. And according to ww3school
(https://www.w3schools.com/html/html_form_elements.asp)

The select element defines a drop-down list.

The option elements defines an option that can be selected.

I suggest you try this code:

<?php echo form_open('app/admin/to-do-add'); ?>
    <input type="hidden" name="<?=$this->security->get_csrf_token_name();?>" value="<?=$this->security->get_csrf_hash();?>">

    <select class="custom-select mb-3" name="status">
        <option selected disabled>-- Status--</option>
        <option value="star"><i class="feather icon-star" data-toggle="tooltip" data-placement="left" title="Starred" ></i></option>
        <option value="important"><i class="feather icon-info" data-toggle="tooltip" data-placement="left" title="Important"></i></option>
        <option value="complete"><i class="feather icon-check" data-toggle="tooltip" data-placement="left" title="Completed"></i></option>
    </select>

    <div class="form-group">
        <label>To</label>
        <div class="controls">
            <select class="select2 form-control" name="to">
                <option value="<?php echo $dataLogin->MEmployee_ID;?>">-SELECT-</option>
                <?php foreach ($data1 as $row){ ?>
                <option value=" <?php echo $row->MEmployee_ID ?>"><?php echo $row->EmployeeName?></option>
                <?php } ?>
            </select>
        </div>
    </div>

    <div class=" modal-footer">
        <button type="submit" class="btn btn-primary"><?= $this->lang->line('add');?></button>
    </div>
<?php echo form_close(); ?>


问:
Text not getting rendered in React Web Applications
I am trying to build a personal React web app by modularizing the Hookup template from ColorLib. However, React is not rendering the text components on-screen while images are getting displayed correctly. The text and the corresponding CSS styles are being mapped correctly, as I saw when I checked the DevTools.

This is my code:

```<code>import React, { Component } from 'react'

export default class Details extends Component {
  render() {
    return (
    <section className="ftco-section ftco-about ftco-no-pt ftco-no-pb" id="groom-bride-section">
        <div className="container">
          <div className="row">
            <div className="col-md-12">
              <div className="wrap">
                <div className="row d-flex">
                  <div className="col-md-6 d-flex">
                    <div className="img d-flex align-self-stretch align-items-center" style={{backgroundImage: 'url(images/about.jpg)'}}>
                    </div>
                  </div>
                  <div className="col-md-6 py-md-5 text">
                    <div className="py-md-4">
                      <div className="row justify-content-start pb-3">
                        <div className="col-md-12 ftco-animate p-4 p-lg-5 text-center">
                          <span className="subheading mb-4">Join us to celebrate <br />the wedding day of</span>
                          <h2 className="mb-4">Francisco <span>&</span> Laura</h2>
                          <span className="icon flaticon-rose-variant-outline-with-vines" />
                          <span className="subheading">Which is celebration on</span>
                          <p className="time mb-4"><span>Dec | 28 | 2019</span></p>
                          <span className="subheading mb-5">Starting at 2:00 <br /> in the afternoon</span>
                          <span className="subheading mb-5">Saint John Paul Church <br /> in YorkNew.in</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    )
  }
}
</code>```

Any help on resolving the same is appreciated.

答: I checked the computed styles as @Drew Reese suggested, and {visibility: hidden, opacity: 0} styles were getting applies to the text. All I had to do was override the same. Thanks for the help!</p>

Body:
I am trying to build a personal React web app by modularizing the Hookup template from ColorLib. However, React is not rendering the text components on-screen while images are getting displayed correctly. The text and the corresponding CSS styles are being mapped correctly, as I saw when I checked the DevTools.

This is my code:

import React, { Component } from 'react'

export default class Details extends Component {
  render() {
    return (

                          Join us to celebrate
the wedding day of

Francisco & Laura

                          Which is celebration on

Dec | 28 | 2019

                          Starting at 2:00
 in the afternoon
                          Saint John Paul Church
 in YorkNew.in

    )
  }
}

Any help on resolving the same is appreciated.


问:
Android WebView crashes after a few days with Out of memory message
I have an app that can have multiple WebViews. For testing i only use one WebView though. The WebView is refreshed every 15 minutes, and the app is just meant to be open all the time on the device as sort of a dashboard. The above works fine, but after a day or two the App will suddenly crash with the following message:

```<code>06-03 09:59:43.165 6243-6267/? A/libc: Fatal signal 5 (SIGTRAP), code -6 in tid 6267 (RenderThread)
06-03 09:59:43.227 310-310/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
06-03 09:59:43.228 310-310/? A/DEBUG: Build fingerprint: 'Lenovo/TB2-X30F/TB2-X30F:6.0.1/LenovoTB2-X30F/TB2-X30F_S000113_160816_ROW:user/release-keys'
06-03 09:59:43.228 310-310/? A/DEBUG: Revision: '0'
06-03 09:59:43.229 310-310/? A/DEBUG: ABI: 'arm'
06-03 09:59:43.230 310-310/? A/DEBUG: pid: 6243, tid: 6267, name: RenderThread  >>> namespace.of.app <<<
06-03 09:59:43.230 310-310/? A/DEBUG: signal 5 (SIGTRAP), code -6 (SI_TKILL), fault addr 0x1863
06-03 09:59:43.326 310-310/? A/DEBUG: Abort message: '[FATAL:memory_linux.cc(37)] Out of memory.
    '
06-03 09:59:43.327 310-310/? A/DEBUG:     r0 00000000  r1 00000000  r2 7fffffff  r3 00000000
06-03 09:59:43.327 310-310/? A/DEBUG:     r4 a34144e4  r5 0000002a  r6 a7c16c38  r7 0000002a
06-03 09:59:43.327 310-310/? A/DEBUG:     r8 a3414930  r9 a3414934  sl b6cc7e40  fp a34144e4
06-03 09:59:43.327 310-310/? A/DEBUG:     ip a34144a8  sp a34144d0  lr b6ca5459  pc a64f473c  cpsr 60070030
06-03 09:59:43.330 310-310/? A/DEBUG: backtrace:
06-03 09:59:43.330 310-310/? A/DEBUG:     #00 pc 015fb73c  /data/app/com.google.android.webview-2/lib/arm/libwebviewchromium.so
</code>```

I simply have a a Runnable that handles the refreshing like so

```<code>UpdateTimerWeb = new Runnable() {
    @Override
    public void run() {
        webView.reload();
        Web.WebHandler.postDelayed(UpdateTimerWeb, 15 * 60 * 1000); // every 15 mins
    }

};
Web.WebHandler.postDelayed(UpdateTimerWeb, 15 * 60 * 1000); // every 15 mins
</code>```

Am i supposed to flush it somehow or reinit the webView object or what am i missing?

答:
I have this experience that webView keeps caching, if you want to stop caching use :

```<code>webView.settings.setAppCacheEnabled(false)
webView.settings.cacheMode = WebSettings.LOAD_NO_CACHE
webView.settings.javaScriptEnabled = true
</code>```

you can handle actions on webView by this class in your fragment or activitity :

```<code>inner class WebClientCustom : WebViewClient() {

override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
    super.onPageStarted(view, url, favicon)
    //for example progress
    prg.visibility = View.VISIBLE
}

override fun onPageFinished(view: WebView?, url: String?) {
    super.onPageFinished(view, url)
    stopLoading()
}

@TargetApi(Build.VERSION_CODES.M)
override fun onReceivedError(
    view: WebView?,
    request: WebResourceRequest?,
    error: WebResourceError?
) {
    stopLoading()
}

@SuppressWarnings("deprecation")
override fun onReceivedError(
    view: WebView,
    errorCode: Int,
    description: String,
    failingUrl: String
) {
    stopLoading()
}

private fun stopLoading() {
    prg.visibility = View.GONE
    swipeRefreshLayout.isRefreshing = false

}
</code>```

Body:
I have an app that can have multiple WebViews. For testing i only use one WebView though. The WebView is refreshed every 15 minutes, and the app is just meant to be open all the time on the device as sort of a dashboard. The above works fine, but after a day or two the App will suddenly crash with the following message:

06-03 09:59:43.165 6243-6267/? A/libc: Fatal signal 5 (SIGTRAP), code -6 in tid 6267 (RenderThread)
06-03 09:59:43.227 310-310/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
06-03 09:59:43.228 310-310/? A/DEBUG: Build fingerprint: 'Lenovo/TB2-X30F/TB2-X30F:6.0.1/LenovoTB2-X30F/TB2-X30F_S000113_160816_ROW:user/release-keys'
06-03 09:59:43.228 310-310/? A/DEBUG: Revision: '0'
06-03 09:59:43.229 310-310/? A/DEBUG: ABI: 'arm'
06-03 09:59:43.230 310-310/? A/DEBUG: pid: 6243, tid: 6267, name: RenderThread  >>> namespace.of.app <<<
06-03 09:59:43.230 310-310/? A/DEBUG: signal 5 (SIGTRAP), code -6 (SI_TKILL), fault addr 0x1863
06-03 09:59:43.326 310-310/? A/DEBUG: Abort message: '[FATAL:memory_linux.cc(37)] Out of memory.
    '
06-03 09:59:43.327 310-310/? A/DEBUG:     r0 00000000  r1 00000000  r2 7fffffff  r3 00000000
06-03 09:59:43.327 310-310/? A/DEBUG:     r4 a34144e4  r5 0000002a  r6 a7c16c38  r7 0000002a
06-03 09:59:43.327 310-310/? A/DEBUG:     r8 a3414930  r9 a3414934  sl b6cc7e40  fp a34144e4
06-03 09:59:43.327 310-310/? A/DEBUG:     ip a34144a8  sp a34144d0  lr b6ca5459  pc a64f473c  cpsr 60070030
06-03 09:59:43.330 310-310/? A/DEBUG: backtrace:
06-03 09:59:43.330 310-310/? A/DEBUG:     #00 pc 015fb73c  /data/app/com.google.android.webview-2/lib/arm/libwebviewchromium.so

I simply have a a Runnable that handles the refreshing like so

UpdateTimerWeb = new Runnable() {
    @Override
    public void run() {
        webView.reload();
        Web.WebHandler.postDelayed(UpdateTimerWeb, 15 * 60 * 1000); // every 15 mins
    }

};
Web.WebHandler.postDelayed(UpdateTimerWeb, 15 * 60 * 1000); // every 15 mins

Am i supposed to flush it somehow or reinit the webView object or what am i missing?

Body:
I have this experience that webView keeps caching, if you want to stop caching use :

webView.settings.setAppCacheEnabled(false)
webView.settings.cacheMode = WebSettings.LOAD_NO_CACHE
webView.settings.javaScriptEnabled = true

you can handle actions on webView by this class in your fragment or activitity :

inner class WebClientCustom : WebViewClient() {

override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
    super.onPageStarted(view, url, favicon)
    //for example progress
    prg.visibility = View.VISIBLE
}

override fun onPageFinished(view: WebView?, url: String?) {
    super.onPageFinished(view, url)
    stopLoading()
}

@TargetApi(Build.VERSION_CODES.M)
override fun onReceivedError(
    view: WebView?,
    request: WebResourceRequest?,
    error: WebResourceError?
) {
    stopLoading()
}

@SuppressWarnings("deprecation")
override fun onReceivedError(
    view: WebView,
    errorCode: Int,
    description: String,
    failingUrl: String
) {
    stopLoading()
}

private fun stopLoading() {
    prg.visibility = View.GONE
    swipeRefreshLayout.isRefreshing = false

}


问:
RMarkdown: ggplot into a table
There are already a few questions considering ggplots in RMarkdown but none has answered my question as how to put a ggplot into a table with kable() by knitr.
I ve tried this link:

How can I embed a plot within a RMarkdown table?

But have not had any luck so far. Any ideas?

The idea was to put all plots into a list with

a<-list(p1,p2,p3...)

and then having the table with

{r}kable(a)

Additional text should also be able to be included

```<code>b<-("x","y","z",...)
kable (c(a,b),col.names=c())
</code>```

Thanks for your help

Frieder

答:
I have found my way around it as described in the link I posted.

I. Saved my plot as a picture
II. Used sprintf() to insert picture into table with this command from Rmarkdown:
![](path/to/file)

Poor, but it works. If anybody finds a solution, I will always be interested in smart coding.

Title: RMarkdown: ggplot into a table

Body:
There are already a few questions considering ggplots in RMarkdown but none has answered my question as how to put a ggplot into a table with kable() by knitr.
I ve tried this link:

How can I embed a plot within a RMarkdown table?

But have not had any luck so far. Any ideas?

The idea was to put all plots into a list with

a<-list(p1,p2,p3...)

and then having the table with

{r}kable(a)

Additional text should also be able to be included

b<-("x","y","z",...)
kable (c(a,b),col.names=c())

Thanks for your help

Frieder


问:
How to display interactive graphics from another website?
For fun, I'm trying to copy the source code of entire websites into an .html file and run it locally from my Desktop (not public). While mostly everything loads like it appears on the original website, I am having trouble displaying the actual content of interactive graphs.

For example, the NOAA's Global Monitoring Laboratory displays an interactive version of the Keeling's Curve, which features two graphs that can be manipulated from the bottom (timeframe), hovered over to display figures, etc.

It should look something like this:

But instead, my local file looks like this:

As you can see, the slope/plot itself is missing, as well as some of the other features below and to the side. What am I doing wrong? Obviously, the website's actual stylesheet has shortened file paths (e.g. /gmd/css/gmd.css), so I made sure there were direct links in the local HTML file (e.g. https://esrl.noaa/gov/gmd/css/gmd.css).

I copied the entire HTML code in the Elements tab of the Inspect Element console (everything after <!DOCTYPE html>). Is there something else I should add to the local file?

Update: There was a long list of errors in the console, but only four actual lines of faulty code. Both the errors and the faulty code are shown below:

答:
The first script tag(highlighted) in error contains a typo(/gov instead of .gov). It should be:

```<code>https://esrl.noaa.gov/gmd/js/dygraph.min.js
</code>```

instead of

```<code>https://esrl.noaa/gov/gmd/js/dygraph.min.js
</code>```

Body:
The first script tag(highlighted) in error contains a typo(/gov instead of .gov). It should be:

https://esrl.noaa.gov/gmd/js/dygraph.min.js

instead of

https://esrl.noaa/gov/gmd/js/dygraph.min.js


问:
Android golang bind refresh *.aar
I am importing an aar file using the new module > import JAR or AAR package option. Initially I was able call a method from my library. However after updating the library and running Gomobile bind again, I can't figure out how to update the aar file. The new methods are not shown after updating the .aar file manually.
Importing again causes "Project already contains subproject with name mobilelib".

Android Studio 2.2.3
How do I refresh the .aar file?

build.gradle(app)

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "23.0.2"
    defaultConfig {
        applicationId "com.testing.testgolanglib"
        minSdkVersion 16
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    testCompile 'junit:junit:4.12'
    compile project(':mobilelib')
}
</code>```

mobilelib

```<code>configurations.maybeCreate("default")
artifacts.add("default", file('mobilelib.aar'))
</code>```

Project build.gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        flatDir{
            dirs '/Users/abc/projects/go/src/com.abc/mobilelib'
        }

    }

}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

答: I had the same problem. I solved it by simplifying a new function on golang. I used struct with supported by gomobile data types to return the result, when I simplified the function (encoded the result into a simple string), everything worked.</p>

Title: Android golang bind refresh *.aar

Body:
I am importing an aar file using the new module > import JAR or AAR package option. Initially I was able call a method from my library. However after updating the library and running Gomobile bind again, I can't figure out how to update the aar file. The new methods are not shown after updating the .aar file manually.
Importing again causes "Project already contains subproject with name mobilelib".

Android Studio 2.2.3
How do I refresh the .aar file?

build.gradle(app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "23.0.2"
    defaultConfig {
        applicationId "com.testing.testgolanglib"
        minSdkVersion 16
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    testCompile 'junit:junit:4.12'
    compile project(':mobilelib')
}

mobilelib

configurations.maybeCreate("default")
artifacts.add("default", file('mobilelib.aar'))

Project build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        flatDir{
            dirs '/Users/abc/projects/go/src/com.abc/mobilelib'
        }

    }

}

task clean(type: Delete) {
    delete rootProject.buildDir
}


问:
Switching endianness in the middle of a struct.unpack format string
I have a bunch of binary data (the contents of a video game save-file, as it happens) where a part of the data contains both little-endian and big-endian integer values. Naively, without reading much of the docs, I tried to unpack it this way...

```<code>struct.unpack(
    '3sB<H<H<H<H4s<I<I32s>IbBbBbBbB12s20sBB4s',
    string_data
)
</code>```

...and of course I got this cryptic error message:

```<code>struct.error: bad char in struct format
</code>```

The problem is that struct.unpack format strings do not expect individual fields to be marked with endianness. The actually correct format-string here would be something like

```<code>struct.unpack(
    '<3sBHHHH4sII32sIbBbBbBbB12s20sBB4s',
    string_data
)
</code>```

except that this will flip the endianness of the third I field (parsing it as little-endian, when I really want to parse it as big-endian).

Is there an easy and/or "Pythonic" solution to my problem? I have already thought of three possible solutions, but none of them is particularly elegant. In the absence of better ideas I'll probably go with number 3:

I could extract a substring and parse it separately:

```<code>(my.f1, my.f2, ...) = struct.unpack('<3sBHHHH4sII32sIbBbBbBbB12s20sBB4s', string_data)
my.f11 = struct.unpack('>I', string_data[56:60])
</code>```

I could flip the bits in the field after the fact:

```<code>(my.f1, my.f2, ...) = struct.unpack('<3sBHHHH4sII32sIbBbBbBbB12s20sBB4s', string_data)
my.f11 = swap32(my.f11)
</code>```

I could just change my downstream code to expect this field to be represented differently — it's actually a bitmask, not an arithmetic integer, so it wouldn't be too hard to flip around all the bitmasks I'm using with it; but the big-endian versions of these bitmasks are more mnemonically relevant than the little-endian versions.

答:
A little late to the party, but I just had the same problem. I solved it with a custom numpy dtype, which allows to mix elements with different endianess (see https://numpy.org/doc/stable/reference/generated/numpy.dtype.html):</p>

```<code>t=np.dtype('>u4,<u4') # Compound type with two 4-byte unsigned int with different byte order
a=np.zeros(shape=1, dtype=t) # Create an array of length one with above type
a[0][0]=1 # Assign first uint
a[0][1]=1 # Assign second uint
bytes=a.tobytes() # bytes should be b'\x01\x00\x00\x00\x00\x00\x00\x01'
b=np.frombuffer(buf, dtype=t) # should yield array[(1,1)]
c=np.frombuffer(buf, dtype=np.uint32) # yields array([       1, 16777216]
</code>```

Body:
I have a bunch of binary data (the contents of a video game save-file, as it happens) where a part of the data contains both little-endian and big-endian integer values. Naively, without reading much of the docs, I tried to unpack it this way...

struct.unpack(
    '3sB<H<H<H<H4s<I<I32s>IbBbBbBbB12s20sBB4s',
    string_data
)

...and of course I got this cryptic error message:

struct.error: bad char in struct format

The problem is that struct.unpack format strings do not expect individual fields to be marked with endianness. The actually correct format-string here would be something like

struct.unpack(
    '<3sBHHHH4sII32sIbBbBbBbB12s20sBB4s',
    string_data
)

except that this will flip the endianness of the third I field (parsing it as little-endian, when I really want to parse it as big-endian).

Is there an easy and/or "Pythonic" solution to my problem? I have already thought of three possible solutions, but none of them is particularly elegant. In the absence of better ideas I'll probably go with number 3:

I could extract a substring and parse it separately:

(my.f1, my.f2, ...) = struct.unpack('<3sBHHHH4sII32sIbBbBbBbB12s20sBB4s', string_data)
my.f11 = struct.unpack('>I', string_data[56:60])

I could flip the bits in the field after the fact:

(my.f1, my.f2, ...) = struct.unpack('<3sBHHHH4sII32sIbBbBbBbB12s20sBB4s', string_data)
my.f11 = swap32(my.f11)

I could just change my downstream code to expect this field to be represented differently — it's actually a bitmask, not an arithmetic integer, so it wouldn't be too hard to flip around all the bitmasks I'm using with it; but the big-endian versions of these bitmasks are more mnemonically relevant than the little-endian versions.

Body:
A little late to the party, but I just had the same problem. I solved it with a custom numpy dtype, which allows to mix elements with different endianess (see https://numpy.org/doc/stable/reference/generated/numpy.dtype.html):

t=np.dtype('>u4,<u4') # Compound type with two 4-byte unsigned int with different byte order
a=np.zeros(shape=1, dtype=t) # Create an array of length one with above type
a[0][0]=1 # Assign first uint
a[0][1]=1 # Assign second uint
bytes=a.tobytes() # bytes should be b'\x01\x00\x00\x00\x00\x00\x00\x01'
b=np.frombuffer(buf, dtype=t) # should yield array[(1,1)]
c=np.frombuffer(buf, dtype=np.uint32) # yields array([       1, 16777216]


问:
Python: capturing each thread details in individual log file
I am performing web sanity for a couple of URLs and currently, we are logging the entire log details of these urls in a single log file (using logging module), but it is required to capture log details of each url in a separate log file.

Currently, I have 7 urls in a list and created 7 logging.txt files in a list.  Then, in a loop, I used the basicConfig() method for each of the logging.txt file and passed the corresponding url and logger object in the thread (please check the code below).

Upon running the script, I can find only one logging0.txt file generated with all the urls log details captured in it.  Clearly, passing the logger object as arg in thread do not perform what I thought it would.

```<code>log_files_here = ['logging0.txt','logging1.txt','logging2.txt','logging3.txt','logging4.txt','logging5.txt','logging6.txt']
urls = ['url1', 'url2', 'url3', 'url4', 'url5', 'url6', 'url7']

for i in range(0, len(urls)):
    url = urls[i]
    logfilepath = log_files_here[i]
    logging.basicConfig(filename=logfilepath, format='%(asctime)s %(message)s',level=logging.INFO)
    logger=logging.getLogger(__name__)

    print(f'Current logging file here {logfilepath} and loggere here is {logger}')
    logobject = getLogger(i)
    # Initiating thread here
    node_thread = threading.Thread(target=url_sanity, args=(url,logger))
    node_thread.start()  # starting the thread
    node_thread.join()
</code>```

I further researched and created only one logger object and used RotatingFilehandler(), tested the below code and passed the logger object in the thread.

This generates 7 backup files with same INFO but not each of the url log details in 7 file.  Understand by passing the backUpCount arg takes backup only.

```<code>logger = logging.getLogger('my_logger')
logger.setLevel(logging.INFO)
handler = RotatingFileHandler('my_log.log', maxBytes=2000, backupCount=7)
logger.addHandler(handler)
</code>```

So, this also doesnt solve the requirement.  Now, I have one log file generated with all the url log details in it, while all I want is each log file to be generated capturing each url (thread) information.
Please note that I cant provide any traceback error as I am getting the log details of these urls in a single log file.

Could you please assist on how I can capture the log details of each url in a separate log file?  Thanks in advance.

答:
The problem here is that you're only configuring a single instance of the logger, as basicConfig() only configures the root logger, even if you're looping that configuration X times, you're only configuring the same instance.

When you are doing logger=logging.getLogger(__name__) you're getting an instance that inherits from root logger and this has only one fileHandler configured.

An approach to solve the multi-file logging problem is to create as many named loggers as files you want, assigning each one of them a fileHandler.

This is achieved by using the naming system of the logging core. You can use, for example, the name of your url to get the logger you want to use.

Please check this example built from your code:

```<code>import logging
import threading

log_files_here = ['logging0.txt','logging1.txt','logging2.txt','logging3.txt','logging4.txt','logging5.txt','logging6.txt']
urls = ['url1', 'url2', 'url3', 'url4', 'url5', 'url6', 'url7']

def configure_logging():
    """ Configuring all the logging instances with files-urls mapping"""
    for i in range(0, len(urls)):
        url = urls[i]
        logfilepath = log_files_here[i]
        # This will create and get a named urlX instance of the logger
        log = logging.getLogger(url)
        # NOTE: You can use a RotatingFileHandler here if fits better
        filehandler = logging.FileHandler(logfilepath, mode='a')
        log.addHandler(filehandler)
        # Feel free to parametrize this if you want different loglevel settings on your files.
        log.setLevel(logging.INFO)

def logger_worker(url):
    log = logging.getLogger(url)
    log.info(f"{url} logging! .")

def main():
    """ Testing current log settings"""
    configure_logging()

    for i in range(0, len(urls)):
        url = urls[i]
        node_thread = threading.Thread(target=logger_worker, args=(url,))
        node_thread.start()  # starting the thread
        node_thread.join()

if __name__ == "__main__":
    main()
</code>```

Body:
I am performing web sanity for a couple of URLs and currently, we are logging the entire log details of these urls in a single log file (using logging module), but it is required to capture log details of each url in a separate log file.

Currently, I have 7 urls in a list and created 7 logging.txt files in a list.  Then, in a loop, I used the basicConfig() method for each of the logging.txt file and passed the corresponding url and logger object in the thread (please check the code below).

Upon running the script, I can find only one logging0.txt file generated with all the urls log details captured in it.  Clearly, passing the logger object as arg in thread do not perform what I thought it would.

log_files_here = ['logging0.txt','logging1.txt','logging2.txt','logging3.txt','logging4.txt','logging5.txt','logging6.txt']
urls = ['url1', 'url2', 'url3', 'url4', 'url5', 'url6', 'url7']

for i in range(0, len(urls)):
    url = urls[i]
    logfilepath = log_files_here[i]
    logging.basicConfig(filename=logfilepath, format='%(asctime)s %(message)s',level=logging.INFO)
    logger=logging.getLogger(__name__)

    print(f'Current logging file here {logfilepath} and loggere here is {logger}')
    logobject = getLogger(i)
    # Initiating thread here
    node_thread = threading.Thread(target=url_sanity, args=(url,logger))
    node_thread.start()  # starting the thread
    node_thread.join()

I further researched and created only one logger object and used RotatingFilehandler(), tested the below code and passed the logger object in the thread.

This generates 7 backup files with same INFO but not each of the url log details in 7 file.  Understand by passing the backUpCount arg takes backup only.

logger = logging.getLogger('my_logger')
logger.setLevel(logging.INFO)
handler = RotatingFileHandler('my_log.log', maxBytes=2000, backupCount=7)
logger.addHandler(handler)

So, this also doesnt solve the requirement.  Now, I have one log file generated with all the url log details in it, while all I want is each log file to be generated capturing each url (thread) information.
Please note that I cant provide any traceback error as I am getting the log details of these urls in a single log file.

Could you please assist on how I can capture the log details of each url in a separate log file?  Thanks in advance.

Body:
The problem here is that you're only configuring a single instance of the logger, as basicConfig() only configures the root logger, even if you're looping that configuration X times, you're only configuring the same instance.

When you are doing logger=logging.getLogger(__name__) you're getting an instance that inherits from root logger and this has only one fileHandler configured.

An approach to solve the multi-file logging problem is to create as many named loggers as files you want, assigning each one of them a fileHandler.

This is achieved by using the naming system of the logging core. You can use, for example, the name of your url to get the logger you want to use.

Please check this example built from your code:

import logging
import threading

log_files_here = ['logging0.txt','logging1.txt','logging2.txt','logging3.txt','logging4.txt','logging5.txt','logging6.txt']
urls = ['url1', 'url2', 'url3', 'url4', 'url5', 'url6', 'url7']

def configure_logging():
    """ Configuring all the logging instances with files-urls mapping"""
    for i in range(0, len(urls)):
        url = urls[i]
        logfilepath = log_files_here[i]
        # This will create and get a named urlX instance of the logger
        log = logging.getLogger(url)
        # NOTE: You can use a RotatingFileHandler here if fits better
        filehandler = logging.FileHandler(logfilepath, mode='a')
        log.addHandler(filehandler)
        # Feel free to parametrize this if you want different loglevel settings on your files.
        log.setLevel(logging.INFO)

def logger_worker(url):
    log = logging.getLogger(url)
    log.info(f"{url} logging! .")

def main():
    """ Testing current log settings"""
    configure_logging()

    for i in range(0, len(urls)):
        url = urls[i]
        node_thread = threading.Thread(target=logger_worker, args=(url,))
        node_thread.start()  # starting the thread
        node_thread.join()

if __name__ == "__main__":
    main()


问:
NET Core web.api sudden memory peak after dozen of calls
I have a web.api in .net core 3.1 that continually receives byte array data. I have noticed that after a dozen of calls, the memory suddenly increases with +100Mb.

As you can see in the GIF, the memory increases steadily as the calls are being handled. And then at 155Mb, the memory increases to 296Mb

I have created a repo: https://github.com/puppetSpace/MemoryIssue
This contains a client project, that calls the API continually.
And the web.api project, that gets the byte array from the body and waits 500ms (simulate work).
I just want to know a couple of things:
- Is someone else also getting this result?
- Is this normal behavior? like it's reserving memory? Or it's just because of debbuging?

I tried to use a profiler, but I can't figure out what causes the sudden increase.

答:
I tried to use a profiler, but I can't figure out what causes the sudden increase

You can see there is yellow marked when the memory increased from 155 to 296 in the shared screenshot. It means that GC started of managed heap garbage collection. And when the first time running, it will initialize lots of object. You can take a snapshot before and after the GC for the detailed objects are created.

After that the memory is stabled, I am running the code sample about 6 minutes to monitoring the memory usage, you can refer the figure below:


问:
Best practice to create a thread that runs every hour in Android?
So I'm attempting to create background task that needs to be run every hour in an Android app. Its a rather heavy task that takes around 5 - 10 minutes to finish, and right now it runs on the UI thread which of course isn't good, because it hangs the whole application. I've attempted the following in my MainActivity onCreate:

```<code>new Thread(new Runnable() {

    private Handler HeavyTaskHandler = new Handler(Looper.getMainLooper());

    public void run(){
        final TextView updatedTxt = findViewById(R.id.txt);
        updatedTxt.post(new Runnable() {
            @Override
            public void run() {
                updatedTxt.setText("Performing cleanup..");
            }
        });

        HeavyTask(); // <-- This method runs for 5 - 10 minutes

        updatedTxt.post(new Runnable() {
            @Override
            public void run() {
                updatedTxt.setText("Done..");
            }
        });

        HeavyTaskHandler.postDelayed(this, HeavyTaskCycle);
    }
}).start();
</code>```

I have two issues with the above

It works fine the first time, and the task is performed in the background well without hanging the UI thread. However, after this first time and the next time(s) it is run, the UI thread hangs again when it is run. What am I missing?

Notice that before the HeavyTask() method is called i try to set a TextViews text to "Performing cleanup.." .. This never shows, only the "Done.." which happens after the HeavyTask() method is done. How can i ensure that the message also appears before?

答:
I ended up doing the following from MainActivity which doesn't hang the application

```<code>private void CreateCleanUpThread()
{
    CleanUpThread = new Thread(new Runnable() {

        public void run(){
            try {
                while(true) {
                    performingCleanup = true;
                    final TextView updatedTxt = findViewById(R.id.updated_txt);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updatedTxt.setText("Performing database history cleanup..");
                        }
                    });

                    HeavyTask(); // <-- This method runs for 5 - 10 minutes

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updatedTxt.setText("Done..");
                        }
                    });
                    performingCleanup = false;
                    Thread.sleep(CleanUpCycle); // 1 hour wait time
                }
            } catch(Exception ex) {
                System.out.println("Error in CreateCleanUpThread : " + ex.getMessage());
            }
        }
    });
}

// onCreate in MainActivity
...
CleanUpThread.start();

</code>```

Certainly not the best way, but it works and will do for now. Should be moved to a service instead i think.

Body:
So I'm attempting to create background task that needs to be run every hour in an Android app. Its a rather heavy task that takes around 5 - 10 minutes to finish, and right now it runs on the UI thread which of course isn't good, because it hangs the whole application. I've attempted the following in my MainActivity onCreate:

new Thread(new Runnable() {

    private Handler HeavyTaskHandler = new Handler(Looper.getMainLooper());

    public void run(){
        final TextView updatedTxt = findViewById(R.id.txt);
        updatedTxt.post(new Runnable() {
            @Override
            public void run() {
                updatedTxt.setText("Performing cleanup..");
            }
        });

        HeavyTask(); // <-- This method runs for 5 - 10 minutes

        updatedTxt.post(new Runnable() {
            @Override
            public void run() {
                updatedTxt.setText("Done..");
            }
        });

        HeavyTaskHandler.postDelayed(this, HeavyTaskCycle);
    }
}).start();

I have two issues with the above

It works fine the first time, and the task is performed in the background well without hanging the UI thread. However, after this first time and the next time(s) it is run, the UI thread hangs again when it is run. What am I missing?

Notice that before the HeavyTask() method is called i try to set a TextViews text to "Performing cleanup.." .. This never shows, only the "Done.." which happens after the HeavyTask() method is done. How can i ensure that the message also appears before?

Body:
I ended up doing the following from MainActivity which doesn't hang the application

private void CreateCleanUpThread()
{
    CleanUpThread = new Thread(new Runnable() {

        public void run(){
            try {
                while(true) {
                    performingCleanup = true;
                    final TextView updatedTxt = findViewById(R.id.updated_txt);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updatedTxt.setText("Performing database history cleanup..");
                        }
                    });

                    HeavyTask(); // <-- This method runs for 5 - 10 minutes

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updatedTxt.setText("Done..");
                        }
                    });
                    performingCleanup = false;
                    Thread.sleep(CleanUpCycle); // 1 hour wait time
                }
            } catch(Exception ex) {
                System.out.println("Error in CreateCleanUpThread : " + ex.getMessage());
            }
        }
    });
}

// onCreate in MainActivity
...
CleanUpThread.start();

Certainly not the best way, but it works and will do for now. Should be moved to a service instead i think.


问:
Copy file contents to the clipboard in Linux terminal
I'm generating an SSH key but I don't know how to copy the key from id_rsa.pub to the clipboard. I'm using BackBox Linux.

答:
```<code>xclip -sel c < input_file
</code>```

will copy the contents of input_file to clipboard. xclip requires installation. To install

```<code>sudo apt install xclip
</code>```

-sel stands for -selection. c is for clipboard. Interchangeable.

Capable of much more, I advise reading its man page.

There is also xsel. This answer on Unix SE gives a very thorough answer to this exact question.

Body:
xclip -sel c < input_file

will copy the contents of input_file to clipboard. xclip requires installation. To install

sudo apt install xclip

-sel stands for -selection. c is for clipboard. Interchangeable.

Capable of much more, I advise reading its man page.

There is also xsel. This answer on Unix SE gives a very thorough answer to this exact question.


问:
how to get data from an mp3 file and put it on html automatically?
Does anyone know how to get specific data from an mp3 file and also automatically putting it in HTML?

For example this data:

And let's say that I want all that data to be placed in a HTML table like this:

```<code><table class="pl5 lh1-4"><tr>
    <td>Artist/Band:</td>
    <td>PLACEHOLDER</td>
  </tr><tr>
    <td>Album:</td>
    <td>PLACEHOLDER</td>
  </tr><tr>
    <td>Gerne:</td>
    <td>PLACEHOLDER</td>
  </tr><tr>
    <td>Duration:</td>
    <td>PLACEHOLDER</td>
  </tr><tr>
    <td>Release date:</td>
    <td>PLACEHOLDER</td>
  </tr><tr>
    <td>Size:</td>
    <td>PLACEHOLDER</td>
  </tr></table>
<table class="pl5 lh1-4"><tr><td>
 1. PLACEHOLDER<br>
 2. PLACEHOLDER<br>
 3. PLACEHOLDER<br>
 4. PLACEHOLDER<br>
</td></tr></table>
</code>```

答:
https://github.com/aadsm/jsmediatags

I found this library, never tried it myself so you have to thinker with it

Body:
Does anyone know how to get specific data from an mp3 file and also automatically putting it in HTML?

For example this data:

And let's say that I want all that data to be placed in a HTML table like this:

    Artist/Band:
    PLACEHOLDER

    Album:
    PLACEHOLDER

    Gerne:
    PLACEHOLDER

    Duration:
    PLACEHOLDER

    Release date:
    PLACEHOLDER

    Size:
    PLACEHOLDER

 1. PLACEHOLDER

 2. PLACEHOLDER

 3. PLACEHOLDER

 4. PLACEHOLDER


问:
spacing nodes at networkx/plotly network and labeling
I created a network using networkx and plotly as following:

```<code>edges = df.stack().reset_index()
edges.columns = ['var_1','var_2','correlation']
edges = edges.loc[ (edges['correlation'] < -0.6) | (edges['correlation'] > 0.6) & (edges['var_1'] != edges['var_2']) ].copy()

#create undirected graph with weights corresponding to the correlation magnitude
G0 = nx.from_pandas_edgelist(edges, 'var_1', 'var_2', edge_attr=['correlation'])

mst = G0
# assign colours to edges depending on positive or negative correlation
# assign edge thickness depending on magnitude of correlation
edge_colours = []
edge_width = []
for key, value in nx.get_edge_attributes(mst, 'correlation').items():
    edge_colours.append(assign_colour(value))
    edge_width.append(assign_thickness(value))

node_size = []
degrees = [val for key, val in dict(G0.degree).items()]
max_deg = max(degrees)
min_deg = min(degrees)
for value in degrees:
    node_size.append(assign_node_size(value,min_deg,max_deg))

#draw the network:
nx.draw(mst, pos=nx.fruchterman_reingold_layout(mst),
        node_size=15, edge_color=edge_colours, node_colour="black",
        edge_width=0.2)
plt.show()

def get_coordinates(G=mst):
    """Returns the positions of nodes and edges in a format for Plotly to draw the network"""
    # get list of node positions
    pos = nx.fruchterman_reingold_layout(mst)

    Xnodes = [pos[n][0] for n in mst.nodes()]
    Ynodes = [pos[n][1] for n in mst.nodes()]

    Xedges_red = []
    Yedges_red = []
    Xedges_green = []
    Yedges_green = []

    def insert_edge(Xedges, Yedges):
        Xedges.extend([pos[e[0]][0], pos[e[1]][0], None])
        Yedges.extend([pos[e[0]][1], pos[e[1]][1], None])

    search_dict = nx.get_edge_attributes(mst, 'correlation')
    for e in mst.edges():
        correlation = search_dict[(e[0], e[1])]
        if correlation <= 0 :  # red_edges
          insert_edge(Xedges_red, Yedges_red)
        else:
          insert_edge(Xedges_green, Yedges_green)
        # x coordinates of the nodes defining the edge e

    return Xnodes, Ynodes, Xedges_red, Yedges_red, Xedges_green, Yedges_green

node_label = list(mst.nodes())
node_label = [fix_string(x) for x in node_label]

# get coordinates for nodes and edges
Xnodes, Ynodes, Xedges_red, Yedges_red, Xedges_green, Yedges_green = get_coordinates()

external_data = [list(x) for x in coding_names_df.values]
external_data = {fix_string(x[0]): x[1] for x in external_data}
external_data2 = [list(y) for y in coding_names_df.values]
external_data2 = {fix_string(y[0]): y[2] for y in external_data2}
external_data3 = [list(z) for z in coding_names_df.values]
external_data3 = {fix_string(z[0]): z[3] for z in external_data3}
external_data4 = [list(s) for s in coding_names_df.values]
external_data4 = {fix_string(s[0]): s[4] for s in external_data4}

# =============================================================================
description = [f"<b>{index}) {node}</b>"
                "<br><br>Realm: " +
                "<br>" + external_data.get(node, 'No external data found') +
                "<br><br>Type: " +
                "<br>" + external_data2.get(node, 'No external data found')
               for index, node in enumerate(node_label)]
# =============================================================================

# def nodes colours:
node_colour = [assign_node_colour(node, external_data3, coding_names_df) for node in node_label]
node_shape = [assign_node_shape(node, external_data4, coding_names_df) for node in node_label]
# edges
# negative:
tracer_red = go.Scatter(x=Xedges_red, y=Yedges_red,
                    mode='lines',
                    line= dict(color="#FA0000", width=1),
                    hoverinfo='none',
                    showlegend=False)
# positive:
tracer_green = go.Scatter(x=Xedges_green, y=Yedges_green,
                    mode='lines',
                    line= dict(color= "#29A401", width=1),
                    hoverinfo='none',
                    showlegend=False)

# nodes
tracer_marker = go.Scatter(x=Xnodes, y=Ynodes,
                           mode='markers+text',
                           textposition='top center',
                           marker=dict(size=node_size,
                                            line=dict(width=0.8, color='black'),
                                            color=node_colour,
                                                                    symbol=node_shape),
                                       hovertext=description,
                           hoverinfo='text',
                           textfont=dict(size=7),
                           showlegend=False)

axis_style = dict(title='',
                  titlefont=dict(size=20),
                  showgrid=False,
                  zeroline=False,
                  showline=False,
                  ticks='',
                  showticklabels=False)

layout = dict(title='',
              width=1300,
              height=900,
              autosize=False,
              showlegend=False,
              xaxis=axis_style,
              yaxis=axis_style,
              hovermode='closest',
             plot_bgcolor = '#fff')

fig = dict(data=[tracer_red, tracer_green, tracer_marker], layout=layout)
display(HTML("""<p>Node sizes are proportional to the size of annualised returns.<br>
                Node colours signify positive or negative returns since beginning of the timeframe.</p> """))
plot(fig)
</code>```

and I got this plot: network

I want to add labels, but it's getting too crowded (especially in the middle)
so I have two questions:

How can I spacing the middle? (but still to keep the fruchterman_reingold possition)

How can I add just a few specific labels?

any help will be graet! Tnx :)

答:
Something you could try is setting the k parameter in the layout algorithm, which as mentioned in the docs it sets:

k: (float (default=None)) – Optimal distance between nodes. If None the distance is set to 1/sqrt(n) where n is the number of nodes. Increase this value to move nodes farther apart.

So by playing a bit with this value, and increasing accordingly we can get a more spread out layout and avoid overlap between node labels.
Here's a simple example to illustrate what the behavior is:

```<code>result_set = {('plant','tree'), ('tree','oak'), ('flower', 'rose'), ('flower','daisy'), ('plant','flower'), ('tree','pine'), ('plant','roots'), ('animal','fish'),('animal','bird'), ('bird','robin'), ('bird','falcon'), ('animal', 'homo'),('homo','homo-sapiens'), ('animal','reptile'), ('reptile','snake'),('fungi','mushroom'), ('fungi','mold'), ('fungi','toadstool'),('reptile','crocodile'), ('mushroom','Portabello'), ('mushroom','Shiitake'),('pine','roig'),('pine','pinyer'), ('tree','eucaliptus'),('rose','Floribunda'),('rose','grandiflora')}
G=nx.from_edgelist(result_set)

pos=nx.fruchterman_reingold_layout(G)
plt.figure(figsize=(8,5))
nx.draw(G, pos=pos,
        with_labels=True,
        nodesize=1000,
        node_color='lightgreen')
</code>```

And if we increase the value of k to say 0.5, we get a nice spreading of the nodes in the layout:

```<code>pos_spaced=nx.fruchterman_reingold_layout(G, k=0.5, iterations=100)

plt.figure(figsize=(10,6))
nx.draw(G,
        pos=pos_spaced,
        with_labels=True,
        nodesize=1000,
        node_color='lightgreen')
</code>```

How can I add just a few specific labels?

For this you set the labels parameters in draw to a dictionary containing the labels you want displayed. In the case the node names are the same as the labels, just create a dictionary mapping node->node as follows:

```<code>show_labels = ['plant', 'tree', 'oak', 'eucaliptus']

pos_spaced=nx.fruchterman_reingold_layout(G, k=0.54, iterations=100)

plt.figure(figsize=(10,6))
nx.draw(G,
        pos=pos_spaced,
        with_labels=True,
        nodesize=1000,
        labels=dict(zip(show_labels,show_labels)),
        node_color='lightgreen')
</code>```

Body:
I created a network using networkx and plotly as following:

edges = df.stack().reset_index()
edges.columns = ['var_1','var_2','correlation']
edges = edges.loc[ (edges['correlation'] < -0.6) | (edges['correlation'] > 0.6) & (edges['var_1'] != edges['var_2']) ].copy()

#create undirected graph with weights corresponding to the correlation magnitude
G0 = nx.from_pandas_edgelist(edges, 'var_1', 'var_2', edge_attr=['correlation'])

mst = G0
# assign colours to edges depending on positive or negative correlation
# assign edge thickness depending on magnitude of correlation
edge_colours = []
edge_width = []
for key, value in nx.get_edge_attributes(mst, 'correlation').items():
    edge_colours.append(assign_colour(value))
    edge_width.append(assign_thickness(value))

node_size = []
degrees = [val for key, val in dict(G0.degree).items()]
max_deg = max(degrees)
min_deg = min(degrees)
for value in degrees:
    node_size.append(assign_node_size(value,min_deg,max_deg))

#draw the network:
nx.draw(mst, pos=nx.fruchterman_reingold_layout(mst),
        node_size=15, edge_color=edge_colours, node_colour="black",
        edge_width=0.2)
plt.show()

def get_coordinates(G=mst):
    """Returns the positions of nodes and edges in a format for Plotly to draw the network"""
    # get list of node positions
    pos = nx.fruchterman_reingold_layout(mst)

    Xnodes = [pos[n][0] for n in mst.nodes()]
    Ynodes = [pos[n][1] for n in mst.nodes()]

    Xedges_red = []
    Yedges_red = []
    Xedges_green = []
    Yedges_green = []

    def insert_edge(Xedges, Yedges):
        Xedges.extend([pos[e[0]][0], pos[e[1]][0], None])
        Yedges.extend([pos[e[0]][1], pos[e[1]][1], None])

    search_dict = nx.get_edge_attributes(mst, 'correlation')
    for e in mst.edges():
        correlation = search_dict[(e[0], e[1])]
        if correlation <= 0 :  # red_edges
          insert_edge(Xedges_red, Yedges_red)
        else:
          insert_edge(Xedges_green, Yedges_green)
        # x coordinates of the nodes defining the edge e

    return Xnodes, Ynodes, Xedges_red, Yedges_red, Xedges_green, Yedges_green

node_label = list(mst.nodes())
node_label = [fix_string(x) for x in node_label]

# get coordinates for nodes and edges
Xnodes, Ynodes, Xedges_red, Yedges_red, Xedges_green, Yedges_green = get_coordinates()

external_data = [list(x) for x in coding_names_df.values]
external_data = {fix_string(x[0]): x[1] for x in external_data}
external_data2 = [list(y) for y in coding_names_df.values]
external_data2 = {fix_string(y[0]): y[2] for y in external_data2}
external_data3 = [list(z) for z in coding_names_df.values]
external_data3 = {fix_string(z[0]): z[3] for z in external_data3}
external_data4 = [list(s) for s in coding_names_df.values]
external_data4 = {fix_string(s[0]): s[4] for s in external_data4}

# =============================================================================
description = [f"{index}) {node}"
                "

Realm: " +
                "
" + external_data.get(node, 'No external data found') +
                "

Type: " +
                "
" + external_data2.get(node, 'No external data found')
               for index, node in enumerate(node_label)]
# =============================================================================

# def nodes colours:
node_colour = [assign_node_colour(node, external_data3, coding_names_df) for node in node_label]
node_shape = [assign_node_shape(node, external_data4, coding_names_df) for node in node_label]
# edges
# negative:
tracer_red = go.Scatter(x=Xedges_red, y=Yedges_red,
                    mode='lines',
                    line= dict(color="#FA0000", width=1),
                    hoverinfo='none',
                    showlegend=False)
# positive:
tracer_green = go.Scatter(x=Xedges_green, y=Yedges_green,
                    mode='lines',
                    line= dict(color= "#29A401", width=1),
                    hoverinfo='none',
                    showlegend=False)

# nodes
tracer_marker = go.Scatter(x=Xnodes, y=Ynodes,
                           mode='markers+text',
                           textposition='top center',
                           marker=dict(size=node_size,
                                            line=dict(width=0.8, color='black'),
                                            color=node_colour,
                                                                    symbol=node_shape),
                                       hovertext=description,
                           hoverinfo='text',
                           textfont=dict(size=7),
                           showlegend=False)

axis_style = dict(title='',
                  titlefont=dict(size=20),
                  showgrid=False,
                  zeroline=False,
                  showline=False,
                  ticks='',
                  showticklabels=False)

layout = dict(title='',
              width=1300,
              height=900,
              autosize=False,
              showlegend=False,
              xaxis=axis_style,
              yaxis=axis_style,
              hovermode='closest',
             plot_bgcolor = '#fff')

fig = dict(data=[tracer_red, tracer_green, tracer_marker], layout=layout)
display(HTML("""
Node sizes are proportional to the size of annualised returns.

                Node colours signify positive or negative returns since beginning of the timeframe.
 """))
plot(fig)

and I got this plot: network

I want to add labels, but it's getting too crowded (especially in the middle)
so I have two questions:

How can I spacing the middle? (but still to keep the fruchterman_reingold possition)

How can I add just a few specific labels?

any help will be graet! Tnx :)

Body:
Something you could try is setting the k parameter in the layout algorithm, which as mentioned in the docs it sets:

k: (float (default=None)) – Optimal distance between nodes. If None the distance is set to 1/sqrt(n) where n is the number of nodes. Increase this value to move nodes farther apart.

So by playing a bit with this value, and increasing accordingly we can get a more spread out layout and avoid overlap between node labels.
Here's a simple example to illustrate what the behavior is:

result_set = {('plant','tree'), ('tree','oak'), ('flower', 'rose'), ('flower','daisy'), ('plant','flower'), ('tree','pine'), ('plant','roots'), ('animal','fish'),('animal','bird'), ('bird','robin'), ('bird','falcon'), ('animal', 'homo'),('homo','homo-sapiens'), ('animal','reptile'), ('reptile','snake'),('fungi','mushroom'), ('fungi','mold'), ('fungi','toadstool'),('reptile','crocodile'), ('mushroom','Portabello'), ('mushroom','Shiitake'),('pine','roig'),('pine','pinyer'), ('tree','eucaliptus'),('rose','Floribunda'),('rose','grandiflora')}
G=nx.from_edgelist(result_set)

pos=nx.fruchterman_reingold_layout(G)
plt.figure(figsize=(8,5))
nx.draw(G, pos=pos,
        with_labels=True,
        nodesize=1000,
        node_color='lightgreen')

And if we increase the value of k to say 0.5, we get a nice spreading of the nodes in the layout:

pos_spaced=nx.fruchterman_reingold_layout(G, k=0.5, iterations=100)

plt.figure(figsize=(10,6))
nx.draw(G,
        pos=pos_spaced,
        with_labels=True,
        nodesize=1000,
        node_color='lightgreen')

How can I add just a few specific labels?

For this you set the labels parameters in draw to a dictionary containing the labels you want displayed. In the case the node names are the same as the labels, just create a dictionary mapping node->node as follows:

show_labels = ['plant', 'tree', 'oak', 'eucaliptus']

pos_spaced=nx.fruchterman_reingold_layout(G, k=0.54, iterations=100)

plt.figure(figsize=(10,6))
nx.draw(G,
        pos=pos_spaced,
        with_labels=True,
        nodesize=1000,
        labels=dict(zip(show_labels,show_labels)),
        node_color='lightgreen')


问:
Retrieve LINK_ATTRIBUTE_FC1..5 based on LINK_ID
Assume I have a LINK_ID which I got using the LINK_FC5 layer with search/proximity resource described here.

Note that the search/proximity resource doesn't allow non-geometric layers such as LINK_ATTRIBUTE_FC5 to be specified.

Errorcode: 400, message: Provided layer does not contain geometries.

The documentation suggests using tile resource for getting the non-geometric layers, but that seems quite inefficient. Within one tile there are many LINK_IDs. Hard for me to believe there is no better way to do this. Hence the question:

What is a efficient way to retrieve all attributes from the LINK_ATTRIBUTE_FC5 layer using the LINK_ID?

答:
You need to club to APIs to get the desired attributes for link IDs. So a tile comprises of multiple layers, Each layer contains multiple link IDs. this requires to make association between these resources. You can also refer to example : https://tcs.ext.here.com/examples/v3/pde_get_any_link_info

First API is :
https://s.fleet.ls.hereapi.com/1/index.json?layer=ROAD_GEOM_FCn&attributes=LINK_ID&values=548294575,833539855,550088940,930893121&apiKey=xxx

The response will be like :
"Layers": [
        {
            "layer": "ROAD_GEOM_FC5",
            "level": 13,
            "tileXYs": [
                {
                    "x": 8580,
                    "y": 6376
                }
            ]
        },
        {
            "layer": "ROAD_GEOM_FC1",
            "level": 9,
            "tileXYs": [
                {
                    "x": 534,
                    "y": 397
                },
                {
                    "x": 536,
                    "y": 398
                }
            ]
        }

From here you will get level, tile x,y and layer,
2nd API will be :
https://s.fleet.ls.hereapi.com/1/tiles.json?apiKey=xx&tilexy=536,398&levels=13&layers=LINK_ATTRIBUTE_FC5


问:
SMTP error for php emailer
I am trying to set up a php script that would send an email to selected users, I looked on the internet and found out how but can't run the script cos I get the following error:

Warning: mail() [function.mail]:
  "sendmail_from" not set in php.ini or
  custom "From:" header missing in
  E:\Program
  Files\xampp\phpMyAdmin\emailer.php on
  line 10

Here is the code of the script I designed following examples:

```<code><?php
    $recipient = "<ismael.srcyber@gmail.com>";
    $subject = "Flight Status";
    $body = "Flight has just landed.";

    $host = "ssl://smtp.gmail.com";
    $port = "465";

    if(mail($recipient, $subject, $body))
    {
        echo("<p>Message successfully sent</p>");
    }
    else
    {
        echo("<p>Message Delivery failed </p>");
    }
?>
</code>```

Thanks in advance.

答:
As the error suggest you must add the default "from" field (who sends the mail) in php.ini:

```<code>SMTP = localhost

sendmail_from = me@localhost.com
</code>```

And then restart apache

Otherwise you can set it dinamically as the fourth parameter as stated in the php manual (look http://php.net/manual/en/function.mail.php)

Note:

When sending mail, the mail must
  contain a From header. This can be set
  with the additional_headers parameter,
  or a default can be set in php.ini.

Failing to do this will result in an
  error message similar to Warning:
  mail(): "sendmail_from" not set in
  php.ini or custom "From:" header
  missing. The From header sets also
  Return-Path under Windows.

Example:

```<code><?php
$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
</code>```

Title: SMTP error for php emailer

Body:
I am trying to set up a php script that would send an email to selected users, I looked on the internet and found out how but can't run the script cos I get the following error:

Warning: mail() [function.mail]:
  "sendmail_from" not set in php.ini or
  custom "From:" header missing in
  E:\Program
  Files\xampp\phpMyAdmin\emailer.php on
  line 10

Here is the code of the script I designed following examples:

<?php
    $recipient = "<ismael.srcyber@gmail.com>";
    $subject = "Flight Status";
    $body = "Flight has just landed.";

    $host = "ssl://smtp.gmail.com";
    $port = "465";

    if(mail($recipient, $subject, $body))
    {
        echo("
Message successfully sent
");
    }
    else
    {
        echo("
Message Delivery failed
");
    }
?>

Thanks in advance.

Body:
As the error suggest you must add the default "from" field (who sends the mail) in php.ini:

SMTP = localhost

sendmail_from = me@localhost.com

And then restart apache

Otherwise you can set it dinamically as the fourth parameter as stated in the php manual (look http://php.net/manual/en/function.mail.php)

Note:

When sending mail, the mail must
  contain a From header. This can be set
  with the additional_headers parameter,
  or a default can be set in php.ini.

Failing to do this will result in an
  error message similar to Warning:
  mail(): "sendmail_from" not set in
  php.ini or custom "From:" header
  missing. The From header sets also
  Return-Path under Windows.

Example:

<?php
$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);


问:
how do i connect my custom button board to pc via usb?

Goal/Challenge:

i have a challenge to create a custom controller without using special controllers e.g. raspberry pi or Arduino.

What i have done so far:

I have created a custom board that takes power from the red wire and outputs power via the coloured strip depending on what buttons the user has pressed. 1= on, 0 = off, 9 outputs, 1 power input

my problem:

i am trying to connect this board to my pc via usb.
I have seen that some chips can be used to do this but, i have no idea of what to use or how to connect them.

Help/Info i need:

what could i use to connect my button board to pc(windows 10) via usb?

Extra:

i don't know if i'm posting this in the right place or i'm using the right tags.
please suggest any changes i need to make

答:
If you just want to make a custom button board the easiest way is to buy some buttons e.g arcade buttons und a zero delay usb encoder.
Plugs into pc via usb and work like any controller.. you can set the desired functions for each button via windows itself.</p>


问:
How to input a 2-D array directly in C with negative values, spaces and newline
I want to directly input a 2-D Array in C, separated just by single spaces and newlines. At the same time I also want to verify whether the user is entering a valid single digit integer (either positive or negative).
I tried the following.

```<code>int A[3][3];
    int i,j;
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
            scanf("%d",&A[i][j]);
    }
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
            printf("%d ",A[i][j]);
        printf("\n");
    }
</code>```

But I want 2 things in this:-

Input that is first verified whether its a single digit integer or not.

Not works merely for positive integers and 0 but also for negative integers.

eg.
input such as the following should be accepted and stored in 2-d array

1 2 -3 4
-5 1 2 -6
1 1 2 3
```
<p>I'm sorry if I wasn't clear. An important component is that the input should be confirmed whether its integer or not i.e. the input should be either as char or string and if it is an integer  (which can be ascertained by functions such as isdigit() , then it should be converted to an integer value.
This following code chunk works for single positive values</p>
```char c = getchar();
  if (isdigit(c))
     int value = c - '0';
```

However, I don't know how to enable this functionality for negative integers in a complete 2D array input.

答:
If you want to verify that a number is a single digit, just check if its between -9 and 9.

As for negative numbers, im pretty sure the %d modifier for the scanf captures that.

Please comment down below if the answer is incorrect so i could fix it :)

Edit: i forgot to note that scanf returns the number of read elements. so comparing this against 1 (since you read one element at a time) will allow you to know if the input was partial or not.
something like this:

```<code>if (scanf(" %d", &A[i][j]) != 1){
   //here goes the code for when the input is partial
}
</code>```

should do the trick

Body:
I want to directly input a 2-D Array in C, separated just by single spaces and newlines. At the same time I also want to verify whether the user is entering a valid single digit integer (either positive or negative).
I tried the following.

int A[3][3];
    int i,j;
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
            scanf("%d",&A[i][j]);
    }
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
            printf("%d ",A[i][j]);
        printf("\n");
    }

But I want 2 things in this:-

Input that is first verified whether its a single digit integer or not.

Not works merely for positive integers and 0 but also for negative integers.

eg.
input such as the following should be accepted and stored in 2-d array

1 2 -3 4
-5 1 2 -6
1 1 2 3

I'm sorry if I wasn't clear. An important component is that the input should be confirmed whether its integer or not i.e. the input should be either as char or string and if it is an integer  (which can be ascertained by functions such as isdigit() , then it should be converted to an integer value.
This following code chunk works for single positive values

char c = getchar();
  if (isdigit(c))
     int value = c - '0';

However, I don't know how to enable this functionality for negative integers in a complete 2D array input.

Body:
If you want to verify that a number is a single digit, just check if its between -9 and 9.

As for negative numbers, im pretty sure the %d modifier for the scanf captures that.

Please comment down below if the answer is incorrect so i could fix it :)

Edit: i forgot to note that scanf returns the number of read elements. so comparing this against 1 (since you read one element at a time) will allow you to know if the input was partial or not.
something like this:

if (scanf(" %d", &A[i][j]) != 1){
   //here goes the code for when the input is partial
}

should do the trick


问:
Moving an accelerator Dataset to an other computer
We have been running all our accelerator jobs on our shared server. Now, however, we would like to take out a small development subset of our main dataset and work in isolation on our own laptops.

Is it possible to produce a dataset on one machine and move it to an other, hopefully without exporting it?

答:
Yes and no. As long as you use the same number of slices on both computers you can copy the jobdir as is. If the dataset has parents you will need to copy those jobs as as well. Keep the job names, and don't build jobs in that workdir on your laptop (so you can copy newer jobs from the server without ID collisions later).

You don't have to copy previous jobs in the chain as long as you don't try to follow the chain on the laptop.

This is probably the way you want to go, and just have accept having too many slices on your laptop.


问:
Issue with doubles rounding down to nearest whole
Unlike many of the other posts I am wanting to find out why my code is automatically rounding down to the nearest whole number??

See code here

```<code>    double sixes = 200/3;
    double threes = 100/3;

    System.out.println("Sixes: " + sixes + "\nThrees: " + threes);
</code>```

See the output here:

Sixes: 66.0

Threes: 33.0

These should both be 66.66666666666 and 33.3333333333 respectively but I am not sure why they are being rounded down?

答:
The algorithm depends on the most complex argument. You calculate integer numbers, therefore an algorithm is used that produces integer as output. Finally that integer gets implicitly converted to double to fit into your variable.

Try double sixes = 200.0/3.0;to verify that.

Body:
Unlike many of the other posts I am wanting to find out why my code is automatically rounding down to the nearest whole number??

See code here

    double sixes = 200/3;
    double threes = 100/3;

    System.out.println("Sixes: " + sixes + "\nThrees: " + threes);

See the output here:

Sixes: 66.0

Threes: 33.0

These should both be 66.66666666666 and 33.3333333333 respectively but I am not sure why they are being rounded down?


问:
Java applet: run native code from browser?
Is it still possible to start a 'native' application under windows via a java applet in a browser? IE "Click here to start notepad.exe" on a web page. The most recent reference I could find for this was dated 2002. Im wondering if this model / concept is no longer supported. </p>

答:
..Is it still possible to start a 'native' application under windows via a java applet in a browser?

Sure thing.  As mentioned in other replies, a signed (and trusted) applet can use Runtime.exec(String) to launch a native application.

As of Java 1.6, it becomes simpler with the implementation of Dekstop.getDesktop.open(File), which will open the selected File with whatever application the OS has registered as a consumer for that file type.

As of Sun's Plugin2 architecture (1.6.0_10+ in  a Sun/Oracle JRE) offers a more generic method for an (sand-boxed) applet embedded in a web page, using the JNLP API's BasicService.  Here is my demo. of the BasicService


问:
"set is iterable,but set is not sequence"，I have some questions
I am reading the book fluent python. It says all collections such as list, set are iterable. But set is not a sequence. Dictionary is also not a sequence, that is to say, the item in sequence can not be accessed by index, such as set[9], am I right? It's a bit like both linked lists and lists can be traversed, but only arrays can quickly get values through an index. I was wondering How is dictionary traversed?

Please forgive me for my poor English

答:
Different structures in python

Sets are Unordered collection of unique objects. They can be iterated but not indexed like how you do on lists or arrays.

Dictionary is similar to hash or maps in other languages. It is unordered and consists of key value pairs. The value can be accessed by unique key
in the dictionary. Unlike sets, it can be iterated as well as indexed
through one of its keys.

List are just like arrays or vectors in C++. They can be iterated and indexed by numbers from 0 to length-1.

So , coming to your question, a dictionary can be traversed using its keys, it's values or the key-value pair. Below are the 3 ways to traverse a dictionary :

```<code>for key in dict :
    print(key)

for value in dict.values() :
    print(value)

for key,value in dict.items() :
    print(key,value)
</code>```

Hope this helps !

Body:
Different structures in python

Sets are Unordered collection of unique objects. They can be iterated but not indexed like how you do on lists or arrays.

Dictionary is similar to hash or maps in other languages. It is unordered and consists of key value pairs. The value can be accessed by unique key
in the dictionary. Unlike sets, it can be iterated as well as indexed
through one of its keys.

List are just like arrays or vectors in C++. They can be iterated and indexed by numbers from 0 to length-1.

So , coming to your question, a dictionary can be traversed using its keys, it's values or the key-value pair. Below are the 3 ways to traverse a dictionary :

for key in dict :
    print(key)

for value in dict.values() :
    print(value)

for key,value in dict.items() :
    print(key,value)

Hope this helps !


问:
In Vs2013 with resharper, what are the yellow lines on the left margin
In Vs2013 with Resharper, what are the yellow lines on the left margin.

This ought to be an easy question to answer, but I wasn't able to guess the keywords to search.

答: The coloured marks in the border are how Visual Studio tracks changes (not related to ReSharper). The yellow marks indicate that the line has changes but not yet been saved, they will turn green once saved or orange if saved and then undone, according to this link</p>