问:
Extract multiple words using regexp_extract in PySpark
I have a list which contains some words and I need to extract matching words from a text line, I found this, but it only extracts one word.

keys file content

this is a keyword

part_description file content

32015   this is a keyword hello world

Code

import pyspark.sql.functions as F

keywords = sc.textFile('file:///home/description_search/keys') #1
part_description =  sc.textFile('file:///description_search/part_description') #2
keywords = keywords.map(lambda x: x.split(' ')) #3
keywords = keywords.collect()[0] #4
df = part_description.map(lambda r: Row(r)).toDF(['line']) #5
df.withColumn('extracted_word', F.regexp_extract(df['line'],'|'.join(keywords), 0)).show() #6
```
<p><strong>Outputs</strong></p>
```+--------------------+--------------+
|                line|extracted_word|
+--------------------+--------------+
|32015   this is a...|          this|
+--------------------+--------------+
```
<p><strong>Expected output</strong></p>
```+--------------------+-----------------+
|                line|   extracted_word|
+--------------------+-----------------+
|32015   this is a...|this,is,a,keyword|
+--------------------+-----------------+
```
<p>I want to</p>
<ol>
<li><p>return all matching keyword and their count</p>
</li>
<li><p>and if <code>step #4</code> is the most effecient way</p>
</li>
</ol>
<p>Reproducible example:</p>
<pre class="lang-py prettyprint-override"><code>keywords = ['this','is','a','keyword']
l = [('32015 this is a keyword hello world'      , ),
('keyword this'      ,   ),
('32015 this is a keyword hello world 32015 this is a keyword hello world'      ,   ),
('keyword keyword'      ,   ),
('is a'      , )]

columns = ['line']

df=spark.createDataFrame(l, columns)
</code>```

答:
I managed to solve it by using UDF instead as below

```<code>def build_regex(keywords):
    res = '('
    for key in keywords:
        res += '\\b' + key + '\\b|'
    res = res[0:len(res) - 1] + ')'

    return res

def get_matching_string(line, regex):
    matches = re.findall(regex, line)
    return matches if matches else None

udf_func = udf(lambda line, regex: get_matching_string(line, regex),
               ArrayType(StringType()))

df = df.withColumn('matched', udf_func(df['line'], F.lit(build_regex(keywords)))).withColumn('count', F.size('matched'))
</code>```

Result

```<code>+--------------------+--------------------+-----+
|                line|             matched|count|
+--------------------+--------------------+-----+
|32015    this is ...|[this, is, this, ...|    5|
|12832    Shb is a...|             [is, a]|    2|
|35015    this is ...|          [this, is]|    2|
+--------------------+--------------------+-----+
</code>```

Body:
I have a list which contains some words and I need to extract matching words from a text line, I found this, but it only extracts one word.

keys file content

this is a keyword

part_description file content

32015   this is a keyword hello world

Code

import pyspark.sql.functions as F

keywords = sc.textFile('file:///home/description_search/keys') #1
part_description =  sc.textFile('file:///description_search/part_description') #2
keywords = keywords.map(lambda x: x.split(' ')) #3
keywords = keywords.collect()[0] #4
df = part_description.map(lambda r: Row(r)).toDF(['line']) #5
df.withColumn('extracted_word', F.regexp_extract(df['line'],'|'.join(keywords), 0)).show() #6

Outputs

+--------------------+--------------+
|                line|extracted_word|
+--------------------+--------------+
|32015   this is a...|          this|
+--------------------+--------------+

Expected output

+--------------------+-----------------+
|                line|   extracted_word|
+--------------------+-----------------+
|32015   this is a...|this,is,a,keyword|
+--------------------+-----------------+

I want to

return all matching keyword and their count

and if step #4 is the most effecient way

Reproducible example:

keywords = ['this','is','a','keyword']
l = [('32015 this is a keyword hello world'      , ),
('keyword this'      ,   ),
('32015 this is a keyword hello world 32015 this is a keyword hello world'      ,   ),
('keyword keyword'      ,   ),
('is a'      , )]

columns = ['line']

df=spark.createDataFrame(l, columns)

Body:
I managed to solve it by using UDF instead as below

def build_regex(keywords):
    res = '('
    for key in keywords:
        res += '\\b' + key + '\\b|'
    res = res[0:len(res) - 1] + ')'

    return res

def get_matching_string(line, regex):
    matches = re.findall(regex, line)
    return matches if matches else None

udf_func = udf(lambda line, regex: get_matching_string(line, regex),
               ArrayType(StringType()))

df = df.withColumn('matched', udf_func(df['line'], F.lit(build_regex(keywords)))).withColumn('count', F.size('matched'))

Result

+--------------------+--------------------+-----+
|                line|             matched|count|
+--------------------+--------------------+-----+
|32015    this is ...|[this, is, this, ...|    5|
|12832    Shb is a...|             [is, a]|    2|
|35015    this is ...|          [this, is]|    2|
+--------------------+--------------------+-----+


来源: stackexchange

问:
How to check on client if image was correctly loaded
In my laravel 5.8 / bootstrap 4.3 / vuejs "^2.5.17" / "jquery": "^3.4.1" app I read data from remote web
service and any rows can have link to image, so in my template
I make :

```<code><td class="align-middle" style="width: 180px" v-if="nextSearchResult.PictureUrl">
    <img :src="nextSearchResult.PictureUrl" alt="" class=" mx-auto d-block" style="width:100px; height: auto; ">
</td>
</code>```

But when nextSearchResult.PictureUrl is filled but has invalid url or some urls return “access denied” I got empty block on my image.
Sure, I can check on server when all data are red, but such checking can add a lot of time to working of my remote request.
If there is a way to make this check on client with JS/vuejs/jquery ?

Thanks!

答:
Try this:

```<code><td v-if="nextSearchResult.PictureUrl" class="align-middle" style="width: 180px">
    <img :src="nextSearchResult.PictureUrl" alt="" class=" mx-auto d-block" style="width:100px; height: auto; ">
</td>
<td v-else class="align-middle" style="width: 180px">
 <div>Sorry we are having trouble loading this image</div>
</td>
</code>```

If you want to see in your code, simply write a computed property:

```<code>computed: {
   isPicture(){
         const value =  this.nextSearchResult.PictureUrl
         if (value === some option I dont like){
         return false
    }
    return true
    }

</code>```

ContentLicense: CC BY-SA 4.0

Body:
In my laravel 5.8 / bootstrap 4.3 / vuejs "^2.5.17" / "jquery": "^3.4.1" app I read data from remote web
service and any rows can have link to image, so in my template
I make :

But when nextSearchResult.PictureUrl is filled but has invalid url or some urls return “access denied” I got empty block on my image.
Sure, I can check on server when all data are red, but such checking can add a lot of time to working of my remote request.
If there is a way to make this check on client with JS/vuejs/jquery ?

Thanks!

Body:
Try this:

<td v-if="nextSearchResult.PictureUrl" class="align-middle" style="width: 180px">
    <img :src="nextSearchResult.PictureUrl" alt="" class=" mx-auto d-block" style="width:100px; height: auto; ">
</td>
<td v-else class="align-middle" style="width: 180px">
 <div>Sorry we are having trouble loading this image</div>
</td>

If you want to see in your code, simply write a computed property:

computed: {
   isPicture(){
         const value =  this.nextSearchResult.PictureUrl
         if (value === some option I dont like){
         return false
    }
    return true
    }


问:
how to populate a model field via django signals with post_save?
After creating a model object I would like to use a post_save signal to populate another model field in the same object with the ID and other values.

But the real question here is, how do i access the field from the instance? nothing worked

Example:
User creates an object -> id of the object is 93 -> I would like to add #00093 as value of another field in the same object.

models.py

```<code>class Ticket(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    designation = models.CharField(max_length=255, blank=True, null=True)
    summary = models.CharField(max_length=255)
</code>```

signals.py

```<code>@receiver(post_save, sender=Ticket)
def ticket_designation(sender, instance, **kwargs):
    instance.designation = "#" + "000" + str(instance.id)
    print("Ticket" + instance.designation + " was created.")
</code>```

答:
I think you really want to do this:

```<code>@receiver(post_save, sender=Ticket)
def ticket_designation(sender, instance, created, **kwargs):
    if created:
        designation = "#" + "000" + str(instance.id)
        Ticket.filter(pk=instance.pk).update(designation=designation)
        print("Ticket" + instance.designation + " was created.")
</code>```

Explanation:

why use if created: designation is only created once when the new Ticket is created. It's not updated every time you save the same object.

why use Ticket.objects.filter(..).update(..) : we cannot do instance.save() as it'll then call this post_save again and recursion occurs. .update on queryset does not call signals so we're safe.

If you want to use instance.save you might want to look at how to prevent post_save recursion in django.

Body:
After creating a model object I would like to use a post_save signal to populate another model field in the same object with the ID and other values.

But the real question here is, how do i access the field from the instance? nothing worked

Example:
User creates an object -> id of the object is 93 -> I would like to add #00093 as value of another field in the same object.

models.py

class Ticket(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    designation = models.CharField(max_length=255, blank=True, null=True)
    summary = models.CharField(max_length=255)

signals.py

@receiver(post_save, sender=Ticket)
def ticket_designation(sender, instance, **kwargs):
    instance.designation = "#" + "000" + str(instance.id)
    print("Ticket" + instance.designation + " was created.")

Body:
I think you really want to do this:

@receiver(post_save, sender=Ticket)
def ticket_designation(sender, instance, created, **kwargs):
    if created:
        designation = "#" + "000" + str(instance.id)
        Ticket.filter(pk=instance.pk).update(designation=designation)
        print("Ticket" + instance.designation + " was created.")

Explanation:

why use if created: designation is only created once when the new Ticket is created. It's not updated every time you save the same object.

why use Ticket.objects.filter(..).update(..) : we cannot do instance.save() as it'll then call this post_save again and recursion occurs. .update on queryset does not call signals so we're safe.

If you want to use instance.save you might want to look at how to prevent post_save recursion in django.


问:
List all virtualenv created by virtualenvwrapper
In virtualenvwrapper, is there a simple way to list all virtualenv on my machine?

(like what yolk -l does to list all python packages in the current virtual environment?)

CLARIFICATION: "ls -la" in my env directory does not count. I am looking for a virtualenv or virtualenvwrapper specific command.

答:
This works on Windows only:

If you are trying to find all envs created using virtualenv

search for "activate_this.py" or "pip-selfcheck.json"


问:
Check if a week of dates sits between two specific dates SQL ORACLE
I have two dates and want to only keep rows where a certain week falls in between those two dates. I need to run this for 67+ different weeks so I'd like to change my below code to run quicker and not have to type out the 7 days of the week each time. </p>

```<code>SELECT * FROM MY_DATA
WHERE  ('05-JUNE-2017' BETWEEN start_date AND end_date
OR      '06-JUNE-2017' BETWEEN start_date AND end_date
OR      '07-JUNE-2017' BETWEEN start_date AND end_date
OR      '08-JUNE-2017' BETWEEN start_date AND end_date
OR      '09-JUNE-2017' BETWEEN start_date AND end_date
OR      '10-JUNE-2017' BETWEEN start_date AND end_date
OR      '11-JUNE-2017' BETWEEN start_date AND end_date);
</code>```

答:
So, you have two date intervals. One is from input_date to input_date + 6 (note: 6, not 7; you are counting the input_date too!) and the other is from start_date to end_date. And you want to write a condition that means the two intervals overlap (have non-empty intersection).

Two intervals do not overlap if one entirely precedes the other. So, the last day of one interval must be strictly less than the first day of the other interval. This can happen in one of two ways (depending on which interval comes first). The condition would look like this:

```<code>input_date + 6 < start_date OR end_date < input_date
</code>```

So, this is the negation of the condition you want. Apply the logical NOT operator to this; so the condition becomes:

```<code>input_date + 6 >= start_date AND end_date >= input_date
</code>```

Body:
I have two dates and want to only keep rows where a certain week falls in between those two dates. I need to run this for 67+ different weeks so I'd like to change my below code to run quicker and not have to type out the 7 days of the week each time.

SELECT * FROM MY_DATA
WHERE  ('05-JUNE-2017' BETWEEN start_date AND end_date
OR      '06-JUNE-2017' BETWEEN start_date AND end_date
OR      '07-JUNE-2017' BETWEEN start_date AND end_date
OR      '08-JUNE-2017' BETWEEN start_date AND end_date
OR      '09-JUNE-2017' BETWEEN start_date AND end_date
OR      '10-JUNE-2017' BETWEEN start_date AND end_date
OR      '11-JUNE-2017' BETWEEN start_date AND end_date);

Body:
So, you have two date intervals. One is from input_date to input_date + 6 (note: 6, not 7; you are counting the input_date too!) and the other is from start_date to end_date. And you want to write a condition that means the two intervals overlap (have non-empty intersection).

Two intervals do not overlap if one entirely precedes the other. So, the last day of one interval must be strictly less than the first day of the other interval. This can happen in one of two ways (depending on which interval comes first). The condition would look like this:

input_date + 6 < start_date OR end_date < input_date

So, this is the negation of the condition you want. Apply the logical NOT operator to this; so the condition becomes:

input_date + 6 >= start_date AND end_date >= input_date


问:
Pandas does not read CSV as it write it
I created a dataframe, and i wanted to export it as a CSV. i used the
df.to_csv() method.

When i read my csv that i created it's not parsed well and i have some
values of columns mixed between each others.

I tried to change the encoding, as well as the delimiter, but it
doesn't solve my problem.

here is a sample of my dataframe before being exported as a CSV :

```<code>                                           societe  ...     cluster
    6                      ACTION AIR ENVIRONNEMENT  ...  aquavalley
    7                                    AD NUCLEIS  ...  aquavalley
    8                                        AD'OCC  ...  aquavalley
    9                                     ADEQUABIO  ...  aquavalley
    10                              ADICT SOLUTIONS  ...  aquavalley
</code>```

then i use to export it :

```<code>csv_df.to_csv(r"path.csv", sep="\t")
</code>```

and to read it :

```<code>pd.read_csv(r"path.csv", sep="\t", engine='python')
</code>```

and i obtain something like that

```<code>    7                                    AD NUCLEIS  ...  aquavalley
    8                                        AD'OCC  ...        None
    215 Rue         34000 Mont...    contact@cc.com  ...        None
    9                                     ADEQUABIO  ...  aquavalley

</code>```

答: try reading it as pd.read_csv("path.csv")

Title: Pandas does not read CSV as it write it

Body:
I created a dataframe, and i wanted to export it as a CSV. i used the
df.to_csv() method.

When i read my csv that i created it's not parsed well and i have some
values of columns mixed between each others.

I tried to change the encoding, as well as the delimiter, but it
doesn't solve my problem.

here is a sample of my dataframe before being exported as a CSV :

                                           societe  ...     cluster
    6                      ACTION AIR ENVIRONNEMENT  ...  aquavalley
    7                                    AD NUCLEIS  ...  aquavalley
    8                                        AD'OCC  ...  aquavalley
    9                                     ADEQUABIO  ...  aquavalley
    10                              ADICT SOLUTIONS  ...  aquavalley

then i use to export it :

csv_df.to_csv(r"path.csv", sep="\t")

and to read it :

pd.read_csv(r"path.csv", sep="\t", engine='python')

and i obtain something like that

    7                                    AD NUCLEIS  ...  aquavalley
    8                                        AD'OCC  ...        None
    215 Rue         34000 Mont...    contact@cc.com  ...        None
    9                                     ADEQUABIO  ...  aquavalley


答:
You can try adding the argument index in to_csv:

```<code>df.to_csv(r"path.csv", sep="\t", index=False)
</code>```

Or a problem could be that your fields contain tabs, so in this case I would suggest you to change separator

Title: Pandas does not read CSV as it write it

Body:
You can try adding the argument index in to_csv:

df.to_csv(r"path.csv", sep="\t", index=False)

Or a problem could be that your fields contain tabs, so in this case I would suggest you to change separator


问:
How to read gz compressed file by pyspark
I have line data in .gz compressed format. I have to read it in pyspark
Following is the code snippet

```<code>rdd = sc.textFile("data/label.gz").map(func)
</code>```

But I could not read the above file successfully. How do I read gz compressed file. I have found a similar question here but my current version of spark is different that the version in that question. I expect there should be some built in function as in hadoop.

答:
You can load compressed files directly into dataframes through the spark instance, you just need to specify the compression in the path:

```<code>df = spark.read.csv("filepath/part-000.csv.gz")
</code>```

You can also optionally specify if a header present or if schema needs applying too

```<code>df = spark.read.csv("filepath/part-000.csv.gz", header=True, schema=schema).
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have line data in .gz compressed format. I have to read it in pyspark
Following is the code snippet

rdd = sc.textFile("data/label.gz").map(func)

But I could not read the above file successfully. How do I read gz compressed file. I have found a similar question here but my current version of spark is different that the version in that question. I expect there should be some built in function as in hadoop.

Body:
You can load compressed files directly into dataframes through the spark instance, you just need to specify the compression in the path:

df = spark.read.csv("filepath/part-000.csv.gz")

You can also optionally specify if a header present or if schema needs applying too

df = spark.read.csv("filepath/part-000.csv.gz", header=True, schema=schema).


问:
How to open json file dynamically?
I have a json file within a folder that I want to open dynamically within my main app.py, is there a way to do this?

This is what my folders look like

```<code>C:.
|   app.py
|   README.txt
|   tree.txt
|
+---resources
|       stores.json
|
+---templates
|       Tails.html
|
+---test
|       Unit_Test.py
|
\---__pycache__
        app.cpython-37.pyc
        Tails.cpython-37.pyc
</code>```

I currently have this is app.py which gives me an error; expected str, bytes or os.PathLike object, not NoneType

```<code>from pydoc import locate

def read_jsonfile():
    with open(locate('resources.stores.json')) as f:
        stpres = json.load(f)

    return stores
</code>```

Any help or suggestions would be appreciated.

答:
Try:</p>

```<code>import json

def read_jsonfile():
    with open('resources/stores.json') as f:
        stores = json.load(f)

    return stores
</code>```

Title: How to open json file dynamically?

Body:
I have a json file within a folder that I want to open dynamically within my main app.py, is there a way to do this?

This is what my folders look like

C:.
|   app.py
|   README.txt
|   tree.txt
|
+---resources
|       stores.json
|
+---templates
|       Tails.html
|
+---test
|       Unit_Test.py
|
\---__pycache__
        app.cpython-37.pyc
        Tails.cpython-37.pyc

I currently have this is app.py which gives me an error; expected str, bytes or os.PathLike object, not NoneType

from pydoc import locate

def read_jsonfile():
    with open(locate('resources.stores.json')) as f:
        stpres = json.load(f)

    return stores

Any help or suggestions would be appreciated.

Body:
Try:

import json

def read_jsonfile():
    with open('resources/stores.json') as f:
        stores = json.load(f)

    return stores


问:
How to keep div elements at bottom of page
I have a two-columned div element that I need to have at the bottom of the page to act as a footer. The problem is I have tried using position:fixed and bottom:0 to make the element appear at the bottom. This works but only brings one of the #column divs down to the bottom, the other disappears. I would appreciate any assistance.

Code:

/* ~ Copyright (c) Macleay Netball Association (made by Tom Carpenter for Year 11 IPT Assessment Task #2.) 2019. */

html>body {
  background: none;
  padding: 0;
  margin: 0;
  height: 100%;
  overflow: hidden;
  font-family: 'Trebuchet MS', sans-serif;
  /* Trebuchet MS as main font throughout website, sans-serif acting as a backup */
}

#wrapper {
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: hidden;
  position: absolute;
  background: #1B315E;
}

::-webkit-scrollbar {
  display: none;
}

* {
  box-sizing: border-box;
  /* Alignment of DropDown Navigation Menu and Slideshow */
}

.navigation {
  background: #444;
  overflow: hidden;
  top: 0;
}

.menuDropDown {
  overflow: hidden;
  float: left;
}

.menuDropDown>#menuButton {
  font-size: 12px;
  padding: 16px 16px;
  /* Will result in final height of navigation */
  margin: 0;
  outline: none;
  border: none;
  font: inherit;
  background: inherit;
  color: #FFF;
}

#menuButton:hover,
.navigation>.menuDropDown:hover>#menuButton {
  border: none;
  outline: none;
  background: #666;
  color: #1B315E;
}

.menuDropDown:hover>.menuContent {
  display: block;
}

.menuContent {
  display: none;
  position: absolute;
  background: none;
  width: 100%;
  left: 0;
  max-height: 85vh;
  overflow: auto;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.menuRow:after {
  display: table;
  clear: both;
  content: "";
}

.menuColumn {
  width: 25%;
  height: 100px;
  overflow-y: auto;
  padding: 5px;
  float: left;
  background: #666;
}

.menuColumn>a {
  float: none;
  display: block;
  text-align: left;
  text-decoration: none;
  font-size: 14px;
  padding: 8px;
  color: #1B315E;
}

.menuColumn>a.current {
  background: #777;
}

.menuColumn>a:hover {
  background: #888;
}

.logo {
  float: right;
  padding-right: 10px;
  width: 60px;
  height: 50px;
}

.main {
  width: 100%;
  height: calc(100vh - 43px);
  float: left;
  background: none;
  position: absolute;
  overflow: auto;
  padding: 8px;
}

.mainHeader {
  color: #FFF;
  text-align: center;
}

.mainImg {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
}

.mainBody {
  color: #FFF;
  padding: 8px;
}

.row:after {
  content: "";
  clear: both;
  display: table;
}

.column {
  float: left;
  width: 33.33%;
  padding: 8px;
}

#column {
  float: left;
  width: 50%;
  padding: 8px;
  background: #888;
  bottom: 0;
}

.sponsers {
  float: left;
  width: 20%;
  padding: 8px;
  -webkit-filter: grayscale(100%);
  filter: grayscale(100%);
}

.sponsers:hover {
  -webkit-filter: grayscale(80%);
  filter: grayscale(80%);
}

.slideshow {
  /* Slideshow Container containing Images, Sliders and Captions */
  position: relative;
  margin: auto;
  max-width: 1000px;
}

.slides {
  display: none;
}

.slideshowImages {
  width: 100%;
}

.slideButton {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  background: #888;
  color: #FFF;
  border: none;
  cursor: pointer;
  padding: 16px 32px;
  font-size: 18px;
  text-align: center;
  border-radius: 10px;
  font-weight: bold;
}

.mnaHeader {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
}

.slideButton:hover {
  background: #666;
}

.previous,
.next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  margin-top: -22px;
  padding: 16px;
  color: #FFF;
  font-weight: bold;
  font-size: 18px;
  transition: 0.3s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
}

.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

.previous:hover,
.next:hover {
  background: rgba(0, 0, 0, 0.8);
}

table {
  width: 100%;
  font-size: 16px;
  color: #FFF;
}

.tableCaption {
  font-weight: bold;
  font-size: 18px;
  color: #33CC33;
}

table,
th,
td {
  border-collapse: collapse;
  border: 2px solid #888;
}

th,
td {
  padding: 8px;
  text-align: left;
}

#headerTable {
  width: 33.33%;
  background: #888;
  font-size: 18px;
  color: #33CC33;
}

.linkProp {
  color: #FFF;
  text-decoration: underline;
}

.newsPanel {
  width: 100%;
  background: #888;
  height: 135px;
}

.imgNewsPreview {
  width: 215px;
  height: 135px;
  padding: 4px;
  float: left;
}

.newsHeaderPreview {
  color: #FFF;
  margin-top: 0px;
}

.newsBodyPreview {
  color: #FFF;
  margin-top: -12px;
}

.caption {
  color: #33CC33;
  text-align: center;
  position: absolute;
  font-size: 20px;
  width: 100%;
  padding: 8px 12px;
  bottom: 16px;
}

.collapsible {
  background: #888;
  color: #FFF;
  font-weight: bold;
  width: 100%;
  padding: 18px;
  cursor: pointer;
  font-size: 16px;
  outline: none;
  border: none;
  text-align: left;
}

.active,
.collapsible:hover {
  background: #666;
}

.collapsible:after {
  content: '\002B';
  color: #FFF;
  font-weight: bold;
  float: right;
  margin-left: 4px;
}

.active:after {
  content: '\2212';
}

.contentCollapsible {
  padding: 0px 18px;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
  background: #F8F8F8;
}

.fade {
  -webkit-animation-name: fade;
  /* To work on Safari (Apple) */
  -webkit-animation-duration: 1s;
  /* To work on Safari (Apple) */
  animation-name: fade;
  animation-duration: 1s;
}

.buttonReturn {
  position: absolute;
  margin-left: 20px;
  margin-top: 20px;
  background: #888;
  color: #FFF;
  border: none;
  cursor: pointer;
  font-size: 36px;
  text-align: center;
  border-radius: 50%;
  font-weight: bold;
}

.videoProp {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
  height: 400px;
}

@-webkit-keyframes fade {
  from {
    opacity: 0.4
  }
  to {
    opacity: 1
  }
}

@keyframes fade {
  from {
    opacity: 0.4
  }
  to {
    opacity: 1
  }
}

@media screen and (max-width: 600px) {
  /* Stacks navigation menu acting for the site to be responsive */
  .menuColumn {
    width: 100%;
    height: auto;
  }
}

@media screen and (max-width: 800px) {
  /* Stacks Image Header on Top - acting as responsive */
  .column,
  #column {
    width: 100%;
  }
}

@media screen and (max-width: 600px) {
  /* Responsive Sponser Images */
  .sponsers {
    width: 33.33%;
  }
}

@media screen and (max-width: 800px) {
  /* Increases video resolution as screen reduces */
  .videoProp {
    width: 100%;
  }
}

@media screen and (max-width: 600px) {
  /* Reduces font-size as screen resolution lowers */
  .newsBodyPreview {
    font-size: 14px;
  }
}

@media screen and (max-width: 300px) {
  /* Reduces font-sizes within the slideshow
 */
  .previous,
  .next,
  .caption {
    font-size: 14px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE HTML>
<!--
 ~ Copyright (c) Macleay Netball Association (made by Tom Carpenter for Year 11 IPT Assessment Task #2.) 2019.
-->
<html lang="en-AU">

<head>
  <title>Contact Us — Macleay Netball Association</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0">
  <link rel="stylesheet" href="../style.css" type="text/css">
  <!-- Internal Stylesheet -->
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
  <!-- External Font Stylesheet -->
  <link rel="shortcut icon" href="../Assets/Img/mnaHeader.png">
  <!-- Tab Browser Icon (Favicon) -->
</head>

<body>
  <div id="wrapper">
    <div class="navigation">
      <div class="menuDropDown">
        <button id="menuButton" title="Navigation Menu"><i class="fas fa-bars"></i> Menu</button>
        <div class="menuContent">
          <div class="menuRow">
            <div class="menuColumn">
              <i class="fas fa-home"></i> Home
              <i class="fas fa-address-book"></i> Association Contacts
            </div>
            <div class="menuColumn">
              <i class="fas fa-user-friends"></i> Weekly Draw
              <i class="far fa-newspaper"></i> News
            </div>
            <div class="menuColumn">
              <i class="fas fa-bookmark"></i> Quick Links
              <i class="fas fa-certificate"></i> Representative Teams
            </div>
            <div class="menuColumn">
              <i class="fas fa-file"></i> Documentation
              <i class="fas fa-phone"></i> Contact Us
            </div>
          </div>
        </div>
      </div>
      <img src="../Assets/Img/mnaHeader.png" alt="Macleay Netball Association" title="Macleay Netball Association" class="logo">
      <!-- Macleay Netball Association Main Logo -->
    </div>
    <!-- End of Navigation -->
    <div class="main">
      <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3417.0548484369647!2d152.83521681537312!3d-31.080401281517187!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x6b9ddf84d6da904b%3A0xfc941d1ded8f7a25!2sPam+Guyer+Netball+Centre!5e0!3m2!1sen!2sau!4v1559129788713!5m2!1sen!2sau"
        width="100%" height="400px" frameborder="0" style="border:0" allowfullscreen></iframe>
      <!-- Google Maps Embed -->
      <br>

      <div class="row">
        <div id="column">1</div>
        <div id="column">2</div>
      </div>
      <!-- End of Footer -->
    </div>
    <!-- End of Main -->
  </div>
  <!-- End of Wrapper -->
</body>

</html></code>```

Attached are some images if I put position:fixed bottom:0 in the #column CSS Code. Only Column 2 goes down, 1 is hidden.

答:
First of all id must be unique for an element, shouldn't set same id on two elements.

When you set position fixed on an element it is positioned relative to viewport, not relative to flow of the page.

Both of your elements have bottom: 0, which is relative to browser window, that's why your first element is covered by the second one (it's not hidden). You can group them in the same parent and position the parent, so your elements are stacked as expected. Take a look at the following code:

body {
    min-height: 200vh;
}

#column {
    display: block;
    padding 15px;
    width: 100%;
    position: fixed;
    bottom: 0;
    background: #e5e5e5;
}

#column div {
    display: block;
    padding: 10px;
    width: 100%;
    background: #9b009b;
    color: #fff;
    margin-bottom: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="column">
    <div>first col</div>
    <div>second col</div>
</div></code>```

Body:
I have a two-columned div element that I need to have at the bottom of the page to act as a footer. The problem is I have tried using position:fixed and bottom:0 to make the element appear at the bottom. This works but only brings one of the #column divs down to the bottom, the other disappears. I would appreciate any assistance.

Code:

/* ~ Copyright (c) Macleay Netball Association (made by Tom Carpenter for Year 11 IPT Assessment Task #2.) 2019. */

html>body {
  background: none;
  padding: 0;
  margin: 0;
  height: 100%;
  overflow: hidden;
  font-family: 'Trebuchet MS', sans-serif;
  /* Trebuchet MS as main font throughout website, sans-serif acting as a backup */
}

#wrapper {
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: hidden;
  position: absolute;
  background: #1B315E;
}

::-webkit-scrollbar {
  display: none;
}

* {
  box-sizing: border-box;
  /* Alignment of DropDown Navigation Menu and Slideshow */
}

.navigation {
  background: #444;
  overflow: hidden;
  top: 0;
}

.menuDropDown {
  overflow: hidden;
  float: left;
}

.menuDropDown>#menuButton {
  font-size: 12px;
  padding: 16px 16px;
  /* Will result in final height of navigation */
  margin: 0;
  outline: none;
  border: none;
  font: inherit;
  background: inherit;
  color: #FFF;
}

#menuButton:hover,
.navigation>.menuDropDown:hover>#menuButton {
  border: none;
  outline: none;
  background: #666;
  color: #1B315E;
}

.menuDropDown:hover>.menuContent {
  display: block;
}

.menuContent {
  display: none;
  position: absolute;
  background: none;
  width: 100%;
  left: 0;
  max-height: 85vh;
  overflow: auto;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.menuRow:after {
  display: table;
  clear: both;
  content: "";
}

.menuColumn {
  width: 25%;
  height: 100px;
  overflow-y: auto;
  padding: 5px;
  float: left;
  background: #666;
}

.menuColumn>a {
  float: none;
  display: block;
  text-align: left;
  text-decoration: none;
  font-size: 14px;
  padding: 8px;
  color: #1B315E;
}

.menuColumn>a.current {
  background: #777;
}

.menuColumn>a:hover {
  background: #888;
}

.logo {
  float: right;
  padding-right: 10px;
  width: 60px;
  height: 50px;
}

.main {
  width: 100%;
  height: calc(100vh - 43px);
  float: left;
  background: none;
  position: absolute;
  overflow: auto;
  padding: 8px;
}

.mainHeader {
  color: #FFF;
  text-align: center;
}

.mainImg {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
}

.mainBody {
  color: #FFF;
  padding: 8px;
}

.row:after {
  content: "";
  clear: both;
  display: table;
}

.column {
  float: left;
  width: 33.33%;
  padding: 8px;
}

#column {
  float: left;
  width: 50%;
  padding: 8px;
  background: #888;
  bottom: 0;
}

.sponsers {
  float: left;
  width: 20%;
  padding: 8px;
  -webkit-filter: grayscale(100%);
  filter: grayscale(100%);
}

.sponsers:hover {
  -webkit-filter: grayscale(80%);
  filter: grayscale(80%);
}

.slideshow {
  /* Slideshow Container containing Images, Sliders and Captions */
  position: relative;
  margin: auto;
  max-width: 1000px;
}

.slides {
  display: none;
}

.slideshowImages {
  width: 100%;
}

.slideButton {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  background: #888;
  color: #FFF;
  border: none;
  cursor: pointer;
  padding: 16px 32px;
  font-size: 18px;
  text-align: center;
  border-radius: 10px;
  font-weight: bold;
}

.mnaHeader {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
}

.slideButton:hover {
  background: #666;
}

.previous,
.next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  margin-top: -22px;
  padding: 16px;
  color: #FFF;
  font-weight: bold;
  font-size: 18px;
  transition: 0.3s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
}

.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

.previous:hover,
.next:hover {
  background: rgba(0, 0, 0, 0.8);
}

table {
  width: 100%;
  font-size: 16px;
  color: #FFF;
}

.tableCaption {
  font-weight: bold;
  font-size: 18px;
  color: #33CC33;
}

table,
th,
td {
  border-collapse: collapse;
  border: 2px solid #888;
}

th,
td {
  padding: 8px;
  text-align: left;
}

#headerTable {
  width: 33.33%;
  background: #888;
  font-size: 18px;
  color: #33CC33;
}

.linkProp {
  color: #FFF;
  text-decoration: underline;
}

.newsPanel {
  width: 100%;
  background: #888;
  height: 135px;
}

.imgNewsPreview {
  width: 215px;
  height: 135px;
  padding: 4px;
  float: left;
}

.newsHeaderPreview {
  color: #FFF;
  margin-top: 0px;
}

.newsBodyPreview {
  color: #FFF;
  margin-top: -12px;
}

.caption {
  color: #33CC33;
  text-align: center;
  position: absolute;
  font-size: 20px;
  width: 100%;
  padding: 8px 12px;
  bottom: 16px;
}

.collapsible {
  background: #888;
  color: #FFF;
  font-weight: bold;
  width: 100%;
  padding: 18px;
  cursor: pointer;
  font-size: 16px;
  outline: none;
  border: none;
  text-align: left;
}

.active,
.collapsible:hover {
  background: #666;
}

.collapsible:after {
  content: '\002B';
  color: #FFF;
  font-weight: bold;
  float: right;
  margin-left: 4px;
}

.active:after {
  content: '\2212';
}

.contentCollapsible {
  padding: 0px 18px;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
  background: #F8F8F8;
}

.fade {
  -webkit-animation-name: fade;
  /* To work on Safari (Apple) */
  -webkit-animation-duration: 1s;
  /* To work on Safari (Apple) */
  animation-name: fade;
  animation-duration: 1s;
}

.buttonReturn {
  position: absolute;
  margin-left: 20px;
  margin-top: 20px;
  background: #888;
  color: #FFF;
  border: none;
  cursor: pointer;
  font-size: 36px;
  text-align: center;
  border-radius: 50%;
  font-weight: bold;
}

.videoProp {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
  height: 400px;
}

@-webkit-keyframes fade {
  from {
    opacity: 0.4
  }
  to {
    opacity: 1
  }
}

@keyframes fade {
  from {
    opacity: 0.4
  }
  to {
    opacity: 1
  }
}

@media screen and (max-width: 600px) {
  /* Stacks navigation menu acting for the site to be responsive */
  .menuColumn {
    width: 100%;
    height: auto;
  }
}

@media screen and (max-width: 800px) {
  /* Stacks Image Header on Top - acting as responsive */
  .column,
  #column {
    width: 100%;
  }
}

@media screen and (max-width: 600px) {
  /* Responsive Sponser Images */
  .sponsers {
    width: 33.33%;
  }
}

@media screen and (max-width: 800px) {
  /* Increases video resolution as screen reduces */
  .videoProp {
    width: 100%;
  }
}

@media screen and (max-width: 600px) {
  /* Reduces font-size as screen resolution lowers */
  .newsBodyPreview {
    font-size: 14px;
  }
}

@media screen and (max-width: 300px) {
  /* Reduces font-sizes within the slideshow
 */
  .previous,
  .next,
  .caption {
    font-size: 14px;
  }
}

<!DOCTYPE HTML>

  <title>Contact Us — Macleay Netball Association</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0">
  <link rel="stylesheet" href="../style.css" type="text/css">

  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">

  <link rel="shortcut icon" href="../Assets/Img/mnaHeader.png">

        <button id="menuButton" title="Navigation Menu"> Menu</button>

               Home
               Association Contacts

               Weekly Draw
               News

               Quick Links
               Representative Teams

               Documentation
               Contact Us

1

2

Attached are some images if I put position:fixed bottom:0 in the #column CSS Code. Only Column 2 goes down, 1 is hidden.

Body:
First of all id must be unique for an element, shouldn't set same id on two elements.

When you set position fixed on an element it is positioned relative to viewport, not relative to flow of the page.

Both of your elements have bottom: 0, which is relative to browser window, that's why your first element is covered by the second one (it's not hidden). You can group them in the same parent and position the parent, so your elements are stacked as expected. Take a look at the following code:

body {
    min-height: 200vh;
}

#column {
    display: block;
    padding 15px;
    width: 100%;
    position: fixed;
    bottom: 0;
    background: #e5e5e5;
}

#column div {
    display: block;
    padding: 10px;
    width: 100%;
    background: #9b009b;
    color: #fff;
    margin-bottom: 10px;
}

<div id="column">
    <div>first col</div>
    <div>second col</div>
</div>


问:
VBA, Excel. Execute code that offsets & resizes a range & then copies it. "Compile error: Invalid watch expression"
I'm trying to offset,resize and copy a range containing data and is typing this line of code in the immediate window:

```<code>shAll.Range("A1:I78").Offset(1).Resize(.Rows.Count - 1, .Columns.Count -
1).SpecialCells(xlCellTypeVisible).copy
</code>```

When I press enter I get this error: "Compile error: Invalid watch expression"

Is it a syntax issue?

This part of the code it working fine when executed in the immediate window:

```<code>shAll.Range("A1:I78").Offset(1).select
</code>```

It's getting offseted the way I want. The remaining part is to resize and copy it.

By the way, the range shAll.Range("A1:I78") contains data in all cells.

Thanks in advance!

答:
You have not specified which object .Rows and .Columns apply to.

If they apply to the range then

```<code>With shAll.Range("A1:I78")
    .Offset(1).Resize(.Rows.Count - 1, .Columns.Count - 1).SpecialCells(xlCellTypeVisible).copy
End with
</code>```

or

```<code>shAll.Range("A1:I78").Offset(1).Resize(shAll.Range("A1:I78").Rows.Count - 1, _
shAll.Range("A1:I78").Columns.Count - 1).SpecialCells(xlCellTypeVisible).copy
</code>```

Body:
I'm trying to offset,resize and copy a range containing data and is typing this line of code in the immediate window:

shAll.Range("A1:I78").Offset(1).Resize(.Rows.Count - 1, .Columns.Count -
1).SpecialCells(xlCellTypeVisible).copy

When I press enter I get this error: "Compile error: Invalid watch expression"

Is it a syntax issue?

This part of the code it working fine when executed in the immediate window:

shAll.Range("A1:I78").Offset(1).select

It's getting offseted the way I want. The remaining part is to resize and copy it.

By the way, the range shAll.Range("A1:I78") contains data in all cells.

Thanks in advance!

Body:
You have not specified which object .Rows and .Columns apply to.

If they apply to the range then

With shAll.Range("A1:I78")
    .Offset(1).Resize(.Rows.Count - 1, .Columns.Count - 1).SpecialCells(xlCellTypeVisible).copy
End with

or

shAll.Range("A1:I78").Offset(1).Resize(shAll.Range("A1:I78").Rows.Count - 1, _
shAll.Range("A1:I78").Columns.Count - 1).SpecialCells(xlCellTypeVisible).copy


问:
Loading indication with a delay and anti-flickering in RxJS
I want to implement loading indication using RxJS (version 6). A loading indicator (a spinner) would be shown in a component before asynchronous data call finishes. I have some rules to implement (whether these rules are correct might be another question, maybe leave a comment):

If the data arrives successfully earlier than in 1 second, no indicator should be shown (and data should be rendered normally)

If the call fails earlier than in 1 second, no indicator should be shown (and error message should be rendered)

If the data arrives later than in 1 second an indicator should be shown for at least 1 second (to prevent flashing spinner, the data should be rendered afterwards)

If the call fails later than in 1 second an indicator should be shown for at least 1 second

If the call takes more than 10 seconds the call should be canceled (and error message displayed)

I am implementing this in an Angular project, but I believe, that this is not Angular specific.

I have found some pieces of this puzzle, but I need help to assemble them together.

In this SO answer there is an implementation of an operator that delays the showing of a loading indicator.

A nice but incomplete implementation for Angular is described in this article.

Showing loading indicator for a minimum amount of time is described in this Medium article.

答:
First of all, this is a nice question, Lukas!

Foreword: while there are other ways to achieve what you ask, I just wanted to make my answer more like a detailed step-by-step tutorial. Do take a look at Brandon's amazing solution, right below this one.

For convenience, let's imagine that we have a method that does the request and returns us an Observable of string messages:

const makeARequest: () => Observable<{ msg: string }>;
```
<p>Now we can declare our Observables that will hold the result:</p>
<pre class="lang-js prettyprint-override"><code>// Our result will be either a string message or an error
const result$: Observable<{ msg: string } | { error: string }>;
</code>```

and a loading indication:

// This stream will control a loading indicator visibility
// if we get a true on the stream -- we'll show a loading indicator
// on false -- we'll hide it
const loadingIndicator$: Observable<boolean>;
```
<p>Now, to solve #1</p>
<blockquote>
<p>If the data arrives successfully earlier than in 1 second, no indicator should be shown (and data should be rendered normally)</p>
</blockquote>
<p>We can set a timer for 1 second and turn that timer event into a <code>true</code> value, meaning that loading indicator is shown. <code>takeUntil</code> will ensure that if a <code>result$</code> comes before 1 second — we wont show the loading indicator:</p>
<pre class="lang-js prettyprint-override"><code>const showLoadingIndicator$ = timer(1000).pipe(
  mapTo(true),       // turn the value into `true`, meaning loading is shown
  takeUntil(result$) // emit only if result$ wont emit before 1s
);
</code>```

#2

If the call fails earlier than in 1 second, no indicator should be shown (and error message should be rendered)

While the first part will be solved by #1, to show an error message we'll need to catch an error from the source stream and turn it into some sort of { error: 'Oops' }. A catchError operator will let us do that:

result$ = makeARequest().pipe(
  catchError(() => {
    return of({ error: 'Oops' });
  })
)
```
<p>You might've noticed that we're kind of using the <code>result$</code> in two places. This means that we'll have two subscriptions to the same request Observable, which will make two requests, which is not what we desire. To solve this, we can simply share this observable among subscribers:</p>
<pre class="lang-js prettyprint-override"><code>result$ = makeARequest().pipe(
  catchError(() => { // an error from the request will be handled here
    return of({ error: 'Oops' });
  }),
  share()
)
</code>```

#3

If the data arrives later than in 1 second an indicator should be shown for at least 1 second (to prevent flashing spinner, the data should be rendered afterwards)

First, we have a way to turn the loading indicator on, though we currently don't turn it off. Lets use an event on the result$ stream as an notification that we can hide the loading indicator. Once we receive a result — we can hide the indicator:

// this we'll use as an off switch:
result$.pipe( mapTo(false) )
```
<p>So we can <code>merge</code> the on-off switching:</p>
<pre class="lang-js prettyprint-override"><code>const showLoadingIndicator$ = merge(
  // ON in 1second
  timer(1000).pipe( mapTo(true), takeUntil(result$) ),

  // OFF once we receive a result
  result$.pipe( mapTo(false) )
)
</code>```

Now we have loading indicator switching on and off, though we need to get rid of loading indicator being flashy and show it at least for 1 second. I guess, the simplest way would be to combineLatest values of the off switch and a 2 seconds timer:

const showLoadingIndicator$ = merge(
  // ON in 1second
  timer(1000).pipe( mapTo(true), takeUntil(result$) ),

  // OFF once we receive a result, yet at least in 2s
  combineLatest(result$, timer(2000)).pipe( mapTo(false) )
)
```
<p><em>NOTE:</em> this approach might give us a redundant <em>off</em> switch at 2s, if the result was received before 2nd second. We'll deal with that later.</p>
<p>#4</p>
<blockquote>
<p>If the call fails later than in 1 second an indicator should be shown for at least 1 second</p>
</blockquote>
<p>Our solution to #3 already has an anti-flash code and in #2 we've handled the case when stream throws an error, so we're good here.</p>
<p>#5</p>
<blockquote>
<p>If the call takes more than 10 seconds the call should be canceled (and error message displayed)</p>
</blockquote>
<p>To help us with cancelling long-running requests, we have a timeout operator: it will throw an error if the source observable wont emit a value within given time</p>
<pre class="lang-js prettyprint-override"><code>result$ = makeARequest().pipe(
  timeout(10000),     // 10 seconds timeout for the result to come
  catchError(() => {  // an error from the request or timeout will be handled here
    return of({ error: 'Oops' });
  }),
  share()
)
</code>```

We're almost done, just a small improvement left. Lets start our showLoadingIndicator$ stream with a false value, indicating that we're not showing loader at the start. And use a distinctUntilChanged to omit redundant off to off switches that we can get due to our approach in #3.

To sum up everything, heres what we've achieved:

const { fromEvent, timer, combineLatest, merge, throwError, of } = rxjs;
const { timeout, share, catchError, mapTo, takeUntil, startWith, distinctUntilChanged, switchMap } = rxjs.operators;

function startLoading(delayTime, shouldError){
  console.log('====');
  const result$ = makeARequest(delayTime, shouldError).pipe(
    timeout(10000),     // 10 seconds timeout for the result to come
    catchError(() => {  // an error from the request or timeout will be handled here
      return of({ error: 'Oops' });
    }),
    share()
  );

  const showLoadingIndicator$ = merge(
    // ON in 1second
    timer(1000).pipe( mapTo(true), takeUntil(result$) ),

    // OFF once we receive a result, yet at least in 2s
    combineLatest(result$, timer(2000)).pipe( mapTo(false) )
  )
  .pipe(
    startWith(false),
    distinctUntilChanged()
  );

  result$.subscribe((result)=>{
    if (result.error) { console.log('Error: ', result.error); }
    if (result.msg) { console.log('Result: ', result.msg); }
  });

  showLoadingIndicator$.subscribe(isLoading =>{
    console.log(isLoading ? '⏳ loading' : ' free');
  });
}

function makeARequest(delayTime, shouldError){
  return timer(delayTime).pipe(switchMap(()=>{
    return shouldError
      ? throwError('X')
      : of({ msg: 'awesome' });
  }))
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b>Fine requests</b>

<button
 onclick="startLoading(500)"
>500ms</button>

<button
 onclick="startLoading(1500)"
>1500ms</button>

<button
 onclick="startLoading(3000)"
>3000ms</button>

<button
 onclick="startLoading(11000)"
>11000ms</button>

<b>Error requests</b>

<button
 onclick="startLoading(500, true)"
>Err 500ms</button>

<button
 onclick="startLoading(1500, true)"
>Err 1500ms</button>

<button
 onclick="startLoading(3000, true)"
>Err 3000ms</button>

<script src="https://unpkg.com/rxjs@6.5.2/bundles/rxjs.umd.min.js"></script></code>```

Hope this helps

Body:
First of all, this is a nice question, Lukas!

Foreword: while there are other ways to achieve what you ask, I just wanted to make my answer more like a detailed step-by-step tutorial. Do take a look at Brandon's amazing solution, right below this one.

For convenience, let's imagine that we have a method that does the request and returns us an Observable of string messages:

const makeARequest: () => Observable<{ msg: string }>;

Now we can declare our Observables that will hold the result:

// Our result will be either a string message or an error
const result$: Observable<{ msg: string } | { error: string }>;

and a loading indication:

// This stream will control a loading indicator visibility
// if we get a true on the stream -- we'll show a loading indicator
// on false -- we'll hide it
const loadingIndicator$: Observable<boolean>;

Now, to solve #1

If the data arrives successfully earlier than in 1 second, no indicator should be shown (and data should be rendered normally)

We can set a timer for 1 second and turn that timer event into a true value, meaning that loading indicator is shown. takeUntil will ensure that if a result$ comes before 1 second — we wont show the loading indicator:

const showLoadingIndicator$ = timer(1000).pipe(
  mapTo(true),       // turn the value into `true`, meaning loading is shown
  takeUntil(result$) // emit only if result$ wont emit before 1s
);

#2

If the call fails earlier than in 1 second, no indicator should be shown (and error message should be rendered)

While the first part will be solved by #1, to show an error message we'll need to catch an error from the source stream and turn it into some sort of { error: 'Oops' }. A catchError operator will let us do that:

result$ = makeARequest().pipe(
  catchError(() => {
    return of({ error: 'Oops' });
  })
)

You might've noticed that we're kind of using the result$ in two places. This means that we'll have two subscriptions to the same request Observable, which will make two requests, which is not what we desire. To solve this, we can simply share this observable among subscribers:

result$ = makeARequest().pipe(
  catchError(() => { // an error from the request will be handled here
    return of({ error: 'Oops' });
  }),
  share()
)

#3

If the data arrives later than in 1 second an indicator should be shown for at least 1 second (to prevent flashing spinner, the data should be rendered afterwards)

First, we have a way to turn the loading indicator on, though we currently don't turn it off. Lets use an event on the result$ stream as an notification that we can hide the loading indicator. Once we receive a result — we can hide the indicator:

// this we'll use as an off switch:
result$.pipe( mapTo(false) )

So we can merge the on-off switching:

const showLoadingIndicator$ = merge(
  // ON in 1second
  timer(1000).pipe( mapTo(true), takeUntil(result$) ),

  // OFF once we receive a result
  result$.pipe( mapTo(false) )
)

Now we have loading indicator switching on and off, though we need to get rid of loading indicator being flashy and show it at least for 1 second. I guess, the simplest way would be to combineLatest values of the off switch and a 2 seconds timer:

const showLoadingIndicator$ = merge(
  // ON in 1second
  timer(1000).pipe( mapTo(true), takeUntil(result$) ),

  // OFF once we receive a result, yet at least in 2s
  combineLatest(result$, timer(2000)).pipe( mapTo(false) )
)

NOTE: this approach might give us a redundant off switch at 2s, if the result was received before 2nd second. We'll deal with that later.

#4

If the call fails later than in 1 second an indicator should be shown for at least 1 second

Our solution to #3 already has an anti-flash code and in #2 we've handled the case when stream throws an error, so we're good here.

#5

If the call takes more than 10 seconds the call should be canceled (and error message displayed)

To help us with cancelling long-running requests, we have a timeout operator: it will throw an error if the source observable wont emit a value within given time

result$ = makeARequest().pipe(
  timeout(10000),     // 10 seconds timeout for the result to come
  catchError(() => {  // an error from the request or timeout will be handled here
    return of({ error: 'Oops' });
  }),
  share()
)

We're almost done, just a small improvement left. Lets start our showLoadingIndicator$ stream with a false value, indicating that we're not showing loader at the start. And use a distinctUntilChanged to omit redundant off to off switches that we can get due to our approach in #3.

To sum up everything, heres what we've achieved:

const { fromEvent, timer, combineLatest, merge, throwError, of } = rxjs;
const { timeout, share, catchError, mapTo, takeUntil, startWith, distinctUntilChanged, switchMap } = rxjs.operators;

function startLoading(delayTime, shouldError){
  console.log('====');
  const result$ = makeARequest(delayTime, shouldError).pipe(
    timeout(10000),     // 10 seconds timeout for the result to come
    catchError(() => {  // an error from the request or timeout will be handled here
      return of({ error: 'Oops' });
    }),
    share()
  );

  const showLoadingIndicator$ = merge(
    // ON in 1second
    timer(1000).pipe( mapTo(true), takeUntil(result$) ),

    // OFF once we receive a result, yet at least in 2s
    combineLatest(result$, timer(2000)).pipe( mapTo(false) )
  )
  .pipe(
    startWith(false),
    distinctUntilChanged()
  );

  result$.subscribe((result)=>{
    if (result.error) { console.log('Error: ', result.error); }
    if (result.msg) { console.log('Result: ', result.msg); }
  });

  showLoadingIndicator$.subscribe(isLoading =>{
    console.log(isLoading ? '⏳ loading' : ' free');
  });
}

function makeARequest(delayTime, shouldError){
  return timer(delayTime).pipe(switchMap(()=>{
    return shouldError
      ? throwError('X')
      : of({ msg: 'awesome' });
  }))
}

<b>Fine requests</b>

<button
 onclick="startLoading(500)"
>500ms</button>

<button
 onclick="startLoading(1500)"
>1500ms</button>

<button
 onclick="startLoading(3000)"
>3000ms</button>

<button
 onclick="startLoading(11000)"
>11000ms</button>

<b>Error requests</b>

<button
 onclick="startLoading(500, true)"
>Err 500ms</button>

<button
 onclick="startLoading(1500, true)"
>Err 1500ms</button>

<button
 onclick="startLoading(3000, true)"
>Err 3000ms</button>

<script src="https://unpkg.com/rxjs@6.5.2/bundles/rxjs.umd.min.js"></script>

Hope this helps


问:
How to fix "sqlite3.h is missing"?
I am trying to do some project in ruby and make like this

git commit -am "Add hello"
heroku create
git push heroku master

then I got this error

```<code>remote:        checking for sqlite3.h... no
remote:        sqlite3.h is missing. Try 'brew install sqlite3',
remote:        'yum install sqlite-devel' or 'apt-get install libsqlite3-dev'
remote:        and check your shared library search path (the
remote:        location where your sqlite3 shared library is located).
remote:        *** extconf.rb failed ***
remote:        Could not create Makefile due to some reason, probably lack of necessary
remote:        libraries and/or headers.  Check the mkmf.log file for more details.  You may
remote:        need configuration options.
remote:
remote:        Provided configuration options:
remote:         --with-opt-dir
remote:         --without-opt-dir
remote:         --with-opt-include
remote:         --without-opt-include=${opt-dir}/include
remote:         --with-opt-lib
remote:         --without-opt-lib=${opt-dir}/lib
remote:         --with-make-prog
remote:         --without-make-prog
remote:         --srcdir=.
remote:        checking for sqlite3.h... no
remote:        sqlite3.h is missing. Try 'brew install sqlite3',
remote:        'yum install sqlite-devel' or 'apt-get install libsqlite3-dev'
remote:        and check your shared library search path (the
remote:        location where your sqlite3 shared library is located).
remote:        *** extconf.rb failed ***
remote:        Could not create Makefile due to some reason, probably lack of necessary
remote:        libraries and/or headers.  Check the mkmf.log file for more details.  You may
remote:        need configuration options.
remote:
remote:        Provided configuration options:
remote:         --with-opt-dir
remote:         --without-opt-dir
remote:         --with-opt-include
remote:         --without-opt-include=${opt-dir}/include
remote:         --with-opt-lib
remote:         --without-opt-lib=${opt-dir}/lib
remote:         --with-make-prog
remote:         --without-make-prog
remote:         --srcdir=.
</code>```

I tried to change my gemfile like this tutorial https://devcenter.heroku.com/articles/sqlite3 and this tutorial Detected sqlite3 gem which is not supported on Heroku but nothing changed.

I tried to install sqlite3 by this

```<code>gem install sqlite3
</code>```

and success, but nothing changed. It still give me error when I want to push heroku master.

Could you please give me any suggestion?

答:
After removing sqlite from gemfile (or making it be only in development/test group) - run bundle install and commit changes.

Point is that heroku is container-based, you need to distinguish that from your local machine - local files are only getting there when they are committed and pushed, then heroku builds a readonly (stricly speaking, its "disk" can be written, but all changes can be lost at any time) container that it then runs.

Title: How to fix "sqlite3.h is missing"?

Body:
I am trying to do some project in ruby and make like this

git commit -am "Add hello"
heroku create
git push heroku master

then I got this error

remote:        checking for sqlite3.h... no
remote:        sqlite3.h is missing. Try 'brew install sqlite3',
remote:        'yum install sqlite-devel' or 'apt-get install libsqlite3-dev'
remote:        and check your shared library search path (the
remote:        location where your sqlite3 shared library is located).
remote:        *** extconf.rb failed ***
remote:        Could not create Makefile due to some reason, probably lack of necessary
remote:        libraries and/or headers.  Check the mkmf.log file for more details.  You may
remote:        need configuration options.
remote:
remote:        Provided configuration options:
remote:         --with-opt-dir
remote:         --without-opt-dir
remote:         --with-opt-include
remote:         --without-opt-include=${opt-dir}/include
remote:         --with-opt-lib
remote:         --without-opt-lib=${opt-dir}/lib
remote:         --with-make-prog
remote:         --without-make-prog
remote:         --srcdir=.
remote:        checking for sqlite3.h... no
remote:        sqlite3.h is missing. Try 'brew install sqlite3',
remote:        'yum install sqlite-devel' or 'apt-get install libsqlite3-dev'
remote:        and check your shared library search path (the
remote:        location where your sqlite3 shared library is located).
remote:        *** extconf.rb failed ***
remote:        Could not create Makefile due to some reason, probably lack of necessary
remote:        libraries and/or headers.  Check the mkmf.log file for more details.  You may
remote:        need configuration options.
remote:
remote:        Provided configuration options:
remote:         --with-opt-dir
remote:         --without-opt-dir
remote:         --with-opt-include
remote:         --without-opt-include=${opt-dir}/include
remote:         --with-opt-lib
remote:         --without-opt-lib=${opt-dir}/lib
remote:         --with-make-prog
remote:         --without-make-prog
remote:         --srcdir=.

I tried to change my gemfile like this tutorial https://devcenter.heroku.com/articles/sqlite3 and this tutorial Detected sqlite3 gem which is not supported on Heroku but nothing changed.

I tried to install sqlite3 by this

gem install sqlite3

and success, but nothing changed. It still give me error when I want to push heroku master.

Could you please give me any suggestion?


问:
Automating the maintenance of Athena views
I am currently working on creating a data lake where we can compile, combine and analysis multiple data sets in S3.

I am using Athena and Quicksight as a central part of this to be able to quickly query and explore the data.  To make things easier in Quicksight for end-users, I am creating many Athena views that do some basic transformation and aggregations.

I would like to be able to source control my views and create some automation around them so that we can have a code-driven approach and not rely on users manually updating views and running DDL to update the definitions.

There does not seem to be any support in Cloudformation for Athena views.

My current approach would be to just save the create or replace view as ... DDL in an .sql file in source control and then create some sort of script that runs the DDL so it could be made part of a continuous integration solution.

Anyone have any other experience with automation and CI for Athena views?

答:
I think you could use AWS Glue

When Should I Use AWS Glue?

You can use AWS Glue to build a data warehouse to organize, cleanse,
  validate, and format data. You can transform and move AWS Cloud data
  into your data store. You can also load data from disparate sources
  into your data warehouse for regular reporting and analysis. By
  storing it in a data warehouse, you integrate information from
  different parts of your business and provide a common source of data
  for decision making.

AWS Glue simplifies many tasks when you are building a data warehouse:

Discovers and catalogs metadata about your data stores into a central catalog.

You can process semi-structured data, such as clickstream or process logs.

Populates the AWS Glue Data Catalog with table definitions from scheduled crawler programs. Crawlers call classifier logic to infer
  the schema, format, and data types of your data. This metadata is
  stored as tables in the AWS Glue Data Catalog and used in the
  authoring process of your ETL jobs.

Generates ETL scripts to transform, flatten, and enrich your data from source to target.

Detects schema changes and adapts based on your preferences.

Triggers your ETL jobs based on a schedule or event. You can initiate jobs automatically to move your data into your data
  warehouse. Triggers can be used to create a dependency flow between
  jobs.

Gathers runtime metrics to monitor the activities of your data warehouse.

Handles errors and retries automatically.

Scales resources, as needed, to run your jobs.

https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html


问:
Wordpress : HTML code to insert before and after a custom posts type loop
I'm blocked with an issue on wordpress and I need your help.

On my homepage, I would like to display a list of custom posts types (FAQ). For that, I used the widgets tool (wp-admin/widgets.php) with a widget Post loop (which seems to be added by the SiteOrigin Widgets Bundle plugin) and an associated template (path : /wp-content/themes/construction-field-pro/template-parts/) for the display of the different FAQ items.

The issue is that I should call HTML before and after that loop items and I never success it. I tried by 2 ways :

1 - by adding HTML widgets before and after the loop but WordPress is blocking the save as HTML end tags or start tags are missing.

2 - by adding short codes (which contains the desired html) before and after the loop. Saving is possible in that case but, at rendering, html end tags or start tags are added automatically which I do not expect.

So i need your help. How can I insert those loop items in an HTML blocks ?

Thank you in advance for your help.

Best regards,

答:
If I have understood this correctly, you are just trying to loop through your FAQs, which is a custom post type and to do this you have chosen to use widgets? Before and after the loop you are looking to add HTML code?

Why not just put the code directly into your homepage? Locate the place on the homepage you want the list to appear and enter:

<?php
$the_query = new WP_Query(array(
  'post_type'         => 'faq_post_type_name',
  'order'             => 'ASC',
  'orderby'           => 'date',
  'posts_per_page'    => -1
));

if ( $the_query->have_posts() ) : ?>

    <?php while ( $the_query->have_posts() ) :$the_query->the_post(); ?>

      <?php the_title(); ?>

    <?php endwhile; ?>

<?php endif; wp_reset_query(); ?>```

Body:
If I have understood this correctly, you are just trying to loop through your FAQs, which is a custom post type and to do this you have chosen to use widgets? Before and after the loop you are looking to add HTML code?

Why not just put the code directly into your homepage? Locate the place on the homepage you want the list to appear and enter:

<?php
$the_query = new WP_Query(array(
  'post_type'         => 'faq_post_type_name',
  'order'             => 'ASC',
  'orderby'           => 'date',
  'posts_per_page'    => -1
));

if ( $the_query->have_posts() ) : ?>
  <!-- Enter HTML before loop here -->
  <ul>
    <?php while ( $the_query->have_posts() ) :$the_query->the_post(); ?>
    <li>
      <?php the_title(); ?>
    </li>
    <?php endwhile; ?>
  </ul>
  <!-- Enter HTML after loop here -->
<?php endif; wp_reset_query(); ?>


问:
Random number generator doesn't produce expected numbers within a given range using values from input fields
I'm trying to generate a random number between two given values. I'm able to produce this with a pretty standard little function, however when I try to set the maximum and minimum values through an input field, I get some unexpected results.

This is using jQuery, which isn't necessary for this particular function but is needed for the larger project.

Here's an example of what I'm finding:

https://jsfiddle.net/u2k41hzd/

```<code>function randomNumber(min, max) {
    points = Math.floor(Math.random() * (max - min + 1) + min);
}

$( "button" ).on( "click", function ( event ) {
    minPoints = $( ".min-points" ).val();
    maxPoints = $( ".max-points" ).val();
    randomNumber(minPoints, maxPoints);
    $(".random").html(points);
});
</code>```

In the case of the minimum number being 1 and the maximum being 6, I would expect to get numbers between 1 and 6. However, I get numbers between 0 and 5.

If the minimum number is 2 and the maximum 6, I would expect to get numbers between 2 and 6, but get numbers between 0 and 4. Passing in 3 and 6 gives numbers between 0 and 3, and so on.

Ignoring the input values and hard coding them instead seems produce expected results with no issue. Essentially I'm just unsure as to why the input values are behaving as they are. I'm sure I've just misunderstood something or made a mistake somewhere, but I've not been able to determine the reason!

答:
The issue is that you need to add the min to the rounded number, not to the randomly generated number:

```<code>function randomNumber(min, max) {
    points = Math.floor(Math.random() * (max - min + 1)) + min;
}
</code>```

To explain further, for the case of 2 and 9:

Math.random() generates a number between 0 and 0.999999999...

max - min + 1 = 8

So the generated number will be in the range 8 * 0 and 8 * 0.99999999...

Flooring it will round down in the range [0, 7]

The result would need to be offset by the starting number (i.e. the minimum allowed number - 2)

Body:
I'm trying to generate a random number between two given values. I'm able to produce this with a pretty standard little function, however when I try to set the maximum and minimum values through an input field, I get some unexpected results.

This is using jQuery, which isn't necessary for this particular function but is needed for the larger project.

Here's an example of what I'm finding:

https://jsfiddle.net/u2k41hzd/

function randomNumber(min, max) {
    points = Math.floor(Math.random() * (max - min + 1) + min);
}

$( "button" ).on( "click", function ( event ) {
    minPoints = $( ".min-points" ).val();
    maxPoints = $( ".max-points" ).val();
    randomNumber(minPoints, maxPoints);
    $(".random").html(points);
});

In the case of the minimum number being 1 and the maximum being 6, I would expect to get numbers between 1 and 6. However, I get numbers between 0 and 5.

If the minimum number is 2 and the maximum 6, I would expect to get numbers between 2 and 6, but get numbers between 0 and 4. Passing in 3 and 6 gives numbers between 0 and 3, and so on.

Ignoring the input values and hard coding them instead seems produce expected results with no issue. Essentially I'm just unsure as to why the input values are behaving as they are. I'm sure I've just misunderstood something or made a mistake somewhere, but I've not been able to determine the reason!

Body:
The issue is that you need to add the min to the rounded number, not to the randomly generated number:

function randomNumber(min, max) {
    points = Math.floor(Math.random() * (max - min + 1)) + min;
}

To explain further, for the case of 2 and 9:

Math.random() generates a number between 0 and 0.999999999...

max - min + 1 = 8

So the generated number will be in the range 8 * 0 and 8 * 0.99999999...

Flooring it will round down in the range [0, 7]

The result would need to be offset by the starting number (i.e. the minimum allowed number - 2)


问:
Is there a C# code in unity to identify when a Button is pressed and when it is released?
I'm currently trying to set up a code in C# that identifies when a certain button is pressed and when it is released

I'm trying to make this certain button scale down when pressed and scale up when released

```<code>public class clickshake : MonoBehaviour
{
    public GameObject click;
    public void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
           transform.localScale += new Vector3(-0.1F, -0.1f, 0);
        }
        if (Input.GetMouseButtonUp(0))
        {
           transform.localScale += new Vector3(0.1F, 0.1f, 0);
        }
    }
}
</code>```

by making this script exclusive to the button in its On Click command
it only grew the button in size and didn't shrink it down

答:
making this script exclusive to the button in its On Click  command

that makes little sense. Especially since the Update method is called all the time every frame. So calling it additionally from the onClick will call it twice in that frame. Also from Button.onClick

Note that EventType.MouseDown and EventType.MouseUp are called prior to onClick.

You can e.g. use the IPointerDownHandler and IPointerUpHandler interfaces to implement that

```<code>public class clickshake : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
{
    //Detect current clicks on the GameObject (the one with the script attached)
    public void OnPointerDown(PointerEventData pointerEventData)
    {
        transform.localScale -= new Vector3(0.1F, 0.1f, 0);
    }

    //Detect if clicks are no longer registering
    public void OnPointerUp(PointerEventData pointerEventData)
    {
        transform.localScale += new Vector3(0.1F, 0.1f, 0);
    }
}
</code>```

Note

Ensure an EventSystem exists in the Scene to allow click detection. For click detection on non-UI GameObjects, ensure a PhysicsRaycaster is attached to the Camera.

and non-UI objects ofcourse will also need a Collider.

Body:
I'm currently trying to set up a code in C# that identifies when a certain button is pressed and when it is released

I'm trying to make this certain button scale down when pressed and scale up when released

public class clickshake : MonoBehaviour
{
    public GameObject click;
    public void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
           transform.localScale += new Vector3(-0.1F, -0.1f, 0);
        }
        if (Input.GetMouseButtonUp(0))
        {
           transform.localScale += new Vector3(0.1F, 0.1f, 0);
        }
    }
}

by making this script exclusive to the button in its On Click command
it only grew the button in size and didn't shrink it down

Body:
making this script exclusive to the button in its On Click  command

that makes little sense. Especially since the Update method is called all the time every frame. So calling it additionally from the onClick will call it twice in that frame. Also from Button.onClick

Note that EventType.MouseDown and EventType.MouseUp are called prior to onClick.

You can e.g. use the IPointerDownHandler and IPointerUpHandler interfaces to implement that

public class clickshake : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
{
    //Detect current clicks on the GameObject (the one with the script attached)
    public void OnPointerDown(PointerEventData pointerEventData)
    {
        transform.localScale -= new Vector3(0.1F, 0.1f, 0);
    }

    //Detect if clicks are no longer registering
    public void OnPointerUp(PointerEventData pointerEventData)
    {
        transform.localScale += new Vector3(0.1F, 0.1f, 0);
    }
}

Note

Ensure an EventSystem exists in the Scene to allow click detection. For click detection on non-UI GameObjects, ensure a PhysicsRaycaster is attached to the Camera.

and non-UI objects ofcourse will also need a Collider.


问:
UITableVIew Fails To render UITableViewCell Currectly
When I am going to populate my tableView with different states one state act wrong, I'm sure that it cause by delay of tableView. please see video and picture first.

I populating my UITableView like:

```<code>func tableView(_ tableView: UITableView,
              cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId")
    cell.state = myStates[indexPath.row]
}
</code>```

on my UITableViewCell:

```<code>var state: MyCustomDesignState? {
    didSet {
        self.button.set(state: self.state)
    }
}
</code>```

on my UIButton:

```<code>func set(state: MyCustomDesignState?) {
    switch state {
    case ...
    case .blackBack:
        self.backgroundColor = background
        self.setTitleColor(textColor, for: .normal)
        self.frame = CGRect.init(x: 40, y: 190 - 40, width: 180, height: 34)
        self.dropFlatShadow(color: #colorLiteral(red: 0.1008123383, green: 0.1008369699, blue: 0.1008091196, alpha: 1))
        self.clipsToBounds = true
        self.layer.cornerRadius = 5
    }
}
</code>```

this is what I want, and what I did get:

how my tableView looks like:

video to bug:

https://streamable.com/ki7vx

答:
In your TableViewCell : Try calling this method which you are currently calling in state change like below :

```<code>override func layoutSubviews() {
          super.layoutSubviews()
          self.button.set(state: self.state)
    }
</code>```

Hope I got the question right and this helps you.

Body:
When I am going to populate my tableView with different states one state act wrong, I'm sure that it cause by delay of tableView. please see video and picture first.

I populating my UITableView like:

func tableView(_ tableView: UITableView,
              cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId")
    cell.state = myStates[indexPath.row]
}

on my UITableViewCell:

var state: MyCustomDesignState? {
    didSet {
        self.button.set(state: self.state)
    }
}

on my UIButton:

func set(state: MyCustomDesignState?) {
    switch state {
    case ...
    case .blackBack:
        self.backgroundColor = background
        self.setTitleColor(textColor, for: .normal)
        self.frame = CGRect.init(x: 40, y: 190 - 40, width: 180, height: 34)
        self.dropFlatShadow(color: #colorLiteral(red: 0.1008123383, green: 0.1008369699, blue: 0.1008091196, alpha: 1))
        self.clipsToBounds = true
        self.layer.cornerRadius = 5
    }
}

this is what I want, and what I did get:

how my tableView looks like:

video to bug:

https://streamable.com/ki7vx

Body:
In your TableViewCell : Try calling this method which you are currently calling in state change like below :

override func layoutSubviews() {
          super.layoutSubviews()
          self.button.set(state: self.state)
    }

Hope I got the question right and this helps you.


问:
How to restrict "type=number" to certain decimal places
I am developing an application in which i require to restrict the amount "type=number" filed to certain (2 places) places. Below is the HTML rules for element :
Please can someone help me regarding this query, Thanks in advance :

 <input type="number" name="amount" ng-model="orderStock.amount" class="form-control" id="amount"
                        step="0.01" min="10" max="9999.99" placeholder=" Please enter Amount" ng-disabled="isDisabled"
                        required />```

答:
You can attach an input event listener to your input element and check if it's value contains a comma. If it does, check if there are more than two characters to the right of the comma and remove the excess.

function process() {
  var text = document.getElementById("amount").value;
  var index = text.indexOf(".");
  if (index > -1) {
    if (text.length - index > 3) {
      document.getElementById("amount").value = text.substr(0, text.length - 1);
    }
  }
}
document.getElementById("amount").addEventListener("input", process);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" name="amount" ng-model="orderStock.amount" class="form-control" id="amount" step="0.01" min="10" max="9999.99" placeholder=" Please enter Amount" ng-disabled="isDisabled" required /></code>```

If you want to have all the code inside the html tag, you can do this:

<input type="number" name="amount" ng-model="orderStock.amount" class="form-control" id="amount" step="0.01" min="10" max="9999.99" oninput="var text = this.value;var index = text.indexOf('.');if (index > -1) {if (text.length - index > 3) {this.value = text.substr(0, text.length - 1);}}" placeholder=" Please enter Amount" ng-disabled="isDisabled" required />```

Body:
You can attach an input event listener to your input element and check if it's value contains a comma. If it does, check if there are more than two characters to the right of the comma and remove the excess.

function process() {
  var text = document.getElementById("amount").value;
  var index = text.indexOf(".");
  if (index > -1) {
    if (text.length - index > 3) {
      document.getElementById("amount").value = text.substr(0, text.length - 1);
    }
  }
}
document.getElementById("amount").addEventListener("input", process);

<input type="number" name="amount" ng-model="orderStock.amount" class="form-control" id="amount" step="0.01" min="10" max="9999.99" placeholder=" Please enter Amount" ng-disabled="isDisabled" required />

If you want to have all the code inside the html tag, you can do this:

<input type="number" name="amount" ng-model="orderStock.amount" class="form-control" id="amount" step="0.01" min="10" max="9999.99" oninput="var text = this.value;var index = text.indexOf('.');if (index > -1) {if (text.length - index > 3) {this.value = text.substr(0, text.length - 1);}}" placeholder=" Please enter Amount" ng-disabled="isDisabled" required />


问:
Zero an array in C code

Possible Duplicates:

  How to initialize an array to something in C without a loop?

  How to initialize an array in C

How can I zero a known size of an array without using a for or any other loop ?

For example:

```<code>arr[20] = 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;
</code>```

This is the long way... I need it the short way.

答:
```<code>int arr[20] = {0};
</code>```

C99 [$6.7.8/21]

If there are fewer initializers in a brace-enclosed list than there are elements or members
  of an aggregate, or fewer characters in a string literal used to initialize an array of known
  size  than  there  are  elements  in  the  array,  the  remainder  of  the  aggregate  shall  be initialized implicitly the same as objects that have static storage duration.

Title: Zero an array in C code

Body:
Possible Duplicates:

  How to initialize an array to something in C without a loop?

  How to initialize an array in C

How can I zero a known size of an array without using a for or any other loop ?

For example:

arr[20] = 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;

This is the long way... I need it the short way.

Body:
int arr[20] = {0};

C99 [$6.7.8/21]

If there are fewer initializers in a brace-enclosed list than there are elements or members
  of an aggregate, or fewer characters in a string literal used to initialize an array of known
  size  than  there  are  elements  in  the  array,  the  remainder  of  the  aggregate  shall  be initialized implicitly the same as objects that have static storage duration.


问:
How to handle two different times if they are not in the same day?
I'm handling restaurant opening and closing hours , i am using moment to parse time it and it works perfect but there is one case in which its not working,
If the restaurant open at 9:00 am and closes 1:00 am (next day), it gives restaurant is closed no matter the time .</p>

```<code>   if (current_time.isBetween(opening_hour, close_hour))  {
     console.log('its open');
   } else {
     console.log('its closed');
   }

</code>```

答:
For a generic solution without mention of date, you can also test first if close_hour is before opening_hour, and if the case, use isAfter(opening_hour) || isBefore(opening_hour):

NOTE: if close_hour is not a momentJs, the first line would be if (moment(close_hour, 'hh:mm').isAfter(opening_hour)) {

```<code>if (close_hour.isAfter(opening_hour)) {
    if (current_time.isBetween(opening_hour, close_hour)) {
        console.log('its open');
    } else {
        console.log('its closed');
    }
} else {
    if (current_time.isAfter(opening_hour) || current_time.isBefore(close_hour)) {
        console.log('its open');
    } else {
        console.log('its closed');
    }
}
</code>```

Body:
I'm handling restaurant opening and closing hours , i am using moment to parse time it and it works perfect but there is one case in which its not working,
If the restaurant open at 9:00 am and closes 1:00 am (next day), it gives restaurant is closed no matter the time .

   if (current_time.isBetween(opening_hour, close_hour))  {
     console.log('its open');
   } else {
     console.log('its closed');
   }

Body:
For a generic solution without mention of date, you can also test first if close_hour is before opening_hour, and if the case, use isAfter(opening_hour) || isBefore(opening_hour):

NOTE: if close_hour is not a momentJs, the first line would be if (moment(close_hour, 'hh:mm').isAfter(opening_hour)) {

if (close_hour.isAfter(opening_hour)) {
    if (current_time.isBetween(opening_hour, close_hour)) {
        console.log('its open');
    } else {
        console.log('its closed');
    }
} else {
    if (current_time.isAfter(opening_hour) || current_time.isBefore(close_hour)) {
        console.log('its open');
    } else {
        console.log('its closed');
    }
}


问:
How to render a static html page in ReactJS?
I am trying to render an html page in react. I have tried multiple solutions but still, I am getting an error. Yes I know there are many questions similar to this one but none of those solutions has worked for me. I am using reactjs as front-end and simply trying to show a static html page.

html file is below:

```<code><!DOCTYPE html>

<html>
  <head>
    <title>Ably WebRTC Video call Demo</title>

    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"
    />
  </head>

  <body>
    <script src="https://cdn.temasys.io/adapterjs/0.15.x/adapter.min.js"></script>

    <script src="https://cdn.temasys.io/adapterjs/0.15.x/adapter.screenshare.js"></script>

    <script src="https://cdn.ably.io/lib/ably.min-1.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/simple-peer/9.1.2/simplepeer.min.js"></script>

    <script src="ably-screenshare.js"></script>

    <script src="connection-helper.js"></script>

    <div class="container-fluid" style="margin-top: 5em;">
      <div class="container" id="join">
        <h4 id="online">Users online (0)</h4>

        <ul id="memberList"></ul>
      </div>

      <div class="container" id="call" style="display:none;">
        <video width="320" height="240" id="local" controls></video>

        <video width="320" height="240" id="remote" controls></video>

        <button class="btn btn-xs btn-danger" onclick="handleEndCall()">
          End call
        </button>
      </div>
    </div>
  </body>

  <style>
    small {
      border-bottom: 2px solid black;
    }

    li {
      list-style: none;
    }
  </style>
</html>
</code>```

and the solution that I tried is

```<code>import React, { Component } from "react";
var __html = require("./screen.html");
var template = { __html: __html };

class ScreenShare extends Component {
  render() {
    return (
      <div className="screen-share">
        <span dangerouslySetInnerHTML={template} />
      </div>
    );
  }
}
export default ScreenShare;
</code>```

Even using the above solution, I am getting this error

```<code>./src/components/screenShare/screen.html
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| <!DOCTYPE html>
|
| <html>
</code>```

is there something wrong that I am doing? I know dangerouslySetInnerHTML is not the best way to solve the issue but I tried to change the above html code into react component and it didn't help. So I tried dangerouslySetInnerHTML to convert it but it is still giving error.

答:
By default, importing an HTML file with react will not work. Given your use case and the route which you want to go, the best bet will be to convert the HTML page to a js file and then export for example:

html.js file

```<code>module.exports = `<!DOCTYPE html>

<html>
  <head>
    <title>Ably WebRTC Video call Demo</title>

    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"
    />
  </head>

  <body>
    <script src="https://cdn.temasys.io/adapterjs/0.15.x/adapter.min.js"></script>

    <script src="https://cdn.temasys.io/adapterjs/0.15.x/adapter.screenshare.js"></script>

    <script src="https://cdn.ably.io/lib/ably.min-1.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/simple-peer/9.1.2/simplepeer.min.js"></script>

    <script src="ably-screenshare.js"></script>

    <script src="connection-helper.js"></script>

    <div class="container-fluid" style="margin-top: 5em;">
      <div class="container" id="join">
        <h4 id="online">Users online (0)</h4>

        <ul id="memberList"></ul>
      </div>

      <div class="container" id="call" style="display:none;">
        <video width="320" height="240" id="local" controls></video>

        <video width="320" height="240" id="remote" controls></video>

        <button class="btn btn-xs btn-danger" onclick="handleEndCall()">
          End call
        </button>
      </div>
    </div>
  </body>

  <style>
    small {
      border-bottom: 2px solid black;
    }

    li {
      list-style: none;
    }
  </style>
</html>`;
</code>```

Here, note the module.exports, as well as the template string used, so you can call it in your react page this way:

```<code>import React, { Component } from "react";
var __html = require('./index.html.js');
var template = { __html: __html };

class ScreenShare extends Component {
  render() {
    return (
      <div className="screen-share">
        <span dangerouslySetInnerHTML={template} />
      </div>
    );
  }
}
export default ScreenShare;
</code>```

Body:
I am trying to render an html page in react. I have tried multiple solutions but still, I am getting an error. Yes I know there are many questions similar to this one but none of those solutions has worked for me. I am using reactjs as front-end and simply trying to show a static html page.

html file is below:

<!DOCTYPE html>

    <title>Ably WebRTC Video call Demo</title>

    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"
    />

Users online (0)

        <video width="320" height="240" id="local" controls></video>

        <video width="320" height="240" id="remote" controls></video>

        <button class="btn btn-xs btn-danger" onclick="handleEndCall()">
          End call
        </button>

and the solution that I tried is

import React, { Component } from "react";
var __html = require("./screen.html");
var template = { __html: __html };

class ScreenShare extends Component {
  render() {
    return (

    );
  }
}
export default ScreenShare;

Even using the above solution, I am getting this error

./src/components/screenShare/screen.html
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| <!DOCTYPE html>
|
|

is there something wrong that I am doing? I know dangerouslySetInnerHTML is not the best way to solve the issue but I tried to change the above html code into react component and it didn't help. So I tried dangerouslySetInnerHTML to convert it but it is still giving error.

Body:
By default, importing an HTML file with react will not work. Given your use case and the route which you want to go, the best bet will be to convert the HTML page to a js file and then export for example:

html.js file

module.exports = `<!DOCTYPE html>

<html>
  <head>
    <title>Ably WebRTC Video call Demo</title>

    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"
    />
  </head>

  <body>
    <script src="https://cdn.temasys.io/adapterjs/0.15.x/adapter.min.js"></script>

    <script src="https://cdn.temasys.io/adapterjs/0.15.x/adapter.screenshare.js"></script>

    <script src="https://cdn.ably.io/lib/ably.min-1.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/simple-peer/9.1.2/simplepeer.min.js"></script>

    <script src="ably-screenshare.js"></script>

    <script src="connection-helper.js"></script>

    <div class="container-fluid" style="margin-top: 5em;">
      <div class="container" id="join">
        <h4 id="online">Users online (0)</h4>

        <ul id="memberList"></ul>
      </div>

      <div class="container" id="call" style="display:none;">
        <video width="320" height="240" id="local" controls></video>

        <video width="320" height="240" id="remote" controls></video>

        <button class="btn btn-xs btn-danger" onclick="handleEndCall()">
          End call
        </button>
      </div>
    </div>
  </body>

  <style>
    small {
      border-bottom: 2px solid black;
    }

    li {
      list-style: none;
    }
  </style>
</html>`;

Here, note the module.exports, as well as the template string used, so you can call it in your react page this way:

import React, { Component } from "react";
var __html = require('./index.html.js');
var template = { __html: __html };

class ScreenShare extends Component {
  render() {
    return (
      <div className="screen-share">
        <span dangerouslySetInnerHTML={template} />
      </div>
    );
  }
}
export default ScreenShare;