问:
Extract the 'src' attribute from an 'img' tag using Beautiful Soup
Consider:

```

I want to extract the source (i.e., src) attribute from an image (i.e., img) tag using Beautiful Soup. I use Beautiful Soup 4, and I cannot use a.attrs['src'] to get the src, but I can get href. What should I do?

答:
You can use Beautiful Soup to extract the src attribute of an HTML img tag. In my example, the htmlText contains the img tag itself, but this can be used for a URL too, along with urllib2.

The solution provided by the Abu Shoeb's answer is not working any more with Python 3. This is the correct implementation:

For URLs

from bs4 import BeautifulSoup as BSHTML
import urllib3

http = urllib3.PoolManager()
url = 'your_url'

response = http.request('GET', url)
soup = BSHTML(response.data, "html.parser")
images = soup.findAll('img')

for image in images:
    # Print image source
    print(image['src'])
    # Print alternate text
    print(image['alt'])
```
<p><strong>For texts with the 'img' tag</strong></p>
<pre class="lang-py prettyprint-override"><code>from bs4 import BeautifulSoup as BSHTML
htmlText = """<img src="https://src1.com/" <img src="https://src2.com/" /> """
soup = BSHTML(htmlText)
images = soup.findAll('img')
for image in images:
    print(image['src'])
</code>```

Body:
Consider:

I want to extract the source (i.e., src) attribute from an image (i.e., img) tag using Beautiful Soup. I use Beautiful Soup 4, and I cannot use a.attrs['src'] to get the src, but I can get href. What should I do?

Body:
You can use Beautiful Soup to extract the src attribute of an HTML img tag. In my example, the htmlText contains the img tag itself, but this can be used for a URL too, along with urllib2.

The solution provided by the Abu Shoeb's answer is not working any more with Python 3. This is the correct implementation:

For URLs

from bs4 import BeautifulSoup as BSHTML
import urllib3

http = urllib3.PoolManager()
url = 'your_url'

response = http.request('GET', url)
soup = BSHTML(response.data, "html.parser")
images = soup.findAll('img')

for image in images:
    # Print image source
    print(image['src'])
    # Print alternate text
    print(image['alt'])

For texts with the 'img' tag

from bs4 import BeautifulSoup as BSHTML
htmlText = """<img src="https://src1.com/" <img src="https://src2.com/" /> """
soup = BSHTML(htmlText)
images = soup.findAll('img')
for image in images:
    print(image['src'])


来源: stackexchange

问:
Creating Cognito User Pool With Custom Domain name from AWS CDK
I'm trying to creating Cognito user pool with a custom domain name through AWS CDK. I manage to get everyting working untill to the point where I needed to create an A record in the Rout53 hosted zone. I searched through all the documents but coudn't find a way to do that. Following is my code. Any help would be much appriciated.

```<code>      const cfnUserPool = new CfnUserPool(this, 'MyCognitoUserPool', {
            userPoolName: 'MyCognitoUserPool',
            adminCreateUserConfig: {
                allowAdminCreateUserOnly: false
            },
            policies: {
                passwordPolicy: {
                    minimumLength: 8,
                    requireLowercase: true,
                    requireNumbers: true,
                    requireSymbols: true,
                    requireUppercase: true,
                    temporaryPasswordValidityDays: 30
                }
            },
            usernameAttributes: [
                UserPoolAttribute.EMAIL
            ],
            schema: [
                {
                    attributeDataType: 'String',
                    name: UserPoolAttribute.EMAIL,
                    mutable: true,
                    required: true
                },
                {
                    attributeDataType: 'String',
                    name: UserPoolAttribute.FAMILY_NAME,
                    mutable: false,
                    required: true
                },
                {
                    attributeDataType: 'String',
                    name: UserPoolAttribute.GIVEN_NAME,
                    mutable: false,
                    required: true
                }
            ]
        });

      const cognitoAppDomain = new CfnUserPoolDomain(this, "PigletAuthDomainName", {
            domain: authDomainName,
            userPoolId: cfnUserPool.ref,
            customDomainConfig: {
                certificateArn: 'ACM Certificate arn'
            }
        });

    /*
      TODO: Create an A record from the created cnfUserPoolDomain
    */
</code>```

Everything works up untill to this point. Now the question is how to create an A record using the CfnUserPoolDomain

Any help is much appriciated.

答:
Update May 2020

The UserPoolDomain construct has been extended and a UserPoolDomainTarget was added to provide this functionality.

Now, all you need to do is the following:

const userPoolDomain = new cognito.UserPoolDomain(this, 'UserPoolDomain', {
  userPool,
  customDomain: {
    domainName: authDomainName,
    certificate,
  },
});

new route53.ARecord(this, 'UserPoolCloudFrontAliasRecord', {
  zone: hostedZone,
  recordName: authDomainName,
  target: route53.RecordTarget.fromAlias(new route53_targets.UserPoolDomainTarget(userPoolDomain)),
});
```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to creating Cognito user pool with a custom domain name through AWS CDK. I manage to get everyting working untill to the point where I needed to create an A record in the Rout53 hosted zone. I searched through all the documents but coudn't find a way to do that. Following is my code. Any help would be much appriciated.

      const cfnUserPool = new CfnUserPool(this, 'MyCognitoUserPool', {
            userPoolName: 'MyCognitoUserPool',
            adminCreateUserConfig: {
                allowAdminCreateUserOnly: false
            },
            policies: {
                passwordPolicy: {
                    minimumLength: 8,
                    requireLowercase: true,
                    requireNumbers: true,
                    requireSymbols: true,
                    requireUppercase: true,
                    temporaryPasswordValidityDays: 30
                }
            },
            usernameAttributes: [
                UserPoolAttribute.EMAIL
            ],
            schema: [
                {
                    attributeDataType: 'String',
                    name: UserPoolAttribute.EMAIL,
                    mutable: true,
                    required: true
                },
                {
                    attributeDataType: 'String',
                    name: UserPoolAttribute.FAMILY_NAME,
                    mutable: false,
                    required: true
                },
                {
                    attributeDataType: 'String',
                    name: UserPoolAttribute.GIVEN_NAME,
                    mutable: false,
                    required: true
                }
            ]
        });

      const cognitoAppDomain = new CfnUserPoolDomain(this, "PigletAuthDomainName", {
            domain: authDomainName,
            userPoolId: cfnUserPool.ref,
            customDomainConfig: {
                certificateArn: 'ACM Certificate arn'
            }
        });

    /*
      TODO: Create an A record from the created cnfUserPoolDomain
    */

Everything works up untill to this point. Now the question is how to create an A record using the CfnUserPoolDomain

Any help is much appriciated.


问:
How do I configure an output device for PyAudio
I have been looking for a method to play a wavfile on a specific output-device using a PyAudio-stream.
The documentation of the stream-class initialization hasn't provided any further information :(
The wav file playing part is done, so the only thing that remains is the device configuration
Thanks in advance!</p>

答:
Came up with the solution myself:

You gotta pass the keyword argument "output_device_index" into the stream class constructor
Namely:

p = pyaudio.PyAudio()
stream = p.open(
    format              = p.get_format_from_width(wf.getsampwidth()),
    channels            = wf.getnchannels(),
    rate                = wf.getframerate(),
    output              = True,
    output_device_index = 16
)
```


问:
Automatically select all text on focus Xamarin
How to automatically select all text on focus in Entry,Editor,Label? Use Cross Platforms.

```<code>Quantity.IsFocused = true;
</code>```

No work :(

答:
As mentioned in other answers, if you are using Xamarin Forms 4.2+, you can use the CursorPosition and SelectionLength properties.  However, you need to make sure you invoke on the Main/UI thread as all direct manipulation of UI elements must be done there.  The app will very likely crash when deployed to a device without doing so, even if it appears to run fine in a simulator.

XAML

```<code><Entry x:Name="MyEntry" Focused="MyEntry_Focused"  />
</code>```

C#

```<code>private void MyEntry_Focused(object sender, FocusEventArgs e)
{
    Dispatcher.BeginInvokeOnMainThread(() =>
    {
        MyEntry.CursorPosition = 0;
        MyEntry.SelectionLength = MyEntry.Text != null ? MyEntry.Text.Length : 0
    });
}
</code>```

For Xamarin.Forms, you can also use Device.BeginInvokeOnMainThread() rather than Dispatcher.  If you're using Xamarin Essentials, there is also MainThread.BeginInvokeOnMainThread() (which does the same as Device.BeginInvokeOnMainThread()).

Xamarin.Forms has a method called Device.BeginInvokeOnMainThread(Action) that does the same thing as MainThread.BeginInvokeOnMainThread(Action). While you can use either method in a Xamarin.Forms app, consider whether or not the calling code has any other need for a dependency on Xamarin.Forms. If not, MainThread.BeginInvokeOnMainThread(Action) is likely a better option.

ContentLicense: CC BY-SA 3.0

Body:
How to automatically select all text on focus in Entry,Editor,Label? Use Cross Platforms.

Quantity.IsFocused = true;

No work :(

Body:
As mentioned in other answers, if you are using Xamarin Forms 4.2+, you can use the CursorPosition and SelectionLength properties.  However, you need to make sure you invoke on the Main/UI thread as all direct manipulation of UI elements must be done there.  The app will very likely crash when deployed to a device without doing so, even if it appears to run fine in a simulator.

XAML

<Entry x:Name="MyEntry" Focused="MyEntry_Focused"  />

C#

private void MyEntry_Focused(object sender, FocusEventArgs e)
{
    Dispatcher.BeginInvokeOnMainThread(() =>
    {
        MyEntry.CursorPosition = 0;
        MyEntry.SelectionLength = MyEntry.Text != null ? MyEntry.Text.Length : 0
    });
}

For Xamarin.Forms, you can also use Device.BeginInvokeOnMainThread() rather than Dispatcher.  If you're using Xamarin Essentials, there is also MainThread.BeginInvokeOnMainThread() (which does the same as Device.BeginInvokeOnMainThread()).

Xamarin.Forms has a method called Device.BeginInvokeOnMainThread(Action) that does the same thing as MainThread.BeginInvokeOnMainThread(Action). While you can use either method in a Xamarin.Forms app, consider whether or not the calling code has any other need for a dependency on Xamarin.Forms. If not, MainThread.BeginInvokeOnMainThread(Action) is likely a better option.


问:
Error creating a table in SQLite using CREATE TABLE <name> AS SELECT
I am trying to create a dates table that generates EOM dates for a specific date range, but SQLite is throwing an error when creating the table. The current code I have is as follows:

```<code>WITH RECURSIVE cnt (
        x
) AS (
    SELECT
            0
    UNION ALL
    SELECT
            x + 1
    FROM
            cnt
    LIMIT (
            SELECT
                    ROUND(((julianday ('2020-05-01') - julianday ('2016-04-01')) / 30) + 1))
)

CREATE TABLE report_dates AS
SELECT
  date(date(julianday ('2016-04-01'), '+' || x || ' month'), '-1 day') AS month
FROM
  cnt;
</code>```

However, I am getting the error Query 1 ERROR: near "CREATE": syntax error. Removing the CREATE TABLE report_dates AS line does render the results no problem. What could be driving this?

答:
The cte goes after the create table:

```<code>CREATE TABLE report_dates AS
WITH RECURSIVE cnt (x) AS (
    SELECT 0
    UNION ALL
    SELECT x + 1
    FROM cnt
    LIMIT (
        SELECT ROUND(((julianday ('2020-05-01') - julianday ('2016-04-01')) / 30) + 1)
    )
)
SELECT date(date(julianday ('2016-04-01'), '+' || x || ' month'), '-1 day') AS month
FROM cnt;
</code>```

Body:
I am trying to create a dates table that generates EOM dates for a specific date range, but SQLite is throwing an error when creating the table. The current code I have is as follows:

WITH RECURSIVE cnt (
        x
) AS (
    SELECT
            0
    UNION ALL
    SELECT
            x + 1
    FROM
            cnt
    LIMIT (
            SELECT
                    ROUND(((julianday ('2020-05-01') - julianday ('2016-04-01')) / 30) + 1))
)

CREATE TABLE report_dates AS
SELECT
  date(date(julianday ('2016-04-01'), '+' || x || ' month'), '-1 day') AS month
FROM
  cnt;

However, I am getting the error Query 1 ERROR: near "CREATE": syntax error. Removing the CREATE TABLE report_dates AS line does render the results no problem. What could be driving this?

Body:
The cte goes after the create table:

CREATE TABLE report_dates AS
WITH RECURSIVE cnt (x) AS (
    SELECT 0
    UNION ALL
    SELECT x + 1
    FROM cnt
    LIMIT (
        SELECT ROUND(((julianday ('2020-05-01') - julianday ('2016-04-01')) / 30) + 1)
    )
)
SELECT date(date(julianday ('2016-04-01'), '+' || x || ' month'), '-1 day') AS month
FROM cnt;


问:
How to run an async task for every x mins in android?
how to run the async task at specific time? (I want to run it every 2 mins)

I tried using  post delayed but it's not working?

```<code>    tvData.postDelayed(new Runnable(){

    @Override
    public void run() {
        readWebpage();

    }}, 100);
</code>```

In the above code readwebpage is function which calls the async task for me..

Right now below is the method which I am using

```<code>   public void onCreate(Bundle savedInstanceState) {

         readwebapage();

   }

   public void readWebpage() {
    DownloadWebPageTask task = new DownloadWebPageTask();
    task.execute("http://www.google.com");

   }

   private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        String response1 = "";
        response1=read();
                   //read is my another function which does the real work
        response1=read();
        super.onPostExecute(response1);
        return response1;
    }

      protected void onPostExecute(String result) {

         try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            TextView tvData = (TextView) findViewById(R.id.TextView01);
            tvData.setText(result);

        DownloadWebPageTask task = new DownloadWebPageTask();
        task.execute(new String[] { "http://www.google.com" });

    }

    }
</code>```

This is what I  my code is and it works perfectly fine but the big problem I drains my battery?

答:
You could run a loop within the AsyncTask that sleeps for two seconds between doing the tasks. Something like this:

```<code>protected Result doInBackground (Params... params) {
    while (!interrupted) {
        doWork();
        Thread.sleep(2000);
    }
}
</code>```

Body:
how to run the async task at specific time? (I want to run it every 2 mins)

I tried using  post delayed but it's not working?

    tvData.postDelayed(new Runnable(){

    @Override
    public void run() {
        readWebpage();

    }}, 100);

In the above code readwebpage is function which calls the async task for me..

Right now below is the method which I am using

   public void onCreate(Bundle savedInstanceState) {

         readwebapage();

   }

   public void readWebpage() {
    DownloadWebPageTask task = new DownloadWebPageTask();
    task.execute("http://www.google.com");

   }

   private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        String response1 = "";
        response1=read();
                   //read is my another function which does the real work
        response1=read();
        super.onPostExecute(response1);
        return response1;
    }

      protected void onPostExecute(String result) {

         try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            TextView tvData = (TextView) findViewById(R.id.TextView01);
            tvData.setText(result);

        DownloadWebPageTask task = new DownloadWebPageTask();
        task.execute(new String[] { "http://www.google.com" });

    }

    }

This is what I  my code is and it works perfectly fine but the big problem I drains my battery?

Body:
You could run a loop within the AsyncTask that sleeps for two seconds between doing the tasks. Something like this:

protected Result doInBackground (Params... params) {
    while (!interrupted) {
        doWork();
        Thread.sleep(2000);
    }
}


问:
How can I implement Material Date Range Picker correctly?
I am implementing Date Range Picker with this material library.

```<code>implementation "com.google.android.material:material:1.2.0-alpha05"
</code>```

And this is what I implemented.

```<code>btn_calendar.setOnClickListener {
    val builder = MaterialDatePicker
        .Builder
        .dateRangePicker()
        .setTheme(R.style.DatePickerTheme)
//                .setTitleText("Select dates")
//                .build()

    val now = Calendar.getInstance()

    val picker = builder.build()
    builder.setSelection(androidx.core.util.Pair(now.timeInMillis, now.timeInMillis))
    picker.show(supportFragmentManager, picker.toString())

    picker.addOnPositiveButtonClickListener {
        Toast.makeText(this, "Date String = ${picker.headerText}::  Date epoch values::${it.first}:: to :: ${it.second}", Toast.LENGTH_SHORT).show()
    }
}
</code>```

And the style is:

```<code><style name="DatePickerTheme" parent="Theme.MaterialComponents"/>
</code>```

However, it shows weird looking view. How can I fix this? I want dialog

答:
You should use a Material Components Theme as app theme.

In any case if you are using:

```<code>.setTheme(R.style.DatePickerTheme)
</code>```

you should define a theme like:

```<code>  <style name="DatePickerTheme"
           parent="ThemeOverlay.MaterialComponents.MaterialCalendar" >
       ....
  </style>
</code>```

Body:
I am implementing Date Range Picker with this material library.

implementation "com.google.android.material:material:1.2.0-alpha05"

And this is what I implemented.

btn_calendar.setOnClickListener {
    val builder = MaterialDatePicker
        .Builder
        .dateRangePicker()
        .setTheme(R.style.DatePickerTheme)
//                .setTitleText("Select dates")
//                .build()

    val now = Calendar.getInstance()

    val picker = builder.build()
    builder.setSelection(androidx.core.util.Pair(now.timeInMillis, now.timeInMillis))
    picker.show(supportFragmentManager, picker.toString())

    picker.addOnPositiveButtonClickListener {
        Toast.makeText(this, "Date String = ${picker.headerText}::  Date epoch values::${it.first}:: to :: ${it.second}", Toast.LENGTH_SHORT).show()
    }
}

And the style is:

Body:
You should use a Material Components Theme as app theme.

In any case if you are using:

.setTheme(R.style.DatePickerTheme)

you should define a theme like:

  <style name="DatePickerTheme"
           parent="ThemeOverlay.MaterialComponents.MaterialCalendar" >
       ....
  </style>


问:
What method is called when using a BottomNavigationBar in flutter. I have code in the Init State that is not being called
When I switch from one tab to another tab on my application the init tab is not being called. What method would be the proper method to call when the index is switched?

```<code>return new Scaffold(
      appBar: new AppBar(
        title: new Text('ConnectU'),
        backgroundColor: Colors.blueGrey[600],
        actions: <Widget>[
          new FlatButton(
              child: new Text('Logout',
                  style: new TextStyle(fontSize: 17.0, color: Colors.white)),
              onPressed: signOut)
        ],
      ),
      body: _children[_currentIndex], // new
      bottomNavigationBar: BottomNavigationBar(
        onTap: onTabTapped, // new
        currentIndex: _currentIndex,
        selectedItemColor: Colors.blueGrey,
        unselectedItemColor: Colors.blueGrey[200],// new
        items: [
          new BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: Text('Home'),
          ),
          new BottomNavigationBarItem(
            icon: Icon(Icons.search),
            title: Text('Search'),
          ),
          new BottomNavigationBarItem(
            icon: Icon(Icons.add),
            title: Text('Add'),
          ),
          new BottomNavigationBarItem(
            icon: Icon(Icons.mail),
            title: Text('Messages'),
          ),
          new BottomNavigationBarItem(
              icon: Icon(Icons.person),
              title: Text('Profile')
          )
        ],
      ),
    );
  }
</code>```

This is my code for the navigation bar.

```<code>class homeIndexState extends State<playerHomePageIndex> {
  List<Post> postList;

  final _textEditingController = TextEditingController();

  final databaseReference = Firestore.instance;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: showTodoList(),
    );
  }

  @override
  void initState() {
    super.initState();
    //_checkEmailVerification();
    postList = new List();

    postList.clear();
    popList();

  }
</code>```

This is the init state I am attempting to call. What method should I expect to be called instead?

答: you should use didUpdateWidget insted of initState, since initState is only called one and one time only before the first render, and didUpdateWidget gets called whenever setState is called

Body:
When I switch from one tab to another tab on my application the init tab is not being called. What method would be the proper method to call when the index is switched?

return new Scaffold(
      appBar: new AppBar(
        title: new Text('ConnectU'),
        backgroundColor: Colors.blueGrey[600],
        actions: <Widget>[
          new FlatButton(
              child: new Text('Logout',
                  style: new TextStyle(fontSize: 17.0, color: Colors.white)),
              onPressed: signOut)
        ],
      ),
      body: _children[_currentIndex], // new
      bottomNavigationBar: BottomNavigationBar(
        onTap: onTabTapped, // new
        currentIndex: _currentIndex,
        selectedItemColor: Colors.blueGrey,
        unselectedItemColor: Colors.blueGrey[200],// new
        items: [
          new BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: Text('Home'),
          ),
          new BottomNavigationBarItem(
            icon: Icon(Icons.search),
            title: Text('Search'),
          ),
          new BottomNavigationBarItem(
            icon: Icon(Icons.add),
            title: Text('Add'),
          ),
          new BottomNavigationBarItem(
            icon: Icon(Icons.mail),
            title: Text('Messages'),
          ),
          new BottomNavigationBarItem(
              icon: Icon(Icons.person),
              title: Text('Profile')
          )
        ],
      ),
    );
  }

This is my code for the navigation bar.

class homeIndexState extends State<playerHomePageIndex> {
  List<Post> postList;

  final _textEditingController = TextEditingController();

  final databaseReference = Firestore.instance;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: showTodoList(),
    );
  }

  @override
  void initState() {
    super.initState();
    //_checkEmailVerification();
    postList = new List();

    postList.clear();
    popList();

  }

This is the init state I am attempting to call. What method should I expect to be called instead?


问:
How to make CSS animations occur after clicking on an image
I'm trying to have images move using CSS animations, but after I click on them. Currently, they move as soon as I get on the page. I want it to be that when you click on any of the images, the CSS animation occurs. I believe you would have to do that with some javascript code, but I don't know how to. I'm new to programming and I would love any help I can get. Let me know if you guys need any more information. Thanks

var doineedtowait = 0;
function myFunction(imgs) {
  if(doineedtowait == 0){
  sleep(1000);
  }
  var expandImg = document.getElementById("expandedImg");
  expandImg.src = imgs.src;
  var imgParagraph = document.getElementById('img-paragraph');
  imgParagraph.innerHTML = imgs.getAttribute("yeep");

  expandImg.parentElement.style.display = "table-cell";
  imgParagraph.style.display = 'table-cell';
  doineedtowait++; //after executing we update the doineedtowait to +1
  //so the if with sleep for 1 second will not be used anymore
}
function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}
document.getElementById("myBtn").addEventListener("click", displayDate);

function displayDate() {
  document.getElementById("demo").innerHTML = Date();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@font-face {
  font-family: 'futuralight';
  src: url('../Fonts/Futura Light/futura_light_regular-webfont.woff2') format('woff2'), url('../Fonts/Futura Light/futura_light_regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'tekoregular';
  src: url('../Fonts/Teko/teko-regular-webfont.woff2') format('woff2'), url('../Fonts/Teko/teko-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'playfair_displayregular';
  src: url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff2') format('woff2'), url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'poppinsmedium';
  src: url('../Fonts/Poppins/poppins-medium-webfont.woff2') format('woff2'), url('../Fonts/Poppins/poppins-medium-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

* {
  margin: 0px;
  padding: 0px;
  border: 0px;
}

.topnav {
  background-color: rgb(84, 104, 217);
  overflow: hidden;
  font-family: 'futuralight';
  font-weight: 900;
}

.topnav a {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 20px 21px;
  text-decoration: none;
  font-size: 19px;
  position: relative;
  left: 2%;
}

.topnav a:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
}

.topnav a:hover:before {
  visibility: visible;
  transform: scaleX(1);
}

.topnav a.active-menu:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: visible;
  transform: scaleX(1);
  transition: all 0.3s ease-in-out 0s;
}

.column {
  float: left;
  width: 25%;
  padding: 10px;
}

/* Style the images inside the grid */

.column img {
  opacity: 0.85;
  cursor: pointer;
}

.column img:hover {
  opacity: 1;
}

.totalbody {
  background-color: #EEF0FC;
  height: 5000px;
}

/* Clear floats after the columns */

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

/* The expanding image container */

#expandedImg {
  width: 40%;
  padding-top:20px;
  padding-left:20px;
}

/* Expanding image text */

/* image paragraph */

#img-paragraph {
  display: none;
  vertical-align: top;
  text-align: left;
  position: absolute;
  height: 400px;
  width: 50%;
  background-color: white;
  box-shadow: 0 2.8px 2.2px rgba(0, 0, 0, 0.034), 0 6.7px 5.3px rgba(0, 0, 0, 0.048), 0 12.5px 10px rgba(0, 0, 0, 0.06), 0 22.3px 17.9px rgba(0, 0, 0, 0.072), 0 41.8px 33.4px rgba(0, 0, 0, 0.086), 0 100px 80px rgba(0, 0, 0, 0.12);
  border-radius: 7px;
  float: right;
  right: 30px;
  top: 120px;
}

#expanded-wrapper {
  width: 100%;
}

/* Closable button inside the expanded image */

.row {
  position: absolute;
  top: 80px;
}

.yeep1 {
  position: relative;
  left: 12px;
  top: 16px;
  color: rgb(84, 104, 217);
  font-weight: 900;
  font-size: 40px;
  font-family: 'futuralight';
  text-decoration: none;
  line-height: 1;
  padding-left:4%;
  padding-top:30px;
}

.yeep2 {
  color: purple;
}

.yeep3 {
  color: green;
}
.yeep4 {
  color: blue;
}

.yeep1::before {
  content: '';
  background-color: rgb(84, 104, 217);
  width: 12px;
  height: 100%;
  position: absolute;
  right: 100%;
  bottom: -16px;
}
#column1 {
  position: relative;
  -webkit-animation: floatBubble 2s  normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column2 {
  position: relative;
  -webkit-animation: floatBubble 2s  normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column3 {
  position: relative;
  -webkit-animation: floatBubble 2s  normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column4 {
  position: relative;
  -webkit-animation: floatBubble 2s  normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}

@media only screen and (max-width: 830px) and (min-width: 760px) {
  .topnav {
    background-color: yellow;
    overflow: hidden;
  }
}

@media only screen and (max-width: 759px) and (min-width: 646px) {
  .topnav {
    background-color: red;
    overflow: hidden;
  }
}

@media only screen and (max-width: 645px) {
  .topnav {
    background-color: black;
    overflow: hidden;
  }
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css"  href="../CSS/styleprojects.css" />

    <title>Projects</title>

    Home
    Academics
    Projects
    Community Service

```

答:
You can put the animation in a separate css class, and then apply this class when you click on the image:

in your .css:

```<code>#column1 {
    position: relative;
}

.animate {
    -webkit-animation: floatBubble 2s normal ease-out;
    animation: floatBubble 2s forwards normal ease-out;
}
</code>```

in your .js:

```<code>function myFunction(imgs) {
    document.getElementById('column1').classList.add('animate');

    // your code ...
}
</code>```

Body:
I'm trying to have images move using CSS animations, but after I click on them. Currently, they move as soon as I get on the page. I want it to be that when you click on any of the images, the CSS animation occurs. I believe you would have to do that with some javascript code, but I don't know how to. I'm new to programming and I would love any help I can get. Let me know if you guys need any more information. Thanks

var doineedtowait = 0;
function myFunction(imgs) {
  if(doineedtowait == 0){
  sleep(1000);
  }
  var expandImg = document.getElementById("expandedImg");
  expandImg.src = imgs.src;
  var imgParagraph = document.getElementById('img-paragraph');
  imgParagraph.innerHTML = imgs.getAttribute("yeep");

  expandImg.parentElement.style.display = "table-cell";
  imgParagraph.style.display = 'table-cell';
  doineedtowait++; //after executing we update the doineedtowait to +1
  //so the if with sleep for 1 second will not be used anymore
}
function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}
document.getElementById("myBtn").addEventListener("click", displayDate);

function displayDate() {
  document.getElementById("demo").innerHTML = Date();
}

@font-face {
  font-family: 'futuralight';
  src: url('../Fonts/Futura Light/futura_light_regular-webfont.woff2') format('woff2'), url('../Fonts/Futura Light/futura_light_regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'tekoregular';
  src: url('../Fonts/Teko/teko-regular-webfont.woff2') format('woff2'), url('../Fonts/Teko/teko-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'playfair_displayregular';
  src: url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff2') format('woff2'), url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'poppinsmedium';
  src: url('../Fonts/Poppins/poppins-medium-webfont.woff2') format('woff2'), url('../Fonts/Poppins/poppins-medium-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

* {
  margin: 0px;
  padding: 0px;
  border: 0px;
}

.topnav {
  background-color: rgb(84, 104, 217);
  overflow: hidden;
  font-family: 'futuralight';
  font-weight: 900;
}

.topnav a {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 20px 21px;
  text-decoration: none;
  font-size: 19px;
  position: relative;
  left: 2%;
}

.topnav a:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
}

.topnav a:hover:before {
  visibility: visible;
  transform: scaleX(1);
}

.topnav a.active-menu:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: visible;
  transform: scaleX(1);
  transition: all 0.3s ease-in-out 0s;
}

.column {
  float: left;
  width: 25%;
  padding: 10px;
}

/* Style the images inside the grid */

.column img {
  opacity: 0.85;
  cursor: pointer;
}

.column img:hover {
  opacity: 1;
}

.totalbody {
  background-color: #EEF0FC;
  height: 5000px;
}

/* Clear floats after the columns */

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

/* The expanding image container */

#expandedImg {
  width: 40%;
  padding-top:20px;
  padding-left:20px;
}

/* Expanding image text */

/* image paragraph */

#img-paragraph {
  display: none;
  vertical-align: top;
  text-align: left;
  position: absolute;
  height: 400px;
  width: 50%;
  background-color: white;
  box-shadow: 0 2.8px 2.2px rgba(0, 0, 0, 0.034), 0 6.7px 5.3px rgba(0, 0, 0, 0.048), 0 12.5px 10px rgba(0, 0, 0, 0.06), 0 22.3px 17.9px rgba(0, 0, 0, 0.072), 0 41.8px 33.4px rgba(0, 0, 0, 0.086), 0 100px 80px rgba(0, 0, 0, 0.12);
  border-radius: 7px;
  float: right;
  right: 30px;
  top: 120px;
}

#expanded-wrapper {
  width: 100%;
}

/* Closable button inside the expanded image */

.row {
  position: absolute;
  top: 80px;
}

.yeep1 {
  position: relative;
  left: 12px;
  top: 16px;
  color: rgb(84, 104, 217);
  font-weight: 900;
  font-size: 40px;
  font-family: 'futuralight';
  text-decoration: none;
  line-height: 1;
  padding-left:4%;
  padding-top:30px;
}

.yeep2 {
  color: purple;
}

.yeep3 {
  color: green;
}
.yeep4 {
  color: blue;
}

.yeep1::before {
  content: '';
  background-color: rgb(84, 104, 217);
  width: 12px;
  height: 100%;
  position: absolute;
  right: 100%;
  bottom: -16px;
}
#column1 {
  position: relative;
  -webkit-animation: floatBubble 2s  normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column2 {
  position: relative;
  -webkit-animation: floatBubble 2s  normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column3 {
  position: relative;
  -webkit-animation: floatBubble 2s  normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column4 {
  position: relative;
  -webkit-animation: floatBubble 2s  normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}

@media only screen and (max-width: 830px) and (min-width: 760px) {
  .topnav {
    background-color: yellow;
    overflow: hidden;
  }
}

@media only screen and (max-width: 759px) and (min-width: 646px) {
  .topnav {
    background-color: red;
    overflow: hidden;
  }
}

@media only screen and (max-width: 645px) {
  .topnav {
    background-color: black;
    overflow: hidden;
  }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css"  href="../CSS/styleprojects.css" />

    <title>Projects</title>

    Home
    Academics
    Projects
    Community Service

Body:
You can put the animation in a separate css class, and then apply this class when you click on the image:

in your .css:

#column1 {
    position: relative;
}

.animate {
    -webkit-animation: floatBubble 2s normal ease-out;
    animation: floatBubble 2s forwards normal ease-out;
}

in your .js:

function myFunction(imgs) {
    document.getElementById('column1').classList.add('animate');

    // your code ...
}


问:
Most efficient way to return values conditionally from populated Models using Mongoose and GraphQL?
My goal is to conditionally return Model values based on data retrieved from the Models themselves after population.

This is my current solution:

```<code>const bcrypt = require("bcryptjs")
const jwt = require("jsonwebtoken")
const moment = require("moment")

const User = require("../../models/user")
const Post = require("../../models/post")

const { checkAuthorSettings, checkFollowingAuthorSettings } = require('../../shared/utility')

login: async ({ email, password }) => {
  try {
    const user = await User.findOne({ email }).populate([
      {
        path: 'posts',
        model: 'Post',
        populate: [
          {
            path: 'author',
            model: 'User',
          },
          {
            path: 'comments',
            model: 'Comment',
            populate: {
              path: 'author',
              model: 'User',
            },
          },
        ],
      },
      {
        path: 'following',
        model: 'User',
        populate: {
          path: 'posts',
          model: 'Post',
          populate: [
            {
              path: 'author',
              model: 'User',
            },
            {
              path: 'comments',
              model: 'Comment',
              populate: {
                path: 'author',
                model: 'User',
              },
            },
          ],
        },
      },
      {
        path: 'favourites',
        model: 'Post',
        populate: [
          {
            path: 'author',
            model: 'User',
          },
          {
            path: 'comments',
            model: 'Comment',
            populate: {
              path: 'author',
              model: 'User',
            },
          },
        ],
      },
    ])

    if (!user) throw new Error("An Account by that Email was not found!")
    if (!password) throw new Error("Please enter your password")

    const passIsValid = bcrypt.compareSync( password, user.password )
    if (!passIsValid) throw new Error("Incorrect Password")

    const token = jwt.sign(
      {
        _id: user._id,
        email: user.email,
      },
      `${process.env.JWT_SECRET}`,
      { expiresIn: "1h" }
    )

    user.status = "online"
    user.logged_in_at = moment().format()
    await user.save()

    return {
      ...user._doc,
      token,
      token_expiry: 1,
      email: user.settings.display_email ? user.email : "",
      website: user.settings.display_website ? user.website : "",
      password: null,
      posts: await checkAuthorSettings(user.posts),
      following: await checkFollowingAuthorSettings(user.following),
      favourites: await checkAuthorSettings(user.favourites),
      info: JSON.stringify(user._doc.info),
      geolocation: JSON.stringify(user._doc.geolocation),
      settings: JSON.stringify(user._doc.settings),
    }
  } catch (err) {
    throw err
  }
},
</code>```

utility.js:

```<code>const checkAuthorSettings = array => {
  return array.map(post => {
    return {
      ...post._doc,
      author: {
        ...post._doc.author._doc,
        email: post._doc.author._doc.settings.display_email ? post._doc.author._doc.email : "",
        website: post._doc.author._doc.settings.display_website ? post._doc.author._doc.website : "",
      }
    }
  })
}

const checkFollowingAuthorSettings = array => {
  return array.map(followed => {
    return {
      ...followed._doc,
      posts: checkAuthorSettings(followed.posts)
    }
  })
}

exports.checkAuthorSettings = checkAuthorSettings
exports.checkFollowingAuthorSettings = checkFollowingAuthorSettings
</code>```

I'm currently looping through each array in User which I imagine is far from the most efficient way to achieve this.

Does anybody have a better solution than this?

答:
You can use virtuals, there are many ways to implement virtuals, if you want to replace the email field directly, you can use getters

For example

const AuthorSchema = new Schema({
// other fields
  email: String,
}, {
  toObject: { getters: true }
})

AuthorSchema.path('email').get(function(email) {
  return this.get('settings.display_email') ? email : ''
})

```

Then when you call .toObject() on a document, you will get a virtual value instead.

Body:
My goal is to conditionally return Model values based on data retrieved from the Models themselves after population.

This is my current solution:

const bcrypt = require("bcryptjs")
const jwt = require("jsonwebtoken")
const moment = require("moment")

const User = require("../../models/user")
const Post = require("../../models/post")

const { checkAuthorSettings, checkFollowingAuthorSettings } = require('../../shared/utility')

login: async ({ email, password }) => {
  try {
    const user = await User.findOne({ email }).populate([
      {
        path: 'posts',
        model: 'Post',
        populate: [
          {
            path: 'author',
            model: 'User',
          },
          {
            path: 'comments',
            model: 'Comment',
            populate: {
              path: 'author',
              model: 'User',
            },
          },
        ],
      },
      {
        path: 'following',
        model: 'User',
        populate: {
          path: 'posts',
          model: 'Post',
          populate: [
            {
              path: 'author',
              model: 'User',
            },
            {
              path: 'comments',
              model: 'Comment',
              populate: {
                path: 'author',
                model: 'User',
              },
            },
          ],
        },
      },
      {
        path: 'favourites',
        model: 'Post',
        populate: [
          {
            path: 'author',
            model: 'User',
          },
          {
            path: 'comments',
            model: 'Comment',
            populate: {
              path: 'author',
              model: 'User',
            },
          },
        ],
      },
    ])

    if (!user) throw new Error("An Account by that Email was not found!")
    if (!password) throw new Error("Please enter your password")

    const passIsValid = bcrypt.compareSync( password, user.password )
    if (!passIsValid) throw new Error("Incorrect Password")

    const token = jwt.sign(
      {
        _id: user._id,
        email: user.email,
      },
      `${process.env.JWT_SECRET}`,
      { expiresIn: "1h" }
    )

    user.status = "online"
    user.logged_in_at = moment().format()
    await user.save()

    return {
      ...user._doc,
      token,
      token_expiry: 1,
      email: user.settings.display_email ? user.email : "",
      website: user.settings.display_website ? user.website : "",
      password: null,
      posts: await checkAuthorSettings(user.posts),
      following: await checkFollowingAuthorSettings(user.following),
      favourites: await checkAuthorSettings(user.favourites),
      info: JSON.stringify(user._doc.info),
      geolocation: JSON.stringify(user._doc.geolocation),
      settings: JSON.stringify(user._doc.settings),
    }
  } catch (err) {
    throw err
  }
},

utility.js:

const checkAuthorSettings = array => {
  return array.map(post => {
    return {
      ...post._doc,
      author: {
        ...post._doc.author._doc,
        email: post._doc.author._doc.settings.display_email ? post._doc.author._doc.email : "",
        website: post._doc.author._doc.settings.display_website ? post._doc.author._doc.website : "",
      }
    }
  })
}

const checkFollowingAuthorSettings = array => {
  return array.map(followed => {
    return {
      ...followed._doc,
      posts: checkAuthorSettings(followed.posts)
    }
  })
}

exports.checkAuthorSettings = checkAuthorSettings
exports.checkFollowingAuthorSettings = checkFollowingAuthorSettings

I'm currently looping through each array in User which I imagine is far from the most efficient way to achieve this.

Does anybody have a better solution than this?

Body:
You can use virtuals, there are many ways to implement virtuals, if you want to replace the email field directly, you can use getters

For example

const AuthorSchema = new Schema({
// other fields
  email: String,
}, {
  toObject: { getters: true }
})

AuthorSchema.path('email').get(function(email) {
  return this.get('settings.display_email') ? email : ''
})

Then when you call .toObject() on a document, you will get a virtual value instead.


问:
How to check effectively if one path is a child of another path in C#?
I am trying to determine if one path is a child of another path.

I already tried with:

```<code>if (Path.GetFullPath(A).StartsWith(Path.GetFullPath(B)) ||
    Path.GetFullPath(B).StartsWith(Path.GetFullPath(A)))
   { /* ... do your magic ... */ }
</code>```

like in How to check if one path is a child of another path?  post

But it doesn't work. For example if I write "C:\files" and "C:\files baaa" the code thinks that the "C:\files baaa" is a child of "C:\files", when it isn't, it is only of C:.
The problem is really heavy when I try with long paths, with an amount of childs.

I also tried with "if contains \"... but still not really working in all the chases

What can I do?

Thanks!

答:
I needed to know if folder B was the same as OR was contained within folder A.

The following worked for me:

```<code>if (A.FullName.Contains(B.FullName))
{
// Path A is equal to or contained within path B. (B is a child of A)
}
</code>```

Body:
I am trying to determine if one path is a child of another path.

I already tried with:

if (Path.GetFullPath(A).StartsWith(Path.GetFullPath(B)) ||
    Path.GetFullPath(B).StartsWith(Path.GetFullPath(A)))
   { /* ... do your magic ... */ }

like in How to check if one path is a child of another path?  post

But it doesn't work. For example if I write "C:\files" and "C:\files baaa" the code thinks that the "C:\files baaa" is a child of "C:\files", when it isn't, it is only of C:.
The problem is really heavy when I try with long paths, with an amount of childs.

I also tried with "if contains \"... but still not really working in all the chases

What can I do?

Thanks!

Body:
I needed to know if folder B was the same as OR was contained within folder A.

The following worked for me:

if (A.FullName.Contains(B.FullName))
{
// Path A is equal to or contained within path B. (B is a child of A)
}


问:
SignalR client flutter library shows null values in another widget when using Flutter Provider
Am trying to connect on a SignalR server with flutter, and I tried to use Provider to access the data which comes to another Widget, but am receiving a null value. This is the SignalR  library for flutter am using.

Below is my Class which extends a ChangeNotifier :

```<code>class BreakingNewsSignalRClient with ChangeNotifier {
  String  _breakingNews;

  Future<void> getBreakingNews() async {
    final hubConnection = HubConnectionBuilder()
        .withUrl('https://services.xxxx.com/breakingNews')
        .build();
      await hubConnection.start();
      hubConnection.on("UpdateBreakingNews", (data){

        _breakingNews = data.toString();
        print(data.toString());

        notifyListeners();
      });
      hubConnection.onclose((error) => print("Connection Closed"));

  }

  String get breakingNewsFunction => _breakingNews;
}

class BreakingNewsModel {
  final String News;
  BreakingNewsModel(this.News);
}
</code>```

As you can see the code above, am having a getter String get breakingNewsFunction => _breakingNews;,  this is called in another Stateful Widget to populate some data from the SignalR  server, but it returns null in the other widget, however, when you try to print data here in the getBreakingNews method the data is shown.

Below is another Widget class which receives the data :

```<code>class BreakingNews extends StatefulWidget {
  const BreakingNews({Key key, @required this.article, @required this.index})
      : super(key: key);
  final Article article;
  final int index;

  @override
  _BreakingNewsState createState() => _BreakingNewsState();
}

class _BreakingNewsState extends State<BreakingNews> {

  settings() async{
    var breakingNewsInfo =
    Provider.of<BreakingNewsSignalRClient>(context, listen: false);

    await breakingNewsInfo.getBreakingNews();

    print('lets see -- ${breakingNewsInfo.breakingNewsFunction}');
  }

  @override
  void initState() {
    // TODO: implement initState
    settings();
    super.initState();
  }
}
</code>```

So when you look at this line print('lets see -- ${breakingNewsInfo.breakingNewsFunction}');, it prints null, am still wondering what am doing wrong here.

Kindly need some help.

答:
This is pretty simple. Your Future<void> getBreakingNews() async returns void and therefore null. Just adjust the return type to whatever you need.

Edit:

Actually, the problem is you are not calling your getter here.

```<code>await breakingNewsInfo.getBreakingNews();
</code>```

So either return your result from the function, or call the getter. Either should work.

Body:
Am trying to connect on a SignalR server with flutter, and I tried to use Provider to access the data which comes to another Widget, but am receiving a null value. This is the SignalR  library for flutter am using.

Below is my Class which extends a ChangeNotifier :

class BreakingNewsSignalRClient with ChangeNotifier {
  String  _breakingNews;

  Future<void> getBreakingNews() async {
    final hubConnection = HubConnectionBuilder()
        .withUrl('https://services.xxxx.com/breakingNews')
        .build();
      await hubConnection.start();
      hubConnection.on("UpdateBreakingNews", (data){

        _breakingNews = data.toString();
        print(data.toString());

        notifyListeners();
      });
      hubConnection.onclose((error) => print("Connection Closed"));

  }

  String get breakingNewsFunction => _breakingNews;
}

class BreakingNewsModel {
  final String News;
  BreakingNewsModel(this.News);
}

As you can see the code above, am having a getter String get breakingNewsFunction => _breakingNews;,  this is called in another Stateful Widget to populate some data from the SignalR  server, but it returns null in the other widget, however, when you try to print data here in the getBreakingNews method the data is shown.

Below is another Widget class which receives the data :

class BreakingNews extends StatefulWidget {
  const BreakingNews({Key key, @required this.article, @required this.index})
      : super(key: key);
  final Article article;
  final int index;

  @override
  _BreakingNewsState createState() => _BreakingNewsState();
}

class _BreakingNewsState extends State<BreakingNews> {

  settings() async{
    var breakingNewsInfo =
    Provider.of<BreakingNewsSignalRClient>(context, listen: false);

    await breakingNewsInfo.getBreakingNews();

    print('lets see -- ${breakingNewsInfo.breakingNewsFunction}');
  }

  @override
  void initState() {
    // TODO: implement initState
    settings();
    super.initState();
  }
}

So when you look at this line print('lets see -- ${breakingNewsInfo.breakingNewsFunction}');, it prints null, am still wondering what am doing wrong here.

Kindly need some help.

Body:
This is pretty simple. Your Future<void> getBreakingNews() async returns void and therefore null. Just adjust the return type to whatever you need.

Edit:

Actually, the problem is you are not calling your getter here.

await breakingNewsInfo.getBreakingNews();

So either return your result from the function, or call the getter. Either should work.


问:
Linq - how to write group by query to get quantity of each product
Hello every one I have a data as follows

```<code>Item    Qty Type
1       2   Purchase
1       3   Sales
1       8   Return

2       5   Purchase
2       4   Sales
2       5   Return
</code>```

Now I have a requirement of getting quantity of each item by Subtracting Sales and Return with Purchase
And my final output would be

```<code>item    Qty
1      -9
2      -4
</code>```

Note : To get quantity: Qty => (Purchase Qty - SalesQty - Return Qty) eg: (2-3-8)

So how can I write this query on LINQ or in SQL

答:
If you are using LINQ to SQL, you can do:

```<code>var ans = from i in src
          group i by i.Item into ig
          let PurchaseQty = ig.Where(i => i.Type == "Purchase").Sum(i => i.Qty)
          let SalesQty = ig.Where(i => i.Type == "Sales").Sum(i => i.Qty)
          let ReturnQty = ig.Where(i => i.Type == "Return").Sum(i => i.Qty)
          select new {
              Item = ig.Key,
              Qty = PurchaseQty - SalesQty - ReturnQty
          };
</code>```

If you are using LINQ to EF 2.2, it may work but will do the grouping client side. If you are using EF 3.x, good luck!

Body:
Hello every one I have a data as follows

Item    Qty Type
1       2   Purchase
1       3   Sales
1       8   Return

2       5   Purchase
2       4   Sales
2       5   Return

Now I have a requirement of getting quantity of each item by Subtracting Sales and Return with Purchase
And my final output would be

item    Qty
1      -9
2      -4

Note : To get quantity: Qty => (Purchase Qty - SalesQty - Return Qty) eg: (2-3-8)

So how can I write this query on LINQ or in SQL

Body:
If you are using LINQ to SQL, you can do:

var ans = from i in src
          group i by i.Item into ig
          let PurchaseQty = ig.Where(i => i.Type == "Purchase").Sum(i => i.Qty)
          let SalesQty = ig.Where(i => i.Type == "Sales").Sum(i => i.Qty)
          let ReturnQty = ig.Where(i => i.Type == "Return").Sum(i => i.Qty)
          select new {
              Item = ig.Key,
              Qty = PurchaseQty - SalesQty - ReturnQty
          };

If you are using LINQ to EF 2.2, it may work but will do the grouping client side. If you are using EF 3.x, good luck!


问:
will an in clause always return the same order in mysql
ok so i have this query

```<code>select price from product where product_id in (49, 50, 51)
</code>```

and I want to know if the three records returned will be in the same order as my in clause. SO for example

```<code>100.0000
166.0000
55.0000
</code>```

will 100.0000 belong to 49, 166.0000 to 50 and 55.0000 to 51

答: No. They will be returned in the order which they are encountered when selecting from the product table. Ordering in a database is an expensive operation, so it won't sort anything unless you explicitly tell it to. You should have an order by clause if order is important.

Body:
ok so i have this query

select price from product where product_id in (49, 50, 51)

and I want to know if the three records returned will be in the same order as my in clause. SO for example

100.0000
166.0000
55.0000

will 100.0000 belong to 49, 166.0000 to 50 and 55.0000 to 51


问:
How do I assign multiple labels at once in matplotlib?
I have the following dataset:

```<code>x = [0, 1, 2, 3, 4]
y = [ [0, 1, 2, 3, 4],
      [5, 6, 7, 8, 9],
      [9, 8, 7, 6, 5] ]
</code>```

Now I plot it with:

```<code>import matplotlib.pyplot as plt
plt.plot(x, y)
</code>```

However, I want to label the 3 y-datasets with this command, which raises an error when .legend() is called:

```<code>lineObjects = plt.plot(x, y, label=['foo', 'bar', 'baz'])
plt.legend()

File "./plot_nmos.py", line 33, in <module>
  plt.legend()
...
AttributeError: 'list' object has no attribute 'startswith'
</code>```

When I inspect the lineObjects:

```<code>>>> lineObjects[0].get_label()
['foo', 'bar', 'baz']
>>> lineObjects[1].get_label()
['foo', 'bar', 'baz']
>>> lineObjects[2].get_label()
['foo', 'bar', 'baz']
</code>```

Question

Is there an elegant way to assign multiple labels by just using the .plot() method?

答:
The best current solution is:

lineObjects = plt.plot(x, y)  # y describes 3 lines
plt.legend(['foo', 'bar', 'baz'])
```

Body:
I have the following dataset:

x = [0, 1, 2, 3, 4]
y = [ [0, 1, 2, 3, 4],
      [5, 6, 7, 8, 9],
      [9, 8, 7, 6, 5] ]

Now I plot it with:

import matplotlib.pyplot as plt
plt.plot(x, y)

However, I want to label the 3 y-datasets with this command, which raises an error when .legend() is called:

lineObjects = plt.plot(x, y, label=['foo', 'bar', 'baz'])
plt.legend()

File "./plot_nmos.py", line 33, in <module>
  plt.legend()
...
AttributeError: 'list' object has no attribute 'startswith'

When I inspect the lineObjects:

>>> lineObjects[0].get_label()
['foo', 'bar', 'baz']
>>> lineObjects[1].get_label()
['foo', 'bar', 'baz']
>>> lineObjects[2].get_label()
['foo', 'bar', 'baz']

Question

Is there an elegant way to assign multiple labels by just using the .plot() method?


问:
Notification Api System Correct Process
I built a small notification api system that has id, user_id, subject, text, status, created_at columns in the data base.

My current process is that when a user requests for her notifications i get the most recent 100 unread messages and send to the user, then wait for the front end to send me a list of ids of those that have been read by the user so that i can change their status to read.

but sometimes this does not happen meaning the when the user requests for another set of messages they will get back their already read messages.

So i am thinking of marking the messages as read once i retrieve them for the user rather than wait for update from the frontend.

but i am not sure if this is the best way to handle this! is there a better process for api notification systems please advice me. Thanks.

答:
We can't see your code here, but I would suggest the following:

Store the ids of messages displayed to the use in an array on the frontend, so when a user views a message, you add the id to that array. I'm not sure what your frontend is using so can't really make a code suggestions.

Create an endpoint that receives this array on the backend in your routes file

```<code>Route::post('somepath/read-messages', 'MessageController@readMessages');
</code>```

Then, in your message controller:

```<code>public function readMessages(Request $request) {

   if ($request->has('read_messages') {
       $messages = Message::whereIn('id', $request->read_messages)->get();
       $messages->update(array('staus' => 'read');
   }

}
</code>```

Title: Notification Api System Correct Process

Body:
We can't see your code here, but I would suggest the following:

Store the ids of messages displayed to the use in an array on the frontend, so when a user views a message, you add the id to that array. I'm not sure what your frontend is using so can't really make a code suggestions.

Create an endpoint that receives this array on the backend in your routes file

Route::post('somepath/read-messages', 'MessageController@readMessages');

Then, in your message controller:

public function readMessages(Request $request) {

   if ($request->has('read_messages') {
       $messages = Message::whereIn('id', $request->read_messages)->get();
       $messages->update(array('staus' => 'read');
   }

}


问:
extent reports not generating reports
I am using extentent reports to generate report but the test excution fails on extent.flush() method. I am using

extentreports 3.1.3

Specflow.xunit 2.2.1

This code use to work previously but not working anymore. Error returned :

System.IO.FileNotFoundException
        HResult=0x80070002
        Message=Could not load file or assembly 'System.Web.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified.
        Source=RazorEngine
        StackTrace:
         at RazorEngine.Compilation.CSharp.CSharpDirectCompilerService..ctor(Boolean strictMode, Func1 markupParserFactory)
         at RazorEngine.Compilation.DefaultCompilerServiceFactory.CreateCompilerService(Language language)
         at RazorEngine.Templating.RazorEngineCore.CreateTemplateType(ITemplateSource razorTemplate, Type modelType)
         at RazorEngine.Templating.RazorEngineCore.Compile(ITemplateKey key, Type modelType)
         at RazorEngine.Templating.RazorEngineService.CompileAndCacheInternal(ITemplateKey key, Type modelType)
         at RazorEngine.Templating.RazorEngineService.GetCompiledTemplate(ITemplateKey key, Type modelType, Boolean compileOnCacheMiss)
         at RazorEngine.Templating.RazorEngineService.RunCompile(ITemplateKey key, TextWriter writer, Type modelType, Object model, DynamicViewBag viewBag)
         at RazorEngine.Templating.RazorEngineServiceExtensions.<>c__DisplayClass16_0.<RunCompile>b__0(TextWriter writer)
         at RazorEngine.Templating.RazorEngineServiceExtensions.WithWriter(Action1 withWriter)
         at AventStack.ExtentReports.Reporter.ExtentHtmlReporter.Flush()
         at AventStack.ExtentReports.Model.Report.<>c.b__29_1(IExtentReporter x)
         at System.Collections.Generic.List1.ForEach(Action1 action)
         at AventStack.ExtentReports.Model.Report.NotifyReporters()
         at AventStack.ExtentReports.Model.Report.Flush()
         at AventStack.ExtentReports.ExtentReports.Flush()
         at XUnitTestProject5.UnitTest1.Test1() in C:\Users\kotar\source\repos\XUnitTestProject5\XUnitTestProject5\UnitTest1.cs:line 25

```<code> var HTMLReporter = new ExtentHtmlReporter(@"C:\test\TestReport.html");
 HTMLReporter.Configuration().Theme = AventStack.ExtentReports.Reporter.Configuration.Theme.Dark;
 var extent = new ExtentReports();
 extent.AttachReporter(HTMLReporter);
 var featurename = extent.CreateTest<Feature>("login feature");
 var scenario= featurename.CreateNode<Scenario>("Login as a user ");
 scenario.CreateNode<Given>("user has access to the methos ");

 extent.Flush();
</code>```

答:
If you are using .net core, you have to use "ExtentReports.Core" NuGet package instead of "ExtentReports" and initialize your extent object like this : </p>

```<code>public AventStack.ExtentReports.ExtentReports _extent = new
AventStack.ExtentReports.ExtentReports();
</code>```

Title: extent reports not generating reports

Body:
I am using extentent reports to generate report but the test excution fails on extent.flush() method. I am using

extentreports 3.1.3

Specflow.xunit 2.2.1

This code use to work previously but not working anymore. Error returned :

System.IO.FileNotFoundException
        HResult=0x80070002
        Message=Could not load file or assembly 'System.Web.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified.
        Source=RazorEngine
        StackTrace:
         at RazorEngine.Compilation.CSharp.CSharpDirectCompilerService..ctor(Boolean strictMode, Func1 markupParserFactory)
         at RazorEngine.Compilation.DefaultCompilerServiceFactory.CreateCompilerService(Language language)
         at RazorEngine.Templating.RazorEngineCore.CreateTemplateType(ITemplateSource razorTemplate, Type modelType)
         at RazorEngine.Templating.RazorEngineCore.Compile(ITemplateKey key, Type modelType)
         at RazorEngine.Templating.RazorEngineService.CompileAndCacheInternal(ITemplateKey key, Type modelType)
         at RazorEngine.Templating.RazorEngineService.GetCompiledTemplate(ITemplateKey key, Type modelType, Boolean compileOnCacheMiss)
         at RazorEngine.Templating.RazorEngineService.RunCompile(ITemplateKey key, TextWriter writer, Type modelType, Object model, DynamicViewBag viewBag)
         at RazorEngine.Templating.RazorEngineServiceExtensions.<>c__DisplayClass16_0.<RunCompile>b__0(TextWriter writer)
         at RazorEngine.Templating.RazorEngineServiceExtensions.WithWriter(Action1 withWriter)
         at AventStack.ExtentReports.Reporter.ExtentHtmlReporter.Flush()
         at AventStack.ExtentReports.Model.Report.<>c.b__29_1(IExtentReporter x)
         at System.Collections.Generic.List1.ForEach(Action1 action)
         at AventStack.ExtentReports.Model.Report.NotifyReporters()
         at AventStack.ExtentReports.Model.Report.Flush()
         at AventStack.ExtentReports.ExtentReports.Flush()
         at XUnitTestProject5.UnitTest1.Test1() in C:\Users\kotar\source\repos\XUnitTestProject5\XUnitTestProject5\UnitTest1.cs:line 25

 var HTMLReporter = new ExtentHtmlReporter(@"C:\test\TestReport.html");
 HTMLReporter.Configuration().Theme = AventStack.ExtentReports.Reporter.Configuration.Theme.Dark;
 var extent = new ExtentReports();
 extent.AttachReporter(HTMLReporter);
 var featurename = extent.CreateTest<Feature>("login feature");
 var scenario= featurename.CreateNode<Scenario>("Login as a user ");
 scenario.CreateNode<Given>("user has access to the methos ");

 extent.Flush();

Body:
If you are using .net core, you have to use "ExtentReports.Core" NuGet package instead of "ExtentReports" and initialize your extent object like this :

public AventStack.ExtentReports.ExtentReports _extent = new
AventStack.ExtentReports.ExtentReports();


问:
PHP index is not recognized (post method)
I am very new to php and am still in the learning phase. I typed a small script 1 to 1 and had to find out that the index from my HTML file is not recognized in php. In the given video the "GET" method is used, but it should actually work exactly the same way. It is just a test script. Nevertheless, an answer would be helpful.

Here are my scripts:

HTML:

```<code><form id="register-form" action="Memeon.php" method="post">
    <img class="register_avatar" src="pictures/login_register_avatar.png" oncontextmenu="return false;">
    <h2>Welcome to Memeon</h2>
    <div class="reg-input-div one">
        <div class="i">
          <i class="fas fa-user"></i>
        </div>
        <div>
            <h5>Username</h5>
            <input id="reg_un" class="reg-input" name="username" type="text" autocorrect="off" autocapitalize="off" spellcheck="false">
        </div>
    </div>
    <div class="reg-input-div two">
        <div class="i">
            <i class="fas fa-at"></i>
        </div>
        <div>
            <h5>Email-Adress</h5>
            <input id="reg_ea" class="reg-input" name="email" type="email" autocorrect="off" autocapitalize="off" spellcheck="false">
        </div>
    </div>
    <div class="reg-input-div three">
        <div class="i">
            <i class="fas fa-lock"></i>
        </div>
        <div>
            <h5>Password</h5>
            <input id="reg_pw" class="reg-input" name="password" type="password" autocorrect="off" autocapitalize="off" spellcheck="false">
        </div>
    </div>
    <a id="rl_l1" href="#">2-Factor-Authentication</a>
    <a id="rl_l2" href="#">Forgot Password?</a>
    <input type="submit" onclick="setRegisterInfo()" class="register_btn" value="Sign in">
</form>
</code>```

PHP:

```<code><?php
  echo "Hallo ". $_POST["username"];
?><br>
Der sehnlichst erwünschte Newsletter wird gesendet an <?php echo $_POST["email"]; ?>
</code>```

Both are in the same folder. With a submit button I get to the PHP page. An error always appears there.

答:
Maybe it haves to be with something in your "setRegisterInfo()" function (is it implemented ? if so, you should post it here too :) ) in the "onclick" attribute of the submit input at the very end. If that function breaks, the form won't be submitted.

```<code><input type="submit" onclick="setRegisterInfo()" class="register_btn" value="Sign in">
</code>```

Try again without that function.

```<code><input type="submit" class="register_btn" value="Sign in">
</code>```

Body:
I am very new to php and am still in the learning phase. I typed a small script 1 to 1 and had to find out that the index from my HTML file is not recognized in php. In the given video the "GET" method is used, but it should actually work exactly the same way. It is just a test script. Nevertheless, an answer would be helpful.

Here are my scripts:

HTML:

<form id="register-form" action="Memeon.php" method="post">

Welcome to Memeon

Username

            <input id="reg_un" class="reg-input" name="username" type="text" autocorrect="off" autocapitalize="off" spellcheck="false">

Email-Adress

            <input id="reg_ea" class="reg-input" name="email" type="email" autocorrect="off" autocapitalize="off" spellcheck="false">

Password

            <input id="reg_pw" class="reg-input" name="password" type="password" autocorrect="off" autocapitalize="off" spellcheck="false">

    2-Factor-Authentication
    Forgot Password?
    <input type="submit" onclick="setRegisterInfo()" class="register_btn" value="Sign in">
</form>

PHP:

<?php
  echo "Hallo ". $_POST["username"];
?>

Der sehnlichst erwünschte Newsletter wird gesendet an <?php echo $_POST["email"]; ?>

Both are in the same folder. With a submit button I get to the PHP page. An error always appears there.

Body:
Maybe it haves to be with something in your "setRegisterInfo()" function (is it implemented ? if so, you should post it here too :) ) in the "onclick" attribute of the submit input at the very end. If that function breaks, the form won't be submitted.

<input type="submit" onclick="setRegisterInfo()" class="register_btn" value="Sign in">

Try again without that function.

<input type="submit" class="register_btn" value="Sign in">


问:
LaTeX equations do not render in google Colaboratory when using matplotlib
If I take the official example containing latex from the matplotlib website:

```<code>from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
import numpy as np
import matplotlib.pyplot as plt

# Example data
t = np.arange(0.0, 1.0 + 0.01, 0.01)
s = np.cos(4 * np.pi * t) + 2

plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.plot(t, s)

plt.xlabel(r'\textbf{time} (s)')
plt.ylabel(r'\textit{voltage} (mV)',fontsize=16)
plt.title(r"\TeX\ is Number "
          r"$\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!",
          fontsize=16, color='gray')
# Make room for the ridiculously large title.
plt.subplots_adjust(top=0.8)

plt.savefig('tex_demo')
plt.show()
</code>```

and try to run it in a Google Colab notebook it will produce a big stacktrace with the following message at the end:

```<code> [Errno 2] No such file or directory: 'latex': 'latex'
</code>```

Why does this happen and how can I fix that?

My attempts:

I thought this error might happen because latex is missing in the serving VM so I tried to install texlive before importing matplotlib with:

```<code>! sudo apt-get install texlive-latex-recommended
</code>```

This finishes successfully. However matplotlib complains about some missing latex *.sty file which after googling should be contained in the texlive-latex-extra package. But during the installation of the extra package  some errors occurred:

```<code>Err:5 http://security.ubuntu.com/ubuntu bionic-updates/main amd64 ruby2.5 amd64 2.5.1-1ubuntu1.1
  404  Not Found [IP: 91.189.88.162 80]
Get:16 http://archive.ubuntu.com/ubuntu bionic/universe amd64 texlive-latex-extra all 2017.20180305-2 [10.6 MB]
Err:13 http://security.ubuntu.com/ubuntu bionic-updates/main amd64 libruby2.5 amd64 2.5.1-1ubuntu1.1
  404  Not Found [IP: 91.189.88.162 80]
Get:17 http://archive.ubuntu.com/ubuntu bionic/universe amd64 texlive-plain-generic all 2017.20180305-2 [23.6 MB]
Fetched 41.5 MB in 4s (11.3 MB/s)
</code>```

So I cant finish the installation of texlive-latex-extra. How can I proceed?

答:
The Cause

Basically, the problem is that type1cm and type1em is not installed by default with matplotlib in colab environment. More on this issue here: https://github.com/matplotlib/matplotlib/issues/17412

Solution

```<code>!apt install texlive-fonts-recommended texlive-fonts-extra cm-super dvipng
</code>```

The type1cm is part of texlive-fonts-extra and type1ec is a part of cm-super.

So to setup latex in matplotlib, you should have this block in your colab notebook:

```<code>import matplotlib
from matplotlib import rc
import matplotlib.pyplot as plt
%matplotlib inline

rc('text', usetex=True)
matplotlib.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}']
!apt install texlive-fonts-recommended texlive-fonts-extra cm-super dvipng
</code>```

Body:
If I take the official example containing latex from the matplotlib website:

from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
import numpy as np
import matplotlib.pyplot as plt

# Example data
t = np.arange(0.0, 1.0 + 0.01, 0.01)
s = np.cos(4 * np.pi * t) + 2

plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.plot(t, s)

plt.xlabel(r'\textbf{time} (s)')
plt.ylabel(r'\textit{voltage} (mV)',fontsize=16)
plt.title(r"\TeX\ is Number "
          r"$\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!",
          fontsize=16, color='gray')
# Make room for the ridiculously large title.
plt.subplots_adjust(top=0.8)

plt.savefig('tex_demo')
plt.show()

and try to run it in a Google Colab notebook it will produce a big stacktrace with the following message at the end:

 [Errno 2] No such file or directory: 'latex': 'latex'

Why does this happen and how can I fix that?

My attempts:

I thought this error might happen because latex is missing in the serving VM so I tried to install texlive before importing matplotlib with:

! sudo apt-get install texlive-latex-recommended

This finishes successfully. However matplotlib complains about some missing latex *.sty file which after googling should be contained in the texlive-latex-extra package. But during the installation of the extra package  some errors occurred:

Err:5 http://security.ubuntu.com/ubuntu bionic-updates/main amd64 ruby2.5 amd64 2.5.1-1ubuntu1.1
  404  Not Found [IP: 91.189.88.162 80]
Get:16 http://archive.ubuntu.com/ubuntu bionic/universe amd64 texlive-latex-extra all 2017.20180305-2 [10.6 MB]
Err:13 http://security.ubuntu.com/ubuntu bionic-updates/main amd64 libruby2.5 amd64 2.5.1-1ubuntu1.1
  404  Not Found [IP: 91.189.88.162 80]
Get:17 http://archive.ubuntu.com/ubuntu bionic/universe amd64 texlive-plain-generic all 2017.20180305-2 [23.6 MB]
Fetched 41.5 MB in 4s (11.3 MB/s)

So I cant finish the installation of texlive-latex-extra. How can I proceed?

Body:
The Cause

Basically, the problem is that type1cm and type1em is not installed by default with matplotlib in colab environment. More on this issue here: https://github.com/matplotlib/matplotlib/issues/17412

Solution

!apt install texlive-fonts-recommended texlive-fonts-extra cm-super dvipng

The type1cm is part of texlive-fonts-extra and type1ec is a part of cm-super.

So to setup latex in matplotlib, you should have this block in your colab notebook:

import matplotlib
from matplotlib import rc
import matplotlib.pyplot as plt
%matplotlib inline

rc('text', usetex=True)
matplotlib.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}']
!apt install texlive-fonts-recommended texlive-fonts-extra cm-super dvipng


问:
Stripe validate card element is filled out
When using saved cards or elements I need to validate one or the other is present when hitting submit.

I can see my own saved card radios easily but the Stripe elements are in an iframe.

Is there an event fired when the card is filled out?
Or some means to check it is good to submit. I am sure I am missing something obvious.

Something like this scenario

```<code>form.addEventListener('submit', function(event) {
                event.preventDefault();
                $('button.buy').prop('disabled', true);
                if ($('.saved_cards input[type="radio"]:checked')) {
                    self.save_card = false;
                    self.payment_method = $('.saved_cards input[type="radio"]:checked').val();
                    self.make_payment().then(self.handleMakePaymentResponse);
                } else {
// There should be a way to validate card is filled out
// Stripe validates as you type but no way to know it is simply done.
// we need to know this is filled out.
                    stripe.createPaymentMethod({
.........
</code>```

答: You would listen to the change event on an Element, and then check for the complete field on the event handler object: https://stripe.com/docs/js/element/events/on_change?type=cardElement

Body:
When using saved cards or elements I need to validate one or the other is present when hitting submit.

I can see my own saved card radios easily but the Stripe elements are in an iframe.

Is there an event fired when the card is filled out?
Or some means to check it is good to submit. I am sure I am missing something obvious.

Something like this scenario

form.addEventListener('submit', function(event) {
                event.preventDefault();
                $('button.buy').prop('disabled', true);
                if ($('.saved_cards input[type="radio"]:checked')) {
                    self.save_card = false;
                    self.payment_method = $('.saved_cards input[type="radio"]:checked').val();
                    self.make_payment().then(self.handleMakePaymentResponse);
                } else {
// There should be a way to validate card is filled out
// Stripe validates as you type but no way to know it is simply done.
// we need to know this is filled out.
                    stripe.createPaymentMethod({
.........


问:
Bind image to datagrid using resources
I am trying to retrieve the image from resource file and tryin to bind it to the datagrid of my WPF application.

The datagrid is somewhat like this:

```<code><DataGridTemplateColumn Header="Image" Width="45">
  <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Image  Source="{Binding Path=Icon}" />
                    </DataTemplate>
 </DataGridTemplateColumn.CellTemplate>
</code>```

And Image is a property of type image of my MVVm class like this:

```<code> public Image Icon
    {
        get { return _licenseImage; }
        set { _licenseImage = value;
        PropertChanged("Icon");}
    }
</code>```

And in the code behind Im tryin to do something like this to get image from resource file and tryin to bind it to datagrid column.

```<code>ResourceManager resourceManager =
        new ResourceManager("Resources.Images", Assembly.GetExecutingAssembly());
BitMap bitmap = resourceManager.GetObject("okimage") as BitMap;

Image image = bitmap;
return image;
</code>```

I can see that image is populated but it is not displaying in the grid.

答:
You should bind to an ImageSource instead of Image.

we use this helper class:

```<code>public static class ImageSourceHelper
{
    public static ImageSource GetResourceImage(string resourcePath)
    {
        return GetResourceImage(Assembly.GetCallingAssembly(), resourcePath);
    }

    public static ImageSource GetResourceImage(Assembly resourceAssembly, string resourcePath)
    {
        if (string.IsNullOrEmpty(resourcePath)) return null;

        var assembly = resourceAssembly.GetName().Name;
        const string uriFormat = "pack://application:,,,/{0};component/{1}";

        if (!UriParser.IsKnownScheme("pack")) new System.Windows.Application();

        var uri = new Uri(string.Format(uriFormat, assembly, resourcePath), UriKind.RelativeOrAbsolute);

        return BitmapFrame.Create(uri);
    }

    public static ImageSource ConvertFromGdiBitmap(Bitmap bitmap)
    {
        return Common.SystemAbstraction.Media.ImageConverter.ConvertToBitmapSource(bitmap);
    }

    public static Bitmap ConvertToGdiBitmap(ImageSource imageSource)
    {
        return Common.SystemAbstraction.Media.ImageConverter.ConvertToBitmap(imageSource as BitmapSource);
    }
}
</code>```

It creates an ImageSource from Bitmap or resource images.

Usage is

```<code>img.Source = ImageSourceHelper("Path/To/Your/Image.png");
</code>```

or

```<code>var resourceAssembly = // get resource assembly...
img.Source = ImageSourceHelper(resourceAssembly, "Path/To/Your/Image.png");
</code>```

if the image is contained in an other assembly than the currently calling assembly.

The path of your image is the path starting at the project file root of your assembly.
Say you have an folder images your path will be "images/somepicture.png".

Title: Bind image to datagrid using resources

Body:
I am trying to retrieve the image from resource file and tryin to bind it to the datagrid of my WPF application.

The datagrid is somewhat like this:

<DataGridTemplateColumn Header="Image" Width="45">
  <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Image  Source="{Binding Path=Icon}" />
                    </DataTemplate>
 </DataGridTemplateColumn.CellTemplate>

And Image is a property of type image of my MVVm class like this:

 public Image Icon
    {
        get { return _licenseImage; }
        set { _licenseImage = value;
        PropertChanged("Icon");}
    }

And in the code behind Im tryin to do something like this to get image from resource file and tryin to bind it to datagrid column.

ResourceManager resourceManager =
        new ResourceManager("Resources.Images", Assembly.GetExecutingAssembly());
BitMap bitmap = resourceManager.GetObject("okimage") as BitMap;

Image image = bitmap;
return image;

I can see that image is populated but it is not displaying in the grid.

Body:
You should bind to an ImageSource instead of Image.

we use this helper class:

public static class ImageSourceHelper
{
    public static ImageSource GetResourceImage(string resourcePath)
    {
        return GetResourceImage(Assembly.GetCallingAssembly(), resourcePath);
    }

    public static ImageSource GetResourceImage(Assembly resourceAssembly, string resourcePath)
    {
        if (string.IsNullOrEmpty(resourcePath)) return null;

        var assembly = resourceAssembly.GetName().Name;
        const string uriFormat = "pack://application:,,,/{0};component/{1}";

        if (!UriParser.IsKnownScheme("pack")) new System.Windows.Application();

        var uri = new Uri(string.Format(uriFormat, assembly, resourcePath), UriKind.RelativeOrAbsolute);

        return BitmapFrame.Create(uri);
    }

    public static ImageSource ConvertFromGdiBitmap(Bitmap bitmap)
    {
        return Common.SystemAbstraction.Media.ImageConverter.ConvertToBitmapSource(bitmap);
    }

    public static Bitmap ConvertToGdiBitmap(ImageSource imageSource)
    {
        return Common.SystemAbstraction.Media.ImageConverter.ConvertToBitmap(imageSource as BitmapSource);
    }
}

It creates an ImageSource from Bitmap or resource images.

Usage is

img.Source = ImageSourceHelper("Path/To/Your/Image.png");

or

var resourceAssembly = // get resource assembly...
img.Source = ImageSourceHelper(resourceAssembly, "Path/To/Your/Image.png");

if the image is contained in an other assembly than the currently calling assembly.

The path of your image is the path starting at the project file root of your assembly.
Say you have an folder images your path will be "images/somepicture.png".


问:
Getting "Error: Invalid IdP response/credential" trying to add FB user on Firebase Auth list
I've been working on implementing Facebook & Google sign-in method in an app based on Expo.

Having Firebase connected with my app, I want the user to be listed in Firebase Users. While Google sign-in seems to work fine, Facebook gives an error as stated below from firebase.auth().signInWithCredential(credential):

```<code>[Error: Invalid IdP response/credential: http://localhost?id_token=EAAGUBzIZAgb0BABAkdrj5NcUcvljcsLeNBQlV5VUZAZC7M8e7sSRg2MkqlFCuD7tKjin4uZBep5gSs20oAo8fXKiUqq2deEbUl6HoaAUskTda7x49VCqqcbYh1W3566fMZBtRFB5S3fRV7D41AGVGPMAck91l1KiFCzQzCGtSf5g6ZBKoyHw03LOVONcOiwVZB4vXVcGPYmIzL3RuzzztdBNLRql5ndSk0ZD&providerId=facebook.com]
</code>```

Here's the relevant part of the code:

Firebase.js

```<code>// imports, configs and exports omitted
export const facebookProvider = new firebase.auth.FacebookAuthProvider;
</code>```

LoadingScreen.js (the sign-in part)

```<code>import firebase, { googleProvider, facebookProvider } from "../firebase";
import * as Facebook from "expo-facebook";

const LoadingScreen = ({ navigation }) => {
  const signInWithFacebook = async () => {
    try {
      await Facebook.initializeAsync("444233602924989");
      const { type, token } = await Facebook.logInWithReadPermissionsAsync(
        "444233602924989",
        {
          permissions: ["public_profile", "email"]
        }
      );
      if (type === "success") {
        const credential = facebookProvider.credential(token);
        onSignInFB(credential);
      } else {
        Alert.alert('FB sign-in failed')
      }
    } catch ({ message }) {
      console.log(`Facebook 1 Error: ${message}`);
      Alert.alert(`first ${message}`);
    }
  };

  const onSignInFB = credential => {
    firebase
      .auth()
      .signInWithCredential(credential)
      .then(function() {
        navigation.navigate("Home");
      })
      .catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // The email of the user's account used.
        var email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        var credential = error.credential;
      });
  };
};
</code>```

I've logged some of the elements as follows:

While none of the error properties were available, the error code was auth/internal-error. Console.logging the error itself produced the error Invalid IdP response/credential.

The token from logInWithReadPermissionsAsync was a valid access token (string)

The credential from facebookProvider.credential(token) was:

```<code>    Object {"oauthIdToken": "EAAGUBzIZAgb0BAKgeMa5E7qHm8WNJYv5SeuQ8DHyhkUlAnkMhE7niu6tx3e2amSMHSEqG9B0MV4a9dygwgjs337PR7AA3M4PZB2F6x6n1FwAEyZBKhZBpOSE2OWQ9dJipirpafg61TKX36hnKIzaIcwRkjs8YYRBbDuLnZAhJzWst3ZBM5tafwxYKumv2F4kYdexxZAXqb1nosnwYodNvB9bstkcaBrfB8ZD",
      "providerId": "facebook.com",
      "signInMethod": "facebook.com",
    }
</code>```

firebase.auth().currentUser was null.

I've also gone through my own sanity checklist of possible mistakes below, but couldn't find any:

FB is enabled in Firebase Auth Sign-in

AppId & App Secret is correctly copied from FB app to Firebase(and also the redirect URI)

Pass in the access token from Facebook.logInWithReadPermissionsAsync to Facebook's access token debugger and see if anything is wrong (e.g. expired or invalid)

Check if an actual credential is returned from facebookProvider.credential(token) and passed to signInWithCredential

It would be great to find out the source of the problem! (one possibility might be the access token returned from logInWithReadPermissionsAsync is identical with the oauthIdToken property in the credential object, but I haven't manually put or changed any one of those.)

Thanks for reading :)

答:
I banged my head against this today and the solution was to pass an object in to the credential call, even though the docs say to pass in a string. In addition, the object property needs to be keyed as accessToken.

So instead of:
const credential = facebookProvider.credential(token);

try:
const credential = facebookProvider.credential({ accessToken: token });

Based on the docs, I have no idea why that key is needed or why it has to be an object, but it worked in my case. Hope it helps!

Body:
I've been working on implementing Facebook & Google sign-in method in an app based on Expo.

Having Firebase connected with my app, I want the user to be listed in Firebase Users. While Google sign-in seems to work fine, Facebook gives an error as stated below from firebase.auth().signInWithCredential(credential):

[Error: Invalid IdP response/credential: http://localhost?id_token=EAAGUBzIZAgb0BABAkdrj5NcUcvljcsLeNBQlV5VUZAZC7M8e7sSRg2MkqlFCuD7tKjin4uZBep5gSs20oAo8fXKiUqq2deEbUl6HoaAUskTda7x49VCqqcbYh1W3566fMZBtRFB5S3fRV7D41AGVGPMAck91l1KiFCzQzCGtSf5g6ZBKoyHw03LOVONcOiwVZB4vXVcGPYmIzL3RuzzztdBNLRql5ndSk0ZD&providerId=facebook.com]

Here's the relevant part of the code:

Firebase.js

// imports, configs and exports omitted
export const facebookProvider = new firebase.auth.FacebookAuthProvider;

LoadingScreen.js (the sign-in part)

import firebase, { googleProvider, facebookProvider } from "../firebase";
import * as Facebook from "expo-facebook";

const LoadingScreen = ({ navigation }) => {
  const signInWithFacebook = async () => {
    try {
      await Facebook.initializeAsync("444233602924989");
      const { type, token } = await Facebook.logInWithReadPermissionsAsync(
        "444233602924989",
        {
          permissions: ["public_profile", "email"]
        }
      );
      if (type === "success") {
        const credential = facebookProvider.credential(token);
        onSignInFB(credential);
      } else {
        Alert.alert('FB sign-in failed')
      }
    } catch ({ message }) {
      console.log(`Facebook 1 Error: ${message}`);
      Alert.alert(`first ${message}`);
    }
  };

  const onSignInFB = credential => {
    firebase
      .auth()
      .signInWithCredential(credential)
      .then(function() {
        navigation.navigate("Home");
      })
      .catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // The email of the user's account used.
        var email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        var credential = error.credential;
      });
  };
};

I've logged some of the elements as follows:

While none of the error properties were available, the error code was auth/internal-error. Console.logging the error itself produced the error Invalid IdP response/credential.

The token from logInWithReadPermissionsAsync was a valid access token (string)

The credential from facebookProvider.credential(token) was:

    Object {"oauthIdToken": "EAAGUBzIZAgb0BAKgeMa5E7qHm8WNJYv5SeuQ8DHyhkUlAnkMhE7niu6tx3e2amSMHSEqG9B0MV4a9dygwgjs337PR7AA3M4PZB2F6x6n1FwAEyZBKhZBpOSE2OWQ9dJipirpafg61TKX36hnKIzaIcwRkjs8YYRBbDuLnZAhJzWst3ZBM5tafwxYKumv2F4kYdexxZAXqb1nosnwYodNvB9bstkcaBrfB8ZD",
      "providerId": "facebook.com",
      "signInMethod": "facebook.com",
    }

firebase.auth().currentUser was null.

I've also gone through my own sanity checklist of possible mistakes below, but couldn't find any:

FB is enabled in Firebase Auth Sign-in

AppId & App Secret is correctly copied from FB app to Firebase(and also the redirect URI)

Pass in the access token from Facebook.logInWithReadPermissionsAsync to Facebook's access token debugger and see if anything is wrong (e.g. expired or invalid)

Check if an actual credential is returned from facebookProvider.credential(token) and passed to signInWithCredential

It would be great to find out the source of the problem! (one possibility might be the access token returned from logInWithReadPermissionsAsync is identical with the oauthIdToken property in the credential object, but I haven't manually put or changed any one of those.)

Thanks for reading :)


问:
LiveData does not emit required value
I have my live data created like this:

```<code>val authTokenLiveData: LiveData<String?> = liveData {
    emit(accountManager.myAuthToken())
}
</code>```

And I am observing it like it:

```<code>accountViewModel.authTokenLiveData.observe(this) {
    toast("Token is $it")
    if(it == null) goToLogin()
}
</code>```

It works well at first, I get the token toasted, however when I logout, and hence remove the token such that the token is null, I do not go to login which I should according to my observer.

How do I ensure that the authTokenLiveData emits null when the token becomes null so that my observer allows me to go to the login screen?

答:
The simple answer here is "You can't". The liveData builder runs once. After the first emit it will not emit again when the source changes.

I had to manually go to the login screen without observing authTokenLiveData.

Title: LiveData does not emit required value

Body:
I have my live data created like this:

val authTokenLiveData: LiveData<String?> = liveData {
    emit(accountManager.myAuthToken())
}

And I am observing it like it:

accountViewModel.authTokenLiveData.observe(this) {
    toast("Token is $it")
    if(it == null) goToLogin()
}

It works well at first, I get the token toasted, however when I logout, and hence remove the token such that the token is null, I do not go to login which I should according to my observer.

How do I ensure that the authTokenLiveData emits null when the token becomes null so that my observer allows me to go to the login screen?


问:
Best practices for using `peerDependency`and `devDependency`
I am writing a react component library, and dont want to bundle react, so I added the libs to peerDependencies rather than dependencies.

Also, to prevent those stupid warnings about missing peerDependencies, I add the same libs to the devDependencies section.

Thats not DRY, but a fixed warning is more important to me than a DRY package.json.

So the question is: Is there a DRYer method to achieve this, or do I actually follow the May 2020 best practice?

```<code>{
    "peerDependencies": {
        "react": "^16.9.0",
        "react-dom": "^16.9.0",
        "tslib": "^1.11.0",
    },
    "devDependencies": {
        "@types/react": "^16.9.0",
        "react": "^16.9.0",
        "react-dom": "^16.9.0",
        "typescript": "^3.8.0"
    },
    "dependencies": {
        // nothing here
    }
}

</code>```

答:
I'm not sure what you're using to create your bundle but if you're using Webpack or Rollup you can define externals not to be included in the bundle.

In your care everything you have in peerDependencies would go into dependencies and in the config for webpack or rollup you'd define the externals as follows:

{
  ...
  externals: ['react', 'react-doe', 'tslib'],
}
```

Body:
I am writing a react component library, and dont want to bundle react, so I added the libs to peerDependencies rather than dependencies.

Also, to prevent those stupid warnings about missing peerDependencies, I add the same libs to the devDependencies section.

Thats not DRY, but a fixed warning is more important to me than a DRY package.json.

So the question is: Is there a DRYer method to achieve this, or do I actually follow the May 2020 best practice?

{
    "peerDependencies": {
        "react": "^16.9.0",
        "react-dom": "^16.9.0",
        "tslib": "^1.11.0",
    },
    "devDependencies": {
        "@types/react": "^16.9.0",
        "react": "^16.9.0",
        "react-dom": "^16.9.0",
        "typescript": "^3.8.0"
    },
    "dependencies": {
        // nothing here
    }
}


问:
How to save all raw files from a web browser?
How can i save all pages sources loaded from a website, including images, js files, and any webstream to some local folder, while i am visiting them?

So i need to be able to use the browser normally, but then later be able to inspect the source files, one by one.

I used to use "Fiddler" with a special plugin, but recently, some sites do not work at all with it enabled.
My guess, probably because the fake HTTPS it adds, and that the webapps now directly verify the HTTPS ceritificate, or because of 'webstreams'.

So is there a proxy to offer similar behavior, or a way to do it from within the browser itself.

答:
Best tool I ever had opportunity to work with is python scrapy.

It has the best of all scrapers, and is very easy to use.


问:
Web Application to know database update
My web application (ASP.NET 4) connects to a database (SQL Server 2005). For every new row inserted in a certain table, I want the web app can do some process (like send  an email to me with new data).

How do I implement the system? My first though is having web app check the table SN column, and have a variable lastProcessedSN. And keep polling every minute. Is it possible to have DB notify web app when there's a new row being inserted?

Please advise, thanks.

EDIT:
Sending an email is just an example, not the exact thing I want to do. So this question is focusing on how to implement the trigger on MSSQL table insert to call my program.

答: Probably the easiest approach would be to setup a Windows scheduled task that ran every X minutes that would execute a console app you create.  Your app would select the newest rows from the table (based on timestamp, or possibly a Flag you can set) and e-mail them.</p>

Title: Web Application to know database update