问:
how to pass pandas series element to another dataframe
I want to check if an error occurred.
I have this two dataframes, from excel files:

Log_frame is a dataframe of log files, reporting data recording and error:

```<code>               Time       Voltage[V]  Freq[Hz] Speed    Motor_Stt: ErrNo
           0  10:00          220         50     30           1      0
           1  10:10          220         50     30           1      0
           2  10:20          220         50      0           2      3601
           3  10:30          220         47      0           1      1500
           4  10:40          250         50      0           1      7707
           5  10:50          220         50      0           2      3601
           6  11:00          220         50      0           2      3601
           7  11:10          220         47      0           1      1500
           8  11:20          220         50     30           1      0
           9  11:30          220         50     30           1      0
</code>```

Dev_frame is the dataframe of error description:

```<code>    Fehler-Nr.         Descr                Cause

0   1500          Chk_Voltage      Voltage out of range
1   7707           Chk_Freq.       Freq. out of range
2   3601         Chk_Motor_Stt          Motor_defec
3   7704          switch_trip           chk_over_curr
</code>```

from Log_frame I can check if, which and how many errors occurred during a day by:

```<code>Err_log = Log_frame['ErrNo']
p = Err_log[Err_log != 0].drop_duplicates('first').reset_index(drop=True)
</code>```

and this result is a pandas series:

```<code><class 'pandas.core.series.Series'>
0    3601
1    1500
2    7707
</code>```

I can "pass" first error (or second and all the other) by this:

```<code>Dev_Err = Dev_frame['Fehler-Nr.']
n = Dev_Err[Dev_Err == p.iloc[0]] #or 1, 2 and so on
</code>```

I was wondering how to loop trough p.iloc[i].
Should I use a for loop or can be done by any pandas function

EDIT: e.g. if I put 1 in p.iloc[] I can get:

```<code>0   1500
</code>```

if 2:

```<code>1   7707
</code>```

答:
If you're using pandas and going for for loops you are wrong. Use pandas vectorised operations. These are done using (simple exaple)

```<code>df.apply(some function, axis)
</code>```

I'm not 100% convinced I understood what you're trying to achieve, but I believe you just want to merge/join number of errors for a given error. If so, pandas.join() and pandas.merge() are to help. Check the docs.

Body:
I want to check if an error occurred.
I have this two dataframes, from excel files:

Log_frame is a dataframe of log files, reporting data recording and error:

               Time       Voltage[V]  Freq[Hz] Speed    Motor_Stt: ErrNo
           0  10:00          220         50     30           1      0
           1  10:10          220         50     30           1      0
           2  10:20          220         50      0           2      3601
           3  10:30          220         47      0           1      1500
           4  10:40          250         50      0           1      7707
           5  10:50          220         50      0           2      3601
           6  11:00          220         50      0           2      3601
           7  11:10          220         47      0           1      1500
           8  11:20          220         50     30           1      0
           9  11:30          220         50     30           1      0

Dev_frame is the dataframe of error description:

    Fehler-Nr.         Descr                Cause

0   1500          Chk_Voltage      Voltage out of range
1   7707           Chk_Freq.       Freq. out of range
2   3601         Chk_Motor_Stt          Motor_defec
3   7704          switch_trip           chk_over_curr

from Log_frame I can check if, which and how many errors occurred during a day by:

Err_log = Log_frame['ErrNo']
p = Err_log[Err_log != 0].drop_duplicates('first').reset_index(drop=True)

and this result is a pandas series:

<class 'pandas.core.series.Series'>
0    3601
1    1500
2    7707

I can "pass" first error (or second and all the other) by this:

Dev_Err = Dev_frame['Fehler-Nr.']
n = Dev_Err[Dev_Err == p.iloc[0]] #or 1, 2 and so on

I was wondering how to loop trough p.iloc[i].
Should I use a for loop or can be done by any pandas function

EDIT: e.g. if I put 1 in p.iloc[] I can get:

0   1500

if 2:

1   7707

Body:
If you're using pandas and going for for loops you are wrong. Use pandas vectorised operations. These are done using (simple exaple)

df.apply(some function, axis)

I'm not 100% convinced I understood what you're trying to achieve, but I believe you just want to merge/join number of errors for a given error. If so, pandas.join() and pandas.merge() are to help. Check the docs.


来源: stackexchange

问:
Collate language codes into one combined locale code using CASE WHEN, and count the number of times the combined locale code occurs on a date
Learning about CASE WHEN, and I've come across a use case when I see multiple locale codes in Analytics. This is a much simpler question that is much easier to answer and read, than my prior question that was posted.

Examples are:
en-us (english US)
en-au (english australia)
en-br (english brazil)
es-es (spanish spain)
es-419 (spanish-latam)
pt-br (portuguese brazil)
pt-pt (portugal)

How do I aggregate these in BigQuery so that instead of counting distinct values, I can count the number of times where only the first two characters of the locale are found?

The second part of this question is: How do I structure my table in such a way so that I am able to plot these counts by date?

Currently, the output is:
date:language_code:CombinedLocale

Link to example data table: https://docs.google.com/spreadsheets/d/1XZp1nhNZySWI39kKhb3ydYYIImmrfAMcGJDS6ASThqg/edit?usp=sharing

I've tried:

```<code>SELECT date, COUNT(language_code),
CASE
    WHEN language_code like '%af%' THEN 'AF'
    WHEN language_code like '%en%' THEN 'EN'
    WHEN language_code like '%ar%' THEN 'AR'
    WHEN language_code like '%ba%' THEN 'BA'
ELSE "Others"
END AS CombinedLocale
FROM date_locales
</code>```

And:

```<code>Select date, COUNT(language_code)
FROM date_locales
WHERE CASE
WHEN language_code like '%af%' THEN 'AF'
WHEN language_code like '%en%' THEN 'EN'
WHEN language_code like '%ar%' THEN 'AR'
WHEN language_code like '%ba%' THEN 'BA'
ELSE "Others"
END
</code>```

This is the working code I have:

```<code>SELECT date, language_code,
CASE
    WHEN language_code like '%af%' THEN 'AF'
    WHEN language_code like '%en%' THEN 'EN'
    WHEN language_code like '%ar%' THEN 'AR'
    WHEN language_code like '%ba%' THEN 'BA'
ELSE "Others"
END AS CombinedLocale
FROM date_locales
</code>```

I expected the results to display a count of CombinedLocale table over time as such:
    ```
    Jan AF 3
    JAN EN 5
    FEB AF 5
    FEB EN 6
    MAR EN 2
    MAR EN 3```

but I get an error message stating:
SELECT list expression references column date which is neither grouped nor aggregated (Line: 1, Column: 8)

I believe I will need to aggregate the dates into Months first? I am under the impression BigQuery integration w/ DataStudio will automatically aggregate the date column.

答:
Are you just looking for an aggregation query?</p>

```<code>SELECT date,
       (CASE WHEN language_code like '%af%' THEN 'AF'
             WHEN language_code like '%en%' THEN 'EN'
             WHEN language_code like '%ar%' THEN 'AR'
             WHEN language_code like '%ba%' THEN 'BA'
             ELSE 'Others'
        END) AS CombinedLocale,
       COUNT(*)
FROM date_locales
GROUP BY date, CombinedLocale;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Learning about CASE WHEN, and I've come across a use case when I see multiple locale codes in Analytics. This is a much simpler question that is much easier to answer and read, than my prior question that was posted.

Examples are:
en-us (english US)
en-au (english australia)
en-br (english brazil)
es-es (spanish spain)
es-419 (spanish-latam)
pt-br (portuguese brazil)
pt-pt (portugal)

How do I aggregate these in BigQuery so that instead of counting distinct values, I can count the number of times where only the first two characters of the locale are found?

The second part of this question is: How do I structure my table in such a way so that I am able to plot these counts by date?

Currently, the output is:
date:language_code:CombinedLocale

Link to example data table: https://docs.google.com/spreadsheets/d/1XZp1nhNZySWI39kKhb3ydYYIImmrfAMcGJDS6ASThqg/edit?usp=sharing

I've tried:

SELECT date, COUNT(language_code),
CASE
    WHEN language_code like '%af%' THEN 'AF'
    WHEN language_code like '%en%' THEN 'EN'
    WHEN language_code like '%ar%' THEN 'AR'
    WHEN language_code like '%ba%' THEN 'BA'
ELSE "Others"
END AS CombinedLocale
FROM date_locales

And:

Select date, COUNT(language_code)
FROM date_locales
WHERE CASE
WHEN language_code like '%af%' THEN 'AF'
WHEN language_code like '%en%' THEN 'EN'
WHEN language_code like '%ar%' THEN 'AR'
WHEN language_code like '%ba%' THEN 'BA'
ELSE "Others"
END

This is the working code I have:

SELECT date, language_code,
CASE
    WHEN language_code like '%af%' THEN 'AF'
    WHEN language_code like '%en%' THEN 'EN'
    WHEN language_code like '%ar%' THEN 'AR'
    WHEN language_code like '%ba%' THEN 'BA'
ELSE "Others"
END AS CombinedLocale
FROM date_locales

I expected the results to display a count of CombinedLocale table over time as such:

    Jan AF 3
    JAN EN 5
    FEB AF 5
    FEB EN 6
    MAR EN 2
    MAR EN 3

but I get an error message stating:
SELECT list expression references column date which is neither grouped nor aggregated (Line: 1, Column: 8)

I believe I will need to aggregate the dates into Months first? I am under the impression BigQuery integration w/ DataStudio will automatically aggregate the date column.

Body:
Are you just looking for an aggregation query?

SELECT date,
       (CASE WHEN language_code like '%af%' THEN 'AF'
             WHEN language_code like '%en%' THEN 'EN'
             WHEN language_code like '%ar%' THEN 'AR'
             WHEN language_code like '%ba%' THEN 'BA'
             ELSE 'Others'
        END) AS CombinedLocale,
       COUNT(*)
FROM date_locales
GROUP BY date, CombinedLocale;


问:
SELECTing top N rows without ROWNUM?
I hope you can help me with my homework :)

We need to build a query that outputs the top N best paid employees.

My version works perfectly fine.

For example the top 3:

```<code>SELECT name, salary
FROM staff
WHERE salary IN ( SELECT *
                  FROM ( SELECT salary
                         FROM staff
                         ORDER BY salary DESC )
                  WHERE ROWNUM <= 3 )
ORDER BY salary DESC
;
</code>```

Note that this will output employees that are in the top 3 and have the same salary, too.

1: Mike, 4080

  2: Steve, 2800

  2: Susan, 2800

  2: Jack, 2800

  3: Chloe, 1400

But now our teacher does not allow us to use ROWNUM.

I searched far and wide and didn't find anything useable.

My second solution thanks to Justin Caves' hint.

First i tried this:

```<code>SELECT name, salary, ( rank() OVER ( ORDER BY salary DESC ) ) as myorder
FROM staff
WHERE myorder <= 3
;
</code>```

The errormessage is: "myorder: invalid identifier"

Thanks to DCookie its now clear:

"[...] Analytics are applied AFTER
  the where clause is evaluated, which
  is why you get the error that myorder
  is an invalid identifier."

Wrapping a SELECT around solves this:

```<code>SELECT *
FROM ( SELECT name, salary, rank() OVER ( ORDER BY salary DESC ) as myorder FROM staff )
WHERE myorder <= 3
;
</code>```

My teacher strikes again and don't allow such exotic analytic functions.

3rd solution from @Justin Caves.

"If analytic functions are also
  disallowed, the other option I could
  imagine-- one that you would never,
  ever, ever actually write in practice,
  would be something like"

```<code>SELECT name, salary
  FROM staff s1
 WHERE (SELECT COUNT(*)
          FROM staff s2
         WHERE s1.salary < s2.salary) <= 3
</code>```

答: The reason you must wrap the statement with another select is because the outer select statement is the one that limits your result set to the row numbers desired. Here's a helpful link on analytics. If you run the inner select by itself you'll see why you have to do this. Analytics are applied AFTER the where clause is evaluated, which is why you get the error that myorder is an invalid identifier.</p>

ContentLicense: CC BY-SA 3.0

Title: SELECTing top N rows without ROWNUM?

Body:
I hope you can help me with my homework :)

We need to build a query that outputs the top N best paid employees.

My version works perfectly fine.

For example the top 3:

SELECT name, salary
FROM staff
WHERE salary IN ( SELECT *
                  FROM ( SELECT salary
                         FROM staff
                         ORDER BY salary DESC )
                  WHERE ROWNUM <= 3 )
ORDER BY salary DESC
;

Note that this will output employees that are in the top 3 and have the same salary, too.

1: Mike, 4080

  2: Steve, 2800

  2: Susan, 2800

  2: Jack, 2800

  3: Chloe, 1400

But now our teacher does not allow us to use ROWNUM.

I searched far and wide and didn't find anything useable.

My second solution thanks to Justin Caves' hint.

First i tried this:

SELECT name, salary, ( rank() OVER ( ORDER BY salary DESC ) ) as myorder
FROM staff
WHERE myorder <= 3
;

The errormessage is: "myorder: invalid identifier"

Thanks to DCookie its now clear:

"[...] Analytics are applied AFTER
  the where clause is evaluated, which
  is why you get the error that myorder
  is an invalid identifier."

Wrapping a SELECT around solves this:

SELECT *
FROM ( SELECT name, salary, rank() OVER ( ORDER BY salary DESC ) as myorder FROM staff )
WHERE myorder <= 3
;

My teacher strikes again and don't allow such exotic analytic functions.

3rd solution from @Justin Caves.

"If analytic functions are also
  disallowed, the other option I could
  imagine-- one that you would never,
  ever, ever actually write in practice,
  would be something like"

SELECT name, salary
  FROM staff s1
 WHERE (SELECT COUNT(*)
          FROM staff s2
         WHERE s1.salary < s2.salary) <= 3


问:
Convert Html to raw text in python
I have set up a function in my Django views that requests data from an API and save them into my database by clicking a button, but I have a problem with the format of the data.

The goal is fairly simple: Remove all html code from the product description.

Here's an example of the current format of a description:

```<code><ul>\n  <li>\n  <p>Based on the legendary Roald Dahl’s classic children’s book of the same name, “Matilda! The Musical” is all about little Matilda Wormwood, an extremely smart and bright girl whose genius is unfortunately, unrecognized by her dull parents.</p></li>\n  <li>\n  <p>Meet other characters you will love to hate such as the wicked Mrs. Trunchbull, her evil headmistress and meet Miss Honey, the only one who understands love Matilda with her sharp mind and vivid imagination</p></li>\n  <li>\n  <p>\"Once in a blue moon, a show comes out blazing and restores your faith in Broadway. 'Matilda The Musical' is that show\" <strong>-Elisabeth Vincentelli, NEW YORK POST</strong></p></li>\n  <li>\n  <p>Winner of <strong>5 Tony Awards</strong> and <strong>7 Olivier Awards</strong></p></li>\n</ul>\n<p><strong>FAQ's</strong></p>\n<p>1) <strong>Is there a possibility that I will get partial view seating with my Matilda tickets?</strong></p>\n<p>No, you will only receive full view seats. Although, there are a few seats in the Balcony section that have a thin structural pipe within eyesight. This, however, will not hamper your view or affect your show experience.</p>\n<p>2) <strong>Is there a dress code for Matilda The Musical?</strong></p>\n<p>Smart casual is recommended for Matilda The Musical. Keep in mind the theater is air conditioned throughout the year and can get a bit chilly. </p>\n<p>3) <strong>Is there a minimum age requirement to watch Matilda The Musical?</strong></p>\n<p>All guests require a ticket, regardless of age (for which there is no minimum requirement). We recommend children be at least 6 years of age to attend a performance of Matilda.</p>\n<p>4) <strong>Is the ticket price for children different than adults?</strong></p>\n<p>No, children will have to purchase a full priced ticket.</p>\n<p>5) <strong>Does the Shubert Theater have wheelchair accessible seating?</strong></p>\n<p>Wheelchair accessible seating is available at the Shubert Theater; however, seats are subject to availability. </p>\n<p>6) <strong>What is Matilda The Musical's duration and will there be an intermission?</strong></p>\n<p>The show runs for 2 hours and 30 minutes, with one intermission. </p>\n<p>7) <strong>Can we bring outside food into the Shubert Theater?</strong></p>\n<p>Food and beverages from outside are strictly prohibited.</p>\n<p>8) <strong>Can I can bring a bag, luggage, camera etc.?</strong> </p>\n<p>No large pieces of luggage are allowed inside, but you can check them in at the Secure Baggage Area, located near the entrance. Handbags, cameras, and other small accessories are allowed inside. If carrying a camera, be sure to keep it in your bag at all times. Photography is strictly prohibited inside the theater. </p>\n<p>9) <strong>When should I arrive at the theater?</strong></p>\n<p>We recommend reaching the theater 30 minutes before curtain time. Performances begin promptly at the time stated on your ticket and the theater reserves the right to deny entry if you are late. </p>\n<p>10) <strong>Will my Matilda The Musical seats be together?</strong></p>\n<p>Yes, we always make sure your reservation seats are together. Keep in mind, many theaters use an odd and even-numbered sequence for seating. </p>
</code>```

And the expected result should look like this (removing all

 to get it as raw text):

```<code>Based on the legendary children's book by the legendary Roald Dahl, "Matilda! "The musical" is about little Matilda Wormwood, an extremely intelligent and brilliant girl whose genius is unfortunately not recognized by her dull parents. Darling, the only person who understands Matilda's love with her lively mind and overflowing imagination. "Once in a blue moon, a show ignites and restores your confidence in Broadway." NEW YORK POST Winner of 5 Tony Awards and 7 Olivier Awards Faq 1) Can I get a partial view with my Matilda tickets? No, you will only receive tickets with a full view. Although some seats in the Balcony section have a thin structural pipe within sight. This, however, will not interfere with your vision or affect your entertainment experience. 2) Is there a dress code for Matilda The Musical? Relaxed chic is recommended for Matilda The Musical. Keep in mind that the theatre is air-conditioned all year round and may be a little cold. 3) Is there a minimum age to watch Matilda The Musical? All customers need a ticket, regardless of their age (for which there is no minimum requirement). We recommend that children be at least 6 years old to attend a Matilda performance. 4) Is the price of the ticket for children different from that of adults? No, the children will have to buy a full fare ticket. 5) Does the Shubert Theatre have wheelchair accessible seats?  Wheelchair accessible seats are available at the Shubert Theatre; however, seats are subject to availability. 6) How long is Matilda The Musical and will there be an intermission? The show lasts 2 hours and 30 minutes, with an intermission. 7) Can we bring food from outside in the Shubert Theatre? Food and drinks from outside are strictly forbidden. 8) Can I bring a bag, luggage, camera, etc.?
</code>```

This is my Def from my Django views:

```<code>def api_data(request):
    if request.GET.get('mybtn'):
        resp_1 = requests.get(
            "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=en&cityCode=PARIS&limit=5000&currencyCode=CAD",
            headers={
                "Headout-Auth": HEADOUT_TEST_API_KEY
            })
        resp_1_data = resp_1.json()
        base_url_2 = "https://www.test-headout.com/api/public/v1/product/get/"

        for item in resp_1_data['items']:
            # concat ID to the URL string
            url = '{}{}'.format(base_url_2, item['id'])

            # make the HTTP request
            resp_2 = requests.get(
                url,
                headers={
                    "Headout-Auth": HEADOUT_TEST_API_KEY
                })
            resp_2_data = resp_2.json()

            Product.objects.get_or_create(
                title=item['name'],
                destination=item['city']['name'],
                description=resp_2_data['contentListHtml'][0]['html'], # this is what needs to be formated
                link=item['canonicalUrl'],
                image=item['image']['url']
            )

    return render(request, "form.html")
</code>```

And my Django models:

```<code>class Product(models.Model):
    destination = models.CharField(max_length=255, default='')
    title = models.CharField(max_length=255, default='')
    slug = models.SlugField(null=True, blank=True, unique=True, max_length=255, default='')
    description = models.TextField(max_length=2000, default='')
    link = models.TextField(max_length=500, default='')

    ptags = TaggableManager()

    image = models.ImageField(max_length=500, default='images/zero-image-found.png')
    timestamp = models.DateTimeField(auto_now=True)

    def get_absolute_url(self):
        return reverse('experience',
                       kwargs={'slug': self.slug})

    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.title)
        super(Product, self).save(*args, **kwargs)

    def __str__(self):
        return self.destination
</code>```

How can I achieve this?

Please help.

答:
You can use lxml or beautiful soup to parse the html.

https://lxml.de/parsing.html

Title: Convert Html to raw text in python

Body:
I have set up a function in my Django views that requests data from an API and save them into my database by clicking a button, but I have a problem with the format of the data.

The goal is fairly simple: Remove all html code from the product description.

Here's an example of the current format of a description:

\n
\n
Based on the legendary Roald Dahl’s classic children’s book of the same name, “Matilda! The Musical” is all about little Matilda Wormwood, an extremely smart and bright girl whose genius is unfortunately, unrecognized by her dull parents.

\n
\n
Meet other characters you will love to hate such as the wicked Mrs. Trunchbull, her evil headmistress and meet Miss Honey, the only one who understands love Matilda with her sharp mind and vivid imagination

\n
\n
\"Once in a blue moon, a show comes out blazing and restores your faith in Broadway. 'Matilda The Musical' is that show\" -Elisabeth Vincentelli, NEW YORK POST

\n
\n
Winner of 5 Tony Awards and 7 Olivier Awards

\n
\n
FAQ's
\n
1) Is there a possibility that I will get partial view seating with my Matilda tickets?
\n
No, you will only receive full view seats. Although, there are a few seats in the Balcony section that have a thin structural pipe within eyesight. This, however, will not hamper your view or affect your show experience.
\n
2) Is there a dress code for Matilda The Musical?
\n
Smart casual is recommended for Matilda The Musical. Keep in mind the theater is air conditioned throughout the year and can get a bit chilly.
\n
3) Is there a minimum age requirement to watch Matilda The Musical?
\n
All guests require a ticket, regardless of age (for which there is no minimum requirement). We recommend children be at least 6 years of age to attend a performance of Matilda.
\n
4) Is the ticket price for children different than adults?
\n
No, children will have to purchase a full priced ticket.
\n
5) Does the Shubert Theater have wheelchair accessible seating?
\n
Wheelchair accessible seating is available at the Shubert Theater; however, seats are subject to availability.
\n
6) What is Matilda The Musical's duration and will there be an intermission?
\n
The show runs for 2 hours and 30 minutes, with one intermission.
\n
7) Can we bring outside food into the Shubert Theater?
\n
Food and beverages from outside are strictly prohibited.
\n
8) Can I can bring a bag, luggage, camera etc.?
\n
No large pieces of luggage are allowed inside, but you can check them in at the Secure Baggage Area, located near the entrance. Handbags, cameras, and other small accessories are allowed inside. If carrying a camera, be sure to keep it in your bag at all times. Photography is strictly prohibited inside the theater.
\n
9) When should I arrive at the theater?
\n
We recommend reaching the theater 30 minutes before curtain time. Performances begin promptly at the time stated on your ticket and the theater reserves the right to deny entry if you are late.
\n
10) Will my Matilda The Musical seats be together?
\n
Yes, we always make sure your reservation seats are together. Keep in mind, many theaters use an odd and even-numbered sequence for seating.

And the expected result should look like this (removing all

 to get it as raw text):

Based on the legendary children's book by the legendary Roald Dahl, "Matilda! "The musical" is about little Matilda Wormwood, an extremely intelligent and brilliant girl whose genius is unfortunately not recognized by her dull parents. Darling, the only person who understands Matilda's love with her lively mind and overflowing imagination. "Once in a blue moon, a show ignites and restores your confidence in Broadway." NEW YORK POST Winner of 5 Tony Awards and 7 Olivier Awards Faq 1) Can I get a partial view with my Matilda tickets? No, you will only receive tickets with a full view. Although some seats in the Balcony section have a thin structural pipe within sight. This, however, will not interfere with your vision or affect your entertainment experience. 2) Is there a dress code for Matilda The Musical? Relaxed chic is recommended for Matilda The Musical. Keep in mind that the theatre is air-conditioned all year round and may be a little cold. 3) Is there a minimum age to watch Matilda The Musical? All customers need a ticket, regardless of their age (for which there is no minimum requirement). We recommend that children be at least 6 years old to attend a Matilda performance. 4) Is the price of the ticket for children different from that of adults? No, the children will have to buy a full fare ticket. 5) Does the Shubert Theatre have wheelchair accessible seats?  Wheelchair accessible seats are available at the Shubert Theatre; however, seats are subject to availability. 6) How long is Matilda The Musical and will there be an intermission? The show lasts 2 hours and 30 minutes, with an intermission. 7) Can we bring food from outside in the Shubert Theatre? Food and drinks from outside are strictly forbidden. 8) Can I bring a bag, luggage, camera, etc.?

This is my Def from my Django views:

def api_data(request):
    if request.GET.get('mybtn'):
        resp_1 = requests.get(
            "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=en&cityCode=PARIS&limit=5000&currencyCode=CAD",
            headers={
                "Headout-Auth": HEADOUT_TEST_API_KEY
            })
        resp_1_data = resp_1.json()
        base_url_2 = "https://www.test-headout.com/api/public/v1/product/get/"

        for item in resp_1_data['items']:
            # concat ID to the URL string
            url = '{}{}'.format(base_url_2, item['id'])

            # make the HTTP request
            resp_2 = requests.get(
                url,
                headers={
                    "Headout-Auth": HEADOUT_TEST_API_KEY
                })
            resp_2_data = resp_2.json()

            Product.objects.get_or_create(
                title=item['name'],
                destination=item['city']['name'],
                description=resp_2_data['contentListHtml'][0]['html'], # this is what needs to be formated
                link=item['canonicalUrl'],
                image=item['image']['url']
            )

    return render(request, "form.html")

And my Django models:

class Product(models.Model):
    destination = models.CharField(max_length=255, default='')
    title = models.CharField(max_length=255, default='')
    slug = models.SlugField(null=True, blank=True, unique=True, max_length=255, default='')
    description = models.TextField(max_length=2000, default='')
    link = models.TextField(max_length=500, default='')

    ptags = TaggableManager()

    image = models.ImageField(max_length=500, default='images/zero-image-found.png')
    timestamp = models.DateTimeField(auto_now=True)

    def get_absolute_url(self):
        return reverse('experience',
                       kwargs={'slug': self.slug})

    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.title)
        super(Product, self).save(*args, **kwargs)

    def __str__(self):
        return self.destination

How can I achieve this?

Please help.


问:
Football teams league
Imagine I have 3 teams, and I want to generate random matches between the three teams. I used itertools permutations to print all matches. The problem is generating a score in a game. Imagine team A vs team B (2-1). How do I input the 2 goals by team A and 1 goal by team B in a match?

I have printed all possible matches. Note that I used permutations because Team A vs Team B is different from Team B vs Team A because one team plays at home, and in another game plays at the other team's home.

```<code>import itertools
import random

teams=['A','B','C']

def games():
  permutations=itertools.permutations(teams,2)
  for i in permutations:
    print(i)
    result=random.randint(0,5)
</code>```

My doubt is when I have to generate a result in a game in every iteration.

答:
```<code>import itertools
import random

teams=['A','B','C']

def make_games():
    games=[]
    permutations=itertools.permutations(teams,2)
    for team_tuple in permutations:
        game={}
        team_one, team_two = team_tuple[0],team_tuple[1]
        team_one_score, team_two_score=random.randint(0,5),random.randint(0,5)
        game[team_one]=team_one_score
        game[team_two]=team_two_score
        games.append(game)
    return games

print(make_games())
</code>```

Out:

```<code>[
{'A': 1, 'B': 4},
{'A': 1, 'C': 0},
{'B': 5, 'A': 1},
{'B': 1, 'C': 1},
{'C': 1, 'A': 5},
{'C': 2, 'B': 3}
]
</code>```

Title: Football teams league

Body:
Imagine I have 3 teams, and I want to generate random matches between the three teams. I used itertools permutations to print all matches. The problem is generating a score in a game. Imagine team A vs team B (2-1). How do I input the 2 goals by team A and 1 goal by team B in a match?

I have printed all possible matches. Note that I used permutations because Team A vs Team B is different from Team B vs Team A because one team plays at home, and in another game plays at the other team's home.

import itertools
import random

teams=['A','B','C']

def games():
  permutations=itertools.permutations(teams,2)
  for i in permutations:
    print(i)
    result=random.randint(0,5)

My doubt is when I have to generate a result in a game in every iteration.

Body:
import itertools
import random

teams=['A','B','C']

def make_games():
    games=[]
    permutations=itertools.permutations(teams,2)
    for team_tuple in permutations:
        game={}
        team_one, team_two = team_tuple[0],team_tuple[1]
        team_one_score, team_two_score=random.randint(0,5),random.randint(0,5)
        game[team_one]=team_one_score
        game[team_two]=team_two_score
        games.append(game)
    return games

print(make_games())

Out:

[
{'A': 1, 'B': 4},
{'A': 1, 'C': 0},
{'B': 5, 'A': 1},
{'B': 1, 'C': 1},
{'C': 1, 'A': 5},
{'C': 2, 'B': 3}
]


问:
How to overload stream operators to work with functions located in different files?
I am trying to make a template max function (finds the biggest of three of something) to work with a class I have created.

Therefor I should overload the > operator and if I want to display the result of the max function I should also overload the << operator.

If I create the class in another .h file and then overload the << operator the program doesn't seem to recognize that the << is overloaded.

```<code>template <typename X> X max(X a, X b, X c)
{
X maxNum = a;

if( b > maxNum )
    maxNum = b;
if( c > maxNum )
    maxNum = c;

return maxNum;
}
</code>```

The class is in a separate .h file.

```<code>class Person
{
private:
    std::string Name;
    int Height;
    bool Gender;

public:
    Person() :Name(""), Height(0), Gender(false) {};
    Person(std::string Name, int Height, bool Gender) : Name(Name),
    Height(Height), Gender(Gender) {};

    void SetName(std::string Name) { this->Name = Name; }
    void SetHeight(int Height) { this->Height = Height; }
    void SetGender(bool Gender) { this->Gender = Gender; }

    std::string GetName() { return Name; }
    int GetHeight() { return Height; }
    bool GetGender() { return Gender; }
};

std::ostream & operator << (std::ostream &MyStream, Person &a)
{
    MyStream << "Name: " << a.GetName() << ", Height: " << a.GetHeight()
<< ", Gender: " << a.GetGender() << std::endl;
    return MyStream;
}
</code>```

The main function is located in the same file as the max method (not the same as the class):

```<code>int main()
{
    Person a("Bob", 207, true), b("Alice", 367, false), c("Mickey", 107,
    true);

    std::cout << max(a,b,c) <<  std::endl;
}
</code>```

The error I get is:

```<code>Error   C2679   binary '<<': no operator found which takes a right-hand
operand of type 'X' (or there is no acceptable conversion)

Error (active)  E0349   no operator "<<" matches these operands
</code>```

However if I put everything in a single file it works just fine.

I would like to know why this happens and if there is a way around it.

答:
You need to put a forward declaration of your operator overload in the Person header file as well, to have the compiler recognizing it:

```<code>std::ostream& operator<<(std::ostream&, Person&);
</code>```

Also the signature of the overloaded operator should be

```<code>std::ostream& operator<<(std::ostream&, const Person&);
</code>```

and getter / comparator functions accordingly

```<code>    std::string GetName() const { return Name; }
    int GetHeight() const { return Height; }
    bool GetGender() const { return Gender; }

    bool operator > (const Person&) const;
</code>```

All of the const stuff is necessary to allow the compiler having these functions (which aren't intended to change the Person instance passed) to be applied for rvalues (e.g. results of expressions or temporary instances).

Body:
I am trying to make a template max function (finds the biggest of three of something) to work with a class I have created.

Therefor I should overload the > operator and if I want to display the result of the max function I should also overload the << operator.

If I create the class in another .h file and then overload the << operator the program doesn't seem to recognize that the << is overloaded.

template <typename X> X max(X a, X b, X c)
{
X maxNum = a;

if( b > maxNum )
    maxNum = b;
if( c > maxNum )
    maxNum = c;

return maxNum;
}

The class is in a separate .h file.

class Person
{
private:
    std::string Name;
    int Height;
    bool Gender;

public:
    Person() :Name(""), Height(0), Gender(false) {};
    Person(std::string Name, int Height, bool Gender) : Name(Name),
    Height(Height), Gender(Gender) {};

    void SetName(std::string Name) { this->Name = Name; }
    void SetHeight(int Height) { this->Height = Height; }
    void SetGender(bool Gender) { this->Gender = Gender; }

    std::string GetName() { return Name; }
    int GetHeight() { return Height; }
    bool GetGender() { return Gender; }
};

std::ostream & operator << (std::ostream &MyStream, Person &a)
{
    MyStream << "Name: " << a.GetName() << ", Height: " << a.GetHeight()
<< ", Gender: " << a.GetGender() << std::endl;
    return MyStream;
}

The main function is located in the same file as the max method (not the same as the class):

int main()
{
    Person a("Bob", 207, true), b("Alice", 367, false), c("Mickey", 107,
    true);

    std::cout << max(a,b,c) <<  std::endl;
}

The error I get is:

Error   C2679   binary '<<': no operator found which takes a right-hand
operand of type 'X' (or there is no acceptable conversion)

Error (active)  E0349   no operator "<<" matches these operands

However if I put everything in a single file it works just fine.

I would like to know why this happens and if there is a way around it.

Body:
You need to put a forward declaration of your operator overload in the Person header file as well, to have the compiler recognizing it:

std::ostream& operator<<(std::ostream&, Person&);

Also the signature of the overloaded operator should be

std::ostream& operator<<(std::ostream&, const Person&);

and getter / comparator functions accordingly

    std::string GetName() const { return Name; }
    int GetHeight() const { return Height; }
    bool GetGender() const { return Gender; }

    bool operator > (const Person&) const;

All of the const stuff is necessary to allow the compiler having these functions (which aren't intended to change the Person instance passed) to be applied for rvalues (e.g. results of expressions or temporary instances).


问:
Converting an ajax call to a fetch api call and pulling the information into a php function
I'm trying to convert an .ajax call to a fetch call. The ajax works but the fetch pulls a 500 error when I try to pull the data in my wordPress php file.

I'm fairly new to the fetch api and that is why I'm trying to learn it. I have looked at MDN, wordPress site on custom hooks and rest api, searched the web and searched stack overflow. All they talk about is ajax. I don't know if I'm using the wrong search phrase but I have been trying to figure this out for hours and frustrated.

```<code>//working ajax in js file
createLike() {
    $.ajax({
        url: `${universityData.root_url}/wp-json/university/v1/manageLike`,
        type: 'POST',
        data: {'professorId' : 789},
        success: response => {
            console.log(response);
        },
        error: response => {
            console.log(response);
        }
    });

//my conversion to fetch
createLike() {
            const data = {
                'professorId' : 789,
            };
            fetch(`${universityData.root_url}/wp-json/university/v1/manageLike`, {
                headers: {
                    'X-WP-Nonce' : universityData.nonce,
                    'Content-Type' : 'application/json'
                },
                credentials: 'same-origin',
                method: 'POST',
                body: JSON.stringify(data),
            }).then(function(response){
                return response.json();
            }).then(response => {
                console.log(response);
            }).catch(err => console.log(`error : ${err}`))
        },

//php file
function createLike($data) {
    $professor = sanatize_text_field($data['professorId']);
    wp_insert_post(array(
        'post_type' => 'like',
        'post_status' => 'publish',
        'post_title' => '3rd PHP Create Post Test',
        'meta_input' => array(
            'liked_professor_id' => $professor
        )
    ));
}

function universityLikeRoutes() {
register_rest_route('university/v1', 'manageLike', array(
    'methods' => 'POST',
    'callback' => 'createLike',
));

}

add_action('rest_api_init', 'universityLikeRoutes');
</code>```

my error

```<code>{code: "internal_server_error", message: "The site is experiencing technical difficulties.", data: {…}, additional_errors: Array(0)}
additional_errors: []
code: "internal_server_error"
data: {status: 500}
message: "The site is experiencing technical difficulties."
__proto__: Object
</code>```

答:
The key is understanding what $.ajax() does differently than fetch and thus how you have to handle the data differently in wordpress.

$.ajax takes whatever you pass to the data option and converts into the application/x-www-form-urlencoded MIME type by default. $_POST in PHP automatically decodes indexed form variable names, which the WP_REST_Request object makes available to you within your callback as the $data argument.

fetch is different in several ways, you can read about this in several articles online, such as this one. One thing you are doing differently is passing along a serialized JSON string and you are telling your endpoint that the data type is application/json. By design, the wp-json API doesn't by default parse this data for you. But you can access it nevertheless.

Instead of using $data as your callback argument, change it to a WP_REST_Request object. Then you can call the get_json_params method, and access whatever body you passed to the api that way.

For instance, change your PHP callback to the following:

```<code>function createLike( WP_REST_Request $request ) {
    $data = $request->get_json_params();
    $professor = sanitize_text_field( $data['professorId'] );
    wp_insert_post( array(
        'post_type' => 'like',
        'post_status' => 'publish',
        'post_title' => '3rd PHP Create Post Test',
        'meta_input' => array(
            'liked_professor_id' => $professor
        )
    ) );
}
</code>```

Body:
I'm trying to convert an .ajax call to a fetch call. The ajax works but the fetch pulls a 500 error when I try to pull the data in my wordPress php file.

I'm fairly new to the fetch api and that is why I'm trying to learn it. I have looked at MDN, wordPress site on custom hooks and rest api, searched the web and searched stack overflow. All they talk about is ajax. I don't know if I'm using the wrong search phrase but I have been trying to figure this out for hours and frustrated.

//working ajax in js file
createLike() {
    $.ajax({
        url: `${universityData.root_url}/wp-json/university/v1/manageLike`,
        type: 'POST',
        data: {'professorId' : 789},
        success: response => {
            console.log(response);
        },
        error: response => {
            console.log(response);
        }
    });

//my conversion to fetch
createLike() {
            const data = {
                'professorId' : 789,
            };
            fetch(`${universityData.root_url}/wp-json/university/v1/manageLike`, {
                headers: {
                    'X-WP-Nonce' : universityData.nonce,
                    'Content-Type' : 'application/json'
                },
                credentials: 'same-origin',
                method: 'POST',
                body: JSON.stringify(data),
            }).then(function(response){
                return response.json();
            }).then(response => {
                console.log(response);
            }).catch(err => console.log(`error : ${err}`))
        },

//php file
function createLike($data) {
    $professor = sanatize_text_field($data['professorId']);
    wp_insert_post(array(
        'post_type' => 'like',
        'post_status' => 'publish',
        'post_title' => '3rd PHP Create Post Test',
        'meta_input' => array(
            'liked_professor_id' => $professor
        )
    ));
}

function universityLikeRoutes() {
register_rest_route('university/v1', 'manageLike', array(
    'methods' => 'POST',
    'callback' => 'createLike',
));

}

add_action('rest_api_init', 'universityLikeRoutes');

my error

{code: "internal_server_error", message: "The site is experiencing technical difficulties.", data: {…}, additional_errors: Array(0)}
additional_errors: []
code: "internal_server_error"
data: {status: 500}
message: "The site is experiencing technical difficulties."
__proto__: Object

Body:
The key is understanding what $.ajax() does differently than fetch and thus how you have to handle the data differently in wordpress.

$.ajax takes whatever you pass to the data option and converts into the application/x-www-form-urlencoded MIME type by default. $_POST in PHP automatically decodes indexed form variable names, which the WP_REST_Request object makes available to you within your callback as the $data argument.

fetch is different in several ways, you can read about this in several articles online, such as this one. One thing you are doing differently is passing along a serialized JSON string and you are telling your endpoint that the data type is application/json. By design, the wp-json API doesn't by default parse this data for you. But you can access it nevertheless.

Instead of using $data as your callback argument, change it to a WP_REST_Request object. Then you can call the get_json_params method, and access whatever body you passed to the api that way.

For instance, change your PHP callback to the following:

function createLike( WP_REST_Request $request ) {
    $data = $request->get_json_params();
    $professor = sanitize_text_field( $data['professorId'] );
    wp_insert_post( array(
        'post_type' => 'like',
        'post_status' => 'publish',
        'post_title' => '3rd PHP Create Post Test',
        'meta_input' => array(
            'liked_professor_id' => $professor
        )
    ) );
}


问:
MaterialUI Table - Equal width Columns using Span?
I'm trying to utilize the Table component from Material UI to build a data table. However, I'm struggling with making equal width columns for my datatable. Currently I'm trying something like this:

```<code><TableCell key={props.name} style={{width: '25%'}}>
          <span
            style={{
              width: `${(100 / props.numCols)}%`,
              whiteSpace: "pre",
              overflow: "scroll",
              display: 'block'
            }}
          >
            {props.value}
          </span>
 </TableCell>
</code>```

However, this doesn't seem to do the trick. I expect 4 columns of equal widths but in this photo you'll see that you can only see 3 of the columns (the 4th one is way off-screen) and notably, the 3rd column is extremely long. I would appreciate any pointers!

Edit: It seems like the width property is actually taking 100% of the length of the text? Is there a way I can get it to take the width of the tablerow?

答:
I know this question is a little bit dated, but you can do the following to get more control over your table row width distribution:</p>

```<code><Table style={{ tableLayout: 'fixed' }} > .. </Table>
</code>```

Body:
I'm trying to utilize the Table component from Material UI to build a data table. However, I'm struggling with making equal width columns for my datatable. Currently I'm trying something like this:

<TableCell key={props.name} style={{width: '25%'}}>
          <span
            style={{
              width: `${(100 / props.numCols)}%`,
              whiteSpace: "pre",
              overflow: "scroll",
              display: 'block'
            }}
          >
            {props.value}

 </TableCell>

However, this doesn't seem to do the trick. I expect 4 columns of equal widths but in this photo you'll see that you can only see 3 of the columns (the 4th one is way off-screen) and notably, the 3rd column is extremely long. I would appreciate any pointers!

Edit: It seems like the width property is actually taking 100% of the length of the text? Is there a way I can get it to take the width of the tablerow?

Body:
I know this question is a little bit dated, but you can do the following to get more control over your table row width distribution:

<Table style={{ tableLayout: 'fixed' }} > .. </Table>


问:
Pagination not initializing on page refresh with multiple sliders throughout the page-slick library
The pagination value is not initialized when I refresh the page. Works only once I click on next or previous button.</p>

```<code>var $slickElement = $('.paragraph-slider, .gallery-slider');
$slickElement.each(function() {
    if($(this).find('.pagination').length < 1) {
        $(".gallery-slider").append('<div class="pagination"></div>');
    }
    $(this).once().on('init reInit afterChange', function (event, slick, currentSlide, nextSlide) {
        event.preventDefault();
        // CurrentSlide is undefined on init -- set it to 0 in this case (currentSlide is 0 based).
        var i = (currentSlide ? currentSlide : 0) + 1;
        // $value = $status.text(i + '/' + slick.slideCount);
        $(this).find('.pagination').html(i + '/' + slick.slideCount);
    });
});
</code>```

答:
Fixed it...incase anyone stumbles across this.All you need is a window onload function to initialize the pagination value.You can add this to the above code. </p>

```<code>        $slickElement.each(function(){
          var count = $(this).find(".slick-slide").length;
          $(this).find('.pagination').html(1 + '/' + count);
        });
      }

      // Window onload call addPagination function.
      $(window).on('load', function(){
        addPagination();
      });
</code>```

Body:
The pagination value is not initialized when I refresh the page. Works only once I click on next or previous button.

var $slickElement = $('.paragraph-slider, .gallery-slider');
$slickElement.each(function() {
    if($(this).find('.pagination').length < 1) {
        $(".gallery-slider").append('

');
    }
    $(this).once().on('init reInit afterChange', function (event, slick, currentSlide, nextSlide) {
        event.preventDefault();
        // CurrentSlide is undefined on init -- set it to 0 in this case (currentSlide is 0 based).
        var i = (currentSlide ? currentSlide : 0) + 1;
        // $value = $status.text(i + '/' + slick.slideCount);
        $(this).find('.pagination').html(i + '/' + slick.slideCount);
    });
});

Body:
Fixed it...incase anyone stumbles across this.All you need is a window onload function to initialize the pagination value.You can add this to the above code.

        $slickElement.each(function(){
          var count = $(this).find(".slick-slide").length;
          $(this).find('.pagination').html(1 + '/' + count);
        });
      }

      // Window onload call addPagination function.
      $(window).on('load', function(){
        addPagination();
      });


问:
how to print text from a JtextField by clicking a JButton
I'm creating a little program for my self to learn Java now I did make a GUI with 12 JTextFields and now I want to use the text that's in the text fields in another class where I print them out.

When I press the button class print is successful, summand I get the last System.out.println("Test if class is triggerd") in my console but I don't get the JTextFields output in the console

Class Frame1

```<code>
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

public class Frame1 {

    public JFrame frmCratingRecipieGenerator;
    public JTextField txtSlot;
    public JTextField textField_1;
    public JTextField textField_2;
    public JTextField textField_3;
    public JTextField textField_4;
    public JTextField textField_5;
    public JTextField textField_6;
    public JTextField textField_7;
    public JTextField textField_8;
    public JTextField textField_9;
    public JTextField textField_10;
    public JTextField textField_11;
    public JLabel lblNewLabel;
    public String slot1;
    public String slot2;
    public String slot3;
    public String slot4;
    public String slot5;
    public String slot6;
    public String slot7;
    public String slot8;
    public String slot9;
    public String output;
    public String output_count;
    public String file_num;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Frame1 window = new Frame1();
                    window.frmCratingRecipieGenerator.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Frame1() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    public void initialize() {
        frmCratingRecipieGenerator = new JFrame();
        frmCratingRecipieGenerator.setResizable(false);
        frmCratingRecipieGenerator.setTitle("Crating Recipie Generator Alpha 1");
        frmCratingRecipieGenerator.getContentPane().setBackground(new Color(192, 192, 192));
        frmCratingRecipieGenerator.setBounds(100, 100, 452, 248);
        frmCratingRecipieGenerator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmCratingRecipieGenerator.getContentPane().setLayout(null);

        txtSlot = new JTextField();
        txtSlot.setBounds(10, 19, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(txtSlot);
        txtSlot.setColumns(10);

        textField_1 = new JTextField();
        textField_1.setBounds(106, 19, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_1);
        textField_1.setColumns(10);

        textField_2 = new JTextField();
        textField_2.setBounds(202, 19, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_2);
        textField_2.setColumns(10);

        textField_3 = new JTextField();
        textField_3.setBounds(10, 50, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_3);
        textField_3.setColumns(10);

        textField_4 = new JTextField();
        textField_4.setBounds(106, 50, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_4);
        textField_4.setColumns(10);

        textField_5 = new JTextField();
        textField_5.setBounds(202, 50, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_5);
        textField_5.setColumns(10);

        textField_6 = new JTextField();
        textField_6.setBounds(10, 81, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_6);
        textField_6.setColumns(10);

        textField_7 = new JTextField();
        textField_7.setBounds(106, 81, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_7);
        textField_7.setColumns(10);

        textField_8 = new JTextField();
        textField_8.setBounds(202, 81, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_8);
        textField_8.setColumns(10);

        textField_9 = new JTextField();
        textField_9.setBounds(351, 19, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_9);
        textField_9.setColumns(10);

        textField_10 = new JTextField();
        textField_10.setBounds(351, 81, 46, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_10);
        textField_10.setColumns(10);

        textField_11 = new JTextField();
        textField_11.setText("1");
        textField_11.setBounds(351, 50, 46, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_11);
        textField_11.setColumns(10);

        JLabel lblFileId = new JLabel("File ID");
        lblFileId.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblFileId.setHorizontalAlignment(SwingConstants.LEFT);
        lblFileId.setBounds(298, 82, 86, 14);
        frmCratingRecipieGenerator.getContentPane().add(lblFileId);

        JLabel lblOutput = new JLabel("Output");
        lblOutput.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblOutput.setBounds(298, 20, 58, 14);
        frmCratingRecipieGenerator.getContentPane().add(lblOutput);

        JLabel lblCount = new JLabel("Count");
        lblCount.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblCount.setBounds(298, 51, 52, 14);
        frmCratingRecipieGenerator.getContentPane().add(lblCount);

        JLabel lblThisJavaProgram = new JLabel("This Java program is coded by Jason");
        lblThisJavaProgram.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblThisJavaProgram.setBounds(10, 179, 270, 20);
        frmCratingRecipieGenerator.getContentPane().add(lblThisJavaProgram);

        JLabel TestLabel = new JLabel("");
        TestLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
        TestLabel.setBounds(391, 179, 46, 19);
        frmCratingRecipieGenerator.getContentPane().add(TestLabel);

        JButton btnNewButton = new JButton("Generate the McFunction File's");
        btnNewButton.setBounds(10, 108, 427, 60);
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                TestLabel.setText(textField_10.getText());
                print name = new print();
                name.Print();
            }
        });
        frmCratingRecipieGenerator.getContentPane().add(btnNewButton);

        lblNewLabel = new JLabel("Last File num");
        lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblNewLabel.setBounds(287, 182, 110, 14);
        frmCratingRecipieGenerator.getContentPane().add(lblNewLabel);

        this.slot1 = txtSlot.getText();
        this.slot2 = textField_1.getText();
        this.slot3 = textField_2.getText();;
        this.slot4 = textField_3.getText();;
        this.slot5 = textField_4.getText();;
        this.slot6 = textField_5.getText();;
        this.slot7 = textField_6.getText();;
        this.slot8 = textField_7.getText();;
        this.slot9 = textField_8.getText();;
        this.output = textField_9.getText();
        this.output_count = textField_11.getText();
        this.file_num = textField_10.getText();

        }

}

</code>```

Class print

```<code>package example;

public class print {
    public void Print() {
        Frame1 slots =  new Frame1();
        String slot1 = slots.slot1;
        String slot2 = slots.slot2;
        String slot3 = slots.slot3;
        String slot4 = slots.slot4;
        String slot5 = slots.slot5;
        String slot6 = slots.slot6;
        String slot7 = slots.slot7;
        String slot8 = slots.slot8;
        String slot9 = slots.slot9;
        String output = slots.output;
        String output_count = slots.output_count;
        String file_num = slots.file_num;

        System.out.println(slot1);
        System.out.println(slot2);
        System.out.println(slot3);
        System.out.println(slot4);
        System.out.println(slot5);
        System.out.println(slot6);
        System.out.println(slot7);
        System.out.println(slot8);
        System.out.println(slot9);
        System.out.println(output);
        System.out.println(output_count);
        System.out.println(file_num);
        System.out.println("Test if class is triggerd");
    }

}
</code>```

答:
This is happening because you create on the print class a new Object of frame1 so the variables by default are null. You can add on the Print method a list parameter that stores all the Strings in that list.

```<code>public void Print(List<String> slots) {
    System.out.println(slots.get(0));
    System.out.println(slots.get(1));
    System.out.println(slots.get(2));
    System.out.println(slots.get(3));
    System.out.println(slots.get(4));
    System.out.println(slots.get(5));
    System.out.println(slots.get(6));
    System.out.println(slots.get(7));
    System.out.println(slots.get(8));
    System.out.println(slots.get(9));
    System.out.println(slots.get(10));
    System.out.println(slots.get(11));
}
</code>```

and redefine before the method call all the variables and store them in the list.

You can learn some things about Java's lists here

If you are struggling finding the code I made it for you

```<code>            slot1 = txtSlot.getText();
            slot2 = textField_1.getText();
            slot3 = textField_2.getText();;
            slot4 = textField_3.getText();;
            slot5 = textField_4.getText();;
            slot6 = textField_5.getText();;
            slot7 = textField_6.getText();;
            slot8 = textField_7.getText();;
            slot9 = textField_8.getText();;
            output = textField_9.getText();
            List<String> slots = new ArrayList<String>();
            slots.add(slot1);
            slots.add(slot2);
            slots.add(slot3);
            slots.add(slot4);
            slots.add(slot5);
            slots.add(slot6);
            slots.add(slot7);
            slots.add(slot8);
            slots.add(slot9);
            slots.add(output);
            slots.add(output_count);
            slots.add(file_num);
            output_count = textField_11.getText();
            file_num = textField_10.getText();
            TestLabel.setText(textField_10.getText());

            print name = new print();

            name.Print(slots);
</code>```

and Print class:

```<code>public void Print(List<String> slots) {

    System.out.println(slots.get(0));
    System.out.println(slots.get(1));
    System.out.println(slots.get(2));
    System.out.println(slots.get(3));
    System.out.println(slots.get(4));
    System.out.println(slots.get(5));
    System.out.println(slots.get(6));
    System.out.println(slots.get(7));
    System.out.println(slots.get(8));
    System.out.println(slots.get(9));
    System.out.println(slots.get(10));
    System.out.println(slots.get(11));
    System.out.println("Test if class is triggerd");
}
</code>```

Body:
I'm creating a little program for my self to learn Java now I did make a GUI with 12 JTextFields and now I want to use the text that's in the text fields in another class where I print them out.

When I press the button class print is successful, summand I get the last System.out.println("Test if class is triggerd") in my console but I don't get the JTextFields output in the console

Class Frame1

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

public class Frame1 {

    public JFrame frmCratingRecipieGenerator;
    public JTextField txtSlot;
    public JTextField textField_1;
    public JTextField textField_2;
    public JTextField textField_3;
    public JTextField textField_4;
    public JTextField textField_5;
    public JTextField textField_6;
    public JTextField textField_7;
    public JTextField textField_8;
    public JTextField textField_9;
    public JTextField textField_10;
    public JTextField textField_11;
    public JLabel lblNewLabel;
    public String slot1;
    public String slot2;
    public String slot3;
    public String slot4;
    public String slot5;
    public String slot6;
    public String slot7;
    public String slot8;
    public String slot9;
    public String output;
    public String output_count;
    public String file_num;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Frame1 window = new Frame1();
                    window.frmCratingRecipieGenerator.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Frame1() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    public void initialize() {
        frmCratingRecipieGenerator = new JFrame();
        frmCratingRecipieGenerator.setResizable(false);
        frmCratingRecipieGenerator.setTitle("Crating Recipie Generator Alpha 1");
        frmCratingRecipieGenerator.getContentPane().setBackground(new Color(192, 192, 192));
        frmCratingRecipieGenerator.setBounds(100, 100, 452, 248);
        frmCratingRecipieGenerator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmCratingRecipieGenerator.getContentPane().setLayout(null);

        txtSlot = new JTextField();
        txtSlot.setBounds(10, 19, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(txtSlot);
        txtSlot.setColumns(10);

        textField_1 = new JTextField();
        textField_1.setBounds(106, 19, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_1);
        textField_1.setColumns(10);

        textField_2 = new JTextField();
        textField_2.setBounds(202, 19, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_2);
        textField_2.setColumns(10);

        textField_3 = new JTextField();
        textField_3.setBounds(10, 50, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_3);
        textField_3.setColumns(10);

        textField_4 = new JTextField();
        textField_4.setBounds(106, 50, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_4);
        textField_4.setColumns(10);

        textField_5 = new JTextField();
        textField_5.setBounds(202, 50, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_5);
        textField_5.setColumns(10);

        textField_6 = new JTextField();
        textField_6.setBounds(10, 81, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_6);
        textField_6.setColumns(10);

        textField_7 = new JTextField();
        textField_7.setBounds(106, 81, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_7);
        textField_7.setColumns(10);

        textField_8 = new JTextField();
        textField_8.setBounds(202, 81, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_8);
        textField_8.setColumns(10);

        textField_9 = new JTextField();
        textField_9.setBounds(351, 19, 86, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_9);
        textField_9.setColumns(10);

        textField_10 = new JTextField();
        textField_10.setBounds(351, 81, 46, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_10);
        textField_10.setColumns(10);

        textField_11 = new JTextField();
        textField_11.setText("1");
        textField_11.setBounds(351, 50, 46, 20);
        frmCratingRecipieGenerator.getContentPane().add(textField_11);
        textField_11.setColumns(10);

        JLabel lblFileId = new JLabel("File ID");
        lblFileId.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblFileId.setHorizontalAlignment(SwingConstants.LEFT);
        lblFileId.setBounds(298, 82, 86, 14);
        frmCratingRecipieGenerator.getContentPane().add(lblFileId);

        JLabel lblOutput = new JLabel("Output");
        lblOutput.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblOutput.setBounds(298, 20, 58, 14);
        frmCratingRecipieGenerator.getContentPane().add(lblOutput);

        JLabel lblCount = new JLabel("Count");
        lblCount.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblCount.setBounds(298, 51, 52, 14);
        frmCratingRecipieGenerator.getContentPane().add(lblCount);

        JLabel lblThisJavaProgram = new JLabel("This Java program is coded by Jason");
        lblThisJavaProgram.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblThisJavaProgram.setBounds(10, 179, 270, 20);
        frmCratingRecipieGenerator.getContentPane().add(lblThisJavaProgram);

        JLabel TestLabel = new JLabel("");
        TestLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
        TestLabel.setBounds(391, 179, 46, 19);
        frmCratingRecipieGenerator.getContentPane().add(TestLabel);

        JButton btnNewButton = new JButton("Generate the McFunction File's");
        btnNewButton.setBounds(10, 108, 427, 60);
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                TestLabel.setText(textField_10.getText());
                print name = new print();
                name.Print();
            }
        });
        frmCratingRecipieGenerator.getContentPane().add(btnNewButton);

        lblNewLabel = new JLabel("Last File num");
        lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblNewLabel.setBounds(287, 182, 110, 14);
        frmCratingRecipieGenerator.getContentPane().add(lblNewLabel);

        this.slot1 = txtSlot.getText();
        this.slot2 = textField_1.getText();
        this.slot3 = textField_2.getText();;
        this.slot4 = textField_3.getText();;
        this.slot5 = textField_4.getText();;
        this.slot6 = textField_5.getText();;
        this.slot7 = textField_6.getText();;
        this.slot8 = textField_7.getText();;
        this.slot9 = textField_8.getText();;
        this.output = textField_9.getText();
        this.output_count = textField_11.getText();
        this.file_num = textField_10.getText();

        }

}

Class print

package example;

public class print {
    public void Print() {
        Frame1 slots =  new Frame1();
        String slot1 = slots.slot1;
        String slot2 = slots.slot2;
        String slot3 = slots.slot3;
        String slot4 = slots.slot4;
        String slot5 = slots.slot5;
        String slot6 = slots.slot6;
        String slot7 = slots.slot7;
        String slot8 = slots.slot8;
        String slot9 = slots.slot9;
        String output = slots.output;
        String output_count = slots.output_count;
        String file_num = slots.file_num;

        System.out.println(slot1);
        System.out.println(slot2);
        System.out.println(slot3);
        System.out.println(slot4);
        System.out.println(slot5);
        System.out.println(slot6);
        System.out.println(slot7);
        System.out.println(slot8);
        System.out.println(slot9);
        System.out.println(output);
        System.out.println(output_count);
        System.out.println(file_num);
        System.out.println("Test if class is triggerd");
    }

}

Body:
This is happening because you create on the print class a new Object of frame1 so the variables by default are null. You can add on the Print method a list parameter that stores all the Strings in that list.

public void Print(List<String> slots) {
    System.out.println(slots.get(0));
    System.out.println(slots.get(1));
    System.out.println(slots.get(2));
    System.out.println(slots.get(3));
    System.out.println(slots.get(4));
    System.out.println(slots.get(5));
    System.out.println(slots.get(6));
    System.out.println(slots.get(7));
    System.out.println(slots.get(8));
    System.out.println(slots.get(9));
    System.out.println(slots.get(10));
    System.out.println(slots.get(11));
}

and redefine before the method call all the variables and store them in the list.

You can learn some things about Java's lists here

If you are struggling finding the code I made it for you

            slot1 = txtSlot.getText();
            slot2 = textField_1.getText();
            slot3 = textField_2.getText();;
            slot4 = textField_3.getText();;
            slot5 = textField_4.getText();;
            slot6 = textField_5.getText();;
            slot7 = textField_6.getText();;
            slot8 = textField_7.getText();;
            slot9 = textField_8.getText();;
            output = textField_9.getText();
            List<String> slots = new ArrayList<String>();
            slots.add(slot1);
            slots.add(slot2);
            slots.add(slot3);
            slots.add(slot4);
            slots.add(slot5);
            slots.add(slot6);
            slots.add(slot7);
            slots.add(slot8);
            slots.add(slot9);
            slots.add(output);
            slots.add(output_count);
            slots.add(file_num);
            output_count = textField_11.getText();
            file_num = textField_10.getText();
            TestLabel.setText(textField_10.getText());

            print name = new print();

            name.Print(slots);

and Print class:

public void Print(List<String> slots) {

    System.out.println(slots.get(0));
    System.out.println(slots.get(1));
    System.out.println(slots.get(2));
    System.out.println(slots.get(3));
    System.out.println(slots.get(4));
    System.out.println(slots.get(5));
    System.out.println(slots.get(6));
    System.out.println(slots.get(7));
    System.out.println(slots.get(8));
    System.out.println(slots.get(9));
    System.out.println(slots.get(10));
    System.out.println(slots.get(11));
    System.out.println("Test if class is triggerd");
}


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

Input:

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

Output:

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

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

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

Input:

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

Output:

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

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

Body:
var array = [1,2,[3,4],[5,6]];
var newArray = [].concat(...array);
console.log(newArray); // [1, 2, 3, 4, 5, 6]


问:
Works perfect locally but on server: Failed to load resource: 500 (Internal Server Error)
I have a MVC5 web application which i have been working for a while. When i work on local it works perfect. But when i publish it to our company server, in a section where i print a receipt im having "Failed to load resource" error. As I said it works perfect when im working on local. Im using devexpress xtrareport .print() method to print the receipt. Here are some codes that im using:

POST method, this is the view where i get the error:

```<code> function result() {
    $(document).ready(function () {
        value = document.getElementById('tutar').value;
        var value3 = document.getElementById('bankalar').value;
        var value2 = parseFloat(value);
        try {
            value1 = document.getElementById('1001').innerHTML;
        } catch {
            value1 = "Girilmedi";
        }

        if (document.getElementById("musteriAdi0").value == "") {
            alert("Müşteri Adı Girilmeden İşlem Yapılamaz");
            for (var u = p; u < i; u++) {
                try {
                    var element = document.getElementById(u);
                    var row = element.parentNode.parentNode;
                    row.parentNode.removeChild(row);
                } catch {
                }
            }
            window.location.href = '@Url.Action("HizliAlimSatim", "Kuyumcu")';
        }
        else {
            ekle();
            var m = JSON.stringify({
                'model': things, 'toplam': value2, 'personel': value1, 'KrediKarti': value3
            });
            things = [];
            $(function () {
                $.ajax({
                    type: "POST",
                    url: "/Kuyumcu/HizliAlimSatim",
                    contentType: "application/json; charset=utf-8",
                    dataType: "Json",
                    data: m,
                    success: function (data) {

                        if (data.includes("/Kuyumcu/Document") == false) {
                            g = g - i;
                        } else {
                            alert("İşlem Başarılı!");
                            //window.open(data, '_blank');
                            document.getElementById('tutar').value = 0;
                            toplam = 0;
                            degistir();

                            for (var u = p; u < i; u++) {
                                try {
                                    var element = document.getElementById(u);
                                    var row = element.parentNode.parentNode;
                                    row.parentNode.removeChild(row);
                                } catch {
                                }
                            }
                            p = i;

                            window.location.reload(true);
                        }
                    }
                });
            });
        }

    });
}
</code>```

this is the controller where i call print method:

```<code>Fis report = new Fis();
        report.Parameters["FisNo"].Value = id;
        report.Parameters["Musteri"].Value = model[0].MusteriAdSoyad;
        report.Parameters["Islemci"].Value = personel;
        report.CreateDocument(false);
        //report.ShowPreview();
        report.PrintingSystem.ShowMarginsWarning = false;
        report.Print();

        return Json(Url.Action("Document", "Kuyumcu");
</code>```

I have been trying to solve the issue for 2 days, I thought its a server side problem but whatever i changed it didnt work.

答:
The XtraReport.Print method from your controller is invoked at the server side - that's why it works when you run your application on localhost. When you deploy it to the production server, the Print method will be executed at the server's machine - not the client one.

Assuming that you use a DocumentViewer to display a report on your web page, use the viewer's client-side API (see the Print method) to print a report. For instance, refer to the sample code snippet from the How to display print dialog after the WebDocumentViewer is loaded on the web page thread.

If you want to print a report without displaying it, use the approach shown in the following example.

Body:
I have a MVC5 web application which i have been working for a while. When i work on local it works perfect. But when i publish it to our company server, in a section where i print a receipt im having "Failed to load resource" error. As I said it works perfect when im working on local. Im using devexpress xtrareport .print() method to print the receipt. Here are some codes that im using:

POST method, this is the view where i get the error:

 function result() {
    $(document).ready(function () {
        value = document.getElementById('tutar').value;
        var value3 = document.getElementById('bankalar').value;
        var value2 = parseFloat(value);
        try {
            value1 = document.getElementById('1001').innerHTML;
        } catch {
            value1 = "Girilmedi";
        }

        if (document.getElementById("musteriAdi0").value == "") {
            alert("Müşteri Adı Girilmeden İşlem Yapılamaz");
            for (var u = p; u < i; u++) {
                try {
                    var element = document.getElementById(u);
                    var row = element.parentNode.parentNode;
                    row.parentNode.removeChild(row);
                } catch {
                }
            }
            window.location.href = '@Url.Action("HizliAlimSatim", "Kuyumcu")';
        }
        else {
            ekle();
            var m = JSON.stringify({
                'model': things, 'toplam': value2, 'personel': value1, 'KrediKarti': value3
            });
            things = [];
            $(function () {
                $.ajax({
                    type: "POST",
                    url: "/Kuyumcu/HizliAlimSatim",
                    contentType: "application/json; charset=utf-8",
                    dataType: "Json",
                    data: m,
                    success: function (data) {

                        if (data.includes("/Kuyumcu/Document") == false) {
                            g = g - i;
                        } else {
                            alert("İşlem Başarılı!");
                            //window.open(data, '_blank');
                            document.getElementById('tutar').value = 0;
                            toplam = 0;
                            degistir();

                            for (var u = p; u < i; u++) {
                                try {
                                    var element = document.getElementById(u);
                                    var row = element.parentNode.parentNode;
                                    row.parentNode.removeChild(row);
                                } catch {
                                }
                            }
                            p = i;

                            window.location.reload(true);
                        }
                    }
                });
            });
        }

    });
}

this is the controller where i call print method:

Fis report = new Fis();
        report.Parameters["FisNo"].Value = id;
        report.Parameters["Musteri"].Value = model[0].MusteriAdSoyad;
        report.Parameters["Islemci"].Value = personel;
        report.CreateDocument(false);
        //report.ShowPreview();
        report.PrintingSystem.ShowMarginsWarning = false;
        report.Print();

        return Json(Url.Action("Document", "Kuyumcu");

I have been trying to solve the issue for 2 days, I thought its a server side problem but whatever i changed it didnt work.


问:
Make nav underline animate based on class
I have a .nav-link

When .active is added to it, it gets text-decoration: underline. How do i make this text decoration animate by sliding in from the left?

答:
You can create and animate custom underline like this. As you cannot animate the text-decordation: underline;</p>

```<code>.nav-link:after{
      content: '';
      position: absolute;
      width: 0; height: 3px;
      display: block;
      margin-top: 5px;
      right: 0;
      background: #fff;
      transition: width .2s ease; // this will add animation from left to right.
      -webkit-transition: width .2s ease;
    }

.nav-link:active:after{
  width: 100%;
  left: 0;
  background: #fff;
}
</code>```

Body:
You can create and animate custom underline like this. As you cannot animate the text-decordation: underline;

.nav-link:after{
      content: '';
      position: absolute;
      width: 0; height: 3px;
      display: block;
      margin-top: 5px;
      right: 0;
      background: #fff;
      transition: width .2s ease; // this will add animation from left to right.
      -webkit-transition: width .2s ease;
    }

.nav-link:active:after{
  width: 100%;
  left: 0;
  background: #fff;
}


问:
Removing all instances of [] and ' ' from files
I have text file with the following content:

```<code>Hi, my name is 'James'. What is your [name]
</code>```

I wont to remove the ' ' and the [] from the text so the output looks like this:

```<code>Hi, my name is James. What is your name
</code>```

Here is my code:

```<code>s=  Hi, my name is 'James'. What is your [name]
s=s.replace("[","")
s=s.replace("'","")
</code>```

However the output leave a bracket to the right of name:

```<code>Hi, my name is James. What is your name]
</code>```

Any ideas?

答:
if your trying to just put this in console or terminal then print("Hi, my name is James. What is your name? ") will work just fine
But if you are looking  for a person to 'talk' and respond then use an input like,
input('Hi, my name is James. What is your name ')
the user can then type after this and if you use a variable you can respond to the users response
example

name = input('whats your name'? )
print('Hi' + name + 'How are you'? )

putting spaces after question marks will make the code look better(in my opinion) when being executed.

Body:
I have text file with the following content:

Hi, my name is 'James'. What is your [name]

I wont to remove the ' ' and the [] from the text so the output looks like this:

Hi, my name is James. What is your name

Here is my code:

s=  Hi, my name is 'James'. What is your [name]
s=s.replace("[","")
s=s.replace("'","")

However the output leave a bracket to the right of name:

Hi, my name is James. What is your name]

Any ideas?


问:
React app 'Failed to compile' because './node_modules/jss-default-unit/lib/index.js' not found
I've just updated some Node modules in a React react project, but now when I go to localhost:3000 I get a Failed to compile error because ./node_modules/jss-default-unit/lib/index.js was not found:

The packages I've upgraded are Material UI and react-scripts, as seen from a git diff of package.json:

How can I resolve this issue?

(This issue, https://github.com/cssinjs/react-jss/issues/146, describes a similar issue caused by Babel running on node_modules, but I wasn't able to find a webpack.config.js in node_modules/babel-loader to modify).

答: I resolved this by running npm install jss-default-unit and restarting the server with npm start.


问:
How do I resize a field manually in tableau without others resizing automatically?
I would like to resize a field manually without the others being affected. How can this be done?

Pict 1 is how it is currently displayed
Pict 2 is when I try to resize MIN(0). The others also resizes as a result. How to avoid that?

Thank you

Pict 1 and Pict 2

答: You can't do that as of 2019.2.</p>

Body: You can't do that as of 2019.2.


问:
Install pandas on linux, only using a python file
I am required to install pandas using the .py file using the linux command line, before importing pandas once it is installed.
If anyone knows how to also do this on macOS that would be appreciated as well.

Thanks

答:
I believe you want to do something like:

```<code>import os
cmd = 'sudo pip install pandas'
os.system(cmd)
</code>```

based on: https://cmdlinetips.com/2014/03/how-to-run-a-shell-command-from-python-and-get-the-output/

Body:
I believe you want to do something like:

import os
cmd = 'sudo pip install pandas'
os.system(cmd)

based on: https://cmdlinetips.com/2014/03/how-to-run-a-shell-command-from-python-and-get-the-output/


问:
Checking if avro schema is according to the avro spec
I cannot find a tool for checking whether avro schemas follow the avro spec.  How can I check this?

I have generated a 300kB avro schema, but I do not know whether its syntax is according to the avro spec.  The avro spec has quite a few quirks, like naming conventions, handling records in records and other quirks.

What is more, if I try my avro schema using a tool that validates json according to an avro schema, I get an unspecified error or crash.

Is there a tool, maybe a JSON Schema validator that can validate the avro schema itself?

答:
If you want to validate the schema definition, then it's enough to try to build an object that is generated by the schema definition. You can do it in a unit test for example and when you will run the unit test, an exception will be thrown if you will not respect the avro schema definition.

If you want to check for compatibility issues, then you can use the Schema Registry REST API, more details here.

Best regards!