问:
Can someone explain this regular expression?
```<code>(.*)([0-9]{6})|(.*)([0-9]{4})
</code>```

<p>Does it mean pick up a number that is either 6 digits or 4 digits ? Is there a concise way to write it ? </p>

答:
See other answers for what it means.

Whether or not there is a more concise way to write it, all ways would almost certainly compile to the same DFA, so be executed the same. This way is at least clear. You're having trouble understanding this one, why would you want to make it more concise?

Body:
(.*)([0-9]{6})|(.*)([0-9]{4})

Does it mean pick up a number that is either 6 digits or 4 digits ? Is there a concise way to write it ?


来源: stackexchange

问:
read_csv wont open .csv file; rather have to use csv.reader+defaultdict to parse in a frame
Im trying to open the Kaggle spotify top 50 songs csv file using pd.read_csv but its giving below error:
"'utf-8' codec can't decode byte 0xf1 in position 2: invalid continuation byte"

In excel, it looks like a normal csv file. I tried using the csv.reader method and im able to open, using a defaultdict, and a few for loops. Why didnt the pd.read_csv work?

link to Kaggle csv file for convenience: https://www.kaggle.com/leonardopena/top50spotify2019

答:
Setting the encoding to latin-1:

```<code>import pandas as pd

df = pd.read_csv('datasets_456958_861311_top50contry.csv',
                 encoding='latin-1'
                 )

print(df.head())
</code>```

Outputs:

```<code>   Unnamed: 0                            title          artist  ...  spch  pop country
0           1                     Dance Monkey     Tones and I  ...   9.0  100   world
1           2                          ROXANNE  Arizona Zervas  ...  15.0   99   world
2           3                         Memories        Maroon 5  ...   5.0   99   world
3           4                          Circles     Post Malone  ...   4.0   99   world
4           5  All I Want for Christmas Is You    Mariah Carey  ...   4.0   98   world

[5 rows x 17 columns]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Setting the encoding to latin-1:

import pandas as pd

df = pd.read_csv('datasets_456958_861311_top50contry.csv',
                 encoding='latin-1'
                 )

print(df.head())

Outputs:

   Unnamed: 0                            title          artist  ...  spch  pop country
0           1                     Dance Monkey     Tones and I  ...   9.0  100   world
1           2                          ROXANNE  Arizona Zervas  ...  15.0   99   world
2           3                         Memories        Maroon 5  ...   5.0   99   world
3           4                          Circles     Post Malone  ...   4.0   99   world
4           5  All I Want for Christmas Is You    Mariah Carey  ...   4.0   98   world

[5 rows x 17 columns]


问:
When/why to prefix variables with "$" when using jQuery?

Possible Duplicate:

  Why would a javascript variable start with a dollar sign?

I see people using the dollar sign in front of variables when using jQuery. Is there any reason behind this? I'm I missing something basic or is it just a common practice?

答: In my experience this is just a readability. Some developers like to prefix their variables so that they are easy to spot. It could also be a PHP habit creeping it's way in to Javascript.</p>

ContentLicense: CC BY-SA 3.0


问:
Smooth transition to make element appear
When I click on the button, I would like the arrow to appear by sliding out smoothly.  I'm currently doing this by adding the 'show' class if the arrow should be shown.  I've tried display: none; -> display: inline-block  I've tried width:0 -> width: 100%.

This code makes the arrow appear/disappear onclick, but without a smooth transition.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
  <style>
    span {
      -webkit-transition: all .5s;
      -moz-transition: all .5s;
      transition: all .5s;
      width: 0;
      overflow: hidden;
      max-width: 0;
      display:none;
    }
    .show {
      width: 100%;
      display: inline;
    }

  </style>
  <script>
    function toggleArrow(elemId) {
      let elem = document.getElementById(elemId);
      if (elem.classList.contains('show')) {
        elem.classList.remove('show');
      } else {
        elem.classList.add('show');
      }
    }
  </script>
</head>
<body>
  <div> Here's the button:
    <button onClick="toggleArrow('title-arrow')">my button<span id="title-arrow" > ↑</span></button>
  </div>
</body>
</html>
</code>```

答:
Did it works right?

<!DOCTYPE html>

    <meta charset="UTF-8">

 Here's the button:
    <button onClick="toggleArrow('title-arrow')">my button ↑</button>

```

Body:
When I click on the button, I would like the arrow to appear by sliding out smoothly.  I'm currently doing this by adding the 'show' class if the arrow should be shown.  I've tried display: none; -> display: inline-block  I've tried width:0 -> width: 100%.

This code makes the arrow appear/disappear onclick, but without a smooth transition.

<!DOCTYPE html>

    <meta charset="UTF-8">

 Here's the button:
    <button onClick="toggleArrow('title-arrow')">my button ↑</button>

Body:
Did it works right?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
  <style>
    button{
      position:relative;
      padding-right:20px;
      overflow: hidden
    }
    span {
      -webkit-transition: all .5s;
      -moz-transition: all .5s;
      transition: all .5s;
      overflow: hidden;
      top:50px;
      position: absolute;
      right:5px;
    }
    .show {
      top:0;
    }

  </style>
  <script>
    function toggleArrow(elemId) {
      let elem = document.getElementById(elemId);
      if (elem.classList.contains('show')) {
        elem.classList.remove('show');
      } else {
        elem.classList.add('show');
      }
    }
  </script>
</head>
<body>
  <div> Here's the button:
    <button onClick="toggleArrow('title-arrow')">my button<span id="title-arrow" > ↑</span></button>
  </div>
</body>
</html>


问:
How to convert parquet file to CSV using .NET Core?
I have a parquet file and I am trying to convert it to a CSV file, it seems as though most recommend using Spark, however I need to use C# to accomplish this task, specifically I need to use .NET Core 3.0.

Its tricky because parquet is columnar data which is making it annoying to convert to CSV...

I have tried loading it into a datatable but I dont like that solution because I need the entire file in memory and I am losing certain records somehow.

I am using parquet.net but I am open to any other parquet library that works on .net core/standard

Thank you in advance.

答:
I haven't given it a shot, but I wonder whether you could leverage / abuse the Microsoft Spark SQL libraries to your benefit.

There's

DataFrameReader.Parquet(String[])

https://learn.microsoft.com/en-us/dotnet/api/microsoft.spark.sql.dataframereader.parquet?view=spark-dotnet

And also:

DataFrameWriter.Csv(String) Method

https://learn.microsoft.com/en-us/dotnet/api/microsoft.spark.sql.dataframewriter.csv?view=spark-dotnet#Microsoft_Spark_Sql_DataFrameWriter_Csv_System_String_

I wonder whether you could use a DataFrame as an in memory intermediary.

It's just a guess at the moment as your question intrigued me, perhaps I'll give it a shot once I've got some sleep. :-)


问:
How to build custom event with delay
I wrote the below custom event, which is working fine.

```<code>constructor() {
  super();
  this.addEventListener('tick', event =>
    this.timerElem.setAttribute('datetime', event.detail.time)
  );
}

connectedCallback() {
  this.timer = setInterval(() =>
    this.dispatchEvent(new CustomEvent('tick', {
      detail: {
        time: new Date()
      }
    })), 1000);
}
</code>```

I tried to split the even into another file, but failed to get it run, I wrote:

```<code>var tick_event = setInterval(() => {
  document.dispatchEvent(new CustomEvent('tick', {
  // window.dispatchEvent(new CustomEvent('tick', {
    detail: {
      time: new Date()
    }
  }));
  console.log('test'); // this is print out
}, 1000);
</code>```

Is there a way to do something like this!!

UPDATE

In response to the note, if the question is not clear, the below code, worked fine with me:

```<code>// file: timer.js, one file only
customElements.define("live-timer", class extends HTMLElement {
  constructor() {
    super();
      this.innerHTML = `
        <time-formatted hour="numeric" minute="numeric" second="numeric">
        </time-formatted>
        `;

      this.timerElem = this.firstElementChild;

      this.addEventListener('tick', event =>
        this.timerElem.setAttribute('datetime', event.detail.time)
      );
  }

  connectedCallback() {
      this.timer = setInterval(() =>
          this.dispatchEvent(new CustomEvent('tick', {
            detail: {
              time: new Date()
            }
          }))
      , 1000);
  }

  disconnectedCallback() {
    clearInterval(this.timer); // important to let the element be garbage-collected
  }
});
</code>```

The below code did not work fully, and did not give any error:

```<code>// file: timer.js, first file
customElements.define("live-timer", class extends HTMLElement {
  constructor() {
    super();
      this.innerHTML = `
        <time-formatted hour="numeric" minute="numeric" second="numeric">
        </time-formatted>
        `;

      this.timerElem = this.firstElementChild;

      this.addEventListener('tick', event =>
        this.timerElem.setAttribute('datetime', event.detail.time)
      );
  }

  disconnectedCallback() {
    clearInterval(this.timer); // important to let the element be garbage-collected
  }
});

// file: timer trigger, the second file:
var tick_event = setInterval(() => {
    console.log('tick');   // <===================== this works fine
    window.dispatchEvent(new CustomEvent('tick', {   // <== this is not returning anything
      detail: {
        time: new Date()
      }
    }));
    console.log('test'); }
, 1000);
</code>```

With the second option, I got no error, and no result.

答:
The solution I came with is to do it with window as it looks both even trigger and listener should ne the same element (hope someone to correct me if wrong), so I added the event to the window, listen it from there, and push the required to my element, i.e. if I need to do the same tick_listner for multiple elements, I've to to push to all of them at once.

```<code>// tick_event.js
var tick_event = setInterval(() => {
    window.dispatchEvent(new CustomEvent('tick', {
      detail: {
        time: new Date()
      }
    }));
 }
, 1000);

window.addEventListener('tick', event =>
  $("#timer").timerElem.setAttribute('datetime', event.detail.time)
);
</code>```

Title: How to build custom event with delay

Body:
I wrote the below custom event, which is working fine.

constructor() {
  super();
  this.addEventListener('tick', event =>
    this.timerElem.setAttribute('datetime', event.detail.time)
  );
}

connectedCallback() {
  this.timer = setInterval(() =>
    this.dispatchEvent(new CustomEvent('tick', {
      detail: {
        time: new Date()
      }
    })), 1000);
}

I tried to split the even into another file, but failed to get it run, I wrote:

var tick_event = setInterval(() => {
  document.dispatchEvent(new CustomEvent('tick', {
  // window.dispatchEvent(new CustomEvent('tick', {
    detail: {
      time: new Date()
    }
  }));
  console.log('test'); // this is print out
}, 1000);

Is there a way to do something like this!!

UPDATE

In response to the note, if the question is not clear, the below code, worked fine with me:

// file: timer.js, one file only
customElements.define("live-timer", class extends HTMLElement {
  constructor() {
    super();
      this.innerHTML = `
        <time-formatted hour="numeric" minute="numeric" second="numeric">
        </time-formatted>
        `;

      this.timerElem = this.firstElementChild;

      this.addEventListener('tick', event =>
        this.timerElem.setAttribute('datetime', event.detail.time)
      );
  }

  connectedCallback() {
      this.timer = setInterval(() =>
          this.dispatchEvent(new CustomEvent('tick', {
            detail: {
              time: new Date()
            }
          }))
      , 1000);
  }

  disconnectedCallback() {
    clearInterval(this.timer); // important to let the element be garbage-collected
  }
});

The below code did not work fully, and did not give any error:

// file: timer.js, first file
customElements.define("live-timer", class extends HTMLElement {
  constructor() {
    super();
      this.innerHTML = `
        <time-formatted hour="numeric" minute="numeric" second="numeric">
        </time-formatted>
        `;

      this.timerElem = this.firstElementChild;

      this.addEventListener('tick', event =>
        this.timerElem.setAttribute('datetime', event.detail.time)
      );
  }

  disconnectedCallback() {
    clearInterval(this.timer); // important to let the element be garbage-collected
  }
});

// file: timer trigger, the second file:
var tick_event = setInterval(() => {
    console.log('tick');   // <===================== this works fine
    window.dispatchEvent(new CustomEvent('tick', {   // <== this is not returning anything
      detail: {
        time: new Date()
      }
    }));
    console.log('test'); }
, 1000);

With the second option, I got no error, and no result.

Body:
The solution I came with is to do it with window as it looks both even trigger and listener should ne the same element (hope someone to correct me if wrong), so I added the event to the window, listen it from there, and push the required to my element, i.e. if I need to do the same tick_listner for multiple elements, I've to to push to all of them at once.

// tick_event.js
var tick_event = setInterval(() => {
    window.dispatchEvent(new CustomEvent('tick', {
      detail: {
        time: new Date()
      }
    }));
 }
, 1000);

window.addEventListener('tick', event =>
  $("#timer").timerElem.setAttribute('datetime', event.detail.time)
);


问:
Reading a CSV file stored in Active Storage in Rails 6
I'm using Active Storage to upload CSV files, which are then read to update values in the database.  I have set up a basic upload file class to do this;

```<code>class VendorFile < ApplicationRecord
    has_one_attached :vendor_upload_file
    validate :acceptable_file
end
</code>```

I open the CSV files using the Rails 6 open method like this;

```<code>self.vendor_upload_file.open do |file|
  CSV.foreach(file) do |row|
    do some processing....
  end
end
</code>```

This works great for processing through the whole file.  The issue is before processing I'd like to open the file and just read the first line to ensure the file is the correct format.  I cannot find a way to open the file and read just the first line if the file is stored in Active Storage.  Does anyone know a way to do this?
Thanks!

答:
How about?</p>

```<code>headers = self.vendor_upload_file.open(&:first).parse_csv
</code>```

Body:
I'm using Active Storage to upload CSV files, which are then read to update values in the database.  I have set up a basic upload file class to do this;

class VendorFile < ApplicationRecord
    has_one_attached :vendor_upload_file
    validate :acceptable_file
end

I open the CSV files using the Rails 6 open method like this;

self.vendor_upload_file.open do |file|
  CSV.foreach(file) do |row|
    do some processing....
  end
end

This works great for processing through the whole file.  The issue is before processing I'd like to open the file and just read the first line to ensure the file is the correct format.  I cannot find a way to open the file and read just the first line if the file is stored in Active Storage.  Does anyone know a way to do this?
Thanks!

Body:
How about?

headers = self.vendor_upload_file.open(&:first).parse_csv


问:
MapPoint Web Service Zoom Level
I am modifying an application that someone else wrote for MapPoint Web Service. Its a pretty old application and I think its using version 3.5 of MapPoint Web Service. I would like to know how to set the default zoom level? I would like to get a closer view of the location by default.

I found the MapOptions.Zoom Properties but that looks like how much it zooms each time you hit the button.

答: I believe you just set the MapSpecification.MapOptions.Zoom to a double value. But the MSDN will most likely have better answer</p>

OwnerDisplayName: MaxGeek

ContentLicense: CC BY-SA 2.5

Title: MapPoint Web Service Zoom Level

OwnerDisplayName: BtBh


问:
Double group by in multiple tables
I have three joined tables.

```<code>select *
from Ordering
inner join Client on client.id=ordering.client_id
inner join Dish on ordering.dish_id=dish.id
</code>```

I would like sum quantity column and group by name_dish and later  client_id.

Now I made it but it is not enough (for one client):

```<code>select client.familyName, client.name, client.phone, sum(ordering.quantity),dish.name_dish
from Ordering
inner join Client on client.id=ordering.client_id
inner join Dish on ordering.dish_id=dish.id
where ordering.client_id=1
group by (dish.name_dish)
</code>```

答:
Starting from your existing query, you need to put all selected columns that are not within an aggregate function in the group by clause (that is, all columns excepted quantity). I would also suggest including the primary keys of the client and dish table, in case two clients (resp. dishes) have the same name.

Consider the following aggregate query:

```<code>select c.family_name, c.name, c.phone, sum(o.quantity) sum_quantity, d.name_dish
from ordering o
inner join client c on c.id = o.client_id
inner join dish d on o.dish_id = d.id
group by c.client_id, c.family_name, c.name, c.phone, d.id, d.name_dish
</code>```

Some databases (actually, Postgres) are content with just the primary keys of the two tables in the group by clause:

```<code>select c.family_name, c.name, c.phone, sum(o.quantity) sum_quantity, d.name_dish
from ordering o
inner join client c on c.id = o.client_id
inner join dish d on o.dish_id = d.id
group by c.client_id, d.id
</code>```

Title: Double group by in multiple tables

Body:
I have three joined tables.

select *
from Ordering
inner join Client on client.id=ordering.client_id
inner join Dish on ordering.dish_id=dish.id

I would like sum quantity column and group by name_dish and later  client_id.

Now I made it but it is not enough (for one client):

select client.familyName, client.name, client.phone, sum(ordering.quantity),dish.name_dish
from Ordering
inner join Client on client.id=ordering.client_id
inner join Dish on ordering.dish_id=dish.id
where ordering.client_id=1
group by (dish.name_dish)

Body:
Starting from your existing query, you need to put all selected columns that are not within an aggregate function in the group by clause (that is, all columns excepted quantity). I would also suggest including the primary keys of the client and dish table, in case two clients (resp. dishes) have the same name.

Consider the following aggregate query:

select c.family_name, c.name, c.phone, sum(o.quantity) sum_quantity, d.name_dish
from ordering o
inner join client c on c.id = o.client_id
inner join dish d on o.dish_id = d.id
group by c.client_id, c.family_name, c.name, c.phone, d.id, d.name_dish

Some databases (actually, Postgres) are content with just the primary keys of the two tables in the group by clause:

select c.family_name, c.name, c.phone, sum(o.quantity) sum_quantity, d.name_dish
from ordering o
inner join client c on c.id = o.client_id
inner join dish d on o.dish_id = d.id
group by c.client_id, d.id


问:
DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
hi i create a custom manager class called usermanager in monage.py
to customise my login template for 2 types of user admin,entrepreneur

```<code>#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
from django.contrib.auth.models import BaseUserManager
import sys
def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oasisconsuting.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
        execute_from_command_line(sys.argv)

if __name__ == '__main__':
    main()

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        if not email:
            raise ValueError("The given email must be set")

        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault("is_staff", False)
        extra_fields.setdefault("is_superuser", False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", True)

        if extra_fields.get("is_staff") is not True:
            raise ValueError("Superuser must have is_staff=True.")
        if extra_fields.get("is_superuser") is not True:
            raise ValueError("Superuser must have is_superuser=True.")

        return self._create_user(email, password, **extra_fields)
</code>```

after running the makemigration (it's ok)
when i run the migration code we receive the errors
what is the wrong in this code to show me this errors :

```<code>C:\Users\hp\PycharmProjects\business\Scripts\python.exe
C:/Users/hp/PycharmProjects/business/oasisconsuting/manage.py runserver
Traceback (most recent call last):
  File "C:/Users/hp/PycharmProjects/business/oasisconsuting/manage.py", line 4, in <module>
    from django.contrib.auth.models import BaseUserManager
  File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\contrib\auth\models.py", line
2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\contrib\auth\base_user.py",
line 47, in <module>
    class AbstractBaseUser(models.Model):
  File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\db\models\base.py", line 107,
in __new__
    app_config = apps.get_containing_app_config(module)
  File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\apps\registry.py", line 252, in
get_containing_app_config
    self.check_apps_ready()
  File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\apps\registry.py", line 134, in
check_apps_ready
    settings.INSTALLED_APPS
  File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\conf\__init__.py", line 76, in
__getattr__
    self._setup(name)
  File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\conf\__init__.py", line 57, in
_setup
    raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not
configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call
settings.configure() before accessing settings.
</code>```

should i keep this code or i should change it
how i can

call setting.configure()
or

define the environment variable DJANGO_SETTINGS_MODULE
to fix my problem or there is another method to do

答:
I can see some issues:

In main() function I think there is a bug in last line, Is not having one indent more than it should?. Perhaps the code should be:

```<code>def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oasisconsuting.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)
</code>```

Do you really need to do a script? Best practice with Django will be to create a custom django-admin commands, you can check documentation

Body:
hi i create a custom manager class called usermanager in monage.py
to customise my login template for 2 types of user admin,entrepreneur

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
from django.contrib.auth.models import BaseUserManager
import sys
def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oasisconsuting.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
        execute_from_command_line(sys.argv)

if __name__ == '__main__':
    main()

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        if not email:
            raise ValueError("The given email must be set")

        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault("is_staff", False)
        extra_fields.setdefault("is_superuser", False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", True)

        if extra_fields.get("is_staff") is not True:
            raise ValueError("Superuser must have is_staff=True.")
        if extra_fields.get("is_superuser") is not True:
            raise ValueError("Superuser must have is_superuser=True.")

        return self._create_user(email, password, **extra_fields)

after running the makemigration (it's ok)
when i run the migration code we receive the errors
what is the wrong in this code to show me this errors :

C:\Users\hp\PycharmProjects\business\Scripts\python.exe
C:/Users/hp/PycharmProjects/business/oasisconsuting/manage.py runserver
Traceback (most recent call last):
  File "C:/Users/hp/PycharmProjects/business/oasisconsuting/manage.py", line 4, in <module>
    from django.contrib.auth.models import BaseUserManager
  File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\contrib\auth\models.py", line
2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\contrib\auth\base_user.py",
line 47, in <module>
    class AbstractBaseUser(models.Model):
  File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\db\models\base.py", line 107,
in __new__
    app_config = apps.get_containing_app_config(module)
  File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\apps\registry.py", line 252, in
get_containing_app_config
    self.check_apps_ready()
  File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\apps\registry.py", line 134, in
check_apps_ready
    settings.INSTALLED_APPS
  File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\conf\__init__.py", line 76, in
__getattr__
    self._setup(name)
  File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\conf\__init__.py", line 57, in
_setup
    raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not
configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call
settings.configure() before accessing settings.

should i keep this code or i should change it
how i can

call setting.configure()
or

define the environment variable DJANGO_SETTINGS_MODULE
to fix my problem or there is another method to do

Body:
I can see some issues:

In main() function I think there is a bug in last line, Is not having one indent more than it should?. Perhaps the code should be:

def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oasisconsuting.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

Do you really need to do a script? Best practice with Django will be to create a custom django-admin commands, you can check documentation


问:
Remove duplicate empty lines in terminal in Node.js
Not sure if this is possible, I would love to remove duplicate empty lines in the terminal in real-time

For example:

```<code>console.log('cat');
console.log('');
console.log('');
console.log('');
console.log('dog');
</code>```

received:

```<code>cat

dog
</code>```

expected:

```<code>cat

dog
</code>```

Noticed that 2 duplicate empty lines are removed

I think a possible solution is that before printing a new empty line, read current stout, if the last item is an empty line, do not console.log this new empty line

Not sure how to do this in real-time

答:
You can use cat with -s or --squeeze-blank option.

Pipe the nodejs script output to cat -s,

```<code>node whatever.js | cat -s
</code>```

Body:
Not sure if this is possible, I would love to remove duplicate empty lines in the terminal in real-time

For example:

console.log('cat');
console.log('');
console.log('');
console.log('');
console.log('dog');

received:

cat

dog

expected:

cat

dog

Noticed that 2 duplicate empty lines are removed

I think a possible solution is that before printing a new empty line, read current stout, if the last item is an empty line, do not console.log this new empty line

Not sure how to do this in real-time

Body:
You can use cat with -s or --squeeze-blank option.

Pipe the nodejs script output to cat -s,

node whatever.js | cat -s


问:
insert into tables from another tables
Well, I trying insert into tables to another but I get this error;

WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''lcl_user_agent' (user_agent, hitcount, click_timestap) SELECT visite_useragent,' at line 1]

This is my code;

```<code>$addagent = "INSERT INTO $wpdb->prefix.'lcl_user_agent' (user_agent, hitcount, click_timestap) SELECT visite_useragent, visite_hitcount, click_timestap FROM $wpdb->prefix.'lcl_visite_agent' .agent_id IN (' . $agent_id . ')";

$wpdb->query($addagent);
</code>```

I want insert into lcl_user_agent the visites from visite_useragent then I get the visite for block with $agent_id from the form

答:
Give this a shot:

$addagent = "INSERT INTO " . $wpdb->prefix . 'lcl_user_agent' . " (user_agent, hitcount, click_timestap) SELECT visite_useragent, visite_hitcount, click_timestap FROM " . $wpdb->prefix.'lcl_visite_agent' . " where agent_id IN (' . $agent_id . ')";

$wpdb->query($addagent);

I've never had much luck embedding the -> within a double-quoted string. Just makes it more clear to concatenate the strings together. Also, in this case, unless you have multiple $agent_id values, you might consider where agent_id = $agent_id instead  of using IN.

Title: insert into tables from another tables

Body:
Well, I trying insert into tables to another but I get this error;

WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''lcl_user_agent' (user_agent, hitcount, click_timestap) SELECT visite_useragent,' at line 1]

This is my code;

$addagent = "INSERT INTO $wpdb->prefix.'lcl_user_agent' (user_agent, hitcount, click_timestap) SELECT visite_useragent, visite_hitcount, click_timestap FROM $wpdb->prefix.'lcl_visite_agent' .agent_id IN (' . $agent_id . ')";

$wpdb->query($addagent);

I want insert into lcl_user_agent the visites from visite_useragent then I get the visite for block with $agent_id from the form


问:
How to render a less costly sphere in aframe/three js?
I have a vr application that renders a lot of spheres. The built-in aframe  element renders spheres using triangles and as a result my scene has a ton of triangles. This is killing the performance, dropping frame rates down into the teens. Is there a more efficient sphere like object I could use? These spheres really dont need to do anything special, Im willing to sacrifice their appearance in order to be able to render more of them without killing performance.

答:
You could resort to InstancedMesh, which uses GPU instancing to render duplicate geometries in a single drawcall.

Check the demo below. Rendering 1000 elements would typically take 1000 individual drawcalls, greatly slowing down performance. But with instancing, you can render all of them in the same pass.

var camera, scene, renderer, stats;

   var mesh;
   var amount = parseInt( window.location.search.substr( 1 ) ) || 10;
   var count = Math.pow( amount, 3 );
   var dummy = new THREE.Object3D();

   init();
   animate();

   function init() {

    camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 100 );
    camera.position.set( amount * 0.9, amount * 0.9, amount * 0.9 );
    camera.lookAt( 0, 0, 0 );

    scene = new THREE.Scene();

    var loader = new THREE.BufferGeometryLoader();
    loader.load( 'https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/json/suzanne_buffergeometry.json', function ( geometry ) {

     geometry.computeVertexNormals();
     geometry.scale( 0.5, 0.5, 0.5 );

     var material = new THREE.MeshNormalMaterial();
     // check overdraw
     // var material = new THREE.MeshBasicMaterial( { color: 0xff0000, opacity: 0.1, transparent: true } );

     mesh = new THREE.InstancedMesh( geometry, material, count );
     mesh.instanceMatrix.setUsage( THREE.DynamicDrawUsage ); // will be updated every frame
     scene.add( mesh );

     //

     var gui = new dat.GUI();
     gui.add( mesh, 'count', 0, count );

    } );

    //

    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

    //

    stats = new Stats();
    document.body.appendChild( stats.dom );

    //

    window.addEventListener( 'resize', onWindowResize, false );

   }

   function onWindowResize() {

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );

   }

   //

   function animate() {

    requestAnimationFrame( animate );

    render();

    stats.update();

   }

   function render() {

    if ( mesh ) {

     var time = Date.now() * 0.001;

     mesh.rotation.x = Math.sin( time / 4 );
     mesh.rotation.y = Math.sin( time / 2 );

     var i = 0;
     var offset = ( amount - 1 ) / 2;

     for ( var x = 0; x < amount; x ++ ) {

      for ( var y = 0; y < amount; y ++ ) {

       for ( var z = 0; z < amount; z ++ ) {

        dummy.position.set( offset - x, offset - y, offset - z );
        dummy.rotation.y = ( Math.sin( x / 4 + time ) + Math.sin( y / 4 + time ) + Math.sin( z / 4 + time ) );
        dummy.rotation.z = dummy.rotation.y * 2;

        dummy.updateMatrix();

        mesh.setMatrixAt( i ++, dummy.matrix );

       }

      }

     }

     mesh.instanceMatrix.needsUpdate = true;

    }

    renderer.render( scene, camera );

   }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {margin: 0; padding: 0;overflow: hidden;}</code>```

<!DOCTYPE html>

  <title>three.js webgl - instancing - dynamic</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

```

Click here to see demo source

Body:
You could resort to InstancedMesh, which uses GPU instancing to render duplicate geometries in a single drawcall.

Check the demo below. Rendering 1000 elements would typically take 1000 individual drawcalls, greatly slowing down performance. But with instancing, you can render all of them in the same pass.

var camera, scene, renderer, stats;

   var mesh;
   var amount = parseInt( window.location.search.substr( 1 ) ) || 10;
   var count = Math.pow( amount, 3 );
   var dummy = new THREE.Object3D();

   init();
   animate();

   function init() {

    camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 100 );
    camera.position.set( amount * 0.9, amount * 0.9, amount * 0.9 );
    camera.lookAt( 0, 0, 0 );

    scene = new THREE.Scene();

    var loader = new THREE.BufferGeometryLoader();
    loader.load( 'https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/json/suzanne_buffergeometry.json', function ( geometry ) {

     geometry.computeVertexNormals();
     geometry.scale( 0.5, 0.5, 0.5 );

     var material = new THREE.MeshNormalMaterial();
     // check overdraw
     // var material = new THREE.MeshBasicMaterial( { color: 0xff0000, opacity: 0.1, transparent: true } );

     mesh = new THREE.InstancedMesh( geometry, material, count );
     mesh.instanceMatrix.setUsage( THREE.DynamicDrawUsage ); // will be updated every frame
     scene.add( mesh );

     //

     var gui = new dat.GUI();
     gui.add( mesh, 'count', 0, count );

    } );

    //

    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

    //

    stats = new Stats();
    document.body.appendChild( stats.dom );

    //

    window.addEventListener( 'resize', onWindowResize, false );

   }

   function onWindowResize() {

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );

   }

   //

   function animate() {

    requestAnimationFrame( animate );

    render();

    stats.update();

   }

   function render() {

    if ( mesh ) {

     var time = Date.now() * 0.001;

     mesh.rotation.x = Math.sin( time / 4 );
     mesh.rotation.y = Math.sin( time / 2 );

     var i = 0;
     var offset = ( amount - 1 ) / 2;

     for ( var x = 0; x < amount; x ++ ) {

      for ( var y = 0; y < amount; y ++ ) {

       for ( var z = 0; z < amount; z ++ ) {

        dummy.position.set( offset - x, offset - y, offset - z );
        dummy.rotation.y = ( Math.sin( x / 4 + time ) + Math.sin( y / 4 + time ) + Math.sin( z / 4 + time ) );
        dummy.rotation.z = dummy.rotation.y * 2;

        dummy.updateMatrix();

        mesh.setMatrixAt( i ++, dummy.matrix );

       }

      }

     }

     mesh.instanceMatrix.needsUpdate = true;

    }

    renderer.render( scene, camera );

   }

html, body {margin: 0; padding: 0;overflow: hidden;}

<!DOCTYPE html>
<html lang="en">
 <head>
  <title>three.js webgl - instancing - dynamic</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  <script src="https://cdn.jsdelivr.net/npm/three@0.117.1/build/three.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/stats.js@0.17.0/build/stats.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/three@0.117.1/examples/js/libs/dat.gui.min.js"></script>
 </head>
 <body>

 </body>
</html>

Click here to see demo source


问:
FileReader read as DataUrl
I am working  on this app on the Chrome App Store. Evidently the File API changed, so I needed to implement FileReader to get the local URL of a file that is dropped onto the page.

```<code>function drop(evt) {

    v = evt.target.id;

    evt.stopPropagation();
    evt.preventDefault();

    var files = evt.dataTransfer.files; // FileList object.

    var f = files[0];

    var reader = new FileReader();

          // Closure to capture the file information.
          reader.onload = (function(theFile) {
            return function(e) {
              document.getElementById(v).src = e.target.result;
            };
          })(f);

   reader.readAsDataURL(f);
}
</code>```

What I am trying to do is load the URL of a song that is dropped onto the page into an HTML5 Audio tag's src attribute. I can't figure out what I am doing wrong with this drop function.

Does anybody have any ideas?

答:
Hmm, this looks right to me. What is the current behavior? You're attaching the drop event to the audio element itself? You can get rid of the closure, since you're only using the first file and not looping through the FileList

Here's a similar DnD file snippet (it uses images instead of an  src):
http://www.html5rocks.com/tutorials/file/dndfiles/#toc-selecting-files-dnd

As an alternative, you could use a blobURL:

```<code>window.URL = window.URL || window.webkitURL;

function drop(evt) {
  ...
  var file = evt.dataTransfer.files[0];
  ...
  audio.src = window.URL.createObjectURL(file);
  audio.onload = function(e) {
    window.URL.revokeObjectURL(this.arc); // clean up
  };
}
</code>```

Title: FileReader read as DataUrl

Body:
I am working  on this app on the Chrome App Store. Evidently the File API changed, so I needed to implement FileReader to get the local URL of a file that is dropped onto the page.

function drop(evt) {

    v = evt.target.id;

    evt.stopPropagation();
    evt.preventDefault();

    var files = evt.dataTransfer.files; // FileList object.

    var f = files[0];

    var reader = new FileReader();

          // Closure to capture the file information.
          reader.onload = (function(theFile) {
            return function(e) {
              document.getElementById(v).src = e.target.result;
            };
          })(f);

   reader.readAsDataURL(f);
}

What I am trying to do is load the URL of a song that is dropped onto the page into an HTML5 Audio tag's src attribute. I can't figure out what I am doing wrong with this drop function.

Does anybody have any ideas?

Body:
Hmm, this looks right to me. What is the current behavior? You're attaching the drop event to the audio element itself? You can get rid of the closure, since you're only using the first file and not looping through the FileList

Here's a similar DnD file snippet (it uses images instead of an  src):
http://www.html5rocks.com/tutorials/file/dndfiles/#toc-selecting-files-dnd

As an alternative, you could use a blobURL:

window.URL = window.URL || window.webkitURL;

function drop(evt) {
  ...
  var file = evt.dataTransfer.files[0];
  ...
  audio.src = window.URL.createObjectURL(file);
  audio.onload = function(e) {
    window.URL.revokeObjectURL(this.arc); // clean up
  };
}


问:
Trying to access data returned from Stripe API with Alamofire, but result is not valid JSON
I'm trying to interface a Swift app with the Stripe API, using Alamofire, but I'm having trouble with the returned results. I was expecting valid JSON, but I am getting the following:

```<code>Stripe\SetupIntent JSON: {
    "id": "seti_1Go**************g4qyJgp",
    "object": "setup_intent",
    "application": null,
    "cancellation_reason": null,
    "client_secret": "seti_1Go***************gp_secret_HM*******************ObpHy7Mk",
    "created": 1590784053,
    "customer": "cus_H*********Tna",
    "description": null,
    "last_setup_error": null,
    "livemode": false,
    "mandate": null,
    "metadata": [],
    "next_action": null,
    "on_behalf_of": null,
    "payment_method": null,
    "payment_method_options": {
        "card": {
            "request_three_d_secure": "automatic"
        }
    },
    "payment_method_types": [
        "card"
    ],
    "single_use_mandate": null,
    "status": "requires_payment_method",
    "usage": "off_session"
}
</code>```

I'm using the following PHP code:

```<code>$customer = \Stripe\Customer::create();
$setupIntent = \Stripe\SetupIntent::create([
    'customer' => $customer->id
]);

$this->response($setupIntent, 200);
</code>```

How can I get at the JSON inside this object? I tried converting it to json, but then I get nothing. Alamofire doesn't like it the way it is now. Do I need to somehow strip off the "Stripe\SetupIntent JSON:"?

答:
You can access the json object body that came back from the API with getLastResponse():

```<code>$setupIntent->getLastResponse()->body
</code>```

edit. You can also use json_encode() to produce the json from the object yourself:

```<code>json_encode($setupIntent)
</code>```

Body:
I'm trying to interface a Swift app with the Stripe API, using Alamofire, but I'm having trouble with the returned results. I was expecting valid JSON, but I am getting the following:

Stripe\SetupIntent JSON: {
    "id": "seti_1Go**************g4qyJgp",
    "object": "setup_intent",
    "application": null,
    "cancellation_reason": null,
    "client_secret": "seti_1Go***************gp_secret_HM*******************ObpHy7Mk",
    "created": 1590784053,
    "customer": "cus_H*********Tna",
    "description": null,
    "last_setup_error": null,
    "livemode": false,
    "mandate": null,
    "metadata": [],
    "next_action": null,
    "on_behalf_of": null,
    "payment_method": null,
    "payment_method_options": {
        "card": {
            "request_three_d_secure": "automatic"
        }
    },
    "payment_method_types": [
        "card"
    ],
    "single_use_mandate": null,
    "status": "requires_payment_method",
    "usage": "off_session"
}

I'm using the following PHP code:

$customer = \Stripe\Customer::create();
$setupIntent = \Stripe\SetupIntent::create([
    'customer' => $customer->id
]);

$this->response($setupIntent, 200);

How can I get at the JSON inside this object? I tried converting it to json, but then I get nothing. Alamofire doesn't like it the way it is now. Do I need to somehow strip off the "Stripe\SetupIntent JSON:"?

Body:
You can access the json object body that came back from the API with getLastResponse():

$setupIntent->getLastResponse()->body

edit. You can also use json_encode() to produce the json from the object yourself:

json_encode($setupIntent)


问:
JPEG category encode bitwise operation
In the Cryx note about JPEG compression, categories are described as "the minimum size in bits in which we can keep that value". It goes on to say that values falling within certain ranges are put into categories. I have pasted a segment below but not the whole table.

```<code>     Values             Category        Bits for the value

    0                   0                   -

      -1,1                  1                  0,1

   -3,-2,2,3                2              00,01,10,11

 -7,-6,-5,-4,4,5,6,7            3    000,001,010,011,100,101,110,111
</code>```

The JPEG encoder/decoder found here performs the category encoding with a bitwise operation that I don't understand and I am hoping someone can clarify for me. RLE of 0's is done elsewhere, but this portion of the code breaks up the remaining pixel values into the categories as specified in the Cryx document.

In the code below, the variable code is the value of the YUV value of the pixel. In the while loop, if the conditions are met, i is decremented until the correct category is reached. For example, if the pixel value is 6.0, starting from category 15, i is decremented until 3 is reached. This is done with a bitwise operation that I do not understand. Can someone please clarify what condition is being tested for in the while loop? More specifically, !(absc & mask) is a Boolean, but I don't understand how this helps us to know the correct category.

The reason for the last if statement is also unclear to me. Thanks

```<code>    unsigned absc = abs(*code);
    unsigned mask = (1 << 15);
    int i    = 15;
    if (absc == 0) { *size = 0; return; }
    while (i && !(absc & mask)) { mask >>= 1; i--; }
    *size = i + 1;
    if (*code < 0) *code = (1 << *size) - absc - 1;
</code>```

答:
while here is used to find the most significant bit in code. Or in other words - length of code in bits.

The loop consequently applies mask to get next bit in code. First, mask is 1000000000000000 in binary form with 1 in 15th bit (zero based), the most valued bit in 2-byte (16 bit) number. Operator & (binary AND) zeros all bits in absc except one with 1 in mask. If result is zero than shift mask right (remove last binary digit) and repeat with next bit.

For value 6 = 110b (binary form) while will work till mask = 100b and i = 2. After it size will be set to 3.

If code was negative than the last line will convert it in one’s compliment representation with size length. Such encoding of negative numbers is described in your categories list.

Title: JPEG category encode bitwise operation

Body:
In the Cryx note about JPEG compression, categories are described as "the minimum size in bits in which we can keep that value". It goes on to say that values falling within certain ranges are put into categories. I have pasted a segment below but not the whole table.

     Values             Category        Bits for the value

    0                   0                   -

      -1,1                  1                  0,1

   -3,-2,2,3                2              00,01,10,11

 -7,-6,-5,-4,4,5,6,7            3    000,001,010,011,100,101,110,111

The JPEG encoder/decoder found here performs the category encoding with a bitwise operation that I don't understand and I am hoping someone can clarify for me. RLE of 0's is done elsewhere, but this portion of the code breaks up the remaining pixel values into the categories as specified in the Cryx document.

In the code below, the variable code is the value of the YUV value of the pixel. In the while loop, if the conditions are met, i is decremented until the correct category is reached. For example, if the pixel value is 6.0, starting from category 15, i is decremented until 3 is reached. This is done with a bitwise operation that I do not understand. Can someone please clarify what condition is being tested for in the while loop? More specifically, !(absc & mask) is a Boolean, but I don't understand how this helps us to know the correct category.

The reason for the last if statement is also unclear to me. Thanks

    unsigned absc = abs(*code);
    unsigned mask = (1 << 15);
    int i    = 15;
    if (absc == 0) { *size = 0; return; }
    while (i && !(absc & mask)) { mask >>= 1; i--; }
    *size = i + 1;
    if (*code < 0) *code = (1 << *size) - absc - 1;


问:
Does setTimeout delay the creation of the function?
This doesn't work because when "log" is being created while "message" doesn't exist.

function x() {
  function log() {
    console.log(message)
  }
  const message = "hello"
   log()
}

x()```
</div>
</div>
</p>

<p>But this works? setTimeout isn't aware of the message and in my opinion, should throw an error. But it seems like the "log" is being created after "x" function is done executing? How is this explained?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function x() {
  setTimeout(() => {
    console.log(message)
  }, 500)
  const message = "hello"
}

x()</code>```

答:
This happens because of the event loop, and the fact that setTimeout takes a callback function as an argument.

Basically the order of operations are below

The function named x is defined

The function x is called

The function setTimeout is called

The constant variable named message is declared

The callback function that was passed as an argument to SetTimeout is called

The log method of the console object is called.

The first code snippet does not log to the console because your are not calling the function defined within function x.  You can log the variable to the console in the first code snippet by accessing the variable through a closure.

This should work with the first code snippet.

function x() {
  const message = "hello"
  return function() {
    console.log(message)
  }

}

x()()
```

<p>Another more simpler way, would be just to call the function within the function:</p>

<pre class="lang-js prettyprint-override"><code>function x() {
  function log() {
    console.log(message)
  }
  const message = "hello"
  log()
}

x()
</code>```

Body:
This doesn't work because when "log" is being created while "message" doesn't exist.

function x() {
  function log() {
    console.log(message)
  }
  const message = "hello"
   log()
}

x()

But this works? setTimeout isn't aware of the message and in my opinion, should throw an error. But it seems like the "log" is being created after "x" function is done executing? How is this explained?

function x() {
  setTimeout(() => {
    console.log(message)
  }, 500)
  const message = "hello"
}

x()

Body:
This happens because of the event loop, and the fact that setTimeout takes a callback function as an argument.

Basically the order of operations are below

The function named x is defined

The function x is called

The function setTimeout is called

The constant variable named message is declared

The callback function that was passed as an argument to SetTimeout is called

The log method of the console object is called.

The first code snippet does not log to the console because your are not calling the function defined within function x.  You can log the variable to the console in the first code snippet by accessing the variable through a closure.

This should work with the first code snippet.

function x() {
  const message = "hello"
  return function() {
    console.log(message)
  }

}

x()()

Another more simpler way, would be just to call the function within the function:

function x() {
  function log() {
    console.log(message)
  }
  const message = "hello"
  log()
}

x()


问:
How to make pthreads work concurrent without pthread_join()
I'm making a program where I have multiple threads working at the same time. After messing with the code for a while, I had an issue where I would send a string (char *) to the thread to do further operations with, and somehow the string did not send at all.

Later, I wrote a very simple code where I just send a string to a thread and the function prints it to the console. I found out that without using pthread_join(), it wouldn't work at all. I have no idea why, because I know that whenever pthread_join() is called, it blocks every other thread and waits until that one is finished.

Here's the simple program:

```<code>void* prisntstr(void* string);

int main(int argc, char *argv[])
{
    char* string = "Hello!";

    pthread_t thread;

    pthread_create(&thread, NULL, prisntstr, (void*)string);

    pthread_join(thread, NULL);

}

void* prisntstr(void* string)
{
    char* str = (char*)string;

    printf("%s\n", str);
}
</code>```

Does anyone know how I can do this without using pthread_join()?

答:
The problem with your program, if you remove the pthread_join, is that main is returning and thereby causing the program to exit without doing anything to synchronize with the other thread and determine whether it's actually finished. When main returns, it's just as if you called exit, and the whole process terminates.

Aside from pthread_join there are lots of ways you could make main wait for other actions to be finished. You could wait on a semaphore that the other threads post, you could loop on a condition variable inspecting data other threads set, etc.

Alternatively you could have main call pthread_exit so to terminate the initial thread. Then the process will not exit until you call exit or until each thread has exited.

Body:
I'm making a program where I have multiple threads working at the same time. After messing with the code for a while, I had an issue where I would send a string (char *) to the thread to do further operations with, and somehow the string did not send at all.

Later, I wrote a very simple code where I just send a string to a thread and the function prints it to the console. I found out that without using pthread_join(), it wouldn't work at all. I have no idea why, because I know that whenever pthread_join() is called, it blocks every other thread and waits until that one is finished.

Here's the simple program:

void* prisntstr(void* string);

int main(int argc, char *argv[])
{
    char* string = "Hello!";

    pthread_t thread;

    pthread_create(&thread, NULL, prisntstr, (void*)string);

    pthread_join(thread, NULL);

}

void* prisntstr(void* string)
{
    char* str = (char*)string;

    printf("%s\n", str);
}

Does anyone know how I can do this without using pthread_join()?


问:
How to test an async function in an event listener with Jest?
I have an event listener that runs an asynchronous function, and removes some elements from the DOM after completion:

```<code>async function fetchAndRemove() {
  try {
    const response = await fetch('/endpoint-that-returns-json')

    const result = await response.json()
    if (result.status === 'Success') {
      document.querySelector('.my-element').remove()
    }
  } catch (error) {
    console.log(error)
  }
}

function setupListeners () {
  const button = document.querySelector('.my-button')
  button.addEventListener('click', () => {
    fetchAndRemove()
  })
}

setupListeners()
</code>```

In my test, I have:

```<code>import fetch from 'jest-fetch-mock';

test('it removes the element after clicking', () => {
  fetch.mockResponse(JSON.stringify({ status: 'Success' }))
  setupListeners()
  document.querySelector('.my-button').click() // .click comes from JSDOM

  expect(document.querySelector('.my-element')).toBeNull()
}
</code>```

However that doesn't work because I believe in the test, setting up the event listener and clicking the button runs synchronously and doesn't wait for the async work to finish.

I tried this idea but no good results:

```<code>test('it removes the element after clicking', async () => {
  fetch.mockResponse(JSON.stringify({ status: 'Success' }))
  setupListeners()
  await Promise.resolve(document.querySelector('.my-button').click())

  expect(document.querySelector('.my-element')).toBeNull()
}
</code>```

答:
This is wrong because DOM events don't involve promises and await Promise.resolve is redundant:

```<code>await Promise.resolve(document.querySelector('.my-button').click())
</code>```

It creates one-tick delay and that's all.

Since fetchAndRemove is referred in the same module it's defined, it cannot be spied, so fetch promise should be chained in order to maintain correct execution order.

Considering that fetch is a spy, it can be:

```<code>  fetch.mockResponse(JSON.stringify({ status: 'Success' }))
  setupListeners()
  document.querySelector('.my-button').click()
  await fetch.mock.results[0].value; // delay for fetch()
  await null; // another delay for res.json()
  expect(fetch).toBeCalledWith('/endpoint-that-returns-json')
  expect(document.querySelector('.my-element')).toBeNull()
</code>```

Body:
I have an event listener that runs an asynchronous function, and removes some elements from the DOM after completion:

async function fetchAndRemove() {
  try {
    const response = await fetch('/endpoint-that-returns-json')

    const result = await response.json()
    if (result.status === 'Success') {
      document.querySelector('.my-element').remove()
    }
  } catch (error) {
    console.log(error)
  }
}

function setupListeners () {
  const button = document.querySelector('.my-button')
  button.addEventListener('click', () => {
    fetchAndRemove()
  })
}

setupListeners()

In my test, I have:

import fetch from 'jest-fetch-mock';

test('it removes the element after clicking', () => {
  fetch.mockResponse(JSON.stringify({ status: 'Success' }))
  setupListeners()
  document.querySelector('.my-button').click() // .click comes from JSDOM

  expect(document.querySelector('.my-element')).toBeNull()
}

However that doesn't work because I believe in the test, setting up the event listener and clicking the button runs synchronously and doesn't wait for the async work to finish.

I tried this idea but no good results:

test('it removes the element after clicking', async () => {
  fetch.mockResponse(JSON.stringify({ status: 'Success' }))
  setupListeners()
  await Promise.resolve(document.querySelector('.my-button').click())

  expect(document.querySelector('.my-element')).toBeNull()
}

Body:
This is wrong because DOM events don't involve promises and await Promise.resolve is redundant:

await Promise.resolve(document.querySelector('.my-button').click())

It creates one-tick delay and that's all.

Since fetchAndRemove is referred in the same module it's defined, it cannot be spied, so fetch promise should be chained in order to maintain correct execution order.

Considering that fetch is a spy, it can be:

  fetch.mockResponse(JSON.stringify({ status: 'Success' }))
  setupListeners()
  document.querySelector('.my-button').click()
  await fetch.mock.results[0].value; // delay for fetch()
  await null; // another delay for res.json()
  expect(fetch).toBeCalledWith('/endpoint-that-returns-json')
  expect(document.querySelector('.my-element')).toBeNull()


问:
Capistrano/Passenger deploy failing due to different gem versions
I'm trying to deploy my Rails app to my webhost (DreamHost) using Capistrano but it keeps failing because the various gems installed on the server are of a different version.

I can work around this by manually installing, one by one, the specific gem version when Capistrano complains about it.

There must be a better way.. is there something I can do so that when deploying, it automatically installs the different versions if required?

答:
Yes there is, and it's baked right into bundler...

You just need to add require 'bundler/capistrano' to your cap file and all should be fine from then on.

If all is not well you can try cap bundle:install manually to clear things up before install.


问:
Application is not supported over the /common or /consumers endpoints. Please use the /organizations or tenant-specific endpoint
I know there are several other posts listed about this topic but I cannot seem to find any useful info in them to apply to my own application. I am building a .Net MVC Web App that uses the Microsoft Graph API. I followed another project (https://github.com/microsoftgraph/aspnet-snippets-sample) but when I launch the application, it redirects to https://login.microsoftonline.com where it attempts to log in using a Microsoft work account, and redirects back to the homepage. However, after entering Microsoft account credentials and before being redirected back, I am shown an error:

.

Below is a section from my Startup.Auth.cs that I believe is causing the problems. If anyone can see anything that seems off or has any insight on this topic, I would greatly appreciate it. I have been spinning my wheels just trying to sign-in to this application using Open Id Connect to be able to use the Microsoft Graph API. Thanks!

```<code>app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions {

    // The `Authority` represents the v2.0 endpoint - https://login.microsoftonline.com/common/v2.0
    // The `Scope` describes the permissions that your app will need. See https://azure.microsoft.com/documentation/articles/active-directory-v2-scopes/
    ClientId = appId,

        * * Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, "common", "/v2.0"), * *
        RedirectUri = redirectUri,
        Scope = scopes,
        PostLogoutRedirectUri = redirectUri,
        TokenValidationParameters = new TokenValidationParameters {
            ValidateIssuer = false,
        },
        Notifications = new OpenIdConnectAuthenticationNotifications {
            AuthorizationCodeReceived = async(context) => {
                    var code = context.Code;
                    string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                    string graphScopes = nonAdminScopes;
                    string[] scopes = graphScopes.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    ConfidentialClientApplication cca = new ConfidentialClientApplication(appId, redirectUri,
                        new ClientCredential(appSecret),
                        new SessionTokenCache(signedInUserID, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance(), null);
                    AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes);

                    // Check whether the login is from the MSA tenant.
                    // The sample uses this attribute to disable UI buttons for unsupported operations when the user is logged in with an MSA account.
                    var currentTenantId = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                    if (currentTenantId == "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") {
                        HttpContext.Current.Session.Add("AccountType", "msa");
                    }
                    // Set IsAdmin session variable to false, since the user hasn't consented to admin scopes yet.
                    HttpContext.Current.Session.Add("IsAdmin", false);
                },
                AuthenticationFailed = (context) => {
                    context.HandleResponse();
                    context.Response.Redirect("/Error?message=" + context.Exception.Message);
                    return Task.FromResult(0);
                }
        }
});
</code>```

答:
If you are using microsoftgraph/msgraph-sdk-dotnet-auth for getting access token, then /common endpoint is valid.

If you are using AzureAD/microsoft-authentication-library-for-java for getting access token, then use /organizations endpoint instead of /common.

Body:
I know there are several other posts listed about this topic but I cannot seem to find any useful info in them to apply to my own application. I am building a .Net MVC Web App that uses the Microsoft Graph API. I followed another project (https://github.com/microsoftgraph/aspnet-snippets-sample) but when I launch the application, it redirects to https://login.microsoftonline.com where it attempts to log in using a Microsoft work account, and redirects back to the homepage. However, after entering Microsoft account credentials and before being redirected back, I am shown an error:

.

Below is a section from my Startup.Auth.cs that I believe is causing the problems. If anyone can see anything that seems off or has any insight on this topic, I would greatly appreciate it. I have been spinning my wheels just trying to sign-in to this application using Open Id Connect to be able to use the Microsoft Graph API. Thanks!

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions {

    // The `Authority` represents the v2.0 endpoint - https://login.microsoftonline.com/common/v2.0
    // The `Scope` describes the permissions that your app will need. See https://azure.microsoft.com/documentation/articles/active-directory-v2-scopes/
    ClientId = appId,

        * * Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, "common", "/v2.0"), * *
        RedirectUri = redirectUri,
        Scope = scopes,
        PostLogoutRedirectUri = redirectUri,
        TokenValidationParameters = new TokenValidationParameters {
            ValidateIssuer = false,
        },
        Notifications = new OpenIdConnectAuthenticationNotifications {
            AuthorizationCodeReceived = async(context) => {
                    var code = context.Code;
                    string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                    string graphScopes = nonAdminScopes;
                    string[] scopes = graphScopes.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    ConfidentialClientApplication cca = new ConfidentialClientApplication(appId, redirectUri,
                        new ClientCredential(appSecret),
                        new SessionTokenCache(signedInUserID, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance(), null);
                    AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes);

                    // Check whether the login is from the MSA tenant.
                    // The sample uses this attribute to disable UI buttons for unsupported operations when the user is logged in with an MSA account.
                    var currentTenantId = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                    if (currentTenantId == "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") {
                        HttpContext.Current.Session.Add("AccountType", "msa");
                    }
                    // Set IsAdmin session variable to false, since the user hasn't consented to admin scopes yet.
                    HttpContext.Current.Session.Add("IsAdmin", false);
                },
                AuthenticationFailed = (context) => {
                    context.HandleResponse();
                    context.Response.Redirect("/Error?message=" + context.Exception.Message);
                    return Task.FromResult(0);
                }
        }
});


问:
Collapsing Toolbar title not centered
My app contains a collapsing toolbar with a title. The title is centerend when it is expanded and should stay centered when it is collapsing. With my layout which is below, my device doesn't center the title when it is collapsed, but moves it a little to the right. What do I have to change so it keeps being centered? If it's helpful I can add images as well of course.

My layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@android:color/white"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:expandedTitleGravity="center|bottom"
            app:title="Test"
            app:collapsedTitleGravity="center"
            app:expandedTitleMarginBottom="56dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:toolbarId="@+id/toolbar">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:layout_marginBottom="48dp"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:fillViewport="true"
        android:layout_gravity="fill_vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">>

    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
</code>```

This is what it looks like expanded

As you see on this image, it's not centered, but a little moved to the right side

答:
Setting content related properties to 0dp will help you. Here is my working Toolbar entry.

```<code><androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    app:contentInsetLeft="0dp"
                    android:contentInsetLeft="0dp"
                    app:contentInsetStartWithNavigation="0dp"
                    app:contentInsetStart="0dp"
                    android:contentInsetStart="0dp"
                    app:theme="@style/YourTheme"
                    android:gravity="center_horizontal"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"
                    app:titleMargin="0dp" />
</code>```

Hope it will help :)

Title: Collapsing Toolbar title not centered

Body:
My app contains a collapsing toolbar with a title. The title is centerend when it is expanded and should stay centered when it is collapsing. With my layout which is below, my device doesn't center the title when it is collapsed, but moves it a little to the right. What do I have to change so it keeps being centered? If it's helpful I can add images as well of course.

My layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@android:color/white"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:expandedTitleGravity="center|bottom"
            app:title="Test"
            app:collapsedTitleGravity="center"
            app:expandedTitleMarginBottom="56dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:toolbarId="@+id/toolbar">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:layout_marginBottom="48dp"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:fillViewport="true"
        android:layout_gravity="fill_vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">>

    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>

This is what it looks like expanded

As you see on this image, it's not centered, but a little moved to the right side

Body:
Setting content related properties to 0dp will help you. Here is my working Toolbar entry.

<androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    app:contentInsetLeft="0dp"
                    android:contentInsetLeft="0dp"
                    app:contentInsetStartWithNavigation="0dp"
                    app:contentInsetStart="0dp"
                    android:contentInsetStart="0dp"
                    app:theme="@style/YourTheme"
                    android:gravity="center_horizontal"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"
                    app:titleMargin="0dp" />

Hope it will help :)


问:
Use clipboard images to draw paths that repeat over entire length of the line
Using Inkscape, I have an image path created similar to below:

With this image copied to the clipboard I can then draw paths using the image, however each line I draw will 'stretch' the base image...for example:

Or...

My question is to find if there is a way to prevent the 'stretching'...?  I would like the base image copied to clipboard to 'fill' and/or 'repeat' over the entire length of the drawn line...is this possible?  To show it graphically I would like to draw line(s) where the base image repeats to cover the entire length of the drawn line, similar to this:

...Possible?  Any advice appreciated.  I thank you in advance.

答:
Sure. Use the 'Pattern along Path' extension or the 'Pattern along Path' path effect (< recommended, because you can modify it 'live').

Actually, that path effect is the same one as the 'from clipboard' option in the Bézier and Pencil tools, only with the 'single, stretched' option instead of 'repeated'.


问:
Getting W/NetworkRequest: error sending network request POST when working with Firebase Storage
The problem is when

```<code>I try to upload an image to firebase storage sometimes it successfully uploads the image but most of the time it keep saying

 *****/com.example.firebasestoragedemo W/NetworkRequest: error sending network request POST https://firebasestorage.googleapis.com/*myproject_name/some_more_extension.
when I enter to this link I found
{
  "error": {
    "code": 403,
    "message": "Permission denied. Could not perform this operation"
  }
}
but I have enabled signInWithEmailAndPassword in my onStart(){...} function and my security rule is here
rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write : if request.auth != null;
    }
  }
}*****
</code>```

These two exceptions I get..

java.net.ConnectException: Failed to connect to firebasestorage.googleapis.com/....
javax.net.ssl.SSLHandshakeException: SSL handshake aborted: ssl=0xe096ebb8: I/O error during system call, Connection reset by peer

my code is truly current otherwise it couldn't be working sometimes. I think the problem is somewhere else in most probably in Firebase.

Please help me out. It will will be a great pleasure if you try to help.
Thank you

答: Having the same issue when I tried to access "Firebase Storage" over mobile data. (from Bangladesh). Then I tried it over Broad Band internet connection and everything worked fine.</p>

Body:
The problem is when

I try to upload an image to firebase storage sometimes it successfully uploads the image but most of the time it keep saying

 *****/com.example.firebasestoragedemo W/NetworkRequest: error sending network request POST https://firebasestorage.googleapis.com/*myproject_name/some_more_extension.
when I enter to this link I found
{
  "error": {
    "code": 403,
    "message": "Permission denied. Could not perform this operation"
  }
}
but I have enabled signInWithEmailAndPassword in my onStart(){...} function and my security rule is here
rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write : if request.auth != null;
    }
  }
}*****

These two exceptions I get..

java.net.ConnectException: Failed to connect to firebasestorage.googleapis.com/....
javax.net.ssl.SSLHandshakeException: SSL handshake aborted: ssl=0xe096ebb8: I/O error during system call, Connection reset by peer

my code is truly current otherwise it couldn't be working sometimes. I think the problem is somewhere else in most probably in Firebase.

Please help me out. It will will be a great pleasure if you try to help.
Thank you


问:
UICollectionView in landscape on iPhone X
When iPhone X is used landscape, you're supposed to check safeAreaInsets to make suitably large gutters on the left and right. UITableView has the new insetsContentViewsToSafeArea property (default true) to automatically keep cell contents in the safe area.

I'm surprised that UICollectionView seems to not have anything similar. I'd expect that for a vertically-scrolling collection view, the left and right sides would be inset to the safe area when in landscape (and conversely, a horizontally-scrolling collection view would be inset if needed in portrait).

The simplest way to ensure this behaviour seems to be to add to the collection view controller:

```<code>- (void)viewSafeAreaInsetsDidChange {
    [super viewSafeAreaInsetsDidChange];
    UIEdgeInsets contentInset = self.collectionView.contentInset;
    contentInset.left = self.view.safeAreaInsets.left;
    contentInset.right = self.view.safeAreaInsets.right;
    self.collectionView.contentInset = contentInset;
}
</code>```

... assuming contentInset.left/right are normally zero.

(NOTE: yes, for a UICollectionViewController, that needs to be self.view.safeAreaInsets; at the time this is called, the change to safeAreaInsets has oddly not yet propagated to self.collectionView)

Am I missing something? That boilerplate is simple enough, but it's effectively necessary now for every collection view that touches a screen edge. It seems really odd that Apple didn't provide something to enable this by default.

答:
If you're adding collection view as your main view's subview programmatically - then you can just do this in your viewDidLoad method:

```<code>collectionView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(collectionView)

NSLayoutConstraint.activate([
        collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
        collectionView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
        collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
        collectionView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor)
])
</code>```

Body:
When iPhone X is used landscape, you're supposed to check safeAreaInsets to make suitably large gutters on the left and right. UITableView has the new insetsContentViewsToSafeArea property (default true) to automatically keep cell contents in the safe area.

I'm surprised that UICollectionView seems to not have anything similar. I'd expect that for a vertically-scrolling collection view, the left and right sides would be inset to the safe area when in landscape (and conversely, a horizontally-scrolling collection view would be inset if needed in portrait).

The simplest way to ensure this behaviour seems to be to add to the collection view controller:

- (void)viewSafeAreaInsetsDidChange {
    [super viewSafeAreaInsetsDidChange];
    UIEdgeInsets contentInset = self.collectionView.contentInset;
    contentInset.left = self.view.safeAreaInsets.left;
    contentInset.right = self.view.safeAreaInsets.right;
    self.collectionView.contentInset = contentInset;
}

... assuming contentInset.left/right are normally zero.

(NOTE: yes, for a UICollectionViewController, that needs to be self.view.safeAreaInsets; at the time this is called, the change to safeAreaInsets has oddly not yet propagated to self.collectionView)

Am I missing something? That boilerplate is simple enough, but it's effectively necessary now for every collection view that touches a screen edge. It seems really odd that Apple didn't provide something to enable this by default.

Body:
If you're adding collection view as your main view's subview programmatically - then you can just do this in your viewDidLoad method:

collectionView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(collectionView)

NSLayoutConstraint.activate([
        collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
        collectionView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
        collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
        collectionView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor)
])


问:
Sign Out button to Present Login View Controller - Swift 5
Hi I'm kind of new to Swift and I can't figure this out. I am trying to create a sign out button that would take user to the login page. I used the following two methods but the first one doesn't do anything and the second one is throwing Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value and it refers to the code with the customButton:

```<code>//this one doesn't do anything
@objc func SignOut(){

    let vc = self.storyboard?.instantiateViewController(identifier: "LoginViewController") as! LoginViewController
    let appDelegate = UIApplication.shared.delegate
    appDelegate?.window??.rootViewController = vc
}

//this one is throwing an error
let vc = CustomViewController()
self.present(vc, animated: true, completion: nil)

//the Fatal error refers to this code
override func viewDidLoad() {
    super.viewDidLoad()
    self.customButton.addTarget(self, action: #selector(customButtonPressed), for: .touchUpInside)
}
</code>```

Also, I was wondering if AppDelegate is the right approach or if I should use SceneDelegate. Any help would be greatly appreciated.

答:
Try to do this </p>

```<code>@objc func SignOut(){

    let vc = self.storyboard?.instantiateViewController(identifier: "LoginViewController") as! LoginViewController
    self.view.window?.rootViewController = vc
}
</code>```

Body:
Hi I'm kind of new to Swift and I can't figure this out. I am trying to create a sign out button that would take user to the login page. I used the following two methods but the first one doesn't do anything and the second one is throwing Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value and it refers to the code with the customButton:

//this one doesn't do anything
@objc func SignOut(){

    let vc = self.storyboard?.instantiateViewController(identifier: "LoginViewController") as! LoginViewController
    let appDelegate = UIApplication.shared.delegate
    appDelegate?.window??.rootViewController = vc
}

//this one is throwing an error
let vc = CustomViewController()
self.present(vc, animated: true, completion: nil)

//the Fatal error refers to this code
override func viewDidLoad() {
    super.viewDidLoad()
    self.customButton.addTarget(self, action: #selector(customButtonPressed), for: .touchUpInside)
}

Also, I was wondering if AppDelegate is the right approach or if I should use SceneDelegate. Any help would be greatly appreciated.

Body:
Try to do this

@objc func SignOut(){

    let vc = self.storyboard?.instantiateViewController(identifier: "LoginViewController") as! LoginViewController
    self.view.window?.rootViewController = vc
}


问:
How do I import react-modal into existing application?
I've been slowly trying to migrate some pieces of an existing, large php/jquery project to use ReactJS, especially using some reusable components. ReactJS has been working well for me, but today I tried to import a library using npm, which is completely new to me.

After running npm install react-modal I see that node_modules\react-modal (along with several other folders) were created. So far, so good.

However, I cannot seem to include that component into my project. If I try import ReactModal from 'react-modal'; at the top of my component's .js file, I get: Uncaught ReferenceError: require is not defined. I get errors thrown if I try to include the node_modules\react-modal\lib\components\Modal.js file directly, which I realize is probably the wrong approach but I'm grasping at straws here. I suspect I'm missing something basic, but I just can't seem to figure this one out. Does anyone have any ideas?

Edit: here is how I include React into my project currently:

```<code><!-- Load React. -->
{if $env=="prod"}
    <script src="https://unpkg.com/react@16/umd/react.production.min.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js" crossorigin></script>

    {* tabs support *}
    <script src="https://unpkg.com/prop-types/prop-types.js"></script>
    <script src="https://unpkg.com/react-tabs@3/dist/react-tabs.production.min.js"></script>
    <link href="https://unpkg.com/react-tabs@3/style/react-tabs.css" rel="stylesheet">

{else}

    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

    {* tabs support *}
    <script src="https://unpkg.com/prop-types/prop-types.js"></script>
    <script src="https://unpkg.com/react-tabs@3/dist/react-tabs.development.js"></script>
    <link href="https://unpkg.com/react-tabs@3/style/react-tabs.css" rel="stylesheet">

{/if}

{* Babel support *}
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</code>```

This is the full component (contents of the matchSelector.js file):

```<code>import Modal from 'react-modal';

/**
 * Select a match with hooks to return the proper match info to the instantiator
 */
class MatchSelector extends React.Component {
    /**
     * Class Constructor
     *
     * props expected:
     *      className - (optional) use if you want to style the picker button/icon differently. Note that
     *      if given, all standard classes will be overrided.
     *
     *      type - (optional) can be "text", "icon", "both". Default is "both".
     *
     *      text - (optional) if type is "text" or "both", the text to use on the button. Default is "Select Match"
     *
     */
    constructor(props) {
        super(props);       // let Dad know what's up

        this.state = {showDialog:false}

        this.handleClick = this.handleClick.bind(this);
        this.handleClose = this.handleClose.bind(this);
    }

    handleClick(event) {
        event.preventDefault();

        this.setState({showDialog:true});
    }

    handleClose() {
        this.setState({showDialog:false});
    }

    render() {
        const defaultClassName = "ui-state-default ui-corner-all ui-button compressed";
        let className = (odcmp.empty(this.props.className)?defaultClassName:this.props.className);

        return (
                <React.Fragment>
                    <button
                        className={className}
                        onClick={this.handleClick}>
                            {this.buttonContent()}
                    </button>
                    <MatchSearchDialog
                        show={this.state.showDialog} />
                </React.Fragment>
        );
    }

    buttonContent() {
        var text = (odcmp.empty(this.props.text)?"Select Match":this.props.text);

        if (odcmp.empty(this.props.type) || (this.props.type.toLowerCase()=="both")) {
            return (
                <span><span className="ui-icon ui-icon-search inline"></span>{text}</span>
            );
        } else if (this.props.type.toLowerCase()=="icon") {
            return (
                <span className="ui-icon ui-icon-search inline"></span>
            );
        } else {
            return text;
        }
    }
}

class MatchSearchDialog extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <ReactModal isOpen={false}><div>hi</div></ReactModal>
        );
    }
}
</code>```

答:
The doc of the npm package state that to import your modal, you need to write:

import Modal from 'react-modal';

It's not import ReactModal from 'react-modal'; as you tried (ReactModal => Modal).

With this eveything works fine for me as you can see on this repro on Stackblitz. Here is the code :

```<code>import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import Modal from 'react-modal';
import "./style.css";

Modal.setAppElement('#root');

const App = () => {
  const [modalIsOpen,setIsOpen] = React.useState(false);
  const openModal = () => {
    setIsOpen(true);
  }

  const closeModal = () => {
    setIsOpen(false);
  }

  return (
    <div>
      <p>Start editing to see some magic happen :)</p>
      <button onClick={openModal}>Open Modal</button>
        <Modal
          isOpen={modalIsOpen}
          contentLabel="Example Modal"
        >
        <div>Wow nice modal !</div>
        <button onClick={closeModal}>close</button>
        </Modal>
    </div>
  );
};

render(<App />, document.getElementById("root"));

</code>```

Body:
I've been slowly trying to migrate some pieces of an existing, large php/jquery project to use ReactJS, especially using some reusable components. ReactJS has been working well for me, but today I tried to import a library using npm, which is completely new to me.

After running npm install react-modal I see that node_modules\react-modal (along with several other folders) were created. So far, so good.

However, I cannot seem to include that component into my project. If I try import ReactModal from 'react-modal'; at the top of my component's .js file, I get: Uncaught ReferenceError: require is not defined. I get errors thrown if I try to include the node_modules\react-modal\lib\components\Modal.js file directly, which I realize is probably the wrong approach but I'm grasping at straws here. I suspect I'm missing something basic, but I just can't seem to figure this one out. Does anyone have any ideas?

Edit: here is how I include React into my project currently:

{if $env=="prod"}

    {* tabs support *}

    <link href="https://unpkg.com/react-tabs@3/style/react-tabs.css" rel="stylesheet">

{else}

    {* tabs support *}

    <link href="https://unpkg.com/react-tabs@3/style/react-tabs.css" rel="stylesheet">

{/if}

{* Babel support *}

This is the full component (contents of the matchSelector.js file):

import Modal from 'react-modal';

/**
 * Select a match with hooks to return the proper match info to the instantiator
 */
class MatchSelector extends React.Component {
    /**
     * Class Constructor
     *
     * props expected:
     *      className - (optional) use if you want to style the picker button/icon differently. Note that
     *      if given, all standard classes will be overrided.
     *
     *      type - (optional) can be "text", "icon", "both". Default is "both".
     *
     *      text - (optional) if type is "text" or "both", the text to use on the button. Default is "Select Match"
     *
     */
    constructor(props) {
        super(props);       // let Dad know what's up

        this.state = {showDialog:false}

        this.handleClick = this.handleClick.bind(this);
        this.handleClose = this.handleClose.bind(this);
    }

    handleClick(event) {
        event.preventDefault();

        this.setState({showDialog:true});
    }

    handleClose() {
        this.setState({showDialog:false});
    }

    render() {
        const defaultClassName = "ui-state-default ui-corner-all ui-button compressed";
        let className = (odcmp.empty(this.props.className)?defaultClassName:this.props.className);

        return (
                <React.Fragment>
                    <button
                        className={className}
                        onClick={this.handleClick}>
                            {this.buttonContent()}
                    </button>
                    <MatchSearchDialog
                        show={this.state.showDialog} />
                </React.Fragment>
        );
    }

    buttonContent() {
        var text = (odcmp.empty(this.props.text)?"Select Match":this.props.text);

        if (odcmp.empty(this.props.type) || (this.props.type.toLowerCase()=="both")) {
            return (
                {text}
            );
        } else if (this.props.type.toLowerCase()=="icon") {
            return (

            );
        } else {
            return text;
        }
    }
}

class MatchSearchDialog extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <ReactModal isOpen={false}>
hi
</ReactModal>
        );
    }
}

Body:
The doc of the npm package state that to import your modal, you need to write:

import Modal from 'react-modal';

It's not import ReactModal from 'react-modal'; as you tried (ReactModal => Modal).

With this eveything works fine for me as you can see on this repro on Stackblitz. Here is the code :

import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import Modal from 'react-modal';
import "./style.css";

Modal.setAppElement('#root');

const App = () => {
  const [modalIsOpen,setIsOpen] = React.useState(false);
  const openModal = () => {
    setIsOpen(true);
  }

  const closeModal = () => {
    setIsOpen(false);
  }

  return (
    <div>
      <p>Start editing to see some magic happen :)</p>
      <button onClick={openModal}>Open Modal</button>
        <Modal
          isOpen={modalIsOpen}
          contentLabel="Example Modal"
        >
        <div>Wow nice modal !</div>
        <button onClick={closeModal}>close</button>
        </Modal>
    </div>
  );
};

render(<App />, document.getElementById("root"));