问:
How to achieve this in XML schema?
This is an XML that I want to get:

```<code><root>
    <A>
        <C>asd</C>
        <D>asd</D>
        <E>asd</E>
    </A>
    <B>
        <C>asd</C>
        <D>asd</D>
        <E>asd</E>
        <F>asd</F>
    </B>
</root>
</code>```

Here are some more limits:

There can be multiple A and B elements, in any order.

A and B have exactly the same contents, except that B also may contain element F;

C, D, E and F may appear in any order.

E can appear multiple times;

C and D can appear 0 or 1 times;

F must appear exactly 1 time

Is this possible? And on a side note - why is XML schema so awkward in defining such simple scenarios?

答:
If you're just looking for code-completion (as you mentioned in a comment), then just define each type as an unlimited choice of the possible children. For example, for B:

```<code>  <xs:choice minOccurs="0" maxOccurs="unbounded">
    <xs:element name="C" type="xs:string"/>
    <xs:element name="D" type="xs:string"/>
    <xs:element name="E" type="xs:string"/>
    <xs:element name="F" type="xs:string"/>
  </xs:choice>
</code>```

And on a side note - why is XML schema so awkward in defining such simple scenarios?

Partly because sparse XML/DTD had beaten rich SGML/DTD by keeping features at a minimum and being friendly to simple processors. So XML Schema wanted to stay closer to XML than SGML.

ContentLicense: CC BY-SA 2.5

Title: How to achieve this in XML schema?

Body:
This is an XML that I want to get:

<root>

        <C>asd</C>
        <D>asd</D>
        <E>asd</E>

        <C>asd</C>
        <D>asd</D>
        <E>asd</E>
        <F>asd</F>

</root>

Here are some more limits:

There can be multiple A and B elements, in any order.

A and B have exactly the same contents, except that B also may contain element F;

C, D, E and F may appear in any order.

E can appear multiple times;

C and D can appear 0 or 1 times;

F must appear exactly 1 time

Is this possible? And on a side note - why is XML schema so awkward in defining such simple scenarios?

Body:
If you're just looking for code-completion (as you mentioned in a comment), then just define each type as an unlimited choice of the possible children. For example, for B:

  <xs:choice minOccurs="0" maxOccurs="unbounded">
    <xs:element name="C" type="xs:string"/>
    <xs:element name="D" type="xs:string"/>
    <xs:element name="E" type="xs:string"/>
    <xs:element name="F" type="xs:string"/>
  </xs:choice>

And on a side note - why is XML schema so awkward in defining such simple scenarios?

Partly because sparse XML/DTD had beaten rich SGML/DTD by keeping features at a minimum and being friendly to simple processors. So XML Schema wanted to stay closer to XML than SGML.


来源: stackexchange

问:
React Axios Input Undefined
I must post {input} data to http://localhost:4000/prediction with Axios. But {input} turns undefined.

I am using const instead of class Main extends component. onChange, it sets form data.

```<code>const Main = ({ value, suggestions, auth: { user } }) => {

  const [formData, setFormData] = useState("");

  const [messages, setMessages] = useState([]);

  const { input } = formData;

  const onChange = e => setFormData(e.target.value);

  const onSubmit = event => {
    event.preventDefault();
    setMessages(prevMsgs => [...prevMsgs, formData]);

    console.log({ input });
</code>```

Axios post.

```<code>    axios
      .post(
        `http://localhost:4000/prediction`,
        { input },
        { crossdomain: true }
      )
      .then(res => {
        console.log(res.data);
        //setMessages(prevMsgs => [...prevMsgs, formData]);
      })
      .catch(error => {
        console.log(error.message);
      });
  };
</code>```

Return (form) with onSubmit, onChange.

```<code>  return (
    <div className="true">
      <br />
      <form noValidate onSubmit={e => onSubmit(e)}>
        <div className="input-group mb-3">
           <input
                name="input"
                type="text"
                className="form-control"
                placeholder="Type text"
                onChange={e => onChange(e)}
              />
            )}
          <div className="input-group-append">
            <button className="btn btn-outline-secondary">Send</button>
          </div>
        </div>
      </form>
    </div>
  );
};
</code>```

答:
As I have mentioned in the comment section formData is a string as I see which does not have a property called input what you try to destructure and that's why it is undefined always.

If you really need that format for axios then you can try change the structure of formData with useState as the following first:

```<code>const [formData, setFormData] = useState({input: null});
</code>```

Then maybe you can try updating as:

```<code>const onChange = e => setFormData({input: e.target.value});
</code>```

I hope that helps!

ContentLicense: CC BY-SA 4.0

Title: React Axios Input Undefined

Body:
I must post {input} data to http://localhost:4000/prediction with Axios. But {input} turns undefined.

I am using const instead of class Main extends component. onChange, it sets form data.

const Main = ({ value, suggestions, auth: { user } }) => {

  const [formData, setFormData] = useState("");

  const [messages, setMessages] = useState([]);

  const { input } = formData;

  const onChange = e => setFormData(e.target.value);

  const onSubmit = event => {
    event.preventDefault();
    setMessages(prevMsgs => [...prevMsgs, formData]);

    console.log({ input });

Axios post.

    axios
      .post(
        `http://localhost:4000/prediction`,
        { input },
        { crossdomain: true }
      )
      .then(res => {
        console.log(res.data);
        //setMessages(prevMsgs => [...prevMsgs, formData]);
      })
      .catch(error => {
        console.log(error.message);
      });
  };

Return (form) with onSubmit, onChange.

  return (

      <form noValidate onSubmit={e => onSubmit(e)}>

           <input
                name="input"
                type="text"
                className="form-control"
                placeholder="Type text"
                onChange={e => onChange(e)}
              />
            )}

            <button className="btn btn-outline-secondary">Send</button>

      </form>

  );
};

Body:
As I have mentioned in the comment section formData is a string as I see which does not have a property called input what you try to destructure and that's why it is undefined always.

If you really need that format for axios then you can try change the structure of formData with useState as the following first:

const [formData, setFormData] = useState({input: null});

Then maybe you can try updating as:

const onChange = e => setFormData({input: e.target.value});

I hope that helps!


问:
GroupJoin with one single window ending on completion of streams
I have two sources of data which are dumping data from separate thread. I am trying to join both sources by a key. I am able to do it using GroupJoin. I have to use Observable.Never so that window never ends. Everything is working fine in terms of joining the streams. When both sources complete dumping data, they call their repective onComplete on Observers. I am expecting streaming to end as soon as OnComplete is received for both the sources. As I have used Observable.Never stream never ends and Oncomplete event of my aggSource is never called.

is there way to tell Rx that close window when OnComplete received for both the sources instead of infinitely keeping it open?

I am new to Rx and not sure if this is something can be achieved. Below is code snippet. Thanks in Advance!!

```<code>var l = Source1;
var r = Source2;

var q = r.GroupJoin(l,
                _ => Observable.Never<Unit>(), // windows from each left event going on forever
                _ => Observable.Never<Unit>(), // windows from each right event going on forever
                (left, obsOfRight) => Tuple.Create(left, obsOfRight)); // create tuple of left event with observable of right events

        var joinSource =   q.SelectMany(e => {
            return e.Item2.Where(
               x =>
               {
                 return x.ID== e.Item1.ID;
               })
               .Select(v=>  (Item1:v.Value, Item2: e.Item1.Value));
        });

var aggSource = joinSource.GroupBy(x => x.Item1).SelectMany(grp =>
            {
                return grp.Scan(0.0, (accumulator, current) => accumulator + current.Item2).Select(z => (Group: grp.Key, Value: z));
            });

aggSource.Subscribe(x => dictResults[x.Group] = x,
              y => { Console.WriteLine("Error Ocurred: " + y.Message); completed = true; },
              () => { completed = true; Console.WriteLine("Subcription comnpleted"); }
              );
// dict results is dictionary which is my projection which is shown to View. Right now my view is just console window.
</code>```

答:
The duration selector controls the join window overlap - which we need to cut short when either of the sources complete. First, we'll use LastOrDefaultAsync to get a notification when an OnComplete is emitted.

```<code>var either = Observable.CombineLatest(l.LastOrDefaultAsync(), r.LastOrDefaultAsync());
</code>```

Now we can modify the duration selector from the sample:

```<code>var q = r.GroupJoin(l,
                _ => Observable.Never<Unit>().TakeUntil(either), // windows from each left event until l or r completes
                _ => Observable.Never<Unit>().TakeUntil(either), // windows from each right event until l or r completes
                (left, obsOfRight) => Tuple.Create(left, obsOfRight)); // create tuple of left event with observable of right events
</code>```

This should cause a cascade and complete the rest of the observable pipeline.

Body:
I have two sources of data which are dumping data from separate thread. I am trying to join both sources by a key. I am able to do it using GroupJoin. I have to use Observable.Never so that window never ends. Everything is working fine in terms of joining the streams. When both sources complete dumping data, they call their repective onComplete on Observers. I am expecting streaming to end as soon as OnComplete is received for both the sources. As I have used Observable.Never stream never ends and Oncomplete event of my aggSource is never called.

is there way to tell Rx that close window when OnComplete received for both the sources instead of infinitely keeping it open?

I am new to Rx and not sure if this is something can be achieved. Below is code snippet. Thanks in Advance!!

var l = Source1;
var r = Source2;

var q = r.GroupJoin(l,
                _ => Observable.Never<Unit>(), // windows from each left event going on forever
                _ => Observable.Never<Unit>(), // windows from each right event going on forever
                (left, obsOfRight) => Tuple.Create(left, obsOfRight)); // create tuple of left event with observable of right events

        var joinSource =   q.SelectMany(e => {
            return e.Item2.Where(
               x =>
               {
                 return x.ID== e.Item1.ID;
               })
               .Select(v=>  (Item1:v.Value, Item2: e.Item1.Value));
        });

var aggSource = joinSource.GroupBy(x => x.Item1).SelectMany(grp =>
            {
                return grp.Scan(0.0, (accumulator, current) => accumulator + current.Item2).Select(z => (Group: grp.Key, Value: z));
            });

aggSource.Subscribe(x => dictResults[x.Group] = x,
              y => { Console.WriteLine("Error Ocurred: " + y.Message); completed = true; },
              () => { completed = true; Console.WriteLine("Subcription comnpleted"); }
              );
// dict results is dictionary which is my projection which is shown to View. Right now my view is just console window.

Body:
The duration selector controls the join window overlap - which we need to cut short when either of the sources complete. First, we'll use LastOrDefaultAsync to get a notification when an OnComplete is emitted.

var either = Observable.CombineLatest(l.LastOrDefaultAsync(), r.LastOrDefaultAsync());

Now we can modify the duration selector from the sample:

var q = r.GroupJoin(l,
                _ => Observable.Never<Unit>().TakeUntil(either), // windows from each left event until l or r completes
                _ => Observable.Never<Unit>().TakeUntil(either), // windows from each right event until l or r completes
                (left, obsOfRight) => Tuple.Create(left, obsOfRight)); // create tuple of left event with observable of right events

This should cause a cascade and complete the rest of the observable pipeline.


问:
how to write a fastq file from other file
I was asked to read from two files (left and right reads) Aip02.R1.fastq and Aip02.R2.fastq, and get an interleaved fasta file using zip function.  The left and right files were fastq files, but when I zip them together to make a new fastq file, the writer function doesn't work anymore. It gives me error "SeqRecord (id=) has an invalid sequence."</p>

```<code>  #!/usr/bin/env python3
  # Import Seq, SeqRecord, and SeqIO
  from Bio import SeqIO
  from Bio.SeqRecord import SeqRecord
  from Bio.Seq import Seq
  leftReads = SeqIO.parse("/scratch/AiptasiaMiSeq/fastq/Aip02.R1.fastq", "fastq")
  rightReads = SeqIO.parse("/scratch/AiptasiaMiSeq/fastq/Aip02.R2.fastq","fastq")
  A= zip(leftReads,rightReads)
  SeqIO.write(SeqRecord(list(A)), "interleave.fastq", "fastq")
</code>```

答:
Your forward and reverse sequences probably have the same ID. So use the following code to add a suffix to the IDs. I used /1 and /2 here, but things like .f and .r are also used.

```<code>from Bio import SeqIO
import itertools

def interleave(iter1, iter2) :
    for (forward, reverse) in itertools.izip(iter1, iter2):
        assert forward.id == reverse.id
        forward.id += "/1"
        reverse.id += "/2"
        yield forward
        yield reverse

leftReads = SeqIO.parse("/scratch/AiptasiaMiSeq/fastq/Aip02.R1.fastq", "fastq")
rightReads = SeqIO.parse("/scratch/AiptasiaMiSeq/fastq/Aip02.R2.fastq","fastq")

handle = open("interleave.fastq", "w")
count = SeqIO.write(interleave(leftReads, rightReads), handle, "fastq")
handle.close()
print("{} records written to interleave.fastq".format(count))
</code>```

This code can become slow for large fastq files. For example see here where they report that it takes 14 minutes to create a 2GB fastq file. So they give this improved way:

```<code>from Bio.SeqIO.QualityIO import FastqGeneralIterator
import itertools

file_f = "/scratch/AiptasiaMiSeq/fastq/Aip02.R1.fastq"
file_r = "/scratch/AiptasiaMiSeq/fastq/Aip02.R2.fastq"

handle = open("interleave.fastq", "w")
count = 0

f_iter = FastqGeneralIterator(open(file_f,"rU"))
r_iter = FastqGeneralIterator(open(file_r,"rU"))
for (f_id, f_seq, f_q), (r_id, r_seq, r_q) in itertools.izip(f_iter,r_iter):
    assert f_id == r_id
    count += 2
    #Write out both reads with "/1" and "/2" suffix on ID
    handle.write("@%s/1n%sn+n%sn@%s/2n%sn+n%sn"
                 % (f_id, f_seq, f_q, r_id, r_seq, r_q))
handle.close()
print("{} records written to interleave.fastq".format(count)
</code>```

Body:
I was asked to read from two files (left and right reads) Aip02.R1.fastq and Aip02.R2.fastq, and get an interleaved fasta file using zip function.  The left and right files were fastq files, but when I zip them together to make a new fastq file, the writer function doesn't work anymore. It gives me error "SeqRecord (id=) has an invalid sequence."

  #!/usr/bin/env python3
  # Import Seq, SeqRecord, and SeqIO
  from Bio import SeqIO
  from Bio.SeqRecord import SeqRecord
  from Bio.Seq import Seq
  leftReads = SeqIO.parse("/scratch/AiptasiaMiSeq/fastq/Aip02.R1.fastq", "fastq")
  rightReads = SeqIO.parse("/scratch/AiptasiaMiSeq/fastq/Aip02.R2.fastq","fastq")
  A= zip(leftReads,rightReads)
  SeqIO.write(SeqRecord(list(A)), "interleave.fastq", "fastq")

Body:
Your forward and reverse sequences probably have the same ID. So use the following code to add a suffix to the IDs. I used /1 and /2 here, but things like .f and .r are also used.

from Bio import SeqIO
import itertools

def interleave(iter1, iter2) :
    for (forward, reverse) in itertools.izip(iter1, iter2):
        assert forward.id == reverse.id
        forward.id += "/1"
        reverse.id += "/2"
        yield forward
        yield reverse

leftReads = SeqIO.parse("/scratch/AiptasiaMiSeq/fastq/Aip02.R1.fastq", "fastq")
rightReads = SeqIO.parse("/scratch/AiptasiaMiSeq/fastq/Aip02.R2.fastq","fastq")

handle = open("interleave.fastq", "w")
count = SeqIO.write(interleave(leftReads, rightReads), handle, "fastq")
handle.close()
print("{} records written to interleave.fastq".format(count))

This code can become slow for large fastq files. For example see here where they report that it takes 14 minutes to create a 2GB fastq file. So they give this improved way:

from Bio.SeqIO.QualityIO import FastqGeneralIterator
import itertools

file_f = "/scratch/AiptasiaMiSeq/fastq/Aip02.R1.fastq"
file_r = "/scratch/AiptasiaMiSeq/fastq/Aip02.R2.fastq"

handle = open("interleave.fastq", "w")
count = 0

f_iter = FastqGeneralIterator(open(file_f,"rU"))
r_iter = FastqGeneralIterator(open(file_r,"rU"))
for (f_id, f_seq, f_q), (r_id, r_seq, r_q) in itertools.izip(f_iter,r_iter):
    assert f_id == r_id
    count += 2
    #Write out both reads with "/1" and "/2" suffix on ID
    handle.write("@%s/1n%sn+n%sn@%s/2n%sn+n%sn"
                 % (f_id, f_seq, f_q, r_id, r_seq, r_q))
handle.close()
print("{} records written to interleave.fastq".format(count)


问:
Django: Passing context to another view
I'm trying to pass my context of items to another view, with only the specific item's details, but I'm having trouble to even find the correct documentation on how this works.

I need to get my specific package to another view, and have all of it's properties with it, like dependencies, description, homepage etc, but I don't know what's the correct/proper way to even pass those to another view?

Views:

from django.shortcuts import render
import re, random

def index(request):
    packages = {}
    latset_header = None

    with open("app/packages/status.real.txt", encoding="UTF-8") as f:
        for l in f:
            l = l.strip()
            # if line contains a keyword
            if "Package: " in l:
                latset_header = l.replace("Package: ", "")
                packages[latset_header] = {'name': latset_header}
            elif "Depends: " in l:
                packages[latset_header]['depends'] = l.replace("Depends: ", "")
            elif "Description: " in l:
                packages[latset_header]["description"] = l.replace("Description: ", "")
            elif "Homepage: " in l:
                packages[latset_header]["homepage"] = l.replace("Homepage: ", "")

    context = {'items': packages}

    return render(request, 'packages_index.html', context)

def show_package_details(request, package):
    context = {'item': package}
    return render(request, 'packages_details.html', context)
```

<p>Urls:</p>

<pre class="lang-py prettyprint-override"><code>from django.urls import include, path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('<str:package>', views.show_package_details, name='package-details')
]
</code>```

packages_index.html - template:

{% extends "home.html" %}

{% block container %}

The packages

    {% if items %}

            {% for item, value in items.items %}

                    {{ item }}

            {% endfor %}

    {% else %}

No items available.

    {% endif %}
{% endblock %}
```

<p>Package details view template:</p>

<pre class="lang-html prettyprint-override"><code>{% extends "home.html" %}

{% block container %}
    {% if item %}
        <h2>Details of {{ item }}</h2>
        <p>Dependencies: {{ item.dependencies }}</p>
    {% else %}
        <p>No item can be seen.</p>
    {% endif %}
{% endblock %}
</code>```

答:
Just extract that piece of logic into a function and use it on both views:

from django.shortcuts import render
import re, random

def get_packages():
    packages = {}
    latset_header = None

    with open("app/packages/status.real.txt", encoding="UTF-8") as f:
        for l in f:
            l = l.strip()
            # if line contains a keyword
            if "Package: " in l:
                latset_header = l.replace("Package: ", "")
                packages[latset_header] = {'name': latset_header}
            elif "Depends: " in l:
                packages[latset_header]['depends'] = l.replace("Depends: ", "")
            elif "Description: " in l:
                packages[latset_header]["description"] = l.replace("Description: ", "")
            elif "Homepage: " in l:
                packages[latset_header]["homepage"] = l.replace("Homepage: ", "")

    return packages

def index(request):
    context = {'items': get_packages()}
    return render(request, 'packages_index.html', context)

def show_package_details(request, package):
    context = {'item': get_packages()}
    return render(request, 'packages_details.html', context)
```

Title: Django: Passing context to another view

Body:
I'm trying to pass my context of items to another view, with only the specific item's details, but I'm having trouble to even find the correct documentation on how this works.

I need to get my specific package to another view, and have all of it's properties with it, like dependencies, description, homepage etc, but I don't know what's the correct/proper way to even pass those to another view?

Views:

from django.shortcuts import render
import re, random

def index(request):
    packages = {}
    latset_header = None

    with open("app/packages/status.real.txt", encoding="UTF-8") as f:
        for l in f:
            l = l.strip()
            # if line contains a keyword
            if "Package: " in l:
                latset_header = l.replace("Package: ", "")
                packages[latset_header] = {'name': latset_header}
            elif "Depends: " in l:
                packages[latset_header]['depends'] = l.replace("Depends: ", "")
            elif "Description: " in l:
                packages[latset_header]["description"] = l.replace("Description: ", "")
            elif "Homepage: " in l:
                packages[latset_header]["homepage"] = l.replace("Homepage: ", "")

    context = {'items': packages}

    return render(request, 'packages_index.html', context)

def show_package_details(request, package):
    context = {'item': package}
    return render(request, 'packages_details.html', context)

Urls:

from django.urls import include, path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('<str:package>', views.show_package_details, name='package-details')
]

packages_index.html - template:

{% extends "home.html" %}

{% block container %}

The packages

    {% if items %}

            {% for item, value in items.items %}

                    {{ item }}

            {% endfor %}

    {% else %}

No items available.

    {% endif %}
{% endblock %}

Package details view template:

{% extends "home.html" %}

{% block container %}
    {% if item %}

Details of {{ item }}

Dependencies: {{ item.dependencies }}

    {% else %}

No item can be seen.

    {% endif %}
{% endblock %}


问:
Renaming integers within a data.frame
Using R...

I have a data.frame with five variables.

One of the variables colr has values ranging from 1 to 5.

Defined as an integer with values   1, 2, 3, 4, and 5.

Problem: I would like to build a regression model where the values within colr, the integers 1,2,3,4, and 5 are reported as independent variables with the following names.

1 = Silver,
2 = Blue,
3 = Pink,
4 = Other than Silver, Blue or Pink,
5 = Color Not Reported.

Question: Is there a way to extract or rename these values in a way that is different from the following (as this process does not rename, eg. 1 to Silver in the summary regression output):

```<code>lm(dependent variable ~ + I(colr.f == 1) +
                          I(colr.f == 2) +
                          I(colr.f == 3) +
                          I(colr.f == 4) +
                          I(colr.f == 5),
                          data = df)
</code>```

I am open to any method that would allow me to create and name these different values independently but would prefer to see if there is a way to do so using the tidyverse or dplyr as this is something I have to do frequently when building multivariate models.

Thank you for any help.

答:
With base R.</p>

```<code>labels <- c("Silver", "Blue", "Pink", "Other Color", "Color Not Reported")

df$colr.f2 <- factor(colr.f, labels = labels, levels = seq_along(labels))
</code>```

Title: Renaming integers within a data.frame

Body:
Using R...

I have a data.frame with five variables.

One of the variables colr has values ranging from 1 to 5.

Defined as an integer with values   1, 2, 3, 4, and 5.

Problem: I would like to build a regression model where the values within colr, the integers 1,2,3,4, and 5 are reported as independent variables with the following names.

1 = Silver,
2 = Blue,
3 = Pink,
4 = Other than Silver, Blue or Pink,
5 = Color Not Reported.

Question: Is there a way to extract or rename these values in a way that is different from the following (as this process does not rename, eg. 1 to Silver in the summary regression output):

lm(dependent variable ~ + I(colr.f == 1) +
                          I(colr.f == 2) +
                          I(colr.f == 3) +
                          I(colr.f == 4) +
                          I(colr.f == 5),
                          data = df)

I am open to any method that would allow me to create and name these different values independently but would prefer to see if there is a way to do so using the tidyverse or dplyr as this is something I have to do frequently when building multivariate models.

Thank you for any help.

Body:
With base R.

labels <- c("Silver", "Blue", "Pink", "Other Color", "Color Not Reported")

df$colr.f2 <- factor(colr.f, labels = labels, levels = seq_along(labels))


问:
Next js routing triggers useEffect
I'm trying to fetch data inside useEffect using axios but it fetches the data everytime I change the page. Is there a way to not trigger useEffect when changing the page? I tried to use shawllow push but it didn't work. I can't fetch on server side because I use next/router inside axios interceptor. </p>

```<code>   import { useRouter } from 'next/router';
   const router = useRouter();
   router.push('/', '/', { shallow: true })
</code>```

<p>With the above code, it will trigger useEffect when switching routes. </p>

```<code>  useEffect(() => {
    fetch.get('/endpoint').then(response => {
     // do stuff
    });
  }, []);
</code>```

答:
Try:

```<code>useEffect(() => {
    fetch.get('/endpoint').then(response => {
     // do stuff
    });
}, []); // the empty array will call useEffect only for first time while loading the component
</code>```

Refer: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects See Notes

Title: Next js routing triggers useEffect

Body:
I'm trying to fetch data inside useEffect using axios but it fetches the data everytime I change the page. Is there a way to not trigger useEffect when changing the page? I tried to use shawllow push but it didn't work. I can't fetch on server side because I use next/router inside axios interceptor.

   import { useRouter } from 'next/router';
   const router = useRouter();
   router.push('/', '/', { shallow: true })

With the above code, it will trigger useEffect when switching routes.

  useEffect(() => {
    fetch.get('/endpoint').then(response => {
     // do stuff
    });
  }, []);

Body:
Try:

useEffect(() => {
    fetch.get('/endpoint').then(response => {
     // do stuff
    });
}, []); // the empty array will call useEffect only for first time while loading the component

Refer: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects See Notes


问:
How to find the number of times that 2 follows 3 in a list
If I have a number 13245. What I need is to return how many times 2 follows behind number 3.

```<code>def thirtyTwos(n):
  lst=(map(int,str(n)))
  count=0
  i=0
  j=1
  while i<len(lst):
    while j<len(lst):
        if lst[i]==3>lst[j]==2:

                count+=1
        j+=1
    j=i+1
    i+=1
return count
</code>```

But it turns wrong on some numbers. What should I do now?

答:
This appears to work:

```<code>def count_32(number):
    number = str(number)

    prev_char = ""
    count = 0
    for char in number:
        if char == "2" and prev_char == "3":
            count += 1
        prev_char = char

    return count

for x in [13245, 2345, 32432, 3323232]:
    print(x, count_32(x))
</code>```

Output:

```<code>13245 1
2345 0
32432 2
3323232 3
</code>```

Body:
If I have a number 13245. What I need is to return how many times 2 follows behind number 3.

def thirtyTwos(n):
  lst=(map(int,str(n)))
  count=0
  i=0
  j=1
  while i<len(lst):
    while j<len(lst):
        if lst[i]==3>lst[j]==2:

                count+=1
        j+=1
    j=i+1
    i+=1
return count

But it turns wrong on some numbers. What should I do now?

Body:
This appears to work:

def count_32(number):
    number = str(number)

    prev_char = ""
    count = 0
    for char in number:
        if char == "2" and prev_char == "3":
            count += 1
        prev_char = char

    return count

for x in [13245, 2345, 32432, 3323232]:
    print(x, count_32(x))

Output:

13245 1
2345 0
32432 2
3323232 3


问:
Is there a good objc library wrapper for File System Events/kqueue that handles recursive watching for me?
I want to write an OSX (Snow Leopard) app that receives notifications when files within a specific directory are changed, and I want access to the path of the specific file that was changed.

I know I can do this using either File System Events or kqueue. The former doesn't provide the details of which specific file changed (requiring me to build a snapshot of the directory I'm watching and then scan it to find out which file changed). The latter doesn't support recursive watching (requiring me to recursively add watches to every file and directory within the parent directory).

I've had a look for libraries that handle the snapshot/recursion fun for me, but can't find any. UKKQueue looks like a good wrapper for the low level kqueue stuff, but doesn't seem to do recursion. Same for GTMFileSystemKQueue. SCEvents looks like a good wrapper for File System Events but doesn't seem to handle finding out the specific file that changed.

Is there a library that does what I want and is suitable for an objc project for either of these technologies?

答:
I ended up using GTMFileSystemKQueue after I found out how easy it is to recursively iterate over a directory in objc:

```<code>// Create a directory enumerator for the given top level directory
NSDirectoryEnumerator *de = [[NSFileManager defaultManager] enumeratorAtPath:dir];

// Add a kqueue on every file and folder below the top level
NSString *file;
while ((file = [de nextObject])) {
    [[GTMFileSystemKQueue alloc] initWithPath:[dir stringByAppendingString:file]
                                    forEvents:kGTMFileSystemKQueueAllEvents
                                acrossReplace:YES
                                       target:self
                                       action:@selector(fileSystemKQueue:events:)];
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I ended up using GTMFileSystemKQueue after I found out how easy it is to recursively iterate over a directory in objc:

// Create a directory enumerator for the given top level directory
NSDirectoryEnumerator *de = [[NSFileManager defaultManager] enumeratorAtPath:dir];

// Add a kqueue on every file and folder below the top level
NSString *file;
while ((file = [de nextObject])) {
    [[GTMFileSystemKQueue alloc] initWithPath:[dir stringByAppendingString:file]
                                    forEvents:kGTMFileSystemKQueueAllEvents
                                acrossReplace:YES
                                       target:self
                                       action:@selector(fileSystemKQueue:events:)];
}


问:
Printing utf8 characters from utf8 codes in Go
Problem:
I am trying to retrieve the value of a utf8 code designation.

let's say we have this situation:

```<code>//String with the alphabet and some numbers.
var aMess string = "abcdefghijklmnopqrstuvwxyz123456789"
</code>```

I want to output the value of what a utf8 code is assigned to.

If a is 97 in the utf8 table. What function do I call to output the character 'a' if 97 is the utf8 code?

```<code>fmt.Println(aMess[0]) // outputs 97 how do I convert 97 to what it is assigned too?
</code>```

答:
Go use  runes for such sort of operations where in other languages we would refer as char

If I understood your question correctly. In order to get the code of a char you can use a function like this:

```<code>func fromStringToRune(message string) {
    for _, r := range message {
        fmt.Println(r)
    }
}
</code>```

and if you want to get the char based on it's code you can use a function like this:

```<code>func fromRuneToChar(r int) {
    fmt.Println(string(r))
}
</code>```

Here is Example usage.

Body:
Problem:
I am trying to retrieve the value of a utf8 code designation.

let's say we have this situation:

//String with the alphabet and some numbers.
var aMess string = "abcdefghijklmnopqrstuvwxyz123456789"

I want to output the value of what a utf8 code is assigned to.

If a is 97 in the utf8 table. What function do I call to output the character 'a' if 97 is the utf8 code?

fmt.Println(aMess[0]) // outputs 97 how do I convert 97 to what it is assigned too?

Body:
Go use  runes for such sort of operations where in other languages we would refer as char

If I understood your question correctly. In order to get the code of a char you can use a function like this:

func fromStringToRune(message string) {
    for _, r := range message {
        fmt.Println(r)
    }
}

and if you want to get the char based on it's code you can use a function like this:

func fromRuneToChar(r int) {
    fmt.Println(string(r))
}

Here is Example usage.


问:
How to concatenate two unique arrays and remove 'nan'?
Using the Pokemon Dataset, I want to extract all the unique types in columns: "Type 1" & "Type 2" and print them out after. So far, I've been able to concatenate the unique values from both columns together into an array. Now I'm having trouble removing 'nan' from the array.

My code:

```<code>import pandas as pd
import numpy as np
df = pd.read_csv("/Users/edwinandrew/Documents/Datasets/Pokemon.csv")
type_class1 = df['Type 1'].unique()
type_class2 = df['Type 2'].unique()
all_types = np.concatenate((type_class1, type_class2))
print(all_types)
</code>```

Output:

```<code>['Grass' 'Fire' 'Water' 'Bug' 'Normal' 'Poison' 'Electric' 'Ground'
 'Fairy' 'Fighting' 'Psychic' 'Rock' 'Ghost' 'Ice' 'Dragon' 'Dark' 'Steel'
 'Flying' 'Poison' nan 'Flying' 'Dragon' 'Ground' 'Fairy' 'Grass'
 'Fighting' 'Psychic' 'Steel' 'Ice' 'Rock' 'Dark' 'Water' 'Electric'
 'Fire' 'Ghost' 'Bug' 'Normal']
</code>```

I tried using x = x[~numpy.isnan(x)] to see if that would remove the nan value but I got an error. What would be the best way to solve this problem?

答:
Use this

type_class1 = df['Type 1'].dropna().unique()
type_class2 = df['Type 2'].dropna().unique()

Or use fillna() Method

Body:
Using the Pokemon Dataset, I want to extract all the unique types in columns: "Type 1" & "Type 2" and print them out after. So far, I've been able to concatenate the unique values from both columns together into an array. Now I'm having trouble removing 'nan' from the array.

My code:

import pandas as pd
import numpy as np
df = pd.read_csv("/Users/edwinandrew/Documents/Datasets/Pokemon.csv")
type_class1 = df['Type 1'].unique()
type_class2 = df['Type 2'].unique()
all_types = np.concatenate((type_class1, type_class2))
print(all_types)

Output:

['Grass' 'Fire' 'Water' 'Bug' 'Normal' 'Poison' 'Electric' 'Ground'
 'Fairy' 'Fighting' 'Psychic' 'Rock' 'Ghost' 'Ice' 'Dragon' 'Dark' 'Steel'
 'Flying' 'Poison' nan 'Flying' 'Dragon' 'Ground' 'Fairy' 'Grass'
 'Fighting' 'Psychic' 'Steel' 'Ice' 'Rock' 'Dark' 'Water' 'Electric'
 'Fire' 'Ghost' 'Bug' 'Normal']

I tried using x = x[~numpy.isnan(x)] to see if that would remove the nan value but I got an error. What would be the best way to solve this problem?


问:
Python code snippet is taking very long time to run.. how to increase efficiency?
The task is to select elements from a list(li) so that the sum is as close to a given number(m) as possible!. But, The idk method is taking a very long time to run: it never completes. When I compile the code, the method just keeps on running and running.</p>

```<code>from itertools import combinations, permutations

def idk(typeOfSlices, maxNoOfPizzaSlices):
    length = len(typeOfSlices) + 1
    listToReturn = []
    temporarySum = 0

    for r in range(length):

        pool = tuple(typeOfSlices)
        n = len(pool)
        for indices in permutations(range(n), r):
            if sorted(indices) == list(indices):
                le = tuple(pool[i] for i in indices)
                ts = sum(le)
                if(ts == maxNoOfPizzaSlices):
                    print(le, ":", sum(le))
                    return le

                if(ts > temporarySum and ts <= maxNoOfPizzaSlices):
                    temporarySum = ts
                    listToreturn = le

    print(le, ":", sum(le))
    return listToReturn

m = 4500
li = [7, 12, 12, 13, 14, 28, 29, 29, 30, 32, 32, 34, 41, 45, 46, 56, 61, 61, 62, 63, 65, 68, 76, 77, 77, 92, 93, 94, 97, 103, 113, 114, 114, 120, 135, 145, 145, 149, 156, 157, 160, 169, 172, 179, 184, 185, 189, 194, 195, 195,
]
idk(li, m)
</code>```

答:
My 2 cents...

Does the code snippet work for a smaller array size?  If it doesn't work for a smaller list, then you may have a bad algorithm.

This may be a good match for multithreading.  You are not modifying the input list, thus there won't be any race conditions.  Slice the list up like you do with the first for-loop, then have each thread handle the permutations.

You sort the list, then look for a repeated value every time you compute a permutation.  Even worse, you don't even save the sorted list.  I would create a dedicated data structure to store the intermediate results so you can reduce the amount of sorting and hashing required.

Body:
The task is to select elements from a list(li) so that the sum is as close to a given number(m) as possible!. But, The idk method is taking a very long time to run: it never completes. When I compile the code, the method just keeps on running and running.

from itertools import combinations, permutations

def idk(typeOfSlices, maxNoOfPizzaSlices):
    length = len(typeOfSlices) + 1
    listToReturn = []
    temporarySum = 0

    for r in range(length):

        pool = tuple(typeOfSlices)
        n = len(pool)
        for indices in permutations(range(n), r):
            if sorted(indices) == list(indices):
                le = tuple(pool[i] for i in indices)
                ts = sum(le)
                if(ts == maxNoOfPizzaSlices):
                    print(le, ":", sum(le))
                    return le

                if(ts > temporarySum and ts <= maxNoOfPizzaSlices):
                    temporarySum = ts
                    listToreturn = le

    print(le, ":", sum(le))
    return listToReturn

m = 4500
li = [7, 12, 12, 13, 14, 28, 29, 29, 30, 32, 32, 34, 41, 45, 46, 56, 61, 61, 62, 63, 65, 68, 76, 77, 77, 92, 93, 94, 97, 103, 113, 114, 114, 120, 135, 145, 145, 149, 156, 157, 160, 169, 172, 179, 184, 185, 189, 194, 195, 195,
]
idk(li, m)


问:
Material-ui table pagination
I am using Material-ui table for listing data. table will load all data at once from remote server. Is there any way to load data through pagination, as page changes data has to be fetched from remote.

when page loads i will get data from following code.

```<code>const options = { method: 'GET', headers: { Origin: '*' } };
    fetch(`https://some-url/user_groups`, options)
        .then(function (result) {
           //i will get data here
        })
        .catch(error => console.log('error while fetching ', error));
</code>```

答:
yes you can by adding condition to the pagination slicing logic</p>

```<code>rows.slice((useDbPagination ? 0 : page) * rowsPerPage,
           (useDbPagination ? 0 : page) * rowsPerPage + rowsPerPage).map(/*render row here*/);
</code>```

Title: Material-ui table pagination

Body:
I am using Material-ui table for listing data. table will load all data at once from remote server. Is there any way to load data through pagination, as page changes data has to be fetched from remote.

when page loads i will get data from following code.

const options = { method: 'GET', headers: { Origin: '*' } };
    fetch(`https://some-url/user_groups`, options)
        .then(function (result) {
           //i will get data here
        })
        .catch(error => console.log('error while fetching ', error));

Body:
yes you can by adding condition to the pagination slicing logic

rows.slice((useDbPagination ? 0 : page) * rowsPerPage,
           (useDbPagination ? 0 : page) * rowsPerPage + rowsPerPage).map(/*render row here*/);


问:
LINQ Get full list of objects, include only the properties that match certain condition
I have these two models:

    public class Seat
    {
        public int Id { get; set; }
        public ICollection<Reservation> Reservations { get; set; }
    //..
    }

    public class Reservation
    {
        public int Id { get; set; }
        public int SeatId { get; set; }
        public Seat Seat { get; set; }
        public DateTime DateTime { get; set; }
        //..
    }
```

<p>Say a seat has a reservations for every day of the week. I want to make a query that takes the seats and filters the reservations for the seats for a requested day. I want to display the seats and show which ones are free/reserved for the day X.
The ways I tried to achieve it:</p>

<pre class="lang-cs prettyprint-override"><code>        var seats = _dbContext.Seats
             .Include(s => s.Reservations.Where(r => r.DateTime.Date == dateParam.Date));
        // InvalidOperationException: 'Lambda expression used
        // inside Include is not valid.'
</code>```

Sample

       var seats = _dbContext.Seats
             .Include(s => s.Reservations)
             .Where(r => r.Reservations.Any(r => r.DateTime.Date == dateParam.Date));
        // Gets the seats which meet the condition. I want these, but also I want the free seats
```

<p>Sample</p>

<pre class="lang-cs prettyprint-override"><code>        var seatsFiltered = _dbContext.Seats
             .Include(t => t.Reservations)
             .Where(r => r.Reservations.Any(r => r.DateTime.Date == dateParam.Date))
             .ToList();

        var seats = _dbContext.Seats
             .ToList()
             .Select(x => { x.Reservations = new List<Reservation>(); return x; })
             .Concat(seatsFiltered);
        // Not optimal since I obviously ToList twice
        // In the end I get an empty list

        return (ICollection<Seat>)seats;
</code>```

EDIT: Add sample data as requested:

Seats

```<code>Id|AreaId|
--|------|
 1|3     |
 2|3     |
 3|3     |
 4|3     |
 5|3     |
 6|3     |
 7|3     |
 8|3     |
</code>```

Reservations

```<code>Id|SeatId|Name|Phone|DateTime           |
--|------|----|-----|-------------------|
 7|     1|    |     |2020-02-15 20:30:00|
 8|     1|    |     |2020-02-21 12:00:00|
 9|     1|    |     |2020-02-23 09:00:00|
10|     2|    |     |2020-02-15 20:30:00|
11|     2|    |     |2020-02-21 12:00:00|
12|     2|    |     |2020-02-23 09:00:00|
13|     4|    |     |2020-02-21 12:00:00|
15|     7|    |     |2020-02-15 20:30:00|
16|     7|    |     |2020-02-21 12:00:00|
17|     8|    |     |2020-02-21 12:00:00|
14|     8|    |     |2020-02-23 09:00:00|
18|     3|    |     |2020-02-15 20:30:00|
19|     3|    |     |2020-02-21 12:00:00|
20|     3|    |     |2020-02-23 09:00:00|
</code>```

When I tried the code by Phong, I got the following error:

System.InvalidOperationException: 'The LINQ expression '(GroupByShaperExpression:
  KeySelector: (r.SeatId),
  ElementSelector:(EntityShaperExpression:
      EntityType: Reservation
      ValueBufferExpression:
          (ProjectionBindingExpression: EmptyProjectionMember)
      IsNullable: False
  )
  )
      .ToList()' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.'

答:
Phong's solution might be absolutely valid and useful but since I couldn't understand it myself and apply it, I used this method

var seats = _dbContext.Seats.ToList();
var reservations = _dbContext.Reservations.Where(r => r.DateTime.Day == dateTime.Day).ToList();

foreach (var seat in seats)
{
    seat.Reservations = reservations.Where(r => r.SeatId == seat.Id).ToList();
}
```

I still believe there's also a LINQ one-liner that can do this, without the performance hit of .ToList()-ing every collection but I couldn't figure it out :)

Body:
I have these two models:

    public class Seat
    {
        public int Id { get; set; }
        public ICollection<Reservation> Reservations { get; set; }
    //..
    }

    public class Reservation
    {
        public int Id { get; set; }
        public int SeatId { get; set; }
        public Seat Seat { get; set; }
        public DateTime DateTime { get; set; }
        //..
    }

Say a seat has a reservations for every day of the week. I want to make a query that takes the seats and filters the reservations for the seats for a requested day. I want to display the seats and show which ones are free/reserved for the day X.
The ways I tried to achieve it:

        var seats = _dbContext.Seats
             .Include(s => s.Reservations.Where(r => r.DateTime.Date == dateParam.Date));
        // InvalidOperationException: 'Lambda expression used
        // inside Include is not valid.'

Sample

       var seats = _dbContext.Seats
             .Include(s => s.Reservations)
             .Where(r => r.Reservations.Any(r => r.DateTime.Date == dateParam.Date));
        // Gets the seats which meet the condition. I want these, but also I want the free seats

Sample

        var seatsFiltered = _dbContext.Seats
             .Include(t => t.Reservations)
             .Where(r => r.Reservations.Any(r => r.DateTime.Date == dateParam.Date))
             .ToList();

        var seats = _dbContext.Seats
             .ToList()
             .Select(x => { x.Reservations = new List<Reservation>(); return x; })
             .Concat(seatsFiltered);
        // Not optimal since I obviously ToList twice
        // In the end I get an empty list

        return (ICollection<Seat>)seats;

EDIT: Add sample data as requested:

Seats

Id|AreaId|
--|------|
 1|3     |
 2|3     |
 3|3     |
 4|3     |
 5|3     |
 6|3     |
 7|3     |
 8|3     |

Reservations

Id|SeatId|Name|Phone|DateTime           |
--|------|----|-----|-------------------|
 7|     1|    |     |2020-02-15 20:30:00|
 8|     1|    |     |2020-02-21 12:00:00|
 9|     1|    |     |2020-02-23 09:00:00|
10|     2|    |     |2020-02-15 20:30:00|
11|     2|    |     |2020-02-21 12:00:00|
12|     2|    |     |2020-02-23 09:00:00|
13|     4|    |     |2020-02-21 12:00:00|
15|     7|    |     |2020-02-15 20:30:00|
16|     7|    |     |2020-02-21 12:00:00|
17|     8|    |     |2020-02-21 12:00:00|
14|     8|    |     |2020-02-23 09:00:00|
18|     3|    |     |2020-02-15 20:30:00|
19|     3|    |     |2020-02-21 12:00:00|
20|     3|    |     |2020-02-23 09:00:00|

When I tried the code by Phong, I got the following error:

System.InvalidOperationException: 'The LINQ expression '(GroupByShaperExpression:
  KeySelector: (r.SeatId),
  ElementSelector:(EntityShaperExpression:
      EntityType: Reservation
      ValueBufferExpression:
          (ProjectionBindingExpression: EmptyProjectionMember)
      IsNullable: False
  )
  )
      .ToList()' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.'

Body:
Phong's solution might be absolutely valid and useful but since I couldn't understand it myself and apply it, I used this method

var seats = _dbContext.Seats.ToList();
var reservations = _dbContext.Reservations.Where(r => r.DateTime.Day == dateTime.Day).ToList();

foreach (var seat in seats)
{
    seat.Reservations = reservations.Where(r => r.SeatId == seat.Id).ToList();
}

I still believe there's also a LINQ one-liner that can do this, without the performance hit of .ToList()-ing every collection but I couldn't figure it out :)


问:
What is the difference between a volume and persistent volume?
I've previously used both types, I've also read through the docs at:

https://kubernetes.io/docs/concepts/storage/persistent-volumes/
https://kubernetes.io/docs/concepts/storage/volumes/

However it's still not clear what the difference is, both seem to support the same storage types, the only thing that comes to mind is there seems to be a 'provisioning' aspect to persistent volumes.

What is the practical difference?
Are there advantages / disadvantages between the two - or for what use case would one be better suited to than the other?

Is it perhaps just 'synctactic sugar'?

For example NFS could be mounted as a volume, or a persistent volume. Both require a NFS server, both will have it's data 'persisted' between mounts. What difference would be had in this situation?

答:
They are two different implementations which can provide some similar common functionality (hence a lot of confusion).

Persistent volumes:

Support storage provisioned via StorageClass

Does not support emptyDir volume type (https://github.com/kubernetes/kubernetes/issues/75378)

Volumes:

Are bound to a pod

Are simpler to define (less Kubernetes resources required)


问:
Laravel Gate::any() returns reverted value
I am defining gate in my code like this

```<code>    Gate::define('fullAccess',function ($user){
        return $user->id == 1;
    });
    Gate::define('manager',function ($user){
        return $user->type == User::TYPE_MANAGER;
    });
</code>```

then in contoller I am checking if user has access

```<code> public function __construct()
 {
     if(!Gate::any(['fullAccess','manager'])){
         abort(403);
     }
 }
</code>```

But there is a problem:

```<code> if(!Gate::any(['fullAccess','manager'])){
     //returns true
 }
 if(Gate::any(['fullAccess','manager'])){
     //returns false
 }
</code>```

I'm absolutly sure my ID equals 1, and I think any() function must return true if at least one access action is available for curent user. Am I missing something?

I've tried none function also, and it works the same way

```<code> if(Gate::none(['fullAccess','manager'])){
    //returns true;
 }
</code>```

答:
As I've stated in the comment, checking things in a constructor is usually not safe and can result in unexpected order of execution. The solution for the OP's problem is to move the access check out from constructor to some controller function or elsewhere. Cheers :)

UPD with code example:
You override callAction method to check access before every action in controller

```<code>public function callAction($method, $parameters)
{
    if(Gate::none(['fullAccess','manager'])){
        abort(403);
    }
    return parent::callAction($method, $parameters);
}
</code>```

Body:
I am defining gate in my code like this

    Gate::define('fullAccess',function ($user){
        return $user->id == 1;
    });
    Gate::define('manager',function ($user){
        return $user->type == User::TYPE_MANAGER;
    });

then in contoller I am checking if user has access

 public function __construct()
 {
     if(!Gate::any(['fullAccess','manager'])){
         abort(403);
     }
 }

But there is a problem:

 if(!Gate::any(['fullAccess','manager'])){
     //returns true
 }
 if(Gate::any(['fullAccess','manager'])){
     //returns false
 }

I'm absolutly sure my ID equals 1, and I think any() function must return true if at least one access action is available for curent user. Am I missing something?

I've tried none function also, and it works the same way

 if(Gate::none(['fullAccess','manager'])){
    //returns true;
 }

Body:
As I've stated in the comment, checking things in a constructor is usually not safe and can result in unexpected order of execution. The solution for the OP's problem is to move the access check out from constructor to some controller function or elsewhere. Cheers :)

UPD with code example:
You override callAction method to check access before every action in controller

public function callAction($method, $parameters)
{
    if(Gate::none(['fullAccess','manager'])){
        abort(403);
    }
    return parent::callAction($method, $parameters);
}


问:
How can I designate a comment box in WordPress to use a particular plugin
I have a plugin installed on my wordpress blog that takes the email address and message and creates a new user on my other CMS platform. Problem is this effects all comment boxes. I want to re-work this plugin to check if its on a particular page if so some values would be different. If not then proceed like usual.

```<code>function ifcj_createUser_SFI($comment_id) {

# determine commenters email
global $wpdb;
$sql = "SELECT comment_author_email FROM $wpdb->comments WHERE comment_ID = $comment_id";

$userEmail = $wpdb->get_var($sql);

if ( $userEmail == NULL ) {
    return false;
}

# pull in class file
require( ABSPATH . 'class.convio_api.php');

# create instance and connection with convio, ALWAYS REQUIRED
$c = new ConvioAPI('site_id=xxx&api_key=xxxxxx&login_name=xxx@xxx.org&login_password=xxxxx');

# add user to groups/interests (this can be done when creating the user also)
$c->createUpdateUser('primary_email='.$userEmail.'&add_group_ids=73663&add_interest_ids=3761');

return true;

}

add_action('comment_post','ifcj_createUser_SFI',0,1);
</code>```

Thanks in advance.

答:
Use conditional tags: http://codex.wordpress.org/Conditional_Tags

Here is how you would test for a certain page: http://codex.wordpress.org/Conditional_Tags#A_PAGE_Page

Like:

```<code>if ( is_page( '2' ) ) {
    return false;
}
</code>```

Body:
I have a plugin installed on my wordpress blog that takes the email address and message and creates a new user on my other CMS platform. Problem is this effects all comment boxes. I want to re-work this plugin to check if its on a particular page if so some values would be different. If not then proceed like usual.

function ifcj_createUser_SFI($comment_id) {

# determine commenters email
global $wpdb;
$sql = "SELECT comment_author_email FROM $wpdb->comments WHERE comment_ID = $comment_id";

$userEmail = $wpdb->get_var($sql);

if ( $userEmail == NULL ) {
    return false;
}

# pull in class file
require( ABSPATH . 'class.convio_api.php');

# create instance and connection with convio, ALWAYS REQUIRED
$c = new ConvioAPI('site_id=xxx&api_key=xxxxxx&login_name=xxx@xxx.org&login_password=xxxxx');

# add user to groups/interests (this can be done when creating the user also)
$c->createUpdateUser('primary_email='.$userEmail.'&add_group_ids=73663&add_interest_ids=3761');

return true;

}

add_action('comment_post','ifcj_createUser_SFI',0,1);

Thanks in advance.

Body:
Use conditional tags: http://codex.wordpress.org/Conditional_Tags

Here is how you would test for a certain page: http://codex.wordpress.org/Conditional_Tags#A_PAGE_Page

Like:

if ( is_page( '2' ) ) {
    return false;
}


问:
Python itertools permutations without repetitions
I have a string show the step going in m x n grid like this problem:
https://leetcode.com/problems/unique-paths/

```<code>step = 'DDRR'
</code>```

D mean go Down and R mean go to Right
I want to show permutations without replacement, and i found the itertools built-in on Python.But it's say:

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values.

So that when I using itertools.permutation(step,4), it's contain many replications.

```<code>>>> itertools.permutations(step,4)
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'D', 'R', 'R')
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'R', 'D', 'D')
('R', 'R', 'D', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'R', 'D', 'D')
('R', 'R', 'D', 'D')
</code>```

I want something like:

```<code>('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('R', 'R', 'D', 'D')
</code>```

I found some answer using set(itertools.permutations(step,4)), but because apply set() method, the itertools.permutation() method still calculate all possibilities. Is there anyway to avoid it, or is there any built-in function can do permutation without repetitions in Python?

答:
To get the answer you need, you could use multiset_permutations

```<code>>>> from sympy.utilities.iterables import multiset_permutations
>>> from pprint import pprint
>>> pprint(list(multiset_permutations(['D','D','R','R'])))
[['D', 'D', 'R', 'R'],
 ['D', 'R', 'D', 'R'],
 ['D', 'R', 'R', 'D'],
 ['R', 'D', 'D', 'R'],
 ['R', 'D', 'R', 'D'],
 ['R', 'R', 'D', 'D']]
</code>```

To get just the total number, use factorial of number of items divided by the product of factorials for the count of each unique item. Here there are 2 D's and 2 R's

```<code>>>> from math import factorial
>>> factorial(4)//(factorial(2)*factorial(2))
6
</code>```

Body:
I have a string show the step going in m x n grid like this problem:
https://leetcode.com/problems/unique-paths/

step = 'DDRR'

D mean go Down and R mean go to Right
I want to show permutations without replacement, and i found the itertools built-in on Python.But it's say:

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values.

So that when I using itertools.permutation(step,4), it's contain many replications.

>>> itertools.permutations(step,4)
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'D', 'R', 'R')
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'R', 'D', 'D')
('R', 'R', 'D', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'R', 'D', 'D')
('R', 'R', 'D', 'D')

I want something like:

('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('R', 'R', 'D', 'D')

I found some answer using set(itertools.permutations(step,4)), but because apply set() method, the itertools.permutation() method still calculate all possibilities. Is there anyway to avoid it, or is there any built-in function can do permutation without repetitions in Python?

Body:
To get the answer you need, you could use multiset_permutations

>>> from sympy.utilities.iterables import multiset_permutations
>>> from pprint import pprint
>>> pprint(list(multiset_permutations(['D','D','R','R'])))
[['D', 'D', 'R', 'R'],
 ['D', 'R', 'D', 'R'],
 ['D', 'R', 'R', 'D'],
 ['R', 'D', 'D', 'R'],
 ['R', 'D', 'R', 'D'],
 ['R', 'R', 'D', 'D']]

To get just the total number, use factorial of number of items divided by the product of factorials for the count of each unique item. Here there are 2 D's and 2 R's

>>> from math import factorial
>>> factorial(4)//(factorial(2)*factorial(2))
6


问:
how to sort list in alphabetical order in python?
I have a program where I take in a txt file and break up the text into individual words and puts them into a list. the next part is to sort the list alphabetically and print it.

so far I have a text file that just says:
 "the quick brown fox jumps over the lazy dog"

and my program so far looks like:

```<code>file = input("Enter File Name: ")
myList =[]

readFile = open(file, 'r')

for line in readFile:
    myList.append(line.split(" "))

myList.sort()

print(myList)
</code>```

the problem is that when I run the program the list is being created and filled with each word but when it is printed out it is not being sorted in alphabetical order. I also tried print(myList.sort()) and the only thing that prints is "none"

答:
You should probably read the whole file rather than one line at a time:

```<code>with open(filename) as f:
    words = f.read().split()
words.sort()
</code>```

This uses the default for split which splits on a space, line break or any other whitespace.

Body:
I have a program where I take in a txt file and break up the text into individual words and puts them into a list. the next part is to sort the list alphabetically and print it.

so far I have a text file that just says:
 "the quick brown fox jumps over the lazy dog"

and my program so far looks like:

file = input("Enter File Name: ")
myList =[]

readFile = open(file, 'r')

for line in readFile:
    myList.append(line.split(" "))

myList.sort()

print(myList)

the problem is that when I run the program the list is being created and filled with each word but when it is printed out it is not being sorted in alphabetical order. I also tried print(myList.sort()) and the only thing that prints is "none"

Body:
You should probably read the whole file rather than one line at a time:

with open(filename) as f:
    words = f.read().split()
words.sort()

This uses the default for split which splits on a space, line break or any other whitespace.


Title: Renaming integers within a data.frame

Body:
Using R...

I have a data.frame with five variables.

One of the variables colr has values ranging from 1 to 5.

Defined as an integer with values   1, 2, 3, 4, and 5.

Problem: I would like to build a regression model where the values within colr, the integers 1,2,3,4, and 5 are reported as independent variables with the following names.

1 = Silver,
2 = Blue,
3 = Pink,
4 = Other than Silver, Blue or Pink,
5 = Color Not Reported.

Question: Is there a way to extract or rename these values in a way that is different from the following (as this process does not rename, eg. 1 to Silver in the summary regression output):

lm(dependent variable ~ + I(colr.f == 1) +
                          I(colr.f == 2) +
                          I(colr.f == 3) +
                          I(colr.f == 4) +
                          I(colr.f == 5),
                          data = df)

I am open to any method that would allow me to create and name these different values independently but would prefer to see if there is a way to do so using the tidyverse or dplyr as this is something I have to do frequently when building multivariate models.

Thank you for any help.

Body:
If you have this:

df <- data.frame(int = sample(5, 20, TRUE), value = rnorm(20))
df
#>    int       value
#> 1    3 -0.62042198
#> 2    4  0.85009260
#> 3    5 -1.04971518
#> 4    1 -2.58255471
#> 5    1  0.62357772
#> 6    4  0.00286785
#> 7    4 -0.05981318
#> 8    4  0.72961261
#> 9    4 -0.03156315
#> 10   1 -2.05486209
#> 11   5  1.77099554
#> 12   1  1.02790956
#> 13   1 -0.70354012
#> 14   1  0.27353731
#> 15   2 -0.04817215
#> 16   2  0.17151374
#> 17   5 -0.54824346
#> 18   2  0.41123284
#> 19   5  0.05466070
#> 20   1 -0.41029986

You can do this:

library(tidyverse)

df <- df %>% mutate(color = factor(c("red", "green", "orange", "blue", "pink"))[int])
df
#>    int       value  color
#> 1    3 -0.62042198 orange
#> 2    4  0.85009260   blue
#> 3    5 -1.04971518   pink
#> 4    1 -2.58255471    red
#> 5    1  0.62357772    red
#> 6    4  0.00286785   blue
#> 7    4 -0.05981318   blue
#> 8    4  0.72961261   blue
#> 9    4 -0.03156315   blue
#> 10   1 -2.05486209    red
#> 11   5  1.77099554   pink
#> 12   1  1.02790956    red
#> 13   1 -0.70354012    red
#> 14   1  0.27353731    red
#> 15   2 -0.04817215  green
#> 16   2  0.17151374  green
#> 17   5 -0.54824346   pink
#> 18   2  0.41123284  green
#> 19   5  0.05466070   pink
#> 20   1 -0.41029986    red

Which allows a regression like this:

lm(value ~ color, data = df) %>% summary()
#>
#> Call:
#> lm(formula = value ~ color, data = df)
#>
#> Residuals:
#>      Min       1Q   Median       3Q      Max
#> -2.03595 -0.33687 -0.00447  0.46149  1.71407
#>
#> Coefficients:
#>             Estimate Std. Error t value Pr(>|t|)
#> (Intercept)   0.2982     0.4681   0.637    0.534
#> colorgreen   -0.1200     0.7644  -0.157    0.877
#> colororange  -0.9187     1.1466  -0.801    0.436
#> colorpink    -0.2413     0.7021  -0.344    0.736
#> colorred     -0.8448     0.6129  -1.378    0.188
#>
#> Residual standard error: 1.047 on 15 degrees of freedom
#> Multiple R-squared:  0.1451, Adjusted R-squared:  -0.0829
#> F-statistic: 0.6364 on 4 and 15 DF,  p-value: 0.6444

Created on 2020-02-16 by the reprex package (v0.3.0)


问:
How can i make pointer to a template function?
I have a template sort function that takes pointer to another function as a paramater to define sorting rule.

```<code>template<typename T>
void sort(T* arr, int size, function<bool(T, T)>& comparer);
</code>```

and i want to call this function with lambda expression

```<code>sort(arr, size, [](int num1, int num2) { if (num1 > num2) { return true; } else { return false; } });
</code>```

However i had an error:

Error (active) E0304   no instance of overloaded function "sort" matches the argument list

Is there a way to create pointer to template function? How can i do this?

答:
Template argument deduction will try to deduce T from both the first parameter T* arr and the third one function<bool(T, T)>& comparer.

This will fail, because the lambda doesn't actually have type function<bool(T, T)> for any T. (It can only be converted to one.)

In function templates function objects are usually taken directly by a template parameter, not as std::function:

```<code>template<typename T, typename F>
void sort(T* arr, int size, F comparer);
</code>```

or

```<code>template<typename T, typename F>
void sort(T* arr, int size, F&& comparer);
</code>```

depending on whether you want a copy of the function object or just a reference.

Body:
I have a template sort function that takes pointer to another function as a paramater to define sorting rule.

template<typename T>
void sort(T* arr, int size, function<bool(T, T)>& comparer);

and i want to call this function with lambda expression

sort(arr, size, [](int num1, int num2) { if (num1 > num2) { return true; } else { return false; } });

However i had an error:

Error (active) E0304   no instance of overloaded function "sort" matches the argument list

Is there a way to create pointer to template function? How can i do this?

Body:
Template argument deduction will try to deduce T from both the first parameter T* arr and the third one function<bool(T, T)>& comparer.

This will fail, because the lambda doesn't actually have type function<bool(T, T)> for any T. (It can only be converted to one.)

In function templates function objects are usually taken directly by a template parameter, not as std::function:

template<typename T, typename F>
void sort(T* arr, int size, F comparer);

or

template<typename T, typename F>
void sort(T* arr, int size, F&& comparer);

depending on whether you want a copy of the function object or just a reference.


问:
How to set navigator.webdriver to undefined with Selenium for Firefox (geckodriver)
I am trying to set the navigator.webdriver variable in the Firefox browser to undefined using Selenium in Python.

I have been able to successfully do this when using Chrome, but now I need to do the same thing using in Firefox. When using the Firefox webdriver, execute_cdp_cmd(...) does not exist.

Does anyone know how to do the same thing using the firefox webdriver instead of the chrome webdriver?

Please see the relevant code below.

```<code>driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": """
        Object.defineProperty(navigator, 'webdriver', {
            get: () => undefined
        })
    """
})
</code>```

答:
I have since found a solution to my problem. The code below will set "navigator.webdriver" to undefined in a Firefox browser being run by Selenium.</p>

```<code>profile.set_preference("dom.webdriver.enabled", False)
</code>```

Body:
I am trying to set the navigator.webdriver variable in the Firefox browser to undefined using Selenium in Python.

I have been able to successfully do this when using Chrome, but now I need to do the same thing using in Firefox. When using the Firefox webdriver, execute_cdp_cmd(...) does not exist.

Does anyone know how to do the same thing using the firefox webdriver instead of the chrome webdriver?

Please see the relevant code below.

driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": """
        Object.defineProperty(navigator, 'webdriver', {
            get: () => undefined
        })
    """
})

Body:
I have since found a solution to my problem. The code below will set "navigator.webdriver" to undefined in a Firefox browser being run by Selenium.

profile.set_preference("dom.webdriver.enabled", False)


答:
You probably want to take a const reference.

You have convert to std::function explicitly.

```<code>#include <functional>

template <typename T>
void sort(T* arr, int size, std::function<bool(T, T)> const & comparer)
{
        // sort
}

int main()
{
    int const size = 10;
    int arr[size];
    sort(arr, size, std::function{[](int num1, int num2) {
        if (num1 > num2) {
            return true;
        } else {
            return false;
        }
    }});
}
</code>```

If you can change the signature of sort, see walnut's answer.

Title: How can i make pointer to a template function?

Body:
You probably want to take a const reference.

You have convert to std::function explicitly.

#include <functional>

template <typename T>
void sort(T* arr, int size, std::function<bool(T, T)> const & comparer)
{
        // sort
}

int main()
{
    int const size = 10;
    int arr[size];
    sort(arr, size, std::function{[](int num1, int num2) {
        if (num1 > num2) {
            return true;
        } else {
            return false;
        }
    }});
}

If you can change the signature of sort, see walnut's answer.


问:
Invalid parameter rf for estimator Pipeline
I am using RandomForestRegressor with  GridSearchCV.
I'm getting this error:

```<code>   ValueError: Invalid parameter RandomForestRegressor for estimator Pipeline
</code>```

I don't understand why.
This is my code:

```<code> pipelines = {
        'rf': make_pipeline(StandardScaler(),
                            RandomForestRegressor(random_state=42)),

rf_hyperparameters = {
    'RandomForestRegressor__n_estimators': [100, 200, 300, 400, 500],
    'RandomForestRegressor__max_features': ['auto', 'sqrt', 0.33]
    }

hyperparameters = {
    'rf': rf_hyperparameters,
}

fitted_alternative_models = {}
for name, pipeline in pipelines.items():
    alt_model = GridSearchCV(pipeline, hyperparameters[name], cv=10, n_jobs=-1)
    alt_model.fit(X_train, y_train.values.ravel())
</code>```

Thanks!

答:
I changed:

```<code>rf_hyperparameters = {
    'RandomForestRegressor__n_estimators': [100, 200, 300, 400, 500],
    'RandomForestRegressor__max_features': ['auto', 'sqrt', 0.33]
    }
</code>```

to:

```<code>rf_hyperparameters = {
     'randomforestregressor__n_estimators': [100, 200, 300, 400, 500],
     'randomforestregressor__max_features': ['auto', 'sqrt', 0.33]
}
</code>```

and it's working.

Body:
I am using RandomForestRegressor with  GridSearchCV.
I'm getting this error:

   ValueError: Invalid parameter RandomForestRegressor for estimator Pipeline

I don't understand why.
This is my code:

 pipelines = {
        'rf': make_pipeline(StandardScaler(),
                            RandomForestRegressor(random_state=42)),

rf_hyperparameters = {
    'RandomForestRegressor__n_estimators': [100, 200, 300, 400, 500],
    'RandomForestRegressor__max_features': ['auto', 'sqrt', 0.33]
    }

hyperparameters = {
    'rf': rf_hyperparameters,
}

fitted_alternative_models = {}
for name, pipeline in pipelines.items():
    alt_model = GridSearchCV(pipeline, hyperparameters[name], cv=10, n_jobs=-1)
    alt_model.fit(X_train, y_train.values.ravel())

Thanks!

Body:
I changed:

rf_hyperparameters = {
    'RandomForestRegressor__n_estimators': [100, 200, 300, 400, 500],
    'RandomForestRegressor__max_features': ['auto', 'sqrt', 0.33]
    }

to:

rf_hyperparameters = {
     'randomforestregressor__n_estimators': [100, 200, 300, 400, 500],
     'randomforestregressor__max_features': ['auto', 'sqrt', 0.33]
}

and it's working.


问:
Unset/Forget/Repalce a user git Credential.Helper and remember new one
I am only able to able to unset (temporarily) my credentials with following

git config credential.helper ""

This overrides the store option and every time i am asked for username password but it is not a solution because I want to store my new credentials but as soon as i apply

```<code>git config credential.helper store
</code>```

It again stores the unwanted remembered user (Muha****) please see screenshots and I am stuck again to push to my repo, please help me to get rid of that remembered username

What config I have now is

I studied and followed almost everything relevant given in following answers

How do I update the password for Git?

How to change my Git username in terminal?

https://askubuntu.com/questions/206449/git-config-global-file-remove-settings

But never able to forget/replace completely my old user (Muha***)

答:
The easiest way to delete credentials for Git is to run a command like the following, which tells whatever credential helper you're using that the password is invalid and it should delete it:

```<code>$ echo url=https://bk2204@github.com | git credential reject
</code>```

Your URL must have the proper scheme, username, and host, but generally need not have the remainder of the URL (unless you've set credential.useHTTPpath) or the password.  This should work anywhere the credential helper speaks the protocol correctly, although it is known that the Git Credential Manager for Windows is broken in this regard.

Once you delete the existing username and password, you'll be prompted again the next time and can enter a new username and password.  Note that if you need to have two different usernames for the same domain, the easiest way to do that is to put the username in the remote URL, and the credential manager will automatically fill in the right password for the right user.

Body:
I am only able to able to unset (temporarily) my credentials with following

git config credential.helper ""

This overrides the store option and every time i am asked for username password but it is not a solution because I want to store my new credentials but as soon as i apply

git config credential.helper store

It again stores the unwanted remembered user (Muha****) please see screenshots and I am stuck again to push to my repo, please help me to get rid of that remembered username

What config I have now is

I studied and followed almost everything relevant given in following answers

How do I update the password for Git?

How to change my Git username in terminal?

https://askubuntu.com/questions/206449/git-config-global-file-remove-settings

But never able to forget/replace completely my old user (Muha***)

Body:
The easiest way to delete credentials for Git is to run a command like the following, which tells whatever credential helper you're using that the password is invalid and it should delete it:

$ echo url=https://bk2204@github.com | git credential reject

Your URL must have the proper scheme, username, and host, but generally need not have the remainder of the URL (unless you've set credential.useHTTPpath) or the password.  This should work anywhere the credential helper speaks the protocol correctly, although it is known that the Git Credential Manager for Windows is broken in this regard.

Once you delete the existing username and password, you'll be prompted again the next time and can enter a new username and password.  Note that if you need to have two different usernames for the same domain, the easiest way to do that is to put the username in the remote URL, and the credential manager will automatically fill in the right password for the right user.


问:
How do I use url_for in wtf before the app has initialized?
I was wondering how I could use the url_for() function from flask in an wtf form class before the app has initialized.
My form class looks like this:

```<code>class UserRegisterForm(FlaskForm):
    accept_terms = BooleanField(
        "I have read the <a href=\"{{ url_for('terms_of_service') }}\">terms of service</a><br> and I
        agree with them.", validators=[DataRequired()])
</code>```

Now, you see, I'm trying to use url_for() function in the label text. Unfortunately that does not work.
I am not able to use the function outside of the label because the I get an rumtime error, because I'm using the function before the website is getting generated.
Who has a solution for this?

答:
You could create the url outside of the label:</p>

```<code>terms_url = url_for('terms_of_service')

accept_terms = BooleanField(f"I have read the {terms_url}...")
</code>```

Body:
I was wondering how I could use the url_for() function from flask in an wtf form class before the app has initialized.
My form class looks like this:

class UserRegisterForm(FlaskForm):
    accept_terms = BooleanField(
        "I have read the terms of service
 and I
        agree with them.", validators=[DataRequired()])

Now, you see, I'm trying to use url_for() function in the label text. Unfortunately that does not work.
I am not able to use the function outside of the label because the I get an rumtime error, because I'm using the function before the website is getting generated.
Who has a solution for this?

Body:
You could create the url outside of the label:

terms_url = url_for('terms_of_service')

accept_terms = BooleanField(f"I have read the {terms_url}...")


问:
SQL Query Involving Finding Most Frequent Tuple Value in Column
I have the following relations:

teaches(ID,course_id,sec_id,semester,year)

instructor(ID,name,dept_name,salary)

I am trying to express the following as an SQL query:

Find the ID and name of the instructor who has taught the most courses(i.e has the most tuples in teaches).

My Query

```<code>select ID, name
from teaches
  natural join instructor
group by ID
order by count(*) desc
</code>```

I know this isn't correct, but I feel like I'm on the right track. In order to answer the question, you need to work with both relations, hence the natural join operation is required. Since the question asks for the instructor that has taught the most courses, that tells me that we are trying to count the number of times each instructor ID appears in the teaches relation. From what I understand, we are looking to count distinct instructor IDs, hence the group by command is needed.

答:
Don't use natural joins: all they do is rely on column names to decide which columns relate across tables (they don't check for foreign keys constraints or the-like, as you would thought). This is unreliable by nature.

You can use a regular inner join:

```<code>select i.id, i.name
from teaches t
inner join instructor i on i.id = t.sec_id
group by i.id, i.name
order by count(*) desc
limit 1
</code>```

Notes:

this assumes that column teaches.sec_id relates to instructor.id (I cannot see which other column could be used)

I added a limit clause to the query since you stated that you want the top instructor - the syntax may vary across databases

always prefix the column names with the table they belong to, to make the query unambiguous and easier to understand

it is a good practice (and a requirement in many databases) that in an aggregate query all non-aggregared columns listed in the select clause should appear in the group by clause; I added the instructur name to your group by clause

Body:
I have the following relations:

teaches(ID,course_id,sec_id,semester,year)

instructor(ID,name,dept_name,salary)

I am trying to express the following as an SQL query:

Find the ID and name of the instructor who has taught the most courses(i.e has the most tuples in teaches).

My Query

select ID, name
from teaches
  natural join instructor
group by ID
order by count(*) desc

I know this isn't correct, but I feel like I'm on the right track. In order to answer the question, you need to work with both relations, hence the natural join operation is required. Since the question asks for the instructor that has taught the most courses, that tells me that we are trying to count the number of times each instructor ID appears in the teaches relation. From what I understand, we are looking to count distinct instructor IDs, hence the group by command is needed.

Body:
Don't use natural joins: all they do is rely on column names to decide which columns relate across tables (they don't check for foreign keys constraints or the-like, as you would thought). This is unreliable by nature.

You can use a regular inner join:

select i.id, i.name
from teaches t
inner join instructor i on i.id = t.sec_id
group by i.id, i.name
order by count(*) desc
limit 1

Notes:

this assumes that column teaches.sec_id relates to instructor.id (I cannot see which other column could be used)

I added a limit clause to the query since you stated that you want the top instructor - the syntax may vary across databases

always prefix the column names with the table they belong to, to make the query unambiguous and easier to understand

it is a good practice (and a requirement in many databases) that in an aggregate query all non-aggregared columns listed in the select clause should appear in the group by clause; I added the instructur name to your group by clause


问:
How to open/save docx file to be aditted as xml and save the result as docx after editting using python
I have a docx file in which I need to edit its paragraphs (the paragraphs might contain equations). I tried to do these jobs using python-docx but it was not successful since editing the text of each paragraph and replacing it with the edited new paragraph needs to call p.add_paragraphs(editText(paragraph.text)) which ignores and omits any mathematical equation.

By searching for a method to gain this goal I found that this job is possible through XML codes by finding <w:t> tags and editing their content like this:

```<code>tree= ET.parse(filename)
root=tree.getroot()

for par in root.findall('w:p'):
   if par.find('w:r'):
   myText= par.find('w:r').find('w:t')
   myText.text= editText(myText.text)
</code>```

Then I must save the result as docx.
My quation is: what the format of filename is? should it be a document.xml file? If so, how can I reach that from my original document.docx file? and one more question is that how can I save the result as a .docx file again?

For saving docx as xml, I have given a try to save it by document.save('Document2.xml'). But the content of the result was not correct.

Would you give me some advice how to do them?

答:
Not experienced with this at all, but perhaps this is what you were looking for?
https://virantha.com/2013/08/16/reading-and-writing-microsoft-word-docx-files-with-python/
From the article:

import zipfile
from lxml import etree
class DocsWriter:
    def __init__(self, docx_file):
        self.zipfile = zipfile.ZipFile(docx_file)

    def _write_and_close_docx (self, xml_content, output_filename):
        """ Create a temp directory, expand the original docx zip.
            Write the modified xml to word/document.xml
            Zip it up as the new docx
        """

        tmp_dir = tempfile.mkdtemp()

        self.zipfile.extractall(tmp_dir)

        with open(os.path.join(tmp_dir,'word/document.xml'), 'w') as f:
            xmlstr = etree.tostring (xml_content, pretty_print=True)
            f.write(xmlstr)

        # Get a list of all the files in the original docx zipfile
        filenames = self.zipfile.namelist()
        # Now, create the new zip file and add all the filex into the archive
        zip_copy_filename = output_filename
        with zipfile.ZipFile(zip_copy_filename, "w") as docx:
            for filename in filenames:
                docx.write(os.path.join(tmp_dir,filename), filename)

        # Clean up the temp dir
        shutil.rmtree(tmp_dir)
```

From what I can tell, this code block writes an xml document as .docx. Refer to the article for more context.

Body:
I have a docx file in which I need to edit its paragraphs (the paragraphs might contain equations). I tried to do these jobs using python-docx but it was not successful since editing the text of each paragraph and replacing it with the edited new paragraph needs to call p.add_paragraphs(editText(paragraph.text)) which ignores and omits any mathematical equation.

By searching for a method to gain this goal I found that this job is possible through XML codes by finding <w:t> tags and editing their content like this:

tree= ET.parse(filename)
root=tree.getroot()

for par in root.findall('w:p'):
   if par.find('w:r'):
   myText= par.find('w:r').find('w:t')
   myText.text= editText(myText.text)

Then I must save the result as docx.
My quation is: what the format of filename is? should it be a document.xml file? If so, how can I reach that from my original document.docx file? and one more question is that how can I save the result as a .docx file again?

For saving docx as xml, I have given a try to save it by document.save('Document2.xml'). But the content of the result was not correct.

Would you give me some advice how to do them?

Body:
Not experienced with this at all, but perhaps this is what you were looking for?
https://virantha.com/2013/08/16/reading-and-writing-microsoft-word-docx-files-with-python/
From the article:

import zipfile
from lxml import etree
class DocsWriter:
    def __init__(self, docx_file):
        self.zipfile = zipfile.ZipFile(docx_file)

    def _write_and_close_docx (self, xml_content, output_filename):
        """ Create a temp directory, expand the original docx zip.
            Write the modified xml to word/document.xml
            Zip it up as the new docx
        """

        tmp_dir = tempfile.mkdtemp()

        self.zipfile.extractall(tmp_dir)

        with open(os.path.join(tmp_dir,'word/document.xml'), 'w') as f:
            xmlstr = etree.tostring (xml_content, pretty_print=True)
            f.write(xmlstr)

        # Get a list of all the files in the original docx zipfile
        filenames = self.zipfile.namelist()
        # Now, create the new zip file and add all the filex into the archive
        zip_copy_filename = output_filename
        with zipfile.ZipFile(zip_copy_filename, "w") as docx:
            for filename in filenames:
                docx.write(os.path.join(tmp_dir,filename), filename)

        # Clean up the temp dir
        shutil.rmtree(tmp_dir)

From what I can tell, this code block writes an xml document as .docx. Refer to the article for more context.


问:
SQL Server: How do I work out what is changing my data?
Here's a simplified version of my problem:

I have lots of articles in a table. Say, 10,000 rows. About once a week 5-10 of the values of the ArticleAuthor column [Nvarchar(255)] get overwritten with the same data - all from another article.

The code is actaully really huge and old and it's proved tough to find the offending process.

I'm thinking I might put a temporary trigger on the table to log when it gets updated etc and work from there.

Anyone got any better ideas?

Thanks in advance!

I'm using SQL Server 2005 by the way!

答: Unless the data provides you date/time information a temporary trigger is probably the best starting point.  You could also try searching application code for keywords like ('UPDATE TABLENAME' or 'Set ArticleAuthor=').  I would also take a look at the triggers that are already on the table to make sure none of them contain the rogue code.</p>


问:
CPU Barrier in Large Combination
I'm trying a script that can calculate all 8-digit probabilities that occur with [a-z] [A-Z] [0-9].

Even if my processor is very powerful, it will take weeks to realize all the possibilities as it uses only one core. How can I do this the fastest?

```<code>import sys
import os

chrList = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9']

def doCombination(charset, prefix, num):
    if num == 0:
        print(prefix)
        return
    for letter in (charset):
        hRet = doCombination(charset, prefix + letter, num - 1)

doCombination(chrList, "", 8)
</code>```

答:
Here are some tips:

Do not print your output.

Make your code such that you can restart it half way.

Save where you are at a regular interval (so that when it crashes you can restart).

Consider not using Python but something like C or GPU acceleration.

Title: CPU Barrier in Large Combination

Body:
I'm trying a script that can calculate all 8-digit probabilities that occur with [a-z] [A-Z] [0-9].

Even if my processor is very powerful, it will take weeks to realize all the possibilities as it uses only one core. How can I do this the fastest?

import sys
import os

chrList = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9']

def doCombination(charset, prefix, num):
    if num == 0:
        print(prefix)
        return
    for letter in (charset):
        hRet = doCombination(charset, prefix + letter, num - 1)

doCombination(chrList, "", 8)


问:
Query to calculate Mysql row max size
Say I have a db table with 5 fields.

```<code>id bigint(20)
name varchar(255)
place varchar(255)
DOB date
about TEXT
</code>```

Maximum row size is 65535 bytes in MySQL that is shared among all columns in the table, except TEXT/BLOB columns.

I need a query which will give me the maximum row size in bytes for this table so that I can check if the max size exceeds 65535. The charset used is utf8mb4. I need something like this

(20*8 + 255*4 + 255*4 + 3) = 2203
 the size of about field is ignored since the type is TEXT.

答:
It is much simpler -- Write and run the CREATE TABLE statement.  It will spit at you if it is too large.

Meanwhile, here are some of the flaws in your attempt:

BIGINT is 8 bytes; the (20) is useless information.

Each VARCHAR needs 1- or 2-bytes for length field.

TEXT takes some amount of space toward the 64K limit.

There is a bunch of "overhead" for each column and the row, so it is really impractical to try to compute the length.

Note also -- When the length gets too large, some of the VARCHARs may be treated like TEXT.  That is they won't necessarily count toward the 64K limit.  However, they will leave a 20-byte pointer in their place.

If you are tempted to have a table with too many too-big columns, describe the table to us; we can suggest improvements, such as:

BIGINT is rarely needed; use a smaller int type.

Don't blindly use (255) is has several drawbacks.  Analyze your data and pick a more realistic limit.

Be aware that there are four ROW_FORMATs.  DYNAMIC is probably optimal for you.  (Old versions of MySQL did not have Dynamic.

Parallel tables  (Two tables with the same PK)

Normalization  (Replacing a common string with a smaller INT.)

Don't use a bunch of columns as an "array"; make another table.  (Example: 3 phone number columns.)

Have you hit any INDEX limits yet?  It smells like you might get bitten by that, too.  Write up the CREATE TABLE, including tentative indexes.  We'll chew it up and advise you.

Title: Query to calculate Mysql row max size

Body:
Say I have a db table with 5 fields.

id bigint(20)
name varchar(255)
place varchar(255)
DOB date
about TEXT

Maximum row size is 65535 bytes in MySQL that is shared among all columns in the table, except TEXT/BLOB columns.

I need a query which will give me the maximum row size in bytes for this table so that I can check if the max size exceeds 65535. The charset used is utf8mb4. I need something like this

(20*8 + 255*4 + 255*4 + 3) = 2203
 the size of about field is ignored since the type is TEXT.


问:
Match key and value from two different dictionaries and merge them
I have this two dictionaries:

```<code>    {'data': {'id': '001_101_001', 'name': 'chview', 'type': 'multiple', 'mapping': {}},
             {'id': '001_102_001', 'name': 'view', 'type': 'binary', 'mapping': {'abc':'exp'}}
</code>```

And:

```<code>{'queries':{'view': 'text', 'chview': 'text1'}}
</code>```

The desired output should be:

```<code>{'new_data' : {'001_101_001': { 'query': 'text1', 'type': 'multiple', 'mapping': {}},
               '001_102_001': { 'query1': 'text', 'type': 'binary', 'mapping': {'abc':'exp'}}
</code>```

Because there are a lot of this dictionaries I need to match them by 'name', to have the coresponding id matched. Any ideas?

答:
Your first dictionary has a problem, it is not hashable. It should be a list of dictionaries.

```<code>{"data" :[
    {'id': '001_101_001', 'name': 'chview', 'type': 'multiple', 'mapping': {}},
    {'id': '001_102_001', 'name': 'view', 'type': 'binary', 'mapping': {'abc':'exp'}}
]}
</code>```

Complete code:

```<code>data = {"data" :[
    {'id': '001_101_001', 'name': 'chview', 'type': 'multiple', 'mapping': {}},
    {'id': '001_102_001', 'name': 'view', 'type': 'binary', 'mapping': {'abc':'exp'}}
]}

queries = {"queries" : {'view': 'text', 'chview': 'text1'}}

new_data = {}
for d in data["data"]:
    item = {d["id"] : {
        "query": queries["queries"][d["name"]],
        "type": d["type"],
        "mapping": d["mapping"]
    }}
    new_data.update(item)

print({"new_data": new_data})
</code>```

OUTPUT:

```<code>{'new_data': {'001_101_001': {'query': 'text1', 'type': 'multiple', 'mapping': {}}, '001_102_001': {'query': 'text', 'type': 'binary', 'mapping': {'abc': 'exp'}}}}
</code>```

Body:
I have this two dictionaries:

    {'data': {'id': '001_101_001', 'name': 'chview', 'type': 'multiple', 'mapping': {}},
             {'id': '001_102_001', 'name': 'view', 'type': 'binary', 'mapping': {'abc':'exp'}}

And:

{'queries':{'view': 'text', 'chview': 'text1'}}

The desired output should be:

{'new_data' : {'001_101_001': { 'query': 'text1', 'type': 'multiple', 'mapping': {}},
               '001_102_001': { 'query1': 'text', 'type': 'binary', 'mapping': {'abc':'exp'}}

Because there are a lot of this dictionaries I need to match them by 'name', to have the coresponding id matched. Any ideas?

Body:
Your first dictionary has a problem, it is not hashable. It should be a list of dictionaries.

{"data" :[
    {'id': '001_101_001', 'name': 'chview', 'type': 'multiple', 'mapping': {}},
    {'id': '001_102_001', 'name': 'view', 'type': 'binary', 'mapping': {'abc':'exp'}}
]}

Complete code:

data = {"data" :[
    {'id': '001_101_001', 'name': 'chview', 'type': 'multiple', 'mapping': {}},
    {'id': '001_102_001', 'name': 'view', 'type': 'binary', 'mapping': {'abc':'exp'}}
]}

queries = {"queries" : {'view': 'text', 'chview': 'text1'}}

new_data = {}
for d in data["data"]:
    item = {d["id"] : {
        "query": queries["queries"][d["name"]],
        "type": d["type"],
        "mapping": d["mapping"]
    }}
    new_data.update(item)

print({"new_data": new_data})

OUTPUT:

{'new_data': {'001_101_001': {'query': 'text1', 'type': 'multiple', 'mapping': {}}, '001_102_001': {'query': 'text', 'type': 'binary', 'mapping': {'abc': 'exp'}}}}


问:
Dockerfile FROM --platform option
Dockerfile documentation states that there is possibility to pass --platform option in FROM instruction like this:

```<code>FROM [--platform=<platform>] <image> [AS <name>]
</code>```

In my dockerfile I have following statements:

```<code>ARG arch
FROM --platform linux/${arch} bounz/hgbe.base
</code>```

where bounz/hgbe.base image has two os/arch variants: linux/amd64 and linux/arm/v7.

But trying to build an image using this dockerfile I get an error:

```<code>$ docker build -f hgbe.dockerfile --build-arg arch=amd64 -t bounz/hgbetest:amd64-0.1 .
Sending build context to Docker daemon  12.29kB
Error response from daemon: Dockerfile parse error line 2: FROM requires either one or three arguments
</code>```

What am I doing wrong?
And is there a way to reference specific platform of the base image if it has been built using docker buildx?

答:
update your docker file, you are missing <strong>=</strong> </p>

```<code>ARG arch
FROM --platform=linux/${arch} bounz/hgbe.base
</code>```

Title: Dockerfile FROM --platform option

Body:
Dockerfile documentation states that there is possibility to pass --platform option in FROM instruction like this:

FROM [--platform=<platform>] <image> [AS <name>]

In my dockerfile I have following statements:

ARG arch
FROM --platform linux/${arch} bounz/hgbe.base

where bounz/hgbe.base image has two os/arch variants: linux/amd64 and linux/arm/v7.

But trying to build an image using this dockerfile I get an error:

$ docker build -f hgbe.dockerfile --build-arg arch=amd64 -t bounz/hgbetest:amd64-0.1 .
Sending build context to Docker daemon  12.29kB
Error response from daemon: Dockerfile parse error line 2: FROM requires either one or three arguments

What am I doing wrong?
And is there a way to reference specific platform of the base image if it has been built using docker buildx?

Body:
update your docker file, you are missing =

ARG arch
FROM --platform=linux/${arch} bounz/hgbe.base