问:
How to create a python module as a single callable function?
I'd like to write the module as a function and not a class.

Is there a way to make this work as intended?

greet.py

def main(x):
    print(f'Hello {x}!')
```

<p>Now how do I write the module so that when <code>greet</code> is executed, <code>main</code> runs.</p>

<strong><code>main.py</code></strong>

<pre class="lang-py prettyprint-override"><code>import greet

greet('Foo') # output: Hello Foo!
</code>```

答:
Don't do this. If you're not sure whether you need this, you don't. Making a module callable is a really weird thing to do. However, it is an interesting intellectual curiosity, so...

It is possible to do this, exploiting the fact that a module is itself an object, and that an object is callable if its class has a __call__ method.

However, one problem is that module is a builtin, and you cannot modify the attributes of a builtin.

The simplest solution, therefore, is to create a class that will take the place of the module in sys.modules, but also has a __call__ method.

In greet.py:

```<code>import sys

class CallableModule():

    def __init__(self, wrapped):
        self._wrapped = wrapped

    def __call__(self, *args, **kwargs):
        return self._wrapped.main(*args, **kwargs)

    def __getattr__(self, attr):
        return object.__getattribute__(self._wrapped, attr)

sys.modules[__name__] = CallableModule(sys.modules[__name__])

def main(x):
    print(f'Hello {x}!')
</code>```

From the shell:

```<code>>>> import greet
>>> greet('there')
Hello there!
</code>```

Body:
I'd like to write the module as a function and not a class.

Is there a way to make this work as intended?

greet.py

def main(x):
    print(f'Hello {x}!')

Now how do I write the module so that when greet is executed, main runs.

main.py

import greet

greet('Foo') # output: Hello Foo!

Body:
Don't do this. If you're not sure whether you need this, you don't. Making a module callable is a really weird thing to do. However, it is an interesting intellectual curiosity, so...

It is possible to do this, exploiting the fact that a module is itself an object, and that an object is callable if its class has a __call__ method.

However, one problem is that module is a builtin, and you cannot modify the attributes of a builtin.

The simplest solution, therefore, is to create a class that will take the place of the module in sys.modules, but also has a __call__ method.

In greet.py:

import sys

class CallableModule():

    def __init__(self, wrapped):
        self._wrapped = wrapped

    def __call__(self, *args, **kwargs):
        return self._wrapped.main(*args, **kwargs)

    def __getattr__(self, attr):
        return object.__getattribute__(self._wrapped, attr)

sys.modules[__name__] = CallableModule(sys.modules[__name__])

def main(x):
    print(f'Hello {x}!')

From the shell:

>>> import greet
>>> greet('there')
Hello there!


来源: stackexchange

问:
How to spread the inner array elements of an array?
I am trying to spread the inner array elements of an array but couldn't figure it out how it works.

Input:

```<code>[1,2,[3,4],[5,6]]
</code>```

Output:

```<code>[1,2,3,4,5,6]
</code>```

How do I convert the first array into 2nd one?

答:
The term is "flattening" - here's a simple one-level flattening function:

const arr = [1, 2, [3, 4], [5, 6]];
const flatten = a => a.reduce((acc, curr) => acc.concat(curr), []);
console.log(flatten(arr));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: auto; }</code>```

Deeply nested arrays require a different approach - here's a recursive function:

const arr = [1, 2, [3, 4, "a", ["b", "c"]], [5, 6]];
const flatten = a => a.reduce((acc, curr) => acc.concat(Array.isArray(curr) ? flatten(curr) : curr), []);
console.log(flatten(arr));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: auto; }</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to spread the inner array elements of an array but couldn't figure it out how it works.

Input:

[1,2,[3,4],[5,6]]

Output:

[1,2,3,4,5,6]

How do I convert the first array into 2nd one?

Body:
The term is "flattening" - here's a simple one-level flattening function:

const arr = [1, 2, [3, 4], [5, 6]];
const flatten = a => a.reduce((acc, curr) => acc.concat(curr), []);
console.log(flatten(arr));

.as-console-wrapper { max-height: 100% !important; top: auto; }

Deeply nested arrays require a different approach - here's a recursive function:

const arr = [1, 2, [3, 4, "a", ["b", "c"]], [5, 6]];
const flatten = a => a.reduce((acc, curr) => acc.concat(Array.isArray(curr) ? flatten(curr) : curr), []);
console.log(flatten(arr));

.as-console-wrapper { max-height: 100% !important; top: auto; }


问:
Cannot inject request paraemter into blade view file
I have the following URL:

https://example.com/?email=test@test.com

then I have the following blade template

<input value="{{Request::query('email') or old('email')}}">

But it's not displaying the email I passed in the get parameter into the input. Instead, it's displaying the value 1

Tried searching haven't found a solution that works.

答:
That's because you have {{Request::query('email') or old('email')}} which is conditional. It will always return true or false.

Try any of these:

{{Request::query('email') ||  old('email')}}

or

{{Request::query('email') ? Request::query('email') : old('email')}}


问:
Vue.js - search form with query parameters
I am using Vue.js 2.6 with the vue-router component. I have a search form as follows:

```<code><form class="search-form" @submit.prevent="search">
    <div class="form-group">
        <input type="text" class="form-control" v-model="term" placeholder="Search">
    </div>
</form>
</code>```

And here is my script:

```<code><script>
  export default {
    data() {
      return {
        term: this.$route.query.term,
        items: []
      }
    },
    created() {
      if (this.term != null) {
        this.search()
      }
    },
    watch: {
      '$route.query.term'() {
        this.term = this.$route.query.term
        this.search()
      }
    },
    methods: {
      search: function () {
        window.axios.get('/images/search', {
          params: {
            term: this.term
          }
        })
        .then(response => {
          this.$router.push({query: { 'term' : this.term}})
          this.items = response.data.collection.items
        })
        .catch(error => {
          return error
        })
      }
    }
  }
</script>
</code>```

What I am trying to achieve with this code is the following:

User submits form, the search() function is called. The URL is updated with the query param, e.g. /search?term=<term>. This is working but the search() function is being called twice.

User carries out several searches, then presses the back button. The search field in the form is updated and the search is carried out. This is working but the search() function is being called twice.

User manually enters query param in the URL bar. The search field in the form is populated and the search is carried out. This is working.

Where the search() function is being called twice, this is due to the watch() function, which is designed to watch changes to the URL bar. I am not sure how to combine this function correctly with the search() function.

答:
In watch, you can compare new value with old value, and only perform search when new value is different with old value

```<code>watch: {
  '$route.query.term'(newVal, oldVal) {
    if (newVal != oldVal) {
      this.term = this.$route.query.term
      this.search()
    }
  }
},
</code>```

To make it call only 1 for 1st case, you might want to separate button click handler with real search call

```<code><script>
  export default {
    data() {
      return {
        term: this.$route.query.term,
        items: []
      }
    },
    created() {
      if (this.term != null) {
        this.performSearch()
      }
    },
    watch: {
      '$route.query.term': {
        handler: function(newVal, oldVal) {
          if (newVal != oldVal) {
            this.term = this.$route.query.term
            this.performSearch()
          }
        },
        immediate: true
      }
    },
    methods: {
      search: function () {
        // this is call when user click search Button
        this.$router.push({query: { 'term' : this.term}})

      },
      performSearch() {
        // perform actual searcch
        window.axios.get('/images/search', {
          params: {
            term: this.term
          }
        })
        .then(response => {
          this.items = response.data.collection.items
        })
        .catch(error => {
          return error
        })
      }
    }
  }
</script>
</code>```

Body:
I am using Vue.js 2.6 with the vue-router component. I have a search form as follows:

<form class="search-form" @submit.prevent="search">

        <input type="text" class="form-control" v-model="term" placeholder="Search">

</form>

And here is my script:

What I am trying to achieve with this code is the following:

User submits form, the search() function is called. The URL is updated with the query param, e.g. /search?term=<term>. This is working but the search() function is being called twice.

User carries out several searches, then presses the back button. The search field in the form is updated and the search is carried out. This is working but the search() function is being called twice.

User manually enters query param in the URL bar. The search field in the form is populated and the search is carried out. This is working.

Where the search() function is being called twice, this is due to the watch() function, which is designed to watch changes to the URL bar. I am not sure how to combine this function correctly with the search() function.

Body:
In watch, you can compare new value with old value, and only perform search when new value is different with old value

watch: {
  '$route.query.term'(newVal, oldVal) {
    if (newVal != oldVal) {
      this.term = this.$route.query.term
      this.search()
    }
  }
},

To make it call only 1 for 1st case, you might want to separate button click handler with real search call

<script>
  export default {
    data() {
      return {
        term: this.$route.query.term,
        items: []
      }
    },
    created() {
      if (this.term != null) {
        this.performSearch()
      }
    },
    watch: {
      '$route.query.term': {
        handler: function(newVal, oldVal) {
          if (newVal != oldVal) {
            this.term = this.$route.query.term
            this.performSearch()
          }
        },
        immediate: true
      }
    },
    methods: {
      search: function () {
        // this is call when user click search Button
        this.$router.push({query: { 'term' : this.term}})

      },
      performSearch() {
        // perform actual searcch
        window.axios.get('/images/search', {
          params: {
            term: this.term
          }
        })
        .then(response => {
          this.items = response.data.collection.items
        })
        .catch(error => {
          return error
        })
      }
    }
  }
</script>


问:
How to develop the code to save more than word in the selected file?
The goal of my program is to give the user the opportunity to add something in a new or old file.

Because of my code the user can add only one word to the file.
I wrote down where the problem is.
I do not know how to make the saving of the words in the file unlimited.
I tried with a for loop... Unfortunately it did not make any sense.

```<code>public class AddAndSave {

private static Scanner scanner = new Scanner(System.in);

    private static Formatter formatter = null;
    private static Scanner reader;

    public static void main(String args[]) {

        System.out.println("In which file do you want to add?");
        String fileName = scanner.next();
        File myFile = new File("C://Meine Dateien// " + fileName + ".txt");

        if (myFile.exists() == true) {
            try {
                reader = new Scanner(myFile);
                String fileContent = "";

                while (reader.hasNext() == true) {
                    fileContent = fileContent + reader.next();
                }
                formatter = new Formatter(myFile);
                formatter.format("%s", fileContent + "  ");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            try {
                formatter = new Formatter(myFile);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        System.out.println("What do you want to add?");
        String newInput = scanner.next();//hier is the problem

        formatter.format("%s", newInput);
        System.out.println();
        System.out.println("Finish! Thank you for using our programm!");
        formatter.close();
    }
}
</code>```

答:
Your problem is the fact that you are utilizing the wrong Scanner method for retrieving String line data from both file and User.

Use the Scanner#nextLine() method instead of the Scanner#next() method and use it in conjunction with the Scanner#HasNextLine() method in your while loop condition (instead of the Scanner#hasNext() method):

```<code>String newInput = scanner.nextLine();
</code>```

Use the Scanner#nextLine() method where you prompt for a file name and prompt for what to add to file!. Also use it within your while loop for reading the file (in conjuction with the Scanner#hasNextLine() method). Carefully read about the differences between all these methods!

Scanner#hasNext() and Scanner#next() methods are more geared towords Token (word) based situations (one word at a time) whereas the Scanner#hasNextLine() and Scanner#nextLine() methods are used for entire string lines. This is what I believe you really want.

Other Notes:

You may want to remove the white-space after your last forward slashes (//):

```<code>"C://Meine Dateien// " + fileName + ".txt";
</code>```

unless of course you want t0 add a white-space at the beginning of every every name for every file created by your application.

When using boolean variables in conditions such as those in if statements, you can just use:

```<code>if (myFile.exists()) {   // IF true
</code>```

instead of:

```<code>if (myFile.exists() == true) {  // IF true
</code>```

and:

```<code>if (!myFile.exists()) {   // IF false
</code>```

instead of:

```<code>if (myFile.exists() == false) {  // IF false
</code>```

Either way works just fine but you will later find that the shorter way is less prone to errors due to typo's and I think it's easier to read but that's just my opinion.

Don't forget to close your file reader. Use Try With Resources to take care of this sort of thing for you with regards to both your reader and writer.

Body:
The goal of my program is to give the user the opportunity to add something in a new or old file.

Because of my code the user can add only one word to the file.
I wrote down where the problem is.
I do not know how to make the saving of the words in the file unlimited.
I tried with a for loop... Unfortunately it did not make any sense.

public class AddAndSave {

private static Scanner scanner = new Scanner(System.in);

    private static Formatter formatter = null;
    private static Scanner reader;

    public static void main(String args[]) {

        System.out.println("In which file do you want to add?");
        String fileName = scanner.next();
        File myFile = new File("C://Meine Dateien// " + fileName + ".txt");

        if (myFile.exists() == true) {
            try {
                reader = new Scanner(myFile);
                String fileContent = "";

                while (reader.hasNext() == true) {
                    fileContent = fileContent + reader.next();
                }
                formatter = new Formatter(myFile);
                formatter.format("%s", fileContent + "  ");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            try {
                formatter = new Formatter(myFile);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        System.out.println("What do you want to add?");
        String newInput = scanner.next();//hier is the problem

        formatter.format("%s", newInput);
        System.out.println();
        System.out.println("Finish! Thank you for using our programm!");
        formatter.close();
    }
}

Body:
Your problem is the fact that you are utilizing the wrong Scanner method for retrieving String line data from both file and User.

Use the Scanner#nextLine() method instead of the Scanner#next() method and use it in conjunction with the Scanner#HasNextLine() method in your while loop condition (instead of the Scanner#hasNext() method):

String newInput = scanner.nextLine();

Use the Scanner#nextLine() method where you prompt for a file name and prompt for what to add to file!. Also use it within your while loop for reading the file (in conjuction with the Scanner#hasNextLine() method). Carefully read about the differences between all these methods!

Scanner#hasNext() and Scanner#next() methods are more geared towords Token (word) based situations (one word at a time) whereas the Scanner#hasNextLine() and Scanner#nextLine() methods are used for entire string lines. This is what I believe you really want.

Other Notes:

You may want to remove the white-space after your last forward slashes (//):

"C://Meine Dateien// " + fileName + ".txt";

unless of course you want t0 add a white-space at the beginning of every every name for every file created by your application.

When using boolean variables in conditions such as those in if statements, you can just use:

if (myFile.exists()) {   // IF true

instead of:

if (myFile.exists() == true) {  // IF true

and:

if (!myFile.exists()) {   // IF false

instead of:

if (myFile.exists() == false) {  // IF false

Either way works just fine but you will later find that the shorter way is less prone to errors due to typo's and I think it's easier to read but that's just my opinion.

Don't forget to close your file reader. Use Try With Resources to take care of this sort of thing for you with regards to both your reader and writer.


问:
Custom binning in seaborn pairplot
I am new to seaborn, and I'm currently playing around with the pairplot functionalities... With the following

```<code>seaborn.pairplot(data,
                 hue="Class",
                 diag_king="hist",
                 diag_kws={'alpha'=0.5}
                 )
</code>```

I'm able to achieve most of what I want: a grid of scatter plots from my pandas dataframe data, with separated distributions according to the Class column, and semi-transparent histograms along the diagonal.

I've figured out that by passing bin=[...] to diag_kws I can have all diagonal plots adopt that binning, but I'd like each column of my dataframe to take its binning from a dedicated dictionary (with keys the column names).

Is it possible to achieve this with diag_kws? Or do I need to access each of the diagonal plots individually after calling pairplot and rebin them manually? What's the most efficient way?

答:
PairGrid offers map_diag which one could use to map a custom function which changes the parameters in each call. This could look like this. Mind that one needs to take care of the order (via vars argument) to make sure the correct parameters are applied.

```<code>import matplotlib.pyplot as plt
import seaborn as sns

iris = sns.load_dataset("iris", cache=True)
col_list = ['petal_length', 'petal_width', 'sepal_length', 'sepal_width']
cols = iter(col_list)

bins = {'sepal_length' : 10, 'sepal_width' : 5,
        'petal_length' : 35, 'petal_width' : 12}

def myhist(x, **kwargs):
    b = bins[next(cols)]
    plt.text(0.5,0.9, f"bins = {b}", ha="center",
             transform=plt.gca().transAxes)
    plt.hist(x, bins=b, **kwargs)

g = sns.PairGrid(iris, vars=col_list)
g = g.map_diag(myhist)
g = g.map_offdiag(plt.scatter)

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

Title: Custom binning in seaborn pairplot

Body:
I am new to seaborn, and I'm currently playing around with the pairplot functionalities... With the following

seaborn.pairplot(data,
                 hue="Class",
                 diag_king="hist",
                 diag_kws={'alpha'=0.5}
                 )

I'm able to achieve most of what I want: a grid of scatter plots from my pandas dataframe data, with separated distributions according to the Class column, and semi-transparent histograms along the diagonal.

I've figured out that by passing bin=[...] to diag_kws I can have all diagonal plots adopt that binning, but I'd like each column of my dataframe to take its binning from a dedicated dictionary (with keys the column names).

Is it possible to achieve this with diag_kws? Or do I need to access each of the diagonal plots individually after calling pairplot and rebin them manually? What's the most efficient way?

Body:
PairGrid offers map_diag which one could use to map a custom function which changes the parameters in each call. This could look like this. Mind that one needs to take care of the order (via vars argument) to make sure the correct parameters are applied.

import matplotlib.pyplot as plt
import seaborn as sns

iris = sns.load_dataset("iris", cache=True)
col_list = ['petal_length', 'petal_width', 'sepal_length', 'sepal_width']
cols = iter(col_list)

bins = {'sepal_length' : 10, 'sepal_width' : 5,
        'petal_length' : 35, 'petal_width' : 12}

def myhist(x, **kwargs):
    b = bins[next(cols)]
    plt.text(0.5,0.9, f"bins = {b}", ha="center",
             transform=plt.gca().transAxes)
    plt.hist(x, bins=b, **kwargs)

g = sns.PairGrid(iris, vars=col_list)
g = g.map_diag(myhist)
g = g.map_offdiag(plt.scatter)

plt.show()


问:
Tried to use setTimeout inside a generator to control the process of producing random numbers but failed
I was trying to implement a seeded pseudo-random generator. It will produce random numbers until the time is up. The code is below

```<code>function* pseudoRandom(seed) {
  let random = seed;
  let flag = true;
  setTimeout(() => {flag = !flag}, 100); // stop generating after 100ms
  while (flag) {
    random = random * 16807 % 2147483647;
    yield random;
  }
}

let generator = pseudoRandom(1);

console.log([...generator]);
</code>```

But I still get an error saying FATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memory. I guess the loop didn't stop. So what has gone wrong?

答:
All the synchronous code in a script will be executed before callbacks get a chance to run. If you have code that blocks (such as endlessly yielding in a while loop without stopping), the callback will never have a chance to run.

For similar reasons, the following code will never exit the while loop:

```<code>let flag = false;
setTimeout(() => flag = true);
while (!flag) {
  // do something
}
</code>```

Check to see if 100ms have passed inside the loop instead:

function* pseudoRandom(seed) {
  let random = seed;
  const start = Date.now();
  while (Date.now() - start < 100) { // stop generating after 100ms
    random = random * 16807 % 2147483647;
    yield random;
  }
}

let generator = pseudoRandom(1);

console.log([...generator].length);```
</div>
</div>
</p>

<p>Do note that the number of elements generated in the 100 ms may have a very large range, depending on what else the processor/browser is doing in that time.</p>

<p>Thanks Kaiido, To avoid blocking the visible UI, you could consider moving the blocking part of the script to a worker:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// https://stackoverflow.com/questions/10343913/how-to-create-a-web-worker-from-a-string
// I put in a Stack Snippet for live demonstration
// in a real project, put this in a separate file
const workerFn = () => {
  function* pseudoRandom(seed) {
    let random = seed;
    const start = Date.now();
    while (Date.now() - start < 100) { // stop generating after 100ms
      random = random * 16807 % 2147483647;
      yield random;
    }
  }
  self.onmessage = ({ data }) => {
    let generator = pseudoRandom(1);
    const arr = [...generator];
    self.postMessage(arr.length);
  };
};
const workerFnStr = `(${workerFn})();`;
const blob = new Blob([workerFnStr], { type: 'text/javascript' });
const worker = new Worker(window.URL.createObjectURL(blob));

worker.onmessage = ({ data: length }) => console.log(length);
worker.postMessage(1234);</code>```

Body:
I was trying to implement a seeded pseudo-random generator. It will produce random numbers until the time is up. The code is below

function* pseudoRandom(seed) {
  let random = seed;
  let flag = true;
  setTimeout(() => {flag = !flag}, 100); // stop generating after 100ms
  while (flag) {
    random = random * 16807 % 2147483647;
    yield random;
  }
}

let generator = pseudoRandom(1);

console.log([...generator]);

But I still get an error saying FATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memory. I guess the loop didn't stop. So what has gone wrong?

Body:
All the synchronous code in a script will be executed before callbacks get a chance to run. If you have code that blocks (such as endlessly yielding in a while loop without stopping), the callback will never have a chance to run.

For similar reasons, the following code will never exit the while loop:

let flag = false;
setTimeout(() => flag = true);
while (!flag) {
  // do something
}

Check to see if 100ms have passed inside the loop instead:

function* pseudoRandom(seed) {
  let random = seed;
  const start = Date.now();
  while (Date.now() - start < 100) { // stop generating after 100ms
    random = random * 16807 % 2147483647;
    yield random;
  }
}

let generator = pseudoRandom(1);

console.log([...generator].length);

Do note that the number of elements generated in the 100 ms may have a very large range, depending on what else the processor/browser is doing in that time.

Thanks Kaiido, To avoid blocking the visible UI, you could consider moving the blocking part of the script to a worker:

// https://stackoverflow.com/questions/10343913/how-to-create-a-web-worker-from-a-string
// I put in a Stack Snippet for live demonstration
// in a real project, put this in a separate file
const workerFn = () => {
  function* pseudoRandom(seed) {
    let random = seed;
    const start = Date.now();
    while (Date.now() - start < 100) { // stop generating after 100ms
      random = random * 16807 % 2147483647;
      yield random;
    }
  }
  self.onmessage = ({ data }) => {
    let generator = pseudoRandom(1);
    const arr = [...generator];
    self.postMessage(arr.length);
  };
};
const workerFnStr = `(${workerFn})();`;
const blob = new Blob([workerFnStr], { type: 'text/javascript' });
const worker = new Worker(window.URL.createObjectURL(blob));

worker.onmessage = ({ data: length }) => console.log(length);
worker.postMessage(1234);


问:
Reformatting a phone number in Laravel using Javascript
I have a function that formats telephone numbers as a user types their phone number in. I also have a blade.php template that has the phone number field as part of the form. How do I get the blade template to invoke my telephone() function from my main.js file?

Contact.blade.php

```<code>               <div class="field">
                    <label for="name" class="label">Phone Number</label>
                    <div class="control">
                        <input type="text" id="phonenumber" class="input {{$errors->has('phonenumber') ? 'is-danger' : 'is-success'}}"
                               name="phonenumber" placeholder="Enter phone number" value="{{old('phonenumber')}}">
                    </div>
                </div>
</code>```

main.js

```<code>function telephone(){
    document.getElementById('phonenumber').addEventListener('input', function (e) {
        var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
        e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
    });
}
</code>```

app.blade.php

```<code><!DOCTYPE html>
<html lang="en">
<head>

 <script type="text/javascript" src="{{URL::asset('js/main.js')}}"></script>
    <link href="{{url('/css/style.css')}}" type="text/css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

@include('inc.contact')
</body>
</code>```

答:
A server side language (php) can not invoke an action in a client browser; there is a physical boundary that separates the two.

What you are looking for is a an event in the client browser that can trigger your function.

main.js

```<code>function telephone(e){
    var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
    e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
}
document.getElementById("phonenumber").input = telephone
</code>```

You will also want to make sure your javascript executes after the content of the DOM is available.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <link href="{{url('/css/style.css')}}" type="text/css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    @include('inc.contact')
    <script type="text/javascript" src="{{URL::asset('js/main.js')}}"></script>
</body>
</code>```

Body:
I have a function that formats telephone numbers as a user types their phone number in. I also have a blade.php template that has the phone number field as part of the form. How do I get the blade template to invoke my telephone() function from my main.js file?

Contact.blade.php

                    Phone Number

                        <input type="text" id="phonenumber" class="input {{$errors->has('phonenumber') ? 'is-danger' : 'is-success'}}"
                               name="phonenumber" placeholder="Enter phone number" value="{{old('phonenumber')}}">

main.js

function telephone(){
    document.getElementById('phonenumber').addEventListener('input', function (e) {
        var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
        e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
    });
}

app.blade.php

<!DOCTYPE html>

    <link href="{{url('/css/style.css')}}" type="text/css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">

@include('inc.contact')

Body:
A server side language (php) can not invoke an action in a client browser; there is a physical boundary that separates the two.

What you are looking for is a an event in the client browser that can trigger your function.

main.js

function telephone(e){
    var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
    e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
}
document.getElementById("phonenumber").input = telephone

You will also want to make sure your javascript executes after the content of the DOM is available.

<!DOCTYPE html>
<html lang="en">
<head>
    <link href="{{url('/css/style.css')}}" type="text/css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    @include('inc.contact')
    <script type="text/javascript" src="{{URL::asset('js/main.js')}}"></script>
</body>


问:
Solution to add className in specific Array element
I created one calendar and I don't find the solution to add one className when the date is equal "today", please see the link demo:

https://compassionate-beaver-fe6c05.netlify.com/

the code is:

https://github.com/fzabra/react-calendar/blob/master/src/Components/Calendar.jsx

The follow condition return the date today:

```<code> if (dateDay === today.getDate() && currentYear === today.getFullYear() && currentMonth === today.getMonth()) {
   console.log(dateDay)
}
</code>```

Observe that the console show the date of today. The square today is a  it element have one id="dateDay", I think something like document.getElementById doesn't work, anybody has any ideas?

Thank you

答:
Using the .box .green class from your CSS file, you can push the
 inside the if condition or else don't use the className, like so:

```<code>if (dateDay === today.getDate() && currentYear === today.getFullYear() && currentMonth === today.getMonth()) {
  children.push(<Table.Cell key={j} id={dateDay} className="box green">{dateDay}</Table.Cell>)
  } else{
  children.push(<Table.Cell key={j} id={dateDay} className="box">{dateDay}</Table.Cell>)
</code>```

This way the current date will have a green background.

Result

Full code

Body:
I created one calendar and I don't find the solution to add one className when the date is equal "today", please see the link demo:

https://compassionate-beaver-fe6c05.netlify.com/

the code is:

https://github.com/fzabra/react-calendar/blob/master/src/Components/Calendar.jsx

The follow condition return the date today:

 if (dateDay === today.getDate() && currentYear === today.getFullYear() && currentMonth === today.getMonth()) {
   console.log(dateDay)
}

Observe that the console show the date of today. The square today is a  it element have one id="dateDay", I think something like document.getElementById doesn't work, anybody has any ideas?

Thank you

Body:
Using the .box .green class from your CSS file, you can push the <Table.Cell> inside the if condition or else don't use the className, like so:

if (dateDay === today.getDate() && currentYear === today.getFullYear() && currentMonth === today.getMonth()) {
  children.push(<Table.Cell key={j} id={dateDay} className="box green">{dateDay}</Table.Cell>)
  } else{
  children.push(<Table.Cell key={j} id={dateDay} className="box">{dateDay}</Table.Cell>)

This way the current date will have a green background.

Result

Full code


问:
Temperature Converter is giving me NaN
I need to make a temperature converter using forms and it has to have the ok button display the information and a clear button to clear all information.

This is what I have tried to do but it gives me NaN

function temperatureConverter(valNum) {

  valNum = parseFloat(valNum);

  document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Temperature Converter</h2>

Ok now my issue is that I need everything cleared even the Celsius data but I can't find a way for it to work
<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>

<p>

  <label>Fahrenheit</label>

  <input id="inputFahrenheit" type="text" placeholder="Fahrenheit">

  <input id= "button1" type= "button" value= "OK"  onclick="temperatureConverter(this.value)">

  <input id= "reset1" type= "reset" value= "Clear" onclick="temperatureConverter">

</p>

<p>Celcius: <span id="outputCelcius"></span></p></code>```

答:
can't see you using any form.

your function,

```<code>function temperatureConverter(valNum) {
  valNum = parseFloat(valNum);

  document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;

}
</code>```

then,

```<code><form id="tempConverter">
  Convert: <input type="text" id="unit" name="converter" />
  <input
   type="button"
   value="Submit"
   onclick="temperatureConverter(document.getElementById('unit').value);"
  />
 </form>

<p>Celcius: <span id="outputCelcius"></span></p>
</code>```

apparently, if you console the value, you were obviously sending "OK" as param to the function(not the value of input field) which is NAN.

Title: Temperature Converter is giving me NaN

Body:
I need to make a temperature converter using forms and it has to have the ok button display the information and a clear button to clear all information.

This is what I have tried to do but it gives me NaN

function temperatureConverter(valNum) {

  valNum = parseFloat(valNum);

  document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;

}

Temperature Converter

Ok now my issue is that I need everything cleared even the Celsius data but I can't find a way for it to work

Type a value in the Fahrenheit field to convert te value to Celsius:

  Fahrenheit

  <input id="inputFahrenheit" type="text" placeholder="Fahrenheit">

  <input id= "button1" type= "button" value= "OK"  onclick="temperatureConverter(this.value)">

  <input id= "reset1" type= "reset" value= "Clear" onclick="temperatureConverter">

Celcius:

Body:
can't see you using any form.

your function,

function temperatureConverter(valNum) {
  valNum = parseFloat(valNum);

  document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;

}

then,

<form id="tempConverter">
  Convert: <input type="text" id="unit" name="converter" />
  <input
   type="button"
   value="Submit"
   onclick="temperatureConverter(document.getElementById('unit').value);"
  />
 </form>

<p>Celcius: <span id="outputCelcius"></span></p>

apparently, if you console the value, you were obviously sending "OK" as param to the function(not the value of input field) which is NAN.


问:
Char array returns four times more data than expected
Before I continue, here's the code:

#include <iostream>
using namespace std;

int main() {
    char array[] = {'a','b','c'};
    cout << array << endl;

    return 0;
}
```

<p>My system:  </p>

<blockquote>
  <ul>
  <li>VisualStudio 2019, default C++ settings  </li>
  <li>Using Debug build instead of release  </li>
  </ul>
</blockquote>

<p>When I run this code sample, I get something like this in my console output:</p>

```abcXXXXXXXXX
```

Those X's represent seemingly random characters. I know they're from existing values in memory at that address, but I don't understand why I'm getting 12 bytes back instead of the three from my array.

Now, I know that if I were doing this with ints which are four bytes long, maybe this would make sense but sizeof(array) returns three (ie. three bytes long, I know the sizeof(array) / sizeof(array[0] trick.) And when I do try it with ints, I'm even more confused because I get some four-byte hex number instead (maybe a memory address?)

This may be some trivial question, I'm sorry, but I'm just trying to figure out why it behaves like this. No vectors please, I'm trying to stay as non-STL as possible here.

答:
cout takes this char array and addresses it as a null-terminated string.

Since the terminating character in this array is not the null character (i.e., char(0)), it attempts to print until encountering the null character.

At this point, it attempts to read memory outside of the array which you have allocated, and technically, anything could happen.

For example, there can be different data in that memory every time the function is called, or the memory access operation may even be illegal, depending on the address where array was allocated at the time the function was called.

So the behavior of your program is generally considered undefined (or non-deterministic).

Body:
Before I continue, here's the code:

#include <iostream>
using namespace std;

int main() {
    char array[] = {'a','b','c'};
    cout << array << endl;

    return 0;
}

My system:

VisualStudio 2019, default C++ settings

Using Debug build instead of release

When I run this code sample, I get something like this in my console output:

abcXXXXXXXXX

Those X's represent seemingly random characters. I know they're from existing values in memory at that address, but I don't understand why I'm getting 12 bytes back instead of the three from my array.

Now, I know that if I were doing this with ints which are four bytes long, maybe this would make sense but sizeof(array) returns three (ie. three bytes long, I know the sizeof(array) / sizeof(array[0] trick.) And when I do try it with ints, I'm even more confused because I get some four-byte hex number instead (maybe a memory address?)

This may be some trivial question, I'm sorry, but I'm just trying to figure out why it behaves like this. No vectors please, I'm trying to stay as non-STL as possible here.


问:
Rounding up to nearest 30 minutes in Python
I have the following code below.

I would like to roundup TIME to the nearest 30 minutes in the hour. For example: 12:00PM or 12:30PM and so on.

```<code>EASTERN_NOW = timezone.localtime(timezone.now() + timedelta(minutes=30))

TIME = datetime.time(EASTERN_NOW.time().hour, EASTERN_NOW.time().minute).strftime(
    VALID_TIME_FORMATS[2])
</code>```

答:
To round down:

extract the minute from the time that you want to round

using floor division, find the whole number intervals there are in the current hour (from the floor division of the current minute and the time interval, i.e. the intervals that you want to round down to).

multiply the time interval by that whole number, which gives you the rounded down minutes

use .replace() to change the minutes to those rounded down minutes (and seconds and milliseconds to zero).

Or, in words, using the number of whole intervals (x) there are in the current minutes, replace the minutes by that number of intervals (x * interval):

```<code>#!/usr/bin/env python3
def floor_dt(dt, interval):
    replace = (dt.minute // interval)*interval
    return dt.replace(minute = replace, second=0, microsecond=0)

print(datetime.now())
# datetime.datetime(2019, 5, 30, 22, 25, 31, 115901)
print(floor_dt(datetime.now(),30))
# datetime.datetime(2019, 5, 30, 22, 0)

print(datetime.now())
# datetime.datetime(2019, 5, 30, 22, 26, 29, 469555)
print(floor_dt(datetime.now(),10))
# datetime.datetime(2019, 5, 30, 22, 20)
</code>```

Body:
I have the following code below.

I would like to roundup TIME to the nearest 30 minutes in the hour. For example: 12:00PM or 12:30PM and so on.

EASTERN_NOW = timezone.localtime(timezone.now() + timedelta(minutes=30))

TIME = datetime.time(EASTERN_NOW.time().hour, EASTERN_NOW.time().minute).strftime(
    VALID_TIME_FORMATS[2])

Body:
To round down:

extract the minute from the time that you want to round

using floor division, find the whole number intervals there are in the current hour (from the floor division of the current minute and the time interval, i.e. the intervals that you want to round down to).

multiply the time interval by that whole number, which gives you the rounded down minutes

use .replace() to change the minutes to those rounded down minutes (and seconds and milliseconds to zero).

Or, in words, using the number of whole intervals (x) there are in the current minutes, replace the minutes by that number of intervals (x * interval):

#!/usr/bin/env python3
def floor_dt(dt, interval):
    replace = (dt.minute // interval)*interval
    return dt.replace(minute = replace, second=0, microsecond=0)

print(datetime.now())
# datetime.datetime(2019, 5, 30, 22, 25, 31, 115901)
print(floor_dt(datetime.now(),30))
# datetime.datetime(2019, 5, 30, 22, 0)

print(datetime.now())
# datetime.datetime(2019, 5, 30, 22, 26, 29, 469555)
print(floor_dt(datetime.now(),10))
# datetime.datetime(2019, 5, 30, 22, 20)


问:
How to deal with large number of edges from few vertex in graph db
I'm trying to model a graph db based on large RDBMS data. Reason behind graph db is to answer a lot of relationship based questions, enable traversal between different nodes and performance. While modeling this, I'm noticing that few nodes have large set of outgoing edges.

For example, think about "category" as a vertex, "product" as another vertex. There are other vertices like "product" exist. However, a lot of edges originate from "category" out to other edges.Outgoing number of edges are in few 100,000.

Is this an alert?
are there better any design principles to proactively design this in a different way?

答:
Let's assume that your current data model looks something like this:

```<code>(:Category {name: 'Toy'})<-[:IS_A]-(:Product {id: 123})
</code>```

and that some nodes with the Category label have an enormous number of related Products.

To reduce the number of relationships and simplify your queries a bit, you can consider eliminating the Category nodes and instead adding an additional label to each Product node. For example:

```<code>(:Product:Toy {id: 123})
</code>```

With this new data model, you could directly find all Toy products without traversing any relationships (e.g., MATCH (t:Toy) RETURN t).

Body:
Let's assume that your current data model looks something like this:

(:Category {name: 'Toy'})<-[:IS_A]-(:Product {id: 123})

and that some nodes with the Category label have an enormous number of related Products.

To reduce the number of relationships and simplify your queries a bit, you can consider eliminating the Category nodes and instead adding an additional label to each Product node. For example:

(:Product:Toy {id: 123})

With this new data model, you could directly find all Toy products without traversing any relationships (e.g., MATCH (t:Toy) RETURN t).


问:
CABasicAnimation on CATextLayer fontSize not working
I'm trying to make a pulsing animation on a CATextLayer when the user enters more characters in a UITextView than the maximum allowed.

The code runs but the animation does not happen.

```<code>public partial class MyViewController : UIViewController, IUITextViewDelegate
{
   const int MAX_COMMENTS_CHARS = 500;
   CATextLayer charsLeftTextLayer;

   public override void ViewDidLoad()
   {
      base.ViewDidLoad();

      charsLeftTextLayer = new CATextLayer();
      var uiFont = UIFont.SystemFontOfSize(12);
      charsLeftTextLayer.ContentsScale = UIScreen.MainScreen.Scale; //stops text appearing blurry
      charsLeftTextLayer.SetFont(uiFont.Name);
      charsLeftTextLayer.FontSize = 12;
      charsLeftTextLayer.String = $"{MAX_COMMENTS_CHARS} chars left";
      charsLeftTextLayer.ForegroundColor = UIColor.Black.CGColor;
      charsLeftTextLayer.BackgroundColor = UIColor.Clear.CGColor;
      charsLeftTextLayer.Frame = new CGRect(582, 153, 99, 21);

      View.Layer.AddSublayer(charsLeftTextLayer);
   }

   private void PulseCharsLeft()
    {
        var animation = CABasicAnimation.FromKeyPath("fontSize");

        animation.SetFrom(NSNumber.FromNInt(12));
        animation.SetTo(NSNumber.FromNInt(16));
        animation.Duration = 1.0;
        animation.BeginTime = 0.01;
        animation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear);
        animation.AutoReverses = true;

        charsLeftTextLayer.AddAnimation(animation, null);
    }

    #region UITextView delegates

    [Export("textView:shouldChangeTextInRange:replacementText:")]
    public bool ShouldChangeText(UITextView textView, NSRange range, string text)
    {
        if (textView.Text.Length + text.Length > MAX_COMMENTS_CHARS)
        {
            PulseCharsLeft();
            return false;
        }

        return true;
    }

    #endregion
}
</code>```

I'll accept answers in C#, Swift or Objective-C

答:
Remove the animation.BeginTime = 0.01; in method PulseCharsLeft() and then it will work.

It should look like:

```<code>private void PulseCharsLeft()
{
    var animation = CABasicAnimation.FromKeyPath("fontSize");

    animation.SetFrom(NSNumber.FromNInt(12));
    animation.SetTo(NSNumber.FromNInt(16));
    animation.Duration = 1.0;
    //animation.BeginTime = 10;
    animation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear);
    animation.AutoReverses = true;

    charsLeftTextLayer.AddAnimation(animation, "basic");

}
</code>```

BeginTime specifies a relative start time from its parent animation (by default multiple animations in a group all fire at once).

From the document:

Specifies the begin time of the receiver in relation to its parent
  object, if applicable.

You can look at the answer here to learn more about BeginTime.

BTW, in the question, your charsLeftTextLayer.Frame = new CGRect(582, 153, 99, 21);, is the x(582) too big for you to test?

I changed it into a small value and add a textView to test it.

```<code>    charsLeftTextLayer.Frame = new CGRect(82, 153, 99, 21);
</code>```

Also I changed the MAX_COMMENTS_CHARS to 10 and it is easier to test.

Body:
I'm trying to make a pulsing animation on a CATextLayer when the user enters more characters in a UITextView than the maximum allowed.

The code runs but the animation does not happen.

public partial class MyViewController : UIViewController, IUITextViewDelegate
{
   const int MAX_COMMENTS_CHARS = 500;
   CATextLayer charsLeftTextLayer;

   public override void ViewDidLoad()
   {
      base.ViewDidLoad();

      charsLeftTextLayer = new CATextLayer();
      var uiFont = UIFont.SystemFontOfSize(12);
      charsLeftTextLayer.ContentsScale = UIScreen.MainScreen.Scale; //stops text appearing blurry
      charsLeftTextLayer.SetFont(uiFont.Name);
      charsLeftTextLayer.FontSize = 12;
      charsLeftTextLayer.String = $"{MAX_COMMENTS_CHARS} chars left";
      charsLeftTextLayer.ForegroundColor = UIColor.Black.CGColor;
      charsLeftTextLayer.BackgroundColor = UIColor.Clear.CGColor;
      charsLeftTextLayer.Frame = new CGRect(582, 153, 99, 21);

      View.Layer.AddSublayer(charsLeftTextLayer);
   }

   private void PulseCharsLeft()
    {
        var animation = CABasicAnimation.FromKeyPath("fontSize");

        animation.SetFrom(NSNumber.FromNInt(12));
        animation.SetTo(NSNumber.FromNInt(16));
        animation.Duration = 1.0;
        animation.BeginTime = 0.01;
        animation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear);
        animation.AutoReverses = true;

        charsLeftTextLayer.AddAnimation(animation, null);
    }

    #region UITextView delegates

    [Export("textView:shouldChangeTextInRange:replacementText:")]
    public bool ShouldChangeText(UITextView textView, NSRange range, string text)
    {
        if (textView.Text.Length + text.Length > MAX_COMMENTS_CHARS)
        {
            PulseCharsLeft();
            return false;
        }

        return true;
    }

    #endregion
}

I'll accept answers in C#, Swift or Objective-C

Body:
Remove the animation.BeginTime = 0.01; in method PulseCharsLeft() and then it will work.

It should look like:

private void PulseCharsLeft()
{
    var animation = CABasicAnimation.FromKeyPath("fontSize");

    animation.SetFrom(NSNumber.FromNInt(12));
    animation.SetTo(NSNumber.FromNInt(16));
    animation.Duration = 1.0;
    //animation.BeginTime = 10;
    animation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear);
    animation.AutoReverses = true;

    charsLeftTextLayer.AddAnimation(animation, "basic");

}

BeginTime specifies a relative start time from its parent animation (by default multiple animations in a group all fire at once).

From the document:

Specifies the begin time of the receiver in relation to its parent
  object, if applicable.

You can look at the answer here to learn more about BeginTime.

BTW, in the question, your charsLeftTextLayer.Frame = new CGRect(582, 153, 99, 21);, is the x(582) too big for you to test?

I changed it into a small value and add a textView to test it.

    charsLeftTextLayer.Frame = new CGRect(82, 153, 99, 21);

Also I changed the MAX_COMMENTS_CHARS to 10 and it is easier to test.


问:
FrameRenderer avoids the Frame.GestureRecognizers Command on Android
I have created my own button with text and an image. To do so, I used a frame where I encapsulate everything. In Android it should have the button pressed. For that, I used a FrameRenderer, where I have the Touch event in the case of Android and it works great.

The problem is that I also want to use a Frame.GestureRecognizers to send a command when it is pressed, but this apparently cancels the invocation of the event since the command is not executed. It should be noted that I did exactly the same for UWP, and this problem does not happen. I guess I'm eating something on Android. I will share the code with you to see if you can help me. Thank you.

Xaml:

```<code>            <local:MyFrameButton
                x:Name="ButtonFrame"
                Grid.Column="0"
                Grid.Row="6"
                Grid.ColumnSpan="2"
                Grid.RowSpan="4"
                CornerRadius="5"
                BackgroundColor="{StaticResource ButtonColor}"
                HorizontalOptions="CenterAndExpand"
                VerticalOptions="CenterAndExpand"
                HeightRequest="172"
                WidthRequest="172"
                Padding="0" >
                <Grid Padding="8">
                    <Label
                          Text="{Binding IconCustomer}"
                          FontFamily="{DynamicResource MaterialFontFamilyID}"
                          FontSize="{OnPlatform Android='45', iOS='45', UWP='55'}"
                          TextColor="White"
                          HorizontalOptions="CenterAndExpand"
                          VerticalOptions="CenterAndExpand" >
                    </Label>
                    <Label
                          Grid.Row="1"
                          Text="Clientes"
                          FontSize="17"
                          TextColor="White"
                          HorizontalOptions="Center"
                          VerticalOptions="Center" />
                </Grid>
                <Frame.GestureRecognizers>
                    <TapGestureRecognizer
                            Command="{Binding CustomerListCommand}"
                            />
                </Frame.GestureRecognizers>
            </local:MyFrameButton>
</code>```

ViewModel:

```<code>  public ICommand CustomerListCommand => new RelayCommand(GoCustomerList);

    private async void GoCustomerList()
    {
        isRunning = true;
        MainViewModel.Instance.CustomersV = new CustomersViewModel(CustomerList);
        await MainViewModel.Instance.CustomersV.LoadConditionInitialsAsync();
        await navigationService.Navigate("CustomersView");
        isRunning = false;
    }
</code>```

FrameRenderer:

```<code>
 class MyFrameButtonRenderer : FrameRenderer
    {

        public MyFrameButtonRenderer(Context context) : base(context)
        {

        }

        protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement != null)
            {
                var drawable = new GradientDrawable();
                ViewGroup.SetBackground(drawable);
                UpdateBackgroundColor(drawable);
                UpdateCornerRadius(drawable);
                UpdateOutlineColor(drawable);
                UpdateShadow();

                this.Touch += (v, me) =>
                {
                    switch (me.Event.Action & MotionEventActions.Mask)
                    {
                        case MotionEventActions.Down:
                            Element.Scale = 1.05;
                            break;
                        case MotionEventActions.Up:
                            Element.Scale = 1;
                            break;
                        case MotionEventActions.PointerDown:
                            break;
                        case MotionEventActions.PointerUp:
                            break;
                        case MotionEventActions.Move:
                            break;
                    }
                };
            }
        }
}
</code>```

答:
The solution was to change in the FrameRender the Touch event by public override bool OnTouchEvent (MotionEvent e) as I show it below:

```<code>public override bool OnTouchEvent(MotionEvent e)
        {
            switch (e.Action & MotionEventActions.Mask)
            {
                case MotionEventActions.Down:
                    Element.Scale = 1.05;
                    break;
                case MotionEventActions.Up:
                    Element.Scale = 1;
                    break;
                case MotionEventActions.PointerDown:
                    break;
                case MotionEventActions.PointerUp:
                    break;
                case MotionEventActions.Move:
                    break;
            }
            return base.OnTouchEvent(e);
        }
</code>```

The idea was given to me by Mr. FaizalSaidali in the Xamarin forum:

https://forums.xamarin.com/discussion/comment/376599#Comment_376599

Body:
I have created my own button with text and an image. To do so, I used a frame where I encapsulate everything. In Android it should have the button pressed. For that, I used a FrameRenderer, where I have the Touch event in the case of Android and it works great.

The problem is that I also want to use a Frame.GestureRecognizers to send a command when it is pressed, but this apparently cancels the invocation of the event since the command is not executed. It should be noted that I did exactly the same for UWP, and this problem does not happen. I guess I'm eating something on Android. I will share the code with you to see if you can help me. Thank you.

Xaml:

            <local:MyFrameButton
                x:Name="ButtonFrame"
                Grid.Column="0"
                Grid.Row="6"
                Grid.ColumnSpan="2"
                Grid.RowSpan="4"
                CornerRadius="5"
                BackgroundColor="{StaticResource ButtonColor}"
                HorizontalOptions="CenterAndExpand"
                VerticalOptions="CenterAndExpand"
                HeightRequest="172"
                WidthRequest="172"
                Padding="0" >
                <Grid Padding="8">

                </Grid>
                <Frame.GestureRecognizers>
                    <TapGestureRecognizer
                            Command="{Binding CustomerListCommand}"
                            />
                </Frame.GestureRecognizers>
            </local:MyFrameButton>

ViewModel:

  public ICommand CustomerListCommand => new RelayCommand(GoCustomerList);

    private async void GoCustomerList()
    {
        isRunning = true;
        MainViewModel.Instance.CustomersV = new CustomersViewModel(CustomerList);
        await MainViewModel.Instance.CustomersV.LoadConditionInitialsAsync();
        await navigationService.Navigate("CustomersView");
        isRunning = false;
    }

FrameRenderer:

 class MyFrameButtonRenderer : FrameRenderer
    {

        public MyFrameButtonRenderer(Context context) : base(context)
        {

        }

        protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement != null)
            {
                var drawable = new GradientDrawable();
                ViewGroup.SetBackground(drawable);
                UpdateBackgroundColor(drawable);
                UpdateCornerRadius(drawable);
                UpdateOutlineColor(drawable);
                UpdateShadow();

                this.Touch += (v, me) =>
                {
                    switch (me.Event.Action & MotionEventActions.Mask)
                    {
                        case MotionEventActions.Down:
                            Element.Scale = 1.05;
                            break;
                        case MotionEventActions.Up:
                            Element.Scale = 1;
                            break;
                        case MotionEventActions.PointerDown:
                            break;
                        case MotionEventActions.PointerUp:
                            break;
                        case MotionEventActions.Move:
                            break;
                    }
                };
            }
        }
}

Body:
The solution was to change in the FrameRender the Touch event by public override bool OnTouchEvent (MotionEvent e) as I show it below:

public override bool OnTouchEvent(MotionEvent e)
        {
            switch (e.Action & MotionEventActions.Mask)
            {
                case MotionEventActions.Down:
                    Element.Scale = 1.05;
                    break;
                case MotionEventActions.Up:
                    Element.Scale = 1;
                    break;
                case MotionEventActions.PointerDown:
                    break;
                case MotionEventActions.PointerUp:
                    break;
                case MotionEventActions.Move:
                    break;
            }
            return base.OnTouchEvent(e);
        }

The idea was given to me by Mr. FaizalSaidali in the Xamarin forum:

https://forums.xamarin.com/discussion/comment/376599#Comment_376599


问:
how to change font awesome icons on click?
I'm use Font awesome icons in my vBulletin style and i want to change the (minus) icon to (plus) when click ! Is there a way to do it ?</p>

```<code>    <a rel="nofollow" style="float:left" href="#" onclick="return
 toggle_collapse('forumbit_$forumid')">
 <span style="color:#24356C;" >
<i class="fa fa-minus-square-o fa-2x"></i>
</span>
</a>
</code>```

答:
Assign an id to your icon, e.g.

```<code><i class="fa fa-minus-square-o fa-2x" id="i-1"></i>
</code>```

The id can be dynamic value like 'i-$forumid' depend on how you generate your html.

In your toggle_collapse('forumbit_$forumid') function,
Add

```<code>var e = document.getElementById('i-1');
if (e.classList.contains('fa-plus-square-o')) {
  e.classList.toggle('fa-plus-square-o');
} else {
  e.classList.add('fa-plus-square-o');
}
</code>```

or

```<code>function toggle_collapse(forumID) {
  ...

  var iconID = 'i-' + formumID.replace('forumbit_','')
  var e = document.getElementById(iconID);
  if (e.classList.contains('fa-plus-square-o')) {
    e.classList.toggle('fa-plus-square-o');
  } else {
    e.classList.add('fa-plus-square-o');
  }

  ...
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Assign an id to your icon, e.g.

<i class="fa fa-minus-square-o fa-2x" id="i-1"></i>

The id can be dynamic value like 'i-$forumid' depend on how you generate your html.

In your toggle_collapse('forumbit_$forumid') function,
Add

var e = document.getElementById('i-1');
if (e.classList.contains('fa-plus-square-o')) {
  e.classList.toggle('fa-plus-square-o');
} else {
  e.classList.add('fa-plus-square-o');
}

or

function toggle_collapse(forumID) {
  ...

  var iconID = 'i-' + formumID.replace('forumbit_','')
  var e = document.getElementById(iconID);
  if (e.classList.contains('fa-plus-square-o')) {
    e.classList.toggle('fa-plus-square-o');
  } else {
    e.classList.add('fa-plus-square-o');
  }

  ...
}


问:
Flutter Bloc for navigation flow
I am getting started with the BLoC pattern but I have a question:

1) Should you use the BloC pattern to determine if the routes should change?
Example: authentication object changes to unauthenticated so the listeners should handle the route changes.

2) Should the BLoC pattern only be used for UI state and handle the route changes on UI changes?
Example: User clicks on login and navigates to the home screen.

I ask this question because I'm facing a problem where I don't have a central navigation management solution.

This code is in my BLoC now:

```<code>loggedIn.listen((AuthResponse user) {
      currentUserSubject.add(user);
      Navigator.pushReplacement(
        _context,
        PageRouteBuilder(
          pageBuilder: (context, animation1, animation2) {
            return HomePage();
          },
          transitionsBuilder: (context, animation, _, child) {
            return new SlideTransition(
              child: child,
              position: new Tween<Offset>(
                begin: const Offset(0.0, 1.0),
                end: Offset.zero,
              ).animate(animation),
            );
          },
          transitionDuration: Duration(milliseconds: 400),
        ),
      );
    }, onError: (error) {
      Scaffold.of(_context).showSnackBar(new SnackBar(
        content: new Text(error.message),
      ));
    });
</code>```

答:
What I'm currently doing is:

Register a NavigatorBloc that receive a NavigatorState in the constructor and receive actions to navigate to different pages in your app Ex: GoToHomePageAction, GoToRegisterPageAction, NavigatorActionPop.

In your App widget you register the NavigatorBloc and provide the navigator key attached to the MaterialApp widget.

```<code>@override
  Widget build(BuildContext context) {
    return BlocProvider<NavigatorBloc>(
      bloc: NavigatorBloc(navigatorKey: widget.navigatorKey),
      child: MaterialApp(
        navigatorKey: widget.navigatorKey,
        title: 'Medicine Tracker',
        theme: ThemeData(
            primarySwatch: Colors.red,
            scaffoldBackgroundColor: Colors.white
        ),
        home: HomePage(),
      ),
    );
  }
</code>```

Then in side your NavigatorBloc you just check the the action and navigate to the desired page:

```<code>class NavigatorBloc extends Bloc<NavigatorAction, dynamic>{
  final GlobalKey<NavigatorState> navigatorKey;
  NavigatorBloc({this.navigatorKey});

  @override
  dynamic get initialState => 0;

  @override
  Stream<dynamic> mapEventToState(NavigatorAction event) async* {
    if(event is NavigatorActionPop){
      yield navigatorKey.currentState.pop();
    }
  }
}
</code>```

Hope it help.

Title: Flutter Bloc for navigation flow

Body:
I am getting started with the BLoC pattern but I have a question:

1) Should you use the BloC pattern to determine if the routes should change?
Example: authentication object changes to unauthenticated so the listeners should handle the route changes.

2) Should the BLoC pattern only be used for UI state and handle the route changes on UI changes?
Example: User clicks on login and navigates to the home screen.

I ask this question because I'm facing a problem where I don't have a central navigation management solution.

This code is in my BLoC now:

loggedIn.listen((AuthResponse user) {
      currentUserSubject.add(user);
      Navigator.pushReplacement(
        _context,
        PageRouteBuilder(
          pageBuilder: (context, animation1, animation2) {
            return HomePage();
          },
          transitionsBuilder: (context, animation, _, child) {
            return new SlideTransition(
              child: child,
              position: new Tween<Offset>(
                begin: const Offset(0.0, 1.0),
                end: Offset.zero,
              ).animate(animation),
            );
          },
          transitionDuration: Duration(milliseconds: 400),
        ),
      );
    }, onError: (error) {
      Scaffold.of(_context).showSnackBar(new SnackBar(
        content: new Text(error.message),
      ));
    });

Body:
What I'm currently doing is:

Register a NavigatorBloc that receive a NavigatorState in the constructor and receive actions to navigate to different pages in your app Ex: GoToHomePageAction, GoToRegisterPageAction, NavigatorActionPop.

In your App widget you register the NavigatorBloc and provide the navigator key attached to the MaterialApp widget.

@override
  Widget build(BuildContext context) {
    return BlocProvider<NavigatorBloc>(
      bloc: NavigatorBloc(navigatorKey: widget.navigatorKey),
      child: MaterialApp(
        navigatorKey: widget.navigatorKey,
        title: 'Medicine Tracker',
        theme: ThemeData(
            primarySwatch: Colors.red,
            scaffoldBackgroundColor: Colors.white
        ),
        home: HomePage(),
      ),
    );
  }

Then in side your NavigatorBloc you just check the the action and navigate to the desired page:

class NavigatorBloc extends Bloc<NavigatorAction, dynamic>{
  final GlobalKey<NavigatorState> navigatorKey;
  NavigatorBloc({this.navigatorKey});

  @override
  dynamic get initialState => 0;

  @override
  Stream<dynamic> mapEventToState(NavigatorAction event) async* {
    if(event is NavigatorActionPop){
      yield navigatorKey.currentState.pop();
    }
  }
}

Hope it help.


问:
Fragment setCustomAnimations() not working well?
I have some problem with using fragmentTransaction.setCustomAnimations(R.animator.slide_in_down, R.animator.slide_out_down), when I hope two fragment slide down smoothly, the in-fragment appears immediately after the out-fragment finish the animator of slide_out_down , and when I change the animator hoping two fragment slide up smoothly, the in-fragment disappears immediately before the out-fragment start animator.

look like this picture

why ? How to solve this ?

There are more details.

I have a listview with three items on screen left, and three fragments on right,one fragment for one item.

Sample like

in MyActivity, I  initialize all my fragment in onCreate()

```<code>private void createFragment(int initPosition) {
     mFragment[0] = new Fragment();
     mFragment[1] = new Fragment();
     mFragment[2] = new Fragment();

     mFragmentManager = getFragmentManager();
     mFragmentTransaction = mFragmentManager.beginTransaction();
     mFragmentTransaction.add(R.id.content_layout, mFragment[initPosition]);
     mFragmentTransaction.commit();
}
</code>```

and I set a onItemSelectedListener to listview, when listview change it's selection, called replaceFragment(int fromPos, int toPos).

```<code>private void replaceFragment(int fromPos, int toPos) {
    if(fromPos != toPos) {
        mFragmentTransactoin = mFragmentManager.beginTransaction();

        //add animator
        if (fromPos < toPos) {
            mFragmentTransaction.setCustomAnimations(R.animator.slide_in_up, R.animator.slide_out_up);
        } else {
            mFragmentTransaction.setCustomAnimations(R.animator.slide_in_down, R.animator.slide_out_down);
        }

        if (!mFragments[toPos].isAdded()) {
            mFragmentTransaction.add(R.id.content_layout, mFragments[toPos]);
        }
        mFragmentTransaction.show(mFragments[toPos]);
        mFragmentTransaction.hide(mFragments[toPos]);
        mFragmentTransaction.commit();
    }
}
</code>```

Why not use replace(), because replace() cause out-fragment destroyed, in-fragment will initialize every time. It's bad.show() and hide() could avoid that.

animator code :

```<code>slide_in_up.xml

<objectAnimator
    android:valueFrom="1280"
    android:valueTo="0"
    android:propertyName="translationY"
    android:duration="800"/>

slide_out_up.xml

<objectAnimator
    android:valueFrom="0"
    android:valueTo="-1280"
    android:propertyName="translationY"
    android:duration="800"/>

slide_in_down.xml

<objectAnimator
    android:valueFrom="-1280"
    android:valueTo="0"
    android:propertyName="translationY"
    android:duration="800"/>

slide_out_down.xml

<objectAnimator
    android:valueFrom="0"
    android:valueTo="1280"
    android:propertyName="translationY"
    android:duration="800"/>
</code>```

Any reply is appreciated.

答:
```<code>mFragmentTransaction.hide(mFragments[toPos]);
//need change to
mFragmentTransaction.hide(mFragments[fromPos]);
</code>```

Body:
I have some problem with using fragmentTransaction.setCustomAnimations(R.animator.slide_in_down, R.animator.slide_out_down), when I hope two fragment slide down smoothly, the in-fragment appears immediately after the out-fragment finish the animator of slide_out_down , and when I change the animator hoping two fragment slide up smoothly, the in-fragment disappears immediately before the out-fragment start animator.

look like this picture

why ? How to solve this ?

There are more details.

I have a listview with three items on screen left, and three fragments on right,one fragment for one item.

Sample like

in MyActivity, I  initialize all my fragment in onCreate()

private void createFragment(int initPosition) {
     mFragment[0] = new Fragment();
     mFragment[1] = new Fragment();
     mFragment[2] = new Fragment();

     mFragmentManager = getFragmentManager();
     mFragmentTransaction = mFragmentManager.beginTransaction();
     mFragmentTransaction.add(R.id.content_layout, mFragment[initPosition]);
     mFragmentTransaction.commit();
}

and I set a onItemSelectedListener to listview, when listview change it's selection, called replaceFragment(int fromPos, int toPos).

private void replaceFragment(int fromPos, int toPos) {
    if(fromPos != toPos) {
        mFragmentTransactoin = mFragmentManager.beginTransaction();

        //add animator
        if (fromPos < toPos) {
            mFragmentTransaction.setCustomAnimations(R.animator.slide_in_up, R.animator.slide_out_up);
        } else {
            mFragmentTransaction.setCustomAnimations(R.animator.slide_in_down, R.animator.slide_out_down);
        }

        if (!mFragments[toPos].isAdded()) {
            mFragmentTransaction.add(R.id.content_layout, mFragments[toPos]);
        }
        mFragmentTransaction.show(mFragments[toPos]);
        mFragmentTransaction.hide(mFragments[toPos]);
        mFragmentTransaction.commit();
    }
}

Why not use replace(), because replace() cause out-fragment destroyed, in-fragment will initialize every time. It's bad.show() and hide() could avoid that.

animator code :

slide_in_up.xml

<objectAnimator
    android:valueFrom="1280"
    android:valueTo="0"
    android:propertyName="translationY"
    android:duration="800"/>

slide_out_up.xml

<objectAnimator
    android:valueFrom="0"
    android:valueTo="-1280"
    android:propertyName="translationY"
    android:duration="800"/>

slide_in_down.xml

<objectAnimator
    android:valueFrom="-1280"
    android:valueTo="0"
    android:propertyName="translationY"
    android:duration="800"/>

slide_out_down.xml

<objectAnimator
    android:valueFrom="0"
    android:valueTo="1280"
    android:propertyName="translationY"
    android:duration="800"/>

Any reply is appreciated.


问:
How to setup environment variables for `flask run` on Windows?
I just started learning flask and I am stuck at setting up the Flask environment variables. I don't know how to setup the environment variables. Whenever I use the flask run command, I encounter the following error:

Error message : Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory.

I did a lot of google searches to setup environment variables on Windows but I am unable to find a solution and sometimes I am not able to understand the solution.

How to do this ? How to get the "app.py" or "wsgi.py" ?

答:
I used this and it worked because I am doing it in Windows PowerShell.

```<code>$env:FLASK_APP = "app.py"
</code>```

however, flask run didn't and gave me could not import application.

Body:
I used this and it worked because I am doing it in Windows PowerShell.

$env:FLASK_APP = "app.py"

however, flask run didn't and gave me could not import application.


问:
Use of Ngfor in label mat-ltab
I am facing a problem when using *ngFor in a mat-tab (included from angular material). I have a button that when clicked duplicates the code with *ngFor. My textArea inside this code has an id = serReal{{j}} where j is the index of the *ngFor. My reference is not working though. When I tried to get the element in my typescript code, it gets only the first one (serReal0). For the others I receive null.

My Html code:

```<code>    <!-- here I call it to duplicate -->
    <button mat-icon-button (click)="addData()" type="button" id="add_icon"></button>

    <!-- here it is my ngfor code which will duplicate -->
    <mat-tab-group>
          <mat-tab *ngFor="let itemServ of itemsServ; let j = index;" [label] = label[j]>
                <div class="areaTexto">
                      <div class="mdc-text-field text-field mdc-text-field--fullwidth mdc-text-field--textarea">
                            <textarea class="campoTextoServReal"
id ="servReal{{j}}"></textarea>
                      </div>
                </div>
          </mat-tab>
    </mat-tab-group>

    <!-- here I call it to read the text areas by the id -->
    <div class="divEncerraRel" id = apply>
          <button mat-raised-button (click) = 'setRelatorio()'>Encerrar Relatório</button>
    </div>
</code>```

My TS code:

```<code>    itemsServ: number[] = [1];

addData() {
  this.itemsServ.push(this.itemsServ.length + 1);
  this.label.push('Titulo');
}

setRelatorio() {
  for (let i = 0; i < this.itemsServ.length; i++) {
     console.log((<HTMLInputElement>document.getElementById("servReal" + i)));
  }
}
</code>```

答:
Problems I see is:

Separate states tracking data this.label & this.itemsServ

Querying the DOM to update the data

You should really start by defining your domain or data structure before working on rendering them.

For eg.

Define an interface that will hold your data structure

```<code>export interface Item {
  id: number;
  label: string;
  data: string;
}`
</code>```

Then define a function to add:

```<code>addItem() {
    const newIndex = this.items.length;
    const newItem = {
      id: newIndex,
      label: 'Titulo '+newIndex,
      data: 'data '+newIndex
    } as Item

    this.items.push(newItem);
}
</code>```

Define a function to update:

```<code>updateItem(id, data) {
    this.items.find((item) => item.id === id).data = data;
  }
</code>```

Then you can start working on your template

To add call the addItem function above on button click

```<code>(click)="addItem()"
</code>```

To update call your update function, for your situation you may want to update your data when your text-area change event gets triggered

```<code>(change)="updateItem(item.id, data.value)"
</code>```

To render all tabs

```<code><mat-tab-group>
    <mat-tab *ngFor="let item of items; let j = index;" [label]="item.label">
        <div class="mdc-text-field text-field mdc-text-field--fullwidth mdc-text-field--textarea">
            <textarea class="campoTextoServReal"
                #data
                [id]="item.id"
                (change)="updateItem(item.id, data.value)">
                {{item.data}}
            </textarea>
        </div>
    </mat-tab>
</mat-tab-group>
</code>```

Doing this may be more work but it eliminates you having to query the dom every time you want to update data.

You can find a complete example here

Title: Use of Ngfor in label mat-ltab

Body:
I am facing a problem when using *ngFor in a mat-tab (included from angular material). I have a button that when clicked duplicates the code with *ngFor. My textArea inside this code has an id = serReal{{j}} where j is the index of the *ngFor. My reference is not working though. When I tried to get the element in my typescript code, it gets only the first one (serReal0). For the others I receive null.

My Html code:

    <button mat-icon-button (click)="addData()" type="button" id="add_icon"></button>

    <mat-tab-group>
          <mat-tab *ngFor="let itemServ of itemsServ; let j = index;" [label] = label[j]>

                            <textarea class="campoTextoServReal"
id ="servReal{{j}}"></textarea>

          </mat-tab>
    </mat-tab-group>

          <button mat-raised-button (click) = 'setRelatorio()'>Encerrar Relatório</button>

My TS code:

    itemsServ: number[] = [1];

addData() {
  this.itemsServ.push(this.itemsServ.length + 1);
  this.label.push('Titulo');
}

setRelatorio() {
  for (let i = 0; i < this.itemsServ.length; i++) {
     console.log((<HTMLInputElement>document.getElementById("servReal" + i)));
  }
}

Body:
Problems I see is:

Separate states tracking data this.label & this.itemsServ

Querying the DOM to update the data

You should really start by defining your domain or data structure before working on rendering them.

For eg.

Define an interface that will hold your data structure

export interface Item {
  id: number;
  label: string;
  data: string;
}`

Then define a function to add:

addItem() {
    const newIndex = this.items.length;
    const newItem = {
      id: newIndex,
      label: 'Titulo '+newIndex,
      data: 'data '+newIndex
    } as Item

    this.items.push(newItem);
}

Define a function to update:

updateItem(id, data) {
    this.items.find((item) => item.id === id).data = data;
  }

Then you can start working on your template

To add call the addItem function above on button click

(click)="addItem()"

To update call your update function, for your situation you may want to update your data when your text-area change event gets triggered

(change)="updateItem(item.id, data.value)"

To render all tabs

<mat-tab-group>
    <mat-tab *ngFor="let item of items; let j = index;" [label]="item.label">
        <div class="mdc-text-field text-field mdc-text-field--fullwidth mdc-text-field--textarea">
            <textarea class="campoTextoServReal"
                #data
                [id]="item.id"
                (change)="updateItem(item.id, data.value)">
                {{item.data}}
            </textarea>
        </div>
    </mat-tab>
</mat-tab-group>

Doing this may be more work but it eliminates you having to query the dom every time you want to update data.

You can find a complete example here


问:
Community detection in extracted ego network using igraph
I used the igraph library installed in R software and I want to extract an ego-network from the network "Les Miserables".

Here is my code:

```<code>library("igraph")
lesmis<-read.graph("lesmis.gml", format="gml")
gavroche <- graph.neighborhood(lesmis, order = 2, nodes = which(V(lesmis)$label == "Gavroche"))
wc<-infomap.community(gavroche)
plot(wc, gavroche)
</code>```

I get this error :

Error in infomap.community(gavroche) : Not a graph object

here is the link of the gml file :
http://www-personal.umich.edu/~mejn/netdata/lesmis.zip

答:
I've reached this question just now searching for other theme.
I found that the object created by graph.neighborhood is not a graph itself but a list instead, that in turn contains your expected graph. Then you can replace:

```<code>wc <- infomap.community(gavroche[[1]])
plot(wc, gavroche[[1]])
</code>```

And it must work.

Body:
I used the igraph library installed in R software and I want to extract an ego-network from the network "Les Miserables".

Here is my code:

library("igraph")
lesmis<-read.graph("lesmis.gml", format="gml")
gavroche <- graph.neighborhood(lesmis, order = 2, nodes = which(V(lesmis)$label == "Gavroche"))
wc<-infomap.community(gavroche)
plot(wc, gavroche)

I get this error :

Error in infomap.community(gavroche) : Not a graph object

here is the link of the gml file :
http://www-personal.umich.edu/~mejn/netdata/lesmis.zip

Body:
I've reached this question just now searching for other theme.
I found that the object created by graph.neighborhood is not a graph itself but a list instead, that in turn contains your expected graph. Then you can replace:

wc <- infomap.community(gavroche[[1]])
plot(wc, gavroche[[1]])

And it must work.


问:
How to remove a specific value from an array in JavaScript?
Suppose, i have an array

```<code>const anArray = ['value 1', 'value 2', 'value 3', 'value 4', 'value 5'];
</code>```

If i want to remove the value 3 from anArray but don't know the position of that value in the array, how can i remove that?

Note: I'm a beginner in JavaScript

答:
Use indexOf to get the index, and splice to delete:

const anArray = ['value 1', 'value 2', 'value 3', 'value 4', 'value 5'];
anArray.splice(anArray.indexOf("value 3"), 1);
console.log(anArray);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: auto; }</code>```

Body:
Suppose, i have an array

const anArray = ['value 1', 'value 2', 'value 3', 'value 4', 'value 5'];

If i want to remove the value 3 from anArray but don't know the position of that value in the array, how can i remove that?

Note: I'm a beginner in JavaScript

Body:
Use indexOf to get the index, and splice to delete:

const anArray = ['value 1', 'value 2', 'value 3', 'value 4', 'value 5'];
anArray.splice(anArray.indexOf("value 3"), 1);
console.log(anArray);

.as-console-wrapper { max-height: 100% !important; top: auto; }


问:
Change barButtonSystemItem after tapping
I have a bar button in the right side of the screen, it's barButtonSystemItem: .edit and it's used to put tableView in the editing mode. I want when, user tap on it, it change to barButtonSystemItem: .done and it close tableview from editing mode.
Just to be clear, every time that barButton is clicked, the type of it should be change from edit to done.

Here is my code, but it always stay with edit, and not changing to done

```<code>fileprivate func addBarButton() {
    if tableView.isEditing {
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(editButtonAction))
    } else {
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(doneButtonAction))
    }
}

@objc func editButtonAction(sender: UIBarButtonItem) {
    tableView.isEditing = !tableView.isEditing
}

@objc func doneButtonAction(sender: UIBarButtonItem) {
    tableView.isEditing = !tableView.isEditing
}

override func viewDidLoad() {
    super.viewDidLoad()
    addBarButton()
    tableView?.isEditing = true
}
</code>```

答:
In the bodies of methods editButtonAction and editButtonAction you only change the tableView editing state by doing tableView.isEditing = !tableView.isEditing. This action does nothing to navigationItem at all.

I'd recommend you to refactor the code a bit by renaming addBarButton into updateBarButton and call it every time when the table editing state changes and additionally from viewDidLoad as you do now. So your code would become something like this:

  fileprivate func updateBarButton() {
    if tableView.isEditing {
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(editButtonAction))
    } else {
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(doneButtonAction))
    }
}

@objc func editButtonAction(sender: UIBarButtonItem) {
    tableView.isEditing = !tableView.isEditing
    updateBarButton() // Note the additional call of the update method
}

@objc func doneButtonAction(sender: UIBarButtonItem) {
    tableView.isEditing = !tableView.isEditing
    updateBarButton() // Note the additional call of the update method
}

override func viewDidLoad() {
    super.viewDidLoad()
    tableView?.isEditing = true
    updateBarButton() // Note that we call this method after changing the table view state so that it will have the most recent value
}
```

Body:
I have a bar button in the right side of the screen, it's barButtonSystemItem: .edit and it's used to put tableView in the editing mode. I want when, user tap on it, it change to barButtonSystemItem: .done and it close tableview from editing mode.
Just to be clear, every time that barButton is clicked, the type of it should be change from edit to done.

Here is my code, but it always stay with edit, and not changing to done

fileprivate func addBarButton() {
    if tableView.isEditing {
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(editButtonAction))
    } else {
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(doneButtonAction))
    }
}

@objc func editButtonAction(sender: UIBarButtonItem) {
    tableView.isEditing = !tableView.isEditing
}

@objc func doneButtonAction(sender: UIBarButtonItem) {
    tableView.isEditing = !tableView.isEditing
}

override func viewDidLoad() {
    super.viewDidLoad()
    addBarButton()
    tableView?.isEditing = true
}